@open-artifact/export-kit 0.0.0-stage → 0.2.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/src/capture.js ADDED
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Capturing rendered DOM as pictures, two ways:
3
+ *
4
+ * - through an SVG `<foreignObject>`: a copy of the markup with every
5
+ * picture inlined as a `data:` URL ({@link inlinedCopy}) is wrapped in an
6
+ * SVG document ({@link foreignObjectSvg}), loaded as an image
7
+ * ({@link loadSvgImage}) and drawn onto a canvas. It keeps everything the
8
+ * browser can draw, but some browsers refuse to read the canvas back;
9
+ * - with dom-to-svg ({@link elementSvg}), which rebuilds the element as
10
+ * plain SVG shapes: a vector drawing that pastes into design tools, and
11
+ * the fallback when the first way fails.
12
+ *
13
+ * What is captured (a slide, an artboard's element) and how the result is
14
+ * drawn stays with each editor.
15
+ */
16
+ import { elementToSVG, inlineResources } from 'dom-to-svg';
17
+ import { withCaptureSafeDom } from "./capture-safe.js";
18
+ import { cssUrls } from "./fonts.js";
19
+ /** A transparent 1×1 GIF: stands in for pictures a capture leaves out. */
20
+ export const BLANK_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
21
+ export const SVG_NS = 'http://www.w3.org/2000/svg';
22
+ export const XHTML_NS = 'http://www.w3.org/1999/xhtml';
23
+ /** The largest scale an area of `width` × `height` can be drawn at within `limits`. */
24
+ export function maxCaptureScale(width, height, limits) {
25
+ return Math.min(limits.maxSide / Math.max(width, height, 1), Math.sqrt(limits.maxPixels / Math.max(width * height, 1)));
26
+ }
27
+ /** Resolves once every picture in the element loaded (or failed, or took longer than `timeout` ms) and decoded. */
28
+ export async function picturesReady(root, timeout) {
29
+ await Promise.all(Array.from(root.querySelectorAll('img')).map(async (image) => {
30
+ if (!image.complete) {
31
+ await new Promise((resolve) => {
32
+ const done = () => resolve();
33
+ image.addEventListener('load', done, { once: true });
34
+ image.addEventListener('error', done, { once: true });
35
+ setTimeout(done, timeout);
36
+ });
37
+ }
38
+ await image.decode().catch(() => undefined);
39
+ }));
40
+ }
41
+ /**
42
+ * Hides everything under `root` but `target` (live elements or a copy), so a
43
+ * capture draws only the target where it sits. `bare` also hides what the
44
+ * target holds (its background and border only). Returns an undo.
45
+ */
46
+ export function hideOutside(root, target, bare) {
47
+ const touched = [];
48
+ const set = (el, property, value) => {
49
+ const styled = el;
50
+ if (!styled.style)
51
+ return;
52
+ touched.push([styled, property, styled.style.getPropertyValue(property), styled.style.getPropertyPriority(property)]);
53
+ styled.style.setProperty(property, value, 'important');
54
+ };
55
+ if (target) {
56
+ if (target !== root) {
57
+ set(root, 'visibility', 'hidden');
58
+ set(target, 'visibility', 'visible');
59
+ }
60
+ if (bare) {
61
+ for (const child of Array.from(target.children))
62
+ set(child, 'visibility', 'hidden');
63
+ set(target, '-webkit-text-fill-color', 'transparent');
64
+ set(target, 'text-shadow', 'none');
65
+ }
66
+ }
67
+ return () => {
68
+ for (const [el, property, value, priority] of touched.reverse()) {
69
+ if (value)
70
+ el.style.setProperty(property, value, priority);
71
+ else
72
+ el.style.removeProperty(property);
73
+ }
74
+ };
75
+ }
76
+ /** Replaces `url(…)` references in an element's inline style with `data:` URLs. */
77
+ export async function inlineStyleUrls(el, options) {
78
+ const style = el.getAttribute('style');
79
+ if (!style || !style.includes('url('))
80
+ return;
81
+ let next = style;
82
+ for (const { match, url: raw } of cssUrls(style)) {
83
+ const url = raw.replace(/&quot;/g, '');
84
+ if (url.startsWith('data:'))
85
+ continue;
86
+ const data = await options.dataUrl(url);
87
+ if (data)
88
+ next = next.replace(match, `url("${data}")`);
89
+ else if (options.unreadable === 'blank')
90
+ next = next.replace(match, `url("${BLANK_GIF}")`);
91
+ else
92
+ options.onMissing?.(url);
93
+ }
94
+ el.setAttribute('style', next);
95
+ }
96
+ /** A copy of the element's markup with every picture inlined, ready to be drawn in isolation. */
97
+ export async function inlinedCopy(root, options) {
98
+ const copy = root.cloneNode(true);
99
+ const live = [root, ...Array.from(root.querySelectorAll('*'))];
100
+ const copies = [copy, ...Array.from(copy.querySelectorAll('*'))];
101
+ const target = options.only;
102
+ const inside = (el) => !target || target === el || target.contains(el);
103
+ await Promise.all(live.map(async (el, i) => {
104
+ const twin = copies[i];
105
+ if (el instanceof HTMLImageElement) {
106
+ twin.removeAttribute('srcset');
107
+ twin.removeAttribute('loading');
108
+ const src = el.currentSrc || el.src;
109
+ if (inside(el)) {
110
+ const data = src ? await options.dataUrl(src) : null;
111
+ if (data)
112
+ twin.setAttribute('src', data);
113
+ else if (options.unreadable === 'blank')
114
+ twin.setAttribute('src', BLANK_GIF);
115
+ else {
116
+ twin.removeAttribute('src');
117
+ if (src)
118
+ options.onMissing?.(src);
119
+ }
120
+ }
121
+ else {
122
+ twin.setAttribute('src', BLANK_GIF);
123
+ twin.style.width = `${el.offsetWidth}px`;
124
+ twin.style.height = `${el.offsetHeight}px`;
125
+ }
126
+ }
127
+ else if (el instanceof SVGImageElement) {
128
+ const href = el.getAttribute('href') ?? el.getAttribute('xlink:href');
129
+ if (href && !href.startsWith('data:')) {
130
+ const data = await options.dataUrl(href);
131
+ if (data)
132
+ twin.setAttribute('href', data);
133
+ else if (options.unreadable === 'blank')
134
+ twin.setAttribute('href', BLANK_GIF);
135
+ twin.removeAttribute('xlink:href');
136
+ }
137
+ }
138
+ if (inside(el))
139
+ await inlineStyleUrls(twin, options);
140
+ }));
141
+ if (target) {
142
+ const index = live.indexOf(target);
143
+ if (index >= 0)
144
+ hideOutside(copy, copies[index], Boolean(options.bare));
145
+ }
146
+ return copy;
147
+ }
148
+ /** Escapes text (such as CSS) for an XML text node. */
149
+ export function xmlText(text) {
150
+ return text.replace(/&/g, '&amp;').replace(/</g, '&lt;');
151
+ }
152
+ /** An SVG document drawing serialized XHTML `markup`, styled by `css`, through a `<foreignObject>`. */
153
+ export function foreignObjectSvg(markup, css, size) {
154
+ const { width, height } = size;
155
+ return (`<svg xmlns="${SVG_NS}" width="${size.outerWidth ?? width}" height="${size.outerHeight ?? height}" viewBox="0 0 ${width} ${height}">` +
156
+ `<foreignObject x="0" y="0" width="${width}" height="${height}">` +
157
+ `<div xmlns="${XHTML_NS}" style="width:${width}px;height:${height}px;margin:0;overflow:hidden"><style>${xmlText(css)}</style>${markup}</div>` +
158
+ '</foreignObject></svg>');
159
+ }
160
+ /** Loads an SVG document as an image (from a `data:` URL), decoded; rejects with `error` when it will not load. */
161
+ export async function loadSvgImage(svg, options) {
162
+ const image = new Image();
163
+ if (options.decoding)
164
+ image.decoding = options.decoding;
165
+ await new Promise((resolve, reject) => {
166
+ image.onload = () => resolve();
167
+ image.onerror = () => reject(new Error(options.error));
168
+ image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
169
+ });
170
+ await image.decode().catch(() => undefined);
171
+ return image;
172
+ }
173
+ /**
174
+ * The element rebuilt as plain SVG by dom-to-svg (links dropped), its
175
+ * resources inlined. `area` defaults to the element's own box.
176
+ */
177
+ export async function elementSvg(element, area) {
178
+ const box = area ?? element.getBoundingClientRect();
179
+ const view = element.ownerDocument.defaultView;
180
+ const doc = withCaptureSafeDom(element, () => elementToSVG(element, { captureArea: new view.DOMRect(box.x, box.y, box.width, box.height), keepLinks: false }));
181
+ await inlineResources(doc.documentElement);
182
+ return doc;
183
+ }
package/src/fonts.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Reading font stylesheets for exports that inline their fonts. Pictures
3
+ * drawn from serialized markup cannot load fonts from the network, and an
4
+ * exported page should open offline, so editors inline `@font-face` rules
5
+ * with `data:` URLs. Stylesheets such as Google Fonts' are split by
6
+ * `unicode-range`; these helpers find the blocks that cover the characters
7
+ * a document uses. Pure.
8
+ */
9
+ /** The `@font-face` blocks of a stylesheet. */
10
+ export declare function fontFaceBlocks(css: string): string[];
11
+ /** The `unicode-range` value of a `@font-face` block, if it has one. */
12
+ export declare function blockUnicodeRange(block: string): string | undefined;
13
+ /** A `unicode-range` as inclusive code point ranges (null: everything). */
14
+ export declare function parseUnicodeRange(value: string | undefined): [number, number][] | null;
15
+ /** True when any of the code points falls in the ranges (always, for null ranges). */
16
+ export declare function rangeCovers(ranges: [number, number][] | null, points: Iterable<number>): boolean;
17
+ /** Every `url(…)` in a CSS text: the whole match and the address. */
18
+ export declare function cssUrls(css: string): {
19
+ match: string;
20
+ url: string;
21
+ }[];
package/src/fonts.js ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Reading font stylesheets for exports that inline their fonts. Pictures
3
+ * drawn from serialized markup cannot load fonts from the network, and an
4
+ * exported page should open offline, so editors inline `@font-face` rules
5
+ * with `data:` URLs. Stylesheets such as Google Fonts' are split by
6
+ * `unicode-range`; these helpers find the blocks that cover the characters
7
+ * a document uses. Pure.
8
+ */
9
+ /** The `@font-face` blocks of a stylesheet. */
10
+ export function fontFaceBlocks(css) {
11
+ return css.match(/@font-face\s*\{[^}]*\}/g) ?? [];
12
+ }
13
+ /** The `unicode-range` value of a `@font-face` block, if it has one. */
14
+ export function blockUnicodeRange(block) {
15
+ return /unicode-range\s*:\s*([^;}]+)/i.exec(block)?.[1];
16
+ }
17
+ /** A `unicode-range` as inclusive code point ranges (null: everything). */
18
+ export function parseUnicodeRange(value) {
19
+ if (!value)
20
+ return null;
21
+ const ranges = [];
22
+ for (const part of value.split(',')) {
23
+ const text = part.trim().replace(/^u\+/i, '');
24
+ if (!text)
25
+ continue;
26
+ if (text.includes('?')) {
27
+ ranges.push([parseInt(text.replace(/\?/g, '0'), 16), parseInt(text.replace(/\?/g, 'f'), 16)]);
28
+ }
29
+ else if (text.includes('-')) {
30
+ const [from, to] = text.split('-');
31
+ ranges.push([parseInt(from, 16), parseInt(to, 16)]);
32
+ }
33
+ else {
34
+ const point = parseInt(text, 16);
35
+ ranges.push([point, point]);
36
+ }
37
+ }
38
+ return ranges.filter(([a, b]) => Number.isFinite(a) && Number.isFinite(b));
39
+ }
40
+ /** True when any of the code points falls in the ranges (always, for null ranges). */
41
+ export function rangeCovers(ranges, points) {
42
+ if (!ranges)
43
+ return true;
44
+ for (const point of points)
45
+ for (const [from, to] of ranges)
46
+ if (point >= from && point <= to)
47
+ return true;
48
+ return false;
49
+ }
50
+ /** Every `url(…)` in a CSS text: the whole match and the address. */
51
+ export function cssUrls(css) {
52
+ return Array.from(css.matchAll(/url\((['"]?)([^'")]+)\1\)/g), (match) => ({ match: match[0], url: match[2] }));
53
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @open-artifact/export-kit: the capture and export code the Slides, Design
3
+ * and Whiteboard editors share in the browser.
4
+ *
5
+ * - capture.ts: DOM to pictures (inlined copies drawn through
6
+ * `<foreignObject>`, or dom-to-svg) and capture size limits;
7
+ * - measure.ts and text-layer.ts: the PDF text layer (words and links
8
+ * measured on a rendered page, words grouped into lines);
9
+ * - pictures.ts: `data:` URLs, canvas encoding, decoding and shrinking pictures;
10
+ * - fonts.ts: reading font stylesheets for inlined `@font-face` rules.
11
+ *
12
+ * It never imports an editor or a document model; each editor passes its
13
+ * own limits and policies. The pure modules (text-layer.ts, fonts.ts) load
14
+ * in `node --test`.
15
+ */
16
+ export * from './capture.ts';
17
+ export * from './fonts.ts';
18
+ export * from './measure.ts';
19
+ export * from './pictures.ts';
20
+ export * from './text-layer.ts';
package/src/index.js ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @open-artifact/export-kit: the capture and export code the Slides, Design
3
+ * and Whiteboard editors share in the browser.
4
+ *
5
+ * - capture.ts: DOM to pictures (inlined copies drawn through
6
+ * `<foreignObject>`, or dom-to-svg) and capture size limits;
7
+ * - measure.ts and text-layer.ts: the PDF text layer (words and links
8
+ * measured on a rendered page, words grouped into lines);
9
+ * - pictures.ts: `data:` URLs, canvas encoding, decoding and shrinking pictures;
10
+ * - fonts.ts: reading font stylesheets for inlined `@font-face` rules.
11
+ *
12
+ * It never imports an editor or a document model; each editor passes its
13
+ * own limits and policies. The pure modules (text-layer.ts, fonts.ts) load
14
+ * in `node --test`.
15
+ */
16
+ export * from "./capture.js";
17
+ export * from "./fonts.js";
18
+ export * from "./measure.js";
19
+ export * from "./pictures.js";
20
+ export * from "./text-layer.js";
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Measuring a rendered page for the PDF text layer: the words drawn, in
3
+ * reading (document) order, and the clickable areas of web links. Lines are
4
+ * grouped from the words by text-layer.ts.
5
+ *
6
+ * The editors measure differently framed pages (a slide offscreen on the
7
+ * editor's own page, an artboard alone in a hidden frame), so where to
8
+ * measure from, how far up "drawn" is decided, which elements hold no text
9
+ * and how a word broken across lines is boxed are options, not guesses.
10
+ */
11
+ import { type LinkArea, type Word } from './text-layer.ts';
12
+ /** Where measures are taken from, and what decides whether something is drawn. */
13
+ export interface MeasureOptions {
14
+ /**
15
+ * `root`: from the root element's top left (a slide offscreen); `client`:
16
+ * client rects as they are (an unscrolled frame, where they are document
17
+ * coordinates).
18
+ */
19
+ origin: 'root' | 'client';
20
+ /**
21
+ * The topmost element whose styles can hide what it holds (the root, for
22
+ * a slide inside the editor's page); null checks every ancestor.
23
+ */
24
+ drawnWithin: Element | null;
25
+ }
26
+ /** How words are measured. */
27
+ export interface WordOptions extends MeasureOptions {
28
+ /** Text whose parent element's local name matches is skipped (scripts, styles…). */
29
+ skip?: RegExp;
30
+ /**
31
+ * The box of a word broken across lines, for each piece on one line:
32
+ * `domrect` is a `DOMRect` from the first character's top left to the
33
+ * last character's right, as tall as the tallest character; `extent` runs
34
+ * from the first character's left and top to the last character's right
35
+ * and the lowest character's bottom.
36
+ */
37
+ brokenWord: 'domrect' | 'extent';
38
+ }
39
+ /** How links are measured. */
40
+ export interface LinkOptions extends MeasureOptions {
41
+ /** Leave out links that are not drawn. */
42
+ drawnOnly: boolean;
43
+ }
44
+ /**
45
+ * Is this element (and every ancestor up to `within`, or to the document
46
+ * root when null) drawn: not `display: none`, `visibility: hidden` or
47
+ * `opacity: 0`? Answers are kept in `cache`.
48
+ */
49
+ export declare function isDrawn(element: Element, within: Element | null, cache?: Map<Element, boolean>): boolean;
50
+ /** The words drawn under `root`, in reading (document) order. */
51
+ export declare function measureWords(root: Element, options: WordOptions): Word[];
52
+ /** The clickable areas of web links (http, https, mailto) under `root`. */
53
+ export declare function measureLinks(root: Element, options: LinkOptions): LinkArea[];
package/src/measure.js ADDED
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Measuring a rendered page for the PDF text layer: the words drawn, in
3
+ * reading (document) order, and the clickable areas of web links. Lines are
4
+ * grouped from the words by text-layer.ts.
5
+ *
6
+ * The editors measure differently framed pages (a slide offscreen on the
7
+ * editor's own page, an artboard alone in a hidden frame), so where to
8
+ * measure from, how far up "drawn" is decided, which elements hold no text
9
+ * and how a word broken across lines is boxed are options, not guesses.
10
+ */
11
+ import { isWebLink } from "./text-layer.js";
12
+ const styleOf = (element) => element.ownerDocument.defaultView.getComputedStyle(element);
13
+ /**
14
+ * Is this element (and every ancestor up to `within`, or to the document
15
+ * root when null) drawn: not `display: none`, `visibility: hidden` or
16
+ * `opacity: 0`? Answers are kept in `cache`.
17
+ */
18
+ export function isDrawn(element, within, cache = new Map()) {
19
+ const known = cache.get(element);
20
+ if (known !== undefined)
21
+ return known;
22
+ const style = styleOf(element);
23
+ const own = style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0';
24
+ const result = own && (element === within || !element.parentElement ? true : isDrawn(element.parentElement, within, cache));
25
+ cache.set(element, result);
26
+ return result;
27
+ }
28
+ /** The words drawn under `root`, in reading (document) order. */
29
+ export function measureWords(root, options) {
30
+ const doc = root.ownerDocument;
31
+ const view = doc.defaultView;
32
+ const origin = options.origin === 'root' ? root.getBoundingClientRect() : { left: 0, top: 0 };
33
+ const out = [];
34
+ const range = doc.createRange();
35
+ const walker = doc.createTreeWalker(root, NodeFilter.SHOW_TEXT);
36
+ const shown = new Map();
37
+ const info = new Map();
38
+ const grow = options.brokenWord === 'domrect'
39
+ ? (box, rect) => new view.DOMRect(box.left, box.top, rect.right - box.left, Math.max(box.bottom - box.top, rect.height))
40
+ : (box, rect) => ({ left: box.left, top: box.top, right: rect.right, bottom: Math.max(box.bottom, rect.bottom) });
41
+ const start = (rect) => (options.brokenWord === 'domrect' ? rect : { left: rect.left, right: rect.right, top: rect.top, bottom: rect.bottom });
42
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
43
+ const text = node.nodeValue ?? '';
44
+ if (!text.trim())
45
+ continue;
46
+ const parent = node.parentElement;
47
+ if (!parent || options.skip?.test(parent.localName) || !isDrawn(parent, options.drawnWithin, shown))
48
+ continue;
49
+ let meta = info.get(parent);
50
+ if (!meta) {
51
+ const style = styleOf(parent);
52
+ meta = { size: parseFloat(style.fontSize) || 16, upper: style.textTransform === 'uppercase' };
53
+ info.set(parent, meta);
54
+ }
55
+ const { size, upper } = meta;
56
+ for (const match of text.matchAll(/\S+/g)) {
57
+ const from = match.index;
58
+ const end = from + match[0].length;
59
+ const space = end < text.length;
60
+ range.setStart(node, from);
61
+ range.setEnd(node, end);
62
+ const rects = Array.from(range.getClientRects()).filter((r) => r.width > 0 && r.height > 0);
63
+ const push = (value, rect, trailing) => {
64
+ out.push({
65
+ text: upper ? value.toUpperCase() : value,
66
+ left: rect.left - origin.left,
67
+ right: rect.right - origin.left,
68
+ top: rect.top - origin.top,
69
+ bottom: rect.bottom - origin.top,
70
+ size,
71
+ space: trailing,
72
+ });
73
+ };
74
+ if (rects.length === 1)
75
+ push(match[0], rects[0], space);
76
+ else if (rects.length > 1) {
77
+ // A word broken across lines: split it where its characters land.
78
+ let piece = '';
79
+ let box = null;
80
+ let offset = from;
81
+ for (const char of match[0]) {
82
+ range.setStart(node, offset);
83
+ range.setEnd(node, offset + char.length);
84
+ offset += char.length;
85
+ const rect = range.getBoundingClientRect();
86
+ if (box && Math.abs(rect.top - box.top) > size * 0.5) {
87
+ push(piece, box, false);
88
+ piece = '';
89
+ box = null;
90
+ }
91
+ piece += char;
92
+ box = box ? grow(box, rect) : start(rect);
93
+ }
94
+ if (box)
95
+ push(piece, box, space);
96
+ }
97
+ }
98
+ }
99
+ return out;
100
+ }
101
+ /** The clickable areas of web links (http, https, mailto) under `root`. */
102
+ export function measureLinks(root, options) {
103
+ const origin = options.origin === 'root' ? root.getBoundingClientRect() : { left: 0, top: 0 };
104
+ const areas = [];
105
+ const shown = new Map();
106
+ for (const link of Array.from(root.querySelectorAll('a[href]'))) {
107
+ const href = link.getAttribute('href') ?? '';
108
+ if (!isWebLink(href) || (options.drawnOnly && !isDrawn(link, options.drawnWithin, shown)))
109
+ continue;
110
+ for (const rect of Array.from(link.getClientRects())) {
111
+ if (rect.width > 0 && rect.height > 0)
112
+ areas.push({ href, x: rect.left - origin.left, y: rect.top - origin.top, w: rect.width, h: rect.height });
113
+ }
114
+ }
115
+ return areas;
116
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Pictures in the browser: reading blobs as `data:` URLs, encoding canvases,
3
+ * decoding picture files, and drawing them smaller. Exports inline pictures
4
+ * into self-contained files and uploads shrink pictures to the stored limits;
5
+ * each caller keeps its own limits and qualities and passes them in.
6
+ *
7
+ * Everything here needs a DOM (FileReader, canvas, `createImageBitmap`).
8
+ */
9
+ /** Reads a blob as a `data:` URL. `failure` makes the error a failed read rejects with (default: the reader's error, else "The file could not be read."). */
10
+ export declare function blobToDataUrl(blob: Blob, failure?: (error: DOMException | null) => Error): Promise<string>;
11
+ /** A canvas as a blob (null when empty, or when the browser refuses to read it back). */
12
+ export declare function canvasBlob(canvas: HTMLCanvasElement, type: string, quality?: number): Promise<Blob | null>;
13
+ /**
14
+ * Encodes a canvas as WebP where the browser writes it, else as the type
15
+ * `fallback` names (asked only then). Null when neither could be written.
16
+ */
17
+ export declare function encodePreferringWebp(canvas: HTMLCanvasElement, quality: number, fallback: () => string): Promise<Blob | null>;
18
+ /** Decodes a picture file (SVG through an image element, drawn at 1024 × 1024 when it has no size); null when it cannot be decoded. */
19
+ export declare function decodePicture(blob: Blob): Promise<ImageBitmap | HTMLImageElement | null>;
20
+ /** The scale that brings a picture's long edge down to `maxEdge` (1 when it already fits). */
21
+ export declare function edgeScale(width: number, height: number, maxEdge: number): number;
22
+ /** How {@link drawScaled} draws. */
23
+ export interface DrawScaledOptions {
24
+ /** The canvas's `imageSmoothingQuality` (left at the browser's default when omitted). */
25
+ smoothing?: ImageSmoothingQuality;
26
+ /** Smallest canvas side, px (default 1). */
27
+ minSide?: number;
28
+ }
29
+ /**
30
+ * Draws a picture of `width` × `height` px onto a new canvas at `scale`
31
+ * (each side rounded, at least `minSide`). Null when the browser gives no
32
+ * 2D context.
33
+ */
34
+ export declare function drawScaled(source: CanvasImageSource, width: number, height: number, scale: number, options?: DrawScaledOptions): HTMLCanvasElement | null;
35
+ /** Below this many bytes, a picture that already fits is left as it is by {@link shrinkPicture}. */
36
+ export declare const SHRINK_MIN_BYTES: number;
37
+ /**
38
+ * A raster picture redrawn so its long edge is at most `maxEdge` px and
39
+ * re-encoded (WebP where the browser writes it, else JPEG, or PNG for a PNG
40
+ * that may be transparent) at `quality`. Null when the file should stay as
41
+ * it is: not a still raster picture (SVG, GIF), already small enough (fits
42
+ * and under `minBytes`), undecodable, or when the smaller copy is not
43
+ * smaller in bytes.
44
+ */
45
+ export declare function shrinkPicture(blob: Blob, maxEdge: number, quality: number, minBytes?: number): Promise<Blob | null>;
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Pictures in the browser: reading blobs as `data:` URLs, encoding canvases,
3
+ * decoding picture files, and drawing them smaller. Exports inline pictures
4
+ * into self-contained files and uploads shrink pictures to the stored limits;
5
+ * each caller keeps its own limits and qualities and passes them in.
6
+ *
7
+ * Everything here needs a DOM (FileReader, canvas, `createImageBitmap`).
8
+ */
9
+ /** Reads a blob as a `data:` URL. `failure` makes the error a failed read rejects with (default: the reader's error, else "The file could not be read."). */
10
+ export function blobToDataUrl(blob, failure = (error) => error ?? new Error('The file could not be read.')) {
11
+ return new Promise((resolve, reject) => {
12
+ const reader = new FileReader();
13
+ reader.onload = () => resolve(String(reader.result));
14
+ reader.onerror = () => reject(failure(reader.error));
15
+ reader.readAsDataURL(blob);
16
+ });
17
+ }
18
+ /** A canvas as a blob (null when empty, or when the browser refuses to read it back). */
19
+ export function canvasBlob(canvas, type, quality) {
20
+ return new Promise((resolve) => {
21
+ try {
22
+ canvas.toBlob((blob) => resolve(blob), type, quality);
23
+ }
24
+ catch {
25
+ resolve(null);
26
+ }
27
+ });
28
+ }
29
+ /**
30
+ * Encodes a canvas as WebP where the browser writes it, else as the type
31
+ * `fallback` names (asked only then). Null when neither could be written.
32
+ */
33
+ export async function encodePreferringWebp(canvas, quality, fallback) {
34
+ const webp = await canvasBlob(canvas, 'image/webp', quality);
35
+ if (webp && webp.type === 'image/webp')
36
+ return webp;
37
+ return canvasBlob(canvas, fallback(), quality);
38
+ }
39
+ /** Decodes a picture file (SVG through an image element, drawn at 1024 × 1024 when it has no size); null when it cannot be decoded. */
40
+ export async function decodePicture(blob) {
41
+ if (blob.type !== 'image/svg+xml' && typeof createImageBitmap === 'function') {
42
+ try {
43
+ return await createImageBitmap(blob);
44
+ }
45
+ catch {
46
+ // Fall through to an image element.
47
+ }
48
+ }
49
+ const url = URL.createObjectURL(blob);
50
+ try {
51
+ const image = new Image();
52
+ image.decoding = 'async';
53
+ await new Promise((resolve, reject) => {
54
+ image.onload = () => resolve();
55
+ image.onerror = () => reject(new Error('undecodable'));
56
+ image.src = url;
57
+ });
58
+ if (!image.naturalWidth || !image.naturalHeight) {
59
+ // SVG without a size: draw it at a reasonable default.
60
+ image.width = 1024;
61
+ image.height = 1024;
62
+ }
63
+ return image;
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ finally {
69
+ URL.revokeObjectURL(url);
70
+ }
71
+ }
72
+ /** The scale that brings a picture's long edge down to `maxEdge` (1 when it already fits). */
73
+ export function edgeScale(width, height, maxEdge) {
74
+ return Math.min(1, maxEdge / Math.max(width, height, 1));
75
+ }
76
+ /**
77
+ * Draws a picture of `width` × `height` px onto a new canvas at `scale`
78
+ * (each side rounded, at least `minSide`). Null when the browser gives no
79
+ * 2D context.
80
+ */
81
+ export function drawScaled(source, width, height, scale, options = {}) {
82
+ const minSide = options.minSide ?? 1;
83
+ const canvas = document.createElement('canvas');
84
+ canvas.width = Math.max(minSide, Math.round(width * scale));
85
+ canvas.height = Math.max(minSide, Math.round(height * scale));
86
+ const context = canvas.getContext('2d');
87
+ if (!context)
88
+ return null;
89
+ if (options.smoothing)
90
+ context.imageSmoothingQuality = options.smoothing;
91
+ context.drawImage(source, 0, 0, canvas.width, canvas.height);
92
+ return canvas;
93
+ }
94
+ /** Below this many bytes, a picture that already fits is left as it is by {@link shrinkPicture}. */
95
+ export const SHRINK_MIN_BYTES = 512 * 1024;
96
+ /**
97
+ * A raster picture redrawn so its long edge is at most `maxEdge` px and
98
+ * re-encoded (WebP where the browser writes it, else JPEG, or PNG for a PNG
99
+ * that may be transparent) at `quality`. Null when the file should stay as
100
+ * it is: not a still raster picture (SVG, GIF), already small enough (fits
101
+ * and under `minBytes`), undecodable, or when the smaller copy is not
102
+ * smaller in bytes.
103
+ */
104
+ export async function shrinkPicture(blob, maxEdge, quality, minBytes = SHRINK_MIN_BYTES) {
105
+ if (!/^image\/(png|jpeg|jpg|webp|avif|bmp)$/.test(blob.type))
106
+ return null;
107
+ const bitmap = await decodePicture(blob);
108
+ if (!bitmap)
109
+ return null;
110
+ try {
111
+ const { width, height } = bitmap;
112
+ const scale = edgeScale(width, height, maxEdge);
113
+ if (scale >= 1 && blob.size < minBytes)
114
+ return null;
115
+ const canvas = drawScaled(bitmap, width, height, scale, { smoothing: 'high' });
116
+ if (!canvas)
117
+ return null;
118
+ const out = await encodePreferringWebp(canvas, quality, () => (blob.type === 'image/png' ? 'image/png' : 'image/jpeg'));
119
+ return out && out.size < blob.size ? out : null;
120
+ }
121
+ finally {
122
+ if ('close' in bitmap)
123
+ bitmap.close();
124
+ }
125
+ }