@weasel-js/export 0.0.0-stage → 2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 orochi235
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,87 @@
1
- # Temporary Holding Version
1
+ # @weasel-js/export
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Regions of a scene written to a file: a page, a selection or any world-space
4
+ rect, as PNG or any format another package registers.
5
+
6
+ Part of [weasel](https://github.com/orochi235/weasel), a domain-agnostic
7
+ scene-graph engine for React. See the
8
+ [API reference](https://orochi235.github.io/weasel/#pkg/export).
9
+
10
+ ```sh
11
+ npm install @weasel-js/export
12
+ ```
13
+
14
+ A registry of export formats, each writing one or more world-space rectangles
15
+ of a `@weasel-js/core` scene to a file. This package registers `png`;
16
+ `@weasel-js/svg` registers `svg` (`registerSvgExport()`) and
17
+ `@weasel-js/pdf/export` registers `pdf` (`registerPdfExport()`), so it depends
18
+ on neither.
19
+
20
+ ```ts
21
+ import { placedPagesOf, viewportWorldRect } from '@weasel-js/core';
22
+ import { exportPages, exportRegions, selectionRegionsSource } from '@weasel-js/export';
23
+
24
+ const pages = placedPagesOf(scene);
25
+ const png = await exportPages(scene, [pages[0]], 'png', { scale: 2, background: '#ffffff' });
26
+ const shown = await exportRegions(scene, [viewportWorldRect(view, { width, height })], 'png');
27
+ const picked = await exportRegions(scene, selectionRegionsSource(selection.get()), 'svg');
28
+ ```
29
+
30
+ A region is an `ExportRegion`: `{ x, y, width, height, name? }` in world
31
+ units. `exportPages` makes one of each `PlacedPage`, named as the page order
32
+ shows it; `viewportWorldRect(view, size)` is the one a view shows;
33
+ `selectionRegion(scene, ids, { scale })` is the box the ids draw, strokes
34
+ included, measured at the export's `scale`; `selectionRegionsSource(ids)` reads
35
+ that box from the revision the export draws, as `pageRegionsSource` does for
36
+ pages, and fails the export when the selection draws nothing.
37
+ `name` labels a PDF page and titles an SVG.
38
+
39
+ A region is of the document: every format draws each layer at its document
40
+ pose, a parallax layer's included, so what a page or selection holds lands
41
+ inside it at any `scale`. Parallax is the camera's, and a region export has
42
+ none. To capture what a camera shows, planes and all, render with that camera:
43
+ `renderSceneToPixels({ scene, sourceRect: viewportWorldRect(view, size), scale, camera: view })`
44
+ places each plane as `view` does, and its `scale` changes only the resolution.
45
+
46
+ `exportRegions(scene, regions, formatId, opts)` writes them in the format
47
+ registered under `formatId` and answers a `Blob`. It rejects for an id nothing
48
+ registered, and for several regions handed to a format that is not
49
+ `multiRegion`. Every format takes `background` (default none: core holds no
50
+ page color), `onDiagnostic`, and `strict`; the rest of `opts`
51
+ goes to the format (`scale` for `png`, `title` for `svg` and `pdf`).
52
+ `exportFormats()` lists what is registered, `png` first, the same array until
53
+ the registry changes; `exportFormatRegistry` is its reflection, with
54
+ `subscribe` for a menu that lists them. `registerExportFormat(format)` adds
55
+ one and returns its disposer; registering an id that is held overrides it.
56
+
57
+ Each export draws the document, not what an open gesture or edit is showing,
58
+ writes nothing to the scene, and leaves annotation layers out. It draws one
59
+ revision of it: `captureExport` loads what the regions need, and reads them
60
+ only if no content changed meanwhile, or starts again, up to
61
+ `EXPORT_CAPTURE_ATTEMPTS` times before rejecting with `ExportRevisionError`.
62
+ Regions may be a function of the document, `(doc) => regions`, read again each
63
+ time, so bounds measured from it belong to the revision drawn: `exportPages`
64
+ places its pages that way, by id, through `pageRegionsSource(pages)`, and
65
+ `pageRegionSource(page)` is the same for one page. A format of your own goes through
66
+ `captureExport` too, warming in `warm` and reading everything it writes in
67
+ `read`.
68
+ What an export draws without reaches `onDiagnostic` once each, as an
69
+ `ExportDiagnostic`: `{ kind, subject, message }`, where `kind` is `image` (a
70
+ picture that failed to load, drawn as a placeholder), `font` (a face that
71
+ failed, or glyphs a format could not carry), `paint-kind` (a kind nothing
72
+ registered, or one whose load failed), `shader` (a program with no source the
73
+ target draws), or `unsupported` (what the format cannot hold), and `subject`
74
+ names the source, family, kind or program. An export is best-effort: it
75
+ writes the file without them, so a caller that heard nothing has a complete
76
+ file. With `strict: true` it writes nothing when it hears anything and rejects
77
+ with `ExportIncompleteError`, whose `diagnostics` lists them. Nothing goes to
78
+ the console. A format of your own reports through `exportReporter(opts)`, and
79
+ `warmRender({ render, report })` reports a headless render's losses the same way.
80
+
81
+ `exportRegionPng(scene, region, { scale, background })` is the `png` format
82
+ on its own: the renderer's pixels, `region × scale` in size. It needs WebGL2.
83
+
84
+ `regionRenderArgs(scene, region, { scale, background })` is the render a
85
+ region draws with, which the PNG and PDF exports build on. Handed to
86
+ `@weasel-js/headless`'s raster host as they are, they render a region from
87
+ Node.
@@ -0,0 +1,255 @@
1
+ import { Reflection, PushOptions } from '@weasel-js/registry';
2
+ import { Rect } from '@weasel-js/geom';
3
+ import { Scene, RectPose, RenderDiagnostic, PlacedPage, RenderSceneToPixelsArgs, RenderDiagnosticSink } from '@weasel-js/core';
4
+
5
+ /** The types the export registry and its formats share. */
6
+
7
+ /**
8
+ * A rectangle of the document to export: a page (`exportPages` makes one of
9
+ * each `PlacedPage`), the world rect a view spans (`viewportWorldRect`), a
10
+ * selection's bounds, or any other. Every format draws each layer in it at its
11
+ * document pose: a parallax layer's camera tracking is not applied. `name` is
12
+ * what a format that labels its pages or documents calls it: a PDF page's
13
+ * label, an SVG's `<title>`.
14
+ */
15
+ interface ExportRegion extends Rect {
16
+ readonly name?: string;
17
+ }
18
+ /**
19
+ * The regions an export writes: fixed rects, or a function reading them from
20
+ * the document. A function is called each time the export reads the document,
21
+ * so bounds that come from it, a page's or a selection's, belong to the same
22
+ * revision as what is drawn in them.
23
+ */
24
+ type ExportRegions = readonly ExportRegion[] | ((doc: ExportScene) => readonly ExportRegion[]);
25
+ /** One region an export writes, fixed or read from the document, as {@link ExportRegions} holds them. */
26
+ type ExportRegionSource = ExportRegion | ((doc: ExportScene) => ExportRegion);
27
+ /** A scene as the exports read it: world-space `RectPose`s. */
28
+ type ExportScene = Scene<unknown, string, RectPose>;
29
+ /** The color painted under a region: a color, `null` for none, or a function reading it from the
30
+ * document the export draws, so a color that comes from it belongs to the revision drawn. */
31
+ type ExportBackground = string | null | ((doc: ExportScene) => string | null);
32
+ /** `background` as of `doc`. */
33
+ declare const exportBackgroundOf: (background: ExportBackground | undefined, doc: ExportScene) => string | null;
34
+ /** What every format takes. */
35
+ interface ExportOptions {
36
+ /** The color painted under each region, or a function reading it from the document the export draws.
37
+ * Default none: core holds no page color. */
38
+ background?: ExportBackground;
39
+ /** Hears each thing the export could not draw or load, once: a picture or face
40
+ * that failed, a paint kind or shader nothing can draw, what the format cannot hold. */
41
+ onDiagnostic?: (diagnostic: RenderDiagnostic) => void;
42
+ /** Write nothing when anything is diagnosed, and reject with `ExportIncompleteError`.
43
+ * Default `false`: best-effort, the file is written without it. */
44
+ strict?: boolean;
45
+ }
46
+ /**
47
+ * One way of writing regions of a scene to a file, registered with
48
+ * `registerExportFormat`. `TOptions` is what the format reads beyond
49
+ * {@link ExportOptions}. `exportRegions` hands a format whatever its caller
50
+ * passed, so a format treats every option of its own as optional there.
51
+ */
52
+ interface ExportFormat<TOptions extends ExportOptions = ExportOptions> {
53
+ /** The id `exportRegions` names it by: `'png'`, `'svg'`, `'pdf'`. */
54
+ readonly id: string;
55
+ /** What a menu calls it: "PNG Image". */
56
+ readonly label: string;
57
+ readonly mimeType: string;
58
+ /** The file extension, without the dot. */
59
+ readonly extension: string;
60
+ /** Whether one file holds several regions, as a PDF's pages do. A single-region format takes exactly one. */
61
+ readonly multiRegion: boolean;
62
+ /**
63
+ * The option keys it reads beyond {@link ExportOptions}. `exportRegions` warns in development about a
64
+ * key passed to this format that neither lists, and {@link pickExportOptions} picks these. Left out,
65
+ * nothing is checked.
66
+ */
67
+ readonly options?: readonly Exclude<keyof TOptions, keyof ExportOptions>[];
68
+ export(scene: ExportScene, regions: ExportRegions, opts: TOptions): Promise<Blob>;
69
+ }
70
+
71
+ /**
72
+ * The export registry: the formats a scene's regions can be written in, each
73
+ * registered by the package that can write it. This package registers `png`;
74
+ * svg and pdf register theirs (`registerSvgExport`, `registerPdfExport`), so it
75
+ * depends on neither.
76
+ */
77
+
78
+ /** Every registered export format, keyed by id, with the overrides each displaced. */
79
+ declare const exportFormatRegistry: Reflection<ExportFormat>;
80
+ /**
81
+ * Register an export format. Returns a disposer that removes this
82
+ * registration. Registering an id already held overrides it, `png` included;
83
+ * disposing uncovers what it displaced. `fallback` marks an engine default,
84
+ * which a later registration replaces without the development clash warning.
85
+ */
86
+ declare function registerExportFormat<TOptions extends ExportOptions>(format: ExportFormat<TOptions>, options?: Pick<PushOptions, 'fallback'>): () => void;
87
+ /** Every registered format, `png` first, then in registration order. The same array until the registry changes. */
88
+ declare function exportFormats(): readonly ExportFormat[];
89
+ /**
90
+ * Write `regions` of `scene` in the format registered as `formatId`. Rejects
91
+ * for an id nothing registered, for more or fewer than one region handed to a
92
+ * format that is not `multiRegion` (a multi-region format takes one or more),
93
+ * and with whatever the format throws, synchronously or not. Regions given as
94
+ * a function of the document are counted each time the export reads them.
95
+ */
96
+ declare function exportRegions(scene: ExportScene, regions: ExportRegions, formatId: string, opts?: ExportOptions & Readonly<Record<string, unknown>>): Promise<Blob>;
97
+ /** The options `format` reads out of `opts`, the shared ones and those it declares, leaving out any undefined. */
98
+ declare function pickExportOptions<TOptions extends ExportOptions>(format: ExportFormat<TOptions>, opts: TOptions): Partial<TOptions>;
99
+
100
+ /** `page` as an export region, named as the page order shows it. */
101
+ declare function pageRegion(page: PlacedPage): ExportRegion;
102
+ /**
103
+ * `pages` as regions read from the document an export draws: each page placed
104
+ * as that document places it, found by its id, and named for it. A page the
105
+ * document no longer holds fails the export.
106
+ */
107
+ declare function pageRegionsSource(pages: readonly PlacedPage[]): (doc: ExportScene) => readonly ExportRegion[];
108
+ /** One page as {@link pageRegionsSource} reads it: the region source of a single-region export. */
109
+ declare function pageRegionSource(page: PlacedPage): (doc: ExportScene) => ExportRegion;
110
+ /**
111
+ * Write `pages` of `scene` in the format registered as `formatId`, each page
112
+ * a region named for the page: `exportRegions` over {@link pageRegionsSource}. A
113
+ * single-region format takes one page.
114
+ */
115
+ declare function exportPages(scene: ExportScene, pages: readonly PlacedPage[], formatId: string, opts?: ExportOptions & Readonly<Record<string, unknown>>): Promise<Blob>;
116
+
117
+ /** Options for {@link exportRegionPng}. */
118
+ interface ExportRegionPngOptions extends Pick<ExportOptions, 'onDiagnostic' | 'strict'> {
119
+ /** Output pixels per world unit: 2 makes an image twice the region's size. */
120
+ scale: number;
121
+ /** The color painted under the region, or a function reading it from the document drawn. Default none: the
122
+ * image is transparent where nothing is drawn. */
123
+ background?: ExportBackground;
124
+ }
125
+ /**
126
+ * Draw `region` of `scene` into a PNG, `region × scale` pixels, through the
127
+ * renderer the canvas draws with, so it shows what the canvas shows, cut to
128
+ * the region's edges. It draws the document: a gesture or edit in flight is
129
+ * not shown. Annotation layers are left out.
130
+ *
131
+ * The caller has registered whatever the scene needs painting with, as it
132
+ * must to draw it at all: its painters (`registerNodeShape`) and its fonts.
133
+ * Paint kinds and faces that load on demand are waited for, and the image is
134
+ * of one revision of the document: see `captureExport`. What it draws
135
+ * without goes to `onDiagnostic`, and a `strict` export rejects with
136
+ * `ExportIncompleteError` rather than write it. Needs WebGL2.
137
+ */
138
+ declare function exportRegionPng(scene: ExportScene, region: ExportRegionSource, opts: ExportRegionPngOptions): Promise<Blob>;
139
+ /** The `png` format's own option. */
140
+ interface PngExportOptions extends ExportOptions {
141
+ /** Output pixels per world unit. Default 1. */
142
+ scale?: number;
143
+ }
144
+
145
+ /** Options for {@link selectionRegion} and its sources. */
146
+ interface SelectionRegionOptions {
147
+ /** What the region is called: a PDF page's label, an SVG's `<title>`. */
148
+ name?: string;
149
+ /** The output pixels per world unit the export draws at, which a screen-pixel (`{ px }`) stroke is
150
+ * measured at. Default 1. Pass the export's `scale` so such a stroke is not cut at its edge. */
151
+ scale?: number;
152
+ }
153
+ /**
154
+ * The world box `ids` cover as the document draws them, strokes included:
155
+ * the region that exports a selection. Pages and the page run are left out of
156
+ * `ids`, and so is what no export draws: a hidden node, and a node on a
157
+ * hidden or annotation layer (what its children draw still counts). `null`
158
+ * when none of them draws anything. A string third argument is the name.
159
+ */
160
+ declare function selectionRegion(scene: ExportScene, ids: readonly string[], opts?: string | SelectionRegionOptions): ExportRegion | null;
161
+ /**
162
+ * `ids`' region read from the document an export draws, so the bounds belong to
163
+ * the revision drawn in them: the region source of a single-region export. A
164
+ * selection that draws nothing in that document fails the export.
165
+ */
166
+ declare function selectionRegionSource(ids: readonly string[], opts?: SelectionRegionOptions): (doc: ExportScene) => ExportRegion;
167
+ /** {@link selectionRegionSource} as the regions `exportRegions` takes. */
168
+ declare function selectionRegionsSource(ids: readonly string[], opts?: SelectionRegionOptions): (doc: ExportScene) => readonly ExportRegion[];
169
+
170
+ /** What {@link regionRenderArgs} answers: the part of `renderSceneToPixels`'s arguments a region decides. */
171
+ type RegionRenderArgs = Pick<RenderSceneToPixelsArgs<unknown, string, RectPose>, 'scene' | 'sourceRect' | 'scale' | 'background'>;
172
+ /** Options for {@link regionRenderArgs}. */
173
+ interface RegionRenderArgsOptions {
174
+ /** Output pixels per world unit. */
175
+ scale: number;
176
+ /** The color painted under the region, or a function reading it from the document drawn. Default none: transparent. */
177
+ background?: ExportBackground;
178
+ }
179
+ /**
180
+ * The arguments `region` of `scene` renders with: the scene's document (not
181
+ * what an open gesture or edit is showing), the region as the source rect, and
182
+ * `scale` on both axes. The PNG and PDF exports draw through these.
183
+ *
184
+ * Outside a browser, hand them to `@weasel-js/headless`'s raster host, whose
185
+ * `NodeRenderArgs` they satisfy as they are, to render a page or any other
186
+ * region from Node.
187
+ */
188
+ declare function regionRenderArgs(scene: ExportScene, region: ExportRegion, opts: RegionRenderArgsOptions): RegionRenderArgs;
189
+
190
+ /**
191
+ * The one boundary every export reads the document at: what it draws comes
192
+ * from a single revision, with what that revision needs loaded.
193
+ */
194
+
195
+ /** How many times an export reads the document before giving up on it holding still. */
196
+ declare const EXPORT_CAPTURE_ATTEMPTS = 3;
197
+ /** An export gave up: the document changed while each of its attempts loaded what it draws. */
198
+ declare class ExportRevisionError extends Error {
199
+ readonly attempts: number;
200
+ constructor(attempts: number);
201
+ }
202
+ /** The two halves of an export's read of the document, as {@link captureExport} runs them. Each
203
+ * reports what the export will draw without to `report`. */
204
+ interface ExportCaptureSteps<T> {
205
+ /** Load what drawing `regions` of `doc` needs: fonts, paint kinds, pictures. */
206
+ warm(doc: ExportScene, regions: readonly ExportRegion[], report: RenderDiagnosticSink): Promise<void>;
207
+ /** Read everything the file is written from, synchronously, into values the document cannot change. */
208
+ read(doc: ExportScene, regions: readonly ExportRegion[], report: RenderDiagnosticSink): T;
209
+ }
210
+ /** One region source as the {@link ExportRegions} {@link captureExport} takes. */
211
+ declare const regionsOfOne: (region: ExportRegionSource) => ExportRegions;
212
+ /** `regions` as of `doc`: each a copy, so a caller's later edit to one reaches no export in flight. */
213
+ declare function exportRegionsOf(regions: ExportRegions, doc: ExportScene): readonly ExportRegion[];
214
+ /**
215
+ * Read `regions` of `scene`'s document through `steps`, from one content
216
+ * revision (`getContentVersion`): warm, then, if no content changed while it
217
+ * loaded, read at once, in the same task. Fixed regions are copied when it is
218
+ * called. A change restarts it, with the
219
+ * regions read again when they are a function of the document, so the bounds
220
+ * and the content come from the same revision. After
221
+ * {@link EXPORT_CAPTURE_ATTEMPTS} attempts it rejects with
222
+ * {@link ExportRevisionError}.
223
+ *
224
+ * What a gesture or an open edit shows is never read, and a change of
225
+ * selection restarts nothing. The painters, paint kinds and fonts registered
226
+ * when `read` runs are the ones it draws with. What the steps report reaches
227
+ * `report` only from the attempt that is read, once it has been.
228
+ */
229
+ declare function captureExport<T>(scene: ExportScene, regions: ExportRegions, steps: ExportCaptureSteps<T>, report?: RenderDiagnosticSink): Promise<T>;
230
+
231
+ /** How every export reports what it could not draw, and when it refuses to write a file without it. */
232
+
233
+ /** One thing an export drew without, or drew in part: a `RenderDiagnostic`. */
234
+ type ExportDiagnostic = RenderDiagnostic;
235
+ /** A strict export (`strict: true`) found something it could not draw, and wrote nothing. */
236
+ declare class ExportIncompleteError extends Error {
237
+ readonly diagnostics: readonly ExportDiagnostic[];
238
+ constructor(diagnostics: readonly ExportDiagnostic[]);
239
+ }
240
+ /** One export's diagnostics: `report` hears each, `settle` ends the export's reporting. */
241
+ interface ExportReporter {
242
+ readonly report: RenderDiagnosticSink;
243
+ /** Throws {@link ExportIncompleteError} for a strict export that reported anything. */
244
+ settle(): void;
245
+ }
246
+ /**
247
+ * The reporter an export with `opts` reports through. Each diagnostic reaches
248
+ * `onDiagnostic` once, however often it is found. Best-effort, the default,
249
+ * writes the file without what it reports; `strict` writes none when it
250
+ * reports anything, and `settle` throws instead.
251
+ */
252
+ declare function exportReporter(opts: Pick<ExportOptions, 'onDiagnostic' | 'strict'>): ExportReporter;
253
+
254
+ export { EXPORT_CAPTURE_ATTEMPTS, ExportIncompleteError, ExportRevisionError, captureExport, exportBackgroundOf, exportFormatRegistry, exportFormats, exportPages, exportRegionPng, exportRegions, exportRegionsOf, exportReporter, pageRegion, pageRegionSource, pageRegionsSource, pickExportOptions, regionRenderArgs, regionsOfOne, registerExportFormat, selectionRegion, selectionRegionSource, selectionRegionsSource };
255
+ export type { ExportBackground, ExportCaptureSteps, ExportDiagnostic, ExportFormat, ExportOptions, ExportRegion, ExportRegionPngOptions, ExportRegionSource, ExportRegions, ExportReporter, ExportScene, PngExportOptions, RegionRenderArgs, RegionRenderArgsOptions, SelectionRegionOptions };
package/dist/index.js ADDED
@@ -0,0 +1,259 @@
1
+ import { createReflectable, isDev } from '@weasel-js/registry';
2
+ import { holdImageBitmaps } from '@weasel-js/renderer';
3
+ import { documentOf, createRasterSession, rasterToPng, pageName, placedPagesOf, worldPoseLookup, scenePoseAdapter, drawnBoundsScene, unionAabb, withoutPageStructure, nodeGates, annotationLayerIds, drawnAabbOf, planPixelRender, warmRender } from '@weasel-js/core';
4
+
5
+ // src/exportFormats.ts
6
+ var EXPORT_CAPTURE_ATTEMPTS = 3;
7
+ var ExportRevisionError = class extends Error {
8
+ constructor(attempts) {
9
+ super(`export: the document changed while the export loaded what it draws, ${attempts} times running; nothing was written`);
10
+ this.attempts = attempts;
11
+ }
12
+ attempts;
13
+ };
14
+ var regionsOfOne = (region) => typeof region === "function" ? (doc) => [region(doc)] : [region];
15
+ function exportRegionsOf(regions, doc) {
16
+ const list = typeof regions === "function" ? regions(doc) : regions;
17
+ return Object.freeze(list.map((r) => Object.freeze({ ...r })));
18
+ }
19
+ async function captureExport(scene, regions, steps, report = () => {
20
+ }) {
21
+ const doc = documentOf(scene);
22
+ const source = typeof regions === "function" ? regions : exportRegionsOf(regions, doc);
23
+ for (let attempt = 1; ; attempt++) {
24
+ const revision = scene.getContentVersion();
25
+ const heard = [];
26
+ const hear = (d) => {
27
+ heard.push(d);
28
+ };
29
+ await steps.warm(doc, exportRegionsOf(source, doc), hear);
30
+ if (scene.getContentVersion() === revision) {
31
+ const read = steps.read(doc, exportRegionsOf(source, doc), hear);
32
+ heard.forEach(report);
33
+ return read;
34
+ }
35
+ if (attempt >= EXPORT_CAPTURE_ATTEMPTS) throw new ExportRevisionError(attempt);
36
+ }
37
+ }
38
+
39
+ // src/exportDiagnostics.ts
40
+ var ExportIncompleteError = class extends Error {
41
+ constructor(diagnostics) {
42
+ super(`export: ${diagnostics.length === 1 ? "one thing" : `${diagnostics.length} things`} could not be drawn, and a strict export writes nothing without them: ${diagnostics.map((d) => d.message).join("; ")}`);
43
+ this.diagnostics = diagnostics;
44
+ }
45
+ diagnostics;
46
+ };
47
+ function exportReporter(opts) {
48
+ const seen = /* @__PURE__ */ new Map();
49
+ return {
50
+ report(d) {
51
+ const key = `${d.kind}\0${d.subject}\0${d.message}`;
52
+ if (seen.has(key)) return;
53
+ seen.set(key, d);
54
+ opts.onDiagnostic?.(d);
55
+ },
56
+ settle() {
57
+ if (opts.strict && seen.size > 0) throw new ExportIncompleteError([...seen.values()]);
58
+ }
59
+ };
60
+ }
61
+
62
+ // src/exportTypes.ts
63
+ var exportBackgroundOf = (background, doc) => typeof background === "function" ? background(doc) : background ?? null;
64
+
65
+ // src/regionRenderArgs.ts
66
+ function regionRenderArgs(scene, region, opts) {
67
+ const doc = documentOf(scene);
68
+ const background = exportBackgroundOf(opts.background, doc);
69
+ return {
70
+ scene: doc,
71
+ sourceRect: { x: region.x, y: region.y, width: region.width, height: region.height },
72
+ scale: { x: opts.scale, y: opts.scale },
73
+ ...background !== null ? { background } : {}
74
+ };
75
+ }
76
+
77
+ // src/regionPng.ts
78
+ function capturePngRegion(scene, region, opts, report) {
79
+ return captureExport(scene, regionsOfOne(region), {
80
+ warm: (doc, [r], hear) => warmRender({ render: regionRenderArgs(doc, r, opts), report: hear }),
81
+ read: (doc, [r]) => planPixelRender(regionRenderArgs(doc, r, opts))
82
+ }, report);
83
+ }
84
+ async function exportRegionPng(scene, region, opts) {
85
+ const reporter = exportReporter(opts);
86
+ const release = holdImageBitmaps();
87
+ try {
88
+ const plan = await capturePngRegion(scene, region, opts, reporter.report);
89
+ reporter.settle();
90
+ const session = createRasterSession();
91
+ try {
92
+ return await rasterToPng(session.renderPlan(plan));
93
+ } finally {
94
+ session.dispose();
95
+ }
96
+ } finally {
97
+ release();
98
+ }
99
+ }
100
+ var PNG_EXPORT = {
101
+ id: "png",
102
+ label: "PNG Image",
103
+ mimeType: "image/png",
104
+ extension: "png",
105
+ multiRegion: false,
106
+ options: ["scale"],
107
+ export: (scene, regions, opts) => exportRegionPng(scene, typeof regions === "function" ? (doc) => regions(doc)[0] : regions[0], {
108
+ scale: opts.scale ?? 1,
109
+ ...opts.background !== void 0 ? { background: opts.background } : {},
110
+ ...opts.onDiagnostic ? { onDiagnostic: opts.onDiagnostic } : {},
111
+ ...opts.strict !== void 0 ? { strict: opts.strict } : {}
112
+ })
113
+ };
114
+
115
+ // src/exportFormats.ts
116
+ var FORMATS = createReflectable({ name: "export formats" });
117
+ var builtInsRegistered = false;
118
+ function ensureBuiltIns() {
119
+ if (builtInsRegistered) return;
120
+ builtInsRegistered = true;
121
+ FORMATS.push(PNG_EXPORT.id, PNG_EXPORT, { source: "kit", fallback: true });
122
+ }
123
+ var exportFormatRegistry = {
124
+ name: FORMATS.name,
125
+ get: (id) => {
126
+ ensureBuiltIns();
127
+ return FORMATS.get(id);
128
+ },
129
+ has: (id) => {
130
+ ensureBuiltIns();
131
+ return FORMATS.has(id);
132
+ },
133
+ entries: () => {
134
+ ensureBuiltIns();
135
+ return FORMATS.entries();
136
+ },
137
+ subscribe: (listener) => {
138
+ ensureBuiltIns();
139
+ return FORMATS.subscribe(listener);
140
+ },
141
+ getVersion: () => {
142
+ ensureBuiltIns();
143
+ return FORMATS.getVersion();
144
+ }
145
+ };
146
+ function registerExportFormat(format, options) {
147
+ ensureBuiltIns();
148
+ return FORMATS.push(format.id, format, options);
149
+ }
150
+ var listed = null;
151
+ function exportFormats() {
152
+ const entries = exportFormatRegistry.entries();
153
+ if (listed?.from !== entries) listed = { from: entries, formats: Object.freeze(entries.map((e) => e.value)) };
154
+ return listed.formats;
155
+ }
156
+ function exportRegions(scene, regions, formatId, opts = {}) {
157
+ const format = exportFormatRegistry.get(formatId);
158
+ if (!format) {
159
+ const known = exportFormats().map((f) => f.id).join(", ");
160
+ return Promise.reject(new Error(`exportRegions: no export format "${formatId}" is registered (registered: ${known})`));
161
+ }
162
+ warnUnreadOptions(format, opts);
163
+ try {
164
+ if (typeof regions !== "function") return Promise.resolve(format.export(scene, checkCount(format, regions), opts));
165
+ return Promise.resolve(format.export(scene, (doc) => checkCount(format, regions(doc)), opts));
166
+ } catch (err) {
167
+ return Promise.reject(err);
168
+ }
169
+ }
170
+ var SHARED_OPTIONS = ["background", "onDiagnostic", "strict"];
171
+ var warnedOptions = /* @__PURE__ */ new Set();
172
+ function warnUnreadOptions(format, opts) {
173
+ if (!format.options || !isDev()) return;
174
+ const reads = /* @__PURE__ */ new Set([...SHARED_OPTIONS, ...format.options]);
175
+ for (const key of Object.keys(opts)) {
176
+ if (opts[key] === void 0 || reads.has(key) || warnedOptions.has(`${format.id}\0${key}`)) continue;
177
+ warnedOptions.add(`${format.id}\0${key}`);
178
+ console.warn(
179
+ `exportRegions: the "${format.id}" format does not read the option "${key}", so it is ignored (it reads: ${[...reads].join(", ")}). Check the spelling, or whether another format takes it.`
180
+ );
181
+ }
182
+ }
183
+ function pickExportOptions(format, opts) {
184
+ const out = {};
185
+ for (const key of [...SHARED_OPTIONS, ...format.options ?? []]) {
186
+ if (opts[key] !== void 0) out[key] = opts[key];
187
+ }
188
+ return out;
189
+ }
190
+ function checkCount(format, regions) {
191
+ if (regions.length === 0) throw new Error(`exportRegions: "${format.id}" was handed no regions`);
192
+ if (!format.multiRegion && regions.length > 1) {
193
+ throw new Error(`exportRegions: "${format.id}" writes one region to a file and was handed ${regions.length}; export them one at a time`);
194
+ }
195
+ return regions;
196
+ }
197
+ function pageRegion(page) {
198
+ return { x: page.x, y: page.y, width: page.width, height: page.height, name: pageName(page, page.index) };
199
+ }
200
+ function pageRegionsSource(pages) {
201
+ const ids = pages.map((p) => p.id);
202
+ return (doc) => {
203
+ const placed = new Map(placedPagesOf(doc).map((p) => [p.id, p]));
204
+ return ids.map((id) => {
205
+ const page = placed.get(id);
206
+ if (page === void 0) throw new Error(`exportPages: the document holds no page "${id}"`);
207
+ return pageRegion(page);
208
+ });
209
+ };
210
+ }
211
+ function pageRegionSource(page) {
212
+ const read = pageRegionsSource([page]);
213
+ return (doc) => read(doc)[0];
214
+ }
215
+ function exportPages(scene, pages, formatId, opts = {}) {
216
+ return exportRegions(scene, pageRegionsSource(pages), formatId, opts);
217
+ }
218
+ function selectionRegion(scene, ids, opts) {
219
+ const { name, scale } = typeof opts === "string" ? { name: opts, scale: void 0 } : opts ?? {};
220
+ const doc = documentOf(scene);
221
+ const world = worldPoseLookup(scenePoseAdapter(doc), doc.composition.compose);
222
+ const drawn = drawnBoundsScene(doc);
223
+ const boxOf = (id) => {
224
+ const pose = world(id);
225
+ return pose === null ? null : drawnAabbOf(drawn, id, pose, {
226
+ worldPoseOf: (m) => world(m),
227
+ ...scale !== void 0 ? { scale } : {}
228
+ });
229
+ };
230
+ const box = unionAabb(shownIds(doc, withoutPageStructure(doc, ids)).map(boxOf));
231
+ return box === null ? null : { x: box.x, y: box.y, width: box.width, height: box.height, ...name !== void 0 ? { name } : {} };
232
+ }
233
+ function shownIds(doc, ids) {
234
+ const flags = nodeGates({ get: (id) => doc.get(id) });
235
+ const gates = nodeGates(doc);
236
+ const annotations = annotationLayerIds(doc.layers);
237
+ const shown = (id) => {
238
+ const node = doc.get(id);
239
+ if (node === void 0 || flags.hidden(node)) return [];
240
+ return gates.hidden(node) || annotations.has(node.layer) ? doc.childrenOf(id).flatMap(shown) : [id];
241
+ };
242
+ return ids.flatMap((id) => shown(id));
243
+ }
244
+ function selectionRegionSource(ids, opts) {
245
+ const held = [...ids];
246
+ return (doc) => {
247
+ const region = selectionRegion(doc, held, opts);
248
+ if (region === null) throw new Error(`exportRegions: the selection (${held.join(", ")}) draws nothing in the document exported`);
249
+ return region;
250
+ };
251
+ }
252
+ function selectionRegionsSource(ids, opts) {
253
+ const read = selectionRegionSource(ids, opts);
254
+ return (doc) => [read(doc)];
255
+ }
256
+
257
+ export { EXPORT_CAPTURE_ATTEMPTS, ExportIncompleteError, ExportRevisionError, captureExport, exportBackgroundOf, exportFormatRegistry, exportFormats, exportPages, exportRegionPng, exportRegions, exportRegionsOf, exportReporter, pageRegion, pageRegionSource, pageRegionsSource, pickExportOptions, regionRenderArgs, regionsOfOne, registerExportFormat, selectionRegion, selectionRegionSource, selectionRegionsSource };
258
+ //# sourceMappingURL=index.js.map
259
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/captureExport.ts","../src/exportDiagnostics.ts","../src/exportTypes.ts","../src/regionRenderArgs.ts","../src/regionPng.ts","../src/exportFormats.ts","../src/exportPages.ts","../src/selectionRegion.ts"],"names":["documentOf"],"mappings":";;;;;AAQO,IAAM,uBAAA,GAA0B;AAGhC,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,YAAqB,QAAA,EAAkB;AACrC,IAAA,KAAA,CAAM,CAAA,oEAAA,EAAuE,QAAQ,CAAA,mCAAA,CAAqC,CAAA;AADvG,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAAA,EAErB;AAAA,EAFqB,QAAA;AAGvB;AAYO,IAAM,YAAA,GAAe,CAAC,MAAA,KAC3B,OAAO,WAAW,UAAA,GAAa,CAAC,GAAA,KAAQ,CAAC,MAAA,CAAO,GAAG,CAAC,CAAA,GAAI,CAAC,MAAM;AAG1D,SAAS,eAAA,CAAgB,SAAwB,GAAA,EAA2C;AACjG,EAAA,MAAM,OAAO,OAAO,OAAA,KAAY,UAAA,GAAa,OAAA,CAAQ,GAAG,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A,wCAAA,CAA0C,CAAA;AAC/H,IAAA,OAAO,MAAA;AAAA,EACT,CAAA;AACF;AAGO,SAAS,sBAAA,CAAuB,KAAwB,IAAA,EAA8E;AAC3I,EAAA,MAAM,IAAA,GAAO,qBAAA,CAAsB,GAAA,EAAK,IAAI,CAAA;AAC5C,EAAA,OAAO,CAAC,GAAA,KAAQ,CAAC,IAAA,CAAK,GAAG,CAAC,CAAA;AAC5B","file":"index.js","sourcesContent":["/**\n * The one boundary every export reads the document at: what it draws comes\n * from a single revision, with what that revision needs loaded.\n */\nimport { documentOf, type RenderDiagnostic, type RenderDiagnosticSink } from '@weasel-js/core';\nimport type { ExportRegion, ExportRegionSource, ExportRegions, ExportScene } from './exportTypes';\n\n/** How many times an export reads the document before giving up on it holding still. */\nexport const EXPORT_CAPTURE_ATTEMPTS = 3;\n\n/** An export gave up: the document changed while each of its attempts loaded what it draws. */\nexport class ExportRevisionError extends Error {\n constructor(readonly attempts: number) {\n super(`export: the document changed while the export loaded what it draws, ${attempts} times running; nothing was written`);\n }\n}\n\n/** The two halves of an export's read of the document, as {@link captureExport} runs them. Each\n * reports what the export will draw without to `report`. */\nexport interface ExportCaptureSteps<T> {\n /** Load what drawing `regions` of `doc` needs: fonts, paint kinds, pictures. */\n warm(doc: ExportScene, regions: readonly ExportRegion[], report: RenderDiagnosticSink): Promise<void>;\n /** Read everything the file is written from, synchronously, into values the document cannot change. */\n read(doc: ExportScene, regions: readonly ExportRegion[], report: RenderDiagnosticSink): T;\n}\n\n/** One region source as the {@link ExportRegions} {@link captureExport} takes. */\nexport const regionsOfOne = (region: ExportRegionSource): ExportRegions =>\n typeof region === 'function' ? (doc) => [region(doc)] : [region];\n\n/** `regions` as of `doc`: each a copy, so a caller's later edit to one reaches no export in flight. */\nexport function exportRegionsOf(regions: ExportRegions, doc: ExportScene): readonly ExportRegion[] {\n const list = typeof regions === 'function' ? regions(doc) : regions;\n return Object.freeze(list.map((r) => Object.freeze({ ...r })));\n}\n\n/**\n * Read `regions` of `scene`'s document through `steps`, from one content\n * revision (`getContentVersion`): warm, then, if no content changed while it\n * loaded, read at once, in the same task. Fixed regions are copied when it is\n * called. A change restarts it, with the\n * regions read again when they are a function of the document, so the bounds\n * and the content come from the same revision. After\n * {@link EXPORT_CAPTURE_ATTEMPTS} attempts it rejects with\n * {@link ExportRevisionError}.\n *\n * What a gesture or an open edit shows is never read, and a change of\n * selection restarts nothing. The painters, paint kinds and fonts registered\n * when `read` runs are the ones it draws with. What the steps report reaches\n * `report` only from the attempt that is read, once it has been.\n */\nexport async function captureExport<T>(\n scene: ExportScene, regions: ExportRegions, steps: ExportCaptureSteps<T>, report: RenderDiagnosticSink = () => {},\n): Promise<T> {\n const doc = documentOf(scene);\n const source = typeof regions === 'function' ? regions : exportRegionsOf(regions, doc);\n for (let attempt = 1; ; attempt++) {\n const revision = scene.getContentVersion();\n const heard: RenderDiagnostic[] = [];\n const hear = (d: RenderDiagnostic) => { heard.push(d); };\n await steps.warm(doc, exportRegionsOf(source, doc), hear);\n if (scene.getContentVersion() === revision) {\n const read = steps.read(doc, exportRegionsOf(source, doc), hear);\n heard.forEach(report);\n return read;\n }\n if (attempt >= EXPORT_CAPTURE_ATTEMPTS) throw new ExportRevisionError(attempt);\n }\n}\n","/** How every export reports what it could not draw, and when it refuses to write a file without it. */\nimport type { RenderDiagnostic, RenderDiagnosticSink } from '@weasel-js/core';\nimport type { ExportOptions } from './exportTypes';\n\n/** One thing an export drew without, or drew in part: a `RenderDiagnostic`. */\nexport type ExportDiagnostic = RenderDiagnostic;\n\n/** A strict export (`strict: true`) found something it could not draw, and wrote nothing. */\nexport class ExportIncompleteError extends Error {\n constructor(readonly diagnostics: readonly ExportDiagnostic[]) {\n super(`export: ${diagnostics.length === 1 ? 'one thing' : `${diagnostics.length} things`} could not be drawn, and a strict export writes nothing without them: ${\n diagnostics.map((d) => d.message).join('; ')}`);\n }\n}\n\n/** One export's diagnostics: `report` hears each, `settle` ends the export's reporting. */\nexport interface ExportReporter {\n readonly report: RenderDiagnosticSink;\n /** Throws {@link ExportIncompleteError} for a strict export that reported anything. */\n settle(): void;\n}\n\n/**\n * The reporter an export with `opts` reports through. Each diagnostic reaches\n * `onDiagnostic` once, however often it is found. Best-effort, the default,\n * writes the file without what it reports; `strict` writes none when it\n * reports anything, and `settle` throws instead.\n */\nexport function exportReporter(opts: Pick<ExportOptions, 'onDiagnostic' | 'strict'>): ExportReporter {\n const seen = new Map<string, ExportDiagnostic>();\n return {\n report(d) {\n const key = `${d.kind}\\u0000${d.subject}\\u0000${d.message}`;\n if (seen.has(key)) return;\n seen.set(key, d);\n opts.onDiagnostic?.(d);\n },\n settle() {\n if (opts.strict && seen.size > 0) throw new ExportIncompleteError([...seen.values()]);\n },\n };\n}\n","/** The types the export registry and its formats share. */\nimport type { Rect } from '@weasel-js/geom';\nimport type { RectPose, RenderDiagnostic, Scene } from '@weasel-js/core';\n\n/**\n * A rectangle of the document to export: a page (`exportPages` makes one of\n * each `PlacedPage`), the world rect a view spans (`viewportWorldRect`), a\n * selection's bounds, or any other. Every format draws each layer in it at its\n * document pose: a parallax layer's camera tracking is not applied. `name` is\n * what a format that labels its pages or documents calls it: a PDF page's\n * label, an SVG's `<title>`.\n */\nexport interface ExportRegion extends Rect {\n readonly name?: string;\n}\n\n/**\n * The regions an export writes: fixed rects, or a function reading them from\n * the document. A function is called each time the export reads the document,\n * so bounds that come from it, a page's or a selection's, belong to the same\n * revision as what is drawn in them.\n */\nexport type ExportRegions = readonly ExportRegion[] | ((doc: ExportScene) => readonly ExportRegion[]);\n\n/** One region an export writes, fixed or read from the document, as {@link ExportRegions} holds them. */\nexport type ExportRegionSource = ExportRegion | ((doc: ExportScene) => ExportRegion);\n\n/** A scene as the exports read it: world-space `RectPose`s. */\nexport type ExportScene = Scene<unknown, string, RectPose>;\n\n/** The color painted under a region: a color, `null` for none, or a function reading it from the\n * document the export draws, so a color that comes from it belongs to the revision drawn. */\nexport type ExportBackground = string | null | ((doc: ExportScene) => string | null);\n\n/** `background` as of `doc`. */\nexport const exportBackgroundOf = (background: ExportBackground | undefined, doc: ExportScene): string | null =>\n typeof background === 'function' ? background(doc) : background ?? null;\n\n/** What every format takes. */\nexport interface ExportOptions {\n /** The color painted under each region, or a function reading it from the document the export draws.\n * Default none: core holds no page color. */\n background?: ExportBackground;\n /** Hears each thing the export could not draw or load, once: a picture or face\n * that failed, a paint kind or shader nothing can draw, what the format cannot hold. */\n onDiagnostic?: (diagnostic: RenderDiagnostic) => void;\n /** Write nothing when anything is diagnosed, and reject with `ExportIncompleteError`.\n * Default `false`: best-effort, the file is written without it. */\n strict?: boolean;\n}\n\n/**\n * One way of writing regions of a scene to a file, registered with\n * `registerExportFormat`. `TOptions` is what the format reads beyond\n * {@link ExportOptions}. `exportRegions` hands a format whatever its caller\n * passed, so a format treats every option of its own as optional there.\n */\nexport interface ExportFormat<TOptions extends ExportOptions = ExportOptions> {\n /** The id `exportRegions` names it by: `'png'`, `'svg'`, `'pdf'`. */\n readonly id: string;\n /** What a menu calls it: \"PNG Image\". */\n readonly label: string;\n readonly mimeType: string;\n /** The file extension, without the dot. */\n readonly extension: string;\n /** Whether one file holds several regions, as a PDF's pages do. A single-region format takes exactly one. */\n readonly multiRegion: boolean;\n /**\n * The option keys it reads beyond {@link ExportOptions}. `exportRegions` warns in development about a\n * key passed to this format that neither lists, and {@link pickExportOptions} picks these. Left out,\n * nothing is checked.\n */\n readonly options?: readonly Exclude<keyof TOptions, keyof ExportOptions>[];\n export(scene: ExportScene, regions: ExportRegions, opts: TOptions): Promise<Blob>;\n}\n","import { documentOf, type RectPose, type RenderSceneToPixelsArgs } from '@weasel-js/core';\nimport { exportBackgroundOf, type ExportBackground, type ExportRegion, type ExportScene } from './exportTypes';\n\n/** What {@link regionRenderArgs} answers: the part of `renderSceneToPixels`'s arguments a region decides. */\nexport type RegionRenderArgs = Pick<RenderSceneToPixelsArgs<unknown, string, RectPose>, 'scene' | 'sourceRect' | 'scale' | 'background'>;\n\n/** Options for {@link regionRenderArgs}. */\nexport interface RegionRenderArgsOptions {\n /** Output pixels per world unit. */\n scale: number;\n /** The color painted under the region, or a function reading it from the document drawn. Default none: transparent. */\n background?: ExportBackground;\n}\n\n/**\n * The arguments `region` of `scene` renders with: the scene's document (not\n * what an open gesture or edit is showing), the region as the source rect, and\n * `scale` on both axes. The PNG and PDF exports draw through these.\n *\n * Outside a browser, hand them to `@weasel-js/headless`'s raster host, whose\n * `NodeRenderArgs` they satisfy as they are, to render a page or any other\n * region from Node.\n */\nexport function regionRenderArgs(scene: ExportScene, region: ExportRegion, opts: RegionRenderArgsOptions): RegionRenderArgs {\n const doc = documentOf(scene);\n const background = exportBackgroundOf(opts.background, doc);\n return {\n scene: doc,\n sourceRect: { x: region.x, y: region.y, width: region.width, height: region.height },\n scale: { x: opts.scale, y: opts.scale },\n ...(background !== null ? { background } : {}),\n };\n}\n","import { holdImageBitmaps } from '@weasel-js/renderer';\nimport { createRasterSession, planPixelRender, rasterToPng, warmRender, type PixelRenderPlan, type RenderDiagnosticSink } from '@weasel-js/core';\nimport { captureExport, regionsOfOne } from './captureExport';\nimport { exportReporter } from './exportDiagnostics';\nimport type { ExportBackground, ExportFormat, ExportOptions, ExportRegionSource, ExportScene } from './exportTypes';\nimport { regionRenderArgs } from './regionRenderArgs';\n\n/** Options for {@link exportRegionPng}. */\nexport interface ExportRegionPngOptions extends Pick<ExportOptions, 'onDiagnostic' | 'strict'> {\n /** Output pixels per world unit: 2 makes an image twice the region's size. */\n scale: number;\n /** The color painted under the region, or a function reading it from the document drawn. Default none: the\n * image is transparent where nothing is drawn. */\n background?: ExportBackground;\n}\n\n/** The plan a PNG of `region` draws, read through `captureExport` from one revision of the document, its faces,\n * kinds and pictures loaded, and what it draws without told to `report`. */\nexport function capturePngRegion(\n scene: ExportScene, region: ExportRegionSource, opts: ExportRegionPngOptions, report?: RenderDiagnosticSink,\n): Promise<PixelRenderPlan> {\n return captureExport(scene, regionsOfOne(region), {\n warm: (doc, [r], hear) => warmRender({ render: regionRenderArgs(doc, r!, opts), report: hear }),\n read: (doc, [r]) => planPixelRender(regionRenderArgs(doc, r!, opts)),\n }, report);\n}\n\n/**\n * Draw `region` of `scene` into a PNG, `region × scale` pixels, through the\n * renderer the canvas draws with, so it shows what the canvas shows, cut to\n * the region's edges. It draws the document: a gesture or edit in flight is\n * not shown. Annotation layers are left out.\n *\n * The caller has registered whatever the scene needs painting with, as it\n * must to draw it at all: its painters (`registerNodeShape`) and its fonts.\n * Paint kinds and faces that load on demand are waited for, and the image is\n * of one revision of the document: see `captureExport`. What it draws\n * without goes to `onDiagnostic`, and a `strict` export rejects with\n * `ExportIncompleteError` rather than write it. Needs WebGL2.\n */\nexport async function exportRegionPng(scene: ExportScene, region: ExportRegionSource, opts: ExportRegionPngOptions): Promise<Blob> {\n const reporter = exportReporter(opts);\n // The plan's pictures stay open until it is drawn.\n const release = holdImageBitmaps();\n try {\n const plan = await capturePngRegion(scene, region, opts, reporter.report);\n reporter.settle();\n const session = createRasterSession();\n try {\n return await rasterToPng(session.renderPlan(plan));\n } finally {\n session.dispose();\n }\n } finally {\n release();\n }\n}\n\n/** The `png` format's own option. */\nexport interface PngExportOptions extends ExportOptions {\n /** Output pixels per world unit. Default 1. */\n scale?: number;\n}\n\n/** The built-in `png` format: one region as a PNG image, through {@link exportRegionPng}. */\nexport const PNG_EXPORT: ExportFormat<PngExportOptions> = {\n id: 'png',\n label: 'PNG Image',\n mimeType: 'image/png',\n extension: 'png',\n multiRegion: false,\n options: ['scale'],\n export: (scene, regions, opts) => exportRegionPng(scene, typeof regions === 'function' ? (doc) => regions(doc)[0]! : regions[0]!, {\n scale: opts.scale ?? 1,\n ...(opts.background !== undefined ? { background: opts.background } : {}),\n ...(opts.onDiagnostic ? { onDiagnostic: opts.onDiagnostic } : {}),\n ...(opts.strict !== undefined ? { strict: opts.strict } : {}),\n }),\n};\n","/**\n * The export registry: the formats a scene's regions can be written in, each\n * registered by the package that can write it. This package registers `png`;\n * svg and pdf register theirs (`registerSvgExport`, `registerPdfExport`), so it\n * depends on neither.\n */\nimport { createReflectable, isDev, type PushOptions, type Reflection } from '@weasel-js/registry';\nimport type { ExportFormat, ExportOptions, ExportRegion, ExportRegions, ExportScene } from './exportTypes';\nimport { PNG_EXPORT } from './regionPng';\n\nconst FORMATS = createReflectable<ExportFormat>({ name: 'export formats' });\n\n// The built-ins go in on first use, not at module load: a bundler may drop an\n// import kept only for its side effect, and the registry would come up empty.\nlet builtInsRegistered = false;\nfunction ensureBuiltIns(): void {\n if (builtInsRegistered) return;\n builtInsRegistered = true;\n FORMATS.push(PNG_EXPORT.id, PNG_EXPORT as ExportFormat, { source: 'kit', fallback: true });\n}\n\n/** Every registered export format, keyed by id, with the overrides each displaced. */\nexport const exportFormatRegistry: Reflection<ExportFormat> = {\n name: FORMATS.name,\n get: (id) => { ensureBuiltIns(); return FORMATS.get(id); },\n has: (id) => { ensureBuiltIns(); return FORMATS.has(id); },\n entries: () => { ensureBuiltIns(); return FORMATS.entries(); },\n subscribe: (listener) => { ensureBuiltIns(); return FORMATS.subscribe(listener); },\n getVersion: () => { ensureBuiltIns(); return FORMATS.getVersion(); },\n};\n\n/**\n * Register an export format. Returns a disposer that removes this\n * registration. Registering an id already held overrides it, `png` included;\n * disposing uncovers what it displaced. `fallback` marks an engine default,\n * which a later registration replaces without the development clash warning.\n */\nexport function registerExportFormat<TOptions extends ExportOptions>(\n format: ExportFormat<TOptions>,\n options?: Pick<PushOptions, 'fallback'>,\n): () => void {\n ensureBuiltIns();\n return FORMATS.push(format.id, format as ExportFormat, options);\n}\n\nlet listed: { from: readonly unknown[]; formats: readonly ExportFormat[] } | null = null;\n\n/** Every registered format, `png` first, then in registration order. The same array until the registry changes. */\nexport function exportFormats(): readonly ExportFormat[] {\n const entries = exportFormatRegistry.entries();\n if (listed?.from !== entries) listed = { from: entries, formats: Object.freeze(entries.map((e) => e.value)) };\n return listed.formats;\n}\n\n/**\n * Write `regions` of `scene` in the format registered as `formatId`. Rejects\n * for an id nothing registered, for more or fewer than one region handed to a\n * format that is not `multiRegion` (a multi-region format takes one or more),\n * and with whatever the format throws, synchronously or not. Regions given as\n * a function of the document are counted each time the export reads them.\n */\nexport function exportRegions(\n scene: ExportScene,\n regions: ExportRegions,\n formatId: string,\n opts: ExportOptions & Readonly<Record<string, unknown>> = {},\n): Promise<Blob> {\n const format = exportFormatRegistry.get(formatId);\n if (!format) {\n const known = exportFormats().map((f) => f.id).join(', ');\n return Promise.reject(new Error(`exportRegions: no export format \"${formatId}\" is registered (registered: ${known})`));\n }\n warnUnreadOptions(format, opts);\n // Every failure rejects, a format's own synchronous throw included, so a caller has one channel to hear it on.\n try {\n if (typeof regions !== 'function') return Promise.resolve(format.export(scene, checkCount(format, regions), opts));\n return Promise.resolve(format.export(scene, (doc) => checkCount(format, regions(doc)), opts));\n } catch (err) {\n return Promise.reject(err);\n }\n}\n\n/** The keys every format reads, {@link ExportOptions}'s. */\nconst SHARED_OPTIONS: readonly (keyof ExportOptions)[] = ['background', 'onDiagnostic', 'strict'];\n\nconst warnedOptions = new Set<string>();\n\nfunction warnUnreadOptions(format: ExportFormat, opts: Readonly<Record<string, unknown>>): void {\n if (!format.options || !isDev()) return;\n const reads = new Set<string>([...SHARED_OPTIONS, ...format.options]);\n for (const key of Object.keys(opts)) {\n if (opts[key] === undefined || reads.has(key) || warnedOptions.has(`${format.id}\\0${key}`)) continue;\n warnedOptions.add(`${format.id}\\0${key}`);\n console.warn(\n `exportRegions: the \"${format.id}\" format does not read the option \"${key}\", so it is ignored ` +\n `(it reads: ${[...reads].join(', ')}). Check the spelling, or whether another format takes it.`,\n );\n }\n}\n\n/** The options `format` reads out of `opts`, the shared ones and those it declares, leaving out any undefined. */\nexport function pickExportOptions<TOptions extends ExportOptions>(\n format: ExportFormat<TOptions>, opts: TOptions,\n): Partial<TOptions> {\n const out: Partial<TOptions> = {};\n for (const key of [...SHARED_OPTIONS, ...(format.options ?? [])] as (keyof TOptions)[]) {\n if (opts[key] !== undefined) out[key] = opts[key];\n }\n return out;\n}\n\nfunction checkCount(format: ExportFormat, regions: readonly ExportRegion[]): readonly ExportRegion[] {\n if (regions.length === 0) throw new Error(`exportRegions: \"${format.id}\" was handed no regions`);\n if (!format.multiRegion && regions.length > 1) {\n throw new Error(`exportRegions: \"${format.id}\" writes one region to a file and was handed ${regions.length}; export them one at a time`);\n }\n return regions;\n}\n\n/** Drop every registration and the built-ins, so the next use registers them again. */\nexport function _resetExportFormatsForTests(): void {\n FORMATS.clear();\n builtInsRegistered = false;\n listed = null;\n warnedOptions.clear();\n}\n","import { pageName, placedPagesOf, type PlacedPage } from '@weasel-js/core';\nimport { exportRegions } from './exportFormats';\nimport type { ExportOptions, ExportRegion, ExportScene } from './exportTypes';\n\n/** `page` as an export region, named as the page order shows it. */\nexport function pageRegion(page: PlacedPage): ExportRegion {\n return { x: page.x, y: page.y, width: page.width, height: page.height, name: pageName(page, page.index) };\n}\n\n/**\n * `pages` as regions read from the document an export draws: each page placed\n * as that document places it, found by its id, and named for it. A page the\n * document no longer holds fails the export.\n */\nexport function pageRegionsSource(pages: readonly PlacedPage[]): (doc: ExportScene) => readonly ExportRegion[] {\n const ids = pages.map((p) => p.id);\n return (doc) => {\n const placed = new Map(placedPagesOf(doc).map((p) => [p.id, p]));\n return ids.map((id) => {\n const page = placed.get(id);\n if (page === undefined) throw new Error(`exportPages: the document holds no page \"${id}\"`);\n return pageRegion(page);\n });\n };\n}\n\n/** One page as {@link pageRegionsSource} reads it: the region source of a single-region export. */\nexport function pageRegionSource(page: PlacedPage): (doc: ExportScene) => ExportRegion {\n const read = pageRegionsSource([page]);\n return (doc) => read(doc)[0]!;\n}\n\n/**\n * Write `pages` of `scene` in the format registered as `formatId`, each page\n * a region named for the page: `exportRegions` over {@link pageRegionsSource}. A\n * single-region format takes one page.\n */\nexport function exportPages(\n scene: ExportScene,\n pages: readonly PlacedPage[],\n formatId: string,\n opts: ExportOptions & Readonly<Record<string, unknown>> = {},\n): Promise<Blob> {\n return exportRegions(scene, pageRegionsSource(pages), formatId, opts);\n}\n","import {\n annotationLayerIds, documentOf, drawnAabbOf, drawnBoundsScene, nodeGates, scenePoseAdapter, unionAabb,\n withoutPageStructure, worldPoseLookup, type NodeId,\n} from '@weasel-js/core';\nimport type { ExportRegion, ExportScene } from './exportTypes';\n\n/** Options for {@link selectionRegion} and its sources. */\nexport interface SelectionRegionOptions {\n /** What the region is called: a PDF page's label, an SVG's `<title>`. */\n name?: string;\n /** The output pixels per world unit the export draws at, which a screen-pixel (`{ px }`) stroke is\n * measured at. Default 1. Pass the export's `scale` so such a stroke is not cut at its edge. */\n scale?: number;\n}\n\n/**\n * The world box `ids` cover as the document draws them, strokes included:\n * the region that exports a selection. Pages and the page run are left out of\n * `ids`, and so is what no export draws: a hidden node, and a node on a\n * hidden or annotation layer (what its children draw still counts). `null`\n * when none of them draws anything. A string third argument is the name.\n */\nexport function selectionRegion(\n scene: ExportScene, ids: readonly string[], opts?: string | SelectionRegionOptions,\n): ExportRegion | null {\n const { name, scale } = typeof opts === 'string' ? { name: opts, scale: undefined } : opts ?? {};\n const doc = documentOf(scene);\n const world = worldPoseLookup(scenePoseAdapter(doc), doc.composition.compose as (p: unknown, c: unknown) => unknown);\n const drawn = drawnBoundsScene(doc);\n const boxOf = (id: NodeId) => {\n const pose = world(id);\n return pose === null ? null : drawnAabbOf(drawn, id, pose, {\n worldPoseOf: (m) => world(m),\n ...(scale !== undefined ? { scale } : {}),\n });\n };\n const box = unionAabb(shownIds(doc, withoutPageStructure(doc, ids)).map(boxOf));\n return box === null ? null : { x: box.x, y: box.y, width: box.width, height: box.height, ...(name !== undefined ? { name } : {}) };\n}\n\n/** `ids` as an export draws them: a hidden node and its subtree dropped, and a node on a hidden or\n * annotation layer replaced by its children, as the render walk paints them. */\nfunction shownIds(doc: ExportScene, ids: readonly string[]): NodeId[] {\n const flags = nodeGates({ get: (id) => doc.get(id) });\n const gates = nodeGates(doc);\n const annotations = annotationLayerIds(doc.layers);\n const shown = (id: NodeId): NodeId[] => {\n const node = doc.get(id);\n if (node === undefined || flags.hidden(node)) return [];\n return gates.hidden(node) || annotations.has(node.layer) ? doc.childrenOf(id).flatMap(shown) : [id];\n };\n return ids.flatMap((id) => shown(id as NodeId));\n}\n\n/**\n * `ids`' region read from the document an export draws, so the bounds belong to\n * the revision drawn in them: the region source of a single-region export. A\n * selection that draws nothing in that document fails the export.\n */\nexport function selectionRegionSource(ids: readonly string[], opts?: SelectionRegionOptions): (doc: ExportScene) => ExportRegion {\n const held = [...ids];\n return (doc) => {\n const region = selectionRegion(doc, held, opts);\n if (region === null) throw new Error(`exportRegions: the selection (${held.join(', ')}) draws nothing in the document exported`);\n return region;\n };\n}\n\n/** {@link selectionRegionSource} as the regions `exportRegions` takes. */\nexport function selectionRegionsSource(ids: readonly string[], opts?: SelectionRegionOptions): (doc: ExportScene) => readonly ExportRegion[] {\n const read = selectionRegionSource(ids, opts);\n return (doc) => [read(doc)];\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@weasel-js/export",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.0.0",
4
+ "description": "Exports regions of a @weasel-js/core scene: a page, a selection or any rect, as PNG or any format another package registers (SVG, PDF), with a diagnostics report and a retry when the scene changes mid-export.",
5
+ "weasel": {
6
+ "tier": "plugin"
7
+ },
8
+ "license": "MIT",
9
+ "type": "module",
10
+ "sideEffects": false,
11
+ "main": "./dist/index.js",
12
+ "module": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ },
19
+ "./package.json": "./package.json"
20
+ },
21
+ "author": "orochi235",
22
+ "homepage": "https://orochi235.github.io/weasel/",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/orochi235/weasel.git",
26
+ "directory": "packages/export"
27
+ },
28
+ "bugs": {
29
+ "url": "https://github.com/orochi235/weasel/issues"
30
+ },
31
+ "engines": {
32
+ "node": ">=24"
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "README.md",
37
+ "LICENSE"
38
+ ],
39
+ "scripts": {
40
+ "build": "tsup",
41
+ "test": "node ../../scripts/package-test.mjs"
42
+ },
43
+ "dependencies": {
44
+ "@weasel-js/geom": "2.0.0",
45
+ "@weasel-js/registry": "2.0.0",
46
+ "@weasel-js/renderer": "2.0.0"
47
+ },
48
+ "peerDependencies": {
49
+ "@weasel-js/core": "2.0.0"
50
+ },
51
+ "devDependencies": {
52
+ "@weasel-js/paint": "2.0.0"
53
+ },
54
+ "publishConfig": {
55
+ "access": "public",
56
+ "provenance": true
57
+ }
58
+ }