File size: 10,736 Bytes
c27ae8d |
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 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 |
# Interactive Notation Editor
## Overview
The editor allows users to modify transcribed notation directly in the browser: add/delete notes, change durations, transpose passages, and adjust musical parameters.
## MVP Editor Features
### Phase 1 (Minimum Viable Product)
- **Add Note**: Click on staff to add new note
- **Delete Note**: Click note + Delete key or right-click → Delete
- **Move Note**: Drag note vertically to change pitch
- **Change Duration**: Select note, press number key (1=whole, 2=half, 4=quarter, 8=eighth)
### Phase 2 (Future)
- Copy/paste, multi-select
- Transpose selection
- Add articulations (staccato, accents)
- Lyrics, dynamics
- Undo/redo stack
---
## State Management
### Notation State Structure
```typescript
interface NotationState {
score: {
id: string;
title: string;
composer: string;
key: string; // e.g., "C", "Gm"
timeSignature: string; // e.g., "4/4"
tempo: number; // BPM
measures: Measure[];
};
selectedNoteIds: string[];
clipboard: Note[] | null;
history: NotationState[]; // For undo/redo
historyIndex: number;
}
interface Measure {
id: string;
number: number;
notes: Note[];
}
interface Note {
id: string;
pitch: string; // e.g., "C4", "F#5"
duration: string; // "whole", "half", "quarter", "eighth", "16th"
octave: number;
dotted: boolean;
accidental?: 'sharp' | 'flat' | 'natural';
}
```
### Zustand Store
```typescript
import create from 'zustand';
interface NotationStore extends NotationState {
// Actions
addNote: (measureId: string, note: Note) => void;
deleteNote: (noteId: string) => void;
updateNote: (noteId: string, changes: Partial<Note>) => void;
selectNote: (noteId: string) => void;
deselectAll: () => void;
undo: () => void;
redo: () => void;
}
export const useNotationStore = create<NotationStore>((set, get) => ({
score: { /* initial state */ },
selectedNoteIds: [],
clipboard: null,
history: [],
historyIndex: -1,
addNote: (measureId, note) => set(state => {
const measure = state.score.measures.find(m => m.id === measureId);
if (!measure) return state;
return {
score: {
...state.score,
measures: state.score.measures.map(m =>
m.id === measureId
? { ...m, notes: [...m.notes, note].sort(byTimestamp) }
: m
),
},
};
}),
deleteNote: (noteId) => set(state => ({
score: {
...state.score,
measures: state.score.measures.map(m => ({
...m,
notes: m.notes.filter(n => n.id !== noteId),
})),
},
})),
updateNote: (noteId, changes) => set(state => ({
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: [] }),
undo: () => {
const { history, historyIndex } = get();
if (historyIndex > 0) {
set(history[historyIndex - 1]);
set({ historyIndex: historyIndex - 1 });
}
},
redo: () => {
const { history, historyIndex } = get();
if (historyIndex < history.length - 1) {
set(history[historyIndex + 1]);
set({ historyIndex: historyIndex + 1 });
}
},
}));
```
---
## Edit Operations
### 1. Add Note
**User Action**: Click on staff at desired pitch/time
```typescript
function handleStaffClick(event: MouseEvent, staveElement: SVGElement) {
// Get click position relative to stave
const rect = staveElement.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
// Convert Y position to pitch
const pitch = yPositionToPitch(y, stave.clef);
// Convert X position to time (measure + beat)
const { measureId, beat } = xPositionToTime(x, stave.width);
// Create new note
const newNote: Note = {
id: generateId(),
pitch: pitch,
duration: currentDuration, // From toolbar
octave: parseInt(pitch.slice(-1)),
dotted: false,
};
// Add to state
useNotationStore.getState().addNote(measureId, newNote);
}
function yPositionToPitch(y: number, clef: 'treble' | 'bass'): string {
// Map Y pixel to line/space on staff
// Treble clef: E5 (top line) to F4 (bottom line)
// Each line/space is ~10px
const lineHeight = 10;
const pitches = clef === 'treble'
? ['F5', 'E5', 'D5', 'C5', 'B4', 'A4', 'G4', 'F4', 'E4']
: ['A3', 'G3', 'F3', 'E3', 'D3', 'C3', 'B2', 'A2', 'G2'];
const index = Math.floor(y / lineHeight);
return pitches[index] || 'C4';
}
```
---
### 2. Delete Note
**User Action**: Select note, press Delete key
```typescript
useEffect(() => {
function handleKeyDown(event: KeyboardEvent) {
const { selectedNoteIds, deleteNote } = useNotationStore.getState();
if (event.key === 'Delete' || event.key === 'Backspace') {
selectedNoteIds.forEach(id => deleteNote(id));
}
}
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, []);
```
---
### 3. Move Note (Change Pitch)
**User Action**: Drag note vertically
```typescript
function handleNoteDrag(noteId: string, event: MouseEvent) {
const startY = event.clientY;
let currentY = startY;
function onMouseMove(e: MouseEvent) {
currentY = e.clientY;
const deltaY = currentY - startY;
// Convert delta to semitones (10px per semitone)
const semitoneShift = Math.round(deltaY / 10);
// Update note pitch
const originalNote = findNoteById(noteId);
const newPitch = transposePitch(originalNote.pitch, semitoneShift);
useNotationStore.getState().updateNote(noteId, { pitch: newPitch });
// Re-render VexFlow
renderNotation();
}
function onMouseUp() {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
}
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
}
function transposePitch(pitch: string, semitones: number): string {
const pitchMap = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
const [note, octaveStr] = [pitch.slice(0, -1), pitch.slice(-1)];
let octave = parseInt(octaveStr);
let index = pitchMap.indexOf(note);
index += semitones;
// Handle octave wrap
while (index < 0) {
index += 12;
octave--;
}
while (index >= 12) {
index -= 12;
octave++;
}
return `${pitchMap[index]}${octave}`;
}
```
---
### 4. Change Duration
**User Action**: Select note, press number key
```typescript
const durationKeyMap: { [key: string]: string } = {
'1': 'whole',
'2': 'half',
'4': 'quarter',
'8': 'eighth',
'6': '16th', // 6 for 16th note
};
useEffect(() => {
function handleKeyDown(event: KeyboardEvent) {
const { selectedNoteIds, updateNote } = useNotationStore.getState();
const newDuration = durationKeyMap[event.key];
if (newDuration && selectedNoteIds.length > 0) {
selectedNoteIds.forEach(id => {
updateNote(id, { duration: newDuration });
});
renderNotation(); // Re-render
}
}
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, []);
```
---
## UI Components
### Toolbar
```typescript
export const EditorToolbar: React.FC = () => {
const [selectedTool, setSelectedTool] = useState<'select' | 'add' | 'delete'>('select');
const [selectedDuration, setSelectedDuration] = useState<string>('quarter');
return (
<div className="editor-toolbar">
<ToolButton
icon="cursor"
active={selectedTool === 'select'}
onClick={() => setSelectedTool('select')}
tooltip="Select (V)"
/>
<ToolButton
icon="plus"
active={selectedTool === 'add'}
onClick={() => setSelectedTool('add')}
tooltip="Add Note (A)"
/>
<ToolButton
icon="trash"
active={selectedTool === 'delete'}
onClick={() => setSelectedTool('delete')}
tooltip="Delete (D)"
/>
<Divider />
<DurationSelector value={selectedDuration} onChange={setSelectedDuration} />
<Divider />
<ToolButton icon="undo" onClick={() => useNotationStore.getState().undo()} tooltip="Undo (Cmd+Z)" />
<ToolButton icon="redo" onClick={() => useNotationStore.getState().redo()} tooltip="Redo (Cmd+Shift+Z)" />
</div>
);
};
```
### Context Menu (Right-Click)
```typescript
export const NoteContextMenu: React.FC<{ noteId: string, position: { x: number, y: number } }> = ({ noteId, position }) => {
const { deleteNote, updateNote } = useNotationStore();
return (
<Menu style={{ top: position.y, left: position.x }}>
<MenuItem onClick={() => deleteNote(noteId)}>Delete</MenuItem>
<MenuItem onClick={() => updateNote(noteId, { dotted: true })}>Add Dot</MenuItem>
<MenuItem onClick={() => { /* transpose logic */ }}>Transpose...</MenuItem>
</Menu>
);
};
```
---
## Keyboard Shortcuts
```typescript
const shortcuts = {
'v': 'select tool',
'a': 'add note tool',
'd': 'delete tool',
'1-8': 'change duration',
'Delete': 'delete selected',
'Cmd+Z': 'undo',
'Cmd+Shift+Z': 'redo',
'Cmd+C': 'copy',
'Cmd+V': 'paste',
'ArrowUp': 'transpose up',
'ArrowDown': 'transpose down',
};
```
---
## Undo/Redo Implementation
```typescript
// Save state before every mutation
function saveHistory() {
const state = useNotationStore.getState();
const newHistory = state.history.slice(0, state.historyIndex + 1);
newHistory.push(state);
set({
history: newHistory,
historyIndex: newHistory.length - 1,
});
}
// Call before mutations
addNote: (measureId, note) => {
saveHistory();
// ... perform mutation
}
```
---
## Validation
### Prevent Invalid Edits
```typescript
function validateNote(note: Note, measure: Measure): string | null {
// Check measure capacity (e.g., 4/4 = 4 beats max)
const totalBeats = measure.notes.reduce((sum, n) => sum + durationToBeats(n.duration), 0);
if (totalBeats + durationToBeats(note.duration) > measure.maxBeats) {
return 'Measure is full';
}
// Check pitch range for instrument
if (!isPitchInRange(note.pitch, 'piano')) {
return 'Pitch out of range for piano';
}
return null; // Valid
}
```
---
## Next Steps
1. Implement [Playback System](playback.md) to hear edited notation
2. Add advanced features (copy/paste, multi-select)
3. Test editing with complex scores
See [Data Flow](data-flow.md) for how state propagates through the app.
|