customer/src/modules/library/chapter.ts

96 lines
3.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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, "<strong>$1</strong>")
.replace(/(^|[^*\p{L}])\*(?!\s)(.+?)\*(?![*\p{L}])/gu, "$1<em>$2</em>");
}
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(`<h${level}${id ? ` id="${id}"` : ""}>${inline(text)}</h${level}>`);
i++;
continue;
}
if (line.startsWith(">")) {
const inner: string[] = [];
while (i < lines.length && at(i).startsWith(">")) inner.push(at(i++).replace(/^>\s?/, ""));
out.push(`<aside class="box">${blocks(inner, toc, meta)}</aside>`);
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(
`<div class="table"><table><thead><tr>${head.map((c) => `<th>${inline(c)}</th>`).join("")}</tr></thead><tbody>${rows
.map((r) => `<tr>${r.map((c) => `<td>${inline(c)}</td>`).join("")}</tr>`)
.join("")}</tbody></table></div>`,
);
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) => `<li>${inline(x)}</li>`).join("")}</${tag}>`);
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(`<p>${inline(para.join(" "))}</p>`);
}
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 };
}