返回 slidev
capture.ts
根目录 / packages / slidev / node / commands / pptx / capture.ts
1 import type { Page } from 'playwright-chromium'
2 import type { IrImage, IrRaster, Rect, SlideIr } from './ir'
3 import type { RasterRequest } from './normalize'
4 import { Buffer } from 'node:buffer'
5
6 /**
7 * The only Playwright glue in the exporter. Rasterization runs as a second phase,
8 * after every measurement is in hand, because isolating an element for a screenshot
9 * means mutating the DOM of the live app. Only inline `visibility`/`background-color`
10 * (no reflow) and the viewport height are touched; width is what `PrintContainer`
11 * scales from, so the coordinates the walker measured stay valid here.
12 */
13
14 export const ID_ATTRIBUTE = 'data-slidev-export-id'
15
16 /** Marks an element this module hid, and remembers what to put back. */
17 const RESTORE_ATTRIBUTE = 'data-slidev-export-restore'
18
19 /**
20 * Cache the document plus every open shadow root on `window`. `isolate` and `restore`
21 * both need to see inside shadow roots (Mermaid renders into one), and rescanning the
22 * tree per capture is a full walk per picture. Built on first use, after every slide has rendered.
23 */
24 async function installRootFinder(page: Page): Promise<void> {
25 await page.evaluate(() => {
26 if ((window as any).__slidevExportRoots)
27 return
28 let cache: (Document | ShadowRoot)[] | undefined
29 ;(window as any).__slidevExportRoots = () => {
30 if (cache)
31 return cache
32 const found: (Document | ShadowRoot)[] = [document]
33 const collect = (root: Document | ShadowRoot) => {
34 for (const el of Array.from(root.querySelectorAll('*'))) {
35 const shadow = (el as any).shadowRoot
36 if (shadow) {
37 found.push(shadow)
38 collect(shadow)
39 }
40 }
41 }
42 collect(document)
43 cache = found
44 return cache
45 }
46 })
47 }
48
49 /**
50 * Hide everything except the target and its ancestors. `locator.screenshot()` clips
51 * the page to the element's box rather than isolating it, so overlapping content would
52 * be captured and then drawn again as shapes. `visibility` rather than `display`:
53 * `display: none` reflows and moves the target.
54 */
55 async function isolate(page: Page, id: number, hideDescendants: boolean): Promise<boolean> {
56 return await page.evaluate(
57 ({ id, idAttribute, restoreAttribute, hideDescendants }) => {
58 // `document.querySelector` does not pierce shadow DOM while `page.locator` does,
59 // so the screenshot succeeds even when isolation silently misses a shadow-DOM target.
60 const roots = (window as any).__slidevExportRoots() as (Document | ShadowRoot)[]
61 let target: Element | null = null
62 for (const root of roots) {
63 const hit = root.querySelector(`[${idAttribute}="${id}"]`)
64 if (hit) {
65 target = hit
66 break
67 }
68 }
69 if (!target)
70 return false
71
72 const hide = (el: Element) => {
73 const html = el as HTMLElement
74 html.setAttribute(restoreAttribute, html.style.visibility || '')
75 html.style.visibility = 'hidden'
76 }
77
78 // `omitBackground` only drops the browser's default backdrop; clear ancestor
79 // backgrounds too, or a mostly transparent element captures an opaque one.
80 const clear = (el: Element) => {
81 const html = el as HTMLElement
82 html.setAttribute(`${restoreAttribute}-bg`, html.style.backgroundColor || '')
83 html.style.backgroundColor = 'transparent'
84 }
85
86 // Only correct when the descendants are redrawn as shapes afterwards;
87 // a leaf's children are its artwork.
88 if (hideDescendants) {
89 for (const child of Array.from(target.children))
90 hide(child)
91 // A direct text child has no element to hide; make it transparent.
92 const html = target as HTMLElement
93 html.setAttribute(`${restoreAttribute}-color`, html.style.color || '')
94 html.style.color = 'transparent'
95 }
96
97 // Climbs through shadow boundaries: `parentElement` is null at the top
98 // of a shadow tree, so a loop conditioned on it hides nothing there.
99 let node: Element = target
100 for (;;) {
101 const parent: HTMLElement | null = node.parentElement
102 if (parent) {
103 for (const sibling of Array.from(parent.children)) {
104 if (sibling !== node)
105 hide(sibling)
106 }
107 // The target keeps its own background: a backdrop is the thing captured.
108 clear(parent)
109 node = parent
110 continue
111 }
112 const root = node.getRootNode() as ShadowRoot
113 if (!root || !root.host)
114 break
115 for (const sibling of Array.from(root.children)) {
116 if (sibling !== node)
117 hide(sibling)
118 }
119 node = root.host
120 }
121 return true
122 },
123 {
124 id,
125 idAttribute: ID_ATTRIBUTE,
126 restoreAttribute: RESTORE_ATTRIBUTE,
127 hideDescendants,
128 },
129 )
130 }
131
132 /**
133 * Put back everything `isolate` hid. Driven off an attribute rather than a remembered
134 * list, so it is correct even if a previous restore was interrupted. Runs in a
135 * `finally`: a half-hidden deck corrupts every capture after it.
136 */
137 async function restore(page: Page): Promise<void> {
138 await page.evaluate((restoreAttribute) => {
139 // Shadow roots too, or elements hidden inside them stay hidden.
140 const roots = (window as any).__slidevExportRoots()
141 const all = (selector: string) => roots.flatMap((root: Document | ShadowRoot) => Array.from(root.querySelectorAll(selector)))
142 for (const el of all(`[${restoreAttribute}-bg]`)) {
143 const previous = el.getAttribute(`${restoreAttribute}-bg`) ?? ''
144 const style = (el as HTMLElement).style
145 if (previous)
146 style.backgroundColor = previous
147 else
148 style.removeProperty('background-color')
149 el.removeAttribute(`${restoreAttribute}-bg`)
150 }
151 for (const el of all(`[${restoreAttribute}-color]`)) {
152 const previous = el.getAttribute(`${restoreAttribute}-color`) ?? ''
153 const style = (el as HTMLElement).style
154 if (previous)
155 style.color = previous
156 else
157 style.removeProperty('color')
158 el.removeAttribute(`${restoreAttribute}-color`)
159 }
160 for (const el of all(`[${restoreAttribute}]`)) {
161 const previous = el.getAttribute(restoreAttribute) ?? ''
162 const style = (el as HTMLElement).style
163 if (previous)
164 style.visibility = previous
165 else
166 style.removeProperty('visibility')
167 el.removeAttribute(restoreAttribute)
168 }
169 }, RESTORE_ATTRIBUTE)
170 }
171
172 /**
173 * Screenshot an element, or return undefined; never throws, since two of the three
174 * call sites are fallback paths. `locator.screenshot()` is not used: on a print page
175 * far taller than its viewport it returns a region from elsewhere on the page
176 * entirely, so the element's live box is read and the page clipped at it instead.
177 */
178 async function shoot(page: Page, selector: string): Promise<string | undefined> {
179 try {
180 const locator = page.locator(selector).first()
181 if (!(await locator.count()))
182 return undefined
183 const box = await locator.boundingBox()
184 if (!box || box.width <= 0 || box.height <= 0)
185 return undefined
186 // `boundingBox()` is viewport-relative; `shootClip` wants document coordinates.
187 const scrollY = await page.evaluate(() => window.scrollY)
188 return await shootClip(page, {
189 x: box.x,
190 y: box.y + scrollY,
191 w: box.width,
192 h: box.height,
193 })
194 }
195 catch {
196 return undefined
197 }
198 }
199
200 /**
201 * Chromium silently truncates captures past roughly twenty thousand CSS pixels, and
202 * the print route sizes its viewport to the whole deck, so on a long deck every clip
203 * below that point fails. Clips are taken through a short, scrolled viewport instead.
204 */
205 const CLIP_VIEWPORT_MIN_HEIGHT = 2000
206
207 /**
208 * A viewport tall enough to hold the tallest thing being captured: with `canvasWidth: 3840`
209 * a single 16:9 slide is 2160 tall, so a fixed height would fail every whole-slide clip.
210 */
211 function clipViewportHeight(slides: SlideIr[], requests: RasterRequest[]): number {
212 const tallest = Math.max(
213 0,
214 ...slides.map(slide => slide.size.h),
215 ...requests.map(request => request.clip?.h ?? 0),
216 )
217 return Math.max(CLIP_VIEWPORT_MIN_HEIGHT, Math.ceil(tallest) + 200)
218 }
219
220 /**
221 * Screenshot a rectangle of the document. `clip` is in document coordinates while
222 * Playwright reads it as viewport-relative, so the region is scrolled to first and the
223 * clip rebased onto the scroll position actually reached. `fullPage` is not an option:
224 * on a long deck it asks Chromium for a bitmap large enough to kill the page.
225 */
226 export async function shootClip(page: Page, clip: Rect): Promise<string | undefined> {
227 // Chromium rejects a clip with a negative origin outright; clamp and keep what there is.
228 const x = Math.max(0, clip.x)
229 const y = Math.max(0, clip.y)
230 const w = clip.w - (x - clip.x)
231 const h = clip.h - (y - clip.y)
232 if (w <= 0 || h <= 0)
233 return undefined
234 try {
235 const scrollY = await page.evaluate((top) => {
236 window.scrollTo(0, top)
237 return window.scrollY
238 }, Math.max(0, y - 1))
239 const buffer = await page.screenshot({
240 clip: {
241 x,
242 y: y - scrollY,
243 width: w,
244 height: h,
245 },
246 omitBackground: true,
247 timeout: 10_000,
248 })
249 return `data:image/png;base64,${buffer.toString('base64')}`
250 }
251 catch {
252 return undefined
253 }
254 }
255
256 /**
257 * Whether a data URI can be embedded as-is. pptxgenjs needs `image/<type>;base64,` and
258 * emits nothing for a URL-encoded data URI; SVG is rasterized on this path regardless.
259 * Both fall through to a screenshot.
260 */
261 export function isUsableDataUri(url: string): boolean {
262 return /^data:image\/(?!svg\+xml)[\w.+-]+;base64,/.test(url)
263 }
264
265 /**
266 * Fetch an image through `APIRequestContext`, which is not subject to CORS;
267 * the in-page route, `canvas.toDataURL()`, throws on a cross-origin image.
268 */
269 async function fetchImage(page: Page, url: string): Promise<string | undefined> {
270 if (url.startsWith('data:')) {
271 return isUsableDataUri(url)
272 ? url
273 : undefined
274 }
275 try {
276 const response = await page.context().request.get(url, { timeout: 15_000 })
277 if (!response.ok())
278 return undefined
279 const type = response.headers()['content-type']?.split(';')[0] ?? 'image/png'
280 // pptxgenjs writes a broken raster fallback for SVG from Node; let the
281 // caller screenshot the element instead.
282 if (type.includes('svg'))
283 return undefined
284 const body = await response.body()
285 return `data:${type};base64,${Buffer.from(body).toString('base64')}`
286 }
287 catch {
288 return undefined
289 }
290 }
291
292 export interface CaptureReport {
293 rastersCaptured: number
294 rastersFailed: number
295 imagesFetched: number
296 /** Images that could be neither fetched nor screenshotted. */
297 imagesDropped: number
298 /** Captures that asked for isolation and could not find their element. A silent miss bakes the slide's own text into the picture, which is then drawn again as shapes. */
299 isolationMissed: number
300 fallbackSlides: { no: number, reason: string }[]
301 }
302
303 /**
304 * Run every capture through one short, scrollable viewport. Resizing reflows the page,
305 * so it happens once around all of them rather than per capture; boxes are read live
306 * inside this viewport, so they stay consistent with it.
307 */
308 async function throughShortViewport(page: Page, needed: boolean, height: number, fn: () => Promise<void>): Promise<void> {
309 if (!needed) {
310 await fn()
311 return
312 }
313 const viewport = page.viewportSize()
314 try {
315 if (viewport && viewport.height > height)
316 await page.setViewportSize({ width: viewport.width, height })
317 await fn()
318 }
319 finally {
320 if (viewport)
321 await page.setViewportSize(viewport)
322 await page.evaluate(() => window.scrollTo(0, 0))
323 }
324 }
325
326 /** Fill in every picture the IR asked for, and shoot whole-slide fallbacks. Mutates `slides` in place. */
327 export async function capture(
328 page: Page,
329 slides: SlideIr[],
330 requests: RasterRequest[],
331 ): Promise<CaptureReport> {
332 const report: CaptureReport = {
333 rastersCaptured: 0,
334 rastersFailed: 0,
335 imagesFetched: 0,
336 imagesDropped: 0,
337 isolationMissed: 0,
338 fallbackSlides: [],
339 }
340
341 await installRootFinder(page)
342
343 const rasterBySource = new Map<number, IrRaster[]>()
344 const imagesBySource = new Map<number, IrImage[]>()
345 for (const slide of slides) {
346 for (const node of slide.nodes) {
347 if (node.kind === 'raster') {
348 const list = rasterBySource.get(node.sourceId) ?? []
349 list.push(node)
350 rasterBySource.set(node.sourceId, list)
351 }
352 else if (node.kind === 'image') {
353 const list = imagesBySource.get(node.sourceId) ?? []
354 list.push(node)
355 imagesBySource.set(node.sourceId, list)
356 }
357 }
358 }
359
360 const fulfil = async (request: RasterRequest): Promise<void> => {
361 let data: string | undefined
362 try {
363 if (request.isolate && !(await isolate(page, request.isolateId ?? request.sourceId, request.hideDescendants)))
364 report.isolationMissed++
365 // A pseudo-element has no element to point at; clip the page to the box
366 // the walker computed for it instead.
367 data = request.clip
368 ? await shootClip(page, request.clip)
369 : await shoot(page, `[${ID_ATTRIBUTE}="${request.sourceId}"]`)
370 }
371 catch {
372 data = undefined
373 }
374 finally {
375 if (request.isolate)
376 await restore(page)
377 }
378
379 for (const node of rasterBySource.get(request.sourceId) ?? []) {
380 if (data) {
381 node.data = data
382 report.rastersCaptured++
383 }
384 else {
385 report.rastersFailed++
386 }
387 }
388 }
389
390 const viewportHeight = clipViewportHeight(slides, requests)
391
392 await throughShortViewport(page, !!requests.length || !!imagesBySource.size, viewportHeight, async () => {
393 for (const request of requests)
394 await fulfil(request)
395
396 for (const [sourceId, nodes] of imagesBySource) {
397 let data = await fetchImage(page, nodes[0].data)
398 if (data) {
399 report.imagesFetched++
400 }
401 else {
402 // Unfetchable, or an SVG: screenshot the element instead, isolated so
403 // the picture does not carry what the slide painted behind it.
404 try {
405 if (!(await isolate(page, sourceId, false)))
406 report.isolationMissed++
407 // Once per element, not once per node it produced across click steps.
408 data = await shoot(page, `[${ID_ATTRIBUTE}="${sourceId}"]`)
409 if (data)
410 report.imagesFetched++
411 }
412 finally {
413 await restore(page)
414 }
415 }
416 if (!data)
417 continue
418 for (const node of nodes)
419 node.data = data
420 }
421 })
422
423 // Anything without real image data would reach pptxgenjs as a bare URL or
424 // an empty string, which it rejects on stderr while writing nothing.
425 for (const slide of slides) {
426 slide.nodes = slide.nodes.filter((node) => {
427 if (node.kind === 'raster')
428 return !!node.data
429 if (node.kind === 'image' && !node.data.startsWith('data:')) {
430 report.imagesDropped++
431 return false
432 }
433 return true
434 })
435 }
436
437 await throughShortViewport(page, slides.some(slide => !!slide.fallbackReason), viewportHeight, async () => {
438 for (const slide of slides) {
439 if (!slide.fallbackReason)
440 continue
441 // The exact container id: a prefix match plus `.first()` hands every
442 // click step of a slide the picture of step one.
443 const shot = await shoot(page, `[id="${slide.containerId}"]`)
444 if (shot) {
445 slide.fallbackPng = shot
446 report.fallbackSlides.push({ no: slide.no, reason: slide.fallbackReason })
447 }
448 else {
449 // Screenshot failed too. The slide keeps its shapes, but `normalize`
450 // withheld its raster requests, so keep the warning and clear the reason.
451 report.fallbackSlides.push({
452 no: slide.no,
453 reason: `${slide.fallbackReason}, and the replacement screenshot failed, so the slide is incomplete`,
454 })
455 slide.fallbackReason = undefined
456 }
457 }
458 })
459
460 return report
461 }
462
462 lines TYPESCRIPT