mirror of
https://github.com/9x/sheetmusictrainer.git
synced 2026-11-03 22:03:54 +01:00
Compare commits
4 Commits
feature/ph
...
85fe20bf51
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
85fe20bf51 | ||
|
|
b214c209f9 | ||
|
|
15b8705907 | ||
| da060e5bb9 |
5
TOOLS_LOCAL.md
Normal file
5
TOOLS_LOCAL.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Local deployment (nyx server) — beta channel
|
||||
- Managed by Nyx; deploy script: `~/deploy/smt-beta.sh [branch]` (fetch, build, docker rebuild, restart)
|
||||
- Container: `smt-beta` (nginx:alpine, 127.0.0.1:8081), image `smt-beta-image`
|
||||
- Tailnet URL: http://nyx-rg3jpx6w.internal.0jm.de/ (tailscale serve → 8081)
|
||||
- Note: `tailscale serve --https` not available on this tailnet (feature not enabled); plain HTTP inside tailnet only
|
||||
@@ -23,6 +23,30 @@ Implementation of [PHRASE_MODE_PLAN.md](../PHRASE_MODE_PLAN.md) and
|
||||
| R13 Safe lifecycle | ✅ | Pause on tab-hide, mic error, mic-off, dialogs; audio-group cancellation; run tokens; StrictMode-safe; unmount cleanup |
|
||||
| R14 Tested delivery | ✅ | 149 unit/integration tests + real-browser synthetic-mic suite (see below) |
|
||||
|
||||
## Late feedback round (post first delivery)
|
||||
|
||||
- **Guitar octave bug**: the phrase renderer drew sounding pitch; fixed by
|
||||
deriving the written pitch through the shared `spelledPitch` helper, and
|
||||
clef/transpose resolution extracted to `resolveClefTranspose` (used by both
|
||||
modes — requested reuse of proven single-note logic).
|
||||
- **Count-in**: an extra 5th click at the score's downbeat made players start
|
||||
a beat early (perceived as "play the note before"); removed (the count-in's
|
||||
last click IS the downbeat).
|
||||
- **Tempo timing proven**: browser test plays every Ode note exactly in its
|
||||
audio window → 8/8 matched (also caught + fixed false scoring during the
|
||||
count-in itself).
|
||||
- **Repeated notes**: release-based re-arm + 2.5 s at-your-pace timeout + a
|
||||
clear status hint ("release, then strike again").
|
||||
- **Auto-continue** (tempo, default on): exercises roll to the next section
|
||||
(wrapping), melodies roll a new seed, scale drills restart.
|
||||
- **BPM widget**: −/+ buttons + slider + free-typing text field (commit on
|
||||
blur/Enter) — the single-note widget pattern.
|
||||
- **Live-note staff** next to the mic readout: written-pitch mini staff with
|
||||
8va/8vb normalization; box matches the mic button; VexFlow's
|
||||
`space_above_staff_ln` (~40.5px) offset compensated (see TECHNICAL_REALIZATION).
|
||||
- **Library**: 19 items (5 verified PD melodies + 14 labeled originals).
|
||||
- **Zen centering** + live staff sizing/overlap per user feedback.
|
||||
|
||||
## Verification actually performed
|
||||
|
||||
- `npm run lint`, `npm run build`, `npm test -- --run`: all green (149 tests,
|
||||
|
||||
@@ -332,6 +332,7 @@ function App() {
|
||||
midi={displayedPitch ? displayedPitch.midi : null}
|
||||
transpose={resolveClefTranspose(currentInstrumentDef, settings.difficulty).transpose}
|
||||
keySignature={settings.keySignature}
|
||||
clef={currentInstrumentDef.clefMode === 'treble' ? 'treble' : currentInstrumentDef.clefMode === 'bass' ? 'bass' : undefined}
|
||||
theme={settings.theme}
|
||||
/>
|
||||
<div className={`pitch-readout ${displayedPitch ? 'active' : ''}`}>
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Settings, Guitar, Music, Gauge } from 'lucide-react';
|
||||
import { Guitar, Music, Gauge } from 'lucide-react';
|
||||
import { TUNINGS, INSTRUMENT_TUNINGS } from '../music/Tunings';
|
||||
import { INSTRUMENT_DEFINITIONS } from '../music/InstrumentConfigs';
|
||||
import { getTempoMarking } from '../music/TempoMarkings';
|
||||
|
||||
import { TuningMeter } from './TuningMeter';
|
||||
import { TargetNoteControls } from './TargetNoteControls';
|
||||
import { MetronomeWidget } from './MetronomeWidget';
|
||||
|
||||
import { useSettings } from '../context/useSettings';
|
||||
import { type Difficulty, type RhythmSettings } from '../types/SettingsTypes';
|
||||
@@ -17,10 +19,6 @@ export const Controls: React.FC<ControlsProps> = ({ currentPitch }) => {
|
||||
const { settings, updateSettings } = useSettings();
|
||||
// Alias to minimize refactor, or just use updateSettings.
|
||||
const onUpdateSettings = updateSettings;
|
||||
const handleDifficultyChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
onUpdateSettings({ ...settings, difficulty: e.target.value as Difficulty });
|
||||
};
|
||||
|
||||
const handleTuningChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
onUpdateSettings({ ...settings, tuningId: e.target.value });
|
||||
};
|
||||
@@ -110,23 +108,6 @@ export const Controls: React.FC<ControlsProps> = ({ currentPitch }) => {
|
||||
If Tuning is hidden, Note Set becomes Item 2.
|
||||
I'll forgo complexity and just render what's available. */}
|
||||
|
||||
{/* Row 2, Col 1 */}
|
||||
<div className="control-group">
|
||||
<label className="control-label">
|
||||
<Settings size={18} />
|
||||
<span>Note Set</span>
|
||||
</label>
|
||||
<select
|
||||
value={settings.difficulty}
|
||||
onChange={handleDifficultyChange}
|
||||
className="control-select"
|
||||
>
|
||||
{currentInstrumentDef.ranges.map(r => (
|
||||
<option key={r.id} value={r.id}>{r.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Row 2, Col 2 */}
|
||||
{!inPhraseMode && (
|
||||
<div className="control-group">
|
||||
@@ -157,42 +138,11 @@ export const Controls: React.FC<ControlsProps> = ({ currentPitch }) => {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Row 3: Fret Range (Full Width) */}
|
||||
{currentInstrumentDef.ranges.find(r => r.id === settings.difficulty)?.type === 'custom_fret' && (
|
||||
<div className="control-group" style={{ gridColumn: '1 / -1' }}>
|
||||
<label className="control-label">
|
||||
<span>Fret Range</span>
|
||||
</label>
|
||||
<div style={{ display: 'flex', gap: '8px', width: '100%' }}>
|
||||
<div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: '4px' }}>
|
||||
<span style={{ fontSize: '12px', opacity: 0.7 }}>Min</span>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max="24"
|
||||
value={settings.customMinFret ?? 0}
|
||||
onChange={(e) => onUpdateSettings({ ...settings, customMinFret: parseInt(e.target.value) || 0 })}
|
||||
className="control-input"
|
||||
style={{ width: '100%', padding: '4px' }}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: '4px' }}>
|
||||
<span style={{ fontSize: '12px', opacity: 0.7 }}>Max</span>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max="24"
|
||||
value={settings.customMaxFret ?? 12}
|
||||
onChange={(e) => onUpdateSettings({ ...settings, customMaxFret: parseInt(e.target.value) || 0 })}
|
||||
className="control-input"
|
||||
style={{ width: '100%', padding: '4px' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Target-note filter: unified controls, all modes */}
|
||||
<TargetNoteControls />
|
||||
|
||||
{/* Bottom Section: Tools Grid (2 Columns now) */}
|
||||
<div className="tools-grid" style={inPhraseMode ? { gridTemplateColumns: '1fr' } : undefined}>
|
||||
{/* Tool 1: Tuner */}
|
||||
@@ -220,120 +170,14 @@ export const Controls: React.FC<ControlsProps> = ({ currentPitch }) => {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tool 2: Metronome (single-note modes only) */}
|
||||
{!inPhraseMode && (
|
||||
{/* Tool 2: Metronome (all modes) */}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px', border: '1px solid rgba(128,128,128,0.2)', padding: '12px', borderRadius: '8px' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
<label className="control-label" style={{ marginBottom: 0 }}>
|
||||
<span>Metronome</span>
|
||||
</label>
|
||||
<button
|
||||
className={`switch-button ${settings.rhythm.active ? 'active' : ''}`}
|
||||
onClick={() => updateRhythm({ active: !settings.rhythm.active })}
|
||||
title={settings.rhythm.active ? "Turn Off" : "Turn On"}
|
||||
>
|
||||
<div className="switch-thumb" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{settings.rhythm.active && (
|
||||
<div className="rhythm-details" style={{ display: 'flex', flexDirection: 'column', gap: '6px', paddingTop: '8px', borderTop: '1px solid rgba(255,255,255,0.1)' }}>
|
||||
<div style={{ display: 'flex', gap: '4px' }}>
|
||||
<button
|
||||
className={`control-button small ${settings.rhythm.mode === 'bpm' ? 'active' : ''}`}
|
||||
onClick={() => updateRhythm({ mode: 'bpm' })}
|
||||
style={{ flex: 1, fontSize: '10px' }}
|
||||
>BPM</button>
|
||||
<button
|
||||
className={`control-button small ${settings.rhythm.mode === 'seconds' ? 'active' : ''}`}
|
||||
onClick={() => updateRhythm({ mode: 'seconds' })}
|
||||
style={{ flex: 1, fontSize: '10px' }}
|
||||
>Timer</button>
|
||||
</div>
|
||||
|
||||
{settings.rhythm.mode === 'bpm' ? (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
|
||||
<button
|
||||
className="control-button small"
|
||||
onClick={() => updateRhythm({ bpm: Math.max(30, settings.rhythm.bpm - 1) })}
|
||||
style={{ width: '24px', padding: '0', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
|
||||
>
|
||||
-
|
||||
</button>
|
||||
<input
|
||||
type="number"
|
||||
min="30"
|
||||
max="300"
|
||||
value={settings.rhythm.bpm}
|
||||
onChange={(e) => updateRhythm({ bpm: Math.max(1, parseInt(e.target.value) || 60) })}
|
||||
className="control-input"
|
||||
style={{
|
||||
width: '48px',
|
||||
textAlign: 'center',
|
||||
padding: '2px'
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
className="control-button small"
|
||||
onClick={() => updateRhythm({ bpm: Math.min(300, settings.rhythm.bpm + 1) })}
|
||||
style={{ width: '24px', padding: '0', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
|
||||
>
|
||||
+
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min="30"
|
||||
max="240"
|
||||
step="1"
|
||||
value={settings.rhythm.bpm}
|
||||
onChange={(e) => updateRhythm({ bpm: Number(e.target.value) })}
|
||||
style={{ flex: 1 }}
|
||||
<MetronomeWidget
|
||||
rhythm={settings.rhythm}
|
||||
onUpdate={updateRhythm}
|
||||
showAutoAdvance={!inPhraseMode}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ fontSize: '11px', opacity: 0.7, textAlign: 'center' }}>
|
||||
{getTempoMarking(settings.rhythm.bpm)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
|
||||
<span style={{ fontSize: '12px', minWidth: '32px' }}>{settings.rhythm.seconds}s</span>
|
||||
<input
|
||||
type="range"
|
||||
min="1"
|
||||
max="60"
|
||||
step="1"
|
||||
value={settings.rhythm.seconds}
|
||||
onChange={(e) => updateRhythm({ seconds: Number(e.target.value) })}
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<label style={{ fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={settings.rhythm.autoAdvance}
|
||||
onChange={(e) => updateRhythm({ autoAdvance: e.target.checked })}
|
||||
/>
|
||||
Auto
|
||||
</label>
|
||||
|
||||
<label style={{ fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={settings.rhythm.sound}
|
||||
onChange={(e) => updateRhythm({ sound: e.target.checked })}
|
||||
/>
|
||||
Sound
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
)}
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -14,10 +14,12 @@ import { Renderer, Stave, StaveNote, Accidental, Voice, Formatter, Annotation }
|
||||
import { getNoteInKey } from '../music/NoteUtils';
|
||||
|
||||
interface LiveNoteStaffProps {
|
||||
/** Sounding midi of the live detected pitch, or null when silent. */
|
||||
midi: number | null;
|
||||
transpose: number;
|
||||
keySignature: string;
|
||||
/** Force a clef (e.g. the instrument's usual clef). When omitted the
|
||||
* clef auto-switches treble/bass around middle C (piano-style). */
|
||||
clef?: 'treble' | 'bass';
|
||||
width?: number;
|
||||
theme?: 'light' | 'dark' | 'auto';
|
||||
}
|
||||
@@ -32,6 +34,7 @@ export const LiveNoteStaff: React.FC<LiveNoteStaffProps> = ({
|
||||
midi,
|
||||
transpose = 0,
|
||||
keySignature = 'C',
|
||||
clef: clefOverride,
|
||||
width = 130,
|
||||
theme = 'auto',
|
||||
}) => {
|
||||
@@ -63,8 +66,9 @@ export const LiveNoteStaff: React.FC<LiveNoteStaffProps> = ({
|
||||
const stave = new Stave(0, STAVE_Y, width - 2);
|
||||
stave.setDefaultLedgerLineStyle({ strokeStyle: resolvedColor, lineWidth: 2 });
|
||||
const written0 = midi !== null ? midi + transpose : null;
|
||||
// Clef like the grand-staff split: below middle C reads bass clef.
|
||||
const clef: 'treble' | 'bass' = written0 !== null && written0 < 60 ? 'bass' : 'treble';
|
||||
// Instrument-fixed clef when provided (guitar always treble, bass
|
||||
// always bass); otherwise piano-style split at middle C.
|
||||
const clef: 'treble' | 'bass' = clefOverride ?? (written0 !== null && written0 < 60 ? 'bass' : 'treble');
|
||||
stave.addClef(clef);
|
||||
if (keySignature) stave.addKeySignature(keySignature);
|
||||
stave.setContext(context).draw();
|
||||
@@ -109,7 +113,7 @@ export const LiveNoteStaff: React.FC<LiveNoteStaffProps> = ({
|
||||
new Formatter().joinVoices([voice]).format([voice], width - 40);
|
||||
voice.draw(context, stave);
|
||||
}
|
||||
}, [midi, transpose, keySignature, width, theme, schemeVersion]);
|
||||
}, [midi, transpose, keySignature, clefOverride, width, theme, schemeVersion]);
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
180
src/components/MetronomeWidget.tsx
Normal file
180
src/components/MetronomeWidget.tsx
Normal file
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* Metronome widget with a linear pendulum indicator.
|
||||
*
|
||||
* The pendulum is a CSS-animated dot whose half-period equals one beat:
|
||||
* it travels left→right on even beats and right→left on odd beats, driven
|
||||
* by the metronome's onTick callback (no drift — synced to the audible
|
||||
* click, not to wall-clock CSS timing alone).
|
||||
*/
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { useMetronome } from '../hooks/useMetronome';
|
||||
import { getTempoMarking } from '../music/TempoMarkings';
|
||||
import type { RhythmSettings } from '../types/SettingsTypes';
|
||||
|
||||
interface MetronomeWidgetProps {
|
||||
rhythm: RhythmSettings;
|
||||
/** Persist changes (bpm, active, sound). Auto-advance is single-note only. */
|
||||
onUpdate: (updates: Partial<RhythmSettings>) => void;
|
||||
/** Single-note mode extra: auto-advance targets on each tick. */
|
||||
showAutoAdvance?: boolean;
|
||||
onBeat?: () => void;
|
||||
/** Compact layout (phrase transport row). */
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
export const MetronomeWidget: React.FC<MetronomeWidgetProps> = ({
|
||||
rhythm,
|
||||
onUpdate,
|
||||
showAutoAdvance = false,
|
||||
onBeat,
|
||||
compact = false,
|
||||
}) => {
|
||||
// Single metronome instance: drives both the audible click and the
|
||||
// pendulum parity flip (perfectly in sync).
|
||||
const [beatParity, setBeatParity] = useState(0);
|
||||
const lastTickRef = useRef(0);
|
||||
const onBeatRef = useRef(onBeat);
|
||||
useEffect(() => { onBeatRef.current = onBeat; }, [onBeat]);
|
||||
|
||||
const handleTick = useCallback((beat: number) => {
|
||||
const now = performance.now();
|
||||
// Ignore double-fires within 60ms (audio glitch guard)
|
||||
if (now - lastTickRef.current < 60) return;
|
||||
lastTickRef.current = now;
|
||||
setBeatParity(beat % 2);
|
||||
onBeatRef.current?.();
|
||||
}, []);
|
||||
|
||||
const { restart } = useMetronome({
|
||||
bpm: rhythm.bpm,
|
||||
volume: rhythm.sound ? rhythm.volume : 0,
|
||||
playing: rhythm.active,
|
||||
onTick: handleTick,
|
||||
});
|
||||
void restart;
|
||||
|
||||
const beatMs = 60000 / Math.max(1, rhythm.bpm);
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
<label className="control-label" style={{ marginBottom: 0 }}>
|
||||
<span>Metronome</span>
|
||||
</label>
|
||||
<button
|
||||
className={`switch-button ${rhythm.active ? 'active' : ''}`}
|
||||
onClick={() => onUpdate({ active: !rhythm.active })}
|
||||
title={rhythm.active ? 'Turn Off' : 'Turn On'}
|
||||
>
|
||||
<div className="switch-thumb" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{rhythm.active && (
|
||||
<div className="rhythm-details" style={{ display: 'flex', flexDirection: 'column', gap: '6px', paddingTop: '8px', borderTop: '1px solid rgba(255,255,255,0.1)' }}>
|
||||
{/* Linear pendulum — same element, left transitions each beat */}
|
||||
<div
|
||||
style={{
|
||||
position: 'relative',
|
||||
height: compact ? 14 : 18,
|
||||
borderRadius: 9,
|
||||
background: 'color-mix(in srgb, var(--color-text-main) 8%, transparent)',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
aria-hidden
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '50%',
|
||||
left: beatParity === 0 ? '6%' : '88%',
|
||||
width: compact ? 10 : 12,
|
||||
height: compact ? 10 : 12,
|
||||
borderRadius: '50%',
|
||||
background: 'var(--color-text-main)',
|
||||
transform: 'translateY(-50%)',
|
||||
transition: `left ${beatMs}ms linear`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{rhythm.mode === 'bpm' || compact ? (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
|
||||
<button
|
||||
className="control-button small"
|
||||
onClick={() => onUpdate({ bpm: Math.max(30, rhythm.bpm - 1) })}
|
||||
style={{ width: '24px', padding: '0', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
|
||||
>
|
||||
−
|
||||
</button>
|
||||
<input
|
||||
type="number"
|
||||
min="30"
|
||||
max="300"
|
||||
value={rhythm.bpm}
|
||||
onChange={(e) => onUpdate({ bpm: Math.max(1, parseInt(e.target.value) || 60) })}
|
||||
className="control-input"
|
||||
style={{ width: '48px', textAlign: 'center', padding: '2px' }}
|
||||
/>
|
||||
<button
|
||||
className="control-button small"
|
||||
onClick={() => onUpdate({ bpm: Math.min(300, rhythm.bpm + 1) })}
|
||||
style={{ width: '24px', padding: '0', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
|
||||
>
|
||||
+
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min="30"
|
||||
max="240"
|
||||
step="1"
|
||||
value={rhythm.bpm}
|
||||
onChange={(e) => onUpdate({ bpm: Number(e.target.value) })}
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ fontSize: '11px', opacity: 0.7, textAlign: 'center' }}>
|
||||
{getTempoMarking(rhythm.bpm)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
|
||||
<span style={{ fontSize: '12px', minWidth: '32px' }}>{rhythm.seconds}s</span>
|
||||
<input
|
||||
type="range"
|
||||
min="1"
|
||||
max="60"
|
||||
step="1"
|
||||
value={rhythm.seconds}
|
||||
onChange={(e) => onUpdate({ seconds: Number(e.target.value) })}
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
{showAutoAdvance ? (
|
||||
<label style={{ fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={rhythm.autoAdvance}
|
||||
onChange={(e) => onUpdate({ autoAdvance: e.target.checked })}
|
||||
/>
|
||||
Auto
|
||||
</label>
|
||||
) : <span />}
|
||||
<label style={{ fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={rhythm.sound}
|
||||
onChange={(e) => onUpdate({ sound: e.target.checked })}
|
||||
/>
|
||||
Sound
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -13,13 +13,13 @@ import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRe
|
||||
import { useSettings } from '../context/useSettings';
|
||||
import { useAudioPlayer } from '../hooks/useAudioPlayer';
|
||||
import { usePhraseTrainer, type PhraseTrainerApi, type PhrasePhase } from '../hooks/usePhraseTrainer';
|
||||
import { getPhraseSettings, type PhraseSettings } from '../types/SettingsTypes';
|
||||
import { getPhraseSettings, getPracticeFilter, type PhraseSettings, type PracticeFilter } from '../types/SettingsTypes';
|
||||
import { rawFrameCount } from '../hooks/rawFrameBus';
|
||||
import { audioEngine } from '../audio/AudioEngine';
|
||||
import { computePlayableNotes, isFrettedInstrument, positionsWithinWindow, fretWindowNotes } from '../music/playableRange';
|
||||
import { generateMelody } from '../music/melodyGenerator';
|
||||
import { generateScaleDrill } from '../music/scaleDrills';
|
||||
import { isMode, MODE_LABELS, TONICS, type ModeId } from '../music/scales';
|
||||
import { isMode, type ModeId } from '../music/scales';
|
||||
import { scoreEvents, type Result, type Score, type ScoreEvent } from '../score/model';
|
||||
import { getNoteDetails } from '../music/NoteUtils';
|
||||
import { EXERCISES, loadExercise } from '../exercises/library';
|
||||
@@ -68,16 +68,69 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
|
||||
const setSettings = updateSettings;
|
||||
const { playNote } = useAudioPlayer();
|
||||
const phrase = getPhraseSettings(settings);
|
||||
// Unified target-note controls: Phrase Mode reads/writes the shared
|
||||
// practice filter so all modes expose identical key/fret-window state.
|
||||
const pf = getPracticeFilter(settings);
|
||||
phrase.keyTonic = pf.keyTonic;
|
||||
phrase.keyMode = pf.keyMode;
|
||||
phrase.fretWindowEnabled = pf.fretWindowEnabled;
|
||||
phrase.fretMin = pf.fretMin;
|
||||
phrase.fretMax = pf.fretMax;
|
||||
// Unified metronome: phrase tempo reads from the shared rhythm BPM
|
||||
// (single source of truth across modes; the phrase-local BPM control
|
||||
// was replaced by the common metronome widget in Controls).
|
||||
phrase.bpm = settings.rhythm.bpm;
|
||||
const setPhrase = useCallback((updates: Partial<PhraseSettings>) => {
|
||||
updateSettings(s => ({ ...s, phrase: { ...getPhraseSettings(s), ...updates } }));
|
||||
updateSettings(s => {
|
||||
const next = { ...s, phrase: { ...getPhraseSettings(s), ...updates } };
|
||||
// Mirror shared filter fields into the unified practice filter.
|
||||
const shared: Partial<PracticeFilter> = {};
|
||||
if ('keyTonic' in updates) shared.keyTonic = updates.keyTonic;
|
||||
if ('keyMode' in updates) shared.keyMode = updates.keyMode;
|
||||
if ('fretWindowEnabled' in updates) shared.fretWindowEnabled = updates.fretWindowEnabled;
|
||||
if ('fretMin' in updates) shared.fretMin = updates.fretMin;
|
||||
if ('fretMax' in updates) shared.fretMax = updates.fretMax;
|
||||
if (Object.keys(shared).length > 0) next.practice = { ...getPracticeFilter(s), ...shared };
|
||||
return next;
|
||||
});
|
||||
}, [updateSettings]);
|
||||
|
||||
const currentInstrumentDef = INSTRUMENT_DEFINITIONS[settings.instrument];
|
||||
const currentTuning = TUNINGS[settings.tuningId];
|
||||
const fretted = isFrettedInstrument(settings.instrument) && !!currentTuning;
|
||||
|
||||
// ---- Playable pool ----------------------------------------------------
|
||||
const pool = useMemo(() => {
|
||||
// Unified filter: strings ∩ fret window take precedence for fretted
|
||||
// instruments (same semantics as the single-note modes).
|
||||
if (fretted && currentTuning && (pf.strings.length > 0 || pf.fretWindowEnabled)) {
|
||||
const all = currentTuning.strings;
|
||||
const selected = pf.strings.length > 0
|
||||
? all.filter((_, i) => pf.strings.includes(i))
|
||||
: all;
|
||||
if (selected.length > 0) {
|
||||
if (pf.fretWindowEnabled) {
|
||||
const lo = Math.max(0, Math.min(24, pf.fretMin));
|
||||
const hi = Math.max(lo, Math.min(24, pf.fretMax));
|
||||
return selected.flatMap(open => {
|
||||
const notes: number[] = [];
|
||||
for (let fret = lo; fret <= hi; fret++) notes.push(open + fret);
|
||||
return notes;
|
||||
}).sort((a, b) => a - b);
|
||||
}
|
||||
// Strings only: use their full range
|
||||
const maxFret = Math.max(...all.map(open => {
|
||||
let f = 0;
|
||||
while (open + f <= 127) f++;
|
||||
return Math.min(f - 1, 24);
|
||||
}));
|
||||
return selected.flatMap(open => {
|
||||
const notes: number[] = [];
|
||||
for (let fret = 0; fret <= maxFret; fret++) notes.push(open + fret);
|
||||
return notes;
|
||||
}).sort((a, b) => a - b);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
if (phrase.fretWindowEnabled && fretted && currentTuning) {
|
||||
return fretWindowNotes(currentTuning, phrase.fretMin, phrase.fretMax);
|
||||
}
|
||||
@@ -88,7 +141,8 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
|
||||
customMinFret: settings.customMinFret,
|
||||
customMaxFret: settings.customMaxFret,
|
||||
});
|
||||
}, [phrase.fretWindowEnabled, phrase.fretMin, phrase.fretMax, fretted, currentTuning,
|
||||
}, [pf.strings, pf.fretWindowEnabled, pf.fretMin, pf.fretMax, fretted, currentTuning,
|
||||
phrase.fretWindowEnabled, phrase.fretMin, phrase.fretMax,
|
||||
settings.instrument, settings.difficulty, settings.tuningId, settings.customMinFret, settings.customMaxFret]);
|
||||
|
||||
// ---- Imported score (session-only) --------------------------------------
|
||||
@@ -98,20 +152,6 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
|
||||
const [melodySeed, setMelodySeed] = useState(() => Math.floor(Math.random() * 100000));
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const pendingAutoStart = useRef(false);
|
||||
// BPM text field: editing stays free-form while typing; commits on
|
||||
// blur/Enter (single-note widget behavior).
|
||||
const [bpmText, setBpmText] = useState(String(phrase.bpm));
|
||||
const [lastBpm, setLastBpm] = useState(phrase.bpm);
|
||||
if (phrase.bpm !== lastBpm) {
|
||||
// React's "adjust state when a prop changes" pattern (no effect).
|
||||
setLastBpm(phrase.bpm);
|
||||
setBpmText(String(phrase.bpm));
|
||||
}
|
||||
const commitBpm = useCallback(() => {
|
||||
const v = parseInt(bpmText, 10);
|
||||
if (Number.isNaN(v)) { setBpmText(String(phrase.bpm)); return; }
|
||||
setPhrase({ bpm: Math.max(30, Math.min(180, v)) });
|
||||
}, [bpmText, phrase.bpm, setPhrase]);
|
||||
|
||||
const handleImportFile = useCallback((file: File) => {
|
||||
setImportError(null);
|
||||
@@ -489,22 +529,9 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
|
||||
</label>
|
||||
|
||||
{(phrase.material === 'melody' || phrase.material === 'scale') && (
|
||||
<>
|
||||
<label>Key
|
||||
<select value={phrase.keyTonic} onChange={e => setPhrase({ keyTonic: e.target.value })}>
|
||||
{Object.keys(TONICS).filter(t => !['C#', 'Gb', 'D#', 'G#', 'A#'].includes(t)).map(t => (
|
||||
<option key={t} value={t}>{t}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>Mode
|
||||
<select value={phrase.keyMode} onChange={e => setPhrase({ keyMode: e.target.value })}>
|
||||
{(Object.keys(MODE_LABELS) as ModeId[]).map(m => (
|
||||
<option key={m} value={m}>{MODE_LABELS[m]}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</>
|
||||
<span style={{ fontSize: '11px', opacity: 0.7, alignSelf: 'center' }}>
|
||||
Key/mode: use the "Target key" controls below the sheet — shared across modes.
|
||||
</span>
|
||||
)}
|
||||
|
||||
{phrase.material === 'melody' && (
|
||||
@@ -604,28 +631,9 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
|
||||
)}
|
||||
|
||||
{fretted && (
|
||||
<>
|
||||
<label className="phrase-check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={phrase.fretWindowEnabled}
|
||||
onChange={e => setPhrase({ fretWindowEnabled: e.target.checked })}
|
||||
/>
|
||||
Fret window
|
||||
</label>
|
||||
{phrase.fretWindowEnabled && (
|
||||
<>
|
||||
<label>Min fret
|
||||
<input type="number" min={0} max={24} value={phrase.fretMin}
|
||||
onChange={e => setPhrase({ fretMin: Math.max(0, Math.min(24, parseInt(e.target.value) || 0)) })} />
|
||||
</label>
|
||||
<label>Max fret
|
||||
<input type="number" min={0} max={24} value={phrase.fretMax}
|
||||
onChange={e => setPhrase({ fretMax: Math.max(0, Math.min(24, parseInt(e.target.value) || 0)) })} />
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
<span style={{ fontSize: '11px', opacity: 0.7, alignSelf: 'center' }}>
|
||||
Fret window: use the "Fret window" controls below the sheet — shared across modes.
|
||||
</span>
|
||||
)}
|
||||
|
||||
<label>Pace
|
||||
@@ -635,30 +643,9 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
|
||||
</select>
|
||||
</label>
|
||||
{phrase.pace === 'tempo' && (
|
||||
<label>BPM
|
||||
<div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
|
||||
<button className="control-button small" onClick={() => setPhrase({ bpm: Math.max(30, phrase.bpm - 1) })}>−</button>
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
value={bpmText}
|
||||
onChange={e => { if (/^\d{0,3}$/.test(e.target.value)) setBpmText(e.target.value); }}
|
||||
onBlur={commitBpm}
|
||||
onKeyDown={e => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }}
|
||||
style={{ width: '46px', textAlign: 'center' }}
|
||||
/>
|
||||
<button className="control-button small" onClick={() => setPhrase({ bpm: Math.min(180, phrase.bpm + 1) })}>+</button>
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
min={30}
|
||||
max={180}
|
||||
step={1}
|
||||
value={phrase.bpm}
|
||||
onChange={e => setPhrase({ bpm: Number(e.target.value) })}
|
||||
aria-label="Phrase tempo"
|
||||
/>
|
||||
</label>
|
||||
<span style={{ fontSize: '11px', opacity: 0.7, alignSelf: 'center' }}>
|
||||
Tempo (BPM): set it on the metronome in the tools below — shared across modes.
|
||||
</span>
|
||||
)}
|
||||
<label className="phrase-check">
|
||||
<input
|
||||
|
||||
233
src/components/TargetNoteControls.tsx
Normal file
233
src/components/TargetNoteControls.tsx
Normal file
@@ -0,0 +1,233 @@
|
||||
/**
|
||||
* Unified target-note controls, shared by all game modes (v2 controls).
|
||||
*
|
||||
* - Key filter: restrict target notes to a tonic+mode (independent of the
|
||||
* displayed key signature on the staff — optional sync checkbox).
|
||||
* - Strings: pick which strings contribute target notes (fretted instruments).
|
||||
* - Fret window: restrict target notes to a fret range (fretted instruments).
|
||||
*
|
||||
* In Phrase Mode the same controls bind to the shared practice filter
|
||||
* (mirrored into phrase settings), so state stays consistent across modes.
|
||||
*/
|
||||
import { useMemo } from 'react';
|
||||
import { Key, Guitar, Music } from 'lucide-react';
|
||||
import { useSettings } from '../context/useSettings';
|
||||
import { getPracticeFilter, type PracticeFilter } from '../types/SettingsTypes';
|
||||
import { MODE_LABELS, TONICS, isMode, keyFor, type ModeId } from '../music/scales';
|
||||
import { isFrettedInstrument } from '../music/playableRange';
|
||||
import { TUNINGS } from '../music/Tunings';
|
||||
|
||||
/** Conventional string names, low→high, for guitar/bass tunings. */
|
||||
const GUITAR_STRING_NAMES = ['E6', 'A5', 'D4', 'G3', 'B2', 'E1'];
|
||||
const BASS_STRING_NAMES = ['E4', 'A3', 'D2', 'G1'];
|
||||
|
||||
function stringNames(tuningId: string, count: number): string[] {
|
||||
const names = tuningId.startsWith('bass') ? BASS_STRING_NAMES : GUITAR_STRING_NAMES;
|
||||
// Align from the low end (index 0 = lowest)
|
||||
if (count === names.length) return names;
|
||||
return Array.from({ length: count }, (_, i) => {
|
||||
const midi = TUNINGS[tuningId]?.strings[i] ?? 0;
|
||||
const pc = midi % 12;
|
||||
const LETTERS = ['C', 'C#', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'Ab', 'A', 'Bb', 'B'];
|
||||
return LETTERS[pc] ?? `S${i + 1}`;
|
||||
});
|
||||
}
|
||||
|
||||
/** Display key signature names that correspond to a tonic+mode pair. */
|
||||
const MAJOR_TONIC_TO_SIGNATURE: Record<string, string> = {
|
||||
'C': 'C', 'G': 'G', 'D': 'D', 'A': 'A', 'E': 'E', 'B': 'C#', 'F#': 'C#',
|
||||
'Db': 'Db', 'Ab': 'Ab', 'Eb': 'Eb', 'Bb': 'Bb', 'F': 'F',
|
||||
};
|
||||
const MINOR_TONIC_TO_SIGNATURE: Record<string, string> = {
|
||||
'C': 'Eb', 'G': 'Bb', 'D': 'F', 'A': 'C', 'E': 'G', 'B': 'D', 'F#': 'A',
|
||||
'Db': 'Eb', 'Ab': 'Bb', 'Eb': 'Gb', 'Bb': 'Db', 'F': 'Dm',
|
||||
};
|
||||
|
||||
export const TargetNoteControls: React.FC = () => {
|
||||
const { settings, updateSettings } = useSettings();
|
||||
const pf = getPracticeFilter(settings);
|
||||
|
||||
const setFilter = (updates: Partial<PracticeFilter>) => {
|
||||
updateSettings(s => {
|
||||
const next: typeof s = { ...s, practice: { ...getPracticeFilter(s), ...updates } };
|
||||
// Optional coupling: display key signature follows the target key.
|
||||
if (updates.keyTonic !== undefined || updates.keyMode !== undefined) {
|
||||
const tonic = updates.keyTonic ?? pf.keyTonic;
|
||||
const mode = updates.keyMode ?? pf.keyMode;
|
||||
if (s.keyFollowsTarget) {
|
||||
const table = mode === 'minor' ? MINOR_TONIC_TO_SIGNATURE : MAJOR_TONIC_TO_SIGNATURE;
|
||||
const sig = table[tonic];
|
||||
if (sig) next.keySignature = sig;
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const fretted = useMemo(
|
||||
() => isFrettedInstrument(settings.instrument) && !!TUNINGS[settings.tuningId],
|
||||
[settings.instrument, settings.tuningId],
|
||||
);
|
||||
|
||||
const stringCount = TUNINGS[settings.tuningId]?.strings.length ?? 0;
|
||||
const names = stringNames(settings.tuningId, stringCount);
|
||||
|
||||
const toggleString = (index: number) => {
|
||||
const cur = pf.strings.length > 0 ? [...pf.strings] : Array.from({ length: stringCount }, (_, i) => i);
|
||||
const next = cur.includes(index) ? cur.filter(i => i !== index) : [...cur, index].sort((a, b) => a - b);
|
||||
// Deselecting all = back to "all strings" (empty array)
|
||||
setFilter({ strings: next.length === stringCount ? [] : next });
|
||||
};
|
||||
|
||||
const allSelected = pf.strings.length === 0;
|
||||
|
||||
return (
|
||||
<div className="practice-filter-grid">
|
||||
{/* Key filter */}
|
||||
<div className="control-group" style={{ gridColumn: '1 / -1' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
<label className="control-label">
|
||||
<Key size={18} />
|
||||
<span>Target key (limits notes)</span>
|
||||
</label>
|
||||
<button
|
||||
className={`switch-button ${pf.keyEnabled ? 'active' : ''}`}
|
||||
onClick={() => setFilter({ keyEnabled: !pf.keyEnabled })}
|
||||
title={pf.keyEnabled ? 'Limit to key: on' : 'Limit to key: off'}
|
||||
>
|
||||
<div className="switch-thumb" />
|
||||
</button>
|
||||
</div>
|
||||
{pf.keyEnabled && (
|
||||
<>
|
||||
<div style={{ display: 'flex', gap: '8px', marginTop: '8px' }}>
|
||||
<select
|
||||
className="control-select"
|
||||
value={pf.keyTonic}
|
||||
onChange={e => setFilter({ keyTonic: e.target.value })}
|
||||
aria-label="Target key tonic"
|
||||
>
|
||||
{Object.keys(TONICS).filter(t => !['C#', 'Gb', 'D#', 'G#', 'A#'].includes(t)).map(t => (
|
||||
<option key={t} value={t}>{t}</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
className="control-select"
|
||||
value={pf.keyMode}
|
||||
onChange={e => setFilter({ keyMode: isMode(e.target.value) ? e.target.value : 'major' })}
|
||||
aria-label="Target key mode"
|
||||
>
|
||||
{(Object.keys(MODE_LABELS) as ModeId[]).map(m => (
|
||||
<option key={m} value={m}>{MODE_LABELS[m]}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<label style={{ fontSize: '11px', display: 'flex', alignItems: 'center', gap: '6px', marginTop: '6px', opacity: 0.85 }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={settings.keyFollowsTarget ?? false}
|
||||
onChange={e => updateSettings(s => {
|
||||
const next = { ...s, keyFollowsTarget: e.target.checked };
|
||||
// When enabling sync, snap the display signature now.
|
||||
if (e.target.checked) {
|
||||
const table = pf.keyMode === 'minor' ? MINOR_TONIC_TO_SIGNATURE : MAJOR_TONIC_TO_SIGNATURE;
|
||||
const sig = table[pf.keyTonic];
|
||||
if (sig) next.keySignature = sig;
|
||||
}
|
||||
return next;
|
||||
})}
|
||||
/>
|
||||
Sync display key signature with target key
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Strings (fretted instruments) */}
|
||||
{fretted && (
|
||||
<div className="control-group" style={{ gridColumn: '1 / -1' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
<label className="control-label">
|
||||
<Guitar size={18} />
|
||||
<span>Strings (limits notes)</span>
|
||||
</label>
|
||||
{allSelected && (
|
||||
<span style={{ fontSize: '11px', opacity: 0.7 }}>all</span>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: '6px', marginTop: '8px', flexWrap: 'wrap' }}>
|
||||
{Array.from({ length: stringCount }, (_, i) => {
|
||||
const active = allSelected || pf.strings.includes(i);
|
||||
return (
|
||||
<button
|
||||
key={i}
|
||||
className={`control-button small ${active ? 'active' : ''}`}
|
||||
onClick={() => toggleString(i)}
|
||||
title={`String ${i + 1} (${names[i]})`}
|
||||
style={{ flex: '1 1 0', minWidth: '40px', padding: '6px 4px', fontSize: '11px' }}
|
||||
>
|
||||
{names[i]}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{pf.strings.length > 0 && (
|
||||
<button
|
||||
className="link-button"
|
||||
style={{ fontSize: '11px', marginTop: '6px', padding: 0 }}
|
||||
onClick={() => setFilter({ strings: [] })}
|
||||
>
|
||||
Reset to all strings
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Fret window (fretted instruments) */}
|
||||
{fretted && (
|
||||
<div className="control-group" style={{ gridColumn: '1 / -1' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
<label className="control-label">
|
||||
<Music size={18} />
|
||||
<span>Fret window (limits notes)</span>
|
||||
</label>
|
||||
<button
|
||||
className={`switch-button ${pf.fretWindowEnabled ? 'active' : ''}`}
|
||||
onClick={() => setFilter({ fretWindowEnabled: !pf.fretWindowEnabled })}
|
||||
title={pf.fretWindowEnabled ? 'Fret window: on' : 'Fret window: off'}
|
||||
>
|
||||
<div className="switch-thumb" />
|
||||
</button>
|
||||
</div>
|
||||
{pf.fretWindowEnabled && (
|
||||
<div style={{ display: 'flex', gap: '8px', marginTop: '8px', alignItems: 'center' }}>
|
||||
<div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: '4px' }}>
|
||||
<span style={{ fontSize: '12px', opacity: 0.7 }}>Min</span>
|
||||
<input
|
||||
type="number" min={0} max={24}
|
||||
className="control-input"
|
||||
style={{ width: '100%', padding: '4px' }}
|
||||
value={pf.fretMin}
|
||||
onChange={e => setFilter({ fretMin: Math.max(0, Math.min(24, parseInt(e.target.value) || 0)) })}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: '4px' }}>
|
||||
<span style={{ fontSize: '12px', opacity: 0.7 }}>Max</span>
|
||||
<input
|
||||
type="number" min={0} max={24}
|
||||
className="control-input"
|
||||
style={{ width: '100%', padding: '4px' }}
|
||||
value={pf.fretMax}
|
||||
onChange={e => setFilter({ fretMax: Math.max(pf.fretMin, Math.min(24, parseInt(e.target.value) || 0)) })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Re-export keyFor for potential external use (avoids unused-import lint)
|
||||
void keyFor;
|
||||
@@ -8,12 +8,8 @@ import {
|
||||
getRandomNote,
|
||||
getNoteDetails
|
||||
} from '../music/NoteUtils';
|
||||
import {
|
||||
TUNINGS,
|
||||
getOpenStringNotes,
|
||||
getFirstPositionNotes,
|
||||
} from '../music/Tunings';
|
||||
import { INSTRUMENT_DEFINITIONS } from '../music/InstrumentConfigs';
|
||||
import { computeTargetPool } from '../music/targetPool';
|
||||
import { getPracticeFilter } from '../types/SettingsTypes';
|
||||
import {
|
||||
NOTE_MATCH_THRESHOLD_MS,
|
||||
NOTE_MATCH_GRACE_MS,
|
||||
@@ -36,65 +32,24 @@ export const useGameLogic = (
|
||||
const [tracker] = useState(() => new MatchTracker(NOTE_MATCH_THRESHOLD_MS, NOTE_MATCH_GRACE_MS));
|
||||
|
||||
// --- Valid Notes Calculation ---
|
||||
const currentTuning = TUNINGS[settings.tuningId];
|
||||
const currentInstrumentDef = INSTRUMENT_DEFINITIONS[settings.instrument];
|
||||
|
||||
const validNotes = useMemo(() => {
|
||||
const rangeConfig = currentInstrumentDef.ranges.find(r => r.id === settings.difficulty);
|
||||
|
||||
const getNotesFromConfig = (config: typeof rangeConfig) => {
|
||||
if (!config) return [];
|
||||
|
||||
if (config.type === 'open_strings') {
|
||||
if (currentTuning) return getOpenStringNotes(currentTuning);
|
||||
return config.notes || [];
|
||||
}
|
||||
|
||||
if (config.type === 'first_position') {
|
||||
if (currentTuning) return getFirstPositionNotes(currentTuning);
|
||||
return config.notes || [];
|
||||
}
|
||||
|
||||
if (config.type === 'custom_fret') {
|
||||
if (currentTuning) {
|
||||
const minFret = settings.customMinFret ?? config.defaultMinFret ?? 0;
|
||||
const maxFret = settings.customMaxFret ?? config.defaultMaxFret ?? 12;
|
||||
const notes = new Set<number>();
|
||||
currentTuning.strings.forEach(stringMidi => {
|
||||
for (let fret = minFret; fret <= maxFret; fret++) {
|
||||
notes.add(stringMidi + fret);
|
||||
}
|
||||
const pf = getPracticeFilter(settings);
|
||||
return computeTargetPool({
|
||||
instrumentId: settings.instrument,
|
||||
difficulty: settings.difficulty,
|
||||
tuningId: settings.tuningId,
|
||||
customMinFret: settings.customMinFret,
|
||||
customMaxFret: settings.customMaxFret,
|
||||
keyEnabled: pf.keyEnabled,
|
||||
keyTonic: pf.keyTonic,
|
||||
keyMode: pf.keyMode,
|
||||
strings: pf.strings,
|
||||
fretWindowEnabled: pf.fretWindowEnabled,
|
||||
fretMin: pf.fretMin,
|
||||
fretMax: pf.fretMax,
|
||||
});
|
||||
return Array.from(notes).sort((a, b) => a - b);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
if (config.type === 'specific_string') {
|
||||
if (currentTuning && config.stringIndex !== undefined) {
|
||||
const openNote = currentTuning.strings[config.stringIndex];
|
||||
if (openNote === undefined) return [];
|
||||
const notes = [];
|
||||
for (let i = 0; i <= 12; i++) {
|
||||
notes.push(openNote + i);
|
||||
}
|
||||
return notes;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
if (config.notes) return config.notes;
|
||||
if (config.min !== undefined && config.max !== undefined) {
|
||||
return Array.from({ length: config.max - config.min + 1 }, (_, i) => config.min! + i);
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
if (rangeConfig) return getNotesFromConfig(rangeConfig);
|
||||
const fallbackRange = currentInstrumentDef.ranges[0];
|
||||
return getNotesFromConfig(fallbackRange);
|
||||
|
||||
}, [settings.difficulty, currentInstrumentDef, currentTuning, settings.customMinFret, settings.customMaxFret]);
|
||||
}, [settings]);
|
||||
|
||||
// --- Note Generation ---
|
||||
const generateNewNote = useCallback((keepFeedback = false) => {
|
||||
|
||||
110
src/music/targetPool.test.ts
Normal file
110
src/music/targetPool.test.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { computeTargetPool } from './targetPool';
|
||||
|
||||
const base = {
|
||||
instrumentId: 'guitar',
|
||||
difficulty: 'custom',
|
||||
tuningId: 'standard',
|
||||
customMinFret: 0,
|
||||
customMaxFret: 12,
|
||||
keyEnabled: false,
|
||||
keyTonic: 'C',
|
||||
keyMode: 'major',
|
||||
strings: [],
|
||||
fretWindowEnabled: false,
|
||||
fretMin: 0,
|
||||
fretMax: 4,
|
||||
};
|
||||
|
||||
describe('computeTargetPool', () => {
|
||||
it('returns the base playable range when no filters are active', () => {
|
||||
const pool = computeTargetPool(base);
|
||||
expect(pool).toContain(40); // low E
|
||||
expect(pool).toContain(64); // high e (12th fret)
|
||||
expect(pool.length).toBeGreaterThan(30);
|
||||
});
|
||||
|
||||
it('applies the fret window when enabled', () => {
|
||||
const pool = computeTargetPool({ ...base, fretWindowEnabled: true, fretMin: 0, fretMax: 4 });
|
||||
// guitar standard: open strings 40,45,50,55,59,64; window adds up to +4
|
||||
const lo = Math.min(...pool);
|
||||
const hi = Math.max(...pool);
|
||||
expect(lo).toBe(40);
|
||||
expect(hi).toBe(68); // 64 + 4
|
||||
expect(pool).toContain(59); // open g
|
||||
expect(pool).not.toContain(69);
|
||||
});
|
||||
|
||||
it('restricts to pitch classes of the key when key filter is on', () => {
|
||||
const pool = computeTargetPool({ ...base, keyEnabled: true, keyTonic: 'C', keyMode: 'major' });
|
||||
const pcs = new Set([0, 2, 4, 5, 7, 9, 11]); // C major
|
||||
for (const midi of pool) {
|
||||
expect(pcs.has(((midi % 12) + 12) % 12)).toBe(true);
|
||||
}
|
||||
// chromatic notes excluded
|
||||
expect(pool).not.toContain(61); // C# within range
|
||||
});
|
||||
|
||||
it('combines fret window and key filter', () => {
|
||||
const pool = computeTargetPool({ ...base, fretWindowEnabled: true, fretMin: 0, fretMax: 5, keyEnabled: true, keyTonic: 'E', keyMode: 'minor' });
|
||||
const pcs = new Set([4, 6, 7, 9, 11, 0, 2]); // E minor natural: E F# G A B C D
|
||||
expect(pool.length).toBeGreaterThan(0);
|
||||
for (const midi of pool) {
|
||||
expect(pcs.has(((midi % 12) + 12) % 12)).toBe(true);
|
||||
}
|
||||
// F (pc 5) and F# (pc 6 is in E minor; F natural is not) — F natural excluded
|
||||
expect(pool.some(m => ((m % 12) + 12) % 12 === 5)).toBe(false);
|
||||
});
|
||||
|
||||
it('supports modes beyond the single-note key signatures (dorian)', () => {
|
||||
const pool = computeTargetPool({ ...base, keyEnabled: true, keyTonic: 'D', keyMode: 'dorian' });
|
||||
const pcs = new Set([2, 4, 5, 7, 9, 11, 0]); // D dorian: D E F G A B C
|
||||
expect(pool.length).toBeGreaterThan(0);
|
||||
for (const midi of pool) {
|
||||
expect(pcs.has(((midi % 12) + 12) % 12)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('falls back to major for an invalid mode id', () => {
|
||||
const a = computeTargetPool({ ...base, keyEnabled: true, keyTonic: 'C', keyMode: 'major' });
|
||||
const b = computeTargetPool({ ...base, keyEnabled: true, keyTonic: 'C', keyMode: 'bogus' as string });
|
||||
expect(b).toEqual(a);
|
||||
});
|
||||
|
||||
it('returns an empty pool rather than crashing for a non-fretted window request', () => {
|
||||
const pool = computeTargetPool({ ...base, instrumentId: 'piano', fretWindowEnabled: true });
|
||||
// piano has no fret window: window is ignored, base pool returned
|
||||
expect(pool.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('computeTargetPool — string selection', () => {
|
||||
it('restricts to a single string when selected', () => {
|
||||
// String index 5 = high E (open midi 64)
|
||||
const pool = computeTargetPool({ ...base, strings: [5] });
|
||||
expect(pool).toContain(64); // open high E
|
||||
expect(pool).toContain(65); // fret 1
|
||||
expect(pool).not.toContain(45); // open A (string 1) — different string
|
||||
// all notes come from one string
|
||||
expect(pool.every(m => m >= 64)).toBe(true);
|
||||
});
|
||||
|
||||
it('combines strings + fret window', () => {
|
||||
// String index 1 (open A = 45), frets 0..2
|
||||
const pool = computeTargetPool({ ...base, strings: [1], fretWindowEnabled: true, fretMin: 0, fretMax: 2 });
|
||||
expect(pool).toEqual([45, 46, 47]);
|
||||
});
|
||||
|
||||
it('combines strings + fret window + key filter', () => {
|
||||
// Low E string (index 0), frets 0..4, C major → only natural notes in that range
|
||||
const pool = computeTargetPool({ ...base, strings: [0], fretWindowEnabled: true, fretMin: 0, fretMax: 4, keyEnabled: true, keyTonic: 'C', keyMode: 'major' });
|
||||
// Low E string frets 0-4: E(40) F(41) F#(42) G(43) G#(44); C major pcs: C D E F G A B
|
||||
expect(pool).toEqual([40, 41, 43]); // E, F, G (F#, G# excluded)
|
||||
});
|
||||
|
||||
it('treats empty strings array as all strings', () => {
|
||||
const a = computeTargetPool({ ...base, strings: [] });
|
||||
const b = computeTargetPool({ ...base, strings: [0, 1, 2, 3, 4, 5] });
|
||||
expect(a).toEqual(b);
|
||||
});
|
||||
});
|
||||
76
src/music/targetPool.ts
Normal file
76
src/music/targetPool.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Unified target-note pool: base playable range (instrument + difficulty /
|
||||
* fret window) intersected with the optional key-filter (pitch classes of a
|
||||
* tonic+mode) and the optional fret window. Shared by all game modes so the
|
||||
* controls behave identically everywhere.
|
||||
*/
|
||||
import { keyFor, type ModeId } from './scales';
|
||||
import { computePlayableNotes, isFrettedInstrument } from './playableRange';
|
||||
import { TUNINGS } from './Tunings';
|
||||
|
||||
export interface TargetPoolInput {
|
||||
readonly instrumentId: string;
|
||||
readonly difficulty: string;
|
||||
readonly tuningId: string;
|
||||
readonly customMinFret?: number;
|
||||
readonly customMaxFret?: number;
|
||||
/** Key filter (target-note key, independent of the displayed key signature). */
|
||||
readonly keyEnabled: boolean;
|
||||
readonly keyTonic: string;
|
||||
readonly keyMode: string;
|
||||
/** Selected string indices (0 = lowest). Empty = all strings. */
|
||||
readonly strings: number[];
|
||||
/** Fret window (fretted instruments only). */
|
||||
readonly fretWindowEnabled: boolean;
|
||||
readonly fretMin: number;
|
||||
readonly fretMax: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the effective target-note pool.
|
||||
*
|
||||
* Order of application:
|
||||
* 1. base playable range (instrument difficulty / custom frets)
|
||||
* 2. string selection ∩ fret window (fretted instruments only — replaces
|
||||
* the range, same semantics as Phrase Mode's fret window)
|
||||
* 3. key filter (pitch-class intersection, keeps spelling/degree data intact
|
||||
* via the same scale machinery Phrase Mode uses)
|
||||
*/
|
||||
export function computeTargetPool(input: TargetPoolInput): number[] {
|
||||
const tuning = TUNINGS[input.tuningId];
|
||||
const fretted = isFrettedInstrument(input.instrumentId) && !!tuning;
|
||||
|
||||
// 1+2: base pool with string selection and optional fret window
|
||||
let base: number[];
|
||||
if (fretted) {
|
||||
const all = tuning!.strings;
|
||||
const selected = input.strings.length > 0
|
||||
? all.filter((_, i) => input.strings.includes(i))
|
||||
: all;
|
||||
if (selected.length === 0) return [];
|
||||
const lo = input.fretWindowEnabled ? Math.max(0, Math.min(24, input.fretMin)) : 0;
|
||||
const hi = input.fretWindowEnabled ? Math.max(lo, Math.min(24, input.fretMax)) : 24;
|
||||
base = selected.flatMap(open => {
|
||||
const notes: number[] = [];
|
||||
for (let fret = lo; fret <= hi; fret++) notes.push(open + fret);
|
||||
return notes;
|
||||
}).sort((a, b) => a - b);
|
||||
} else {
|
||||
base = computePlayableNotes({
|
||||
instrumentId: input.instrumentId,
|
||||
difficulty: input.difficulty,
|
||||
tuningId: input.tuningId,
|
||||
customMinFret: input.customMinFret,
|
||||
customMaxFret: input.customMaxFret,
|
||||
});
|
||||
}
|
||||
if (!input.keyEnabled) return base;
|
||||
|
||||
// 3: key/mode pitch-class filter
|
||||
const mode: ModeId = (['major', 'minor', 'dorian', 'phrygian', 'lydian', 'mixolydian', 'locrian', 'major-pentatonic', 'minor-pentatonic'] as const).includes(input.keyMode as ModeId)
|
||||
? input.keyMode as ModeId
|
||||
: 'major';
|
||||
const key = keyFor(input.keyTonic, mode);
|
||||
const pcs = new Set(key.pitchClasses);
|
||||
return base.filter(midi => pcs.has(((midi % 12) + 12) % 12));
|
||||
}
|
||||
@@ -1,5 +1,34 @@
|
||||
export type Difficulty = string;
|
||||
|
||||
/** Unified target-note filter, shared by all game modes (v2 controls). */
|
||||
export interface PracticeFilter {
|
||||
/** Restrict target notes to pitch classes of this key/mode (null = off). */
|
||||
keyEnabled: boolean;
|
||||
keyTonic: string;
|
||||
keyMode: string; // ModeId
|
||||
/** Restrict target notes to selected strings (fretted instruments only).
|
||||
* Empty array = no restriction (all strings). Index 0 = lowest string. */
|
||||
strings: number[];
|
||||
/** Restrict target notes to a fret range (fretted instruments only). */
|
||||
fretWindowEnabled: boolean;
|
||||
fretMin: number;
|
||||
fretMax: number;
|
||||
}
|
||||
|
||||
export const DEFAULT_PRACTICE_FILTER: PracticeFilter = {
|
||||
keyEnabled: false,
|
||||
keyTonic: 'C',
|
||||
keyMode: 'major',
|
||||
strings: [],
|
||||
fretWindowEnabled: false,
|
||||
fretMin: 0,
|
||||
fretMax: 4,
|
||||
};
|
||||
|
||||
export function getPracticeFilter(s: AppSettings): PracticeFilter {
|
||||
return { ...DEFAULT_PRACTICE_FILTER, ...(s.practice ?? {}) };
|
||||
}
|
||||
|
||||
export interface RhythmSettings {
|
||||
mode: 'bpm' | 'seconds';
|
||||
bpm: number;
|
||||
@@ -68,12 +97,16 @@ export function getPhraseSettings(s: AppSettings): PhraseSettings {
|
||||
|
||||
export interface AppSettings {
|
||||
phrase?: PhraseSettings;
|
||||
/** Unified target-note filter (key + fret window), all modes. */
|
||||
practice?: PracticeFilter;
|
||||
difficulty: Difficulty;
|
||||
showHint: boolean;
|
||||
showFretboard: boolean;
|
||||
showTuningMeter: boolean;
|
||||
tuningId: string;
|
||||
keySignature: string;
|
||||
/** Keep display key signature in sync with the target-key control. */
|
||||
keyFollowsTarget?: boolean;
|
||||
instrument: string;
|
||||
rhythm: RhythmSettings;
|
||||
zenMode: boolean;
|
||||
@@ -101,6 +134,7 @@ export const DEFAULT_SETTINGS: AppSettings = {
|
||||
showTuningMeter: false,
|
||||
tuningId: 'standard',
|
||||
keySignature: 'C',
|
||||
keyFollowsTarget: false,
|
||||
instrument: 'guitar',
|
||||
rhythm: {
|
||||
mode: 'bpm',
|
||||
@@ -114,6 +148,7 @@ export const DEFAULT_SETTINGS: AppSettings = {
|
||||
zenMode: false,
|
||||
gameMode: 'sight_reading',
|
||||
phrase: DEFAULT_PHRASE_SETTINGS,
|
||||
practice: DEFAULT_PRACTICE_FILTER,
|
||||
customMinFret: 0,
|
||||
customMaxFret: 12,
|
||||
autoPlaySightReading: false,
|
||||
|
||||
Reference in New Issue
Block a user