@pencil-lang/figure 0.0.5 → 0.0.7

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
@@ -42,20 +42,39 @@
42
42
  // within a handle's reach drags it and doesn't scroll the page; anywhere else on the figure the
43
43
  // page scrolls and zooms as it would over an image. Nothing in the figure is text to select, and a
44
44
  // drag never selects the page's. The element does all this itself: a page needs no CSS for it.
45
+ // A figure's shaders are compiled while the one before it, or its poster, stays on screen: on
46
+ // WebGPU the browser does that off the thread that composites the page, so the page doesn't stop.
47
+ // A figure asked for after another that's still compiling takes its place. Its handles and keys
48
+ // wait for it too.
45
49
  // A browser can lose the GPU under a figure, after sleep or when its GPU process restarts. The
46
50
  // figure then starts its GPU again, keeping its sources, time, held params and whether it's
47
51
  // paused, and shows its poster meanwhile. It tries at once, after a second and after five, then
48
52
  // says `error` (with `detail.gpu`), and tries once more each time the page is shown.
49
- // Events: `load` when a figure is compiled, `draw` after each frame drawn, `resize` when its drawn
50
- // size or its em changes (its `detail.em`, in CSS pixels), `input` when a reader
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.
53
+ // `controls` asks for the default controls, as `<video controls>` does: play and time when anything
54
+ // follows time, beat stepping with its caption, a control for each param a handle doesn't set, and
55
+ // the readouts. They're `<pencil-controls slot="controls">`, a child whose shadow root holds them,
56
+ // styled through `::part` and custom properties (`controls.js`). A build writes it into the page,
57
+ // with every size reserved, and disabled until the figure loads (the Astro component does); a page
58
+ // that wrote none gets one when the figure loads. Without the attribute they're hidden, and what a
59
+ // page put in `<pencil-controls>` stays, as `<video controls>` does. A page with its own fills the `controls` slot
60
+ // with inputs and outputs marked `data-param="q"` or `data-readout="ratio"`, and the element sets
61
+ // their ranges, steps and values and follows them each frame (`wiring.js`), with or without the
62
+ // attribute. `readouts` is what the readouts say this frame.
63
+ // Events: `load` when a figure is compiled and its shaders are ready, `draw` after each frame
64
+ // drawn, `resize` when its drawn size or its em changes (its `detail.em`, in CSS pixels), `input`
65
+ // when a reader drags a param (its `detail.name` and `detail.value`, and `detail.values`, every
66
+ // param that one move set, by name: two for a point dragged in two dimensions), `play` and `pause`,
67
+ // `error` (its `detail.error`) when one can't load or draw, and `recover` when one that said
68
+ // `error` because it lost its GPU draws again. An `error` for a new figure's shaders, which the GPU
69
+ // couldn't make, has `detail.kept`: `true` when the figure before stays on screen, and `false` when
70
+ // the player had none, as for the first figure, or after a new player started, which then shows
71
+ // the figure that drew before, if there was one.
55
72
  import { Player, let_go, figure_size, figure_size_compiled, ready, isReady, gather, ahead } from './host.js';
56
73
  import { LABEL_CSS, LabelLayer, fonts } from './labels.js';
57
74
  import { match } from './fit.js';
58
75
  import { follow, settle, unfollow } from './scheme.js';
76
+ import { CONTROLS_CSS, hasControls, markup, shape } from './controls.js';
77
+ import { Wiring, identity } from './wiring.js';
59
78
 
60
79
  // How long time runs before it loops, for a figure that declares no `duration`.
61
80
  const LOOP = 10;
@@ -100,14 +119,26 @@ slot { display: none; }
100
119
  .handles { position: absolute; inset: 0; pointer-events: none; }
101
120
  .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
121
  .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. */
122
+ /* With no figure on the GPU, as while the poster shows or a new player compiles the figure's
123
+ shaders, a handle can't be dragged, so it takes no pointer, and a touch on it scrolls the page.
124
+ The keys still find it. */
105
125
  .stage:not(.live) .handle { pointer-events: none; touch-action: auto; }
106
126
  .handle:focus-visible { outline: 2px solid var(--pencil-focus, currentColor); outline-offset: 1px; box-shadow: 0 0 0 2px var(--pencil-focus-halo, Canvas); }
107
127
  .handle[hidden] { display: none; }
