@zumer/snapdom-plugins 5.1.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +26 -19
  3. package/jxl.d.ts +40 -54
  4. package/jxl.js +309 -271
  5. package/package.json +6 -5
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Plugin changes
2
2
 
3
+ ## 6.0.0
4
+
5
+ > 17 November 2026
6
+
7
+ **Docs**
8
+
9
+ - the plugin contribution guide lives in .github [`4bdb2d4`](https://github.com/zumerlab/snapdom/commit/4bdb2d4176284a13345bc7a068cf97ad6d8447d0)
10
+
11
+ **Chores**
12
+
13
+ - release each package from its workspace instead of sixteen root aliases [`37f6b34`](https://github.com/zumerlab/snapdom/commit/37f6b341e842f6480786b663a3bc1123de393659)
14
+
15
+ **Other**
16
+
17
+ - Update the JPEG XL plugin for jpegxl 8.4 (#566) [`9fd9092`](https://github.com/zumerlab/snapdom/commit/9fd909257cb0e1e8e26e7c6ad8395db7054ca04c)
18
+
3
19
  ## 5.1.0
4
20
 
5
21
  > 10 November 2026
package/README.md CHANGED
@@ -398,12 +398,12 @@ The document retains source markup, including event-handler attributes; it is no
398
398
 
399
399
  ### `jxl`
400
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.
401
+ Adds `toJxl()`, `toBlob({ format: 'jxl' })` and `download({ format: 'jxl' })`. Text stays exact
402
+ while photos take the quality, in one JPEG XL file. The encoder is rapier-jxl, published on npm
403
+ as [jpegxl](https://www.npmjs.com/package/jpegxl) (MIT), an optional peer.
404
404
 
405
405
  ```bash
406
- npm install rapier-jxl
406
+ npm install jpegxl@^8.4.0
407
407
  ```
408
408
 
409
409
  ```js
@@ -417,18 +417,25 @@ await result.download({ format: 'jxl', filename: 'card' });
417
417
 
418
418
  | Option | Type | Default | Description |
419
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 |
420
+ | `module` | `string` | `'jpegxl/capture-complete'` | With your `codec`: `'jpegxl/capture'` (exact, efforts 1-5) or `'jpegxl/upload'` (photographic, efforts 1-3) |
421
+ | `codec` | `object` | imported capture-complete module | An encoder with `prepare` and `capture` |
422
+ | `effort` | `number` | `3` | Default effort, 1-9 with capture-complete |
423
+ | `webgpu` | `false \| 'required'` | none | Capture-complete only: disable WebGPU, or require a device |
426
424
 
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.
425
+ For the smaller exact-only module:
429
426
 
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.
427
+ ```js
428
+ import * as codec from 'jpegxl/capture';
429
+ const result = await snapdom(el, { plugins: [jxl({ module: 'jpegxl/capture', codec })] });
430
+ ```
431
+
432
+ Exports take `toWebp()`'s options, plus `effort`, `signal`, `onProgress` (0 to 1) and `onEncoded`
433
+ (once, with `{ exact, textMarks? }`). Quality defaults to `0.92`; `1` is exact. The background stays
434
+ transparent unless `backgroundColor` is set. Callback promises settle before the export resolves.
435
+ Configure helper workers on the encoder module with `configure({ helpers })`.
436
+
437
+ `toBlob()` and `download()` give `image/jxl`. Where the browser cannot show JPEG XL, `toJxl()` uses
438
+ the drawn canvas for an exact file or loads `jpegxl/decode` for a lossy one.
432
439
 
433
440
  ---
434
441
 
@@ -530,7 +537,7 @@ npx degit zumerlab/snapdom/packages/plugin-template my-plugin
530
537
  cd my-plugin && npm install --save-dev @zumer/snapdom@latest
531
538
  ```
532
539
 
533
- See [PLUGIN_SPEC.md](../../PLUGIN_SPEC.md) for the full hook specification and [CONTRIBUTING_PLUGINS.md](../../CONTRIBUTING_PLUGINS.md) to get your plugin listed on the community page.
540
+ See [PLUGIN_SPEC.md](../../PLUGIN_SPEC.md) for the full hook specification and [CONTRIBUTING_PLUGINS.md](../../.github/CONTRIBUTING_PLUGINS.md) to get your plugin listed on the community page.
534
541
 
535
542
  ---
536
543
 
@@ -541,14 +548,14 @@ Run `npm run compile` and `npm run site` from the monorepo root, then open `/plu
541
548
  ## Releasing from the repository root
542
549
 
543
550
  ```sh
544
- npm run bump:plugins:dry
545
- npm run bump:plugins
551
+ npm run bump:dry -w packages/plugins
552
+ npm run bump -w packages/plugins
546
553
  # review packages/plugins/CHANGELOG.md
547
- npm run release:plugins
554
+ npm run release -w packages/plugins
548
555
  npm run publish:plugins
549
556
  ```
550
557
 
551
- `release:plugins` commits the plugin version, the lockfile and the changelog, then pushes. `publish:plugins` runs the packaging check (`scripts/check-pack.mjs`), then publishes only `@zumer/snapdom-plugins` under `latest`. PDF, Vector and Stream have the same scripts under their own suffix (`bump:pdf`, `release:pdf`, `publish:pdf`, `publish:pdf:dev`). `bump:plugins` runs `@zumerbox/bump` followed by `@zumerbox/changelog` inside the plugin workspace, matching the core's tools. The bump command requires a clean Git working tree and prompts for the next version. It updates the plugin version and root lockfile; the changelog command writes `packages/plugins/CHANGELOG.md`. `bump:plugins:dry` previews the bump without updating the version or changelog. Skip the bump if the version has already been prepared.
558
+ `bump` asks for the next version, commits and tags it, and writes the changelog; it needs a clean working tree, and `bump:dry` previews it. `release` commits the version, the lockfile and the changelog, then pushes. `publish:plugins` runs the packaging check (`scripts/check-pack.mjs`) and publishes only `@zumer/snapdom-plugins` under `latest`. PDF, Vector and Stream release the same way from `packages/pdf`, `packages/vector` and `packages/stream`, with `publish:pdf`, `publish:vector` and `publish:stream`.
552
559
 
553
560
  ## Migrating from 4.x
554
561
 
package/jxl.d.ts CHANGED
@@ -1,92 +1,78 @@
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';
1
+ /** JPEG XL exports. The host owns the plugin contract; jpegxl remains an optional peer. */
2
+ import type { SnapdomPlugin, CanvasCrop } from '@zumer/snapdom';
9
3
 
10
4
  /** Every pixel exact, efforts 1-5. */
11
- export type ExactCaptureModule = 'rapier-jxl/capture';
5
+ export type ExactCaptureModule = 'jpegxl/capture';
12
6
  /** 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';
7
+ export type UploadCaptureModule = 'jpegxl/upload';
8
+ /** Exact text and lossy photos, efforts 1-9. The default. */
9
+ export type CompleteCaptureModule = 'jpegxl/capture-complete';
16
10
  export type JxlCaptureModule = ExactCaptureModule | UploadCaptureModule | CompleteCaptureModule;
17
-
18
- /** Higher effort takes longer to encode, usually for a smaller file. */
19
11
  export type JxlEffort = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
20
12
 
21
13
  /** Reported once for the file the export returns. */
22
14
  export interface JxlEncodedRecord {
23
15
  /** True when every pixel of the file is exact. */
24
16
  exact: boolean;
25
- bands?: number;
17
+ /** Unboxed text was not searched for. */
18
+ textMarks?: 'skipped';
26
19
  }
27
20
 
28
- /** Your own encoder: a rapier-jxl codec (`createCodec`) or a directly imported capture module. */
21
+ /** A directly imported capture module, or an encoder with its prepare and capture methods. */
29
22
  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 };
23
+ prepare(operation?: 'capture'): Promise<void>;
24
+ capture(input: HTMLCanvasElement, options?: Record<string, unknown>): Promise<{
25
+ meetsTarget: boolean;
26
+ bytes?: Uint8Array | null;
27
+ kept?: string | null;
28
+ textMarks?: 'skipped';
29
+ reason?: { code?: string; message?: string } | null;
35
30
  }>;
36
31
  }
37
32
 
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`. */
33
+ /** Alternate modules need the codec you import. Configure helpers on that module. */
34
+ export type JxlOptions = {
35
+ module?: CompleteCaptureModule;
51
36
  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. */
37
+ /** Default 3; each export can override it. */
55
38
  effort?: JxlEffort;
56
- /** `false` disables WebGPU; `'required'` requires a device for work that uses it. */
39
+ /** Disable WebGPU, or require a device for work that uses it. */
57
40
  webgpu?: false | 'required';
58
- helpers?: JxlHelpers;
59
- }
41
+ } | {
42
+ module: ExactCaptureModule;
43
+ codec: JxlEncoder;
44
+ effort?: 1 | 2 | 3 | 4 | 5;
45
+ webgpu?: never;
46
+ } | {
47
+ module: UploadCaptureModule;
48
+ codec: JxlEncoder;
49
+ effort?: 1 | 2 | 3;
50
+ webgpu?: never;
51
+ };
60
52
 
61
- /** `toWebp()`'s options with the same defaults, plus effort and the encoding callbacks. */
53
+ /** Export options and encoding callbacks. Callback promises settle before the export does. */
62
54
  export interface JxlExportOptions {
63
- /** Default 0.92. Below 1, photos take this quality; 1 is exact. */
55
+ /** Default 0.92. Photos take this quality; 1 is exact. */
64
56
  quality?: number;
65
57
  scale?: number;
66
58
  width?: number;
67
59
  height?: number;
68
60
  dpr?: number;
69
- /** Default `'#ffffff'`. */
61
+ crop?: CanvasCrop;
62
+ /** Transparent unless a color is set. */
70
63
  backgroundColor?: string | null;
71
64
  filename?: string;
72
65
  format?: string;
73
66
  effort?: JxlEffort;
74
67
  signal?: AbortSignal;
75
68
  /** Encoding progress from 0 to 1, after SnapDOM draws. */
76
- onProgress?: (fraction: number) => void;
77
- onEncoded?: (record: JxlEncodedRecord) => void;
69
+ onProgress?: ((fraction: number) => void) | ((fraction: number) => PromiseLike<void>);
70
+ onEncoded?: ((record: JxlEncodedRecord) => void) | ((record: JxlEncodedRecord) => PromiseLike<void>);
78
71
  }
79
72
 
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
- */
73
+ /** Add toJxl(), toBlob({ format: 'jxl' }) and download({ format: 'jxl' }). */
84
74
  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
- }
75
+ export type JxlPlugin = SnapdomPlugin;
90
76
  export default jxl;
91
77
 
92
78
  declare module '@zumer/snapdom' {
package/jxl.js CHANGED
@@ -1,91 +1,56 @@
1
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
2
+ * JPEG XL exports with exact text and lossy photos. Captures are measured in afterClone;
3
+ * exports encode the frozen canvas and preserve transparency unless a background is set.
4
+ * Requires the optional jpegxl 8.4.0 peer. Pinned by __tests__/plugin.jxl.test.js.
5
+ * @module @zumer/snapdom-plugins/jxl
6
+ */
7
+ import { measure, pageRects } from 'jpegxl/page-rects';
8
+
9
+ /**
10
+ * Add toJxl(), toBlob({ format: 'jxl' }) and download({ format: 'jxl' }).
11
+ * @param {import('./jxl.js').JxlOptions} [options]
12
+ * @returns {import('./jxl.js').JxlPlugin} SnapDOM plugin
27
13
  */
28
14
  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;
15
+ const { module = 'jpegxl/capture-complete', codec, effort: preset, webgpu } = options;
33
16
  // Equal options give the same plugin, so SnapDOM's memo of an unchanged capture holds for an
34
17
  // 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));
18
+ const id = JSON.stringify([module, preset, webgpu]);
19
+ const made = codec ? byCodec.get(codec) ?? byCodec.set(codec, new Map()).get(codec) : plugins;
20
+ if (!made.has(id)) made.set(id, create(module, codec, preset, webgpu));
38
21
  return made.get(id);
39
22
  }
40
23
 
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);
24
+ export default jxl;
25
+
26
+ const plugins = new Map(), byCodec = new WeakMap();
44
27
 
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';
28
+ function create(module, codec, preset, webgpu) {
29
+ const exactOnly = module === 'jpegxl/capture';
51
30
  // Edges are measured with the page, for any export effort from 4 (a scan of about 0.1 ms on
52
31
  // 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
-
32
+ const edges = module !== 'jpegxl/upload';
33
+ if (!MODULES.includes(module)) throw new Error(`The jxl plugin's module is ${MODULES.join(', ')} or left out.`);
34
+ if (webgpu !== undefined && module !== COMPLETE) throw new Error(`jxl({module: '${module}'}) runs on WebAssembly; remove webgpu.`);
35
+ if (!codec && module !== COMPLETE) throw new Error(`jxl({module: '${module}'}) needs its codec: import * as codec from '${module}' and pass {codec}.`);
36
+ // Start loading now, so the first export does not wait on the network.
37
+ if (!codec) door().catch(() => {});
60
38
  return {
61
39
  name: 'jxl',
62
40
  // The measurement reads the live DOM and nothing else, so SnapDOM can keep memoizing
63
41
  // unchanged captures.
64
42
  pure: true,
65
43
 
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
44
  // 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.
45
+ // as it was captured; the export maps them onto the drawn canvas.
80
46
  ...(exactOnly ? {} : {
81
- async afterClone(context) {
47
+ afterClone(context) {
82
48
  const element = context.element;
83
49
  // Only what SnapDOM cloned is drawn: exclude, filter and unslotted children add nothing.
84
50
  const keep = context.nodeMap ? new Set(context.nodeMap.values()) : undefined;
51
+ // The measurement serves this plugin's exports only: one that fails rejects a JPEG XL export, never another.
85
52
  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;
53
+ context[SNAPSHOT] = element ? { ...measured(measure, element, edges, keep), frame: frameOf(element, context.outerTransforms !== false) } : null;
89
54
  } catch (error) {
90
55
  context[SNAPSHOT] = { error };
91
56
  }
@@ -93,44 +58,103 @@ function create(module, codec, decoder, preset, webgpu, helpers) {
93
58
  }),
94
59
 
95
60
  defineExports: ({ exports }) => {
96
- const encoded = async (context, options) => {
61
+ const encodedOnce = async (context, options, callbacks) => {
97
62
  // The export's own options first: a beforeExport plugin may have changed them, and a
98
63
  // direct call has nothing else.
99
64
  const asked = context.export?.requestedOptions ?? {}, pick = k => options[k] !== undefined ? options[k] : asked[k];
100
65
  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.');
66
+ const observe = async (callback, value) => {
67
+ try { await abortable(Promise.resolve(callback(value)), signal); }
68
+ catch (error) { callbacks.failed = true; throw error; }
69
+ };
103
70
  signal?.throwIfAborted();
104
71
  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' });
72
+ const encoder = codec ?? await abortable(door(), signal);
73
+ // Upload carries two coders: the capture one is warmed; every other module prepares its own.
74
+ (module === 'jpegxl/upload' ? encoder.prepare('capture') : encoder.prepare()).catch(() => {});
75
+ const drawOptions = { ...options }, suppliedCanvas = drawOptions.canvas;
114
76
  let canvas;
115
77
  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 {
78
+ await abortable(Promise.resolve(exports.canvas(drawOptions)).then(drawn => {
79
+ if (signal?.aborted) {
80
+ if (drawn !== suppliedCanvas) free(drawn);
81
+ signal.throwIfAborted();
82
+ }
83
+ canvas = drawn;
84
+ }), signal);
123
85
  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) };
86
+
87
+ // A quality outside 0 to 1 is ignored for the default, as toWebp's canvas.toBlob ignores it.
88
+ const quality = Number.isFinite(options.quality) && options.quality >= 0 && options.quality <= 1 ? options.quality : 0.92;
89
+ const photo = { quality: Math.max(1, quality * 100) };
90
+ // The canvas shows the capture's viewBox: the measurement moves into it the way SnapDOM
91
+ // drew the root (its outer shadow, transform and clip window), or, where it cannot, the
92
+ // whole capture stays exact.
93
+ const both = o => Number.isFinite(o.width) && Number.isFinite(o.height);
94
+ const fitted = both(context) && !safari(), exported = both(options) && firefox() && options;
95
+ const shot = inView(context[SNAPSHOT], context.meta, fitted, exported, options.crop);
96
+ // WebKit draws a clip window's positioned boxes as if the window began at the element's corner
97
+ // (SnapDOM 3.7.2): in Safari the text stays exact in both places.
98
+ const unclipped = shot && safari() && context.meta?.clip ? inView(context[SNAPSHOT], { ...context.meta, clip: null }, fitted, exported, options.crop) : null;
99
+ const area = {};
100
+
101
+ // Below 1:1, text boxes map through the drawn scale (outward to whole pixels) so glyphs
102
+ // stay exact, and photos still take the quality. With no photos left the page stays exact;
103
+ // with photos, the smaller of that file and the whole page exact wins, so a scaled export
104
+ // is never larger.
105
+ const naturalW = shot?.box.width, naturalH = shot?.box.height;
106
+ const below = !!(shot && naturalW && naturalH &&
107
+ (canvas.width < Math.floor(naturalW) || canvas.height < Math.floor(naturalH)));
108
+ const measured = [shot, unclipped].filter(Boolean).map(s => pageRects(s, canvas, { area, edges: !below && (effort ?? 3) >= 4 }));
109
+ let rects = quality < 1 && !exactOnly && measured.length
110
+ ? { exactRects: measured.flatMap(r => r.exactRects), photoRects: measured.flatMap(r => r.photoRects),
111
+ ...(measured.every(r => r.textComplete === true) && { textComplete: true }) } : null;
112
+ // A page SnapDOM had to shrink to its canvas limit is drawn with its text moved from where
113
+ // the page has it, so the rectangles cannot follow: it stays exact.
114
+ if (below && (!rects?.photoRects?.length || atLimit(canvas))) rects = null;
115
+ // Text over a photograph: one more draw, the capture with its text alone (textMask), gives the encoder the
116
+ // page without its text, so the photograph under the letters takes the quality and the letters stay exact.
117
+ if (rects && !below) {
118
+ const under = await abortable(withoutText(context, options, canvas, rects), signal).catch(error => { if (signal?.aborted) throw error; return null; });
119
+ if (under) rects = { ...rects, withoutText: under };
120
+ }
121
+
122
+ const base = { ...(effort !== undefined && { effort }), ...(webgpu !== undefined && { webgpu }), ...(signal && { signal }) };
123
+ // The encoder's progress up to 1; the export's 1 comes after its record (the record, the abort check, then 1).
124
+ const rising = onProgress && (f => { if (f < 1) return observe(onProgress, f); });
125
+ const file = below && rects
126
+ ? await smaller(encoder, canvas, base, [{ fidelity: photo, ...rects }, { fidelity: 'exact' }], { signal, onProgress: rising })
127
+ : await encoder.capture(canvas, {
128
+ ...(rects ? { fidelity: photo, ...rects } : { fidelity: 'exact' }),
129
+ ...base, ...(rising && { onProgress: rising }),
130
+ });
131
+ // An encoder that finished after the abort still loses to it.
132
+ signal?.throwIfAborted();
133
+ bytesOf(file);
134
+ // The capture's record, read from its result: exact, and whether unboxed text was looked for.
135
+ const record = { exact: file.kept === 'pixels', ...(file.textMarks && { textMarks: file.textMarks }) }, { exact } = record;
136
+ if (onEncoded != null) await observe(onEncoded, record);
137
+ signal?.throwIfAborted();
138
+ if (onProgress != null) await observe(onProgress, 1);
139
+ signal?.throwIfAborted();
140
+ return { blob: new Blob([bytesOf(file)], { type: 'image/jxl' }), canvas, exact, own: canvas !== suppliedCanvas };
128
141
  } catch (error) {
129
- if (mine(canvas)) free(canvas);
142
+ if (canvas !== suppliedCanvas) free(canvas);
130
143
  throw error;
131
144
  }
132
145
  };
133
- const blobOf = async (context, options) => {
146
+ // A canvas the browser handed over blank (WebKit under load: a white canvas where the page has photographs) is
147
+ // refused by the capture with JXL_PLATFORM; SnapDOM draws it once more. A canvas the caller supplied is not redrawn.
148
+ const encoded = async (context, options) => {
149
+ const callbacks = {failed: false};
150
+ try { return await encodedOnce(context, options, callbacks); } catch (error) {
151
+ if (callbacks.failed) throw error;
152
+ const asked = context.export?.requestedOptions ?? {}, signal = options.signal !== undefined ? options.signal : asked.signal;
153
+ if (!blankCanvas(error) || options.canvas || signal?.aborted) throw error;
154
+ return encodedOnce(context, options, callbacks);
155
+ }
156
+ };
157
+ const encode = async (context, options) => {
134
158
  const { blob, canvas, own } = await encoded(context, options);
135
159
  if (own) free(canvas);
136
160
  return blob;
@@ -147,128 +171,58 @@ function create(module, codec, decoder, preset, webgpu, helpers) {
147
171
 
148
172
  return {
149
173
  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);
174
+ const { blob, canvas: drawn, exact, own } = await encoded(context, options);
175
+ return image(blob, drawn, own, options.dpr || 1, signalOf(context, options), exact);
154
176
  },
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).
177
+ blob: (context, options = {}) => isJxl(context, options) ? encode(context, options) : exports.blob(options),
158
178
  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 });
179
+ const format = isJxl(context, options) ? 'jxl' : options.format === 'jpg' ? 'jpeg' : options.format || 'png';
180
+ const name = options.filename || 'snapdom';
181
+ const filename = /\.(png|jpe?g|webp|svg|jxl)$/i.test(name) ? name : `${name}.${format}`;
182
+ const next = { ...options, dpr: 1 };
183
+ const blob = format === 'jxl' ? await encode(context, next) : await exports.blob({ ...next, format });
167
184
  signalOf(context, options)?.throwIfAborted();
168
- await save(blob, filename, true);
185
+ await save(blob, filename);
169
186
  },
170
187
  };
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
188
  },
220
189
  };
