@openartifactsai/export-kit 0.0.0-stage → 0.23.0-rc.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,507 @@
1
+ /**
2
+ * A rendered document as pictures: {@link pageImage} draws a document's
3
+ * viewport (an artboard, a page of a long document), and {@link captureHtml}
4
+ * rewrites an element as standalone HTML with its computed styles inlined,
5
+ * which is what the browser is asked to paint through a `<foreignObject>`.
6
+ *
7
+ * The browser paints the computed HTML, which keeps what only it can draw:
8
+ * shadows, filters, blending, masks, `::before`. Where the canvas cannot be
9
+ * read back afterwards, and for a slice of a long page, dom-to-svg rebuilds
10
+ * the page as SVG shapes instead. Every picture carries the web fonts its
11
+ * document uses, inlined (`embeddedFontCss`): a picture is drawn apart from
12
+ * the page and cannot load them itself.
13
+ *
14
+ * Needs a DOM. Shared by the Design editor (artboards) and the Data editor
15
+ * (the dashboard's PDF).
16
+ */
17
+ import { canvasArea, SAFE_CANVAS_AREA } from "./canvas-area.js";
18
+ import { elementSvg, foreignObjectSvg, loadSvgImage, maxCaptureScale, SVG_NS } from "./capture.js";
19
+ import { embeddedFontCss } from "./font-embed.js";
20
+ import { cssUrls } from "./fonts.js";
21
+ import { blobToDataUrl } from "./pictures.js";
22
+ const PNG_SCALE = 2;
23
+ /** How large a capture may be: 12000 px a side, 120 megapixels. */
24
+ export const CAPTURE_LIMITS = { maxSide: 12000, maxPixels: 120_000_000 };
25
+ /** Rounding a capture's sides up adds at most a row and a column of pixels. */
26
+ const canvasPixels = canvasArea(CAPTURE_LIMITS.maxPixels, SAFE_CANVAS_AREA - (CAPTURE_LIMITS.maxSide + 1));
27
+ /** {@link CAPTURE_LIMITS} with the canvas area this browser is drawing at now (lowered after a canvas it would not make). */
28
+ export function captureLimits() {
29
+ return { maxSide: CAPTURE_LIMITS.maxSide, maxPixels: canvasPixels.limit };
30
+ }
31
+ /** Web fonts inlined into one picture unless the caller sets its own limit, characters of `data:` URL. */
32
+ const FONT_BYTES = 64 * 1024 * 1024;
33
+ /** The web fonts a document's pictures carry; none when they cannot be read (the picture is still drawn, in fallback fonts). */
34
+ export const documentFonts = (doc, maxBytes = FONT_BYTES) => embeddedFontCss(doc, { maxBytes }).catch(() => ({ css: '', skipped: [] }));
35
+ /* ----------------------------------- SVG ---------------------------------- */
36
+ /** Removes what the copy should not carry: scripts, handlers, debug data, external links. */
37
+ export function cleanSvg(root) {
38
+ for (const node of [root, ...root.querySelectorAll('*')]) {
39
+ if (/^(script|foreignObject)$/i.test(node.localName)) {
40
+ node.remove();
41
+ continue;
42
+ }
43
+ for (const attr of [...node.attributes]) {
44
+ const name = attr.name.toLowerCase();
45
+ const href = name === 'href' || name === 'xlink:href';
46
+ if (name.startsWith('on') || name.startsWith('data-') || name === 'class' || (href && !(attr.value.startsWith('#') || (node.localName === 'image' && attr.value.startsWith('data:image/')))))
47
+ node.removeAttribute(attr.name);
48
+ }
49
+ }
50
+ // Links become plain groups.
51
+ for (const link of [...root.querySelectorAll('a')]) {
52
+ const group = root.ownerDocument.createElementNS(SVG_NS, 'g');
53
+ for (const attr of [...link.attributes])
54
+ group.setAttribute(attr.name, attr.value);
55
+ group.append(...link.childNodes);
56
+ link.replaceWith(group);
57
+ }
58
+ // Empty groups and styles (stacking layers with nothing in the captured area).
59
+ for (const node of [...root.querySelectorAll('g, style')].reverse()) {
60
+ if (!node.childNodes.length && !node.id)
61
+ node.remove();
62
+ }
63
+ root.removeAttribute('aria-owns');
64
+ }
65
+ /** Figma's Chrome capture reads paint from the definition, losing the
66
+ * currentColor inherited through a use. Specialise simple geometry symbols
67
+ * per instance, keeping the original for other uses and referenced IDs. */
68
+ function portableSymbolPaints(source, copy) {
69
+ const originals = source.querySelectorAll('use');
70
+ for (const [i, use] of [...copy.querySelectorAll('use')].entries()) {
71
+ const href = use.getAttribute('href') ?? use.getAttribute('xlink:href');
72
+ if (!href?.startsWith('#'))
73
+ continue;
74
+ const symbol = copy.querySelector('symbol#' + CSS.escape(href.slice(1)));
75
+ if (!symbol || symbol.querySelector('[id], use') || !/currentcolor/i.test(symbol.outerHTML))
76
+ continue;
77
+ const instance = symbol.cloneNode(true);
78
+ instance.id = 'export-symbol-' + crypto.getRandomValues(new Uint32Array(4)).join('-');
79
+ const paint = source.ownerDocument.defaultView.getComputedStyle(originals[i]).color;
80
+ for (const shape of [instance, ...instance.querySelectorAll('*')]) {
81
+ let color = paint;
82
+ for (let ancestor = shape; ancestor; ancestor = ancestor.parentElement) {
83
+ const own = ancestor.style.color || ancestor.getAttribute('color');
84
+ if (own && !/^(currentcolor|inherit|unset)$/i.test(own)) {
85
+ color = own;
86
+ break;
87
+ }
88
+ }
89
+ for (const name of ['fill', 'stroke']) {
90
+ if ((shape.style.getPropertyValue(name) || shape.getAttribute(name))?.toLowerCase() === 'currentcolor') {
91
+ shape.style.setProperty(name, color);
92
+ shape.setAttribute(name, color);
93
+ }
94
+ }
95
+ }
96
+ symbol.after(instance);
97
+ use.setAttribute('href', '#' + instance.id);
98
+ }
99
+ }
100
+ /** One drawing of `image` on a canvas; `blob` is null when the browser gave back an empty canvas. */
101
+ async function drawOnCanvas(image, width, height, scale, { type = 'image/png', background, keep }) {
102
+ const canvas = document.createElement('canvas');
103
+ canvas.width = Math.max(1, Math.round(width * scale));
104
+ canvas.height = Math.max(1, Math.round(height * scale));
105
+ const pixels = canvas.width * canvas.height;
106
+ const context = canvas.getContext('2d');
107
+ if (!context)
108
+ return { blob: null, pixels };
109
+ if (background) {
110
+ context.fillStyle = background;
111
+ context.fillRect(0, 0, canvas.width, canvas.height);
112
+ }
113
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
114
+ if (keep) {
115
+ context.fillStyle = background ?? '#ffffff';
116
+ const k = canvas.height / height;
117
+ const from = Math.max(0, Math.round(keep.from * k));
118
+ const to = Math.min(canvas.height, Math.round(keep.to * k));
119
+ if (from > 0)
120
+ context.fillRect(0, 0, canvas.width, from);
121
+ if (to < canvas.height)
122
+ context.fillRect(0, to, canvas.width, canvas.height - to);
123
+ }
124
+ const blob = await new Promise((resolve) => canvas.toBlob(resolve, type, 0.92));
125
+ if (blob)
126
+ canvasPixels.drawn(pixels);
127
+ return { blob, pixels };
128
+ }
129
+ /**
130
+ * An SVG drawing as a picture at `scale` (2 by default), within the capture
131
+ * limits. With `onSmaller`, a canvas the browser will not make lowers the
132
+ * area captures use, and the picture is drawn once more under it.
133
+ */
134
+ export async function rasterize(svg, width, height, options = {}) {
135
+ const asked = options.scale ?? PNG_SCALE;
136
+ const scaleNow = () => Math.min(asked, maxCaptureScale(width, height, captureLimits()));
137
+ const fullScale = Math.min(asked, maxCaptureScale(width, height, CAPTURE_LIMITS));
138
+ const image = await loadSvgImage(svg, { error: 'The drawing could not be rendered.', decoding: 'sync' });
139
+ let scale = scaleNow();
140
+ let drawn = await drawOnCanvas(image, width, height, scale, options);
141
+ if (!drawn.blob && options.onSmaller && canvasPixels.lowerFor(drawn.pixels)) {
142
+ scale = scaleNow();
143
+ drawn = await drawOnCanvas(image, width, height, scale, options);
144
+ if (!drawn.blob)
145
+ canvasPixels.reset();
146
+ }
147
+ if (!drawn.blob)
148
+ throw new Error('The image is empty.');
149
+ if (scale < fullScale)
150
+ options.onSmaller?.(scale);
151
+ return drawn.blob;
152
+ }
153
+ /** dom-to-svg cannot paint CSS masks or SVG use shadow trees. */
154
+ export function needsBrowserPaint(element) {
155
+ const selector = 'svg use, [style*="mask"]';
156
+ return element.matches(selector) || !!element.querySelector(selector) || [...element.ownerDocument.styleSheets].some(sheet => {
157
+ try {
158
+ return [...sheet.cssRules].some(rule => /mask(?:-image)?\s*:/.test(rule.cssText));
159
+ }
160
+ catch {
161
+ return false;
162
+ }
163
+ });
164
+ }
165
+ /**
166
+ * False once this browser refused to read a canvas a `<foreignObject>` was
167
+ * drawn on (Safari): browser paint is then tried only where nothing else
168
+ * can draw the page.
169
+ */
170
+ let paintReadable = true;
171
+ /**
172
+ * Paint the computed HTML, with embedded images and the fonts of `fontCss`, so shadows, masks and ::before survive.
173
+ * `margin` (px) is room left around the element on every side, for what it draws outside its box (an outline).
174
+ */
175
+ export async function browserDrawing(element, width, height, top = 0, fontCss = '', html, margin = 0) {
176
+ const holder = document.createElement('div');
177
+ holder.innerHTML = html ?? (await captureHtml(element, 'raster'));
178
+ const root = holder.firstElementChild;
179
+ if (root && element !== element.ownerDocument.body) {
180
+ Object.assign(root.style, { position: 'relative', inset: 'auto', margin: '0' });
181
+ }
182
+ holder.style.marginTop = `-${top}px`;
183
+ if (margin > 0)
184
+ holder.style.padding = `${margin}px`;
185
+ // Laid out at the device pixels the element was measured at, so its text is as wide in the drawing.
186
+ const zoom = element.ownerDocument.defaultView?.devicePixelRatio ?? 1;
187
+ return foreignObjectSvg(new XMLSerializer().serializeToString(holder), fontCss, { width: width + margin * 2, height: height + margin * 2, zoom });
188
+ }
189
+ /**
190
+ * A frame's page as an image: its viewport (`width` × `height` CSS pixels
191
+ * from the top left) drawn at `scale`, on white.
192
+ *
193
+ * The browser paints it (the page's computed HTML through a
194
+ * `<foreignObject>`), which keeps what only it can draw: shadows, filters,
195
+ * blending, masks. Where the canvas cannot be read back afterwards, and for
196
+ * a `slice` of a long page, dom-to-svg rebuilds the page as SVG shapes
197
+ * instead. Both carry the page's web fonts; call this once they loaded.
198
+ */
199
+ export async function pageImage(doc, width, height, options) {
200
+ const rasterOptions = { ...options, background: options.background ?? '#ffffff' };
201
+ const fonts = await documentFonts(doc, options.fontBytes);
202
+ if (fonts.skipped.length)
203
+ options.onSkippedFonts?.(fonts.skipped);
204
+ if (needsBrowserPaint(doc.body) || (paintReadable && !options.slice)) {
205
+ try {
206
+ const html = options.reuse?.html ?? (await captureHtml(doc.body, 'raster'));
207
+ if (options.reuse)
208
+ options.reuse.html = html;
209
+ const svg = await browserDrawing(doc.body, width, height, options.top ?? 0, fonts.css, html);
210
+ return await rasterize(svg, width, height, rasterOptions);
211
+ }
212
+ catch (error) {
213
+ // Some browsers disallow reading a foreignObject canvas; a drawing that will not load is rebuilt as shapes too.
214
+ if (error instanceof DOMException && error.name === 'SecurityError')
215
+ paintReadable = false;
216
+ }
217
+ }
218
+ const svgDoc = await elementSvg(doc.documentElement, { x: 0, y: options.top ?? 0, width, height }, { fontCss: fonts.css });
219
+ const root = svgDoc.documentElement;
220
+ cleanSvg(root);
221
+ root.setAttribute('width', String(width));
222
+ root.setAttribute('height', String(height));
223
+ for (const node of [...root.childNodes])
224
+ if (node.nodeType === Node.COMMENT_NODE)
225
+ node.remove();
226
+ return rasterize(new XMLSerializer().serializeToString(svgDoc), width, height, rasterOptions);
227
+ }
228
+ /* ---------------------------------- HTML ---------------------------------- */
229
+ /** Properties children inherit: dropped when equal to the parent's. */
230
+ const INHERITED = new Set([
231
+ 'color', 'cursor', 'direction', 'font-family', 'font-feature-settings', 'font-kerning', 'font-size', 'font-stretch',
232
+ 'font-style', 'font-variant', 'font-variant-caps', 'font-variant-ligatures', 'font-variant-numeric', 'font-weight',
233
+ 'hyphens', 'letter-spacing', 'line-height', 'list-style-image', 'list-style-position', 'list-style-type', 'orphans',
234
+ 'quotes', 'tab-size', 'text-align', 'text-align-last', 'text-indent', 'text-rendering', 'text-shadow',
235
+ 'text-transform', 'visibility', 'white-space', 'white-space-collapse', 'text-wrap', 'text-wrap-mode', 'widows',
236
+ 'word-break', 'word-spacing', 'overflow-wrap', 'writing-mode', 'caret-color', '-webkit-text-fill-color',
237
+ '-webkit-text-stroke-color', '-webkit-text-stroke-width', 'paint-order', 'fill', 'stroke', 'text-size-adjust',
238
+ '-webkit-font-smoothing', 'border-collapse', 'border-spacing', 'empty-cells', 'caption-side',
239
+ ]);
240
+ /** Shorthand-free duplicates (logical properties mirror physical ones). */
241
+ const SKIPPED = /^(inline-size|block-size|min-inline-size|min-block-size|max-inline-size|max-block-size|margin-(block|inline)|padding-(block|inline)|border-(block|inline)|inset-(block|inline)|border-(start|end)-|overflow-(block|inline)|contain-intrinsic|-webkit-(?!text-fill|text-stroke|font-smoothing)|transition|animation|will-change|view-transition|anchor|position-(try|anchor|visibility)|user-select|pointer-events|cursor|perspective-origin|transform-origin)/;
242
+ /**
243
+ * What a stylesheet says about a shape or a label inside an `<svg>`, written on its copy (which has no stylesheet):
244
+ * the paints, and the type a `<text>` is set in (a label a class makes smaller would be drawn at its parent's size,
245
+ * wider than the room the chart left for it).
246
+ */
247
+ const SVG_STYLED = [
248
+ 'fill', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', 'stroke-dasharray', 'fill-rule', 'fill-opacity',
249
+ 'stroke-opacity', 'opacity', 'color', 'stop-color', 'stop-opacity', 'font-family', 'font-size', 'font-weight',
250
+ 'font-style', 'font-stretch', 'font-variant-numeric', 'letter-spacing', 'word-spacing', 'text-anchor',
251
+ 'dominant-baseline', 'visibility',
252
+ ];
253
+ const KEPT_ATTRIBUTES = new Set(['alt', 'title', 'width', 'height', 'colspan', 'rowspan', 'dir', 'lang', 'start', 'reversed', 'value', 'span']);
254
+ const DROPPED_TAGS = new Set(['script', 'style', 'link', 'meta', 'template', 'noscript', 'iframe', 'object', 'embed', 'audio', 'source', 'track']);
255
+ let defaultsFrame = null;
256
+ const defaultsCache = new Map();
257
+ /** Browser-default computed styles of a tag, from a blank frame. */
258
+ function defaultsOf(tag) {
259
+ const cached = defaultsCache.get(tag);
260
+ if (cached)
261
+ return cached;
262
+ if (!defaultsFrame) {
263
+ defaultsFrame = document.createElement('iframe');
264
+ defaultsFrame.setAttribute('aria-hidden', 'true');
265
+ defaultsFrame.style.cssText = 'position:fixed;left:-10000px;top:0;width:100px;height:100px;visibility:hidden;border:0';
266
+ document.body.append(defaultsFrame);
267
+ }
268
+ const doc = defaultsFrame.contentDocument;
269
+ const probe = doc.createElement(tag);
270
+ doc.body.append(probe);
271
+ const style = defaultsFrame.contentWindow.getComputedStyle(probe);
272
+ const map = new Map();
273
+ for (const name of style)
274
+ map.set(name, style.getPropertyValue(name));
275
+ probe.remove();
276
+ defaultsCache.set(tag, map);
277
+ return map;
278
+ }
279
+ const escapeText = (text) => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
280
+ const escapeAttr = (text) => escapeText(text).replace(/"/g, '&quot;');
281
+ /** A style value the copy can carry. */
282
+ const portable = (value) => !/var\(|env\(|attr\(/.test(value) && !/url\((?!\s*["']?data:image\/)/.test(value);
283
+ /** Fetches an image as a data URL (so the copy does not point at this server). */
284
+ async function dataUrl(url) {
285
+ if (url.startsWith('data:'))
286
+ return url;
287
+ try {
288
+ const blob = await (await fetch(url)).blob();
289
+ if (!blob.type.startsWith('image/'))
290
+ return null;
291
+ return await blobToDataUrl(blob).catch(() => null);
292
+ }
293
+ catch {
294
+ return null;
295
+ }
296
+ }
297
+ const IMAGE_TOKEN = /\u0000img:([\s\S]*?)\u0000/g;
298
+ /**
299
+ * The element as standalone HTML with inline computed styles (trimmed
300
+ * against browser defaults). Image sources come back as tokens, with the
301
+ * set of sources they stand for.
302
+ */
303
+ function standalone(element, mode = 'clipboard') {
304
+ const keepPosition = mode !== 'clipboard';
305
+ const view = element.ownerDocument.defaultView;
306
+ const images = new Set();
307
+ const imageToken = (src) => {
308
+ images.add(src);
309
+ return `\u0000img:${encodeURIComponent(src)}\u0000`;
310
+ };
311
+ const styleOf = (node, tag, parent, root, pseudo) => {
312
+ const computed = view.getComputedStyle(node, pseudo);
313
+ const defaults = defaultsOf(tag);
314
+ const out = [];
315
+ for (const name of computed) {
316
+ if (name.startsWith('--') || SKIPPED.test(name))
317
+ continue;
318
+ let value = computed.getPropertyValue(name);
319
+ if (!value)
320
+ continue;
321
+ if (keepPosition && value.includes('url(')) {
322
+ for (const { match, url } of cssUrls(value)) {
323
+ if (url.startsWith('data:') || url.startsWith('#'))
324
+ continue;
325
+ const resolved = new URL(url, node.baseURI);
326
+ if (resolved.origin === location.origin || resolved.protocol === 'blob:')
327
+ value = value.replace(match, () => `url('${imageToken(resolved.href)}')`);
328
+ }
329
+ }
330
+ if (!portable(value.replace(IMAGE_TOKEN, 'data:image/embedded')))
331
+ continue;
332
+ // A drawn side's width is always said: a side that is `solid` but 0 px wide (a reset's `border: 0 solid`)
333
+ // computes to the default's 0 px, and left unsaid the copy would draw it `medium` wide.
334
+ const drawnSide = /^(border-(?:top|right|bottom|left)|outline)-width$/.exec(name);
335
+ const drawnWidth = drawnSide !== null && computed.getPropertyValue(`${drawnSide[1]}-style`) !== 'none';
336
+ if (INHERITED.has(name) && parent) {
337
+ if (parent.getPropertyValue(name) === value)
338
+ continue;
339
+ }
340
+ else if (!drawnWidth && defaults.get(name) === value)
341
+ continue;
342
+ if (root && !keepPosition && /^(margin-|top$|left$|right$|bottom$|transform$|rotate$|scale$|translate$)/.test(name))
343
+ continue;
344
+ // A side or outline that is not drawn needs no color or width.
345
+ const side = /^(border-(?:top|right|bottom|left)|outline)-(?:color|width)$/.exec(name);
346
+ if (side && computed.getPropertyValue(`${side[1]}-style`) === 'none')
347
+ continue;
348
+ out.push(`${name}: ${value}`);
349
+ }
350
+ if (root && !keepPosition) {
351
+ if (computed.position === 'static' || computed.position === 'absolute' || computed.position === 'fixed')
352
+ out.push('position: relative');
353
+ out.push('margin: 0');
354
+ }
355
+ // Keep the rendered size of replaced and sized boxes.
356
+ return out.filter((decl) => !(root && decl === 'position: static')).join('; ');
357
+ };
358
+ const walk = (node, parent, root) => {
359
+ if (node.nodeType === Node.TEXT_NODE)
360
+ return escapeText(node.textContent ?? '');
361
+ if (node.nodeType !== Node.ELEMENT_NODE)
362
+ return '';
363
+ const el = node;
364
+ const computed = view.getComputedStyle(el);
365
+ if (computed.display === 'none')
366
+ return '';
367
+ if (el.namespaceURI === SVG_NS) {
368
+ const copy = el.cloneNode(true);
369
+ // A symbol is styled in the shadow tree of each <use>. Keep inherited
370
+ // paints as currentColor so the same definition can serve different colours.
371
+ const originals = [el, ...el.querySelectorAll('*')];
372
+ const twins = [copy, ...copy.querySelectorAll('*')];
373
+ for (const [i, original] of originals.entries()) {
374
+ const source = original;
375
+ const styles = view.getComputedStyle(source);
376
+ const inherited = source.parentElement && view.getComputedStyle(source.parentElement);
377
+ for (const name of SVG_STYLED) {
378
+ let value = styles.getPropertyValue(name);
379
+ if (!value || (name !== 'opacity' && inherited?.getPropertyValue(name) === value))
380
+ continue;
381
+ if ((name === 'fill' || name === 'stroke') && value === styles.color) {
382
+ const color = source.style.getPropertyValue('color'), priority = source.style.getPropertyPriority('color');
383
+ const probe = value === 'rgb(1, 2, 3)' ? 'rgb(3, 2, 1)' : 'rgb(1, 2, 3)';
384
+ try {
385
+ source.style.setProperty('color', probe, 'important');
386
+ if (styles.getPropertyValue(name) === probe)
387
+ value = 'currentColor';
388
+ }
389
+ finally {
390
+ if (color)
391
+ source.style.setProperty('color', color, priority);
392
+ else
393
+ source.style.removeProperty('color');
394
+ }
395
+ }
396
+ twins[i].style.setProperty(name, value);
397
+ }
398
+ }
399
+ if (mode === 'figma')
400
+ portableSymbolPaints(el, copy);
401
+ cleanSvg(copy);
402
+ if (el.localName === 'svg') {
403
+ copy.setAttribute('xmlns', SVG_NS);
404
+ if (!root || keepPosition)
405
+ copy.setAttribute('style', styleOf(el, 'svg', parent, false));
406
+ }
407
+ return new XMLSerializer().serializeToString(copy).replace(/ xmlns="http:\/\/www\.w3\.org\/1999\/xhtml"/g, '');
408
+ }
409
+ let tag = keepPosition && el.localName === 'body' ? 'div' : el.localName;
410
+ if (DROPPED_TAGS.has(tag))
411
+ return '';
412
+ if (computed.display === 'contents')
413
+ return [...el.childNodes].map((child) => walk(child, parent, root)).join('');
414
+ const pseudo = (name) => {
415
+ if (!keepPosition)
416
+ return '';
417
+ const css = view.getComputedStyle(el, name);
418
+ const content = css.content;
419
+ if (!content || content === 'none' || content === 'normal' || css.display === 'none')
420
+ return '';
421
+ const text = /^["'].*["']$/.test(content) ? content.slice(1, -1) : '';
422
+ return `<span aria-hidden="true" style="${escapeAttr(styleOf(el, 'span', computed, false, name))}">${escapeText(text)}</span>`;
423
+ };
424
+ const children = () => pseudo('::before') + [...el.childNodes].map((child) => walk(child, computed, false)).join('') + pseudo('::after');
425
+ let inner = null;
426
+ let attrs = keepPosition && el.id ? ` id="${escapeAttr(el.id)}"` : '';
427
+ switch (tag) {
428
+ case 'input': {
429
+ const input = el;
430
+ if (input.type === 'checkbox' || input.type === 'radio') {
431
+ tag = 'span';
432
+ inner = input.checked ? '☑' : '☐';
433
+ }
434
+ else {
435
+ tag = 'span';
436
+ inner = escapeText(input.value || input.placeholder);
437
+ }
438
+ break;
439
+ }
440
+ case 'textarea':
441
+ tag = 'div';
442
+ inner = escapeText(el.value || el.placeholder);
443
+ break;
444
+ case 'select':
445
+ tag = 'span';
446
+ inner = escapeText(el.selectedOptions[0]?.text ?? '');
447
+ break;
448
+ case 'canvas':
449
+ tag = 'img';
450
+ try {
451
+ attrs += ` src="${el.toDataURL('image/png')}"`;
452
+ }
453
+ catch {
454
+ // Tainted canvas: an empty box of the same size.
455
+ tag = 'div';
456
+ }
457
+ break;
458
+ case 'video':
459
+ tag = 'div';
460
+ inner = '';
461
+ break;
462
+ case 'img': {
463
+ const src = el.currentSrc || el.src;
464
+ if (src)
465
+ attrs += ` src="${imageToken(src)}"`;
466
+ break;
467
+ }
468
+ case 'a': {
469
+ const href = el.getAttribute('href') ?? '';
470
+ if (/^(https?:|mailto:|#)/i.test(href))
471
+ attrs += ` href="${escapeAttr(href)}"`;
472
+ break;
473
+ }
474
+ }
475
+ for (const attr of el.attributes)
476
+ if (KEPT_ATTRIBUTES.has(attr.name) && !(tag !== el.localName && attr.name === 'value'))
477
+ attrs += ` ${attr.name}="${escapeAttr(attr.value)}"`;
478
+ // The language picks the fonts of Han text (and so how wide it is): the copy's root says the one it had from
479
+ // an element above it (`<html lang>`), which the copy leaves behind.
480
+ if (root && !el.hasAttribute('lang')) {
481
+ const lang = el.parentElement?.closest('[lang]')?.getAttribute('lang');
482
+ if (lang)
483
+ attrs += ` lang="${escapeAttr(lang)}"`;
484
+ }
485
+ const style = styleOf(el, el.localName === tag ? tag : 'div', parent, root);
486
+ if (style)
487
+ attrs += ` style="${escapeAttr(style)}"`;
488
+ if (tag === 'img' || tag === 'br' || tag === 'hr' || tag === 'wbr')
489
+ return `<${tag}${attrs}>`;
490
+ return `<${tag}${attrs}>${inner ?? children()}</${tag}>`;
491
+ };
492
+ // The root inherits from its real parent, so its own inherited values are kept unless default.
493
+ return { html: walk(element, null, true), images };
494
+ }
495
+ /** The element as standalone HTML, images by URL (for a synchronous clipboard write). */
496
+ export function standaloneHtml(element) {
497
+ return standalone(element).html.replace(IMAGE_TOKEN, (_m, encoded) => escapeAttr(decodeURIComponent(encoded)));
498
+ }
499
+ /** The element as standalone HTML, images inlined as data URLs. */
500
+ export async function captureHtml(element, mode = 'clipboard') {
501
+ const { html, images } = standalone(element, mode);
502
+ const urls = new Map(await Promise.all([...images].map(async (src) => [src, await dataUrl(src)])));
503
+ return html.replace(IMAGE_TOKEN, (_m, encoded) => {
504
+ const src = decodeURIComponent(encoded);
505
+ return escapeAttr(urls.get(src) ?? src);
506
+ });
507
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Cutting a long rendered document into paper pages: where each page starts so no cut falls inside a line of text or a
3
+ * picture, headings stay with what they introduce, and a forced break starts a new page. Pure: the measures come from
4
+ * document-measure.ts.
5
+ */
6
+ /** Paper sizes in CSS px (96 px/in). */
7
+ export type Paper = 'letter' | 'a4';
8
+ export declare const PAPER: Record<Paper, {
9
+ width: number;
10
+ height: number;
11
+ }>;
12
+ /** Most pages one Flow artboard exports to. */
13
+ export declare const MAX_FLOW_PAGES = 100;
14
+ /** Share of a page added at each break, below the cut and above the next page's content. */
15
+ export declare const BREAK_MARGIN = 0.05;
16
+ /** Pictures taller than this are cut where the page ends instead of being kept whole. */
17
+ export declare const MAX_UNSPLIT_PICTURE = 950;
18
+ /** A vertical span `[top, bottom]` in document px. */
19
+ export type Interval = readonly [number, number];
20
+ /** A block kept with what it introduces (headings, captions, header rows). */
21
+ export interface KeepBlock {
22
+ /** The block itself. */
23
+ top: number;
24
+ bottom: number;
25
+ /** Where the kept run starts: the block, or a short lead-in line above it. */
26
+ from: number;
27
+ /** Kept with what follows (headings, top captions, header rows). */
28
+ next: boolean;
29
+ /** Kept with what precedes (a caption below a picture or table). */
30
+ prev: boolean;
31
+ }
32
+ /** One page: content `[top, bottom)` of the document drawn at `offset` px from the page's top. */
33
+ export interface PageSlice {
34
+ top: number;
35
+ bottom: number;
36
+ offset: number;
37
+ }
38
+ /** The margin added at each break for a page height (0 when the page is too short for it). */
39
+ export declare function breakMargin(pageHeight: number): number;
40
+ /**
41
+ * Spans that should not be cut so a block stays with its neighbour: a
42
+ * heading with the first band (line or picture) after it, a bottom caption
43
+ * with the band before it. A span longer than a quarter of a page is not
44
+ * kept (that much empty space costs more than the split).
45
+ */
46
+ export declare function keepTogetherSpans(blocks: readonly KeepBlock[], bands: readonly Interval[], pageHeight: number): Interval[];
47
+ /** Options of {@link paginate}. */
48
+ export interface PaginateOptions {
49
+ maxPages?: number;
50
+ /** Margin added at each break (see {@link breakMargin}). */
51
+ overlap?: number;
52
+ /** Spans from {@link keepTogetherSpans}: kept when that costs at most a quarter page. */
53
+ keep?: readonly Interval[];
54
+ }
55
+ /**
56
+ * Where each page starts, in document px (the first is 0). `intervals` are
57
+ * the spans a cut must not fall inside (text lines, pictures); a span longer
58
+ * than a page's content height is ignored (it is cut where the page ends).
59
+ */
60
+ export declare function paginate(intervals: readonly Interval[], contentHeight: number, pageHeight: number, options?: PaginateOptions): number[];
61
+ /** The pages for the tops {@link paginate} chose. The last page ends with the content (or its room, at the page limit). */
62
+ export declare function pageSlices(tops: readonly number[], contentHeight: number, pageHeight: number, overlap?: number): PageSlice[];
63
+ /** Everything at once: the page slices of a measured Flow document. */
64
+ export declare function flowPages(measured: {
65
+ contentHeight: number;
66
+ bands: readonly Interval[];
67
+ blocks: readonly KeepBlock[];
68
+ }, pageHeight: number, maxPages?: number): PageSlice[];
69
+ /**
70
+ * The page slices of a measured document that also has forced breaks (`break-before: page`): each break starts a new
71
+ * page, and what lies between two breaks is paginated on its own ({@link flowPages}). A page a break starts keeps the
72
+ * break margin above its content, as the pages after a cut do. Breaks at or before the top, past the content, or
73
+ * within 1 px of another are ignored. At most `maxPages` slices; the rest of the document is left out.
74
+ */
75
+ export declare function flowPagesWithBreaks(measured: {
76
+ contentHeight: number;
77
+ bands: readonly Interval[];
78
+ blocks: readonly KeepBlock[];
79
+ }, pageHeight: number, breaks: readonly number[], maxPages?: number): PageSlice[];