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,612 @@
1
+ /**
2
+ * The gallery page (/player/?mode=gallery): every scene type of the project with a live, looping
3
+ * preview per sample, a sound board and a music browser. State (tab, format, filters, the open
4
+ * sample) lives in the URL hash and the scroll position in sessionStorage, so a hot reload after a
5
+ * scene code change (Vite full reload in studio mode) comes back to the same place.
6
+ */
7
+ import { SCENE_CATEGORIES, createPlayer, h, type Player, type ProjectConfig, type ResolvedSample, type SceneType } from '@beatsheet/core';
8
+ import { GALLERY_CSS } from './gallery-css';
9
+ import { DetailView } from './gallery-detail';
10
+ import { buildMusicBrowser } from './gallery-music';
11
+ import { buildSoundBoard, type Panel } from './gallery-sounds';
12
+ import {
13
+ GALLERY_FORMATS,
14
+ categoryCounts,
15
+ filterScenes,
16
+ groupByCategory,
17
+ loopTime,
18
+ parseSampleKey,
19
+ parseState,
20
+ sampleKey,
21
+ sceneEntry,
22
+ serializeState,
23
+ singleSceneDoc,
24
+ tileBoxes,
25
+ toggleCategory,
26
+ formatSeconds,
27
+ isStudioPause,
28
+ sampleCountLabel,
29
+ tilesToUnmount,
30
+ type GalleryState,
31
+ type GalleryTab,
32
+ type PreviewBox,
33
+ type TileSize,
34
+ type TypeEntry,
35
+ } from './gallery-state';
36
+
37
+ const SCROLL_KEY = 'beatsheet-gallery-scroll';
38
+ /** Preview frames per second while looping (scenes are pure functions of t, so any rate is exact). */
39
+ const TILE_FPS = 30;
40
+ /** Time per frame spent mounting tiles (createPlayer), so tiles appear one after the other, not all after a long freeze. */
41
+ const MOUNT_BUDGET_MS = 12;
42
+
43
+ interface Tile {
44
+ key: string;
45
+ type: SceneType;
46
+ sample: ResolvedSample;
47
+ el: HTMLElement;
48
+ boxes: PreviewBox[];
49
+ holders: HTMLElement[];
50
+ bar: HTMLElement;
51
+ players: Player[] | null;
52
+ duration: number;
53
+ startedAt: number;
54
+ /** When it last left the view (for unmounting the longest unseen first). */
55
+ lastSeen: number;
56
+ }
57
+
58
+ function storage(): Storage | null {
59
+ try {
60
+ return window.sessionStorage;
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ function errorText(err: unknown): string {
67
+ return err instanceof Error ? err.message : String(err);
68
+ }
69
+
70
+ class Gallery {
71
+ private state: GalleryState = parseState(location.hash);
72
+ private readonly embedded = window.parent !== window;
73
+ private readonly types: SceneType[];
74
+ private readonly tiles = new Map<string, Tile>();
75
+ private tileConfig = '';
76
+ private readonly visible = new Set<Tile>();
77
+ /** Tiles in view waiting for their players, mounted a few per frame (in view order). */
78
+ private readonly pending = new Set<Tile>();
79
+ private readonly observer: IntersectionObserver;
80
+ private raf = 0;
81
+ private lastFrame = 0;
82
+ private detail: DetailView | null = null;
83
+ /** The samples in the order shown (for prev/next in the large view). */
84
+ private order: string[] = [];
85
+ private searchTimer: ReturnType<typeof setTimeout> | undefined;
86
+
87
+ private readonly head = h('header', { class: 'g-head' });
88
+ private readonly tabsEl = h('nav', { class: 'g-tabs', role: 'tablist', 'aria-label': 'Gallery sections' });
89
+ private readonly formatSeg = h('div', { class: 'g-seg', role: 'group', 'aria-label': 'Preview format' });
90
+ private readonly sizeSeg = h('div', { class: 'g-seg', role: 'group', 'aria-label': 'Tile size' });
91
+ private readonly chips = h('div', { class: 'g-chips', role: 'group', 'aria-label': 'Categories' });
92
+ private readonly search = h('input', { type: 'search', placeholder: 'Search types and samples ( / )', 'aria-label': 'Search' });
93
+ private readonly stress = h('input', { type: 'checkbox' });
94
+ private readonly summary = h('span', { class: 'g-summary', role: 'status' });
95
+ private readonly sceneTools = h('div', { class: 'g-row' });
96
+ private readonly panels: Record<GalleryTab, HTMLElement> = {
97
+ scenes: h('section', { class: 'g-panel', 'aria-label': 'Scene types' }),
98
+ sounds: h('section', { class: 'g-panel', 'aria-label': 'Sounds' }),
99
+ music: h('section', { class: 'g-panel', 'aria-label': 'Music' }),
100
+ };
101
+ private sounds: Panel | null = null;
102
+ private music: Panel | null = null;
103
+
104
+ constructor(
105
+ private readonly project: ProjectConfig,
106
+ private readonly assetBase: string,
107
+ ) {
108
+ this.types = project.scenes;
109
+ // root: document, so the margin applies to this page's own viewport also inside the studio's iframe
110
+ // (with the implicit root a same-origin iframe clips to its viewport first, and tiles mount only once on screen).
111
+ this.observer = new IntersectionObserver((entries) => this.onIntersect(entries), { root: document, rootMargin: '200px 0px' });
112
+ }
113
+
114
+ start(): void {
115
+ document.documentElement.classList.add('bs-gallery');
116
+ document.title = `${this.project.name} · beatsheet gallery`;
117
+ const style = document.createElement('style');
118
+ style.id = 'bs-gallery-css';
119
+ style.textContent = GALLERY_CSS;
120
+ document.head.appendChild(style);
121
+
122
+ this.buildHead();
123
+ const main = h('main', { class: 'g-main' }, this.panels.scenes, this.panels.sounds, this.panels.music);
124
+ document.body.append(this.head, main);
125
+ const measure = (): void => document.documentElement.style.setProperty('--g-head-h', `${this.head.offsetHeight}px`);
126
+ new ResizeObserver(measure).observe(this.head);
127
+
128
+ this.render();
129
+ this.restoreScroll();
130
+ this.openFromState();
131
+
132
+ window.addEventListener('pagehide', () => this.saveScroll());
133
+ // The studio hides this page (its editor comes back): nothing may keep playing behind the editor.
134
+ window.addEventListener('message', (e) => {
135
+ if (this.embedded && isStudioPause(e, window.parent, location.origin)) this.stopSound();
136
+ });
137
+ let scrollTimer: ReturnType<typeof setTimeout> | undefined;
138
+ window.addEventListener('scroll', () => {
139
+ clearTimeout(scrollTimer);
140
+ scrollTimer = setTimeout(() => this.saveScroll(), 150);
141
+ });
142
+ window.addEventListener('hashchange', () => {
143
+ this.state = parseState(location.hash);
144
+ this.render();
145
+ this.openFromState();
146
+ });
147
+ document.addEventListener('keydown', (e) => {
148
+ if (this.detail || e.metaKey || e.ctrlKey || e.altKey) return;
149
+ if (e.key === '/' && document.activeElement !== this.search && this.state.tab === 'scenes') {
150
+ e.preventDefault();
151
+ this.search.focus();
152
+ this.search.select();
153
+ }
154
+ });
155
+ }
156
+
157
+ // --- state ---------------------------------------------------------------------------
158
+
159
+ private update(patch: Partial<GalleryState>): void {
160
+ // A search still waiting for its debounce goes along, so renderHead doesn't put the old query back.
161
+ if (this.searchTimer !== undefined) {
162
+ clearTimeout(this.searchTimer);
163
+ this.searchTimer = undefined;
164
+ if (patch.query === undefined) patch = { ...patch, query: this.search.value.trim() };
165
+ }
166
+ const prev = this.state;
167
+ const tabChanged = patch.tab !== undefined && patch.tab !== prev.tab;
168
+ if (tabChanged) this.saveScroll();
169
+ this.state = { ...prev, ...patch };
170
+ const hash = serializeState(this.state);
171
+ history.replaceState(history.state, '', hash || `${location.pathname}${location.search}`);
172
+ const next = this.state;
173
+ const scenesChanged =
174
+ next.format !== prev.format ||
175
+ next.size !== prev.size ||
176
+ next.query !== prev.query ||
177
+ next.hideStress !== prev.hideStress ||
178
+ next.categories.join(',') !== prev.categories.join(',');
179
+ this.renderHead();
180
+ if (tabChanged) this.renderTab();
181
+ if (scenesChanged) this.renderScenes();
182
+ if (tabChanged) this.restoreScroll();
183
+ }
184
+
185
+ private scrollKey(): string {
186
+ return `${SCROLL_KEY}:${this.state.tab}`;
187
+ }
188
+
189
+ private saveScroll(): void {
190
+ try {
191
+ storage()?.setItem(this.scrollKey(), String(Math.round(window.scrollY)));
192
+ } catch {
193
+ // storage full or blocked: the scroll position just isn't kept
194
+ }
195
+ }
196
+
197
+ private restoreScroll(): void {
198
+ const y = Number(storage()?.getItem(this.scrollKey()) ?? 0);
199
+ window.scrollTo(0, Number.isFinite(y) ? y : 0);
200
+ }
201
+
202
+ // --- header ----------------------------------------------------------------------------
203
+
204
+ private segButton(label: string, title: string, onClick: () => void): HTMLButtonElement {
205
+ const b = h('button', { type: 'button', title }, label);
206
+ b.addEventListener('click', onClick);
207
+ return b;
208
+ }
209
+
210
+ private buildHead(): void {
211
+ const theme = this.project.theme;
212
+ const tabs: { id: GalleryTab; label: string; count: number }[] = [
213
+ { id: 'scenes', label: 'Scenes', count: this.types.length },
214
+ { id: 'sounds', label: 'Sounds', count: Object.keys(theme.sounds).length },
215
+ { id: 'music', label: 'Music', count: Object.keys(theme.music ?? {}).length },
216
+ ];
217
+ for (const t of tabs) {
218
+ const b = h('button', { type: 'button', role: 'tab', 'data-tab': t.id }, t.label, h('span', { class: 'g-count' }, String(t.count)));
219
+ b.addEventListener('click', () => this.update({ tab: t.id }));
220
+ this.tabsEl.appendChild(b);
221
+ }
222
+ for (const f of GALLERY_FORMATS) {
223
+ const b = this.segButton(f === 'pair' ? '16:9 + 4:5' : f, f === 'pair' ? '16:9 and 4:5 side by side' : `${f} previews`, () => this.update({ format: f }));
224
+ b.dataset.value = f;
225
+ this.formatSeg.appendChild(b);
226
+ }
227
+ for (const s of ['s', 'm', 'l'] as TileSize[]) {
228
+ const b = this.segButton(s.toUpperCase(), `Tile size ${s.toUpperCase()}`, () => this.update({ size: s }));
229
+ b.dataset.value = s;
230
+ this.sizeSeg.appendChild(b);
231
+ }
232
+ this.search.value = this.state.query;
233
+ this.search.addEventListener('input', () => {
234
+ clearTimeout(this.searchTimer);
235
+ this.searchTimer = setTimeout(() => {
236
+ this.searchTimer = undefined;
237
+ this.update({ query: this.search.value.trim() });
238
+ }, 120);
239
+ });
240
+ this.search.addEventListener('keydown', (e) => {
241
+ if (e.key === 'Escape' && this.search.value) {
242
+ this.search.value = '';
243
+ this.update({ query: '' });
244
+ }
245
+ });
246
+ this.stress.addEventListener('change', () => this.update({ hideStress: this.stress.checked }));
247
+
248
+ const counts = categoryCounts(this.types);
249
+ const all = this.segButton('All', 'Every category', () => this.update({ categories: [] }));
250
+ all.className = 'g-chip';
251
+ all.dataset.value = '';
252
+ this.chips.appendChild(all);
253
+ const cats = [...SCENE_CATEGORIES, { id: 'other', title: 'Other' }].filter((c) => counts.has(c.id));
254
+ for (const c of cats) {
255
+ const b = this.segButton(c.title, `Only ${c.title}`, () => this.update({ categories: toggleCategory(this.state.categories, c.id) }));
256
+ b.className = 'g-chip';
257
+ b.dataset.value = c.id;
258
+ b.appendChild(h('span', { class: 'g-count' }, String(counts.get(c.id))));
259
+ this.chips.appendChild(b);
260
+ }
261
+
262
+ this.head.append(
263
+ h(
264
+ 'div',
265
+ { class: 'g-row' },
266
+ // In the studio's iframe the studio's own top bar already says beatsheet.
267
+ this.embedded ? null : h('span', { class: 'g-brand' }, 'beatsheet'),
268
+ h('span', { class: 'g-sub' }, `${this.embedded ? 'Gallery' : 'gallery'} · ${this.project.name} · theme ${theme.title}`),
269
+ this.tabsEl,
270
+ h('span', { class: 'g-spacer' }),
271
+ ),
272
+ this.sceneTools,
273
+ );
274
+ this.sceneTools.append(
275
+ this.formatSeg,
276
+ this.sizeSeg,
277
+ this.chips,
278
+ this.search,
279
+ h('label', { class: 'g-check' }, this.stress, 'Hide stress samples'),
280
+ h('span', { class: 'g-spacer' }),
281
+ this.summary,
282
+ );
283
+ }
284
+
285
+ private renderHead(): void {
286
+ const s = this.state;
287
+ for (const b of Array.from(this.tabsEl.children) as HTMLElement[]) b.setAttribute('aria-selected', String(b.dataset.tab === s.tab));
288
+ for (const b of Array.from(this.formatSeg.children) as HTMLElement[]) b.setAttribute('aria-pressed', String(b.dataset.value === s.format));
289
+ for (const b of Array.from(this.sizeSeg.children) as HTMLElement[]) b.setAttribute('aria-pressed', String(b.dataset.value === s.size));
290
+ for (const b of Array.from(this.chips.children) as HTMLElement[]) {
291
+ const v = b.dataset.value ?? '';
292
+ b.setAttribute('aria-pressed', String(v === '' ? s.categories.length === 0 : s.categories.includes(v)));
293
+ }
294
+ if (document.activeElement !== this.search) this.search.value = s.query;
295
+ this.stress.checked = s.hideStress;
296
+ this.sceneTools.hidden = s.tab !== 'scenes';
297
+ }
298
+
299
+ /** Stops every sound of the page: the large view's playback, the music browser and the sound board. */
300
+ private stopSound(): void {
301
+ this.detail?.pause();
302
+ this.music?.deactivate();
303
+ this.sounds?.deactivate();
304
+ }
305
+
306
+ // --- render ----------------------------------------------------------------------------
307
+
308
+ private render(): void {
309
+ this.renderHead();
310
+ this.renderTab();
311
+ this.renderScenes();
312
+ }
313
+
314
+ private renderTab(): void {
315
+ for (const [id, el] of Object.entries(this.panels) as [GalleryTab, HTMLElement][]) el.hidden = id !== this.state.tab;
316
+ if (this.state.tab === 'sounds') {
317
+ if (!this.sounds) {
318
+ this.sounds = buildSoundBoard(this.project);
319
+ this.panels.sounds.appendChild(this.sounds.el);
320
+ }
321
+ this.sounds.activate();
322
+ }
323
+ if (this.state.tab === 'music') {
324
+ if (!this.music) {
325
+ this.music = buildMusicBrowser(this.project, this.assetBase);
326
+ this.panels.music.appendChild(this.music.el);
327
+ }
328
+ this.music.activate();
329
+ } else {
330
+ this.music?.deactivate();
331
+ }
332
+ if (this.state.tab === 'scenes') {
333
+ const now = performance.now();
334
+ for (const tile of this.visible) tile.startedAt = now;
335
+ this.kick();
336
+ }
337
+ }
338
+
339
+ private renderScenes(): void {
340
+ const s = this.state;
341
+ const config = `${s.format}|${s.size}`;
342
+ if (config !== this.tileConfig) {
343
+ for (const tile of this.tiles.values()) this.destroyTile(tile);
344
+ this.tiles.clear();
345
+ this.tileConfig = config;
346
+ }
347
+ const entries = filterScenes(this.types, s);
348
+ const groups = groupByCategory(entries, (e) => e.type.category, SCENE_CATEGORIES);
349
+ const used = new Set<string>();
350
+ this.order = [];
351
+ const panel = this.panels.scenes;
352
+ const content = document.createDocumentFragment();
353
+ for (const g of groups) {
354
+ content.appendChild(h('h2', { class: 'g-cat' }, g.title, h('span', { class: 'g-count' }, `${g.items.length} ${g.items.length === 1 ? 'type' : 'types'}`)));
355
+ for (const entry of g.items) content.appendChild(this.typeBlock(entry, used));
356
+ }
357
+ if (!groups.length) content.appendChild(h('p', { class: 'g-empty' }, this.types.length ? 'No scene type or sample matches.' : 'This project has no scene types.'));
358
+ // Tiles no longer shown are destroyed (their players hold DOM and listeners).
359
+ for (const [key, tile] of this.tiles) {
360
+ if (!used.has(key)) {
361
+ this.destroyTile(tile);
362
+ this.tiles.delete(key);
363
+ }
364
+ }
365
+ panel.replaceChildren(content);
366
+ const sampleCount = entries.reduce((n, e) => n + e.samples.length, 0);
367
+ this.summary.textContent = `${entries.length} ${entries.length === 1 ? 'type' : 'types'} · ${sampleCount} ${sampleCount === 1 ? 'sample' : 'samples'}`;
368
+ }
369
+
370
+ private typeBlock(entry: TypeEntry, used: Set<string>): HTMLElement {
371
+ const { type } = entry;
372
+ const tiles = h('div', { class: 'g-tiles' });
373
+ for (const sample of entry.samples) {
374
+ const tile = this.tile(type, sample);
375
+ used.add(tile.key);
376
+ this.order.push(tile.key);
377
+ tiles.appendChild(tile.el);
378
+ }
379
+ const total = this.findSamples(type).length;
380
+ return h(
381
+ 'article',
382
+ { class: 'g-type', 'data-type': type.id },
383
+ h(
384
+ 'div',
385
+ { class: 'g-type-head' },
386
+ h('h3', null, type.title),
387
+ h('code', null, type.id),
388
+ h('span', { class: 'g-dur' }, `${sampleCountLabel(entry.samples.length, total)} · default ${formatSeconds(type.defaultDuration)}`),
389
+ type.description ? h('p', null, type.description) : null,
390
+ ),
391
+ tiles,
392
+ );
393
+ }
394
+
395
+ // --- tiles -----------------------------------------------------------------------------
396
+
397
+ private tile(type: SceneType, sample: ResolvedSample): Tile {
398
+ const key = sampleKey(type.id, sample.id);
399
+ const cached = this.tiles.get(key);
400
+ // Same type object and sample: reuse (filter changes keep running previews).
401
+ if (cached && cached.type === type && cached.sample.props === sample.props && cached.sample.duration === sample.duration) return cached;
402
+ if (cached) this.destroyTile(cached);
403
+ const boxes = tileBoxes(this.state.format, this.state.size);
404
+ const holders: HTMLElement[] = [];
405
+ const previews = h('div', { class: 'g-previews' });
406
+ for (const b of boxes) {
407
+ const holder = h('div', { class: 'g-holder' });
408
+ holder.style.transform = `scale(${b.scale})`;
409
+ holders.push(holder);
410
+ // The sample's title stands in until the players are mounted (a few per frame, see mountPending).
411
+ const box = h(
412
+ 'div',
413
+ { class: 'g-preview' },
414
+ h('span', { class: 'g-ph', 'aria-hidden': 'true' }, sample.title),
415
+ holder,
416
+ boxes.length > 1 ? h('span', { class: 'g-preview-label' }, b.format) : null,
417
+ );
418
+ box.style.width = `${b.width}px`;
419
+ box.style.height = `${b.height}px`;
420
+ previews.appendChild(box);
421
+ }
422
+ const bar = h('i');
423
+ const el = h(
424
+ 'div',
425
+ { class: 'g-tile', role: 'button', tabindex: 0, 'data-key': key, title: `${type.title} · ${sample.title} — click for the large view` },
426
+ previews,
427
+ h('div', { class: 'g-progress' }, bar),
428
+ h(
429
+ 'div',
430
+ { class: 'g-tile-meta' },
431
+ h('span', { class: 'g-tile-title' }, sample.title),
432
+ sample.stress ? h('span', { class: 'g-badge stress' }, 'stress') : null,
433
+ h('span', { class: 'g-dur' }, formatSeconds(sample.duration)),
434
+ ),
435
+ );
436
+ el.style.width = `${boxes.reduce((w, b) => w + b.width, 0) + 6 * (boxes.length - 1) + 14}px`;
437
+ el.addEventListener('click', () => {
438
+ this.update({ open: key });
439
+ this.openFromState();
440
+ });
441
+ el.addEventListener('keydown', (e) => {
442
+ if (e.key === 'Enter' || e.key === ' ') {
443
+ e.preventDefault();
444
+ this.update({ open: key });
445
+ this.openFromState();
446
+ }
447
+ });
448
+ const tile: Tile = { key, type, sample, el, boxes, holders, bar, players: null, duration: sample.duration, startedAt: 0, lastSeen: 0 };
449
+ this.tiles.set(key, tile);
450
+ this.observer.observe(el);
451
+ return tile;
452
+ }
453
+
454
+ private mountTile(tile: Tile): void {
455
+ if (tile.players) return;
456
+ tile.players = [];
457
+ tile.el.classList.add('live');
458
+ for (const err of Array.from(tile.el.querySelectorAll('.g-error'))) err.remove();
459
+ const entry = sceneEntry(tile.type.id, tile.sample);
460
+ tile.boxes.forEach((b, i) => {
461
+ const holder = tile.holders[i] as HTMLElement;
462
+ try {
463
+ const player = createPlayer({ container: holder, project: this.project, doc: singleSceneDoc(entry, [b.format]), format: b.format, assetBase: this.assetBase });
464
+ tile.players?.push(player);
465
+ tile.duration = player.timeline.duration;
466
+ } catch (err) {
467
+ holder.parentElement?.appendChild(h('div', { class: 'g-error' }, errorText(err)));
468
+ }
469
+ });
470
+ }
471
+
472
+ private destroyTile(tile: Tile): void {
473
+ this.observer.unobserve(tile.el);
474
+ this.visible.delete(tile);
475
+ this.unmountTile(tile);
476
+ }
477
+
478
+ /** Destroys the tile's players (it stays observed and mounts again when it comes back into view). */
479
+ private unmountTile(tile: Tile): void {
480
+ this.pending.delete(tile);
481
+ for (const p of tile.players ?? []) p.destroy();
482
+ tile.players = null;
483
+ tile.el.classList.remove('live');
484
+ }
485
+
486
+ /** Mounts waiting tiles within the frame budget (at least one), then unmounts the longest unseen over the cap. */
487
+ private mountPending(): void {
488
+ if (!this.pending.size) return;
489
+ const start = performance.now();
490
+ for (const tile of this.pending) {
491
+ this.pending.delete(tile);
492
+ this.mountTile(tile);
493
+ // Its loop starts when it shows.
494
+ tile.startedAt = performance.now();
495
+ if (performance.now() - start >= MOUNT_BUDGET_MS) break;
496
+ }
497
+ const live = [...this.tiles.values()]
498
+ .filter((t) => t.players)
499
+ .map((t) => ({ key: t.key, players: t.players?.length ?? 0, visible: this.visible.has(t), lastSeen: t.lastSeen }));
500
+ for (const key of tilesToUnmount(live)) {
501
+ const tile = this.tiles.get(key);
502
+ if (tile) this.unmountTile(tile);
503
+ }
504
+ }
505
+
506
+ private onIntersect(entries: IntersectionObserverEntry[]): void {
507
+ const now = performance.now();
508
+ for (const e of entries) {
509
+ const key = (e.target as HTMLElement).dataset.key ?? '';
510
+ const tile = this.tiles.get(key);
511
+ if (!tile || tile.el !== e.target) continue;
512
+ if (e.isIntersecting) {
513
+ if (!tile.players) this.pending.add(tile);
514
+ tile.startedAt = now;
515
+ this.visible.add(tile);
516
+ } else {
517
+ if (this.visible.delete(tile)) tile.lastSeen = now;
518
+ this.pending.delete(tile);
519
+ }
520
+ }
521
+ this.kick();
522
+ }
523
+
524
+ private kick(): void {
525
+ if (!this.raf && this.visible.size && !this.detail) this.raf = requestAnimationFrame((t) => this.frame(t));
526
+ }
527
+
528
+ private frame(now: number): void {
529
+ this.raf = 0;
530
+ if (!this.visible.size || this.detail || this.state.tab !== 'scenes') return;
531
+ this.mountPending();
532
+ if (now - this.lastFrame >= 1000 / TILE_FPS - 2) {
533
+ this.lastFrame = now;
534
+ for (const tile of this.visible) {
535
+ if (!tile.players) continue;
536
+ const t = loopTime((now - tile.startedAt) / 1000, tile.duration);
537
+ for (const p of tile.players) p.seek(t);
538
+ tile.bar.style.transform = `scaleX(${tile.duration > 0 ? t / tile.duration : 0})`;
539
+ }
540
+ }
541
+ this.raf = requestAnimationFrame((t) => this.frame(t));
542
+ }
543
+
544
+ // --- large view --------------------------------------------------------------------------
545
+
546
+ private openFromState(): void {
547
+ const want = this.state.open;
548
+ if (this.detail && this.detailKey === want) return;
549
+ this.closeDetail(false);
550
+ const parts = parseSampleKey(want);
551
+ if (!parts) return;
552
+ const type = this.types.find((t) => t.id === parts.typeId);
553
+ const sample = this.tiles.get(sampleKey(parts.typeId, parts.sampleId))?.sample ?? (type ? this.findSample(type, parts.sampleId) : undefined);
554
+ if (!type || !sample) {
555
+ this.update({ open: null });
556
+ return;
557
+ }
558
+ const index = this.order.indexOf(want as string);
559
+ this.detailKey = want;
560
+ this.detail = new DetailView({
561
+ project: this.project,
562
+ assetBase: this.assetBase,
563
+ type,
564
+ sample,
565
+ formats: this.state.format === 'pair' ? ['16:9', '4:5'] : [this.state.format],
566
+ embedded: this.embedded,
567
+ position: index >= 0 ? `${index + 1} / ${this.order.length}` : '',
568
+ onClose: () => {
569
+ this.update({ open: null });
570
+ this.closeDetail(true);
571
+ },
572
+ onStep: (delta) => {
573
+ if (!this.order.length) return;
574
+ const i = this.order.indexOf(want as string);
575
+ const next = this.order[(i + delta + this.order.length) % this.order.length] as string;
576
+ this.update({ open: next });
577
+ this.openFromState();
578
+ },
579
+ });
580
+ document.body.appendChild(this.detail.root);
581
+ this.detail.attached();
582
+ }
583
+
584
+ private detailKey: string | null = null;
585
+
586
+ private findSample(type: SceneType, sampleId: string): ResolvedSample | undefined {
587
+ return this.findSamples(type).find((s) => s.id === sampleId);
588
+ }
589
+
590
+ /** Every sample of a type, unfiltered. */
591
+ private findSamples(type: SceneType): ResolvedSample[] {
592
+ return filterScenes([type], { categories: [], query: '', hideStress: false })[0]?.samples ?? [];
593
+ }
594
+
595
+ private closeDetail(focusTile: boolean): void {
596
+ if (!this.detail) return;
597
+ const key = this.detailKey;
598
+ this.detail.destroy();
599
+ this.detail = null;
600
+ this.detailKey = null;
601
+ // Restart the tiles in view.
602
+ const now = performance.now();
603
+ for (const tile of this.visible) tile.startedAt = now;
604
+ this.kick();
605
+ if (focusTile && key) this.tiles.get(key)?.el.focus({ preventScroll: true });
606
+ }
607
+ }
608
+
609
+ /** Builds the gallery into the player page. */
610
+ export function startGallery(project: ProjectConfig, assetBase: string): void {
611
+ new Gallery(project, assetBase).start();
612
+ }
@@ -0,0 +1,49 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <title>beatsheet player</title>
6
+ <style>
7
+ html, body { margin: 0; padding: 0; overflow: hidden; background: transparent; }
8
+ #beatsheet-player { position: absolute; left: 0; top: 0; }
9
+ </style>
10
+ <script>
11
+ // The gallery is dark (gallery-css.ts) and shown in the studio's dark iframe. Say so before the
12
+ // first paint: until the gallery module has loaded, a light document there gets an opaque white
13
+ // backdrop (a flash on every hot reload); a dark one stays transparent over the iframe's background.
14
+ if (new URLSearchParams(location.search).get('mode') === 'gallery') document.documentElement.style.colorScheme = 'dark';
15
+ </script>
16
+ </head>
17
+ <body>
18
+ <div id="beatsheet-player"></div>
19
+ <script>
20
+ // Until main.ts runs (it sets __beatsheetBooted first), an error is the player module or one
21
+ // of its imports (a scene file) failing to load: report it like main.ts's fail() does, so the
22
+ // renderer and the studio stop waiting instead of running into their timeout. Pages without
23
+ // the Vite client (render mode) report at once. With it (HMR), Vite answers dependencies it
24
+ // re-optimized on a first visit with a failed module load and then reloads the page, however
25
+ // long the optimizing took (the renderer retries that): those report after HMR_GRACE_MS and
26
+ // only if main.ts still has not run; a reload ends the timer.
27
+ const HMR_GRACE_MS = 10000;
28
+ let loadError = null;
29
+ addEventListener(
30
+ 'error',
31
+ (e) => {
32
+ if (window.__beatsheetBooted || window.__beatsheetError || loadError !== null) return;
33
+ const src = e.target && e.target !== window ? e.target.src || e.target.href : '';
34
+ loadError = e.error instanceof Error ? e.error.message : e.message || ('failed to load ' + (src || 'the player module'));
35
+ const grace = document.querySelector('script[src$="/@vite/client"]') ? HMR_GRACE_MS : 0;
36
+ setTimeout(() => {
37
+ if (window.__beatsheetBooted || window.__beatsheetError) return;
38
+ window.__beatsheetError = loadError;
39
+ if (new URLSearchParams(location.search).get('mode') === 'studio' && window.parent !== window) {
40
+ window.parent.postMessage({ source: 'beatsheet-player', type: 'error', message: loadError }, '*');
41
+ }
42
+ }, grace);
43
+ },
44
+ true,
45
+ );
46
+ </script>
47
+ <script type="module" src="./main.ts"></script>
48
+ </body>
49
+ </html>