返回 slidev
walker.ts
根目录 / packages / slidev / node / commands / pptx / walker.ts
1 import type { RawNode, RawSlide, RawSnapshot, RawStyle } from './ir'
2
3 /**
4 * The one function that runs inside the browser. Invariant: zero free variables.
5 * Playwright serializes this function's source and evaluates it where none of this
6 * module's imports exist, so everything it needs is nested inside it or passed as a
7 * parameter; `walker.test.ts` enforces this mechanically. The type-only import above
8 * is erased at compile time and is safe.
9 *
10 * It extracts facts only a live layout engine can supply and makes no decisions;
11 * every judgement lives in `normalize.ts`, where it can be unit-tested.
12 */
13 export function collectSnapshot(options: {
14 containerSelector: string
15 idAttribute: string
16 }): RawSnapshot {
17 const STYLE_KEYS = [
18 'display',
19 'position',
20 'zIndex',
21 'visibility',
22 'opacity',
23 'color',
24 'backgroundColor',
25 'backgroundImage',
26 'fontFamily',
27 'fontSize',
28 'fontWeight',
29 'fontStyle',
30 'textAlign',
31 'textDecorationLine',
32 'textTransform',
33 'letterSpacing',
34 'lineHeight',
35 'whiteSpace',
36 'paddingLeft',
37 'paddingRight',
38 'borderTopWidth',
39 'borderTopStyle',
40 'borderTopColor',
41 'borderRightWidth',
42 'borderRightStyle',
43 'borderRightColor',
44 'borderBottomWidth',
45 'borderBottomStyle',
46 'borderBottomColor',
47 'borderLeftWidth',
48 'borderLeftStyle',
49 'borderLeftColor',
50 'borderTopLeftRadius',
51 'boxShadow',
52 'filter',
53 'backdropFilter',
54 'mixBlendMode',
55 'clipPath',
56 'transform',
57 'writingMode',
58 'webkitBackgroundClip',
59 'top',
60 'right',
61 'bottom',
62 'left',
63 'width',
64 'height',
65 'overflow',
66 ] as const
67
68 /** Strips the quotes CSS keeps around a `content` or font family value. */
69 const RE_QUOTES = /^["']|["']$/g
70
71 const styles: RawStyle[] = []
72 const styleIndex = new Map<string, number>()
73
74 /**
75 * Intern a computed style: `getComputedStyle` exposes several hundred properties,
76 * so serializing a full style per node turns a snapshot into megabytes crossing
77 * the CDP boundary. A few hundred nodes collapse to a few dozen distinct styles.
78 */
79 function intern(computed: CSSStyleDeclaration): number {
80 const record: Record<string, string> = {}
81 for (const key of STYLE_KEYS)
82 record[key] = computed[key as any] ?? ''
83 const key = JSON.stringify(record)
84 const existing = styleIndex.get(key)
85 if (existing !== undefined)
86 return existing
87 const index = styles.length
88 // Complete by construction: every `RawStyle` key comes from `STYLE_KEYS`.
89 styles.push(record as unknown as RawStyle)
90 styleIndex.set(key, index)
91 return index
92 }
93
94 /**
95 * Which family a CSS font stack actually resolves to on this machine, measured by
96 * rendering a probe string and comparing widths: `document.fonts.check()` returns
97 * true for families that do not exist.
98 */
99 const unplaceablePseudos: string[] = []
100 const fontResolution: Record<string, string> = {}
101 const probeCanvas = document.createElement('canvas')
102 const probeContext = probeCanvas.getContext('2d')!
103 const PROBE = 'mmmmmmmmmmlliWWWWWW0Oo'
104 const BASES = ['monospace', 'sans-serif', 'serif']
105 const baseWidths: Record<string, number> = {}
106 for (const base of BASES) {
107 probeContext.font = `72px ${base}`
108 baseWidths[base] = probeContext.measureText(PROBE).width
109 }
110
111 function isAvailable(family: string): boolean {
112 for (const base of BASES) {
113 probeContext.font = `72px "${family}", ${base}`
114 // A missing family falls through to the base, so an identical width
115 // against every base means it never took effect.
116 if (probeContext.measureText(PROBE).width !== baseWidths[base])
117 return true
118 }
119 return false
120 }
121
122 // CSS keywords, not typefaces; naming one in a .pptx makes PowerPoint substitute its default.
123 const GENERIC = [
124 'system-ui',
125 'ui-sans-serif',
126 'ui-serif',
127 'ui-monospace',
128 'ui-rounded',
129 'sans-serif',
130 'serif',
131 'monospace',
132 'cursive',
133 'fantasy',
134 'math',
135 'emoji',
136 'fangsong',
137 'inherit',
138 'initial',
139 'unset',
140 ]
141
142 function resolveStack(stack: string): void {
143 if (stack in fontResolution)
144 return
145 for (const raw of stack.split(',')) {
146 const family = raw.trim().replace(RE_QUOTES, '')
147 if (!family)
148 continue
149 if (GENERIC.includes(family.toLowerCase()) || family.charAt(0) === '-')
150 continue
151 // `@fontsource-variable` names its family "Inter Variable"; the face
152 // people actually have installed is "Inter". So the stack is probed
153 // under the name the page really registered, and only the name written
154 // into the file is stripped. Testing the stripped name first finds
155 // nothing whenever the theme ships the font as a webfont and the machine
156 // has no static copy, which is the usual case, and the whole deck then
157 // falls through to a system face the author never chose.
158 const cleaned = family.replace(/\s+Variable$/, '')
159 if (isAvailable(family) || isAvailable(cleaned)) {
160 fontResolution[stack] = cleaned
161 return
162 }
163 }
164 fontResolution[stack] = ''
165 }
166
167 /**
168 * The nearest painted background color at or above the slide container; themes
169 * can put `bg-main` on an ancestor rather than on the container itself.
170 */
171 function backgroundOf(container: Element): string | undefined {
172 // Any fully transparent color ends nothing: matching only the literal
173 // `rgba(0, 0, 0, 0)` misses `rgba(255, 255, 255, 0)` and `oklch(... / 0)`.
174 // The browser judges, since it accepts syntaxes no parser here does.
175 const probe = document.createElement('canvas').getContext('2d')
176 let node: Element | null = container
177 while (node) {
178 const color = getComputedStyle(node).backgroundColor
179 if (color && color !== 'transparent') {
180 if (!probe)
181 return color
182 // Painting over an opaque backdrop leaves it untouched only when the color contributes nothing.
183 probe.clearRect(0, 0, 1, 1)
184 probe.fillStyle = color
185 probe.fillRect(0, 0, 1, 1)
186 if (probe.getImageData(0, 0, 1, 1).data[3] !== 0)
187 return color
188 }
189 node = node.parentElement
190 }
191 return undefined
192 }
193
194 /**
195 * The text an ordinary list marker renders, which the DOM never exposes; ordered
196 * lists need the ordinal counted over previous list-item siblings.
197 */
198 function markerGlyph(el: Element, listStyleType: string): string {
199 const BULLETS: Record<string, string> = {
200 'disc': '\u2022 ',
201 'circle': '\u25E6 ',
202 'square': '\u25AA ',
203 'disclosure-open': '\u25BE ',
204 'disclosure-closed': '\u25B8 ',
205 }
206 if (listStyleType in BULLETS)
207 return BULLETS[listStyleType]
208
209 let ordinal = 1
210 let sibling = el.previousElementSibling
211 while (sibling) {
212 if (getComputedStyle(sibling).display === 'list-item')
213 ordinal++
214 sibling = sibling.previousElementSibling
215 }
216 const parent = el.parentElement
217 const start = parent && parent.tagName.toUpperCase() === 'OL'
218 ? Number(parent.getAttribute('start') || '1')
219 : 1
220 const value = ordinal + (Number.isFinite(start)
221 ? start
222 : 1) - 1
223
224 if (listStyleType === 'lower-alpha' || listStyleType === 'lower-latin')
225 return `${String.fromCharCode(96 + ((value - 1) % 26) + 1)}. `
226 if (listStyleType === 'upper-alpha' || listStyleType === 'upper-latin')
227 return `${String.fromCharCode(64 + ((value - 1) % 26) + 1)}. `
228 return `${value}. `
229 }
230
231 const containers = Array.from(document.querySelectorAll(options.containerSelector))
232 const slides: RawSlide[] = []
233 let nextId = 0
234
235 for (const container of containers) {
236 const containerRect = container.getBoundingClientRect()
237
238 // A print page stacks every slide into one tall viewport; a container not
239 // being rendered has a zero-sized rect. `--range` is the caller's filter.
240 if (containerRect.width === 0 || containerRect.height === 0)
241 continue
242
243 // `003-02` is slide 3, click step 2 (1-based in the id).
244 const parts = (container.id || '').split('-')
245 const no = Number(parts[0])
246 const clickIndex = Number(parts[1]) - 1
247 if (!Number.isFinite(no))
248 continue
249
250 const nodes: RawNode[] = []
251
252 function relative(rect: DOMRect | { left: number, top: number, width: number, height: number }) {
253 return {
254 x: rect.left - containerRect.left,
255 y: rect.top - containerRect.top,
256 w: rect.width,
257 h: rect.height,
258 }
259 }
260
261 function walk(node: Node, parent: number, fromShadowRoot: boolean, inheritedOpacity: number): void {
262 if (node.nodeType === 3) {
263 const text = node.textContent ?? ''
264 // A whitespace-only node can hold the only space between two inline
265 // elements; kept when it occupies a line box, ignored when collapsed.
266 if (!text)
267 return
268 const range = document.createRange()
269 range.selectNodeContents(node)
270 const rects = Array.from(range.getClientRects())
271 range.detach()
272 // A rect-less node still matters twice over: inside `white-space: pre`
273 // a newline is the only record of where a line ends, and a
274 // whitespace-only node is the only record that two inline elements are
275 // separated at all. Chromium reports no rect for the space between two
276 // inline-blocks, and without it `<kbd>shift</kbd> <kbd>space</kbd>`
277 // came out as "shiftspace".
278 if (!rects.length) {
279 if (text.trim())
280 return
281 nodes.push({
282 id: nextId++,
283 parent,
284 tag: '#text',
285 style: -1,
286 rect: { x: 0, y: 0, w: 0, h: 0 },
287 glyphRects: [],
288 text,
289 })
290 return
291 }
292 // Glyph rects, not the element box: positioned from the element rect the text lands offset and re-wraps.
293 const bounds = {
294 left: Math.min(...rects.map(r => r.left)),
295 top: Math.min(...rects.map(r => r.top)),
296 width: Math.max(...rects.map(r => r.right)) - Math.min(...rects.map(r => r.left)),
297 height: Math.max(...rects.map(r => r.bottom)) - Math.min(...rects.map(r => r.top)),
298 }
299 nodes.push({
300 id: nextId++,
301 parent,
302 tag: '#text',
303 style: -1,
304 rect: relative(bounds),
305 glyphRects: rects.map(relative),
306 text,
307 // A text node inherits the compounded opacity; without it a greyed paragraph exports solid.
308 ...(inheritedOpacity < 1
309 ? { opacity: inheritedOpacity }
310 : {}),
311 })
312 return
313 }
314
315 if (node.nodeType !== 1)
316 return
317
318 const el = node as Element
319 const id = nextId++
320 const computed = getComputedStyle(el)
321
322 // `visibility: hidden` and `opacity: 0` still have boxes: a not-yet-revealed
323 // v-click element sits at opacity 0 and would export onto every click step.
324 if (computed.display === 'none' || computed.visibility === 'hidden')
325 return
326 const own = Number(computed.opacity)
327 // CSS `opacity` does not inherit, and DrawingML has no group opacity to stand
328 // in for a wrapper's, so it is compounded here while the tree is available.
329 const effectiveOpacity = inheritedOpacity * (Number.isFinite(own)
330 ? own
331 : 1)
332 if (effectiveOpacity === 0)
333 return
334
335 el.setAttribute(options.idAttribute, String(id))
336 resolveStack(computed.fontFamily)
337
338 const box = el.getBoundingClientRect()
339 const record: RawNode = {
340 id,
341 parent,
342 tag: el.tagName.toUpperCase(),
343 style: intern(computed),
344 rect: relative(box),
345 // Document coordinates too: an element overflowing the slide is
346 // captured as a page clip, which needs a page-space rectangle.
347 pageRect: {
348 x: box.left + window.scrollX,
349 y: box.top + window.scrollY,
350 w: box.width,
351 h: box.height,
352 },
353 }
354 if (effectiveOpacity < 1)
355 record.opacity = effectiveOpacity
356 // An inline box that wraps paints once per line, so backgrounds belong to
357 // the fragments. Only `inline` proper: an inline-block has one rect.
358 if (computed.display === 'inline') {
359 const fragments = Array.from(el.getClientRects())
360 if (fragments.length > 1)
361 record.fragments = fragments.map(relative)
362 }
363 if (fromShadowRoot)
364 record.fromShadowRoot = true
365 // KaTeX marks its root by class; the MathML it writes for screen readers is display:none.
366 if (el.classList.contains('katex'))
367 record.isMath = true
368 if (el.tagName.toUpperCase() === 'IMG') {
369 record.src = (el as HTMLImageElement).currentSrc || (el as HTMLImageElement).src
370 const alt = (el as HTMLImageElement).alt
371 if (alt)
372 record.alt = alt
373 }
374 if (el.tagName.toUpperCase() === 'A') {
375 const href = (el as HTMLAnchorElement).href
376 if (href)
377 record.href = href
378 }
379 if (el.tagName.toUpperCase() === 'SVG' && el.querySelector('foreignObject'))
380 // Mermaid puts its labels in <foreignObject> HTML with no <text>
381 // element; the normalizer routes these to a picture.
382 record.hasForeignObject = true
383
384 // `::marker` is a pseudo-element, so a bullet has no text node. Reading
385 // `content` alone recovers only custom markers: Chromium reports it as
386 // `normal` for ordinary lists and leaves the glyph to `list-style-type`.
387 if (computed.display === 'list-item') {
388 const marker = getComputedStyle(el, '::marker')
389 const explicit = marker && marker.content
390 && marker.content !== 'none'
391 && marker.content !== 'normal'
392 if (explicit) {
393 record.marker = marker.content.replace(RE_QUOTES, '')
394 }
395 else if (computed.listStyleType !== 'none') {
396 record.marker = markerGlyph(el, computed.listStyleType)
397 }
398 }
399
400 nodes.push(record)
401
402 // `::before` and `::after` have no DOM node, so a tree walk cannot see
403 // them, and themes use them for decorative marks. Only absolutely
404 // positioned pseudos are placeable: anything in flow has geometry not
405 // recoverable from computed style alone, and is reported instead.
406 for (const which of ['::before', '::after']) {
407 const pseudo = getComputedStyle(el, which)
408 if (!pseudo || !pseudo.content || pseudo.content === 'none')
409 continue
410 const paints = pseudo.content !== 'normal'
411 || (pseudo.backgroundImage && pseudo.backgroundImage !== 'none')
412 if (!paints)
413 continue
414 if (pseudo.position !== 'absolute' || computed.position === 'static') {
415 unplaceablePseudos.push(`${el.tagName.toLowerCase()}${which}`)
416 continue
417 }
418
419 const own = el.getBoundingClientRect()
420 const width = Number.parseFloat(pseudo.width) || 0
421 const height = Number.parseFloat(pseudo.height) || 0
422 if (width <= 0 || height <= 0) {
423 unplaceablePseudos.push(`${el.tagName.toLowerCase()}${which}`)
424 continue
425 }
426 // `auto` parses to NaN, which spreads through the whole `pageRect` and
427 // loses the decoration to a failed clip. Zero is what `auto` resolves
428 // to for an absolutely positioned box with no other constraint.
429 const px = (value: string): number => Number.parseFloat(value) || 0
430 const left = pseudo.left === 'auto'
431 ? own.width - px(pseudo.right) - width
432 : px(pseudo.left)
433 const top = pseudo.top === 'auto'
434 ? own.height - px(pseudo.bottom) - height
435 : px(pseudo.top)
436
437 const box = {
438 left: own.left + left,
439 top: own.top + top,
440 width,
441 height,
442 }
443 // Document coordinates, not viewport ones: the clip screenshot is taken
444 // after other captures have scrolled the page, so viewport coordinates
445 // read at measurement time are stale by then.
446 const pageRect = {
447 x: box.left + window.scrollX,
448 y: box.top + window.scrollY,
449 w: width,
450 h: height,
451 }
452 const text = pseudo.content.replace(RE_QUOTES, '')
453 nodes.push({
454 id: nextId++,
455 parent: id,
456 tag: which === '::before'
457 ? '::BEFORE'
458 : '::AFTER',
459 style: intern(pseudo),
460 rect: relative(box),
461 // A pseudo has no element to screenshot, so it is captured by clipping the page.
462 pageRect,
463 ...(text && pseudo.content !== 'normal'
464 ? { text }
465 : {}),
466 })
467 }
468
469 // Descend into the shadow root as well; Mermaid renders into one.
470 const shadow = (el as any).shadowRoot
471 if (shadow) {
472 for (const child of Array.from(shadow.childNodes) as Node[])
473 walk(child, id, true, effectiveOpacity)
474 }
475
476 // Recurse through zero-sized boxes rather than pruning them: a cover
477 // slide commonly hangs its title off a wrapper that measures 0 high.
478 for (const child of Array.from(el.childNodes) as Node[])
479 walk(child, id, fromShadowRoot, effectiveOpacity)
480 }
481
482 for (const child of Array.from(container.childNodes) as Node[])
483 walk(child, -1, false, 1)
484
485 slides.push({
486 no,
487 clickIndex: Number.isFinite(clickIndex)
488 ? clickIndex
489 : 0,
490 // The exact id: with `--with-clicks` a prefix match plus `.first()`
491 // hands every step a picture of step one.
492 containerId: container.id,
493 size: { w: containerRect.width, h: containerRect.height },
494 // The container's own background is never reached by a walk that starts
495 // at its children; without it a dark theme exports onto default white.
496 background: backgroundOf(container),
497 nodes,
498 })
499 }
500
501 return {
502 slides,
503 styles,
504 fontResolution,
505 unplaceablePseudos,
506 } as RawSnapshot
507 }
508
508 lines TYPESCRIPT