@pencil-lang/figure 0.0.2 → 0.0.4

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/src/element.js CHANGED
@@ -38,10 +38,21 @@
38
38
  // is defined: changes made before that script finishes are fetched once.
39
39
  // Its labels are an em of the text where it sits, and follow when a reader changes their text size.
40
40
  // `reload()` fetches the sources again, for a page that watches them change.
41
+ // A handle is dragged with a mouse, a pen or a finger, or tabbed to and moved with the keys. A touch
42
+ // within a handle's reach drags it and doesn't scroll the page; anywhere else on the figure the
43
+ // page scrolls and zooms as it would over an image. Nothing in the figure is text to select, and a
44
+ // drag never selects the page's. The element does all this itself: a page needs no CSS for it.
45
+ // A browser can lose the GPU under a figure, after sleep or when its GPU process restarts. The
46
+ // figure then starts its GPU again, keeping its sources, time, held params and whether it's
47
+ // paused, and shows its poster meanwhile. It tries at once, after a second and after five, then
48
+ // says `error` (with `detail.gpu`), and tries once more each time the page is shown.
41
49
  // Events: `load` when a figure is compiled, `draw` after each frame drawn, `resize` when its drawn
42
50
  // size or its em changes (its `detail.em`, in CSS pixels), `input` when a reader
43
- // drags a param, `play` and `pause`, and `error` (its `detail.error`) when one can't load or draw.
44
- import { Player, figure_size, figure_size_compiled, ready, isReady, gather, ahead } from './host.js';
51
+ // drags a param (its `detail.name` and `detail.value`, and `detail.values`, every param that one
52
+ // move set, by name: two for a point dragged in two dimensions), `play` and `pause`, `error` (its
53
+ // `detail.error`) when one can't load or draw, and `recover` when one that said `error` because it
54
+ // lost its GPU draws again.
55
+ import { Player, let_go, figure_size, figure_size_compiled, ready, isReady, gather, ahead } from './host.js';
45
56
  import { LABEL_CSS, LabelLayer, fonts } from './labels.js';
46
57
  import { match } from './fit.js';
47
58
  import { follow, settle, unfollow } from './scheme.js';
@@ -53,6 +64,12 @@ const REACH = 24;
53
64
  // How far from the viewport the GPU starts, so a figure is drawn by the time it's scrolled to.
54
65
  const NEAR = '200px';
55
66
 
