beatsheet 0.0.0-stage → 0.2.0

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.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -2
  3. package/bin/beatsheet.js +14 -0
  4. package/bin/register-fallback.mjs +23 -0
  5. package/bin/resolve-fallback.mjs +83 -0
  6. package/package.json +45 -4
  7. package/player/env.d.ts +5 -0
  8. package/player/gallery-audio.ts +147 -0
  9. package/player/gallery-css.ts +144 -0
  10. package/player/gallery-detail.ts +385 -0
  11. package/player/gallery-music.ts +257 -0
  12. package/player/gallery-pick-state.ts +167 -0
  13. package/player/gallery-pick.ts +749 -0
  14. package/player/gallery-sounds.ts +137 -0
  15. package/player/gallery-state.ts +457 -0
  16. package/player/gallery.ts +612 -0
  17. package/player/index.html +49 -0
  18. package/player/main.ts +83 -0
  19. package/skill/SKILL.md +658 -0
  20. package/skill/examples/library/assets/tour/avatar-mk.svg +1 -0
  21. package/skill/examples/library/assets/tour/dashboard-insights.svg +1 -0
  22. package/skill/examples/library/assets/tour/dashboard.svg +1 -0
  23. package/skill/examples/library/assets/tour/settings.svg +1 -0
  24. package/skill/examples/library/library-tour.plan.md +32 -0
  25. package/skill/examples/library/library-tour.video.json +268 -0
  26. package/skill/reference/scene-techniques.md +306 -0
  27. package/skill/scripts/beats.ts +34 -0
  28. package/skill/scripts/catalogue.ts +120 -0
  29. package/skill/scripts/frames.ts +105 -0
  30. package/src/args.ts +344 -0
  31. package/src/cli.ts +95 -0
  32. package/src/commands.ts +812 -0
  33. package/src/default-project.config.ts +9 -0
  34. package/src/index.ts +47 -0
  35. package/src/packages.ts +17 -0
  36. package/src/paths.ts +32 -0
  37. package/src/project.ts +200 -0
  38. package/src/render/browser.ts +185 -0
  39. package/src/render/capture.ts +320 -0
  40. package/src/render/ffmpeg.ts +229 -0
  41. package/src/render/gif-info.ts +61 -0
  42. package/src/render/render.ts +220 -0
  43. package/src/samples.ts +557 -0
  44. package/src/server/api.ts +494 -0
  45. package/src/server/jobs.ts +210 -0
  46. package/src/server/security.ts +47 -0
  47. package/src/server/server.ts +191 -0
  48. package/src/server/sse.ts +76 -0
  49. package/src/server/static.ts +127 -0
  50. package/src/server/vite.ts +100 -0
  51. package/src/skill.ts +111 -0
  52. package/src/snap.ts +212 -0
  53. package/src/speech.ts +689 -0
  54. package/src/svg-text.ts +136 -0
  55. package/src/voicefx.ts +311 -0
  56. package/studio/3rdpartylicenses.txt +287 -0
  57. package/studio/favicon.ico +0 -0
  58. package/studio/icons/apple-touch-icon.png +0 -0
  59. package/studio/icons/icon-192.png +0 -0
  60. package/studio/icons/icon-512.png +0 -0
  61. package/studio/icons/icon.svg +1 -0
  62. package/studio/icons/maskable-512.png +0 -0
  63. package/studio/index.html +18 -0
  64. package/studio/main-KMYDBWZH.js +15 -0
  65. package/studio/manifest.webmanifest +17 -0
  66. package/studio/offline.html +92 -0
  67. package/studio/styles-NJ2CULOW.css +1 -0
  68. package/studio/sw.js +71 -0
