File size: 6,518 Bytes
44a2550 0dfd298 44a2550 6293e69 44a2550 6293e69 44a2550 0dfd298 44a2550 0dfd298 44a2550 6293e69 0dfd298 6293e69 0dfd298 44a2550 0dfd298 44a2550 0dfd298 44a2550 0dfd298 6293e69 0dfd298 6293e69 0dfd298 6293e69 0dfd298 6293e69 0dfd298 6293e69 0dfd298 44a2550 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 |
/**
* Zustand store for notation state management.
* Supports multi-instrument transcription.
*/
import { create } from 'zustand';
import { parseMidiFile, assignChordIds } from '../utils/midi-parser';
export interface Note {
id: string;
pitch: string; // e.g., "C4", "F#5", or empty string for rests
duration: string; // "whole", "half", "quarter", "eighth", "16th"
octave: number;
startTime: number;
dotted: boolean;
accidental?: 'sharp' | 'flat' | 'natural';
isRest: boolean;
chordId?: string; // Group chord notes together (notes with same chordId are rendered as single VexFlow chord)
}
export interface Measure {
id: string;
number: number;
notes: Note[];
}
export interface Part {
id: string;
name: string; // "Piano Right Hand", "Piano Left Hand"
clef: 'treble' | 'bass';
measures: Measure[];
}
export interface Score {
id: string;
title: string;
composer: string;
key: string; // e.g., "C", "Gm"
timeSignature: string; // e.g., "4/4"
tempo: number; // BPM
parts: Part[]; // Support multiple parts for grand staff
measures: Measure[]; // Legacy: for backward compatibility, use parts[0].measures
}
interface NotationState {
// Multi-instrument support
scores: Map<string, Score>; // instrument -> Score
activeInstrument: string; // Currently viewing instrument (e.g., 'piano', 'vocals')
availableInstruments: string[]; // All transcribed instruments
// Legacy single-score access (for backward compatibility)
score: Score | null;
selectedNoteIds: string[];
currentTool: 'select' | 'add' | 'delete';
currentDuration: string;
playingNoteIds: string[]; // Notes currently being played (for visual feedback)
// Actions
loadFromMidi: (
instrument: string,
midiData: ArrayBuffer,
metadata?: {
tempo?: number;
keySignature?: string;
timeSignature?: { numerator: number; denominator: number };
}
) => Promise<void>;
setActiveInstrument: (instrument: string) => void;
addNote: (measureId: string, note: Note) => void;
deleteNote: (noteId: string) => void;
updateNote: (noteId: string, changes: Partial<Note>) => void;
selectNote: (noteId: string) => void;
deselectAll: () => void;
setCurrentTool: (tool: 'select' | 'add' | 'delete') => void;
setCurrentDuration: (duration: string) => void;
setPlayingNoteIds: (noteIds: string[]) => void;
}
export const useNotationStore = create<NotationState>((set, get) => ({
// Multi-instrument state
scores: new Map(),
activeInstrument: 'piano',
availableInstruments: [],
// Legacy single-score (points to active instrument's score)
score: null,
selectedNoteIds: [],
currentTool: 'select',
currentDuration: 'quarter',
playingNoteIds: [],
loadFromMidi: async (instrument, midiData, metadata) => {
try {
let score = await parseMidiFile(midiData, {
tempo: metadata?.tempo,
timeSignature: metadata?.timeSignature,
keySignature: metadata?.keySignature,
splitAtMiddleC: instrument === 'piano', // Only split piano into grand staff
middleCNote: 60,
});
// Assign chord IDs to simultaneous notes
score = assignChordIds(score);
// Update scores map
const state = get();
const newScores = new Map(state.scores);
newScores.set(instrument, score);
// Update available instruments if this is a new one
const newAvailableInstruments = state.availableInstruments.includes(instrument)
? state.availableInstruments
: [...state.availableInstruments, instrument];
set({
scores: newScores,
availableInstruments: newAvailableInstruments,
// Update legacy score if this is the active instrument
score: state.activeInstrument === instrument ? score : state.score,
});
} catch (error) {
console.error('Failed to parse MIDI:', error);
// Create fallback empty score
const emptyScore: Score = {
id: `score-${instrument}`,
title: 'Transcribed Score',
composer: 'YourMT3+',
key: metadata?.keySignature || 'C',
timeSignature: metadata?.timeSignature
? `${metadata.timeSignature.numerator}/${metadata.timeSignature.denominator}`
: '4/4',
tempo: metadata?.tempo || 120,
parts: [],
measures: [],
};
const state = get();
const newScores = new Map(state.scores);
newScores.set(instrument, emptyScore);
const newAvailableInstruments = state.availableInstruments.includes(instrument)
? state.availableInstruments
: [...state.availableInstruments, instrument];
set({
scores: newScores,
availableInstruments: newAvailableInstruments,
score: state.activeInstrument === instrument ? emptyScore : state.score,
});
}
},
setActiveInstrument: (instrument) => {
const state = get();
const instrumentScore = state.scores.get(instrument);
set({
activeInstrument: instrument,
score: instrumentScore || null,
selectedNoteIds: [], // Clear selection when switching instruments
});
},
addNote: (measureId, note) =>
set((state) => {
if (!state.score) return state;
return {
score: {
...state.score,
measures: state.score.measures.map((m) =>
m.id === measureId
? { ...m, notes: [...m.notes, note].sort((a, b) => a.startTime - b.startTime) }
: m
),
},
};
}),
deleteNote: (noteId) =>
set((state) => {
if (!state.score) return state;
return {
score: {
...state.score,
measures: state.score.measures.map((m) => ({
...m,
notes: m.notes.filter((n) => n.id !== noteId),
})),
},
};
}),
updateNote: (noteId, changes) =>
set((state) => {
if (!state.score) return state;
return {
score: {
...state.score,
measures: state.score.measures.map((m) => ({
...m,
notes: m.notes.map((n) => (n.id === noteId ? { ...n, ...changes } : n)),
})),
},
};
}),
selectNote: (noteId) => set({ selectedNoteIds: [noteId] }),
deselectAll: () => set({ selectedNoteIds: [] }),
setCurrentTool: (tool) => set({ currentTool: tool }),
setCurrentDuration: (duration) => set({ currentDuration: duration }),
setPlayingNoteIds: (noteIds) => set({ playingNoteIds: noteIds }),
}));
|