@pencil-lang/figure 0.0.6 → 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
package/src/controls.js CHANGED
@@ -7,9 +7,10 @@
7
7
  // Nothing moves when a value changes. An `<output>` is as wide as the widest value its param's
8
8
  // range can show, a readout's box is as big as the most it says at the moments a build tries, every
9
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.
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.
13
14
  //
14
15
  // Every control is marked with what it sets (`data-param`, `data-time`, `data-play`, `data-step`),
15
16
  // and each output with what it shows (`data-param`, `data-time`, `data-beat`, `data-readout`), as a
@@ -27,11 +28,20 @@ const attrs = (pairs) =>
27
28
  const LOOP = 10;
28
29
 
29
30
  /**
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.
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`.
33
36
  */
34
- export const BAR = 'first';
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
+ }
35
45
 
36
46
  /** When the controls are a phone's: one row, and a menu. The styles below say the same. */
37
47
  export const PHONE = '(max-width: 40rem), (max-height: 32rem)';
@@ -184,7 +194,8 @@ export function readoutHtml(readout) {
184
194
  * - `--pencil-ink`: values, and a name, which is mathematics. `--pencil-muted`: what controls say
185
195
  * they are, and captions.
186
196
  * - `--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.
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.
188
199
  * - `--pencil-math-font`: a param's name, as the `font` shorthand.
189
200
  * - `--pencil-focus`: the focus ring, as on the figure's handles.
190
201
  * - `--pencil-readout-size`: how big a readout's text is.
@@ -202,8 +213,8 @@ export const CONTROLS_CSS = `
202
213
  .more, .more-words, .row.phone { display: none; }
203
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; }
204
215
  .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. */
216
+ /* The readouts come after the controls, though a phone's bar can hold them, and what a page put in
217
+ after them. */
207
218
  .row.readouts { order: 1; }
208
219
  slot { display: contents; }
209
220
  ::slotted(*) { grid-column: 1 / -1; order: 2; }
@@ -235,28 +246,33 @@ input:disabled, select:disabled { cursor: default; }
235
246
  input[type='range']:focus-visible { outline-offset: 1px; }
236
247
  .said { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
237
248
  /* 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. */
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. */
242
257
  @media (max-width: 40rem), (max-height: 32rem) {
243
258
  .controls { display: block; }
244
259
  .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; }
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; }
246
261
  .bar > .row > *, .bar > .row label { flex: none; white-space: nowrap; }
247
262
  .bar > .row > input[type='range'] { flex: 1 1 4rem; min-width: 4rem; }
248
263
  .beats .captions { display: none; }
249
264
  .row.phone { display: flex; margin-top: 0.25rem; }
250
265
  .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; }
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; }
253
268
  .rest { display: grid; }
254
269
  .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); }
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); }
256
271
  }