221
190
  }
222
191
 
223
- export default jxl;
224
-
225
192
  const SNAPSHOT = Symbol('jxl measurement');
226
193
  // SnapDOM's raster limits: 32767 pixels a side (16384 in Safari) and 16384 * 16384 in all.
227
194
  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 });
195
+ const MAX_PIXELS = 16384 * 16384;
196
+ let decoder = null, complete = null;
259
197
 
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
- }
198
+ // The default module, the one encoder import here (in a browser it runs in its own worker), so a bundler ships no
199
+ // other module; capture and upload arrive only as the `codec` the app imports.
200
+ const COMPLETE = 'jpegxl/capture-complete';
201
+ const MODULES = [COMPLETE, 'jpegxl/capture', 'jpegxl/upload'];
202
+ const door = () => complete ??= import('jpegxl/capture-complete').catch(error => { complete = null; throw needs(error); });
203
+ const needs = error => new Error('The jxl plugin needs jpegxl 8.4.0 or later: npm install jpegxl', { cause: error });
267
204
 
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.
205
+ // SnapDOM draws <html> without the top margins that collapse through its first children (<body>'s
206
+ // own included), so what lies in <body>'s flow is drawn higher by that much; a box positioned on the
207
+ // page itself is not. Those boxes are measured on their own, and the rest moves up.
270
208
  function measured(measure, element, edges, keep) {
271
- return keep && liftOf(element) ? null : measure(element, { edges, keep });
209
+ const lift = keep ? liftOf(element) : 0;
210
+ if (!lift) return measure(element, { edges, keep });
211
+ const placed = onPage(element.ownerDocument.body), inFlow = new Set(keep);
212
+ for (const el of placed) inFlow.delete(el);
213
+ const up = r => ({ ...r, top: r.top - lift, bottom: r.bottom - lift });
214
+ const shot = measure(element, { edges, keep: inFlow });
215
+ shot.text = shot.text.map(t => ({ ...t, r: up(t.r) }));
216
+ shot.photos = shot.photos.map(up);
217
+ if (shot.edges) shot.edges = shot.edges.map(up);
218
+ for (const el of placed) {
219
+ if (!keep.has(el)) continue;
220
+ const own = measure(el, { edges, keep });
221
+ shot.text.push(...own.text);
222
+ shot.photos.push(...own.photos);
223
+ if (shot.edges) shot.edges.push(...own.edges);
224
+ }
225
+ return shot;
272
226
  }
