1import { useSyncExternalStore } from 'react';
2import type { Song, SongMeta, SongRecord, Track } from '../types.ts';
3import { defaultSong, newId } from '../types.ts';
4import * as db from '../storage/db.ts';
5import { parseMidi } from '../midi/parse.ts';
6import { TempoMap } from '../midi/time.ts';
7import { quantizeNotes } from '../midi/ops.ts';
8import { player } from '../audio/player.ts';
9import { Recorder, type CapturedNote } from '../input/recorder.ts';
11// Application state and every action that edits it. Song edits go through
12// beginEdit/editSong/endEdit so a whole drag gesture is one undo step;
13// mutateSong wraps the three for one-shot edits. Songs autosave to
14// IndexedDB shortly after each committed edit.
16export interface AppState {
17 ready: boolean;
18 rec: SongRecord | null;
19 songs: SongMeta[];
20 activeTrackId: string | null;
21 armedTrackId: string | null;
22 selection: string[];
23 snapBeats: number; // snap grid in quarter notes; 0 = off
24 libraryOpen: boolean;
25 status: string;
26}
28const LAST_SONG_KEY = 'midiboot:lastSong';
29const UNDO_CAP = 200;
31class Store {
32 state: AppState = {
33 ready: false,
34 rec: null,
35 songs: [],
36 activeTrackId: null,
37 armedTrackId: null,
38 selection: [],
39 snapBeats: 0.25,
40 libraryOpen: false,
41 status: '',
42 };
43 recorder = new Recorder();
45 private listeners = new Set<() => void>();
46 private undoStack: Song[] = [];
47 private redoStack: Song[] = [];
48 private pendingUndo: Song | null = null;
49 private saveTimer: ReturnType<typeof setTimeout> | null = null;
51 subscribe = (cb: () => void): (() => void) => {
52 this.listeners.add(cb);
53 return () => this.listeners.delete(cb);
54 };
56 getSnapshot = (): AppState => this.state;
58 private set(patch: Partial<AppState>) {
59 this.state = { ...this.state, ...patch };
60 for (const cb of this.listeners) cb();
61 }
63 song(): Song | null { return this.state.rec?.song ?? null; }
65 setStatus(msg: string): void { this.set({ status: msg }); }
67 tempoMap(): TempoMap | null {
68 const song = this.song();
69 return song ? new TempoMap(song.ppq, song.tempo, song.timeSig) : null;
70 }
72 snapTicks(): number {
73 const song = this.song();
74 if (!song || this.state.snapBeats <= 0) return 0;
75 return Math.round(song.ppq * this.state.snapBeats);
76 }
78 async init(): Promise<void> {
79 const songs = await db.listSongs();
80 let rec: SongRecord | null = null;
81 try {
82 const last = localStorage.getItem(LAST_SONG_KEY);
83 if (last) rec = await db.getSong(last);
84 } catch { /* localStorage unavailable */ }
85 if (!rec && songs.length > 0) rec = await db.getSong(songs[0].id);
86 if (!rec) {
87 rec = this.freshRecord('Untitled song');
88 await db.putSong(rec);
89 }
90 this.set({ ready: true, songs, rec, activeTrackId: rec.song.tracks[0]?.id ?? null });
91 this.rememberLast(rec.id);
92 }
94 private freshRecord(name: string, song?: Song): SongRecord {
95 const now = Date.now();
96 return { id: newId('s'), name, createdAt: now, updatedAt: now, song: song ?? defaultSong() };
97 }
99 private rememberLast(id: string) {
100 try { localStorage.setItem(LAST_SONG_KEY, id); } catch { /* ignore */ }
101 }
103 private scheduleSave() {
104 if (this.saveTimer !== null) clearTimeout(this.saveTimer);
105 this.saveTimer = setTimeout(() => {
106 this.saveTimer = null;
107 void this.saveNow();
108 }, 400);
109 }
111 private async saveNow() {
112 const rec = this.state.rec;
113 if (!rec) return;
114 await db.putSong(rec);
115 this.set({ songs: await db.listSongs() });
116 }
118 // --- edit protocol ---
120 beginEdit(): void {
121 if (!this.state.rec || this.pendingUndo) return;
122 this.pendingUndo = structuredClone(this.state.rec.song);
123 }
125 editSong(fn: (song: Song) => void): void {
126 const rec = this.state.rec;
127 if (!rec) return;
128 const song = structuredClone(rec.song);
129 fn(song);
130 this.set({ rec: { ...rec, song, updatedAt: Date.now() } });
131 }
133 endEdit(): void {
134 if (this.pendingUndo) {
135 this.undoStack.push(this.pendingUndo);
136 if (this.undoStack.length > UNDO_CAP) this.undoStack.shift();
137 this.redoStack = [];
138 this.pendingUndo = null;
139 }
140 this.scheduleSave();
141 }
143 mutateSong(fn: (song: Song) => void): void {
144 this.beginEdit();
145 this.editSong(fn);
146 this.endEdit();
147 }
149 undo(): void {
150 const rec = this.state.rec;
151 const prev = this.undoStack.pop();
152 if (!rec || !prev) return;
153 this.redoStack.push(structuredClone(rec.song));
154 this.set({ rec: { ...rec, song: prev, updatedAt: Date.now() }, selection: [] });
155 this.scheduleSave();
156 }
158 redo(): void {
159 const rec = this.state.rec;
160 const next = this.redoStack.pop();
161 if (!rec || !next) return;
162 this.undoStack.push(structuredClone(rec.song));
163 this.set({ rec: { ...rec, song: next, updatedAt: Date.now() }, selection: [] });
164 this.scheduleSave();
165 }
167 private resetHistory() {
168 this.undoStack = [];
169 this.redoStack = [];
170 this.pendingUndo = null;
171 }
173 // --- library ---
175 setLibraryOpen(v: boolean): void { this.set({ libraryOpen: v }); }
177 async newSong(): Promise<void> {
178 player.stop();
179 const rec = this.freshRecord('Untitled song');
180 await db.putSong(rec);
181 this.resetHistory();
182 this.set({ rec, songs: await db.listSongs(), activeTrackId: rec.song.tracks[0]?.id ?? null, armedTrackId: null, selection: [], libraryOpen: false });
183 player.seek(0);
184 this.rememberLast(rec.id);
185 }
187 async openSong(id: string): Promise<void> {
188 const rec = await db.getSong(id);
189 if (!rec) return;
190 player.stop();
191 this.resetHistory();
192 this.set({ rec, activeTrackId: rec.song.tracks[0]?.id ?? null, armedTrackId: null, selection: [], libraryOpen: false });
193 player.seek(0);
194 this.rememberLast(rec.id);
195 }
197 async deleteSongById(id: string): Promise<void> {
198 await db.deleteSong(id);
199 const songs = await db.listSongs();
200 this.set({ songs });
201 if (this.state.rec?.id === id) {
202 if (songs.length > 0) await this.openSong(songs[0].id);
203 else await this.newSong();
204 }
205 }
207 renameSong(name: string): void {
208 const rec = this.state.rec;
209 if (!rec) return;
210 this.set({ rec: { ...rec, name, updatedAt: Date.now() } });
211 this.scheduleSave();
212 }
214 async duplicateSong(id: string): Promise<void> {
215 const src = await db.getSong(id);
216 if (!src) return;
217 const rec = this.freshRecord(`${src.name} copy`, structuredClone(src.song));
218 await db.putSong(rec);
219 this.set({ songs: await db.listSongs() });
220 }
222 async importMidi(fileName: string, data: Uint8Array): Promise<void> {
223 let song: Song;
224 try {
225 song = parseMidi(data);
226 } catch (err) {
227 this.set({ status: `Import failed: ${err instanceof Error ? err.message : String(err)}` });
228 return;
229 }
230 if (song.tracks.length === 0) {
231 this.set({ status: 'Import: no notes found in file' });
232 return;
233 }
234 player.stop();
235 const name = fileName.replace(/\.(mid|midi)$/i, '') || 'Imported song';
236 const rec = this.freshRecord(name, song);
237 await db.putSong(rec);
238 this.resetHistory();
239 this.set({ rec, songs: await db.listSongs(), activeTrackId: song.tracks[0].id, armedTrackId: null, selection: [], libraryOpen: false, status: `Imported ${song.tracks.length} track(s)` });
240 player.seek(0);
241 this.rememberLast(rec.id);
242 }
244 // --- tracks ---
246 setActiveTrack(id: string): void { this.set({ activeTrackId: id, selection: [] }); }
248 setArmedTrack(id: string | null): void { this.set({ armedTrackId: id }); }
250 addTrack(): void {
251 const id = newId('t');
252 this.mutateSong((song) => {
253 song.tracks.push({ id, name: `Track ${song.tracks.length + 1}`, instrumentId: 'pluck', volume: 1, mute: false, solo: false, notes: [] });
254 });
255 this.set({ activeTrackId: id });
256 }
258 removeTrack(id: string): void {
259 this.mutateSong((song) => {
260 song.tracks = song.tracks.filter((t) => t.id !== id);
261 });
262 const song = this.song();
263 if (this.state.activeTrackId === id) this.set({ activeTrackId: song?.tracks[0]?.id ?? null });
264 if (this.state.armedTrackId === id) this.set({ armedTrackId: null });
265 }
267 updateTrack(id: string, patch: Partial<Track>, undoable = true): void {
268 const fn = (song: Song) => {
269 const t = song.tracks.find((x) => x.id === id);
270 if (t) Object.assign(t, patch);
271 };
272 if (undoable) this.mutateSong(fn);
273 else {
274 this.editSong(fn);
275 this.scheduleSave();
276 }
277 }
279 setSelection(ids: string[]): void { this.set({ selection: ids }); }
281 setSnapBeats(v: number): void { this.set({ snapBeats: v }); }
283 deleteSelection(): void {
284 if (this.state.selection.length === 0) return;
285 const sel = new Set(this.state.selection);
286 this.mutateSong((song) => {
287 for (const t of song.tracks) t.notes = t.notes.filter((n) => !sel.has(n.id));
288 });
289 this.set({ selection: [] });
290 }
292 quantize(): void {
293 const grid = this.snapTicks();
294 if (grid <= 0) { this.set({ status: 'Quantize: snap is off' }); return; }
295 const sel = this.state.selection.length > 0 ? new Set(this.state.selection) : null;
296 const activeId = this.state.activeTrackId;
297 this.mutateSong((song) => {
298 for (const t of song.tracks) {
299 if (sel) t.notes = quantizeNotes(t.notes, grid, sel);
300 else if (t.id === activeId) t.notes = quantizeNotes(t.notes, grid);
301 }
302 });
303 }
305 // --- transport ---
307 async togglePlay(): Promise<void> {
308 const song = this.song();
309 if (!song) return;
310 if (player.state !== 'stopped') this.stopTransport();
311 else {
312 try {
313 await player.play(song);
314 } catch (err) {
315 player.stop();
316 this.set({ status: `Playback failed: ${err instanceof Error ? err.message : String(err)}` });
317 }
318 }
319 }
321 async record(): Promise<void> {
322 const song = this.song();
323 if (!song) return;
324 if (player.state !== 'stopped') this.stopTransport();
325 const armed = this.state.armedTrackId ?? this.state.activeTrackId;
326 if (!armed) { this.set({ status: 'Record: no track to record into' }); return; }
327 this.set({ armedTrackId: armed });
328 try {
329 await player.play(song, { record: true, countInBars: 1 });
330 } catch (err) {
331 player.stop();
332 this.set({ status: `Record failed: ${err instanceof Error ? err.message : String(err)}` });
333 return;
334 }
335 this.recorder.start();
336 }
338 stopTransport(): void {
339 if (player.state === 'recording') {
340 const endSec = Math.max(0, player.getPositionSec());
341 const take = this.recorder.stop(endSec);
342 player.stop();
343 this.commitTake(take);
344 } else {
345 player.stop();
346 }
347 }
349 private commitTake(take: CapturedNote[]): void {
350 if (take.length === 0) return;
351 const song = this.song();
352 const armed = this.state.armedTrackId;
353 if (!song || !armed) return;
354 const tm = new TempoMap(song.ppq, song.tempo, song.timeSig);
355 const ids: string[] = [];
356 this.mutateSong((s) => {
357 const track = s.tracks.find((t) => t.id === armed);
358 if (!track) return;
359 for (const c of take) {
360 const tick = Math.max(0, Math.round(tm.secToTick(Math.max(0, c.startSec))));
361 const endTick = Math.round(tm.secToTick(Math.max(0, c.endSec)));
362 const id = newId('n');
363 ids.push(id);
364 track.notes.push({ id, tick, duration: Math.max(Math.round(s.ppq / 16), endTick - tick), pitch: c.pitch, velocity: c.velocity });
365 }
366 track.notes.sort((a, b) => a.tick - b.tick || a.pitch - b.pitch);
367 });
368 this.set({ selection: ids, status: `Recorded ${take.length} note(s)` });
369 }
371 seekTo(sec: number): void {
372 if (player.state === 'recording') return;
373 const song = this.song();
374 if (player.state === 'playing' && song) {
375 player.stop();
376 player.seek(sec);
377 void player.play(song);
378 } else {
379 player.seek(sec);
380 }
381 }
382}
384export const store = new Store();
386export function useApp(): AppState {
387 return useSyncExternalStore(store.subscribe, store.getSnapshot);
388}
390export function usePlayerVersion(): number {
391 return useSyncExternalStore(player.subscribe, () => player.version);
392}