import type { Root, Element, ElementContent, Text } from 'hast'
import type { Plugin } from 'unified'
import { visit } from 'unist-util-visit'
/**
* Strips a leading match from the first text node in the given children array.
* @param children The children array to process.
* @param regex The regex pattern to match and strip from the first text node.
* @returns The modified children array with the leading match stripped.
*/
const stripLeadingColon = (
line: ElementContent[],
): { isNewDefinition: boolean; content: ElementContent[] } => {
const [first, ...rest] = line
if (first?.type === 'text') {
const match = first.value.match(/^[ \t]*:[ \t]*/)
if (match) {
const remainder = first.value.slice(match[0].length)
return {
isNewDefinition: true,
content: remainder ? [{ type: 'text', value: remainder } as Text, ...rest] : rest,
}
}
}
return { isNewDefinition: false, content: line }
}
/**
* Splits an array of ElementContent nodes into lines based on text nodes containing newlines and
elements.
* @param nodes The array of ElementContent nodes to split into lines.
* @returns An array of lines, where each line is an array of ElementContent nodes.
*/
const splitIntoLines = (nodes: ElementContent[]): ElementContent[][] => {
const lines: ElementContent[][] = [[]]
for (const child of nodes) {
if (child.type === 'text') {
const segments = child.value.split('\n')
segments.forEach((segment, i) => {
if (i > 0) lines.push([])
if (segment.length > 0) {
lines[lines.length - 1].push({ type: 'text', value: segment } as Text)
}
})
} else if (child.type === 'element' && child.tagName === 'br') {
lines.push([])
} else {
lines[lines.length - 1].push(child)
}
}
return lines
}
/**
* A rehype plugin that transforms paragraphs containing a leading "Term:" into
* definition lists. For example, a paragraph like "Term: Definition" will be
* transformed into a