67
+ // How long a figure has to draw after starting again before a loss counts as a new one.
68
+ const SETTLED = 30_000;
69
+ // When a figure that has lost its GPU tries again: at once, then after a moment for a GPU process
70
+ // that's restarting, then a little longer. After those it says `error`.
71
+ const RETRIES = [0, 1000, 5000];
72
+
56
73
  const fetchText = async (url) => {
57
74
  const response = await fetch(new URL(url, document.baseURI));
58
75
  if (!response.ok) throw new Error(`${url}: ${response.status}`);
@@ -60,7 +77,10 @@ const fetchText = async (url) => {
60
77
  };
61
78
 
62
79
  const CSS = `
80
+ /* Nothing in a figure is text to select, and a long press on it shows no callout: a handle is
81
+ pressed and held to be dragged. WebKit doesn't carry the host's down, so each part says it. */
63
82
  :host { display: block; }
83
+ :host, .stage *, ::slotted(*) { -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; -webkit-tap-highlight-color: transparent; }
64
84
  :host([hidden]) { display: none; }
65
85
  .stage { position: relative; overflow: hidden; width: 100%; }
66
86
  canvas { display: block; width: 100%; aspect-ratio: var(--pencil-aspect, 16 / 9); outline: none; }
@@ -72,11 +92,17 @@ slot { display: none; }
72
92
  ::slotted(source) { display: none; }
73
93
  ::slotted(img), ::slotted(picture) { display: block; width: 100%; height: auto; }
74
94
  .em { position: absolute; left: 0; top: 0; width: 1em; height: 0; visibility: hidden; pointer-events: none; }
75
- /* Something to focus over each handle. The pointer goes through it to the canvas, which is where
76
- a drag is taken, and a reader on a keyboard tabs to it and moves it with the arrow keys. Its
77
- ring is two tones, so it shows on any paper. */
95
+ /* Something to focus over each handle: a reader on a keyboard tabs to it and moves it with the
96
+ arrow keys. Its ring is two tones, so it shows on any paper. A pointer takes it within the
97
+ handle's reach, the circle its ::before fills, and a touch there drags the handle and doesn't
98
+ scroll the page. Anywhere else on the figure the touch goes to the canvas, which leaves the
99
+ page to scroll and zoom as it would over an image. */
78
100
  .handles { position: absolute; inset: 0; pointer-events: none; }
79
- .handle { position: absolute; left: -14px; top: -14px; width: 28px; height: 28px; border-radius: 50%; outline: none; will-change: transform; }
101
+ .handle { position: absolute; left: -14px; top: -14px; width: 28px; height: 28px; border-radius: 50%; outline: none; will-change: transform; pointer-events: auto; touch-action: none; }
102
+ .handle::before { content: ''; position: absolute; inset: ${14 - REACH}px; border-radius: 50%; clip-path: var(--reach, none); }
103
+ /* With no GPU, as while the poster shows, a handle can't be dragged, so it takes no pointer, and
104
+ a touch on it scrolls the page. The keys still find it. */
105
+ .stage:not(.live) .handle { pointer-events: none; touch-action: auto; }
80
106
  .handle:focus-visible { outline: 2px solid var(--pencil-focus, currentColor); outline-offset: 1px; box-shadow: 0 0 0 2px var(--pencil-focus-halo, Canvas); }
81
107
  .handle[hidden] { display: none; }
82
108
  .said { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
@@ -132,6 +158,24 @@ export class PencilFigure extends HTMLElement {
132
158
  #fresh = false;
133
159
  #seen = null;
134
160
  #resized = null;
161
+ // Starting again after the GPU is lost: how many times since the figure last settled, when it
162
+ // last did, whether it has drawn since, whether it's waiting for the page to be seen again,
163
+ // and that the `load` a start sends isn't news.
164
+ #tries = 0;
165
+ #restarted = 0;
166
+ #healthy = false;
167
+ #awaiting = false;
168
+ #quiet = false;
169
+ #retry = 0; // the timer for the next try
170
+ #reported = false; // whether it said `error` since it last drew
171
+ #playerId = -1; // the player's number and backend, which a trapped player can't say
172
+ #backend = null;
173
+ // A WebGL2 canvas whose context is being brought back, for the next player, and a start that
174
+ // waits for it.
175
+ #restoring = false;
176
+ #restoreTimer = 0;
177
+ #startPending = false;
178
+ #lose = null; // the canvas's `WEBGL_lose_context`, which a lost context doesn't give
135
179
 
136
180
  constructor() {
137
181
  super();
@@ -156,6 +200,19 @@ export class PencilFigure extends HTMLElement {
156
200
  this.#said.className = 'said';
157
201
  this.#said.setAttribute('aria-live', 'polite');
158
202
  this.#stage.append(this.#handleLayer, this.#said);
203
+ // A press on the canvas or on a handle's reach comes here, and a grab captures the pointer.
204
+ const stage = this.#stage;
205
+ stage.addEventListener('pointerdown', this.#pointerDown);
206
+ stage.addEventListener('pointermove', this.#pointerMove);
207
+ stage.addEventListener('pointerup', this.#pointerEnd);
208
+ stage.addEventListener('pointercancel', this.#pointerEnd);
209
+ // A grab focuses its handle, and the press mustn't take the focus away again, or start a
210
+ // selection that follows the pointer out over the page. Nor does a long press open a menu.
211
+ const grabbing = (e) => {
212
+ if (this.#player?.grabbed() >= 0) e.preventDefault();
213
+ };
214
+ stage.addEventListener('mousedown', grabbing);
215
+ stage.addEventListener('contextmenu', grabbing);
159
216
  this.addEventListener('keydown', this.#key);
160
217
  try {
161
218
  this.#internals = this.attachInternals();
@@ -239,6 +296,8 @@ export class PencilFigure extends HTMLElement {
239
296
  });
240
297
  this.#children.observe(this, { childList: true, attributes: true, subtree: true, attributeFilter: ['media', 'src', 'sheets', 'compiled'] });
241
298
  document.fonts?.addEventListener('loadingdone', this.#fontsChanged);
299
+ document.addEventListener('visibilitychange', this.#shown);
300
+ window.addEventListener('pageshow', this.#shown);
242
301
  follow(this);
243
302
  this.#wait();
244
303
  this.#listen();
@@ -255,6 +314,8 @@ export class PencilFigure extends HTMLElement {
255
314
 
256
315
  disconnectedCallback() {
257
316
  document.fonts?.removeEventListener('loadingdone', this.#fontsChanged);
317
+ document.removeEventListener('visibilitychange', this.#shown);
318
+ window.removeEventListener('pageshow', this.#shown);
258
319
  this.#seen?.disconnect();
259
320
  this.#resized?.disconnect();
260
321
  this.#children?.disconnect();
@@ -270,7 +331,7 @@ export class PencilFigure extends HTMLElement {
270
331
 
271
332
  attributeChangedCallback(name) {
272
333
  if (name === 'params') {
273
- for (const [param, value] of parseParams(this.getAttribute('params'))) this.hold(param, value);
334
+ this.#hold(parseParams(this.getAttribute('params')));
274
335
  } else {
275
336
  this.#refetch();
276
337
  }
@@ -280,13 +341,20 @@ export class PencilFigure extends HTMLElement {
280
341
  const canvas = document.createElement('canvas');
281
342
  canvas.setAttribute('part', 'canvas');
282
343
  if (this.#size) canvas.style.setProperty('--pencil-aspect', `${this.#size[0]} / ${this.#size[1]}`);
283
- canvas.addEventListener('pointerdown', this.#pointerDown);
284
- canvas.addEventListener('pointermove', this.#pointerMove);
285
- canvas.addEventListener('pointerup', this.#pointerEnd);
286
- canvas.addEventListener('pointercancel', this.#pointerEnd);
287
- // A grab focuses its handle, and the press mustn't take the focus away again.
288
- canvas.addEventListener('mousedown', (e) => {
289
- if (this.#player?.grabbed() >= 0) e.preventDefault();
344
+ // WebGL says so when it loses its context, and drawing on carries on drawing nothing. The
345
+ // context is kept, to be brought back, since a browser counts a canvas's against its cap
346
+ // until the canvas is collected, which WebKit can leave for a long while.
347
+ canvas.addEventListener('webglcontextlost', (e) => {
348
+ e.preventDefault();
349
+ if (canvas !== this.#canvas) return;
350
+ if (this.#player) this.#recover(new Error('GPU context lost'));
351
+ else if (this.#restoring) this.#restoreLater(canvas);
352
+ });
353
+ canvas.addEventListener('webglcontextrestored', () => {
354
+ if (canvas !== this.#canvas || !this.#restoring) return;
355
+ this.#restoring = false;
356
+ clearTimeout(this.#restoreTimer);
357
+ this.#startIfPending();
290
358
  });
291
359
  return canvas;
292
360
  }
@@ -294,6 +362,11 @@ export class PencilFigure extends HTMLElement {
294
362
  /** Starts the GPU, once, when the element is near the viewport. */
295
363
  async #start() {
296
364
  if (this.#player || this.#starting) return;
365
+ // Its WebGL context is on its way back.
366
+ if (this.#restoring) {
367
+ this.#startPending = true;
368
+ return;
369
+ }
297
370
  this.#starting = true;
298
371
  const generation = this.#generation;
299
372
  try {
@@ -307,6 +380,14 @@ export class PencilFigure extends HTMLElement {
307
380
  return;
308
381
  }
309
382
  this.#player = player;
383
+ this.#playerId = player.id;
384
+ this.#backend = player.backend;
385
+ this.#lose = player.backend === 'Gl' ? (this.#canvas.getContext('webgl2')?.getExtension('WEBGL_lose_context') ?? null) : null;
386
+ this.#stage.classList.add('live');
387
+ // A browser loses a GPU device after sleep or when its GPU process restarts, and says so.
388
+ player.on_lost(() => {
389
+ if (this.#player === player) this.#recover(new Error('GPU device lost'));
390
+ });
310
391
  player.set_measure(this.#layer.measure);
311
392
  this.#setEm();
312
393
  if (this.#sources) {
@@ -316,13 +397,169 @@ export class PencilFigure extends HTMLElement {
316
397
  this.#fail(error);
317
398
  }
318
399
  }
400
+ // Started, so nothing is waiting to try again, and the next `load` is news.
401
+ this.#awaiting = false;
402
+ this.#quiet = false;
403
+ clearTimeout(this.#retry);
404
+ this.#retry = 0;
319
405
  } catch (error) {
320
- this.#fail(error);
406
+ // Starting again can fail while the browser's GPU is still coming back.
407
+ if (this.#tries && generation === this.#generation) {
408
+ this.#starting = false;
409
+ this.#recover(error);
410
+ } else this.#fail(error);
321
411
  } finally {
322
412
  if (generation === this.#generation) this.#starting = false;
323
413
  }
324
414
  }
325
415
 
416
+ // ---- A lost GPU ----
417
+
418
+ /** Whether a draw failed on the GPU's side, which a new player gets past: a trap inside the
419
+ * WASM (`unreachable`), after which that player can't be used again ("recursive use of an
420
+ * object"), a lost device or context, or no texture to draw into, as when a draw comes before
421
+ * the word that the device is lost. A GPU error on a device that isn't lost is the figure's,
422
+ * and is said at once, as any other. A trap can be the core's too: that one fails each time it's
423
+ * tried, and is said once the tries are done. */
424
+ #recoverable(error) {
425
+ if (error instanceof WebAssembly.RuntimeError) return true;
426
+ const message = String(error?.message ?? '');
427
+ if (/recursive use of an object|^GPU (device lost|context lost|surface)/.test(message)) return true;
428
+ if (!message.startsWith('GPU error:')) return false;
429
+ try {
430
+ return this.#player?.lost ?? false;
431
+ } catch {
432
+ return true;
433
+ }
434
+ }
435
+
436
+ /**
437
+ * The GPU went away under the figure, or a draw failed on its side: start the GPU again, keeping
438
+ * the figure's sources, time, held params and whether it's paused, with its poster meanwhile.
439
+ * It's tried at once, then after a second and after five, for a GPU process that's coming back,
440
+ * and then it's an `error` (with `detail.gpu`), tried once more each time the page is shown. A
441
+ * figure that draws again after that says `recover`. One that has drawn for a while since, or
442
+ * that the reader has come back to, has its tries back.
443
+ */
444
+ #recover(error) {
445
+ clearTimeout(this.#retry);
446
+ this.#retry = 0;
447
+ if (this.#healthy && performance.now() - this.#restarted > SETTLED) this.#tries = 0;
448
+ this.#tries += 1;
449
+ this.#dropGpu();
450
+ const wait = RETRIES[this.#tries - 1];
451
+ if (wait === undefined) {
452
+ this.#awaiting = true;
453
+ this.#reported = true;
454
+ this.dispatchEvent(new CustomEvent('error', { detail: { error, time: this.#time, fresh: false, gpu: true } }));
455
+ } else if (wait === 0) {
456
+ this.#restart();
457
+ } else {
458
+ this.#retry = setTimeout(() => {
459
+ this.#retry = 0;
460
+ this.#restart();
461
+ }, wait);
462
+ }
463
+ }
464
+
465
+ #restart() {
466
+ this.#restarted = performance.now();
467
+ this.#quiet = true;
468
+ if (this.#visible) this.#start();
469
+ }
470
+
471
+ /** The page was seen again, or brought back from the back/forward cache. */
472
+ #shown = () => {
473
+ if (document.visibilityState !== 'visible') return;
474
+ if (this.#awaiting && !this.#player) {
475
+ // One more try, which says `error` again if it fails.
476
+ this.#awaiting = false;
477
+ this.#tries = RETRIES.length;
478
+ this.#restart();
479
+ } else if (this.#healthy) {
480
+ this.#tries = 0;
481
+ }
482
+ };
483
+
484
+ /** Lets go of a player, even one that trapped, which can't be borrowed again: its device is
485
+ * let go of by its number. */
486
+ #letGo(player) {
487
+ try {
488
+ player.destroy();
489
+ } catch {
490
+ let_go(this.#playerId);
491
+ }
492
+ }
493
+
494
+ /** Lets go of the player, and nothing else, as `#teardown` does with the rest. The poster shows
495
+ * again until the figure draws. A WebGL2 canvas keeps its context, lost and brought back for
496
+ * the next player, and a WebGPU one gets a new canvas. */
497
+ #dropGpu() {
498
+ cancelAnimationFrame(this.#raf);
499
+ this.#raf = 0;
500
+ this.#idle = true;
501
+ this.#generation += 1;
502
+ this.#starting = false;
503
+ this.#healthy = false;
504
+ this.#stage.classList.remove('live');
505
+ const player = this.#player;
506
+ this.#player = null;
507
+ // The clock stops where it is, and runs again once there's a figure to draw.
508
+ this.#sync();
509
+ if (player) {
510
+ this.#letGo(player);
511
+ if (this.#backend === 'Gl') this.#restore(this.#canvas);
512
+ else this.#freshCanvas();
513
+ }
514
+ this.#drawn = false;
515
+ this.#wait();
516
+ }
517
+
518
+ /** Loses a WebGL2 context, if it isn't already, and brings it back, for the next player. One the
519
+ * browser lost and doesn't bring back within two seconds is given up on, for a new canvas. */
520
+ #restore(canvas) {
521
+ const gl = canvas.getContext('webgl2');
522
+ if (!gl || !this.#lose) {
523
+ this.#freshCanvas();
524
+ return;
525
+ }
526
+ this.#restoring = true;
527
+ // Its `webglcontextlost` brings it back; one already lost is brought back now.
528
+ if (gl.isContextLost()) this.#restoreLater(canvas);
529
+ else this.#lose.loseContext();
530
+ clearTimeout(this.#restoreTimer);
531
+ this.#restoreTimer = setTimeout(() => {
532
+ if (!this.#restoring || canvas !== this.#canvas) return;
533
+ this.#restoring = false;
534
+ this.#freshCanvas();
535
+ this.#startIfPending();
536
+ }, 2000);
537
+ }
538
+
539
+ /** Asks for a lost context back, once the event that says it's lost is done: only a loss whose
540
+ * event was cancelled can be restored. One the browser lost comes back by itself, if it can. */
541
+ #restoreLater(canvas) {
542
+ setTimeout(() => {
543
+ if (this.#restoring && canvas === this.#canvas) this.#lose?.restoreContext();
544
+ }, 0);
545
+ }
546
+
547
+ #startIfPending() {
548
+ if (!this.#startPending) return;
549
+ this.#startPending = false;
550
+ if (this.#visible) this.#start();
551
+ }
552
+
553
+ /** A new canvas in place of the old one, which keeps its context for life. */
554
+ #freshCanvas() {
555
+ this.#lose = null;
556
+ const canvas = this.#makeCanvas();
557
+ this.#resized?.unobserve(this.#canvas);
558
+ this.#canvas.replaceWith(canvas);
559
+ this.#canvas = canvas;
560
+ this.#resized?.observe(canvas);
561
+ }
562
+
326
563
  /** Lets go of the clock and the GPU. The figure's sources, time and held params are kept, so
327
564
  * it starts again where it was if it's put back. */
328
565
  #teardown() {
@@ -332,15 +569,27 @@ export class PencilFigure extends HTMLElement {
332
569
  cancelAnimationFrame(this.#raf);
333
570
  this.#raf = 0;
334
571
  this.#idle = true;
335
- const started = this.#player || this.#starting;
572
+ const started = this.#player || this.#starting || this.#restoring;
336
573
  this.#generation += 1;
337
574
  this.#starting = false;
575
+ // Nothing waits to try again: a figure put back starts afresh.
576
+ clearTimeout(this.#retry);
577
+ this.#retry = 0;
578
+ this.#awaiting = false;
579
+ this.#quiet = false;
580
+ this.#tries = 0;
581
+ this.#reported = false;
582
+ this.#restoring = false;
583
+ this.#startPending = false;
584
+ clearTimeout(this.#restoreTimer);
585
+ this.#stage.classList.remove('live');
338
586
  if (this.#player) {
339
- const gl = this.#player.backend === 'Gl';
340
- this.#player.destroy();
587
+ this.#letGo(this.#player);
341
588
  this.#player = null;
342
- if (gl) this.#canvas.getContext('webgl2')?.getExtension('WEBGL_lose_context')?.loseContext();
589
+ // A browser has only so many contexts live, and loses the oldest past that.
590
+ if (this.#backend === 'Gl') this.#lose?.loseContext();
343
591
  else this.#canvas.getContext('webgpu')?.unconfigure();
592
+ this.#lose = null;
344
593
  }
345
594
  // A canvas keeps its context for life, so a figure put back gets a new one.
346
595
  if (started) {
@@ -474,7 +723,9 @@ export class PencilFigure extends HTMLElement {
474
723
  this.#fresh = true;
475
724
  this.#invalidate();
476
725
  this.#sync();
477
- this.dispatchEvent(new Event('load'));
726
+ // A figure started again after losing its GPU is the same figure.
727
+ if (this.#quiet) this.#quiet = false;
728
+ else this.dispatchEvent(new Event('load'));
478
729
  }
479
730
 
480
731
  /** Shapes the figure to its design size, so nothing moves as it loads. */
@@ -500,15 +751,15 @@ export class PencilFigure extends HTMLElement {
500
751
  return this.#info?.duration ?? LOOP;
501
752
  }
502
753
 
503
- /** The time last drawn, in seconds. Setting it seeks, and a `beat` that follows time follows
504
- * it again. */
754
+ /** The time last drawn, in seconds. Setting it seeks, and hands every param time drives back
755
+ * to time, as a reader setting any param hands back the params whose bindings read it. */
505
756
  get time() {
506
757
  return this.#time;
507
758
  }
508
759
 
509
760
  set time(seconds) {
510
761
  this.#seek(seconds);
511
- if (this.#driven.has('beat')) this.#release('beat');
762
+ for (const name of [...this.#held.keys()]) if (this.#driven.has(name)) this.#release(name);
512
763
  this.#invalidate();
513
764
  }
514
765
 
@@ -659,14 +910,40 @@ export class PencilFigure extends HTMLElement {
659
910
  }
660
911
  }
661
912
 
662
- /** Takes a param over from time, at this value, until it's released or the figure plays. */
913
+ /** Takes a param over from its binding, at this value, as a reader setting it does, until it's
914
+ * released, the figure plays, or a param its binding reads is set. */
663
915
  hold(name, value) {
664
- this.#held.delete(name);
665
- this.#held.set(name, value);
666
- this.#player?.set_param(name, value);
916
+ this.#hold([[name, value]]);
917
+ }
918
+
919
+ /** Holds params together: none of them hands another back. */
920
+ #hold(pairs) {
921
+ this.#reclaim(pairs.map(([name]) => name));
922
+ for (const [name, value] of pairs) {
923
+ this.#held.delete(name);
924
+ this.#held.set(name, value);
925
+ this.#player?.set_param(name, value);
926
+ }
667
927
  this.#invalidate();
668
928
  }
669
929
 
930
+ /**
931
+ * A param with a binding has two drivers, its binding and the reader, and the reader's last
932
+ * action picks. So when a reader sets params, every other held param whose binding reads one
933
+ * of them (`reads`, in `info.params`, which the core works out) goes back to its binding, as
934
+ * θ in Bounds goes back to closing the flower when q or the case is set. Before a figure is
935
+ * loaded nothing is known of its bindings, so holds made then are all kept.
936
+ */
937
+ #reclaim(names) {
938
+ const params = this.#info?.params;
939
+ if (!params) return;
940
+ for (const name of [...this.#held.keys()]) {
941
+ if (names.includes(name)) continue;
942
+ const reads = params.find((p) => p.id === name)?.reads ?? [];
943
+ if (reads.some((read) => names.includes(read))) this.#release(name);
944
+ }
945
+ }
946
+
670
947
  /** Hands a param back to its binding, or every param with no name. */
671
948
  release(name) {
672
949
  for (const each of name === undefined ? [...this.#held.keys()] : [name]) this.#release(each);
@@ -683,13 +960,13 @@ export class PencilFigure extends HTMLElement {
683
960
  return new Map(this.#held);
684
961
  }
685
962
 
686
- /** Every param's value this frame, by name. Setting holds each one given. */
963
+ /** Every param's value this frame, by name. Setting holds each one given, together. */
687
964
  get params() {
688
965
  return Object.fromEntries((this.#info?.params ?? []).map((p) => [p.id, this.value(p.id)]));
689
966
  }
690
967
 
691
968
  set params(values) {
692
- for (const [name, value] of Object.entries(values)) this.hold(name, value);
969
+ this.#hold(Object.entries(values));
693
970
  }
694
971
 
695
972
  /** The figure's design size, `[width, height]` in design pixels, from its sheets. */
@@ -726,13 +1003,14 @@ export class PencilFigure extends HTMLElement {
726
1003
  }
727
1004
 
728
1005
  #pointerDown = (e) => {
729
- if (!this.#player) return;
1006
+ // One pointer drags at a time, and only with the main button.
1007
+ if (!this.#player || !e.isPrimary || e.button !== 0) return;
730
1008
  const [x, y] = this.#device(e);
731
1009
  try {
732
1010
  if (!this.#player.grab(this.#time, x, y, REACH * (window.devicePixelRatio || 1))) return;
733
1011
  this.pause();
734
- this.#canvas.setPointerCapture(e.pointerId);
735
- this.#canvas.style.cursor = 'grabbing';
1012
+ this.#stage.setPointerCapture(e.pointerId);
1013
+ this.#stage.style.cursor = 'grabbing';
736
1014
  // The keys carry on from where the pointer leaves it.
737
1015
  this.#handles[this.#player.grabbed()]?.focus({ preventScroll: true });
738
1016
  this.#drag(x, y);
@@ -743,8 +1021,8 @@ export class PencilFigure extends HTMLElement {
743
1021
  if (!this.#player) return;
744
1022
  const [x, y] = this.#device(e);
745
1023
  try {
746
- if (!this.#canvas.hasPointerCapture(e.pointerId)) {
747
- this.#canvas.style.cursor = this.#player.grab(this.#time, x, y, REACH * (window.devicePixelRatio || 1)) ? 'grab' : '';
1024
+ if (!this.#stage.hasPointerCapture(e.pointerId)) {
1025
+ this.#stage.style.cursor = this.#player.grab(this.#time, x, y, REACH * (window.devicePixelRatio || 1)) ? 'grab' : '';
748
1026
  this.#player.release();
749
1027
  return;
750
1028
  }
@@ -753,23 +1031,31 @@ export class PencilFigure extends HTMLElement {
753
1031
  };
754
1032
 
755
1033
  #pointerEnd = (e) => {
756
- if (this.#canvas.hasPointerCapture(e.pointerId)) this.#canvas.releasePointerCapture(e.pointerId);
1034
+ if (!this.#stage.hasPointerCapture(e.pointerId)) return;
1035
+ this.#stage.releasePointerCapture(e.pointerId);
757
1036
  this.#player?.release();
758
- this.#canvas.style.cursor = '';
1037
+ this.#stage.style.cursor = '';
759
1038
  };
760
1039
 
761
1040
  #drag(x, y) {
762
1041
  this.#moved(this.#player.drag(this.#time, x, y));
763
1042
  }
764
1043
 
765
- /** A handle set this param in the player: hold it here too, draw, and tell the page. */
766
- #moved(name) {
767
- if (!name) return;
768
- const value = this.#player.value(name, this.#time);
769
- this.#held.delete(name);
770
- this.#held.set(name, value);
1044
+ /**
1045
+ * A handle set these params in the player, one or two: hold them here too, draw, and tell the
1046
+ * page. Two are held together, so neither hands the other back.
1047
+ */
1048
+ #moved(names) {
1049
+ if (!names?.length) return;
1050
+ const values = Object.fromEntries(names.map((name) => [name, this.#player.value(name, this.#time)]));
1051
+ this.#reclaim(names);
1052
+ for (const name of names) {
1053
+ this.#held.delete(name);
1054
+ this.#held.set(name, values[name]);
1055
+ }
771
1056
  this.#invalidate();
772
- this.dispatchEvent(new CustomEvent('input', { bubbles: true, detail: { name, value } }));
1057
+ const [name] = names;
1058
+ this.dispatchEvent(new CustomEvent('input', { bubbles: true, detail: { name, value: values[name], values } }));
773
1059
  }
774
1060
 
775
1061
  // ---- Keys: every handle can be tabbed to and moved, and beats stepped ----
@@ -783,9 +1069,10 @@ export class PencilFigure extends HTMLElement {
783
1069
  /**
784
1070
  * Makes what a reader can do with the figure reachable without a pointer, once it's known.
785
1071
  * Each handle gets something to focus, named for its mark, that says its param's value as a
786
- * slider does. A figure with beats becomes a tab stop itself, unless the page has said where
787
- * it is in the tab order, and a figure with either is a group, so its name is read. One with
788
- * neither is an image.
1072
+ * slider does. One that sets two params is a 2D slider, as React Aria's color area calls its
1073
+ * own, and says both. A figure with beats becomes a tab stop itself, unless the page has said
1074
+ * where it is in the tab order, and a figure with either is a group, so its name is read. One
1075
+ * with neither is an image.
789
1076
  */
790
1077
  #operable() {
791
1078
  const handles = this.#info.handles ?? [];
@@ -798,6 +1085,7 @@ export class PencilFigure extends HTMLElement {
798
1085
  el.setAttribute('part', 'handle');
799
1086
  el.setAttribute('role', 'slider');
800
1087
  el.setAttribute('aria-label', handle.mark);
1088
+ if (handle.params.length > 1) el.setAttribute('aria-roledescription', '2D slider');
801
1089
  el.tabIndex = 0;
802
1090
  el.hidden = true;
803
1091
  el.addEventListener('keydown', (e) => this.#handleKey(e, index));
@@ -828,6 +1116,8 @@ export class PencilFigure extends HTMLElement {
828
1116
  return;
829
1117
  }
830
1118
  const scale = this.#canvas.clientWidth / this.#canvas.width;
1119
+ const [width, height] = [this.#canvas.clientWidth, this.#canvas.clientHeight];
1120
+ const panels = this.#info.panels ?? [];
831
1121
  this.#handles.forEach((el, i) => {
832
1122
  const [x, y] = [places[2 * i] * scale, places[2 * i + 1] * scale];
833
1123
  const there = Number.isFinite(x) && Number.isFinite(y);
@@ -835,16 +1125,26 @@ export class PencilFigure extends HTMLElement {
835
1125
  if (!there) return;
836
1126
  const moved = `translate(${x.toFixed(2)}px, ${y.toFixed(2)}px)`;
837
1127
  if (el.style.transform !== moved) el.style.transform = moved;
838
- const param = this.#info.handles[i].param;
839
- const value = this.#valueAt(param, this.#time);
840
- const [min, max] = this.range(param);
841
- const said = [min, max, value].join(' ');
1128
+ // A handle can't be grabbed outside its panel, so its reach stops there, and a touch past
1129
+ // it scrolls the page. The figure's own edge already stops it.
1130
+ if (panels.length > 1) {
1131
+ const [px, py, pw, ph] = panels[this.#info.handles[i].panel]?.rect ?? [0, 0, 1, 1];
1132
+ const cut = [py * height - (y - REACH), x + REACH - (px + pw) * width, y + REACH - (py + ph) * height, px * width - (x - REACH)];
1133
+ const reach = cut.some((c) => c > 0) ? `inset(${cut.map((c) => `${Math.max(0, c).toFixed(1)}px`).join(' ')})` : 'none';
1134
+ if (el.style.getPropertyValue('--reach') !== reach) el.style.setProperty('--reach', reach);
1135
+ }
1136
+ // A slider has one number, so a handle that sets two gives its first as the number, and
1137
+ // says both in its text, which is what a screen reader reads.
1138
+ const params = this.#info.handles[i].params;
1139
+ const values = params.map((param) => this.#valueAt(param, this.#time));
1140
+ const [min, max] = this.range(params[0]);
1141
+ const said = [min, max, ...values].join(' ');
842
1142
  if (el.dataset.said === said) return;
843
1143
  el.dataset.said = said;
844
1144
  el.setAttribute('aria-valuemin', String(min));
845
1145
  el.setAttribute('aria-valuemax', String(max));
846
- el.setAttribute('aria-valuenow', String(value));
847
- el.setAttribute('aria-valuetext', `${param} = ${this.#format(param, value)}`);
1146
+ el.setAttribute('aria-valuenow', String(values[0]));
1147
+ el.setAttribute('aria-valuetext', params.map((param, k) => `${param} = ${this.#format(param, values[k])}`).join(', '));
848
1148
  });
849
1149
  }
850
1150
 
@@ -857,18 +1157,23 @@ export class PencilFigure extends HTMLElement {
857
1157
 
858
1158
  /**
859
1159
  * A key on a focused handle. An arrow moves it that way on the page, a hundredth of the
860
- * figure's shorter side, or a tenth with Shift, through the handle's own inverse, as a drag
861
- * that far would. A param with steps goes to its next one that way. Home and End take the
862
- * param to the ends of its range, and Page Up and Page Down move it a tenth of the range.
1160
+ * figure's shorter side, or a tenth with Shift, through the handle's own inverses, as a drag
1161
+ * that far would. A param with steps goes to its next one that way. On a handle that sets one
1162
+ * param, Home and End take it to the ends of its range, and Page Up and Page Down move it a
1163
+ * tenth of the range. A handle that sets two has no one range to go to the end of, so those
1164
+ * keys are the long moves on the page, as in a 2D slider: Home and End left and right, Page
1165
+ * Up and Page Down up and down, as far as Shift and an arrow.
863
1166
  */
864
1167
  #handleKey(e, index) {
865
1168
  if (!this.#player || e.altKey || e.ctrlKey || e.metaKey) return;
866
- const way = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[e.key];
867
- const param = this.#info.handles[index].param;
1169
+ const params = this.#info.handles[index].params;
1170
+ const [param] = params;
1171
+ const long = params.length > 1 && { Home: [-1, 0], End: [1, 0], PageUp: [0, -1], PageDown: [0, 1] }[e.key];
1172
+ const way = long || { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[e.key];
868
1173
  try {
869
1174
  if (way) {
870
1175
  const { width, height } = this.#canvas;
871
- const step = Math.max(Math.min(width, height) / 100, 2 * (window.devicePixelRatio || 1)) * (e.shiftKey ? 10 : 1);
1176
+ const step = Math.max(Math.min(width, height) / 100, 2 * (window.devicePixelRatio || 1)) * (e.shiftKey || long ? 10 : 1);
872
1177
  this.pause();
873
1178
  this.#moved(this.#player.nudge(this.#time, index, way[0] * step, way[1] * step));
874
1179
  } else if (['Home', 'End', 'PageUp', 'PageDown'].includes(e.key)) {
@@ -877,7 +1182,7 @@ export class PencilFigure extends HTMLElement {
877
1182
  const to = { Home: min, End: max, PageUp: now + (max - min) / 10, PageDown: now - (max - min) / 10 }[e.key];
878
1183
  this.pause();
879
1184
  this.#player.set_param(param, to);
880
- this.#moved(param);
1185
+ this.#moved([param]);
881
1186
  } else {
882
1187
  return;
883
1188
  }
@@ -950,6 +1255,10 @@ export class PencilFigure extends HTMLElement {
950
1255
  try {
951
1256
  this.#layer.update(JSON.parse(this.#player.draw(this.#time, dpr)));
952
1257
  } catch (error) {
1258
+ if (this.#recoverable(error)) {
1259
+ this.#recover(error);
1260
+ return;
1261
+ }
953
1262
  this.pause();
954
1263
  this.dispatchEvent(new CustomEvent('error', { detail: { error, time: this.#time, fresh } }));
955
1264
  return;
@@ -958,7 +1267,12 @@ export class PencilFigure extends HTMLElement {
958
1267
  this.#drawn = true;
959
1268
  this.#wait();
960
1269
  }
1270
+ this.#healthy = true;
961
1271
  this.#placeHandles();
1272
+ if (this.#reported) {
1273
+ this.#reported = false;
1274
+ this.dispatchEvent(new Event('recover'));
1275
+ }
962
1276
  this.dispatchEvent(new CustomEvent('draw', { detail: { time: this.#time, fresh } }));
963
1277
  }
964
1278
 
@@ -980,8 +1294,15 @@ export class PencilFigure extends HTMLElement {
980
1294
  return;
981
1295
  }
982
1296
  const [width, height] = [this.#canvas.width, this.#canvas.height];
983
- this.#player.resize(...match(this.#canvas));
984
- const em = this.#setEm();
1297
+ let em;
1298
+ try {
1299
+ this.#player.resize(...match(this.#canvas));
1300
+ em = this.#setEm();
1301
+ } catch (error) {
1302
+ if (!this.#recoverable(error)) throw error;
1303
+ this.#recover(error);
1304
+ return;
1305
+ }
985
1306
  if (em || this.#canvas.width !== width || this.#canvas.height !== height) {
986
1307
  this.#paint();
987
1308
  this.dispatchEvent(new CustomEvent('resize', { detail: { em: this.#emPx } }));