Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

epubSource.ts

82 lines4.2 KB

1import type { EpubPage } from "./officePreviewProtocol";
2​
3const mathNamespace = "http://www.w3.org/1998/Math/MathML";
4​
5export function epubSource(page: EpubPage, dark: boolean) {
6 const styles =
7 page.styles
8 ?.map(
9 ({ css, media }) =>
10 `<style media="${media.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;")}">${css}</style>`,
11 )
12 .join("") ?? "";
13 const layout = page.imagePage
14 ? page.fixed
15 ? "html,body{width:100%;height:100%;margin:0}body>img,body>svg{display:block}"
16 : "body{margin:0;display:grid;place-items:center;min-height:100vh}img,svg{max-width:100vw;max-height:100vh;height:auto;object-fit:contain}"
17 : "";
18 const media = page.fixed
19 ? ""
20 : "@media(max-width:600px){audio,video{max-width:100%}video{height:auto}}";
21 const narration = page.narration?.length
22 ? ".t3-epub-narration-active{outline:2px solid #3195ac!important;outline-offset:2px}"
23 : "";
24 return `<!doctype html><html${page.htmlAttrs ?? ""}><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src blob:; font-src data:; media-src blob:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"><style>@layer preview{*,*::before,*::after{animation:none!important;transition:none!important;scroll-behavior:auto!important}${media}}:root{color-scheme:${dark ? "dark" : "light"}}${layout}${narration}</style>${styles}</head><body${page.bodyAttrs ?? ""}>${page.html}</body></html>`;
26​
27export function prepareEpubDocument(doc: Document) {
28 // XHTML can contain nested links, which the HTML parser would split and truncate.
29 for (const placeholder of doc.querySelectorAll("epub-nested-link")) {
30 const link = doc.createElement("a");
31 for (const { name, value } of placeholder.attributes) link.setAttribute(name, value);
32 while (placeholder.firstChild) link.append(placeholder.firstChild);
33 placeholder.replaceWith(link);
34 }
35 // HTML inserts tbody around direct rows. XHTML styles can target those rows as table children.
36 for (const body of doc.querySelectorAll(
37 "table[data-epub-direct-rows] > tbody:not([data-epub-authored])",
38 )) {
39 const rows = doc.createDocumentFragment();
40 while (body.firstChild) rows.append(body.firstChild);
41 body.replaceWith(rows);
42 }
43 const expressions = doc.getElementsByTagNameNS(mathNamespace, "mfenced");
44 const fences = Array.from(expressions).flatMap((expression) => expandMathFences(doc, expression));
45 // WebKit can drop a stretchy fence if the available math font lacks a glyph for it.
46 const missing = fences.filter((fence) => fence.getBoundingClientRect().width === 0);
47 for (const fence of missing) fence.setAttribute("stretchy", "false");
49​
50function expandMathFences(doc: Document, expression: Element) {
51 const row = doc.createElementNS(mathNamespace, "mrow");
52 for (const { name, value } of expression.attributes) row.setAttribute(name, value);
53 const appendOperator = (
54 target: Element,
55 text: string,
56 kind: "fence" | "separator",
57 form: string,
58 ) => {
59 if (!text) return;
60 const operator = doc.createElementNS(mathNamespace, "mo");
61 operator.setAttribute(kind, "true");
62 operator.setAttribute("form", form);
63 operator.textContent = text;
64 target.append(operator);
65 return operator;
66 };
67 const open = (expression.getAttribute("open") ?? "(").replace(/[\t\n\r ]+/g, " ").trim();
68 const close = (expression.getAttribute("close") ?? ")").replace(/[\t\n\r ]+/g, " ").trim();
69 const separators = [...(expression.getAttribute("separators") ?? ",").replace(/[\t\n\r ]/g, "")];
70 const opening = appendOperator(row, open, "fence", "prefix");
71 const args = Array.from(expression.children);
72 const contents = args.length > 1 ? doc.createElementNS(mathNamespace, "mrow") : row;
73 for (const [index, child] of args.entries()) {
74 const separator = separators[Math.min(index - 1, separators.length - 1)];
75 if (separator) appendOperator(contents, separator, "separator", "infix");
76 contents.append(child);
77 }
78 if (contents !== row) row.append(contents);
79 const closing = appendOperator(row, close, "fence", "postfix");
80 expression.replaceWith(row);
81 return [opening, closing].filter((operator) => operator !== undefined);