@openmaic/renderer 0.1.6 → 0.1.7

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.
@@ -1,25 +1,16 @@
1
1
  "use client";
2
2
  import { jsx } from 'react/jsx-runtime';
3
- import { useRef, useMemo, useEffect } from 'react';
3
+ import { useRef, useState, useMemo, useCallback, useEffect } from 'react';
4
4
  import tinycolor from 'tinycolor2';
5
5
  import { getChartOption } from './chartOption.js';
6
- import * as echarts from 'echarts/core';
7
- import { BarChart, LineChart, PieChart, ScatterChart, RadarChart } from 'echarts/charts';
8
- import { LegendComponent } from 'echarts/components';
9
- import { SVGRenderer } from 'echarts/renderers';
6
+ import { loadChartRuntime } from './chartRuntime.js';
10
7
 
11
- echarts.use([
12
- BarChart,
13
- LineChart,
14
- PieChart,
15
- ScatterChart,
16
- RadarChart,
17
- LegendComponent,
18
- SVGRenderer,
19
- ]);
20
8
  function Chart({ width: _width, height: _height, type, data, themeColors: rawThemeColors, textColor, lineColor, options, }) {
21
9
  const chartRef = useRef(null);
22
10
  const chartInstance = useRef(null);
11
+ const resizeObserverRef = useRef(null);
12
+ const updateOptionRef = useRef(() => undefined);
13
+ const [chartState, setChartState] = useState('loading');
23
14
  const themeColors = useMemo(() => {
24
15
  let colors = [];
25
16
  if (rawThemeColors.length >= 10) {
@@ -39,44 +30,58 @@ function Chart({ width: _width, height: _height, type, data, themeColors: rawThe
39
30
  }
40
31
  return colors;
41
32
  }, [rawThemeColors]);
42
- const updateOption = useMemo(() => {
43
- return () => {
44
- if (!chartInstance.current)
45
- return;
46
- const option = getChartOption({
47
- type,
48
- data,
49
- themeColors,
50
- textColor,
51
- lineColor,
52
- lineSmooth: options?.lineSmooth || false,
53
- stack: options?.stack || false,
54
- });
55
- if (option) {
56
- chartInstance.current.setOption(option, true);
57
- }
58
- };
33
+ const updateOption = useCallback(() => {
34
+ if (!chartInstance.current)
35
+ return;
36
+ const option = getChartOption({
37
+ type,
38
+ data,
39
+ themeColors,
40
+ textColor,
41
+ lineColor,
42
+ lineSmooth: options?.lineSmooth || false,
43
+ stack: options?.stack || false,
44
+ });
45
+ if (option) {
46
+ chartInstance.current.setOption(option, true);
47
+ }
59
48
  }, [type, data, themeColors, textColor, lineColor, options]);
60
49
  useEffect(() => {
61
- if (!chartRef.current)
62
- return;
63
- chartInstance.current = echarts.init(chartRef.current, null, { renderer: 'svg' });
64
- updateOption();
65
- const resizeObserver = new ResizeObserver(() => {
66
- chartInstance.current?.resize();
50
+ updateOptionRef.current = updateOption;
51
+ }, [updateOption]);
52
+ useEffect(() => {
53
+ let mounted = true;
54
+ void loadChartRuntime()
55
+ .then((echarts) => {
56
+ if (!mounted || !chartRef.current)
57
+ return;
58
+ chartInstance.current = echarts.init(chartRef.current, null, { renderer: 'svg' });
59
+ setChartState('ready');
60
+ updateOptionRef.current();
61
+ const resizeObserver = new ResizeObserver(() => {
62
+ chartInstance.current?.resize();
63
+ });
64
+ resizeObserver.observe(chartRef.current);
65
+ resizeObserverRef.current = resizeObserver;
66
+ })
67
+ .catch(() => {
68
+ if (mounted)
69
+ setChartState('error');
67
70
  });
68
- resizeObserver.observe(chartRef.current);
69
71
  return () => {
70
- resizeObserver.disconnect();
72
+ mounted = false;
73
+ resizeObserverRef.current?.disconnect();
74
+ resizeObserverRef.current = null;
71
75
  chartInstance.current?.dispose();
72
76
  chartInstance.current = null;
73
77
  };
74
- // eslint-disable-next-line react-hooks/exhaustive-deps -- Init-only effect
78
+ // The runtime and ECharts instance are initialized once per mounted chart.
79
+ // Option changes are applied by the effect below without re-initializing.
75
80
  }, []);
76
81
  useEffect(() => {
77
82
  updateOption();
78
83
  }, [updateOption]);
79
- return jsx("div", { ref: chartRef, className: "chart", style: { width: '100%', height: '100%' } });
84
+ return (jsx("div", { ref: chartRef, className: "chart", "data-chart-state": chartState, "aria-busy": chartState === 'loading', style: { width: '100%', height: '100%' } }));
80
85
  }
81
86
 
82
87
  export { Chart };
@@ -1 +1 @@
1
- {"version":3,"file":"Chart.js","sources":["../../../src/elements/chart/Chart.tsx"],"sourcesContent":["'use client';\n\nimport { useEffect, useRef, useMemo } from 'react';\nimport tinycolor from 'tinycolor2';\nimport type { ChartData, ChartOptions, ChartType } from '@openmaic/dsl';\nimport { getChartOption } from './chartOption';\n\nimport * as echarts from 'echarts/core';\nimport { BarChart, LineChart, PieChart, ScatterChart, RadarChart } from 'echarts/charts';\nimport { LegendComponent } from 'echarts/components';\nimport { SVGRenderer } from 'echarts/renderers';\n\necharts.use([\n BarChart,\n LineChart,\n PieChart,\n ScatterChart,\n RadarChart,\n LegendComponent,\n SVGRenderer,\n]);\n\ninterface ChartProps {\n width: number;\n height: number;\n type: ChartType;\n data: ChartData;\n themeColors: string[];\n textColor?: string;\n lineColor?: string;\n options?: ChartOptions;\n}\n\nexport function Chart({\n width: _width,\n height: _height,\n type,\n data,\n themeColors: rawThemeColors,\n textColor,\n lineColor,\n options,\n}: ChartProps) {\n const chartRef = useRef<HTMLDivElement>(null);\n const chartInstance = useRef<echarts.ECharts | null>(null);\n\n const themeColors = useMemo(() => {\n let colors: string[] = [];\n if (rawThemeColors.length >= 10) {\n colors = rawThemeColors;\n } else if (rawThemeColors.length === 1) {\n colors = tinycolor(rawThemeColors[0])\n .analogous(10)\n .map((color) => color.toRgbString());\n } else {\n const len = rawThemeColors.length;\n const supplement = tinycolor(rawThemeColors[len - 1])\n .analogous(10 + 1 - len)\n .map((color) => color.toRgbString());\n colors = [...rawThemeColors.slice(0, len - 1), ...supplement];\n }\n return colors;\n }, [rawThemeColors]);\n\n const updateOption = useMemo(() => {\n return () => {\n if (!chartInstance.current) return;\n\n const option = getChartOption({\n type,\n data,\n themeColors,\n textColor,\n lineColor,\n lineSmooth: options?.lineSmooth || false,\n stack: options?.stack || false,\n });\n\n if (option) {\n chartInstance.current.setOption(option, true);\n }\n };\n }, [type, data, themeColors, textColor, lineColor, options]);\n\n useEffect(() => {\n if (!chartRef.current) return;\n\n chartInstance.current = echarts.init(chartRef.current, null, { renderer: 'svg' });\n updateOption();\n\n const resizeObserver = new ResizeObserver(() => {\n chartInstance.current?.resize();\n });\n resizeObserver.observe(chartRef.current);\n\n return () => {\n resizeObserver.disconnect();\n chartInstance.current?.dispose();\n chartInstance.current = null;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps -- Init-only effect\n }, []);\n\n useEffect(() => {\n updateOption();\n }, [updateOption]);\n\n return <div ref={chartRef} className=\"chart\" style={{ width: '100%', height: '100%' }} />;\n}\n"],"names":[],"mappings":";;;;;;;;;;AAYA;;;;;;;;AAQC;AAaK;AAUJ;AACA;AAEA;;AAEE;;;AAEO;AACL;;;;;AAIA;;AAEG;;AAEH;;AAEF;AACF;AAEA;AACE;;;;;;;;;AASI;AACA;AACD;;;;AAKH;AACF;;;;AAKE;AACA;AAEA;AACE;AACF;AACA;AAEA;;AAEE;AACA;AACF;;;;AAKA;AACF;;AAGF;;"}
1
+ {"version":3,"file":"Chart.js","sources":["../../../src/elements/chart/Chart.tsx"],"sourcesContent":["'use client';\n\nimport { useEffect, useRef, useMemo, useState, useCallback } from 'react';\nimport tinycolor from 'tinycolor2';\nimport type { ChartData, ChartOptions, ChartType } from '@openmaic/dsl';\nimport { getChartOption } from './chartOption';\nimport { loadChartRuntime } from './chartRuntime';\n\ninterface ChartProps {\n width: number;\n height: number;\n type: ChartType;\n data: ChartData;\n themeColors: string[];\n textColor?: string;\n lineColor?: string;\n options?: ChartOptions;\n}\n\nexport function Chart({\n width: _width,\n height: _height,\n type,\n data,\n themeColors: rawThemeColors,\n textColor,\n lineColor,\n options,\n}: ChartProps) {\n const chartRef = useRef<HTMLDivElement>(null);\n const chartInstance = useRef<import('echarts/core').ECharts | null>(null);\n const resizeObserverRef = useRef<ResizeObserver | null>(null);\n const updateOptionRef = useRef<() => void>(() => undefined);\n const [chartState, setChartState] = useState<'loading' | 'ready' | 'error'>('loading');\n\n const themeColors = useMemo(() => {\n let colors: string[] = [];\n if (rawThemeColors.length >= 10) {\n colors = rawThemeColors;\n } else if (rawThemeColors.length === 1) {\n colors = tinycolor(rawThemeColors[0])\n .analogous(10)\n .map((color) => color.toRgbString());\n } else {\n const len = rawThemeColors.length;\n const supplement = tinycolor(rawThemeColors[len - 1])\n .analogous(10 + 1 - len)\n .map((color) => color.toRgbString());\n colors = [...rawThemeColors.slice(0, len - 1), ...supplement];\n }\n return colors;\n }, [rawThemeColors]);\n\n const updateOption = useCallback(() => {\n if (!chartInstance.current) return;\n\n const option = getChartOption({\n type,\n data,\n themeColors,\n textColor,\n lineColor,\n lineSmooth: options?.lineSmooth || false,\n stack: options?.stack || false,\n });\n\n if (option) {\n chartInstance.current.setOption(option, true);\n }\n }, [type, data, themeColors, textColor, lineColor, options]);\n\n useEffect(() => {\n updateOptionRef.current = updateOption;\n }, [updateOption]);\n\n useEffect(() => {\n let mounted = true;\n\n void loadChartRuntime()\n .then((echarts) => {\n if (!mounted || !chartRef.current) return;\n\n chartInstance.current = echarts.init(chartRef.current, null, { renderer: 'svg' });\n setChartState('ready');\n updateOptionRef.current();\n\n const resizeObserver = new ResizeObserver(() => {\n chartInstance.current?.resize();\n });\n resizeObserver.observe(chartRef.current);\n resizeObserverRef.current = resizeObserver;\n })\n .catch(() => {\n if (mounted) setChartState('error');\n });\n\n return () => {\n mounted = false;\n resizeObserverRef.current?.disconnect();\n resizeObserverRef.current = null;\n chartInstance.current?.dispose();\n chartInstance.current = null;\n };\n // The runtime and ECharts instance are initialized once per mounted chart.\n // Option changes are applied by the effect below without re-initializing.\n }, []);\n\n useEffect(() => {\n updateOption();\n }, [updateOption]);\n\n return (\n <div\n ref={chartRef}\n className=\"chart\"\n data-chart-state={chartState}\n aria-busy={chartState === 'loading'}\n style={{ width: '100%', height: '100%' }}\n />\n );\n}\n"],"names":[],"mappings":";;;;;;;AAmBM;AAUJ;AACA;AACA;;;AAIA;;AAEE;;;AAEO;AACL;;;;;AAIA;;AAEG;;AAEH;;AAEF;AACF;AAEA;;;;;;;;;AASI;AACA;AACD;;;;AAKH;;AAGE;AACF;;;AAKE;AACG;AACC;;AAEA;;;AAIA;AACE;AACF;AACA;AACA;AACF;;AAEE;;AACF;AAEF;;AAEE;AACA;AACA;AACA;AACF;;;;;AAMA;AACF;AAEA;AASF;;"}
@@ -0,0 +1,11 @@
1
+ import type * as echartsCore from 'echarts/core';
2
+ type EChartsRuntime = typeof echartsCore;
3
+ /**
4
+ * Load and register the small ECharts surface used by chart elements.
5
+ *
6
+ * Keeping this behind a shared promise is important for two reasons: charts
7
+ * remain optional for consumers that only render text/images, and multiple
8
+ * charts on one slide do not race to register the same ECharts extensions.
9
+ */
10
+ export declare function loadChartRuntime(): Promise<EChartsRuntime>;
11
+ export {};
@@ -0,0 +1,31 @@
1
+ let runtimePromise;
2
+ /**
3
+ * Load and register the small ECharts surface used by chart elements.
4
+ *
5
+ * Keeping this behind a shared promise is important for two reasons: charts
6
+ * remain optional for consumers that only render text/images, and multiple
7
+ * charts on one slide do not race to register the same ECharts extensions.
8
+ */
9
+ function loadChartRuntime() {
10
+ runtimePromise ??= Promise.all([
11
+ import('echarts/core'),
12
+ import('echarts/charts'),
13
+ import('echarts/components'),
14
+ import('echarts/renderers'),
15
+ ]).then(([echarts, charts, components, renderers]) => {
16
+ echarts.use([
17
+ charts.BarChart,
18
+ charts.LineChart,
19
+ charts.PieChart,
20
+ charts.ScatterChart,
21
+ charts.RadarChart,
22
+ components.LegendComponent,
23
+ renderers.SVGRenderer,
24
+ ]);
25
+ return echarts;
26
+ });
27
+ return runtimePromise;
28
+ }
29
+
30
+ export { loadChartRuntime };
31
+ //# sourceMappingURL=chartRuntime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chartRuntime.js","sources":["../../../src/elements/chart/chartRuntime.ts"],"sourcesContent":["import type * as echartsCore from 'echarts/core';\n\ntype EChartsRuntime = typeof echartsCore;\n\nlet runtimePromise: Promise<EChartsRuntime> | undefined;\n\n/**\n * Load and register the small ECharts surface used by chart elements.\n *\n * Keeping this behind a shared promise is important for two reasons: charts\n * remain optional for consumers that only render text/images, and multiple\n * charts on one slide do not race to register the same ECharts extensions.\n */\nexport function loadChartRuntime(): Promise<EChartsRuntime> {\n runtimePromise ??= Promise.all([\n import('echarts/core'),\n import('echarts/charts'),\n import('echarts/components'),\n import('echarts/renderers'),\n ]).then(([echarts, charts, components, renderers]) => {\n echarts.use([\n charts.BarChart,\n charts.LineChart,\n charts.PieChart,\n charts.ScatterChart,\n charts.RadarChart,\n components.LegendComponent,\n renderers.SVGRenderer,\n ]);\n return echarts;\n });\n\n return runtimePromise;\n}\n"],"names":[],"mappings":"AAIA,IAAI,cAAmD;AAEvD;;;;;;AAMG;SACa,gBAAgB,GAAA;AAC9B,IAAA,cAAc,KAAK,OAAO,CAAC,GAAG,CAAC;QAC7B,OAAO,cAAc,CAAC;QACtB,OAAO,gBAAgB,CAAC;QACxB,OAAO,oBAAoB,CAAC;QAC5B,OAAO,mBAAmB,CAAC;AAC5B,KAAA,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,CAAC,KAAI;QACnD,OAAO,CAAC,GAAG,CAAC;AACV,YAAA,MAAM,CAAC,QAAQ;AACf,YAAA,MAAM,CAAC,SAAS;AAChB,YAAA,MAAM,CAAC,QAAQ;AACf,YAAA,MAAM,CAAC,YAAY;AACnB,YAAA,MAAM,CAAC,UAAU;AACjB,YAAA,UAAU,CAAC,eAAe;AAC1B,YAAA,SAAS,CAAC,WAAW;AACtB,SAAA,CAAC;AACF,QAAA,OAAO,OAAO;AAChB,IAAA,CAAC,CAAC;AAEF,IAAA,OAAO,cAAc;AACvB;;;;"}
@@ -69,6 +69,11 @@ async function slideToPng(slide, options = {}) {
69
69
  // viewportSize differs from the container.
70
70
  await nextFrame();
71
71
  await nextFrame();
72
+ // Charts load ECharts asynchronously because it is an optional peer
73
+ // dependency. Wait for every chart element to finish loading before
74
+ // rasterizing; otherwise exports can capture the intentionally empty
75
+ // loading container while the live slide eventually renders correctly.
76
+ await waitForCharts(container, timeoutMs);
72
77
  // Explicitly force-load every (style, weight, family) the slide actually
73
78
  // uses BEFORE snapshotting. `document.fonts.ready` alone is racy: it can
74
79
  // resolve before the off-screen render has triggered a self-hosted woff2
@@ -246,6 +251,14 @@ async function slideToPng(slide, options = {}) {
246
251
  function nextFrame() {
247
252
  return new Promise((resolve) => requestAnimationFrame(() => resolve()));
248
253
  }
254
+ async function waitForCharts(root, timeoutMs) {
255
+ const deadline = performance.now() + timeoutMs;
256
+ while (root.querySelector('[data-chart-state="loading"]')) {
257
+ if (performance.now() >= deadline)
258
+ return;
259
+ await nextFrame();
260
+ }
261
+ }
249
262
  /**
250
263
  * KaTeX faces (`KaTeX_Main`, `KaTeX_Size4`, …) actually referenced by the
251
264
  * formulas in `root` that are NOT declared in `fontEmbedCSS`. A non-empty result
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../src/snapshot/index.ts"],"sourcesContent":["'use client';\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';\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\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 // 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\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\n/**\n * Bake the soft-edge feather (a:softEdge) into an <img>'s bitmap. html2canvas-pro\n * ignores CSS masks, so the feather BaseImageElement applies is lost in the PNG.\n * The feather radius is read from `data-soft-edge` (px in the element's displayed\n * box) and scaled to the image's natural pixels. Two `destination-in` linear\n * gradient passes multiply the alpha down to 0 within `r` of each edge (corners\n * get both axes), matching the live CSS mask. No-ops on undecoded/ CORS-tainted\n * images or zero radius.\n */\nasync function bakeImageSoftEdge(img: HTMLImageElement): Promise<void> {\n const rCss = parseFloat(img.dataset.softEdge || '');\n if (!rCss || rCss <= 0) return;\n if (!img.complete || img.naturalWidth === 0) return;\n\n const displayedW = img.offsetWidth || img.naturalWidth;\n const scale = img.naturalWidth / displayedW;\n const w = img.naturalWidth;\n const h = img.naturalHeight;\n const r = Math.min(rCss * scale, w / 2, h / 2);\n if (r <= 0) return;\n\n try {\n const canvas = document.createElement('canvas');\n canvas.width = w;\n canvas.height = h;\n const ctx = canvas.getContext('2d');\n if (!ctx) return;\n ctx.drawImage(img, 0, 0, w, h);\n ctx.globalCompositeOperation = 'destination-in';\n\n const stops = (g: CanvasGradient, extent: number) => {\n const f = r / extent;\n g.addColorStop(0, 'rgba(0,0,0,0)');\n g.addColorStop(f, 'rgba(0,0,0,1)');\n g.addColorStop(1 - f, 'rgba(0,0,0,1)');\n g.addColorStop(1, 'rgba(0,0,0,0)');\n return g;\n };\n const gh = stops(ctx.createLinearGradient(0, 0, w, 0), w);\n ctx.fillStyle = gh;\n ctx.fillRect(0, 0, w, h);\n const gv = stops(ctx.createLinearGradient(0, 0, 0, h), h);\n ctx.fillStyle = gv;\n ctx.fillRect(0, 0, w, h);\n\n const baked = canvas.toDataURL('image/png');\n img.removeAttribute('data-soft-edge');\n img.style.maskImage = '';\n (img.style as unknown as Record<string, string>).webkitMaskImage = '';\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 — 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":";;;;;;;;;;AA+EA;AACA;AAEA;;;;;;AAMG;AACI;AAIL;AACE;;;AAIF;;AAEA;;AAEA;AACA;AACA;;;;;;;;AASA;;;;AAIE;AACA;;AAEA;AACD;AACD;;AAGA;AACE;;;;;;AAME;AACF;;;;;;AAOE;AACF;;;;;;;;;;;;;;AAgBA;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;;;;;;;;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;;;;;;;;AAQG;AACH;AACE;AACA;;;;;AAIA;AACA;AACA;AACA;;;AAGA;;AAEE;AACA;;AAEA;;AACA;AACA;AAEA;AACE;AACA;AACA;;AAEA;AACA;AACF;AACA;AACA;;AAEA;AACA;;;AAIA;AACA;AACC;AACD;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\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';\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\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\n/**\n * Bake the soft-edge feather (a:softEdge) into an <img>'s bitmap. html2canvas-pro\n * ignores CSS masks, so the feather BaseImageElement applies is lost in the PNG.\n * The feather radius is read from `data-soft-edge` (px in the element's displayed\n * box) and scaled to the image's natural pixels. Two `destination-in` linear\n * gradient passes multiply the alpha down to 0 within `r` of each edge (corners\n * get both axes), matching the live CSS mask. No-ops on undecoded/ CORS-tainted\n * images or zero radius.\n */\nasync function bakeImageSoftEdge(img: HTMLImageElement): Promise<void> {\n const rCss = parseFloat(img.dataset.softEdge || '');\n if (!rCss || rCss <= 0) return;\n if (!img.complete || img.naturalWidth === 0) return;\n\n const displayedW = img.offsetWidth || img.naturalWidth;\n const scale = img.naturalWidth / displayedW;\n const w = img.naturalWidth;\n const h = img.naturalHeight;\n const r = Math.min(rCss * scale, w / 2, h / 2);\n if (r <= 0) return;\n\n try {\n const canvas = document.createElement('canvas');\n canvas.width = w;\n canvas.height = h;\n const ctx = canvas.getContext('2d');\n if (!ctx) return;\n ctx.drawImage(img, 0, 0, w, h);\n ctx.globalCompositeOperation = 'destination-in';\n\n const stops = (g: CanvasGradient, extent: number) => {\n const f = r / extent;\n g.addColorStop(0, 'rgba(0,0,0,0)');\n g.addColorStop(f, 'rgba(0,0,0,1)');\n g.addColorStop(1 - f, 'rgba(0,0,0,1)');\n g.addColorStop(1, 'rgba(0,0,0,0)');\n return g;\n };\n const gh = stops(ctx.createLinearGradient(0, 0, w, 0), w);\n ctx.fillStyle = gh;\n ctx.fillRect(0, 0, w, h);\n const gv = stops(ctx.createLinearGradient(0, 0, 0, h), h);\n ctx.fillStyle = gv;\n ctx.fillRect(0, 0, w, h);\n\n const baked = canvas.toDataURL('image/png');\n img.removeAttribute('data-soft-edge');\n img.style.maskImage = '';\n (img.style as unknown as Record<string, string>).webkitMaskImage = '';\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 — 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":";;;;;;;;;;AA+EA;AACA;AAEA;;;;;;AAMG;AACI;AAIL;AACE;;;AAIF;;AAEA;;AAEA;AACA;AACA;;;;;;;;AASA;;;;AAIE;AACA;;AAEA;AACD;AACD;;AAGA;AACE;;;;;;AAME;AACF;;;;;;AAOE;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;;;;;;;;AAQG;AACH;AACE;AACA;;;;;AAIA;AACA;AACA;AACA;;;AAGA;;AAEE;AACA;;AAEA;;AACA;AACA;AAEA;AACE;AACA;AACA;;AAEA;AACA;AACF;AACA;AACA;;AAEA;AACA;;;AAIA;AACA;AACC;AACD;AACE;AACA;AACA;AACF;;AACA;;;AAGJ;AAEA;;AAEI;AACE;;;AACK;;AAET;AACF;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openmaic/renderer",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "React component for rendering PPTist-style Slide JSON, extracted from OpenMAIC.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",