hephaestus-wasm 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/hephaestus.js ADDED
@@ -0,0 +1,719 @@
1
+ // Page-facing API for the hephaestus render client.
2
+ //
3
+ // The wasm module is deliberately imperative — render, resize, setDark — and
4
+ // everything browser-shaped lives here: ResizeObserver, matchMedia,
5
+ // requestAnimationFrame, fetch. JavaScript costs a page nothing to download
6
+ // twice over; wasm bytes are the thing worth being careful with.
7
+
8
+ import init, {
9
+ PlotHandle,
10
+ documentFormatVersion,
11
+ hasFonts,
12
+ isSupported,
13
+ registerFont,
14
+ setGenericFamily,
15
+ } from './hephaestus_wasm.js';
16
+
17
+ export {
18
+ init as default,
19
+ documentFormatVersion,
20
+ hasFonts,
21
+ isSupported,
22
+ registerFont,
23
+ setGenericFamily,
24
+ };
25
+
26
+ // Fonts are registered into a process-global context that lives as long as
27
+ // the module, so registering the same file twice is waste rather than an
28
+ // error. Tracking what has been asked for lets several plots on one page
29
+ // each request the font they need without refetching.
30
+ const registered = new Set();
31
+
32
+ /**
33
+ * Fetch a font file and register it.
34
+ *
35
+ * Accepts TTF, OTF, TTC, OTC, WOFF and WOFF2 — the container formats are
36
+ * unwrapped to the sfnt inside on the wasm side, so a URL from a font CDN
37
+ * works as-is.
38
+ *
39
+ * **A variable font is the best thing to point this at.** The shaper applies
40
+ * the `wght` axis, so one file serves every weight — including interpolated
41
+ * ones a static set cannot reach — which means one call rather than one per
42
+ * weight, and no per-face subset to choose. Italic is still a second file,
43
+ * since it is a separate axis-space in practice.
44
+ *
45
+ * @param {string} url
46
+ * @param {{ genericFor?: string, key?: string }} [opts] `genericFor` also
47
+ * points that generic family at whatever families the file turned out to
48
+ * contain — which a theme asking for `sans-serif` needs, and which is why
49
+ * the family name comes back from `registerFont` rather than being guessed
50
+ * here. `key` overrides the dedupe key, normally the URL.
51
+ * @returns {Promise<string[]>} family names registered, or `[]` if this URL
52
+ * was already registered.
53
+ */
54
+ export async function registerFontFromUrl(url, opts = {}) {
55
+ const key = opts.key ?? url;
56
+ if (registered.has(key)) return [];
57
+
58
+ const response = await fetch(url);
59
+ if (!response.ok) {
60
+ throw new Error(`font fetch failed: ${response.status} ${response.statusText} for ${url}`);
61
+ }
62
+ const families = registerFont(new Uint8Array(await response.arrayBuffer()));
63
+ registered.add(key);
64
+ if (opts.genericFor) setGenericFamily(opts.genericFor, families);
65
+ return families;
66
+ }
67
+
68
+ /**
69
+ * Register a Google Fonts family. No API key needed.
70
+ *
71
+ * Uses the keyless CSS2 endpoint, which is possible because WOFF2 is decoded
72
+ * (the `webfonts` feature). CORS allows the `fetch`, and the response is
73
+ * WOFF2 whatever a page does — `User-Agent` is a forbidden header, so the
74
+ * TTF the native `google-fonts` cargo feature relies on is unreachable here.
75
+ *
76
+ * **Exactly one file is registered per weight/style, by design.** Google
77
+ * splits every face into per-script subset files sharing one family name, and
78
+ * the shaper selects within a family by weight and style with no notion of CSS
79
+ * `unicode-range` — so registering several subsets lets one without basic
80
+ * Latin win and turns every label into tofu. `subset` picks which to take.
81
+ * That cap is also why the bundled default font is a single file per face
82
+ * covering five scripts: see {@link registerDefaultFonts}.
83
+ *
84
+ * @param {string} family e.g. `'Inter'`, `'Open Sans'`. Case-sensitive.
85
+ * There is no "all subsets" option, and none is possible: the CSS endpoints
86
+ * never serve a single full-coverage file. Asking for one weight returns seven
87
+ * `unicode-range`-split files, and the legacy `&subset=` parameter no longer
88
+ * merges them. For coverage beyond one script, use a **variable** font through
89
+ * {@link registerFontFromUrl} — one file carries every weight, so it sidesteps
90
+ * both this and the one-file-per-face cap — or the bundled default, which is
91
+ * one file per face across five scripts.
92
+ *
93
+ * @param {{ weights?: number[], italics?: boolean, subset?: string,
94
+ * genericFor?: string }} [opts] `weights` defaults to `[400, 700]`
95
+ * and `italics` to `true`, which is what the theme and markdown chrome
96
+ * between them ask for. `subset` defaults to `'latin'`; it names one of the
97
+ * subsets the CSS response offers, and the error lists them if it misses.
98
+ * @returns {Promise<string[]>} family names registered.
99
+ */
100
+ export async function registerGoogleFont(family, opts = {}) {
101
+ const weights = opts.weights ?? [400, 700];
102
+ const italics = opts.italics !== false;
103
+ const subset = opts.subset ?? 'latin';
104
+
105
+ // ital,wght axis spec: 0 is upright, 1 italic, and the pairs must be sorted.
106
+ const specs = [];
107
+ for (const ital of italics ? [0, 1] : [0]) {
108
+ for (const w of [...weights].sort((a, b) => a - b)) specs.push(`${ital},${w}`);
109
+ }
110
+ const url = new URL('https://fonts.googleapis.com/css2');
111
+ url.searchParams.set('family', `${family}:ital,wght@${specs.join(';')}`);
112
+
113
+ const response = await fetch(url);
114
+ if (!response.ok) {
115
+ throw new Error(
116
+ `Google Fonts CSS2 failed: ${response.status} ${response.statusText} ` +
117
+ `for ${JSON.stringify(family)}`,
118
+ );
119
+ }
120
+ const css = await response.text();
121
+
122
+ // Each @font-face is preceded by a comment naming its subset.
123
+ const blocks = [...css.matchAll(/\/\*\s*([\w-]+)\s*\*\/\s*@font-face\s*\{([^}]*)\}/g)]
124
+ .map(([, name, body]) => ({
125
+ subset: name,
126
+ weight: (body.match(/font-weight:\s*(\d+)/) || [])[1],
127
+ style: (body.match(/font-style:\s*(\w+)/) || [])[1],
128
+ src: (body.match(/url\((https:[^)]+)\)/) || [])[1],
129
+ }))
130
+ .filter((b) => b.src);
131
+ if (!blocks.length) {
132
+ throw new Error(`no @font-face blocks for ${JSON.stringify(family)} — check the name`);
133
+ }
134
+
135
+ const wanted = blocks.filter((b) => b.subset === subset);
136
+ if (!wanted.length) {
137
+ const available = [...new Set(blocks.map((b) => b.subset))].join(', ');
138
+ throw new Error(
139
+ `${JSON.stringify(family)} has no ${JSON.stringify(subset)} subset; available: ${available}`,
140
+ );
141
+ }
142
+
143
+ const names = new Set();
144
+ for (const b of wanted) {
145
+ for (const n of await registerFontFromUrl(b.src, {
146
+ key: `google:${family}:${subset}:${b.style}:${b.weight}`,
147
+ })) {
148
+ names.add(n);
149
+ }
150
+ }
151
+ const out = [...names];
152
+ if (opts.genericFor && out.length) setGenericFamily(opts.genericFor, out);
153
+ return out;
154
+ }
155
+
156
+ /**
157
+ * The bundled faces, resolved against this module so a CDN copy finds its own.
158
+ *
159
+ * Four static instances rather than one variable font: `gvar` deltas survive
160
+ * charset subsetting, so a variable roman/italic pair at this coverage is
161
+ * about 1 MB against ~260 kB brotli for these four. The trade is that a theme
162
+ * asking for weight 500 snaps to 400 or 700 rather than interpolating; the
163
+ * built-in themes only use 400 and 700.
164
+ */
165
+ const DEFAULT_FACES = ['regular', 'bold', 'italic', 'bolditalic'].map(
166
+ (v) => new URL(`./fonts/roboto-${v}.ttf`, import.meta.url).href,
167
+ );
168
+
169
+ /** Family the bundled faces register under. */
170
+ const DEFAULT_FAMILY = 'Roboto';
171
+
172
+ /**
173
+ * Register the bundled default font — Roboto, four faces.
174
+ *
175
+ * Covers latin, latin-ext, Greek, Cyrillic and Vietnamese, in regular, bold,
176
+ * italic and bold-italic. All four matter: the theme sets a bold plot title,
177
+ * and the rich-text sheet maps weight and italic independently, so markdown
178
+ * chrome reaches every combination including nested `***emphasis***`. CJK is
179
+ * deliberately absent — a CJK face is megabytes, and stays a bring-your-own
180
+ * case.
181
+ *
182
+ * Fetched, not embedded in the wasm, so a page supplying its own font pays
183
+ * nothing. Also points `sans-serif` at the family, without which a theme
184
+ * naming the generic resolves to nothing.
185
+ *
186
+ * OFL-1.1; `fonts/OFL-Roboto.txt` ships alongside.
187
+ */
188
+ export async function registerDefaultFonts() {
189
+ const registered = await Promise.all(
190
+ DEFAULT_FACES.map((url) => registerFontFromUrl(url, { key: url })),
191
+ );
192
+ // After the faces, so the name the mapping points at exists.
193
+ setGenericFamily('sans-serif', [DEFAULT_FAMILY]);
194
+ return [...new Set(registered.flat())];
195
+ }
196
+
197
+ /**
198
+ * A plot document bound to a canvas, with resize and color-scheme handling.
199
+ *
200
+ * Frames are coalesced: every mutator marks the view dirty and schedules one
201
+ * animation frame, so a resize and a theme change in the same tick cost one
202
+ * render. `redraw()` forces one immediately.
203
+ */
204
+ export class PlotView {
205
+ /**
206
+ * @param {HTMLCanvasElement} canvas
207
+ * @param {Uint8Array|ArrayBuffer} doc bytes of a `.hplot` document.
208
+ * @param {{ colorScheme?: 'light'|'dark'|'auto', autoResize?: boolean,
209
+ * picking?: boolean, saveOnRightClick?: boolean|string }} [opts]
210
+ * `picking` allocates a second render target and reads it back after
211
+ * every frame, so leave it off unless `pickAt` is going to be called.
212
+ * `saveOnRightClick` gives the canvas an ordinary image's context menu.
213
+ * Pass a string to name the saved file — a bare `true` uses `plot.png`.
214
+ * The name is a hint: a `data:` URL has no path for a browser to take a
215
+ * filename from, so it travels as a media-type parameter and an engine
216
+ * that ignores it falls back to whatever it would have chosen (Safari
217
+ * says "Unknown"). See {@link PlotView#_installImageOverlay}.
218
+ * `defaultFont: false` suppresses fetching the bundled font when nothing
219
+ * else is registered, for a page that would rather render no text than
220
+ * pull ~260 kB.
221
+ */
222
+ static async create(canvas, doc, opts = {}) {
223
+ if (!isSupported()) {
224
+ throw new Error(
225
+ 'This browser cannot run the renderer. The default build needs a ' +
226
+ 'WebGL2 context; a bundle built with the wgpu backend needs WebGPU ' +
227
+ 'instead. Serve a static image as the fallback.',
228
+ );
229
+ }
230
+ const bytes = doc instanceof Uint8Array ? doc : new Uint8Array(doc);
231
+
232
+ // A browser enumerates no system fonts, so a page that has registered
233
+ // none would render chrome with no text at all — no error, just missing
234
+ // glyphs. Fetch the bundled default rather than let that happen, and skip
235
+ // it entirely when anything is already registered. Before `create`, not
236
+ // after: reading a document decodes its theme, which is already enough to
237
+ // shape, so arriving late would mean a textless first frame.
238
+ if (opts.defaultFont !== false && !hasFonts()) {
239
+ await registerDefaultFonts();
240
+ }
241
+
242
+ const handle = await PlotHandle.create(canvas, bytes, opts.picking === true);
243
+ return new PlotView(canvas, handle, opts);
244
+ }
245
+
246
+ /** @private — use {@link PlotView.create}. */
247
+ constructor(canvas, handle, opts) {
248
+ this.canvas = canvas;
249
+ this.handle = handle;
250
+ this._frame = null;
251
+ this._observer = null;
252
+ this._media = null;
253
+ this._onMedia = null;
254
+ this._overlay = null;
255
+ this._refreshOverlay = null;
256
+ // Kept in step with `_applySize` so an exported PNG can declare the
257
+ // resolution it was actually rendered at.
258
+ this._dpi = 96 * (window.devicePixelRatio || 1);
259
+ this._freed = false;
260
+
261
+ this.setColorScheme(opts.colorScheme ?? 'light');
262
+
263
+ if (opts.autoResize !== false) {
264
+ // ResizeObserver rather than a window resize listener: the canvas can
265
+ // change size from a flex reflow or a sibling appearing, neither of
266
+ // which resizes the window.
267
+ this._observer = new ResizeObserver((entries) => this._onObserved(entries));
268
+ try {
269
+ // device-pixel-content-box reports the exact device-pixel box, so the
270
+ // backing store matches it with no rounding drift against
271
+ // devicePixelRatio. Not universally supported — observe() throws where
272
+ // it isn't, and the CSS box times the ratio is the fallback.
273
+ this._observer.observe(this.canvas, { box: 'device-pixel-content-box' });
274
+ } catch {
275
+ this._observer.observe(this.canvas);
276
+ }
277
+ }
278
+ this._syncSize();
279
+
280
+ if (opts.saveOnRightClick) {
281
+ this._installImageOverlay(
282
+ typeof opts.saveOnRightClick === 'string' ? opts.saveOnRightClick : 'plot.png',
283
+ );
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Give the canvas the context menu an ordinary image has.
289
+ *
290
+ * A `<canvas>` never offers "Save image as…" / "Copy image" / drag-to-save:
291
+ * those come from the hit-test node being an image, and a canvas is not
292
+ * one. Nor can a `contextmenu` handler retarget the menu. So the only way
293
+ * to get the *native* affordance — rather than a bespoke menu that looks
294
+ * nothing like the browser's — is for the right-click to genuinely land on
295
+ * an `<img>`.
296
+ *
297
+ * This overlays a transparent image exactly on the canvas and keeps its
298
+ * `src` refreshed from the live frame, so the canvas below stays the thing
299
+ * that renders while the image above is the thing the menu acts on.
300
+ *
301
+ * Encoding is lazy: a PNG per frame would be pointless work, so the src is
302
+ * refreshed only when a menu is plausibly about to open — pointer entry,
303
+ * a right/ctrl mousedown, and `contextmenu` itself. `mousedown` matters
304
+ * because a browser gathers the menu's image URL from the hit test, which
305
+ * can precede the `contextmenu` dispatch.
306
+ */
307
+ _installImageOverlay(filename) {
308
+ const parent = this.canvas.parentElement;
309
+ if (!parent) return;
310
+ // The overlay is positioned against the canvas's containing block, so
311
+ // that block has to be positioned. Only touched when it isn't already.
312
+ if (getComputedStyle(parent).position === 'static') parent.style.position = 'relative';
313
+
314
+ const img = document.createElement('img');
315
+ img.alt = '';
316
+ // Invisible but hit-testable: the canvas underneath is what the viewer
317
+ // sees, and `opacity` (rather than `visibility` or `display`) is what
318
+ // keeps the element in the hit-test tree.
319
+ img.style.cssText =
320
+ 'position:absolute;inset:0;width:100%;height:100%;opacity:0;' +
321
+ 'pointer-events:auto;touch-action:none';
322
+ // If the named URL is ever rejected — an engine that dislikes the extra
323
+ // media-type parameter — fall back to the same bytes unnamed. An overlay
324
+ // that fails to load is not an image, and a right-click would silently get
325
+ // the ordinary element menu instead, which is the failure this guards.
326
+ img.addEventListener('error', () => {
327
+ const plain = img.src.replace(/;name=[^;,]*/, '');
328
+ if (plain !== img.src) {
329
+ this._nameRejected = true;
330
+ img.src = plain;
331
+ }
332
+ });
333
+ parent.appendChild(img);
334
+ this._overlay = img;
335
+
336
+ const refresh = () => {
337
+ if (this._freed) return;
338
+ try {
339
+ // Draw first, always, and synchronously — nothing may await between
340
+ // the render and the capture. Two separate reasons converge on it:
341
+ // Safari returns an all-black snapshot unless a render happened
342
+ // recently, its drawable being consumed once composited; and the
343
+ // WebGL2 build's context has no `preserveDrawingBuffer`, so its
344
+ // drawing buffer is cleared after compositing too. Rendering in the
345
+ // same task as the capture satisfies both.
346
+ this._renderNow();
347
+ const raw = this.canvas.toDataURL('image/png');
348
+ const png = withPngDpi(dataUrlToBytes(raw), this._dpi);
349
+ // Back to a data URL rather than a blob: Safari's image context menu
350
+ // loses its save entries for `blob:` sources. Reuse the canvas's own
351
+ // string when the patch was a no-op.
352
+ // Name the resource. A `data:` URL has no path for a browser to take
353
+ // a filename from, which is why Safari offers "Unknown"; a `name`
354
+ // media-type parameter is the only hint the URL can carry. Ignored by
355
+ // browsers that do not read it, so it costs nothing to send.
356
+ const url = png === null ? raw : bytesToPngDataUrl(png);
357
+ img.src = this._nameRejected ? url : named(url, filename);
358
+ } catch (e) {
359
+ // A tainted or zero-sized canvas is the expected reason, and the
360
+ // previous src is the right thing to keep. But swallowing this
361
+ // silently once hid a genuinely broken capture path for a long time —
362
+ // the overlay simply never got a src, and a right-click showed the
363
+ // wrong menu with nothing logged. Report the first failure and stay
364
+ // quiet after that, since the handlers fire on every pointer entry.
365
+ if (!this._overlayWarned) {
366
+ this._overlayWarned = true;
367
+ console.warn('hephaestus: could not refresh the save overlay', e);
368
+ }
369
+ }
370
+ };
371
+ this._refreshOverlay = refresh;
372
+ refresh();
373
+
374
+ img.addEventListener('pointerenter', refresh);
375
+ img.addEventListener('mousedown', (e) => {
376
+ // Right-click, or macOS ctrl-click.
377
+ if (e.button === 2 || e.ctrlKey) refresh();
378
+ });
379
+ img.addEventListener('contextmenu', refresh);
380
+ }
381
+
382
+ /** Draw immediately, cancelling any frame already scheduled. */
383
+ redraw() {
384
+ this._renderNow();
385
+ }
386
+
387
+ /**
388
+ * Set the drawing surface size explicitly, in CSS pixels.
389
+ *
390
+ * Only needed when `autoResize` is off, or to drive the size from
391
+ * something the observer cannot see.
392
+ */
393
+ resize(cssWidth, cssHeight, ratio = window.devicePixelRatio || 1) {
394
+ if (this._freed) return;
395
+ this._applySize(
396
+ Math.max(1, Math.round(cssWidth * ratio)),
397
+ Math.max(1, Math.round(cssHeight * ratio)),
398
+ ratio,
399
+ );
400
+ // Synchronously, not on the next frame: see `_applySize`.
401
+ this._renderNow();
402
+ }
403
+
404
+ /**
405
+ * Choose the theme: as authored, inverted, or following the OS.
406
+ *
407
+ * `'auto'` attaches a `prefers-color-scheme` listener and re-renders when
408
+ * it changes. Inversion swaps the palette's paper and ink anchors, so
409
+ * chrome follows; a geom given an explicit color keeps it.
410
+ *
411
+ * @param {'light'|'dark'|'auto'} scheme
412
+ */
413
+ setColorScheme(scheme) {
414
+ if (this._freed) return;
415
+ if (!['light', 'dark', 'auto'].includes(scheme)) {
416
+ throw new Error(`unknown color scheme ${JSON.stringify(scheme)}`);
417
+ }
418
+ this._detachMedia();
419
+ this._scheme = scheme;
420
+
421
+ if (scheme === 'auto') {
422
+ this._media = window.matchMedia('(prefers-color-scheme: dark)');
423
+ this._onMedia = (e) => {
424
+ this.handle.setDark(e.matches);
425
+ this._schedule();
426
+ };
427
+ this._media.addEventListener('change', this._onMedia);
428
+ this.handle.setDark(this._media.matches);
429
+ } else {
430
+ this.handle.setDark(scheme === 'dark');
431
+ }
432
+ this._schedule();
433
+ }
434
+
435
+ /** The scheme last asked for — `'auto'` if it is following the OS. */
436
+ colorScheme() {
437
+ return this._scheme;
438
+ }
439
+
440
+ /** Whether the inverted theme is currently drawn. Resolves `'auto'`. */
441
+ isDark() {
442
+ return this.handle.isDark();
443
+ }
444
+
445
+ /**
446
+ * The row id under a point, or `undefined` for empty space.
447
+ *
448
+ * Takes **CSS** pixels — an event's `offsetX` / `offsetY` — and scales them
449
+ * to the backing store itself, which is the conversion every caller would
450
+ * otherwise get wrong on a high-density display.
451
+ *
452
+ * Returns `undefined` unless the view was created with `picking: true`.
453
+ * The hitmap may lag the visible frame slightly, since the readback is
454
+ * never waited on.
455
+ */
456
+ pickAt(cssX, cssY) {
457
+ if (this._freed) return undefined;
458
+ const ratio = this.canvas.width / (this.canvas.clientWidth || this.canvas.width);
459
+ return this.handle.pickAt(Math.round(cssX * ratio), Math.round(cssY * ratio));
460
+ }
461
+
462
+ /**
463
+ * The size and dpi the document's writer recorded, if any.
464
+ *
465
+ * Advisory. Useful as an aspect ratio for a container that must be sized
466
+ * before the plot is laid out.
467
+ */
468
+ hints() {
469
+ return {
470
+ width: this.handle.hintWidth(),
471
+ height: this.handle.hintHeight(),
472
+ dpi: this.handle.hintDpi(),
473
+ };
474
+ }
475
+
476
+ /** Detach observers and release the wasm-side handle. */
477
+ free() {
478
+ if (this._freed) return;
479
+ this._freed = true;
480
+ if (this._frame !== null) cancelAnimationFrame(this._frame);
481
+ this._observer?.disconnect();
482
+ this._detachMedia();
483
+ this._overlay?.remove();
484
+ this._overlay = null;
485
+ this.handle.free();
486
+ }
487
+
488
+ _onObserved(entries) {
489
+ if (this._freed) return;
490
+ const entry = entries[entries.length - 1];
491
+ const ratio = window.devicePixelRatio || 1;
492
+ const exact = entry.devicePixelContentBoxSize?.[0];
493
+ if (exact) {
494
+ this._applySize(
495
+ Math.max(1, exact.inlineSize),
496
+ Math.max(1, exact.blockSize),
497
+ ratio,
498
+ );
499
+ } else {
500
+ // Reading the entry rather than clientWidth avoids forcing a layout
501
+ // flush inside the callback.
502
+ const box = entry.contentBoxSize?.[0];
503
+ const cssW = box ? box.inlineSize : this.canvas.clientWidth;
504
+ const cssH = box ? box.blockSize : this.canvas.clientHeight;
505
+ this._applySize(
506
+ Math.max(1, Math.round(cssW * ratio)),
507
+ Math.max(1, Math.round(cssH * ratio)),
508
+ ratio,
509
+ );
510
+ }
511
+ this._renderNow();
512
+ }
513
+
514
+ _syncSize() {
515
+ // clientWidth is 0 for a canvas that isn't laid out (display:none, or
516
+ // detached); fall back to the attributes so the surface stays valid.
517
+ const w = this.canvas.clientWidth || this.canvas.width;
518
+ const h = this.canvas.clientHeight || this.canvas.height;
519
+ this.resize(w, h);
520
+ }
521
+
522
+ /**
523
+ * Point the backing store and the renderer at a device-pixel size.
524
+ *
525
+ * Assigning `canvas.width` / `canvas.height` **clears the drawing buffer**,
526
+ * so every caller has to draw again before the browser next paints or a
527
+ * blank frame reaches the screen. That is why nothing here defers a
528
+ * post-resize draw to `requestAnimationFrame`: a `ResizeObserver` callback
529
+ * runs after layout but *before* paint, so drawing in the same turn lands
530
+ * the new frame in the same paint, while an rAF lands it one paint later —
531
+ * with the cleared buffer shown in between.
532
+ */
533
+ _applySize(width, height, ratio) {
534
+ if (this.canvas.width !== width) this.canvas.width = width;
535
+ if (this.canvas.height !== height) this.canvas.height = height;
536
+ this._dpi = 96 * ratio;
537
+ this.handle.resize(width, height, ratio);
538
+ }
539
+
540
+ /** Draw now, dropping any frame already scheduled. */
541
+ _renderNow() {
542
+ if (this._freed) return;
543
+ if (this._frame !== null) {
544
+ cancelAnimationFrame(this._frame);
545
+ this._frame = null;
546
+ }
547
+ this.handle.render();
548
+ }
549
+
550
+ /**
551
+ * Coalesce a draw into the next frame.
552
+ *
553
+ * For changes that do *not* clear the backing store — a theme swap — where
554
+ * batching several mutations into one frame is worth a frame of latency.
555
+ */
556
+ _schedule() {
557
+ if (this._freed || this._frame !== null) return;
558
+ this._frame = requestAnimationFrame(() => {
559
+ this._frame = null;
560
+ if (!this._freed) this.handle.render();
561
+ });
562
+ }
563
+
564
+ _detachMedia() {
565
+ if (this._media && this._onMedia) {
566
+ this._media.removeEventListener('change', this._onMedia);
567
+ }
568
+ this._media = null;
569
+ this._onMedia = null;
570
+ }
571
+ }
572
+
573
+ // ─── PNG dpi patching ───────────────────────────────────────────────────────
574
+ //
575
+ // A canvas writes no `pHYs` chunk, so a viewer assumes 72 dpi and a plot
576
+ // rendered at 2x device pixels claims twice its physical size. These three
577
+ // helpers exist to fix that on the way from `toDataURL` to the overlay image:
578
+ // decode the data URL, insert or replace `pHYs`, re-encode.
579
+
580
+ /** Bytes behind a `data:` URL. Throws if it is not base64-encoded. */
581
+ function dataUrlToBytes(dataUrl) {
582
+ const comma = dataUrl.indexOf(',');
583
+ if (comma < 0 || !dataUrl.slice(0, comma).includes(';base64')) {
584
+ throw new Error('not a base64 data URL');
585
+ }
586
+ const raw = atob(dataUrl.slice(comma + 1));
587
+ const bytes = new Uint8Array(raw.length);
588
+ for (let i = 0; i < raw.length; i += 1) bytes[i] = raw.charCodeAt(i);
589
+ return bytes;
590
+ }
591
+
592
+ /** A `data:image/png;base64,` URL for `bytes`. */
593
+ function bytesToPngDataUrl(bytes) {
594
+ // Chunked because `String.fromCharCode(...bytes)` blows the argument limit
595
+ // on anything bigger than a thumbnail.
596
+ let ascii = '';
597
+ const step = 0x8000;
598
+ for (let i = 0; i < bytes.length; i += step) {
599
+ ascii += String.fromCharCode.apply(null, bytes.subarray(i, i + step));
600
+ }
601
+ return `data:image/png;base64,${btoa(ascii)}`;
602
+ }
603
+
604
+ /**
605
+ * Add a `name` parameter to a `data:` URL's media type.
606
+ *
607
+ * Rewrites only the prefix, so the base64 payload is never re-encoded — this
608
+ * runs on pointer entry and the payload is the expensive part. A name that
609
+ * already looks right is left alone.
610
+ */
611
+ function named(dataUrl, filename) {
612
+ const comma = dataUrl.indexOf(',');
613
+ if (comma < 0) return dataUrl;
614
+ const safe = sanitiseFilename(filename);
615
+ if (!safe) return dataUrl;
616
+ let prefix = dataUrl.slice(0, comma);
617
+ if (prefix.includes(';name=')) return dataUrl;
618
+ // `;base64` has to stay immediately before the comma.
619
+ prefix = prefix.replace(/;base64$/, `;name=${safe};base64`);
620
+ return prefix + dataUrl.slice(comma);
621
+ }
622
+
623
+ /**
624
+ * Reduce `filename` to something safe to put in a URL parameter, or `null`.
625
+ *
626
+ * Path separators and quotes are dropped rather than escaped: this ends up in
627
+ * a header-ish position and in a save dialog, and neither wants a path.
628
+ */
629
+ function sanitiseFilename(filename) {
630
+ if (typeof filename !== 'string') return null;
631
+ const base = filename.split(/[\\/]/).pop().replace(/[^\w.\- ]/g, '').trim();
632
+ if (!base || base === '.' || base === '..') return null;
633
+ return /\.png$/i.test(base) ? base : `${base}.png`;
634
+ }
635
+
636
+ const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
637
+
638
+ let crcTable = null;
639
+
640
+ /** CRC-32 as PNG defines it, over `bytes[from..to)`. */
641
+ function crc32(bytes, from, to) {
642
+ if (crcTable === null) {
643
+ crcTable = new Int32Array(256);
644
+ for (let n = 0; n < 256; n += 1) {
645
+ let c = n;
646
+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
647
+ crcTable[n] = c;
648
+ }
649
+ }
650
+ let c = 0xffffffff;
651
+ for (let i = from; i < to; i += 1) c = crcTable[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
652
+ return (c ^ 0xffffffff) >>> 0;
653
+ }
654
+
655
+ /**
656
+ * Return `png` with a `pHYs` chunk describing `dpi`, or `null` when the bytes
657
+ * already say that.
658
+ *
659
+ * `null` rather than a copy so the caller can reuse the string it already has
660
+ * — re-encoding a megabyte of base64 to change nothing is the one cost worth
661
+ * avoiding on a path that runs on pointer entry.
662
+ */
663
+ function withPngDpi(png, dpi) {
664
+ for (let i = 0; i < PNG_SIGNATURE.length; i += 1) {
665
+ if (png[i] !== PNG_SIGNATURE[i]) throw new Error('not a PNG');
666
+ }
667
+ // `pHYs` counts pixels per metre, and one inch is exactly 0.0254 m.
668
+ const perMetre = Math.round(dpi / 0.0254);
669
+
670
+ const chunk = new Uint8Array(21);
671
+ const view = new DataView(chunk.buffer);
672
+ view.setUint32(0, 9); // data length
673
+ chunk[4] = 0x70; // 'p'
674
+ chunk[5] = 0x48; // 'H'
675
+ chunk[6] = 0x59; // 'Y'
676
+ chunk[7] = 0x73; // 's'
677
+ view.setUint32(8, perMetre);
678
+ view.setUint32(12, perMetre);
679
+ chunk[16] = 1; // unit specifier: metre
680
+ view.setUint32(17, crc32(chunk, 4, 17));
681
+
682
+ // Walk the chunk list to find where `pHYs` belongs: after IHDR, and before
683
+ // the first IDAT. An existing one is replaced rather than duplicated.
684
+ let offset = PNG_SIGNATURE.length;
685
+ let insertAt = -1;
686
+ let replaceEnd = -1;
687
+ while (offset + 8 <= png.length) {
688
+ const len = new DataView(png.buffer, png.byteOffset + offset, 4).getUint32(0);
689
+ const type = String.fromCharCode(png[offset + 4], png[offset + 5], png[offset + 6], png[offset + 7]);
690
+ const total = 12 + len;
691
+ if (type === 'pHYs') {
692
+ // Already correct? Then the caller keeps what it has.
693
+ let same = true;
694
+ for (let i = 0; i < 21; i += 1) {
695
+ if (png[offset + i] !== chunk[i]) {
696
+ same = false;
697
+ break;
698
+ }
699
+ }
700
+ if (same) return null;
701
+ insertAt = offset;
702
+ replaceEnd = offset + total;
703
+ break;
704
+ }
705
+ if (type === 'IDAT' || type === 'IEND') {
706
+ insertAt = offset;
707
+ replaceEnd = offset;
708
+ break;
709
+ }
710
+ offset += total;
711
+ }
712
+ if (insertAt < 0) throw new Error('PNG has no IDAT');
713
+
714
+ const out = new Uint8Array(png.length - (replaceEnd - insertAt) + chunk.length);
715
+ out.set(png.subarray(0, insertAt), 0);
716
+ out.set(chunk, insertAt);
717
+ out.set(png.subarray(replaceEnd), insertAt + chunk.length);
718
+ return out;
719
+ }