@pencil-lang/figure 0.0.5 → 0.0.6

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
@@ -46,6 +46,16 @@
46
46
  // figure then starts its GPU again, keeping its sources, time, held params and whether it's
47
47
  // paused, and shows its poster meanwhile. It tries at once, after a second and after five, then
48
48
  // says `error` (with `detail.gpu`), and tries once more each time the page is shown.
49
+ // `controls` asks for the default controls, as `<video controls>` does: play and time when anything
50
+ // follows time, beat stepping with its caption, a control for each param a handle doesn't set, and
51
+ // the readouts. They're `<pencil-controls slot="controls">`, a child whose shadow root holds them,
52
+ // styled through `::part` and custom properties (`controls.js`). A build writes it into the page,
53
+ // with every size reserved, and disabled until the figure loads (the Astro component does); a page
54
+ // that wrote none gets one when the figure loads. Without the attribute they're hidden, and what a
55
+ // page put in `<pencil-controls>` stays, as `<video controls>` does. A page with its own fills the `controls` slot
56
+ // with inputs and outputs marked `data-param="q"` or `data-readout="ratio"`, and the element sets
57
+ // their ranges, steps and values and follows them each frame (`wiring.js`), with or without the
58
+ // attribute. `readouts` is what the readouts say this frame.
49
59
  // Events: `load` when a figure is compiled, `draw` after each frame drawn, `resize` when its drawn
50
60
  // size or its em changes (its `detail.em`, in CSS pixels), `input` when a reader
51
61
  // drags a param (its `detail.name` and `detail.value`, and `detail.values`, every param that one
