@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,202 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/export/fonts
3
+ *
4
+ * The page's web fonts that an element's text uses, as `@font-face` rules
5
+ * with the files inlined (`data:` URLs), so an exported SVG sets its words
6
+ * in the same faces wherever it is opened in a browser.
7
+ *
8
+ * Only the faces needed go in: the families, styles and weights the text
9
+ * is set in, and of those only the `unicode-range` subsets its characters
10
+ * fall in (a font split into latin, latin-ext, cyrillic and so on).
11
+ */
12
+
13
+ import { toDataUrl } from './fetch.js';
14
+ import { PSEUDOS } from './styles.js';
15
+
16
+ /** @typedef {{ style: string, weights: Set<number>, chars: Set<number> }} FontUse A face the text asks for: its style, the weights, and the characters set in it. */
17
+
18
+ /** The descriptors a face's rule keeps, besides its `src`. */
19
+ const DESCRIPTORS = ['font-family', 'font-style', 'font-weight', 'font-stretch', 'unicode-range'];
20
+
21
+ /**
22
+ * A family name as it is matched: unquoted, lower case.
23
+ *
24
+ * @param {string} s The name, as CSS writes it.
25
+ * @returns {string} The name to match on.
26
+ */
27
+ export const familyKey = (s) => s.trim().replace(/^['"]|['"]$/g, '').toLowerCase();
28
+
29
+ /**
30
+ * Notes a piece of text's font against each family in its stack.
31
+ *
32
+ * @param {Map<string, FontUse[]>} uses The uses so far, by family; added to.
33
+ * @param {{ fontStyle: string, fontWeight: string, fontFamily: string }} cs The text's computed style.
34
+ * @param {string} text The text.
35
+ */
36
+ export function noteUse(uses, cs, text) {
37
+ if (!text.trim()) return;
38
+ const style = cs.fontStyle === 'normal' ? 'normal' : 'italic';
39
+ const weight = Number(cs.fontWeight) || 400;
40
+ // both cases: text-transform may set it either way
41
+ const chars = [...text, ...text.toUpperCase(), ...text.toLowerCase()].map((c) => /** @type {number} */ (c.codePointAt(0)));
42
+ for (const family of cs.fontFamily.split(',').map(familyKey)) {
43
+ const list = uses.get(family) ?? [];
44
+ let use = list.find((x) => x.style === style);
45
+ if (!use) list.push((use = { style, weights: new Set(), chars: new Set() }));
46
+ use.weights.add(weight);
47
+ for (const c of chars) use.chars.add(c);
48
+ uses.set(family, list);
49
+ }
50
+ }
51
+
52
+ /**
53
+ * The fonts of every visible piece of text under `root`, pseudo-elements'
54
+ * text too.
55
+ *
56
+ * @param {Element} root The element.
57
+ * @returns {Map<string, FontUse[]>} The uses, by family.
58
+ */
59
+ function textUses(root) {
60
+ /** @type {Map<string, FontUse[]>} */
61
+ const uses = new Map();
62
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
63
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
64
+ const el = n.parentElement;
65
+ if (el) noteUse(uses, getComputedStyle(el), n.textContent ?? '');
66
+ }
67
+ for (const el of [root, ...root.querySelectorAll('*')])
68
+ for (const p of PSEUDOS) {
69
+ const cs = getComputedStyle(el, p);
70
+ const c = cs.content;
71
+ if (c && c !== 'none' && c !== 'normal') noteUse(uses, cs, c.replace(/^["']|["']$/g, ''));
72
+ }
73
+ return uses;
74
+ }
75
+
76
+ /**
77
+ * A `unicode-range` descriptor as code point ranges.
78
+ *
79
+ * @param {string} desc The descriptor (`U+0000-00FF, U+0131, U+02??`).
80
+ * @returns {[number, number][]} Each range's first and last code point; all of Unicode when it is empty.
81
+ */
82
+ export function unicodeRanges(desc) {
83
+ if (!desc.trim()) return [[0, 0x10ffff]];
84
+ return desc.split(',').map((part) => {
85
+ const [a, b] = part.trim().replace(/^u\+/i, '').split('-');
86
+ if (a.includes('?')) return [parseInt(a.replace(/\?/g, '0'), 16), parseInt(a.replace(/\?/g, 'f'), 16)];
87
+ return [parseInt(a, 16), parseInt(b ?? a, 16)];
88
+ });
89
+ }
90
+
91
+ /**
92
+ * Whether any of the characters falls in the ranges.
93
+ *
94
+ * @param {Iterable<number>} chars Code points.
95
+ * @param {[number, number][]} ranges From `unicodeRanges`.
96
+ * @returns {boolean} Whether one does.
97
+ */
98
+ export const coversAny = (chars, ranges) => [...chars].some((c) => ranges.some(([a, b]) => c >= a && c <= b));
99
+
100
+ /**
101
+ * Whether a face serves any of the weights: a variable face's range, or a
102
+ * static face at the weight asked for or the nearest the browser would
103
+ * fall back to (within 100).
104
+ *
105
+ * @param {string} desc The face's `font-weight` descriptor (`400`, `100 900`).
106
+ * @param {number[]} weights The weights the text is set in.
107
+ * @returns {boolean} Whether it does (always, for a descriptor that is not a number).
108
+ */
109
+ export function servesWeight(desc, weights) {
110
+ const [lo, hi = lo] = desc.split(/\s+/).map(Number);
111
+ return !Number.isFinite(lo) || weights.some((w) => w >= lo - 100 && w <= hi + 100);
112
+ }
113
+
114
+ /**
115
+ * A face's file and format, from its `src` descriptor (the first with a
116
+ * `format()`, else the first URL).
117
+ *
118
+ * @param {string} src The descriptor.
119
+ * @returns {{ url: string, format: string } | null} The file's URL (as written) and format (`woff2` when unsaid), or null for none.
120
+ */
121
+ export function fontSource(src) {
122
+ const m = src.match(/url\((['"]?)([^'")]+)\1\)\s*format\((['"]?)([^'")]+)\3\)/) ?? src.match(/url\((['"]?)([^'")]+)\1\)/);
123
+ return m ? { url: m[2], format: m[4] ?? 'woff2' } : null;
124
+ }
125
+
126
+ /**
127
+ * A face's rule again, its file inlined.
128
+ *
129
+ * @param {{ getPropertyValue(name: string): string }} style The face rule's descriptors.
130
+ * @param {string} data The file as a `data:` URL.
131
+ * @param {string} format The file's format.
132
+ * @returns {string} The `@font-face` rule.
133
+ */
134
+ export function faceRule(style, data, format) {
135
+ const desc = DESCRIPTORS.map((p) => [p, style.getPropertyValue(p)])
136
+ .filter(([, v]) => v)
137
+ .map(([p, v]) => `${p}:${v};`)
138
+ .join('');
139
+ return `@font-face{${desc}src:url("${data}") format("${format}");}`;
140
+ }
141
+
142
+ /**
143
+ * Every `@font-face` rule the page can read: same-origin sheets, inside
144
+ * `@media`, `@supports`, `@layer` and `@import` too.
145
+ *
146
+ * @returns {Generator<CSSFontFaceRule>} The rules.
147
+ */
148
+ function* faceRules() {
149
+ for (const sheet of document.styleSheets) {
150
+ try {
151
+ yield* faceRulesIn(sheet.cssRules);
152
+ } catch {
153
+ /* a cross-origin sheet */
154
+ }
155
+ }
156
+ }
157
+
158
+ /**
159
+ * The `@font-face` rules in a list of rules, at any depth.
160
+ *
161
+ * @param {CSSRuleList} rules The rules.
162
+ * @returns {Generator<CSSFontFaceRule>} The face rules.
163
+ */
164
+ function* faceRulesIn(rules) {
165
+ for (const r of rules) {
166
+ if (r instanceof CSSFontFaceRule) yield r;
167
+ else if (r instanceof CSSImportRule && r.styleSheet) {
168
+ try {
169
+ yield* faceRulesIn(r.styleSheet.cssRules);
170
+ } catch {
171
+ /* a cross-origin import */
172
+ }
173
+ } else if ('cssRules' in r) yield* faceRulesIn(/** @type {CSSGroupingRule} */ (r).cssRules);
174
+ }
175
+ }
176
+
177
+ /**
178
+ * The `@font-face` rules for the text under `root`, each file inlined (a
179
+ * file that cannot be fetched is left out).
180
+ *
181
+ * @param {Element} root The element being exported.
182
+ * @returns {Promise<string>} The rules, one a line.
183
+ */
184
+ export async function fontFaceCss(root) {
185
+ const want = textUses(root);
186
+ /** @type {Promise<string>[]} */
187
+ const jobs = [];
188
+ for (const rule of faceRules()) {
189
+ const list = want.get(familyKey(rule.style.getPropertyValue('font-family')));
190
+ if (!list) continue;
191
+ const style = /italic|oblique/.test(rule.style.getPropertyValue('font-style')) ? 'italic' : 'normal';
192
+ const use = list.find((x) => x.style === style);
193
+ if (!use) continue;
194
+ if (!servesWeight(rule.style.getPropertyValue('font-weight'), [...use.weights])) continue;
195
+ if (!coversAny(use.chars, unicodeRanges(rule.style.getPropertyValue('unicode-range')))) continue;
196
+ const source = fontSource(rule.style.getPropertyValue('src'));
197
+ if (!source) continue;
198
+ const file = new URL(source.url, rule.parentStyleSheet?.href ?? location.href).href;
199
+ jobs.push(toDataUrl(file).then((data) => faceRule(rule.style, data, source.format), () => ''));
200
+ }
201
+ return (await Promise.all(jobs)).join('\n');
202
+ }
@@ -0,0 +1,11 @@
1
+ /** A CSS length or number as a number (`'12.5px'` is 12.5); 0 when it is not one. */
2
+ export function cssNumber(v: string): number;
3
+
4
+ /** A number to at most two decimal places, as an attribute's text. */
5
+ export function round2(n: number): string;
6
+
7
+ /** Text made safe inside an XML element or a double-quoted attribute (`&`, `<`, `>` and `"` escaped). */
8
+ export function escapeXml(s: string): string;
9
+
10
+ /** A computed 2D transform's six numbers, `[a, b, c, d, e, f]`; null for anything but a `matrix()`. */
11
+ export function matrixOf(t: string): number[] | null;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/export/format
3
+ *
4
+ * Values read from a computed style, and values written into SVG: a CSS
5
+ * length as a number, a number to two decimal places, text escaped for
6
+ * XML, and a 2D `matrix()` transform as its six numbers.
7
+ */
8
+
9
+ /**
10
+ * A CSS length or number as a number (`'12.5px'` is 12.5); 0 when it is not one.
11
+ *
12
+ * @param {string} v The computed value.
13
+ * @returns {number} Its number.
14
+ */
15
+ export const cssNumber = (v) => parseFloat(v) || 0;
16
+
17
+ /**
18
+ * A number to at most two decimal places, as an attribute's text.
19
+ *
20
+ * @param {number} n The number.
21
+ * @returns {string} It, rounded.
22
+ */
23
+ export const round2 = (n) => String(Math.round(n * 100) / 100);
24
+
25
+ /**
26
+ * Text made safe inside an XML element or a double-quoted attribute.
27
+ *
28
+ * @param {string} s The text.
29
+ * @returns {string} It, with `&`, `<`, `>` and `"` escaped.
30
+ */
31
+ export const escapeXml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
32
+
33
+ /**
34
+ * A computed 2D transform's six numbers.
35
+ *
36
+ * @param {string} t The computed `transform`.
37
+ * @returns {number[] | null} `[a, b, c, d, e, f]` of a `matrix()`, or null for anything else (`none`, a `matrix3d()`).
38
+ */
39
+ export function matrixOf(t) {
40
+ const m = t.match(/^matrix\(([^)]+)\)$/);
41
+ return m ? m[1].split(',').map(Number) : null;
42
+ }
@@ -0,0 +1,16 @@
1
+ /** A colour as hex and alpha. */
2
+ export interface HexColor {
3
+ /** `#rrggbb`. */
4
+ hex: string;
5
+ /** Alpha, 0–1. */
6
+ a: number;
7
+ }
8
+
9
+ /** A pixel (each channel 0–255) as hex and alpha, un-premultiplied; null for a clear pixel. */
10
+ export function pixelColor(r: number, g: number, b: number, a: number): HexColor | null;
11
+
12
+ /** Any CSS colour (`rgb()`, `color()`, `oklab()`, a `color-mix()` result) as hex and alpha, read back from a pixel; null for none or anything fully clear. */
13
+ export function cssColor(v: string): HexColor | null;
14
+
15
+ /** A font's ascent and descent at a size (a CSS `font` shorthand), CSS px, as the browser lays a line's content box. */
16
+ export function fontMetrics(font: string): { asc: number; desc: number };
@@ -0,0 +1,89 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/export/probe
3
+ *
4
+ * What the browser alone can say about a value, read back from a 1 × 1
5
+ * canvas: any CSS colour (`rgb()`, `color()`, `oklab()`, a `color-mix()`
6
+ * result) as hex and alpha, and a font's ascent and descent. Each answer
7
+ * is kept, so asking again costs nothing.
8
+ */
9
+
10
+ /** The canvas the values are read from, made on first use. */
11
+ /** @type {CanvasRenderingContext2D | null} */
12
+ let probe = null;
13
+
14
+ /** @type {Map<string, { hex: string, a: number } | null>} */
15
+ const colors = new Map();
16
+
17
+ /** @type {Map<string, { asc: number, desc: number }>} */
18
+ const metrics = new Map();
19
+
20
+ /**
21
+ * The 1 × 1 canvas's context.
22
+ *
23
+ * @returns {CanvasRenderingContext2D} The context.
24
+ */
25
+ function context() {
26
+ probe ??= /** @type {CanvasRenderingContext2D} */ (Object.assign(document.createElement('canvas'), { width: 1, height: 1 }).getContext('2d', { willReadFrequently: true }));
27
+ return probe;
28
+ }
29
+
30
+ /**
31
+ * A pixel as hex and alpha, un-premultiplied (exact for an opaque colour,
32
+ * which is nearly all of them; approximate at low alpha).
33
+ *
34
+ * @param {number} r Red, 0–255.
35
+ * @param {number} g Green, 0–255.
36
+ * @param {number} b Blue, 0–255.
37
+ * @param {number} a Alpha, 0–255.
38
+ * @returns {{ hex: string, a: number } | null} `#rrggbb` and alpha 0–1, or null for a clear pixel.
39
+ */
40
+ export function pixelColor(r, g, b, a) {
41
+ if (!a) return null;
42
+ /**
43
+ * A channel as two hex digits.
44
+ *
45
+ * @param {number} x The channel, 0–255.
46
+ * @returns {string} Its digits.
47
+ */
48
+ const hex = (x) => x.toString(16).padStart(2, '0');
49
+ if (a === 255) return { hex: `#${[r, g, b].map(hex).join('')}`, a: 1 };
50
+ return { hex: `#${[r, g, b].map((x) => hex(Math.round(x * (255 / a)))).join('').slice(0, 6)}`, a: a / 255 };
51
+ }
52
+
53
+ /**
54
+ * Any CSS colour as hex and alpha.
55
+ *
56
+ * @param {string} v The colour, as a computed style gives it.
57
+ * @returns {{ hex: string, a: number } | null} `#rrggbb` and alpha 0–1, or null for none, `transparent` or anything fully clear.
58
+ */
59
+ export function cssColor(v) {
60
+ if (!v || v === 'none' || v === 'transparent') return null;
61
+ if (colors.has(v)) return /** @type {{ hex: string, a: number } | null} */ (colors.get(v));
62
+ const ctx = context();
63
+ ctx.clearRect(0, 0, 1, 1);
64
+ ctx.fillStyle = '#000';
65
+ ctx.fillStyle = v;
66
+ ctx.fillRect(0, 0, 1, 1);
67
+ const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data;
68
+ const out = pixelColor(r, g, b, a);
69
+ colors.set(v, out);
70
+ return out;
71
+ }
72
+
73
+ /**
74
+ * A font's ascent and descent at a size, as the browser lays a line's
75
+ * content box.
76
+ *
77
+ * @param {string} font A CSS `font` shorthand (style, weight, size and family).
78
+ * @returns {{ asc: number, desc: number }} Ascent and descent, CSS px.
79
+ */
80
+ export function fontMetrics(font) {
81
+ const known = metrics.get(font);
82
+ if (known) return known;
83
+ const ctx = context();
84
+ ctx.font = font;
85
+ const m = ctx.measureText('Hg');
86
+ const out = { asc: m.fontBoundingBoxAscent, desc: m.fontBoundingBoxDescent };
87
+ metrics.set(font, out);
88
+ return out;
89
+ }
@@ -0,0 +1,17 @@
1
+ /** An SVG document's text as a `data:` URL (which a CSP with `img-src data:` allows, where it may not allow `blob:`). */
2
+ export function svgDataUrl(svg: string): string;
3
+
4
+ /** Loads a picture (a `data:` URL, or same-origin) and waits until it can be drawn, then `settle` ms more (default 0) for an SVG's own web fonts. */
5
+ export function decodeImage(src: string, settle?: number): Promise<HTMLImageElement>;
6
+
7
+ /** Draws an SVG (its text, or a URL to it) onto a canvas, filling it at `width` × `height` px: a new canvas unless one is given (cleared and sized first); waits `settle` ms (default 250) after it decodes, for its fonts. */
8
+ export function drawSvg<C extends HTMLCanvasElement | OffscreenCanvas = HTMLCanvasElement>(svg: string, width: number, height: number, canvas?: C, settle?: number): Promise<C>;
9
+
10
+ /** A canvas as an image file: `type` (default `image/png`; `image/jpeg` or `image/webp` at `quality`, 0–1). */
11
+ export function imageOf(canvas: HTMLCanvasElement | OffscreenCanvas, type?: string, quality?: number): Promise<Blob>;
12
+
13
+ /** A canvas as a PNG. */
14
+ export function pngOf(canvas: HTMLCanvasElement | OffscreenCanvas): Promise<Blob>;
15
+
16
+ /** An SVG (its text, or a URL to it) drawn to an image file's bytes at `width` × `height` px: a PNG by default, or `type` (`image/jpeg`, `image/webp`) at `quality`, 0–1; `settle` ms (default 0) to wait for its fonts. */
17
+ export function rasterize(svg: string, size: { width: number; height: number; settle?: number }, type?: string, quality?: number): Promise<Uint8Array>;
@@ -0,0 +1,91 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/export/raster
3
+ *
4
+ * Pictures out of SVG: an SVG (as text or by URL) drawn to a canvas at any
5
+ * size, and a canvas as a PNG or JPEG. SVG text is loaded as a `data:`
6
+ * URL, never a `blob:` one, so a page whose Content Security Policy
7
+ * allows `img-src data:` (and not `blob:`) can use it.
8
+ */
9
+
10
+ /**
11
+ * An SVG document's text as a `data:` URL.
12
+ *
13
+ * @param {string} svg The document.
14
+ * @returns {string} Its `data:` URL.
15
+ */
16
+ export const svgDataUrl = (svg) => `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
17
+
18
+ /**
19
+ * Loads a picture and waits until it can be drawn.
20
+ *
21
+ * @param {string} src Its URL (a `data:` URL, or same-origin).
22
+ * @param {number} [settle] Milliseconds more to wait after it decodes. An SVG's own web fonts load after its first paint (its words are blank until then), so an SVG that carries fonts wants a moment the first time; a font it has loaded once is kept for the page. Default 0.
23
+ * @returns {Promise<HTMLImageElement>} The picture, decoded.
24
+ */
25
+ export async function decodeImage(src, settle = 0) {
26
+ const img = new Image();
27
+ img.decoding = 'sync';
28
+ img.src = src;
29
+ await img.decode();
30
+ if (settle) await new Promise((r) => setTimeout(r, settle));
31
+ return img;
32
+ }
33
+
34
+ /**
35
+ * Draws an SVG onto a canvas, filling it.
36
+ *
37
+ * @template {HTMLCanvasElement | OffscreenCanvas} C
38
+ * @param {string} svg The SVG document's text, or a URL to it.
39
+ * @param {number} width Pixels.
40
+ * @param {number} height Pixels.
41
+ * @param {C} [canvas] A canvas to draw on (cleared first; its size is set to `width` × `height`). Default a new one.
42
+ * @param {number} [settle] Milliseconds to wait after it decodes (see `decodeImage`). Default 250.
43
+ * @returns {Promise<C>} The canvas.
44
+ */
45
+ export async function drawSvg(svg, width, height, canvas = /** @type {C} */ (document.createElement('canvas')), settle = 250) {
46
+ const img = await decodeImage(svg.trimStart().startsWith('<') ? svgDataUrl(svg) : svg, settle);
47
+ if (canvas.width !== width) canvas.width = width;
48
+ if (canvas.height !== height) canvas.height = height;
49
+ const ctx = /** @type {CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D} */ (canvas.getContext('2d'));
50
+ ctx.clearRect(0, 0, width, height);
51
+ ctx.drawImage(img, 0, 0, width, height);
52
+ return canvas;
53
+ }
54
+
55
+ /**
56
+ * A canvas as an image file.
57
+ *
58
+ * @param {HTMLCanvasElement | OffscreenCanvas} canvas The canvas.
59
+ * @param {string} [type] Its media type: `image/png`, or `image/jpeg` or `image/webp` at a quality. Default `image/png`.
60
+ * @param {number} [quality] For JPEG and WebP, 0–1. Default the browser's.
61
+ * @returns {Promise<Blob>} The file.
62
+ * @throws {Error} When the browser cannot encode it.
63
+ */
64
+ export function imageOf(canvas, type = 'image/png', quality) {
65
+ if ('convertToBlob' in canvas) return canvas.convertToBlob({ type, quality });
66
+ return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error(`export: ${type} failed`))), type, quality));
67
+ }
68
+
69
+ /**
70
+ * A canvas as a PNG.
71
+ *
72
+ * @param {HTMLCanvasElement | OffscreenCanvas} canvas The canvas.
73
+ * @returns {Promise<Blob>} The PNG.
74
+ */
75
+ export const pngOf = (canvas) => imageOf(canvas);
76
+
77
+ /**
78
+ * An SVG drawn to an image file's bytes, on a canvas of its own: a PNG,
79
+ * or a JPEG (or WebP) at a quality.
80
+ *
81
+ * @param {string} svg The SVG document's text, or a URL to it.
82
+ * @param {{ width: number, height: number, settle?: number }} size Pixels, and milliseconds to wait after it decodes for its fonts (see `decodeImage`; default 0).
83
+ * @param {string} [type] The file's media type. Default `image/png`.
84
+ * @param {number} [quality] For JPEG and WebP, 0–1. Default the browser's.
85
+ * @returns {Promise<Uint8Array>} The file's bytes.
86
+ */
87
+ export async function rasterize(svg, { width, height, settle = 0 }, type = 'image/png', quality) {
88
+ const canvas = await drawSvg(svg, width, height, document.createElement('canvas'), settle);
89
+ const blob = await imageOf(canvas, type, quality);
90
+ return new Uint8Array(await blob.arrayBuffer());
91
+ }
@@ -0,0 +1,5 @@
1
+ /** Hands a file to the browser to save as `filename` (a Blob, or text saved as `type`, default `image/svg+xml`). */
2
+ export function save(data: Blob | string, filename: string, type?: string): void;
3
+
4
+ /** A file name's part from any text: accents dropped, lower case, letters and digits with hyphens between; `export` when nothing is left. */
5
+ export function fileSlug(s: string): string;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/export/save
3
+ *
4
+ * A file handed to the browser to save, and a name for it made from any
5
+ * text.
6
+ */
7
+
8
+ /**
9
+ * Hands a file to the browser to save.
10
+ *
11
+ * @param {Blob | string} data The file (a Blob, or text saved as `type`).
12
+ * @param {string} filename Its name.
13
+ * @param {string} [type] The text's media type. Default `image/svg+xml`.
14
+ */
15
+ export function save(data, filename, type = 'image/svg+xml') {
16
+ const blob = typeof data === 'string' ? new Blob([data], { type }) : data;
17
+ const url = URL.createObjectURL(blob);
18
+ const a = document.createElement('a');
19
+ a.href = url;
20
+ a.download = filename;
21
+ a.rel = 'noopener';
22
+ document.body.append(a);
23
+ a.click();
24
+ a.remove();
25
+ setTimeout(() => URL.revokeObjectURL(url), 30_000);
26
+ }
27
+
28
+ /**
29
+ * A file name's part from any text: accents dropped, lower case, letters
30
+ * and digits with hyphens between.
31
+ *
32
+ * @param {string} s The text.
33
+ * @returns {string} The slug; `export` when nothing is left.
34
+ */
35
+ export const fileSlug = (s) =>
36
+ s
37
+ .normalize('NFKD')
38
+ .replace(/[̀-ͯ]/g, '')
39
+ .toLowerCase()
40
+ .replace(/[^a-z0-9]+/g, '-')
41
+ .replace(/^-|-$/g, '') || 'export';
@@ -0,0 +1,43 @@
1
+ /** What moved between frames: an element (or its pseudo-element) and the properties to read again. */
2
+ export interface Moved {
3
+ el: Element;
4
+ /** `'::before'` or `'::after'`, for its pseudo-element. */
5
+ pseudo?: string;
6
+ /** The properties; `'all'` reads the element and everything in it again (for a custom property others are computed from). */
7
+ props: string[] | 'all';
8
+ }
9
+
10
+ /** An element as a live, self-contained SVG. */
11
+ export interface Snapshot {
12
+ /** The element's width, CSS px. */
13
+ readonly width: number;
14
+ /** The element's height, CSS px. */
15
+ readonly height: number;
16
+ /** The SVG document, `scale` (default 1) times the element's size, every vector and word sharp. */
17
+ svg(scale?: number): string;
18
+ /** Reads the moved properties again from the page into the copy. */
19
+ update(moved: Moved[]): Promise<void>;
20
+ }
21
+
22
+ export interface SnapshotOptions {
23
+ /** Square corners, whatever the element's border-radius (an export of a card, not of its frame). Default true. */
24
+ square?: boolean;
25
+ /** Elements to leave out. */
26
+ skip?: (el: Element) => boolean;
27
+ }
28
+
29
+ /** The inline style that sets a snapshot's root in place, at its size, untransformed and with no shadow (`square` corners too). */
30
+ export function rootStyle(width: number, height: number, square: boolean): string;
31
+
32
+ /** The pseudo-elements' rules (`${n}::before` → declarations), each on the `xs${n}` class its element's copy carries. */
33
+ export function pseudoCss(rules: Map<string, string>): string;
34
+
35
+ /** The SVG document round a serialised copy: `scale` times the element's size, a `<foreignObject>` holding it. */
36
+ export function snapshotSvg(body: string, width: number, height: number, scale: number): string;
37
+
38
+ /**
39
+ * An element (shown, laid out) as a self-contained SVG: a copy with every computed style inline, its pseudo-elements as
40
+ * rules, its pictures, canvases and fonts inlined, in a `<foreignObject>`. Drawn to a canvas it is a pixel-faithful
41
+ * picture of the element; `update()` rewrites only what a stepped `clock` moved.
42
+ */
43
+ export function snapshot(el: HTMLElement, options?: SnapshotOptions): Promise<Snapshot>;