@openmaic/renderer 0.1.15 → 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 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 render in idle time after foreground canvases; unrelated
116
- parent rerenders do not advance that queued work. Snapshot APIs still finish all
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
@@ -13,4 +13,5 @@ export { useElementFill } from './shared/useElementFill';
13
13
  export { useElementOutline } from './shared/useElementOutline';
14
14
  export { useElementShadow } from './shared/useElementShadow';
15
15
  export { useElementFlip } from './shared/useElementFlip';
16
+ export { hasTextInsets } from './shared/hasTextInsets';
16
17
  export { getTextStyle } from './table/tableUtils';
@@ -13,5 +13,6 @@ export { useElementFill } from './shared/useElementFill.js';
13
13
  export { useElementOutline } from './shared/useElementOutline.js';
14
14
  export { useElementShadow } from './shared/useElementShadow.js';
15
15
  export { useElementFlip } from './shared/useElementFlip.js';
16
+ export { hasTextInsets } from './shared/hasTextInsets.js';
16
17
  export { getTextStyle } from './table/tableUtils.js';
17
18
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;"}
@@ -5,4 +5,4 @@ export interface BaseShapeElementProps {
5
5
  /** Replace the static Shape label with editor content. */
6
6
  renderLabel?: (element: PPTShapeElement, defaultContent: ReactNode) => ReactNode;
7
7
  }
8
- export declare function BaseShapeElement({ elementInfo, renderLabel }: BaseShapeElementProps): import("react/jsx-runtime").JSX.Element;
8
+ export declare function BaseShapeElement({ elementInfo, renderLabel }: BaseShapeElementProps): import("react/jsx-runtime").JSX.Element | null;
@@ -1,98 +1,34 @@
1
1
  "use client";
2
2
  import { jsx, jsxs } from 'react/jsx-runtime';
3
- import { useRef } from 'react';
3
+ import { useMemo, useRef } from 'react';
4
+ import { validateShapeGeometry, RENDER_PATH_LIMITS, shapeToTextFallback } from '@openmaic/geometry';
4
5
  import { useElementOutline } from '../shared/useElementOutline.js';
5
6
  import { useElementShadow } from '../shared/useElementShadow.js';
6
7
  import { useElementFlip } from '../shared/useElementFlip.js';
7
8
  import { useElementFill } from '../shared/useElementFill.js';
8
9
  import { GradientDefs } from './GradientDefs.js';
10
+ import { BaseTextElement } from '../text/BaseTextElement.js';
9
11
  import { PatternDefs } from './PatternDefs.js';
10
12
  import { preservesPlainTextLineBreaks } from '../../utils/richText.js';
11
13
  import { useInnerHtml, useInlineMath } from '../../utils/inlineMath.js';
14
+ import { hasTextInsets } from '../shared/hasTextInsets.js';
12
15
 