273
227
 
274
228
  function liftOf(element) {
@@ -285,6 +239,23 @@ function liftOf(element) {
285
239
  return body.getBoundingClientRect().top - moved - element.getBoundingClientRect().top;
286
240
  }
287
241
 
242
+ // The outermost absolute or fixed boxes in <body> whose containing block is the page.
243
+ function onPage(body) {
244
+ const placed = [];
245
+ const fixedBlock = s => s.transform !== 'none' || s.perspective !== 'none' || s.filter !== 'none' ||
246
+ /layout|content|paint|strict/.test(s.contain) || /transform|perspective|filter/.test(s.willChange);
247
+ const visit = (el, absolute, fixed) => {
248
+ for (const child of el.children) {
249
+ const s = getComputedStyle(child);
250
+ if (s.position === 'absolute' && absolute || s.position === 'fixed' && fixed) { placed.push(child); continue; }
251
+ visit(child, absolute && s.position === 'static' && !fixedBlock(s), fixed && !fixedBlock(s));
252
+ }
253
+ };
254
+ const s = getComputedStyle(body);
255
+ visit(body, s.position === 'static' && !fixedBlock(s), !fixedBlock(s));
256
+ return placed;
257
+ }
258
+
288
259
  // How the page shows the capture root: the viewport point of its layout corner, the scale of the
289
260
  // ancestors and the root's own transform. null where an ancestor rotates or skews it, or a
290
261
  // transform cannot be read: the export then keeps the whole capture exact.
@@ -356,67 +327,130 @@ function scaleSkew({ a, b, c, d }) {
356
327
  // The box is what the canvas shows, in viewBox units. A capture given both width and height fits its
357
328
  // viewBox inside them, centered (Safari stretches it instead), and Firefox draws an export given
358
329
  // both fitted and centered too (the others stretch it): mapping the box onto the canvas is a stretch.
330
+ // An export's crop is a window of the viewBox, drawn 1:1 (SnapDOM's cropSvgText), never a downscale: the box is the
331
+ // window; over a fitted capture or a fitted export the capture stays exact.
359
332
  function inView(shot, meta, fitted, exported, crop) {
360
333
  if (!shot?.frame || !meta || !Number.isFinite(meta.vbW)) return null;
361
334
  const { contentX = 0, contentY = 0, vbW, vbH, clip, targetW, targetH } = meta, { toDrawn } = shot.frame;
362
- let width = vbW, height = vbH;
335
+ let width = vbW, height = vbH, left = 0, top = 0;
363
336
  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;
337
+ if (crop) {
338
+ if (fitted && targetW && targetH || exported) return null;
339
+ left = Math.max(0, crop.x); top = Math.max(0, crop.y);
340
+ width = Math.min(vbW, crop.x + crop.width) - left; height = Math.min(vbH, crop.y + crop.height) - top;
341
+ if (!(width > 0 && height > 0)) return null;
342
+ } else {
343
+ if (fitted && targetW && targetH) fit(targetW, targetH);
344
+ if (exported) fit(exported.width, exported.height);
345
+ }
346
+ const dx = contentX - (clip?.x ?? 0) - left + (crop ? 0 : (width - vbW) / 2), dy = contentY - (clip?.y ?? 0) - top + (crop ? 0 : (height - vbH) / 2);
367
347
  const move = r => {
368
348
  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
349
  const xs = ps.map(p => p.x + dx), ys = ps.map(p => p.y + dy);
370
350
  return { ...r, left: Math.min(...xs), top: Math.min(...ys), right: Math.max(...xs), bottom: Math.max(...ys) };
371
351
  };
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
352
  return {
382
- ...measurement,
383
- box,
353
+ box: { left: 0, top: 0, width, height },
384
354
  text: shot.text.map(t => ({ ...t, r: move(t.r) })),
385
355
  photos: shot.photos.map(move),
356
+ ...(shot.textComplete === true && { textComplete: true }),
386
357
  ...(shot.edges && { edges: shot.edges.map(move) }),
387
358
  };
388
359
  }
389
360
 
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.
361
+ // Text over a photograph, SnapDOM's way: the export's own SVG drawn once more with every text white and all else
362
+ // transparent (a layer first in its first <style>, so its important rules win), on the export's canvas (the crop as the
363
+ // source rectangle). Its alpha is the text. Images are hidden, so a capture whose originals an export restored draws the
364
+ // same mask. WebKit redraws a page's shadows as filters and moves its letters by up to 2 px, so there the mask grows by
365
+ // 2 px; a first draw that comes back empty is drawn again (WebKit). null where there is no SVG, no text over a
366
+ // photograph, or no mask: the text boxes stay exact.
367
+ const MASK = encodeURIComponent('@layer snapdom-mask{*{color:#fff!important;-webkit-text-fill-color:#fff!important;' +
368
+ 'background:none!important;border-color:transparent!important;box-shadow:none!important;text-shadow:none!important;' +
369
+ 'outline:none!important}img,video,canvas,iframe,foreignObject svg{visibility:hidden!important}}');
370
+ async function withoutText(context, options, canvas, rects) {
371
+ if (typeof HTMLCanvasElement === 'undefined' || !(canvas instanceof HTMLCanvasElement)) return null;
372
+ const over = rects.exactRects.filter(r => !r.edge && rects.photoRects.some(p => r.x < p.x + p.width && p.x < r.x + r.width && r.y < p.y + p.height && p.y < r.y + r.height));
373
+ const url = over.length ? context.export?.url : null, meta = context.meta;
374
+ if (typeof url !== 'string' || !url.startsWith('data:image/svg+xml') || !meta || !Number.isFinite(meta.vbW)) return null;
375
+ // SnapDOM's URL is encodeURIComponent of the SVG: the layer goes in after the first <style ...>, the URL left encoded.
376
+ const at = url.search(/%3Cstyle(%20|%3E)/), end = at < 0 ? -1 : url.indexOf('%3E', at) + 3;
377
+ if (end < 3) return null;
378
+ const img = new Image();
379
+ img.src = url.slice(0, end) + MASK + url.slice(end);
380
+ await img.decode();
381
+ const { width: w, height: h } = canvas, crop = options.crop, kx = img.naturalWidth / meta.vbW, ky = img.naturalHeight / meta.vbH;
382
+ const draw = document.createElement('canvas');
383
+ draw.width = w; draw.height = h;
384
+ const g = draw.getContext('2d', { willReadFrequently: true });
385
+ let alpha = null;
386
+ try {
387
+ for (let tries = 0; tries < 2 && !alpha; tries++) {
388
+ g.clearRect(0, 0, w, h);
389
+ if (crop) {
390
+ const x = Math.max(0, crop.x), y = Math.max(0, crop.y);
391
+ g.drawImage(img, x * kx, y * ky, (Math.min(meta.vbW, crop.x + crop.width) - x) * kx, (Math.min(meta.vbH, crop.y + crop.height) - y) * ky, 0, 0, w, h);
392
+ } else g.drawImage(img, 0, 0, w, h);
393
+ const a = g.getImageData(0, 0, w, h).data;
394
+ for (let i = 3; i < a.length; i += 4) if (a[i]) { alpha = a; break; }
395
+ }
396
+ } finally { free(draw); }
397
+ if (!alpha) return null;
398
+ // A shadow with a length, read in the encoded URL (a declaration ends at ;, } or ").
399
+ const grow = safari() && /(box|text)-shadow%3A(?:[^%]|%(?!3B|7D|22))*?px/i.test(url) ? 2 : 0;
400
+ let mask = new Uint8Array(w * h);
401
+ for (let i = 0; i < mask.length; i++) mask[i] = alpha[i * 4 + 3] ? 1 : 0;
402
+ if (grow) {
403
+ const out = new Uint8Array(mask.length);
404
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (mask[y * w + x])
405
+ for (let dy = Math.max(0, y - grow); dy <= Math.min(h - 1, y + grow); dy++) out.fill(1, dy * w + Math.max(0, x - grow), dy * w + Math.min(w - 1, x + grow) + 1);
406
+ mask = out;
407
+ }
408
+ // The page without its text: each text sample takes the nearest sample left of it on its row that is not text (or
409
+ // right of it, at a row's start), changed where it would equal the drawn one, so every text sample differs.
410
+ const data = canvas.getContext('2d', { willReadFrequently: true }).getImageData(0, 0, w, h).data, under = new Uint8ClampedArray(data);
411
+ for (let y = 0; y < h; y++) {
412
+ let last = -1;
413
+ for (let x = 0; x < w; x++) {
414
+ const i = y * w + x;
415
+ if (!mask[i]) { last = i; continue; }
416
+ let from = last;
417
+ if (from < 0) for (let r = x + 1; r < w; r++) if (!mask[y * w + r]) { from = y * w + r; break; }
418
+ if (from >= 0) under.set(data.subarray(from * 4, from * 4 + 4), i * 4);
419
+ if (under[i * 4] === data[i * 4] && under[i * 4 + 1] === data[i * 4 + 1] && under[i * 4 + 2] === data[i * 4 + 2]) under[i * 4] ^= 1;
420
+ }
421
+ }
422
+ return { data: under, width: w, height: h, rects: over.map(({ x, y, width, height }) => ({ x, y, width, height })) };
423
+ }
424
+
425
+ // Where JPEG XL does not display (found on the first try, then remembered), a PNG of the exact
426
+ // canvas, or of jpegxl/decode's copy (loaded only then). The saved Blob stays JPEG XL. The image
427
+ // takes the drawn canvas's CSS size; its own canvases are emptied once read.
393
428
  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) {
429
+ async function image(blob, drawn, own, dpr, signal, exact) {
396
430
  const img = new Image(), wait = promise => abortable(promise, signal);
397
431
  const { width, height } = drawn?.style ?? {};
398
- if (own) free(drawn);
399
432
  let decoded = null;
400
433
  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;
434
+ try {
435
+ if (showsJxl === false) throw new Error('JPEG XL does not display here');
436
+ await wait(shown(img, await wait(dataURL(blob))));
437
+ showsJxl = true;
438
+ } catch {
439
+ if (signal?.aborted) throw signal.reason;
440
+ if (showsJxl === undefined) showsJxl = false;
441
+ if (!exact) {
442
+ decoder ??= import('jpegxl/decode').catch(error => { decoder = null; throw needs(error); });
443
+ const { data, width: w, height: h } = await wait((await wait(decoder)).decode(blob, { format: 'uint8', colorSpace: 'srgb', maxPixels: MAX_PIXELS, ...(signal && { signal }) }));
444
+ decoded = document.createElement('canvas');
445
+ decoded.width = w;
446
+ decoded.height = h;
447
+ decoded.getContext('2d').putImageData(new ImageData(new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength), w, h), 0, 0);
408
448
  }
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')))));
449
+ const source = decoded ?? drawn;
450
+ await wait(shown(img, await wait(dataURL(await wait(new Promise(resolve => source.toBlob(resolve, 'image/png')))))));
418
451
  }
419
452
  } finally {
453
+ if (own) free(drawn);
420
454
  free(decoded);
421
455
  }
422
456
  signal?.throwIfAborted();
@@ -427,35 +461,33 @@ async function image(blob, drawn, own, dpr, signal, decoder) {
427
461
 
428
462
  // A canvas holds its pixels until it is emptied, even once nothing reads it. Only the export's own
429
463
  // canvases are emptied, never one the app passed as `canvas`.
464
+ // The capture's refusal of a canvas that reads back blank where its rectangles hold content (JXL_PLATFORM; its words, which cross
465
+ // a worker, say "blank" in every jpegxl version).
466
+ const blankCanvas = error => error?.code === 'JXL_PLATFORM' && /\bblank\b/.test(error?.message ?? '');
467
+
430
468
  function free(canvas) {
431
469
  if (typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement) canvas.width = canvas.height = 0;
432
470
  }
433
471
 
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
- }
472
+ const shown = (img, src) => new Promise((resolve, reject) => { img.onload = resolve; img.onerror = reject; img.src = src; })
473
+ .finally(() => { img.onload = img.onerror = null; });
474
+
475
+ const dataURL = blob => new Promise((resolve, reject) => {
476
+ const reader = new FileReader();
477
+ reader.onload = () => resolve(reader.result);
478
+ reader.onerror = () => reject(reader.error);
479
+ reader.readAsDataURL(blob);
480
+ });
443
481
 
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) {
482
+ // iOS saves a file only through the share sheet.
483
+ async function save(blob, filename) {
447
484
  const file = new File([blob], filename, { type: blob.type });
448
485
  const ios = navigator.userAgentData ? navigator.userAgentData.platform === 'iOS'
449
486
  : /iPhone|iPad|iPod/.test(navigator.userAgent) || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;
450
487
  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
- }
488
+ // Closing the sheet is the person's choice; any other refusal is the export's failure.
489
+ try { await navigator.share({ files: [file], title: filename }); } catch (error) { if (error.name !== 'AbortError') throw error; }
490
+ return;
459
491
  }
