@pencil-lang/figure 0.0.0-stage → 0.0.2
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/LICENSE +21 -0
- package/README.md +127 -2
- package/astro/Figure.astro +108 -0
- package/astro/build.js +264 -0
- package/astro/client.js +9 -0
- package/astro/index.js +153 -0
- package/fonts/LibertinusMath-Regular.otf +0 -0
- package/fonts/LibertinusSans-Regular.otf +0 -0
- package/fonts/LibertinusSerif-Italic.otf +0 -0
- package/fonts/OFL.txt +94 -0
- package/fonts/README.md +18 -0
- package/package.json +54 -3
- package/pkg/pencil-figure.min.js +32 -0
- package/pkg/pencil_web.js +3094 -0
- package/pkg/pencil_web_bg.wasm +0 -0
- package/src/element.js +992 -0
- package/src/fit.js +14 -0
- package/src/host.js +109 -0
- package/src/labels.js +266 -0
- package/src/pack.js +67 -0
- package/src/scheme.js +62 -0
package/src/element.js
ADDED
|
@@ -0,0 +1,992 @@
|
|
|
1
|
+
// <pencil-figure>: a Pencil figure on a page. It owns the canvas, the labels over it, the GPU and
|
|
2
|
+
// the clock, so a page only says which figure and which sheets:
|
|
3
|
+
//
|
|
4
|
+
// <pencil-figure src="unroll.pen" sheets="theme.style blog.style"></pencil-figure>
|
|
5
|
+
//
|
|
6
|
+
// Importing this module defines the element: `import '@pencil-lang/figure'`. The WASM it runs
|
|
7
|
+
// on is `./host.js`, which a page can call directly too.
|
|
8
|
+
//
|
|
9
|
+
// The clock is a Web Animations `Animation` on the element (`clock`), so its time, pausing and
|
|
10
|
+
// rate are the browser's own, and DevTools' Animations panel can scrub it. Time and a reader's input
|
|
11
|
+
// both set the figure's bindings, as everywhere else: nothing here works out a value of its own.
|
|
12
|
+
//
|
|
13
|
+
// The GPU starts only when the element comes near the viewport, the clock pauses while it's away,
|
|
14
|
+
// and both are let go when it leaves the page, since browsers cap how many contexts can be live.
|
|
15
|
+
// A figure that never reads time gets no clock at all. Nothing draws while nothing changes.
|
|
16
|
+
//
|
|
17
|
+
// A document or sheet that says `use "parts/arms.pen"` gets that file fetched too, from beside the
|
|
18
|
+
// file that says it.
|
|
19
|
+
//
|
|
20
|
+
// A build can compile a figure ahead (`pencil build`), and then a page gives that one file:
|
|
21
|
+
//
|
|
22
|
+
// <pencil-figure compiled="tube.pfig">
|
|
23
|
+
// <source media="(prefers-color-scheme: dark)" compiled="tube.dark.pfig">
|
|
24
|
+
// <img src="tube.png" width="640" height="524" alt="…">
|
|
25
|
+
// </pencil-figure>
|
|
26
|
+
//
|
|
27
|
+
// Its children are its poster: they show until the first frame is drawn, and stay where a figure
|
|
28
|
+
// can't run. With one, nothing is fetched until the figure is near the viewport, since the poster
|
|
29
|
+
// already has its shape. A `<source>` child picks other sources while its `media` matches, as in
|
|
30
|
+
// `<picture>`: the first that matches wins, and the element's own attributes are the rest. It can
|
|
31
|
+
// give `compiled`, or `sheets` (and `src`, which is the element's if it gives none).
|
|
32
|
+
// Where a page pins a theme over the reader's system, with `color-scheme` in its CSS, the element
|
|
33
|
+
// answers `prefers-color-scheme` in those `media` with the page's scheme (`scheme.js`).
|
|
34
|
+
//
|
|
35
|
+
// Attributes: `src` and `sheets` (space-separated URLs, in order), or `compiled`, `params`
|
|
36
|
+
// (`a: 0.5; beat: 2`, held as if a reader set them), `paused` to start paused, and `gl` to skip
|
|
37
|
+
// WebGPU. A page can also pick its sheets in script, by setting `sheets` as soon as the element
|
|
38
|
+
// is defined: changes made before that script finishes are fetched once.
|
|
39
|
+
// Its labels are an em of the text where it sits, and follow when a reader changes their text size.
|
|
40
|
+
// `reload()` fetches the sources again, for a page that watches them change.
|
|
41
|
+
// Events: `load` when a figure is compiled, `draw` after each frame drawn, `resize` when its drawn
|
|
42
|
+
// size or its em changes (its `detail.em`, in CSS pixels), `input` when a reader
|
|
43
|
+
// drags a param, `play` and `pause`, and `error` (its `detail.error`) when one can't load or draw.
|
|
44
|
+
import { Player, figure_size, figure_size_compiled, ready, isReady, gather, ahead } from './host.js';
|
|
45
|
+
import { LABEL_CSS, LabelLayer, fonts } from './labels.js';
|
|
46
|
+
import { match } from './fit.js';
|
|
47
|
+
import { follow, settle, unfollow } from './scheme.js';
|
|
48
|
+
|
|
49
|
+
// How long time runs before it loops, for a figure that declares no `duration`.
|
|
50
|
+
const LOOP = 10;
|
|
51
|
+
// How near a handle a pointer has to be to take it, in CSS pixels.
|
|
52
|
+
const REACH = 24;
|
|
53
|
+
// How far from the viewport the GPU starts, so a figure is drawn by the time it's scrolled to.
|
|
54
|
+
const NEAR = '200px';
|
|
55
|
+
|
|
56
|
+
const fetchText = async (url) => {
|
|
57
|
+
const response = await fetch(new URL(url, document.baseURI));
|
|
58
|
+
if (!response.ok) throw new Error(`${url}: ${response.status}`);
|
|
59
|
+
return response.text();
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const CSS = `
|
|
63
|
+
:host { display: block; }
|
|
64
|
+
:host([hidden]) { display: none; }
|
|
65
|
+
.stage { position: relative; overflow: hidden; width: 100%; }
|
|
66
|
+
canvas { display: block; width: 100%; aspect-ratio: var(--pencil-aspect, 16 / 9); outline: none; }
|
|
67
|
+
/* The poster: the element's children, until the first frame. It has the figure's shape, and the
|
|
68
|
+
canvas waits under it at the same size, so nothing moves when they swap. */
|
|
69
|
+
slot { display: none; }
|
|
70
|
+
.stage.waiting slot { display: block; }
|
|
71
|
+
.stage.waiting canvas { position: absolute; inset: 0; height: 100%; aspect-ratio: auto; opacity: 0; }
|
|
72
|
+
::slotted(source) { display: none; }
|
|
73
|
+
::slotted(img), ::slotted(picture) { display: block; width: 100%; height: auto; }
|
|
74
|
+
.em { position: absolute; left: 0; top: 0; width: 1em; height: 0; visibility: hidden; pointer-events: none; }
|
|
75
|
+
/* Something to focus over each handle. The pointer goes through it to the canvas, which is where
|
|
76
|
+
a drag is taken, and a reader on a keyboard tabs to it and moves it with the arrow keys. Its
|
|
77
|
+
ring is two tones, so it shows on any paper. */
|
|
78
|
+
.handles { position: absolute; inset: 0; pointer-events: none; }
|
|
79
|
+
.handle { position: absolute; left: -14px; top: -14px; width: 28px; height: 28px; border-radius: 50%; outline: none; will-change: transform; }
|
|
80
|
+
.handle:focus-visible { outline: 2px solid var(--pencil-focus, currentColor); outline-offset: 1px; box-shadow: 0 0 0 2px var(--pencil-focus-halo, Canvas); }
|
|
81
|
+
.handle[hidden] { display: none; }
|
|
82
|
+
.said { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
|
83
|
+
${LABEL_CSS}`;
|
|
84
|
+
|
|
85
|
+
/** `a: 0.5; beat: 2` as pairs. */
|
|
86
|
+
const parseParams = (text) =>
|
|
87
|
+
(text ?? '')
|
|
88
|
+
.split(';')
|
|
89
|
+
.map((part) => part.split(':').map((s) => s.trim()))
|
|
90
|
+
.filter(([name, value]) => name && value !== undefined && value !== '' && Number.isFinite(Number(value)))
|
|
91
|
+
.map(([name, value]) => [name, Number(value)]);
|
|
92
|
+
|
|
93
|
+
export class PencilFigure extends HTMLElement {
|
|
94
|
+
static observedAttributes = ['src', 'sheets', 'compiled', 'params'];
|
|
95
|
+
|
|
96
|
+
/** Resolves once the WASM core is ready, after which `load` checks sources at once. */
|
|
97
|
+
static get ready() {
|
|
98
|
+
return ready();
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
#stage;
|
|
102
|
+
#canvas;
|
|
103
|
+
#em;
|
|
104
|
+
#emPx = 0;
|
|
105
|
+
#layer;
|
|
106
|
+
#handleLayer;
|
|
107
|
+
#handles = []; // what a reader focuses for each handle, in `info.handles`' order
|
|
108
|
+
#said; // what a key just did, for a screen reader
|
|
109
|
+
#internals = null;
|
|
110
|
+
#tabbable = false; // whether the element made itself a tab stop, for stepping beats
|
|
111
|
+
#size = null;
|
|
112
|
+
#player = null;
|
|
113
|
+
#starting = false;
|
|
114
|
+
#generation = 0;
|
|
115
|
+
#sources = null; // { doc, sheets, names, files } or { compiled }, loaded or waiting for the GPU
|
|
116
|
+
#drawn = false; // whether a frame has been drawn since the canvas was made
|
|
117
|
+
#children = null; // watches for a poster or a <source> arriving
|
|
118
|
+
#media = []; // each <source>'s media query, and what's listening to it
|
|
119
|
+
#fetched = null;
|
|
120
|
+
#fetching = false;
|
|
121
|
+
#info = null;
|
|
122
|
+
#driven = new Set();
|
|
123
|
+
#held = new Map();
|
|
124
|
+
#clock = null;
|
|
125
|
+
#rate = 1;
|
|
126
|
+
#time = 0;
|
|
127
|
+
#paused = null;
|
|
128
|
+
#visible = false;
|
|
129
|
+
#raf = 0;
|
|
130
|
+
#idle = true;
|
|
131
|
+
#dirty = false;
|
|
132
|
+
#fresh = false;
|
|
133
|
+
#seen = null;
|
|
134
|
+
#resized = null;
|
|
135
|
+
|
|
136
|
+
constructor() {
|
|
137
|
+
super();
|
|
138
|
+
const root = this.attachShadow({ mode: 'open' });
|
|
139
|
+
const style = document.createElement('style');
|
|
140
|
+
style.textContent = CSS;
|
|
141
|
+
this.#stage = document.createElement('div');
|
|
142
|
+
this.#stage.className = 'stage';
|
|
143
|
+
this.#stage.setAttribute('part', 'stage');
|
|
144
|
+
root.append(style, this.#stage);
|
|
145
|
+
this.#canvas = this.#makeCanvas();
|
|
146
|
+
// One em wide and out of sight. A reader changing their text size resizes it, though nothing
|
|
147
|
+
// else about the figure changes, so the labels follow.
|
|
148
|
+
this.#em = document.createElement('span');
|
|
149
|
+
this.#em.className = 'em';
|
|
150
|
+
this.#em.setAttribute('aria-hidden', 'true');
|
|
151
|
+
this.#stage.append(document.createElement('slot'), this.#canvas, this.#em);
|
|
152
|
+
this.#layer = new LabelLayer(this.#stage, window.devicePixelRatio || 1);
|
|
153
|
+
this.#handleLayer = document.createElement('div');
|
|
154
|
+
this.#handleLayer.className = 'handles';
|
|
155
|
+
this.#said = document.createElement('div');
|
|
156
|
+
this.#said.className = 'said';
|
|
157
|
+
this.#said.setAttribute('aria-live', 'polite');
|
|
158
|
+
this.#stage.append(this.#handleLayer, this.#said);
|
|
159
|
+
this.addEventListener('keydown', this.#key);
|
|
160
|
+
try {
|
|
161
|
+
this.#internals = this.attachInternals();
|
|
162
|
+
} catch {}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// ---- The poster and the sources ----
|
|
166
|
+
|
|
167
|
+
/** Whether the element has a poster: any child that isn't a `<source>`, or a script. */
|
|
168
|
+
#hasPoster() {
|
|
169
|
+
return [...this.children].some((child) => child.localName !== 'source' && child.localName !== 'script');
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Shows the poster until a frame is drawn. */
|
|
173
|
+
#wait() {
|
|
174
|
+
this.#stage.classList.toggle('waiting', !this.#drawn && this.#hasPoster());
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Where the sources come from now: the first `<source>` child whose media matches, or the
|
|
178
|
+
* element itself. */
|
|
179
|
+
#chosen() {
|
|
180
|
+
for (const source of this.querySelectorAll(':scope > source')) {
|
|
181
|
+
const media = source.getAttribute('media');
|
|
182
|
+
if (!media || matchMedia(media).matches) return source;
|
|
183
|
+
}
|
|
184
|
+
return this;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Follows each `<source>`'s media query, so the figure changes sheets when the reader's
|
|
188
|
+
* theme or the page's width does. */
|
|
189
|
+
#listen() {
|
|
190
|
+
for (const [query, listener] of this.#media) query.removeEventListener('change', listener);
|
|
191
|
+
this.#media = [];
|
|
192
|
+
if (!this.isConnected) return;
|
|
193
|
+
for (const source of this.querySelectorAll(':scope > source[media]')) {
|
|
194
|
+
const query = matchMedia(source.getAttribute('media'));
|
|
195
|
+
const listener = () => this.#refetch();
|
|
196
|
+
query.addEventListener('change', listener);
|
|
197
|
+
this.#media.push([query, listener]);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Fetches the sources, unless a poster is standing in and the figure isn't near yet. */
|
|
202
|
+
#refetch() {
|
|
203
|
+
if (this.#visible || !this.#hasPoster()) this.#queueFetch();
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// ---- Lifecycle ----
|
|
207
|
+
|
|
208
|
+
connectedCallback() {
|
|
209
|
+
this.#paused ??= this.hasAttribute('paused') || matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
210
|
+
if (!this.#clock) {
|
|
211
|
+
this.#clock = this.animate([], { id: this.#clockName(), duration: this.duration * 1000, iterations: Infinity });
|
|
212
|
+
this.#clock.pause();
|
|
213
|
+
this.#clock.currentTime = this.#time * 1000;
|
|
214
|
+
this.#clock.playbackRate = this.#rate;
|
|
215
|
+
}
|
|
216
|
+
this.#seen = new IntersectionObserver(
|
|
217
|
+
(entries) => {
|
|
218
|
+
this.#visible = entries[entries.length - 1].isIntersecting;
|
|
219
|
+
if (this.#visible) {
|
|
220
|
+
this.#queueFetch();
|
|
221
|
+
this.#start();
|
|
222
|
+
}
|
|
223
|
+
this.#sync();
|
|
224
|
+
},
|
|
225
|
+
{ rootMargin: NEAR },
|
|
226
|
+
);
|
|
227
|
+
this.#seen.observe(this);
|
|
228
|
+
this.#resized = new ResizeObserver(() => this.#follow());
|
|
229
|
+
this.#resized.observe(this.#canvas);
|
|
230
|
+
this.#resized.observe(this.#em);
|
|
231
|
+
// Children can arrive after the element does, while the page is still being read.
|
|
232
|
+
this.#children = new MutationObserver(() => {
|
|
233
|
+
// A `<source>` that has just arrived is answered too. What that changes comes back here
|
|
234
|
+
// once, and then changes nothing.
|
|
235
|
+
settle(this);
|
|
236
|
+
this.#wait();
|
|
237
|
+
this.#listen();
|
|
238
|
+
this.#refetch();
|
|
239
|
+
});
|
|
240
|
+
this.#children.observe(this, { childList: true, attributes: true, subtree: true, attributeFilter: ['media', 'src', 'sheets', 'compiled'] });
|
|
241
|
+
document.fonts?.addEventListener('loadingdone', this.#fontsChanged);
|
|
242
|
+
follow(this);
|
|
243
|
+
this.#wait();
|
|
244
|
+
this.#listen();
|
|
245
|
+
this.#refetch();
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** A font that arrives after text was measured without it, as the math font does the first time
|
|
249
|
+
* a label needs a glyph from it: what was measured is forgotten, here and in the player. */
|
|
250
|
+
#fontsChanged = () => {
|
|
251
|
+
this.#layer.remeasure();
|
|
252
|
+
this.#player?.set_measure(this.#layer.measure);
|
|
253
|
+
this.#invalidate();
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
disconnectedCallback() {
|
|
257
|
+
document.fonts?.removeEventListener('loadingdone', this.#fontsChanged);
|
|
258
|
+
this.#seen?.disconnect();
|
|
259
|
+
this.#resized?.disconnect();
|
|
260
|
+
this.#children?.disconnect();
|
|
261
|
+
unfollow(this);
|
|
262
|
+
this.#listen();
|
|
263
|
+
this.#visible = false;
|
|
264
|
+
this.#sync();
|
|
265
|
+
// Moving an element disconnects it and connects it again at once: only let go if it stays out.
|
|
266
|
+
queueMicrotask(() => {
|
|
267
|
+
if (!this.isConnected) this.#teardown();
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
attributeChangedCallback(name) {
|
|
272
|
+
if (name === 'params') {
|
|
273
|
+
for (const [param, value] of parseParams(this.getAttribute('params'))) this.hold(param, value);
|
|
274
|
+
} else {
|
|
275
|
+
this.#refetch();
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
#makeCanvas() {
|
|
280
|
+
const canvas = document.createElement('canvas');
|
|
281
|
+
canvas.setAttribute('part', 'canvas');
|
|
282
|
+
if (this.#size) canvas.style.setProperty('--pencil-aspect', `${this.#size[0]} / ${this.#size[1]}`);
|
|
283
|
+
canvas.addEventListener('pointerdown', this.#pointerDown);
|
|
284
|
+
canvas.addEventListener('pointermove', this.#pointerMove);
|
|
285
|
+
canvas.addEventListener('pointerup', this.#pointerEnd);
|
|
286
|
+
canvas.addEventListener('pointercancel', this.#pointerEnd);
|
|
287
|
+
// A grab focuses its handle, and the press mustn't take the focus away again.
|
|
288
|
+
canvas.addEventListener('mousedown', (e) => {
|
|
289
|
+
if (this.#player?.grabbed() >= 0) e.preventDefault();
|
|
290
|
+
});
|
|
291
|
+
return canvas;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Starts the GPU, once, when the element is near the viewport. */
|
|
295
|
+
async #start() {
|
|
296
|
+
if (this.#player || this.#starting) return;
|
|
297
|
+
this.#starting = true;
|
|
298
|
+
const generation = this.#generation;
|
|
299
|
+
try {
|
|
300
|
+
// The text faces too, so labels are measured and first drawn in the fonts the poster has.
|
|
301
|
+
await Promise.all([ready(), fonts]);
|
|
302
|
+
if (generation !== this.#generation) return;
|
|
303
|
+
match(this.#canvas);
|
|
304
|
+
const player = await Player.create(this.#canvas, this.hasAttribute('gl'));
|
|
305
|
+
if (generation !== this.#generation) {
|
|
306
|
+
player.destroy();
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
this.#player = player;
|
|
310
|
+
player.set_measure(this.#layer.measure);
|
|
311
|
+
this.#setEm();
|
|
312
|
+
if (this.#sources) {
|
|
313
|
+
try {
|
|
314
|
+
this.#compile(this.#sources);
|
|
315
|
+
} catch (error) {
|
|
316
|
+
this.#fail(error);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
} catch (error) {
|
|
320
|
+
this.#fail(error);
|
|
321
|
+
} finally {
|
|
322
|
+
if (generation === this.#generation) this.#starting = false;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** Lets go of the clock and the GPU. The figure's sources, time and held params are kept, so
|
|
327
|
+
* it starts again where it was if it's put back. */
|
|
328
|
+
#teardown() {
|
|
329
|
+
this.#time = this.time;
|
|
330
|
+
this.#clock?.cancel();
|
|
331
|
+
this.#clock = null;
|
|
332
|
+
cancelAnimationFrame(this.#raf);
|
|
333
|
+
this.#raf = 0;
|
|
334
|
+
this.#idle = true;
|
|
335
|
+
const started = this.#player || this.#starting;
|
|
336
|
+
this.#generation += 1;
|
|
337
|
+
this.#starting = false;
|
|
338
|
+
if (this.#player) {
|
|
339
|
+
const gl = this.#player.backend === 'Gl';
|
|
340
|
+
this.#player.destroy();
|
|
341
|
+
this.#player = null;
|
|
342
|
+
if (gl) this.#canvas.getContext('webgl2')?.getExtension('WEBGL_lose_context')?.loseContext();
|
|
343
|
+
else this.#canvas.getContext('webgpu')?.unconfigure();
|
|
344
|
+
}
|
|
345
|
+
// A canvas keeps its context for life, so a figure put back gets a new one.
|
|
346
|
+
if (started) {
|
|
347
|
+
const canvas = this.#makeCanvas();
|
|
348
|
+
this.#canvas.replaceWith(canvas);
|
|
349
|
+
this.#canvas = canvas;
|
|
350
|
+
// And its poster back, until that one has drawn.
|
|
351
|
+
this.#drawn = false;
|
|
352
|
+
this.#wait();
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// ---- Sources ----
|
|
357
|
+
|
|
358
|
+
/** Fetches the sources once the task that set them is done, so `src` and `sheets` set one
|
|
359
|
+
* after the other, or set by a page's script just after the element is parsed, fetch once. */
|
|
360
|
+
#queueFetch() {
|
|
361
|
+
if (this.#fetching) return;
|
|
362
|
+
this.#fetching = true;
|
|
363
|
+
queueMicrotask(() => {
|
|
364
|
+
this.#fetching = false;
|
|
365
|
+
if (this.isConnected) this.#fetchSources();
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Fetches the sources again and loads them, as after a file changed. The figure on screen,
|
|
370
|
+
* its time and its held params stay until the new one is compiled. */
|
|
371
|
+
reload() {
|
|
372
|
+
this.#fetched = null;
|
|
373
|
+
this.#queueFetch();
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
async #fetchSources() {
|
|
377
|
+
const chosen = this.#chosen();
|
|
378
|
+
const compiled = chosen.getAttribute('compiled');
|
|
379
|
+
if (compiled) {
|
|
380
|
+
const key = JSON.stringify(['compiled', compiled]);
|
|
381
|
+
if (key === this.#fetched) return;
|
|
382
|
+
this.#fetched = key;
|
|
383
|
+
if (this.#clock) this.#clock.id = this.#clockName();
|
|
384
|
+
try {
|
|
385
|
+
const url = new URL(compiled, document.baseURI);
|
|
386
|
+
// The page may have started on it already (`ahead`, in host.js).
|
|
387
|
+
let bytes = null;
|
|
388
|
+
const early = await ahead(url.href);
|
|
389
|
+
if (early) {
|
|
390
|
+
try {
|
|
391
|
+
bytes = new Uint8Array(await early.arrayBuffer());
|
|
392
|
+
} catch {}
|
|
393
|
+
}
|
|
394
|
+
if (!bytes) {
|
|
395
|
+
const response = await fetch(url);
|
|
396
|
+
if (!response.ok) throw new Error(`${compiled}: ${response.status}`);
|
|
397
|
+
bytes = new Uint8Array(await response.arrayBuffer());
|
|
398
|
+
}
|
|
399
|
+
await ready();
|
|
400
|
+
if (key !== this.#fetched) return;
|
|
401
|
+
this.loadCompiled(bytes);
|
|
402
|
+
} catch (error) {
|
|
403
|
+
this.#fail(error);
|
|
404
|
+
}
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
const src = chosen.getAttribute('src') ?? this.getAttribute('src');
|
|
408
|
+
if (!src) return;
|
|
409
|
+
const sheets = (chosen.getAttribute('sheets') ?? this.getAttribute('sheets') ?? '').split(/\s+/).filter(Boolean);
|
|
410
|
+
const key = JSON.stringify([src, sheets]);
|
|
411
|
+
if (key === this.#fetched) return;
|
|
412
|
+
this.#fetched = key;
|
|
413
|
+
if (this.#clock) this.#clock.id = this.#clockName();
|
|
414
|
+
try {
|
|
415
|
+
const names = [src, ...sheets];
|
|
416
|
+
const texts = await Promise.all(names.map(fetchText));
|
|
417
|
+
const used = await gather(names, texts);
|
|
418
|
+
if (key !== this.#fetched) return;
|
|
419
|
+
const [doc, ...sheetTexts] = texts;
|
|
420
|
+
this.load(doc, sheetTexts, used);
|
|
421
|
+
} catch (error) {
|
|
422
|
+
this.#fail(error);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** Compiles a figure from its `.pen` text and its sheets' texts, in order. A compile error is
|
|
427
|
+
* thrown, with `line`, `col` and `sheet` saying where, and leaves the last figure on screen.
|
|
428
|
+
* Before the GPU starts it's only checked, and shapes the element; it's drawn once the GPU is up.
|
|
429
|
+
* Params held before keep their values if the new figure has them.
|
|
430
|
+
*
|
|
431
|
+
* `used` is what `gather` read: the files these texts `use`. Without it, a `use "file"` is an
|
|
432
|
+
* error. An error in a used file says so in `file`, its name. */
|
|
433
|
+
load(doc, sheets = [], used = {}) {
|
|
434
|
+
const sources = { doc, sheets, names: used.names ?? [], files: used.files ?? {} };
|
|
435
|
+
if (this.#player) {
|
|
436
|
+
this.#compile(sources);
|
|
437
|
+
} else if (isReady()) {
|
|
438
|
+
this.#shape(JSON.parse(figure_size(doc, sheets, sources.names, sources.files)));
|
|
439
|
+
this.#sources = sources;
|
|
440
|
+
} else {
|
|
441
|
+
this.#sources = sources;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** Loads a figure a build compiled (`pencil build`, `pencil compile`), from its bytes. One that
|
|
446
|
+
* another build of Pencil wrote is an error that says to compile it again, and leaves the last
|
|
447
|
+
* figure, or the poster, on screen. */
|
|
448
|
+
loadCompiled(bytes) {
|
|
449
|
+
const sources = { compiled: bytes };
|
|
450
|
+
if (this.#player) {
|
|
451
|
+
this.#compile(sources);
|
|
452
|
+
} else if (isReady()) {
|
|
453
|
+
this.#shape(JSON.parse(figure_size_compiled(bytes)));
|
|
454
|
+
this.#sources = sources;
|
|
455
|
+
} else {
|
|
456
|
+
this.#sources = sources;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
#compile(sources) {
|
|
461
|
+
if (sources.compiled) this.#player.load_compiled(sources.compiled);
|
|
462
|
+
else this.#player.load(sources.doc, sources.sheets, sources.names, sources.files);
|
|
463
|
+
this.#sources = sources;
|
|
464
|
+
const info = JSON.parse(this.#player.info());
|
|
465
|
+
this.#info = info;
|
|
466
|
+
this.#driven = new Set(info.timeDriven);
|
|
467
|
+
this.#shape(info.size);
|
|
468
|
+
for (const [name, value] of this.#held) {
|
|
469
|
+
if (info.params.some((p) => p.id === name)) this.#player.set_param(name, value);
|
|
470
|
+
else this.#held.delete(name);
|
|
471
|
+
}
|
|
472
|
+
this.#retime();
|
|
473
|
+
this.#operable();
|
|
474
|
+
this.#fresh = true;
|
|
475
|
+
this.#invalidate();
|
|
476
|
+
this.#sync();
|
|
477
|
+
this.dispatchEvent(new Event('load'));
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** Shapes the figure to its design size, so nothing moves as it loads. */
|
|
481
|
+
#shape(size) {
|
|
482
|
+
this.#size = size;
|
|
483
|
+
this.#canvas.style.setProperty('--pencil-aspect', `${size[0]} / ${size[1]}`);
|
|
484
|
+
this.#follow();
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
#clockName() {
|
|
488
|
+
const src = this.getAttribute('src') ?? this.getAttribute('compiled');
|
|
489
|
+
return `pencil ${this.id || (src ? src.split('/').pop() : 'figure')}`;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
#fail(error) {
|
|
493
|
+
this.dispatchEvent(new CustomEvent('error', { detail: { error, time: this.#time, fresh: this.#fresh } }));
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// ---- Time ----
|
|
497
|
+
|
|
498
|
+
/** The figure's loop length in seconds: its `duration`, or 10 s for one that says none. */
|
|
499
|
+
get duration() {
|
|
500
|
+
return this.#info?.duration ?? LOOP;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** The time last drawn, in seconds. Setting it seeks, and a `beat` that follows time follows
|
|
504
|
+
* it again. */
|
|
505
|
+
get time() {
|
|
506
|
+
return this.#time;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
set time(seconds) {
|
|
510
|
+
this.#seek(seconds);
|
|
511
|
+
if (this.#driven.has('beat')) this.#release('beat');
|
|
512
|
+
this.#invalidate();
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** Whether the reader (or the page) has paused it. A figure that's offscreen or never reads
|
|
516
|
+
* time doesn't run its clock either way. */
|
|
517
|
+
get paused() {
|
|
518
|
+
return this.#paused ?? true;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** Plays from where it is. Each param time drives is handed back to time, carrying on from
|
|
522
|
+
* where the reader left the last one they moved. */
|
|
523
|
+
play() {
|
|
524
|
+
const moved = [...this.#held.keys()].filter((name) => this.#driven.has(name)).pop();
|
|
525
|
+
if (moved && this.#player) {
|
|
526
|
+
try {
|
|
527
|
+
this.#seek(this.#player.time_for(moved, this.#held.get(moved)));
|
|
528
|
+
} catch {}
|
|
529
|
+
}
|
|
530
|
+
for (const name of [...this.#held.keys()]) if (this.#driven.has(name)) this.#release(name);
|
|
531
|
+
const was = this.#paused;
|
|
532
|
+
this.#paused = false;
|
|
533
|
+
this.#sync();
|
|
534
|
+
this.#invalidate();
|
|
535
|
+
if (was !== false) this.dispatchEvent(new Event('play'));
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
pause() {
|
|
539
|
+
const was = this.#paused;
|
|
540
|
+
this.#paused = true;
|
|
541
|
+
this.#sync();
|
|
542
|
+
if (was !== true) this.dispatchEvent(new Event('pause'));
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
get playbackRate() {
|
|
546
|
+
return this.#rate;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
set playbackRate(rate) {
|
|
550
|
+
this.#rate = rate;
|
|
551
|
+
if (this.#clock) this.#clock.playbackRate = rate;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/** The `Animation` that keeps the figure's time. Read it, but play, pause and seek through
|
|
555
|
+
* the element, which knows when to draw. */
|
|
556
|
+
get clock() {
|
|
557
|
+
return this.#clock;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
#clockTime() {
|
|
561
|
+
return (this.#clock?.effect.getComputedTiming().progress ?? 0) * this.duration;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
#seek(seconds) {
|
|
565
|
+
this.#time = Math.min(Math.max(0, seconds), this.duration);
|
|
566
|
+
if (this.#clock) this.#clock.currentTime = this.#time * 1000;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/** Follows a new figure's duration, keeping the time where it is. */
|
|
570
|
+
#retime() {
|
|
571
|
+
if (!this.#clock) return;
|
|
572
|
+
const time = this.#clock.playState === 'running' ? this.#clockTime() : this.#time;
|
|
573
|
+
this.#clock.effect.updateTiming({ duration: this.duration * 1000 });
|
|
574
|
+
this.#seek(time > this.duration ? time % this.duration : time);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/** Runs the clock when the figure is playing, near the viewport and reads time, and stops it
|
|
578
|
+
* otherwise. */
|
|
579
|
+
#sync() {
|
|
580
|
+
const clock = this.#clock;
|
|
581
|
+
if (!clock) return;
|
|
582
|
+
const run = this.#paused === false && this.#visible && !!this.#player && !!this.#info?.usesTime;
|
|
583
|
+
const running = clock.playState === 'running';
|
|
584
|
+
if (run && !running) {
|
|
585
|
+
clock.currentTime = this.#time * 1000;
|
|
586
|
+
clock.play();
|
|
587
|
+
this.#schedule();
|
|
588
|
+
} else if (!run && running) {
|
|
589
|
+
this.#time = this.#clockTime();
|
|
590
|
+
clock.pause();
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
// ---- Beats ----
|
|
595
|
+
|
|
596
|
+
/** The figure's `beat` this frame. Setting it seeks time when the beat follows time, so the
|
|
597
|
+
* two can't come apart, and otherwise holds the param. */
|
|
598
|
+
get beat() {
|
|
599
|
+
return this.value('beat');
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
set beat(target) {
|
|
603
|
+
const param = this.#info?.params.find((p) => p.id === 'beat');
|
|
604
|
+
if (!param) return;
|
|
605
|
+
target = Math.min(Math.max(param.min, target), param.max);
|
|
606
|
+
if (!this.#driven.has('beat')) {
|
|
607
|
+
this.hold('beat', target);
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
// A beat that follows time is taken to only count up, so the first moment it reaches the
|
|
611
|
+
// target is found by halving. Sampling, as `time_for` does, lands just short of it.
|
|
612
|
+
let [lo, hi] = [0, this.duration];
|
|
613
|
+
for (let k = 0; k < 40; k++) {
|
|
614
|
+
const mid = (lo + hi) / 2;
|
|
615
|
+
if (this.#valueAt('beat', mid) >= target - 1e-9) hi = mid;
|
|
616
|
+
else lo = mid;
|
|
617
|
+
}
|
|
618
|
+
this.time = hi;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** Steps a beat forward or back, pausing, as a reader stepping through does. */
|
|
622
|
+
step(by) {
|
|
623
|
+
const beat = this.beat;
|
|
624
|
+
if (!Number.isFinite(beat)) return;
|
|
625
|
+
this.pause();
|
|
626
|
+
this.beat = by > 0 ? Math.floor(beat + 1e-6) + by : Math.ceil(beat - 1e-6) + by;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// ---- Params ----
|
|
630
|
+
|
|
631
|
+
/** A binding's value at a time (now, by default), or NaN if it doesn't exist then. */
|
|
632
|
+
value(name, time = this.#time) {
|
|
633
|
+
return this.#valueAt(name, time);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
#valueAt(name, time) {
|
|
637
|
+
if (!this.#player || !this.#info) return NaN;
|
|
638
|
+
try {
|
|
639
|
+
return this.#player.value(name, time);
|
|
640
|
+
} catch {
|
|
641
|
+
return NaN;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/**
|
|
646
|
+
* A param's range this frame, as `[min, max]`. An end that follows other params, as the `q` of
|
|
647
|
+
* `0..q` does, moves with them, and the figure keeps the param inside it. `info.params` gives
|
|
648
|
+
* the widest each range gets, as `min` and `max`, and the params that move it, as `follows`,
|
|
649
|
+
* so a control only has to ask again for a param that follows something.
|
|
650
|
+
*/
|
|
651
|
+
range(name, time = this.#time) {
|
|
652
|
+
const param = this.#info?.params.find((p) => p.id === name);
|
|
653
|
+
if (!param) return [NaN, NaN];
|
|
654
|
+
if (!param.follows?.length || !this.#player) return [param.min, param.max];
|
|
655
|
+
try {
|
|
656
|
+
return Array.from(this.#player.range(name, time));
|
|
657
|
+
} catch {
|
|
658
|
+
return [param.min, param.max];
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/** Takes a param over from time, at this value, until it's released or the figure plays. */
|
|
663
|
+
hold(name, value) {
|
|
664
|
+
this.#held.delete(name);
|
|
665
|
+
this.#held.set(name, value);
|
|
666
|
+
this.#player?.set_param(name, value);
|
|
667
|
+
this.#invalidate();
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
/** Hands a param back to its binding, or every param with no name. */
|
|
671
|
+
release(name) {
|
|
672
|
+
for (const each of name === undefined ? [...this.#held.keys()] : [name]) this.#release(each);
|
|
673
|
+
this.#invalidate();
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
#release(name) {
|
|
677
|
+
this.#held.delete(name);
|
|
678
|
+
this.#player?.release_param(name);
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/** The params a reader or the page holds, by name. */
|
|
682
|
+
get held() {
|
|
683
|
+
return new Map(this.#held);
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/** Every param's value this frame, by name. Setting holds each one given. */
|
|
687
|
+
get params() {
|
|
688
|
+
return Object.fromEntries((this.#info?.params ?? []).map((p) => [p.id, this.value(p.id)]));
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
set params(values) {
|
|
692
|
+
for (const [name, value] of Object.entries(values)) this.hold(name, value);
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/** The figure's design size, `[width, height]` in design pixels, from its sheets. */
|
|
696
|
+
get designSize() {
|
|
697
|
+
return this.#size;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/** What the figure says of itself: its size, duration, beats, params, which bindings time
|
|
701
|
+
* drives (`timeDriven`), and whether anything reads time (`usesTime`). */
|
|
702
|
+
get info() {
|
|
703
|
+
return this.#info;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/** The named colors the figure's sheets define, by name, so the page around it can match:
|
|
707
|
+
* `{ paper_color: 'rgb(…)', … }`. Empty until the figure has loaded. */
|
|
708
|
+
get colors() {
|
|
709
|
+
return this.#info?.colors ?? {};
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/** The WASM host, for measuring and debugging. */
|
|
713
|
+
get player() {
|
|
714
|
+
return this.#player;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
get backend() {
|
|
718
|
+
return this.#player?.backend ?? null;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
// ---- Handles: a drag sets its param through the figure's own inverse ----
|
|
722
|
+
|
|
723
|
+
#device(e) {
|
|
724
|
+
const box = this.#canvas.getBoundingClientRect();
|
|
725
|
+
return [(e.clientX - box.left) * (this.#canvas.width / box.width), (e.clientY - box.top) * (this.#canvas.height / box.height)];
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
#pointerDown = (e) => {
|
|
729
|
+
if (!this.#player) return;
|
|
730
|
+
const [x, y] = this.#device(e);
|
|
731
|
+
try {
|
|
732
|
+
if (!this.#player.grab(this.#time, x, y, REACH * (window.devicePixelRatio || 1))) return;
|
|
733
|
+
this.pause();
|
|
734
|
+
this.#canvas.setPointerCapture(e.pointerId);
|
|
735
|
+
this.#canvas.style.cursor = 'grabbing';
|
|
736
|
+
// The keys carry on from where the pointer leaves it.
|
|
737
|
+
this.#handles[this.#player.grabbed()]?.focus({ preventScroll: true });
|
|
738
|
+
this.#drag(x, y);
|
|
739
|
+
} catch {}
|
|
740
|
+
};
|
|
741
|
+
|
|
742
|
+
#pointerMove = (e) => {
|
|
743
|
+
if (!this.#player) return;
|
|
744
|
+
const [x, y] = this.#device(e);
|
|
745
|
+
try {
|
|
746
|
+
if (!this.#canvas.hasPointerCapture(e.pointerId)) {
|
|
747
|
+
this.#canvas.style.cursor = this.#player.grab(this.#time, x, y, REACH * (window.devicePixelRatio || 1)) ? 'grab' : '';
|
|
748
|
+
this.#player.release();
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
this.#drag(x, y);
|
|
752
|
+
} catch {}
|
|
753
|
+
};
|
|
754
|
+
|
|
755
|
+
#pointerEnd = (e) => {
|
|
756
|
+
if (this.#canvas.hasPointerCapture(e.pointerId)) this.#canvas.releasePointerCapture(e.pointerId);
|
|
757
|
+
this.#player?.release();
|
|
758
|
+
this.#canvas.style.cursor = '';
|
|
759
|
+
};
|
|
760
|
+
|
|
761
|
+
#drag(x, y) {
|
|
762
|
+
this.#moved(this.#player.drag(this.#time, x, y));
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/** A handle set this param in the player: hold it here too, draw, and tell the page. */
|
|
766
|
+
#moved(name) {
|
|
767
|
+
if (!name) return;
|
|
768
|
+
const value = this.#player.value(name, this.#time);
|
|
769
|
+
this.#held.delete(name);
|
|
770
|
+
this.#held.set(name, value);
|
|
771
|
+
this.#invalidate();
|
|
772
|
+
this.dispatchEvent(new CustomEvent('input', { bubbles: true, detail: { name, value } }));
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// ---- Keys: every handle can be tabbed to and moved, and beats stepped ----
|
|
776
|
+
|
|
777
|
+
/** Whether the figure has beats to step through. */
|
|
778
|
+
#steps() {
|
|
779
|
+
const info = this.#info;
|
|
780
|
+
return !!info && info.beats.length > 0 && info.params.some((p) => p.id === 'beat');
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
/**
|
|
784
|
+
* Makes what a reader can do with the figure reachable without a pointer, once it's known.
|
|
785
|
+
* Each handle gets something to focus, named for its mark, that says its param's value as a
|
|
786
|
+
* slider does. A figure with beats becomes a tab stop itself, unless the page has said where
|
|
787
|
+
* it is in the tab order, and a figure with either is a group, so its name is read. One with
|
|
788
|
+
* neither is an image.
|
|
789
|
+
*/
|
|
790
|
+
#operable() {
|
|
791
|
+
const handles = this.#info.handles ?? [];
|
|
792
|
+
const key = JSON.stringify(handles);
|
|
793
|
+
if (this.#handleLayer.dataset.for !== key) {
|
|
794
|
+
this.#handleLayer.dataset.for = key;
|
|
795
|
+
this.#handles = handles.map((handle, index) => {
|
|
796
|
+
const el = document.createElement('div');
|
|
797
|
+
el.className = 'handle';
|
|
798
|
+
el.setAttribute('part', 'handle');
|
|
799
|
+
el.setAttribute('role', 'slider');
|
|
800
|
+
el.setAttribute('aria-label', handle.mark);
|
|
801
|
+
el.tabIndex = 0;
|
|
802
|
+
el.hidden = true;
|
|
803
|
+
el.addEventListener('keydown', (e) => this.#handleKey(e, index));
|
|
804
|
+
return el;
|
|
805
|
+
});
|
|
806
|
+
this.#handleLayer.replaceChildren(...this.#handles);
|
|
807
|
+
}
|
|
808
|
+
const steps = this.#steps();
|
|
809
|
+
if (steps && !this.hasAttribute('tabindex')) {
|
|
810
|
+
this.tabIndex = 0;
|
|
811
|
+
this.#tabbable = true;
|
|
812
|
+
} else if (!steps && this.#tabbable) {
|
|
813
|
+
this.removeAttribute('tabindex');
|
|
814
|
+
this.#tabbable = false;
|
|
815
|
+
}
|
|
816
|
+
// One a reader only looks at is an image, when the page has named it.
|
|
817
|
+
const named = this.hasAttribute('aria-label') || this.hasAttribute('aria-labelledby');
|
|
818
|
+
if (this.#internals) this.#internals.role = steps || handles.length ? 'group' : named ? 'img' : null;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/** Puts each handle's focus where its mark is, and says its value, after a frame is drawn. */
|
|
822
|
+
#placeHandles() {
|
|
823
|
+
if (!this.#handles.length) return;
|
|
824
|
+
let places;
|
|
825
|
+
try {
|
|
826
|
+
places = this.#player.handle_places(this.#time);
|
|
827
|
+
} catch {
|
|
828
|
+
return;
|
|
829
|
+
}
|
|
830
|
+
const scale = this.#canvas.clientWidth / this.#canvas.width;
|
|
831
|
+
this.#handles.forEach((el, i) => {
|
|
832
|
+
const [x, y] = [places[2 * i] * scale, places[2 * i + 1] * scale];
|
|
833
|
+
const there = Number.isFinite(x) && Number.isFinite(y);
|
|
834
|
+
if (el.hidden === there) el.hidden = !there;
|
|
835
|
+
if (!there) return;
|
|
836
|
+
const moved = `translate(${x.toFixed(2)}px, ${y.toFixed(2)}px)`;
|
|
837
|
+
if (el.style.transform !== moved) el.style.transform = moved;
|
|
838
|
+
const param = this.#info.handles[i].param;
|
|
839
|
+
const value = this.#valueAt(param, this.#time);
|
|
840
|
+
const [min, max] = this.range(param);
|
|
841
|
+
const said = [min, max, value].join(' ');
|
|
842
|
+
if (el.dataset.said === said) return;
|
|
843
|
+
el.dataset.said = said;
|
|
844
|
+
el.setAttribute('aria-valuemin', String(min));
|
|
845
|
+
el.setAttribute('aria-valuemax', String(max));
|
|
846
|
+
el.setAttribute('aria-valuenow', String(value));
|
|
847
|
+
el.setAttribute('aria-valuetext', `${param} = ${this.#format(param, value)}`);
|
|
848
|
+
});
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/** A param's value as text: as many decimals as its step has, or three. */
|
|
852
|
+
#format(name, value) {
|
|
853
|
+
const step = this.#info?.params.find((p) => p.id === name)?.step;
|
|
854
|
+
if (step != null) return value.toFixed((String(step).split('.')[1] ?? '').length);
|
|
855
|
+
return String(Number(value.toFixed(3)));
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
/**
|
|
859
|
+
* A key on a focused handle. An arrow moves it that way on the page, a hundredth of the
|
|
860
|
+
* figure's shorter side, or a tenth with Shift, through the handle's own inverse, as a drag
|
|
861
|
+
* that far would. A param with steps goes to its next one that way. Home and End take the
|
|
862
|
+
* param to the ends of its range, and Page Up and Page Down move it a tenth of the range.
|
|
863
|
+
*/
|
|
864
|
+
#handleKey(e, index) {
|
|
865
|
+
if (!this.#player || e.altKey || e.ctrlKey || e.metaKey) return;
|
|
866
|
+
const way = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[e.key];
|
|
867
|
+
const param = this.#info.handles[index].param;
|
|
868
|
+
try {
|
|
869
|
+
if (way) {
|
|
870
|
+
const { width, height } = this.#canvas;
|
|
871
|
+
const step = Math.max(Math.min(width, height) / 100, 2 * (window.devicePixelRatio || 1)) * (e.shiftKey ? 10 : 1);
|
|
872
|
+
this.pause();
|
|
873
|
+
this.#moved(this.#player.nudge(this.#time, index, way[0] * step, way[1] * step));
|
|
874
|
+
} else if (['Home', 'End', 'PageUp', 'PageDown'].includes(e.key)) {
|
|
875
|
+
const [min, max] = this.range(param);
|
|
876
|
+
const now = this.#valueAt(param, this.#time);
|
|
877
|
+
const to = { Home: min, End: max, PageUp: now + (max - min) / 10, PageDown: now - (max - min) / 10 }[e.key];
|
|
878
|
+
this.pause();
|
|
879
|
+
this.#player.set_param(param, to);
|
|
880
|
+
this.#moved(param);
|
|
881
|
+
} else {
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
} catch {
|
|
885
|
+
return;
|
|
886
|
+
}
|
|
887
|
+
// The key is the handle's: the page doesn't scroll, and the figure doesn't step a beat.
|
|
888
|
+
e.preventDefault();
|
|
889
|
+
e.stopPropagation();
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
/** A key on the figure itself: ← and → step its beats, and Home and End go to the first and
|
|
893
|
+
* last. What it came to is said for a screen reader, with the beat's caption. */
|
|
894
|
+
#key = (e) => {
|
|
895
|
+
if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || !this.#player || !this.#steps()) return;
|
|
896
|
+
const range = this.#info.params.find((p) => p.id === 'beat');
|
|
897
|
+
if (e.key === 'ArrowRight') this.step(1);
|
|
898
|
+
else if (e.key === 'ArrowLeft') this.step(-1);
|
|
899
|
+
else if (e.key === 'Home' || e.key === 'End') {
|
|
900
|
+
this.pause();
|
|
901
|
+
this.beat = e.key === 'Home' ? range.min : range.max;
|
|
902
|
+
} else return;
|
|
903
|
+
e.preventDefault();
|
|
904
|
+
const beats = this.#info.beats;
|
|
905
|
+
const beat = this.beat;
|
|
906
|
+
// Beats with lengths count the ones done, from 0. Ones without say which it's on.
|
|
907
|
+
const timed = (this.#info.beatLengths?.length ?? 0) > 0;
|
|
908
|
+
const n = Math.round(timed ? beat : beat + 1);
|
|
909
|
+
const caption = beats[n - 1] ?? '';
|
|
910
|
+
this.#said.textContent = n < 1 ? 'Start' : `Step ${n} of ${beats.length}${caption ? `: ${caption}` : ''}`;
|
|
911
|
+
};
|
|
912
|
+
|
|
913
|
+
// ---- Drawing ----
|
|
914
|
+
|
|
915
|
+
#invalidate() {
|
|
916
|
+
this.#dirty = true;
|
|
917
|
+
this.#schedule();
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
#schedule() {
|
|
921
|
+
if (this.#raf || !this.#player || !this.isConnected) return;
|
|
922
|
+
this.#raf = requestAnimationFrame(this.#frame);
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
/** One frame: read the clock if it runs, draw if anything changed, and move label springs.
|
|
926
|
+
* Another frame is asked for only while the clock runs or a label is still settling. */
|
|
927
|
+
#frame = (now) => {
|
|
928
|
+
this.#raf = 0;
|
|
929
|
+
// Springs coming out of a rest take one frame's step, not the whole time since the last.
|
|
930
|
+
if (this.#idle) this.#layer.last = now - 1000 / 60;
|
|
931
|
+
const running = this.#clock?.playState === 'running';
|
|
932
|
+
if (running) {
|
|
933
|
+
this.#time = this.#clockTime();
|
|
934
|
+
this.#dirty = true;
|
|
935
|
+
}
|
|
936
|
+
if (this.#dirty) this.#paint();
|
|
937
|
+
const settling = this.#layer.tick(now);
|
|
938
|
+
this.#idle = !running && !settling;
|
|
939
|
+
if (!this.#idle) this.#schedule();
|
|
940
|
+
};
|
|
941
|
+
|
|
942
|
+
#paint() {
|
|
943
|
+
this.#dirty = false;
|
|
944
|
+
if (!this.#player || !this.#info) return;
|
|
945
|
+
const fresh = this.#fresh;
|
|
946
|
+
this.#fresh = false;
|
|
947
|
+
// Zooming or moving to another screen changes it, so it's read each frame.
|
|
948
|
+
const dpr = window.devicePixelRatio || 1;
|
|
949
|
+
this.#layer.dpr = dpr;
|
|
950
|
+
try {
|
|
951
|
+
this.#layer.update(JSON.parse(this.#player.draw(this.#time, dpr)));
|
|
952
|
+
} catch (error) {
|
|
953
|
+
this.pause();
|
|
954
|
+
this.dispatchEvent(new CustomEvent('error', { detail: { error, time: this.#time, fresh } }));
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
957
|
+
if (!this.#drawn) {
|
|
958
|
+
this.#drawn = true;
|
|
959
|
+
this.#wait();
|
|
960
|
+
}
|
|
961
|
+
this.#placeHandles();
|
|
962
|
+
this.dispatchEvent(new CustomEvent('draw', { detail: { time: this.#time, fresh } }));
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
/** An `em` is the page's text size where the figure is, so its labels match the text around
|
|
966
|
+
* it at any size it's drawn. */
|
|
967
|
+
#setEm() {
|
|
968
|
+
const em = parseFloat(getComputedStyle(this.#canvas).fontSize);
|
|
969
|
+
const changed = em !== this.#emPx;
|
|
970
|
+
this.#emPx = em;
|
|
971
|
+
this.#player?.set_em(em);
|
|
972
|
+
return changed;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
/** Keeps the canvas's pixels matched to its laid-out size. A new size clears the canvas, and
|
|
976
|
+
* this runs after the frame's drawing and before it's shown, so it draws at once. */
|
|
977
|
+
#follow() {
|
|
978
|
+
if (!this.#player) {
|
|
979
|
+
match(this.#canvas);
|
|
980
|
+
return;
|
|
981
|
+
}
|
|
982
|
+
const [width, height] = [this.#canvas.width, this.#canvas.height];
|
|
983
|
+
this.#player.resize(...match(this.#canvas));
|
|
984
|
+
const em = this.#setEm();
|
|
985
|
+
if (em || this.#canvas.width !== width || this.#canvas.height !== height) {
|
|
986
|
+
this.#paint();
|
|
987
|
+
this.dispatchEvent(new CustomEvent('resize', { detail: { em: this.#emPx } }));
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
customElements.define('pencil-figure', PencilFigure);
|