@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.
Binary file
@@ -0,0 +1,449 @@
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 a bar keeps one row, `barRow` says which, and the
11
+ // rest drop down from it in a menu over the page, so the figure keeps the height. The bar never
12
+ // splits a figure's params: it keeps one only when it's the figure's only one. Its row, too, goes
13
+ // behind the menu if it doesn't fit (the element checks), so nothing in the bar is ever cut off.
14
+ //
15
+ // Every control is marked with what it sets (`data-param`, `data-time`, `data-play`, `data-step`),
16
+ // and each output with what it shows (`data-param`, `data-time`, `data-beat`, `data-readout`), as a
17
+ // page's own controls are. The element wires them the same way either way.
18
+ import { FAMILY } from './labels.js';
19
+
20
+ const escape = (text) => String(text).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
21
+ const attrs = (pairs) =>
22
+ Object.entries(pairs)
23
+ .filter(([, value]) => value !== undefined && value !== null && value !== false)
24
+ .map(([name, value]) => (value === true ? ` ${name}` : ` ${name}="${escape(value)}"`))
25
+ .join('');
26
+
27
+ /** How long time runs before it loops, for a figure that declares no `duration`, as the element has it. */
28
+ const LOOP = 10;
29
+
30
+ /**
31
+ * Which of the rows a phone's bar keeps, with the rest behind its menu: the playback, which is the
32
+ * time's row or else the beats', or else the readouts, or else the figure's one param. A figure with
33
+ * more params than one and nothing else keeps none, and its bar is only the menu's button, so its
34
+ * params are in the menu together. `rows` is what `rows()` gives, and this gives one of them or
35
+ * `undefined`.
36
+ */
37
+ function barRow(rows) {
38
+ for (const kind of ['time', 'beats', 'readouts']) {
39
+ const row = rows.find((each) => each.kind === kind);
40
+ if (row) return row;
41
+ }
42
+ const params = rows.filter((each) => each.kind === 'param');
43
+ return params.length === 1 ? params[0] : undefined;
44
+ }
45
+
46
+ /** When the controls are a phone's: one row, and a menu. The styles below say the same. */
47
+ export const PHONE = '(max-width: 40rem), (max-height: 32rem)';
48
+
49
+ /** As many decimals as a param's step has, so a whole-number param reads as one. */
50
+ export const decimals = (param) => (param.step == null ? 2 : (String(param.step).split('.')[1] ?? '').length);
51
+
52
+ /** A param's value as its control says it: a choice's option, or the number. One that doesn't exist
53
+ * this frame is a dash. */
54
+ export function valueText(param, value) {
55
+ if (!Number.isFinite(value)) return '—';
56
+ if (param.choice) return param.choice.options[Math.round(value)] ?? '—';
57
+ return value.toFixed(decimals(param)).replace('-', '−');
58
+ }
59
+
60
+ export const timeText = (seconds) => `${seconds.toFixed(1)} s`;
61
+
62
+ /** Whether a handle sets this param. Its handle is its control: it takes focus and the arrow
63
+ * keys, and says its value to a screen reader, so the param gets no control of its own. */
64
+ export const handled = (info, param) => (info.handles ?? []).some((handle) => handle.params.includes(param.id));
65
+
66
+ /** Whether the figure has beats to step through. */
67
+ export const steps = (info) => (info.beats?.length ?? 0) > 0 && info.params.some((p) => p.id === 'beat');
68
+
69
+ /** The params that get a control: each one a handle doesn't set, and not `beat` when it's stepped. */
70
+ export const controlled = (info) => info.params.filter((p) => !(p.id === 'beat' && steps(info)) && !handled(info, p));
71
+
72
+ /** Whether a figure has anything for its controls to show: time, beats, a param, or a readout. */
73
+ export const hasControls = (info) =>
74
+ !!info && (info.usesTime || steps(info) || controlled(info).length > 0 || (info.readouts?.length ?? 0) > 0);
75
+
76
+ /** The param a control or an output is for: `data-param` names it, or for a choice, its value. */
77
+ export const paramNamed = (info, name) => info?.params.find((p) => p.id === name || p.choice?.of === name);
78
+
79
+ /** Beats with lengths count the beats done, from 0 to n. Ones without say which beat it's on. */
80
+ const timed = (info) => (info.beatLengths?.length ?? 0) > 0;
81
+
82
+ /** Where a figure is in its beats: what the counter says, and which caption shows. */
83
+ export function beatAt(info, beat) {
84
+ const n = info.beats.length;
85
+ const at = Number.isFinite(beat) ? beat : 0;
86
+ const shown = timed(info) ? at : at + 1;
87
+ const whole = Math.abs(shown - Math.round(shown)) < 1e-6;
88
+ return {
89
+ text: `${whole ? Math.round(shown) : shown.toFixed(1)} / ${n}`,
90
+ caption: timed(info) ? Math.min(n - 1, Math.max(0, Math.ceil(at) - 1)) : Math.round(at),
91
+ };
92
+ }
93
+
94
+ /** What a param's control says it is, as its sheets' `text` picks: its caption, or its name, as
95
+ * parts joined by ` = `, each `{ text, math }`. Its value isn't one of them: it's said after the
96
+ * control. A control with no caption says its name, which is mathematics. */
97
+ export function controlParts(param) {
98
+ const name = param.control?.name ?? param.choice?.of ?? param.id;
99
+ const said = [];
100
+ for (const part of param.control?.text ?? ['caption', 'value']) {
101
+ const piece =
102
+ part === 'caption' ? (param.caption ? { text: param.caption, math: false } : { text: name, math: true })
103
+ : part === 'name' || part === 'expr' ? { text: name, math: true }
104
+ : null;
105
+ if (piece && !said.some((each) => each.text === piece.text)) said.push(piece);
106
+ }
107
+ return said;
108
+ }
109
+
110
+ /** What a control is called, for a screen reader: what it says, or its caption or name when it
111
+ * says only its value. */
112
+ export function controlName(param) {
113
+ const parts = controlParts(param);
114
+ if (parts.length) return parts.map((part) => part.text).join(' = ');
115
+ return param.caption ?? param.control?.name ?? param.choice?.of ?? param.id;
116
+ }
117
+
118
+ /** Whether a control says its value after it: a slider does unless its sheets leave `value` out. */
119
+ export const saysValue = (param) => (param.control?.text ?? ['caption', 'value']).includes('value');
120
+
121
+ /** Which control a param gets, as the core works it out from the figure and its sheets. */
122
+ export const kindOf = (param) => param.control?.kind ?? (param.choice ? 'select' : 'slider');
123
+
124
+ const labelHtml = (param) =>
125
+ controlParts(param)
126
+ .map((part) => (part.math ? `<var>${escape(part.text)}</var>` : escape(part.text)))
127
+ .join(' = ');
128
+
129
+ /** The room an output needs: as many digits wide as the longest thing it will say. With
130
+ * tabular figures a digit is a `ch`, and a sign, a point and a space are no wider. */
131
+ const room = (...texts) => `--room: ${Math.max(...texts.map((text) => String(text).length))}ch`;
132
+
133
+ /**
134
+ * What kind of controls a figure has, as a short string. Controls made for one figure fit another
135
+ * with the same one, so the element keeps what a build wrote and only turns it on.
136
+ */
137
+ export function shape(info) {
138
+ const text = JSON.stringify([
139
+ info.usesTime,
140
+ info.duration,
141
+ info.beats,
142
+ timed(info),
143
+ info.params.map((p) => [p.id, p.min, p.max, p.step, p.choice, handled(info, p), p.caption, p.control]),
144
+ (info.readouts ?? []).map((r) => r.id),
145
+ ]);
146
+ let hash = 5381;
147
+ for (let i = 0; i < text.length; i++) hash = ((hash * 33) ^ text.charCodeAt(i)) >>> 0;
148
+ return hash.toString(36);
149
+ }
150
+
151
+ const px = (v) => `${Math.round(v * 1e4) / 1e4}em`;
152
+
153
+ /**
154
+ * What a readout says, as HTML to put in its box: what the core laid out, each run and rule placed
155
+ * in ems from the left of its line and its middle, as a label over the figure is, in the same
156
+ * fonts. Every style is inline, so it reads the same in a page's own box as in the defaults. Its
157
+ * words are there for a screen reader, and the runs aren't.
158
+ *
159
+ * `readout` is one of the element's `readouts`, or of what a build says of the poster's moment:
160
+ * `{ id, text, words, math, width, height, laid }`.
161
+ */
162
+ export function readoutHtml(readout) {
163
+ if (!readout) return '';
164
+ const box = `position:relative;display:inline-block;vertical-align:middle;width:${px(readout.width)};height:${px(readout.height)}`;
165
+ const run = `position:absolute;white-space:pre;line-height:1;font-kerning:none;font-variant-ligatures:none;font-feature-settings:'calt' 0`;
166
+ const sans = `font-family:${FAMILY.sans};font-style:normal`;
167
+ const italic = `font-family:${FAMILY.math};font-style:italic`;
168
+ const formula = `font-family:'Pencil Math', ${FAMILY.math};font-style:normal`;
169
+ const said = `<span style="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap">${escape(readout.words)}</span>`;
170
+ let drawn;
171
+ if (!readout.laid) {
172
+ drawn = `<span style="${run};left:0;top:calc(50% - 0.5em);font-size:1em;${readout.math ? italic : sans}">${escape(readout.words)}</span>`;
173
+ } else {
174
+ const words = readout.math ? italic : sans;
175
+ drawn = readout.laid.runs
176
+ .map((r) => {
177
+ const stretch = r.stretch !== 1 ? `;transform:scaleY(${r.stretch});transform-origin:0 ${(0.5 + 0.324) * 100}%` : '';
178
+ 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>`;
179
+ })
180
+ .concat(
181
+ readout.laid.rules.map(
182
+ (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>`,
183
+ ),
184
+ )
185
+ .join('');
186
+ }
187
+ return `<span aria-hidden="true" style="${box}">${drawn}</span>${said}`;
188
+ }
189
+
190
+ /** The defaults' styles, in their shadow root. A page styles them through `::part` and these custom
191
+ * properties, which inherit into it:
192
+ *
193
+ * - `--pencil-controls-font`: their text, as the `font` shorthand.
194
+ * - `--pencil-ink`: values, and a name, which is mathematics. `--pencil-muted`: what controls say
195
+ * they are, and captions.
196
+ * - `--pencil-accent`: sliders, radios and checkboxes. `--pencil-rule` and `--pencil-surface`: a
197
+ * button's border and background. On a phone the menu has `--pencil-rule` for its border too, and
198
+ * `--pencil-surface-menu` for its background.
199
+ * - `--pencil-math-font`: a param's name, as the `font` shorthand.
200
+ * - `--pencil-focus`: the focus ring, as on the figure's handles.
201
+ * - `--pencil-readout-size`: how big a readout's text is.
202
+ */
203
+ export const CONTROLS_CSS = `
204
+ :host { display: block; }
205
+ :host([hidden]) { display: none; }
206
+ /* One grid, so every slider starts and ends where the others do: what a control says, the control,
207
+ and its value. What a control says wraps past two fifths of the width, so a long caption doesn't
208
+ squeeze its slider. A row of anything else takes the whole width. */
209
+ .controls, .rest { display: grid; grid-template-columns: fit-content(40%) minmax(0, 1fr) max-content; gap: 0.375rem 0.75rem; align-items: center; }
210
+ .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)); }
211
+ .bar, .rest { display: contents; }
212
+ .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; }
213
+ .more, .more-words, .row.phone { display: none; }
214
+ .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; }
215
+ .row.param, .row.time { display: contents; }
216
+ /* The readouts come after the controls, though a phone's bar can hold them, and what a page put in
217
+ after them. */
218
+ .row.readouts { order: 1; }
219
+ slot { display: contents; }
220
+ ::slotted(*) { grid-column: 1 / -1; order: 2; }
221
+ fieldset.row { min-inline-size: 0; }
222
+ legend { float: left; padding: 0; margin-right: 0.25rem; }
223
+ label { display: inline-flex; align-items: center; gap: 0.375rem; }
224
+ .option { gap: 0.25rem; }
225
+ 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); }
226
+ input[type='radio'], input[type='checkbox'] { margin: 0; accent-color: var(--pencil-accent, auto); }
227
+ select { justify-self: start; }
228
+ 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; }
229
+ .beats output { text-align: center; }
230
+ var { font: var(--pencil-math-font, italic 1.07em Charter, 'Bitstream Charter', 'Sitka Text', Cambria, Georgia, serif); color: var(--pencil-ink, currentColor); }
231
+ /* Every caption lies in the same place and only the beat's own shows, so the row is as tall as the
232
+ longest from the start and stepping moves nothing below it. */
233
+ .captions { flex-basis: 100%; display: grid; font-style: italic; min-width: 0; }
234
+ .caption { grid-area: 1 / 1; visibility: hidden; }
235
+ .caption[data-on] { visibility: visible; }
236
+ .readouts { gap: 0.25rem 1.25rem; -webkit-user-select: text; user-select: text; }
237
+ .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; }
238
+ 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; }
239
+ button:disabled { opacity: 0.4; cursor: default; }
240
+ input:disabled, select:disabled { cursor: default; }
241
+ /* The play button is as wide as the wider of its words, so it doesn't move what's beside it. */
242
+ .play { display: inline-grid; flex: none; justify-self: start; }
243
+ .play > span { grid-area: 1 / 1; }
244
+ .play > span:not([data-on]) { visibility: hidden; }
245
+ :focus-visible { outline: 2px solid var(--pencil-focus, currentColor); outline-offset: 2px; }
246
+ input[type='range']:focus-visible { outline-offset: 1px; }
247
+ .said { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
248
+ /* On a phone, or a screen with little height, one row stays, on one line, in a bar of fixed height,
249
+ and the rest drop down from it in a menu over the page, as wide as the controls: the figure keeps
250
+ the height. Each thing in the bar keeps its own width, so the element can tell when the row
251
+ doesn't fit, and then it goes behind the menu too. A bar that holds no row, for either reason,
252
+ says what its button opens. The beats' caption is a line of its own under the bar, as tall as the
253
+ longest caption at that width, wherever the stepper is, and the menu drops from under it, so the
254
+ caption shows while a reader steps in the menu. The element places the menu where the controls
255
+ end, in the page's coordinates, which its containing block has in the top layer, so it scrolls
256
+ with the page and stays under its bar, and moves it with them while it's open. */
257
+ @media (max-width: 40rem), (max-height: 32rem) {
258
+ .controls { display: block; }
259
+ .bar { display: flex; align-items: center; gap: 0.5rem; height: 2.25rem; min-width: 0; }
260
+ .bar > .row, .bar > .row.param, .bar > .row.time { display: flex; flex: 1 1 auto; order: 0; min-width: 0; flex-wrap: nowrap; overflow: hidden; gap: 0.5rem 0.75rem; }
261
+ .bar > .row > *, .bar > .row label { flex: none; white-space: nowrap; }
262
+ .bar > .row > input[type='range'] { flex: 1 1 4rem; min-width: 4rem; }
263
+ .beats .captions { display: none; }
264
+ .row.phone { display: flex; margin-top: 0.25rem; }
265
+ .row.phone .caption { white-space: normal; }
266
+ .controls[data-more] .more { display: inline-flex; align-items: center; gap: 0.375rem; flex: none; margin-inline-start: auto; padding: 0.25rem 0.5rem; line-height: 1; }
267
+ .bar:not(:has(> .row)) .more-words { display: inline; }
268
+ .rest { display: grid; }
269
+ .rest[popover]:not(:popover-open) { display: none; }
270
+ .rest:popover-open { position: absolute; inset: auto; top: var(--menu-top, 0); left: var(--menu-left, 0); width: var(--menu-width, 100%); box-sizing: border-box; margin: 0; max-height: 60vh; overflow: auto; overscroll-behavior: contain; padding: 0.875rem 1rem 1rem; row-gap: 0.75rem; background: var(--pencil-surface-menu, Canvas); color: var(--pencil-muted, CanvasText); border: 1px solid var(--pencil-rule, color-mix(in srgb, currentColor 25%, transparent)); border-radius: 6px; 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); }
271
+ }
272
+ `;
273
+
274
+ /** The rows, in order: time, beats, each param's control, then the readouts, each as `{ kind, html }`,
275
+ * its kind `time`, `beats`, `param` or `readouts`. */
276
+ function rows({ info, moment, paused, disabled }) {
277
+ const { params = [], beats = [], usesTime } = info;
278
+ const { time = 0, values = {}, ranges = {}, readouts = [] } = moment ?? {};
279
+ const out = [];
280
+
281
+ if (usesTime) {
282
+ const duration = info.duration ?? LOOP;
283
+ out.push({
284
+ kind: 'time',
285
+ html:
286
+ `<div class="row time" part="row time">` +
287
+ `<button${attrs({ type: 'button', class: 'play', part: 'button play', 'data-play': true, disabled })}>` +
288
+ `<span${attrs({ 'data-on': paused })}>Play</span><span${attrs({ 'data-on': !paused })}>Pause</span></button>` +
289
+ `<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 })}>` +
290
+ `<output${attrs({ for: 'time', part: 'value time', 'data-time': true, 'aria-live': 'off', style: room(timeText(duration)) })}>${timeText(time)}</output>` +
291
+ `</div>`,
292
+ });
293
+ }
294
+
295
+ if (steps(info)) {
296
+ const range = params.find((p) => p.id === 'beat');
297
+ const beat = Number.isFinite(values.beat) ? values.beat : 0;
298
+ const at = beatAt(info, beat);
299
+ // The widest it says is a beat part done, as `9.5 / 10`, when beats have lengths.
300
+ const widest = timed(info) ? `${beats.length}.5 / ${beats.length}` : `${beats.length} / ${beats.length}`;
301
+ const captions = beats
302
+ .map((caption, i) => `<span${attrs({ class: 'caption', part: 'caption', 'data-on': i === at.caption })}>${escape(caption ?? '')}</span>`)
303
+ .join('');
304
+ out.push({
305
+ kind: 'beats',
306
+ html:
307
+ `<div class="row beats" part="row beats">` +
308
+ `<button${attrs({ type: 'button', part: 'button step', 'data-step': -1, title: 'Previous beat', 'aria-label': 'Previous beat', disabled: disabled || beat <= range.min })}>←</button>` +
309
+ `<output${attrs({ part: 'value beat', 'data-beat': true, 'aria-live': 'off', style: room(widest) })}>${at.text}</output>` +
310
+ `<button${attrs({ type: 'button', part: 'button step', 'data-step': 1, title: 'Next beat', 'aria-label': 'Next beat', disabled: disabled || beat >= range.max })}>→</button>` +
311
+ `<span class="captions" part="captions" data-captions>${captions}</span>` +
312
+ `</div>`,
313
+ });
314
+ }
315
+
316
+ for (const param of controlled(info)) {
317
+ const id = `param-${param.id}`;
318
+ const name = param.control?.name ?? param.choice?.of ?? param.id;
319
+ const value = values[param.id];
320
+ const index = Math.round(value);
321
+ const kind = kindOf(param);
322
+ const label = labelHtml(param);
323
+ const called = controlName(param);
324
+ if (kind === 'radios') {
325
+ const options = param.choice.options
326
+ .map(
327
+ (text, i) =>
328
+ `<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>`,
329
+ )
330
+ .join('');
331
+ out.push({
332
+ kind: 'param',
333
+ html:
334
+ `<fieldset class="row choice" part="row choice">` +
335
+ `<legend${attrs({ part: 'label', class: label ? undefined : 'said' })}>${label || escape(called)}</legend>${options}</fieldset>`,
336
+ });
337
+ continue;
338
+ }
339
+ if (kind === 'checkbox') {
340
+ out.push({
341
+ kind: 'param',
342
+ html:
343
+ `<div class="row choice" part="row choice"><label part="label">` +
344
+ `<input${attrs({ type: 'checkbox', id, part: 'checkbox', 'data-param': name, checked: index === 1, 'aria-label': label ? undefined : called, disabled })}>${label}</label></div>`,
345
+ });
346
+ continue;
347
+ }
348
+ let input;
349
+ if (kind === 'select') {
350
+ const options = param.choice.options
351
+ .map((text, i) => `<option${attrs({ value: i, selected: i === index })}>${escape(text)}</option>`)
352
+ .join('');
353
+ input = `<select${attrs({ id, part: 'select', 'data-param': name, 'aria-label': label ? undefined : called, disabled })}>${options}</select>`;
354
+ } else {
355
+ const [min, max] = ranges[param.id] ?? [param.min, param.max];
356
+ const step = param.step ?? ((param.max - param.min) / 1000 || 0.001);
357
+ input = `<input${attrs({
358
+ type: 'range',
359
+ id,
360
+ part: 'slider',
361
+ 'data-param': name,
362
+ min,
363
+ max,
364
+ step,
365
+ value: Number.isFinite(value) ? value : undefined,
366
+ 'aria-label': label ? undefined : called,
367
+ 'aria-valuetext': valueText(param, value),
368
+ disabled,
369
+ })}>`;
370
+ }
371
+ // A choice says itself, so only a slider says its value after it.
372
+ const widest = param.choice ? param.choice.options : [valueText(param, param.min), valueText(param, param.max)];
373
+ const out_ =
374
+ kind === 'slider' && saysValue(param)
375
+ ? `<output${attrs({ for: id, part: 'value', 'data-param': name, 'aria-live': 'off', style: room(...widest) })}>${escape(valueText(param, value))}</output>`
376
+ : '';
377
+ // Three cells, always, so every row keeps to the grid's columns.
378
+ const said = label ? `<label${attrs({ for: id, part: 'label', class: 'param' })}>${label}</label>` : '<span></span>';
379
+ out.push({ kind: 'param', html: `<div class="row param" part="row param">${said}${input}${out_ || '<span></span>'}</div>` });
380
+ }
381
+
382
+ const said = info.readouts ?? [];
383
+ if (said.length) {
384
+ const boxes = said
385
+ .map((readout, i) => {
386
+ const [width, height] = readout.room ?? [readouts[i]?.width ?? 4, readouts[i]?.height ?? 1.4];
387
+ return `<output${attrs({ class: 'readout', part: 'readout', 'data-readout': readout.id, 'aria-live': 'off', style: `--width: ${width}; --height: ${height}` })}>${readoutHtml(readouts[i])}</output>`;
388
+ })
389
+ .join('');
390
+ out.push({ kind: 'readouts', html: `<div class="row readouts" part="row readouts">${boxes}</div>` });
391
+ }
392
+ return out;
393
+ }
394
+
395
+ /**
396
+ * The controls for a figure, as the inside of their shadow root, after its styles.
397
+ *
398
+ * - `info`: what the figure says of itself, with each readout's `room` from a build or the element.
399
+ * - `moment`: where it stands: `{ time, values, ranges, readouts }`, the first three by param, and
400
+ * what each readout says.
401
+ * - `paused`: whether it's paused, for the play button.
402
+ * - `disabled`: the figure isn't ready, so nothing can be worked yet.
403
+ * - `extra`: the page puts something of its own in `<pencil-controls>`, as a choice of looks,
404
+ * which comes after the defaults, and on a phone in their menu.
405
+ */
406
+ export function markup({ info, moment, paused = false, disabled = false, extra = false }) {
407
+ const all = rows({ info, moment, paused, disabled });
408
+ // A figure with rows of its own has a bar on a phone, which can hold only the menu's button. One
409
+ // with none, and only what the page put in, has no bar, and that shows where it is.
410
+ const bar = all.length > 0;
411
+ const kept = barRow(all);
412
+ const rest = all.filter((row) => row !== kept);
413
+ // The bar's row comes first in the page, so readouts the bar keeps come before the params, and
414
+ // a screen reader reads them first, though on a desktop they're shown after. That's accepted:
415
+ // a readout takes no focus, so the order Tab goes in is the same.
416
+ // On a phone the beats' caption is a line of its own with the bar, wherever the stepper is: it's
417
+ // the figure's own words. Every caption lies in its one place, so it's as tall as the longest.
418
+ const beats = all.find((row) => row.kind === 'beats')?.html;
419
+ const captions = beats
420
+ ? `<div class="row captions-row phone" part="row captions">${beats.slice(beats.indexOf('<span class="captions"'), beats.lastIndexOf('</div>'))}</div>`
421
+ : '';
422
+ // Where it is in the beats and what the caption says, said when a beat changes, wherever the
423
+ // stepper is, so Next beat is heard.
424
+ const said = beats ? '<span class="said" data-said role="status" aria-live="polite"></span>' : '';
425
+ // On a phone the button opens the menu, and shows whenever anything is in it: the rows that aren't
426
+ // the bar's, what the page put in, or the bar's own row when it doesn't fit. It says "Controls"
427
+ // whenever the bar holds no row beside it, and is called that, and "More controls" beside one.
428
+ // Like the rest it's disabled until the figure loads, or a build's menu would open before the
429
+ // element is there to place it.
430
+ const name = kept ? 'More controls' : 'Controls';
431
+ const more =
432
+ `<button${attrs({ type: 'button', class: 'more', part: 'button more', popovertarget: 'rest', 'aria-label': name, title: name, disabled })}>` +
433
+ `<span class="more-words">Controls</span> ⋯</button>`;
434
+ const menu = rest.length > 0 || extra;
435
+ return (
436
+ `<div${attrs({ class: 'controls', part: 'controls', 'data-more': bar && menu, 'data-menu': bar && menu })}>` +
437
+ (bar ? `<div class="bar" part="bar">${kept?.html ?? ''}${more}</div>` : '') +
438
+ captions +
439
+ `<div class="rest" id="rest" part="rest"${bar ? ' popover' : ''}>${rest.map((row) => row.html).join('')}<slot></slot></div>` +
440
+ said +
441
+ `</div>`
442
+ );
443
+ }
444
+
445
+ /** The controls as a declarative shadow root, for a build to write inside `<pencil-controls>`, so
446
+ * they have their place and their size before any script runs. */
447
+ export function declarative(options) {
448
+ return `<template shadowrootmode="open"><style>${CONTROLS_CSS}</style>${markup(options)}</template>`;
449
+ }