460
492
  const url = URL.createObjectURL(blob), a = document.createElement('a');
461
493
  try {
@@ -469,43 +501,49 @@ async function save(blob, filename, strict) {
469
501
  }
470
502
  }
471
503
 
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.
504
+ // Below 1:1, encode each candidate quietly and keep the smallest. Progress runs 0 to 1 across the candidates without
505
+ // restarting; the export reports its 1 after the record.
474
506
  async function smaller(encoder, canvas, base, jobs, hooks) {
475
507
  const span = 1 / jobs.length;
476
- let best = null, record = null;
508
+ let best = null;
477
509
  for (let i = 0; i < jobs.length; i++) {
478
- let got = null;
479
510
  const result = await encoder.capture(canvas, {
480
511
  ...base, ...jobs[i],
481
- onProgress: hooks.onProgress && (f => { if (f < 1) hooks.onProgress(i * span + f * span); }),
482
- onEncoded: r => { got = r; },
512
+ onProgress: hooks.onProgress && (f => { if (f < 1) return hooks.onProgress(i * span + f * span); }),
483
513
  });
484
- if (result.fits && result.bytes && (!best || result.bytes.byteLength < best.bytes.byteLength)) { best = result; record = got; }
514
+ if (result.meetsTarget && result.bytes && (!best || result.bytes.byteLength < best.bytes.byteLength)) best = result;
485
515
  }
486
516
  hooks.signal?.throwIfAborted();
487
517
  bytesOf(best);
488
- hooks.onEncoded?.(record ?? { exact: false });
489
- hooks.signal?.throwIfAborted();
490
- hooks.onProgress?.(1);
491
518
  hooks.signal?.throwIfAborted();
492
519
  return best;
493
520
  }
