@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/pkg/pencil_web.js CHANGED
@@ -275,6 +275,57 @@ export class Player {
275
275
  wasm.__wbindgen_free(ret[0], ret[1] * 8, 8);
276
276
  return v3;
277
277
  }
278
+ /**
279
+ * How much room each readout needs, as JSON `[[width, height], …]` in ems, so that nothing
280
+ * beside it moves as it changes: the most it takes at the moments a reader can reach that
281
+ * are tried, from this time and the params the page holds. A build works out the same with
282
+ * the same fonts.
283
+ * @param {number} time
284
+ * @returns {string}
285
+ */
286
+ readout_room(time) {
287
+ let deferred2_0;
288
+ let deferred2_1;
289
+ try {
290
+ const ret = wasm.player_readout_room(this.__wbg_ptr, time);
291
+ var ptr1 = ret[0];
292
+ var len1 = ret[1];
293
+ if (ret[3]) {
294
+ ptr1 = 0; len1 = 0;
295
+ throw takeFromExternrefTable0(ret[2]);
296
+ }
297
+ deferred2_0 = ptr1;
298
+ deferred2_1 = len1;
299
+ return getStringFromWasm0(ptr1, len1);
300
+ } finally {
301
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
302
+ }
303
+ }
304
+ /**
305
+ * What the figure's readouts say at a time, as JSON: for each label with no place, in the
306
+ * order it's written, its text and what's laid out of it, in ems, for the page to set beside
307
+ * the figure (`readout_json` in the core).
308
+ * @param {number} time
309
+ * @returns {string}
310
+ */
311
+ readouts(time) {
312
+ let deferred2_0;
313
+ let deferred2_1;
314
+ try {
315
+ const ret = wasm.player_readouts(this.__wbg_ptr, time);
316
+ var ptr1 = ret[0];
317
+ var len1 = ret[1];
318
+ if (ret[3]) {
319
+ ptr1 = 0; len1 = 0;
320
+ throw takeFromExternrefTable0(ret[2]);
321
+ }
322
+ deferred2_0 = ptr1;
323
+ deferred2_1 = len1;
324
+ return getStringFromWasm0(ptr1, len1);
325
+ } finally {
326
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
327
+ }
328
+ }
278
329
  release() {
279
330
  wasm.player_release(this.__wbg_ptr);
280
331
  }
@@ -2565,17 +2616,17 @@ function __wbg_get_imports() {
2565
2616
  },
2566
2617
  __wbindgen_generic_0000000000000004: function(arg0, arg1) {
2567
2618
  // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("GPUUncapturedErrorEvent")], shim_idx: 386, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
2568
- const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h0f29fc2faa2e5086_42);
2619
+ const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h0f29fc2faa2e5086_44);
2569
2620
  return ret;
2570
2621
  },
2571
2622
  __wbindgen_generic_0000000000000005: function(arg0, arg1) {
2572
2623
  // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("any")], shim_idx: 370, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
2573
- const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h0ac39b197b40bdab_43);
2624
+ const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h0ac39b197b40bdab_45);
2574
2625
  return ret;
2575
2626
  },
2576
2627
  __wbindgen_generic_0000000000000006: function(arg0, arg1) {
2577
2628
  // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("undefined")], shim_idx: 370, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
2578
- const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h0ac39b197b40bdab_44);
2629
+ const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h0ac39b197b40bdab_46);
2579
2630
  return ret;
2580
2631
  },
