Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
Math: render $…$ / $$…$$ as MathML via Temml (#15, #33)
nyblnet8ece2bb37da3
diff --git a/slides/package-lock.json b/slides/package-lock.jsonindex 4a095cca..d70d8cc1 100644--- a/slides/package-lock.json+++ b/slides/package-lock.json@@ -1,17 +1,18 @@{"name": "bento-slides",- "version": "0.9.19",+ "version": "1.0.10","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "bento-slides",- "version": "0.9.19",+ "version": "1.0.10","license": "MIT","dependencies": {"moveable": "^0.53.0","reveal.js": "^5.2.1",- "selecto": "^1.26.3"+ "selecto": "^1.26.3",+ "temml": "^0.13.3"},"devDependencies": {"@types/node": "^24.13.2",@@ -1664,6 +1665,15 @@"node": ">=8"}},+ "node_modules/temml": {+ "version": "0.13.3",+ "resolved": "https://registry.npmjs.org/temml/-/temml-0.13.3.tgz",+ "integrity": "sha512-GLNEdf5qBWux3adbOxFus4jlds8nCdEIkkKq99m/4GGTfqnsjlVlK/i371Ux7yYSg/WNmOyAkNT/GJlZoJ0v+w==",+ "license": "MIT",+ "engines": {+ "node": ">=18.13.0"+ }+ },"node_modules/tinyglobby": {"version": "0.2.17","resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",diff --git a/slides/package.json b/slides/package.jsonindex 335f1a5b..52310d10 100644--- a/slides/package.json+++ b/slides/package.json@@ -13,7 +13,8 @@"dependencies": {"moveable": "^0.53.0","reveal.js": "^5.2.1",- "selecto": "^1.26.3"+ "selecto": "^1.26.3",+ "temml": "^0.13.3"},"devDependencies": {"@types/node": "^24.13.2",diff --git a/slides/src/editor/canvas.ts b/slides/src/editor/canvas.tsindex 1d0ebe30..aa767c52 100644--- a/slides/src/editor/canvas.ts+++ b/slides/src/editor/canvas.ts@@ -914,10 +914,10 @@ export class SlideCanvas {this.commitTextEdit()const inner = node.querySelector<HTMLElement>('.bento-text-inner')if (!inner) return- // fields ({{page}} etc.) render resolved; while editing, show the RAW token- // so the author edits the field, not the computed value+ // fields ({{page}} etc.) and math ($…$) render RESOLVED; while editing,+ // show the raw source so the author edits the token, not the computed valueconst model = this.store.element(node.dataset.elId ?? '')- if (model?.type === 'text' && typeof model.html === 'string' && model.html.includes('{{')) {+ if (model?.type === 'text' && typeof model.html === 'string' && /\{\{|\$/.test(model.html)) {inner.innerHTML = model.html}this.editing = nodediff --git a/slides/src/render.ts b/slides/src/render.tsindex c3df9445..26163b6b 100644--- a/slides/src/render.ts+++ b/slides/src/render.ts@@ -6,6 +6,7 @@import type { BentoDoc, ShapeElement, Slide, SlideElement, SvgElement, TableElement } from './model'import { morphKey } from './model'import { chartSnapshotSvg } from './charts'+import temml from 'temml'const SVG_NS = 'http://www.w3.org/2000/svg'@@ -327,6 +328,65 @@ export function shapeSvg(el: ShapeElement): SVGSVGElement {return svg}+// --- math ($…$ → MathML) -----------------------------------------------------++/**+ * LaTeX math in text, resolved at RENDER time — the same trick resolveFields+ * uses for {{page}}. The MODEL stores the raw source (`$E=mc^2$`), so the+ * format gains nothing to version: an older build opening a newer file shows+ * the literal `$E=mc^2$` — degraded, legible, and nothing is lost.+ *+ * MathML, not HTML+CSS, is what makes this affordable. Temml emits MathML and+ * the browser lays it out with its own math fonts; KaTeX would have to ship a+ * layout engine AND ~20 webfont faces (measured: +421KB against Temml's +64KB).+ *+ * MUST run AFTER sanitizeHtml, never before: the sanitizer unwraps every tag+ * outside its allowlist and strips all attributes, so it would demolish the+ * MathML. Running after is also why the allowlist needs no widening — this+ * markup is GENERATED by us from LaTeX source, never accepted from the author.+ * Temml runs with trust off, so \href and friends are inert.+ */+const mathCache = new Map<string, string>()++/** Undo the entity escaping sanitizeHtml applied, so `x < y` reaches TeX as `x < y`. */+function decodeEntities(s: string): string {+ if (s.indexOf('&') < 0) return s+ const ta = document.createElement('textarea')+ ta.innerHTML = s+ return ta.value+}++function renderMath(src: string, display: boolean): string | null {+ const key = (display ? 'D' : 'I') + src+ const hit = mathCache.get(key)+ if (hit !== undefined) return hit || null+ let out: string | null = null+ try {+ out = temml.renderToString(decodeEntities(src), { displayMode: display, throwOnError: true, trust: false })+ } catch {+ out = null // not valid TeX — leave the author's text exactly as typed+ }+ mathCache.set(key, out ?? '')+ return out+}++export function resolveMath(html: string): string {+ if (html.indexOf('$') < 0) return html+ // $$…$$ first (display), then $…$ (inline). The inline form is deliberately+ // fussy so ordinary prose survives: no whitespace just inside the delimiters+ // and no digit straight after the closer, which is what keeps "it costs $5+ // and $10" from parsing as math. A backslash-escaped \$ is a literal dollar.+ let out = html.replace(/(^|[^\\])\$\$([^$]+?)\$\$/g, (m, pre: string, src: string) => {+ const ml = renderMath(src, true)+ return ml ? pre + ml : m+ })+ out = out.replace(/(^|[^\\$])\$(\S(?:[^$\n]*?\S)?)\$(?!\d)/g, (m, pre: string, src: string) => {+ const ml = renderMath(src, false)+ return ml ? pre + ml : m+ })+ return out.replace(/\\\$/g, '$') // the escape has done its job+}+const ALLOWED_TAGS = new Set(['B', 'I', 'U', 'BR', 'SPAN', 'DIV', 'P', 'STRONG', 'EM', 'S', 'CODE'])/** Keep pasted/edited rich text down to a safe inline subset. */@@ -448,7 +508,7 @@ export function renderElement(el: SlideElement, doc: BentoDoc, opts: RenderOptsinner.style.lineHeight = String(el.lineHeight)if (el.letterSpacing) inner.style.letterSpacing = `${el.letterSpacing}px`inner.style.width = '100%'- inner.innerHTML = sanitizeHtml(resolveFields(el.html, opts.fields))+ inner.innerHTML = resolveMath(sanitizeHtml(resolveFields(el.html, opts.fields)))// layout placeholder: prompt while empty (editor), gone while presentingconst isEmpty = !inner.textContent?.trim() && !el.html.includes('<img')if (el.placeholder && isEmpty) {