@openmaic/renderer 0.1.12 → 0.1.14
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/dist/elements/shape/BaseShapeElement.d.ts +1 -1
- package/dist/elements/shape/BaseShapeElement.js +7 -2
- package/dist/elements/shape/BaseShapeElement.js.map +1 -1
- package/dist/elements/table/StaticTable.js +9 -3
- package/dist/elements/table/StaticTable.js.map +1 -1
- package/dist/elements/text/BaseTextElement.d.ts +1 -1
- package/dist/elements/text/BaseTextElement.js +7 -2
- package/dist/elements/text/BaseTextElement.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/snapshot/index.js +5 -0
- package/dist/snapshot/index.js.map +1 -1
- package/dist/snapshot/measure.js +5 -0
- package/dist/snapshot/measure.js.map +1 -1
- package/dist/utils/inlineMath.d.ts +77 -0
- package/dist/utils/inlineMath.js +247 -0
- package/dist/utils/inlineMath.js.map +1 -0
- package/package.json +2 -2
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx, jsxs } from 'react/jsx-runtime';
|
|
3
|
+
import { useRef } from 'react';
|
|
3
4
|
import { useElementOutline } from '../shared/useElementOutline.js';
|
|
4
5
|
import { useElementShadow } from '../shared/useElementShadow.js';
|
|
5
6
|
import { useElementFlip } from '../shared/useElementFlip.js';
|
|
@@ -7,6 +8,7 @@ import { useElementFill } from '../shared/useElementFill.js';
|
|
|
7
8
|
import { GradientDefs } from './GradientDefs.js';
|
|
8
9
|
import { PatternDefs } from './PatternDefs.js';
|
|
9
10
|
import { preservesPlainTextLineBreaks } from '../../utils/richText.js';
|
|
11
|
+
import { useInnerHtml, useInlineMath } from '../../utils/inlineMath.js';
|
|
10
12
|
|
|
11
13
|
/**
|
|
12
14
|
* Bounding box of a path's coordinates (path/viewBox space). Uses control
|
|
@@ -101,6 +103,9 @@ function BaseShapeElement({ elementInfo, renderLabel }) {
|
|
|
101
103
|
defaultFontName: 'Microsoft YaHei',
|
|
102
104
|
defaultColor: '#333333',
|
|
103
105
|
};
|
|
106
|
+
const proseRef = useRef(null);
|
|
107
|
+
const innerHtml = useInnerHtml(text.content);
|
|
108
|
+
useInlineMath(proseRef, text.content);
|
|
104
109
|
const justifyContent = text.align === 'top' ? 'flex-start' : text.align === 'bottom' ? 'flex-end' : 'center';
|
|
105
110
|
const defaultLabelContent = (jsx("div", { className: "shape-text", style: {
|
|
106
111
|
position: 'absolute',
|
|
@@ -115,11 +120,11 @@ function BaseShapeElement({ elementInfo, renderLabel }) {
|
|
|
115
120
|
// 正向。父层 element-content 已应用 flipStyle 镜像 SVG path;这里给文字
|
|
116
121
|
// 叠加同一个 flipStyle,两次 flip 抵消,让文字保持正向。
|
|
117
122
|
transform: flipStyle,
|
|
118
|
-
}, children: jsx("div", { className: "ProseMirror-static slide-renderer-prose", style: {
|
|
123
|
+
}, children: jsx("div", { ref: proseRef, "data-inline-math-root": "", className: "ProseMirror-static slide-renderer-prose", style: {
|
|
119
124
|
// @ts-expect-error CSS custom properties
|
|
120
125
|
'--paragraphSpace': `${text.paragraphSpace === undefined ? 5 : text.paragraphSpace}px`,
|
|
121
126
|
whiteSpace: preservesPlainTextLineBreaks(text.content) ? 'pre-line' : undefined,
|
|
122
|
-
}, dangerouslySetInnerHTML:
|
|
127
|
+
}, dangerouslySetInnerHTML: innerHtml }) }));
|
|
123
128
|
return (jsx("div", { className: "base-element-shape", style: {
|
|
124
129
|
position: 'absolute',
|
|
125
130
|
top: `${elementInfo.top}px`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseShapeElement.js","sources":["../../../src/elements/shape/BaseShapeElement.tsx"],"sourcesContent":["'use client';\n\nimport type
|
|
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,8 +1,9 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsxs, jsx } from 'react/jsx-runtime';
|
|
3
|
-
import { useMemo } from 'react';
|
|
3
|
+
import { useRef, useMemo } from 'react';
|
|
4
4
|
import { getTableSubThemeColor } from '../../utils/element.js';
|
|
5
5
|
import { getTextStyle } from './tableUtils.js';
|
|
6
|
+
import { useInnerHtmlGrid, useInlineMath } from '../../utils/inlineMath.js';
|
|
6
7
|
|
|
7
8
|
function cellBorderCss(b) {
|
|
8
9
|
if (!b || b.width <= 0)
|
|
@@ -12,6 +13,11 @@ function cellBorderCss(b) {
|
|
|
12
13
|
}
|
|
13
14
|
function StaticTable({ elementInfo }) {
|
|
14
15
|
const { width, data, colWidths, cellMinHeight, rowHeights, outline, theme } = elementInfo;
|
|
16
|
+
const tableRef = useRef(null);
|
|
17
|
+
const cellText = data.map((row) => row.map((cell) => cell?.text ?? ''));
|
|
18
|
+
// Stable per-cell values: React then leaves unchanged cell markup alone.
|
|
19
|
+
const cellHtml = useInnerHtmlGrid(cellText);
|
|
20
|
+
useInlineMath(tableRef, cellText.flat().join(''));
|
|
15
21
|
const [subThemeDark, subThemeLight] = useMemo(() => {
|
|
16
22
|
if (!theme)
|
|
17
23
|
return ['', ''];
|
|
@@ -55,7 +61,7 @@ function StaticTable({ elementInfo }) {
|
|
|
55
61
|
return '#fff';
|
|
56
62
|
return undefined;
|
|
57
63
|
};
|
|
58
|
-
return (jsxs("table", { className: "slide-renderer-prose", style: {
|
|
64
|
+
return (jsxs("table", { ref: tableRef, "data-inline-math-root": "", className: "slide-renderer-prose", style: {
|
|
59
65
|
width: '100%',
|
|
60
66
|
height: '100%',
|
|
61
67
|
borderCollapse: 'collapse',
|
|
@@ -107,7 +113,7 @@ function StaticTable({ elementInfo }) {
|
|
|
107
113
|
// replacement corrupts style attributes like
|
|
108
114
|
// `margin-left: calc(42px + 0.25em)` → the title indent is
|
|
109
115
|
// lost and collides with the cell's left icon (slide 5).
|
|
110
|
-
dangerouslySetInnerHTML:
|
|
116
|
+
dangerouslySetInnerHTML: cellHtml[rowIdx][colIdx] }) }, cell.id));
|
|
111
117
|
}) }, rowIdx))) })] }));
|
|
112
118
|
}
|
|
113
119
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StaticTable.js","sources":["../../../src/elements/table/StaticTable.tsx"],"sourcesContent":["'use client';\n\nimport { useMemo, type CSSProperties } from 'react';\nimport type { PPTTableElement, TableCellBorder } from '@openmaic/dsl';\nimport { getTableSubThemeColor } from '../../utils/element';\nimport { getTextStyle } from './tableUtils';\n\nfunction cellBorderCss(b?: TableCellBorder): string | undefined {\n if (!b || b.width <= 0) return undefined;\n const style = b.style === 'dashed' || b.style === 'dotted' ? b.style : 'solid';\n return `${b.width}px ${style} ${b.color}`;\n}\n\ninterface StaticTableProps {\n elementInfo: PPTTableElement;\n}\n\nexport function StaticTable({ elementInfo }: StaticTableProps) {\n const { width, data, colWidths, cellMinHeight, rowHeights, outline, theme } = elementInfo;\n\n const [subThemeDark, subThemeLight] = useMemo(() => {\n if (!theme) return ['', ''];\n return getTableSubThemeColor(theme.color);\n }, [theme]);\n\n const borderStyle = useMemo(() => {\n if (!outline) return 'none';\n const w = outline.width ?? 1;\n const c = outline.color ?? '#000';\n const s = outline.style === 'dashed' ? 'dashed' : 'solid';\n return `${w}px ${s} ${c}`;\n }, [outline]);\n\n const getCellBg = (\n rowIdx: number,\n colIdx: number,\n cellBackcolor?: string,\n ): string | undefined => {\n if (cellBackcolor) return cellBackcolor;\n if (!theme) return undefined;\n\n const rowCount = data.length;\n const colCount = data[0]?.length ?? 0;\n\n if (theme.rowHeader && rowIdx === 0) return theme.color;\n if (theme.rowFooter && rowIdx === rowCount - 1) return theme.color;\n if (theme.colHeader && colIdx === 0) return subThemeDark;\n if (theme.colFooter && colIdx === colCount - 1) return subThemeDark;\n\n const effectiveRow = theme.rowHeader ? rowIdx - 1 : rowIdx;\n if (effectiveRow >= 0 && effectiveRow % 2 === 0) return subThemeLight;\n\n return undefined;\n };\n\n const getHeaderTextColor = (rowIdx: number): string | undefined => {\n if (!theme) return undefined;\n const rowCount = data.length;\n if (theme.rowHeader && rowIdx === 0) return '#fff';\n if (theme.rowFooter && rowIdx === rowCount - 1) return '#fff';\n return undefined;\n };\n\n return (\n <table\n className=\"slide-renderer-prose\"\n style={{\n width: '100%',\n height: '100%',\n borderCollapse: 'collapse',\n tableLayout: 'fixed',\n }}\n >\n <colgroup>\n {colWidths.map((w, i) => (\n <col key={i} style={{ width: `${w * width}px` }} />\n ))}\n </colgroup>\n <tbody>\n {data.map((row, rowIdx) => (\n <tr key={rowIdx} style={{ height: `${rowHeights?.[rowIdx] ?? cellMinHeight}px` }}>\n {row.map((cell, colIdx) => {\n // parser side (transformParsedToSlides) 已经把 hMerge/vMerge\n // continuation 单元格剔除了,data[r] 只剩 top-left cells;浏览器\n // 的 HTML table layout 通过 td.colSpan/rowSpan 自动算正确位置,\n // 不需要再手动算 hiddenCells(旧实现用 data-index 比对 grid-coord\n // key,混了两种坐标系,把 colspan 跨过的 grid-coord 等于另一格\n // 的 data-index 时会误隐藏,slide 26 表头 \"权重\"/\"好\" 就是中招)。\n const bgColor = getCellBg(rowIdx, colIdx, cell.style?.backcolor);\n const headerColor = getHeaderTextColor(rowIdx);\n const textStyle = getTextStyle(cell.style);\n\n if (headerColor && !cell.style?.color) {\n textStyle.color = headerColor;\n }\n\n // 单元格自带逐边描边时按边渲染(未定义的边不画);否则回退到\n // 表级 outline 套四边的旧行为,保留真·网格表格的表现。\n const cellBorders = cell.borders;\n const borderCss: CSSProperties =\n cellBorders &&\n (cellBorders.top || cellBorders.bottom || cellBorders.left || cellBorders.right)\n ? {\n borderTop: cellBorderCss(cellBorders.top) ?? 'none',\n borderBottom: cellBorderCss(cellBorders.bottom) ?? 'none',\n borderLeft: cellBorderCss(cellBorders.left) ?? 'none',\n borderRight: cellBorderCss(cellBorders.right) ?? 'none',\n }\n : { border: borderStyle };\n\n return (\n <td\n key={cell.id}\n colSpan={cell.colspan > 1 ? cell.colspan : undefined}\n rowSpan={cell.rowspan > 1 ? cell.rowspan : undefined}\n style={{\n ...borderCss,\n backgroundColor: bgColor,\n ...textStyle,\n }}\n >\n <div\n className=\"slide-renderer-cell-text\"\n style={{\n minHeight: `${(rowHeights?.[rowIdx] ?? cellMinHeight) - 4}px`,\n padding: cell.padding,\n display: 'flex',\n flexDirection: 'column',\n lineHeight: 1,\n justifyContent:\n cell.vAlign === 'top'\n ? 'flex-start'\n : cell.vAlign === 'bottom'\n ? 'flex-end'\n : 'center',\n }}\n // cell.text is already final HTML (transformParsedToSlides\n // escapes text + converts \\n/spaces and keeps <p> positioning\n // styles). Do NOT run formatText here — its space→ \n // replacement corrupts style attributes like\n // `margin-left: calc(42px + 0.25em)` → the title indent is\n // lost and collides with the cell's left icon (slide 5).\n dangerouslySetInnerHTML={
|
|
1
|
+
{"version":3,"file":"StaticTable.js","sources":["../../../src/elements/table/StaticTable.tsx"],"sourcesContent":["'use client';\n\nimport { useMemo, useRef, type CSSProperties } from 'react';\nimport type { PPTTableElement, TableCellBorder } from '@openmaic/dsl';\nimport { getTableSubThemeColor } from '../../utils/element';\nimport { getTextStyle } from './tableUtils';\nimport { useInlineMath, useInnerHtmlGrid } from '../../utils/inlineMath';\n\nfunction cellBorderCss(b?: TableCellBorder): string | undefined {\n if (!b || b.width <= 0) return undefined;\n const style = b.style === 'dashed' || b.style === 'dotted' ? b.style : 'solid';\n return `${b.width}px ${style} ${b.color}`;\n}\n\ninterface StaticTableProps {\n elementInfo: PPTTableElement;\n}\n\nexport function StaticTable({ elementInfo }: StaticTableProps) {\n const { width, data, colWidths, cellMinHeight, rowHeights, outline, theme } = elementInfo;\n const tableRef = useRef<HTMLTableElement>(null);\n const cellText = data.map((row) => row.map((cell) => cell?.text ?? ''));\n // Stable per-cell values: React then leaves unchanged cell markup alone.\n const cellHtml = useInnerHtmlGrid(cellText);\n useInlineMath(tableRef, cellText.flat().join(''));\n\n const [subThemeDark, subThemeLight] = useMemo(() => {\n if (!theme) return ['', ''];\n return getTableSubThemeColor(theme.color);\n }, [theme]);\n\n const borderStyle = useMemo(() => {\n if (!outline) return 'none';\n const w = outline.width ?? 1;\n const c = outline.color ?? '#000';\n const s = outline.style === 'dashed' ? 'dashed' : 'solid';\n return `${w}px ${s} ${c}`;\n }, [outline]);\n\n const getCellBg = (\n rowIdx: number,\n colIdx: number,\n cellBackcolor?: string,\n ): string | undefined => {\n if (cellBackcolor) return cellBackcolor;\n if (!theme) return undefined;\n\n const rowCount = data.length;\n const colCount = data[0]?.length ?? 0;\n\n if (theme.rowHeader && rowIdx === 0) return theme.color;\n if (theme.rowFooter && rowIdx === rowCount - 1) return theme.color;\n if (theme.colHeader && colIdx === 0) return subThemeDark;\n if (theme.colFooter && colIdx === colCount - 1) return subThemeDark;\n\n const effectiveRow = theme.rowHeader ? rowIdx - 1 : rowIdx;\n if (effectiveRow >= 0 && effectiveRow % 2 === 0) return subThemeLight;\n\n return undefined;\n };\n\n const getHeaderTextColor = (rowIdx: number): string | undefined => {\n if (!theme) return undefined;\n const rowCount = data.length;\n if (theme.rowHeader && rowIdx === 0) return '#fff';\n if (theme.rowFooter && rowIdx === rowCount - 1) return '#fff';\n return undefined;\n };\n\n return (\n <table\n ref={tableRef}\n data-inline-math-root=\"\"\n className=\"slide-renderer-prose\"\n style={{\n width: '100%',\n height: '100%',\n borderCollapse: 'collapse',\n tableLayout: 'fixed',\n }}\n >\n <colgroup>\n {colWidths.map((w, i) => (\n <col key={i} style={{ width: `${w * width}px` }} />\n ))}\n </colgroup>\n <tbody>\n {data.map((row, rowIdx) => (\n <tr key={rowIdx} style={{ height: `${rowHeights?.[rowIdx] ?? cellMinHeight}px` }}>\n {row.map((cell, colIdx) => {\n // parser side (transformParsedToSlides) 已经把 hMerge/vMerge\n // continuation 单元格剔除了,data[r] 只剩 top-left cells;浏览器\n // 的 HTML table layout 通过 td.colSpan/rowSpan 自动算正确位置,\n // 不需要再手动算 hiddenCells(旧实现用 data-index 比对 grid-coord\n // key,混了两种坐标系,把 colspan 跨过的 grid-coord 等于另一格\n // 的 data-index 时会误隐藏,slide 26 表头 \"权重\"/\"好\" 就是中招)。\n const bgColor = getCellBg(rowIdx, colIdx, cell.style?.backcolor);\n const headerColor = getHeaderTextColor(rowIdx);\n const textStyle = getTextStyle(cell.style);\n\n if (headerColor && !cell.style?.color) {\n textStyle.color = headerColor;\n }\n\n // 单元格自带逐边描边时按边渲染(未定义的边不画);否则回退到\n // 表级 outline 套四边的旧行为,保留真·网格表格的表现。\n const cellBorders = cell.borders;\n const borderCss: CSSProperties =\n cellBorders &&\n (cellBorders.top || cellBorders.bottom || cellBorders.left || cellBorders.right)\n ? {\n borderTop: cellBorderCss(cellBorders.top) ?? 'none',\n borderBottom: cellBorderCss(cellBorders.bottom) ?? 'none',\n borderLeft: cellBorderCss(cellBorders.left) ?? 'none',\n borderRight: cellBorderCss(cellBorders.right) ?? 'none',\n }\n : { border: borderStyle };\n\n return (\n <td\n key={cell.id}\n colSpan={cell.colspan > 1 ? cell.colspan : undefined}\n rowSpan={cell.rowspan > 1 ? cell.rowspan : undefined}\n style={{\n ...borderCss,\n backgroundColor: bgColor,\n ...textStyle,\n }}\n >\n <div\n className=\"slide-renderer-cell-text\"\n style={{\n minHeight: `${(rowHeights?.[rowIdx] ?? cellMinHeight) - 4}px`,\n padding: cell.padding,\n display: 'flex',\n flexDirection: 'column',\n lineHeight: 1,\n justifyContent:\n cell.vAlign === 'top'\n ? 'flex-start'\n : cell.vAlign === 'bottom'\n ? 'flex-end'\n : 'center',\n }}\n // cell.text is already final HTML (transformParsedToSlides\n // escapes text + converts \\n/spaces and keeps <p> positioning\n // styles). Do NOT run formatText here — its space→ \n // replacement corrupts style attributes like\n // `margin-left: calc(42px + 0.25em)` → the title indent is\n // lost and collides with the cell's left icon (slide 5).\n dangerouslySetInnerHTML={cellHtml[rowIdx][colIdx]}\n />\n </td>\n );\n })}\n </tr>\n ))}\n </tbody>\n </table>\n );\n}\n"],"names":[],"mappings":";;;;;;;AAQA;AACE;AAAwB;;;AAG1B;AAMM;AACJ;AACA;;;AAGA;AACA;;AAGE;AAAY;AACZ;AACF;AAEA;AACE;AAAc;AACd;AACA;AACA;AACA;AACF;;AAOE;AAAmB;AACnB;AAAY;AAEZ;;AAGA;;;;AAEA;AAAqC;;AACW;AAEhD;;AACiD;AAEjD;AACF;AAEA;AACE;AAAY;AACZ;AACA;AAAqC;;AACW;AAChD;AACF;AAEA;AAMM;AACA;AACA;AACA;AACD;;;;;;;AAiBO;AACA;;;AAIE;;;;AAKF;;AAGE;AACE;;;;;AAKG;AACH;AAEJ;AAMM;AACA;AACA;AACD;AAKG;;AAEA;AACA;AACA;AACA;AAEI;AACA;AACE;AACA;AACP;;;;;;;AAOD;;AAUpB;;"}
|
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx, jsxs } from 'react/jsx-runtime';
|
|
3
|
+
import { useRef } from 'react';
|
|
3
4
|
import { useElementShadow } from '../shared/useElementShadow.js';
|
|
4
5
|
import { ElementOutline } from '../shared/ElementOutline.js';
|
|
5
6
|
import { preservesPlainTextLineBreaks } from '../../utils/richText.js';
|
|
7
|
+
import { useInnerHtml, useInlineMath } from '../../utils/inlineMath.js';
|
|
6
8
|
|
|
7
9
|
function BaseTextElement({ elementInfo, target, renderContent }) {
|
|
8
10
|
const { shadowStyle } = useElementShadow(elementInfo.shadow);
|
|
11
|
+
const proseRef = useRef(null);
|
|
12
|
+
const innerHtml = useInnerHtml(elementInfo.content);
|
|
13
|
+
useInlineMath(proseRef, elementInfo.content);
|
|
9
14
|
// Imported OOXML text carries its own bodyPr insets on the outer div.
|
|
10
15
|
// Adding the editor's default inset again shifts vertical text left and
|
|
11
16
|
// reduces the available line width for horizontal text.
|
|
@@ -15,11 +20,11 @@ function BaseTextElement({ elementInfo, target, renderContent }) {
|
|
|
15
20
|
/^\s*<div\b[^>]*\bstyle\s*=\s*["'][^"']*\bpadding\s*:/i.test(elementInfo.content);
|
|
16
21
|
const vAlign = elementInfo.vAlign ?? 'top';
|
|
17
22
|
const justifyContent = vAlign === 'middle' ? 'center' : vAlign === 'bottom' ? 'flex-end' : 'flex-start';
|
|
18
|
-
const defaultContent = (jsx("div", { className: "text ProseMirror-static", style: {
|
|
23
|
+
const defaultContent = (jsx("div", { ref: proseRef, "data-inline-math-root": "", className: "text ProseMirror-static", style: {
|
|
19
24
|
position: 'relative',
|
|
20
25
|
pointerEvents: target === 'thumbnail' ? 'none' : undefined,
|
|
21
26
|
whiteSpace: preservesPlainTextLineBreaks(elementInfo.content) ? 'pre-line' : undefined,
|
|
22
|
-
}, dangerouslySetInnerHTML:
|
|
27
|
+
}, dangerouslySetInnerHTML: innerHtml }));
|
|
23
28
|
return (jsx("div", { className: "base-element-text", style: {
|
|
24
29
|
position: 'absolute',
|
|
25
30
|
top: `${elementInfo.top}px`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseTextElement.js","sources":["../../../src/elements/text/BaseTextElement.tsx"],"sourcesContent":["'use client';\n\nimport type
|
|
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;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -8,4 +8,5 @@ export { findElementGeometry, findNearestCorner, getElementPercentageGeometry, t
|
|
|
8
8
|
export { cn } from './utils/cn';
|
|
9
9
|
export { getElementRange, getLineElementPath, getTableSubThemeColor } from './utils/element';
|
|
10
10
|
export { createTextProseStyles } from './styles';
|
|
11
|
+
export { INLINE_MATH_ATTRIBUTE, INLINE_MATH_ROOT_ATTRIBUTE, MAX_INLINE_MATH_SOURCE, completeInlineMath, renderInlineMath, useInlineMath, useInnerHtml, useInnerHtmlGrid, } from './utils/inlineMath';
|
|
11
12
|
export * from './types';
|
package/dist/index.js
CHANGED
|
@@ -11,5 +11,6 @@ export { findElementGeometry, findNearestCorner, getElementPercentageGeometry }
|
|
|
11
11
|
export { cn } from './utils/cn.js';
|
|
12
12
|
export { getElementRange, getLineElementPath, getTableSubThemeColor } from './utils/element.js';
|
|
13
13
|
export { createTextProseStyles } from './styles.js';
|
|
14
|
+
export { INLINE_MATH_ATTRIBUTE, INLINE_MATH_ROOT_ATTRIBUTE, MAX_INLINE_MATH_SOURCE, completeInlineMath, renderInlineMath, useInlineMath, useInnerHtml, useInnerHtmlGrid } from './utils/inlineMath.js';
|
|
14
15
|
export * from '@openmaic/dsl';
|
|
15
16
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;"}
|
package/dist/snapshot/index.js
CHANGED
|
@@ -7,6 +7,7 @@ import html2canvas from 'html2canvas-pro';
|
|
|
7
7
|
import { getFontEmbedCSS, toBlob, toPng } from 'html-to-image';
|
|
8
8
|
import { SlideCanvas } from '../SlideCanvas.js';
|
|
9
9
|
import { KATEX_FONT_EMBED_CSS } from './katex-fonts-embed.js';
|
|
10
|
+
import { completeInlineMath } from '../utils/inlineMath.js';
|
|
10
11
|
export { measureSlideElementGeometry } from './measure.js';
|
|
11
12
|
|
|
12
13
|
const DEFAULT_VIEWPORT_RATIO = 0.5625;
|
|
@@ -57,6 +58,10 @@ async function slideToPng(slide, options = {}) {
|
|
|
57
58
|
flushSync(() => {
|
|
58
59
|
root.render(createElement(SlideCanvas, { slide, chrome: false }));
|
|
59
60
|
});
|
|
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
|
|
63
|
+
// capture.
|
|
64
|
+
completeInlineMath(container);
|
|
60
65
|
// BaseImageElement renders <img loading="lazy">, and this container sits
|
|
61
66
|
// permanently outside the viewport — lazy images would never fetch, and
|
|
62
67
|
// the load-wait below would time out on blank slides. Force eager loading
|
|
@@ -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';\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\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":";;;;;;;;;;;AAiFA;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;;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 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;;"}
|
package/dist/snapshot/measure.js
CHANGED
|
@@ -3,6 +3,7 @@ import { createElement } from 'react';
|
|
|
3
3
|
import { flushSync } from 'react-dom';
|
|
4
4
|
import { createRoot } from 'react-dom/client';
|
|
5
5
|
import { SlideCanvas } from '../SlideCanvas.js';
|
|
6
|
+
import { completeInlineMath } from '../utils/inlineMath.js';
|
|
6
7
|
|
|
7
8
|
const DEFAULT_VIEWPORT_RATIO = 0.5625;
|
|
8
9
|
const DEFAULT_TIMEOUT_MS = 5000;
|
|
@@ -49,6 +50,10 @@ async function measureSlideElementGeometry(slide, elementIds, options = {}) {
|
|
|
49
50
|
flushSync(() => {
|
|
50
51
|
root.render(createElement(SlideCanvas, { slide, chrome: false }));
|
|
51
52
|
});
|
|
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
|
|
55
|
+
// capture.
|
|
56
|
+
completeInlineMath(container);
|
|
52
57
|
// Let the ResizeObserver-driven fit settle, then settle fonts before we read
|
|
53
58
|
// rects. Auto-height text only reaches its final extent once the real faces
|
|
54
59
|
// load, and `document.fonts.ready` alone is racy — it can resolve before the
|
|
@@ -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';\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\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":"
|
|
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;;"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { type RefObject } from 'react';
|
|
2
|
+
/**
|
|
3
|
+
* Inline formulas in slide prose. Stored prose carries each formula as LaTeX
|
|
4
|
+
* source (`<span data-inline-math="LATEX">LATEX</span>`); older or unsaved
|
|
5
|
+
* content may still carry a rendered KaTeX tree with the same attribute. The
|
|
6
|
+
* renderer typesets every such span in the browser from its source.
|
|
7
|
+
*/
|
|
8
|
+
export declare const INLINE_MATH_ATTRIBUTE = "data-inline-math";
|
|
9
|
+
/**
|
|
10
|
+
* Marks an element whose injected prose is one typesetting root (a text box,
|
|
11
|
+
* a shape label, a table), so callers that typeset a whole slide at once use
|
|
12
|
+
* the same roots, budgets and caps as the live elements.
|
|
13
|
+
*/
|
|
14
|
+
export declare const INLINE_MATH_ROOT_ATTRIBUTE = "data-inline-math-root";
|
|
15
|
+
/** Longest source typeset; longer sources are shown as plain LaTeX text. */
|
|
16
|
+
export declare const MAX_INLINE_MATH_SOURCE = 2000;
|
|
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.
|
|
23
|
+
*/
|
|
24
|
+
export declare const INLINE_MATH_SYNC_SOURCE_BUDGET = 4000;
|
|
25
|
+
export declare const INLINE_MATH_SYNC_FORMULA_BUDGET = 100;
|
|
26
|
+
/**
|
|
27
|
+
* Hard cap per prose root, counting every formula in document order: past it,
|
|
28
|
+
* formulas are shown as their LaTeX text and never typeset.
|
|
29
|
+
*/
|
|
30
|
+
export declare const INLINE_MATH_MAX_ROOT_SOURCE = 50000;
|
|
31
|
+
export declare const INLINE_MATH_MAX_ROOT_FORMULAS = 1000;
|
|
32
|
+
export interface RenderInlineMathOptions {
|
|
33
|
+
/**
|
|
34
|
+
* Typeset every formula now, ignoring the per-pass budget (the hard cap
|
|
35
|
+
* still applies). For callers that capture the result right away, such as
|
|
36
|
+
* slide snapshots.
|
|
37
|
+
*/
|
|
38
|
+
readonly complete?: boolean;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Typeset the inline formulas under `root`. Each `span[data-inline-math]` is
|
|
42
|
+
* replaced by a KaTeX render of its source carrying the same attribute (the
|
|
43
|
+
* editor's storage shape); a source that cannot be typeset is shown as text.
|
|
44
|
+
* Returns `true` when formulas were left for a later pass by the budget.
|
|
45
|
+
*/
|
|
46
|
+
export declare function renderInlineMath(root: ParentNode, options?: RenderInlineMathOptions): boolean;
|
|
47
|
+
/**
|
|
48
|
+
* Typeset every formula under `container` now, root by root (each element
|
|
49
|
+
* marked with {@link INLINE_MATH_ROOT_ATTRIBUTE}), so each root keeps its own
|
|
50
|
+
* hard cap exactly as the live elements apply it. For snapshots, which
|
|
51
|
+
* capture right away instead of waiting for idle time.
|
|
52
|
+
*/
|
|
53
|
+
export declare function completeInlineMath(container: Element): void;
|
|
54
|
+
/**
|
|
55
|
+
* A `dangerouslySetInnerHTML` value that keeps its identity while `html` is
|
|
56
|
+
* unchanged. React rewrites injected markup whenever it receives a new value
|
|
57
|
+
* object, which would discard typeset formulas and any idle progress on each
|
|
58
|
+
* re-render; a stable value leaves the DOM alone.
|
|
59
|
+
*/
|
|
60
|
+
export declare function useInnerHtml(html: string): {
|
|
61
|
+
__html: string;
|
|
62
|
+
};
|
|
63
|
+
/** {@link useInnerHtml} for a grid of cells (table text), keyed on every cell's markup. */
|
|
64
|
+
export declare function useInnerHtmlGrid(cells: readonly (readonly string[])[]): {
|
|
65
|
+
__html: string;
|
|
66
|
+
}[][];
|
|
67
|
+
/**
|
|
68
|
+
* Typeset the inline formulas of prose injected into `ref` as `html`. Runs
|
|
69
|
+
* after every commit, before paint: React may rewrite the injected markup on
|
|
70
|
+
* any re-render (not only when `html` changes), which would put the stored
|
|
71
|
+
* source spans back. Formulas already typeset are skipped and cached renders
|
|
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.
|
|
75
|
+
* Never updates React state.
|
|
76
|
+
*/
|
|
77
|
+
export declare function useInlineMath(ref: RefObject<Element | null>, html: string): void;
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useMemo, useLayoutEffect } from 'react';
|
|
3
|
+
import katex from 'katex';
|
|
4
|
+
import { safeKatexOptions } from '@openmaic/dsl';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Inline formulas in slide prose. Stored prose carries each formula as LaTeX
|
|
8
|
+
* source (`<span data-inline-math="LATEX">LATEX</span>`); older or unsaved
|
|
9
|
+
* content may still carry a rendered KaTeX tree with the same attribute. The
|
|
10
|
+
* renderer typesets every such span in the browser from its source.
|
|
11
|
+
*/
|
|
12
|
+
const INLINE_MATH_ATTRIBUTE = 'data-inline-math';
|
|
13
|
+
/**
|
|
14
|
+
* Marks an element whose injected prose is one typesetting root (a text box,
|
|
15
|
+
* a shape label, a table), so callers that typeset a whole slide at once use
|
|
16
|
+
* the same roots, budgets and caps as the live elements.
|
|
17
|
+
*/
|
|
18
|
+
const INLINE_MATH_ROOT_ATTRIBUTE = 'data-inline-math-root';
|
|
19
|
+
/** Longest source typeset; longer sources are shown as plain LaTeX text. */
|
|
20
|
+
const MAX_INLINE_MATH_SOURCE = 2_000;
|
|
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.
|
|
27
|
+
*/
|
|
28
|
+
const INLINE_MATH_SYNC_SOURCE_BUDGET = 4_000;
|
|
29
|
+
const INLINE_MATH_SYNC_FORMULA_BUDGET = 100;
|
|
30
|
+
/**
|
|
31
|
+
* Hard cap per prose root, counting every formula in document order: past it,
|
|
32
|
+
* formulas are shown as their LaTeX text and never typeset.
|
|
33
|
+
*/
|
|
34
|
+
const INLINE_MATH_MAX_ROOT_SOURCE = 50_000;
|
|
35
|
+
const INLINE_MATH_MAX_ROOT_FORMULAS = 1_000;
|
|
36
|
+
/** Formula elements this module already handled, so a repeated pass skips them. */
|
|
37
|
+
const handled = new WeakSet();
|
|
38
|
+
/**
|
|
39
|
+
* Typeset formulas by source, cloned on use: React may rewrite the injected
|
|
40
|
+
* markup on any re-render, and re-typesetting the same source must stay
|
|
41
|
+
* cheap. Bounded by the size of the cached markup, counted in serialized
|
|
42
|
+
* characters (an estimate, not heap bytes); large renders are not kept.
|
|
43
|
+
*/
|
|
44
|
+
const TYPESET_CACHE_MAX_MARKUP = 2_000_000;
|
|
45
|
+
const TYPESET_CACHE_MAX_ENTRY = 64_000;
|
|
46
|
+
const typesetCache = new Map();
|
|
47
|
+
let typesetCacheSize = 0;
|
|
48
|
+
/** Typeset one formula, or `null` to keep its source as text. */
|
|
49
|
+
function typesetUncached(doc, latex) {
|
|
50
|
+
if (!latex.trim() || latex.length > MAX_INLINE_MATH_SOURCE)
|
|
51
|
+
return null;
|
|
52
|
+
const host = doc.createElement('span');
|
|
53
|
+
try {
|
|
54
|
+
// Authored input: `safeKatexOptions` forces `trust: false`, makes
|
|
55
|
+
// formula-defined macros inert, bounds expansion, and builds a fresh
|
|
56
|
+
// `macros` object per call (KaTeX writes global definitions into it).
|
|
57
|
+
katex.render(latex, host, safeKatexOptions({
|
|
58
|
+
displayMode: false,
|
|
59
|
+
output: 'html',
|
|
60
|
+
throwOnError: false,
|
|
61
|
+
strict: 'ignore',
|
|
62
|
+
}));
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
// KaTeX refuses to run in a quirks-mode document (no doctype); the source
|
|
66
|
+
// then stays as text.
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
const formula = host.firstElementChild;
|
|
70
|
+
formula?.setAttribute(INLINE_MATH_ATTRIBUTE, latex);
|
|
71
|
+
return formula;
|
|
72
|
+
}
|
|
73
|
+
function typeset(doc, latex) {
|
|
74
|
+
let entry = typesetCache.get(latex);
|
|
75
|
+
if (entry) {
|
|
76
|
+
// Refresh recency.
|
|
77
|
+
typesetCache.delete(latex);
|
|
78
|
+
typesetCache.set(latex, entry);
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
const formula = typesetUncached(doc, latex);
|
|
82
|
+
entry = { formula, size: latex.length + (formula?.outerHTML.length ?? 0) };
|
|
83
|
+
if (entry.size <= TYPESET_CACHE_MAX_ENTRY) {
|
|
84
|
+
typesetCache.set(latex, entry);
|
|
85
|
+
typesetCacheSize += entry.size;
|
|
86
|
+
for (const [key, value] of typesetCache) {
|
|
87
|
+
if (typesetCacheSize <= TYPESET_CACHE_MAX_MARKUP)
|
|
88
|
+
break;
|
|
89
|
+
typesetCache.delete(key);
|
|
90
|
+
typesetCacheSize -= value.size;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (!entry.formula)
|
|
95
|
+
return null;
|
|
96
|
+
return entry.formula.ownerDocument === doc
|
|
97
|
+
? entry.formula.cloneNode(true)
|
|
98
|
+
: doc.importNode(entry.formula, true);
|
|
99
|
+
}
|
|
100
|
+
/** Formulas shown as text because they fell past a root's hard cap. */
|
|
101
|
+
const capped = new WeakSet();
|
|
102
|
+
function showSource(element, latex) {
|
|
103
|
+
element.textContent = latex;
|
|
104
|
+
handled.add(element);
|
|
105
|
+
}
|
|
106
|
+
/** Show a formula past the hard cap as its source text, whatever it shows now. */
|
|
107
|
+
function showCapped(element, latex) {
|
|
108
|
+
if (capped.has(element))
|
|
109
|
+
return;
|
|
110
|
+
const span = (element.ownerDocument ?? document).createElement('span');
|
|
111
|
+
span.setAttribute(INLINE_MATH_ATTRIBUTE, latex);
|
|
112
|
+
span.textContent = latex;
|
|
113
|
+
handled.add(span);
|
|
114
|
+
capped.add(span);
|
|
115
|
+
element.replaceWith(span);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Typeset the inline formulas under `root`. Each `span[data-inline-math]` is
|
|
119
|
+
* replaced by a KaTeX render of its source carrying the same attribute (the
|
|
120
|
+
* editor's storage shape); a source that cannot be typeset is shown as text.
|
|
121
|
+
* Returns `true` when formulas were left for a later pass by the budget.
|
|
122
|
+
*/
|
|
123
|
+
function renderInlineMath(root, options = {}) {
|
|
124
|
+
const doc = root.ownerDocument ?? root;
|
|
125
|
+
let rootSource = 0;
|
|
126
|
+
let rootFormulas = 0;
|
|
127
|
+
let passSource = 0;
|
|
128
|
+
let passFormulas = 0;
|
|
129
|
+
let pending = false;
|
|
130
|
+
for (const element of root.querySelectorAll(`span[${INLINE_MATH_ATTRIBUTE}]`)) {
|
|
131
|
+
// Inside a formula replaced earlier in this pass.
|
|
132
|
+
if (!root.contains(element))
|
|
133
|
+
continue;
|
|
134
|
+
const latex = element.getAttribute(INLINE_MATH_ATTRIBUTE) ?? '';
|
|
135
|
+
rootSource += latex.length;
|
|
136
|
+
rootFormulas += 1;
|
|
137
|
+
// The cap depends only on document order within the root, so a formula
|
|
138
|
+
// ends up the same whatever earlier passes did with it.
|
|
139
|
+
if (rootSource > INLINE_MATH_MAX_ROOT_SOURCE || rootFormulas > INLINE_MATH_MAX_ROOT_FORMULAS) {
|
|
140
|
+
showCapped(element, latex);
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (handled.has(element) && !capped.has(element))
|
|
144
|
+
continue;
|
|
145
|
+
if (!typesetCache.has(latex)) {
|
|
146
|
+
if (!options.complete &&
|
|
147
|
+
passFormulas > 0 &&
|
|
148
|
+
(passSource + latex.length > INLINE_MATH_SYNC_SOURCE_BUDGET ||
|
|
149
|
+
passFormulas >= INLINE_MATH_SYNC_FORMULA_BUDGET)) {
|
|
150
|
+
pending = true;
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
passSource += latex.length;
|
|
154
|
+
passFormulas += 1;
|
|
155
|
+
}
|
|
156
|
+
const formula = typeset(doc, latex);
|
|
157
|
+
if (!formula) {
|
|
158
|
+
showSource(element, latex);
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
handled.add(formula);
|
|
162
|
+
element.replaceWith(formula);
|
|
163
|
+
}
|
|
164
|
+
return pending;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Typeset every formula under `container` now, root by root (each element
|
|
168
|
+
* marked with {@link INLINE_MATH_ROOT_ATTRIBUTE}), so each root keeps its own
|
|
169
|
+
* hard cap exactly as the live elements apply it. For snapshots, which
|
|
170
|
+
* capture right away instead of waiting for idle time.
|
|
171
|
+
*/
|
|
172
|
+
function completeInlineMath(container) {
|
|
173
|
+
const roots = [...container.querySelectorAll(`[${INLINE_MATH_ROOT_ATTRIBUTE}]`)];
|
|
174
|
+
if (container.hasAttribute(INLINE_MATH_ROOT_ATTRIBUTE))
|
|
175
|
+
roots.unshift(container);
|
|
176
|
+
for (const root of roots)
|
|
177
|
+
renderInlineMath(root, { complete: true });
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* A `dangerouslySetInnerHTML` value that keeps its identity while `html` is
|
|
181
|
+
* unchanged. React rewrites injected markup whenever it receives a new value
|
|
182
|
+
* object, which would discard typeset formulas and any idle progress on each
|
|
183
|
+
* re-render; a stable value leaves the DOM alone.
|
|
184
|
+
*/
|
|
185
|
+
function useInnerHtml(html) {
|
|
186
|
+
return useMemo(() => ({ __html: html }), [html]);
|
|
187
|
+
}
|
|
188
|
+
/** {@link useInnerHtml} for a grid of cells (table text), keyed on every cell's markup. */
|
|
189
|
+
function useInnerHtmlGrid(cells) {
|
|
190
|
+
const key = JSON.stringify(cells);
|
|
191
|
+
return useMemo(() => JSON.parse(key).map((row) => row.map((html) => ({ __html: html }))), [key]);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Run `run` when the page is idle. The scheduling functions are read once,
|
|
195
|
+
* here, and the handle is always cancelled with the function from the same
|
|
196
|
+
* pair: the global may be replaced or removed between scheduling and
|
|
197
|
+
* cancelling (polyfills, test stubs), and a handle from one implementation
|
|
198
|
+
* means nothing to another.
|
|
199
|
+
*/
|
|
200
|
+
function whenIdle(run) {
|
|
201
|
+
const scope = globalThis;
|
|
202
|
+
const request = scope.requestIdleCallback;
|
|
203
|
+
const cancel = scope.cancelIdleCallback;
|
|
204
|
+
if (typeof request === 'function' && typeof cancel === 'function') {
|
|
205
|
+
const handle = request.call(scope, run, { timeout: 500 });
|
|
206
|
+
return { cancel: () => cancel.call(scope, handle) };
|
|
207
|
+
}
|
|
208
|
+
const schedule = scope.setTimeout;
|
|
209
|
+
const clear = scope.clearTimeout;
|
|
210
|
+
const handle = schedule.call(scope, run, 16);
|
|
211
|
+
return { cancel: () => clear.call(scope, handle) };
|
|
212
|
+
}
|
|
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)
|
|
219
|
+
return;
|
|
220
|
+
if (renderInlineMath(root))
|
|
221
|
+
handle = whenIdle(step);
|
|
222
|
+
};
|
|
223
|
+
handle = whenIdle(step);
|
|
224
|
+
return () => handle?.cancel();
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Typeset the inline formulas of prose injected into `ref` as `html`. Runs
|
|
228
|
+
* after every commit, before paint: React may rewrite the injected markup on
|
|
229
|
+
* any re-render (not only when `html` changes), which would put the stored
|
|
230
|
+
* source spans back. Formulas already typeset are skipped and cached renders
|
|
231
|
+
* 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.
|
|
234
|
+
* Never updates React state.
|
|
235
|
+
*/
|
|
236
|
+
function useInlineMath(ref, html) {
|
|
237
|
+
useLayoutEffect(() => {
|
|
238
|
+
const root = ref.current;
|
|
239
|
+
if (!root || !html.includes(INLINE_MATH_ATTRIBUTE))
|
|
240
|
+
return;
|
|
241
|
+
if (renderInlineMath(root))
|
|
242
|
+
return finishWhenIdle(root);
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
|
|
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 };
|
|
247
|
+
//# sourceMappingURL=inlineMath.js.map
|
|
@@ -0,0 +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;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openmaic/renderer",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.14",
|
|
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,7 @@
|
|
|
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.
|
|
82
|
+
"@openmaic/dsl": "^0.11.3"
|
|
83
83
|
},
|
|
84
84
|
"devDependencies": {
|
|
85
85
|
"@rollup/plugin-commonjs": "^28.0.1",
|