@openmaic/renderer 0.1.16 → 0.1.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/dist/utils/inlineMath.d.ts +1 -1
- package/dist/utils/inlineMath.js +13 -2
- package/dist/utils/inlineMath.js.map +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -112,8 +112,9 @@ Use `mathPriority="background"` for thumbnails: newly mounted or changed content
|
|
|
112
112
|
shares a copy of the frame's remaining allowance after foreground layout effects,
|
|
113
113
|
before paint. This leaves foreground capacity available if the user switches slides
|
|
114
114
|
after thumbnails mount in the same frame; that frame may use both allowances.
|
|
115
|
-
Remaining formulas
|
|
116
|
-
parent rerenders do not advance that queued work.
|
|
115
|
+
Remaining formulas stay hidden until rendered in idle time after foreground
|
|
116
|
+
canvases; unrelated parent rerenders do not advance that queued work. Formulas
|
|
117
|
+
that cannot be typeset still appear as text. Snapshot APIs still finish all
|
|
117
118
|
formulas synchronously within the existing per-prose-root hard caps.
|
|
118
119
|
|
|
119
120
|
### Play-time effects
|
|
@@ -39,7 +39,7 @@ export interface RenderInlineMathOptions {
|
|
|
39
39
|
* Typeset the inline formulas under `root`. Each `span[data-inline-math]` is
|
|
40
40
|
* replaced by a KaTeX render of its source carrying the same attribute (the
|
|
41
41
|
* editor's storage shape); a source that cannot be typeset is shown as text.
|
|
42
|
-
* Returns `true` when
|
|
42
|
+
* Returns `true` when the budget deferred formulas; pending sources stay hidden.
|
|
43
43
|
*/
|
|
44
44
|
export declare function renderInlineMath(root: ParentNode, options?: RenderInlineMathOptions): boolean;
|
|
45
45
|
/**
|
package/dist/utils/inlineMath.js
CHANGED
|
@@ -104,8 +104,15 @@ function typeset(doc, latex) {
|
|
|
104
104
|
}
|
|
105
105
|
/** Formulas shown as text because they fell past a root's hard cap. */
|
|
106
106
|
const capped = new WeakSet();
|
|
107
|
+
function hidePendingMath(root) {
|
|
108
|
+
for (const element of root.querySelectorAll(`span[${INLINE_MATH_ATTRIBUTE}]`)) {
|
|
109
|
+
if (!handled.has(element))
|
|
110
|
+
element.style.visibility = 'hidden';
|
|
111
|
+
}
|
|
112
|
+
}
|
|
107
113
|
function showSource(element, latex) {
|
|
108
114
|
element.textContent = latex;
|
|
115
|
+
element.style.removeProperty('visibility');
|
|
109
116
|
handled.add(element);
|
|
110
117
|
}
|
|
111
118
|
/** Show a formula past the hard cap as its source text, whatever it shows now. */
|
|
@@ -123,7 +130,7 @@ function showCapped(element, latex) {
|
|
|
123
130
|
* Typeset the inline formulas under `root`. Each `span[data-inline-math]` is
|
|
124
131
|
* replaced by a KaTeX render of its source carrying the same attribute (the
|
|
125
132
|
* editor's storage shape); a source that cannot be typeset is shown as text.
|
|
126
|
-
* Returns `true` when
|
|
133
|
+
* Returns `true` when the budget deferred formulas; pending sources stay hidden.
|
|
127
134
|
*/
|
|
128
135
|
function renderInlineMath(root, options = {}) {
|
|
129
136
|
return renderPass(root, options, newBudget());
|
|
@@ -194,6 +201,8 @@ function renderPass(root, options, budget) {
|
|
|
194
201
|
deferredTypesets.delete(element);
|
|
195
202
|
element.replaceWith(formula);
|
|
196
203
|
}
|
|
204
|
+
if (pending)
|
|
205
|
+
hidePendingMath(root);
|
|
197
206
|
return pending;
|
|
198
207
|
}
|
|
199
208
|
/**
|
|
@@ -401,8 +410,10 @@ function useInlineMath(ref, html) {
|
|
|
401
410
|
if (before?.root === root &&
|
|
402
411
|
before.html === html &&
|
|
403
412
|
before.priority === priority &&
|
|
404
|
-
liveMath.isQueued(root))
|
|
413
|
+
liveMath.isQueued(root)) {
|
|
414
|
+
hidePendingMath(root);
|
|
405
415
|
return;
|
|
416
|
+
}
|
|
406
417
|
liveMath.render(root, priority);
|
|
407
418
|
});
|
|
408
419
|
// Only clean up on unmount: per-commit removal would discard pending queue
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inlineMath.js","sources":["../../src/utils/inlineMath.ts"],"sourcesContent":["'use client';\n\nimport { createContext, useContext, useLayoutEffect, useMemo, useRef, type RefObject } from 'react';\nimport katex from 'katex';\nimport { safeKatexOptions } from '@openmaic/dsl';\n\n/**\n * Inline formulas in slide prose. Stored prose carries each formula as LaTeX\n * source (`<span data-inline-math=\"LATEX\">LATEX</span>`); older or unsaved\n * content may still carry a rendered KaTeX tree with the same attribute. The\n * renderer typesets every such span in the browser from its source.\n */\nexport const INLINE_MATH_ATTRIBUTE = 'data-inline-math';\n\n/**\n * Marks an element whose injected prose is one typesetting root (a text box,\n * a shape label, a table), so callers that typeset a whole slide at once use\n * the same roots, budgets and caps as the live elements.\n */\nexport const INLINE_MATH_ROOT_ATTRIBUTE = 'data-inline-math-root';\n\n/** Longest source typeset; longer sources are shown as plain LaTeX text. */\nexport const MAX_INLINE_MATH_SOURCE = 2_000;\n\n/**\n * Bound uncached typesetting work in a batch. Live prose roots share a batch;\n * standalone renderInlineMath calls get their own. Ordinary slides fit before\n * paint; mixed/dense slides may defer even short formulas to idle time.\n */\nexport const INLINE_MATH_SYNC_SOURCE_BUDGET = 4_000;\nexport const INLINE_MATH_SYNC_FORMULA_BUDGET = 100;\n\n/**\n * Also bound inserted markup, including cache hits: short matrix sources can\n * expand to thousands of nodes whose style/layout cost comes after typesetting.\n * Uses the serialized size already recorded by the cache, not a DOM traversal.\n * Leave room for dense ordinary slides (e.g. 32 integrals/sums across text boxes).\n */\nconst INLINE_MATH_SYNC_MARKUP_BUDGET = 256_000;\n\n/**\n * Hard cap per prose root, counting every formula in document order: past it,\n * formulas are shown as their LaTeX text and never typeset.\n */\nexport const INLINE_MATH_MAX_ROOT_SOURCE = 50_000;\nexport const INLINE_MATH_MAX_ROOT_FORMULAS = 1_000;\n\n/** Formula elements this module already handled, so a repeated pass skips them. */\nconst handled = new WeakSet<Element>();\n\n/**\n * Typeset formulas by source, cloned on use: React may rewrite the injected\n * markup on any re-render, and re-typesetting the same source must stay\n * cheap. Bounded by the size of the cached markup, counted in serialized\n * characters (an estimate, not heap bytes); large renders are not kept.\n */\nconst TYPESET_CACHE_MAX_MARKUP = 2_000_000;\nconst TYPESET_CACHE_MAX_ENTRY = 64_000;\ntype TypesetEntry = { readonly formula: Element | null; readonly size: number };\nconst typesetCache = new Map<string, TypesetEntry>();\nlet typesetCacheSize = 0;\n// Keep a rejected render with its source node until it can be inserted. Unlike\n// the shared cache, this also covers large entries and cannot be overwritten by\n// another root. Replacing/removing the prose releases its pending renders.\nconst deferredTypesets = new WeakMap<Element, { latex: string; entry: TypesetEntry }>();\n\n/** Typeset one formula, or `null` to keep its source as text. */\nfunction typesetUncached(doc: Document, latex: string): Element | null {\n if (!latex.trim() || latex.length > MAX_INLINE_MATH_SOURCE) return null;\n const host = doc.createElement('span');\n try {\n // Authored input: `safeKatexOptions` forces `trust: false`, makes\n // formula-defined macros inert, bounds expansion, and builds a fresh\n // `macros` object per call (KaTeX writes global definitions into it).\n katex.render(\n latex,\n host,\n safeKatexOptions({\n displayMode: false,\n output: 'html',\n throwOnError: false,\n strict: 'ignore',\n }),\n );\n } catch {\n // KaTeX refuses to run in a quirks-mode document (no doctype); the source\n // then stays as text.\n return null;\n }\n const formula = host.firstElementChild;\n formula?.setAttribute(INLINE_MATH_ATTRIBUTE, latex);\n return formula;\n}\n\nfunction typeset(doc: Document, latex: string): TypesetEntry {\n let entry = typesetCache.get(latex);\n if (entry) {\n // Refresh recency.\n typesetCache.delete(latex);\n typesetCache.set(latex, entry);\n } else {\n const formula = typesetUncached(doc, latex);\n entry = { formula, size: latex.length + (formula?.outerHTML.length ?? 0) };\n if (entry.size <= TYPESET_CACHE_MAX_ENTRY) {\n typesetCache.set(latex, entry);\n typesetCacheSize += entry.size;\n for (const [key, value] of typesetCache) {\n if (typesetCacheSize <= TYPESET_CACHE_MAX_MARKUP) break;\n typesetCache.delete(key);\n typesetCacheSize -= value.size;\n }\n }\n }\n return entry;\n}\n\nexport interface RenderInlineMathOptions {\n /**\n * Typeset every formula now, ignoring the per-pass budget (the hard cap\n * still applies). For callers that capture the result right away, such as\n * slide snapshots.\n */\n readonly complete?: boolean;\n}\n\n/** Formulas shown as text because they fell past a root's hard cap. */\nconst capped = new WeakSet<Element>();\n\nfunction showSource(element: Element, latex: string): void {\n element.textContent = latex;\n handled.add(element);\n}\n\n/** Show a formula past the hard cap as its source text, whatever it shows now. */\nfunction showCapped(element: Element, latex: string): void {\n if (capped.has(element)) return;\n const span = (element.ownerDocument ?? document).createElement('span');\n span.setAttribute(INLINE_MATH_ATTRIBUTE, latex);\n span.textContent = latex;\n handled.add(span);\n capped.add(span);\n element.replaceWith(span);\n}\n\n/**\n * Typeset the inline formulas under `root`. Each `span[data-inline-math]` is\n * replaced by a KaTeX render of its source carrying the same attribute (the\n * editor's storage shape); a source that cannot be typeset is shown as text.\n * Returns `true` when formulas were left for a later pass by the budget.\n */\nexport function renderInlineMath(root: ParentNode, options: RenderInlineMathOptions = {}): boolean {\n return renderPass(root, options, newBudget());\n}\n\ntype TypesetBudget = { source: number; formulas: number; markup: number; full: boolean };\n\nfunction newBudget(): TypesetBudget {\n return { source: 0, formulas: 0, markup: 0, full: false };\n}\n\nfunction renderPass(\n root: ParentNode,\n options: RenderInlineMathOptions,\n budget: TypesetBudget,\n): boolean {\n const doc = (root as Node).ownerDocument ?? (root as Document);\n let rootSource = 0;\n let rootFormulas = 0;\n let pending = false;\n for (const element of root.querySelectorAll(`span[${INLINE_MATH_ATTRIBUTE}]`)) {\n // Inside a formula replaced earlier in this pass.\n if (!(root as Node).contains(element)) continue;\n const latex = element.getAttribute(INLINE_MATH_ATTRIBUTE) ?? '';\n rootSource += latex.length;\n rootFormulas += 1;\n // The cap depends only on document order within the root, so a formula\n // ends up the same whatever earlier passes did with it.\n if (rootSource > INLINE_MATH_MAX_ROOT_SOURCE || rootFormulas > INLINE_MATH_MAX_ROOT_FORMULAS) {\n showCapped(element, latex);\n continue;\n }\n if (handled.has(element) && !capped.has(element)) continue;\n const deferred = deferredTypesets.get(element);\n const prepared = deferred?.latex === latex ? deferred.entry : undefined;\n const cached = prepared ?? typesetCache.get(latex);\n // Preserve source order within a root, but let a later root use cached\n // formulas that fit in the space left by a rejected large formula.\n if (!options.complete && (pending || (budget.full && !cached))) {\n pending = true;\n continue;\n }\n if (!cached) {\n if (\n !options.complete &&\n budget.formulas > 0 &&\n (budget.source + latex.length > INLINE_MATH_SYNC_SOURCE_BUDGET ||\n budget.formulas >= INLINE_MATH_SYNC_FORMULA_BUDGET)\n ) {\n budget.full = true;\n pending = true;\n continue;\n }\n budget.source += latex.length;\n budget.formulas += 1;\n }\n const entry = prepared ?? typeset(doc, latex);\n if (!entry.formula) {\n showSource(element, latex);\n continue;\n }\n // Always allow one formula to make progress, even if it exceeds a batch.\n if (\n !options.complete &&\n budget.markup > 0 &&\n budget.markup + entry.size > INLINE_MATH_SYNC_MARKUP_BUDGET\n ) {\n budget.full = true;\n pending = true;\n deferredTypesets.set(element, { latex, entry });\n continue;\n }\n budget.markup += entry.size;\n const formula =\n entry.formula.ownerDocument === doc\n ? (entry.formula.cloneNode(true) as Element)\n : (doc.importNode(entry.formula, true) as Element);\n handled.add(formula);\n deferredTypesets.delete(element);\n element.replaceWith(formula);\n }\n return pending;\n}\n\n/**\n * Typeset every formula under `container` now, root by root (each element\n * marked with {@link INLINE_MATH_ROOT_ATTRIBUTE}), so each root keeps its own\n * hard cap exactly as the live elements apply it. For snapshots, which\n * capture right away instead of waiting for idle time.\n */\nexport function completeInlineMath(container: Element): void {\n const roots = [...container.querySelectorAll(`[${INLINE_MATH_ROOT_ATTRIBUTE}]`)];\n if (container.hasAttribute(INLINE_MATH_ROOT_ATTRIBUTE)) roots.unshift(container);\n for (const root of roots) renderInlineMath(root, { complete: true });\n}\n\n/**\n * A `dangerouslySetInnerHTML` value that keeps its identity while `html` is\n * unchanged. React rewrites injected markup whenever it receives a new value\n * object, which would discard typeset formulas and any idle progress on each\n * re-render; a stable value leaves the DOM alone.\n */\nexport function useInnerHtml(html: string): { __html: string } {\n return useMemo(() => ({ __html: html }), [html]);\n}\n\n/** {@link useInnerHtml} for a grid of cells (table text), keyed on every cell's markup. */\nexport function useInnerHtmlGrid(cells: readonly (readonly string[])[]): { __html: string }[][] {\n const key = JSON.stringify(cells);\n return useMemo(\n () => (JSON.parse(key) as string[][]).map((row) => row.map((html) => ({ __html: html }))),\n [key],\n );\n}\n\ntype IdleHandle = { cancel(): void };\n\ntype IdleScope = typeof globalThis & {\n requestIdleCallback?: (callback: () => void, options?: { timeout: number }) => number;\n cancelIdleCallback?: (handle: number) => void;\n};\n\n/**\n * Run `run` when the page is idle. The scheduling functions are read once,\n * here, and the handle is always cancelled with the function from the same\n * pair: the global may be replaced or removed between scheduling and\n * cancelling (polyfills, test stubs), and a handle from one implementation\n * means nothing to another.\n */\nfunction whenIdle(run: () => void): IdleHandle {\n const scope = globalThis as IdleScope;\n const request = scope.requestIdleCallback;\n const cancel = scope.cancelIdleCallback;\n if (typeof request === 'function' && typeof cancel === 'function') {\n const handle = request.call(scope, run, { timeout: 500 });\n return { cancel: () => cancel.call(scope, handle) };\n }\n const schedule = scope.setTimeout;\n const clear = scope.clearTimeout;\n const handle = schedule.call(scope, run, 16);\n return { cancel: () => clear.call(scope, handle) };\n}\n\ntype MathPriority = 'normal' | 'background';\nexport const InlineMathPriorityContext = createContext<MathPriority>('normal');\n\n/**\n * Own the live queues and frame allowances. Background roots share a copy of\n * the remaining foreground allowance, so an earlier thumbnail commit cannot\n * spend the next foreground commit's budget. Neither is renewed on removal.\n */\nfunction createLiveMath() {\n // Idle work rotates roots within each priority, with foreground canvases first.\n const queuedRoots = new Map<Element, MathPriority>();\n // Only newly admitted background roots may spend the remaining frame allowance.\n const prePaintCandidates = new Set<Element>();\n let frameBudget: TypesetBudget | null = null;\n let backgroundBudget: TypesetBudget | null = null;\n let cancelFrameReset: (() => void) | null = null;\n let idleJob: { cancel?: () => void } | null = null;\n let prePaintScheduled = false;\n\n function resetFrameBudget(): void {\n cancelFrameReset?.();\n cancelFrameReset = null;\n frameBudget = null;\n backgroundBudget = null;\n }\n\n function frameAllowance(): TypesetBudget {\n if (!frameBudget) {\n const budget = (frameBudget = newBudget());\n const reset = () => {\n if (frameBudget === budget) {\n frameBudget = null;\n backgroundBudget = null;\n cancelFrameReset = null;\n }\n };\n if (\n typeof requestAnimationFrame === 'function' &&\n typeof cancelAnimationFrame === 'function'\n ) {\n const cancel = cancelAnimationFrame;\n const handle = requestAnimationFrame(reset);\n cancelFrameReset = () => cancel(handle);\n } else {\n const cancel = clearTimeout;\n const handle = setTimeout(reset, 16);\n cancelFrameReset = () => cancel(handle);\n }\n }\n return frameBudget;\n }\n\n function renderIdleRoots(priority: MathPriority, budget: TypesetBudget): void {\n for (const [root, queuedPriority] of [...queuedRoots]) {\n if (queuedPriority !== priority) continue;\n queuedRoots.delete(root);\n if (root.isConnected && renderPass(root, {}, budget)) queuedRoots.set(root, priority);\n if (budget.full) break;\n }\n }\n\n function scheduleIdle(): void {\n if (!queuedRoots.size) {\n idleJob?.cancel?.();\n idleJob = null;\n return;\n }\n if (idleJob) return;\n const job: { cancel?: () => void } = {};\n idleJob = job;\n job.cancel = whenIdle(() => {\n // A cancelled callback must not drain work queued by a later mount.\n if (idleJob !== job) return;\n idleJob = null;\n resetFrameBudget();\n const budget = newBudget();\n for (const priority of ['normal', 'background'] as const) {\n renderIdleRoots(priority, budget);\n if (budget.full) break;\n }\n scheduleIdle();\n }).cancel;\n }\n\n function flushPrePaint(): void {\n prePaintScheduled = false;\n if (!prePaintCandidates.size) return;\n const budget = (backgroundBudget ??= { ...frameAllowance() });\n // Visit every newly admitted root: cached formulas may fit after an earlier\n // root fills the allowance. Older queued roots remain in idle time.\n for (const root of prePaintCandidates) {\n queuedRoots.delete(root);\n if (root.isConnected && renderPass(root, {}, budget)) queuedRoots.set(root, 'background');\n }\n prePaintCandidates.clear();\n scheduleIdle();\n }\n\n return {\n isQueued: (root: Element): boolean => queuedRoots.has(root),\n\n render(root: Element, priority: MathPriority): void {\n if (priority === 'background') {\n prePaintCandidates.add(root);\n if (!prePaintScheduled) {\n prePaintScheduled = true;\n queueMicrotask(flushPrePaint);\n }\n return;\n }\n prePaintCandidates.delete(root);\n if (renderPass(root, {}, frameAllowance())) queuedRoots.set(root, priority);\n else queuedRoots.delete(root);\n scheduleIdle();\n },\n\n remove(root: Element): void {\n prePaintCandidates.delete(root);\n queuedRoots.delete(root);\n if (!queuedRoots.size) {\n idleJob?.cancel?.();\n idleJob = null;\n }\n },\n };\n}\n\nconst liveMath = createLiveMath();\n\n/**\n * Typeset the inline formulas of prose injected into `ref` as `html`. Runs\n * after every commit, before paint: React may rewrite the injected markup on\n * any re-render (not only when `html` changes), which would put the stored\n * source spans back. Formulas already typeset are skipped and cached renders\n * are cloned, so a commit that left the markup alone costs one query. What the\n * shared budget leaves over is typeset in idle time, using the current markup.\n * Pending roots stay in that queue on unchanged commits (including when an\n * external caller rewrites the HTML). New content can use the current frame's\n * synchronous allowance. Unmounting or replacing a root removes its queued work.\n * Foreground roots run in layout effects; background roots use the remaining\n * allowance in a microtask, following the nearest InlineMathPriorityContext.\n * Never updates React state.\n */\nexport function useInlineMath(ref: RefObject<Element | null>, html: string): void {\n const priority = useContext(InlineMathPriorityContext);\n const previous = useRef<{ root: Element | null; html: string; priority: MathPriority }>(null);\n useLayoutEffect(() => {\n const root = ref.current;\n const before = previous.current;\n if (before?.root && before.root !== root) liveMath.remove(before.root);\n previous.current = { root, html, priority };\n if (!root) return;\n if (!html.includes(INLINE_MATH_ATTRIBUTE)) {\n liveMath.remove(root);\n return;\n }\n if (\n before?.root === root &&\n before.html === html &&\n before.priority === priority &&\n liveMath.isQueued(root)\n )\n return;\n liveMath.render(root, priority);\n });\n // Only clean up on unmount: per-commit removal would discard pending queue\n // membership and let unchanged rerenders reenter the pre-paint path.\n useLayoutEffect(() => {\n return () => {\n if (previous.current?.root) liveMath.remove(previous.current.root);\n previous.current = null;\n };\n }, []);\n}\n"],"names":[],"mappings":";;;;;AAMA;;;;;AAKG;AACI;AAEP;;;;AAIG;AACI;AAEP;AACO;AAEP;;;;AAIG;AACI;AACA;AAEP;;;;;AAKG;AACH;AAEA;;;AAGG;AACI;AACA;AAEP;AACA;AAEA;;;;;AAKG;AACH;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;;AAC8D;;AAE5D;;;;;AAQM;AACA;AACA;AACA;AACD;;AAEH;;;AAGA;;AAEF;AACA;AACA;AACF;AAEA;;;;AAII;AACA;;;;;AAIA;AACE;AACA;;;;AAGE;AACA;;;;AAIN;AACF;AAWA;AACA;AAEA;AACE;AACA;AACF;AAEA;AACA;AACE;;AACA;AACA;AACA;AACA;AACA;AACA;AACF;AAEA;;;;;AAKG;;;AAGH;AAIA;AACE;AACF;AAEA;AAKE;;;;AAIA;;AAEE;;;AAEA;;;;;AAKE;;;AAGF;;;AAEA;;;;AAIA;;;;;;;;AASM;AAEF;;;;AAIF;AACA;;;AAGF;AACE;;;;;;;AASA;;;;;AAKF;;;;AAKA;AACA;AACA;;AAEF;AACF;AAEA;;;;;AAKG;AACG;AACJ;AACA;AAAwD;;;AAE1D;AAEA;;;;;AAKG;AACG;AACJ;AACF;AAEA;AACM;;AAEJ;AAIF;AASA;;;;;;AAMG;AACH;;AAEE;AACA;;AAEE;AACA;;AAEF;AACA;AACA;AACA;AACF;;AAKA;;;;AAIG;AACH;;AAEE;;AAEA;;;;;;AAOA;;;;;;AAOA;;;;AAIM;;;;;AAKF;;AAGE;;AAGA;;;;;;;;;AAQJ;;AAGF;AACE;;;AAEE;;AACsD;;;;;AAK1D;AACE;AACE;;;;AAIF;;;;AAGA;;;;;AAIE;AACA;;AAEE;;;;AAGF;;;AAIJ;;;;;;;AAME;AACE;;AACsD;;;AAGxD;;;;;AAOE;AACE;;;;;;;AAOF;;AAC4C;;AACvC;AACL;;AAGF;AACE;AACA;AACA;AACE;;;;;AAKR;AAEA;AAEA;;;;;;;;;;;;;AAaG;AACG;AACJ;AACA;;AAEE;AACA;;AAC0C;;AAE1C;;;AAEE;;;AAGF;;;AAIE;;AAGF;AACF;;;;AAIE;AACE;;AACA;AACF;;AAEJ;;"}
|
|
1
|
+
{"version":3,"file":"inlineMath.js","sources":["../../src/utils/inlineMath.ts"],"sourcesContent":["'use client';\n\nimport { createContext, useContext, useLayoutEffect, useMemo, useRef, type RefObject } from 'react';\nimport katex from 'katex';\nimport { safeKatexOptions } from '@openmaic/dsl';\n\n/**\n * Inline formulas in slide prose. Stored prose carries each formula as LaTeX\n * source (`<span data-inline-math=\"LATEX\">LATEX</span>`); older or unsaved\n * content may still carry a rendered KaTeX tree with the same attribute. The\n * renderer typesets every such span in the browser from its source.\n */\nexport const INLINE_MATH_ATTRIBUTE = 'data-inline-math';\n\n/**\n * Marks an element whose injected prose is one typesetting root (a text box,\n * a shape label, a table), so callers that typeset a whole slide at once use\n * the same roots, budgets and caps as the live elements.\n */\nexport const INLINE_MATH_ROOT_ATTRIBUTE = 'data-inline-math-root';\n\n/** Longest source typeset; longer sources are shown as plain LaTeX text. */\nexport const MAX_INLINE_MATH_SOURCE = 2_000;\n\n/**\n * Bound uncached typesetting work in a batch. Live prose roots share a batch;\n * standalone renderInlineMath calls get their own. Ordinary slides fit before\n * paint; mixed/dense slides may defer even short formulas to idle time.\n */\nexport const INLINE_MATH_SYNC_SOURCE_BUDGET = 4_000;\nexport const INLINE_MATH_SYNC_FORMULA_BUDGET = 100;\n\n/**\n * Also bound inserted markup, including cache hits: short matrix sources can\n * expand to thousands of nodes whose style/layout cost comes after typesetting.\n * Uses the serialized size already recorded by the cache, not a DOM traversal.\n * Leave room for dense ordinary slides (e.g. 32 integrals/sums across text boxes).\n */\nconst INLINE_MATH_SYNC_MARKUP_BUDGET = 256_000;\n\n/**\n * Hard cap per prose root, counting every formula in document order: past it,\n * formulas are shown as their LaTeX text and never typeset.\n */\nexport const INLINE_MATH_MAX_ROOT_SOURCE = 50_000;\nexport const INLINE_MATH_MAX_ROOT_FORMULAS = 1_000;\n\n/** Formula elements this module already handled, so a repeated pass skips them. */\nconst handled = new WeakSet<Element>();\n\n/**\n * Typeset formulas by source, cloned on use: React may rewrite the injected\n * markup on any re-render, and re-typesetting the same source must stay\n * cheap. Bounded by the size of the cached markup, counted in serialized\n * characters (an estimate, not heap bytes); large renders are not kept.\n */\nconst TYPESET_CACHE_MAX_MARKUP = 2_000_000;\nconst TYPESET_CACHE_MAX_ENTRY = 64_000;\ntype TypesetEntry = { readonly formula: Element | null; readonly size: number };\nconst typesetCache = new Map<string, TypesetEntry>();\nlet typesetCacheSize = 0;\n// Keep a rejected render with its source node until it can be inserted. Unlike\n// the shared cache, this also covers large entries and cannot be overwritten by\n// another root. Replacing/removing the prose releases its pending renders.\nconst deferredTypesets = new WeakMap<Element, { latex: string; entry: TypesetEntry }>();\n\n/** Typeset one formula, or `null` to keep its source as text. */\nfunction typesetUncached(doc: Document, latex: string): Element | null {\n if (!latex.trim() || latex.length > MAX_INLINE_MATH_SOURCE) return null;\n const host = doc.createElement('span');\n try {\n // Authored input: `safeKatexOptions` forces `trust: false`, makes\n // formula-defined macros inert, bounds expansion, and builds a fresh\n // `macros` object per call (KaTeX writes global definitions into it).\n katex.render(\n latex,\n host,\n safeKatexOptions({\n displayMode: false,\n output: 'html',\n throwOnError: false,\n strict: 'ignore',\n }),\n );\n } catch {\n // KaTeX refuses to run in a quirks-mode document (no doctype); the source\n // then stays as text.\n return null;\n }\n const formula = host.firstElementChild;\n formula?.setAttribute(INLINE_MATH_ATTRIBUTE, latex);\n return formula;\n}\n\nfunction typeset(doc: Document, latex: string): TypesetEntry {\n let entry = typesetCache.get(latex);\n if (entry) {\n // Refresh recency.\n typesetCache.delete(latex);\n typesetCache.set(latex, entry);\n } else {\n const formula = typesetUncached(doc, latex);\n entry = { formula, size: latex.length + (formula?.outerHTML.length ?? 0) };\n if (entry.size <= TYPESET_CACHE_MAX_ENTRY) {\n typesetCache.set(latex, entry);\n typesetCacheSize += entry.size;\n for (const [key, value] of typesetCache) {\n if (typesetCacheSize <= TYPESET_CACHE_MAX_MARKUP) break;\n typesetCache.delete(key);\n typesetCacheSize -= value.size;\n }\n }\n }\n return entry;\n}\n\nexport interface RenderInlineMathOptions {\n /**\n * Typeset every formula now, ignoring the per-pass budget (the hard cap\n * still applies). For callers that capture the result right away, such as\n * slide snapshots.\n */\n readonly complete?: boolean;\n}\n\n/** Formulas shown as text because they fell past a root's hard cap. */\nconst capped = new WeakSet<Element>();\n\nfunction hidePendingMath(root: ParentNode): void {\n for (const element of root.querySelectorAll<HTMLElement>(`span[${INLINE_MATH_ATTRIBUTE}]`)) {\n if (!handled.has(element)) element.style.visibility = 'hidden';\n }\n}\n\nfunction showSource(element: HTMLElement, latex: string): void {\n element.textContent = latex;\n element.style.removeProperty('visibility');\n handled.add(element);\n}\n\n/** Show a formula past the hard cap as its source text, whatever it shows now. */\nfunction showCapped(element: Element, latex: string): void {\n if (capped.has(element)) return;\n const span = (element.ownerDocument ?? document).createElement('span');\n span.setAttribute(INLINE_MATH_ATTRIBUTE, latex);\n span.textContent = latex;\n handled.add(span);\n capped.add(span);\n element.replaceWith(span);\n}\n\n/**\n * Typeset the inline formulas under `root`. Each `span[data-inline-math]` is\n * replaced by a KaTeX render of its source carrying the same attribute (the\n * editor's storage shape); a source that cannot be typeset is shown as text.\n * Returns `true` when the budget deferred formulas; pending sources stay hidden.\n */\nexport function renderInlineMath(root: ParentNode, options: RenderInlineMathOptions = {}): boolean {\n return renderPass(root, options, newBudget());\n}\n\ntype TypesetBudget = { source: number; formulas: number; markup: number; full: boolean };\n\nfunction newBudget(): TypesetBudget {\n return { source: 0, formulas: 0, markup: 0, full: false };\n}\n\nfunction renderPass(\n root: ParentNode,\n options: RenderInlineMathOptions,\n budget: TypesetBudget,\n): boolean {\n const doc = (root as Node).ownerDocument ?? (root as Document);\n let rootSource = 0;\n let rootFormulas = 0;\n let pending = false;\n for (const element of root.querySelectorAll<HTMLElement>(`span[${INLINE_MATH_ATTRIBUTE}]`)) {\n // Inside a formula replaced earlier in this pass.\n if (!(root as Node).contains(element)) continue;\n const latex = element.getAttribute(INLINE_MATH_ATTRIBUTE) ?? '';\n rootSource += latex.length;\n rootFormulas += 1;\n // The cap depends only on document order within the root, so a formula\n // ends up the same whatever earlier passes did with it.\n if (rootSource > INLINE_MATH_MAX_ROOT_SOURCE || rootFormulas > INLINE_MATH_MAX_ROOT_FORMULAS) {\n showCapped(element, latex);\n continue;\n }\n if (handled.has(element) && !capped.has(element)) continue;\n const deferred = deferredTypesets.get(element);\n const prepared = deferred?.latex === latex ? deferred.entry : undefined;\n const cached = prepared ?? typesetCache.get(latex);\n // Preserve source order within a root, but let a later root use cached\n // formulas that fit in the space left by a rejected large formula.\n if (!options.complete && (pending || (budget.full && !cached))) {\n pending = true;\n continue;\n }\n if (!cached) {\n if (\n !options.complete &&\n budget.formulas > 0 &&\n (budget.source + latex.length > INLINE_MATH_SYNC_SOURCE_BUDGET ||\n budget.formulas >= INLINE_MATH_SYNC_FORMULA_BUDGET)\n ) {\n budget.full = true;\n pending = true;\n continue;\n }\n budget.source += latex.length;\n budget.formulas += 1;\n }\n const entry = prepared ?? typeset(doc, latex);\n if (!entry.formula) {\n showSource(element, latex);\n continue;\n }\n // Always allow one formula to make progress, even if it exceeds a batch.\n if (\n !options.complete &&\n budget.markup > 0 &&\n budget.markup + entry.size > INLINE_MATH_SYNC_MARKUP_BUDGET\n ) {\n budget.full = true;\n pending = true;\n deferredTypesets.set(element, { latex, entry });\n continue;\n }\n budget.markup += entry.size;\n const formula =\n entry.formula.ownerDocument === doc\n ? (entry.formula.cloneNode(true) as Element)\n : (doc.importNode(entry.formula, true) as Element);\n handled.add(formula);\n deferredTypesets.delete(element);\n element.replaceWith(formula);\n }\n if (pending) hidePendingMath(root);\n return pending;\n}\n\n/**\n * Typeset every formula under `container` now, root by root (each element\n * marked with {@link INLINE_MATH_ROOT_ATTRIBUTE}), so each root keeps its own\n * hard cap exactly as the live elements apply it. For snapshots, which\n * capture right away instead of waiting for idle time.\n */\nexport function completeInlineMath(container: Element): void {\n const roots = [...container.querySelectorAll(`[${INLINE_MATH_ROOT_ATTRIBUTE}]`)];\n if (container.hasAttribute(INLINE_MATH_ROOT_ATTRIBUTE)) roots.unshift(container);\n for (const root of roots) renderInlineMath(root, { complete: true });\n}\n\n/**\n * A `dangerouslySetInnerHTML` value that keeps its identity while `html` is\n * unchanged. React rewrites injected markup whenever it receives a new value\n * object, which would discard typeset formulas and any idle progress on each\n * re-render; a stable value leaves the DOM alone.\n */\nexport function useInnerHtml(html: string): { __html: string } {\n return useMemo(() => ({ __html: html }), [html]);\n}\n\n/** {@link useInnerHtml} for a grid of cells (table text), keyed on every cell's markup. */\nexport function useInnerHtmlGrid(cells: readonly (readonly string[])[]): { __html: string }[][] {\n const key = JSON.stringify(cells);\n return useMemo(\n () => (JSON.parse(key) as string[][]).map((row) => row.map((html) => ({ __html: html }))),\n [key],\n );\n}\n\ntype IdleHandle = { cancel(): void };\n\ntype IdleScope = typeof globalThis & {\n requestIdleCallback?: (callback: () => void, options?: { timeout: number }) => number;\n cancelIdleCallback?: (handle: number) => void;\n};\n\n/**\n * Run `run` when the page is idle. The scheduling functions are read once,\n * here, and the handle is always cancelled with the function from the same\n * pair: the global may be replaced or removed between scheduling and\n * cancelling (polyfills, test stubs), and a handle from one implementation\n * means nothing to another.\n */\nfunction whenIdle(run: () => void): IdleHandle {\n const scope = globalThis as IdleScope;\n const request = scope.requestIdleCallback;\n const cancel = scope.cancelIdleCallback;\n if (typeof request === 'function' && typeof cancel === 'function') {\n const handle = request.call(scope, run, { timeout: 500 });\n return { cancel: () => cancel.call(scope, handle) };\n }\n const schedule = scope.setTimeout;\n const clear = scope.clearTimeout;\n const handle = schedule.call(scope, run, 16);\n return { cancel: () => clear.call(scope, handle) };\n}\n\ntype MathPriority = 'normal' | 'background';\nexport const InlineMathPriorityContext = createContext<MathPriority>('normal');\n\n/**\n * Own the live queues and frame allowances. Background roots share a copy of\n * the remaining foreground allowance, so an earlier thumbnail commit cannot\n * spend the next foreground commit's budget. Neither is renewed on removal.\n */\nfunction createLiveMath() {\n // Idle work rotates roots within each priority, with foreground canvases first.\n const queuedRoots = new Map<Element, MathPriority>();\n // Only newly admitted background roots may spend the remaining frame allowance.\n const prePaintCandidates = new Set<Element>();\n let frameBudget: TypesetBudget | null = null;\n let backgroundBudget: TypesetBudget | null = null;\n let cancelFrameReset: (() => void) | null = null;\n let idleJob: { cancel?: () => void } | null = null;\n let prePaintScheduled = false;\n\n function resetFrameBudget(): void {\n cancelFrameReset?.();\n cancelFrameReset = null;\n frameBudget = null;\n backgroundBudget = null;\n }\n\n function frameAllowance(): TypesetBudget {\n if (!frameBudget) {\n const budget = (frameBudget = newBudget());\n const reset = () => {\n if (frameBudget === budget) {\n frameBudget = null;\n backgroundBudget = null;\n cancelFrameReset = null;\n }\n };\n if (\n typeof requestAnimationFrame === 'function' &&\n typeof cancelAnimationFrame === 'function'\n ) {\n const cancel = cancelAnimationFrame;\n const handle = requestAnimationFrame(reset);\n cancelFrameReset = () => cancel(handle);\n } else {\n const cancel = clearTimeout;\n const handle = setTimeout(reset, 16);\n cancelFrameReset = () => cancel(handle);\n }\n }\n return frameBudget;\n }\n\n function renderIdleRoots(priority: MathPriority, budget: TypesetBudget): void {\n for (const [root, queuedPriority] of [...queuedRoots]) {\n if (queuedPriority !== priority) continue;\n queuedRoots.delete(root);\n if (root.isConnected && renderPass(root, {}, budget)) queuedRoots.set(root, priority);\n if (budget.full) break;\n }\n }\n\n function scheduleIdle(): void {\n if (!queuedRoots.size) {\n idleJob?.cancel?.();\n idleJob = null;\n return;\n }\n if (idleJob) return;\n const job: { cancel?: () => void } = {};\n idleJob = job;\n job.cancel = whenIdle(() => {\n // A cancelled callback must not drain work queued by a later mount.\n if (idleJob !== job) return;\n idleJob = null;\n resetFrameBudget();\n const budget = newBudget();\n for (const priority of ['normal', 'background'] as const) {\n renderIdleRoots(priority, budget);\n if (budget.full) break;\n }\n scheduleIdle();\n }).cancel;\n }\n\n function flushPrePaint(): void {\n prePaintScheduled = false;\n if (!prePaintCandidates.size) return;\n const budget = (backgroundBudget ??= { ...frameAllowance() });\n // Visit every newly admitted root: cached formulas may fit after an earlier\n // root fills the allowance. Older queued roots remain in idle time.\n for (const root of prePaintCandidates) {\n queuedRoots.delete(root);\n if (root.isConnected && renderPass(root, {}, budget)) queuedRoots.set(root, 'background');\n }\n prePaintCandidates.clear();\n scheduleIdle();\n }\n\n return {\n isQueued: (root: Element): boolean => queuedRoots.has(root),\n\n render(root: Element, priority: MathPriority): void {\n if (priority === 'background') {\n prePaintCandidates.add(root);\n if (!prePaintScheduled) {\n prePaintScheduled = true;\n queueMicrotask(flushPrePaint);\n }\n return;\n }\n prePaintCandidates.delete(root);\n if (renderPass(root, {}, frameAllowance())) queuedRoots.set(root, priority);\n else queuedRoots.delete(root);\n scheduleIdle();\n },\n\n remove(root: Element): void {\n prePaintCandidates.delete(root);\n queuedRoots.delete(root);\n if (!queuedRoots.size) {\n idleJob?.cancel?.();\n idleJob = null;\n }\n },\n };\n}\n\nconst liveMath = createLiveMath();\n\n/**\n * Typeset the inline formulas of prose injected into `ref` as `html`. Runs\n * after every commit, before paint: React may rewrite the injected markup on\n * any re-render (not only when `html` changes), which would put the stored\n * source spans back. Formulas already typeset are skipped and cached renders\n * are cloned, so a commit that left the markup alone costs one query. What the\n * shared budget leaves over is typeset in idle time, using the current markup.\n * Pending roots stay in that queue on unchanged commits (including when an\n * external caller rewrites the HTML). New content can use the current frame's\n * synchronous allowance. Unmounting or replacing a root removes its queued work.\n * Foreground roots run in layout effects; background roots use the remaining\n * allowance in a microtask, following the nearest InlineMathPriorityContext.\n * Never updates React state.\n */\nexport function useInlineMath(ref: RefObject<Element | null>, html: string): void {\n const priority = useContext(InlineMathPriorityContext);\n const previous = useRef<{ root: Element | null; html: string; priority: MathPriority }>(null);\n useLayoutEffect(() => {\n const root = ref.current;\n const before = previous.current;\n if (before?.root && before.root !== root) liveMath.remove(before.root);\n previous.current = { root, html, priority };\n if (!root) return;\n if (!html.includes(INLINE_MATH_ATTRIBUTE)) {\n liveMath.remove(root);\n return;\n }\n if (\n before?.root === root &&\n before.html === html &&\n before.priority === priority &&\n liveMath.isQueued(root)\n ) {\n hidePendingMath(root);\n return;\n }\n liveMath.render(root, priority);\n });\n // Only clean up on unmount: per-commit removal would discard pending queue\n // membership and let unchanged rerenders reenter the pre-paint path.\n useLayoutEffect(() => {\n return () => {\n if (previous.current?.root) liveMath.remove(previous.current.root);\n previous.current = null;\n };\n }, []);\n}\n"],"names":[],"mappings":";;;;;AAMA;;;;;AAKG;AACI;AAEP;;;;AAIG;AACI;AAEP;AACO;AAEP;;;;AAIG;AACI;AACA;AAEP;;;;;AAKG;AACH;AAEA;;;AAGG;AACI;AACA;AAEP;AACA;AAEA;;;;;AAKG;AACH;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;;AAC8D;;AAE5D;;;;;AAQM;AACA;AACA;AACA;AACD;;AAEH;;;AAGA;;AAEF;AACA;AACA;AACF;AAEA;;;;AAII;AACA;;;;;AAIA;AACE;AACA;;;;AAGE;AACA;;;;AAIN;AACF;AAWA;AACA;AAEA;AACE;AACE;AAA2B;;AAE/B;AAEA;AACE;AACA;AACA;AACF;AAEA;AACA;AACE;;AACA;AACA;AACA;AACA;AACA;AACA;AACF;AAEA;;;;;AAKG;;;AAGH;AAIA;AACE;AACF;AAEA;AAKE;;;;AAIA;;AAEE;;;AAEA;;;;;AAKE;;;AAGF;;;AAEA;;;;AAIA;;;;;;;;AASM;AAEF;;;;AAIF;AACA;;;AAGF;AACE;;;;;;;AASA;;;;;AAKF;;;;AAKA;AACA;AACA;;AAEF;;AACA;AACF;AAEA;;;;;AAKG;AACG;AACJ;AACA;AAAwD;;;AAE1D;AAEA;;;;;AAKG;AACG;AACJ;AACF;AAEA;AACM;;AAEJ;AAIF;AASA;;;;;;AAMG;AACH;;AAEE;AACA;;AAEE;AACA;;AAEF;AACA;AACA;AACA;AACF;;AAKA;;;;AAIG;AACH;;AAEE;;AAEA;;;;;;AAOA;;;;;;AAOA;;;;AAIM;;;;;AAKF;;AAGE;;AAGA;;;;;;;;;AAQJ;;AAGF;AACE;;;AAEE;;AACsD;;;;;AAK1D;AACE;AACE;;;;AAIF;;;;AAGA;;;;;AAIE;AACA;;AAEE;;;;AAGF;;;AAIJ;;;;;;;AAME;AACE;;AACsD;;;AAGxD;;;;;AAOE;AACE;;;;;;;AAOF;;AAC4C;;AACvC;AACL;;AAGF;AACE;AACA;AACA;AACE;;;;;AAKR;AAEA;AAEA;;;;;;;;;;;;;AAaG;AACG;AACJ;AACA;;AAEE;AACA;;AAC0C;;AAE1C;;;AAEE;;;AAGF;;;AAIE;;;;AAKF;AACF;;;;AAIE;AACE;;AACA;AACF;;AAEJ;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openmaic/renderer",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.17",
|
|
4
4
|
"description": "React component for rendering PPTist-style Slide JSON, extracted from OpenMAIC.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -79,8 +79,8 @@
|
|
|
79
79
|
"lucide-react": "^0.562.0",
|
|
80
80
|
"tailwind-merge": "^3.4.0",
|
|
81
81
|
"tinycolor2": "^1.6.0",
|
|
82
|
-
"@openmaic/
|
|
83
|
-
"@openmaic/
|
|
82
|
+
"@openmaic/geometry": "^0.1.0",
|
|
83
|
+
"@openmaic/dsl": "^0.12.0"
|
|
84
84
|
},
|
|
85
85
|
"devDependencies": {
|
|
86
86
|
"@rollup/plugin-commonjs": "^28.0.1",
|