@pencil-lang/figure 0.0.4 → 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/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
+ }