257
272
  `;
258
273
 
259
- /** The rows, in order: time, beats, each param's control, then the readouts. */
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`. */
260
276
  function rows({ info, moment, paused, disabled }) {
261
277
  const { params = [], beats = [], usesTime } = info;
262
278
  const { time = 0, values = {}, ranges = {}, readouts = [] } = moment ?? {};
@@ -264,14 +280,16 @@ function rows({ info, moment, paused, disabled }) {
264
280
 
265
281
  if (usesTime) {
266
282
  const duration = info.duration ?? LOOP;
267
- out.push(
268
- `<div class="row time" part="row time">` +
283
+ out.push({
284
+ kind: 'time',
285
+ html:
286
+ `<div class="row time" part="row time">` +
269
287
  `<button${attrs({ type: 'button', class: 'play', part: 'button play', 'data-play': true, disabled })}>` +
270
288
  `<span${attrs({ 'data-on': paused })}>Play</span><span${attrs({ 'data-on': !paused })}>Pause</span></button>` +
271
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 })}>` +
272
290
  `<output${attrs({ for: 'time', part: 'value time', 'data-time': true, 'aria-live': 'off', style: room(timeText(duration)) })}>${timeText(time)}</output>` +
273
291
  `</div>`,
274
- );
292
+ });
275
293
  }
276
294
 
277
295
  if (steps(info)) {
@@ -283,14 +301,16 @@ function rows({ info, moment, paused, disabled }) {
283
301
  const captions = beats
284
302
  .map((caption, i) => `<span${attrs({ class: 'caption', part: 'caption', 'data-on': i === at.caption })}>${escape(caption ?? '')}</span>`)
285
303
  .join('');
286
- out.push(
287
- `<div class="row beats" part="row beats">` +
304
+ out.push({
305
+ kind: 'beats',
306
+ html:
307
+ `<div class="row beats" part="row beats">` +
288
308
  `<button${attrs({ type: 'button', part: 'button step', 'data-step': -1, title: 'Previous beat', 'aria-label': 'Previous beat', disabled: disabled || beat <= range.min })}>←</button>` +
289
309
  `<output${attrs({ part: 'value beat', 'data-beat': true, 'aria-live': 'off', style: room(widest) })}>${at.text}</output>` +
290
310
  `<button${attrs({ type: 'button', part: 'button step', 'data-step': 1, title: 'Next beat', 'aria-label': 'Next beat', disabled: disabled || beat >= range.max })}>→</button>` +
291
311
  `<span class="captions" part="captions" data-captions>${captions}</span>` +
292
312
  `</div>`,
293
- );
313
+ });
294
314
  }
295
315
 
296
316
  for (const param of controlled(info)) {
@@ -308,17 +328,21 @@ function rows({ info, moment, paused, disabled }) {
308
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>`,
309
329
  )
310
330
  .join('');
311
- out.push(
312
- `<fieldset class="row choice" part="row choice">` +
331
+ out.push({
332
+ kind: 'param',
333
+ html:
334
+ `<fieldset class="row choice" part="row choice">` +
313
335
  `<legend${attrs({ part: 'label', class: label ? undefined : 'said' })}>${label || escape(called)}</legend>${options}</fieldset>`,
314
- );
336
+ });
315
337
  continue;
316
338
  }
317
339
  if (kind === 'checkbox') {
318
- out.push(
319
- `<div class="row choice" part="row choice"><label part="label">` +
340
+ out.push({
341
+ kind: 'param',
342
+ html:
343
+ `<div class="row choice" part="row choice"><label part="label">` +
320
344
  `<input${attrs({ type: 'checkbox', id, part: 'checkbox', 'data-param': name, checked: index === 1, 'aria-label': label ? undefined : called, disabled })}>${label}</label></div>`,
321
- );
345
+ });
322
346
  continue;
323
347
  }
324
348
  let input;
@@ -352,19 +376,18 @@ function rows({ info, moment, paused, disabled }) {
352
376
  : '';
353
377
  // Three cells, always, so every row keeps to the grid's columns.
354
378
  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>`);
379
+ out.push({ kind: 'param', html: `<div class="row param" part="row param">${said}${input}${out_ || '<span></span>'}</div>` });
356
380
  }
357
381
 
358
382
  const said = info.readouts ?? [];
359
383
  if (said.length) {
360
- out.readouts = out.length;
361
384
  const boxes = said
362
385
  .map((readout, i) => {
363
386
  const [width, height] = readout.room ?? [readouts[i]?.width ?? 4, readouts[i]?.height ?? 1.4];
364
387
  return `<output${attrs({ class: 'readout', part: 'readout', 'data-readout': readout.id, 'aria-live': 'off', style: `--width: ${width}; --height: ${height}` })}>${readoutHtml(readouts[i])}</output>`;
365
388
  })
366
389
  .join('');
367
- out.push(`<div class="row readouts" part="row readouts">${boxes}</div>`);
390
+ out.push({ kind: 'readouts', html: `<div class="row readouts" part="row readouts">${boxes}</div>` });
368
391
  }
369
392
  return out;
370
393
  }
@@ -382,12 +405,17 @@ function rows({ info, moment, paused, disabled }) {
382
405
  */
383
406
  export function markup({ info, moment, paused = false, disabled = false, extra = false }) {
384
407
  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);
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.
388
416
  // On a phone the beats' caption is a line of its own with the bar, wherever the stepper is: it's
389
417
  // 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"'));
418
+ const beats = all.find((row) => row.kind === 'beats')?.html;
391
419
  const captions = beats
392
420
  ? `<div class="row captions-row phone" part="row captions">${beats.slice(beats.indexOf('<span class="captions"'), beats.lastIndexOf('</div>'))}</div>`
393
421
  : '';
@@ -395,16 +423,20 @@ export function markup({ info, moment, paused = false, disabled = false, extra =
395
423
  // stepper is, so Next beat is heard.
396
424
  const said = beats ? '<span class="said" data-said role="status" aria-live="polite"></span>' : '';
397
425
  // 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.
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';
399
431
  const more =
400
- `<button${attrs({ type: 'button', class: 'more', part: 'button more', popovertarget: 'rest', 'aria-label': 'More controls', title: 'More controls' })}>` +
432
+ `<button${attrs({ type: 'button', class: 'more', part: 'button more', popovertarget: 'rest', 'aria-label': name, title: name, disabled })}>` +
401
433
  `<span class="more-words">Controls</span> ⋯</button>`;
402
434
  const menu = rest.length > 0 || extra;
403
435
  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>` : '') +
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>` : '') +
406
438
  captions +
407
- `<div class="rest" id="rest" part="rest"${first ? ' popover' : ''}>${rest.join('')}<slot></slot></div>` +
439
+ `<div class="rest" id="rest" part="rest"${bar ? ' popover' : ''}>${rest.map((row) => row.html).join('')}<slot></slot></div>` +
408
440
  said +
409
441
  `</div>`
410
442
  );
package/src/element.js CHANGED
@@ -42,6 +42,10 @@
42
42
  // within a handle's reach drags it and doesn't scroll the page; anywhere else on the figure the
43
43
  // page scrolls and zooms as it would over an image. Nothing in the figure is text to select, and a
44
44
  // drag never selects the page's. The element does all this itself: a page needs no CSS for it.
45
+ // A figure's shaders are compiled while the one before it, or its poster, stays on screen: on
46
+ // WebGPU the browser does that off the thread that composites the page, so the page doesn't stop.
47
+ // A figure asked for after another that's still compiling takes its place. Its handles and keys
48
+ // wait for it too.
45
49
  // A browser can lose the GPU under a figure, after sleep or when its GPU process restarts. The
46
50
  // figure then starts its GPU again, keeping its sources, time, held params and whether it's
47
51
  // paused, and shows its poster meanwhile. It tries at once, after a second and after five, then
@@ -56,12 +60,15 @@
56
60
  // with inputs and outputs marked `data-param="q"` or `data-readout="ratio"`, and the element sets
57
61
  // their ranges, steps and values and follows them each frame (`wiring.js`), with or without the
58
62
  // attribute. `readouts` is what the readouts say this frame.
59
- // Events: `load` when a figure is compiled, `draw` after each frame drawn, `resize` when its drawn
60
- // size or its em changes (its `detail.em`, in CSS pixels), `input` when a reader
61
- // drags a param (its `detail.name` and `detail.value`, and `detail.values`, every param that one
62
- // move set, by name: two for a point dragged in two dimensions), `play` and `pause`, `error` (its
63
- // `detail.error`) when one can't load or draw, and `recover` when one that said `error` because it
64
- // lost its GPU draws again.
63
+ // Events: `load` when a figure is compiled and its shaders are ready, `draw` after each frame
64
+ // drawn, `resize` when its drawn size or its em changes (its `detail.em`, in CSS pixels), `input`
65
+ // when a reader drags a param (its `detail.name` and `detail.value`, and `detail.values`, every
66
+ // param that one move set, by name: two for a point dragged in two dimensions), `play` and `pause`,
67
+ // `error` (its `detail.error`) when one can't load or draw, and `recover` when one that said
68
+ // `error` because it lost its GPU draws again. An `error` for a new figure's shaders, which the GPU
69
+ // couldn't make, has `detail.kept`: `true` when the figure before stays on screen, and `false` when
70
+ // the player had none, as for the first figure, or after a new player started, which then shows
71
+ // the figure that drew before, if there was one.
65
72
  import { Player, let_go, figure_size, figure_size_compiled, ready, isReady, gather, ahead } from './host.js';
66
73
  import { LABEL_CSS, LabelLayer, fonts } from './labels.js';
67
74
  import { match } from './fit.js';
@@ -112,8 +119,9 @@ slot { display: none; }
112
119
  .handles { position: absolute; inset: 0; pointer-events: none; }
113
120
  .handle { position: absolute; left: -14px; top: -14px; width: 28px; height: 28px; border-radius: 50%; outline: none; will-change: transform; pointer-events: auto; touch-action: none; }
114
121
  .handle::before { content: ''; position: absolute; inset: ${14 - REACH}px; border-radius: 50%; clip-path: var(--reach, none); }
115
- /* With no GPU, as while the poster shows, a handle can't be dragged, so it takes no pointer, and
116
- a touch on it scrolls the page. The keys still find it. */
122
+ /* With no figure on the GPU, as while the poster shows or a new player compiles the figure's
123
+ shaders, a handle can't be dragged, so it takes no pointer, and a touch on it scrolls the page.
124
+ The keys still find it. */
117
125
  .stage:not(.live) .handle { pointer-events: none; touch-action: auto; }
118
126
  .handle:focus-visible { outline: 2px solid var(--pencil-focus, currentColor); outline-offset: 1px; box-shadow: 0 0 0 2px var(--pencil-focus-halo, Canvas); }
119
127
  .handle[hidden] { display: none; }
@@ -161,7 +169,12 @@ export class PencilFigure extends HTMLElement {
161
169
  #player = null;
162
170
  #starting = false;
163
171
  #generation = 0;
164
- #sources = null; // { doc, sheets, names, files } or { compiled }, loaded or waiting for the GPU
172
+ #sources = null; // { doc, sheets, names, files } or { compiled }: the figure last put on a player
173
+ #announced = null; // the sources the last `load` was for: a start again shows them without news
174
+ #wanted = null; // sources a load asked for and that aren't shown yet: a new player starts from them
175
+ #promised = null; // `{ sources, resolve }`, the promise a load gave that's still waiting
176
+ #loads = 0; // each load the player is asked for, in turn: only the last one asked for is shown
177
+ #installed = false; // whether the player has a figure to draw
165
178
  #drawn = false; // whether a frame has been drawn since the canvas was made
166
179
  #children = null; // watches for a poster or a <source> arriving
167
180
  #media = []; // each <source>'s media query, and what's listening to it
@@ -426,20 +439,22 @@ export class PencilFigure extends HTMLElement {
426
439
  return;
427
440
  }
428
441
  this.#player = player;
442
+ this.#installed = false;
429
443
  this.#playerId = player.id;
430
444
  this.#backend = player.backend;
431
445
  this.#lose = player.backend === 'Gl' ? (this.#canvas.getContext('webgl2')?.getExtension('WEBGL_lose_context') ?? null) : null;
432
- this.#stage.classList.add('live');
433
446
  // A browser loses a GPU device after sleep or when its GPU process restarts, and says so.
434
447
  player.on_lost(() => {
435
448
  if (this.#player === player) this.#recover(new Error('GPU device lost'));
436
449
  });
437
450
  player.set_measure(this.#layer.measure);
438
451
  this.#setEm();
439
- if (this.#sources) {
452
+ const sources = this.#wanted ?? this.#sources;
453
+ if (sources) {
440
454
  try {
441
- this.#compile(this.#sources);
455
+ this.#compile(sources);
442
456
  } catch (error) {
457
+ this.#settle(sources, false);
443
458
  this.#fail(error);
444
459
  }
445
460
  }
@@ -453,7 +468,12 @@ export class PencilFigure extends HTMLElement {
453
468
  if (this.#tries && generation === this.#generation) {
454
469
  this.#starting = false;
455
470
  this.#recover(error);
456
- } else this.#fail(error);
471
+ } else {
472
+ // A load waiting on it hears now, and the next start, as when the figure is seen again,
473
+ // still begins from what it asked for.
474
+ this.#letDown();
475
+ this.#fail(error);
476
+ }
457
477
  } finally {
458
478
  if (generation === this.#generation) this.#starting = false;
459
479
  }
@@ -497,6 +517,7 @@ export class PencilFigure extends HTMLElement {
497
517
  if (wait === undefined) {
498
518
  this.#awaiting = true;
499
519
  this.#reported = true;
520
+ this.#letDown();
500
521
  this.dispatchEvent(new CustomEvent('error', { detail: { error, time: this.#time, fresh: false, gpu: true } }));
501
522
  } else if (wait === 0) {
502
523
  this.#restart();
@@ -550,6 +571,7 @@ export class PencilFigure extends HTMLElement {
550
571
  this.#stage.classList.remove('live');
551
572
  const player = this.#player;
552
573
  this.#player = null;
574
+ this.#installed = false;
553
575
  // The clock stops where it is, and runs again once there's a figure to draw.
554
576
  this.#sync();
555
577
  if (player) {
@@ -628,7 +650,14 @@ export class PencilFigure extends HTMLElement {
628
650
  this.#restoring = false;
629
651
  this.#startPending = false;
630
652
  clearTimeout(this.#restoreTimer);
653
+ // As a media element's `play()` does: what a load waits for isn't coming while it's out. A
654
+ // figure put back still shows what was asked for.
655
+ this.#letDown();
631
656
  this.#stage.classList.remove('live');
657
+ // The controls stop listening, and an open menu stops following its bar. A figure put back
658
+ // wires them again as it loads.
659
+ this.#wiring.detach();
660
+ this.#installed = false;
632
661
  if (this.#player) {
633
662
  this.#letGo(this.#player);
634
663
  this.#player = null;
@@ -721,49 +750,122 @@ export class PencilFigure extends HTMLElement {
721
750
  /** Compiles a figure from its `.pen` text and its sheets' texts, in order. A compile error is
722
751
  * thrown, with `line`, `col` and `sheet` saying where, and leaves the last figure on screen.
723
752
  * Before the GPU starts it's only checked, and shapes the element; it's drawn once the GPU is up.
724
- * Params held before keep their values if the new figure has them.
753
+ * Its shaders are compiled after, while the last figure stays on screen (`#compile`), and it
754
+ * resolves once it's shown, with `true`, however long the GPU takes to start, or with `false`
755
+ * when a figure asked for after it takes its place, or when it can't be made, which an `error`
756
+ * says. Params held before keep their values if the new figure has them.
725
757
  *
726
758
  * `used` is what `gather` read: the files these texts `use`. Without it, a `use "file"` is an
727
759
  * error. An error in a used file says so in `file`, its name. */
728
760
  load(doc, sheets = [], used = {}) {
729
761
  const sources = { doc, sheets, names: used.names ?? [], files: used.files ?? {} };
730
- if (this.#player) {
731
- this.#compile(sources);
732
- } else if (isReady()) {
733
- this.#shape(JSON.parse(figure_size(doc, sheets, sources.names, sources.files)));
734
- this.#sources = sources;
735
- } else {
736
- this.#sources = sources;
737
- }
762
+ if (this.#player) this.#compile(sources);
763
+ else if (isReady()) this.#shape(JSON.parse(figure_size(doc, sheets, sources.names, sources.files)));
764
+ return this.#ask(sources);
738
765
  }
739
766
 
740
767
  /** Loads a figure a build compiled (`pencil build`, `pencil compile`), from its bytes. One that
741
768
  * another build of Pencil wrote is an error that says to compile it again, and leaves the last
742
- * figure, or the poster, on screen. */
769
+ * figure, or the poster, on screen. It resolves as `load` does. */
743
770
  loadCompiled(bytes) {
744
771
  const sources = { compiled: bytes };
745
- if (this.#player) {
746
- this.#compile(sources);
747
- } else if (isReady()) {
748
- this.#shape(JSON.parse(figure_size_compiled(bytes)));
749
- this.#sources = sources;
750
- } else {
751
- this.#sources = sources;
752
- }
772
+ if (this.#player) this.#compile(sources);
773
+ else if (isReady()) this.#shape(JSON.parse(figure_size_compiled(bytes)));
774
+ return this.#ask(sources);
775
+ }
776
+
777
+ /** Waits for these sources to be shown, in place of whatever load was waiting before. */
778
+ #ask(sources) {
779
+ this.#letDown();
780
+ this.#wanted = sources;
781
+ return new Promise((resolve) => (this.#promised = { sources, resolve }));
782
+ }
783
+
784
+ /** These sources were shown, or can't be: what was asked for is done with, and its load hears. */
785
+ #settle(sources, shown) {
786
+ if (this.#wanted === sources) this.#wanted = null;
787
+ if (this.#promised?.sources !== sources) return;
788
+ const { resolve } = this.#promised;
789
+ this.#promised = null;
790
+ resolve(shown);
791
+ }
792
+
793
+ /** The load waiting hears it wasn't shown, now, though what it asked for may be later. */
794
+ #letDown() {
795
+ const promised = this.#promised;
796
+ this.#promised = null;
797
+ promised?.resolve(false);
798
+ }
799
+
800
+ /**
801
+ * Compiles sources for the player, which throws a compile error at once, and then waits for the
802
+ * GPU to compile their shaders, while the figure on screen, or the poster, stays and draws on.
803
+ * On WebGPU the browser compiles them off the thread that composites the page: made with
804
+ * `createRenderPipeline`, every frame on the page would wait for them. Only the last figure
805
+ * asked for is shown, and one that the GPU can't make is an `error`. One the GPU lost meanwhile
806
+ * is compiled again on the next player. `again` is for the figure that drew, shown again.
807
+ */
808
+ #compile(sources, again = false) {
809
+ const player = this.#player;
810
+ const pending = sources.compiled
811
+ ? player.prepare_compiled(sources.compiled)
812
+ : player.prepare(sources.doc, sources.sheets, sources.names, sources.files);
813
+ const ticket = ++this.#loads;
814
+ // Started again after losing its GPU, the figure the page heard of is no news. One that was
815
+ // still compiling is, as the first one is.
816
+ const quiet = (this.#quiet || again) && sources === this.#announced;
817
+ const current = () => player === this.#player && ticket === this.#loads;
818
+ pending.then(
819
+ (figure) => {
820
+ if (!current()) {
821
+ figure.free();
822
+ return;
823
+ }
824
+ try {
825
+ this.#show(player, figure, sources, quiet);
826
+ } catch (error) {
827
+ // A new player tries these sources again.
828
+ if (this.#recoverable(error)) return this.#recover(error);
829
+ this.#settle(sources, false);
830
+ this.#fail(error);
831
+ }
832
+ },
833
+ (error) => {
834
+ if (!current()) return;
835
+ if (this.#recoverable(error)) return this.#recover(error);
836
+ // What failed is the new figure. The one on screen stays, if the player has one.
837
+ const kept = this.#installed;
838
+ this.#settle(sources, false);
839
+ this.#fail(error, { fresh: true, kept });
840
+ // A new player has nothing on it yet: the figure that drew before comes back, unless the
841
+ // page asked for another as it heard.
842
+ if (kept || !this.#sources || this.#sources === sources || !current()) return;
843
+ try {
844
+ this.#compile(this.#sources, true);
845
+ } catch (error) {
846
+ this.#fail(error);
847
+ }
848
+ },
849
+ );
753
850
  }
754
851
 
755
- #compile(sources) {
756
- if (sources.compiled) this.#player.load_compiled(sources.compiled);
757
- else this.#player.load(sources.doc, sources.sheets, sources.names, sources.files);
852
+ /** Puts a figure the player prepared on screen, and everything that follows from it. */
853
+ #show(player, figure, sources, quiet) {
854
+ player.install(figure);
855
+ this.#installed = true;
758
856
  this.#sources = sources;
759
- const info = JSON.parse(this.#player.info());
857
+ // Its load hears before anything is dispatched, so a listener's own load can't take its place.
858
+ this.#settle(sources, true);
859
+ this.#stage.classList.add('live');
860
+ const info = JSON.parse(player.info());
760
861
  this.#info = info;
761
862
  this.#driven = new Set(info.timeDriven);
762
- this.#shape(info.size);
863
+ // Before its shape, which can draw a frame at once, with the params a reader holds.
763
864
  for (const [name, value] of this.#held) {
764
- if (info.params.some((p) => p.id === name)) this.#player.set_param(name, value);
865
+ if (info.params.some((p) => p.id === name)) player.set_param(name, value);
765
866
  else this.#held.delete(name);
766
867
  }
868
+ this.#shape(info.size);
767
869
  this.#retime();
768
870
  this.#operable();
769
871
  this.#readouts = null;
@@ -771,9 +873,9 @@ export class PencilFigure extends HTMLElement {
771
873
  this.#fresh = true;
772
874
  this.#invalidate();
773
875
  this.#sync();
774
- // A figure started again after losing its GPU is the same figure.
775
- if (this.#quiet) this.#quiet = false;
776
- else this.dispatchEvent(new Event('load'));
876
+ // Said, so a start again after this shows it without news.
877
+ this.#announced = sources;
878
+ if (!quiet) this.dispatchEvent(new Event('load'));
777
879
  }
778
880
 
779
881
  // ---- Controls ----
@@ -839,7 +941,11 @@ export class PencilFigure extends HTMLElement {
839
941
  // A reader who was on a control is still on it afterwards, as one who picked a look with the
840
942
  // keyboard: the same control, found by what it's for, and a menu that was open is open still.
841
943
  const focused = root.activeElement ? identity(root.activeElement) : null;
842
- const open = !!root.querySelector('[popover]:popover-open');
944
+ // An open menu opens again where it was, before the focus goes back into it, so the focus
945
+ // doesn't scroll the page to wherever a menu not yet placed would be. The wiring places it
946
+ // again once it's attached.
947
+ const open = root.querySelector('[popover]:popover-open');
948
+ const placed = open?.getAttribute('style');
843
949
  let html = '<div class="controls" part="controls"><div class="rest" part="rest"><slot></slot></div></div>';
844
950
  if (info) {
845
951
  let room = [];
@@ -866,11 +972,14 @@ export class PencilFigure extends HTMLElement {
866
972
  host.dataset.shape = info ? shape(info) : 'page';
867
973
  this.#wiring.forget();
868
974
  if (open) {
975
+ const menu = root.querySelector('[popover]');
976
+ if (placed) menu?.setAttribute('style', placed);
869
977
  try {
870
- root.querySelector('[popover]')?.showPopover();
978
+ menu?.showPopover();
871
979
  } catch {}
872
980
  }
873
- if (focused) root.querySelector(focused)?.focus();
981
+ // Without scrolling: the control is where it was, and a menu's may be partly off the screen.
982
+ if (focused) root.querySelector(focused)?.focus({ preventScroll: true });
874
983
  }
875
984
 
876
985
  /** What each readout says this frame, `{ id, text, words, math, width, height, laid }`, in the
@@ -900,8 +1009,8 @@ export class PencilFigure extends HTMLElement {
900
1009
  return `pencil ${this.id || (src ? src.split('/').pop() : 'figure')}`;
901
1010
  }
902
1011
 
903
- #fail(error) {
904
- this.dispatchEvent(new CustomEvent('error', { detail: { error, time: this.#time, fresh: this.#fresh } }));
1012
+ #fail(error, detail = {}) {
1013
+ this.dispatchEvent(new CustomEvent('error', { detail: { error, time: this.#time, fresh: this.#fresh, ...detail } }));
905
1014
  }
906
1015
 
907
1016
  // ---- Time ----
@@ -993,7 +1102,7 @@ export class PencilFigure extends HTMLElement {
993
1102
  #sync() {
994
1103
  const clock = this.#clock;
995
1104
  if (!clock) return;
996
- const run = this.#paused === false && this.#visible && !!this.#player && !!this.#info?.usesTime;
1105
+ const run = this.#paused === false && this.#visible && this.#installed && !!this.#info?.usesTime;
997
1106
  const running = clock.playState === 'running';
998
1107
  if (run && !running) {
999
1108
  clock.currentTime = this.#time * 1000;
@@ -1021,6 +1130,8 @@ export class PencilFigure extends HTMLElement {
1021
1130
  this.hold('beat', target);
1022
1131
  return;
1023
1132
  }
1133
+ // A player started again has no figure to find a beat's time in until it's in.
1134
+ if (!this.#installed) return;
1024
1135
  // A beat that follows time is taken to only count up, so the first moment it reaches the
1025
1136
  // target is found by halving. Sampling, as `time_for` does, lands just short of it.
1026
1137
  let [lo, hi] = [0, this.duration];
@@ -1168,7 +1279,7 @@ export class PencilFigure extends HTMLElement {
1168
1279
 
1169
1280
  #pointerDown = (e) => {
1170
1281
  // One pointer drags at a time, and only with the main button.
1171
- if (!this.#player || !e.isPrimary || e.button !== 0) return;
1282
+ if (!this.#installed || !e.isPrimary || e.button !== 0) return;
1172
1283
  const [x, y] = this.#device(e);
1173
1284
  try {
1174
1285
  if (!this.#player.grab(this.#time, x, y, REACH * (window.devicePixelRatio || 1))) return;
@@ -1182,7 +1293,7 @@ export class PencilFigure extends HTMLElement {
1182
1293
  };
1183
1294
 
1184
1295
  #pointerMove = (e) => {
1185
- if (!this.#player) return;
1296
+ if (!this.#installed) return;
1186
1297
  const [x, y] = this.#device(e);
1187
1298
  try {
1188
1299
  if (!this.#stage.hasPointerCapture(e.pointerId)) {
@@ -1329,7 +1440,7 @@ export class PencilFigure extends HTMLElement {
1329
1440
  * Up and Page Down up and down, as far as Shift and an arrow.
1330
1441
  */
1331
1442
  #handleKey(e, index) {
1332
- if (!this.#player || e.altKey || e.ctrlKey || e.metaKey) return;
1443
+ if (!this.#installed || e.altKey || e.ctrlKey || e.metaKey) return;
1333
1444
  const params = this.#info.handles[index].params;
1334
1445
  const [param] = params;
1335
1446
  const long = params.length > 1 && { Home: [-1, 0], End: [1, 0], PageUp: [0, -1], PageDown: [0, 1] }[e.key];
@@ -1363,7 +1474,7 @@ export class PencilFigure extends HTMLElement {
1363
1474
  #key = (e) => {
1364
1475
  // Keys in the controls are theirs: an arrow on a slider moves the slider.
1365
1476
  if (e.target !== this) return;
1366
- if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || !this.#player || !this.#steps()) return;
1477
+ if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || !this.#installed || !this.#steps()) return;
1367
1478
  const range = this.#info.params.find((p) => p.id === 'beat');
1368
1479
  if (e.key === 'ArrowRight') this.step(1);
1369
1480
  else if (e.key === 'ArrowLeft') this.step(-1);
@@ -1414,7 +1525,8 @@ export class PencilFigure extends HTMLElement {
1414
1525
 
1415
1526
  #paint() {
1416
1527
  this.#dirty = false;
1417
- if (!this.#player || !this.#info) return;
1528
+ // A player started again keeps the figure's info, and has nothing to draw until it's in.
1529
+ if (!this.#player || !this.#info || !this.#installed) return;
1418
1530
  const fresh = this.#fresh;
1419
1531
  this.#fresh = false;
1420
1532
  // Zooming or moving to another screen changes it, so it's read each frame.