返回 oh-my-ppt
browser-scripts.ts
根目录 / src / main / io / html-pptx / browser-scripts.ts
1 export const FREEZE_PAGE_FOR_EXPORT_SCRIPT = `
2 (async () => {
3 const waitForMasterStylesheet = async () => {
4 const master = document.querySelector('link[data-ppt-master="1"]');
5 const expectsMaster = new URLSearchParams(window.location.search).get('_pptMasterExpected') === '1';
6 if (!master || !expectsMaster) return;
7 if (master.dataset.pptMasterExportReady === '1' && master.sheet) return;
8 const masterUrl = new URL(master.href, window.location.href);
9 masterUrl.searchParams.set('_pptMasterExport', String(Date.now()));
10 master.href = masterUrl.toString();
11 await new Promise((resolve, reject) => {
12 let settled = false;
13 const finish = (callback) => {
14 if (settled) return;
15 settled = true;
16 clearTimeout(timeout);
17 master.removeEventListener('load', onLoad);
18 master.removeEventListener('error', onError);
19 callback();
20 };
21 const onLoad = () => finish(() => {
22 master.dataset.pptMasterExportReady = '1';
23 resolve(true);
24 });
25 const onError = () => finish(() => reject(new Error('母版样式表加载失败')));
26 const timeout = setTimeout(
27 () => finish(() => reject(new Error('母版样式表加载超时'))),
28 5000
29 );
30 master.addEventListener('load', onLoad, { once: true });
31 master.addEventListener('error', onError, { once: true });
32 });
33 };
34
35 await waitForMasterStylesheet();
36 if (window.PPT?.whenReadyForPrint) {
37 await window.PPT.whenReadyForPrint(5000);
38 }
39 const expectsMasterElements =
40 new URLSearchParams(window.location.search).get('_pptMasterElementsExpected') === '1';
41 if (expectsMasterElements && !window.PPT?.assertMasterElementsReady) {
42 throw new Error('母版全局元素运行时不可用');
43 }
44 if (window.PPT?.assertMasterElementsReady) {
45 await window.PPT.assertMasterElementsReady(5000);
46 }
47 const root =
48 document.querySelector('.ppt-page-root[data-ppt-guard-root="1"]') ||
49 document.querySelector('.ppt-page-root') ||
50 document.body;
51 const existing = document.getElementById('ohmyppt-export-freeze-page');
52 if (existing) existing.remove();
53 const style = document.createElement('style');
54 style.id = 'ohmyppt-export-freeze-page';
55 style.textContent = [
56 'html { scroll-behavior: auto !important; }',
57 '*, *::before, *::after { animation: none !important; transition: none !important; animation-delay: 0s !important; animation-duration: 0s !important; animation-play-state: paused !important; transition-delay: 0s !important; transition-duration: 0s !important; }',
58 // 只强制显示,不动 transform:data-anim/opacity-0 元素的 class transform 可能是
59 // 静态定位(如 Tailwind -translate-y-1/2 垂直居中),清掉会让元素在背景截图里
60 // 坠到错误位置。动画脚手架是行内样式驱动的,下方 JS 遍历会精确清除行内 transform。
61 '.opacity-0, [data-anim] { opacity: 1 !important; }',
62 '[data-anime], [data-animate] { opacity: 1 !important; transform: none !important; }'
63 ].join('\\n');
64 document.head.appendChild(style);
65
66 try {
67 document.getAnimations?.().forEach((animation) => {
68 try {
69 animation.finish();
70 } catch (_err) {
71 try {
72 animation.cancel();
73 } catch (_cancelErr) {}
74 }
75 });
76 } catch (_err) {}
77
78 const waitFrames = (frames) =>
79 new Promise((resolve) => {
80 let remaining = Math.max(1, Number(frames) || 1);
81 const next = () => {
82 remaining -= 1;
83 if (remaining <= 0) {
84 resolve(true);
85 return;
86 }
87 requestAnimationFrame(next);
88 };
89 requestAnimationFrame(next);
90 });
91
92 const collectChartInstances = () => {
93 const charts = new Set();
94 const ChartCtor = window.Chart;
95 try {
96 if (window.__PPT_CHART_REGISTRY__ instanceof Map) {
97 window.__PPT_CHART_REGISTRY__.forEach((chart) => {
98 if (chart) charts.add(chart);
99 });
100 }
101 } catch (_err) {}
102 try {
103 if (ChartCtor?.instances) {
104 const instances = Array.isArray(ChartCtor.instances)
105 ? ChartCtor.instances
106 : Object.values(ChartCtor.instances);
107 instances.forEach((chart) => {
108 if (chart) charts.add(chart);
109 });
110 }
111 } catch (_err) {}
112 try {
113 root.querySelectorAll('canvas').forEach((canvas) => {
114 let chart = null;
115 try {
116 chart = ChartCtor?.getChart?.(canvas) || null;
117 } catch (_err) {}
118 if (chart) charts.add(chart);
119 });
120 } catch (_err) {}
121 return Array.from(charts);
122 };
123
124 const disableChartAnimations = () => {
125 const ChartCtor = window.Chart;
126 try {
127 if (ChartCtor?.defaults) {
128 ChartCtor.defaults.animation = false;
129 ChartCtor.defaults.animations = false;
130 if (ChartCtor.defaults.transitions) {
131 Object.values(ChartCtor.defaults.transitions).forEach((transition) => {
132 if (transition?.animation) transition.animation.duration = 0;
133 if (transition?.animations) {
134 Object.values(transition.animations).forEach((animation) => {
135 if (animation && typeof animation === 'object') animation.duration = 0;
136 });
137 }
138 });
139 }
140 }
141 } catch (_err) {}
142 };
143
144 const fingerprintCanvases = () => {
145 const canvases = Array.from(root.querySelectorAll('canvas'));
146 if (canvases.length === 0) return '';
147 return canvases
148 .map((canvas) => {
149 const width = canvas.width || 0;
150 const height = canvas.height || 0;
151 if (!width || !height) return 'empty';
152 let ctx = null;
153 try {
154 ctx = canvas.getContext('2d', { willReadFrequently: true }) || canvas.getContext('2d');
155 } catch (_err) {
156 return 'unreadable';
157 }
158 if (!ctx) return 'noctx';
159 const columns = Math.min(8, Math.max(2, Math.floor(width / 80)));
160 const rows = Math.min(6, Math.max(2, Math.floor(height / 60)));
161 let hash = 2166136261;
162 try {
163 for (let yIndex = 0; yIndex < rows; yIndex += 1) {
164 const y = Math.min(height - 1, Math.floor(((yIndex + 0.5) * height) / rows));
165 for (let xIndex = 0; xIndex < columns; xIndex += 1) {
166 const x = Math.min(width - 1, Math.floor(((xIndex + 0.5) * width) / columns));
167 const data = ctx.getImageData(x, y, 1, 1).data;
168 for (let i = 0; i < 4; i += 1) {
169 hash ^= data[i] || 0;
170 hash = Math.imul(hash, 16777619);
171 }
172 }
173 }
174 return String(width) + 'x' + String(height) + ':' + String(hash >>> 0);
175 } catch (_err) {
176 return 'tainted';
177 }
178 })
179 .join('|');
180 };
181
182 const waitForCanvasStability = async () => {
183 if (!root.querySelector('canvas')) return;
184 let previous = '';
185 let stableFrames = 0;
186 const deadline = Date.now() + 1200;
187 while (Date.now() < deadline) {
188 await waitFrames(2);
189 const next = fingerprintCanvases();
190 if (next && next === previous) {
191 stableFrames += 1;
192 if (stableFrames >= 2) return;
193 } else {
194 stableFrames = 0;
195 previous = next;
196 }
197 }
198 };
199
200 const stabilizeCharts = async () => {
201 disableChartAnimations();
202 const applyFinalChartState = () => {
203 collectChartInstances().forEach((chart) => {
204 try {
205 if (chart?.options) {
206 chart.options.animation = false;
207 chart.options.animations = false;
208 chart.options.responsive = false;
209 chart.options.maintainAspectRatio = false;
210 }
211 } catch (_err) {}
212 try {
213 if (typeof chart?.stop === 'function') chart.stop();
214 } catch (_err) {}
215 try {
216 if (typeof chart?.resize === 'function') chart.resize();
217 } catch (_err) {}
218 try {
219 if (typeof chart?.update === 'function') chart.update('none');
220 } catch (_err) {}
221 try {
222 if (typeof chart?.render === 'function') chart.render();
223 else if (typeof chart?.draw === 'function') chart.draw();
224 } catch (_err) {}
225 });
226 };
227
228 applyFinalChartState();
229 await waitFrames(2);
230 applyFinalChartState();
231 await waitForCanvasStability();
232 };
233
234 await stabilizeCharts();
235
236 const shouldForceVisibleForMotion = (node) => {
237 if (!node?.matches?.('.opacity-0, [data-anime], [data-animate], [data-anim]')) return false;
238 return Number(getComputedStyle(node).opacity || '1') <= 0.04;
239 };
240
241 const motionTargets = root.querySelectorAll(
242 '.opacity-0, [data-anime], [data-animate], h1, h2, h3, p, li, .card, .panel, .text-section, .diagram-section, .timeline-node, section, section > *'
243 );
244 motionTargets.forEach((element) => {
245 const node = element;
246 node.style.transition = 'none';
247 node.style.animation = 'none';
248 if (shouldForceVisibleForMotion(node)) {
249 node.setAttribute('data-pptx-animated', '1');
250 node.style.opacity = '1';
251 }
252 if (/translateY\\([^)]*\\)/.test(node.style.transform || '')) {
253 node.setAttribute('data-pptx-animated', '1');
254 node.style.transform = 'none';
255 }
256 });
257
258 root.querySelectorAll('*').forEach((element) => {
259 const node = element;
260 const computed = getComputedStyle(node);
261 if (computed.display === 'none' || computed.visibility === 'hidden') return;
262 if (shouldForceVisibleForMotion(node)) {
263 node.setAttribute('data-pptx-animated', '1');
264 node.style.opacity = '1';
265 }
266 if (/translate(?:3d|X|Y)?\\(/.test(node.style.transform || '')) {
267 node.setAttribute('data-pptx-animated', '1');
268 node.style.transform = 'none';
269 }
270 });
271
272 if (document.fonts?.ready) {
273 try {
274 await document.fonts.ready;
275 } catch (_err) {}
276 }
277 return true;
278 })()
279 `
280
281 export const FREEZE_PAGE_FOR_PPTX_SCRIPT = FREEZE_PAGE_FOR_EXPORT_SCRIPT
282
283 /**
284 * Reset ppt-page-fit-scope transform to scale(1) for full-resolution capture.
285 * Must be executed AFTER text/shape extraction (which needs the scaled coordinates)
286 * but BEFORE screen capture.
287 */
288 export const RESET_SCALE_FOR_PPTX_CAPTURE_SCRIPT = `
289 (async () => {
290 const root =
291 document.querySelector('.ppt-page-root[data-ppt-guard-root="1"]') ||
292 document.querySelector('.ppt-page-root') ||
293 document.body;
294 const scope = root.querySelector(':scope > .ppt-page-fit-scope');
295 if (scope) scope.style.transform = 'scale(1)';
296 void document.body.offsetHeight;
297 await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
298 return true;
299 })()
300 `
301
302 export const HIDE_TEXT_FOR_PPTX_BACKGROUND_SCRIPT = `
303 (async () => {
304 const existing = document.getElementById('ohmyppt-pptx-hide-text');
305 if (existing) existing.remove();
306 const isVisibleColor = (value) => {
307 const color = String(value || '').trim().toLowerCase();
308 return Boolean(color && color !== 'transparent' && !/^rgba?\\([^)]*,\\s*0\\s*\\)$/.test(color));
309 };
310 const resolveVisibleTextColor = (element) => {
311 let current = element;
312 while (current && current.nodeType === 1) {
313 const color = getComputedStyle(current).color;
314 if (isVisibleColor(color)) return color;
315 current = current.parentElement;
316 }
317 return '#111827';
318 };
319 const style = document.createElement('style');
320 style.id = 'ohmyppt-pptx-hide-text';
321 style.textContent = [
322 'body :not(.katex):not(.katex *):not(canvas) { -webkit-text-fill-color: transparent !important; -webkit-text-stroke-color: transparent !important; text-shadow: none !important; text-decoration-color: transparent !important; caret-color: transparent !important; }',
323 'body :not(.katex):not(.katex *)::before, body :not(.katex):not(.katex *)::after { -webkit-text-fill-color: transparent !important; -webkit-text-stroke-color: transparent !important; text-shadow: none !important; text-decoration-color: transparent !important; }',
324 '.katex, .katex * { -webkit-text-fill-color: currentColor !important; text-shadow: none !important; }',
325 'svg text, svg tspan { fill: transparent !important; stroke: transparent !important; }',
326 'input, textarea { color: transparent !important; -webkit-text-fill-color: transparent !important; }'
327 ].join('\\n');
328 document.head.appendChild(style);
329 document.querySelectorAll('.katex').forEach((element) => {
330 const node = element;
331 const color = resolveVisibleTextColor(node);
332 node.style.color = color;
333 node.style.webkitTextFillColor = color;
334 node.style.fontFamily = 'KaTeX_Main, "Times New Roman", "Microsoft YaHei", "PingFang SC", "Noto Sans CJK SC", sans-serif';
335 });
336 const hideTextPaint = (node) => {
337 node.style.setProperty('-webkit-text-fill-color', 'transparent', 'important');
338 node.style.setProperty('-webkit-text-stroke-color', 'transparent', 'important');
339 node.style.setProperty('text-shadow', 'none', 'important');
340 node.style.setProperty('text-decoration-color', 'transparent', 'important');
341 node.style.setProperty('caret-color', 'transparent', 'important');
342 };
343 const hasOwnTextNode = (element) =>
344 Array.from(element.childNodes || []).some((node) => node.nodeType === Node.TEXT_NODE && String(node.textContent || '').trim());
345 document.querySelectorAll('body *').forEach((element) => {
346 if (element.closest('.katex, .katex-mathml, script, style, noscript, canvas')) return;
347 if (hasOwnTextNode(element)) hideTextPaint(element);
348 });
349 document.querySelectorAll('svg text, svg tspan').forEach((element) => {
350 element.style.setProperty('fill', 'transparent', 'important');
351 element.style.setProperty('stroke', 'transparent', 'important');
352 });
353 void document.body.offsetHeight;
354 if (document.fonts?.ready) {
355 try {
356 await document.fonts.ready;
357 } catch (_err) {}
358 }
359 void document.body.offsetHeight;
360 await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
361 return true;
362 })()
363 `
364
365 export const buildMarkPptxExtractedTextForBackgroundScript = (
366 texts: Array<{ x: number; y: number; w: number; h: number }>,
367 slideSize: { widthIn: number; heightIn: number } = { widthIn: 13.333, heightIn: 7.5 }
368 ): string => {
369 const boxes = texts
370 .filter(
371 (text) =>
372 Number.isFinite(text.x) &&
373 Number.isFinite(text.y) &&
374 Number.isFinite(text.w) &&
375 Number.isFinite(text.h) &&
376 text.w > 0.02 &&
377 text.h > 0.02
378 )
379 .map((text) => ({ x: text.x, y: text.y, w: text.w, h: text.h }))
380
381 return `
382 (() => {
383 const root =
384 document.querySelector('.ppt-page-root[data-ppt-guard-root="1"]') ||
385 document.querySelector('.ppt-page-root') ||
386 document.body;
387 // This script is rerun for background-capture retries. Remove stale matches before
388 // evaluating the latest extraction result so a newly unsupported text node stays rasterized.
389 root.querySelectorAll('[data-pptx-background-text-match]').forEach((element) => {
390 element.removeAttribute('data-pptx-background-text-match');
391 });
392 const textBoxes = ${JSON.stringify(boxes)};
393 if (!textBoxes.length) return 0;
394 const rootRect = root.getBoundingClientRect();
395 if (!rootRect.width || !rootRect.height) return 0;
396 const slideWidth = ${JSON.stringify(slideSize.widthIn)};
397 const slideHeight = ${JSON.stringify(slideSize.heightIn)};
398 const toClientBox = (box) => ({
399 left: rootRect.left + (box.x / slideWidth) * rootRect.width,
400 top: rootRect.top + (box.y / slideHeight) * rootRect.height,
401 width: (box.w / slideWidth) * rootRect.width,
402 height: (box.h / slideHeight) * rootRect.height
403 });
404 const boxesInClientSpace = textBoxes.map(toClientBox);
405 const overlapsExtractedText = (rect) => {
406 if (rect.width < 1 || rect.height < 1) return false;
407 const rectArea = rect.width * rect.height;
408 return boxesInClientSpace.some((box) => {
409 const overlapWidth = Math.max(0, Math.min(rect.right, box.left + box.width) - Math.max(rect.left, box.left));
410 const overlapHeight = Math.max(0, Math.min(rect.bottom, box.top + box.height) - Math.max(rect.top, box.top));
411 const overlap = overlapWidth * overlapHeight;
412 // A native PPT box can be intentionally wider than its painted glyphs, but it must
413 // still cover almost all of this DOM text fragment. Partial or center-only overlap
414 // leaves the fragment in the raster background as a conservative fallback.
415 return overlap / rectArea >= 0.85;
416 });
417 };
418 let marked = 0;
419 root.querySelectorAll('*').forEach((element) => {
420 if (element.closest('script, style, noscript, svg, canvas, video, iframe, .katex, .katex-mathml')) return;
421 // aria-hidden text is decorative and intentionally skipped by the extractor;
422 // it must remain painted in the raster background, never matched as extracted.
423 if (element.closest('[aria-hidden="true"]')) return;
424 const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, {
425 acceptNode: (node) =>
426 String(node.textContent || '').trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT
427 });
428 const textNodes = [];
429 while (walker.nextNode()) textNodes.push(walker.currentNode);
430 if (!textNodes.length) return;
431 const textRects = textNodes.flatMap((node) => {
432 const range = document.createRange();
433 range.selectNodeContents(node);
434 return Array.from(range.getClientRects());
435 });
436 if (textRects.length && textRects.every(overlapsExtractedText)) {
437 // Mark the container only when every descendant text fragment maps to a
438 // native PPT text box. This handles mixed content such as "$528<span>亿</span>"
439 // without hiding a neighboring fallback-only child through inheritance.
440 element.setAttribute('data-pptx-background-text-match', '1');
441 marked += 1;
442 }
443 });
444 return marked;
445 })()
446 `
447 }
448
449 // Background capture for PPTX keeps every visual that cannot be represented as
450 // a native PPTX object. Only successfully extracted objects are removed. This
451 // avoids both text ghosts on animated nodes and missing complex CSS/DOM visuals.
452 export const HIDE_FOR_PPTX_BACKGROUND_SCRIPT = `
453 (async () => {
454 // Helper: same rgbToHex as main extraction script
455 const rgbToHex = (value) => {
456 const source = String(value || '').trim();
457 if (!source || source === 'transparent') return '';
458 if (source.startsWith('#')) {
459 const raw = source.slice(1).toUpperCase();
460 return raw.length === 3 ? raw.split('').map((part) => part + part).join('') : raw;
461 }
462 const match = source.match(/rgba?\\(\\s*(\\d+(?:\\.\\d+)?)(?:\\s*,\\s*|\\s+)(\\d+(?:\\.\\d+)?)(?:\\s*,\\s*|\\s+)(\\d+(?:\\.\\d+)?)(?:\\s*(?:,|\\/)\\s*(\\d+(?:\\.\\d+)?%?))?/i);
463 if (!match) return '';
464 const alpha = match[4] === undefined
465 ? 1
466 : String(match[4]).endsWith('%')
467 ? Number.parseFloat(match[4]) / 100
468 : Number(match[4]);
469 if (alpha <= 0.02) return '';
470 return [match[1], match[2], match[3]]
471 .map((part) => Math.max(0, Math.min(255, Math.round(Number(part) || 0))).toString(16).padStart(2, '0'))
472 .join('')
473 .toUpperCase();
474 };
475
476 // 1. Mark additional decorative elements (blur blobs, glass-morphism, very low Tailwind opacity)
477 const root = document.querySelector('.ppt-page-root') || document.body;
478 root.querySelectorAll('*').forEach((el) => {
479 if (el.hasAttribute('data-pptx-animated')) return;
480 const style = getComputedStyle(el);
481 const hasBlur = /blur/i.test(style.filter || '') || /blur/i.test(style.backdropFilter || '');
482 const cls = el.className && typeof el.className === 'string' ? el.className : '';
483 const hasDecoClass = /\\b(opacity-[012]0|opacity-[12]5)\\b/.test(cls) || /\\bblur-(sm|md|lg|xl|2xl|3xl)\\b/.test(cls);
484 if (hasBlur || hasDecoClass) {
485 el.setAttribute('data-pptx-animated', '1');
486 }
487 });
488
489 // 1b. Mark full-page background elements as decorative (preserve their background during capture)
490 const pageArea = root.getBoundingClientRect().width * root.getBoundingClientRect().height;
491 root.querySelectorAll(':scope > div, :scope > section, :scope > main').forEach((el) => {
492 if (el.hasAttribute('data-pptx-animated')) return;
493 const style = getComputedStyle(el);
494 const fill = rgbToHex(style.backgroundColor);
495 if (!fill) return;
496 const rect = el.getBoundingClientRect();
497 if (rect.width * rect.height >= pageArea * 0.5) {
498 el.setAttribute('data-pptx-animated', '1');
499 }
500 });
501
502 // Large edge-anchored fills are structural backgrounds. Keep them in the
503 // screenshot base instead of relying on a native shape whose z-order can
504 // cover the slide or be accidentally targeted by a text animation.
505 root.querySelectorAll('[data-pptx-extracted-shape]').forEach((el) => {
506 const rect = el.getBoundingClientRect();
507 const rootRect = root.getBoundingClientRect();
508 const pageArea = rootRect.width * rootRect.height;
509 if (!pageArea || rect.width * rect.height < pageArea * 0.2) return;
510 const horizontalTolerance = 2;
511 const verticalTolerance = 2;
512 const spansWidth = rect.width >= rootRect.width - horizontalTolerance;
513 const spansHeight = rect.height >= rootRect.height - verticalTolerance;
514 if (!spansWidth && !spansHeight) return;
515 const touchesHorizontalEdge = rect.left <= rootRect.left + horizontalTolerance || rect.right >= rootRect.right - horizontalTolerance;
516 const touchesVerticalEdge = rect.top <= rootRect.top + verticalTolerance || rect.bottom >= rootRect.bottom - verticalTolerance;
517 if (touchesHorizontalEdge && touchesVerticalEdge) {
518 el.setAttribute('data-pptx-static-background', '1');
519 }
520 });
521
522 // 2. Remove previous style
523 const existing = document.getElementById('ohmyppt-pptx-hide-elements');
524 if (existing) existing.remove();
525
526 // 2b. Pin decorative aria-hidden text paint with inline !important. The hide rule
527 // below blanks color/text-fill on everything inside an extracted-text container,
528 // and inherited -webkit-text-fill-color cannot be undone by a selector alone.
529 // Snapshot the pre-hide computed paint and re-apply it inline (rerun-safe: the
530 // snapshot of an already-pinned value is the same value).
531 const paintProps = [
532 'color',
533 '-webkit-text-fill-color',
534 '-webkit-text-stroke-color',
535 'text-shadow',
536 'text-decoration-color'
537 ];
538 root.querySelectorAll('[aria-hidden="true"], [aria-hidden="true"] *').forEach((el) => {
539 if (el.closest('script, style, noscript, svg, canvas, video, iframe, .katex, .katex-mathml')) return;
540 const computed = getComputedStyle(el);
541 paintProps.forEach((prop) => {
542 const value = computed.getPropertyValue(prop);
543 if (!value) return;
544 el.style.setProperty(prop, value, 'important');
545 });
546 });
547
548 // Pseudo-elements are not part of the DOM text extraction. Keep their own
549 // text paint while only confirmed extracted DOM text is made transparent below.
550 root.querySelectorAll('*').forEach((el) => {
551 ['before', 'after'].forEach((kind) => {
552 const pseudo = getComputedStyle(el, '::' + kind);
553 const content = String(pseudo.content || '').trim();
554 if (!content || content === 'none' || content === 'normal') return;
555 el.setAttribute('data-pptx-has-' + kind, '1');
556 el.style.setProperty('--pptx-' + kind + '-color', pseudo.color || 'transparent');
557 el.style.setProperty('--pptx-' + kind + '-text-fill', pseudo.webkitTextFillColor || pseudo.color || 'transparent');
558 el.style.setProperty('--pptx-' + kind + '-text-stroke', pseudo.webkitTextStrokeColor || 'transparent');
559 el.style.setProperty('--pptx-' + kind + '-text-shadow', pseudo.textShadow || 'none');
560 el.style.setProperty('--pptx-' + kind + '-text-decoration', pseudo.textDecorationColor || 'transparent');
561 });
562 });
563
564 // 3. CSS: keep any visual that was not confirmed extracted in the raster
565 // background. This is the fallback for complex or capped-out source content.
566 const style = document.createElement('style');
567 style.id = 'ohmyppt-pptx-hide-elements';
568 style.textContent = [
569 // Precisely hide extracted shapes (background/border) and images (visibility)
570 '[data-pptx-extracted-shape]:not([data-pptx-static-background]) { background-color: transparent !important; border-color: transparent !important; }',
571 '[data-pptx-extracted-image] { opacity: 0 !important; visibility: hidden !important; }',
572 // Keep unmapped images, shadows and complex containers in the raster background.
573 // Their extraction can fail because of data limits, filters or cross-origin assets.
574 // Only hide text whose source element was confirmed extracted. Hiding all DOM
575 // text leaves no fallback when a text-box limit or complex layout skips it.
576 // aria-hidden subtrees are decorative (e.g. giant watermark glyphs): the extractor
577 // deliberately skips them, so they must keep their paint and stay in this raster
578 // instead of being blanked by an ancestor's extracted-text mark.
579 '[data-pptx-extracted-text], [data-pptx-extracted-text] *:not(:is([aria-hidden="true"], [aria-hidden="true"] *)), [data-pptx-background-text-match] { color: transparent !important; -webkit-text-fill-color: transparent !important; -webkit-text-stroke-color: transparent !important; text-shadow: none !important; text-decoration-color: transparent !important; caret-color: transparent !important; }',
580 '[data-pptx-has-before]::before { color: var(--pptx-before-color) !important; -webkit-text-fill-color: var(--pptx-before-text-fill) !important; -webkit-text-stroke-color: var(--pptx-before-text-stroke) !important; text-shadow: var(--pptx-before-text-shadow) !important; text-decoration-color: var(--pptx-before-text-decoration) !important; }',
581 '[data-pptx-has-after]::after { color: var(--pptx-after-color) !important; -webkit-text-fill-color: var(--pptx-after-text-fill) !important; -webkit-text-stroke-color: var(--pptx-after-text-stroke) !important; text-shadow: var(--pptx-after-text-shadow) !important; text-decoration-color: var(--pptx-after-text-decoration) !important; }',
582 // Hide katex elements (captured as separate images before background capture)
583 '.katex { opacity: 0 !important; visibility: hidden !important; }',
584 // Hide formula blocks (captured as block-level overlay images)
585 '[data-pptx-formula-block] { opacity: 0 !important; visibility: hidden !important; }',
586 // An SVG that could not be rasterized stays visible in the background.
587 'svg[data-pptx-extracted-image] text, svg[data-pptx-extracted-image] tspan { fill: transparent !important; stroke: transparent !important; }',
588 // Hide input/textarea text
589 'input, textarea { color: transparent !important; -webkit-text-fill-color: transparent !important; }'
590 ].join('\\n');
591 document.head.appendChild(style);
592 void document.body.offsetHeight;
593 await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
594 return true;
595 })()
596 `
597
598 export const RESTORE_PPTX_PAGE_AFTER_BACKGROUND_CAPTURE_SCRIPT = `
599 (async () => {
600 document.getElementById('ohmyppt-pptx-hide-elements')?.remove();
601 void document.body.offsetHeight;
602 await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
603 return true;
604 })()
605 `
606
607 export const HIDE_ELEMENTS_FOR_PPTX_BACKGROUND_SCRIPT = `
608 (async () => {
609 let existing = document.getElementById('ohmyppt-pptx-hide-elements');
610 if (existing) existing.remove();
611 const style = document.createElement('style');
612 style.id = 'ohmyppt-pptx-hide-elements';
613 style.textContent = [
614 'img, canvas { opacity: 0 !important; visibility: hidden !important; }',
615 'svg { opacity: 0 !important; visibility: hidden !important; }',
616 'section, main, article, header, footer, aside, div, figure, figcaption, table, td, th { background-color: transparent !important; border-color: transparent !important; }',
617 'body :not(canvas) { -webkit-text-fill-color: transparent !important; -webkit-text-stroke-color: transparent !important; text-shadow: none !important; text-decoration-color: transparent !important; caret-color: transparent !important; }',
618 'body::before, body::after { -webkit-text-fill-color: transparent !important; -webkit-text-stroke-color: transparent !important; text-shadow: none !important; text-decoration-color: transparent !important; }',
619 '.katex { opacity: 0 !important; visibility: hidden !important; }',
620 'svg text, svg tspan { fill: transparent !important; stroke: transparent !important; }',
621 'input, textarea { color: transparent !important; -webkit-text-fill-color: transparent !important; }'
622 ].join('\\n');
623 document.head.appendChild(style);
624 void document.body.offsetHeight;
625 await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
626 return true;
627 })()
628 `
629
630 export const MARK_KATEX_BLOCKS_SCRIPT = `
631 (() => {
632 const root = document.querySelector('.ppt-page-root') || document.body;
633 root.querySelectorAll('[data-pptx-formula-block]').forEach((block) => {
634 block.removeAttribute('data-pptx-formula-block');
635 });
636 const blockSelector = [
637 'p',
638 'div',
639 'section',
640 'article',
641 'main',
642 'aside',
643 'header',
644 'footer',
645 'figure',
646 'figcaption',
647 'li',
648 'ul',
649 'ol',
650 'dl',
651 'dt',
652 'dd',
653 'blockquote',
654 'pre',
655 'h1',
656 'h2',
657 'h3',
658 'h4',
659 'h5',
660 'h6',
661 'td',
662 'th'
663 ].join(',');
664 const BLOCK_TAGS = new Set(blockSelector.split(',').map((tag) => tag.toUpperCase()));
665 const allBlocks = root.querySelectorAll(blockSelector);
666 let count = 0;
667 for (const block of allBlocks) {
668 // Must contain katex
669 if (!block.querySelector('.katex')) continue;
670 // Check if any direct child block also contains katex — if so, this is a
671 // parent container and the children are the actual leaf targets.
672 let childBlockHasKatex = false;
673 for (const child of block.children) {
674 if (!BLOCK_TAGS.has(child.tagName)) continue;
675 if (child.querySelector('.katex')) { childBlockHasKatex = true; break; }
676 }
677 if (childBlockHasKatex) continue;
678 block.setAttribute('data-pptx-formula-block', '1');
679 count++;
680 }
681 return count;
682 })()
683 `
684
685 export const COLLECT_PPTX_ANIMATION_TRACES_SCRIPT = `
686 (() => {
687 const root = document.querySelector('.ppt-page-root') || document.body;
688 const pageRect = root.getBoundingClientRect();
689 // These are native PowerPoint effects with a stable final state. Path motion is
690 // intentionally excluded: an HTML path's final CSS transform cannot be
691 // faithfully reconstructed from the static exported geometry.
692 const safeNativeTypes = new Set([
693 'fade',
694 'fade-up',
695 'fade-down',
696 'fade-left',
697 'fade-right',
698 'scale-in',
699 'slide-up',
700 'slide-down',
701 'slide-left',
702 'slide-right',
703 'fly-in',
704 'wipe',
705 'zoom-in',
706 'spin-in',
707 'grow-shrink-soft',
708 'grow-shrink',
709 'grow-shrink-strong',
710 'pulse-soft',
711 'pulse',
712 'pulse-strong',
713 'exit-fade',
714 'exit-scale',
715 'exit-zoom',
716 'exit-wipe',
717 'exit-fly'
718 ]);
719 const supportedTriggers = new Set(['load', 'click', 'with', 'after']);
720 const supportedSequences = new Set(['with', 'after']);
721 const staggerCounters = {};
722 let lastSequenceStart = 0;
723 let lastSequenceEnd = 0;
724 const traces = [];
725 const normalizeType = (value) => {
726 const type = String(value || 'fade-up').trim().toLowerCase();
727 if (type === 'none') return 'none';
728 if (type === 'fly' || type === 'flyin') return 'fly-in';
729 if (type === 'zoom' || type === 'zoomin') return 'zoom-in';
730 if (type === 'spin' || type === 'spinin') return 'spin-in';
731 if (type === 'growsoft' || type === 'growshrinksoft') return 'grow-shrink-soft';
732 if (type === 'grow' || type === 'growshrink') return 'grow-shrink';
733 if (type === 'growstrong' || type === 'growshrinkstrong') return 'grow-shrink-strong';
734 if (type === 'emphasis') return 'pulse';
735 if (type === 'pulsesoft') return 'pulse-soft';
736 if (type === 'pulsestrong') return 'pulse-strong';
737 if (type === 'exitscale') return 'exit-scale';
738 if (type === 'exitzoom') return 'exit-zoom';
739 return safeNativeTypes.has(type) || type === 'path' ? type : 'fade-up';
740 };
741 const normalizeTrigger = (value) => {
742 const trigger = String(value || 'load').trim().toLowerCase();
743 if (trigger === 'on-click') return 'click';
744 if (trigger === 'after-previous') return 'after';
745 if (trigger === 'with-previous') return 'with';
746 return supportedTriggers.has(trigger) ? trigger : 'load';
747 };
748 const normalizeSequence = (value) => {
749 const sequence = String(value || '').trim().toLowerCase();
750 if (sequence === 'after-previous') return 'after';
751 if (sequence === 'with-previous') return 'with';
752 return supportedSequences.has(sequence) ? sequence : '';
753 };
754 const normalizeClickGroup = (value) => {
755 const group = String(value || '').trim();
756 return group || '';
757 };
758 const isValidClickGroup = (value) => /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(String(value || ''));
759 const defaultFrom = (type) => {
760 if (type === 'fade-down') return 'top';
761 if (type === 'slide-down') return 'top';
762 if (type === 'fade-left' || type === 'slide-left') return 'right';
763 if (type === 'slide-right') return 'left';
764 if (type === 'fade-right') return 'left';
765 if (type === 'wipe' || type === 'exit-wipe') return 'left';
766 return 'bottom';
767 };
768 const normalizeFrom = (value, fallback) => {
769 const from = String(value || fallback || 'bottom').trim().toLowerCase();
770 if (from === 'up' || from === 'top') return 'top';
771 if (from === 'down' || from === 'bottom') return 'bottom';
772 if (from === 'start') return 'left';
773 if (from === 'end') return 'right';
774 if (from === 'left' || from === 'right' || from === 'center') return from;
775 return fallback || 'bottom';
776 };
777 const extractedSelector = '[data-pptx-extracted-text], [data-pptx-extracted-shape], [data-pptx-extracted-image]';
778 const collectTrace = (el, type, trigger, from, duration, delay, order, clickGroup) => {
779 const rect = el.getBoundingClientRect();
780 if (rect.width < 2 || rect.height < 2) return;
781 const trace = {
782 type,
783 trigger,
784 from,
785 duration: Math.max(100, Math.min(5000, Number(duration) || 500)),
786 delay: Math.max(0, Math.min(30000, Number(delay) || 0)),
787 order,
788 x: Math.round(rect.left - pageRect.left),
789 y: Math.round(rect.top - pageRect.top),
790 w: Math.round(rect.width),
791 h: Math.round(rect.height)
792 };
793 if (clickGroup) trace.clickGroup = clickGroup;
794 traces.push(trace);
795 };
796
797 const collectExtractedTargets = (animationRoot) => {
798 const candidates = [];
799 if (animationRoot.matches(extractedSelector)) candidates.push(animationRoot);
800 animationRoot.querySelectorAll(extractedSelector).forEach((candidate) => {
801 // Nested data-anim blocks own their extracted objects and receive a
802 // separate native effect, avoiding duplicate timing entries.
803 if (candidate.closest('[data-anim]') === animationRoot) candidates.push(candidate);
804 });
805 return Array.from(new Set(candidates));
806 };
807
808 const elements = Array.from(root.querySelectorAll('[data-anim]'));
809
810 elements.forEach((el, order) => {
811 const type = normalizeType(el.getAttribute('data-anim'));
812 if (type === 'none' || !safeNativeTypes.has(type)) return;
813
814 const trigger = normalizeTrigger(el.getAttribute('data-anim-trigger'));
815 const effectiveTrigger = trigger === 'click' ? 'click' : 'load';
816 const sequence = normalizeSequence(el.getAttribute('data-anim-sequence'));
817 const clickGroupRaw = normalizeClickGroup(el.getAttribute('data-anim-click-group'));
818 const clickGroup =
819 effectiveTrigger === 'click' && isValidClickGroup(clickGroupRaw) ? clickGroupRaw : '';
820 const from = normalizeFrom(el.getAttribute('data-anim-from'), defaultFrom(type));
821 const duration = Math.max(100, Math.min(5000, Number(el.getAttribute('data-anim-duration')) || 500));
822 const delayRaw = (el.getAttribute('data-anim-delay') || '0').trim();
823 const staggerRaw = (el.getAttribute('data-anim-stagger') || '').trim();
824 let delay = 0;
825 if (staggerRaw) {
826 const gap = Number(staggerRaw);
827 const normalizedGap = Number.isFinite(gap) ? Math.max(0, gap) : 0;
828 const key = effectiveTrigger;
829 if (staggerCounters[key] === undefined) staggerCounters[key] = 0;
830 delay = staggerCounters[key] * normalizedGap;
831 staggerCounters[key] += 1;
832 } else if (delayRaw.indexOf('stagger') === 0) {
833 const match = delayRaw.match(/stagger\\s*\\(\\s*(\\d+)\\s*\\)/);
834 const gap = match ? Number(match[1]) : 50;
835 const key = effectiveTrigger;
836 if (staggerCounters[key] === undefined) staggerCounters[key] = 0;
837 delay = staggerCounters[key] * gap;
838 staggerCounters[key] += 1;
839 } else {
840 delay = Number(delayRaw) || 0;
841 }
842
843 if (effectiveTrigger === 'load') {
844 const sequencingMode = sequence || trigger;
845 if (sequencingMode === 'after') {
846 delay += lastSequenceEnd;
847 lastSequenceStart = delay;
848 lastSequenceEnd = Math.max(lastSequenceEnd, delay + duration);
849 } else if (sequencingMode === 'with') {
850 delay += lastSequenceStart;
851 lastSequenceEnd = Math.max(lastSequenceEnd, delay + duration);
852 } else {
853 lastSequenceStart = delay;
854 lastSequenceEnd = Math.max(lastSequenceEnd, delay + duration);
855 }
856 }
857
858 // The extractor adds these attributes only after it has created a native
859 // PPT text/shape/image. Use those exact boxes instead of guessing from a
860 // parent container; unmapped source content remains visible in the raster
861 // fallback and can never disappear because of a timing entry.
862 collectExtractedTargets(el).forEach((target) => {
863 collectTrace(target, type, effectiveTrigger, from, duration, delay, order, clickGroup);
864 });
865 });
866
867 return traces;
868 })()
869 `
870
871 // PPTX element timing is not reliable enough for normal editable exports. This
872 // only detects that the source page contains animation so the slide can use a
873 // safe, page-level transition without hiding individual editable objects.
874 export const HAS_DECLARED_PPTX_ANIMATION_SCRIPT = `
875 (() => {
876 const root =
877 document.querySelector('.ppt-page-root[data-ppt-guard-root="1"]') ||
878 document.querySelector('.ppt-page-root') ||
879 document.body;
880 const selector = '[data-anim]:not([data-anim="none"]), [data-anime], [data-animate]';
881 return Boolean(
882 root.matches(selector) || root.querySelector(selector)
883 );
884 })()
885 `
886
887 export const COLLECT_KATEX_BLOCK_RECTS_SCRIPT = `
888 (async () => {
889 const root = document.querySelector('.ppt-page-root') || document.body;
890 const pageRect = root.getBoundingClientRect();
891 const blocks = root.querySelectorAll('[data-pptx-formula-block="1"]');
892 const results = [];
893 for (const block of blocks) {
894 const rect = block.getBoundingClientRect();
895 if (rect.width < 2 || rect.height < 2) continue;
896 results.push({
897 x: Math.round(rect.left - pageRect.left),
898 y: Math.round(rect.top - pageRect.top),
899 w: Math.round(rect.width),
900 h: Math.round(rect.height)
901 });
902 }
903 return results;
904 })()
905 `
906
907 export const WAIT_FOR_PPTX_CAPTURE_FRAME_SCRIPT = `
908 (async () => {
909 void document.body.offsetHeight;
910 await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
911 void document.body.offsetHeight;
912 return true;
913 })()
914 `
915
915 lines TYPESCRIPT