2581
2632
  __wbindgen_generic_0000000000000007: function(arg0) {
@@ -2642,8 +2693,8 @@ function wasm_bindgen__convert__closures_____invoke__h0f29fc2faa2e5086(arg0, arg
2642
2693
  wasm.wasm_bindgen__convert__closures_____invoke__h0f29fc2faa2e5086(arg0, arg1, arg2);
2643
2694
  }
2644
2695
 
2645
- function wasm_bindgen__convert__closures_____invoke__h0f29fc2faa2e5086_42(arg0, arg1, arg2) {
2646
- wasm.wasm_bindgen__convert__closures_____invoke__h0f29fc2faa2e5086_42(arg0, arg1, arg2);
2696
+ function wasm_bindgen__convert__closures_____invoke__h0f29fc2faa2e5086_44(arg0, arg1, arg2) {
2697
+ wasm.wasm_bindgen__convert__closures_____invoke__h0f29fc2faa2e5086_44(arg0, arg1, arg2);
2647
2698
  }
2648
2699
 
2649
2700
  function wasm_bindgen__convert__closures_____invoke__hd4acdde59c21f30c(arg0, arg1, arg2) {
@@ -2660,15 +2711,15 @@ function wasm_bindgen__convert__closures_____invoke__h0ac39b197b40bdab(arg0, arg
2660
2711
  }
2661
2712
  }
2662
2713
 
2663
- function wasm_bindgen__convert__closures_____invoke__h0ac39b197b40bdab_43(arg0, arg1, arg2) {
2664
- const ret = wasm.wasm_bindgen__convert__closures_____invoke__h0ac39b197b40bdab_43(arg0, arg1, arg2);
2714
+ function wasm_bindgen__convert__closures_____invoke__h0ac39b197b40bdab_45(arg0, arg1, arg2) {
2715
+ const ret = wasm.wasm_bindgen__convert__closures_____invoke__h0ac39b197b40bdab_45(arg0, arg1, arg2);
2665
2716
  if (ret[1]) {
2666
2717
  throw takeFromExternrefTable0(ret[0]);
2667
2718
  }
2668
2719
  }
2669
2720
 
2670
- function wasm_bindgen__convert__closures_____invoke__h0ac39b197b40bdab_44(arg0, arg1, arg2) {
2671
- const ret = wasm.wasm_bindgen__convert__closures_____invoke__h0ac39b197b40bdab_44(arg0, arg1, arg2);
2721
+ function wasm_bindgen__convert__closures_____invoke__h0ac39b197b40bdab_46(arg0, arg1, arg2) {
2722
+ const ret = wasm.wasm_bindgen__convert__closures_____invoke__h0ac39b197b40bdab_46(arg0, arg1, arg2);
2672
2723
  if (ret[1]) {
2673
2724
  throw takeFromExternrefTable0(ret[0]);
2674
2725
  }
Binary file
@@ -0,0 +1,417 @@
1
+ // A figure's default controls, as HTML: a play button and a time slider, beat stepping with its
2
+ // caption, a control for each param a handle doesn't set, and the readouts. One function writes
3
+ // them, for a build, which writes them into the page as a declarative shadow root of
4
+ // `<pencil-controls>` before any script runs, and for `<pencil-figure controls>` on a page that gave
5
+ // none. Nothing here touches the DOM, so a build can call it.
6
+ //
7
+ // Nothing moves when a value changes. An `<output>` is as wide as the widest value its param's
8
+ // range can show, a readout's box is as big as the most it says at the moments a build tries, every
9
+ // caption lies in one place, so the row is as tall as the longest of them, and the play button is
10
+ // as wide as the wider of its words. On a phone one row stays, `BAR` says which, and the rest open
11
+ // from a menu over the page, so the figure keeps the height. That row, too, goes behind the menu if
12
+ // it doesn't fit (the element checks), so nothing in the bar is ever cut off.
13
+ //
14
+ // Every control is marked with what it sets (`data-param`, `data-time`, `data-play`, `data-step`),
15
+ // and each output with what it shows (`data-param`, `data-time`, `data-beat`, `data-readout`), as a
16
+ // page's own controls are. The element wires them the same way either way.
17
+ import { FAMILY } from './labels.js';
18
+
19
+ const escape = (text) => String(text).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
20
+ const attrs = (pairs) =>
21
+ Object.entries(pairs)
22
+ .filter(([, value]) => value !== undefined && value !== null && value !== false)
23
+ .map(([name, value]) => (value === true ? ` ${name}` : ` ${name}="${escape(value)}"`))
24
+ .join('');
25
+
26
+ /** How long time runs before it loops, for a figure that declares no `duration`, as the element has it. */
27
+ const LOOP = 10;
28
+
29
+ /**
30
+ * Which row a phone's bar keeps, of the controls' one line, with the rest behind its menu: `'first'`,
31
+ * the first of them (time, beats, or the first param's control), or `'readouts'`, the readouts when
32
+ * a figure has any, and the first row when it has none.
33
+ */
34
+ export const BAR = 'first';
35
+
36
+ /** When the controls are a phone's: one row, and a menu. The styles below say the same. */
37
+ export const PHONE = '(max-width: 40rem), (max-height: 32rem)';
38
+
39
+ /** As many decimals as a param's step has, so a whole-number param reads as one. */
40
+ export const decimals = (param) => (param.step == null ? 2 : (String(param.step).split('.')[1] ?? '').length);
41
+
42
+ /** A param's value as its control says it: a choice's option, or the number. One that doesn't exist
43
+ * this frame is a dash. */
44
+ export function valueText(param, value) {
45
+ if (!Number.isFinite(value)) return '—';
46
+ if (param.choice) return param.choice.options[Math.round(value)] ?? '—';
47
+ return value.toFixed(decimals(param)).replace('-', '−');
48
+ }
49
+
50
+ export const timeText = (seconds) => `${seconds.toFixed(1)} s`;
51
+
52
+ /** Whether a handle sets this param. Its handle is its control: it takes focus and the arrow
53
+ * keys, and says its value to a screen reader, so the param gets no control of its own. */
54
+ export const handled = (info, param) => (info.handles ?? []).some((handle) => handle.params.includes(param.id));
55
+
56
+ /** Whether the figure has beats to step through. */
57
+ export const steps = (info) => (info.beats?.length ?? 0) > 0 && info.params.some((p) => p.id === 'beat');
58
+
59
+ /** The params that get a control: each one a handle doesn't set, and not `beat` when it's stepped. */
60
+ export const controlled = (info) => info.params.filter((p) => !(p.id === 'beat' && steps(info)) && !handled(info, p));
61
+
62
+ /** Whether a figure has anything for its controls to show: time, beats, a param, or a readout. */
63
+ export const hasControls = (info) =>
64
+ !!info && (info.usesTime || steps(info) || controlled(info).length > 0 || (info.readouts?.length ?? 0) > 0);
65
+
66
+ /** The param a control or an output is for: `data-param` names it, or for a choice, its value. */
67
+ export const paramNamed = (info, name) => info?.params.find((p) => p.id === name || p.choice?.of === name);
68
+
69
+ /** Beats with lengths count the beats done, from 0 to n. Ones without say which beat it's on. */
70
+ const timed = (info) => (info.beatLengths?.length ?? 0) > 0;
71
+
72
+ /** Where a figure is in its beats: what the counter says, and which caption shows. */
73
+ export function beatAt(info, beat) {
74
+ const n = info.beats.length;
75
+ const at = Number.isFinite(beat) ? beat : 0;
76
+ const shown = timed(info) ? at : at + 1;
77
+ const whole = Math.abs(shown - Math.round(shown)) < 1e-6;
78
+ return {
79
+ text: `${whole ? Math.round(shown) : shown.toFixed(1)} / ${n}`,
80
+ caption: timed(info) ? Math.min(n - 1, Math.max(0, Math.ceil(at) - 1)) : Math.round(at),
81
+ };
82
+ }
83
+
84
+ /** What a param's control says it is, as its sheets' `text` picks: its caption, or its name, as
85
+ * parts joined by ` = `, each `{ text, math }`. Its value isn't one of them: it's said after the
86
+ * control. A control with no caption says its name, which is mathematics. */
87
+ export function controlParts(param) {
88
+ const name = param.control?.name ?? param.choice?.of ?? param.id;
89
+ const said = [];
90
+ for (const part of param.control?.text ?? ['caption', 'value']) {
91
+ const piece =
92
+ part === 'caption' ? (param.caption ? { text: param.caption, math: false } : { text: name, math: true })
93
+ : part === 'name' || part === 'expr' ? { text: name, math: true }
94
+ : null;
95
+ if (piece && !said.some((each) => each.text === piece.text)) said.push(piece);
96
+ }
97
+ return said;
98
+ }
99
+
100
+ /** What a control is called, for a screen reader: what it says, or its caption or name when it
101
+ * says only its value. */
102
+ export function controlName(param) {
103
+ const parts = controlParts(param);
104
+ if (parts.length) return parts.map((part) => part.text).join(' = ');
105
+ return param.caption ?? param.control?.name ?? param.choice?.of ?? param.id;
106
+ }
107
+
108
+ /** Whether a control says its value after it: a slider does unless its sheets leave `value` out. */
109
+ export const saysValue = (param) => (param.control?.text ?? ['caption', 'value']).includes('value');
110
+
111
+ /** Which control a param gets, as the core works it out from the figure and its sheets. */
112
+ export const kindOf = (param) => param.control?.kind ?? (param.choice ? 'select' : 'slider');
113
+
114
+ const labelHtml = (param) =>
115
+ controlParts(param)
116
+ .map((part) => (part.math ? `<var>${escape(part.text)}</var>` : escape(part.text)))
117
+ .join(' = ');
118
+
119
+ /** The room an output needs: as many digits wide as the longest thing it will say. With
120
+ * tabular figures a digit is a `ch`, and a sign, a point and a space are no wider. */
121
+ const room = (...texts) => `--room: ${Math.max(...texts.map((text) => String(text).length))}ch`;
122
+
123
+ /**
124
+ * What kind of controls a figure has, as a short string. Controls made for one figure fit another
125
+ * with the same one, so the element keeps what a build wrote and only turns it on.
126
+ */
127
+ export function shape(info) {
128
+ const text = JSON.stringify([
129
+ info.usesTime,
130
+ info.duration,
131
+ info.beats,
132
+ timed(info),
133
+ info.params.map((p) => [p.id, p.min, p.max, p.step, p.choice, handled(info, p), p.caption, p.control]),
134
+ (info.readouts ?? []).map((r) => r.id),
135
+ ]);
136
+ let hash = 5381;
137
+ for (let i = 0; i < text.length; i++) hash = ((hash * 33) ^ text.charCodeAt(i)) >>> 0;
138
+ return hash.toString(36);
139
+ }
140
+
141
+ const px = (v) => `${Math.round(v * 1e4) / 1e4}em`;
142
+
143
+ /**
144
+ * What a readout says, as HTML to put in its box: what the core laid out, each run and rule placed
145
+ * in ems from the left of its line and its middle, as a label over the figure is, in the same
146
+ * fonts. Every style is inline, so it reads the same in a page's own box as in the defaults. Its
147
+ * words are there for a screen reader, and the runs aren't.
148
+ *
149
+ * `readout` is one of the element's `readouts`, or of what a build says of the poster's moment:
150
+ * `{ id, text, words, math, width, height, laid }`.
151
+ */
152
+ export function readoutHtml(readout) {
153
+ if (!readout) return '';
154
+ const box = `position:relative;display:inline-block;vertical-align:middle;width:${px(readout.width)};height:${px(readout.height)}`;
155
+ const run = `position:absolute;white-space:pre;line-height:1;font-kerning:none;font-variant-ligatures:none;font-feature-settings:'calt' 0`;
156
+ const sans = `font-family:${FAMILY.sans};font-style:normal`;
157
+ const italic = `font-family:${FAMILY.math};font-style:italic`;
158
+ const formula = `font-family:'Pencil Math', ${FAMILY.math};font-style:normal`;
159
+ const said = `<span style="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap">${escape(readout.words)}</span>`;
160
+ let drawn;
161
+ if (!readout.laid) {
162
+ drawn = `<span style="${run};left:0;top:calc(50% - 0.5em);font-size:1em;${readout.math ? italic : sans}">${escape(readout.words)}</span>`;
163
+ } else {
164
+ const words = readout.math ? italic : sans;
165
+ drawn = readout.laid.runs
166
+ .map((r) => {
167
+ const stretch = r.stretch !== 1 ? `;transform:scaleY(${r.stretch});transform-origin:0 ${(0.5 + 0.324) * 100}%` : '';
168
+ return `<span style="${run};left:${px(r.x)};top:calc(50% + ${px(r.top)});font-size:${px(r.size)};${r.math ? formula : words}${stretch}">${escape(r.text)}</span>`;
169
+ })
170
+ .concat(
171
+ readout.laid.rules.map(
172
+ (r) => `<span style="position:absolute;left:${px(r.x)};top:calc(50% + ${px(r.y)});width:${px(r.width)};height:${px(r.height)};background:currentColor"></span>`,
173
+ ),
174
+ )
175
+ .join('');
176
+ }
177
+ return `<span aria-hidden="true" style="${box}">${drawn}</span>${said}`;
178
+ }
179
+
180
+ /** The defaults' styles, in their shadow root. A page styles them through `::part` and these custom
181
+ * properties, which inherit into it:
182
+ *
183
+ * - `--pencil-controls-font`: their text, as the `font` shorthand.
184
+ * - `--pencil-ink`: values, and a name, which is mathematics. `--pencil-muted`: what controls say
185
+ * they are, and captions.
186
+ * - `--pencil-accent`: sliders, radios and checkboxes. `--pencil-rule` and `--pencil-surface`: a
187
+ * button's border and background, and the menu's on a phone.
188
+ * - `--pencil-math-font`: a param's name, as the `font` shorthand.
189
+ * - `--pencil-focus`: the focus ring, as on the figure's handles.
190
+ * - `--pencil-readout-size`: how big a readout's text is.
191
+ */
192
+ export const CONTROLS_CSS = `
193
+ :host { display: block; }
194
+ :host([hidden]) { display: none; }
195
+ /* One grid, so every slider starts and ends where the others do: what a control says, the control,
196
+ and its value. What a control says wraps past two fifths of the width, so a long caption doesn't
197
+ squeeze its slider. A row of anything else takes the whole width. */
198
+ .controls, .rest { display: grid; grid-template-columns: fit-content(40%) minmax(0, 1fr) max-content; gap: 0.375rem 0.75rem; align-items: center; }
199
+ .controls { margin-top: 0.625rem; font: var(--pencil-controls-font, 0.875rem/1.4 ui-sans-serif, system-ui, sans-serif); color: var(--pencil-muted, color-mix(in srgb, currentColor 68%, transparent)); }
200
+ .bar, .rest { display: contents; }
201
+ .rest { position: static; inset: auto; margin: 0; padding: 0; border: 0; width: auto; height: auto; max-width: none; max-height: none; overflow: visible; background: none; color: inherit; }
202
+ .more, .more-words, .row.phone { display: none; }
203
+ .row { grid-column: 1 / -1; display: flex; align-items: center; gap: 0.5rem 0.75rem; flex-wrap: wrap; margin: 0; padding: 0; border: 0; min-width: 0; }
204
+ .row.param, .row.time { display: contents; }
205
+ /* The readouts come after the controls, wherever the bar's switch puts them, and what a page put
206
+ in after them. */
207
+ .row.readouts { order: 1; }
208
+ slot { display: contents; }
209
+ ::slotted(*) { grid-column: 1 / -1; order: 2; }
210
+ fieldset.row { min-inline-size: 0; }
211
+ legend { float: left; padding: 0; margin-right: 0.25rem; }
212
+ label { display: inline-flex; align-items: center; gap: 0.375rem; }
213
+ .option { gap: 0.25rem; }
214
+ input[type='range'] { width: 100%; min-width: 4rem; flex: 1 1 8rem; height: 1.25rem; margin: 0; contain: size layout style; accent-color: var(--pencil-accent, auto); }
215
+ input[type='radio'], input[type='checkbox'] { margin: 0; accent-color: var(--pencil-accent, auto); }
216
+ select { justify-self: start; }
217
+ output { display: inline-block; flex: none; justify-self: end; width: var(--room, 3.5rem); text-align: right; white-space: nowrap; overflow: hidden; font-variant-numeric: tabular-nums; color: var(--pencil-ink, currentColor); contain: layout paint style; }
218
+ .beats output { text-align: center; }
219
+ var { font: var(--pencil-math-font, italic 1.07em Charter, 'Bitstream Charter', 'Sitka Text', Cambria, Georgia, serif); color: var(--pencil-ink, currentColor); }
220
+ /* Every caption lies in the same place and only the beat's own shows, so the row is as tall as the
221
+ longest from the start and stepping moves nothing below it. */
222
+ .captions { flex-basis: 100%; display: grid; font-style: italic; min-width: 0; }
223
+ .caption { grid-area: 1 / 1; visibility: hidden; }
224
+ .caption[data-on] { visibility: visible; }
225
+ .readouts { gap: 0.25rem 1.25rem; -webkit-user-select: text; user-select: text; }
226
+ .readout { display: inline-block; width: calc(var(--width, 4) * 1em); height: calc(var(--height, 1.4) * 1em); flex: none; text-align: left; font-size: var(--pencil-readout-size, 1.0625rem); line-height: 1; color: var(--pencil-ink, currentColor); contain: strict; overflow: clip; }
227
+ button, select { font: inherit; color: var(--pencil-ink, currentColor); background: var(--pencil-surface, transparent); border: 1px solid var(--pencil-rule, color-mix(in srgb, currentColor 25%, transparent)); border-radius: 4px; padding: 0.25rem 0.625rem; cursor: pointer; }
228
+ button:disabled { opacity: 0.4; cursor: default; }
229
+ input:disabled, select:disabled { cursor: default; }
230
+ /* The play button is as wide as the wider of its words, so it doesn't move what's beside it. */
231
+ .play { display: inline-grid; flex: none; justify-self: start; }
232
+ .play > span { grid-area: 1 / 1; }
233
+ .play > span:not([data-on]) { visibility: hidden; }
234
+ :focus-visible { outline: 2px solid var(--pencil-focus, currentColor); outline-offset: 2px; }
235
+ input[type='range']:focus-visible { outline-offset: 1px; }
236
+ .said { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
237
+ /* On a phone, or a screen with little height, one row stays, on one line, in a bar of fixed height,
238
+ and the rest open from a menu over the page, as a sheet from the bottom: the figure keeps the
239
+ height. Each thing in the bar keeps its own width, so the element can tell when the row doesn't
240
+ fit, and then it goes behind the menu too. The beats' caption is a line of its own under the bar,
241
+ as tall as the longest caption at that width, wherever the stepper is. */
242
+ @media (max-width: 40rem), (max-height: 32rem) {
243
+ .controls { display: block; }
244
+ .bar { display: flex; align-items: center; gap: 0.5rem; height: 2.25rem; min-width: 0; }
245
+ .bar > .row, .bar > .row.param, .bar > .row.time { display: flex; flex: 1 1 auto; min-width: 0; flex-wrap: nowrap; overflow: hidden; gap: 0.5rem 0.75rem; }
246
+ .bar > .row > *, .bar > .row label { flex: none; white-space: nowrap; }
247
+ .bar > .row > input[type='range'] { flex: 1 1 4rem; min-width: 4rem; }
248
+ .beats .captions { display: none; }
249
+ .row.phone { display: flex; margin-top: 0.25rem; }
250
+ .row.phone .caption { white-space: normal; }
251
+ .controls[data-more] .more { display: inline-flex; align-items: center; gap: 0.375rem; flex: none; margin-left: auto; padding: 0.25rem 0.5rem; line-height: 1; }
252
+ .bar[data-crowded] .more-words { display: inline; }
253
+ .rest { display: grid; }
254
+ .rest[popover]:not(:popover-open) { display: none; }
255
+ .rest:popover-open { position: fixed; inset: auto 0 0 0; margin: 0; width: auto; max-height: 70vh; overflow: auto; padding: 1rem 1rem 1.25rem; row-gap: 0.75rem; background: var(--pencil-surface-menu, Canvas); color: var(--pencil-muted, CanvasText); border-top: 1px solid var(--pencil-rule, color-mix(in srgb, currentColor 25%, transparent)); box-shadow: 0 -0.5rem 1.5rem rgb(0 0 0 / 0.15); font: var(--pencil-controls-font, 0.875rem/1.4 ui-sans-serif, system-ui, sans-serif); }
256
+ }
257
+ `;
258
+
259
+ /** The rows, in order: time, beats, each param's control, then the readouts. */
260
+ function rows({ info, moment, paused, disabled }) {
261
+ const { params = [], beats = [], usesTime } = info;
262
+ const { time = 0, values = {}, ranges = {}, readouts = [] } = moment ?? {};
263
+ const out = [];
264
+
265
+ if (usesTime) {
266
+ const duration = info.duration ?? LOOP;
267
+ out.push(
268
+ `<div class="row time" part="row time">` +
269
+ `<button${attrs({ type: 'button', class: 'play', part: 'button play', 'data-play': true, disabled })}>` +
270
+ `<span${attrs({ 'data-on': paused })}>Play</span><span${attrs({ 'data-on': !paused })}>Pause</span></button>` +
271
+ `<input${attrs({ type: 'range', id: 'time', part: 'slider time', 'data-time': true, min: 0, max: duration, step: 0.001, value: time, 'aria-label': 'Time', 'aria-valuetext': timeText(time), disabled })}>` +
272
+ `<output${attrs({ for: 'time', part: 'value time', 'data-time': true, 'aria-live': 'off', style: room(timeText(duration)) })}>${timeText(time)}</output>` +
273
+ `</div>`,
274
+ );
275
+ }
276
+
277
+ if (steps(info)) {
278
+ const range = params.find((p) => p.id === 'beat');
279
+ const beat = Number.isFinite(values.beat) ? values.beat : 0;
280
+ const at = beatAt(info, beat);
281
+ // The widest it says is a beat part done, as `9.5 / 10`, when beats have lengths.
282
+ const widest = timed(info) ? `${beats.length}.5 / ${beats.length}` : `${beats.length} / ${beats.length}`;
283
+ const captions = beats
284
+ .map((caption, i) => `<span${attrs({ class: 'caption', part: 'caption', 'data-on': i === at.caption })}>${escape(caption ?? '')}</span>`)
285
+ .join('');
286
+ out.push(
287
+ `<div class="row beats" part="row beats">` +
288
+ `<button${attrs({ type: 'button', part: 'button step', 'data-step': -1, title: 'Previous beat', 'aria-label': 'Previous beat', disabled: disabled || beat <= range.min })}>←</button>` +
289
+ `<output${attrs({ part: 'value beat', 'data-beat': true, 'aria-live': 'off', style: room(widest) })}>${at.text}</output>` +
290
+ `<button${attrs({ type: 'button', part: 'button step', 'data-step': 1, title: 'Next beat', 'aria-label': 'Next beat', disabled: disabled || beat >= range.max })}>→</button>` +
291
+ `<span class="captions" part="captions" data-captions>${captions}</span>` +
292
+ `</div>`,
293
+ );
294
+ }
295
+
296
+ for (const param of controlled(info)) {
297
+ const id = `param-${param.id}`;
298
+ const name = param.control?.name ?? param.choice?.of ?? param.id;
299
+ const value = values[param.id];
300
+ const index = Math.round(value);
301
+ const kind = kindOf(param);
302
+ const label = labelHtml(param);
303
+ const called = controlName(param);
304
+ if (kind === 'radios') {
305
+ const options = param.choice.options
306
+ .map(
307
+ (text, i) =>
308
+ `<label class="option" part="option"><input${attrs({ type: 'radio', part: 'radio', name: id, 'data-param': name, value: i, checked: i === index, disabled })}>${escape(text)}</label>`,
309
+ )
310
+ .join('');
311
+ out.push(
312
+ `<fieldset class="row choice" part="row choice">` +
313
+ `<legend${attrs({ part: 'label', class: label ? undefined : 'said' })}>${label || escape(called)}</legend>${options}</fieldset>`,
314
+ );
315
+ continue;
316
+ }
317
+ if (kind === 'checkbox') {
318
+ out.push(
319
+ `<div class="row choice" part="row choice"><label part="label">` +
320
+ `<input${attrs({ type: 'checkbox', id, part: 'checkbox', 'data-param': name, checked: index === 1, 'aria-label': label ? undefined : called, disabled })}>${label}</label></div>`,
321
+ );
322
+ continue;
323
+ }
324
+ let input;
325
+ if (kind === 'select') {
326
+ const options = param.choice.options
327
+ .map((text, i) => `<option${attrs({ value: i, selected: i === index })}>${escape(text)}</option>`)
328
+ .join('');
329
+ input = `<select${attrs({ id, part: 'select', 'data-param': name, 'aria-label': label ? undefined : called, disabled })}>${options}</select>`;
330
+ } else {
331
+ const [min, max] = ranges[param.id] ?? [param.min, param.max];
332
+ const step = param.step ?? ((param.max - param.min) / 1000 || 0.001);
333
+ input = `<input${attrs({
334
+ type: 'range',
335
+ id,
336
+ part: 'slider',
337
+ 'data-param': name,
338
+ min,
339
+ max,
340
+ step,
341
+ value: Number.isFinite(value) ? value : undefined,
342
+ 'aria-label': label ? undefined : called,
343
+ 'aria-valuetext': valueText(param, value),
344
+ disabled,
345
+ })}>`;
346
+ }
347
+ // A choice says itself, so only a slider says its value after it.
348
+ const widest = param.choice ? param.choice.options : [valueText(param, param.min), valueText(param, param.max)];
349
+ const out_ =
350
+ kind === 'slider' && saysValue(param)
351
+ ? `<output${attrs({ for: id, part: 'value', 'data-param': name, 'aria-live': 'off', style: room(...widest) })}>${escape(valueText(param, value))}</output>`
352
+ : '';
353
+ // Three cells, always, so every row keeps to the grid's columns.
354
+ const said = label ? `<label${attrs({ for: id, part: 'label', class: 'param' })}>${label}</label>` : '<span></span>';
355
+ out.push(`<div class="row param" part="row param">${said}${input}${out_ || '<span></span>'}</div>`);
356
+ }
357
+
358
+ const said = info.readouts ?? [];
359
+ if (said.length) {
360
+ out.readouts = out.length;
361
+ const boxes = said
362
+ .map((readout, i) => {
363
+ const [width, height] = readout.room ?? [readouts[i]?.width ?? 4, readouts[i]?.height ?? 1.4];
364
+ return `<output${attrs({ class: 'readout', part: 'readout', 'data-readout': readout.id, 'aria-live': 'off', style: `--width: ${width}; --height: ${height}` })}>${readoutHtml(readouts[i])}</output>`;
365
+ })
366
+ .join('');
367
+ out.push(`<div class="row readouts" part="row readouts">${boxes}</div>`);
368
+ }
369
+ return out;
370
+ }
371
+
372
+ /**
373
+ * The controls for a figure, as the inside of their shadow root, after its styles.
374
+ *
375
+ * - `info`: what the figure says of itself, with each readout's `room` from a build or the element.
376
+ * - `moment`: where it stands: `{ time, values, ranges, readouts }`, the first three by param, and
377
+ * what each readout says.
378
+ * - `paused`: whether it's paused, for the play button.
379
+ * - `disabled`: the figure isn't ready, so nothing can be worked yet.
380
+ * - `extra`: the page puts something of its own in `<pencil-controls>`, as a choice of looks,
381
+ * which comes after the defaults, and on a phone in their menu.
382
+ */
383
+ export function markup({ info, moment, paused = false, disabled = false, extra = false }) {
384
+ const all = rows({ info, moment, paused, disabled });
385
+ const at = BAR === 'readouts' && all.readouts !== undefined ? all.readouts : 0;
386
+ const first = all[at];
387
+ const rest = all.filter((_, i) => i !== at);
388
+ // On a phone the beats' caption is a line of its own with the bar, wherever the stepper is: it's
389
+ // the figure's own words. Every caption lies in its one place, so it's as tall as the longest.
390
+ const beats = all.find((row) => row.startsWith('<div class="row beats"'));
391
+ const captions = beats
392
+ ? `<div class="row captions-row phone" part="row captions">${beats.slice(beats.indexOf('<span class="captions"'), beats.lastIndexOf('</div>'))}</div>`
393
+ : '';
394
+ // Where it is in the beats and what the caption says, said when a beat changes, wherever the
395
+ // stepper is, so Next beat is heard.
396
+ const said = beats ? '<span class="said" data-said role="status" aria-live="polite"></span>' : '';
397
+ // On a phone the button opens the menu, and shows whenever anything is in it: the rows that aren't
398
+ // the bar's, what the page put in, or the bar's own row when it doesn't fit.
399
+ const more =
400
+ `<button${attrs({ type: 'button', class: 'more', part: 'button more', popovertarget: 'rest', 'aria-label': 'More controls', title: 'More controls' })}>` +
401
+ `<span class="more-words">Controls</span> ⋯</button>`;
402
+ const menu = rest.length > 0 || extra;
403
+ return (
404
+ `<div${attrs({ class: 'controls', part: 'controls', 'data-more': first && menu, 'data-menu': first && menu })}>` +
405
+ (first ? `<div class="bar" part="bar">${first}${more}</div>` : '') +
406
+ captions +
407
+ `<div class="rest" id="rest" part="rest"${first ? ' popover' : ''}>${rest.join('')}<slot></slot></div>` +
408
+ said +
409
+ `</div>`
410
+ );
411
+ }
412
+
413
+ /** The controls as a declarative shadow root, for a build to write inside `<pencil-controls>`, so
414
+ * they have their place and their size before any script runs. */
415
+ export function declarative(options) {
416
+ return `<template shadowrootmode="open"><style>${CONTROLS_CSS}</style>${markup(options)}</template>`;
417
+ }