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(c)} | `).join("")}
|---|
| ${inline(c)} | `).join("")}
${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 }; }