@@ -0,0 +1,749 @@
1
+ /**
2
+ * The gallery page as the studio's add-scene picker (/player/?mode=gallery&pick=1#format=<id>): a
3
+ * tile per scene type, by category, looping its default sample (or the sample chosen on its chips)
4
+ * in the editor's format; a search over type title, id and description; and a larger preview of the
5
+ * hovered or focused tile with its facts, silent until Play. A pick (Add, double-click, Enter) posts
6
+ * the 'add-scene' message with the sample id to the studio, which checks it, inserts the scene and
7
+ * closes the overlay. Only tiles in view play; 'pause' from the studio stops everything.
8
+ */
9
+ import {
10
+ SCENE_CATEGORIES,
11
+ allowedProject,
12
+ createPlayer,
13
+ h,
14
+ sceneSamples,
15
+ type FormatId,
16
+ type Player,
17
+ type ProjectConfig,
18
+ type ResolvedSample,
19
+ type SceneType,
20
+ } from '@beatsheet/core';
21
+ import { liveContext, startPlayback, type Playback } from './gallery-audio';
22
+ import { GALLERY_CSS } from './gallery-css';
23
+ import {
24
+ PICK_CLOSE,
25
+ PICK_FORMATS,
26
+ beatLabel,
27
+ filterPickTypes,
28
+ nextTileIndex,
29
+ parsePickState,
30
+ pickMessage,
31
+ readStudioMessage,
32
+ sampleIndexForKey,
33
+ serializePickState,
34
+ tileLabel,
35
+ type PickState,
36
+ } from './gallery-pick-state';
37
+ import { fitRow, formatSeconds, groupByCategory, loopTime, sceneEntry, singleSceneDoc, tileBoxes, tilesToUnmount } from './gallery-state';
38
+
39
+ const SCROLL_KEY = 'beatsheet-picker-scroll';
40
+ const TILE_FPS = 30;
41
+ /** Time per frame spent mounting tiles: less than the gallery's, the editor shares this thread. */
42
+ const MOUNT_BUDGET_MS = 8;
43
+ /** Narrowest tile (room for the title and the chips); the preview is centred in it. */
44
+ const MIN_TILE_W = 196;
45
+
46
+ const PICK_CSS = `
47
+ .bs-pick .p-head { position: sticky; top: 0; z-index: 20; display: flex; align-items: center; gap: 10px; flex-wrap: wrap;
48
+ padding: 8px 14px; background: var(--g-panel); border-bottom: 1px solid var(--g-border); }
49
+ .bs-pick .p-head input[type='search'] { width: 300px; max-width: 100%; }
50
+ .bs-pick .p-body { display: grid; grid-template-columns: minmax(0, 1fr) 400px; align-items: start; }
51
+ .bs-pick .p-list { padding: 0 14px 60px; min-width: 0; }
52
+ .bs-pick .p-grid { display: flex; flex-wrap: wrap; gap: 10px; }
53
+ .bs-pick .p-tile { background: var(--g-panel); border: 1px solid var(--g-border); border-radius: var(--g-radius); padding: 6px;
54
+ cursor: pointer; display: flex; flex-direction: column; gap: 6px; position: relative; }
55
+ .bs-pick .p-tile:hover { border-color: var(--g-faint); }
56
+ .bs-pick .p-tile.active { border-color: var(--g-accent); }
57
+ .bs-pick .p-tile:focus-visible { outline: 2px solid var(--g-accent); outline-offset: 1px; }
58
+ .bs-pick .p-tile .g-preview { align-self: center; }
59
+ .bs-pick .p-tile .g-progress { position: static; margin-top: -4px; }
60
+ .bs-pick .p-tile.live .g-ph { display: none; }
61
+ .bs-pick .p-meta { display: flex; align-items: baseline; gap: 6px; min-width: 0; }
62
+ .bs-pick .p-title { font-size: 12px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
63
+ .bs-pick .p-meta code { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; flex: 1; }
64
+ .bs-pick .p-foot { display: flex; align-items: flex-start; gap: 6px; }
65
+ .bs-pick .p-chips { display: flex; flex-wrap: wrap; align-items: flex-start; align-content: flex-start; gap: 4px; min-width: 0; }
66
+ .bs-pick .p-foot .p-chips { flex: 1; }
67
+ .bs-gallery.bs-pick .p-chip { border-radius: 999px; padding: 0 8px; min-height: 20px; font-size: 11px; line-height: 18px;
68
+ background: transparent; color: var(--g-muted); max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
69
+ .bs-gallery.bs-pick .p-chip[aria-pressed='true'] { background: var(--g-accent-soft); border-color: var(--g-accent); color: var(--g-text); }
70
+ .bs-gallery.bs-pick .p-chip.stress { color: var(--g-warn); border-style: dashed; border-color: rgba(224, 184, 92, 0.55); }
71
+ .bs-gallery.bs-pick .p-chip.stress[aria-pressed='true'] { background: rgba(224, 184, 92, 0.14); }
72
+ .bs-gallery.bs-pick .p-add { min-height: 20px; padding: 0 10px; font-size: 11px; line-height: 18px; }
73
+ .bs-gallery.bs-pick .p-tile:hover .p-add, .bs-gallery.bs-pick .p-tile:focus .p-add, .bs-gallery.bs-pick .p-tile.active .p-add {
74
+ background: var(--g-accent); border-color: var(--g-accent); color: #0d1424; font-weight: 600; }
75
+ .bs-pick .p-side { position: sticky; top: var(--g-head-h, 45px); height: calc(100vh - var(--g-head-h, 45px)); overflow: auto;
76
+ border-left: 1px solid var(--g-border); background: var(--g-panel); padding: 14px; display: flex; flex-direction: column; gap: 10px; }
77
+ .bs-pick .p-stage { display: flex; justify-content: center; flex: 0 0 auto; }
78
+ .bs-pick .p-side > .g-progress { position: relative; left: 0; right: 0; flex: 0 0 auto; margin-top: -6px; }
79
+ .bs-pick .p-side-title { margin: 0; font-size: 16px; font-weight: 600; }
80
+ .bs-pick .p-desc { margin: 0; color: var(--g-muted); }
81
+ .bs-pick .p-facts { display: flex; flex-wrap: wrap; gap: 4px 14px; color: var(--g-muted); font-size: 12px; font-variant-numeric: tabular-nums; }
82
+ .bs-pick .p-facts b { color: var(--g-text); font-weight: 600; }
83
+ .bs-pick .p-actions { display: flex; gap: 8px; align-items: center; }
84
+ .bs-pick .p-hint { color: var(--g-faint); font-size: 11px; margin: auto 0 0; }
85
+ .bs-pick .p-status { color: var(--g-muted); font-size: 12px; }
86
+ .bs-pick .p-empty { color: var(--g-faint); padding: 40px 0; text-align: center; }
87
+ @media (max-width: 860px) { .bs-pick .p-body { grid-template-columns: 1fr; } .bs-pick .p-side { display: none; } }
88
+ `;
89
+
90
+ interface PickTile {
91
+ type: SceneType;
92
+ samples: ResolvedSample[];
93
+ /** The sample the tile shows and adds (its chips choose it). */
94
+ sample: ResolvedSample;
95
+ el: HTMLElement;
96
+ box: HTMLElement;
97
+ holder: HTMLElement;
98
+ bar: HTMLElement;
99
+ chips: HTMLButtonElement[];
100
+ addBtn: HTMLButtonElement;
101
+ player: Player | null;
102
+ duration: number;
103
+ startedAt: number;
104
+ lastSeen: number;
105
+ }
106
+
107
+ function storage(): Storage | null {
108
+ try {
109
+ return window.sessionStorage;
110
+ } catch {
111
+ return null;
112
+ }
113
+ }
114
+
115
+ function errorText(err: unknown): string {
116
+ return err instanceof Error ? err.message : String(err);
117
+ }
118
+
119
+ /** The larger preview of the hovered or focused tile; sound only after Play. */
120
+ class SidePanel {
121
+ readonly el = h('aside', { class: 'p-side', 'aria-label': 'Preview of the highlighted scene type' });
122
+ private readonly stage = h('div', { class: 'p-stage' });
123
+ private readonly box = h('div', { class: 'g-preview' });
124
+ private readonly holder = h('div', { class: 'g-holder' });
125
+ private readonly bar = h('i');
126
+ private readonly titleEl = h('h2', { class: 'p-side-title' });
127
+ private readonly idEl = h('code');
128
+ private readonly descEl = h('p', { class: 'p-desc' });
129
+ private readonly facts = h('div', { class: 'p-facts' });
130
+ private readonly chips = h('div', { class: 'p-chips', role: 'group', 'aria-label': 'Samples' });
131
+ private readonly playBtn = h('button', { type: 'button', title: 'Play this sample with sound (Space on a tile)' }, '▶ Play with sound');
132
+ private readonly addBtn = h('button', { type: 'button', class: 'g-primary' }, 'Add scene');
133
+ readonly status = h('span', { class: 'p-status', role: 'status' });
134
+ private player: Player | null = null;
135
+ private tile: PickTile | null = null;
136
+ private sample: ResolvedSample | null = null;
137
+ private startedAt = 0;
138
+ private duration = 0;
139
+ private playback: Playback | null = null;
140
+ private loading = false;
141
+ private buffer: Promise<AudioBuffer | null> | null = null;
142
+
143
+ constructor(
144
+ private readonly project: ProjectConfig,
145
+ private readonly assetBase: string,
146
+ private readonly onChoose: (tile: PickTile, sample: ResolvedSample) => void,
147
+ private readonly onPick: (tile: PickTile, sample: ResolvedSample) => void,
148
+ ) {
149
+ this.box.append(h('span', { class: 'g-ph', 'aria-hidden': 'true' }, 'Hover or focus a scene type'), this.holder);
150
+ this.stage.append(this.box);
151
+ this.el.append(
152
+ this.stage,
153
+ h('div', { class: 'g-progress' }, this.bar),
154
+ h('div', { class: 'p-meta' }, this.titleEl, this.idEl),
155
+ this.descEl,
156
+ this.facts,
157
+ this.chips,
158
+ h('div', { class: 'p-actions' }, this.playBtn, this.addBtn, this.status),
159
+ h('p', { class: 'p-hint' }, 'Enter or double-click adds · arrows move · 1–9 choose a sample · Space plays · / searches · Esc closes'),
160
+ );
161
+ this.playBtn.addEventListener('click', () => void this.togglePlay());
162
+ this.addBtn.addEventListener('click', () => {
163
+ if (this.tile && this.sample) this.onPick(this.tile, this.sample);
164
+ });
165
+ this.show(null, null, '16:9');
166
+ new ResizeObserver(() => this.layout()).observe(this.stage);
167
+ window.addEventListener('resize', () => this.layout());
168
+ }
169
+
170
+ private format: FormatId = '16:9';
171
+
172
+ /** Fits the preview into the panel's width and at most 46 % of the page's height (372 px wide before layout). */
173
+ private layout(): void {
174
+ const [fit] = fitRow([this.format], this.stage.clientWidth || 372, Math.min(420, Math.max(160, window.innerHeight * 0.46)));
175
+ if (!fit) return;
176
+ this.box.style.width = `${fit.width}px`;
177
+ this.box.style.height = `${fit.height}px`;
178
+ this.holder.style.transform = `scale(${fit.scale})`;
179
+ }
180
+
181
+ get current(): { tile: PickTile; sample: ResolvedSample } | null {
182
+ return this.tile && this.sample ? { tile: this.tile, sample: this.sample } : null;
183
+ }
184
+
185
+ /** Shows a tile's sample (nothing when null); stops any sound. */
186
+ show(tile: PickTile | null, sample: ResolvedSample | null, format: FormatId): void {
187
+ if (tile === this.tile && sample === this.sample && this.player?.format.id === format) return;
188
+ this.stop();
189
+ this.player?.destroy();
190
+ this.player = null;
191
+ this.buffer = null;
192
+ this.tile = tile;
193
+ this.sample = sample;
194
+ this.box.classList.toggle('live', false);
195
+ this.format = format;
196
+ this.layout();
197
+ this.chips.replaceChildren();
198
+ this.facts.replaceChildren();
199
+ if (!tile || !sample) {
200
+ this.titleEl.textContent = 'Pick a scene type';
201
+ this.idEl.textContent = '';
202
+ this.descEl.textContent = 'Hover or focus a tile to see it larger here.';
203
+ this.playBtn.disabled = true;
204
+ this.addBtn.disabled = true;
205
+ return;
206
+ }
207
+ const { type } = tile;
208
+ this.titleEl.textContent = type.title;
209
+ this.idEl.textContent = type.id;
210
+ this.descEl.textContent = type.description ?? '';
211
+ this.playBtn.disabled = false;
212
+ this.addBtn.disabled = false;
213
+ this.addBtn.setAttribute('aria-label', `Add ${type.title}, ${sample.title}`);
214
+ try {
215
+ this.player = createPlayer({ container: this.holder, project: this.project, doc: singleSceneDoc(sceneEntry(type.id, sample), [format]), format, assetBase: this.assetBase });
216
+ this.box.classList.add('live');
217
+ this.box.querySelector('.g-ph')?.remove();
218
+ } catch (err) {
219
+ this.box.appendChild(h('div', { class: 'g-error' }, errorText(err)));
220
+ }
221
+ const resolved = this.player?.timeline;
222
+ this.duration = resolved?.duration ?? sample.duration;
223
+ const beats = resolved?.scenes[0]?.beats.length ?? 0;
224
+ this.facts.append(h('span', null, h('b', null, beatLabel(beats))), h('span', null, 'default ', h('b', null, formatSeconds(type.defaultDuration))));
225
+ if (sample.duration !== type.defaultDuration) this.facts.append(h('span', null, 'this sample ', h('b', null, formatSeconds(sample.duration))));
226
+ this.facts.append(h('span', null, `${tile.samples.length} ${tile.samples.length === 1 ? 'sample' : 'samples'}`));
227
+ tile.samples.forEach((s, i) => {
228
+ const chip = h(
229
+ 'button',
230
+ { type: 'button', class: `p-chip${s.stress ? ' stress' : ''}`, 'aria-pressed': String(s === sample), title: `${s.title}${s.stress ? ' (stress sample: longest content)' : ''} · ${formatSeconds(s.duration)} · key ${i + 1} · double-click adds` },
231
+ s.stress ? `${s.title} · stress` : s.title,
232
+ );
233
+ chip.addEventListener('click', () => this.onChoose(tile, s));
234
+ chip.addEventListener('dblclick', () => this.onPick(tile, s));
235
+ this.chips.appendChild(chip);
236
+ });
237
+ this.startedAt = performance.now();
238
+ this.seek(0);
239
+ }
240
+
241
+ private seek(t: number): void {
242
+ this.player?.seek(t);
243
+ this.bar.style.transform = `scaleX(${this.duration > 0 ? t / this.duration : 0})`;
244
+ }
245
+
246
+ /** One frame: the silent loop, or the playback clock while playing. */
247
+ frame(now: number): void {
248
+ if (!this.player) return;
249
+ if (this.loading) return;
250
+ if (this.playback) {
251
+ const t = this.playback.time();
252
+ if (t >= this.duration) {
253
+ this.stop();
254
+ this.startedAt = now;
255
+ this.seek(0);
256
+ return;
257
+ }
258
+ this.seek(t);
259
+ return;
260
+ }
261
+ this.seek(loopTime((now - this.startedAt) / 1000, this.duration));
262
+ }
263
+
264
+ restart(): void {
265
+ this.startedAt = performance.now();
266
+ }
267
+
268
+ get playing(): boolean {
269
+ return !!this.playback || this.loading;
270
+ }
271
+
272
+ /** Plays the shown sample from its start with sound (a second call stops it). */
273
+ async togglePlay(): Promise<void> {
274
+ if (this.playing) {
275
+ this.stop();
276
+ return;
277
+ }
278
+ const player = this.player;
279
+ if (!player) return;
280
+ // Inside the click or key press: browsers start an AudioContext only from a user gesture.
281
+ liveContext();
282
+ this.loading = true;
283
+ this.playBtn.textContent = '… Mixing';
284
+ this.buffer ??= player.renderAudio({ sampleRate: 22050 }).catch((err: unknown) => {
285
+ console.warn(`[beatsheet picker] audio: ${errorText(err)}`);
286
+ return null;
287
+ });
288
+ const buffer = await this.buffer;
289
+ if (!this.loading || player !== this.player) return;
290
+ this.loading = false;
291
+ this.seek(0);
292
+ this.playback = startPlayback(buffer, 0);
293
+ this.playBtn.textContent = '❚❚ Stop';
294
+ }
295
+
296
+ /** Stops the sound (and a mix still loading from starting). */
297
+ stop(): void {
298
+ this.loading = false;
299
+ this.playback?.stop();
300
+ this.playback = null;
301
+ this.playBtn.textContent = '▶ Play with sound';
302
+ this.startedAt = performance.now();
303
+ }
304
+
305
+ flash(text: string): void {
306
+ this.status.textContent = text;
307
+ setTimeout(() => {
308
+ if (this.status.textContent === text) this.status.textContent = '';
309
+ }, 1800);
310
+ }
311
+ }
312
+
313
+ class Picker {
314
+ private state: PickState = parsePickState(location.hash);
315
+ private readonly embedded = window.parent !== window;
316
+ private readonly tiles = new Map<string, PickTile>();
317
+ /** Tiles shown (after the search), in reading order. */
318
+ private shown: PickTile[] = [];
319
+ private readonly visible = new Set<PickTile>();
320
+ private readonly pending = new Set<PickTile>();
321
+ private readonly observer: IntersectionObserver;
322
+ private raf = 0;
323
+ private lastFrame = 0;
324
+ /** Hidden by the studio (overlay closed): nothing plays until 'pick-open'. */
325
+ private suspended = false;
326
+ private searchTimer: ReturnType<typeof setTimeout> | undefined;
327
+
328
+ private readonly head = h('header', { class: 'p-head g-head' });
329
+ private readonly search = h('input', { type: 'search', placeholder: 'Search scene types ( / )', 'aria-label': 'Search scene types by title, id or description' });
330
+ private readonly formatSeg = h('div', { class: 'g-seg', role: 'group', 'aria-label': 'Preview format' });
331
+ private readonly summary = h('span', { class: 'g-summary', role: 'status' });
332
+ private readonly list = h('main', { class: 'p-list', 'aria-label': 'Scene types' });
333
+ private readonly side: SidePanel;
334
+
335
+ constructor(
336
+ private readonly project: ProjectConfig,
337
+ private readonly assetBase: string,
338
+ ) {
339
+ this.side = new SidePanel(
340
+ project,
341
+ assetBase,
342
+ (tile, sample) => this.choose(tile, sample),
343
+ (tile, sample) => this.pick(tile, sample),
344
+ );
345
+ this.observer = new IntersectionObserver((entries) => this.onIntersect(entries), { root: document, rootMargin: '120px 0px' });
346
+ }
347
+
348
+ start(): void {
349
+ document.documentElement.classList.add('bs-gallery', 'bs-pick');
350
+ document.title = `${this.project.name} · add scene`;
351
+ const style = document.createElement('style');
352
+ style.id = 'bs-gallery-css';
353
+ style.textContent = GALLERY_CSS + PICK_CSS;
354
+ document.head.appendChild(style);
355
+
356
+ for (const f of PICK_FORMATS) {
357
+ const b = h('button', { type: 'button', title: `${f} previews`, 'data-value': f }, f);
358
+ b.addEventListener('click', () => this.setFormat(f));
359
+ this.formatSeg.appendChild(b);
360
+ }
361
+ this.search.value = this.state.query;
362
+ this.search.addEventListener('input', () => {
363
+ clearTimeout(this.searchTimer);
364
+ this.searchTimer = setTimeout(() => this.setQuery(this.search.value.trim()), 100);
365
+ });
366
+ this.search.addEventListener('keydown', (e) => {
367
+ if (e.key === 'Escape' && this.search.value) {
368
+ e.preventDefault();
369
+ e.stopPropagation();
370
+ this.search.value = '';
371
+ this.setQuery('');
372
+ } else if (e.key === 'ArrowDown' || e.key === 'Enter') {
373
+ // From the search into the results (Enter adds the first match when it is the only one).
374
+ const first = this.shown[0];
375
+ if (!first) return;
376
+ e.preventDefault();
377
+ if (e.key === 'Enter' && this.shown.length === 1) this.pick(first, first.sample);
378
+ else first.el.focus();
379
+ }
380
+ });
381
+ this.head.append(this.search, this.formatSeg, h('span', { class: 'g-spacer' }), this.summary);
382
+ document.body.append(this.head, h('div', { class: 'p-body' }, this.list, this.side.el));
383
+ const measure = (): void => document.documentElement.style.setProperty('--g-head-h', `${this.head.offsetHeight}px`);
384
+ new ResizeObserver(measure).observe(this.head);
385
+ measure();
386
+
387
+ for (const type of this.project.scenes) this.tiles.set(type.id, this.buildTile(type));
388
+ this.renderHead();
389
+ this.renderList();
390
+ this.restoreScroll();
391
+ this.side.show(null, null, this.state.format);
392
+
393
+ window.addEventListener('message', (e) => this.onMessage(e));
394
+ window.addEventListener('pagehide', () => this.saveScroll());
395
+ let scrollTimer: ReturnType<typeof setTimeout> | undefined;
396
+ window.addEventListener('scroll', () => {
397
+ clearTimeout(scrollTimer);
398
+ scrollTimer = setTimeout(() => this.saveScroll(), 150);
399
+ });
400
+ document.addEventListener('keydown', (e) => this.onKey(e));
401
+ if (this.embedded) this.search.focus({ preventScroll: true });
402
+ }
403
+
404
+ // --- state ---------------------------------------------------------------------------
405
+
406
+ private writeHash(): void {
407
+ history.replaceState(history.state, '', serializePickState(this.state));
408
+ }
409
+
410
+ private setFormat(format: FormatId): void {
411
+ if (format === this.state.format) return;
412
+ this.state = { ...this.state, format };
413
+ this.writeHash();
414
+ this.renderHead();
415
+ for (const tile of this.tiles.values()) this.resizeTile(tile);
416
+ const cur = this.side.current;
417
+ this.side.show(cur?.tile ?? null, cur?.sample ?? null, format);
418
+ this.kick();
419
+ }
420
+
421
+ private setQuery(query: string): void {
422
+ clearTimeout(this.searchTimer);
423
+ this.searchTimer = undefined;
424
+ if (query === this.state.query) return;
425
+ this.state = { ...this.state, query };
426
+ this.writeHash();
427
+ this.renderList();
428
+ }
429
+
430
+ private renderHead(): void {
431
+ for (const b of Array.from(this.formatSeg.children) as HTMLElement[]) b.setAttribute('aria-pressed', String(b.dataset.value === this.state.format));
432
+ }
433
+
434
+ private renderList(): void {
435
+ const types = filterPickTypes(this.project.scenes, this.state.query);
436
+ const groups = groupByCategory(types, (t) => t.category, SCENE_CATEGORIES);
437
+ const content = document.createDocumentFragment();
438
+ this.shown = [];
439
+ for (const g of groups) {
440
+ const grid = h('div', { class: 'p-grid', role: 'group', 'aria-label': g.title });
441
+ for (const type of g.items) {
442
+ const tile = this.tiles.get(type.id) as PickTile;
443
+ grid.appendChild(tile.el);
444
+ this.shown.push(tile);
445
+ }
446
+ content.append(h('h2', { class: 'g-cat' }, g.title, h('span', { class: 'g-count' }, `${g.items.length} ${g.items.length === 1 ? 'type' : 'types'}`)), grid);
447
+ }
448
+ if (!groups.length) content.appendChild(h('p', { class: 'p-empty' }, this.project.scenes.length ? 'No scene type matches the search.' : 'This project has no scene types.'));
449
+ const shown = new Set(this.shown);
450
+ for (const tile of this.tiles.values()) {
451
+ if (!shown.has(tile)) {
452
+ this.visible.delete(tile);
453
+ this.pending.delete(tile);
454
+ this.unmount(tile);
455
+ }
456
+ }
457
+ this.list.replaceChildren(content);
458
+ // Tabbing reaches the tiles in the order shown; the first one is the default stop after the search.
459
+ const n = this.shown.length;
460
+ this.summary.textContent = `${n} ${n === 1 ? 'type' : 'types'}`;
461
+ const cur = this.side.current;
462
+ if (cur && !shown.has(cur.tile)) this.side.show(null, null, this.state.format);
463
+ }
464
+
465
+ // --- tiles -----------------------------------------------------------------------------
466
+
467
+ private buildTile(type: SceneType): PickTile {
468
+ const samples = sceneSamples(type);
469
+ const sample = samples[0] as ResolvedSample;
470
+ const holder = h('div', { class: 'g-holder' });
471
+ const box = h('div', { class: 'g-preview' }, h('span', { class: 'g-ph', 'aria-hidden': 'true' }, type.title), holder);
472
+ const bar = h('i');
473
+ const addBtn = h('button', { type: 'button', class: 'p-add', tabindex: -1 }, 'Add');
474
+ const chipRow = h('div', { class: 'p-chips', role: 'group', 'aria-label': `Samples of ${type.title}` });
475
+ const el = h(
476
+ 'article',
477
+ { class: 'p-tile', tabindex: 0, 'data-type': type.id },
478
+ box,
479
+ h('div', { class: 'g-progress' }, bar),
480
+ h('div', { class: 'p-meta' }, h('span', { class: 'p-title' }, type.title), h('code', null, type.id), h('span', { class: 'g-dur' }, formatSeconds(type.defaultDuration))),
481
+ h('div', { class: 'p-foot' }, chipRow, addBtn),
482
+ );
483
+ const tile: PickTile = { type, samples, sample, el, box, holder, bar, chips: [], addBtn, player: null, duration: sample.duration, startedAt: 0, lastSeen: 0 };
484
+ samples.forEach((s, i) => {
485
+ const chip = h(
486
+ 'button',
487
+ { type: 'button', class: `p-chip${s.stress ? ' stress' : ''}`, tabindex: -1, title: `${s.title}${s.stress ? ' (stress sample: longest content)' : ''} · ${formatSeconds(s.duration)} · key ${i + 1} · double-click adds` },
488
+ s.stress ? `${s.title} · stress` : s.title,
489
+ );
490
+ chip.addEventListener('click', (e) => {
491
+ e.stopPropagation();
492
+ this.choose(tile, s);
493
+ tile.el.focus({ preventScroll: true });
494
+ });
495
+ chip.addEventListener('dblclick', (e) => {
496
+ e.stopPropagation();
497
+ this.pick(tile, s);
498
+ });
499
+ tile.chips.push(chip);
500
+ chipRow.appendChild(chip);
501
+ });
502
+ addBtn.addEventListener('click', (e) => {
503
+ e.stopPropagation();
504
+ this.pick(tile, tile.sample);
505
+ });
506
+ addBtn.addEventListener('dblclick', (e) => e.stopPropagation());
507
+ el.addEventListener('dblclick', () => this.pick(tile, tile.sample));
508
+ el.addEventListener('mouseenter', () => this.highlight(tile));
509
+ el.addEventListener('mouseleave', () => {
510
+ const focused = this.focusedTile();
511
+ if (focused && focused !== tile) this.highlight(focused);
512
+ });
513
+ el.addEventListener('focus', () => this.highlight(tile));
514
+ el.addEventListener('keydown', (e) => this.onTileKey(e, tile));
515
+ this.resizeTile(tile);
516
+ this.labelTile(tile);
517
+ this.observer.observe(el);
518
+ return tile;
519
+ }
520
+
521
+ private labelTile(tile: PickTile): void {
522
+ tile.el.setAttribute('aria-label', tileLabel(tile.type, tile.sample, tile.samples.length));
523
+ tile.addBtn.setAttribute('aria-label', `Add ${tile.type.title}, ${tile.sample.title}`);
524
+ tile.chips.forEach((c, i) => c.setAttribute('aria-pressed', String(tile.samples[i] === tile.sample)));
525
+ }
526
+
527
+ /** Sizes the tile's preview for the current format (its players are remade on the next mount). */
528
+ private resizeTile(tile: PickTile): void {
529
+ this.unmount(tile);
530
+ const [b] = tileBoxes(this.state.format, 's');
531
+ if (!b) return;
532
+ tile.box.style.width = `${b.width}px`;
533
+ tile.box.style.height = `${b.height}px`;
534
+ tile.holder.style.transform = `scale(${b.scale})`;
535
+ tile.el.style.width = `${Math.max(MIN_TILE_W, b.width + 14)}px`;
536
+ if (this.visible.has(tile)) this.pending.add(tile);
537
+ }
538
+
539
+ private mount(tile: PickTile): void {
540
+ if (tile.player) return;
541
+ for (const err of Array.from(tile.box.querySelectorAll('.g-error'))) err.remove();
542
+ try {
543
+ tile.player = createPlayer({
544
+ container: tile.holder,
545
+ project: this.project,
546
+ doc: singleSceneDoc(sceneEntry(tile.type.id, tile.sample), [this.state.format]),
547
+ format: this.state.format,
548
+ assetBase: this.assetBase,
549
+ });
550
+ tile.duration = tile.player.timeline.duration;
551
+ tile.el.classList.add('live');
552
+ } catch (err) {
553
+ tile.box.appendChild(h('div', { class: 'g-error' }, errorText(err)));
554
+ }
555
+ tile.startedAt = performance.now();
556
+ }
557
+
558
+ private unmount(tile: PickTile): void {
559
+ this.pending.delete(tile);
560
+ tile.player?.destroy();
561
+ tile.player = null;
562
+ tile.el.classList.remove('live');
563
+ }
564
+
565
+ private mountPending(): void {
566
+ if (!this.pending.size) return;
567
+ const start = performance.now();
568
+ for (const tile of this.pending) {
569
+ this.pending.delete(tile);
570
+ this.mount(tile);
571
+ if (performance.now() - start >= MOUNT_BUDGET_MS) break;
572
+ }
573
+ const live = [...this.tiles.values()]
574
+ .filter((t) => t.player)
575
+ .map((t) => ({ key: t.type.id, players: 1, visible: this.visible.has(t), lastSeen: t.lastSeen }));
576
+ for (const key of tilesToUnmount(live)) {
577
+ const tile = this.tiles.get(key);
578
+ if (tile) this.unmount(tile);
579
+ }
580
+ }
581
+
582
+ private onIntersect(entries: IntersectionObserverEntry[]): void {
583
+ const now = performance.now();
584
+ for (const e of entries) {
585
+ const tile = this.tiles.get((e.target as HTMLElement).dataset.type ?? '');
586
+ if (!tile || tile.el !== e.target) continue;
587
+ if (e.isIntersecting) {
588
+ if (!tile.player) this.pending.add(tile);
589
+ tile.startedAt = now;
590
+ this.visible.add(tile);
591
+ } else {
592
+ if (this.visible.delete(tile)) tile.lastSeen = now;
593
+ this.pending.delete(tile);
594
+ }
595
+ }
596
+ this.kick();
597
+ }
598
+
599
+ private kick(): void {
600
+ if (!this.raf && !this.suspended) this.raf = requestAnimationFrame((t) => this.frame(t));
601
+ }
602
+
603
+ private frame(now: number): void {
604
+ this.raf = 0;
605
+ if (this.suspended) return;
606
+ this.mountPending();
607
+ if (now - this.lastFrame >= 1000 / TILE_FPS - 2) {
608
+ this.lastFrame = now;
609
+ for (const tile of this.visible) {
610
+ if (!tile.player) continue;
611
+ const t = loopTime((now - tile.startedAt) / 1000, tile.duration);
612
+ tile.player.seek(t);
613
+ tile.bar.style.transform = `scaleX(${tile.duration > 0 ? t / tile.duration : 0})`;
614
+ }
615
+ this.side.frame(now);
616
+ }
617
+ // Keeps running while something is in view or the side preview shows a scene.
618
+ if (this.visible.size || this.pending.size || this.side.current) this.raf = requestAnimationFrame((t) => this.frame(t));
619
+ }
620
+
621
+ // --- highlight, choose, pick -----------------------------------------------------------
622
+
623
+ private focusedTile(): PickTile | null {
624
+ const el = document.activeElement as HTMLElement | null;
625
+ const id = el?.classList.contains('p-tile') ? el.dataset.type : undefined;
626
+ return id ? (this.tiles.get(id) ?? null) : null;
627
+ }
628
+
629
+ private highlight(tile: PickTile): void {
630
+ const cur = this.side.current;
631
+ if (cur?.tile === tile && cur.sample === tile.sample) return;
632
+ cur?.tile.el.classList.remove('active');
633
+ tile.el.classList.add('active');
634
+ this.side.show(tile, tile.sample, this.state.format);
635
+ this.kick();
636
+ }
637
+
638
+ /** Chooses the sample a tile shows and adds. */
639
+ private choose(tile: PickTile, sample: ResolvedSample): void {
640
+ if (tile.sample !== sample) {
641
+ tile.sample = sample;
642
+ this.labelTile(tile);
643
+ this.unmount(tile);
644
+ if (this.visible.has(tile)) this.pending.add(tile);
645
+ }
646
+ this.highlight(tile);
647
+ }
648
+
649
+ /** Sends the pick to the studio (it inserts the scene and closes the overlay). */
650
+ private pick(tile: PickTile, sample: ResolvedSample): void {
651
+ this.side.stop();
652
+ if (!this.embedded) {
653
+ this.side.flash('Open this from the studio (+ Add scene) to add scenes');
654
+ return;
655
+ }
656
+ window.parent.postMessage(pickMessage(tile.type.id, sample), location.origin);
657
+ this.side.flash(`Adding ${tile.type.title}…`);
658
+ }
659
+
660
+ // --- keys and messages -----------------------------------------------------------------
661
+
662
+ private onTileKey(e: KeyboardEvent, tile: PickTile): void {
663
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
664
+ if (e.key === 'Enter') {
665
+ e.preventDefault();
666
+ this.pick(tile, tile.sample);
667
+ return;
668
+ }
669
+ if (e.key === ' ') {
670
+ e.preventDefault();
671
+ this.highlight(tile);
672
+ void this.side.togglePlay();
673
+ return;
674
+ }
675
+ const s = sampleIndexForKey(e.key, tile.samples.length);
676
+ if (s >= 0) {
677
+ e.preventDefault();
678
+ this.choose(tile, tile.samples[s] as ResolvedSample);
679
+ return;
680
+ }
681
+ if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'].includes(e.key)) {
682
+ e.preventDefault();
683
+ const rects = this.shown.map((t) => t.el.getBoundingClientRect());
684
+ const next = this.shown[nextTileIndex(rects, this.shown.indexOf(tile), e.key)];
685
+ next?.el.focus();
686
+ next?.el.scrollIntoView({ block: 'nearest' });
687
+ }
688
+ }
689
+
690
+ private onKey(e: KeyboardEvent): void {
691
+ if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return;
692
+ if (e.key === 'Escape') {
693
+ e.preventDefault();
694
+ this.side.stop();
695
+ if (this.embedded) window.parent.postMessage(PICK_CLOSE, location.origin);
696
+ return;
697
+ }
698
+ if (e.key === '/' && document.activeElement !== this.search) {
699
+ e.preventDefault();
700
+ this.search.focus();
701
+ this.search.select();
702
+ }
703
+ }
704
+
705
+ private onMessage(e: MessageEvent): void {
706
+ if (!this.embedded) return;
707
+ const msg = readStudioMessage(e, window.parent, location.origin);
708
+ if (!msg) return;
709
+ if (msg.type === 'pause') {
710
+ this.suspend();
711
+ return;
712
+ }
713
+ this.suspended = false;
714
+ const now = performance.now();
715
+ for (const tile of this.visible) tile.startedAt = now;
716
+ this.side.restart();
717
+ this.setFormat(msg.format);
718
+ this.kick();
719
+ this.search.focus({ preventScroll: true });
720
+ this.search.select();
721
+ }
722
+
723
+ /** The overlay closed: stop the sound and every preview (the tiles stay mounted for the next open). */
724
+ private suspend(): void {
725
+ this.suspended = true;
726
+ this.side.stop();
727
+ if (this.raf) cancelAnimationFrame(this.raf);
728
+ this.raf = 0;
729
+ }
730
+
731
+ private saveScroll(): void {
732
+ try {
733
+ storage()?.setItem(SCROLL_KEY, String(Math.round(window.scrollY)));
734
+ } catch {
735
+ // not kept
736
+ }
737
+ }
738
+
739
+ private restoreScroll(): void {
740
+ const y = Number(storage()?.getItem(SCROLL_KEY) ?? 0);
741
+ if (Number.isFinite(y) && y > 0) window.scrollTo(0, y);
742
+ }
743
+ }
744
+
745
+ /** Builds the picker into the player page. */
746
+ export function startPicker(project: ProjectConfig, assetBase: string): void {
747
+ // The project's rules: only allowed scene types, samples in an allowed variant.
748
+ new Picker(allowedProject(project), assetBase).start();
749
+ }