@arraypress/effects-astro 0.6.1 → 0.8.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.
Files changed (41) hide show
  1. package/AGENTS.md +2 -0
  2. package/COMPONENTS.md +33 -0
  3. package/README.md +2 -2
  4. package/package.json +6 -2
  5. package/src/components/EffectCanvas.astro +4 -1
  6. package/src/components/PixelFountain.astro +70 -0
  7. package/src/index.d.ts +4 -1
  8. package/src/index.js +3 -1
  9. package/src/runtime/budget.d.ts +8 -0
  10. package/src/runtime/budget.js +49 -0
  11. package/src/runtime/export/clean-svg.d.ts +21 -0
  12. package/src/runtime/export/clean-svg.js +368 -0
  13. package/src/runtime/export/clock.d.ts +25 -0
  14. package/src/runtime/export/clock.js +122 -0
  15. package/src/runtime/export/fetch.d.ts +14 -0
  16. package/src/runtime/export/fetch.js +121 -0
  17. package/src/runtime/export/fonts.d.ts +30 -0
  18. package/src/runtime/export/fonts.js +202 -0
  19. package/src/runtime/export/format.d.ts +11 -0
  20. package/src/runtime/export/format.js +42 -0
  21. package/src/runtime/export/probe.d.ts +16 -0
  22. package/src/runtime/export/probe.js +89 -0
  23. package/src/runtime/export/raster.d.ts +17 -0
  24. package/src/runtime/export/raster.js +91 -0
  25. package/src/runtime/export/save.d.ts +5 -0
  26. package/src/runtime/export/save.js +41 -0
  27. package/src/runtime/export/snapshot.d.ts +43 -0
  28. package/src/runtime/export/snapshot.js +276 -0
  29. package/src/runtime/export/styles.d.ts +18 -0
  30. package/src/runtime/export/styles.js +152 -0
  31. package/src/runtime/export/svg-attrs.d.ts +8 -0
  32. package/src/runtime/export/svg-attrs.js +274 -0
  33. package/src/runtime/export/svg-text.d.ts +21 -0
  34. package/src/runtime/export/svg-text.js +124 -0
  35. package/src/runtime/export/video.d.ts +45 -0
  36. package/src/runtime/export/video.js +106 -0
  37. package/src/runtime/pixel-fountain.d.ts +134 -0
  38. package/src/runtime/pixel-fountain.js +730 -0
  39. package/src/runtime/pixel-glitch.js +2 -24
  40. package/src/runtime/text.d.ts +6 -0
  41. package/src/runtime/text.js +57 -1
