@arraypress/effects-astro 0.7.0 → 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.
- package/README.md +1 -1
- package/package.json +6 -2
- package/src/index.d.ts +1 -0
- package/src/index.js +1 -0
- package/src/runtime/budget.d.ts +8 -0
- package/src/runtime/budget.js +49 -0
- package/src/runtime/export/clean-svg.d.ts +21 -0
- package/src/runtime/export/clean-svg.js +368 -0
- package/src/runtime/export/clock.d.ts +25 -0
- package/src/runtime/export/clock.js +122 -0
- package/src/runtime/export/fetch.d.ts +14 -0
- package/src/runtime/export/fetch.js +121 -0
- package/src/runtime/export/fonts.d.ts +30 -0
- package/src/runtime/export/fonts.js +202 -0
- package/src/runtime/export/format.d.ts +11 -0
- package/src/runtime/export/format.js +42 -0
- package/src/runtime/export/probe.d.ts +16 -0
- package/src/runtime/export/probe.js +89 -0
- package/src/runtime/export/raster.d.ts +17 -0
- package/src/runtime/export/raster.js +91 -0
- package/src/runtime/export/save.d.ts +5 -0
- package/src/runtime/export/save.js +41 -0
- package/src/runtime/export/snapshot.d.ts +43 -0
- package/src/runtime/export/snapshot.js +276 -0
- package/src/runtime/export/styles.d.ts +18 -0
- package/src/runtime/export/styles.js +152 -0
- package/src/runtime/export/svg-attrs.d.ts +8 -0
- package/src/runtime/export/svg-attrs.js +274 -0
- package/src/runtime/export/svg-text.d.ts +21 -0
- package/src/runtime/export/svg-text.js +124 -0
- package/src/runtime/export/video.d.ts +45 -0
- package/src/runtime/export/video.js +106 -0
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module @arraypress/effects-astro/export/svg-attrs
|
|
3
|
+
*
|
|
4
|
+
* An inline `<svg>` in the page as a plain SVG fragment: each element's
|
|
5
|
+
* computed style written as presentation attributes (inherited ones only
|
|
6
|
+
* where they change), a CSS transform baked into its `transform`, the
|
|
7
|
+
* page's classes and data attributes dropped, and anything a `<use>`
|
|
8
|
+
* points to elsewhere on the page brought along. What plain SVG cannot
|
|
9
|
+
* say (a CSS filter or blend mode, a 3D transform) is listed as an issue.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { cssColor } from './probe.js';
|
|
13
|
+
import { cssNumber, matrixOf, round2 } from './format.js';
|
|
14
|
+
|
|
15
|
+
const SVG_NS = 'http://www.w3.org/2000/svg';
|
|
16
|
+
const XLINK = 'http://www.w3.org/1999/xlink';
|
|
17
|
+
|
|
18
|
+
/** Properties written where they differ from the parent's (they inherit). */
|
|
19
|
+
const INHERITED_ATTRS = [
|
|
20
|
+
'fill',
|
|
21
|
+
'fill-opacity',
|
|
22
|
+
'fill-rule',
|
|
23
|
+
'stroke',
|
|
24
|
+
'stroke-width',
|
|
25
|
+
'stroke-opacity',
|
|
26
|
+
'stroke-linecap',
|
|
27
|
+
'stroke-linejoin',
|
|
28
|
+
'stroke-miterlimit',
|
|
29
|
+
'stroke-dasharray',
|
|
30
|
+
'stroke-dashoffset',
|
|
31
|
+
'clip-rule',
|
|
32
|
+
'paint-order',
|
|
33
|
+
'font-family',
|
|
34
|
+
'font-size',
|
|
35
|
+
'font-weight',
|
|
36
|
+
'font-style',
|
|
37
|
+
'letter-spacing',
|
|
38
|
+
'text-anchor',
|
|
39
|
+
'dominant-baseline',
|
|
40
|
+
'visibility',
|
|
41
|
+
'shape-rendering',
|
|
42
|
+
'color-interpolation-filters',
|
|
43
|
+
];
|
|
44
|
+
|
|
45
|
+
/** Properties written where they differ from SVG's initial value (they do not inherit). */
|
|
46
|
+
const OWN_ATTRS = ['opacity', 'stop-color', 'stop-opacity', 'flood-color', 'flood-opacity', 'lighting-color', 'clip-path', 'mask', 'filter', 'vector-effect'];
|
|
47
|
+
|
|
48
|
+
/** SVG's initial values, what the nested root is compared with. */
|
|
49
|
+
/** @type {Record<string, string>} */
|
|
50
|
+
const INITIAL = {
|
|
51
|
+
fill: '#000000',
|
|
52
|
+
'fill-opacity': '1',
|
|
53
|
+
'fill-rule': 'nonzero',
|
|
54
|
+
stroke: 'none',
|
|
55
|
+
'stroke-width': '1',
|
|
56
|
+
'stroke-opacity': '1',
|
|
57
|
+
'stroke-linecap': 'butt',
|
|
58
|
+
'stroke-linejoin': 'miter',
|
|
59
|
+
'stroke-miterlimit': '4',
|
|
60
|
+
'stroke-dasharray': 'none',
|
|
61
|
+
'stroke-dashoffset': '0',
|
|
62
|
+
'clip-rule': 'nonzero',
|
|
63
|
+
'paint-order': 'normal',
|
|
64
|
+
'letter-spacing': 'normal',
|
|
65
|
+
'text-anchor': 'start',
|
|
66
|
+
'dominant-baseline': 'auto',
|
|
67
|
+
visibility: 'visible',
|
|
68
|
+
'shape-rendering': 'auto',
|
|
69
|
+
'color-interpolation-filters': 'linearRGB',
|
|
70
|
+
opacity: '1',
|
|
71
|
+
'stop-color': '#000000',
|
|
72
|
+
'stop-opacity': '1',
|
|
73
|
+
'flood-color': '#000000',
|
|
74
|
+
'flood-opacity': '1',
|
|
75
|
+
'lighting-color': '#ffffff',
|
|
76
|
+
'clip-path': 'none',
|
|
77
|
+
mask: 'none',
|
|
78
|
+
filter: 'none',
|
|
79
|
+
'vector-effect': 'none',
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** Properties that take a paint (a colour or a `url()`). */
|
|
83
|
+
const PAINTS = new Set(['fill', 'stroke', 'stop-color', 'flood-color', 'lighting-color']);
|
|
84
|
+
|
|
85
|
+
/** Where a paint's alpha goes. */
|
|
86
|
+
/** @type {Record<string, string>} */
|
|
87
|
+
const ALPHA_OF = { fill: 'fill-opacity', stroke: 'stroke-opacity', 'stop-color': 'stop-opacity', 'flood-color': 'flood-opacity' };
|
|
88
|
+
|
|
89
|
+
/** Shapes whose geometry a stylesheet can set. */
|
|
90
|
+
const SHAPES = ['rect', 'circle', 'ellipse'];
|
|
91
|
+
|
|
92
|
+
/** The geometry properties read back from them. */
|
|
93
|
+
const GEOMETRY = ['x', 'y', 'cx', 'cy', 'r', 'rx', 'ry', 'width', 'height'];
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* A computed value as an attribute's: px dropped, `url("#a")` as
|
|
97
|
+
* `url(#a)`, a colour as hex (its alpha noted in `alpha`).
|
|
98
|
+
*
|
|
99
|
+
* @param {string} name The property.
|
|
100
|
+
* @param {string} v Its computed value.
|
|
101
|
+
* @param {Map<string, number>} alpha Collects each paint's alpha, by the opacity attribute it goes into.
|
|
102
|
+
* @returns {string} The attribute's value.
|
|
103
|
+
*/
|
|
104
|
+
export function attrValue(name, v, alpha) {
|
|
105
|
+
if (PAINTS.has(name)) {
|
|
106
|
+
if (v === 'none') return 'none';
|
|
107
|
+
if (v.startsWith('url(')) return v.replace(/url\("?([^")]+)"?\)(.*)/, 'url($1)');
|
|
108
|
+
const c = cssColor(v);
|
|
109
|
+
if (!c) return 'none';
|
|
110
|
+
if (c.a < 1 && ALPHA_OF[name]) alpha.set(ALPHA_OF[name], c.a);
|
|
111
|
+
return c.hex;
|
|
112
|
+
}
|
|
113
|
+
if (['clip-path', 'mask', 'filter'].includes(name)) return v === 'none' ? 'none' : v.replace(/url\("?([^")]+)"?\)/, 'url($1)');
|
|
114
|
+
if (name === 'stroke-dasharray') return v === 'none' ? 'none' : v.replace(/px/g, '').replace(/,\s*/g, ' ');
|
|
115
|
+
if (name === 'font-family') return v.replace(/"/g, "'");
|
|
116
|
+
return v.replace(/(\d)px\b/g, '$1');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* A CSS transform about its origin, as an SVG `transform` attribute
|
|
121
|
+
* (about the user space's 0, 0).
|
|
122
|
+
*
|
|
123
|
+
* @param {number[]} m The computed `matrix()`'s six numbers.
|
|
124
|
+
* @param {number} ox The transform origin's x.
|
|
125
|
+
* @param {number} oy The transform origin's y.
|
|
126
|
+
* @returns {string} The attribute's `matrix(…)`.
|
|
127
|
+
*/
|
|
128
|
+
export function aboutOrigin([a, b, c, d, e, f], ox, oy) {
|
|
129
|
+
const tx = e + ox - a * ox - c * oy,
|
|
130
|
+
ty = f + oy - b * ox - d * oy;
|
|
131
|
+
return `matrix(${[a, b, c, d, tx, ty].map(round2).join(' ')})`;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Removes the page's own attributes from a copied element: its class,
|
|
136
|
+
* style and data attributes, and its ARIA ones when asked.
|
|
137
|
+
*
|
|
138
|
+
* @param {Element} e The copy.
|
|
139
|
+
* @param {boolean} aria Whether to remove `aria-` attributes too.
|
|
140
|
+
*/
|
|
141
|
+
function stripPageAttrs(e, aria) {
|
|
142
|
+
for (const a of [...e.attributes]) if (a.name === 'class' || a.name === 'style' || a.name.startsWith('data-') || (aria && a.name.startsWith('aria-'))) e.removeAttribute(a.name);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Geometry a stylesheet set on a shape (a circle's `r`, a rect's size),
|
|
147
|
+
* where it differs from the attribute.
|
|
148
|
+
*
|
|
149
|
+
* @param {SVGElement} o The element in the page.
|
|
150
|
+
* @param {CSSStyleDeclaration} cs Its computed style.
|
|
151
|
+
* @param {Map<string, string>} set Collects the attributes to write.
|
|
152
|
+
*/
|
|
153
|
+
function shapeGeometry(o, cs, set) {
|
|
154
|
+
if (!SHAPES.includes(o.localName)) return;
|
|
155
|
+
for (const g of GEOMETRY) {
|
|
156
|
+
const v = cs.getPropertyValue(g);
|
|
157
|
+
if (v && v !== 'auto' && /px$/.test(v) && cssNumber(o.getAttribute(g) ?? 'NaN') !== cssNumber(v)) set.set(g, round2(cssNumber(v)));
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* A CSS transform on an element, baked about its origin into the
|
|
163
|
+
* attribute (a 3D one is an issue).
|
|
164
|
+
*
|
|
165
|
+
* @param {SVGElement} o The element in the page.
|
|
166
|
+
* @param {CSSStyleDeclaration} cs Its computed style.
|
|
167
|
+
* @param {Map<string, string>} set Collects the attributes to write.
|
|
168
|
+
* @param {string[]} issues Collects what cannot be said in plain SVG.
|
|
169
|
+
*/
|
|
170
|
+
function bakedTransform(o, cs, set, issues) {
|
|
171
|
+
const t = cs.transform;
|
|
172
|
+
if (!t || t === 'none') return;
|
|
173
|
+
const m = matrixOf(t);
|
|
174
|
+
if (!m) {
|
|
175
|
+
issues.push('a 3D transform on the artwork');
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
let [ox, oy] = cs.transformOrigin.split(' ').map(cssNumber);
|
|
179
|
+
if (cs.transformBox === 'fill-box' && o instanceof SVGGraphicsElement) {
|
|
180
|
+
const bb = o.getBBox();
|
|
181
|
+
ox += bb.x;
|
|
182
|
+
oy += bb.y;
|
|
183
|
+
}
|
|
184
|
+
set.set('transform', aboutOrigin(m, ox, oy));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* One SVG element's computed style as attributes on its copy.
|
|
189
|
+
*
|
|
190
|
+
* @param {SVGElement} o The element in the page.
|
|
191
|
+
* @param {SVGElement} c Its copy.
|
|
192
|
+
* @param {CSSStyleDeclaration | null} parent The parent's computed style; null for the nested root.
|
|
193
|
+
* @param {string[]} issues Collects what cannot be said in plain SVG.
|
|
194
|
+
*/
|
|
195
|
+
function svgAttrs(o, c, parent, issues) {
|
|
196
|
+
const cs = getComputedStyle(o);
|
|
197
|
+
/** @type {Map<string, number>} */
|
|
198
|
+
const alpha = new Map();
|
|
199
|
+
/** @type {Map<string, string>} */
|
|
200
|
+
const set = new Map();
|
|
201
|
+
for (const name of INHERITED_ATTRS) {
|
|
202
|
+
const v = cs.getPropertyValue(name);
|
|
203
|
+
if (parent && v === parent.getPropertyValue(name)) continue;
|
|
204
|
+
const a = attrValue(name, v, alpha);
|
|
205
|
+
// the nested root says its paint whatever it is (its own fill="currentColor" means nothing out of the page)
|
|
206
|
+
if (parent || a !== INITIAL[name] || name === 'fill' || name === 'stroke') set.set(name, a);
|
|
207
|
+
}
|
|
208
|
+
for (const name of OWN_ATTRS) {
|
|
209
|
+
const v = cs.getPropertyValue(name);
|
|
210
|
+
if (name === 'filter' && v !== 'none' && !/^url\(/.test(v)) issues.push('a CSS filter on the artwork');
|
|
211
|
+
const a = attrValue(name, v, alpha);
|
|
212
|
+
if (a !== INITIAL[name]) set.set(name, a);
|
|
213
|
+
}
|
|
214
|
+
for (const [k, a] of alpha) set.set(k, round2(a * cssNumber(set.get(k) ?? cs.getPropertyValue(k) ?? '1')));
|
|
215
|
+
if (cs.mixBlendMode !== 'normal') issues.push('a blend mode on the artwork');
|
|
216
|
+
if (cs.display === 'none') set.set('display', 'none');
|
|
217
|
+
shapeGeometry(o, cs, set);
|
|
218
|
+
bakedTransform(o, cs, set, issues);
|
|
219
|
+
stripPageAttrs(c, true);
|
|
220
|
+
for (const [k, v] of set) c.setAttribute(k, v);
|
|
221
|
+
const href = c.localName === 'use' && c.getAttribute('href');
|
|
222
|
+
if (href) c.setAttributeNS(XLINK, 'xlink:href', href);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* A copy of whatever the `<use>`s in a copied SVG point to elsewhere on
|
|
227
|
+
* the page (a card's one copy of its mark, drawn in a sprite), so the
|
|
228
|
+
* fragment stands alone.
|
|
229
|
+
*
|
|
230
|
+
* @param {SVGSVGElement} c The copied SVG.
|
|
231
|
+
* @returns {SVGDefsElement | null} A `<defs>` holding the copies, or null when nothing is missing.
|
|
232
|
+
*/
|
|
233
|
+
function missingDefs(c) {
|
|
234
|
+
const missing = [...c.querySelectorAll('use')]
|
|
235
|
+
.map((u) => (u.getAttribute('href') ?? u.getAttribute('xlink:href') ?? '').slice(1))
|
|
236
|
+
.filter((id) => id && !c.querySelector(`[id="${CSS.escape(id)}"]`));
|
|
237
|
+
if (!missing.length) return null;
|
|
238
|
+
const defs = /** @type {SVGDefsElement} */ (document.createElementNS(SVG_NS, 'defs'));
|
|
239
|
+
for (const id of new Set(missing)) {
|
|
240
|
+
const target = document.getElementById(id);
|
|
241
|
+
if (!target) continue;
|
|
242
|
+
const copy = /** @type {Element} */ (target.cloneNode(true));
|
|
243
|
+
for (const e of [copy, ...copy.querySelectorAll('*')]) stripPageAttrs(e, false);
|
|
244
|
+
defs.append(copy);
|
|
245
|
+
}
|
|
246
|
+
return defs;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* An inline `<svg>` in the page, as a nested `<svg>` placed where it shows.
|
|
251
|
+
*
|
|
252
|
+
* @param {SVGSVGElement} o The SVG in the page.
|
|
253
|
+
* @param {DOMRect} box Its box.
|
|
254
|
+
* @param {DOMRect} origin The exported element's box (positions are measured from it).
|
|
255
|
+
* @param {string[]} issues Collects what cannot be said in plain SVG.
|
|
256
|
+
* @returns {string} The nested `<svg>`, serialised.
|
|
257
|
+
*/
|
|
258
|
+
export function inlineSvg(o, box, origin, issues) {
|
|
259
|
+
const c = /** @type {SVGSVGElement} */ (o.cloneNode(true));
|
|
260
|
+
const os = [o, ...o.querySelectorAll('*')];
|
|
261
|
+
const cs = [c, ...c.querySelectorAll('*')];
|
|
262
|
+
os.forEach((e, i) => svgAttrs(/** @type {SVGElement} */ (e), /** @type {SVGElement} */ (cs[i]), e === o ? null : getComputedStyle(e.parentElement ?? o), issues));
|
|
263
|
+
const defs = missingDefs(c);
|
|
264
|
+
if (defs) c.prepend(defs);
|
|
265
|
+
c.removeAttribute('transform'); // the outer box's transform is in its rect
|
|
266
|
+
c.removeAttribute('opacity'); // and its opacity on the group round it
|
|
267
|
+
c.setAttribute('x', round2(box.left - origin.left));
|
|
268
|
+
c.setAttribute('y', round2(box.top - origin.top));
|
|
269
|
+
c.setAttribute('width', round2(box.width));
|
|
270
|
+
c.setAttribute('height', round2(box.height));
|
|
271
|
+
if (!c.getAttribute('viewBox')) c.setAttribute('viewBox', `0 0 ${round2(o.clientWidth || box.width)} ${round2(o.clientHeight || box.height)}`);
|
|
272
|
+
if (getComputedStyle(o).overflow === 'visible') c.setAttribute('overflow', 'visible');
|
|
273
|
+
return new XMLSerializer().serializeToString(c).replace(/ xmlns="http:\/\/www\.w3\.org\/2000\/svg"/, '');
|
|
274
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** A line of text as the browser set it. */
|
|
2
|
+
export interface TextLine {
|
|
3
|
+
/** Its top, viewport px. */
|
|
4
|
+
top: number;
|
|
5
|
+
/** Its height, px. */
|
|
6
|
+
h: number;
|
|
7
|
+
/** Its left and right edges, viewport px. */
|
|
8
|
+
left: number;
|
|
9
|
+
right: number;
|
|
10
|
+
/** Its characters. */
|
|
11
|
+
s: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Text as `text-transform` (`uppercase`, `lowercase`, `capitalize`) shows it. */
|
|
15
|
+
export function transformText(s: string, t: string): string;
|
|
16
|
+
|
|
17
|
+
/** Characters (each with its box, in order) grouped into the lines they were set on. */
|
|
18
|
+
export function groupLines(glyphs: { rect: { top: number; left: number; right: number; height: number }; ch: string }[]): TextLine[];
|
|
19
|
+
|
|
20
|
+
/** A text node's lines as SVG `<text>` elements, each where the browser set it within `origin`, in its font and fill. */
|
|
21
|
+
export function textLines(node: Text, cs: CSSStyleDeclaration, origin: DOMRect, opacity: number): string;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module @arraypress/effects-astro/export/svg-text
|
|
3
|
+
*
|
|
4
|
+
* A text node as SVG `<text>` elements, one a line, each where the
|
|
5
|
+
* browser set it: its letters' boxes grouped into lines, the line's
|
|
6
|
+
* baseline from the font's ascent and descent, its width held with
|
|
7
|
+
* `textLength` so a design tool's own face sets it the same length.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { cssColor, fontMetrics } from './probe.js';
|
|
11
|
+
import { cssNumber, escapeXml, round2 } from './format.js';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A line of text as the browser set it.
|
|
15
|
+
*
|
|
16
|
+
* @typedef {object} TextLine
|
|
17
|
+
* @property {number} top Its top, viewport px.
|
|
18
|
+
* @property {number} h Its height, px.
|
|
19
|
+
* @property {number} left Its left edge, viewport px.
|
|
20
|
+
* @property {number} right Its right edge, viewport px.
|
|
21
|
+
* @property {string} s Its characters.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Text as `text-transform` shows it.
|
|
26
|
+
*
|
|
27
|
+
* @param {string} s The text.
|
|
28
|
+
* @param {string} t The computed `text-transform`.
|
|
29
|
+
* @returns {string} The text as shown.
|
|
30
|
+
*/
|
|
31
|
+
export const transformText = (s, t) =>
|
|
32
|
+
t === 'uppercase' ? s.toUpperCase() : t === 'lowercase' ? s.toLowerCase() : t === 'capitalize' ? s.replace(/(^|\s)(\S)/g, (_, a, b) => a + b.toUpperCase()) : s;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Characters grouped into the lines they were set on: a character joins
|
|
36
|
+
* the line whose top is within half its height of its own.
|
|
37
|
+
*
|
|
38
|
+
* @param {{ rect: { top: number, left: number, right: number, height: number }, ch: string }[]} glyphs Each character and its box, in order.
|
|
39
|
+
* @returns {TextLine[]} The lines, in the order they start.
|
|
40
|
+
*/
|
|
41
|
+
export function groupLines(glyphs) {
|
|
42
|
+
/** @type {TextLine[]} */
|
|
43
|
+
const lines = [];
|
|
44
|
+
for (const { rect, ch } of glyphs) {
|
|
45
|
+
let line = lines.find((l) => Math.abs(l.top - rect.top) < rect.height / 2);
|
|
46
|
+
if (!line) lines.push((line = { top: rect.top, h: rect.height, left: rect.left, right: rect.right, s: '' }));
|
|
47
|
+
line.left = Math.min(line.left, rect.left);
|
|
48
|
+
line.right = Math.max(line.right, rect.right);
|
|
49
|
+
line.s += ch;
|
|
50
|
+
}
|
|
51
|
+
return lines;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Each character of a text node and its box (a character with no box,
|
|
56
|
+
* collapsed white space, is left out).
|
|
57
|
+
*
|
|
58
|
+
* @param {Text} node The text node.
|
|
59
|
+
* @returns {{ rect: DOMRect, ch: string }[]} The characters.
|
|
60
|
+
*/
|
|
61
|
+
function glyphsOf(node) {
|
|
62
|
+
const text = node.data;
|
|
63
|
+
const range = document.createRange();
|
|
64
|
+
/** @type {{ rect: DOMRect, ch: string }[]} */
|
|
65
|
+
const glyphs = [];
|
|
66
|
+
for (let i = 0; i < text.length; i++) {
|
|
67
|
+
range.setStart(node, i);
|
|
68
|
+
range.setEnd(node, i + 1);
|
|
69
|
+
const rect = range.getClientRects()[0];
|
|
70
|
+
if (rect) glyphs.push({ rect, ch: text[i] });
|
|
71
|
+
}
|
|
72
|
+
return glyphs;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* What every line of a piece of text shares: its font, spacing and fill
|
|
77
|
+
* as attributes, and what only CSS can say (a width, variable axes) as a
|
|
78
|
+
* style.
|
|
79
|
+
*
|
|
80
|
+
* @param {CSSStyleDeclaration} cs The text's computed style.
|
|
81
|
+
* @param {{ hex: string, a: number }} fill Its fill colour.
|
|
82
|
+
* @param {number} opacity Its element's opacity.
|
|
83
|
+
* @param {number} ls Its letter-spacing, px.
|
|
84
|
+
* @returns {{ attrs: string, style: string }} The attributes (each with a space before it), and the style (empty for none), escaped.
|
|
85
|
+
*/
|
|
86
|
+
function fontAttrs(cs, fill, opacity, ls) {
|
|
87
|
+
const style = [cs.fontStretch !== '100%' && `font-stretch:${cs.fontStretch}`, cs.fontVariationSettings !== 'normal' && `font-variation-settings:${cs.fontVariationSettings}`]
|
|
88
|
+
.filter(Boolean)
|
|
89
|
+
.join(';');
|
|
90
|
+
const attrs =
|
|
91
|
+
` font-family="${escapeXml(cs.fontFamily.replace(/"/g, "'"))}" font-size="${round2(cssNumber(cs.fontSize))}" font-weight="${cs.fontWeight}"` +
|
|
92
|
+
(cs.fontStyle !== 'normal' ? ` font-style="${cs.fontStyle}"` : '') +
|
|
93
|
+
(ls ? ` letter-spacing="${round2(ls)}"` : '') +
|
|
94
|
+
` fill="${fill.hex}"` +
|
|
95
|
+
(fill.a * opacity < 1 ? ` fill-opacity="${round2(fill.a)}"` : '');
|
|
96
|
+
return { attrs, style: escapeXml(style) };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* A text node's lines as `<text>` elements, each where the browser set it.
|
|
101
|
+
*
|
|
102
|
+
* @param {Text} node The text node.
|
|
103
|
+
* @param {CSSStyleDeclaration} cs Its element's computed style.
|
|
104
|
+
* @param {DOMRect} origin The exported element's box (positions are measured from it).
|
|
105
|
+
* @param {number} opacity Its element's opacity.
|
|
106
|
+
* @returns {string} The `<text>` elements.
|
|
107
|
+
*/
|
|
108
|
+
export function textLines(node, cs, origin, opacity) {
|
|
109
|
+
const lines = groupLines(glyphsOf(node));
|
|
110
|
+
const fill = cssColor(cs.getPropertyValue('-webkit-text-fill-color') || cs.color);
|
|
111
|
+
if (!fill) return '';
|
|
112
|
+
const ls = cs.letterSpacing === 'normal' ? 0 : cssNumber(cs.letterSpacing);
|
|
113
|
+
const { asc, desc } = fontMetrics(`${cs.fontStyle} ${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`);
|
|
114
|
+
const { attrs, style } = fontAttrs(cs, fill, opacity, ls);
|
|
115
|
+
return lines
|
|
116
|
+
.map((l) => {
|
|
117
|
+
const body = transformText(l.s.replace(/\s+/g, ' '), cs.textTransform).trim();
|
|
118
|
+
if (!body) return '';
|
|
119
|
+
const y = l.top - origin.top + (l.h - (asc + desc)) / 2 + asc;
|
|
120
|
+
const w = l.right - l.left - ls; // the browser spaces after the last letter too
|
|
121
|
+
return `<text x="${round2(l.left - origin.left)}" y="${round2(y)}"${attrs} textLength="${round2(w)}" lengthAdjust="spacing"${style ? ` style="${style}"` : ''} xml:space="preserve">${escapeXml(body)}</text>`;
|
|
122
|
+
})
|
|
123
|
+
.join('');
|
|
124
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
export interface VideoOptions {
|
|
2
|
+
/** Pixels (made even: H.264 wants it). */
|
|
3
|
+
width: number;
|
|
4
|
+
/** Pixels (made even). */
|
|
5
|
+
height: number;
|
|
6
|
+
/** Frames a second. Default 30. */
|
|
7
|
+
fps?: number;
|
|
8
|
+
/** Seconds. */
|
|
9
|
+
duration: number;
|
|
10
|
+
/** Draws the frame at `t` seconds onto the canvas. */
|
|
11
|
+
draw: (t: number, canvas: HTMLCanvasElement) => Promise<void> | void;
|
|
12
|
+
/** Called after each frame with the share done, 0–1. */
|
|
13
|
+
progress?: (done: number) => void;
|
|
14
|
+
/** Stops the recording when it aborts. */
|
|
15
|
+
signal?: AbortSignal;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** A finished video: the file, its extension and its media type. */
|
|
19
|
+
export interface Video {
|
|
20
|
+
blob: Blob;
|
|
21
|
+
ext: 'mp4' | 'webm';
|
|
22
|
+
type: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The parts of mediabunny `pickFormat` uses. */
|
|
26
|
+
export interface VideoFormats {
|
|
27
|
+
getFirstEncodableVideoCodec(codecs: string[], size: { width: number; height: number }): Promise<string | null>;
|
|
28
|
+
Mp4OutputFormat: new (options: { fastStart: 'in-memory' }) => unknown;
|
|
29
|
+
WebMOutputFormat: new () => unknown;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Whether this browser can encode video at all (WebCodecs). */
|
|
33
|
+
export function canRecord(): boolean;
|
|
34
|
+
|
|
35
|
+
/** A size made even, as H.264 wants it (an odd side loses its last pixel). */
|
|
36
|
+
export function evenSize(width: number, height: number): { width: number; height: number };
|
|
37
|
+
|
|
38
|
+
/** The first container and codec the browser can encode at `size`: MP4 with H.264, else WebM with VP9, VP8 or AV1. Rejects when it can encode none. */
|
|
39
|
+
export function pickFormat<M extends VideoFormats>(mediabunny: M, size: { width: number; height: number }): Promise<{ codec: string; format: InstanceType<M['Mp4OutputFormat']> | InstanceType<M['WebMOutputFormat']> }>;
|
|
40
|
+
|
|
41
|
+
/** Steps through `frames` frames in order at `fps`, calling `frame(t, dt)` for each and `progress` after it; rejects with an `AbortError` once `signal` aborts. */
|
|
42
|
+
export function eachFrame(o: { frames: number; fps: number; signal?: AbortSignal; progress?: (done: number) => void }, frame: (t: number, dt: number) => Promise<void>): Promise<void>;
|
|
43
|
+
|
|
44
|
+
/** Records a video frame by frame (WebCodecs, muxed by the optional peer mediabunny): MP4 (H.264) where the browser can, else WebM. */
|
|
45
|
+
export function record(o: VideoOptions): Promise<Video>;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module @arraypress/effects-astro/export/video
|
|
3
|
+
*
|
|
4
|
+
* Frames to a video file in the browser: each frame drawn onto a canvas
|
|
5
|
+
* by the caller, encoded with WebCodecs and muxed by mediabunny (an
|
|
6
|
+
* optional peer dependency, loaded only when a recording starts). MP4
|
|
7
|
+
* (H.264) where the browser can encode it, else WebM (VP9, VP8 or AV1).
|
|
8
|
+
* Frames are added one at a time with exact timestamps, so a slow frame
|
|
9
|
+
* never stutters the result.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @typedef {object} VideoOptions
|
|
14
|
+
* @property {number} width Pixels (made even: H.264 wants it).
|
|
15
|
+
* @property {number} height Pixels (made even).
|
|
16
|
+
* @property {number} [fps] Frames a second. Default 30.
|
|
17
|
+
* @property {number} duration Seconds.
|
|
18
|
+
* @property {(t: number, canvas: HTMLCanvasElement) => Promise<void> | void} draw Draws the frame at `t` seconds onto the canvas.
|
|
19
|
+
* @property {(done: number) => void} [progress] Called after each frame with the share done, 0–1.
|
|
20
|
+
* @property {AbortSignal} [signal] Stops the recording when it aborts.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** @typedef {{ blob: Blob, ext: 'mp4' | 'webm', type: string }} Video A finished video: the file, its extension and its media type. */
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Whether this browser can encode video at all (WebCodecs).
|
|
27
|
+
*
|
|
28
|
+
* @returns {boolean} Whether it can.
|
|
29
|
+
*/
|
|
30
|
+
export const canRecord = () => typeof window !== 'undefined' && 'VideoEncoder' in window;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* A size made even, as H.264 wants it (an odd side loses its last pixel).
|
|
34
|
+
*
|
|
35
|
+
* @param {number} width Pixels.
|
|
36
|
+
* @param {number} height Pixels.
|
|
37
|
+
* @returns {{ width: number, height: number }} The even size.
|
|
38
|
+
*/
|
|
39
|
+
export const evenSize = (width, height) => ({ width: width - (width % 2), height: height - (height % 2) });
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The first container and codec this browser can encode at a size: MP4
|
|
43
|
+
* with H.264, else WebM with VP9, VP8 or AV1.
|
|
44
|
+
*
|
|
45
|
+
* @param {any} mb The mediabunny module (or anything with its `getFirstEncodableVideoCodec`, `Mp4OutputFormat` and `WebMOutputFormat`).
|
|
46
|
+
* @param {{ width: number, height: number }} size The video's size.
|
|
47
|
+
* @returns {Promise<{ codec: string, format: any }>} The codec and an output format for it.
|
|
48
|
+
* @throws {Error} When the browser can encode none of them.
|
|
49
|
+
*/
|
|
50
|
+
export async function pickFormat(mb, size) {
|
|
51
|
+
const avc = await mb.getFirstEncodableVideoCodec(['avc'], size);
|
|
52
|
+
if (avc) return { codec: avc, format: new mb.Mp4OutputFormat({ fastStart: 'in-memory' }) };
|
|
53
|
+
const web = await mb.getFirstEncodableVideoCodec(['vp9', 'vp8', 'av1'], size);
|
|
54
|
+
if (web) return { codec: web, format: new mb.WebMOutputFormat() };
|
|
55
|
+
throw new Error('export: this browser cannot encode video');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Steps through a recording's frames in order, one at a time, each at its
|
|
60
|
+
* exact time; stops with an `AbortError` as soon as the signal aborts.
|
|
61
|
+
*
|
|
62
|
+
* @param {{ frames: number, fps: number, signal?: AbortSignal, progress?: (done: number) => void }} o How many frames, at what rate, a signal to stop at, and what to tell after each.
|
|
63
|
+
* @param {(t: number, dt: number) => Promise<void>} frame Makes the frame at `t` seconds, `dt` long.
|
|
64
|
+
* @returns {Promise<void>} Once every frame is made.
|
|
65
|
+
*/
|
|
66
|
+
export async function eachFrame({ frames, fps, signal, progress }, frame) {
|
|
67
|
+
for (let i = 0; i < frames; i++) {
|
|
68
|
+
if (signal?.aborted) throw new DOMException('Recording stopped', 'AbortError');
|
|
69
|
+
await frame(i / fps, 1 / fps);
|
|
70
|
+
progress?.((i + 1) / frames);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Records a video, frame by frame.
|
|
76
|
+
*
|
|
77
|
+
* @param {VideoOptions} o Its size, rate and length, and how to draw a frame.
|
|
78
|
+
* @returns {Promise<Video>} The video.
|
|
79
|
+
* @throws {Error} When the browser cannot encode video, or (an `AbortError`) when it was stopped.
|
|
80
|
+
*/
|
|
81
|
+
export async function record(o) {
|
|
82
|
+
const mb = await import('mediabunny');
|
|
83
|
+
const { Output, BufferTarget, CanvasSource, QUALITY_HIGH } = mb;
|
|
84
|
+
const fps = o.fps ?? 30;
|
|
85
|
+
const size = evenSize(o.width, o.height);
|
|
86
|
+
const { codec, format } = await pickFormat(mb, size);
|
|
87
|
+
const canvas = document.createElement('canvas');
|
|
88
|
+
canvas.width = size.width;
|
|
89
|
+
canvas.height = size.height;
|
|
90
|
+
const target = new BufferTarget();
|
|
91
|
+
const output = new Output({ format, target });
|
|
92
|
+
const source = new CanvasSource(canvas, { codec, bitrate: QUALITY_HIGH, keyFrameInterval: 2 });
|
|
93
|
+
output.addVideoTrack(source, { frameRate: fps });
|
|
94
|
+
await output.start();
|
|
95
|
+
try {
|
|
96
|
+
await eachFrame({ frames: Math.round(o.duration * fps), fps, signal: o.signal, progress: o.progress }, async (t, dt) => {
|
|
97
|
+
await o.draw(t, canvas);
|
|
98
|
+
await source.add(t, dt);
|
|
99
|
+
});
|
|
100
|
+
await output.finalize();
|
|
101
|
+
} catch (e) {
|
|
102
|
+
await output.cancel().catch(() => {});
|
|
103
|
+
throw e;
|
|
104
|
+
}
|
|
105
|
+
return { blob: new Blob([/** @type {ArrayBuffer} */ (target.buffer)], { type: format.mimeType }), ext: format.fileExtension.slice(1), type: format.mimeType };
|
|
106
|
+
}
|