13
- /**
14
- * Bounding box of a path's coordinates (path/viewBox space). Uses control
15
- * points for curves (a safe superset). Handles the commands our shapes emit
16
- * (M/L/C/Q/S/H/V/A/T/Z, absolute). Returns null if no coordinates.
17
- */
18
- function pathCoordBBox(d) {
19
- const tokens = d.match(/[a-zA-Z]|-?\d*\.?\d+(?:e[-+]?\d+)?/gi);
20
- if (!tokens)
21
- return null;
22
- let i = 0;
23
- let cmd = '';
24
- let minX = Infinity;
25
- let minY = Infinity;
26
- let maxX = -Infinity;
27
- let maxY = -Infinity;
28
- const addX = (x) => {
29
- if (x < minX)
30
- minX = x;
31
- if (x > maxX)
32
- maxX = x;
33
- };
34
- const addY = (y) => {
35
- if (y < minY)
36
- minY = y;
37
- if (y > maxY)
38
- maxY = y;
39
- };
40
- const num = () => parseFloat(tokens[i++]);
41
- while (i < tokens.length) {
42
- // Path commands are single letters. Use an anchored test so number tokens
43
- // in scientific notation (e.g. "4.74e-16") aren't misread as commands.
44
- if (/^[a-zA-Z]$/.test(tokens[i])) {
45
- cmd = tokens[i];
46
- i++;
47
- }
48
- const c = cmd.toUpperCase();
49
- if (c === 'M' || c === 'L' || c === 'T') {
50
- addX(num());
51
- addY(num());
52
- }
53
- else if (c === 'C') {
54
- addX(num());
55
- addY(num());
56
- addX(num());
57
- addY(num());
58
- addX(num());
59
- addY(num());
60
- }
61
- else if (c === 'Q' || c === 'S') {
62
- addX(num());
63
- addY(num());
64
- addX(num());
65
- addY(num());
66
- }
67
- else if (c === 'H') {
68
- addX(num());
69
- }
70
- else if (c === 'V') {
71
- addY(num());
72
- }
73
- else if (c === 'A') {
74
- num();
75
- num();
76
- num();
77
- num();
78
- num();
79
- addX(num());
80
- addY(num());
81
- }
82
- else if (c === 'Z') ;
83
- else {
84
- i++; // unknown token, skip to avoid infinite loop
85
- }
86
- }
87
- if (!Number.isFinite(minX) ||
88
- !Number.isFinite(minY) ||
89
- !Number.isFinite(maxX) ||
90
- !Number.isFinite(maxY)) {
91
- return null;
16
+ function BaseShapeElement({ elementInfo, renderLabel }) {
17
+ const geometry = useMemo(() => validateShapeGeometry({
18
+ path: elementInfo.path,
19
+ viewBox: elementInfo.viewBox,
20
+ width: elementInfo.width,
21
+ height: elementInfo.height,
22
+ }, RENDER_PATH_LIMITS), [elementInfo.path, elementInfo.viewBox, elementInfo.width, elementInfo.height]);
23
+ if (!geometry.ok) {
24
+ const fallback = shapeToTextFallback(elementInfo);
25
+ return fallback ? (jsx("div", { "data-shape-geometry-error": geometry.error.code, children: jsx(BaseTextElement, { elementInfo: fallback, fillHeight: Boolean(renderLabel), renderContent: renderLabel ? (_text, content) => renderLabel(elementInfo, content) : undefined }) })) : null;
92
26
  }
93
- return { minX, minY, maxX, maxY };
27
+ return (jsx(ValidShapeElement, { elementInfo: elementInfo, renderLabel: renderLabel, geometry: geometry }));
94
28
  }
95
- function BaseShapeElement({ elementInfo, renderLabel }) {
29
+ function ValidShapeElement({ elementInfo, renderLabel, geometry, }) {
30
+ const width = elementInfo.width;
31
+ const height = elementInfo.height;
96
32
  const { fill } = useElementFill(elementInfo, 'base');
97
33
  const { outlineWidth, outlineColor, strokeDashArray } = useElementOutline(elementInfo.outline);
98
34
  const { shadowStyle } = useElementShadow(elementInfo.shadow);
@@ -114,7 +50,9 @@ function BaseShapeElement({ elementInfo, renderLabel }) {
114
50
  flexDirection: 'column',
115
51
  justifyContent,
116
52
  overflowWrap: 'break-word',
117
- lineHeight: text.lineHeight,
53
+ boxSizing: 'border-box',
54
+ padding: hasTextInsets(text.content) ? 0 : 10,
55
+ lineHeight: text.lineHeight ?? 1.625,
118
56
  letterSpacing: `${text.wordSpace || 0}px`,
119
57
  // PowerPoint/WPS 在 group flipH/flipV 时只镜像几何与位置,文字字形保持
120
58
  // 正向。父层 element-content 已应用 flipStyle 镜像 SVG path;这里给文字
@@ -129,8 +67,8 @@ function BaseShapeElement({ elementInfo, renderLabel }) {
129
67
  position: 'absolute',
130
68
  top: `${elementInfo.top}px`,
131
69
  left: `${elementInfo.left}px`,
132
- width: `${elementInfo.width}px`,
133
- height: `${elementInfo.height}px`,
70
+ width: `${width}px`,
71
+ height: `${height}px`,
134
72
  }, children: jsx("div", { className: "rotate-wrapper", style: {
135
73
  width: '100%',
136
74
  height: '100%',
@@ -153,9 +91,9 @@ function BaseShapeElement({ elementInfo, renderLabel }) {
153
91
  // exported PNG. Fix: grow the SVG viewport to contain the full path
154
92
  // bbox and offset it back, so the geometry renders in the exact same
155
93
  // place but nothing falls outside the captured viewport.
156
- const sx = elementInfo.width / (elementInfo.viewBox[0] || elementInfo.width || 1);
157
- const sy = elementInfo.height / (elementInfo.viewBox[1] || elementInfo.height || 1);
158
- const bbox = pathCoordBBox(elementInfo.path);
94
+ const sx = elementInfo.width / elementInfo.viewBox[0];
95
+ const sy = elementInfo.height / elementInfo.viewBox[1];
96
+ const bbox = geometry.bounds;
159
97
  const CAP = 4000; // guard against pathological coords blowing up the SVG
160
98
  let padL = 0;
161
99
  let padT = 0;
@@ -167,7 +105,7 @@ function BaseShapeElement({ elementInfo, renderLabel }) {
167
105
  padR = Math.min(CAP, Math.max(0, bbox.maxX * sx - elementInfo.width));
168
106
  padB = Math.min(CAP, Math.max(0, bbox.maxY * sy - elementInfo.height));
169
107
  }
170
- return (jsxs("svg", { overflow: "visible", width: elementInfo.width + padL + padR, height: elementInfo.height + padT + padB, style: {
108
+ return (jsxs("svg", { overflow: "visible", width: width + padL + padR, height: height + padT + padB, style: {
171
109
  position: 'absolute',
172
110
  left: -padL,
173
111
  top: -padT,
@@ -1 +1 @@
1
- {"version":3,"file":"BaseShapeElement.js","sources":["../../../src/elements/shape/BaseShapeElement.tsx"],"sourcesContent":["'use client';\n\nimport { useRef, type ReactNode } from 'react';\nimport type { PPTShapeElement, ShapeText } from '@openmaic/dsl';\nimport { useElementOutline } from '../shared/useElementOutline';\nimport { useElementShadow } from '../shared/useElementShadow';\nimport { useElementFlip } from '../shared/useElementFlip';\nimport { useElementFill } from '../shared/useElementFill';\nimport { GradientDefs } from './GradientDefs';\nimport { PatternDefs } from './PatternDefs';\nimport { preservesPlainTextLineBreaks } from '../../utils/richText';\nimport { useInlineMath, useInnerHtml } from '../../utils/inlineMath';\n\nexport interface BaseShapeElementProps {\n elementInfo: PPTShapeElement;\n /** Replace the static Shape label with editor content. */\n renderLabel?: (element: PPTShapeElement, defaultContent: ReactNode) => ReactNode;\n}\n\n/**\n * Bounding box of a path's coordinates (path/viewBox space). Uses control\n * points for curves (a safe superset). Handles the commands our shapes emit\n * (M/L/C/Q/S/H/V/A/T/Z, absolute). Returns null if no coordinates.\n */\nfunction pathCoordBBox(\n d: string,\n): { minX: number; minY: number; maxX: number; maxY: number } | null {\n const tokens = d.match(/[a-zA-Z]|-?\\d*\\.?\\d+(?:e[-+]?\\d+)?/gi);\n if (!tokens) return null;\n let i = 0;\n let cmd = '';\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n const addX = (x: number) => {\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n };\n const addY = (y: number) => {\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n };\n const num = () => parseFloat(tokens[i++]);\n while (i < tokens.length) {\n // Path commands are single letters. Use an anchored test so number tokens\n // in scientific notation (e.g. \"4.74e-16\") aren't misread as commands.\n if (/^[a-zA-Z]$/.test(tokens[i])) {\n cmd = tokens[i];\n i++;\n }\n const c = cmd.toUpperCase();\n if (c === 'M' || c === 'L' || c === 'T') {\n addX(num());\n addY(num());\n } else if (c === 'C') {\n addX(num());\n addY(num());\n addX(num());\n addY(num());\n addX(num());\n addY(num());\n } else if (c === 'Q' || c === 'S') {\n addX(num());\n addY(num());\n addX(num());\n addY(num());\n } else if (c === 'H') {\n addX(num());\n } else if (c === 'V') {\n addY(num());\n } else if (c === 'A') {\n num();\n num();\n num();\n num();\n num();\n addX(num());\n addY(num());\n } else if (c === 'Z') {\n // no coords\n } else {\n i++; // unknown token, skip to avoid infinite loop\n }\n }\n if (\n !Number.isFinite(minX) ||\n !Number.isFinite(minY) ||\n !Number.isFinite(maxX) ||\n !Number.isFinite(maxY)\n ) {\n return null;\n }\n return { minX, minY, maxX, maxY };\n}\n\nexport function BaseShapeElement({ elementInfo, renderLabel }: BaseShapeElementProps) {\n const { fill } = useElementFill(elementInfo, 'base');\n const { outlineWidth, outlineColor, strokeDashArray } = useElementOutline(elementInfo.outline);\n const { shadowStyle } = useElementShadow(elementInfo.shadow);\n const { flipStyle } = useElementFlip(elementInfo.flipH, elementInfo.flipV);\n\n const text: ShapeText = elementInfo.text || {\n content: '',\n align: 'middle',\n defaultFontName: 'Microsoft YaHei',\n defaultColor: '#333333',\n };\n\n const proseRef = useRef<HTMLDivElement>(null);\n const innerHtml = useInnerHtml(text.content);\n useInlineMath(proseRef, text.content);\n\n const justifyContent =\n text.align === 'top' ? 'flex-start' : text.align === 'bottom' ? 'flex-end' : 'center';\n const defaultLabelContent = (\n <div\n className=\"shape-text\"\n style={{\n position: 'absolute',\n inset: 0,\n display: 'flex',\n flexDirection: 'column',\n justifyContent,\n overflowWrap: 'break-word',\n lineHeight: text.lineHeight,\n letterSpacing: `${text.wordSpace || 0}px`,\n // PowerPoint/WPS 在 group flipH/flipV 时只镜像几何与位置,文字字形保持\n // 正向。父层 element-content 已应用 flipStyle 镜像 SVG path;这里给文字\n // 叠加同一个 flipStyle,两次 flip 抵消,让文字保持正向。\n transform: flipStyle,\n }}\n >\n <div\n ref={proseRef}\n data-inline-math-root=\"\"\n className=\"ProseMirror-static slide-renderer-prose\"\n style={{\n // @ts-expect-error CSS custom properties\n '--paragraphSpace': `${text.paragraphSpace === undefined ? 5 : text.paragraphSpace}px`,\n whiteSpace: preservesPlainTextLineBreaks(text.content) ? 'pre-line' : undefined,\n }}\n dangerouslySetInnerHTML={innerHtml}\n />\n </div>\n );\n\n return (\n <div\n className=\"base-element-shape\"\n style={{\n position: 'absolute',\n top: `${elementInfo.top}px`,\n left: `${elementInfo.left}px`,\n width: `${elementInfo.width}px`,\n height: `${elementInfo.height}px`,\n }}\n >\n <div\n className=\"rotate-wrapper\"\n style={{\n width: '100%',\n height: '100%',\n transform: `rotate(${elementInfo.rotate}deg)`,\n }}\n >\n <div\n className=\"element-content\"\n style={{\n position: 'relative',\n width: '100%',\n height: '100%',\n opacity: elementInfo.opacity,\n filter: shadowStyle ? `drop-shadow(${shadowStyle})` : '',\n transform: flipStyle,\n color: text.defaultColor,\n fontFamily: text.defaultFontName,\n }}\n >\n {(() => {\n // The shape's path can extend OUTSIDE its width×height box (e.g.\n // curved connectors whose extreme adj values bulge the curve far\n // past the bbox). A browser shows that via overflow:visible, but\n // html2canvas-pro rasterizes each SVG to its width×height viewport\n // and CLIPS the overflow — turning connector arcs into stubs in the\n // exported PNG. Fix: grow the SVG viewport to contain the full path\n // bbox and offset it back, so the geometry renders in the exact same\n // place but nothing falls outside the captured viewport.\n const sx = elementInfo.width / (elementInfo.viewBox[0] || elementInfo.width || 1);\n const sy = elementInfo.height / (elementInfo.viewBox[1] || elementInfo.height || 1);\n const bbox = pathCoordBBox(elementInfo.path);\n const CAP = 4000; // guard against pathological coords blowing up the SVG\n let padL = 0;\n let padT = 0;\n let padR = 0;\n let padB = 0;\n if (bbox) {\n padL = Math.min(CAP, Math.max(0, -bbox.minX * sx));\n padT = Math.min(CAP, Math.max(0, -bbox.minY * sy));\n padR = Math.min(CAP, Math.max(0, bbox.maxX * sx - elementInfo.width));\n padB = Math.min(CAP, Math.max(0, bbox.maxY * sy - elementInfo.height));\n }\n return (\n <svg\n overflow=\"visible\"\n width={elementInfo.width + padL + padR}\n height={elementInfo.height + padT + padB}\n style={{\n position: 'absolute',\n left: -padL,\n top: -padT,\n transformOrigin: '0 0',\n overflow: 'visible',\n display: 'block',\n }}\n >\n <defs>\n {elementInfo.pattern && (\n <PatternDefs id={`base-pattern-${elementInfo.id}`} src={elementInfo.pattern} />\n )}\n {elementInfo.gradient && (\n <GradientDefs\n id={`base-gradient-${elementInfo.id}`}\n type={elementInfo.gradient.type}\n colors={elementInfo.gradient.colors}\n rotate={elementInfo.gradient.rotate}\n />\n )}\n </defs>\n <g transform={`translate(${padL},${padT}) scale(${sx}, ${sy})`}>\n <path\n vectorEffect=\"non-scaling-stroke\"\n strokeLinecap=\"butt\"\n strokeMiterlimit=\"8\"\n d={elementInfo.path}\n fill={fill}\n stroke={outlineColor}\n strokeWidth={outlineWidth}\n strokeDasharray={strokeDashArray}\n />\n </g>\n </svg>\n );\n })()}\n\n {renderLabel ? renderLabel(elementInfo, defaultLabelContent) : defaultLabelContent}\n </div>\n </div>\n </div>\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAmBA;;;;AAIG;AACH;;AAIE;AAAa;;;;;AAKb;AACA;AACA;;;;;AAGA;AACA;;;;;AAGA;AACA;AACA;;;;AAII;AACA;;AAEF;AACA;AACE;AACA;;AACK;AACL;AACA;AACA;AACA;AACA;AACA;;;AAEA;AACA;AACA;AACA;;AACK;AACL;;AACK;AACL;;AACK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;;AACK;;;;;AAMT;AAEE;AACA;AACA;AAEA;;;AAGJ;;;AAIE;;AAEA;AAEA;AACE;AACA;AACA;AACA;;AAGF;;AAEA;;;AAQM;AACA;AACA;AACA;;AAEA;;AAEA;;;;AAIA;AACD;;AAQG;AACA;AACD;AAMP;AAIM;AACA;AACA;AACA;AACA;AACD;AAKG;AACA;AACA;AACD;AAKG;AACA;AACA;;;AAGA;;;;;;;;;;;;;;;AAiBA;;;;;;;;;;;;AAiBM;;;AAGA;AACA;AACA;;;AAqClB;;"}
1
+ {"version":3,"file":"BaseShapeElement.js","sources":["../../../src/elements/shape/BaseShapeElement.tsx"],"sourcesContent":["'use client';\n\nimport { useMemo, useRef, type ReactNode } from 'react';\nimport type { PPTShapeElement, ShapeText } from '@openmaic/dsl';\nimport {\n validateShapeGeometry,\n RENDER_PATH_LIMITS,\n shapeToTextFallback,\n type PathValidation,\n} from '@openmaic/geometry';\nimport { useElementOutline } from '../shared/useElementOutline';\nimport { useElementShadow } from '../shared/useElementShadow';\nimport { useElementFlip } from '../shared/useElementFlip';\nimport { useElementFill } from '../shared/useElementFill';\nimport { GradientDefs } from './GradientDefs';\nimport { BaseTextElement } from '../text/BaseTextElement';\nimport { PatternDefs } from './PatternDefs';\nimport { preservesPlainTextLineBreaks } from '../../utils/richText';\nimport { useInlineMath, useInnerHtml } from '../../utils/inlineMath';\nimport { hasTextInsets } from '../shared/hasTextInsets';\n\nexport interface BaseShapeElementProps {\n elementInfo: PPTShapeElement;\n /** Replace the static Shape label with editor content. */\n renderLabel?: (element: PPTShapeElement, defaultContent: ReactNode) => ReactNode;\n}\n\nexport function BaseShapeElement({ elementInfo, renderLabel }: BaseShapeElementProps) {\n const geometry = useMemo(\n () =>\n validateShapeGeometry(\n {\n path: elementInfo.path,\n viewBox: elementInfo.viewBox,\n width: elementInfo.width,\n height: elementInfo.height,\n },\n RENDER_PATH_LIMITS,\n ),\n [elementInfo.path, elementInfo.viewBox, elementInfo.width, elementInfo.height],\n );\n if (!geometry.ok) {\n const fallback = shapeToTextFallback(elementInfo);\n return fallback ? (\n <div data-shape-geometry-error={geometry.error.code}>\n <BaseTextElement\n elementInfo={fallback}\n fillHeight={Boolean(renderLabel)}\n renderContent={\n renderLabel ? (_text, content) => renderLabel(elementInfo, content) : undefined\n }\n />\n </div>\n ) : null;\n }\n return (\n <ValidShapeElement elementInfo={elementInfo} renderLabel={renderLabel} geometry={geometry} />\n );\n}\n\nfunction ValidShapeElement({\n elementInfo,\n renderLabel,\n geometry,\n}: BaseShapeElementProps & {\n geometry: Extract<PathValidation, { ok: true }>;\n}) {\n const width = elementInfo.width;\n const height = elementInfo.height;\n const { fill } = useElementFill(elementInfo, 'base');\n const { outlineWidth, outlineColor, strokeDashArray } = useElementOutline(elementInfo.outline);\n const { shadowStyle } = useElementShadow(elementInfo.shadow);\n const { flipStyle } = useElementFlip(elementInfo.flipH, elementInfo.flipV);\n\n const text: ShapeText = elementInfo.text || {\n content: '',\n align: 'middle',\n defaultFontName: 'Microsoft YaHei',\n defaultColor: '#333333',\n };\n\n const proseRef = useRef<HTMLDivElement>(null);\n const innerHtml = useInnerHtml(text.content);\n useInlineMath(proseRef, text.content);\n\n const justifyContent =\n text.align === 'top' ? 'flex-start' : text.align === 'bottom' ? 'flex-end' : 'center';\n const defaultLabelContent = (\n <div\n className=\"shape-text\"\n style={{\n position: 'absolute',\n inset: 0,\n display: 'flex',\n flexDirection: 'column',\n justifyContent,\n overflowWrap: 'break-word',\n boxSizing: 'border-box',\n padding: hasTextInsets(text.content) ? 0 : 10,\n lineHeight: text.lineHeight ?? 1.625,\n letterSpacing: `${text.wordSpace || 0}px`,\n // PowerPoint/WPS 在 group flipH/flipV 时只镜像几何与位置,文字字形保持\n // 正向。父层 element-content 已应用 flipStyle 镜像 SVG path;这里给文字\n // 叠加同一个 flipStyle,两次 flip 抵消,让文字保持正向。\n transform: flipStyle,\n }}\n >\n <div\n ref={proseRef}\n data-inline-math-root=\"\"\n className=\"ProseMirror-static slide-renderer-prose\"\n style={{\n // @ts-expect-error CSS custom properties\n '--paragraphSpace': `${text.paragraphSpace === undefined ? 5 : text.paragraphSpace}px`,\n whiteSpace: preservesPlainTextLineBreaks(text.content) ? 'pre-line' : undefined,\n }}\n dangerouslySetInnerHTML={innerHtml}\n />\n </div>\n );\n\n return (\n <div\n className=\"base-element-shape\"\n style={{\n position: 'absolute',\n top: `${elementInfo.top}px`,\n left: `${elementInfo.left}px`,\n width: `${width}px`,\n height: `${height}px`,\n }}\n >\n <div\n className=\"rotate-wrapper\"\n style={{\n width: '100%',\n height: '100%',\n transform: `rotate(${elementInfo.rotate}deg)`,\n }}\n >\n <div\n className=\"element-content\"\n style={{\n position: 'relative',\n width: '100%',\n height: '100%',\n opacity: elementInfo.opacity,\n filter: shadowStyle ? `drop-shadow(${shadowStyle})` : '',\n transform: flipStyle,\n color: text.defaultColor,\n fontFamily: text.defaultFontName,\n }}\n >\n {(() => {\n // The shape's path can extend OUTSIDE its width×height box (e.g.\n // curved connectors whose extreme adj values bulge the curve far\n // past the bbox). A browser shows that via overflow:visible, but\n // html2canvas-pro rasterizes each SVG to its width×height viewport\n // and CLIPS the overflow — turning connector arcs into stubs in the\n // exported PNG. Fix: grow the SVG viewport to contain the full path\n // bbox and offset it back, so the geometry renders in the exact same\n // place but nothing falls outside the captured viewport.\n const sx = elementInfo.width / elementInfo.viewBox[0];\n const sy = elementInfo.height / elementInfo.viewBox[1];\n const bbox = geometry.bounds;\n const CAP = 4000; // guard against pathological coords blowing up the SVG\n let padL = 0;\n let padT = 0;\n let padR = 0;\n let padB = 0;\n if (bbox) {\n padL = Math.min(CAP, Math.max(0, -bbox.minX * sx));\n padT = Math.min(CAP, Math.max(0, -bbox.minY * sy));\n padR = Math.min(CAP, Math.max(0, bbox.maxX * sx - elementInfo.width));\n padB = Math.min(CAP, Math.max(0, bbox.maxY * sy - elementInfo.height));\n }\n return (\n <svg\n overflow=\"visible\"\n width={width + padL + padR}\n height={height + padT + padB}\n style={{\n position: 'absolute',\n left: -padL,\n top: -padT,\n transformOrigin: '0 0',\n overflow: 'visible',\n display: 'block',\n }}\n >\n <defs>\n {elementInfo.pattern && (\n <PatternDefs id={`base-pattern-${elementInfo.id}`} src={elementInfo.pattern} />\n )}\n {elementInfo.gradient && (\n <GradientDefs\n id={`base-gradient-${elementInfo.id}`}\n type={elementInfo.gradient.type}\n colors={elementInfo.gradient.colors}\n rotate={elementInfo.gradient.rotate}\n />\n )}\n </defs>\n <g transform={`translate(${padL},${padT}) scale(${sx}, ${sy})`}>\n <path\n vectorEffect=\"non-scaling-stroke\"\n strokeLinecap=\"butt\"\n strokeMiterlimit=\"8\"\n d={elementInfo.path}\n fill={fill}\n stroke={outlineColor}\n strokeWidth={outlineWidth}\n strokeDasharray={strokeDashArray}\n />\n </g>\n </svg>\n );\n })()}\n\n {renderLabel ? renderLabel(elementInfo, defaultLabelContent) : defaultLabelContent}\n </div>\n </div>\n </div>\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAyCE;AACE;;;AAaF;AAGF;AAEA;AAOE;AACA;;AAEA;;AAEA;AAEA;AACE;AACA;AACA;AACA;;AAGF;;AAEA;;;AAQM;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;;;AAIA;AACD;;AAQG;AACA;AACD;AAMP;AAIM;AACA;AACA;;;AAGD;AAKG;AACA;AACA;AACD;AAKG;AACA;AACA;;;AAGA;;;;;;;;;;;;AAcA;AACA;AACA;AACA;;;;;;;;;;;;AAiBM;;;AAGA;AACA;AACA;;;AAqClB;;"}
@@ -0,0 +1,2 @@
1
+ /** Imported PPTX labels carry their own text box padding on the outer div. */
2
+ export declare function hasTextInsets(content: string): boolean;
@@ -0,0 +1,9 @@
1
+ /** Imported PPTX labels carry their own text box padding on the outer div. */
2
+ function hasTextInsets(content) {
3
+ const hasExplicitTextInsets = /^\s*<div\b[^>]*\sdata-pptx-text-insets\s*=\s*(["'])true\1/i.test(content);
4
+ // Legacy saved slides predate the marker but retain an inline padding style.
5
+ return (hasExplicitTextInsets || /^\s*<div\b[^>]*\sstyle\s*=\s*["'][^"']*\bpadding\s*:/i.test(content));
6
+ }
7
+
8
+ export { hasTextInsets };
9
+ //# sourceMappingURL=hasTextInsets.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hasTextInsets.js","sources":["../../../src/elements/shared/hasTextInsets.ts"],"sourcesContent":["/** Imported PPTX labels carry their own text box padding on the outer div. */\nexport function hasTextInsets(content: string): boolean {\n const hasExplicitTextInsets = /^\\s*<div\\b[^>]*\\sdata-pptx-text-insets\\s*=\\s*([\"'])true\\1/i.test(\n content,\n );\n // Legacy saved slides predate the marker but retain an inline padding style.\n return (\n hasExplicitTextInsets || /^\\s*<div\\b[^>]*\\sstyle\\s*=\\s*[\"'][^\"']*\\bpadding\\s*:/i.test(content)\n );\n}\n"],"names":[],"mappings":"AAAA;AACM,SAAU,aAAa,CAAC,OAAe,EAAA;IAC3C,MAAM,qBAAqB,GAAG,4DAA4D,CAAC,IAAI,CAC7F,OAAO,CACR;;IAED,QACE,qBAAqB,IAAI,uDAAuD,CAAC,IAAI,CAAC,OAAO,CAAC;AAElG;;;;"}
@@ -4,5 +4,7 @@ export interface BaseTextElementProps {
4
4
  elementInfo: PPTTextElement;
5
5
  target?: string;
6
6
  renderContent?: (element: PPTTextElement, defaultContent: ReactNode) => ReactNode;
7
+ /** Keep a recovered shape's label container sized for an absolute-positioned editor. */
8
+ fillHeight?: boolean;
7
9
  }
8
- export declare function BaseTextElement({ elementInfo, target, renderContent }: BaseTextElementProps): import("react/jsx-runtime").JSX.Element;
10
+ export declare function BaseTextElement({ elementInfo, target, renderContent, fillHeight, }: BaseTextElementProps): import("react/jsx-runtime").JSX.Element;
@@ -5,19 +5,16 @@ import { useElementShadow } from '../shared/useElementShadow.js';
5
5
  import { ElementOutline } from '../shared/ElementOutline.js';
6
6
  import { preservesPlainTextLineBreaks } from '../../utils/richText.js';
7
7
  import { useInnerHtml, useInlineMath } from '../../utils/inlineMath.js';
8
+ import { hasTextInsets } from '../shared/hasTextInsets.js';
8
9
 
9
- function BaseTextElement({ elementInfo, target, renderContent }) {
10
+ function BaseTextElement({ elementInfo, target, renderContent, fillHeight = false, }) {
10
11
  const { shadowStyle } = useElementShadow(elementInfo.shadow);
11
12
  const proseRef = useRef(null);
12
13
  const innerHtml = useInnerHtml(elementInfo.content);
13
14
  useInlineMath(proseRef, elementInfo.content);
14
15
  // Imported OOXML text carries its own bodyPr insets on the outer div.
15
- // Adding the editor's default inset again shifts vertical text left and
16
- // reduces the available line width for horizontal text.
17
- const hasExplicitTextInsets = /^\s*<div\b[^>]*\sdata-pptx-text-insets\s*=\s*(["'])true\1/i.test(elementInfo.content);
18
- // Legacy saved slides predate the marker. Retain their existing inset behavior.
19
- const hasTextInsets = hasExplicitTextInsets ||
20
- /^\s*<div\b[^>]*\bstyle\s*=\s*["'][^"']*\bpadding\s*:/i.test(elementInfo.content);
16
+ // Adding the editor's default inset again shifts the label and reduces line width.
17
+ const contentHasTextInsets = hasTextInsets(elementInfo.content);
21
18
  const vAlign = elementInfo.vAlign ?? 'top';
22
19
  const justifyContent = vAlign === 'middle' ? 'center' : vAlign === 'bottom' ? 'flex-end' : 'flex-start';
23
20
  const defaultContent = (jsx("div", { ref: proseRef, "data-inline-math-root": "", className: "text ProseMirror-static", style: {
@@ -44,10 +41,13 @@ function BaseTextElement({ elementInfo, target, renderContent }) {
44
41
  }, children: jsxs("div", { className: "element-content slide-renderer-prose", style: {
45
42
  position: 'relative',
46
43
  boxSizing: 'border-box',
47
- padding: hasTextInsets ? 0 : '10px',
44
+ padding: contentHasTextInsets ? 0 : '10px',
48
45
  overflowWrap: 'break-word',
49
46
  width: elementInfo.vertical ? 'auto' : '100%',
50
- height: elementInfo.vertical ? '100%' : 'auto',
47
+ height: elementInfo.vertical || fillHeight ? '100%' : 'auto',
48
+ display: fillHeight ? 'flex' : undefined,
49
+ flexDirection: fillHeight ? 'column' : undefined,
50
+ justifyContent: fillHeight ? justifyContent : undefined,
51
51
  textShadow: shadowStyle,
52
52
  lineHeight: elementInfo.lineHeight,
53
53
  letterSpacing: elementInfo.wordSpace !== undefined ? `${elementInfo.wordSpace}px` : undefined,
@@ -1 +1 @@
1
- {"version":3,"file":"BaseTextElement.js","sources":["../../../src/elements/text/BaseTextElement.tsx"],"sourcesContent":["'use client';\n\nimport { useRef, type CSSProperties, type ReactNode } from 'react';\nimport type { PPTTextElement } from '@openmaic/dsl';\nimport { useElementShadow } from '../shared/useElementShadow';\nimport { ElementOutline } from '../shared/ElementOutline';\nimport { preservesPlainTextLineBreaks } from '../../utils/richText';\nimport { useInlineMath, useInnerHtml } from '../../utils/inlineMath';\n\nexport interface BaseTextElementProps {\n elementInfo: PPTTextElement;\n target?: string;\n renderContent?: (element: PPTTextElement, defaultContent: ReactNode) => ReactNode;\n}\n\nexport function BaseTextElement({ elementInfo, target, renderContent }: BaseTextElementProps) {\n const { shadowStyle } = useElementShadow(elementInfo.shadow);\n const proseRef = useRef<HTMLDivElement>(null);\n const innerHtml = useInnerHtml(elementInfo.content);\n useInlineMath(proseRef, elementInfo.content);\n // Imported OOXML text carries its own bodyPr insets on the outer div.\n // Adding the editor's default inset again shifts vertical text left and\n // reduces the available line width for horizontal text.\n const hasExplicitTextInsets = /^\\s*<div\\b[^>]*\\sdata-pptx-text-insets\\s*=\\s*([\"'])true\\1/i.test(\n elementInfo.content,\n );\n // Legacy saved slides predate the marker. Retain their existing inset behavior.\n const hasTextInsets =\n hasExplicitTextInsets ||\n /^\\s*<div\\b[^>]*\\bstyle\\s*=\\s*[\"'][^\"']*\\bpadding\\s*:/i.test(elementInfo.content);\n\n const vAlign = elementInfo.vAlign ?? 'top';\n const justifyContent =\n vAlign === 'middle' ? 'center' : vAlign === 'bottom' ? 'flex-end' : 'flex-start';\n const defaultContent = (\n <div\n ref={proseRef}\n data-inline-math-root=\"\"\n className=\"text ProseMirror-static\"\n style={{\n position: 'relative',\n pointerEvents: target === 'thumbnail' ? 'none' : undefined,\n whiteSpace: preservesPlainTextLineBreaks(elementInfo.content) ? 'pre-line' : undefined,\n }}\n dangerouslySetInnerHTML={innerHtml}\n />\n );\n\n return (\n <div\n className=\"base-element-text\"\n style={{\n position: 'absolute',\n top: `${elementInfo.top}px`,\n left: `${elementInfo.left}px`,\n width: `${elementInfo.width}px`,\n height: `${elementInfo.height}px`,\n }}\n >\n <div\n className=\"rotate-wrapper\"\n style={{\n width: '100%',\n height: '100%',\n transform: `rotate(${elementInfo.rotate}deg)`,\n // Fill the full text box and rotate it with the glyphs/outline.\n backgroundColor: elementInfo.fill,\n opacity: elementInfo.opacity,\n display: 'flex',\n flexDirection: 'column',\n justifyContent,\n }}\n >\n <div\n className=\"element-content slide-renderer-prose\"\n style={{\n position: 'relative',\n boxSizing: 'border-box',\n padding: hasTextInsets ? 0 : '10px',\n overflowWrap: 'break-word',\n width: elementInfo.vertical ? 'auto' : '100%',\n height: elementInfo.vertical ? '100%' : 'auto',\n textShadow: shadowStyle,\n lineHeight: elementInfo.lineHeight,\n letterSpacing:\n elementInfo.wordSpace !== undefined ? `${elementInfo.wordSpace}px` : undefined,\n color: elementInfo.defaultColor,\n fontFamily: elementInfo.defaultFontName,\n writingMode: elementInfo.vertical ? 'vertical-rl' : 'horizontal-tb',\n ...(elementInfo.paragraphSpace !== undefined\n ? ({ '--paragraphSpace': `${elementInfo.paragraphSpace}px` } as CSSProperties)\n : null),\n }}\n >\n <ElementOutline\n width={elementInfo.width}\n height={elementInfo.height}\n outline={elementInfo.outline}\n />\n {renderContent?.(elementInfo, defaultContent) ?? defaultContent}\n </div>\n </div>\n </div>\n );\n}\n"],"names":[],"mappings":";;;;;;;;AAeM;;AAEJ;;AAEA;;;;;;;AAUE;AAEF;;AAGA;AAMM;;AAEA;AACD;AAKL;AAIM;AACA;AACA;AACA;AACA;AACD;AAKG;AACA;AACA;;;;AAIA;AACA;;AAED;AAKG;AACA;;AAEA;;;AAGA;;AAEA;;;;AAKA;;;AAGD;AAYX;;"}
1
+ {"version":3,"file":"BaseTextElement.js","sources":["../../../src/elements/text/BaseTextElement.tsx"],"sourcesContent":["'use client';\n\nimport { useRef, type CSSProperties, type ReactNode } from 'react';\nimport type { PPTTextElement } from '@openmaic/dsl';\nimport { useElementShadow } from '../shared/useElementShadow';\nimport { ElementOutline } from '../shared/ElementOutline';\nimport { preservesPlainTextLineBreaks } from '../../utils/richText';\nimport { useInlineMath, useInnerHtml } from '../../utils/inlineMath';\nimport { hasTextInsets } from '../shared/hasTextInsets';\n\nexport interface BaseTextElementProps {\n elementInfo: PPTTextElement;\n target?: string;\n renderContent?: (element: PPTTextElement, defaultContent: ReactNode) => ReactNode;\n /** Keep a recovered shape's label container sized for an absolute-positioned editor. */\n fillHeight?: boolean;\n}\n\nexport function BaseTextElement({\n elementInfo,\n target,\n renderContent,\n fillHeight = false,\n}: BaseTextElementProps) {\n const { shadowStyle } = useElementShadow(elementInfo.shadow);\n const proseRef = useRef<HTMLDivElement>(null);\n const innerHtml = useInnerHtml(elementInfo.content);\n useInlineMath(proseRef, elementInfo.content);\n // Imported OOXML text carries its own bodyPr insets on the outer div.\n // Adding the editor's default inset again shifts the label and reduces line width.\n const contentHasTextInsets = hasTextInsets(elementInfo.content);\n\n const vAlign = elementInfo.vAlign ?? 'top';\n const justifyContent =\n vAlign === 'middle' ? 'center' : vAlign === 'bottom' ? 'flex-end' : 'flex-start';\n const defaultContent = (\n <div\n ref={proseRef}\n data-inline-math-root=\"\"\n className=\"text ProseMirror-static\"\n style={{\n position: 'relative',\n pointerEvents: target === 'thumbnail' ? 'none' : undefined,\n whiteSpace: preservesPlainTextLineBreaks(elementInfo.content) ? 'pre-line' : undefined,\n }}\n dangerouslySetInnerHTML={innerHtml}\n />\n );\n\n return (\n <div\n className=\"base-element-text\"\n style={{\n position: 'absolute',\n top: `${elementInfo.top}px`,\n left: `${elementInfo.left}px`,\n width: `${elementInfo.width}px`,\n height: `${elementInfo.height}px`,\n }}\n >\n <div\n className=\"rotate-wrapper\"\n style={{\n width: '100%',\n height: '100%',\n transform: `rotate(${elementInfo.rotate}deg)`,\n // Fill the full text box and rotate it with the glyphs/outline.\n backgroundColor: elementInfo.fill,\n opacity: elementInfo.opacity,\n display: 'flex',\n flexDirection: 'column',\n justifyContent,\n }}\n >\n <div\n className=\"element-content slide-renderer-prose\"\n style={{\n position: 'relative',\n boxSizing: 'border-box',\n padding: contentHasTextInsets ? 0 : '10px',\n overflowWrap: 'break-word',\n width: elementInfo.vertical ? 'auto' : '100%',\n height: elementInfo.vertical || fillHeight ? '100%' : 'auto',\n display: fillHeight ? 'flex' : undefined,\n flexDirection: fillHeight ? 'column' : undefined,\n justifyContent: fillHeight ? justifyContent : undefined,\n textShadow: shadowStyle,\n lineHeight: elementInfo.lineHeight,\n letterSpacing:\n elementInfo.wordSpace !== undefined ? `${elementInfo.wordSpace}px` : undefined,\n color: elementInfo.defaultColor,\n fontFamily: elementInfo.defaultFontName,\n writingMode: elementInfo.vertical ? 'vertical-rl' : 'horizontal-tb',\n ...(elementInfo.paragraphSpace !== undefined\n ? ({ '--paragraphSpace': `${elementInfo.paragraphSpace}px` } as CSSProperties)\n : null),\n }}\n >\n <ElementOutline\n width={elementInfo.width}\n height={elementInfo.height}\n outline={elementInfo.outline}\n />\n {renderContent?.(elementInfo, defaultContent) ?? defaultContent}\n </div>\n </div>\n </div>\n );\n}\n"],"names":[],"mappings":";;;;;;;;;AAkBM;;AAOJ;;AAEA;;;;AAKA;;AAGA;AAMM;;AAEA;AACD;AAKL;AAIM;AACA;AACA;AACA;AACA;AACD;AAKG;AACA;AACA;;;;AAIA;AACA;;AAED;AAKG;AACA;;AAEA;;AAEA;;;;AAIA;;AAEA;;;;AAKA;;;AAGD;AAYX;;"}
@@ -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 formulas were left for a later pass by the budget.
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
  /**
@@ -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 formulas were left for a later pass by the budget.
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.15",
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,6 +79,7 @@
79
79
  "lucide-react": "^0.562.0",
80
80
  "tailwind-merge": "^3.4.0",
81
81
  "tinycolor2": "^1.6.0",
82
+ "@openmaic/geometry": "^0.1.0",
82
83
  "@openmaic/dsl": "^0.12.0"
83
84
  },
84
85
  "devDependencies": {