import { unified } from 'unified'; import remarkParse from 'remark-parse'; import remarkGfm from 'remark-gfm'; import remarkDirective from 'remark-directive'; // Упрощённый тип узла Markdown-дерева (mdast). Полные типы из @types/mdast здесь // только мешают: у нас есть свои узлы (wikiLink, containerDirective). export interface MdNode { type: string; value?: string; children?: MdNode[]; depth?: number; ordered?: boolean; start?: number | null; checked?: boolean | null; url?: string; alt?: string | null; title?: string | null; name?: string; slug?: string; lang?: string | null; } const WIKI_RE = /\[\[([a-z0-9][a-z0-9-]*)\]\]/g; /** * Свой remark-плагин: превращает текст `[[slug]]` в узел { type: 'wikiLink', slug }. * Дальше рендер делает из него ссылку-чип с названием статьи. */ function remarkWikiLinks() { return (tree: MdNode) => { const walk = (node: MdNode) => { if (!node.children) return; // Внутри кода ссылки не трогаем if (node.type === 'code' || node.type === 'inlineCode') return; const out: MdNode[] = []; for (const child of node.children) { if (child.type !== 'text' || !child.value || !child.value.includes('[[')) { walk(child); out.push(child); continue; } const text = child.value; let last = 0; for (const m of text.matchAll(WIKI_RE)) { const at = m.index ?? 0; if (at > last) out.push({ type: 'text', value: text.slice(last, at) }); out.push({ type: 'wikiLink', slug: m[1] }); last = at + m[0].length; } if (last < text.length) out.push({ type: 'text', value: text.slice(last) }); } node.children = out; }; walk(tree); }; } const processor = unified().use(remarkParse) // singleTilde: false, иначе «~15 см … ~30 см» в одном абзаце станет зачёркнутым текстом .use(remarkGfm, { singleTilde: false }) .use(remarkDirective) .use(remarkWikiLinks); /** Markdown (без front matter) → дерево mdast. */ export function parseMarkdown(md: string): MdNode { const tree = processor.parse(md); return processor.runSync(tree) as unknown as MdNode; } /** Весь текст узла подряд, без разметки. */ export function plainText(node: MdNode): string { if (node.type === 'wikiLink') return ''; if (node.type === 'image') return node.alt ?? ''; if (node.type === 'break') return ' '; if (typeof node.value === 'string') return node.value; return (node.children ?? []).map(plainText).join(''); }