figdriver 0.0.0-stage → 0.4.0

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.
@@ -0,0 +1,999 @@
1
+ import { parseColor } from "../core/css";
2
+ import { assetSlug, titleCase } from "../core/naming";
3
+ import {
4
+ BLOCK_LEVEL,
5
+ messageOf,
6
+ round,
7
+ selectorOf,
8
+ truncateList,
9
+ withoutImages,
10
+ type Asset,
11
+ type Box,
12
+ type Capture,
13
+ type El,
14
+ type Pseudo,
15
+ type Run,
16
+ type Style,
17
+ type Vars,
18
+ } from "../core/snapshot";
19
+
20
+ declare global {
21
+ interface HTMLMediaElement {
22
+ /** Chromium's live stream of what the element plays. */
23
+ captureStream(): MediaStream;
24
+ }
25
+ }
26
+
27
+ const px = (v: string) => parseFloat(v) || 0;
28
+ const boxOf = (r: DOMRect): Box => [round(r.x + scrollX), round(r.y + scrollY), round(r.width), round(r.height)];
29
+ const transparent = (c: string) => (parseColor(c)?.a ?? 1) === 0;
30
+ const PHRASING = /^(EM|STRONG|SPAN|B|I|SMALL|MARK|SUB|SUP|CODE|U|S)$/;
31
+ const BG_URL = /url\("?([^")]+)"?\)/g;
32
+
33
+ /** Color and style of the first side that draws, since a one-sided border leaves the others at currentColor. */
34
+ function borderPaint(cs: CSSStyleDeclaration) {
35
+ const side = (["Top", "Right", "Bottom", "Left"] as const).find((s) => px(cs[`border${s}Width`]) > 0) ?? "Top";
36
+
37
+ return { borderColor: cs[`border${side}Color`], borderStyle: cs[`border${side}Style`] };
38
+ }
39
+
40
+ function styleOf(cs: CSSStyleDeclaration, w: number, h: number): Style {
41
+ const corner = (v: string) => {
42
+ const [x, y = x] = v.split(" ");
43
+
44
+ return x.endsWith("%") ? Math.min(w * px(x), h * px(y)) / 100 : px(x);
45
+ };
46
+
47
+ return {
48
+ display: cs.display,
49
+ position: cs.position,
50
+ zIndex: cs.zIndex,
51
+ flexDirection: cs.flexDirection,
52
+ flexWrap: cs.flexWrap,
53
+ justify: cs.justifyContent,
54
+ align: cs.alignItems,
55
+ alignSelf: cs.alignSelf,
56
+ flexGrow: cs.flexGrow,
57
+ gap: [px(cs.rowGap), px(cs.columnGap)],
58
+ pad: [px(cs.paddingTop), px(cs.paddingRight), px(cs.paddingBottom), px(cs.paddingLeft)],
59
+ margin: [px(cs.marginTop), px(cs.marginRight), px(cs.marginBottom), px(cs.marginLeft)],
60
+ maxWidth: cs.maxWidth,
61
+ gridCols: cs.gridTemplateColumns,
62
+ gridRows: cs.gridTemplateRows,
63
+ textAlign: cs.textAlign,
64
+ bg: cs.backgroundColor,
65
+ bgImage: cs.backgroundImage,
66
+ bgSize: cs.backgroundSize,
67
+ bgPos: cs.backgroundPosition,
68
+ radius: [
69
+ corner(cs.borderTopLeftRadius),
70
+ corner(cs.borderTopRightRadius),
71
+ corner(cs.borderBottomRightRadius),
72
+ corner(cs.borderBottomLeftRadius),
73
+ ],
74
+ border: [px(cs.borderTopWidth), px(cs.borderRightWidth), px(cs.borderBottomWidth), px(cs.borderLeftWidth)],
75
+ ...borderPaint(cs),
76
+ shadow: cs.boxShadow,
77
+ opacity: px(cs.opacity),
78
+ overflow: cs.overflow,
79
+ transform: cs.transform,
80
+ backdrop: cs.backdropFilter,
81
+ objectFit: cs.objectFit,
82
+ filter: cs.filter === "none" ? undefined : cs.filter,
83
+ mixBlendMode: cs.mixBlendMode === "normal" ? undefined : cs.mixBlendMode,
84
+ };
85
+ }
86
+
87
+ const paints = (s: Style) =>
88
+ !transparent(s.bg) ||
89
+ s.bgImage !== "none" ||
90
+ s.border.some((b) => b > 0) ||
91
+ s.shadow !== "none" ||
92
+ s.backdrop !== "none";
93
+
94
+ const inlineStyle = (parent: Style): Style => ({
95
+ ...parent,
96
+ display: "inline",
97
+ position: "static",
98
+ flexGrow: "0",
99
+ maxWidth: "none",
100
+ pad: [0, 0, 0, 0],
101
+ margin: [0, 0, 0, 0],
102
+ bg: "rgba(0, 0, 0, 0)",
103
+ bgImage: "none",
104
+ border: [0, 0, 0, 0],
105
+ shadow: "none",
106
+ backdrop: "none",
107
+ transform: "none",
108
+ opacity: 1,
109
+ filter: undefined,
110
+ mixBlendMode: undefined,
111
+ });
112
+
113
+ /** `at` is the element the text sits in, for the link around it. */
114
+ function runOf(text: string, cs: CSSStyleDeclaration, at?: Element | null): Run {
115
+ const size = px(cs.fontSize);
116
+ const link = at?.closest("a[href]");
117
+
118
+ return {
119
+ text,
120
+ size,
121
+ weight: px(cs.fontWeight),
122
+ lineHeight: px(cs.lineHeight) || round(size * 1.2),
123
+ letterSpacing: px(cs.letterSpacing),
124
+ color: cs.color,
125
+ upper: cs.textTransform === "uppercase",
126
+ underline: cs.textDecorationLine.includes("underline"),
127
+ italic: cs.fontStyle === "italic",
128
+ fontFamily:
129
+ cs.fontFamily
130
+ .split(",")[0]
131
+ .trim()
132
+ .replace(/^["']|["']$/g, "") || undefined,
133
+ strike: cs.textDecorationLine.includes("line-through") || undefined,
134
+ href: link instanceof HTMLAnchorElement && link.href ? link.href : undefined,
135
+ };
136
+ }
137
+
138
+ function hasPseudoText(cs: CSSStyleDeclaration) {
139
+ if (cs.display === "none") return false;
140
+ const raw = cs.content.trim();
141
+
142
+ if (raw.length < 2) return false;
143
+ const quote = raw[0];
144
+
145
+ if ((quote !== '"' && quote !== "'") || raw[raw.length - 1] !== quote) return false;
146
+
147
+ return raw.slice(1, -1).replace(/\\(.)/g, "$1").trim().length > 0;
148
+ }
149
+
150
+ function pseudoOf(cs: CSSStyleDeclaration, which: Pseudo["which"], box: Box, host: Style): Pseudo | undefined {
151
+ if (cs.content === "none" || cs.content === "normal" || cs.display === "none") return;
152
+ const m = cs.transform.match(/^matrix\(([^,]+), [^,]+, [^,]+, ([^,]+),/);
153
+
154
+ if (m && (px(m[1]) === 0 || px(m[2]) === 0)) return;
155
+ const [w, h] = [px(cs.width), px(cs.height)];
156
+ const style = styleOf(cs, w, h);
157
+
158
+ if (!paints(style) || !w || !h) return;
159
+ const flow = cs.position === "static" || cs.position === "relative";
160
+ const [x, y, bw, bh] = box;
161
+ const [pt, pr, pb, pl] = host.pad.map((p, i) => p + host.border[i]);
162
+ const row = !host.display.includes("flex") || !host.flexDirection.startsWith("column");
163
+ const centered = host.align === "center";
164
+ let at: [number, number];
165
+
166
+ if (!flow) at = [x + host.border[3] + px(cs.left), y + host.border[0] + px(cs.top)];
167
+ else if (which === "before") at = [x + pl, centered && row ? y + pt + (bh - pt - pb - h) / 2 : y + pt];
168
+ else at = row ? [x + bw - pr - w, centered ? y + pt + (bh - pt - pb - h) / 2 : y + pt] : [x + pl, y + bh - pb - h];
169
+
170
+ return { which, flow, style, box: [round(at[0]), round(at[1]), w, h] };
171
+ }
172
+
173
+ /** An element that draws pixels instead of boxes, captured as an image. */
174
+ const isPicture = (e: Element) =>
175
+ e instanceof HTMLImageElement || e instanceof HTMLCanvasElement || e instanceof HTMLVideoElement;
176
+
177
+ const isVisible = (e: Element, cs: CSSStyleDeclaration) =>
178
+ cs.display !== "none" &&
179
+ cs.visibility !== "hidden" &&
180
+ px(cs.opacity) > 0 &&
181
+ (e.getClientRects().length > 0 || cs.display === "contents" || cs.position === "absolute" || cs.position === "fixed");
182
+
183
+ /**
184
+ * Text that paints nothing itself: plain text, <br>, and unpainted inline or phrasing elements around them.
185
+ * A flex or grid container only qualifies with bare text, because its element children are layout items.
186
+ */
187
+ function isTextLeaf(e: Element): boolean {
188
+ const layout = /flex|grid/.test(getComputedStyle(e).display);
189
+
190
+ return [...e.childNodes].every((c) => {
191
+ if (c.nodeType === Node.TEXT_NODE) return true;
192
+
193
+ if (!(c instanceof HTMLElement) || isPicture(c)) return false;
194
+
195
+ if (c.tagName === "BR") return true;
196
+ const cs = getComputedStyle(c);
197
+
198
+ if (!isVisible(c, cs)) return true;
199
+
200
+ if (layout || !(cs.display === "inline" || cs.display === "contents" || PHRASING.test(c.tagName))) return false;
201
+
202
+ return !paints(styleOf(cs, 0, 0)) && cs.paddingLeft === "0px" && cs.paddingTop === "0px" && isTextLeaf(c);
203
+ });
204
+ }
205
+
206
+ function runsOf(e: Element): Run[] {
207
+ const out: Run[] = [];
208
+
209
+ const push = (r: Run) => {
210
+ const prev = out[out.length - 1];
211
+ let text = r.text;
212
+
213
+ if (!prev || /\s$/.test(prev.text)) text = text.replace(/^ +/, "");
214
+
215
+ if (text === "\n" && prev) prev.text = prev.text.replace(/ +$/, "");
216
+
217
+ if (text) out.push({ ...r, text });
218
+ };
219
+
220
+ const walk = (n: Node) => {
221
+ if (n.nodeType === Node.TEXT_NODE) {
222
+ const text = (n.textContent ?? "").replace(/\s+/g, " ");
223
+
224
+ if (text) push(runOf(text, getComputedStyle(n.parentElement!), n.parentElement));
225
+ } else if (n instanceof HTMLElement) {
226
+ const cs = getComputedStyle(n);
227
+
228
+ if (n.tagName !== "BR" && !isVisible(n, cs)) return;
229
+ const block = n.tagName === "BR" || BLOCK_LEVEL.test(cs.display);
230
+
231
+ if (block && out.length) push({ ...out[out.length - 1], text: "\n" });
232
+
233
+ if (n.tagName !== "BR") n.childNodes.forEach(walk);
234
+ }
235
+ };
236
+
237
+ e.childNodes.forEach(walk);
238
+
239
+ if (!out.length) return [];
240
+ const last = out[out.length - 1];
241
+ last.text = last.text.replace(/\s+$/, "");
242
+
243
+ return out.filter((r) => r.text);
244
+ }
245
+
246
+ function textChild(t: Text, parent: Style, cs: CSSStyleDeclaration): El {
247
+ const range = document.createRange();
248
+ range.selectNodeContents(t);
249
+ const box = boxOf(range.getBoundingClientRect());
250
+
251
+ return {
252
+ kind: "text",
253
+ tag: "#text",
254
+ cls: [],
255
+ box,
256
+ content: box,
257
+ style: inlineStyle(parent),
258
+ runs: [runOf((t.textContent ?? "").trim().replace(/\s+/g, " "), cs, t.parentElement)],
259
+ };
260
+ }
261
+
262
+ function measureFieldText(
263
+ e: HTMLInputElement | HTMLTextAreaElement,
264
+ box: Box,
265
+ style: Style,
266
+ cs: CSSStyleDeclaration,
267
+ ): El[] {
268
+ const shown = e.value ? (e.type === "password" ? "•".repeat(e.value.length) : e.value) : e.placeholder;
269
+
270
+ if (!shown) return [];
271
+ const runCs = e.value ? cs : getComputedStyle(e, "::placeholder");
272
+ const run = runOf(shown, runCs, e);
273
+ const left = px(cs.paddingLeft) + px(cs.borderLeftWidth);
274
+ const right = px(cs.paddingRight) + px(cs.borderRightWidth);
275
+ const width = box[2] - left - right;
276
+
277
+ let content: Box = [
278
+ round(box[0] + left),
279
+ round(box[1] + (box[3] - run.lineHeight) / 2),
280
+ round(width),
281
+ run.lineHeight,
282
+ ];
283
+
284
+ if (e instanceof HTMLTextAreaElement) {
285
+ // A textarea wraps from its top padding, so measure the wrapped height in a hidden copy at the same width and font.
286
+ const mirror = document.createElement("div");
287
+ Object.assign(mirror.style, {
288
+ position: "absolute",
289
+ visibility: "hidden",
290
+ whiteSpace: "pre-wrap",
291
+ width: `${width}px`,
292
+ font: runCs.font,
293
+ lineHeight: runCs.lineHeight,
294
+ letterSpacing: runCs.letterSpacing,
295
+ });
296
+ mirror.textContent = shown;
297
+ document.body.append(mirror);
298
+ const height = mirror.getBoundingClientRect().height;
299
+ mirror.remove();
300
+ content = [
301
+ round(box[0] + left),
302
+ round(box[1] + px(cs.paddingTop) + px(cs.borderTopWidth)),
303
+ round(width),
304
+ round(height),
305
+ ];
306
+ }
307
+
308
+ return [{ kind: "text", tag: "#text", cls: [], box: content, content, style: inlineStyle(style), runs: [run] }];
309
+ }
310
+
311
+ function serializeSvg(e: SVGSVGElement, box: Box, cs: CSSStyleDeclaration) {
312
+ // SAFETY: a node's clone is an element of the node's own class.
313
+ const clone = e.cloneNode(true) as SVGSVGElement;
314
+ clone.setAttribute("width", String(box[2]));
315
+ clone.setAttribute("height", String(box[3]));
316
+ const sources = e.querySelectorAll("*");
317
+ clone.querySelectorAll("*").forEach((c, i) => {
318
+ const ccs = getComputedStyle(sources[i]);
319
+
320
+ for (const a of ["stroke", "fill"] as const) {
321
+ if (c.getAttribute(a) === "currentColor" || c.getAttribute(a) == null) c.setAttribute(a, ccs[a]);
322
+ }
323
+ });
324
+
325
+ return clone.outerHTML.replace(/currentColor/g, cs.color);
326
+ }
327
+
328
+ /** Resolves once `e` fires `ready` or `error`, or after 8s. */
329
+ const settled = (e: HTMLElement, ready: string) =>
330
+ new Promise<void>((resolve) => {
331
+ const done = () => {
332
+ clearTimeout(timer);
333
+ e.removeEventListener(ready, done);
334
+ e.removeEventListener("error", done);
335
+ resolve();
336
+ };
337
+
338
+ const timer = setTimeout(done, 8000);
339
+ e.addEventListener(ready, done, { once: true });
340
+ e.addEventListener("error", done, { once: true });
341
+ });
342
+
343
+ async function waitForPageMedia() {
344
+ for (const img of document.images) img.loading = "eager";
345
+ await Promise.all([
346
+ ...[...document.images].flatMap((i) => (i.complete && i.naturalWidth ? [] : [settled(i, "load")])),
347
+ // A background video autoplays, and its first frame is what the page shows.
348
+ ...[...document.querySelectorAll("video")].flatMap((v) =>
349
+ v.autoplay && v.readyState < HTMLMediaElement.HAVE_CURRENT_DATA ? [settled(v, "loadeddata")] : [],
350
+ ),
351
+ ]);
352
+ await document.fonts.ready;
353
+ scrollTo(0, 0);
354
+ }
355
+
356
+ function collectRootTokens() {
357
+ const tokens: Record<string, string> = {};
358
+
359
+ for (const sheet of document.styleSheets) {
360
+ let rules: CSSRuleList;
361
+
362
+ try {
363
+ rules = sheet.cssRules;
364
+ } catch {
365
+ continue; // Cross-origin sheets, such as web font CSS, refuse reads and hold no tokens of the page's own.
366
+ }
367
+
368
+ for (const rule of rules) {
369
+ if (!(rule instanceof CSSStyleRule) || !rule.selectorText.startsWith(":root")) continue;
370
+
371
+ for (const p of rule.style)
372
+ if (p.startsWith("--") && !p.startsWith("--tw")) tokens[p.slice(2)] = rule.style.getPropertyValue(p).trim();
373
+ }
374
+ }
375
+
376
+ return tokens;
377
+ }
378
+
379
+ const THEME_SELECTOR = /^(?::root|html|body)?(?:\[data-theme=["']?([\w-]+)["']?\]|\.(dark))$/;
380
+
381
+ /**
382
+ * Token overrides by color mode: `[data-theme="x"]` and `.dark` rules, and `:root` rules inside `prefers-color-scheme: dark`. The page's
383
+ * `:root` tokens are the light mode, so a `light` theme adds nothing.
384
+ */
385
+ function collectThemes() {
386
+ const themes: Record<string, Record<string, string>> = {};
387
+
388
+ const add = (theme: string, style: CSSStyleDeclaration) => {
389
+ if (/^light$/i.test(theme)) return;
390
+ const mode = (themes[titleCase(theme)] ??= {});
391
+
392
+ for (const p of style)
393
+ if (p.startsWith("--") && !p.startsWith("--tw")) mode[p.slice(2)] = style.getPropertyValue(p).trim();
394
+ };
395
+
396
+ const visit = (rules: CSSRuleList, dark: boolean) => {
397
+ for (const rule of rules) {
398
+ if (rule instanceof CSSMediaRule)
399
+ visit(rule.cssRules, dark || /prefers-color-scheme:\s*dark/.test(rule.conditionText));
400
+ else if (rule instanceof CSSStyleRule) {
401
+ const selectors = rule.selectorText.split(",").map((s) => s.trim());
402
+ const theme = selectors.map((s) => s.match(THEME_SELECTOR)).find(Boolean);
403
+
404
+ if (theme) add(theme[1] ?? theme[2], rule.style);
405
+ else if (dark && selectors.some((s) => /^(:root|html)$/.test(s))) add("dark", rule.style);
406
+ } else if (rule instanceof CSSGroupingRule) visit(rule.cssRules, dark);
407
+ }
408
+ };
409
+
410
+ for (const sheet of document.styleSheets) {
411
+ try {
412
+ visit(sheet.cssRules, false);
413
+ } catch {
414
+ continue; // Cross-origin sheets refuse reads, as in collectRootTokens.
415
+ }
416
+ }
417
+
418
+ return themes;
419
+ }
420
+
421
+ const collectBgImages = (bgImage: string, assetName: (url: string) => string) =>
422
+ [...bgImage.matchAll(BG_URL)].map((m) => assetName(m[1]));
423
+
424
+ type Raster = { blob: Blob; size: [number, number] };
425
+
426
+ /**
427
+ * Where an asset comes from: `url` names it in the snapshot and in warnings, and `read` gives its bytes, or nothing when there is
428
+ * nothing to add, such as a clip of a canvas that never moves.
429
+ */
430
+ type Source = { url: string; read: () => Promise<Raster | undefined>; retryWithMotion?: boolean };
431
+
432
+ /** Videos, canvas clips, and stills deferred until motion is back on, read in a second step by `designClips()`. */
433
+ const clips = new Map<string, Source>();
434
+
435
+ class BlankCanvasError extends Error {}
436
+
437
+ /** Reads every source at once, so recorded clips overlap instead of adding up. */
438
+ async function fetchAssets(sources: Map<string, Source>, deferBlank = false) {
439
+ const assets: Record<string, Asset> = {};
440
+ const bytes: Record<string, string> = {};
441
+ const skipped: { url: string; reason: string }[] = [];
442
+
443
+ const read = await Promise.all(
444
+ [...sources].map(
445
+ async ([name, source]): Promise<{
446
+ name: string;
447
+ source: Source;
448
+ raster?: Raster;
449
+ reason?: string;
450
+ deferred?: boolean;
451
+ }> => {
452
+ try {
453
+ return { name, source, raster: await source.read() };
454
+ } catch (e) {
455
+ if (deferBlank && source.retryWithMotion && e instanceof BlankCanvasError)
456
+ return { name, source, deferred: true };
457
+
458
+ return { name, source, reason: messageOf(e) };
459
+ }
460
+ },
461
+ ),
462
+ );
463
+
464
+ for (const r of read) {
465
+ if (r.deferred) {
466
+ clips.set(r.name, r.source);
467
+ continue;
468
+ }
469
+
470
+ if (r.reason) skipped.push({ url: r.source.url, reason: r.reason });
471
+
472
+ if (!r.raster) continue;
473
+ const { blob, size } = r.raster;
474
+ const buf = new Uint8Array(await blob.arrayBuffer());
475
+ let s = "";
476
+
477
+ for (let i = 0; i < buf.length; i += 0x8000) s += String.fromCharCode(...buf.subarray(i, i + 0x8000));
478
+ bytes[r.name] = btoa(s);
479
+ assets[r.name] = { url: r.source.url, mime: blob.type.split(";")[0], size };
480
+ }
481
+
482
+ return { assets, bytes, skipped };
483
+ }
484
+
485
+ async function capture(): Promise<Capture> {
486
+ await waitForPageMedia();
487
+ const tokens = collectRootTokens();
488
+ const themes = collectThemes();
489
+ const sources = new Map<string, Source>();
490
+ const named = new Map<string | Element, string>();
491
+ const namedVideos = new Map<string | Element, string>();
492
+ const clipForStill = new Map<string, string>();
493
+ const takenAssetNames = new Set<string>();
494
+
495
+ /**
496
+ * The asset name for `key`, a URL or a canvas or video element, made once so the second walk in recordVars reuses it. A clip
497
+ * waits for `designClips()`.
498
+ */
499
+ const nameOf = (key: string | Element, slug: string, source: Source, into = sources, registry = named) => {
500
+ const known = registry.get(key);
501
+
502
+ if (known !== undefined) return known;
503
+ const name = assetSlug(slug, takenAssetNames);
504
+ takenAssetNames.add(name);
505
+ into.set(name, source);
506
+ registry.set(key, name);
507
+
508
+ return name;
509
+ };
510
+
511
+ const assetName = (url: string) => nameOf(url, url, { url, read: () => imageOf(url) });
512
+
513
+ /** The still an image shows, and for a video or a canvas the video Figma can play in its place. */
514
+ const pictureOf = (e: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, selector: string) => {
515
+ if (e instanceof HTMLImageElement) return { image: assetName(e.currentSrc) };
516
+ const tag = e.tagName.toLowerCase();
517
+
518
+ // A video with no frame loaded yet shows its poster.
519
+ const image =
520
+ e instanceof HTMLVideoElement && e.readyState < HTMLMediaElement.HAVE_CURRENT_DATA && e.poster
521
+ ? assetName(e.poster)
522
+ : nameOf(e, tag, {
523
+ url: selector,
524
+ read: () => stillOf(e),
525
+ retryWithMotion: e instanceof HTMLCanvasElement,
526
+ });
527
+
528
+ const videoKey = e instanceof HTMLVideoElement && e.currentSrc ? e.currentSrc : e;
529
+ const videoSlug = e instanceof HTMLVideoElement && e.currentSrc ? e.currentSrc : `${tag}-video`;
530
+
531
+ const video = nameOf(
532
+ videoKey,
533
+ videoSlug,
534
+ {
535
+ url: e instanceof HTMLVideoElement ? e.currentSrc || selector : selector,
536
+ async read() {
537
+ try {
538
+ return await (e instanceof HTMLVideoElement ? videoOf(e) : clipOf(e));
539
+ } catch (err) {
540
+ throw new Error(`${messageOf(err)}, so its still frame stands in`);
541
+ }
542
+ },
543
+ },
544
+ clips,
545
+ namedVideos,
546
+ );
547
+
548
+ clipForStill.set(video, image);
549
+
550
+ return { image, video };
551
+ };
552
+
553
+ const pseudoTextHosts = new Set<string>();
554
+ let recordNotes = true;
555
+
556
+ const captureElement = (e: Element): El | undefined => {
557
+ if (e.tagName === "BR") return;
558
+ const cs = getComputedStyle(e);
559
+
560
+ if (!isVisible(e, cs)) return;
561
+ const box = boxOf(e.getBoundingClientRect());
562
+ const style = styleOf(cs, box[2], box[3]);
563
+
564
+ const base = {
565
+ tag: e.tagName.toLowerCase(),
566
+ cls: [...e.classList],
567
+ box,
568
+ style,
569
+ label: e.getAttribute("aria-label") ?? e.getAttribute("alt") ?? undefined,
570
+ };
571
+
572
+ if (isPicture(e)) return { ...base, kind: "image", ...pictureOf(e, selectorOf(base)) };
573
+
574
+ if (e instanceof SVGSVGElement) return { ...base, kind: "svg", svg: serializeSvg(e, box, cs) };
575
+
576
+ if (e instanceof HTMLInputElement || e instanceof HTMLTextAreaElement) {
577
+ return { ...base, kind: "frame", children: measureFieldText(e, box, style, cs), pseudos: [], bgImages: [] };
578
+ }
579
+
580
+ const pseudoStyles = (["before", "after"] as const).map((w) => [w, getComputedStyle(e, `::${w}`)] as const);
581
+
582
+ if (recordNotes) {
583
+ for (const [w, pcs] of pseudoStyles) {
584
+ if (hasPseudoText(pcs)) pseudoTextHosts.add(`${selectorOf(base)}::${w}`);
585
+ }
586
+ }
587
+
588
+ const pseudos = pseudoStyles.flatMap(([w, pcs]) => pseudoOf(pcs, w, box, style) ?? []);
589
+
590
+ if (e.textContent?.trim() && isTextLeaf(e)) {
591
+ const bare = !paints(style) && !pseudos.length && style.pad.every((p) => p === 0);
592
+
593
+ const hasMixedInlineText = [...e.childNodes].some(
594
+ (c) =>
595
+ (c.nodeType === Node.TEXT_NODE && c.textContent?.trim()) || (c instanceof HTMLElement && c.tagName === "BR"),
596
+ );
597
+
598
+ if (bare || hasMixedInlineText) {
599
+ const runs = runsOf(e);
600
+
601
+ if (runs.length) {
602
+ const range = document.createRange();
603
+ range.selectNodeContents(e);
604
+ const content = boxOf(range.getBoundingClientRect());
605
+
606
+ if (bare) return { ...base, kind: "text", runs, content };
607
+
608
+ // Keep text + <br>/phrasing as one text child inside painted or padded containers so grids and flex boxes never collide on split text nodes.
609
+ const text: El = {
610
+ kind: "text",
611
+ tag: "#text",
612
+ cls: [],
613
+ box: content,
614
+ content,
615
+ style: inlineStyle(style),
616
+ runs,
617
+ };
618
+
619
+ return {
620
+ ...base,
621
+ kind: "frame",
622
+ children: [text],
623
+ pseudos,
624
+ bgImages: collectBgImages(style.bgImage, assetName),
625
+ };
626
+ }
627
+ }
628
+ }
629
+
630
+ const children: El[] = [];
631
+
632
+ const appendChildren = (host: Element, parentStyle: Style, parentCs: CSSStyleDeclaration) => {
633
+ for (const c of host.childNodes) {
634
+ if (c instanceof Element) {
635
+ const ccs = getComputedStyle(c);
636
+
637
+ if (ccs.display === "contents") {
638
+ if (ccs.visibility !== "hidden") appendChildren(c, parentStyle, ccs);
639
+ continue;
640
+ }
641
+
642
+ const k = captureElement(c);
643
+
644
+ if (k) children.push(k);
645
+ } else if (c instanceof Text && c.textContent?.trim()) children.push(textChild(c, parentStyle, parentCs));
646
+ }
647
+ };
648
+
649
+ appendChildren(e, style, cs);
650
+
651
+ return { ...base, kind: "frame", children, pseudos, bgImages: collectBgImages(style.bgImage, assetName) };
652
+ };
653
+
654
+ const root = captureElement(document.body)!;
655
+ recordNotes = false;
656
+ recordVars(root, Object.keys(tokens), () => captureElement(document.body)!);
657
+ const { assets, bytes, skipped } = await fetchAssets(sources, true);
658
+
659
+ // Drop queued clips whose still permanently failed, so Phase 2 never records orphan videos.
660
+ for (const [video, still] of clipForStill) if (!assets[still] && !clips.has(still)) clips.delete(video);
661
+
662
+ const snapshot = {
663
+ url: location.href,
664
+ viewport: [innerWidth, document.documentElement.scrollHeight] satisfies [number, number],
665
+ tokens,
666
+ // A clip or motion-deferred still stays for now: the CLI drops the ones `designClips()` cannot read.
667
+ root: withoutImages(root, (name) => !assets[name] && !clips.has(name)),
668
+ assets,
669
+ themes: Object.keys(themes).length ? themes : undefined,
670
+ };
671
+
672
+ const notes = pseudoTextHosts.size
673
+ ? [
674
+ `Pseudo-element text content is dropped (put the text in a real element instead): ${truncateList([...pseudoTextHosts], 8)}`,
675
+ ]
676
+ : [];
677
+
678
+ return { snapshot, bytes, skipped, notes, hasClips: clips.size > 0 };
679
+ }
680
+
681
+ function recordVars(root: El, names: string[], walk: () => El) {
682
+ const probe = document.body.appendChild(document.createElement("i"));
683
+ const rootStyle = getComputedStyle(document.documentElement);
684
+ const byValue = new Map<string, string[]>();
685
+
686
+ for (const name of names) {
687
+ const value = rootStyle.getPropertyValue(`--${name}`).trim();
688
+ probe.style.color = "";
689
+ probe.style.color = /^(inherit|initial|unset|revert|revert-layer|currentcolor)$/i.test(value) ? "" : value;
690
+ const color = getComputedStyle(probe).color;
691
+
692
+ if (probe.style.color && !/rgba|\//.test(color)) byValue.set(color, [...(byValue.get(color) ?? []), name]);
693
+ }
694
+
695
+ probe.remove();
696
+ const shared = [...byValue.values()].filter((n) => n.length > 1).flat();
697
+
698
+ if (!shared.length) return;
699
+
700
+ const sentinel = (i: number) => `rgb(${1 + (i >> 8)}, ${i & 255}, 253)`;
701
+ const tokenOf = new Map(shared.map((n, i) => [sentinel(i), n]));
702
+ const style = document.documentElement.style;
703
+ const saved = shared.map((n) => [style.getPropertyValue(`--${n}`), style.getPropertyPriority(`--${n}`)] as const);
704
+
705
+ // Without transitions, so the probe colors apply at once and the real ones come back without animating from them.
706
+ const still = document.head.appendChild(
707
+ Object.assign(document.createElement("style"), {
708
+ textContent: "*, ::before, ::after { transition: none !important; }",
709
+ }),
710
+ );
711
+
712
+ shared.forEach((n, i) => style.setProperty(`--${n}`, sentinel(i), "important"));
713
+ let probed: El;
714
+
715
+ try {
716
+ probed = walk();
717
+ } finally {
718
+ shared.forEach((n, i) => (saved[i][0] ? style.setProperty(`--${n}`, ...saved[i]) : style.removeProperty(`--${n}`)));
719
+ document.documentElement.getBoundingClientRect();
720
+ still.remove();
721
+ }
722
+
723
+ const varsOf = (pairs: [string, string | undefined][]) => {
724
+ const vars: Vars = {};
725
+
726
+ for (const [real, seen] of pairs) {
727
+ const token = seen && tokenOf.get(seen);
728
+
729
+ if (token) vars[real] = real in vars && vars[real] !== token ? "" : token;
730
+ }
731
+
732
+ for (const color in vars) if (!vars[color]) delete vars[color];
733
+
734
+ return Object.keys(vars).length ? vars : undefined;
735
+ };
736
+
737
+ const boxPairs = (a: Style, b: Style): [string, string][] =>
738
+ a.border.some((w) => w > 0)
739
+ ? [
740
+ [a.bg, b.bg],
741
+ [a.borderColor, b.borderColor],
742
+ ]
743
+ : [[a.bg, b.bg]];
744
+
745
+ const colorsIn = (svg: string) =>
746
+ [...svg.matchAll(/ (?:fill|stroke)="([^"]*)"/g)].flatMap(([, v]) =>
747
+ v !== "none" && v !== "transparent" && parseColor(v) ? [v] : [],
748
+ );
749
+
750
+ const zip = (a: El, b: El | undefined) => {
751
+ if (!b || a.kind !== b.kind) return;
752
+ const pairs: [string, string | undefined][] = boxPairs(a.style, b.style);
753
+
754
+ if (a.kind === "text" && b.kind === "text") a.runs.forEach((r, i) => pairs.push([r.color, b.runs[i]?.color]));
755
+
756
+ if (a.kind === "svg" && b.kind === "svg") {
757
+ const seen = colorsIn(b.svg);
758
+ colorsIn(a.svg).forEach((c, i) => pairs.push([c, seen[i]]));
759
+ }
760
+
761
+ const vars = varsOf(pairs);
762
+
763
+ if (vars) a.vars = vars;
764
+
765
+ if (a.kind !== "frame" || b.kind !== "frame") return;
766
+ a.children.forEach((c, i) => zip(c, b.children[i]));
767
+ a.pseudos.forEach((p, i) => {
768
+ const vars = b.pseudos[i] && varsOf(boxPairs(p.style, b.pseudos[i].style));
769
+
770
+ if (vars) p.vars = vars;
771
+ });
772
+ };
773
+
774
+ zip(root, probed);
775
+ }
776
+
777
+ const pngOf = async (canvas: HTMLCanvasElement) => {
778
+ const png = await new Promise<Blob | null>((done) => canvas.toBlob(done, "image/png"));
779
+
780
+ if (!png) throw new Error("the browser could not encode it as PNG");
781
+
782
+ return png;
783
+ };
784
+
785
+ const sizeOf = (e: HTMLCanvasElement | HTMLVideoElement): [number, number] =>
786
+ e instanceof HTMLVideoElement ? [e.videoWidth, e.videoHeight] : [e.width, e.height];
787
+
788
+ /**
789
+ * A copy of what a canvas or video shows now. A WebGL canvas clears after each frame it shows, so the copy happens in a frame
790
+ * callback, which runs after the page's own callback has drawn the next frame.
791
+ */
792
+ async function frameOf(e: HTMLCanvasElement | HTMLVideoElement) {
793
+ const size = sizeOf(e);
794
+
795
+ if (!size[0] || !size[1]) throw new Error("it has no pixels to copy");
796
+ const copy = Object.assign(document.createElement("canvas"), { width: size[0], height: size[1] });
797
+ const context = copy.getContext("2d", { willReadFrequently: true })!;
798
+
799
+ await new Promise<void>((done) => {
800
+ // A tab in the background runs no frame callbacks, so copy anyway after a second.
801
+ const timer = setTimeout(draw, 1000);
802
+ const frame = requestAnimationFrame(draw);
803
+
804
+ function draw() {
805
+ clearTimeout(timer);
806
+ cancelAnimationFrame(frame);
807
+ context.drawImage(e, 0, 0);
808
+ done();
809
+ }
810
+ });
811
+
812
+ return { copy, data: context.getImageData(0, 0, size[0], size[1]).data };
813
+ }
814
+
815
+ /** What a canvas or video shows now, as a PNG. */
816
+ async function pixelsOf(e: HTMLCanvasElement | HTMLVideoElement): Promise<Raster> {
817
+ const { copy, data } = await frameOf(e);
818
+
819
+ if (!data.some((v, i) => i % 4 === 3 && v > 0))
820
+ throw new BlankCanvasError(
821
+ "it read back blank, as a WebGL canvas does once it shows a frame without preserveDrawingBuffer",
822
+ );
823
+
824
+ return { blob: await pngOf(copy), size: sizeOf(e) };
825
+ }
826
+
827
+ /** A canvas or video's still frame, falling back to a video's poster when the video is cross-origin and cannot be read back. */
828
+ async function stillOf(e: HTMLCanvasElement | HTMLVideoElement): Promise<Raster> {
829
+ try {
830
+ return await pixelsOf(e);
831
+ } catch (err) {
832
+ if (e instanceof HTMLVideoElement && e.poster) return imageOf(e.poster);
833
+
834
+ if (err instanceof DOMException && err.name === "SecurityError")
835
+ throw new Error("it is cross-origin and cannot be read back");
836
+
837
+ throw err;
838
+ }
839
+ }
840
+
841
+ // A clip long enough to show a loop or a drift, at a bitrate that keeps it a few MB, since a design bundles its videos.
842
+ const CLIP_SECONDS = 5;
843
+ const MAX_VIDEO_MB = 8;
844
+ const RECORDER_MIMES = ["video/webm;codecs=vp9", "video/webm;codecs=vp8", "video/webm"];
845
+
846
+ const VIDEO_EXT_MIMES = new Map([
847
+ [".mp4", "video/mp4"],
848
+ [".webm", "video/webm"],
849
+ [".mov", "video/quicktime"],
850
+ ]);
851
+
852
+ const checkVideoSize = (bytes: number) => {
853
+ if (bytes > MAX_VIDEO_MB * 2 ** 20)
854
+ throw new Error(`it is ${Math.round(bytes / 2 ** 20)} MB, over the ${MAX_VIDEO_MB} MB a design bundles`);
855
+ };
856
+
857
+ /** `stream` recorded for CLIP_SECONDS as WebM, which Figma plays. */
858
+ async function recorded(stream: MediaStream) {
859
+ try {
860
+ const mimeType = RECORDER_MIMES.find((m) => MediaRecorder.isTypeSupported(m));
861
+
862
+ if (!mimeType) throw new Error("the browser cannot record WebM video");
863
+ const recorder = new MediaRecorder(stream, { mimeType, videoBitsPerSecond: 4_000_000 });
864
+ const chunks: Blob[] = [];
865
+ recorder.ondataavailable = (e) => {
866
+ if (e.data.size) chunks.push(e.data);
867
+ };
868
+
869
+ const stopped = new Promise<void>((done, fail) => {
870
+ recorder.onstop = () => done();
871
+ recorder.onerror = (e) => fail(e.error ?? new Error(e.message || "video recording failed"));
872
+ });
873
+
874
+ recorder.start();
875
+ await new Promise((done) => setTimeout(done, CLIP_SECONDS * 1000));
876
+
877
+ if (recorder.state !== "inactive") recorder.stop();
878
+ await stopped;
879
+ const blob = new Blob(chunks, { type: "video/webm" });
880
+
881
+ if (!blob.size) throw new Error("the recording produced no frames");
882
+ checkVideoSize(blob.size);
883
+
884
+ return blob;
885
+ } finally {
886
+ stream.getTracks().forEach((t) => t.stop());
887
+ }
888
+ }
889
+
890
+ /** The solid color behind `e`: its own or nearest ancestor background that paints, else the white a page starts on. */
891
+ function backdropOf(e: Element) {
892
+ for (let at: Element | null = e; at; at = at.parentElement) {
893
+ const bg = getComputedStyle(at).backgroundColor;
894
+
895
+ if (!transparent(bg)) return bg;
896
+ }
897
+
898
+ return "white";
899
+ }
900
+
901
+ /**
902
+ * A clip of a canvas that moves, which two frames a quarter second apart show. Nothing for a canvas that holds still. Figma may drop
903
+ * a video's alpha, so a canvas with clear pixels records over the color behind it, as the page shows it.
904
+ */
905
+ async function clipOf(c: HTMLCanvasElement): Promise<Raster | undefined> {
906
+ const before = (await frameOf(c)).data;
907
+ await new Promise((done) => setTimeout(done, 250));
908
+ const after = (await frameOf(c)).data;
909
+
910
+ if (before.every((v, i) => v === after[i])) return;
911
+
912
+ if (after.every((v, i) => i % 4 !== 3 || v === 255))
913
+ return { blob: await recorded(c.captureStream(30)), size: sizeOf(c) };
914
+ const flat = Object.assign(document.createElement("canvas"), { width: c.width, height: c.height });
915
+ const context = flat.getContext("2d")!;
916
+ const backdrop = backdropOf(c);
917
+ let live = true;
918
+
919
+ const draw = () => {
920
+ if (!live) return;
921
+ context.fillStyle = backdrop;
922
+ context.fillRect(0, 0, c.width, c.height);
923
+ context.drawImage(c, 0, 0);
924
+ requestAnimationFrame(draw);
925
+ };
926
+
927
+ draw();
928
+
929
+ try {
930
+ return { blob: await recorded(flat.captureStream(30)), size: sizeOf(c) };
931
+ } finally {
932
+ live = false;
933
+ }
934
+ }
935
+
936
+ function videoMimeOf(response: Response, url: string) {
937
+ const header = response.headers.get("content-type")?.split(";")[0].trim().toLowerCase();
938
+
939
+ if (header && /^video\/(mp4|webm|quicktime)$/.test(header)) return header;
940
+
941
+ if (header && !/^(application|binary)\/octet-stream$/.test(header)) return;
942
+
943
+ const ext = url
944
+ .replace(/[?#].*$/, "")
945
+ .match(/\.[a-z0-9]+$/i)?.[0]
946
+ .toLowerCase();
947
+
948
+ return ext ? VIDEO_EXT_MIMES.get(ext) : undefined;
949
+ }
950
+
951
+ /**
952
+ * The video a `<video>` plays: its own file when the page can fetch one Figma reads, else a clip recorded as it plays, such as a
953
+ * stream. Nothing for a paused video whose file the page cannot fetch.
954
+ */
955
+ async function videoOf(v: HTMLVideoElement): Promise<Raster | undefined> {
956
+ const [vw, vh] = sizeOf(v);
957
+ const size: [number, number] = vw && vh ? [vw, vh] : [Math.round(v.clientWidth), Math.round(v.clientHeight)];
958
+ const response = /^https?:/.test(v.currentSrc) ? await fetch(v.currentSrc).catch(() => undefined) : undefined;
959
+ const type = response?.ok ? videoMimeOf(response, v.currentSrc) : undefined;
960
+
961
+ if (response && type) {
962
+ checkVideoSize(Number(response.headers.get("content-length")));
963
+ const raw = await response.blob();
964
+ checkVideoSize(raw.size);
965
+
966
+ return { blob: new Blob([raw], { type }), size };
967
+ }
968
+
969
+ if (v.paused) return;
970
+
971
+ return { blob: await recorded(v.captureStream()), size };
972
+ }
973
+
974
+ async function imageOf(url: string) {
975
+ const response = await fetch(url).catch(() => undefined);
976
+
977
+ if (response && !response.ok) throw new Error(`HTTP ${response.status}`);
978
+ const blob = await response?.blob();
979
+ const local = blob ? URL.createObjectURL(blob) : url;
980
+
981
+ try {
982
+ const img = new Image();
983
+ img.src = local;
984
+ await img.decode();
985
+ const size: [number, number] = [img.naturalWidth, img.naturalHeight];
986
+
987
+ if (blob && /^image\/(png|jpeg)$/.test(blob.type)) return { blob, size };
988
+
989
+ if (!size[0] || !size[1]) throw new Error("it has no intrinsic size to draw it at");
990
+ const canvas = Object.assign(document.createElement("canvas"), { width: size[0], height: size[1] });
991
+ canvas.getContext("2d")!.drawImage(img, 0, 0);
992
+
993
+ return { blob: await pngOf(canvas), size };
994
+ } finally {
995
+ if (blob) URL.revokeObjectURL(local);
996
+ }
997
+ }
998
+
999
+ Object.assign(globalThis, { designCapture: capture(), designClips: () => fetchAssets(clips) });