import { escapeHtml as e } from "../../html.ts"; /** * Упрощённая разметка глав книги (CLT-15): `#`, `##` (с якорем `{#id}`), `###`, абзацы, * списки `-` и `1.`, врезки `>`, таблицы `|`, `**жирный**`, `*курсив*`. * Весь текст экранируется — HTML из файла главы выводится как текст. */ export interface RenderedChapter { title: string; html: string; toc: { id: string; title: string }[]; } const ANCHOR_RE = /\s*\{#([a-z0-9-]+)\}\s*$/; export function inline(s: string): string { return e(s) .replace(/\*\*(.+?)\*\*/g, "$1") .replace(/(^|[^*\p{L}])\*(?!\s)(.+?)\*(?![*\p{L}])/gu, "$1$2"); } const cells = (line: string): string[] => line .trim() .replace(/^\|/, "") .replace(/\|$/, "") .split("|") .map((c) => c.trim()); const isSeparator = (line: string) => /^\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?$/.test(line.trim()); function blocks(lines: string[], toc: RenderedChapter["toc"], meta: { title: string }): string { const out: string[] = []; let i = 0; const at = (k: number) => lines[k] ?? ""; while (i < lines.length) { const line = at(i); if (!line.trim()) { i++; continue; } const h = /^(#{1,3})\s+(.+)$/.exec(line); if (h) { const level = (h[1] as string).length; let text = h[2] as string; const anchor = ANCHOR_RE.exec(text); if (anchor) text = text.slice(0, anchor.index); if (level === 1 && !meta.title) meta.title = text; const id = anchor?.[1]; if (level === 2 && id) toc.push({ id, title: text }); out.push(`${inline(text)}`); i++; continue; } if (line.startsWith(">")) { const inner: string[] = []; while (i < lines.length && at(i).startsWith(">")) inner.push(at(i++).replace(/^>\s?/, "")); out.push(``); continue; } if (line.trim().startsWith("|") && isSeparator(at(i + 1))) { const head = cells(line); i += 2; const rows: string[][] = []; while (i < lines.length && at(i).trim().startsWith("|")) rows.push(cells(at(i++))); out.push( `
${head.map((c) => ``).join("")}${rows .map((r) => `${r.map((c) => ``).join("")}`) .join("")}
${inline(c)}
${inline(c)}
`, ); continue; } const list = /^(-|\d+\.)\s+/.exec(line); if (list) { const ordered = list[1] !== "-"; const re = ordered ? /^\d+\.\s+/ : /^-\s+/; const items: string[] = []; while (i < lines.length && re.test(at(i))) items.push(at(i++).replace(re, "")); const tag = ordered ? "ol" : "ul"; out.push(`<${tag}>${items.map((x) => `
  • ${inline(x)}
  • `).join("")}`); continue; } const para: string[] = []; while (i < lines.length && at(i).trim() && !/^(#{1,3}\s|>|-\s|\d+\.\s|\|)/.test(at(i))) para.push(at(i++).trim()); if (!para.length) para.push(at(i++).trim()); out.push(`

    ${inline(para.join(" "))}

    `); } return out.join("\n"); } export function renderChapterMarkdown(src: string): RenderedChapter { const toc: RenderedChapter["toc"] = []; const meta = { title: "" }; const html = blocks(src.replace(/\r\n?/g, "\n").split("\n"), toc, meta); return { title: meta.title, html, toc }; }