@zumer/snapdom-plugins 5.0.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.
- package/CHANGELOG.md +28 -0
- package/README.md +50 -7
- package/jxl.d.ts +84 -0
- package/jxl.js +549 -0
- package/package.json +14 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,33 @@
|
|
|
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
|
+
|
|
19
|
+
## 5.1.0
|
|
20
|
+
|
|
21
|
+
> 10 November 2026
|
|
22
|
+
|
|
23
|
+
**Features**
|
|
24
|
+
|
|
25
|
+
- **plugins:** jxl, JPEG XL exports with exact text [`#556`](https://github.com/zumerlab/snapdom/pull/556)
|
|
26
|
+
|
|
27
|
+
**Docs**
|
|
28
|
+
|
|
29
|
+
- **site:** add the JPEG XL plugin page [`5ceba24`](https://github.com/zumerlab/snapdom/commit/5ceba24c2887996381b402c9927d8b9be3445430)
|
|
30
|
+
|
|
3
31
|
## 5.0.0
|
|
4
32
|
|
|
5
33
|
> 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
|
|
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,49 @@ 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 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
|
+
|
|
405
|
+
```bash
|
|
406
|
+
npm install jpegxl@^8.4.0
|
|
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` | `'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 |
|
|
424
|
+
|
|
425
|
+
For the smaller exact-only module:
|
|
426
|
+
|
|
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.
|
|
439
|
+
|
|
440
|
+
---
|
|
441
|
+
|
|
399
442
|
### `gif-export`
|
|
400
443
|
|
|
401
444
|
Adds `toGif()`, which records the live element and returns an `image/gif` Blob. Its built-in
|
|
@@ -494,7 +537,7 @@ npx degit zumerlab/snapdom/packages/plugin-template my-plugin
|
|
|
494
537
|
cd my-plugin && npm install --save-dev @zumer/snapdom@latest
|
|
495
538
|
```
|
|
496
539
|
|
|
497
|
-
See [PLUGIN_SPEC.md](../../PLUGIN_SPEC.md) for the full hook specification and [CONTRIBUTING_PLUGINS.md](
|
|
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.
|
|
498
541
|
|
|
499
542
|
---
|
|
500
543
|
|
|
@@ -505,14 +548,14 @@ Run `npm run compile` and `npm run site` from the monorepo root, then open `/plu
|
|
|
505
548
|
## Releasing from the repository root
|
|
506
549
|
|
|
507
550
|
```sh
|
|
508
|
-
npm run bump:plugins
|
|
509
|
-
npm run bump
|
|
551
|
+
npm run bump:dry -w packages/plugins
|
|
552
|
+
npm run bump -w packages/plugins
|
|
510
553
|
# review packages/plugins/CHANGELOG.md
|
|
511
|
-
npm run release
|
|
554
|
+
npm run release -w packages/plugins
|
|
512
555
|
npm run publish:plugins
|
|
513
556
|
```
|
|
514
557
|
|
|
515
|
-
`
|
|
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`.
|
|
516
559
|
|
|
517
560
|
## Migrating from 4.x
|
|
518
561
|
|
package/jxl.d.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/** JPEG XL exports. The host owns the plugin contract; jpegxl remains an optional peer. */
|
|
2
|
+
import type { SnapdomPlugin, CanvasCrop } from '@zumer/snapdom';
|
|
3
|
+
|
|
4
|
+
/** Every pixel exact, efforts 1-5. */
|
|
5
|
+
export type ExactCaptureModule = 'jpegxl/capture';
|
|
6
|
+
/** Photographic capture, efforts 1-3. */
|
|
7
|
+
export type UploadCaptureModule = 'jpegxl/upload';
|
|
8
|
+
/** Exact text and lossy photos, efforts 1-9. The default. */
|
|
9
|
+
export type CompleteCaptureModule = 'jpegxl/capture-complete';
|
|
10
|
+
export type JxlCaptureModule = ExactCaptureModule | UploadCaptureModule | CompleteCaptureModule;
|
|
11
|
+
export type JxlEffort = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
|
|
12
|
+
|
|
13
|
+
/** Reported once for the file the export returns. */
|
|
14
|
+
export interface JxlEncodedRecord {
|
|
15
|
+
/** True when every pixel of the file is exact. */
|
|
16
|
+
exact: boolean;
|
|
17
|
+
/** Unboxed text was not searched for. */
|
|
18
|
+
textMarks?: 'skipped';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** A directly imported capture module, or an encoder with its prepare and capture methods. */
|
|
22
|
+
export interface JxlEncoder {
|
|
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;
|
|
30
|
+
}>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Alternate modules need the codec you import. Configure helpers on that module. */
|
|
34
|
+
export type JxlOptions = {
|
|
35
|
+
module?: CompleteCaptureModule;
|
|
36
|
+
codec?: JxlEncoder;
|
|
37
|
+
/** Default 3; each export can override it. */
|
|
38
|
+
effort?: JxlEffort;
|
|
39
|
+
/** Disable WebGPU, or require a device for work that uses it. */
|
|
40
|
+
webgpu?: false | 'required';
|
|
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
|
+
};
|
|
52
|
+
|
|
53
|
+
/** Export options and encoding callbacks. Callback promises settle before the export does. */
|
|
54
|
+
export interface JxlExportOptions {
|
|
55
|
+
/** Default 0.92. Photos take this quality; 1 is exact. */
|
|
56
|
+
quality?: number;
|
|
57
|
+
scale?: number;
|
|
58
|
+
width?: number;
|
|
59
|
+
height?: number;
|
|
60
|
+
dpr?: number;
|
|
61
|
+
crop?: CanvasCrop;
|
|
62
|
+
/** Transparent unless a color is set. */
|
|
63
|
+
backgroundColor?: string | null;
|
|
64
|
+
filename?: string;
|
|
65
|
+
format?: string;
|
|
66
|
+
effort?: JxlEffort;
|
|
67
|
+
signal?: AbortSignal;
|
|
68
|
+
/** Encoding progress from 0 to 1, after SnapDOM draws. */
|
|
69
|
+
onProgress?: ((fraction: number) => void) | ((fraction: number) => PromiseLike<void>);
|
|
70
|
+
onEncoded?: ((record: JxlEncodedRecord) => void) | ((record: JxlEncodedRecord) => PromiseLike<void>);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Add toJxl(), toBlob({ format: 'jxl' }) and download({ format: 'jxl' }). */
|
|
74
|
+
export declare function jxl(options?: JxlOptions): JxlPlugin;
|
|
75
|
+
export type JxlPlugin = SnapdomPlugin;
|
|
76
|
+
export default jxl;
|
|
77
|
+
|
|
78
|
+
declare module '@zumer/snapdom' {
|
|
79
|
+
interface CaptureResult {
|
|
80
|
+
toJxl(options?: JxlExportOptions): Promise<HTMLImageElement>;
|
|
81
|
+
toBlob(options: JxlExportOptions & { format: 'jxl' }): Promise<Blob>;
|
|
82
|
+
download(options: JxlExportOptions & { format: 'jxl' }): Promise<void>;
|
|
83
|
+
}
|
|
84
|
+
}
|
package/jxl.js
ADDED
|
@@ -0,0 +1,549 @@
|
|
|
1
|
+
/**
|
|
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
|
|
13
|
+
*/
|
|
14
|
+
export function jxl(options = {}) {
|
|
15
|
+
const { module = 'jpegxl/capture-complete', codec, effort: preset, webgpu } = options;
|
|
16
|
+
// Equal options give the same plugin, so SnapDOM's memo of an unchanged capture holds for an
|
|
17
|
+
// inline `jxl()` too.
|
|
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));
|
|
21
|
+
return made.get(id);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export default jxl;
|
|
25
|
+
|
|
26
|
+
const plugins = new Map(), byCodec = new WeakMap();
|
|
27
|
+
|
|
28
|
+
function create(module, codec, preset, webgpu) {
|
|
29
|
+
const exactOnly = module === 'jpegxl/capture';
|
|
30
|
+
// Edges are measured with the page, for any export effort from 4 (a scan of about 0.1 ms on
|
|
31
|
+
// SnapDOM's demo pages): measuring the page again at export could see it changed.
|
|
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(() => {});
|
|
38
|
+
return {
|
|
39
|
+
name: 'jxl',
|
|
40
|
+
// The measurement reads the live DOM and nothing else, so SnapDOM can keep memoizing
|
|
41
|
+
// unchanged captures.
|
|
42
|
+
pure: true,
|
|
43
|
+
|
|
44
|
+
// Exact capture needs no rectangles. Otherwise text and photos are measured on the page
|
|
45
|
+
// as it was captured; the export maps them onto the drawn canvas.
|
|
46
|
+
...(exactOnly ? {} : {
|
|
47
|
+
afterClone(context) {
|
|
48
|
+
const element = context.element;
|
|
49
|
+
// Only what SnapDOM cloned is drawn: exclude, filter and unslotted children add nothing.
|
|
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.
|
|
52
|
+
try {
|
|
53
|
+
context[SNAPSHOT] = element ? { ...measured(measure, element, edges, keep), frame: frameOf(element, context.outerTransforms !== false) } : null;
|
|
54
|
+
} catch (error) {
|
|
55
|
+
context[SNAPSHOT] = { error };
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
}),
|
|
59
|
+
|
|
60
|
+
defineExports: ({ exports }) => {
|
|
61
|
+
const encodedOnce = async (context, options, callbacks) => {
|
|
62
|
+
// The export's own options first: a beforeExport plugin may have changed them, and a
|
|
63
|
+
// direct call has nothing else.
|
|
64
|
+
const asked = context.export?.requestedOptions ?? {}, pick = k => options[k] !== undefined ? options[k] : asked[k];
|
|
65
|
+
const effort = pick('effort') ?? preset, signal = pick('signal'), onProgress = pick('onProgress'), onEncoded = pick('onEncoded');
|
|
66
|
+
const observe = async (callback, value) => {
|
|
67
|
+
try { await abortable(Promise.resolve(callback(value)), signal); }
|
|
68
|
+
catch (error) { callbacks.failed = true; throw error; }
|
|
69
|
+
};
|
|
70
|
+
signal?.throwIfAborted();
|
|
71
|
+
if (context[SNAPSHOT]?.error) throw context[SNAPSHOT].error;
|
|
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;
|
|
76
|
+
let canvas;
|
|
77
|
+
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);
|
|
85
|
+
signal?.throwIfAborted();
|
|
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 };
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (canvas !== suppliedCanvas) free(canvas);
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
};
|
|
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) => {
|
|
158
|
+
const { blob, canvas, own } = await encoded(context, options);
|
|
159
|
+
if (own) free(canvas);
|
|
160
|
+
return blob;
|
|
161
|
+
};
|
|
162
|
+
// `type` is SnapDOM's older name for `format`, which it keeps for its own formats only. A format
|
|
163
|
+
// chosen for this export (the call, a beforeExport plugin) wins; the capture's own does not.
|
|
164
|
+
const isJxl = (context, options) => {
|
|
165
|
+
if (String(options.format).toLowerCase() === 'jxl') return true;
|
|
166
|
+
const asked = context.export?.requestedOptions ?? options;
|
|
167
|
+
return asked.format === undefined && String(asked.type).toLowerCase() === 'jxl' &&
|
|
168
|
+
(options.__explicitFormat ?? null) === (context.__explicitFormat ?? null);
|
|
169
|
+
};
|
|
170
|
+
const signalOf = (context, options) => options.signal ?? context.export?.requestedOptions?.signal;
|
|
171
|
+
|
|
172
|
+
return {
|
|
173
|
+
jxl: async (context, options = {}) => {
|
|
174
|
+
const { blob, canvas: drawn, exact, own } = await encoded(context, options);
|
|
175
|
+
return image(blob, drawn, own, options.dpr || 1, signalOf(context, options), exact);
|
|
176
|
+
},
|
|
177
|
+
blob: (context, options = {}) => isJxl(context, options) ? encode(context, options) : exports.blob(options),
|
|
178
|
+
async download(context, options = {}) {
|
|
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 });
|
|
184
|
+
signalOf(context, options)?.throwIfAborted();
|
|
185
|
+
await save(blob, filename);
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const SNAPSHOT = Symbol('jxl measurement');
|
|
193
|
+
// SnapDOM's raster limits: 32767 pixels a side (16384 in Safari) and 16384 * 16384 in all.
|
|
194
|
+
const atLimit = ({ width, height }) => [16384, 32767].includes(Math.max(width, height)) || width * height > 0.99 * 16384 * 16384;
|
|
195
|
+
const MAX_PIXELS = 16384 * 16384;
|
|
196
|
+
let decoder = null, complete = null;
|
|
197
|
+
|
|
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 });
|
|
204
|
+
|
|
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.
|
|
208
|
+
function measured(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;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function liftOf(element) {
|
|
229
|
+
const doc = element.ownerDocument, body = doc?.body;
|
|
230
|
+
if (element !== doc?.documentElement || !body) return 0;
|
|
231
|
+
const s = getComputedStyle(element);
|
|
232
|
+
// As SnapDOM decides it: an edge with a border or padding, or a root that starts its own block
|
|
233
|
+
// formatting context, keeps the margins.
|
|
234
|
+
if (parseFloat(s.borderTopWidth) || parseFloat(s.paddingTop) || /flex|grid|table|inline-block|flow-root/.test(s.display) ||
|
|
235
|
+
s.position === 'absolute' || s.position === 'fixed' || s.float !== 'none' || s.overflowX !== 'visible' || s.overflowY !== 'visible' ||
|
|
236
|
+
/layout|content|paint|strict/.test(s.contain)) return 0;
|
|
237
|
+
// A relatively positioned <body> keeps its offset in the clone.
|
|
238
|
+
const b = getComputedStyle(body), moved = b.position === 'relative' ? parseFloat(b.top) || 0 : 0;
|
|
239
|
+
return body.getBoundingClientRect().top - moved - element.getBoundingClientRect().top;
|
|
240
|
+
}
|
|
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
|
+
|
|
259
|
+
// How the page shows the capture root: the viewport point of its layout corner, the scale of the
|
|
260
|
+
// ancestors and the root's own transform. null where an ancestor rotates or skews it, or a
|
|
261
|
+
// transform cannot be read: the export then keeps the whole capture exact.
|
|
262
|
+
function frameOf(element, keepsRotation) {
|
|
263
|
+
try {
|
|
264
|
+
const box = element.getBoundingClientRect(), style = getComputedStyle(element);
|
|
265
|
+
const width = element.offsetWidth ?? box.width, height = element.offsetHeight ?? box.height;
|
|
266
|
+
// No transform on the root or above it, and its layout size is its box: the page's own pixels.
|
|
267
|
+
let flat = none(style.transform) && none(style.rotate) && none(style.scale);
|
|
268
|
+
for (let up = element.parentElement ?? element.getRootNode?.().host; up && flat; up = up.parentElement ?? up.getRootNode?.().host) {
|
|
269
|
+
const s = getComputedStyle(up);
|
|
270
|
+
flat = none(s.transform) && none(s.rotate) && none(s.scale);
|
|
271
|
+
}
|
|
272
|
+
if (flat && Math.abs(box.width - width) < 0.5 && Math.abs(box.height - height) < 0.5) {
|
|
273
|
+
return { toDrawn: p => ({ x: p.x - box.left, y: p.y - box.top }) };
|
|
274
|
+
}
|
|
275
|
+
const [ox, oy] = style.transformOrigin.split(' ').map(parseFloat);
|
|
276
|
+
const transform = style.transform === 'none' ? new DOMMatrix() : new DOMMatrix(style.transform);
|
|
277
|
+
const rotate = style.rotate && style.rotate !== 'none' ? new DOMMatrix(`rotate(${style.rotate})`) : new DOMMatrix();
|
|
278
|
+
const scale = style.scale && style.scale !== 'none' ? new DOMMatrix(`scale(${style.scale.split(' ').slice(0, 2).join(',')})`) : new DOMMatrix();
|
|
279
|
+
transform.e = transform.f = 0; // SnapDOM drops the root's translation
|
|
280
|
+
const live = rotate.multiply(scale).multiply(transform);
|
|
281
|
+
// SnapDOM keeps the root's transform, or with outerTransforms false only its scale and skew,
|
|
282
|
+
// about its top left corner.
|
|
283
|
+
const drawn = keepsRotation ? live : scale.multiply(scaleSkew(transform));
|
|
284
|
+
for (let up = element.parentElement ?? element.getRootNode().host; up; up = up.parentElement ?? up.getRootNode().host) {
|
|
285
|
+
const s = getComputedStyle(up), m = s.transform === 'none' ? null : new DOMMatrix(s.transform);
|
|
286
|
+
if (m && (m.b || m.c) || s.rotate && s.rotate !== 'none') return null;
|
|
287
|
+
}
|
|
288
|
+
const corners = m => [[0, 0], [width, 0], [0, height], [width, height]].map(([x, y]) => m.transformPoint({ x, y }));
|
|
289
|
+
const about = (m, x, y) => new DOMMatrix().translate(x, y).multiply(m).translate(-x, -y);
|
|
290
|
+
const page = corners(about(live, ox, oy));
|
|
291
|
+
const xs = page.map(p => p.x), ys = page.map(p => p.y);
|
|
292
|
+
const near = v => Math.abs(v - 1) < 0.01 ? 1 : v;
|
|
293
|
+
const sx = near(box.width / (Math.max(...xs) - Math.min(...xs) || 1)), sy = near(box.height / (Math.max(...ys) - Math.min(...ys) || 1));
|
|
294
|
+
// From the page to the root's own layout box.
|
|
295
|
+
const toLayout = about(live, ox, oy).inverse()
|
|
296
|
+
.multiply(new DOMMatrix().scale(1 / sx, 1 / sy).translate(-(box.left - Math.min(...xs) * sx), -(box.top - Math.min(...ys) * sy)));
|
|
297
|
+
const shown = (keepsRotation ? about(live, ox, oy) : drawn).multiply(toLayout);
|
|
298
|
+
return { toDrawn: p => shown.transformPoint(p) };
|
|
299
|
+
} catch {
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const none = v => !v || v === 'none';
|
|
305
|
+
|
|
306
|
+
// Firefox as SnapDOM tells it (its isFirefox).
|
|
307
|
+
const firefox = () => typeof navigator !== 'undefined' && (navigator.userAgent || '').toLowerCase().includes('firefox');
|
|
308
|
+
|
|
309
|
+
// Safari as SnapDOM tells it (its isSafari): the browsers whose captures it draws its Safari way.
|
|
310
|
+
function safari() {
|
|
311
|
+
const ua = typeof navigator === 'undefined' ? '' : navigator.userAgent || '', low = ua.toLowerCase(), webkit = /applewebkit/i.test(ua);
|
|
312
|
+
return low.includes('safari') && !/chrome|crios|fxios|android/.test(low) || webkit && /mobile/i.test(ua) && !/safari/i.test(ua) ||
|
|
313
|
+
/(micromessenger|wxwork|wecom|windowswechat|macwechat)/i.test(ua) || /(baiduboxapp|baidubrowser|baidusearch|baiduboxlite)/i.test(low) ||
|
|
314
|
+
/ipad|iphone|ipod/.test(low) && webkit;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// What SnapDOM leaves of a matrix with outerTransforms false: its scale and skew.
|
|
318
|
+
function scaleSkew({ a, b, c, d }) {
|
|
319
|
+
const sx = Math.hypot(a, b);
|
|
320
|
+
if (!sx) return new DOMMatrix();
|
|
321
|
+
const a1 = a / sx, b1 = b / sx, shear = a1 * c + b1 * d;
|
|
322
|
+
const sy = Math.hypot(c - a1 * shear, d - b1 * shear);
|
|
323
|
+
return new DOMMatrix([sx, 0, sy ? shear : 0, sy, 0, 0]);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// The measurement moved into the capture's viewBox, in CSS pixels; null keeps the capture exact.
|
|
327
|
+
// The box is what the canvas shows, in viewBox units. A capture given both width and height fits its
|
|
328
|
+
// viewBox inside them, centered (Safari stretches it instead), and Firefox draws an export given
|
|
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.
|
|
332
|
+
function inView(shot, meta, fitted, exported, crop) {
|
|
333
|
+
if (!shot?.frame || !meta || !Number.isFinite(meta.vbW)) return null;
|
|
334
|
+
const { contentX = 0, contentY = 0, vbW, vbH, clip, targetW, targetH } = meta, { toDrawn } = shot.frame;
|
|
335
|
+
let width = vbW, height = vbH, left = 0, top = 0;
|
|
336
|
+
const fit = (w, h) => { const k = Math.min(w / width, h / height); width = w / k; height = h / k; };
|
|
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);
|
|
347
|
+
const move = r => {
|
|
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 }));
|
|
349
|
+
const xs = ps.map(p => p.x + dx), ys = ps.map(p => p.y + dy);
|
|
350
|
+
return { ...r, left: Math.min(...xs), top: Math.min(...ys), right: Math.max(...xs), bottom: Math.max(...ys) };
|
|
351
|
+
};
|
|
352
|
+
return {
|
|
353
|
+
box: { left: 0, top: 0, width, height },
|
|
354
|
+
text: shot.text.map(t => ({ ...t, r: move(t.r) })),
|
|
355
|
+
photos: shot.photos.map(move),
|
|
356
|
+
...(shot.textComplete === true && { textComplete: true }),
|
|
357
|
+
...(shot.edges && { edges: shot.edges.map(move) }),
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
|
|
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.
|
|
428
|
+
let showsJxl;
|
|
429
|
+
async function image(blob, drawn, own, dpr, signal, exact) {
|
|
430
|
+
const img = new Image(), wait = promise => abortable(promise, signal);
|
|
431
|
+
const { width, height } = drawn?.style ?? {};
|
|
432
|
+
let decoded = null;
|
|
433
|
+
try {
|
|
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);
|
|
448
|
+
}
|
|
449
|
+
const source = decoded ?? drawn;
|
|
450
|
+
await wait(shown(img, await wait(dataURL(await wait(new Promise(resolve => source.toBlob(resolve, 'image/png')))))));
|
|
451
|
+
}
|
|
452
|
+
} finally {
|
|
453
|
+
if (own) free(drawn);
|
|
454
|
+
free(decoded);
|
|
455
|
+
}
|
|
456
|
+
signal?.throwIfAborted();
|
|
457
|
+
img.style.width = width || `${img.naturalWidth / dpr}px`;
|
|
458
|
+
img.style.height = height || `${img.naturalHeight / dpr}px`;
|
|
459
|
+
return img;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// A canvas holds its pixels until it is emptied, even once nothing reads it. Only the export's own
|
|
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
|
+
|
|
468
|
+
function free(canvas) {
|
|
469
|
+
if (typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement) canvas.width = canvas.height = 0;
|
|
470
|
+
}
|
|
471
|
+
|
|
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
|
+
});
|
|
481
|
+
|
|
482
|
+
// iOS saves a file only through the share sheet.
|
|
483
|
+
async function save(blob, filename) {
|
|
484
|
+
const file = new File([blob], filename, { type: blob.type });
|
|
485
|
+
const ios = navigator.userAgentData ? navigator.userAgentData.platform === 'iOS'
|
|
486
|
+
: /iPhone|iPad|iPod/.test(navigator.userAgent) || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;
|
|
487
|
+
if (ios && navigator.canShare?.({ files: [file] })) {
|
|
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;
|
|
491
|
+
}
|
|
492
|
+
const url = URL.createObjectURL(blob), a = document.createElement('a');
|
|
493
|
+
try {
|
|
494
|
+
a.href = url;
|
|
495
|
+
a.download = filename;
|
|
496
|
+
document.body.appendChild(a);
|
|
497
|
+
a.click();
|
|
498
|
+
} finally {
|
|
499
|
+
a.remove();
|
|
500
|
+
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
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.
|
|
506
|
+
async function smaller(encoder, canvas, base, jobs, hooks) {
|
|
507
|
+
const span = 1 / jobs.length;
|
|
508
|
+
let best = null;
|
|
509
|
+
for (let i = 0; i < jobs.length; i++) {
|
|
510
|
+
const result = await encoder.capture(canvas, {
|
|
511
|
+
...base, ...jobs[i],
|
|
512
|
+
onProgress: hooks.onProgress && (f => { if (f < 1) return hooks.onProgress(i * span + f * span); }),
|
|
513
|
+
});
|
|
514
|
+
if (result.meetsTarget && result.bytes && (!best || result.bytes.byteLength < best.bytes.byteLength)) best = result;
|
|
515
|
+
}
|
|
516
|
+
hooks.signal?.throwIfAborted();
|
|
517
|
+
bytesOf(best);
|
|
518
|
+
hooks.signal?.throwIfAborted();
|
|
519
|
+
return best;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
function bytesOf(result) {
|
|
523
|
+
if (!result?.meetsTarget || !result.bytes) {
|
|
524
|
+
throw Object.assign(new Error(result?.reason?.message ?? "No output meets the target; adjust fidelity or size."),
|
|
525
|
+
{ code: result?.reason?.code ?? 'JXL_UNSUPPORTED' });
|
|
526
|
+
}
|
|
527
|
+
return result.bytes;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function abortable(promise, signal) {
|
|
531
|
+
if (!signal) return Promise.resolve(promise);
|
|
532
|
+
return new Promise((resolve, reject) => {
|
|
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); }
|
|
548
|
+
});
|
|
549
|
+
}
|
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zumer/snapdom-plugins",
|
|
3
|
-
"version": "
|
|
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",
|
|
@@ -19,7 +20,8 @@
|
|
|
19
20
|
"./context-export": "./context-export.js",
|
|
20
21
|
"./html-export": "./html-export.js",
|
|
21
22
|
"./gif-export": "./gif-export.js",
|
|
22
|
-
"./video-export": "./video-export.js"
|
|
23
|
+
"./video-export": "./video-export.js",
|
|
24
|
+
"./jxl": "./jxl.js"
|
|
23
25
|
},
|
|
24
26
|
"files": [
|
|
25
27
|
"*.js",
|
|
@@ -51,10 +53,17 @@
|
|
|
51
53
|
"url": "https://github.com/sponsors/tinchox5"
|
|
52
54
|
},
|
|
53
55
|
"peerDependencies": {
|
|
54
|
-
"@zumer/snapdom": "^3.4.0"
|
|
56
|
+
"@zumer/snapdom": "^3.4.0",
|
|
57
|
+
"jpegxl": "^8.4.0"
|
|
58
|
+
},
|
|
59
|
+
"peerDependenciesMeta": {
|
|
60
|
+
"jpegxl": {
|
|
61
|
+
"optional": true
|
|
62
|
+
}
|
|
55
63
|
},
|
|
56
64
|
"devDependencies": {
|
|
57
|
-
"@zumer/snapdom": "file:../.."
|
|
65
|
+
"@zumer/snapdom": "file:../..",
|
|
66
|
+
"jpegxl": "^8.4.0"
|
|
58
67
|
},
|
|
59
68
|
"sideEffects": false
|
|
60
69
|
}
|