494
521
 
495
522
  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.'),
523
+ if (!result?.meetsTarget || !result.bytes) {
524
+ throw Object.assign(new Error(result?.reason?.message ?? "No output meets the target; adjust fidelity or size."),
498
525
  { code: result?.reason?.code ?? 'JXL_UNSUPPORTED' });
499
526
  }
500
527
  return result.bytes;
501
528
  }
502
529
 
503
530
  function abortable(promise, signal) {
504
- if (!signal) return promise;
531
+ if (!signal) return Promise.resolve(promise);
505
532
  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));
533
+ let done = false;
534
+ const finish = (settle, value) => {
535
+ if (done) return;
536
+ done = true;
537
+ try { signal.removeEventListener('abort', stop); }
538
+ catch (reason) { if (settle === resolve) { reject(reason); return; } }
539
+ settle(value);
540
+ };
541
+ const stop = () => {
542
+ try { if (signal.aborted) finish(reject, signal.reason); }
543
+ catch (reason) { finish(reject, reason); }
544
+ };
545
+ Promise.resolve(promise).then(value => finish(resolve, value), error => finish(reject, error));
546
+ try { signal.addEventListener('abort', stop, { once: true }); stop(); }
547
+ catch (reason) { finish(reject, reason); }
510
548
  });
511
549
  }
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@zumer/snapdom-plugins",
3
- "version": "5.1.0",
3
+ "version": "6.0.0",
4
4
  "description": "Official plugin toolbox for SnapDOM: prepare, export and record captures",
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "bump:dry": "npx @zumerbox/bump -d",
8
- "bump": "npx @zumerbox/bump && npx @zumerbox/changelog"
8
+ "bump": "npx @zumerbox/bump && npx @zumerbox/changelog",
9
+ "release": "git add package.json CHANGELOG.md ../../package-lock.json && git commit -m \"Bumped plugins version\" && git push"
9
10
  },
10
11
  "exports": {
11
12
  ".": "./index.js",
@@ -53,16 +54,16 @@
53
54
  },
54
55
  "peerDependencies": {
55
56
  "@zumer/snapdom": "^3.4.0",
56
- "rapier-jxl": "^8.3.2"
57
+ "jpegxl": "^8.4.0"
57
58
  },
58
59
  "peerDependenciesMeta": {
59
- "rapier-jxl": {
60
+ "jpegxl": {
60
61
  "optional": true
61
62
  }
62
63
  },
63
64
  "devDependencies": {
64
65
  "@zumer/snapdom": "file:../..",
65
- "rapier-jxl": "^8.3.2"
66
+ "jpegxl": "^8.4.0"
66
67
  },
67
68
  "sideEffects": false
68
69
  }