@openmaic/renderer 0.1.14 → 0.1.16

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
@@ -84,7 +84,7 @@ The canvas auto-fits its parent container. The parent must have a defined `width
84
84
 
85
85
  ### `<SlideCanvas slide effects? renderImage? renderVideo? onElementClick? scale? background? />`
86
86
 
87
- The main read-only entry. Reads everything from props; zero global state.
87
+ The main read-only entry. Reads slide data and rendering options from props.
88
88
 
89
89
  ```ts
90
90
  interface SlideCanvasProps {
@@ -97,6 +97,7 @@ interface SlideCanvasProps {
97
97
  renderImage?: (el, src, defaultContent) => ReactNode;
98
98
  renderVideo?: (el) => ReactNode;
99
99
  videoInteractive?: boolean; // defaults true; set false to disable video pointer interaction
100
+ mathPriority?: 'normal' | 'background'; // defaults normal; use background for thumbnails
100
101
  onElementClick?: (el, event) => void;
101
102
  elementIdPrefix?: string;
102
103
  className?: string;
@@ -104,6 +105,17 @@ interface SlideCanvasProps {
104
105
  }
105
106
  ```
106
107
 
108
+ Inline formulas share a 256,000-character markup budget so oversized slides can
109
+ yield between batches while dense ordinary slides still fit before paint.
110
+ A short formula following heavy content in the same frame may also be deferred.
111
+ Use `mathPriority="background"` for thumbnails: newly mounted or changed content
112
+ shares a copy of the frame's remaining allowance after foreground layout effects,
113
+ before paint. This leaves foreground capacity available if the user switches slides
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
117
+ formulas synchronously within the existing per-prose-root hard caps.
118
+
107
119
  ### Play-time effects
108
120
 
109
121
  All effects are off by default. Pass any combination via `effects`:
@@ -33,6 +33,11 @@ export interface SlideCanvasProps {
33
33
  renderTable?: (element: PPTTableElement, defaultContent: ReactNode) => ReactNode;
34
34
  /** Enable pointer interaction for video controls or custom video UI. */
35
35
  videoInteractive?: boolean;
36
+ /**
37
+ * Background canvases use the frame allowance left by foreground layout
38
+ * effects, then finish in idle time at lower priority. Defaults to normal.
39
+ */
40
+ mathPriority?: 'normal' | 'background';
36
41
  /** Click handler invoked on any element. */
37
42
  onElementClick?: (element: PPTElement, event: React.MouseEvent) => void;
38
43
  /**
@@ -11,6 +11,7 @@ import { SpotlightOverlay } from './effects/SpotlightOverlay.js';
11
11
  import { LaserOverlay } from './effects/LaserOverlay.js';
12
12
  import { useOptionalSlideContext } from './context.js';
13
13
  import { SLIDE_RENDERER_STYLES } from './styles.js';
14
+ import { InlineMathPriorityContext } from './utils/inlineMath.js';
14
15
 
15
16
  function SlideCanvas(props) {
16
17
  const ctx = useOptionalSlideContext();
@@ -100,7 +101,7 @@ function SlideCanvas(props) {
100
101
  width: `${viewportStyles.width}px`,
101
102
  height: `${viewportStyles.height}px`,
102
103
  transform: `scale(${canvasScale})`,
103
- }, children: [visibleElements.map((element) => (jsx(SlideElement, { elementInfo: element, elementIndex: elementIndexById.get(element.id) ?? 1, theme: slide.theme, renderImage: renderImage, renderVideo: renderVideo, renderText: renderText, renderShapeLabel: renderShapeLabel, renderTable: renderTable, videoInteractive: videoInteractive, onElementClick: onElementClick, idPrefix: elementIdPrefix, dragOffset: dragOffsets?.get(element.id) }, element.id))), highlights.map((highlight) => {
104
+ }, children: [jsx(InlineMathPriorityContext.Provider, { value: props.mathPriority ?? 'normal', children: visibleElements.map((element) => (jsx(SlideElement, { elementInfo: element, elementIndex: elementIndexById.get(element.id) ?? 1, theme: slide.theme, renderImage: renderImage, renderVideo: renderVideo, renderText: renderText, renderShapeLabel: renderShapeLabel, renderTable: renderTable, videoInteractive: videoInteractive, onElementClick: onElementClick, idPrefix: elementIdPrefix, dragOffset: dragOffsets?.get(element.id) }, element.id))) }), highlights.map((highlight) => {
104
105
  const element = visibleElements.find((el) => el.id === highlight.elementId);
105
106
  return element ? (jsx(HighlightOverlay, { element: element, options: highlight }, highlight.elementId)) : null;
106
107
  })] }), jsx(SpotlightOverlay, { options: effects?.spotlight, elementIdPrefix: elementIdPrefix, measurementKey: visibleElements }), jsx("div", { style: {
@@ -1 +1 @@
1
- {"version":3,"file":"SlideCanvas.js","sources":["../src/SlideCanvas.tsx"],"sourcesContent":["'use client';\n\nimport { useMemo, useRef, type CSSProperties, type ReactNode } from 'react';\nimport { AnimatePresence } from 'motion/react';\n\nimport type {\n PPTElement,\n PPTImageElement,\n PPTShapeElement,\n PPTTableElement,\n PPTTextElement,\n PPTVideoElement,\n Slide,\n SlideBackground,\n} from '@openmaic/dsl';\nimport type { SlideEffects } from './types/effects';\nimport { findElementGeometry, type PercentageGeometry } from './utils/geometry';\nimport { useSlideBackgroundStyle } from './hooks/useSlideBackgroundStyle';\nimport { useViewportSize } from './hooks/useViewportSize';\nimport { SlideElement } from './SlideElement';\nimport { HighlightOverlay } from './effects/HighlightOverlay';\nimport { SpotlightOverlay } from './effects/SpotlightOverlay';\nimport { LaserOverlay } from './effects/LaserOverlay';\nimport { useOptionalSlideContext } from './context';\nimport { SLIDE_RENDERER_STYLES } from './styles';\n\nexport interface SlideCanvasProps {\n /**\n * Single slide data (PPTist-style). May be omitted when this component is\n * rendered inside a `<SlideRendererProvider>` that supplies it.\n */\n slide?: Slide;\n /**\n * Canvas scale. When omitted, the canvas auto-fits the container using\n * `slide.viewportSize` and `slide.viewportRatio`. Set to a fixed number\n * (e.g. 1) to skip auto-fit and render at slide-native dimensions.\n */\n scale?: number;\n /** Percent of the container to use when auto-fitting the slide. */\n canvasPercentage?: number;\n /** Called with the computed fit scale when `scale` is omitted. */\n onScaleChange?: (scale: number) => void;\n /** Override `slide.background`. */\n background?: SlideBackground;\n /** Optional play-time effects, all default off. */\n effects?: SlideEffects;\n /** Replace default <img> rendering for image elements. */\n renderImage?: (\n element: PPTImageElement,\n resolvedSrc: string,\n defaultContent: ReactNode,\n ) => ReactNode;\n /** Replace default <video> rendering for video elements. */\n renderVideo?: (element: PPTVideoElement) => ReactNode;\n /** Replace the content node inside the shared text paint wrapper. */\n renderText?: (element: PPTTextElement, defaultContent: ReactNode) => ReactNode;\n /** Replace the static label node inside a Shape element. */\n renderShapeLabel?: (element: PPTShapeElement, defaultContent: ReactNode) => ReactNode;\n /** Replace the static content node inside a Table element. */\n renderTable?: (element: PPTTableElement, defaultContent: ReactNode) => ReactNode;\n /** Enable pointer interaction for video controls or custom video UI. */\n videoInteractive?: boolean;\n /** Click handler invoked on any element. */\n onElementClick?: (element: PPTElement, event: React.MouseEvent) => void;\n /**\n * Prefix used for each element root DOM id. Hosts that layer DOM-measured\n * overlays on top of the canvas can keep their existing id contract.\n */\n elementIdPrefix?: string;\n /** Class on the outer container. */\n className?: string;\n /** Compositor-only offsets used by the editing surface during a move gesture. */\n dragOffsets?: ReadonlyMap<string, { x: number; y: number }>;\n /** Element ids omitted from rendering and effect targeting. */\n hiddenElementIds?: readonly string[];\n /** Inline style on the outer container. */\n style?: CSSProperties;\n /**\n * Card-style chrome on the inner slide container (drop shadow + rounded\n * corners). Defaults to `true` for on-screen previews. Snapshot pipelines\n * pass `false` so the captured PNG matches the source PPT's edges exactly\n * — html2canvas would otherwise bake the 1px shadow outline and the\n * 0.5rem corner radius into the output and the comparator reads them as\n * a thin border + rounded corners that the original PPT does not have.\n */\n chrome?: boolean;\n}\n\nexport function SlideCanvas(props: SlideCanvasProps) {\n const ctx = useOptionalSlideContext();\n const slide = props.slide ?? ctx?.slide;\n if (!slide) {\n throw new Error(\n '<SlideCanvas> requires `slide` either as a prop or via <SlideRendererProvider>.',\n );\n }\n\n const scale = props.scale ?? ctx?.scale;\n const background = props.background ?? ctx?.background;\n const effects = props.effects ?? ctx?.effects;\n const renderImage = props.renderImage ?? ctx?.renderImage;\n const renderVideo = props.renderVideo ?? ctx?.renderVideo;\n const renderText = props.renderText;\n const renderShapeLabel = props.renderShapeLabel;\n const renderTable = props.renderTable;\n const videoInteractive = props.videoInteractive ?? ctx?.videoInteractive;\n const onElementClick = props.onElementClick ?? ctx?.onElementClick;\n const elementIdPrefix = props.elementIdPrefix ?? 'slide-element-';\n const { className, dragOffsets, style } = props;\n const chrome = props.chrome ?? true;\n\n const canvasRef = useRef<HTMLDivElement>(null);\n const elements = slide.elements;\n const visibleElements = useMemo(() => {\n if (!props.hiddenElementIds?.length) return elements;\n const hidden = new Set(props.hiddenElementIds);\n return elements.filter((element) => !hidden.has(element.id));\n }, [elements, props.hiddenElementIds]);\n const elementIndexById = useMemo(\n () => new Map(elements.map((element, index) => [element.id, index + 1])),\n [elements],\n );\n\n const { viewportStyles, fitScale } = useViewportSize(canvasRef, {\n viewportSize: slide.viewportSize,\n viewportRatio: slide.viewportRatio,\n canvasPercentage: props.canvasPercentage,\n onScaleChange: scale === undefined ? props.onScaleChange : undefined,\n });\n const canvasScale = scale ?? fitScale;\n\n const resolvedBackground = background ?? slide.background;\n const { backgroundStyle } = useSlideBackgroundStyle(resolvedBackground);\n\n // Plain derivations: when this package is consumed in a React Compiler build\n // these are auto-memoized; otherwise the cost (O(elements) lookups) is trivial.\n const laserGeometry: PercentageGeometry | null = effects?.laser\n ? findElementGeometry(\n visibleElements,\n effects.laser.elementId,\n slide.viewportSize,\n slide.viewportRatio,\n )\n : null;\n\n const zoomGeometry: PercentageGeometry | null = effects?.zoom\n ? findElementGeometry(\n visibleElements,\n effects.zoom.elementId,\n slide.viewportSize,\n slide.viewportRatio,\n )\n : null;\n\n const highlights = effects?.highlights ?? (effects?.highlight ? [effects.highlight] : []);\n\n return (\n <div\n ref={canvasRef}\n className={className}\n style={{\n position: 'relative',\n width: '100%',\n height: '100%',\n overflow: 'hidden',\n userSelect: 'none',\n ...style,\n }}\n >\n <style dangerouslySetInnerHTML={{ __html: SLIDE_RENDERER_STYLES }} />\n <div\n style={{\n position: 'absolute',\n ...(chrome\n ? {\n boxShadow: '0 0 0 1px rgba(0, 0, 0, 0.01), 0 0 12px 0 rgba(0, 0, 0, 0.1)',\n borderRadius: '0.5rem',\n }\n : {}),\n overflow: 'hidden',\n transitionProperty: 'transform',\n transitionDuration: '700ms',\n width: `${viewportStyles.width * canvasScale}px`,\n height: `${viewportStyles.height * canvasScale}px`,\n left: `${viewportStyles.left}px`,\n top: `${viewportStyles.top}px`,\n ...(effects?.zoom && zoomGeometry\n ? {\n transform: `scale(${effects.zoom.scale})`,\n transformOrigin: `${zoomGeometry.centerX}% ${zoomGeometry.centerY}%`,\n }\n : {}),\n }}\n >\n <div\n style={{\n width: '100%',\n height: '100%',\n backgroundPosition: 'center',\n ...(chrome ? { borderRadius: '0.5rem' } : {}),\n ...backgroundStyle,\n }}\n />\n\n <div\n style={{\n position: 'absolute',\n top: 0,\n left: 0,\n transformOrigin: 'top left',\n width: `${viewportStyles.width}px`,\n height: `${viewportStyles.height}px`,\n transform: `scale(${canvasScale})`,\n }}\n >\n {visibleElements.map((element) => (\n <SlideElement\n key={element.id}\n elementInfo={element}\n elementIndex={elementIndexById.get(element.id) ?? 1}\n theme={slide.theme}\n renderImage={renderImage}\n renderVideo={renderVideo}\n renderText={renderText}\n renderShapeLabel={renderShapeLabel}\n renderTable={renderTable}\n videoInteractive={videoInteractive}\n onElementClick={onElementClick}\n idPrefix={elementIdPrefix}\n dragOffset={dragOffsets?.get(element.id)}\n />\n ))}\n\n {highlights.map((highlight) => {\n const element = visibleElements.find((el) => el.id === highlight.elementId);\n return element ? (\n <HighlightOverlay key={highlight.elementId} element={element} options={highlight} />\n ) : null;\n })}\n </div>\n\n <SpotlightOverlay\n options={effects?.spotlight}\n elementIdPrefix={elementIdPrefix}\n measurementKey={visibleElements}\n />\n\n <div\n style={{\n position: 'absolute',\n inset: 0,\n pointerEvents: 'none',\n padding: '5%',\n }}\n >\n <div style={{ position: 'relative', width: '100%', height: '100%' }}>\n <AnimatePresence>\n {effects?.laser && laserGeometry && (\n <LaserOverlay\n key={`laser-${effects.laser.elementId}`}\n geometry={laserGeometry}\n color={effects.laser.color}\n duration={effects.laser.duration}\n />\n )}\n </AnimatePresence>\n </div>\n </div>\n </div>\n </div>\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAwFM;AACJ;;;AAGE;;;;;;;AAUF;AACA;AACA;;;AAGA;;AAEA;AAEA;AACA;AACA;AACE;AAAqC;;AAErC;;AAEF;;;;;AASE;AACD;AACD;AAEA;;;;AAKA;AACE;;AAQF;AACE;;;;AAeI;AACA;AACA;AACA;AACA;AACA;AACD;AAKG;AACA;AACE;AACI;AACA;AACD;;AAEL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACE;AACI;;AAED;;;AAMH;AACA;AACA;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA;AACA;;;AAuBA;;;AAeA;AACA;AACA;AACA;AACD;AAkBX;;"}
1
+ {"version":3,"file":"SlideCanvas.js","sources":["../src/SlideCanvas.tsx"],"sourcesContent":["'use client';\n\nimport { useMemo, useRef, type CSSProperties, type ReactNode } from 'react';\nimport { AnimatePresence } from 'motion/react';\n\nimport type {\n PPTElement,\n PPTImageElement,\n PPTShapeElement,\n PPTTableElement,\n PPTTextElement,\n PPTVideoElement,\n Slide,\n SlideBackground,\n} from '@openmaic/dsl';\nimport type { SlideEffects } from './types/effects';\nimport { findElementGeometry, type PercentageGeometry } from './utils/geometry';\nimport { useSlideBackgroundStyle } from './hooks/useSlideBackgroundStyle';\nimport { useViewportSize } from './hooks/useViewportSize';\nimport { SlideElement } from './SlideElement';\nimport { HighlightOverlay } from './effects/HighlightOverlay';\nimport { SpotlightOverlay } from './effects/SpotlightOverlay';\nimport { LaserOverlay } from './effects/LaserOverlay';\nimport { useOptionalSlideContext } from './context';\nimport { SLIDE_RENDERER_STYLES } from './styles';\nimport { InlineMathPriorityContext } from './utils/inlineMath';\n\nexport interface SlideCanvasProps {\n /**\n * Single slide data (PPTist-style). May be omitted when this component is\n * rendered inside a `<SlideRendererProvider>` that supplies it.\n */\n slide?: Slide;\n /**\n * Canvas scale. When omitted, the canvas auto-fits the container using\n * `slide.viewportSize` and `slide.viewportRatio`. Set to a fixed number\n * (e.g. 1) to skip auto-fit and render at slide-native dimensions.\n */\n scale?: number;\n /** Percent of the container to use when auto-fitting the slide. */\n canvasPercentage?: number;\n /** Called with the computed fit scale when `scale` is omitted. */\n onScaleChange?: (scale: number) => void;\n /** Override `slide.background`. */\n background?: SlideBackground;\n /** Optional play-time effects, all default off. */\n effects?: SlideEffects;\n /** Replace default <img> rendering for image elements. */\n renderImage?: (\n element: PPTImageElement,\n resolvedSrc: string,\n defaultContent: ReactNode,\n ) => ReactNode;\n /** Replace default <video> rendering for video elements. */\n renderVideo?: (element: PPTVideoElement) => ReactNode;\n /** Replace the content node inside the shared text paint wrapper. */\n renderText?: (element: PPTTextElement, defaultContent: ReactNode) => ReactNode;\n /** Replace the static label node inside a Shape element. */\n renderShapeLabel?: (element: PPTShapeElement, defaultContent: ReactNode) => ReactNode;\n /** Replace the static content node inside a Table element. */\n renderTable?: (element: PPTTableElement, defaultContent: ReactNode) => ReactNode;\n /** Enable pointer interaction for video controls or custom video UI. */\n videoInteractive?: boolean;\n /**\n * Background canvases use the frame allowance left by foreground layout\n * effects, then finish in idle time at lower priority. Defaults to normal.\n */\n mathPriority?: 'normal' | 'background';\n /** Click handler invoked on any element. */\n onElementClick?: (element: PPTElement, event: React.MouseEvent) => void;\n /**\n * Prefix used for each element root DOM id. Hosts that layer DOM-measured\n * overlays on top of the canvas can keep their existing id contract.\n */\n elementIdPrefix?: string;\n /** Class on the outer container. */\n className?: string;\n /** Compositor-only offsets used by the editing surface during a move gesture. */\n dragOffsets?: ReadonlyMap<string, { x: number; y: number }>;\n /** Element ids omitted from rendering and effect targeting. */\n hiddenElementIds?: readonly string[];\n /** Inline style on the outer container. */\n style?: CSSProperties;\n /**\n * Card-style chrome on the inner slide container (drop shadow + rounded\n * corners). Defaults to `true` for on-screen previews. Snapshot pipelines\n * pass `false` so the captured PNG matches the source PPT's edges exactly\n * — html2canvas would otherwise bake the 1px shadow outline and the\n * 0.5rem corner radius into the output and the comparator reads them as\n * a thin border + rounded corners that the original PPT does not have.\n */\n chrome?: boolean;\n}\n\nexport function SlideCanvas(props: SlideCanvasProps) {\n const ctx = useOptionalSlideContext();\n const slide = props.slide ?? ctx?.slide;\n if (!slide) {\n throw new Error(\n '<SlideCanvas> requires `slide` either as a prop or via <SlideRendererProvider>.',\n );\n }\n\n const scale = props.scale ?? ctx?.scale;\n const background = props.background ?? ctx?.background;\n const effects = props.effects ?? ctx?.effects;\n const renderImage = props.renderImage ?? ctx?.renderImage;\n const renderVideo = props.renderVideo ?? ctx?.renderVideo;\n const renderText = props.renderText;\n const renderShapeLabel = props.renderShapeLabel;\n const renderTable = props.renderTable;\n const videoInteractive = props.videoInteractive ?? ctx?.videoInteractive;\n const onElementClick = props.onElementClick ?? ctx?.onElementClick;\n const elementIdPrefix = props.elementIdPrefix ?? 'slide-element-';\n const { className, dragOffsets, style } = props;\n const chrome = props.chrome ?? true;\n\n const canvasRef = useRef<HTMLDivElement>(null);\n const elements = slide.elements;\n const visibleElements = useMemo(() => {\n if (!props.hiddenElementIds?.length) return elements;\n const hidden = new Set(props.hiddenElementIds);\n return elements.filter((element) => !hidden.has(element.id));\n }, [elements, props.hiddenElementIds]);\n const elementIndexById = useMemo(\n () => new Map(elements.map((element, index) => [element.id, index + 1])),\n [elements],\n );\n\n const { viewportStyles, fitScale } = useViewportSize(canvasRef, {\n viewportSize: slide.viewportSize,\n viewportRatio: slide.viewportRatio,\n canvasPercentage: props.canvasPercentage,\n onScaleChange: scale === undefined ? props.onScaleChange : undefined,\n });\n const canvasScale = scale ?? fitScale;\n\n const resolvedBackground = background ?? slide.background;\n const { backgroundStyle } = useSlideBackgroundStyle(resolvedBackground);\n\n // Plain derivations: when this package is consumed in a React Compiler build\n // these are auto-memoized; otherwise the cost (O(elements) lookups) is trivial.\n const laserGeometry: PercentageGeometry | null = effects?.laser\n ? findElementGeometry(\n visibleElements,\n effects.laser.elementId,\n slide.viewportSize,\n slide.viewportRatio,\n )\n : null;\n\n const zoomGeometry: PercentageGeometry | null = effects?.zoom\n ? findElementGeometry(\n visibleElements,\n effects.zoom.elementId,\n slide.viewportSize,\n slide.viewportRatio,\n )\n : null;\n\n const highlights = effects?.highlights ?? (effects?.highlight ? [effects.highlight] : []);\n\n return (\n <div\n ref={canvasRef}\n className={className}\n style={{\n position: 'relative',\n width: '100%',\n height: '100%',\n overflow: 'hidden',\n userSelect: 'none',\n ...style,\n }}\n >\n <style dangerouslySetInnerHTML={{ __html: SLIDE_RENDERER_STYLES }} />\n <div\n style={{\n position: 'absolute',\n ...(chrome\n ? {\n boxShadow: '0 0 0 1px rgba(0, 0, 0, 0.01), 0 0 12px 0 rgba(0, 0, 0, 0.1)',\n borderRadius: '0.5rem',\n }\n : {}),\n overflow: 'hidden',\n transitionProperty: 'transform',\n transitionDuration: '700ms',\n width: `${viewportStyles.width * canvasScale}px`,\n height: `${viewportStyles.height * canvasScale}px`,\n left: `${viewportStyles.left}px`,\n top: `${viewportStyles.top}px`,\n ...(effects?.zoom && zoomGeometry\n ? {\n transform: `scale(${effects.zoom.scale})`,\n transformOrigin: `${zoomGeometry.centerX}% ${zoomGeometry.centerY}%`,\n }\n : {}),\n }}\n >\n <div\n style={{\n width: '100%',\n height: '100%',\n backgroundPosition: 'center',\n ...(chrome ? { borderRadius: '0.5rem' } : {}),\n ...backgroundStyle,\n }}\n />\n\n <div\n style={{\n position: 'absolute',\n top: 0,\n left: 0,\n transformOrigin: 'top left',\n width: `${viewportStyles.width}px`,\n height: `${viewportStyles.height}px`,\n transform: `scale(${canvasScale})`,\n }}\n >\n <InlineMathPriorityContext.Provider value={props.mathPriority ?? 'normal'}>\n {visibleElements.map((element) => (\n <SlideElement\n key={element.id}\n elementInfo={element}\n elementIndex={elementIndexById.get(element.id) ?? 1}\n theme={slide.theme}\n renderImage={renderImage}\n renderVideo={renderVideo}\n renderText={renderText}\n renderShapeLabel={renderShapeLabel}\n renderTable={renderTable}\n videoInteractive={videoInteractive}\n onElementClick={onElementClick}\n idPrefix={elementIdPrefix}\n dragOffset={dragOffsets?.get(element.id)}\n />\n ))}\n </InlineMathPriorityContext.Provider>\n\n {highlights.map((highlight) => {\n const element = visibleElements.find((el) => el.id === highlight.elementId);\n return element ? (\n <HighlightOverlay key={highlight.elementId} element={element} options={highlight} />\n ) : null;\n })}\n </div>\n\n <SpotlightOverlay\n options={effects?.spotlight}\n elementIdPrefix={elementIdPrefix}\n measurementKey={visibleElements}\n />\n\n <div\n style={{\n position: 'absolute',\n inset: 0,\n pointerEvents: 'none',\n padding: '5%',\n }}\n >\n <div style={{ position: 'relative', width: '100%', height: '100%' }}>\n <AnimatePresence>\n {effects?.laser && laserGeometry && (\n <LaserOverlay\n key={`laser-${effects.laser.elementId}`}\n geometry={laserGeometry}\n color={effects.laser.color}\n duration={effects.laser.duration}\n />\n )}\n </AnimatePresence>\n </div>\n </div>\n </div>\n </div>\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AA8FM;AACJ;;;AAGE;;;;;;;AAUF;AACA;AACA;;;AAGA;;AAEA;AAEA;AACA;AACA;AACE;AAAqC;;AAErC;;AAEF;;;;;AASE;AACD;AACD;AAEA;;;;AAKA;AACE;;AAQF;AACE;;;;AAeI;AACA;AACA;AACA;AACA;AACA;AACD;AAKG;AACA;AACE;AACI;AACA;AACD;;AAEL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACE;AACI;;AAED;;;AAMH;AACA;AACA;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA;AACA;;;AAyBA;;;AAeA;AACA;AACA;AACA;AACD;AAkBX;;"}
@@ -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;;"}
@@ -59,7 +59,7 @@ async function slideToPng(slide, options = {}) {
59
59
  root.render(createElement(SlideCanvas, { slide, chrome: false }));
60
60
  });
61
61
  // Typeset every inline formula now, root by root: the live renderer
62
- // leaves what its per-pass budget does not cover to idle time, after this
62
+ // leaves what the shared live budget does not cover to idle time, after this
63
63
  // capture.
64
64
  completeInlineMath(container);
65
65
  // BaseImageElement renders <img loading="lazy">, and this container sits
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../src/snapshot/index.ts"],"sourcesContent":["'use client';\n\nimport { bakeImageSoftEdge } from './bakeImageSoftEdge';\n\n/**\n * Off-screen Slide → PNG renderer.\n *\n * Mounts the given `Slide` into an off-screen container at its native pixel\n * size, waits for fonts + images to settle, then rasterizes the DOM. Returns the\n * rendered output as a Blob (default) or a `data:image/png;base64,...` string.\n *\n * Rasterization is native-paint-first: `html-to-image` serializes the slide into\n * an SVG `<foreignObject>` that the **same Chrome engine painting the live\n * classroom** rasterizes — so formulas (KaTeX HTML), CSS `filter`, soft-edge\n * `mask`, and mixed CJK/Latin text come out exactly as the classroom shows them.\n * html2canvas-pro, by contrast, re-implements layout/paint and so re-rasterizes\n * KaTeX's vlist/frac-line/delimiter internals, drops CSS filter/mask, and can't\n * draw `<video>` — all sources of the exported-vs-live drift.\n *\n * The one thing a foreignObject SVG can't do is reach the document's font\n * registry, so web fonts must be inlined as data URLs first (`getFontEmbedCSS`).\n * This is the historical reason html-to-image was avoided (fonts loaded async →\n * fallback-font wrapping); embedding up front removes it. If the embed still\n * misses the KaTeX faces, or a cross-origin image taints the canvas, we fall back\n * to html2canvas-pro (baking filter/mask into pixels and neutralizing its KaTeX\n * text-rendering override) rather than ship broken output.\n *\n * Use cases: visual regression baselines (compare with the source PPT's\n * own PNG export), user-triggered \"export slide as image\", CI snapshot\n * jobs. Caller does not need a live `<SlideCanvas>` mounted in the UI.\n */\n\nimport { createElement } from 'react';\nimport { flushSync } from 'react-dom';\nimport { createRoot, type Root } from 'react-dom/client';\nimport html2canvas from 'html2canvas-pro';\nimport { getFontEmbedCSS, toBlob, toPng } from 'html-to-image';\nimport { SlideCanvas } from '../SlideCanvas';\nimport type { Slide } from '@openmaic/dsl';\nimport { KATEX_FONT_EMBED_CSS } from './katex-fonts-embed';\nimport { completeInlineMath } from '../utils/inlineMath';\n\nexport { measureSlideElementGeometry, type MeasuredGeometry, type MeasureOptions } from './measure';\n\nexport interface SlideToPngOptions {\n /**\n * Output pixel width. Defaults to the slide's native `viewportSize`\n * (e.g. 1280 for a 16:9 widescreen deck). Height is derived from\n * `viewportRatio`.\n */\n width?: number;\n /**\n * Multiplier on output resolution. Default tracks `window.devicePixelRatio`\n * (typically 2 on retina displays) so the exported PNG is as sharp as\n * the on-screen canvas. Pass 1 for a lighter file at the cost of\n * sub-pixel clarity.\n */\n pixelRatio?: number;\n /**\n * Background color filled behind the slide. Defaults to white. Pass\n * 'transparent' to keep the slide's own background only.\n */\n backgroundColor?: string;\n /**\n * Output format. 'blob' yields a `Blob` suitable for `URL.createObjectURL`\n * + download; 'dataUrl' yields a `data:image/png;base64,...` string.\n */\n format?: 'blob' | 'dataUrl';\n /**\n * Settle timeout in milliseconds. The snapshot waits for `document.fonts.ready`\n * and every `<img>` inside the container to load (or error) before\n * capturing — but won't wait longer than this. Defaults to 5000.\n */\n timeoutMs?: number;\n /**\n * Debug only — render the off-screen container on-screen for the given\n * number of milliseconds after snapshot so you can visually confirm what\n * was captured. Do not use in production.\n */\n debugVisibleMs?: number;\n}\n\nconst DEFAULT_VIEWPORT_RATIO = 0.5625;\nconst DEFAULT_TIMEOUT_MS = 5000;\n\n/**\n * Render a `Slide` to a PNG image.\n *\n * Throws if called outside a browser (no `document` / `window`), if React\n * fails to mount, or if html2canvas-pro hits a CORS-tainted canvas (cross-\n * origin `<img>` without permissive headers will block the snapshot).\n */\nexport async function slideToPng(\n slide: Slide,\n options: SlideToPngOptions = {},\n): Promise<Blob | string> {\n if (typeof document === 'undefined') {\n throw new Error('slideToPng requires a browser environment');\n }\n\n const width = options.width ?? slide.viewportSize ?? 1280;\n const viewportRatio = slide.viewportRatio ?? DEFAULT_VIEWPORT_RATIO;\n const height = Math.round(width * viewportRatio);\n const backgroundColor = options.backgroundColor ?? '#ffffff';\n const pixelRatio = options.pixelRatio ?? window.devicePixelRatio ?? 1;\n const format = options.format ?? 'blob';\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const debugVisibleMs = options.debugVisibleMs ?? 0;\n\n // Off-screen container sized exactly to the slide so SlideCanvas's\n // fit-to-container math collapses to a 1:1 native render (no scale, no\n // centering offset). `position: absolute` (not fixed) + far-left offset\n // keeps the element in layout but out of the viewport; some browsers\n // skip paint for `position: fixed` elements outside the viewport, which\n // breaks the snapshot.\n const container = document.createElement('div');\n container.style.cssText = [\n 'position: absolute',\n 'left: -99999px',\n 'top: 0',\n `width: ${width}px`,\n `height: ${height}px`,\n 'pointer-events: none',\n `background-color: ${backgroundColor}`,\n ].join('; ');\n document.body.appendChild(container);\n\n let root: Root | null = null;\n try {\n root = createRoot(container);\n // flushSync forces the initial commit to happen synchronously instead of\n // being deferred by React 18's scheduler. Without it, the next RAFs can\n // fire before the first render lands and the snapshot captures an empty\n // container.\n flushSync(() => {\n root!.render(createElement(SlideCanvas, { slide, chrome: false }));\n });\n // Typeset every inline formula now, root by root: the live renderer\n // leaves what its per-pass budget does not cover to idle time, after this\n // capture.\n completeInlineMath(container);\n\n // BaseImageElement renders <img loading=\"lazy\">, and this container sits\n // permanently outside the viewport — lazy images would never fetch, and\n // the load-wait below would time out on blank slides. Force eager loading\n // for the throwaway tree so snapshot behavior is unchanged.\n container.querySelectorAll('img').forEach((img) => {\n img.loading = 'eager';\n });\n\n // Give the SlideCanvas's ResizeObserver-driven `useViewportSize` a few\n // frames to fire and write `fitScale`. Default state already paints at\n // 1:1, but waiting avoids a flash of unscaled content when the slide\n // viewportSize differs from the container.\n await nextFrame();\n await nextFrame();\n\n // Charts load ECharts asynchronously because it is an optional peer\n // dependency. Wait for every chart element to finish loading before\n // rasterizing; otherwise exports can capture the intentionally empty\n // loading container while the live slide eventually renders correctly.\n await waitForCharts(container, timeoutMs);\n\n // Explicitly force-load every (style, weight, family) the slide actually\n // uses BEFORE snapshotting. `document.fonts.ready` alone is racy: it can\n // resolve before the off-screen render has triggered a self-hosted woff2\n // fetch, so html2canvas captures a fallback face. For mixed CJK+Latin text\n // the fallback's Latin/digit advance widths differ from the intended font,\n // shifting number/English runs (seen on cold single-slide exports). Loading\n // each face up front makes the capture deterministic regardless of warmup.\n if (document.fonts && typeof document.fonts.load === 'function') {\n const fontSpecs = new Set<string>();\n container.querySelectorAll<HTMLElement>('*').forEach((el) => {\n if (!el.textContent || !el.textContent.trim()) return;\n const cs = getComputedStyle(el);\n if (!cs.fontFamily) return;\n fontSpecs.add(`${cs.fontStyle} ${cs.fontWeight} 16px ${cs.fontFamily}`);\n });\n await Promise.race([\n Promise.all([...fontSpecs].map((spec) => document.fonts.load(spec).catch(() => undefined))),\n new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)),\n ]);\n }\n\n await Promise.race([\n Promise.all([\n document.fonts ? document.fonts.ready : Promise.resolve(),\n ...Array.from(container.querySelectorAll('img')).map((img) => {\n if (img.complete && img.naturalWidth > 0) return Promise.resolve();\n return new Promise<void>((resolve) => {\n const done = () => resolve();\n img.addEventListener('load', done, { once: true });\n img.addEventListener('error', done, { once: true });\n });\n }),\n ]),\n new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)),\n ]);\n\n // html2canvas-pro can't draw <video> elements (it ignores the `poster`\n // attribute and renders nothing for an undecoded source), so a video that\n // shows fine on the live canvas comes out白板 in the PNG. Convert every\n // <video> in the throwaway off-screen tree into an <img> of its poster\n // (or current decoded frame) BEFORE the snapshot. The native-paint path can\n // render a poster'd <video>, but a posterless one still needs the decoded\n // frame, so we do this for both capture paths.\n await Promise.all(\n Array.from(container.querySelectorAll('video')).map((video) => replaceVideoWithFrame(video)),\n );\n\n // Let any font-triggered relayout settle before capture. KaTeX formulas\n // re-run their shrink-to-fit measurement once the KaTeX_Size faces finish\n // loading (BaseLatexElement); that's a React state update, so give it two\n // frames to commit before we read the DOM — otherwise a cold export can\n // capture the stale fallback-metric scale (misaligned large braces).\n await nextFrame();\n await nextFrame();\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.debug('[slideToPng] container ready', {\n innerHTMLLength: container.innerHTML.length,\n imgCount: container.querySelectorAll('img').length,\n size: `${width}x${height}`,\n });\n }\n\n // Target the inner SlideCanvas root so the capture's bounding box matches the\n // slide exactly (otherwise the outer container's padding/margin assumptions\n // can leave white edges).\n const target = (container.firstElementChild as HTMLElement | null) ?? container;\n\n // PRIMARY: native paint via `html-to-image` (foreignObject → the same Chrome\n // engine that paints the live classroom rasterizes the same DOM). Reproduces\n // formulas, CSS filter, soft-edge masks, and mixed CJK/Latin text as the\n // classroom shows them — no per-feature bakes.\n //\n // A foreignObject SVG can't reach the document font registry, so fonts must\n // be inlined as data URLs first. KaTeX math faces are prepended from the\n // bundled woff2 ({@link KATEX_FONT_EMBED_CSS}) — NOT left to `getFontEmbedCSS`,\n // which reads `cssRules` and silently drops a cross-origin KaTeX stylesheet,\n // collapsing large braces to a fallback glyph. `getFontEmbedCSS` still runs\n // for brand/CJK web fonts. As a belt-and-braces guard we verify every KaTeX\n // face the formula actually references is present in the combined CSS, and\n // fall back to html2canvas rather than ship broken glyphs if any is missing.\n try {\n const fontEmbedCSS = KATEX_FONT_EMBED_CSS + '\\n' + (await getFontEmbedCSS(target));\n const missing = missingKatexFaces(target, fontEmbedCSS);\n if (missing.length > 0) {\n throw new Error(\n `KaTeX font faces not embedded (${missing.join(', ')}); using html2canvas fallback`,\n );\n }\n const nativeOpts = {\n width,\n height,\n pixelRatio,\n backgroundColor,\n fontEmbedCSS,\n cacheBust: false,\n };\n if (format === 'blob') {\n const blob = await toBlob(target, nativeOpts);\n if (!blob) throw new Error('html-to-image toBlob returned null');\n return blob;\n }\n return await toPng(target, nativeOpts);\n } catch (nativeErr) {\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.debug(\n '[slideToPng] native paint unavailable, falling back to html2canvas:',\n nativeErr,\n );\n }\n }\n\n // FALLBACK: html2canvas-pro. Reached only when native paint fails (e.g. a\n // cross-origin image taints the foreignObject canvas). It can't render CSS\n // `filter` (PPT lum/alphaModFix washout) or the soft-edge `mask`\n // (a:softEdge), so bake both into pixels first with a Canvas2D pass.\n await Promise.all(\n Array.from(container.querySelectorAll('img')).map((img) => bakeImageFilter(img)),\n );\n await Promise.all(\n Array.from(container.querySelectorAll<HTMLImageElement>('img[data-soft-edge]')).map((img) =>\n bakeImageSoftEdge(img),\n ),\n );\n\n const canvas = await html2canvas(target, {\n backgroundColor,\n width,\n height,\n scale: pixelRatio,\n useCORS: true,\n // Skip walking the page's stylesheets; the cloned DOM already inherits\n // computed styles. This also avoids CORS errors when the document has\n // cross-origin stylesheets.\n foreignObjectRendering: false,\n logging: false,\n // html2canvas-pro's CJK text measurement can mis-position full-width\n // punctuation (e.g. `(`/`)` get pushed past the cell boundary and\n // appear clipped). Force neutral kerning + feature settings on the\n // cloned tree so each glyph advances at its natural width — but restore\n // native rendering for KaTeX, whose glyph metrics the override would\n // reshape (misaligned braces/subscripts).\n onclone: (clonedDoc) => {\n const style = clonedDoc.createElement('style');\n style.textContent = `\n .slide-renderer-cell-text,\n .slide-renderer-cell-text *,\n .slide-renderer-prose,\n .slide-renderer-prose * {\n font-kerning: none !important;\n font-feature-settings: normal !important;\n font-variant-east-asian: normal !important;\n text-rendering: geometricPrecision !important;\n }\n .slide-renderer-prose .katex,\n .slide-renderer-prose .katex * {\n font-kerning: auto !important;\n text-rendering: auto !important;\n }\n `;\n clonedDoc.head.appendChild(style);\n },\n });\n\n if (format === 'blob') {\n return await canvasToBlob(canvas);\n }\n return canvas.toDataURL('image/png');\n } finally {\n if (debugVisibleMs > 0) {\n // Temporarily show the container on-screen so the caller can compare\n // what was captured vs the on-page render.\n container.style.left = '0';\n container.style.top = '0';\n container.style.zIndex = '99999';\n container.style.border = '4px dashed magenta';\n await new Promise((r) => setTimeout(r, debugVisibleMs));\n }\n // Defer unmount one tick so React doesn't warn about unmounting during\n // a commit phase (the html2canvas promise can still be mid-render in\n // dev mode).\n if (root) {\n const r = root;\n setTimeout(() => r.unmount(), 0);\n }\n setTimeout(() => container.remove(), 0);\n }\n}\n\nfunction nextFrame(): Promise<void> {\n return new Promise((resolve) => requestAnimationFrame(() => resolve()));\n}\n\nasync function waitForCharts(root: HTMLElement, timeoutMs: number): Promise<void> {\n const deadline = performance.now() + timeoutMs;\n while (root.querySelector('[data-chart-state=\"loading\"]')) {\n if (performance.now() >= deadline) return;\n await nextFrame();\n }\n}\n\n/**\n * KaTeX faces (`KaTeX_Main`, `KaTeX_Size4`, …) actually referenced by the\n * formulas in `root` that are NOT declared in `fontEmbedCSS`. A non-empty result\n * means the native-paint capture would render those glyphs in a fallback font\n * (e.g. a large brace collapsing to a small `{`), so the caller falls back to\n * html2canvas. Reads each `.katex` descendant's computed `font-family` — the\n * families the browser resolved for the glyphs actually on screen — rather than\n * assuming the full set, so an all-embedded formula never triggers a fallback.\n */\nfunction missingKatexFaces(root: HTMLElement, fontEmbedCSS: string): string[] {\n const used = new Set<string>();\n root.querySelectorAll<HTMLElement>('.katex, .katex *').forEach((el) => {\n for (const part of getComputedStyle(el).fontFamily.split(',')) {\n const name = part.trim().replace(/^[\"']|[\"']$/g, '');\n if (name.startsWith('KaTeX_')) used.add(name);\n }\n });\n return [...used].filter((face) => !fontEmbedCSS.includes(face));\n}\n\n/**\n * Replace a <video> with an <img> showing its poster (or, if no poster is set,\n * its current decoded frame drawn onto a canvas). Copies the video's inline\n * style so layout is unchanged, then waits for the <img> to load so the\n * subsequent html2canvas pass captures it. No-ops if there's nothing to draw.\n */\nasync function replaceVideoWithFrame(video: HTMLVideoElement): Promise<void> {\n const parent = video.parentElement;\n if (!parent) return;\n\n let imgSrc: string | null = video.poster || video.getAttribute('poster') || null;\n\n // No poster but the source decoded → grab the current frame.\n if (!imgSrc && video.readyState >= 2 && video.videoWidth > 0) {\n try {\n const frame = document.createElement('canvas');\n frame.width = video.videoWidth;\n frame.height = video.videoHeight;\n frame.getContext('2d')?.drawImage(video, 0, 0);\n imgSrc = frame.toDataURL('image/png');\n } catch {\n // CORS-tainted frame — leave imgSrc null and bail below.\n }\n }\n if (!imgSrc) return;\n\n const img = document.createElement('img');\n img.src = imgSrc;\n img.style.cssText = video.style.cssText;\n if (!img.style.width) img.style.width = '100%';\n if (!img.style.height) img.style.height = '100%';\n if (!img.style.objectFit) img.style.objectFit = 'contain';\n\n await new Promise<void>((resolve) => {\n if (img.complete && img.naturalWidth > 0) return resolve();\n img.addEventListener('load', () => resolve(), { once: true });\n img.addEventListener('error', () => resolve(), { once: true });\n });\n\n parent.replaceChild(img, video);\n}\n\n/**\n * Bake an <img>'s CSS `filter` into its bitmap. html2canvas-pro ignores the\n * `filter` property, so without this any brightness/contrast/saturate/opacity\n * applied by the renderer (PPT lum/alphaModFix corrections) is lost in the PNG.\n * Draws the image through a Canvas2D `ctx.filter` pass, swaps the src for the\n * baked PNG, and clears the inline filter so the value isn't double-applied.\n * No-ops when there's no filter, the image hasn't decoded, or the canvas is\n * CORS-tainted (export would throw — leave the original img untouched).\n */\nasync function bakeImageFilter(img: HTMLImageElement): Promise<void> {\n const filter = (img.style.filter || '').trim();\n if (!filter || filter === 'none') return;\n if (!img.complete || img.naturalWidth === 0) return;\n\n try {\n const canvas = document.createElement('canvas');\n canvas.width = img.naturalWidth;\n canvas.height = img.naturalHeight;\n const ctx = canvas.getContext('2d');\n if (!ctx) return;\n ctx.filter = filter;\n ctx.drawImage(img, 0, 0, canvas.width, canvas.height);\n const baked = canvas.toDataURL('image/png');\n\n img.style.filter = '';\n await new Promise<void>((resolve) => {\n img.addEventListener('load', () => resolve(), { once: true });\n img.addEventListener('error', () => resolve(), { once: true });\n img.src = baked;\n });\n } catch {\n // CORS-tainted source or unsupported ctx.filter — keep the original <img>.\n }\n}\n\nfunction canvasToBlob(canvas: HTMLCanvasElement): Promise<Blob> {\n return new Promise((resolve, reject) => {\n canvas.toBlob((blob) => {\n if (blob) resolve(blob);\n else reject(new Error('slideToPng: canvas.toBlob returned null'));\n }, 'image/png');\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAkFA;AACA;AAEA;;;;;;AAMG;AACI;AAIL;AACE;;;AAIF;;AAEA;;AAEA;AACA;AACA;;;;;;;;AASA;;;;AAIE;AACA;;AAEA;AACD;AACD;;AAGA;AACE;;;;;;AAME;AACF;;;;;;;;;;AAWE;AACF;;;;;;;;;;;AAaA;;;;;;;;AASA;AACE;;;;AAGE;;;AAEA;AACF;;AAEE;AACA;AACD;;;;AAKC;AACA;;AAC4C;AAC1C;AACE;AACA;AACA;AACF;AACF;;AAEF;AACD;;;;;;;;AASD;;;;;;;;;;AAcE;AACE;;AAEA;AACD;;;;;AAMH;;;;;;;;;;;;;;AAeA;AACE;;AAEA;AACE;;AAIF;;;;;;AAME;;AAEF;;AAEE;AAAW;AACX;;AAEF;;;;;AAIE;;;;;;;AAWJ;AAGA;AAMA;;;;AAIE;AACA;;;;AAIA;AACA;;;;;;;AAOA;;;;;;;;;;;;;;;;;;AAkBE;;AAEH;AAED;AACE;;AAEF;;;AAEA;;;AAGE;AACA;AACA;AACA;AACA;;;;;;;;;;;AAWN;AAEA;AACE;AACF;AAEA;;AAEE;AACE;;;;AAGJ;AAEA;;;;;;;;AAQG;AACH;AACE;;AAEE;AACE;AACA;AAA+B;;AAEnC;;AAEF;AAEA;;;;;AAKG;AACH;AACE;AACA;;AAEA;;AAGA;AACE;;AAEE;AACA;AACA;AACA;;AACA;;;;AAIJ;;;AAGA;;AAEA;AAAsB;AACtB;AAAuB;AACvB;AAA0B;AAE1B;;;AAEE;AACA;AACF;AAEA;AACF;AAEA;;;;;;;;AAQG;AACH;AACE;AACA;;;;AAGA;;AAEE;AACA;;AAEA;;AACA;AACA;;AAGA;AACA;AACE;AACA;AACA;AACF;;AACA;;;AAGJ;AAEA;;AAEI;AACE;;;AACK;;AAET;AACF;;"}
1
+ {"version":3,"file":"index.js","sources":["../../src/snapshot/index.ts"],"sourcesContent":["'use client';\n\nimport { bakeImageSoftEdge } from './bakeImageSoftEdge';\n\n/**\n * Off-screen Slide → PNG renderer.\n *\n * Mounts the given `Slide` into an off-screen container at its native pixel\n * size, waits for fonts + images to settle, then rasterizes the DOM. Returns the\n * rendered output as a Blob (default) or a `data:image/png;base64,...` string.\n *\n * Rasterization is native-paint-first: `html-to-image` serializes the slide into\n * an SVG `<foreignObject>` that the **same Chrome engine painting the live\n * classroom** rasterizes — so formulas (KaTeX HTML), CSS `filter`, soft-edge\n * `mask`, and mixed CJK/Latin text come out exactly as the classroom shows them.\n * html2canvas-pro, by contrast, re-implements layout/paint and so re-rasterizes\n * KaTeX's vlist/frac-line/delimiter internals, drops CSS filter/mask, and can't\n * draw `<video>` — all sources of the exported-vs-live drift.\n *\n * The one thing a foreignObject SVG can't do is reach the document's font\n * registry, so web fonts must be inlined as data URLs first (`getFontEmbedCSS`).\n * This is the historical reason html-to-image was avoided (fonts loaded async →\n * fallback-font wrapping); embedding up front removes it. If the embed still\n * misses the KaTeX faces, or a cross-origin image taints the canvas, we fall back\n * to html2canvas-pro (baking filter/mask into pixels and neutralizing its KaTeX\n * text-rendering override) rather than ship broken output.\n *\n * Use cases: visual regression baselines (compare with the source PPT's\n * own PNG export), user-triggered \"export slide as image\", CI snapshot\n * jobs. Caller does not need a live `<SlideCanvas>` mounted in the UI.\n */\n\nimport { createElement } from 'react';\nimport { flushSync } from 'react-dom';\nimport { createRoot, type Root } from 'react-dom/client';\nimport html2canvas from 'html2canvas-pro';\nimport { getFontEmbedCSS, toBlob, toPng } from 'html-to-image';\nimport { SlideCanvas } from '../SlideCanvas';\nimport type { Slide } from '@openmaic/dsl';\nimport { KATEX_FONT_EMBED_CSS } from './katex-fonts-embed';\nimport { completeInlineMath } from '../utils/inlineMath';\n\nexport { measureSlideElementGeometry, type MeasuredGeometry, type MeasureOptions } from './measure';\n\nexport interface SlideToPngOptions {\n /**\n * Output pixel width. Defaults to the slide's native `viewportSize`\n * (e.g. 1280 for a 16:9 widescreen deck). Height is derived from\n * `viewportRatio`.\n */\n width?: number;\n /**\n * Multiplier on output resolution. Default tracks `window.devicePixelRatio`\n * (typically 2 on retina displays) so the exported PNG is as sharp as\n * the on-screen canvas. Pass 1 for a lighter file at the cost of\n * sub-pixel clarity.\n */\n pixelRatio?: number;\n /**\n * Background color filled behind the slide. Defaults to white. Pass\n * 'transparent' to keep the slide's own background only.\n */\n backgroundColor?: string;\n /**\n * Output format. 'blob' yields a `Blob` suitable for `URL.createObjectURL`\n * + download; 'dataUrl' yields a `data:image/png;base64,...` string.\n */\n format?: 'blob' | 'dataUrl';\n /**\n * Settle timeout in milliseconds. The snapshot waits for `document.fonts.ready`\n * and every `<img>` inside the container to load (or error) before\n * capturing — but won't wait longer than this. Defaults to 5000.\n */\n timeoutMs?: number;\n /**\n * Debug only — render the off-screen container on-screen for the given\n * number of milliseconds after snapshot so you can visually confirm what\n * was captured. Do not use in production.\n */\n debugVisibleMs?: number;\n}\n\nconst DEFAULT_VIEWPORT_RATIO = 0.5625;\nconst DEFAULT_TIMEOUT_MS = 5000;\n\n/**\n * Render a `Slide` to a PNG image.\n *\n * Throws if called outside a browser (no `document` / `window`), if React\n * fails to mount, or if html2canvas-pro hits a CORS-tainted canvas (cross-\n * origin `<img>` without permissive headers will block the snapshot).\n */\nexport async function slideToPng(\n slide: Slide,\n options: SlideToPngOptions = {},\n): Promise<Blob | string> {\n if (typeof document === 'undefined') {\n throw new Error('slideToPng requires a browser environment');\n }\n\n const width = options.width ?? slide.viewportSize ?? 1280;\n const viewportRatio = slide.viewportRatio ?? DEFAULT_VIEWPORT_RATIO;\n const height = Math.round(width * viewportRatio);\n const backgroundColor = options.backgroundColor ?? '#ffffff';\n const pixelRatio = options.pixelRatio ?? window.devicePixelRatio ?? 1;\n const format = options.format ?? 'blob';\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const debugVisibleMs = options.debugVisibleMs ?? 0;\n\n // Off-screen container sized exactly to the slide so SlideCanvas's\n // fit-to-container math collapses to a 1:1 native render (no scale, no\n // centering offset). `position: absolute` (not fixed) + far-left offset\n // keeps the element in layout but out of the viewport; some browsers\n // skip paint for `position: fixed` elements outside the viewport, which\n // breaks the snapshot.\n const container = document.createElement('div');\n container.style.cssText = [\n 'position: absolute',\n 'left: -99999px',\n 'top: 0',\n `width: ${width}px`,\n `height: ${height}px`,\n 'pointer-events: none',\n `background-color: ${backgroundColor}`,\n ].join('; ');\n document.body.appendChild(container);\n\n let root: Root | null = null;\n try {\n root = createRoot(container);\n // flushSync forces the initial commit to happen synchronously instead of\n // being deferred by React 18's scheduler. Without it, the next RAFs can\n // fire before the first render lands and the snapshot captures an empty\n // container.\n flushSync(() => {\n root!.render(createElement(SlideCanvas, { slide, chrome: false }));\n });\n // Typeset every inline formula now, root by root: the live renderer\n // leaves what the shared live budget does not cover to idle time, after this\n // capture.\n completeInlineMath(container);\n\n // BaseImageElement renders <img loading=\"lazy\">, and this container sits\n // permanently outside the viewport — lazy images would never fetch, and\n // the load-wait below would time out on blank slides. Force eager loading\n // for the throwaway tree so snapshot behavior is unchanged.\n container.querySelectorAll('img').forEach((img) => {\n img.loading = 'eager';\n });\n\n // Give the SlideCanvas's ResizeObserver-driven `useViewportSize` a few\n // frames to fire and write `fitScale`. Default state already paints at\n // 1:1, but waiting avoids a flash of unscaled content when the slide\n // viewportSize differs from the container.\n await nextFrame();\n await nextFrame();\n\n // Charts load ECharts asynchronously because it is an optional peer\n // dependency. Wait for every chart element to finish loading before\n // rasterizing; otherwise exports can capture the intentionally empty\n // loading container while the live slide eventually renders correctly.\n await waitForCharts(container, timeoutMs);\n\n // Explicitly force-load every (style, weight, family) the slide actually\n // uses BEFORE snapshotting. `document.fonts.ready` alone is racy: it can\n // resolve before the off-screen render has triggered a self-hosted woff2\n // fetch, so html2canvas captures a fallback face. For mixed CJK+Latin text\n // the fallback's Latin/digit advance widths differ from the intended font,\n // shifting number/English runs (seen on cold single-slide exports). Loading\n // each face up front makes the capture deterministic regardless of warmup.\n if (document.fonts && typeof document.fonts.load === 'function') {\n const fontSpecs = new Set<string>();\n container.querySelectorAll<HTMLElement>('*').forEach((el) => {\n if (!el.textContent || !el.textContent.trim()) return;\n const cs = getComputedStyle(el);\n if (!cs.fontFamily) return;\n fontSpecs.add(`${cs.fontStyle} ${cs.fontWeight} 16px ${cs.fontFamily}`);\n });\n await Promise.race([\n Promise.all([...fontSpecs].map((spec) => document.fonts.load(spec).catch(() => undefined))),\n new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)),\n ]);\n }\n\n await Promise.race([\n Promise.all([\n document.fonts ? document.fonts.ready : Promise.resolve(),\n ...Array.from(container.querySelectorAll('img')).map((img) => {\n if (img.complete && img.naturalWidth > 0) return Promise.resolve();\n return new Promise<void>((resolve) => {\n const done = () => resolve();\n img.addEventListener('load', done, { once: true });\n img.addEventListener('error', done, { once: true });\n });\n }),\n ]),\n new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)),\n ]);\n\n // html2canvas-pro can't draw <video> elements (it ignores the `poster`\n // attribute and renders nothing for an undecoded source), so a video that\n // shows fine on the live canvas comes out白板 in the PNG. Convert every\n // <video> in the throwaway off-screen tree into an <img> of its poster\n // (or current decoded frame) BEFORE the snapshot. The native-paint path can\n // render a poster'd <video>, but a posterless one still needs the decoded\n // frame, so we do this for both capture paths.\n await Promise.all(\n Array.from(container.querySelectorAll('video')).map((video) => replaceVideoWithFrame(video)),\n );\n\n // Let any font-triggered relayout settle before capture. KaTeX formulas\n // re-run their shrink-to-fit measurement once the KaTeX_Size faces finish\n // loading (BaseLatexElement); that's a React state update, so give it two\n // frames to commit before we read the DOM — otherwise a cold export can\n // capture the stale fallback-metric scale (misaligned large braces).\n await nextFrame();\n await nextFrame();\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.debug('[slideToPng] container ready', {\n innerHTMLLength: container.innerHTML.length,\n imgCount: container.querySelectorAll('img').length,\n size: `${width}x${height}`,\n });\n }\n\n // Target the inner SlideCanvas root so the capture's bounding box matches the\n // slide exactly (otherwise the outer container's padding/margin assumptions\n // can leave white edges).\n const target = (container.firstElementChild as HTMLElement | null) ?? container;\n\n // PRIMARY: native paint via `html-to-image` (foreignObject → the same Chrome\n // engine that paints the live classroom rasterizes the same DOM). Reproduces\n // formulas, CSS filter, soft-edge masks, and mixed CJK/Latin text as the\n // classroom shows them — no per-feature bakes.\n //\n // A foreignObject SVG can't reach the document font registry, so fonts must\n // be inlined as data URLs first. KaTeX math faces are prepended from the\n // bundled woff2 ({@link KATEX_FONT_EMBED_CSS}) — NOT left to `getFontEmbedCSS`,\n // which reads `cssRules` and silently drops a cross-origin KaTeX stylesheet,\n // collapsing large braces to a fallback glyph. `getFontEmbedCSS` still runs\n // for brand/CJK web fonts. As a belt-and-braces guard we verify every KaTeX\n // face the formula actually references is present in the combined CSS, and\n // fall back to html2canvas rather than ship broken glyphs if any is missing.\n try {\n const fontEmbedCSS = KATEX_FONT_EMBED_CSS + '\\n' + (await getFontEmbedCSS(target));\n const missing = missingKatexFaces(target, fontEmbedCSS);\n if (missing.length > 0) {\n throw new Error(\n `KaTeX font faces not embedded (${missing.join(', ')}); using html2canvas fallback`,\n );\n }\n const nativeOpts = {\n width,\n height,\n pixelRatio,\n backgroundColor,\n fontEmbedCSS,\n cacheBust: false,\n };\n if (format === 'blob') {\n const blob = await toBlob(target, nativeOpts);\n if (!blob) throw new Error('html-to-image toBlob returned null');\n return blob;\n }\n return await toPng(target, nativeOpts);\n } catch (nativeErr) {\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.debug(\n '[slideToPng] native paint unavailable, falling back to html2canvas:',\n nativeErr,\n );\n }\n }\n\n // FALLBACK: html2canvas-pro. Reached only when native paint fails (e.g. a\n // cross-origin image taints the foreignObject canvas). It can't render CSS\n // `filter` (PPT lum/alphaModFix washout) or the soft-edge `mask`\n // (a:softEdge), so bake both into pixels first with a Canvas2D pass.\n await Promise.all(\n Array.from(container.querySelectorAll('img')).map((img) => bakeImageFilter(img)),\n );\n await Promise.all(\n Array.from(container.querySelectorAll<HTMLImageElement>('img[data-soft-edge]')).map((img) =>\n bakeImageSoftEdge(img),\n ),\n );\n\n const canvas = await html2canvas(target, {\n backgroundColor,\n width,\n height,\n scale: pixelRatio,\n useCORS: true,\n // Skip walking the page's stylesheets; the cloned DOM already inherits\n // computed styles. This also avoids CORS errors when the document has\n // cross-origin stylesheets.\n foreignObjectRendering: false,\n logging: false,\n // html2canvas-pro's CJK text measurement can mis-position full-width\n // punctuation (e.g. `(`/`)` get pushed past the cell boundary and\n // appear clipped). Force neutral kerning + feature settings on the\n // cloned tree so each glyph advances at its natural width — but restore\n // native rendering for KaTeX, whose glyph metrics the override would\n // reshape (misaligned braces/subscripts).\n onclone: (clonedDoc) => {\n const style = clonedDoc.createElement('style');\n style.textContent = `\n .slide-renderer-cell-text,\n .slide-renderer-cell-text *,\n .slide-renderer-prose,\n .slide-renderer-prose * {\n font-kerning: none !important;\n font-feature-settings: normal !important;\n font-variant-east-asian: normal !important;\n text-rendering: geometricPrecision !important;\n }\n .slide-renderer-prose .katex,\n .slide-renderer-prose .katex * {\n font-kerning: auto !important;\n text-rendering: auto !important;\n }\n `;\n clonedDoc.head.appendChild(style);\n },\n });\n\n if (format === 'blob') {\n return await canvasToBlob(canvas);\n }\n return canvas.toDataURL('image/png');\n } finally {\n if (debugVisibleMs > 0) {\n // Temporarily show the container on-screen so the caller can compare\n // what was captured vs the on-page render.\n container.style.left = '0';\n container.style.top = '0';\n container.style.zIndex = '99999';\n container.style.border = '4px dashed magenta';\n await new Promise((r) => setTimeout(r, debugVisibleMs));\n }\n // Defer unmount one tick so React doesn't warn about unmounting during\n // a commit phase (the html2canvas promise can still be mid-render in\n // dev mode).\n if (root) {\n const r = root;\n setTimeout(() => r.unmount(), 0);\n }\n setTimeout(() => container.remove(), 0);\n }\n}\n\nfunction nextFrame(): Promise<void> {\n return new Promise((resolve) => requestAnimationFrame(() => resolve()));\n}\n\nasync function waitForCharts(root: HTMLElement, timeoutMs: number): Promise<void> {\n const deadline = performance.now() + timeoutMs;\n while (root.querySelector('[data-chart-state=\"loading\"]')) {\n if (performance.now() >= deadline) return;\n await nextFrame();\n }\n}\n\n/**\n * KaTeX faces (`KaTeX_Main`, `KaTeX_Size4`, …) actually referenced by the\n * formulas in `root` that are NOT declared in `fontEmbedCSS`. A non-empty result\n * means the native-paint capture would render those glyphs in a fallback font\n * (e.g. a large brace collapsing to a small `{`), so the caller falls back to\n * html2canvas. Reads each `.katex` descendant's computed `font-family` — the\n * families the browser resolved for the glyphs actually on screen — rather than\n * assuming the full set, so an all-embedded formula never triggers a fallback.\n */\nfunction missingKatexFaces(root: HTMLElement, fontEmbedCSS: string): string[] {\n const used = new Set<string>();\n root.querySelectorAll<HTMLElement>('.katex, .katex *').forEach((el) => {\n for (const part of getComputedStyle(el).fontFamily.split(',')) {\n const name = part.trim().replace(/^[\"']|[\"']$/g, '');\n if (name.startsWith('KaTeX_')) used.add(name);\n }\n });\n return [...used].filter((face) => !fontEmbedCSS.includes(face));\n}\n\n/**\n * Replace a <video> with an <img> showing its poster (or, if no poster is set,\n * its current decoded frame drawn onto a canvas). Copies the video's inline\n * style so layout is unchanged, then waits for the <img> to load so the\n * subsequent html2canvas pass captures it. No-ops if there's nothing to draw.\n */\nasync function replaceVideoWithFrame(video: HTMLVideoElement): Promise<void> {\n const parent = video.parentElement;\n if (!parent) return;\n\n let imgSrc: string | null = video.poster || video.getAttribute('poster') || null;\n\n // No poster but the source decoded → grab the current frame.\n if (!imgSrc && video.readyState >= 2 && video.videoWidth > 0) {\n try {\n const frame = document.createElement('canvas');\n frame.width = video.videoWidth;\n frame.height = video.videoHeight;\n frame.getContext('2d')?.drawImage(video, 0, 0);\n imgSrc = frame.toDataURL('image/png');\n } catch {\n // CORS-tainted frame — leave imgSrc null and bail below.\n }\n }\n if (!imgSrc) return;\n\n const img = document.createElement('img');\n img.src = imgSrc;\n img.style.cssText = video.style.cssText;\n if (!img.style.width) img.style.width = '100%';\n if (!img.style.height) img.style.height = '100%';\n if (!img.style.objectFit) img.style.objectFit = 'contain';\n\n await new Promise<void>((resolve) => {\n if (img.complete && img.naturalWidth > 0) return resolve();\n img.addEventListener('load', () => resolve(), { once: true });\n img.addEventListener('error', () => resolve(), { once: true });\n });\n\n parent.replaceChild(img, video);\n}\n\n/**\n * Bake an <img>'s CSS `filter` into its bitmap. html2canvas-pro ignores the\n * `filter` property, so without this any brightness/contrast/saturate/opacity\n * applied by the renderer (PPT lum/alphaModFix corrections) is lost in the PNG.\n * Draws the image through a Canvas2D `ctx.filter` pass, swaps the src for the\n * baked PNG, and clears the inline filter so the value isn't double-applied.\n * No-ops when there's no filter, the image hasn't decoded, or the canvas is\n * CORS-tainted (export would throw — leave the original img untouched).\n */\nasync function bakeImageFilter(img: HTMLImageElement): Promise<void> {\n const filter = (img.style.filter || '').trim();\n if (!filter || filter === 'none') return;\n if (!img.complete || img.naturalWidth === 0) return;\n\n try {\n const canvas = document.createElement('canvas');\n canvas.width = img.naturalWidth;\n canvas.height = img.naturalHeight;\n const ctx = canvas.getContext('2d');\n if (!ctx) return;\n ctx.filter = filter;\n ctx.drawImage(img, 0, 0, canvas.width, canvas.height);\n const baked = canvas.toDataURL('image/png');\n\n img.style.filter = '';\n await new Promise<void>((resolve) => {\n img.addEventListener('load', () => resolve(), { once: true });\n img.addEventListener('error', () => resolve(), { once: true });\n img.src = baked;\n });\n } catch {\n // CORS-tainted source or unsupported ctx.filter — keep the original <img>.\n }\n}\n\nfunction canvasToBlob(canvas: HTMLCanvasElement): Promise<Blob> {\n return new Promise((resolve, reject) => {\n canvas.toBlob((blob) => {\n if (blob) resolve(blob);\n else reject(new Error('slideToPng: canvas.toBlob returned null'));\n }, 'image/png');\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAkFA;AACA;AAEA;;;;;;AAMG;AACI;AAIL;AACE;;;AAIF;;AAEA;;AAEA;AACA;AACA;;;;;;;;AASA;;;;AAIE;AACA;;AAEA;AACD;AACD;;AAGA;AACE;;;;;;AAME;AACF;;;;;;;;;;AAWE;AACF;;;;;;;;;;;AAaA;;;;;;;;AASA;AACE;;;;AAGE;;;AAEA;AACF;;AAEE;AACA;AACD;;;;AAKC;AACA;;AAC4C;AAC1C;AACE;AACA;AACA;AACF;AACF;;AAEF;AACD;;;;;;;;AASD;;;;;;;;;;AAcE;AACE;;AAEA;AACD;;;;;AAMH;;;;;;;;;;;;;;AAeA;AACE;;AAEA;AACE;;AAIF;;;;;;AAME;;AAEF;;AAEE;AAAW;AACX;;AAEF;;;;;AAIE;;;;;;;AAWJ;AAGA;AAMA;;;;AAIE;AACA;;;;AAIA;AACA;;;;;;;AAOA;;;;;;;;;;;;;;;;;;AAkBE;;AAEH;AAED;AACE;;AAEF;;;AAEA;;;AAGE;AACA;AACA;AACA;AACA;;;;;;;;;;;AAWN;AAEA;AACE;AACF;AAEA;;AAEE;AACE;;;;AAGJ;AAEA;;;;;;;;AAQG;AACH;AACE;;AAEE;AACE;AACA;AAA+B;;AAEnC;;AAEF;AAEA;;;;;AAKG;AACH;AACE;AACA;;AAEA;;AAGA;AACE;;AAEE;AACA;AACA;AACA;;AACA;;;;AAIJ;;;AAGA;;AAEA;AAAsB;AACtB;AAAuB;AACvB;AAA0B;AAE1B;;;AAEE;AACA;AACF;AAEA;AACF;AAEA;;;;;;;;AAQG;AACH;AACE;AACA;;;;AAGA;;AAEE;AACA;;AAEA;;AACA;AACA;;AAGA;AACA;AACE;AACA;AACA;AACF;;AACA;;;AAGJ;AAEA;;AAEI;AACE;;;AACK;;AAET;AACF;;"}
@@ -51,7 +51,7 @@ async function measureSlideElementGeometry(slide, elementIds, options = {}) {
51
51
  root.render(createElement(SlideCanvas, { slide, chrome: false }));
52
52
  });
53
53
  // Typeset every inline formula now, root by root: the live renderer
54
- // leaves what its per-pass budget does not cover to idle time, after this
54
+ // leaves what the shared live budget does not cover to idle time, after this
55
55
  // capture.
56
56
  completeInlineMath(container);
57
57
  // Let the ResizeObserver-driven fit settle, then settle fonts before we read
@@ -1 +1 @@
1
- {"version":3,"file":"measure.js","sources":["../../src/snapshot/measure.ts"],"sourcesContent":["'use client';\n\n/**\n * Off-screen element-geometry measurement.\n *\n * The video-export compiler places spotlight/laser/video effects on a slide\n * element's geometry. Its pure fallback ({@link ../geometry}) reads the\n * element's *authored* `left/top/width/height` against a fixed 1000×562.5 base\n * — the element's **outer box**. But the live overlays (and the exported frame\n * PNG) measure the element's `.element-content` box, which differs for\n * auto-sized text (`height:auto`) and its 10px content padding, so a spotlight\n * on the authored box sits offset from the rendered text (issue #867 item 5).\n *\n * This measures the same content box the live `SpotlightOverlay` does: it mounts\n * the slide off-screen at native size (the same 1:1 mount `slideToPng` uses),\n * then for each requested element id reads `.element-content`'s\n * `getBoundingClientRect()` normalized against the canvas container rect → 0–100\n * space. The app feeds the result to the compiler as a `GeometryProbe` so the\n * IR carries rendered geometry; the compile stays pure and falls back to the\n * authored box for anything not measured.\n *\n * App-side / impure: needs a browser (DOM + layout). Mirrors `slideToPng`'s\n * mount lifecycle.\n */\n\nimport { createElement } from 'react';\nimport { flushSync } from 'react-dom';\nimport { createRoot, type Root } from 'react-dom/client';\nimport { SlideCanvas } from '../SlideCanvas';\nimport type { Slide } from '@openmaic/dsl';\nimport { completeInlineMath } from '../utils/inlineMath';\n\n/** Percentage geometry (0–100) — mirrors the compiler's `PercentageGeometry`. */\nexport interface MeasuredGeometry {\n x: number;\n y: number;\n w: number;\n h: number;\n centerX: number;\n centerY: number;\n}\n\nexport interface MeasureOptions {\n /**\n * Off-screen render width in px. Defaults to the slide's native\n * `viewportSize`. Only the *ratio* of element box to container matters for the\n * 0–100 normalization, so the absolute width is not important — but rendering\n * near native size keeps text wrapping (hence auto-height) faithful.\n */\n width?: number;\n /** Settle timeout in ms for `document.fonts.ready`. Default 5000. */\n timeoutMs?: number;\n}\n\nconst DEFAULT_VIEWPORT_RATIO = 0.5625;\nconst DEFAULT_TIMEOUT_MS = 5000;\n/** SlideElement renders each element wrapper as `slide-element-<id>` by default. */\nconst ELEMENT_ID_PREFIX = 'slide-element-';\n\nfunction nextFrame(): Promise<void> {\n return new Promise((resolve) => requestAnimationFrame(() => resolve()));\n}\n\n/**\n * Measure the rendered content-box geometry (0–100) of the given element ids on\n * a slide. Returns a Map keyed by element id; ids that could not be located are\n * absent (the caller falls back to the authored-box calc). Never throws for a\n * missing element — only for a non-browser environment.\n *\n * The measurement matches `SpotlightOverlay`: prefer the element's\n * `.element-content` box, else the element wrapper, normalized against the\n * SlideCanvas inner container so it is independent of the off-screen scale.\n */\nexport async function measureSlideElementGeometry(\n slide: Slide,\n elementIds: readonly string[],\n options: MeasureOptions = {},\n): Promise<Map<string, MeasuredGeometry>> {\n const result = new Map<string, MeasuredGeometry>();\n if (typeof document === 'undefined') {\n throw new Error('measureSlideElementGeometry requires a browser environment');\n }\n const ids = [...new Set(elementIds)].filter(Boolean);\n if (ids.length === 0) return result;\n\n const width = options.width ?? slide.viewportSize ?? 1280;\n const viewportRatio = slide.viewportRatio ?? DEFAULT_VIEWPORT_RATIO;\n const height = Math.round(width * viewportRatio);\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\n const container = document.createElement('div');\n container.style.cssText = [\n 'position: absolute',\n 'left: -99999px',\n 'top: 0',\n `width: ${width}px`,\n `height: ${height}px`,\n 'pointer-events: none',\n ].join('; ');\n document.body.appendChild(container);\n\n let root: Root | null = null;\n try {\n root = createRoot(container);\n flushSync(() => {\n root!.render(createElement(SlideCanvas, { slide, chrome: false }));\n });\n // Typeset every inline formula now, root by root: the live renderer\n // leaves what its per-pass budget does not cover to idle time, after this\n // capture.\n completeInlineMath(container);\n\n // Let the ResizeObserver-driven fit settle, then settle fonts before we read\n // rects. Auto-height text only reaches its final extent once the real faces\n // load, and `document.fonts.ready` alone is racy — it can resolve before the\n // off-screen render triggers a self-hosted woff2 fetch, leaving a fallback\n // face whose Latin/digit advances differ and shift the measured content box.\n // So force-load every (style, weight, family) actually used first (mirrors\n // `slideToPng`), then await readiness, capped by the settle timeout.\n await nextFrame();\n await nextFrame();\n if (document.fonts && typeof document.fonts.load === 'function') {\n const fontSpecs = new Set<string>();\n container.querySelectorAll<HTMLElement>('*').forEach((el) => {\n if (!el.textContent || !el.textContent.trim()) return;\n const cs = getComputedStyle(el);\n if (!cs.fontFamily) return;\n fontSpecs.add(`${cs.fontStyle} ${cs.fontWeight} 16px ${cs.fontFamily}`);\n });\n await Promise.race([\n Promise.all([...fontSpecs].map((spec) => document.fonts.load(spec).catch(() => undefined))),\n new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)),\n ]);\n }\n if (document.fonts?.ready) {\n await Promise.race([\n document.fonts.ready,\n new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)),\n ]);\n }\n // Let any font-triggered relayout settle (KaTeX re-fits once KaTeX_Size loads,\n // a React state update) before reading rects — two frames to commit.\n await nextFrame();\n await nextFrame();\n\n // The SlideCanvas inner container is the positioned box every element is\n // absolute within; normalizing against it (not the outer offscreen div)\n // makes the geometry independent of the fit scale — exactly what\n // SpotlightOverlay does against its own `inset:0` container.\n const canvasEl = (container.firstElementChild as HTMLElement | null) ?? container;\n const containerRect = canvasEl.getBoundingClientRect();\n if (containerRect.width === 0 || containerRect.height === 0) return result;\n\n for (const id of ids) {\n const el = container.querySelector<HTMLElement>(`#${cssEscape(ELEMENT_ID_PREFIX + id)}`);\n if (!el) continue;\n const contentEl = el.querySelector<HTMLElement>('.element-content');\n const targetEl = contentEl ?? el;\n const r = targetEl.getBoundingClientRect();\n if (r.width === 0 && r.height === 0) continue;\n const x = ((r.left - containerRect.left) / containerRect.width) * 100;\n const y = ((r.top - containerRect.top) / containerRect.height) * 100;\n const w = (r.width / containerRect.width) * 100;\n const h = (r.height / containerRect.height) * 100;\n result.set(id, { x, y, w, h, centerX: x + w / 2, centerY: y + h / 2 });\n }\n } finally {\n if (root) {\n const r = root;\n setTimeout(() => r.unmount(), 0);\n }\n setTimeout(() => container.remove(), 0);\n }\n\n return result;\n}\n\n/** Minimal CSS.escape fallback for element ids used in a selector. */\nfunction cssEscape(value: string): string {\n const g = globalThis as { CSS?: { escape?: (v: string) => string } };\n if (g.CSS?.escape) return g.CSS.escape(value);\n // Escape characters that are not safe in a CSS identifier.\n return value.replace(/[^a-zA-Z0-9_-]/g, (ch) => `\\\\${ch}`);\n}\n"],"names":[],"mappings":";;;;;;;AAsDA;AACA;AACA;AACA;AAEA;AACE;AACF;AAEA;;;;;;;;;AASG;AACI;AAKL;AACA;AACE;;AAEF;AACA;AAAsB;;AAGtB;;AAEA;;AAGA;;;;AAIE;AACA;;AAED;AACD;;AAGA;AACE;;AAEE;AACF;;;;;;;;;;;;;;AAeA;AACE;;;;AAGE;;;AAEA;AACF;;AAEE;AACA;AACD;;AAEH;;;AAGI;AACD;;;;;;;;;;AAWH;AACA;;AAC6D;AAE7D;AACE;AACA;;;AAEA;AACA;;;AAEA;AACA;AACA;AACA;AACA;;;;;;;;;;AAUJ;AACF;AAEA;AACA;;AAEE;;;AAEA;AACF;;"}
1
+ {"version":3,"file":"measure.js","sources":["../../src/snapshot/measure.ts"],"sourcesContent":["'use client';\n\n/**\n * Off-screen element-geometry measurement.\n *\n * The video-export compiler places spotlight/laser/video effects on a slide\n * element's geometry. Its pure fallback ({@link ../geometry}) reads the\n * element's *authored* `left/top/width/height` against a fixed 1000×562.5 base\n * — the element's **outer box**. But the live overlays (and the exported frame\n * PNG) measure the element's `.element-content` box, which differs for\n * auto-sized text (`height:auto`) and its 10px content padding, so a spotlight\n * on the authored box sits offset from the rendered text (issue #867 item 5).\n *\n * This measures the same content box the live `SpotlightOverlay` does: it mounts\n * the slide off-screen at native size (the same 1:1 mount `slideToPng` uses),\n * then for each requested element id reads `.element-content`'s\n * `getBoundingClientRect()` normalized against the canvas container rect → 0–100\n * space. The app feeds the result to the compiler as a `GeometryProbe` so the\n * IR carries rendered geometry; the compile stays pure and falls back to the\n * authored box for anything not measured.\n *\n * App-side / impure: needs a browser (DOM + layout). Mirrors `slideToPng`'s\n * mount lifecycle.\n */\n\nimport { createElement } from 'react';\nimport { flushSync } from 'react-dom';\nimport { createRoot, type Root } from 'react-dom/client';\nimport { SlideCanvas } from '../SlideCanvas';\nimport type { Slide } from '@openmaic/dsl';\nimport { completeInlineMath } from '../utils/inlineMath';\n\n/** Percentage geometry (0–100) — mirrors the compiler's `PercentageGeometry`. */\nexport interface MeasuredGeometry {\n x: number;\n y: number;\n w: number;\n h: number;\n centerX: number;\n centerY: number;\n}\n\nexport interface MeasureOptions {\n /**\n * Off-screen render width in px. Defaults to the slide's native\n * `viewportSize`. Only the *ratio* of element box to container matters for the\n * 0–100 normalization, so the absolute width is not important — but rendering\n * near native size keeps text wrapping (hence auto-height) faithful.\n */\n width?: number;\n /** Settle timeout in ms for `document.fonts.ready`. Default 5000. */\n timeoutMs?: number;\n}\n\nconst DEFAULT_VIEWPORT_RATIO = 0.5625;\nconst DEFAULT_TIMEOUT_MS = 5000;\n/** SlideElement renders each element wrapper as `slide-element-<id>` by default. */\nconst ELEMENT_ID_PREFIX = 'slide-element-';\n\nfunction nextFrame(): Promise<void> {\n return new Promise((resolve) => requestAnimationFrame(() => resolve()));\n}\n\n/**\n * Measure the rendered content-box geometry (0–100) of the given element ids on\n * a slide. Returns a Map keyed by element id; ids that could not be located are\n * absent (the caller falls back to the authored-box calc). Never throws for a\n * missing element — only for a non-browser environment.\n *\n * The measurement matches `SpotlightOverlay`: prefer the element's\n * `.element-content` box, else the element wrapper, normalized against the\n * SlideCanvas inner container so it is independent of the off-screen scale.\n */\nexport async function measureSlideElementGeometry(\n slide: Slide,\n elementIds: readonly string[],\n options: MeasureOptions = {},\n): Promise<Map<string, MeasuredGeometry>> {\n const result = new Map<string, MeasuredGeometry>();\n if (typeof document === 'undefined') {\n throw new Error('measureSlideElementGeometry requires a browser environment');\n }\n const ids = [...new Set(elementIds)].filter(Boolean);\n if (ids.length === 0) return result;\n\n const width = options.width ?? slide.viewportSize ?? 1280;\n const viewportRatio = slide.viewportRatio ?? DEFAULT_VIEWPORT_RATIO;\n const height = Math.round(width * viewportRatio);\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\n const container = document.createElement('div');\n container.style.cssText = [\n 'position: absolute',\n 'left: -99999px',\n 'top: 0',\n `width: ${width}px`,\n `height: ${height}px`,\n 'pointer-events: none',\n ].join('; ');\n document.body.appendChild(container);\n\n let root: Root | null = null;\n try {\n root = createRoot(container);\n flushSync(() => {\n root!.render(createElement(SlideCanvas, { slide, chrome: false }));\n });\n // Typeset every inline formula now, root by root: the live renderer\n // leaves what the shared live budget does not cover to idle time, after this\n // capture.\n completeInlineMath(container);\n\n // Let the ResizeObserver-driven fit settle, then settle fonts before we read\n // rects. Auto-height text only reaches its final extent once the real faces\n // load, and `document.fonts.ready` alone is racy — it can resolve before the\n // off-screen render triggers a self-hosted woff2 fetch, leaving a fallback\n // face whose Latin/digit advances differ and shift the measured content box.\n // So force-load every (style, weight, family) actually used first (mirrors\n // `slideToPng`), then await readiness, capped by the settle timeout.\n await nextFrame();\n await nextFrame();\n if (document.fonts && typeof document.fonts.load === 'function') {\n const fontSpecs = new Set<string>();\n container.querySelectorAll<HTMLElement>('*').forEach((el) => {\n if (!el.textContent || !el.textContent.trim()) return;\n const cs = getComputedStyle(el);\n if (!cs.fontFamily) return;\n fontSpecs.add(`${cs.fontStyle} ${cs.fontWeight} 16px ${cs.fontFamily}`);\n });\n await Promise.race([\n Promise.all([...fontSpecs].map((spec) => document.fonts.load(spec).catch(() => undefined))),\n new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)),\n ]);\n }\n if (document.fonts?.ready) {\n await Promise.race([\n document.fonts.ready,\n new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)),\n ]);\n }\n // Let any font-triggered relayout settle (KaTeX re-fits once KaTeX_Size loads,\n // a React state update) before reading rects — two frames to commit.\n await nextFrame();\n await nextFrame();\n\n // The SlideCanvas inner container is the positioned box every element is\n // absolute within; normalizing against it (not the outer offscreen div)\n // makes the geometry independent of the fit scale — exactly what\n // SpotlightOverlay does against its own `inset:0` container.\n const canvasEl = (container.firstElementChild as HTMLElement | null) ?? container;\n const containerRect = canvasEl.getBoundingClientRect();\n if (containerRect.width === 0 || containerRect.height === 0) return result;\n\n for (const id of ids) {\n const el = container.querySelector<HTMLElement>(`#${cssEscape(ELEMENT_ID_PREFIX + id)}`);\n if (!el) continue;\n const contentEl = el.querySelector<HTMLElement>('.element-content');\n const targetEl = contentEl ?? el;\n const r = targetEl.getBoundingClientRect();\n if (r.width === 0 && r.height === 0) continue;\n const x = ((r.left - containerRect.left) / containerRect.width) * 100;\n const y = ((r.top - containerRect.top) / containerRect.height) * 100;\n const w = (r.width / containerRect.width) * 100;\n const h = (r.height / containerRect.height) * 100;\n result.set(id, { x, y, w, h, centerX: x + w / 2, centerY: y + h / 2 });\n }\n } finally {\n if (root) {\n const r = root;\n setTimeout(() => r.unmount(), 0);\n }\n setTimeout(() => container.remove(), 0);\n }\n\n return result;\n}\n\n/** Minimal CSS.escape fallback for element ids used in a selector. */\nfunction cssEscape(value: string): string {\n const g = globalThis as { CSS?: { escape?: (v: string) => string } };\n if (g.CSS?.escape) return g.CSS.escape(value);\n // Escape characters that are not safe in a CSS identifier.\n return value.replace(/[^a-zA-Z0-9_-]/g, (ch) => `\\\\${ch}`);\n}\n"],"names":[],"mappings":";;;;;;;AAsDA;AACA;AACA;AACA;AAEA;AACE;AACF;AAEA;;;;;;;;;AASG;AACI;AAKL;AACA;AACE;;AAEF;AACA;AAAsB;;AAGtB;;AAEA;;AAGA;;;;AAIE;AACA;;AAED;AACD;;AAGA;AACE;;AAEE;AACF;;;;;;;;;;;;;;AAeA;AACE;;;;AAGE;;;AAEA;AACF;;AAEE;AACA;AACD;;AAEH;;;AAGI;AACD;;;;;;;;;;AAWH;AACA;;AAC6D;AAE7D;AACE;AACA;;;AAEA;AACA;;;AAEA;AACA;AACA;AACA;AACA;;;;;;;;;;AAUJ;AACF;AAEA;AACA;;AAEE;;;AAEA;AACF;;"}
@@ -15,11 +15,9 @@ export declare const INLINE_MATH_ROOT_ATTRIBUTE = "data-inline-math-root";
15
15
  /** Longest source typeset; longer sources are shown as plain LaTeX text. */
16
16
  export declare const MAX_INLINE_MATH_SOURCE = 2000;
17
17
  /**
18
- * Typesetting budget per pass over one prose root, counting only formulas not
19
- * already in the typeset cache. Within it formulas are typeset before paint;
20
- * the rest are typeset in idle time, a chunk of the same size at a time, so a
21
- * slide packed with large formulas cannot freeze the page. Ordinary prose (a
22
- * text box with a few dozen short formulas) fits in one pass.
18
+ * Bound uncached typesetting work in a batch. Live prose roots share a batch;
19
+ * standalone renderInlineMath calls get their own. Ordinary slides fit before
20
+ * paint; mixed/dense slides may defer even short formulas to idle time.
23
21
  */
24
22
  export declare const INLINE_MATH_SYNC_SOURCE_BUDGET = 4000;
25
23
  export declare const INLINE_MATH_SYNC_FORMULA_BUDGET = 100;
@@ -64,14 +62,21 @@ export declare function useInnerHtml(html: string): {
64
62
  export declare function useInnerHtmlGrid(cells: readonly (readonly string[])[]): {
65
63
  __html: string;
66
64
  }[][];
65
+ type MathPriority = 'normal' | 'background';
66
+ export declare const InlineMathPriorityContext: import("react").Context<MathPriority>;
67
67
  /**
68
68
  * Typeset the inline formulas of prose injected into `ref` as `html`. Runs
69
69
  * after every commit, before paint: React may rewrite the injected markup on
70
70
  * any re-render (not only when `html` changes), which would put the stored
71
71
  * source spans back. Formulas already typeset are skipped and cached renders
72
72
  * are cloned, so a commit that left the markup alone costs one query. What the
73
- * budget leaves over is typeset in idle time; the next commit, an unmount or
74
- * new content cancels that and starts over from the markup then in place.
73
+ * shared budget leaves over is typeset in idle time, using the current markup.
74
+ * Pending roots stay in that queue on unchanged commits (including when an
75
+ * external caller rewrites the HTML). New content can use the current frame's
76
+ * synchronous allowance. Unmounting or replacing a root removes its queued work.
77
+ * Foreground roots run in layout effects; background roots use the remaining
78
+ * allowance in a microtask, following the nearest InlineMathPriorityContext.
75
79
  * Never updates React state.
76
80
  */
77
81
  export declare function useInlineMath(ref: RefObject<Element | null>, html: string): void;
82
+ export {};
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { useMemo, useLayoutEffect } from 'react';
2
+ import { createContext, useMemo, useContext, useRef, useLayoutEffect } from 'react';
3
3
  import katex from 'katex';
4
4
  import { safeKatexOptions } from '@openmaic/dsl';
5
5
 
@@ -19,14 +19,19 @@ const INLINE_MATH_ROOT_ATTRIBUTE = 'data-inline-math-root';
19
19
  /** Longest source typeset; longer sources are shown as plain LaTeX text. */
20
20
  const MAX_INLINE_MATH_SOURCE = 2_000;
21
21
  /**
22
- * Typesetting budget per pass over one prose root, counting only formulas not
23
- * already in the typeset cache. Within it formulas are typeset before paint;
24
- * the rest are typeset in idle time, a chunk of the same size at a time, so a
25
- * slide packed with large formulas cannot freeze the page. Ordinary prose (a
26
- * text box with a few dozen short formulas) fits in one pass.
22
+ * Bound uncached typesetting work in a batch. Live prose roots share a batch;
23
+ * standalone renderInlineMath calls get their own. Ordinary slides fit before
24
+ * paint; mixed/dense slides may defer even short formulas to idle time.
27
25
  */
28
26
  const INLINE_MATH_SYNC_SOURCE_BUDGET = 4_000;
29
27
  const INLINE_MATH_SYNC_FORMULA_BUDGET = 100;
28
+ /**
29
+ * Also bound inserted markup, including cache hits: short matrix sources can
30
+ * expand to thousands of nodes whose style/layout cost comes after typesetting.
31
+ * Uses the serialized size already recorded by the cache, not a DOM traversal.
32
+ * Leave room for dense ordinary slides (e.g. 32 integrals/sums across text boxes).
33
+ */
34
+ const INLINE_MATH_SYNC_MARKUP_BUDGET = 256_000;
30
35
  /**
31
36
  * Hard cap per prose root, counting every formula in document order: past it,
32
37
  * formulas are shown as their LaTeX text and never typeset.
@@ -45,6 +50,10 @@ const TYPESET_CACHE_MAX_MARKUP = 2_000_000;
45
50
  const TYPESET_CACHE_MAX_ENTRY = 64_000;
46
51
  const typesetCache = new Map();
47
52
  let typesetCacheSize = 0;
53
+ // Keep a rejected render with its source node until it can be inserted. Unlike
54
+ // the shared cache, this also covers large entries and cannot be overwritten by
55
+ // another root. Replacing/removing the prose releases its pending renders.
56
+ const deferredTypesets = new WeakMap();
48
57
  /** Typeset one formula, or `null` to keep its source as text. */
49
58
  function typesetUncached(doc, latex) {
50
59
  if (!latex.trim() || latex.length > MAX_INLINE_MATH_SOURCE)
@@ -91,11 +100,7 @@ function typeset(doc, latex) {
91
100
  }
92
101
  }
93
102
  }
94
- if (!entry.formula)
95
- return null;
96
- return entry.formula.ownerDocument === doc
97
- ? entry.formula.cloneNode(true)
98
- : doc.importNode(entry.formula, true);
103
+ return entry;
99
104
  }
100
105
  /** Formulas shown as text because they fell past a root's hard cap. */
101
106
  const capped = new WeakSet();
@@ -121,11 +126,15 @@ function showCapped(element, latex) {
121
126
  * Returns `true` when formulas were left for a later pass by the budget.
122
127
  */
123
128
  function renderInlineMath(root, options = {}) {
129
+ return renderPass(root, options, newBudget());
130
+ }
131
+ function newBudget() {
132
+ return { source: 0, formulas: 0, markup: 0, full: false };
133
+ }
134
+ function renderPass(root, options, budget) {
124
135
  const doc = root.ownerDocument ?? root;
125
136
  let rootSource = 0;
126
137
  let rootFormulas = 0;
127
- let passSource = 0;
128
- let passFormulas = 0;
129
138
  let pending = false;
130
139
  for (const element of root.querySelectorAll(`span[${INLINE_MATH_ATTRIBUTE}]`)) {
131
140
  // Inside a formula replaced earlier in this pass.
@@ -142,23 +151,47 @@ function renderInlineMath(root, options = {}) {
142
151
  }
143
152
  if (handled.has(element) && !capped.has(element))
144
153
  continue;
145
- if (!typesetCache.has(latex)) {
154
+ const deferred = deferredTypesets.get(element);
155
+ const prepared = deferred?.latex === latex ? deferred.entry : undefined;
156
+ const cached = prepared ?? typesetCache.get(latex);
157
+ // Preserve source order within a root, but let a later root use cached
158
+ // formulas that fit in the space left by a rejected large formula.
159
+ if (!options.complete && (pending || (budget.full && !cached))) {
160
+ pending = true;
161
+ continue;
162
+ }
163
+ if (!cached) {
146
164
  if (!options.complete &&
147
- passFormulas > 0 &&
148
- (passSource + latex.length > INLINE_MATH_SYNC_SOURCE_BUDGET ||
149
- passFormulas >= INLINE_MATH_SYNC_FORMULA_BUDGET)) {
165
+ budget.formulas > 0 &&
166
+ (budget.source + latex.length > INLINE_MATH_SYNC_SOURCE_BUDGET ||
167
+ budget.formulas >= INLINE_MATH_SYNC_FORMULA_BUDGET)) {
168
+ budget.full = true;
150
169
  pending = true;
151
170
  continue;
152
171
  }
153
- passSource += latex.length;
154
- passFormulas += 1;
172
+ budget.source += latex.length;
173
+ budget.formulas += 1;
155
174
  }
156
- const formula = typeset(doc, latex);
157
- if (!formula) {
175
+ const entry = prepared ?? typeset(doc, latex);
176
+ if (!entry.formula) {
158
177
  showSource(element, latex);
159
178
  continue;
160
179
  }
180
+ // Always allow one formula to make progress, even if it exceeds a batch.
181
+ if (!options.complete &&
182
+ budget.markup > 0 &&
183
+ budget.markup + entry.size > INLINE_MATH_SYNC_MARKUP_BUDGET) {
184
+ budget.full = true;
185
+ pending = true;
186
+ deferredTypesets.set(element, { latex, entry });
187
+ continue;
188
+ }
189
+ budget.markup += entry.size;
190
+ const formula = entry.formula.ownerDocument === doc
191
+ ? entry.formula.cloneNode(true)
192
+ : doc.importNode(entry.formula, true);
161
193
  handled.add(formula);
194
+ deferredTypesets.delete(element);
162
195
  element.replaceWith(formula);
163
196
  }
164
197
  return pending;
@@ -210,38 +243,178 @@ function whenIdle(run) {
210
243
  const handle = schedule.call(scope, run, 16);
211
244
  return { cancel: () => clear.call(scope, handle) };
212
245
  }
213
- /** Typeset what a pass left over, one budget-sized chunk per idle period. */
214
- function finishWhenIdle(root) {
215
- let handle = null;
216
- const step = () => {
217
- handle = null;
218
- if (!root.isConnected)
246
+ const InlineMathPriorityContext = createContext('normal');
247
+ /**
248
+ * Own the live queues and frame allowances. Background roots share a copy of
249
+ * the remaining foreground allowance, so an earlier thumbnail commit cannot
250
+ * spend the next foreground commit's budget. Neither is renewed on removal.
251
+ */
252
+ function createLiveMath() {
253
+ // Idle work rotates roots within each priority, with foreground canvases first.
254
+ const queuedRoots = new Map();
255
+ // Only newly admitted background roots may spend the remaining frame allowance.
256
+ const prePaintCandidates = new Set();
257
+ let frameBudget = null;
258
+ let backgroundBudget = null;
259
+ let cancelFrameReset = null;
260
+ let idleJob = null;
261
+ let prePaintScheduled = false;
262
+ function resetFrameBudget() {
263
+ cancelFrameReset?.();
264
+ cancelFrameReset = null;
265
+ frameBudget = null;
266
+ backgroundBudget = null;
267
+ }
268
+ function frameAllowance() {
269
+ if (!frameBudget) {
270
+ const budget = (frameBudget = newBudget());
271
+ const reset = () => {
272
+ if (frameBudget === budget) {
273
+ frameBudget = null;
274
+ backgroundBudget = null;
275
+ cancelFrameReset = null;
276
+ }
277
+ };
278
+ if (typeof requestAnimationFrame === 'function' &&
279
+ typeof cancelAnimationFrame === 'function') {
280
+ const cancel = cancelAnimationFrame;
281
+ const handle = requestAnimationFrame(reset);
282
+ cancelFrameReset = () => cancel(handle);
283
+ }
284
+ else {
285
+ const cancel = clearTimeout;
286
+ const handle = setTimeout(reset, 16);
287
+ cancelFrameReset = () => cancel(handle);
288
+ }
289
+ }
290
+ return frameBudget;
291
+ }
292
+ function renderIdleRoots(priority, budget) {
293
+ for (const [root, queuedPriority] of [...queuedRoots]) {
294
+ if (queuedPriority !== priority)
295
+ continue;
296
+ queuedRoots.delete(root);
297
+ if (root.isConnected && renderPass(root, {}, budget))
298
+ queuedRoots.set(root, priority);
299
+ if (budget.full)
300
+ break;
301
+ }
302
+ }
303
+ function scheduleIdle() {
304
+ if (!queuedRoots.size) {
305
+ idleJob?.cancel?.();
306
+ idleJob = null;
307
+ return;
308
+ }
309
+ if (idleJob)
310
+ return;
311
+ const job = {};
312
+ idleJob = job;
313
+ job.cancel = whenIdle(() => {
314
+ // A cancelled callback must not drain work queued by a later mount.
315
+ if (idleJob !== job)
316
+ return;
317
+ idleJob = null;
318
+ resetFrameBudget();
319
+ const budget = newBudget();
320
+ for (const priority of ['normal', 'background']) {
321
+ renderIdleRoots(priority, budget);
322
+ if (budget.full)
323
+ break;
324
+ }
325
+ scheduleIdle();
326
+ }).cancel;
327
+ }
328
+ function flushPrePaint() {
329
+ prePaintScheduled = false;
330
+ if (!prePaintCandidates.size)
219
331
  return;
220
- if (renderInlineMath(root))
221
- handle = whenIdle(step);
332
+ const budget = (backgroundBudget ??= { ...frameAllowance() });
333
+ // Visit every newly admitted root: cached formulas may fit after an earlier
334
+ // root fills the allowance. Older queued roots remain in idle time.
335
+ for (const root of prePaintCandidates) {
336
+ queuedRoots.delete(root);
337
+ if (root.isConnected && renderPass(root, {}, budget))
338
+ queuedRoots.set(root, 'background');
339
+ }
340
+ prePaintCandidates.clear();
341
+ scheduleIdle();
342
+ }
343
+ return {
344
+ isQueued: (root) => queuedRoots.has(root),
345
+ render(root, priority) {
346
+ if (priority === 'background') {
347
+ prePaintCandidates.add(root);
348
+ if (!prePaintScheduled) {
349
+ prePaintScheduled = true;
350
+ queueMicrotask(flushPrePaint);
351
+ }
352
+ return;
353
+ }
354
+ prePaintCandidates.delete(root);
355
+ if (renderPass(root, {}, frameAllowance()))
356
+ queuedRoots.set(root, priority);
357
+ else
358
+ queuedRoots.delete(root);
359
+ scheduleIdle();
360
+ },
361
+ remove(root) {
362
+ prePaintCandidates.delete(root);
363
+ queuedRoots.delete(root);
364
+ if (!queuedRoots.size) {
365
+ idleJob?.cancel?.();
366
+ idleJob = null;
367
+ }
368
+ },
222
369
  };
223
- handle = whenIdle(step);
224
- return () => handle?.cancel();
225
370
  }
371
+ const liveMath = createLiveMath();
226
372
  /**
227
373
  * Typeset the inline formulas of prose injected into `ref` as `html`. Runs
228
374
  * after every commit, before paint: React may rewrite the injected markup on
229
375
  * any re-render (not only when `html` changes), which would put the stored
230
376
  * source spans back. Formulas already typeset are skipped and cached renders
231
377
  * are cloned, so a commit that left the markup alone costs one query. What the
232
- * budget leaves over is typeset in idle time; the next commit, an unmount or
233
- * new content cancels that and starts over from the markup then in place.
378
+ * shared budget leaves over is typeset in idle time, using the current markup.
379
+ * Pending roots stay in that queue on unchanged commits (including when an
380
+ * external caller rewrites the HTML). New content can use the current frame's
381
+ * synchronous allowance. Unmounting or replacing a root removes its queued work.
382
+ * Foreground roots run in layout effects; background roots use the remaining
383
+ * allowance in a microtask, following the nearest InlineMathPriorityContext.
234
384
  * Never updates React state.
235
385
  */
236
386
  function useInlineMath(ref, html) {
387
+ const priority = useContext(InlineMathPriorityContext);
388
+ const previous = useRef(null);
237
389
  useLayoutEffect(() => {
238
390
  const root = ref.current;
239
- if (!root || !html.includes(INLINE_MATH_ATTRIBUTE))
391
+ const before = previous.current;
392
+ if (before?.root && before.root !== root)
393
+ liveMath.remove(before.root);
394
+ previous.current = { root, html, priority };
395
+ if (!root)
240
396
  return;
241
- if (renderInlineMath(root))
242
- return finishWhenIdle(root);
397
+ if (!html.includes(INLINE_MATH_ATTRIBUTE)) {
398
+ liveMath.remove(root);
399
+ return;
400
+ }
401
+ if (before?.root === root &&
402
+ before.html === html &&
403
+ before.priority === priority &&
404
+ liveMath.isQueued(root))
405
+ return;
406
+ liveMath.render(root, priority);
243
407
  });
408
+ // Only clean up on unmount: per-commit removal would discard pending queue
409
+ // membership and let unchanged rerenders reenter the pre-paint path.
410
+ useLayoutEffect(() => {
411
+ return () => {
412
+ if (previous.current?.root)
413
+ liveMath.remove(previous.current.root);
414
+ previous.current = null;
415
+ };
416
+ }, []);
244
417
  }
245
418
 
246
- export { INLINE_MATH_ATTRIBUTE, INLINE_MATH_MAX_ROOT_FORMULAS, INLINE_MATH_MAX_ROOT_SOURCE, INLINE_MATH_ROOT_ATTRIBUTE, INLINE_MATH_SYNC_FORMULA_BUDGET, INLINE_MATH_SYNC_SOURCE_BUDGET, MAX_INLINE_MATH_SOURCE, completeInlineMath, renderInlineMath, useInlineMath, useInnerHtml, useInnerHtmlGrid };
419
+ export { INLINE_MATH_ATTRIBUTE, INLINE_MATH_MAX_ROOT_FORMULAS, INLINE_MATH_MAX_ROOT_SOURCE, INLINE_MATH_ROOT_ATTRIBUTE, INLINE_MATH_SYNC_FORMULA_BUDGET, INLINE_MATH_SYNC_SOURCE_BUDGET, InlineMathPriorityContext, MAX_INLINE_MATH_SOURCE, completeInlineMath, renderInlineMath, useInlineMath, useInnerHtml, useInnerHtmlGrid };
247
420
  //# sourceMappingURL=inlineMath.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"inlineMath.js","sources":["../../src/utils/inlineMath.ts"],"sourcesContent":["'use client';\n\nimport { useLayoutEffect, useMemo, 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 * Typesetting budget per pass over one prose root, counting only formulas not\n * already in the typeset cache. Within it formulas are typeset before paint;\n * the rest are typeset in idle time, a chunk of the same size at a time, so a\n * slide packed with large formulas cannot freeze the page. Ordinary prose (a\n * text box with a few dozen short formulas) fits in one pass.\n */\nexport const INLINE_MATH_SYNC_SOURCE_BUDGET = 4_000;\nexport const INLINE_MATH_SYNC_FORMULA_BUDGET = 100;\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;\nconst typesetCache = new Map<string, { readonly formula: Element | null; readonly size: number }>();\nlet typesetCacheSize = 0;\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): Element | null {\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 if (!entry.formula) return null;\n return entry.formula.ownerDocument === doc\n ? (entry.formula.cloneNode(true) as Element)\n : (doc.importNode(entry.formula, true) as Element);\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 const doc = (root as Node).ownerDocument ?? (root as Document);\n let rootSource = 0;\n let rootFormulas = 0;\n let passSource = 0;\n let passFormulas = 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 if (!typesetCache.has(latex)) {\n if (\n !options.complete &&\n passFormulas > 0 &&\n (passSource + latex.length > INLINE_MATH_SYNC_SOURCE_BUDGET ||\n passFormulas >= INLINE_MATH_SYNC_FORMULA_BUDGET)\n ) {\n pending = true;\n continue;\n }\n passSource += latex.length;\n passFormulas += 1;\n }\n const formula = typeset(doc, latex);\n if (!formula) {\n showSource(element, latex);\n continue;\n }\n handled.add(formula);\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\n/** Typeset what a pass left over, one budget-sized chunk per idle period. */\nfunction finishWhenIdle(root: Element): () => void {\n let handle: IdleHandle | null = null;\n const step = () => {\n handle = null;\n if (!root.isConnected) return;\n if (renderInlineMath(root)) handle = whenIdle(step);\n };\n handle = whenIdle(step);\n return () => handle?.cancel();\n}\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 * budget leaves over is typeset in idle time; the next commit, an unmount or\n * new content cancels that and starts over from the markup then in place.\n * Never updates React state.\n */\nexport function useInlineMath(ref: RefObject<Element | null>, html: string): void {\n useLayoutEffect(() => {\n const root = ref.current;\n if (!root || !html.includes(INLINE_MATH_ATTRIBUTE)) return;\n if (renderInlineMath(root)) return finishWhenIdle(root);\n });\n}\n"],"names":[],"mappings":";;;;;AAMA;;;;;AAKG;AACI;AAEP;;;;AAIG;AACI;AAEP;AACO;AAEP;;;;;;AAMG;AACI;AACA;AAEP;;;AAGG;AACI;AACA;AAEP;AACA;AAEA;;;;;AAKG;AACH;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;;;;;AAIc;AACpB;;;AAGF;AAWA;AACA;AAEA;AACE;AACA;AACF;AAEA;AACA;AACE;;AACA;AACA;AACA;AACA;AACA;AACA;AACF;AAEA;;;;;AAKG;;AAED;;;;;;AAMA;;AAEE;;;AAEA;;;;;AAKE;;;AAGF;;;;AAII;AACA;AACE;;;;AAKJ;;;;;AAKA;;;AAGF;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;AAEA;AACA;;;;;;;AAKgC;AAC9B;AACA;AACA;AACF;AAEA;;;;;;;;;AASG;AACG;;AAEF;;;;AAE4B;AAC9B;AACF;;"}
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;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openmaic/renderer",
3
- "version": "0.1.14",
3
+ "version": "0.1.16",
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,7 +79,8 @@
79
79
  "lucide-react": "^0.562.0",
80
80
  "tailwind-merge": "^3.4.0",
81
81
  "tinycolor2": "^1.6.0",
82
- "@openmaic/dsl": "^0.11.3"
82
+ "@openmaic/dsl": "^0.12.0",
83
+ "@openmaic/geometry": "^0.1.0"
83
84
  },
84
85
  "devDependencies": {
85
86
  "@rollup/plugin-commonjs": "^28.0.1",