/**
* 电子书 Markdown 解析 - 共享模块
*/
import { marked } from "marked";
export interface EbookChunk {
html: string;
estimatedHeight: number;
}
export interface EbookData {
chunks: EbookChunk[];
headers: string[];
}
export function parseEbookMarkdown(source: string): EbookData {
const html = marked.parse(source, { breaks: true, gfm: true }) as string;
let lazyHtml = html.replace(/();
lazyHtml = lazyHtml.replace(
/<(h[12])(\s[^>]*)?>([\s\S]*?)<\/\1>/gi,
(_m, tag: string, attrs = "", inner: string) => {
if (/\sid\s*=/i.test(attrs || "")) {
return `<${tag}${attrs || ""}>${inner}${tag}>`;
}
const plain = inner.replace(/<[^>]+>/g, "").trim();
let base =
plain
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/[^\w\u4e00-\u9fff-]+/g, "")
.replace(/-+/g, "-")
.replace(/^-|-$/g, "")
.slice(0, 80) || "section";
let id = base;
let n = 2;
while (used.has(id)) {
id = `${base}-${n++}`;
}
used.add(id);
return `<${tag}${attrs || ""} id="${id}">${inner}${tag}>`;
},
);
let rawChunks = lazyHtml.split(/(?=