@@ -0,0 +1,368 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/export/clean-svg
3
+ *
4
+ * An element rebuilt as a plain SVG: real `<rect>`, `<image>` and
5
+ * `<text>` elements (and its own inline SVGs, their styles written as
6
+ * attributes), so it opens and edits in a design tool, not only in a
7
+ * browser. Its web fonts go in as `@font-face` rules (inlined), so
8
+ * browsers set the words exactly; a design tool uses the face if it is
9
+ * installed.
10
+ *
11
+ * Only what plain SVG can say faithfully is rebuilt: flat colour boxes
12
+ * (rounded or not, with a plain border), pictures (cover, contain or
13
+ * fill), inline SVG, and text. Anything else (a CSS filter or blend, a
14
+ * gradient or image background, a shadow, a clip, a rotated box, a
15
+ * pseudo-element that paints) is listed by `cleanIssues()`, and
16
+ * `cleanSvg()` refuses: an export that came out different from the
17
+ * element would be worse than none.
18
+ */
19
+
20
+ import { fontFaceCss } from './fonts.js';
21
+ import { toDataUrl } from './fetch.js';
22
+ import { cssColor } from './probe.js';
23
+ import { cssNumber, escapeXml, matrixOf, round2 } from './format.js';
24
+ import { pseudoShows, PSEUDOS } from './styles.js';
25
+ import { inlineSvg } from './svg-attrs.js';
26
+ import { textLines } from './svg-text.js';
27
+
28
+ const SVG_NS = 'http://www.w3.org/2000/svg';
29
+ const XLINK = 'http://www.w3.org/1999/xlink';
30
+
31
+ /** @typedef {{ w: number, c: string, st: string }} Side A border side: its width, colour and style. */
32
+
33
+ /**
34
+ * Whether a computed transform is a translate and scale only (no rotation
35
+ * or skew).
36
+ *
37
+ * @param {string} t The computed `transform`.
38
+ * @returns {boolean} Whether it is.
39
+ */
40
+ export function plainTransform(t) {
41
+ if (t === 'none') return true;
42
+ const m = matrixOf(t);
43
+ if (!m) return false;
44
+ const [, b, c] = m;
45
+ return Math.abs(b) < 1e-6 && Math.abs(c) < 1e-6;
46
+ }
47
+
48
+ /**
49
+ * An element as an issue's message names it: its tag and first two
50
+ * classes.
51
+ *
52
+ * @param {Element} el The element.
53
+ * @returns {string} Its name (`div.card.wide`).
54
+ */
55
+ export const describe = (el) => `${el.localName}${el.classList.length ? '.' + [...el.classList].slice(0, 2).join('.') : ''}`;
56
+
57
+ /**
58
+ * Markup faded to an opacity, in a group (as it is when it is opaque).
59
+ *
60
+ * @param {string} markup The markup.
61
+ * @param {number} opacity Its opacity, 0–1.
62
+ * @returns {string} The markup, grouped when it is faded and not empty.
63
+ */
64
+ export const faded = (markup, opacity) => (opacity < 1 && markup ? `<g opacity="${round2(opacity)}">${markup}</g>` : markup);
65
+
66
+ /**
67
+ * A box's position and size as attributes.
68
+ *
69
+ * @param {number} x Left.
70
+ * @param {number} y Top.
71
+ * @param {number} w Width.
72
+ * @param {number} h Height.
73
+ * @returns {string} `x`, `y`, `width` and `height`.
74
+ */
75
+ const boxAttrs = (x, y, w, h) => `x="${round2(x)}" y="${round2(y)}" width="${round2(w)}" height="${round2(h)}"`;
76
+
77
+ /**
78
+ * A paint attribute and, for a translucent colour, its opacity.
79
+ *
80
+ * @param {string} c The colour (one `cssColor` reads).
81
+ * @param {string} attr `fill` or `stroke`.
82
+ * @returns {string} The attributes.
83
+ */
84
+ function paintAttr(c, attr) {
85
+ const k = /** @type {{ hex: string, a: number }} */ (cssColor(c));
86
+ return `${attr}="${k.hex}"${k.a < 1 ? ` ${attr}-opacity="${round2(k.a)}"` : ''}`;
87
+ }
88
+
89
+ /**
90
+ * An element's four border sides, top, right, bottom and left.
91
+ *
92
+ * @param {CSSStyleDeclaration} cs Its computed style.
93
+ * @returns {Side[]} The sides.
94
+ */
95
+ const borderSides = (cs) =>
96
+ ['top', 'right', 'bottom', 'left'].map((s) => ({ w: cssNumber(cs.getPropertyValue(`border-${s}-width`)), c: cs.getPropertyValue(`border-${s}-color`), st: cs.getPropertyValue(`border-${s}-style`) }));
97
+
98
+ /**
99
+ * Whether a border side is drawn at all.
100
+ *
101
+ * @param {Side} s The side.
102
+ * @returns {boolean} Whether it is.
103
+ */
104
+ const drawnSide = (s) => s.w > 0 && s.st !== 'none' && !!cssColor(s.c);
105
+
106
+ /**
107
+ * Whether a pseudo-element paints something.
108
+ *
109
+ * @param {Element} el The element.
110
+ * @param {string} p `'::before'` or `'::after'`.
111
+ * @returns {boolean} Whether it does.
112
+ */
113
+ function paints(el, p) {
114
+ const cs = getComputedStyle(el, p);
115
+ if (!pseudoShows(cs)) return false;
116
+ if (cssNumber(cs.opacity) === 0 || cs.visibility === 'hidden') return false;
117
+ if (cssColor(cs.backgroundColor) || cs.backgroundImage !== 'none' || cs.boxShadow !== 'none') return true;
118
+ if (borderSides(cs).some((s) => s.w > 0 && s.st !== 'none')) return true;
119
+ return cs.content.replace(/^["']|["']$/g, '').trim() !== '';
120
+ }
121
+
122
+ /**
123
+ * What stops an element's own box being rebuilt: its filters, blends,
124
+ * clips, image backgrounds, shadows, rotations and painting
125
+ * pseudo-elements.
126
+ *
127
+ * @param {Element} el The element.
128
+ * @param {CSSStyleDeclaration} cs Its computed style.
129
+ * @param {string[]} issues Collects them.
130
+ * @param {boolean} root Whether it is the root (its shadow and transform are the frame's, not the art's).
131
+ */
132
+ function boxIssues(el, cs, issues, root) {
133
+ const name = describe(el);
134
+ if (cs.filter !== 'none') issues.push(`a filter on ${name}`);
135
+ if (cs.backdropFilter && cs.backdropFilter !== 'none') issues.push(`a backdrop filter on ${name}`);
136
+ if (cs.mixBlendMode !== 'normal') issues.push(`a blend mode on ${name}`);
137
+ if (cs.clipPath !== 'none' || cs.maskImage !== 'none') issues.push(`a clip on ${name}`);
138
+ if (cs.backgroundImage !== 'none') issues.push(`an image or gradient background on ${name}`);
139
+ if (!root && cs.boxShadow !== 'none') issues.push(`a shadow on ${name}`);
140
+ if (!root && !plainTransform(cs.transform)) issues.push(`a rotated ${name}`);
141
+ if (!root && (cs.rotate !== 'none' || cs.transform.startsWith('matrix3d'))) issues.push(`a rotated ${name}`);
142
+ for (const p of PSEUDOS) if (paints(el, p)) issues.push(`a ${p.slice(2)} on ${name}`);
143
+ }
144
+
145
+ /**
146
+ * An inline `<svg>` in the page, with what stops it being rebuilt.
147
+ *
148
+ * @param {SVGSVGElement} el The SVG.
149
+ * @param {CSSStyleDeclaration} cs Its computed style.
150
+ * @param {DOMRect} box Its box.
151
+ * @param {DOMRect} origin The root's box.
152
+ * @param {string[]} issues Collects what cannot be rebuilt.
153
+ * @param {boolean} root Whether it is the root.
154
+ * @returns {string} The nested `<svg>`.
155
+ */
156
+ function nestedSvg(el, cs, box, origin, issues, root) {
157
+ const name = describe(el);
158
+ if (!root && !plainTransform(cs.transform)) issues.push(`a rotated ${name}`);
159
+ if (cs.filter !== 'none') issues.push(`a filter on ${name}`);
160
+ if (cs.mixBlendMode !== 'normal') issues.push(`a blend mode on ${name}`);
161
+ if (cs.clipPath !== 'none' || cs.maskImage !== 'none') issues.push(`a clip on ${name}`);
162
+ return inlineSvg(el, box, origin, issues);
163
+ }
164
+
165
+ /**
166
+ * A box's paint: a flat colour, rounded alike at every corner, and a
167
+ * plain border (all four sides alike as a stroke, or some sides only as
168
+ * strips).
169
+ *
170
+ * @param {Element} el The element.
171
+ * @param {CSSStyleDeclaration} cs Its computed style.
172
+ * @param {DOMRect} box Its box.
173
+ * @param {number} x Its left, from the root's.
174
+ * @param {number} y Its top, from the root's.
175
+ * @param {string[]} issues Collects what cannot be rebuilt.
176
+ * @param {boolean} root Whether it is the root (whose corners are the frame's).
177
+ * @returns {string} The rects.
178
+ */
179
+ function boxPaint(el, cs, box, x, y, issues, root) {
180
+ const name = describe(el);
181
+ let out = '';
182
+ const radii = root ? [0] : [cs.borderTopLeftRadius, cs.borderTopRightRadius, cs.borderBottomRightRadius, cs.borderBottomLeftRadius].map(cssNumber);
183
+ if (radii.some((r) => r !== radii[0]) || (!root && /%|\s/.test(cs.borderTopLeftRadius.trim()) && cssNumber(cs.borderTopLeftRadius) > 0)) issues.push(`uneven rounded corners on ${name}`);
184
+ const rx = radii[0] ? ` rx="${round2(Math.min(radii[0], box.width / 2, box.height / 2))}"` : '';
185
+ if (cssColor(cs.backgroundColor)) out += `<rect ${boxAttrs(x, y, box.width, box.height)}${rx} ${paintAttr(cs.backgroundColor, 'fill')} />`;
186
+ const sides = borderSides(cs);
187
+ const drawn = sides.filter(drawnSide);
188
+ if (drawn.some((d) => d.st !== 'solid')) issues.push(`a dashed or styled border on ${name}`);
189
+ const even = drawn.length === 4 && drawn.every((d) => d.w === drawn[0].w && d.c === drawn[0].c);
190
+ if (even) {
191
+ const s = drawn[0];
192
+ return out + `<rect ${boxAttrs(x + s.w / 2, y + s.w / 2, box.width - s.w, box.height - s.w)}${rx} fill="none" ${paintAttr(s.c, 'stroke')} stroke-width="${round2(s.w)}" />`;
193
+ }
194
+ if (!drawn.length) return out;
195
+ // a rule on some sides only (a title block's lines): each side a filled strip
196
+ if (radii[0]) issues.push(`a part border on rounded ${name}`);
197
+ const [t, r, b, l] = sides;
198
+ /**
199
+ * One side as a filled strip, if it is drawn.
200
+ *
201
+ * @param {Side} side The side.
202
+ * @param {number} sx Left.
203
+ * @param {number} sy Top.
204
+ * @param {number} sw Width.
205
+ * @param {number} sh Height.
206
+ * @returns {string} The rect, or nothing.
207
+ */
208
+ const strip = (side, sx, sy, sw, sh) => (drawnSide(side) ? `<rect ${boxAttrs(sx, sy, sw, sh)} ${paintAttr(side.c, 'fill')} />` : '');
209
+ return out + strip(t, x, y, box.width, t.w) + strip(b, x, y + box.height - b.w, box.width, b.w) + strip(l, x, y, l.w, box.height) + strip(r, x + box.width - r.w, y, r.w, box.height);
210
+ }
211
+
212
+ /**
213
+ * A picture, fitted as the page fits it (cover, contain or fill; centred).
214
+ * Its file is fetched later (`inlinePictures`), so it is written with a
215
+ * `data-src`.
216
+ *
217
+ * @param {HTMLImageElement} el The picture.
218
+ * @param {CSSStyleDeclaration} cs Its computed style.
219
+ * @param {DOMRect} box Its box.
220
+ * @param {number} x Its left, from the root's.
221
+ * @param {number} y Its top, from the root's.
222
+ * @param {string[]} issues Collects what cannot be rebuilt.
223
+ * @returns {string} An `<svg>` holding its `<image>`.
224
+ */
225
+ function picture(el, cs, box, x, y, issues) {
226
+ const fit = cs.objectFit;
227
+ if (cs.objectPosition !== '50% 50%') issues.push('an off-centre picture');
228
+ const par = fit === 'cover' ? 'xMidYMid slice' : fit === 'contain' ? 'xMidYMid meet' : fit === 'none' || fit === 'scale-down' ? null : 'none';
229
+ if (!par) issues.push('a picture set at its own size');
230
+ return `<svg ${boxAttrs(x, y, box.width, box.height)}><image data-src="${escapeXml(el.currentSrc || el.src)}" width="100%" height="100%" preserveAspectRatio="${par ?? 'none'}" /></svg>`;
231
+ }
232
+
233
+ /**
234
+ * An element's own words (its text nodes, not its children's), with what
235
+ * stops them being rebuilt.
236
+ *
237
+ * @param {Element} el The element.
238
+ * @param {CSSStyleDeclaration} cs Its computed style.
239
+ * @param {DOMRect} origin The root's box.
240
+ * @param {number} opacity Its opacity.
241
+ * @param {string[]} issues Collects what cannot be rebuilt.
242
+ * @returns {string} The `<text>` elements.
243
+ */
244
+ function ownText(el, cs, origin, opacity, issues) {
245
+ const name = describe(el);
246
+ let out = '';
247
+ for (const n of el.childNodes) {
248
+ if (!(n instanceof Text) || !n.data.trim()) continue;
249
+ if (cs.textShadow !== 'none') issues.push(`a text shadow on ${name}`);
250
+ if (cssNumber(cs.getPropertyValue('-webkit-text-stroke-width')) > 0) issues.push(`outlined text on ${name}`);
251
+ if (cs.backgroundClip === 'text' || cs.getPropertyValue('-webkit-background-clip') === 'text') issues.push(`text filled with a picture on ${name}`);
252
+ const box = /** @type {HTMLElement} */ (el);
253
+ if (cs.textOverflow === 'ellipsis' && box.scrollWidth > box.clientWidth + 1) issues.push(`cut-off text on ${name}`);
254
+ out += textLines(n, cs, origin, opacity);
255
+ }
256
+ return out;
257
+ }
258
+
259
+ /**
260
+ * An element's children in paint order (z-index, else document order).
261
+ * A child under its parent's own background can be drawn only when the
262
+ * parent is a stacking context.
263
+ *
264
+ * @param {Element} el The element.
265
+ * @param {CSSStyleDeclaration} cs Its computed style.
266
+ * @param {DOMRect} origin The root's box.
267
+ * @param {number} opacity Its opacity.
268
+ * @param {string[]} issues Collects what cannot be rebuilt.
269
+ * @param {boolean} root Whether it is the root.
270
+ * @returns {string} The children's SVG.
271
+ */
272
+ function children(el, cs, origin, opacity, issues, root) {
273
+ const kids = [...el.children]
274
+ .filter((k) => getComputedStyle(k).display !== 'none')
275
+ .map((k, i) => ({ k, i, z: getComputedStyle(k).position !== 'static' ? parseInt(getComputedStyle(k).zIndex) || 0 : 0 }));
276
+ const context = root || cs.isolation === 'isolate' || (cs.position !== 'static' && cs.zIndex !== 'auto') || opacity < 1 || cs.transform !== 'none';
277
+ if (!context && kids.some((k) => k.z < 0)) issues.push(`a layer behind ${describe(el)}`);
278
+ kids.sort((a, b) => a.z - b.z || a.i - b.i);
279
+ return kids.map(({ k }) => walk(k, origin, issues)).join('');
280
+ }
281
+
282
+ /**
283
+ * Walks an element: its paint as SVG, and what cannot be said in plain SVG.
284
+ *
285
+ * @param {Element} el The element.
286
+ * @param {DOMRect} origin The root's box (positions are measured from it).
287
+ * @param {string[]} issues Collects what cannot be rebuilt.
288
+ * @param {boolean} [root] Whether it is the root (its shadow, radius and transform are the frame's, not the art's).
289
+ * @returns {string} Its SVG.
290
+ */
291
+ function walk(el, origin, issues, root = false) {
292
+ const cs = getComputedStyle(el);
293
+ if (cs.display === 'none' || cs.visibility === 'hidden') return '';
294
+ const opacity = cssNumber(cs.opacity);
295
+ if (opacity === 0) return '';
296
+ const box = el.getBoundingClientRect();
297
+ if (el instanceof SVGSVGElement) return faded(nestedSvg(el, cs, box, origin, issues, root), opacity);
298
+ if (el instanceof SVGElement) return ''; // (inside an inline svg: drawn with it)
299
+ boxIssues(el, cs, issues, root);
300
+ const x = box.left - origin.left,
301
+ y = box.top - origin.top;
302
+ let out = boxPaint(el, cs, box, x, y, issues, root);
303
+ if (el instanceof HTMLImageElement) out += picture(el, cs, box, x, y, issues);
304
+ let inner = ownText(el, cs, origin, opacity, issues) + children(el, cs, origin, opacity, issues, root);
305
+ // clipped to its box, when it clips and is not the root (whose box is the whole picture)
306
+ if (!root && cs.overflow !== 'visible' && inner) inner = `<svg ${boxAttrs(x, y, box.width, box.height)} viewBox="${round2(x)} ${round2(y)} ${round2(box.width)} ${round2(box.height)}">${inner}</svg>`;
307
+ out += inner;
308
+ return faded(out, opacity);
309
+ }
310
+
311
+ /**
312
+ * Swaps each picture's `data-src` for an `href` to its file as a `data:`
313
+ * URL, so the SVG stands alone (a file that cannot be fetched is left
314
+ * empty).
315
+ *
316
+ * @param {string} body The SVG's markup.
317
+ * @returns {Promise<string>} The markup, its pictures inlined.
318
+ */
319
+ export async function inlinePictures(body) {
320
+ /**
321
+ * A `data-src` attribute's URL, unescaped.
322
+ *
323
+ * @param {string} s The attribute's text.
324
+ * @returns {string} The URL.
325
+ */
326
+ const unescape = (s) => s.replace(/&amp;/g, '&');
327
+ const srcs = [...body.matchAll(/data-src="([^"]+)"/g)].map((m) => unescape(m[1]));
328
+ const data = new Map(await Promise.all(srcs.map(async (s) => /** @type {const} */ ([s, await toDataUrl(s).catch(() => '')]))));
329
+ return body.replace(/data-src="([^"]+)"/g, (_, s) => `href="${data.get(unescape(s)) ?? ''}"`);
330
+ }
331
+
332
+ /**
333
+ * What stops an element being rebuilt faithfully as plain SVG.
334
+ *
335
+ * @param {HTMLElement} el The element, shown and laid out.
336
+ * @returns {string[]} The issues, each once; empty when it can be.
337
+ */
338
+ export function cleanIssues(el) {
339
+ /** @type {string[]} */
340
+ const issues = [];
341
+ walk(el, el.getBoundingClientRect(), issues, true);
342
+ return [...new Set(issues)];
343
+ }
344
+
345
+ /**
346
+ * The element as a plain SVG document.
347
+ *
348
+ * @param {HTMLElement} el The element, shown and laid out.
349
+ * @param {number} [long] The SVG's width or height, whichever is longer, px (its viewBox stays the element's CSS size). Default 1080.
350
+ * @returns {Promise<string>} The SVG document.
351
+ * @throws {Error} Listing why, when it cannot be rebuilt faithfully (see `cleanIssues`).
352
+ */
353
+ export async function cleanSvg(el, long = 1080) {
354
+ /** @type {string[]} */
355
+ const issues = [];
356
+ const body = walk(el, el.getBoundingClientRect(), issues, true);
357
+ if (issues.length) throw new Error(`export: not plain SVG: ${[...new Set(issues)].join('; ')}`);
358
+ const w = el.offsetWidth,
359
+ h = el.offsetHeight;
360
+ const k = long / Math.max(w, h);
361
+ const fonts = await fontFaceCss(el);
362
+ const art = await inlinePictures(body);
363
+ return (
364
+ `<svg xmlns="${SVG_NS}" xmlns:xlink="${XLINK}" width="${Math.round(w * k)}" height="${Math.round(h * k)}" viewBox="0 0 ${w} ${h}">` +
365
+ (fonts ? `<defs><style>${fonts}</style></defs>` : '') +
366
+ `<svg width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${art}</svg></svg>`
367
+ );
368
+ }
@@ -0,0 +1,25 @@
1
+ import type { Moved } from './snapshot.js';
2
+
3
+ /** The animations under an element, held. */
4
+ export interface Clock {
5
+ /** How many animations it holds. */
6
+ readonly count: number;
7
+ /** Sets every animation to `ms` from its start. */
8
+ seek(ms: number): void;
9
+ /** What the animations move: each element (or pseudo-element) and its animated properties. */
10
+ moved(): Moved[];
11
+ /** Lets the animations run on from where they were. */
12
+ release(): void;
13
+ }
14
+
15
+ /** A keyframe's property in CSS's own spelling (`backgroundColor` is `background-color`; a custom property as it is). */
16
+ export function cssProperty(p: string): string;
17
+
18
+ /** The properties a set of keyframes (from `getKeyframes()`) animates, in CSS's spelling. */
19
+ export function keyframeProps(keyframes: object[]): Set<string>;
20
+
21
+ /** What to read again for an element: `'all'` once anything animates a custom property (or keyframes name nothing), else the properties so far and these. */
22
+ export function mergeProps(before: string[] | 'all', props: Set<string>): string[] | 'all';
23
+
24
+ /** Pauses the CSS animations under `root` (and on it) to step them by hand; `release()` lets them run on. */
25
+ export function clock(root: Element): Clock;
@@ -0,0 +1,122 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/export/clock
3
+ *
4
+ * The CSS animations under an element, held and stepped by hand (Web
5
+ * Animations): pause them all, set every one to the same moment, read
6
+ * the frame, move on. A recording made this way is exact, frame by frame,
7
+ * however long each frame takes to draw. `release()` lets them run on
8
+ * from where they were.
9
+ */
10
+
11
+ /** @typedef {import('./snapshot.js').Moved} Moved */
12
+
13
+ /**
14
+ * @typedef {object} Clock
15
+ * @property {number} count How many animations it holds.
16
+ * @property {(ms: number) => void} seek Sets every animation to `ms` from its start.
17
+ * @property {() => Moved[]} moved What the animations move: each element (or pseudo-element) and its animated properties.
18
+ * @property {() => void} release Lets the animations run on from where they were.
19
+ */
20
+
21
+ /** A keyframe's keys that are not properties. */
22
+ const NOT_PROPS = new Set(['offset', 'computedOffset', 'easing', 'composite']);
23
+
24
+ /**
25
+ * A keyframe's property in CSS's own spelling (`backgroundColor` is
26
+ * `background-color`; a custom property as it is).
27
+ *
28
+ * @param {string} p The key.
29
+ * @returns {string} The property.
30
+ */
31
+ export const cssProperty = (p) => (p.startsWith('--') ? p : p.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`));
32
+
33
+ /**
34
+ * The properties a set of keyframes animates.
35
+ *
36
+ * @param {object[]} keyframes From `getKeyframes()`.
37
+ * @returns {Set<string>} The properties, in CSS's spelling.
38
+ */
39
+ export function keyframeProps(keyframes) {
40
+ /** @type {Set<string>} */
41
+ const props = new Set();
42
+ for (const k of keyframes) for (const p of Object.keys(k)) if (!NOT_PROPS.has(p)) props.add(cssProperty(p));
43
+ return props;
44
+ }
45
+
46
+ /**
47
+ * What to read again for an animation, with what was already to be read
48
+ * for its element. A custom property feeds other values, so one that
49
+ * animates one reads the element (and all in it) again; Chrome leaves
50
+ * custom properties out of `getKeyframes()`, so keyframes that name
51
+ * nothing are taken to animate one.
52
+ *
53
+ * @param {string[] | 'all'} before What was to be read.
54
+ * @param {Set<string>} props What this animation animates.
55
+ * @returns {string[] | 'all'} What is to be read now.
56
+ */
57
+ export function mergeProps(before, props) {
58
+ if (!props.size || [...props].some((p) => p.startsWith('--'))) return 'all';
59
+ if (before === 'all') return before;
60
+ return [...new Set([...before, ...props])];
61
+ }
62
+
63
+ /**
64
+ * What a set of animations moves: each element (or pseudo-element) and
65
+ * the properties to read again.
66
+ *
67
+ * @param {Animation[]} anims The animations.
68
+ * @returns {Moved[]} One entry an element or pseudo-element.
69
+ */
70
+ function movedBy(anims) {
71
+ /** @type {Map<string, Moved>} */
72
+ const moved = new Map();
73
+ /** @type {Map<Element, number>} */
74
+ const keyOf = new Map();
75
+ for (const a of anims) {
76
+ const fx = /** @type {KeyframeEffect | null} */ (a.effect);
77
+ if (!fx?.target) continue;
78
+ if (!keyOf.has(fx.target)) keyOf.set(fx.target, keyOf.size);
79
+ const key = `${keyOf.get(fx.target)}${fx.pseudoElement ?? ''}`;
80
+ const m = moved.get(key) ?? { el: fx.target, pseudo: fx.pseudoElement ?? undefined, props: /** @type {string[]} */ ([]) };
81
+ m.props = mergeProps(m.props, keyframeProps(fx.getKeyframes()));
82
+ moved.set(key, m);
83
+ }
84
+ return [...moved.values()];
85
+ }
86
+
87
+ /**
88
+ * Holds the animations running under `root` (and on it).
89
+ *
90
+ * @param {Element} root The element.
91
+ * @returns {Clock} The clock.
92
+ */
93
+ export function clock(root) {
94
+ const anims = root.getAnimations({ subtree: true });
95
+ const was = anims.map((a) => ({ a, t: a.currentTime, running: a.playState === 'running' }));
96
+ for (const a of anims) a.pause();
97
+ const moved = movedBy(anims);
98
+ return {
99
+ count: anims.length,
100
+ /**
101
+ * Sets every animation to the same moment.
102
+ *
103
+ * @param {number} ms From the animations' start.
104
+ */
105
+ seek(ms) {
106
+ for (const a of anims) a.currentTime = ms;
107
+ },
108
+ /**
109
+ * What the animations move.
110
+ *
111
+ * @returns {Moved[]} Each element (or pseudo-element) and its animated properties.
112
+ */
113
+ moved: () => [...moved],
114
+ /** Lets the animations run on from where they were. */
115
+ release() {
116
+ for (const { a, t, running } of was) {
117
+ a.currentTime = t;
118
+ if (running) a.play();
119
+ }
120
+ },
121
+ };
122
+ }
@@ -0,0 +1,14 @@
1
+ /** Every `url(…)` in a CSS value that would load from outside (not `data:`, not a `#fragment`), in order. */
2
+ export function outerUrls(value: string): string[];
3
+
4
+ /** Whether a CSS value has a `url(…)` that would load from outside (not `data:`, not a `#fragment`). */
5
+ export function hasOuterUrl(value: string): boolean;
6
+
7
+ /** A blob as a `data:` URL. */
8
+ export function blobToDataUrl(blob: Blob): Promise<string>;
9
+
10
+ /** A file (absolute, or relative to the page) as a `data:` URL, fetched once per page; a `data:` URL is returned as it is. Rejects when it cannot be fetched. */
11
+ export function toDataUrl(url: string): Promise<string>;
12
+
13
+ /** A CSS value with every `url(…)` that loads from outside swapped for its `data:` URL (`none` for one that cannot be fetched). */
14
+ export function inlineCssUrls(value: string): Promise<string>;
@@ -0,0 +1,121 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/export/fetch
3
+ *
4
+ * Same-origin files as `data:` URLs, for exports that must carry
5
+ * everything inside them: an SVG drawn as an image cannot load anything
6
+ * from outside itself. Each URL is fetched once per page.
7
+ */
8
+
9
+ /** Every URL asked for, by its absolute form, and its `data:` URL to come. */
10
+ /** @type {Map<string, Promise<string>>} */
11
+ const seen = new Map();
12
+
13
+ /**
14
+ * Every top-level `url(…)` in a CSS value: quoted (as computed values are)
15
+ * or bare. A quoted one is matched whole, so a `url(#id)` inside a `data:`
16
+ * URL's own text is never taken for another.
17
+ */
18
+ const URLS = /url\(\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|([^'")\s]*))\s*\)/g;
19
+
20
+ /**
21
+ * The URL a `URLS` match holds, whichever way it was quoted.
22
+ *
23
+ * @param {(string | undefined)[]} groups The match's groups (from 1), or the match itself.
24
+ * @param {number} [from] Where the groups start in it: 1 for a match, 0 for a replacer's groups.
25
+ * @returns {string} The URL.
26
+ */
27
+ const urlOf = (groups, from = 1) => groups[from] ?? groups[from + 1] ?? groups[from + 2] ?? '';
28
+
29
+ /**
30
+ * Whether a URL loads from outside: not a `data:` URL, not a `#fragment`.
31
+ *
32
+ * @param {string} u The URL.
33
+ * @returns {boolean} Whether it does.
34
+ */
35
+ const outer = (u) => !!u && !u.startsWith('data:') && !u.startsWith('#');
36
+
37
+ /**
38
+ * Every `url(…)` in a CSS value that would load from outside.
39
+ *
40
+ * @param {string} value A CSS declaration block or value.
41
+ * @returns {string[]} The URLs, in order (repeats kept).
42
+ */
43
+ export function outerUrls(value) {
44
+ return [...value.matchAll(URLS)].map((m) => urlOf(m)).filter(outer);
45
+ }
46
+
47
+ /**
48
+ * Whether a CSS value has a `url(…)` that would load from outside.
49
+ *
50
+ * @param {string} value A CSS declaration block or value.
51
+ * @returns {boolean} Whether it has.
52
+ */
53
+ export const hasOuterUrl = (value) => outerUrls(value).length > 0;
54
+
55
+ /**
56
+ * A blob as a `data:` URL.
57
+ *
58
+ * @param {Blob} blob The blob.
59
+ * @returns {Promise<string>} Its `data:` URL.
60
+ */
61
+ export const blobToDataUrl = (blob) =>
62
+ new Promise((resolve, reject) => {
63
+ const reader = new FileReader();
64
+ reader.onload = () => resolve(/** @type {string} */ (reader.result));
65
+ reader.onerror = () => reject(reader.error);
66
+ reader.readAsDataURL(blob);
67
+ });
68
+
69
+ /**
70
+ * A file as a `data:` URL, fetched once (a failed fetch is tried again
71
+ * next time); a `data:` URL is returned as it is.
72
+ *
73
+ * @param {string} url Absolute, or relative to the page.
74
+ * @returns {Promise<string>} Its `data:` URL.
75
+ * @throws {Error} When the file cannot be fetched.
76
+ */
77
+ export function toDataUrl(url) {
78
+ if (url.startsWith('data:')) return Promise.resolve(url);
79
+ const abs = new URL(url, location.href).href;
80
+ let p = seen.get(abs);
81
+ if (!p) {
82
+ p = fetch(abs)
83
+ .then((r) => {
84
+ if (!r.ok) throw new Error(`export: ${r.status} fetching ${abs}`);
85
+ return r.blob();
86
+ })
87
+ .then(blobToDataUrl);
88
+ seen.set(abs, p);
89
+ p.catch(() => seen.delete(abs));
90
+ }
91
+ return p;
92
+ }
93
+
94
+ /**
95
+ * A CSS value with every `url(…)` that loads from outside swapped for its
96
+ * `data:` URL; one that cannot be fetched becomes `none` rather than be
97
+ * left pointing outside the image.
98
+ *
99
+ * @param {string} value A CSS declaration block or value.
100
+ * @returns {Promise<string>} The value, self-contained.
101
+ */
102
+ export async function inlineCssUrls(value) {
103
+ const found = outerUrls(value);
104
+ if (!found.length) return value;
105
+ /** @type {Map<string, string>} */
106
+ const map = new Map();
107
+ await Promise.all(
108
+ [...new Set(found)].map(async (u) => {
109
+ try {
110
+ map.set(u, await toDataUrl(u));
111
+ } catch {
112
+ map.set(u, '');
113
+ }
114
+ }),
115
+ );
116
+ return value.replace(URLS, (all, ...groups) => {
117
+ const u = urlOf(groups, 0);
118
+ if (!map.has(u)) return all;
119
+ return map.get(u) ? `url("${map.get(u)}")` : 'none';
120
+ });
121
+ }
@@ -0,0 +1,30 @@
1
+ /** A face the text asks for: its style, the weights, and the characters (code points) set in it. */
2
+ export interface FontUse {
3
+ style: 'normal' | 'italic' | string;
4
+ weights: Set<number>;
5
+ chars: Set<number>;
6
+ }
7
+
8
+ /** A family name as it is matched: unquoted, lower case. */
9
+ export function familyKey(s: string): string;
10
+
11
+ /** Notes a piece of text's font (style, weight, characters in both cases) against each family in its stack, in `uses`. */
12
+ export function noteUse(uses: Map<string, FontUse[]>, cs: { fontStyle: string; fontWeight: string; fontFamily: string }, text: string): void;
13
+
14
+ /** A `unicode-range` descriptor as `[first, last]` code points; all of Unicode when it is empty. */
15
+ export function unicodeRanges(desc: string): [number, number][];
16
+
17
+ /** Whether any of the code points falls in the ranges. */
18
+ export function coversAny(chars: Iterable<number>, ranges: [number, number][]): boolean;
19
+
20
+ /** Whether a face's `font-weight` descriptor serves any of the weights (a static face within 100 of one; always for a non-number). */
21
+ export function servesWeight(desc: string, weights: number[]): boolean;
22
+
23
+ /** A face's file URL (as written) and format (`woff2` when unsaid), from its `src` descriptor; null for none. */
24
+ export function fontSource(src: string): { url: string; format: string } | null;
25
+
26
+ /** A face's `@font-face` rule again (family, style, weight, stretch, unicode-range), its file the `data:` URL given. */
27
+ export function faceRule(style: { getPropertyValue(name: string): string }, data: string, format: string): string;
28
+
29
+ /** The page's `@font-face` rules for the text under `root` (only the families, styles, weights and unicode ranges it uses), each file inlined. */
30
+ export function fontFaceCss(root: Element): Promise<string>;