@@ -56,6 +66,8 @@ import { Player, let_go, figure_size, figure_size_compiled, ready, isReady, gath
56
66
  import { LABEL_CSS, LabelLayer, fonts } from './labels.js';
57
67
  import { match } from './fit.js';
58
68
  import { follow, settle, unfollow } from './scheme.js';
69
+ import { CONTROLS_CSS, hasControls, markup, shape } from './controls.js';
70
+ import { Wiring, identity } from './wiring.js';
59
71
 
60
72
  // How long time runs before it loops, for a figure that declares no `duration`.
61
73
  const LOOP = 10;
@@ -106,8 +118,19 @@ slot { display: none; }
106
118
  .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
119
  .handle[hidden] { display: none; }
108
120
  .said { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
121
+ slot[name='controls'] { display: block; }
109
122
  ${LABEL_CSS}`;
110
123
 
124
+ /** The defaults' styles, made once and shared by every figure's controls the element writes. */
125
+ let controlsSheet = null;
126
+ const controlsStyles = () => {
127
+ if (!controlsSheet && typeof CSSStyleSheet !== 'undefined' && 'replaceSync' in CSSStyleSheet.prototype) {
128
+ controlsSheet = new CSSStyleSheet();
129
+ controlsSheet.replaceSync(CONTROLS_CSS);
130
+ }
131
+ return controlsSheet;
132
+ };
133
+
111
134
  /** `a: 0.5; beat: 2` as pairs. */
112
135
  const parseParams = (text) =>
113
136
  (text ?? '')
@@ -117,7 +140,7 @@ const parseParams = (text) =>
117
140
  .map(([name, value]) => [name, Number(value)]);
118
141
 
119
142
  export class PencilFigure extends HTMLElement {
120
- static observedAttributes = ['src', 'sheets', 'compiled', 'params'];
143
+ static observedAttributes = ['src', 'sheets', 'compiled', 'params', 'controls'];
121
144
 
122
145
  /** Resolves once the WASM core is ready, after which `load` checks sources at once. */
123
146
  static get ready() {
@@ -176,6 +199,9 @@ export class PencilFigure extends HTMLElement {
176
199
  #restoreTimer = 0;
177
200
  #startPending = false;
178
201
  #lose = null; // the canvas's `WEBGL_lose_context`, which a lost context doesn't give
202
+ #controlsSlot; // where the controls go, below the figure
203
+ #wiring = new Wiring(this);
204
+ #readouts = null; // what the readouts say, and at which time, worked out once a frame
179
205
 
180
206
  constructor() {
181
207
  super();
@@ -200,6 +226,11 @@ export class PencilFigure extends HTMLElement {
200
226
  this.#said.className = 'said';
201
227
  this.#said.setAttribute('aria-live', 'polite');
202
228
  this.#stage.append(this.#handleLayer, this.#said);
229
+ // The controls, the defaults or a page's own, below the figure.
230
+ this.#controlsSlot = document.createElement('slot');
231
+ this.#controlsSlot.name = 'controls';
232
+ this.#controlsSlot.addEventListener('slotchange', () => this.#wire());
233
+ root.append(this.#controlsSlot);
203
234
  // A press on the canvas or on a handle's reach comes here, and a grab captures the pointer.
204
235
  const stage = this.#stage;
205
236
  stage.addEventListener('pointerdown', this.#pointerDown);
@@ -221,9 +252,20 @@ export class PencilFigure extends HTMLElement {
221
252
 
222
253
  // ---- The poster and the sources ----
223
254
 
224
- /** Whether the element has a poster: any child that isn't a `<source>`, or a script. */
255
+ /** Whether the element has a poster: any child that isn't a `<source>`, a script, or in a slot,
256
+ * as its controls are. */
225
257
  #hasPoster() {
226
- return [...this.children].some((child) => child.localName !== 'source' && child.localName !== 'script');
258
+ return [...this.children].some(
259
+ (child) => child.localName !== 'source' && child.localName !== 'script' && !child.hasAttribute('slot'),
260
+ );
261
+ }
262
+
263
+ /** Whether a node is in the controls, which change each frame and say nothing of the figure. */
264
+ #inSlot(node) {
265
+ for (let at = node; at && at !== this; at = at.parentNode) {
266
+ if (at.parentNode === this && at.nodeType === 1 && at.hasAttribute('slot')) return true;
267
+ }
268
+ return false;
227
269
  }
228
270
 
229
271
  /** Shows the poster until a frame is drawn. */
@@ -286,7 +328,8 @@ export class PencilFigure extends HTMLElement {
286
328
  this.#resized.observe(this.#canvas);
287
329
  this.#resized.observe(this.#em);
288
330
  // Children can arrive after the element does, while the page is still being read.
289
- this.#children = new MutationObserver(() => {
331
+ this.#children = new MutationObserver((records) => {
332
+ if (records.every((record) => this.#inSlot(record.target))) return;
290
333
  // A `<source>` that has just arrived is answered too. What that changes comes back here
291
334
  // once, and then changes nothing.
292
335
  settle(this);
@@ -332,6 +375,9 @@ export class PencilFigure extends HTMLElement {
332
375
  attributeChangedCallback(name) {
333
376
  if (name === 'params') {
334
377
  this.#hold(parseParams(this.getAttribute('params')));
378
+ } else if (name === 'controls') {
379
+ // As `<video controls>`: without it the defaults are hidden, and what the page wrote stays.
380
+ if (this.#info) this.#controlsReady();
335
381
  } else {
336
382
  this.#refetch();
337
383
  }
@@ -720,6 +766,8 @@ export class PencilFigure extends HTMLElement {
720
766
  }
721
767
  this.#retime();
722
768
  this.#operable();
769
+ this.#readouts = null;
770
+ this.#controlsReady();
723
771
  this.#fresh = true;
724
772
  this.#invalidate();
725
773
  this.#sync();
@@ -728,6 +776,118 @@ export class PencilFigure extends HTMLElement {
728
776
  else this.dispatchEvent(new Event('load'));
729
777
  }
730
778
 
779
+ // ---- Controls ----
780
+
781
+ /** What's in the controls slot: a `<pencil-controls>` by its shadow root, and a page's own
782
+ * element as it is. */
783
+ #controlsRoots() {
784
+ return this.#controlsSlot
785
+ .assignedElements()
786
+ .map((el) => (el.localName === 'pencil-controls' && el.shadowRoot ? el.shadowRoot : el));
787
+ }
788
+
789
+ /** Listens to what's in the controls slot, and shows the figure in it, once there's a figure. */
790
+ #wire() {
791
+ this.#wiring.attach(this.#controlsRoots());
792
+ if (this.#info) this.#wiring.enable();
793
+ }
794
+
795
+ /**
796
+ * The figure has loaded: writes the default controls if the page asked for them and has none,
797
+ * or writes them again if they were made for another kind of figure, as after a reader picks
798
+ * another look, and turns them on. Controls a build wrote for this kind of figure are kept as
799
+ * they are, so nothing moves.
800
+ */
801
+ #controlsReady() {
802
+ const info = this.#info;
803
+ if (!info) return;
804
+ const asked = this.hasAttribute('controls');
805
+ const slotted = this.querySelectorAll(':scope > [slot="controls"]');
806
+ if (asked && slotted.length === 0 && hasControls(info)) {
807
+ const made = document.createElement('pencil-controls');
808
+ made.setAttribute('slot', 'controls');
809
+ made.attachShadow({ mode: 'open' });
810
+ this.#writeControls(made, info);
811
+ this.append(made);
812
+ }
813
+ for (const host of this.querySelectorAll(':scope > pencil-controls[slot="controls"]')) {
814
+ if (!asked) {
815
+ // What a page put in shows, and the defaults don't. One the page wrote without a shadow
816
+ // root of defaults, as the Astro component does without `controls`, is the page's alone.
817
+ if (host.shadowRoot && host.dataset.shape !== 'page') this.#writeControls(host, null);
818
+ host.hidden = host.children.length === 0;
819
+ continue;
820
+ }
821
+ // A declarative shadow root that wasn't read, as in HTML a script put in the page, isn't
822
+ // there: the element writes the defaults into one of its own.
823
+ const unread = !host.shadowRoot || host.shadowRoot.childElementCount === 0;
824
+ // Its template is left as a child, which isn't the page's own content.
825
+ if (unread) for (const left of host.querySelectorAll(':scope > template[shadowrootmode]')) left.remove();
826
+ if (!host.shadowRoot) host.attachShadow({ mode: 'open' });
827
+ if (unread || host.dataset.shape !== shape(info)) this.#writeControls(host, info);
828
+ // A figure with nothing to control, as another look can be, shows only what the page put in.
829
+ host.hidden = !hasControls(info) && host.children.length === 0;
830
+ }
831
+ this.#wiring.attach(this.#controlsRoots());
832
+ this.#wiring.enable();
833
+ }
834
+
835
+ /** Writes the defaults into a `<pencil-controls>`, as a build would for this figure as it stands,
836
+ * or with no `info`, only what the page put in it. */
837
+ #writeControls(host, info) {
838
+ const root = host.shadowRoot;
839
+ // A reader who was on a control is still on it afterwards, as one who picked a look with the
840
+ // keyboard: the same control, found by what it's for, and a menu that was open is open still.
841
+ const focused = root.activeElement ? identity(root.activeElement) : null;
842
+ const open = !!root.querySelector('[popover]:popover-open');
843
+ let html = '<div class="controls" part="controls"><div class="rest" part="rest"><slot></slot></div></div>';
844
+ if (info) {
845
+ let room = [];
846
+ try {
847
+ room = JSON.parse(this.#player.readout_room(this.#time));
848
+ } catch {}
849
+ const values = Object.fromEntries(info.params.map((p) => [p.id, this.value(p.id)]));
850
+ const ranges = Object.fromEntries(info.params.map((p) => [p.id, this.range(p.id)]));
851
+ const sized = { ...info, readouts: (info.readouts ?? []).map((r, i) => ({ ...r, room: room[i] })) };
852
+ html = markup({
853
+ info: sized,
854
+ moment: { time: this.#time, values, ranges, readouts: this.readouts },
855
+ paused: this.paused,
856
+ extra: host.children.length > 0,
857
+ });
858
+ }
859
+ const sheet = controlsStyles();
860
+ if (sheet) {
861
+ root.adoptedStyleSheets = [sheet];
862
+ root.innerHTML = html;
863
+ } else {
864
+ root.innerHTML = `<style>${CONTROLS_CSS}</style>${html}`;
865
+ }
866
+ host.dataset.shape = info ? shape(info) : 'page';
867
+ this.#wiring.forget();
868
+ if (open) {
869
+ try {
870
+ root.querySelector('[popover]')?.showPopover();
871
+ } catch {}
872
+ }
873
+ if (focused) root.querySelector(focused)?.focus();
874
+ }
875
+
876
+ /** What each readout says this frame, `{ id, text, words, math, width, height, laid }`, in the
877
+ * order they're written: a readout is a label with no place, said beside the figure. Its layout
878
+ * is in ems, from the left and middle of its line (`readoutHtml` in `controls.js` sets one). */
879
+ get readouts() {
880
+ if (!this.#player || !this.#info?.readouts?.length) return [];
881
+ if (this.#readouts?.time !== this.#time) {
882
+ let said = [];
883
+ try {
884
+ said = JSON.parse(this.#player.readouts(this.#time));
885
+ } catch {}
886
+ this.#readouts = { time: this.#time, said };
887
+ }
888
+ return this.#readouts.said;
889
+ }
890
+
731
891
  /** Shapes the figure to its design size, so nothing moves as it loads. */
732
892
  #shape(size) {
733
893
  this.#size = size;
@@ -772,6 +932,7 @@ export class PencilFigure extends HTMLElement {
772
932
  /** Plays from where it is. Each param time drives is handed back to time, carrying on from
773
933
  * where the reader left the last one they moved. */
774
934
  play() {
935
+ this.#readouts = null;
775
936
  const moved = [...this.#held.keys()].filter((name) => this.#driven.has(name)).pop();
776
937
  if (moved && this.#player) {
777
938
  try {
@@ -783,6 +944,7 @@ export class PencilFigure extends HTMLElement {
783
944
  this.#paused = false;
784
945
  this.#sync();
785
946
  this.#invalidate();
947
+ this.#wiring.paintPlay();
786
948
  if (was !== false) this.dispatchEvent(new Event('play'));
787
949
  }
788
950
 
@@ -790,6 +952,7 @@ export class PencilFigure extends HTMLElement {
790
952
  const was = this.#paused;
791
953
  this.#paused = true;
792
954
  this.#sync();
955
+ this.#wiring.paintPlay();
793
956
  if (was !== true) this.dispatchEvent(new Event('pause'));
794
957
  }
795
958
 
@@ -918,6 +1081,7 @@ export class PencilFigure extends HTMLElement {
918
1081
 
919
1082
  /** Holds params together: none of them hands another back. */
920
1083
  #hold(pairs) {
1084
+ this.#readouts = null;
921
1085
  this.#reclaim(pairs.map(([name]) => name));
922
1086
  for (const [name, value] of pairs) {
923
1087
  this.#held.delete(name);
@@ -1197,6 +1361,8 @@ export class PencilFigure extends HTMLElement {
1197
1361
  /** A key on the figure itself: ← and → step its beats, and Home and End go to the first and
1198
1362
  * last. What it came to is said for a screen reader, with the beat's caption. */
1199
1363
  #key = (e) => {
1364
+ // Keys in the controls are theirs: an arrow on a slider moves the slider.
1365
+ if (e.target !== this) return;
1200
1366
  if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || !this.#player || !this.#steps()) return;
1201
1367
  const range = this.#info.params.find((p) => p.id === 'beat');
1202
1368
  if (e.key === 'ArrowRight') this.step(1);
@@ -1212,6 +1378,8 @@ export class PencilFigure extends HTMLElement {
1212
1378
  const timed = (this.#info.beatLengths?.length ?? 0) > 0;
1213
1379
  const n = Math.round(timed ? beat : beat + 1);
1214
1380
  const caption = beats[n - 1] ?? '';
1381
+ // Controls that say each new beat say this one, and a beat is said once.
1382
+ if (this.#wiring.speaks) return;
1215
1383
  this.#said.textContent = n < 1 ? 'Start' : `Step ${n} of ${beats.length}${caption ? `: ${caption}` : ''}`;
1216
1384
  };
1217
1385
 
@@ -1269,6 +1437,8 @@ export class PencilFigure extends HTMLElement {
1269
1437
  }
1270
1438
  this.#healthy = true;
1271
1439
  this.#placeHandles();
1440
+ this.#readouts = null;
1441
+ this.#wiring.read();
1272
1442
  if (this.#reported) {
1273
1443
  this.#reported = false;
1274
1444
  this.dispatchEvent(new Event('recover'));
package/src/wiring.js ADDED
@@ -0,0 +1,313 @@
1
+ // What makes a figure's controls work: its defaults in `<pencil-controls>`, or a page's own in the
2
+ // `controls` slot. Either way, each control is marked with what it sets and each output with what
3
+ // it shows, and this sets their ranges, steps and values from the figure, follows them each frame,
4
+ // and hands what a reader does to the figure, through its public API only:
5
+ //
6
+ // input[type=range][data-param="q"] a slider: its min, max, step and value are the figure's
7
+ // select[data-param="along"] a choice's options, filled in if it has none
8
+ // input[type=radio][data-param="along"][value="1"] one option, by its place from 0
9
+ // input[type=checkbox][data-param="glow"] a choice of off and on: checked is on
10
+ // output[data-param="q"] the param's value, as its control says it
11
+ // [data-readout="ratio"] what a readout says, laid out as the figure lays it out
12
+ // button[data-play] plays and pauses; input[type=range][data-time] and
13
+ // output[data-time] are the time
14
+ // button[data-step="1"], [data-step="-1"], output[data-beat], [data-captions] beats
15
+ //
16
+ // A choice's `data-param` is the name its value has, `along`, or its param, `along.index`.
17
+ import { PHONE, paramNamed, valueText, timeText, beatAt, steps, readoutHtml } from './controls.js';
18
+
19
+ const ATTRIBUTES = ['data-play', 'data-time', 'data-step', 'data-param', 'data-readout'];
20
+
21
+ /** What a control is, as a selector that finds the same control in controls written again: its
22
+ * `id`, or what it's marked as being for, or the menu's button. None for anything else. */
23
+ export function identity(el) {
24
+ if (el.id) return `#${CSS.escape(el.id)}`;
25
+ for (const name of ATTRIBUTES) {
26
+ if (!el.hasAttribute(name)) continue;
27
+ const value = el.getAttribute(name);
28
+ let key = `${el.localName}[${name}${value ? `="${CSS.escape(value)}"` : ''}]`;
29
+ if (el.type === 'radio') key += `[value="${CSS.escape(el.value)}"]`;
30
+ return key;
31
+ }
32
+ return el.classList.contains('more') ? '.more' : null;
33
+ }
34
+
35
+ export class Wiring {
36
+ #figure;
37
+ #roots = [];
38
+ #off = null;
39
+ #parts = null;
40
+ #sized = null; // watches the bars, which hold one row on a phone
41
+ #beatSaid = undefined; // the beat last said, by its caption's place
42
+
43
+ constructor(figure) {
44
+ this.#figure = figure;
45
+ }
46
+
47
+ /** Listens on these roots, a shadow root or a page's own element, and looks for what's in them
48
+ * again. */
49
+ attach(roots) {
50
+ this.#beatSaid = undefined;
51
+ this.#off?.abort();
52
+ this.#off = new AbortController();
53
+ this.#roots = roots;
54
+ this.#parts = null;
55
+ const signal = this.#off.signal;
56
+ for (const root of roots) {
57
+ root.addEventListener('input', (e) => this.#input(e.target), { signal });
58
+ root.addEventListener('change', (e) => this.#change(e.target), { signal });
59
+ root.addEventListener('click', (e) => this.#click(e.target.closest?.('button')), { signal });
60
+ this.#menus(root, signal);
61
+ }
62
+ this.#sized?.disconnect();
63
+ this.#sized = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(() => this.fit());
64
+ for (const root of roots) for (const bar of root.querySelectorAll('.bar')) this.#sized?.observe(bar);
65
+ }
66
+
67
+ /** A menu that closes with the focus in it, on Escape, gives the focus back to its button, as a
68
+ * menu should, where a browser can leave it nowhere. */
69
+ #menus(root, signal) {
70
+ const scope = root.getRootNode?.() ?? document;
71
+ for (const menu of root.querySelectorAll('[popover][id]')) {
72
+ const button = root.querySelector(`[popovertarget="${CSS.escape(menu.id)}"]`);
73
+ let inside = false;
74
+ menu.addEventListener(
75
+ 'beforetoggle',
76
+ (e) => {
77
+ if (e.newState === 'closed') inside = menu.contains(scope.activeElement);
78
+ },
79
+ { signal },
80
+ );
81
+ menu.addEventListener(
82
+ 'toggle',
83
+ (e) => {
84
+ if (e.newState !== 'closed' || !inside) return;
85
+ inside = false;
86
+ const now = scope.activeElement;
87
+ if (!now || now === document.body || menu.contains(now)) button?.focus();
88
+ },
89
+ { signal },
90
+ );
91
+ }
92
+ }
93
+
94
+ /**
95
+ * On a phone a bar keeps one row on one line, and one that doesn't fit, as radios with long
96
+ * words or a long caption, goes behind the menu with the rest, so nothing in the bar is cut off.
97
+ * The bar is as tall either way, so nothing moves.
98
+ */
99
+ fit() {
100
+ const phone = typeof matchMedia !== 'undefined' && matchMedia(PHONE).matches;
101
+ for (const root of this.#roots) {
102
+ const bar = root.querySelector('.bar');
103
+ const menu = root.querySelector('.rest');
104
+ const controls = root.querySelector('.controls');
105
+ if (!bar || !menu || !controls) continue;
106
+ const scope = root.getRootNode?.() ?? document;
107
+ const focused = scope.activeElement;
108
+ // A row the bar gave up comes back to see whether it fits now, as when a phone turns.
109
+ const moved = menu.querySelector(':scope > .row[data-moved]');
110
+ if (moved) {
111
+ moved.removeAttribute('data-moved');
112
+ bar.insertBefore(moved, bar.querySelector(':scope > .more'));
113
+ bar.removeAttribute('data-crowded');
114
+ controls.toggleAttribute('data-more', controls.hasAttribute('data-menu'));
115
+ this.#parts = null;
116
+ }
117
+ const row = bar.querySelector(':scope > .row');
118
+ if (phone && row && row.scrollWidth > row.clientWidth + 0.5) {
119
+ menu.prepend(row);
120
+ row.setAttribute('data-moved', '');
121
+ bar.setAttribute('data-crowded', '');
122
+ controls.setAttribute('data-more', '');
123
+ this.#parts = null;
124
+ }
125
+ // Moving what has the focus takes it away, so it's given back.
126
+ if (focused && focused !== scope.activeElement && focused.isConnected) focused.focus({ preventScroll: true });
127
+ }
128
+ }
129
+
130
+ get roots() {
131
+ return this.#roots;
132
+ }
133
+
134
+ /** Whether the controls say each new beat themselves, so the figure needn't say a key's. */
135
+ get speaks() {
136
+ return this.#roots.length > 0 && !!this.#figure.info && this.#find().said.length > 0;
137
+ }
138
+
139
+ /** What's in them changed: look again. */
140
+ forget() {
141
+ this.#parts = null;
142
+ }
143
+
144
+ #all(selector) {
145
+ return this.#roots.flatMap((root) => [...root.querySelectorAll(selector)]);
146
+ }
147
+
148
+ #find() {
149
+ const info = this.#figure.info;
150
+ return (this.#parts ??= {
151
+ play: this.#all('[data-play]'),
152
+ times: this.#all('input[data-time]'),
153
+ timeOuts: this.#all('[data-time]:not(input)'),
154
+ beatOuts: this.#all('[data-beat]'),
155
+ back: this.#all('[data-step="-1"]'),
156
+ next: this.#all('[data-step="1"]'),
157
+ captions: this.#all('[data-captions]').map((list) => [...list.children]),
158
+ params: this.#all('[data-param]')
159
+ .map((el) => ({ el, param: paramNamed(info, el.dataset.param), said: null }))
160
+ .filter((each) => each.param),
161
+ readouts: this.#all('[data-readout]').map((el) => ({ el, id: el.dataset.readout, said: null })),
162
+ said: this.#all('[data-said]'),
163
+ });
164
+ }
165
+
166
+ /** The figure has loaded: everything can be worked, and shows the figure as it stands. */
167
+ enable() {
168
+ for (const root of this.#roots) {
169
+ // Only what's marked as the figure's: a page's other controls are the page's.
170
+ for (const control of root.querySelectorAll('[data-param], [data-time], [data-play], [data-step]')) {
171
+ if ('disabled' in control) control.disabled = false;
172
+ }
173
+ }
174
+ this.#parts = null;
175
+ const info = this.#figure.info;
176
+ for (const { el, param } of this.#find().params) {
177
+ if (el.localName === 'select' && el.options.length === 0 && param.choice) {
178
+ param.choice.options.forEach((text, i) => el.append(new Option(text, String(i))));
179
+ }
180
+ if (el.localName === 'input' && el.type === 'range') {
181
+ const [min, max] = this.#figure.range(param.id);
182
+ Object.assign(el, { min, max, step: param.step ?? ((param.max - param.min) / 1000 || 0.001) });
183
+ }
184
+ }
185
+ for (const input of this.#find().times) Object.assign(input, { min: 0, max: this.#figure.duration, step: 0.001 });
186
+ if (info) this.paintPlay();
187
+ this.fit();
188
+ this.read();
189
+ }
190
+
191
+ #input(target) {
192
+ const figure = this.#figure;
193
+ if (!figure.info || !target?.matches) return;
194
+ if (target.matches('input[type=range][data-time]')) {
195
+ figure.pause();
196
+ figure.time = Number(target.value);
197
+ } else if (target.matches('input[type=range][data-param]')) {
198
+ const param = paramNamed(figure.info, target.dataset.param);
199
+ if (!param) return;
200
+ figure.pause();
201
+ figure.hold(param.id, Number(target.value));
202
+ }
203
+ }
204
+
205
+ #change(target) {
206
+ const figure = this.#figure;
207
+ if (!figure.info || !target?.matches?.('select[data-param], input[type=radio][data-param], input[type=checkbox][data-param]')) return;
208
+ const param = paramNamed(figure.info, target.dataset.param);
209
+ if (!param) return;
210
+ if (target.type === 'checkbox') figure.hold(param.id, target.checked ? 1 : 0);
211
+ else if (target.type !== 'radio' || target.checked) figure.hold(param.id, Number(target.value));
212
+ }
213
+
214
+ #click(button) {
215
+ if (!button || button.disabled || !this.#figure.info) return;
216
+ const figure = this.#figure;
217
+ if (button.matches('[data-play]')) figure.paused ? figure.play() : figure.pause();
218
+ else if (button.dataset.step) figure.step(Number(button.dataset.step));
219
+ }
220
+
221
+ /** Says Play or Pause. A button with a word for each shows the one that applies. */
222
+ paintPlay() {
223
+ const paused = this.#figure.paused;
224
+ for (const button of this.#find().play) {
225
+ const words = button.querySelectorAll(':scope > span');
226
+ if (words.length === 2) {
227
+ words[0].toggleAttribute('data-on', paused);
228
+ words[1].toggleAttribute('data-on', !paused);
229
+ } else {
230
+ const text = paused ? 'Play' : 'Pause';
231
+ if (button.textContent !== text) button.textContent = text;
232
+ }
233
+ button.setAttribute('aria-label', paused ? 'Play' : 'Pause');
234
+ }
235
+ }
236
+
237
+ /** Reads the figure back, so the controls show what's drawn. Only what changed is written. */
238
+ read() {
239
+ const figure = this.#figure;
240
+ const info = figure.info;
241
+ if (!info || !this.#roots.length) return;
242
+ const parts = this.#find();
243
+ const say = (el, text) => {
244
+ if (el.textContent !== text) el.textContent = text;
245
+ };
246
+ const time = figure.time;
247
+ for (const input of parts.times) {
248
+ if (!input.matches(':focus')) input.value = String(time);
249
+ input.setAttribute('aria-valuetext', timeText(time));
250
+ }
251
+ for (const out of parts.timeOuts) say(out, timeText(time));
252
+ for (const each of parts.params) {
253
+ const { el, param } = each;
254
+ const value = figure.value(param.id);
255
+ if (el.localName === 'input' && el.type === 'range') {
256
+ // A range that follows another param is read as it stands, so the control stops where
257
+ // the figure does.
258
+ if (param.follows?.length) [el.min, el.max] = figure.range(param.id);
259
+ if (!el.matches(':focus') && Number.isFinite(value)) el.value = String(value);
260
+ const text = valueText(param, value);
261
+ if (each.said !== text) el.setAttribute('aria-valuetext', text);
262
+ each.said = text;
263
+ } else if (el.localName === 'input' && el.type === 'radio') {
264
+ el.checked = Number(el.value) === Math.round(value);
265
+ } else if (el.localName === 'input' && el.type === 'checkbox') {
266
+ el.checked = Math.round(value) === 1;
267
+ } else if (el.localName === 'select') {
268
+ if (!el.matches(':focus') && Number.isFinite(value)) el.value = String(Math.round(value));
269
+ } else if (el.localName !== 'input') {
270
+ say(el, valueText(param, value));
271
+ }
272
+ }
273
+ if (steps(info) && (parts.beatOuts.length || parts.captions.length)) {
274
+ const range = info.params.find((p) => p.id === 'beat');
275
+ const beat = Number.isFinite(figure.beat) ? figure.beat : 0;
276
+ const at = beatAt(info, beat);
277
+ for (const out of parts.beatOuts) say(out, at.text);
278
+ for (const list of parts.captions) list.forEach((caption, i) => caption.toggleAttribute('data-on', i === at.caption));
279
+ // A beat that changes is said, however it changed: which it is, and its caption, in the
280
+ // words the element says a key's step in, which it leaves to this. Not the first, which is
281
+ // where the figure starts and isn't news. Beats with lengths are at their start before the
282
+ // first is done.
283
+ const step = (info.beatLengths?.length ?? 0) > 0 && beat < 1e-6 ? 0 : at.caption + 1;
284
+ if (this.#beatSaid !== undefined && this.#beatSaid !== step) {
285
+ const caption = info.beats[step - 1];
286
+ const words = step < 1 ? 'Start' : `Step ${step} of ${info.beats.length}${caption ? `: ${caption}` : ''}`;
287
+ for (const said of parts.said) say(said, words);
288
+ }
289
+ this.#beatSaid = step;
290
+ for (const button of parts.back) button.disabled = beat <= range.min;
291
+ for (const button of parts.next) button.disabled = beat >= range.max;
292
+ }
293
+ if (parts.readouts.length) {
294
+ const said = new Map(figure.readouts.map((readout) => [readout.id, readout]));
295
+ for (const each of parts.readouts) {
296
+ const readout = said.get(each.id);
297
+ const key = readout ? readout.text : '';
298
+ if (each.said === key) continue;
299
+ each.said = key;
300
+ each.el.innerHTML = readoutHtml(readout);
301
+ }
302
+ }
303
+ }
304
+
305
+ detach() {
306
+ this.#off?.abort();
307
+ this.#off = null;
308
+ this.#sized?.disconnect();
309
+ this.#sized = null;
310
+ this.#roots = [];
311
+ this.#parts = null;
312
+ }
313
+ }