108
128
  .said { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
129
+ slot[name='controls'] { display: block; }
109
130
  ${LABEL_CSS}`;
110
131
 
132
+ /** The defaults' styles, made once and shared by every figure's controls the element writes. */
133
+ let controlsSheet = null;
134
+ const controlsStyles = () => {
135
+ if (!controlsSheet && typeof CSSStyleSheet !== 'undefined' && 'replaceSync' in CSSStyleSheet.prototype) {
136
+ controlsSheet = new CSSStyleSheet();
137
+ controlsSheet.replaceSync(CONTROLS_CSS);
138
+ }
139
+ return controlsSheet;
140
+ };
141
+
111
142
  /** `a: 0.5; beat: 2` as pairs. */
112
143
  const parseParams = (text) =>
113
144
  (text ?? '')
@@ -117,7 +148,7 @@ const parseParams = (text) =>
117
148
  .map(([name, value]) => [name, Number(value)]);
118
149
 
119
150
  export class PencilFigure extends HTMLElement {
120
- static observedAttributes = ['src', 'sheets', 'compiled', 'params'];
151
+ static observedAttributes = ['src', 'sheets', 'compiled', 'params', 'controls'];
121
152
 
122
153
  /** Resolves once the WASM core is ready, after which `load` checks sources at once. */
123
154
  static get ready() {
@@ -138,7 +169,12 @@ export class PencilFigure extends HTMLElement {
138
169
  #player = null;
139
170
  #starting = false;
140
171
  #generation = 0;
141
- #sources = null; // { doc, sheets, names, files } or { compiled }, loaded or waiting for the GPU
172
+ #sources = null; // { doc, sheets, names, files } or { compiled }: the figure last put on a player
173
+ #announced = null; // the sources the last `load` was for: a start again shows them without news
174
+ #wanted = null; // sources a load asked for and that aren't shown yet: a new player starts from them
175
+ #promised = null; // `{ sources, resolve }`, the promise a load gave that's still waiting
176
+ #loads = 0; // each load the player is asked for, in turn: only the last one asked for is shown
177
+ #installed = false; // whether the player has a figure to draw
142
178
  #drawn = false; // whether a frame has been drawn since the canvas was made
143
179
  #children = null; // watches for a poster or a <source> arriving
144
180
  #media = []; // each <source>'s media query, and what's listening to it
@@ -176,6 +212,9 @@ export class PencilFigure extends HTMLElement {
176
212
  #restoreTimer = 0;
177
213
  #startPending = false;
178
214
  #lose = null; // the canvas's `WEBGL_lose_context`, which a lost context doesn't give
215
+ #controlsSlot; // where the controls go, below the figure
216
+ #wiring = new Wiring(this);
217
+ #readouts = null; // what the readouts say, and at which time, worked out once a frame
179
218
 
180
219
  constructor() {
181
220
  super();
@@ -200,6 +239,11 @@ export class PencilFigure extends HTMLElement {
200
239
  this.#said.className = 'said';
201
240
  this.#said.setAttribute('aria-live', 'polite');
202
241
  this.#stage.append(this.#handleLayer, this.#said);
242
+ // The controls, the defaults or a page's own, below the figure.
243
+ this.#controlsSlot = document.createElement('slot');
244
+ this.#controlsSlot.name = 'controls';
245
+ this.#controlsSlot.addEventListener('slotchange', () => this.#wire());
246
+ root.append(this.#controlsSlot);
203
247
  // A press on the canvas or on a handle's reach comes here, and a grab captures the pointer.
204
248
  const stage = this.#stage;
205
249
  stage.addEventListener('pointerdown', this.#pointerDown);
@@ -221,9 +265,20 @@ export class PencilFigure extends HTMLElement {
221
265
 
222
266
  // ---- The poster and the sources ----
223
267
 
224
- /** Whether the element has a poster: any child that isn't a `<source>`, or a script. */
268
+ /** Whether the element has a poster: any child that isn't a `<source>`, a script, or in a slot,
269
+ * as its controls are. */
225
270
  #hasPoster() {
226
- return [...this.children].some((child) => child.localName !== 'source' && child.localName !== 'script');
271
+ return [...this.children].some(
272
+ (child) => child.localName !== 'source' && child.localName !== 'script' && !child.hasAttribute('slot'),
273
+ );
274
+ }
275
+
276
+ /** Whether a node is in the controls, which change each frame and say nothing of the figure. */
277
+ #inSlot(node) {
278
+ for (let at = node; at && at !== this; at = at.parentNode) {
279
+ if (at.parentNode === this && at.nodeType === 1 && at.hasAttribute('slot')) return true;
280
+ }
281
+ return false;
227
282
  }
228
283
 
229
284
  /** Shows the poster until a frame is drawn. */
@@ -286,7 +341,8 @@ export class PencilFigure extends HTMLElement {
286
341
  this.#resized.observe(this.#canvas);
287
342
  this.#resized.observe(this.#em);
288
343
  // Children can arrive after the element does, while the page is still being read.
289
- this.#children = new MutationObserver(() => {
344
+ this.#children = new MutationObserver((records) => {
345
+ if (records.every((record) => this.#inSlot(record.target))) return;
290
346
  // A `<source>` that has just arrived is answered too. What that changes comes back here
291
347
  // once, and then changes nothing.
292
348
  settle(this);
@@ -332,6 +388,9 @@ export class PencilFigure extends HTMLElement {
332
388
  attributeChangedCallback(name) {
333
389
  if (name === 'params') {
334
390
  this.#hold(parseParams(this.getAttribute('params')));
391
+ } else if (name === 'controls') {
392
+ // As `<video controls>`: without it the defaults are hidden, and what the page wrote stays.
393
+ if (this.#info) this.#controlsReady();
335
394
  } else {
336
395
  this.#refetch();
337
396
  }
@@ -380,20 +439,22 @@ export class PencilFigure extends HTMLElement {
380
439
  return;
381
440
  }
382
441
  this.#player = player;
442
+ this.#installed = false;
383
443
  this.#playerId = player.id;
384
444
  this.#backend = player.backend;
385
445
  this.#lose = player.backend === 'Gl' ? (this.#canvas.getContext('webgl2')?.getExtension('WEBGL_lose_context') ?? null) : null;
386
- this.#stage.classList.add('live');
387
446
  // A browser loses a GPU device after sleep or when its GPU process restarts, and says so.
388
447
  player.on_lost(() => {
389
448
  if (this.#player === player) this.#recover(new Error('GPU device lost'));
390
449
  });
391
450
  player.set_measure(this.#layer.measure);
392
451
  this.#setEm();
393
- if (this.#sources) {
452
+ const sources = this.#wanted ?? this.#sources;
453
+ if (sources) {
394
454
  try {
395
- this.#compile(this.#sources);
455
+ this.#compile(sources);
396
456
  } catch (error) {
457
+ this.#settle(sources, false);
397
458
  this.#fail(error);
398
459
  }
399
460
  }
@@ -407,7 +468,12 @@ export class PencilFigure extends HTMLElement {
407
468
  if (this.#tries && generation === this.#generation) {
408
469
  this.#starting = false;
409
470
  this.#recover(error);
410
- } else this.#fail(error);
471
+ } else {
472
+ // A load waiting on it hears now, and the next start, as when the figure is seen again,
473
+ // still begins from what it asked for.
474
+ this.#letDown();
475
+ this.#fail(error);
476
+ }
411
477
  } finally {
412
478
  if (generation === this.#generation) this.#starting = false;
413
479
  }
@@ -451,6 +517,7 @@ export class PencilFigure extends HTMLElement {
451
517
  if (wait === undefined) {
452
518
  this.#awaiting = true;
453
519
  this.#reported = true;
520
+ this.#letDown();
454
521
  this.dispatchEvent(new CustomEvent('error', { detail: { error, time: this.#time, fresh: false, gpu: true } }));
455
522
  } else if (wait === 0) {
456
523
  this.#restart();
@@ -504,6 +571,7 @@ export class PencilFigure extends HTMLElement {
504
571
  this.#stage.classList.remove('live');
505
572
  const player = this.#player;
506
573
  this.#player = null;
574
+ this.#installed = false;
507
575
  // The clock stops where it is, and runs again once there's a figure to draw.
508
576
  this.#sync();
509
577
  if (player) {
@@ -582,7 +650,14 @@ export class PencilFigure extends HTMLElement {
582
650
  this.#restoring = false;
583
651
  this.#startPending = false;
584
652
  clearTimeout(this.#restoreTimer);
653
+ // As a media element's `play()` does: what a load waits for isn't coming while it's out. A
654
+ // figure put back still shows what was asked for.
655
+ this.#letDown();
585
656
  this.#stage.classList.remove('live');
657
+ // The controls stop listening, and an open menu stops following its bar. A figure put back
658
+ // wires them again as it loads.
659
+ this.#wiring.detach();
660
+ this.#installed = false;
586
661
  if (this.#player) {
587
662
  this.#letGo(this.#player);
588
663
  this.#player = null;
@@ -675,57 +750,251 @@ export class PencilFigure extends HTMLElement {
675
750
  /** Compiles a figure from its `.pen` text and its sheets' texts, in order. A compile error is
676
751
  * thrown, with `line`, `col` and `sheet` saying where, and leaves the last figure on screen.
677
752
  * Before the GPU starts it's only checked, and shapes the element; it's drawn once the GPU is up.
678
- * Params held before keep their values if the new figure has them.
753
+ * Its shaders are compiled after, while the last figure stays on screen (`#compile`), and it
754
+ * resolves once it's shown, with `true`, however long the GPU takes to start, or with `false`
755
+ * when a figure asked for after it takes its place, or when it can't be made, which an `error`
756
+ * says. Params held before keep their values if the new figure has them.
679
757
  *
680
758
  * `used` is what `gather` read: the files these texts `use`. Without it, a `use "file"` is an
681
759
  * error. An error in a used file says so in `file`, its name. */
682
760
  load(doc, sheets = [], used = {}) {
683
761
  const sources = { doc, sheets, names: used.names ?? [], files: used.files ?? {} };
684
- if (this.#player) {
685
- this.#compile(sources);
686
- } else if (isReady()) {
687
- this.#shape(JSON.parse(figure_size(doc, sheets, sources.names, sources.files)));
688
- this.#sources = sources;
689
- } else {
690
- this.#sources = sources;
691
- }
762
+ if (this.#player) this.#compile(sources);
763
+ else if (isReady()) this.#shape(JSON.parse(figure_size(doc, sheets, sources.names, sources.files)));
764
+ return this.#ask(sources);
692
765
  }
693
766
 
694
767
  /** Loads a figure a build compiled (`pencil build`, `pencil compile`), from its bytes. One that
695
768
  * another build of Pencil wrote is an error that says to compile it again, and leaves the last
696
- * figure, or the poster, on screen. */
769
+ * figure, or the poster, on screen. It resolves as `load` does. */
697
770
  loadCompiled(bytes) {
698
771
  const sources = { compiled: bytes };
699
- if (this.#player) {
700
- this.#compile(sources);
701
- } else if (isReady()) {
702
- this.#shape(JSON.parse(figure_size_compiled(bytes)));
703
- this.#sources = sources;
704
- } else {
705
- this.#sources = sources;
706
- }
772
+ if (this.#player) this.#compile(sources);
773
+ else if (isReady()) this.#shape(JSON.parse(figure_size_compiled(bytes)));
774
+ return this.#ask(sources);
775
+ }
776
+
777
+ /** Waits for these sources to be shown, in place of whatever load was waiting before. */
778
+ #ask(sources) {
779
+ this.#letDown();
780
+ this.#wanted = sources;
781
+ return new Promise((resolve) => (this.#promised = { sources, resolve }));
782
+ }
783
+
784
+ /** These sources were shown, or can't be: what was asked for is done with, and its load hears. */
785
+ #settle(sources, shown) {
786
+ if (this.#wanted === sources) this.#wanted = null;
787
+ if (this.#promised?.sources !== sources) return;
788
+ const { resolve } = this.#promised;
789
+ this.#promised = null;
790
+ resolve(shown);
791
+ }
792
+
793
+ /** The load waiting hears it wasn't shown, now, though what it asked for may be later. */
794
+ #letDown() {
795
+ const promised = this.#promised;
796
+ this.#promised = null;
797
+ promised?.resolve(false);
798
+ }
799
+
800
+ /**
801
+ * Compiles sources for the player, which throws a compile error at once, and then waits for the
802
+ * GPU to compile their shaders, while the figure on screen, or the poster, stays and draws on.
803
+ * On WebGPU the browser compiles them off the thread that composites the page: made with
804
+ * `createRenderPipeline`, every frame on the page would wait for them. Only the last figure
805
+ * asked for is shown, and one that the GPU can't make is an `error`. One the GPU lost meanwhile
806
+ * is compiled again on the next player. `again` is for the figure that drew, shown again.
807
+ */
808
+ #compile(sources, again = false) {
809
+ const player = this.#player;
810
+ const pending = sources.compiled
811
+ ? player.prepare_compiled(sources.compiled)
812
+ : player.prepare(sources.doc, sources.sheets, sources.names, sources.files);
813
+ const ticket = ++this.#loads;
814
+ // Started again after losing its GPU, the figure the page heard of is no news. One that was
815
+ // still compiling is, as the first one is.
816
+ const quiet = (this.#quiet || again) && sources === this.#announced;
817
+ const current = () => player === this.#player && ticket === this.#loads;
818
+ pending.then(
819
+ (figure) => {
820
+ if (!current()) {
821
+ figure.free();
822
+ return;
823
+ }
824
+ try {
825
+ this.#show(player, figure, sources, quiet);
826
+ } catch (error) {
827
+ // A new player tries these sources again.
828
+ if (this.#recoverable(error)) return this.#recover(error);
829
+ this.#settle(sources, false);
830
+ this.#fail(error);
831
+ }
832
+ },
833
+ (error) => {
834
+ if (!current()) return;
835
+ if (this.#recoverable(error)) return this.#recover(error);
836
+ // What failed is the new figure. The one on screen stays, if the player has one.
837
+ const kept = this.#installed;
838
+ this.#settle(sources, false);
839
+ this.#fail(error, { fresh: true, kept });
840
+ // A new player has nothing on it yet: the figure that drew before comes back, unless the
841
+ // page asked for another as it heard.
842
+ if (kept || !this.#sources || this.#sources === sources || !current()) return;
843
+ try {
844
+ this.#compile(this.#sources, true);
845
+ } catch (error) {
846
+ this.#fail(error);
847
+ }
848
+ },
849
+ );
707
850
  }
708
851
 
709
- #compile(sources) {
710
- if (sources.compiled) this.#player.load_compiled(sources.compiled);
711
- else this.#player.load(sources.doc, sources.sheets, sources.names, sources.files);
852
+ /** Puts a figure the player prepared on screen, and everything that follows from it. */
853
+ #show(player, figure, sources, quiet) {
854
+ player.install(figure);
855
+ this.#installed = true;
712
856
  this.#sources = sources;
713
- const info = JSON.parse(this.#player.info());
857
+ // Its load hears before anything is dispatched, so a listener's own load can't take its place.
858
+ this.#settle(sources, true);
859
+ this.#stage.classList.add('live');
860
+ const info = JSON.parse(player.info());
714
861
  this.#info = info;
715
862
  this.#driven = new Set(info.timeDriven);
716
- this.#shape(info.size);
863
+ // Before its shape, which can draw a frame at once, with the params a reader holds.
717
864
  for (const [name, value] of this.#held) {
718
- if (info.params.some((p) => p.id === name)) this.#player.set_param(name, value);
865
+ if (info.params.some((p) => p.id === name)) player.set_param(name, value);
719
866
  else this.#held.delete(name);
720
867
  }
868
+ this.#shape(info.size);
721
869
  this.#retime();
722
870
  this.#operable();
871
+ this.#readouts = null;
872
+ this.#controlsReady();
723
873
  this.#fresh = true;
724
874
  this.#invalidate();
725
875
  this.#sync();
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'));
876
+ // Said, so a start again after this shows it without news.
877
+ this.#announced = sources;
878
+ if (!quiet) this.dispatchEvent(new Event('load'));
879
+ }
880
+
881
+ // ---- Controls ----
882
+
883
+ /** What's in the controls slot: a `<pencil-controls>` by its shadow root, and a page's own
884
+ * element as it is. */
885
+ #controlsRoots() {
886
+ return this.#controlsSlot
887
+ .assignedElements()
888
+ .map((el) => (el.localName === 'pencil-controls' && el.shadowRoot ? el.shadowRoot : el));
889
+ }
890
+
891
+ /** Listens to what's in the controls slot, and shows the figure in it, once there's a figure. */
892
+ #wire() {
893
+ this.#wiring.attach(this.#controlsRoots());
894
+ if (this.#info) this.#wiring.enable();
895
+ }
896
+
897
+ /**
898
+ * The figure has loaded: writes the default controls if the page asked for them and has none,
899
+ * or writes them again if they were made for another kind of figure, as after a reader picks
900
+ * another look, and turns them on. Controls a build wrote for this kind of figure are kept as
901
+ * they are, so nothing moves.
902
+ */
903
+ #controlsReady() {
904
+ const info = this.#info;
905
+ if (!info) return;
906
+ const asked = this.hasAttribute('controls');
907
+ const slotted = this.querySelectorAll(':scope > [slot="controls"]');
908
+ if (asked && slotted.length === 0 && hasControls(info)) {
909
+ const made = document.createElement('pencil-controls');
910
+ made.setAttribute('slot', 'controls');
911
+ made.attachShadow({ mode: 'open' });
912
+ this.#writeControls(made, info);
913
+ this.append(made);
914
+ }
915
+ for (const host of this.querySelectorAll(':scope > pencil-controls[slot="controls"]')) {
916
+ if (!asked) {
917
+ // What a page put in shows, and the defaults don't. One the page wrote without a shadow
918
+ // root of defaults, as the Astro component does without `controls`, is the page's alone.
919
+ if (host.shadowRoot && host.dataset.shape !== 'page') this.#writeControls(host, null);
920
+ host.hidden = host.children.length === 0;
921
+ continue;
922
+ }
923
+ // A declarative shadow root that wasn't read, as in HTML a script put in the page, isn't
924
+ // there: the element writes the defaults into one of its own.
925
+ const unread = !host.shadowRoot || host.shadowRoot.childElementCount === 0;
926
+ // Its template is left as a child, which isn't the page's own content.
927
+ if (unread) for (const left of host.querySelectorAll(':scope > template[shadowrootmode]')) left.remove();
928
+ if (!host.shadowRoot) host.attachShadow({ mode: 'open' });
929
+ if (unread || host.dataset.shape !== shape(info)) this.#writeControls(host, info);
930
+ // A figure with nothing to control, as another look can be, shows only what the page put in.
931
+ host.hidden = !hasControls(info) && host.children.length === 0;
932
+ }
933
+ this.#wiring.attach(this.#controlsRoots());
934
+ this.#wiring.enable();
935
+ }
936
+
937
+ /** Writes the defaults into a `<pencil-controls>`, as a build would for this figure as it stands,
938
+ * or with no `info`, only what the page put in it. */
939
+ #writeControls(host, info) {
940
+ const root = host.shadowRoot;
941
+ // A reader who was on a control is still on it afterwards, as one who picked a look with the
942
+ // keyboard: the same control, found by what it's for, and a menu that was open is open still.
943
+ const focused = root.activeElement ? identity(root.activeElement) : null;
944
+ // An open menu opens again where it was, before the focus goes back into it, so the focus
945
+ // doesn't scroll the page to wherever a menu not yet placed would be. The wiring places it
946
+ // again once it's attached.
947
+ const open = root.querySelector('[popover]:popover-open');
948
+ const placed = open?.getAttribute('style');
949
+ let html = '<div class="controls" part="controls"><div class="rest" part="rest"><slot></slot></div></div>';
950
+ if (info) {
951
+ let room = [];
952
+ try {
953
+ room = JSON.parse(this.#player.readout_room(this.#time));
954
+ } catch {}
955
+ const values = Object.fromEntries(info.params.map((p) => [p.id, this.value(p.id)]));
956
+ const ranges = Object.fromEntries(info.params.map((p) => [p.id, this.range(p.id)]));
957
+ const sized = { ...info, readouts: (info.readouts ?? []).map((r, i) => ({ ...r, room: room[i] })) };
958
+ html = markup({
959
+ info: sized,
960
+ moment: { time: this.#time, values, ranges, readouts: this.readouts },
961
+ paused: this.paused,
962
+ extra: host.children.length > 0,
963
+ });
964
+ }
965
+ const sheet = controlsStyles();
966
+ if (sheet) {
967
+ root.adoptedStyleSheets = [sheet];
968
+ root.innerHTML = html;
969
+ } else {
970
+ root.innerHTML = `<style>${CONTROLS_CSS}</style>${html}`;
971
+ }
972
+ host.dataset.shape = info ? shape(info) : 'page';
973
+ this.#wiring.forget();
974
+ if (open) {
975
+ const menu = root.querySelector('[popover]');
976
+ if (placed) menu?.setAttribute('style', placed);
977
+ try {
978
+ menu?.showPopover();
979
+ } catch {}
980
+ }
981
+ // Without scrolling: the control is where it was, and a menu's may be partly off the screen.
982
+ if (focused) root.querySelector(focused)?.focus({ preventScroll: true });
983
+ }
984
+
985
+ /** What each readout says this frame, `{ id, text, words, math, width, height, laid }`, in the
986
+ * order they're written: a readout is a label with no place, said beside the figure. Its layout
987
+ * is in ems, from the left and middle of its line (`readoutHtml` in `controls.js` sets one). */
988
+ get readouts() {
989
+ if (!this.#player || !this.#info?.readouts?.length) return [];
990
+ if (this.#readouts?.time !== this.#time) {
991
+ let said = [];
992
+ try {
993
+ said = JSON.parse(this.#player.readouts(this.#time));
994
+ } catch {}
995
+ this.#readouts = { time: this.#time, said };
996
+ }
997
+ return this.#readouts.said;
729
998
  }
730
999
 
731
1000
  /** Shapes the figure to its design size, so nothing moves as it loads. */
@@ -740,8 +1009,8 @@ export class PencilFigure extends HTMLElement {
740
1009
  return `pencil ${this.id || (src ? src.split('/').pop() : 'figure')}`;
741
1010
  }
742
1011
 
743
- #fail(error) {
744
- this.dispatchEvent(new CustomEvent('error', { detail: { error, time: this.#time, fresh: this.#fresh } }));
1012
+ #fail(error, detail = {}) {
1013
+ this.dispatchEvent(new CustomEvent('error', { detail: { error, time: this.#time, fresh: this.#fresh, ...detail } }));
745
1014
  }
746
1015
 
747
1016
  // ---- Time ----
@@ -772,6 +1041,7 @@ export class PencilFigure extends HTMLElement {
772
1041
  /** Plays from where it is. Each param time drives is handed back to time, carrying on from
773
1042
  * where the reader left the last one they moved. */
774
1043
  play() {
1044
+ this.#readouts = null;
775
1045
  const moved = [...this.#held.keys()].filter((name) => this.#driven.has(name)).pop();
776
1046
  if (moved && this.#player) {
777
1047
  try {
@@ -783,6 +1053,7 @@ export class PencilFigure extends HTMLElement {
783
1053
  this.#paused = false;
784
1054
  this.#sync();
785
1055
  this.#invalidate();
1056
+ this.#wiring.paintPlay();
786
1057
  if (was !== false) this.dispatchEvent(new Event('play'));
787
1058
  }
788
1059
 
@@ -790,6 +1061,7 @@ export class PencilFigure extends HTMLElement {
790
1061
  const was = this.#paused;
791
1062
  this.#paused = true;
792
1063
  this.#sync();
1064
+ this.#wiring.paintPlay();
793
1065
  if (was !== true) this.dispatchEvent(new Event('pause'));
794
1066
  }
795
1067
 
@@ -830,7 +1102,7 @@ export class PencilFigure extends HTMLElement {
830
1102
  #sync() {
831
1103
  const clock = this.#clock;
832
1104
  if (!clock) return;
833
- const run = this.#paused === false && this.#visible && !!this.#player && !!this.#info?.usesTime;
1105
+ const run = this.#paused === false && this.#visible && this.#installed && !!this.#info?.usesTime;
834
1106
  const running = clock.playState === 'running';
835
1107
  if (run && !running) {
836
1108
  clock.currentTime = this.#time * 1000;
@@ -858,6 +1130,8 @@ export class PencilFigure extends HTMLElement {
858
1130
  this.hold('beat', target);
859
1131
  return;
860
1132
  }
1133
+ // A player started again has no figure to find a beat's time in until it's in.
1134
+ if (!this.#installed) return;
861
1135
  // A beat that follows time is taken to only count up, so the first moment it reaches the
862
1136
  // target is found by halving. Sampling, as `time_for` does, lands just short of it.
863
1137
  let [lo, hi] = [0, this.duration];
@@ -918,6 +1192,7 @@ export class PencilFigure extends HTMLElement {
918
1192
 
919
1193
  /** Holds params together: none of them hands another back. */
920
1194
  #hold(pairs) {
1195
+ this.#readouts = null;
921
1196
  this.#reclaim(pairs.map(([name]) => name));
922
1197
  for (const [name, value] of pairs) {
923
1198
  this.#held.delete(name);
@@ -1004,7 +1279,7 @@ export class PencilFigure extends HTMLElement {
1004
1279
 
1005
1280
  #pointerDown = (e) => {
1006
1281
  // One pointer drags at a time, and only with the main button.
1007
- if (!this.#player || !e.isPrimary || e.button !== 0) return;
1282
+ if (!this.#installed || !e.isPrimary || e.button !== 0) return;
1008
1283
  const [x, y] = this.#device(e);
1009
1284
  try {
1010
1285
  if (!this.#player.grab(this.#time, x, y, REACH * (window.devicePixelRatio || 1))) return;
@@ -1018,7 +1293,7 @@ export class PencilFigure extends HTMLElement {
1018
1293
  };
1019
1294
 
1020
1295
  #pointerMove = (e) => {
1021
- if (!this.#player) return;
1296
+ if (!this.#installed) return;
1022
1297
  const [x, y] = this.#device(e);
1023
1298
  try {
1024
1299
  if (!this.#stage.hasPointerCapture(e.pointerId)) {
@@ -1165,7 +1440,7 @@ export class PencilFigure extends HTMLElement {
1165
1440
  * Up and Page Down up and down, as far as Shift and an arrow.
1166
1441
  */
1167
1442
  #handleKey(e, index) {
1168
- if (!this.#player || e.altKey || e.ctrlKey || e.metaKey) return;
1443
+ if (!this.#installed || e.altKey || e.ctrlKey || e.metaKey) return;
1169
1444
  const params = this.#info.handles[index].params;
1170
1445
  const [param] = params;
1171
1446
  const long = params.length > 1 && { Home: [-1, 0], End: [1, 0], PageUp: [0, -1], PageDown: [0, 1] }[e.key];
@@ -1197,7 +1472,9 @@ export class PencilFigure extends HTMLElement {
1197
1472
  /** A key on the figure itself: ← and → step its beats, and Home and End go to the first and
1198
1473
  * last. What it came to is said for a screen reader, with the beat's caption. */
1199
1474
  #key = (e) => {
1200
- if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || !this.#player || !this.#steps()) return;
1475
+ // Keys in the controls are theirs: an arrow on a slider moves the slider.
1476
+ if (e.target !== this) return;
1477
+ if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || !this.#installed || !this.#steps()) return;
1201
1478
  const range = this.#info.params.find((p) => p.id === 'beat');
1202
1479
  if (e.key === 'ArrowRight') this.step(1);
1203
1480
  else if (e.key === 'ArrowLeft') this.step(-1);
@@ -1212,6 +1489,8 @@ export class PencilFigure extends HTMLElement {
1212
1489
  const timed = (this.#info.beatLengths?.length ?? 0) > 0;
1213
1490
  const n = Math.round(timed ? beat : beat + 1);
1214
1491
  const caption = beats[n - 1] ?? '';
1492
+ // Controls that say each new beat say this one, and a beat is said once.
1493
+ if (this.#wiring.speaks) return;
1215
1494
  this.#said.textContent = n < 1 ? 'Start' : `Step ${n} of ${beats.length}${caption ? `: ${caption}` : ''}`;
1216
1495
  };
1217
1496
 
@@ -1246,7 +1525,8 @@ export class PencilFigure extends HTMLElement {
1246
1525
 
1247
1526
  #paint() {
1248
1527
  this.#dirty = false;
1249
- if (!this.#player || !this.#info) return;
1528
+ // A player started again keeps the figure's info, and has nothing to draw until it's in.
1529
+ if (!this.#player || !this.#info || !this.#installed) return;
1250
1530
  const fresh = this.#fresh;
1251
1531
  this.#fresh = false;
1252
1532
  // Zooming or moving to another screen changes it, so it's read each frame.
@@ -1269,6 +1549,8 @@ export class PencilFigure extends HTMLElement {
1269
1549
  }
1270
1550
  this.#healthy = true;
1271
1551
  this.#placeHandles();
1552
+ this.#readouts = null;
1553
+ this.#wiring.read();
1272
1554
  if (this.#reported) {
1273
1555
  this.#reported = false;
1274
1556
  this.dispatchEvent(new Event('recover'));
package/src/host.js CHANGED
@@ -7,6 +7,11 @@
7
7
  // import { ready, Player, gather } from '@pencil-lang/figure/host';
8
8
  // await ready();
9
9
  // const player = await Player.create(canvas, false);
10
+ // player.install(await player.prepare(doc, sheets, names, files));
11
+ //
12
+ // `prepare` throws a compile error at once, and resolves once the GPU has compiled the figure's
13
+ // shaders, or rejects with its error. On WebGPU the browser does that off the thread that
14
+ // composites the page. The player draws on meanwhile, and `install` puts the new figure in.
10
15
  //
11
16
  // `scripts/build-web.sh` writes `../pkg`, which isn't checked in.
12
17
  import init from '../pkg/pencil_web.js';