gabriel / musehub public
piano-roll-page.ts typescript
71 lines 2.4 KB
c0f0b481 release: merge dev → main (#5) Gabriel Cardona <cgcardona@gmail.com> 5d ago
1 /**
2 * piano-roll-page.ts — Piano roll viewer page module.
3 *
4 * Wires transport controls (play / stop) to the PianoRoll global loaded by
5 * piano-roll.ts. Falls back to a legacy loader if PianoRoll.init is absent.
6 *
7 * Data expected in #page-data:
8 * { "page": "piano-roll", "repo_id": "...", "ref": "...", "path": "..." }
9 *
10 * Registered as: window.MusePages['piano-roll']
11 */
12
13 import { initRepoPage, type RepoPageData } from './repo-page.ts';
14
15 export interface PianoRollPageData extends RepoPageData {
16 ref?: string;
17 path?: string;
18 midi_url?: string;
19 }
20
21 function attachTransportControls(): void {
22 const playBtn = document.getElementById('play-btn');
23 const stopBtn = document.getElementById('stop-btn');
24
25 if (playBtn) {
26 playBtn.addEventListener('click', () => {
27 const pr = (window as unknown as { PianoRoll?: { play?: () => void } }).PianoRoll;
28 if (pr?.play) pr.play();
29 });
30 }
31 if (stopBtn) {
32 stopBtn.addEventListener('click', () => {
33 const pr = (window as unknown as { PianoRoll?: { stop?: () => void } }).PianoRoll;
34 if (pr?.stop) pr.stop();
35 });
36 }
37 }
38
39 async function legacyLoad(repoId: string): Promise<void> {
40 const canvas = document.getElementById('piano-canvas') as HTMLCanvasElement | null;
41 if (!canvas) return;
42
43 const pr = (window as unknown as { PianoRoll?: { init?: unknown } }).PianoRoll;
44 if (pr?.init) return; // New-style self-init handles it
45
46 const midiUrl = canvas.dataset.midiUrl;
47 const rollPath = canvas.dataset.path ?? null;
48 const apiFetch = window.apiFetch;
49 if (!apiFetch) return;
50
51 try {
52 const outer = document.getElementById('piano-roll-outer');
53 if (rollPath) {
54 const objData = await apiFetch('/repos/' + encodeURIComponent(repoId) + '/objects?limit=500') as { objects?: Array<{ path: string; objectId: string }> };
55 const obj = (objData.objects ?? []).find((o) => o.path === rollPath);
56 if (obj && typeof window.renderFromObjectId === 'function') {
57 window.renderFromObjectId(repoId, obj.objectId, outer);
58 }
59 } else if (midiUrl) {
60 if (typeof window.renderFromUrl === 'function') {
61 window.renderFromUrl(midiUrl, outer);
62 }
63 }
64 } catch (_) { /* silent */ }
65 }
66
67 export async function initPianoRollPage(data: PianoRollPageData): Promise<void> {
68 initRepoPage(data);
69 attachTransportControls();
70 if (data.repo_id) await legacyLoad(String(data.repo_id));
71 }