@zumer/snapdom-plugins 5.0.0 → 5.1.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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Plugin changes
2
2
 
3
+ ## 5.1.0
4
+
5
+ > 10 November 2026
6
+
7
+ **Features**
8
+
9
+ - **plugins:** jxl, JPEG XL exports with exact text [`#556`](https://github.com/zumerlab/snapdom/pull/556)
10
+
11
+ **Docs**
12
+
13
+ - **site:** add the JPEG XL plugin page [`5ceba24`](https://github.com/zumerlab/snapdom/commit/5ceba24c2887996381b402c9927d8b9be3445430)
14
+
3
15
  ## 5.0.0
4
16
 
5
17
  > 9 November 2026
package/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
  Official plugins for [SnapDOM](https://github.com/zumerlab/snapdom), a high-performance DOM engine
7
7
  that exports a rendered element as PNG, SVG or canvas in the browser. Core exports images and
8
8
  canvases; this package adds HTML, structured context, element maps, ASCII, visual transforms,
9
- redaction and live GIF/video recording. PDF, Vector and Stream are their own packages:
9
+ redaction, JPEG XL and live GIF/video recording. PDF, Vector and Stream are their own packages:
10
10
  [`@zumer/snapdom-pdf`](https://snapdom.dev/plugins/pdf/), [`@zumer/snapdom-vector`](https://snapdom.dev/plugins/vector/)
11
11
  and [`@zumer/snapdom-stream`](https://snapdom.dev/plugins/stream/).
12
12
 
@@ -21,7 +21,7 @@ Install the plugins next to a core supported by their peer dependency:
21
21
  npm install @zumer/snapdom@latest @zumer/snapdom-plugins@latest
22
22
  ```
23
23
 
24
- Plugins 5.x require SnapDOM 3.4.0 or newer within 3.x and hold the eleven toolbox plugins. PDF, Vector and Stream moved to their own packages in 5.0; see [Migrating from 4.x](#migrating-from-4x). See the [migration guide](https://github.com/zumerlab/snapdom#migrating-from-v2) when upgrading from v2.
24
+ Plugins 5.x require SnapDOM 3.4.0 or newer within 3.x and hold the twelve toolbox plugins. PDF, Vector and Stream moved to their own packages in 5.0; see [Migrating from 4.x](#migrating-from-4x). See the [migration guide](https://github.com/zumerlab/snapdom#migrating-from-v2) when upgrading from v2.
25
25
 
26
26
  ## Usage
27
27
 
@@ -396,6 +396,42 @@ The document retains source markup, including event-handler attributes; it is no
396
396
 
397
397
  ---
398
398
 
399
+ ### `jxl`
400
+
401
+ Adds `toJxl()`, `toBlob({ format: 'jxl' })` and `download({ format: 'jxl' })`. Text and interface stay
402
+ exact while photos take the quality, in one JPEG XL file. The encoder is [rapier-jxl](https://www.npmjs.com/package/rapier-jxl)
403
+ (MIT), an optional peer: the text measurement loads at the first capture, the encoder at the first export.
404
+
405
+ ```bash
406
+ npm install rapier-jxl
407
+ ```
408
+
409
+ ```js
410
+ import { jxl } from '@zumer/snapdom-plugins/jxl';
411
+
412
+ const result = await snapdom(el, { plugins: [jxl()] });
413
+ const img = await result.toJxl({ quality: 0.8 });
414
+ const blob = await result.toBlob({ format: 'jxl' });
415
+ await result.download({ format: 'jxl', filename: 'card' });
416
+ ```
417
+
418
+ | Option | Type | Default | Description |
419
+ |--------|------|---------|-------------|
420
+ | `module` | `string` | `'rapier-jxl/capture-complete'` | With your `codec`: `'rapier-jxl/capture'` (every pixel exact) or `'rapier-jxl/upload'` (photographic) |
421
+ | `codec` | `object` | none | Your own encoder with `prepare` and `capture` |
422
+ | `decoder` | `object` | none | `createCodec()` from `rapier-jxl/codec/decode`, for `toJxl()` where JPEG XL does not show |
423
+ | `effort` | `number` | `3` | Default effort, 1-9 |
424
+ | `webgpu` | `false \| 'required'` | none | Disable WebGPU, or require a device |
425
+ | `helpers` | `boolean \| object` | none | Helper workers for the encoder the plugin creates |
426
+
427
+ Exports take `toWebp()`'s options, plus `effort`, `signal`, `onProgress` (0 to 1) and `onEncoded` (once).
428
+ `quality: 1` is exact. The plugin's own encoder takes up to 40 megapixels; `plugin.close()` ends its workers.
429
+
430
+ Encoding works in every browser: `toBlob()` and `download()` give `image/jxl`. Where the browser cannot show
431
+ JPEG XL (Edge, for one), `toJxl()` shows the `decoder`'s pixels, or rejects with `JXL_NOT_SHOWN` without one.
432
+
433
+ ---
434
+
399
435
  ### `gif-export`
400
436
 
401
437
  Adds `toGif()`, which records the live element and returns an `image/gif` Blob. Its built-in
package/jxl.d.ts ADDED
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Type declarations for `@zumer/snapdom-plugins/jxl`.
3
+ *
4
+ * The plugin instance type comes from the core package: one definition of what a plugin IS,
5
+ * so a plugin that stops matching the host's contract fails to typecheck instead of failing
6
+ * at capture time. Nothing here imports rapier-jxl, an optional peer dependency.
7
+ */
8
+ import type { SnapdomPlugin } from '@zumer/snapdom';
9
+
10
+ /** Every pixel exact, efforts 1-5. */
11
+ export type ExactCaptureModule = 'rapier-jxl/capture';
12
+ /** Photographic capture, efforts 1-3. */
13
+ export type UploadCaptureModule = 'rapier-jxl/upload';
14
+ /** Exact text and lossy photos in one file, efforts 1-9. The default. */
15
+ export type CompleteCaptureModule = 'rapier-jxl/capture-complete';
16
+ export type JxlCaptureModule = ExactCaptureModule | UploadCaptureModule | CompleteCaptureModule;
17
+
18
+ /** Higher effort takes longer to encode, usually for a smaller file. */
19
+ export type JxlEffort = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
20
+
21
+ /** Reported once for the file the export returns. */
22
+ export interface JxlEncodedRecord {
23
+ /** True when every pixel of the file is exact. */
24
+ exact: boolean;
25
+ bands?: number;
26
+ }
27
+
28
+ /** Your own encoder: a rapier-jxl codec (`createCodec`) or a directly imported capture module. */
29
+ export interface JxlEncoder {
30
+ prepare(kind: 'capture'): Promise<void>;
31
+ capture(input: HTMLCanvasElement, options: Record<string, unknown>): Promise<{
32
+ fits: boolean;
33
+ bytes?: Uint8Array;
34
+ reason?: { code?: string; message?: string };
35
+ }>;
36
+ }
37
+
38
+ /** Helper workers for a codec the plugin creates; `count: 0` may omit `memoryBytes`. */
39
+ /** `memoryBytes` bounds the helpers' memory; it is required for a `count` above 0. */
40
+ export type JxlHelpers = boolean | { count: 0; memoryBytes?: number } | { count: number; memoryBytes: number };
41
+
42
+ /** A decoder for `toJxl()` where the browser cannot show JPEG XL: `createCodec()` from `rapier-jxl/codec/decode`. */
43
+ export interface JxlDecoder {
44
+ decode(input: Blob, options: Record<string, unknown>): Promise<{ data: Uint8Array; width: number; height: number }>;
45
+ }
46
+
47
+ export interface JxlOptions {
48
+ /** Default `'rapier-jxl/capture-complete'`, which the plugin creates; the others need your `codec`. */
49
+ module?: JxlCaptureModule;
50
+ /** Your own encoder; the plugin then creates none and ignores `helpers`. */
51
+ codec?: JxlEncoder;
52
+ /** Without one, `toJxl()` rejects with `JXL_NOT_SHOWN` where the browser cannot show JPEG XL. */
53
+ decoder?: JxlDecoder;
54
+ /** Default effort for each export (3 when omitted); an export's `effort` wins. */
55
+ effort?: JxlEffort;
56
+ /** `false` disables WebGPU; `'required'` requires a device for work that uses it. */
57
+ webgpu?: false | 'required';
58
+ helpers?: JxlHelpers;
59
+ }
60
+
61
+ /** `toWebp()`'s options with the same defaults, plus effort and the encoding callbacks. */
62
+ export interface JxlExportOptions {
63
+ /** Default 0.92. Below 1, photos take this quality; 1 is exact. */
64
+ quality?: number;
65
+ scale?: number;
66
+ width?: number;
67
+ height?: number;
68
+ dpr?: number;
69
+ /** Default `'#ffffff'`. */
70
+ backgroundColor?: string | null;
71
+ filename?: string;
72
+ format?: string;
73
+ effort?: JxlEffort;
74
+ signal?: AbortSignal;
75
+ /** Encoding progress from 0 to 1, after SnapDOM draws. */
76
+ onProgress?: (fraction: number) => void;
77
+ onEncoded?: (record: JxlEncodedRecord) => void;
78
+ }
79
+
80
+ /**
81
+ * Adds `result.toJxl()` (an `<img>`), `toBlob({ format: 'jxl' })` (the file) and
82
+ * `download({ format: 'jxl' })`. Install rapier-jxl next to the plugins.
83
+ */
84
+ export declare function jxl(options?: JxlOptions): JxlPlugin;
85
+
86
+ export interface JxlPlugin extends SnapdomPlugin {
87
+ /** Ends the encoder the plugin created (never your own `codec` or `decoder`); a later export creates it again. */
88
+ close(): Promise<void>;
89
+ }
90
+ export default jxl;
91
+
92
+ declare module '@zumer/snapdom' {
93
+ interface CaptureResult {
94
+ toJxl(options?: JxlExportOptions): Promise<HTMLImageElement>;
95
+ toBlob(options: JxlExportOptions & { format: 'jxl' }): Promise<Blob>;
96
+ download(options: JxlExportOptions & { format: 'jxl' }): Promise<void>;
97
+ }
98
+ }
package/jxl.js ADDED
@@ -0,0 +1,511 @@
1
+ /**
2
+ * jxl - Official SnapDOM Plugin
3
+ * Adds JPEG XL exports: `result.toJxl()`, `toBlob({ format: 'jxl' })` and
4
+ * `download({ format: 'jxl' })`. They take `toWebp()`'s options and defaults, plus
5
+ * `effort`, `signal`, `onProgress` and `onEncoded`.
6
+ *
7
+ * Text and interface stay exact while photos take the quality, in one file. The plugin
8
+ * measures where text and photos are on the page in `afterClone`, then encodes the drawn
9
+ * canvas in the browser with rapier-jxl 8.3.2 or later (MIT), an optional peer dependency:
10
+ * `npm install rapier-jxl`. The text measurement loads at the first capture, the encoder at the
11
+ * first JPEG XL export.
12
+ *
13
+ * @param {Object} [options]
14
+ * @param {string} [options.module='rapier-jxl/capture-complete'] - What the encoder is:
15
+ * 'rapier-jxl/capture-complete' (efforts 1-9, created by the plugin), or with your own `codec`,
16
+ * 'rapier-jxl/capture' (every pixel exact, efforts 1-5) or 'rapier-jxl/upload' (photographic,
17
+ * efforts 1-3)
18
+ * @param {Object} [options.codec] - Your own encoder with `prepare` and `capture`: a rapier-jxl
19
+ * codec or a directly imported capture module
20
+ * @param {Object} [options.decoder] - A decoder with `decode` (`createCodec()` from
21
+ * 'rapier-jxl/codec/decode'): `toJxl()` shows its pixels where the browser cannot show JPEG XL
22
+ * @param {number} [options.effort=3] - Default effort for each export; an export's `effort` wins
23
+ * @param {false|'required'} [options.webgpu] - Disable WebGPU, or require a device
24
+ * @param {boolean|{count: number, memoryBytes?: number}} [options.helpers] - Helper workers for a
25
+ * codec the plugin creates
26
+ * @returns {Object} SnapDOM plugin
27
+ */
28
+ export function jxl(options = {}) {
29
+ const { module = 'rapier-jxl/capture-complete', codec, decoder, effort: preset, webgpu, helpers: asked } = options;
30
+ // The same helpers written in another order share one plugin.
31
+ const helpers = asked && typeof asked === 'object'
32
+ ? { count: asked.count, ...(asked.memoryBytes !== undefined && { memoryBytes: asked.memoryBytes }) } : asked || undefined;
33
+ // Equal options give the same plugin, so SnapDOM's memo of an unchanged capture holds for an
34
+ // inline `jxl()` too.
35
+ const id = JSON.stringify([module, helpers, preset, webgpu]);
36
+ const made = within(within(plugins, codec, 'codecs'), decoder, 'decoders').ids;
37
+ if (!made.has(id)) made.set(id, create(module, codec, decoder, preset, webgpu, helpers));
38
+ return made.get(id);
39
+ }
40
+
41
+ const scope = () => ({ ids: new Map(), codecs: new WeakMap(), decoders: new WeakMap() });
42
+ const plugins = scope();
43
+ const within = (at, object, kind) => !object ? at : at[kind].get(object) ?? at[kind].set(object, scope()).get(object);
44
+
45
+ function create(module, codec, decoder, preset, webgpu, helpers) {
46
+ checkEffort(preset);
47
+ if (!MODULES.includes(module)) throw new Error(`The jxl plugin's module is ${MODULES.join(', ')} or left out.`);
48
+ // One codec door, so a bundler ships one encoder's workers: the others come as your own codec.
49
+ if (module !== MODULES[0] && !codec) throw new Error(`The jxl plugin's ${module} needs your codec: createCodec() from ${module.replace('/', '/codec/')}.`);
50
+ const exactOnly = module === 'rapier-jxl/capture';
51
+ // Edges are measured with the page, for any export effort from 4 (a scan of about 0.1 ms on
52
+ // SnapDOM's demo pages): measuring the page again at export could see it changed.
53
+ const edges = module !== 'rapier-jxl/upload';
54
+ // The encoder this plugin creates, on its first JPEG XL export; `close()` ends it.
55
+ let own = null;
56
+ const ownCodec = () => own ??= import('rapier-jxl/codec/capture-complete').then(
57
+ ({ createCodec }) => createCodec({ module, ...(helpers !== undefined && { helpers }) }),
58
+ error => { own = null; throw needs(error); });
59
+
60
+ return {
61
+ name: 'jxl',
62
+ // The measurement reads the live DOM and nothing else, so SnapDOM can keep memoizing
63
+ // unchanged captures.
64
+ pure: true,
65
+
66
+ /**
67
+ * Ends the encoder this plugin created (never your own `codec` or `decoder`). Calling it again
68
+ * does nothing; a later export creates it again.
69
+ * @returns {Promise<void>}
70
+ */
71
+ async close() {
72
+ const open = own;
73
+ own = null;
74
+ await open?.then(c => c.close(), () => {});
75
+ },
76
+
77
+ // Exact capture needs no rectangles. Otherwise text and photos are measured on the page
78
+ // as it was captured; the export maps them onto the drawn canvas. A failure to load or
79
+ // measure is kept for the JPEG XL export, which then rejects with it.
80
+ ...(exactOnly ? {} : {
81
+ async afterClone(context) {
82
+ const element = context.element;
83
+ // Only what SnapDOM cloned is drawn: exclude, filter and unslotted children add nothing.
84
+ const keep = context.nodeMap ? new Set(context.nodeMap.values()) : undefined;
85
+ try {
86
+ const { measure } = await loadRects();
87
+ const shot = element && measured(measure, element, edges, keep);
88
+ context[SNAPSHOT] = shot ? { ...shot, frame: frameOf(element, context.outerTransforms !== false) } : null;
89
+ } catch (error) {
90
+ context[SNAPSHOT] = { error };
91
+ }
92
+ },
93
+ }),
94
+
95
+ defineExports: ({ exports }) => {
96
+ const encoded = async (context, options) => {
97
+ // The export's own options first: a beforeExport plugin may have changed them, and a
98
+ // direct call has nothing else.
99
+ const asked = context.export?.requestedOptions ?? {}, pick = k => options[k] !== undefined ? options[k] : asked[k];
100
+ const effort = pick('effort') ?? preset, signal = pick('signal'), onProgress = pick('onProgress'), onEncoded = pick('onEncoded');
101
+ checkEffort(effort);
102
+ if (options.quality !== undefined && !(options.quality >= 0 && options.quality <= 1)) throw new RangeError('The jxl plugin\'s quality is 0 to 1.');
103
+ signal?.throwIfAborted();
104
+ if (context[SNAPSHOT]?.error) throw context[SNAPSHOT].error;
105
+ const { pageRects } = exactOnly ? {} : await abortable(loadRects(), signal);
106
+ // The plugin's own encoder takes up to MAX_PIXELS: a canvas well past it is never drawn.
107
+ if (!codec && drawnPixels(context, options) > 1.5 * MAX_PIXELS) throw tooLarge();
108
+ const encoder = codec ?? await abortable(ownCodec(), signal);
109
+ // Ready while SnapDOM draws; a failure rejects this export.
110
+ const ready = Promise.resolve().then(() => encoder.prepare('capture'));
111
+ ready.catch(() => {});
112
+ const mine = c => c !== options.canvas;
113
+ const drawing = exports.canvas({ ...options, backgroundColor: options.backgroundColor ?? '#ffffff' });
114
+ let canvas;
115
+ try {
116
+ canvas = await abortable(drawing, signal);
117
+ } catch (error) {
118
+ // A draw that ends after the abort still frees its canvas.
119
+ drawing.then(c => { if (mine(c)) free(c); }, () => {});
120
+ throw error;
121
+ }
122
+ try {
123
+ signal?.throwIfAborted();
124
+ if (!codec && canvas.width * canvas.height > MAX_PIXELS) throw tooLarge();
125
+ await abortable(ready, signal);
126
+ const blob = await encode(encoder, canvas, context, options, { effort, signal, onProgress, onEncoded, pageRects });
127
+ return { blob, canvas, own: mine(canvas) };
128
+ } catch (error) {
129
+ if (mine(canvas)) free(canvas);
130
+ throw error;
131
+ }
132
+ };
133
+ const blobOf = async (context, options) => {
134
+ const { blob, canvas, own } = await encoded(context, options);
135
+ if (own) free(canvas);
136
+ return blob;
137
+ };
138
+ // `type` is SnapDOM's older name for `format`, which it keeps for its own formats only. A format
139
+ // chosen for this export (the call, a beforeExport plugin) wins; the capture's own does not.
140
+ const isJxl = (context, options) => {
141
+ if (String(options.format).toLowerCase() === 'jxl') return true;
142
+ const asked = context.export?.requestedOptions ?? options;
143
+ return asked.format === undefined && String(asked.type).toLowerCase() === 'jxl' &&
144
+ (options.__explicitFormat ?? null) === (context.__explicitFormat ?? null);
145
+ };
146
+ const signalOf = (context, options) => options.signal ?? context.export?.requestedOptions?.signal;
147
+
148
+ return {
149
+ jxl: async (context, options = {}) => {
150
+ // Where JPEG XL does not show and there is no decoder, nothing is encoded.
151
+ if (showsJxl === false && !decoder) throw notShown();
152
+ const { blob, canvas, own: owned } = await encoded(context, options);
153
+ return image(blob, canvas, owned, options.dpr || 1, signalOf(context, options), decoder);
154
+ },
155
+ blob: (context, options = {}) => isJxl(context, options) ? blobOf(context, options) : exports.blob(options),
156
+ // Replacing download replaces it for every format: the others are saved as SnapDOM saves
157
+ // them (its file name, its Blob, the iOS share sheet falling back to the anchor).
158
+ async download(context, options = {}) {
159
+ const name = options.filename || 'snapDOM';
160
+ if (!isJxl(context, options)) {
161
+ const format = options.format === 'jpg' ? 'jpeg' : options.format || 'png';
162
+ const blob = await exports.blob({ ...options, format, dpr: 1 });
163
+ return save(blob, /\.(png|jpe?g|webp|svg)$/i.test(name) ? name : `${name}.${format}`, false);
164
+ }
165
+ const filename = /\.jxl$/i.test(name) ? name : `${name.replace(/\.(png|jpe?g|webp|svg)$/i, '')}.jxl`;
166
+ const blob = await blobOf(context, { ...options, dpr: 1 });
167
+ signalOf(context, options)?.throwIfAborted();
168
+ await save(blob, filename, true);
169
+ },
170
+ };
171
+
172
+ // Maps the measurement onto the drawn canvas and encodes it.
173
+ async function encode(encoder, canvas, context, options, { effort, signal, onProgress, onEncoded, pageRects }) {
174
+ const { quality = 0.92 } = options;
175
+ const photo = { quality: Math.max(1, quality * 100) };
176
+ // The canvas shows the capture's viewBox: the measurement moves into it the way SnapDOM
177
+ // drew the root (its outer shadow, transform and clip window), or, where it cannot, the
178
+ // whole capture stays exact.
179
+ const both = o => Number.isFinite(o.width) && Number.isFinite(o.height);
180
+ const fitted = both(context) && !safari(), exported = both(options) && firefox() && options;
181
+ // WebKit draws an export crop's window from the capture's corner (SnapDOM 3.7.2): exact there.
182
+ const crop = options.crop && (safari() || exported ? null : options.crop);
183
+ const shot = exactOnly || options.crop && !crop ? null : inView(context[SNAPSHOT], context.meta, fitted, exported, crop);
184
+ // WebKit draws a clip window's positioned boxes as if the window began at the element's corner
185
+ // (SnapDOM 3.7.2): in Safari the text stays exact in both places.
186
+ const unclipped = shot && safari() && context.meta?.clip ? inView(context[SNAPSHOT], { ...context.meta, clip: null }, fitted, exported, crop) : null;
187
+ const area = {};
188
+
189
+ // Below 1:1, text boxes map through the drawn scale (outward to whole pixels) so glyphs
190
+ // stay exact, and photos still take the quality. With no photos left the page stays exact;
191
+ // with photos, the smaller of that file and the whole page exact wins, so a scaled export
192
+ // is never larger.
193
+ const naturalW = shot?.box.width, naturalH = shot?.box.height;
194
+ const below = !!(shot && naturalW && naturalH &&
195
+ (canvas.width < Math.floor(naturalW) || canvas.height < Math.floor(naturalH)));
196
+ const measured = [shot, unclipped].filter(Boolean).map(s => pageRects(s, canvas, { area, edges: !below && (effort ?? 3) >= 4 }));
197
+ // pageRects' whole result reaches the encoder. Safari's two measurements unite their
198
+ // rectangles, and their text is complete only when both say so.
199
+ let rects = quality < 1 && measured.length ? measured.length === 1 ? measured[0] : {
200
+ exactRects: measured.flatMap(r => r.exactRects), photoRects: measured.flatMap(r => r.photoRects),
201
+ ...(measured.every(r => r.textComplete === true) && { textComplete: true }),
202
+ } : null;
203
+ // A page SnapDOM had to shrink to its canvas limit is drawn with its text moved from where
204
+ // the page has it, so the rectangles cannot follow: it stays exact.
205
+ if (below && (!rects?.photoRects?.length || atLimit(canvas))) rects = null;
206
+
207
+ const base = { ...(effort !== undefined && { effort }), ...(webgpu !== undefined && { webgpu }), ...(signal && { signal }) };
208
+ const hooks = { signal, onProgress, onEncoded };
209
+ const file = below && rects
210
+ ? await smaller(encoder, canvas, base, [{ ...rects, fidelity: photo }, { fidelity: 'exact' }], hooks)
211
+ : await encoder.capture(canvas, {
212
+ ...(rects ? { ...rects, fidelity: photo } : { fidelity: 'exact' }),
213
+ ...base, ...(onProgress !== undefined && { onProgress }), ...(onEncoded !== undefined && { onEncoded }),
214
+ });
215
+ // An encoder that finished after the abort still loses to it.
216
+ signal?.throwIfAborted();
217
+ return new Blob([bytesOf(file)], { type: 'image/jxl' });
218
+ }
219
+ },
220
+ };
221
+ }
222
+
223
+ export default jxl;
224
+
225
+ const SNAPSHOT = Symbol('jxl measurement');
226
+ // SnapDOM's raster limits: 32767 pixels a side (16384 in Safari) and 16384 * 16384 in all.
227
+ const atLimit = ({ width, height }) => [16384, 32767].includes(Math.max(width, height)) || width * height > 0.99 * 16384 * 16384;
228
+ // rapier-jxl's own default limit: 40 MP, 160 MB of RGBA before the encoder's copies. Your own
229
+ // `codec` keeps its own limit.
230
+ const MAX_PIXELS = 40000000;
231
+ const tooLarge = () => Object.assign(new Error(`The capture is over ${MAX_PIXELS} pixels: export it smaller, or pass your own codec with a higher maxPixels.`), { code: 'JXL_LIMIT' });
232
+ let measuring = null, rectsLoading = null;
233
+
234
+ // About how many pixels SnapDOM will draw, before it draws (its v3 sizing rule): width and height
235
+ // win, either one keeps the aspect, otherwise the capture's size times scale; times dpr squared.
236
+ function drawnPixels(context, options) {
237
+ let { vbW, vbH } = context.meta ?? {};
238
+ if (!(vbW > 0 && vbH > 0)) return 0;
239
+ // An export crop draws its window alone.
240
+ const crop = options.crop;
241
+ if (crop && [crop.x, crop.y, crop.width, crop.height].every(Number.isFinite)) {
242
+ vbW = Math.max(0, Math.min(vbW, crop.x + crop.width) - Math.max(0, crop.x));
243
+ vbH = Math.max(0, Math.min(vbH, crop.y + crop.height) - Math.max(0, crop.y));
244
+ if (!(vbW > 0 && vbH > 0)) return 0;
245
+ }
246
+ const w = Number.isFinite(options.width) ? options.width : null, h = Number.isFinite(options.height) ? options.height : null;
247
+ const k = options.scale || 1, dpr = options.dpr || (typeof devicePixelRatio === 'number' ? devicePixelRatio : 1) || 1;
248
+ const width = w ?? (h ? h * vbW / vbH : vbW * k), height = h ?? (w ? w * vbH / vbW : vbH * k);
249
+ return width * height * dpr * dpr;
250
+ }
251
+
252
+ // rapier-jxl is an optional peer dependency, imported the first time a capture or export needs it,
253
+ // so calling jxl() and the rest of the plugins load nothing.
254
+ const checkEffort = effort => {
255
+ if (effort !== undefined && !(Number.isInteger(effort) && effort >= 1 && effort <= 9)) throw new RangeError('The jxl plugin\'s effort is a whole number from 1 to 9.');
256
+ };
257
+ const MODULES = ['rapier-jxl/capture-complete', 'rapier-jxl/capture', 'rapier-jxl/upload'];
258
+ const needs = error => new Error('The jxl plugin needs rapier-jxl 8.3.2 or later: npm install rapier-jxl', { cause: error });
259
+
260
+ function loadRects() {
261
+ if (measuring) return Promise.resolve(measuring);
262
+ rectsLoading ??= import('rapier-jxl/page-rects').then(
263
+ m => (measuring = { measure: m.measure, pageRects: m.pageRects }),
264
+ error => { rectsLoading = null; throw needs(error); });
265
+ return rectsLoading;
266
+ }
267
+
268
+ // SnapDOM 3.7.3 draws <html> without the top margins that collapse through its first children,
269
+ // <body>'s own included, so its text is not where the page has it: such a capture stays exact.
270
+ function measured(measure, element, edges, keep) {
271
+ return keep && liftOf(element) ? null : measure(element, { edges, keep });
272
+ }
273
+
274
+ function liftOf(element) {
275
+ const doc = element.ownerDocument, body = doc?.body;
276
+ if (element !== doc?.documentElement || !body) return 0;
277
+ const s = getComputedStyle(element);
278
+ // As SnapDOM decides it: an edge with a border or padding, or a root that starts its own block
279
+ // formatting context, keeps the margins.
280
+ if (parseFloat(s.borderTopWidth) || parseFloat(s.paddingTop) || /flex|grid|table|inline-block|flow-root/.test(s.display) ||
281
+ s.position === 'absolute' || s.position === 'fixed' || s.float !== 'none' || s.overflowX !== 'visible' || s.overflowY !== 'visible' ||
282
+ /layout|content|paint|strict/.test(s.contain)) return 0;
283
+ // A relatively positioned <body> keeps its offset in the clone.
284
+ const b = getComputedStyle(body), moved = b.position === 'relative' ? parseFloat(b.top) || 0 : 0;
285
+ return body.getBoundingClientRect().top - moved - element.getBoundingClientRect().top;
286
+ }
287
+
288
+ // How the page shows the capture root: the viewport point of its layout corner, the scale of the
289
+ // ancestors and the root's own transform. null where an ancestor rotates or skews it, or a
290
+ // transform cannot be read: the export then keeps the whole capture exact.
291
+ function frameOf(element, keepsRotation) {
292
+ try {
293
+ const box = element.getBoundingClientRect(), style = getComputedStyle(element);
294
+ const width = element.offsetWidth ?? box.width, height = element.offsetHeight ?? box.height;
295
+ // No transform on the root or above it, and its layout size is its box: the page's own pixels.
296
+ let flat = none(style.transform) && none(style.rotate) && none(style.scale);
297
+ for (let up = element.parentElement ?? element.getRootNode?.().host; up && flat; up = up.parentElement ?? up.getRootNode?.().host) {
298
+ const s = getComputedStyle(up);
299
+ flat = none(s.transform) && none(s.rotate) && none(s.scale);
300
+ }
301
+ if (flat && Math.abs(box.width - width) < 0.5 && Math.abs(box.height - height) < 0.5) {
302
+ return { toDrawn: p => ({ x: p.x - box.left, y: p.y - box.top }) };
303
+ }
304
+ const [ox, oy] = style.transformOrigin.split(' ').map(parseFloat);
305
+ const transform = style.transform === 'none' ? new DOMMatrix() : new DOMMatrix(style.transform);
306
+ const rotate = style.rotate && style.rotate !== 'none' ? new DOMMatrix(`rotate(${style.rotate})`) : new DOMMatrix();
307
+ const scale = style.scale && style.scale !== 'none' ? new DOMMatrix(`scale(${style.scale.split(' ').slice(0, 2).join(',')})`) : new DOMMatrix();
308
+ transform.e = transform.f = 0; // SnapDOM drops the root's translation
309
+ const live = rotate.multiply(scale).multiply(transform);
310
+ // SnapDOM keeps the root's transform, or with outerTransforms false only its scale and skew,
311
+ // about its top left corner.
312
+ const drawn = keepsRotation ? live : scale.multiply(scaleSkew(transform));
313
+ for (let up = element.parentElement ?? element.getRootNode().host; up; up = up.parentElement ?? up.getRootNode().host) {
314
+ const s = getComputedStyle(up), m = s.transform === 'none' ? null : new DOMMatrix(s.transform);
315
+ if (m && (m.b || m.c) || s.rotate && s.rotate !== 'none') return null;
316
+ }
317
+ const corners = m => [[0, 0], [width, 0], [0, height], [width, height]].map(([x, y]) => m.transformPoint({ x, y }));
318
+ const about = (m, x, y) => new DOMMatrix().translate(x, y).multiply(m).translate(-x, -y);
319
+ const page = corners(about(live, ox, oy));
320
+ const xs = page.map(p => p.x), ys = page.map(p => p.y);
321
+ const near = v => Math.abs(v - 1) < 0.01 ? 1 : v;
322
+ const sx = near(box.width / (Math.max(...xs) - Math.min(...xs) || 1)), sy = near(box.height / (Math.max(...ys) - Math.min(...ys) || 1));
323
+ // From the page to the root's own layout box.
324
+ const toLayout = about(live, ox, oy).inverse()
325
+ .multiply(new DOMMatrix().scale(1 / sx, 1 / sy).translate(-(box.left - Math.min(...xs) * sx), -(box.top - Math.min(...ys) * sy)));
326
+ const shown = (keepsRotation ? about(live, ox, oy) : drawn).multiply(toLayout);
327
+ return { toDrawn: p => shown.transformPoint(p) };
328
+ } catch {
329
+ return null;
330
+ }
331
+ }
332
+
333
+ const none = v => !v || v === 'none';
334
+
335
+ // Firefox as SnapDOM tells it (its isFirefox).
336
+ const firefox = () => typeof navigator !== 'undefined' && (navigator.userAgent || '').toLowerCase().includes('firefox');
337
+
338
+ // Safari as SnapDOM tells it (its isSafari): the browsers whose captures it draws its Safari way.
339
+ function safari() {
340
+ const ua = typeof navigator === 'undefined' ? '' : navigator.userAgent || '', low = ua.toLowerCase(), webkit = /applewebkit/i.test(ua);
341
+ return low.includes('safari') && !/chrome|crios|fxios|android/.test(low) || webkit && /mobile/i.test(ua) && !/safari/i.test(ua) ||
342
+ /(micromessenger|wxwork|wecom|windowswechat|macwechat)/i.test(ua) || /(baiduboxapp|baidubrowser|baidusearch|baiduboxlite)/i.test(low) ||
343
+ /ipad|iphone|ipod/.test(low) && webkit;
344
+ }
345
+
346
+ // What SnapDOM leaves of a matrix with outerTransforms false: its scale and skew.
347
+ function scaleSkew({ a, b, c, d }) {
348
+ const sx = Math.hypot(a, b);
349
+ if (!sx) return new DOMMatrix();
350
+ const a1 = a / sx, b1 = b / sx, shear = a1 * c + b1 * d;
351
+ const sy = Math.hypot(c - a1 * shear, d - b1 * shear);
352
+ return new DOMMatrix([sx, 0, sy ? shear : 0, sy, 0, 0]);
353
+ }
354
+
355
+ // The measurement moved into the capture's viewBox, in CSS pixels; null keeps the capture exact.
356
+ // The box is what the canvas shows, in viewBox units. A capture given both width and height fits its
357
+ // viewBox inside them, centered (Safari stretches it instead), and Firefox draws an export given
358
+ // both fitted and centered too (the others stretch it): mapping the box onto the canvas is a stretch.
359
+ function inView(shot, meta, fitted, exported, crop) {
360
+ if (!shot?.frame || !meta || !Number.isFinite(meta.vbW)) return null;
361
+ const { contentX = 0, contentY = 0, vbW, vbH, clip, targetW, targetH } = meta, { toDrawn } = shot.frame;
362
+ let width = vbW, height = vbH;
363
+ const fit = (w, h) => { const k = Math.min(w / width, h / height); width = w / k; height = h / k; };
364
+ if (fitted && targetW && targetH) fit(targetW, targetH);
365
+ if (exported) fit(exported.width, exported.height);
366
+ const dx = contentX - (clip?.x ?? 0) + (width - vbW) / 2, dy = contentY - (clip?.y ?? 0) + (height - vbH) / 2;
367
+ const move = r => {
368
+ const ps = [[r.left, r.top], [r.right, r.top], [r.left, r.bottom], [r.right, r.bottom]].map(([x, y]) => toDrawn({ x, y }));
369
+ const xs = ps.map(p => p.x + dx), ys = ps.map(p => p.y + dy);
370
+ return { ...r, left: Math.min(...xs), top: Math.min(...ys), right: Math.max(...xs), bottom: Math.max(...ys) };
371
+ };
372
+ let box = { left: 0, top: 0, width, height };
373
+ // An export crop is a window of the viewBox.
374
+ if (crop) {
375
+ const left = Math.max(0, crop.x), top = Math.max(0, crop.y);
376
+ const right = Math.min(vbW, crop.x + crop.width), bottom = Math.min(vbH, crop.y + crop.height);
377
+ if (!(right > left && bottom > top)) return null;
378
+ box = { left, top, width: right - left, height: bottom - top };
379
+ }
380
+ const { frame: _frame, ...measurement } = shot;
381
+ return {
382
+ ...measurement,
383
+ box,
384
+ text: shot.text.map(t => ({ ...t, r: move(t.r) })),
385
+ photos: shot.photos.map(move),
386
+ ...(shot.edges && { edges: shot.edges.map(move) }),
387
+ };
388
+ }
389
+
390
+ // The file as an image. Where the browser cannot show JPEG XL (found on the first try, then
391
+ // remembered), the decoder's pixels if you gave one; otherwise the export says so. The image
392
+ // takes the drawn canvas's CSS size.
393
+ let showsJxl;
394
+ const notShown = () => Object.assign(new Error('This browser cannot show JPEG XL: use toBlob({ format: \'jxl\' }) for the file, or give the plugin a decoder.'), { code: 'JXL_NOT_SHOWN' });
395
+ async function image(blob, drawn, own, dpr, signal, decoder) {
396
+ const img = new Image(), wait = promise => abortable(promise, signal);
397
+ const { width, height } = drawn?.style ?? {};
398
+ if (own) free(drawn);
399
+ let decoded = null;
400
+ try {
401
+ if (showsJxl !== false) {
402
+ try {
403
+ await wait(shown(img, blob));
404
+ showsJxl = true;
405
+ } catch (error) {
406
+ if (signal?.aborted) throw signal.reason;
407
+ showsJxl = false;
408
+ }
409
+ }
410
+ if (!showsJxl) {
411
+ if (!decoder) throw notShown();
412
+ const { data, width: w, height: h } = await wait(decoder.decode(blob, { format: 'uint8', colorSpace: 'srgb', ...(signal && { signal }) }));
413
+ decoded = document.createElement('canvas');
414
+ decoded.width = w;
415
+ decoded.height = h;
416
+ decoded.getContext('2d').putImageData(new ImageData(new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength), w, h), 0, 0);
417
+ await wait(shown(img, await wait(new Promise(resolve => decoded.toBlob(resolve, 'image/png')))));
418
+ }
419
+ } finally {
420
+ free(decoded);
421
+ }
422
+ signal?.throwIfAborted();
423
+ img.style.width = width || `${img.naturalWidth / dpr}px`;
424
+ img.style.height = height || `${img.naturalHeight / dpr}px`;
425
+ return img;
426
+ }
427
+
428
+ // A canvas holds its pixels until it is emptied, even once nothing reads it. Only the export's own
429
+ // canvases are emptied, never one the app passed as `canvas`.
430
+ function free(canvas) {
431
+ if (typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement) canvas.width = canvas.height = 0;
432
+ }
433
+
434
+ // The image decodes the Blob through an object URL, revoked once it has loaded or failed: the
435
+ // decoded image keeps its pixels, and nothing holds a base64 copy.
436
+ function shown(img, blob) {
437
+ if (!blob) return Promise.reject(new Error('The canvas gave no PNG.'));
438
+ const url = URL.createObjectURL(blob);
439
+ return new Promise((resolve, reject) => { img.onload = resolve; img.onerror = reject; img.src = url; })
440
+ .then(() => img.decode?.().catch(() => {}))
441
+ .finally(() => { img.onload = img.onerror = null; URL.revokeObjectURL(url); });
442
+ }
443
+
444
+ // iOS saves a file only through the share sheet. For JPEG XL a refused share is the export's
445
+ // failure; SnapDOM's own formats fall back to the anchor, as SnapDOM's download does.
446
+ async function save(blob, filename, strict) {
447
+ const file = new File([blob], filename, { type: blob.type });
448
+ const ios = navigator.userAgentData ? navigator.userAgentData.platform === 'iOS'
449
+ : /iPhone|iPad|iPod/.test(navigator.userAgent) || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;
450
+ if (ios && navigator.canShare?.({ files: [file] })) {
451
+ // Closing the sheet is the person's choice.
452
+ try {
453
+ await navigator.share({ files: [file], title: filename });
454
+ return;
455
+ } catch (error) {
456
+ if (error.name === 'AbortError') return;
457
+ if (strict) throw error;
458
+ }
459
+ }
460
+ const url = URL.createObjectURL(blob), a = document.createElement('a');
461
+ try {
462
+ a.href = url;
463
+ a.download = filename;
464
+ document.body.appendChild(a);
465
+ a.click();
466
+ } finally {
467
+ a.remove();
468
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
469
+ }
470
+ }
471
+
472
+ // Below 1:1, encode each candidate quietly, keep the smallest, then report one onEncoded and
473
+ // a final progress of 1. Progress runs 0 to 1 across the candidates without restarting.
474
+ async function smaller(encoder, canvas, base, jobs, hooks) {
475
+ const span = 1 / jobs.length;
476
+ let best = null, record = null;
477
+ for (let i = 0; i < jobs.length; i++) {
478
+ let got = null;
479
+ const result = await encoder.capture(canvas, {
480
+ ...base, ...jobs[i],
481
+ onProgress: hooks.onProgress && (f => { if (f < 1) hooks.onProgress(i * span + f * span); }),
482
+ onEncoded: r => { got = r; },
483
+ });
484
+ if (result.fits && result.bytes && (!best || result.bytes.byteLength < best.bytes.byteLength)) { best = result; record = got; }
485
+ }
486
+ hooks.signal?.throwIfAborted();
487
+ bytesOf(best);
488
+ hooks.onEncoded?.(record ?? { exact: false });
489
+ hooks.signal?.throwIfAborted();
490
+ hooks.onProgress?.(1);
491
+ hooks.signal?.throwIfAborted();
492
+ return best;
493
+ }
494
+
495
+ function bytesOf(result) {
496
+ if (!result?.fits || !result.bytes) {
497
+ throw Object.assign(new Error(result?.reason?.message ?? 'The JPEG XL file did not meet the requested target.'),
498
+ { code: result?.reason?.code ?? 'JXL_UNSUPPORTED' });
499
+ }
500
+ return result.bytes;
501
+ }
502
+
503
+ function abortable(promise, signal) {
504
+ if (!signal) return promise;
505
+ return new Promise((resolve, reject) => {
506
+ const stop = () => reject(signal.reason);
507
+ signal.addEventListener('abort', stop, { once: true });
508
+ if (signal.aborted) stop();
509
+ promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', stop));
510
+ });
511
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zumer/snapdom-plugins",
3
- "version": "5.0.0",
3
+ "version": "5.1.0",
4
4
  "description": "Official plugin toolbox for SnapDOM: prepare, export and record captures",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -19,7 +19,8 @@
19
19
  "./context-export": "./context-export.js",
20
20
  "./html-export": "./html-export.js",
21
21
  "./gif-export": "./gif-export.js",
22
- "./video-export": "./video-export.js"
22
+ "./video-export": "./video-export.js",
23
+ "./jxl": "./jxl.js"
23
24
  },
24
25
  "files": [
25
26
  "*.js",
@@ -51,10 +52,17 @@
51
52
  "url": "https://github.com/sponsors/tinchox5"
52
53
  },
53
54
  "peerDependencies": {
54
- "@zumer/snapdom": "^3.4.0"
55
+ "@zumer/snapdom": "^3.4.0",
56
+ "rapier-jxl": "^8.3.2"
57
+ },
58
+ "peerDependenciesMeta": {
59
+ "rapier-jxl": {
60
+ "optional": true
61
+ }
55
62
  },
56
63
  "devDependencies": {
57
- "@zumer/snapdom": "file:../.."
64
+ "@zumer/snapdom": "file:../..",
65
+ "rapier-jxl": "^8.3.2"
58
66
  },
59
67
  "sideEffects": false
60
68
  }