9 Commits

Author SHA1 Message Date
OpenClaw
6253194632 Metronome sync toggle in widget, more Giuliani figures, chord pool list
- MetronomeWidget: the Phrase Mode switch now lives IN the widget as a
  Free/Sync toggle. Free = independent metronome (own clock, starts when
  toggled, with or without clicks). Sync = silent while idle, starts with
  the exercise (count-in included), pendulum mirrors the run's beats.
- Fixed double phraseBeatBus.emit (leftover from an earlier edit) that
  flipped the pendulum twice per beat — animation appeared frozen.
- Click decision unified: one sound checkbox governs both the widget and
  (in sync mode) the run's click scheduler. 'Click 1 after count-in' is
  musically the last count-in click (suppressed duplicate) — now with a
  working pendulum the offset is visible rather than confusing.
- Giuliani figures extended: p-i-m-a-m-i, p-a-p-i-m-a, a-m-i-p-i-m,
  m-i-a-m-i-m (six-note rolling/bass-skip/tremolo-adjacent figures).
- Arpeggio chord pool: togglable degree list (empty = all 7); functional
  and random progressions honor the pool; first bar draws a random chord
  from the pool.
- Tests 174/174.
2026-09-14 20:13:42 +00:00
OpenClaw
ffb94cc93f Metronome rewrite: single sound checkbox, clean click architecture
- MetronomeWidget rebuilt cleanly: ONE 'Click sound' checkbox (the earlier
  restructure left duplicated option rows behind — neither worked). Widget
  body always visible (dimmed when disarmed); toggle arms sound+pendulum.
- Click decision unified: 'sync to metronome' derives phrase clickSound
  from the widget's sound checkbox (no separate phrase click option);
  'at your pace' clicks when the metronome is armed.
- Chord selection: abwählbare Liste (arpeggioChordSelection) restricts
  progression chords; first bar draws a random chord FROM THE SELECTION
  (fixed first chord repeated the exercise identically).
- Scales: rhythm setting (quarters/eighths) shared with arpeggios;
  drill id includes rhythm to invalidate cached scores.
- Beam fix: register Beam via note.setBeam so VexFlow suppresses flags
  (eighths/16ths previously drew BOTH beam and flag).
2026-09-14 19:46:23 +00:00
OpenClaw
9dc95e3787 Metronome always-visible controls, Giuliani patterns, pool fix
- Metronome widget: BPM/slider row and pendulum always visible (dimmed
  when off); the toggle gates sound + animation only. BPM/Timer mode
  switch restored for single-note auto-advance.
- Giuliani right-hand figures as arpeggio patterns: p-i-m, p-i-m-a,
  p-a-m-i, m-a-m-i, a-m-i — cycle [root, third, fifth, octave] per figure
  with octave register shift per repetition (120-studies feel).
- Pool fix: fretted instruments without active filters now get the full
  0-12 fretboard in ALL modes (legacy difficulty ranges no longer clamp
  the pool since the Note Set dropdown was removed).
- Tests 174/174.
2026-09-14 19:20:15 +00:00
OpenClaw
263b6f6b69 Arpeggio sequences + auto-start on first note
- Sequence mode: bars (2/4/6/8) with one chord per bar, chosen by
  functional rules (I->IV/V/vi...), diatonic cycle, or random (no immediate
  repeats); deterministic via melody seed. Chord symbols per bar in the
  score model (chordSymbols) rendered above the staff via setSection.
- Rhythm: quarters or eighths (cycling up/down through the pattern).
- Single-chord mode unchanged (whole path, overflow bars if needed).
- Auto-start: 'Start on first note (no count-in)' — step pace begins the
  run as soon as the mic detects the first note; no start press needed.
- 'New' button re-rolls the progression (new seed).
- Tests 174/174.
2026-09-14 18:44:14 +00:00
OpenClaw
d76d24ab01 Arpeggio material for Phrase Mode (variant 1)
- music/arpeggioGenerator.ts: diatonic triads (I-vii*) built from the
  selected key/mode via the shared degree spelling; patterns up / down /
  up-down / 1-2-3-5; one or two octaves (cycle ends on the octave; two-
  octave path continues from the turning root). Quarter-note rhythm with
  final note extended to fill the bar; title is labeled 'Arpeggio -
  <tonic> <degree> (pattern, coverage)'.
- Settings: PhraseMaterial 'arpeggio' + arpeggioDegree/Pattern/Coverage
  (defaults I / up / one-octave).
- PhraseTrainer: material option 'Arpeggios (generated)' + Chord/Pattern/
  Coverage/Meter selects; key/mode reuse the shared Target key controls.
- Tests: 9 arpeggio cases (170 total).
2026-09-14 17:10:40 +00:00
OpenClaw
a965dde585 Click behavior per pace: continuous in step, run-synced (incl. preview) in tempo
- Step pace ('at your pace'): metronome ticks continuously when the user
  switches it on — phraseRunBus gate no longer applies (clock stays free).
- Tempo pace ('sync to metronome'): gate now covers preview too; preview
  schedules quarter-note clicks along with the notes (accented each bar)
  so the rhythm is audible while listening.
2026-09-14 16:41:49 +00:00
OpenClaw
fc8f9bfb44 Render dotted durations with visible dots (Dot modifier)
durationCode returned '4d'/'2d' codes but VexFlow only reads the base
duration for glyph/spacing — the dot must be attached explicitly via
Dot.buildAndAttach. Dotted notes rendered without dots, which read like
extra plain quarters ('five quarters in bar 2'). Now dotted notes/rests
show their dot; spacing uses the base code correctly.
2026-09-14 16:37:15 +00:00
OpenClaw
2ed1a88184 Metronome/phrase click unification: run-driven beats, gated widget
- Phrase Mode (sync to metronome): the run's scheduler is the single click
  source (with count-in); the metronome widget is muted and its pendulum
  mirrors the run's beats via the new phraseBeatBus (audio-timestamp
  scheduled). No more double clicks; clicks only while the run is active
  (phraseRunBus gates the widget's own ticking).
- Schedule entries now carry continuous beat index + accent flag (downbeats
  accented, count-in beat 1 accented).
- 'At your pace': optional click via the metronome toggle (kept explicit).
- Metronome widget: gate prop; in gated mode it listens to the beat bus
  instead of running its own scheduler.
2026-09-14 16:33:39 +00:00
OpenClaw
57a6a654a0 Feedback round 3: metronome/phrase integration, 16ths, count-in badge, wider transpose
- Metronome/phrase: 'With tempo' renamed to 'Sync to metronome' (auto-enables
  the metronome when selected); phrase click now yields to the metronome
  click (no more double clicks) with an explicit opt-out checkbox.
- Count-in: subtle numeric badge next to the status line (muted pill, 11px).
- Melody rhythm level 3 'Elaborate': sixteenth/dotted-eighth templates for
  4/4 and 3/4; renderer supports 120/360-tick codes and beams 16th pairs.
- Transpose control for library/import material widened to ±2 octaves.
- Tests 161/161 (bar-total invariants hold over 500 seeds at level 2).
2026-09-14 16:14:20 +00:00
16 changed files with 1097 additions and 185 deletions

View File

@@ -1,3 +1,4 @@
import React, { useEffect, useState } from 'react';
import { Guitar, Music, Gauge } from 'lucide-react';
import { TUNINGS, INSTRUMENT_TUNINGS } from '../music/Tunings';
import { INSTRUMENT_DEFINITIONS } from '../music/InstrumentConfigs';
@@ -5,7 +6,7 @@ import { INSTRUMENT_DEFINITIONS } from '../music/InstrumentConfigs';
import { TuningMeter } from './TuningMeter';
import { TargetNoteControls } from './TargetNoteControls';
import { MetronomeWidget } from './MetronomeWidget';
import { phraseRunBus } from '../hooks/phraseRunBus';
import { useSettings } from '../context/useSettings';
import { type Difficulty, type RhythmSettings } from '../types/SettingsTypes';
@@ -19,6 +20,10 @@ export const Controls: React.FC<ControlsProps> = ({ currentPitch }) => {
const { settings, updateSettings } = useSettings();
// Alias to minimize refactor, or just use updateSettings.
const onUpdateSettings = updateSettings;
// Phrase run gate: the metronome only ticks while the phrase trainer is
// counting in / playing (armed by the user toggle, fired by the run).
const [phraseRunActive, setPhraseRunActive] = useState(false);
useEffect(() => phraseRunBus.subscribe(setPhraseRunActive), []);
const handleTuningChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
onUpdateSettings({ ...settings, tuningId: e.target.value });
};
@@ -176,6 +181,8 @@ export const Controls: React.FC<ControlsProps> = ({ currentPitch }) => {
rhythm={settings.rhythm}
onUpdate={updateRhythm}
showAutoAdvance={!inPhraseMode}
syncMode={inPhraseMode ? 'option' : null}
gate={inPhraseMode ? phraseRunActive : null}
/>
</div>

View File

@@ -1,145 +1,191 @@
/**
* Metronome widget with a linear pendulum indicator.
* Metronome widget — always-visible tempo controls + pendulum.
*
* 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).
* Modes:
* - Plain (single-note modes): one on/off toggle arms sound + animation.
* - Sync option (Phrase Mode): the toggle switches between
* * FREE — the metronome runs independently (own clock, starts as soon
* as toggled, with or without clicks per the sound checkbox)
* * SYNC — the metronome starts with the exercise (count-in included),
* is silent while idle, and its pendulum mirrors the run's beats.
*
* Exactly ONE sound checkbox exists (here). In sync mode it governs the
* run's click scheduler too — clicks can never double.
*/
import { useEffect, useRef, useState, useCallback } from 'react';
import { useMetronome } from '../hooks/useMetronome';
import { getTempoMarking } from '../music/TempoMarkings';
import { phraseBeatBus } from '../hooks/phraseBeatBus';
import { audioEngine } from '../audio/AudioEngine';
import type { RhythmSettings } from '../types/SettingsTypes';
interface MetronomeWidgetProps {
rhythm: RhythmSettings;
/** Persist changes (bpm, active, sound). Auto-advance is single-note only. */
/** Persist changes. */
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;
/** 'option': show the sync/free toggle (Phrase Mode). null: plain on/off. */
syncMode?: 'option' | null;
/** External gate (sync mode): true while the exercise runs. */
gate?: boolean | null;
}
export const MetronomeWidget: React.FC<MetronomeWidgetProps> = ({
rhythm,
onUpdate,
showAutoAdvance = false,
onBeat,
compact = false,
syncMode = null,
gate = null,
}) => {
// 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;
if (now - lastTickRef.current < 60) return; // glitch guard
lastTickRef.current = now;
setBeatParity(beat % 2);
onBeatRef.current?.();
}, []);
const isSync = syncMode === 'option' && !!rhythm.syncToExercise;
const runActive = gate === true;
// Sync: pendulum/click only while the run is active (the run's scheduler
// is the click source; the widget's own scheduler stays off).
// Free/plain: the widget's own scheduler runs whenever armed.
const running = isSync ? runActive : rhythm.active;
const { restart } = useMetronome({
bpm: rhythm.bpm,
volume: rhythm.sound ? rhythm.volume : 0,
playing: rhythm.active,
playing: running && !isSync,
onTick: handleTick,
});
void restart;
// Sync: pendulum mirrors the phrase run's beats (audio-time scheduled).
useEffect(() => {
if (!isSync || !runActive) return;
return phraseBeatBus.subscribe((_beat, at) => {
const delay = Math.max(0, (at - audioEngine.now()) * 1000);
window.setTimeout(() => setBeatParity(p => (p + 1) % 2), delay);
});
}, [isSync, runActive]);
const beatMs = 60000 / Math.max(1, rhythm.bpm);
const armed = rhythm.active;
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
{/* Header: label + mode toggle */}
<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>
{syncMode === 'option' ? (
<button
className={`switch-button ${rhythm.syncToExercise ? 'active' : ''}`}
onClick={() => onUpdate({
syncToExercise: !rhythm.syncToExercise,
active: true, // armed in either mode; the mode decides behavior
})}
title={rhythm.syncToExercise
? 'Sync: starts with the exercise (count-in). Click while idle: off.'
: 'Free: runs independently — start/stop it yourself.'}
>
<div className="switch-thumb" />
</button>
) : (
<button
className={`switch-button ${rhythm.active ? 'active' : ''}`}
onClick={() => onUpdate({ active: !rhythm.active })}
title={rhythm.active ? 'Turn Off' : 'Turn On (sound + pendulum)'}
>
<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 */}
{/* Always visible body; dimmed when disarmed */}
<div style={{ display: 'flex', flexDirection: 'column', gap: '6px', paddingTop: '8px', borderTop: '1px solid rgba(255,255,255,0.1)', opacity: armed ? 1 : 0.5 }}>
{/* Pendulum */}
<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: 'relative',
height: compact ? 14 : 18,
borderRadius: 9,
background: 'color-mix(in srgb, var(--color-text-main) 8%, transparent)',
overflow: 'hidden',
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`,
display: armed && running ? 'block' : 'none',
}}
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>
/>
</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>
{/* BPM / Timer controls */}
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
{!compact && (
<div style={{ display: 'flex', gap: '4px', flexShrink: 0 }}>
<button
className={`control-button small ${rhythm.mode === 'bpm' ? 'active' : ''}`}
onClick={() => onUpdate({ mode: 'bpm' })}
style={{ fontSize: '10px' }}
>BPM</button>
<button
className={`control-button small ${rhythm.mode === 'seconds' ? 'active' : ''}`}
onClick={() => onUpdate({ mode: 'seconds' })}
style={{ fontSize: '10px' }}
>Timer</button>
</div>
)}
{rhythm.mode === 'bpm' ? (
<>
<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 style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<>
<span style={{ fontSize: '12px', minWidth: '32px' }}>{rhythm.seconds}s</span>
<input
type="range"
@@ -150,31 +196,37 @@ export const MetronomeWidget: React.FC<MetronomeWidgetProps> = ({
onChange={(e) => onUpdate({ seconds: Number(e.target.value) })}
style={{ flex: 1 }}
/>
</div>
</>
)}
</div>
{rhythm.mode === 'bpm' && (
<div style={{ fontSize: '11px', opacity: 0.7, textAlign: 'center' }}>
{getTempoMarking(rhythm.bpm)}
</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 />}
{/* Options row */}
<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.sound}
onChange={(e) => onUpdate({ sound: e.target.checked })}
checked={rhythm.autoAdvance}
onChange={(e) => onUpdate({ autoAdvance: e.target.checked })}
/>
Sound
Auto
</label>
</div>
) : <span />}
<label style={{ fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>
<input
type="checkbox"
checked={rhythm.sound}
onChange={(e) => onUpdate({ sound: e.target.checked })}
/>
Click sound
</label>
</div>
)}
</div>
</div>
);
};

View File

@@ -13,7 +13,7 @@
* microphone frame rate.
*/
import React, { useEffect, useRef, useState } from 'react';
import { Renderer, Stave, StaveNote, GhostNote, Accidental, Voice, Formatter, StaveConnector, Beam, StaveTie, Annotation } from 'vexflow';
import { Renderer, Stave, StaveNote, GhostNote, Accidental, Voice, Formatter, StaveConnector, Beam, StaveTie, Annotation, Dot } from 'vexflow';
import { scoreEvents, type Score } from '../score/model';
import { STEP_LETTERS, type StepLetter } from '../score/model';
import type { NoteStatus } from '../game/PhraseMatcher';
@@ -40,6 +40,7 @@ interface Fragment {
ticks: number;
isAttack: boolean;
isEighth: boolean;
isSixteenth: boolean;
staveKey: 'treble' | 'bass';
rest: boolean;
}
@@ -47,7 +48,9 @@ interface Fragment {
// Duration ticks → VexFlow duration code (subset the model guarantees).
function durationCode(ticks: number): string | null {
switch (ticks) {
case 120: return '16';
case 240: return '8';
case 360: return '8d';
case 480: return '4';
case 720: return '4d';
case 960: return '2';
@@ -162,6 +165,11 @@ export const PhraseSheetMusic: React.FC<PhraseSheetMusicProps> = ({
const ticks = fragEnd - cursor;
const code = durationCode(ticks);
if (!code) { cursor = fragEnd; continue; }
// 'd' suffix encodes a dotted duration; the visible dot is
// a modifier that must be added explicitly (VexFlow only
// reads the base duration for spacing otherwise).
const isDotted = code.endsWith('d');
const baseCode = isDotted ? code.slice(0, -1) : code;
const rest = ev.pitch === null;
const staveKey: 'treble' | 'bass' = rest
@@ -171,7 +179,7 @@ export const PhraseSheetMusic: React.FC<PhraseSheetMusicProps> = ({
let note: StaveNote;
if (rest) {
note = new StaveNote({ keys: ['b/4'], duration: `${code}r`, clef: staveKey });
note = new StaveNote({ keys: ['b/4'], duration: `${baseCode}r`, clef: staveKey });
} else {
const p = ev.pitch!;
// WRITTEN pitch for the staff: sounding midi + display
@@ -192,9 +200,10 @@ export const PhraseSheetMusic: React.FC<PhraseSheetMusicProps> = ({
measureState[stateKey] = written.alter;
note = new StaveNote({
keys: [keyString(written.step, written.alter, written.octave)],
duration: code,
duration: baseCode,
clef: staveKey,
});
if (isDotted) Dot.buildAndAttach([note]);
if (glyph) note.addModifier(new Accidental(glyph));
}
@@ -226,6 +235,7 @@ export const PhraseSheetMusic: React.FC<PhraseSheetMusicProps> = ({
ticks,
isAttack,
isEighth: code === '8' && !rest,
isSixteenth: code === '16' && !rest,
staveKey,
rest,
});
@@ -262,6 +272,14 @@ export const PhraseSheetMusic: React.FC<PhraseSheetMusicProps> = ({
if (r === 0) treble.addTimeSignature(`${score.meter.numerator}/${score.meter.denominator}`);
treble.setMeasure(measure.number);
}
// Chord symbol above the staff (bar-indexed), drawn via the
// stave's annotation area so it shifts with the clef offset.
const chordSym = score.chordSymbols?.[m];
if (chordSym) {
try {
treble.setSection(chordSym, 0);
} catch { /* courtesy label — never fatal */ }
}
let bass: Stave | null = null;
if (isGrand) {
bass = new Stave(x, y + 130, barWidth);
@@ -319,16 +337,24 @@ export const PhraseSheetMusic: React.FC<PhraseSheetMusicProps> = ({
line.setContext(context).draw();
}
// --- Beams: consecutive eighth pairs within one beat ---
const eighths = frags.filter(f => f.isEighth && f.note instanceof StaveNote);
for (let i = 0; i + 1 < eighths.length; i++) {
const a = eighths[i], b2 = eighths[i + 1];
// --- Beams: consecutive eighth/16th pairs within one beat ---
// Note: the Beam must be registered on each note via setBeam,
// otherwise VexFlow still draws flags (beam === undefined in
// shouldDrawFlag) and you get BOTH flag and beam.
const beamed = frags.filter(f => (f.isEighth || f.isSixteenth) && f.note instanceof StaveNote);
for (let i = 0; i + 1 < beamed.length; i++) {
const a = beamed[i], b2 = beamed[i + 1];
if (a.staveKey !== b2.staveKey) continue;
if (b2.start - a.start !== 240) continue;
// consecutive within the same beat, same subdivision size
const step = a.isSixteenth ? 120 : 240;
if (b2.start - a.start !== step) continue;
if ((a.ticks !== step) || (b2.ticks !== step)) continue;
const beatA = Math.floor((a.start - measureStart) / 480);
const beatB = Math.floor((b2.start - measureStart) / 480);
if (beatA === beatB) {
const beam = new Beam([a.note, b2.note], false);
a.note.setBeam(beam);
b2.note.setBeam(beam);
beam.setContext(context).draw();
}
}

View File

@@ -16,10 +16,12 @@ import { usePhraseTrainer, type PhraseTrainerApi, type PhrasePhase } from '../ho
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 { computePlayableNotes, isFrettedInstrument, positionsWithinWindow } from '../music/playableRange';
import { generateMelody } from '../music/melodyGenerator';
import { generateScaleDrill } from '../music/scaleDrills';
import { generateArpeggio, type ArpeggioDegree } from '../music/arpeggioGenerator';
import { isMode, type ModeId } from '../music/scales';
import { ARPEGGIO_DEGREE_LABELS } from '../music/arpeggioGenerator';
import { scoreEvents, type Result, type Score, type ScoreEvent } from '../score/model';
import { getNoteDetails } from '../music/NoteUtils';
import { EXERCISES, loadExercise } from '../exercises/library';
@@ -80,6 +82,16 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
// (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;
// Click decision — ONE source: the metronome widget's sound checkbox.
// - Tempo + syncToExercise: the run clicks when armed && sound
// (silent while idle; starts with the exercise incl. count-in).
// - Tempo + free metronome: the widget clicks freely; the run stays
// silent (its beats are visual only) to avoid doubling.
// - Step: widget clicks freely; phrase clickSound follows the switch.
const sync = settings.rhythm.syncToExercise;
phrase.clickSound = phrase.pace === 'tempo'
? (sync ? settings.rhythm.active && settings.rhythm.sound : false)
: settings.rhythm.active && settings.rhythm.sound;
const setPhrase = useCallback((updates: Partial<PhraseSettings>) => {
updateSettings(s => {
const next = { ...s, phrase: { ...getPhraseSettings(s), ...updates } };
@@ -100,39 +112,22 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
// ---- 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)) {
// Unified filter: strings ∩ fret window, computed identically to
// the single-note modes (full 0–12 fretboard when no filter is
// active — the legacy difficulty ranges no longer apply).
if (fretted && currentTuning) {
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);
if (selected.length === 0) return [];
const lo = pf.fretWindowEnabled ? Math.max(0, Math.min(24, pf.fretMin)) : 0;
const hi = pf.fretWindowEnabled ? Math.max(lo, Math.min(24, pf.fretMax)) : 12;
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);
}
return computePlayableNotes({
instrumentId: settings.instrument,
@@ -191,6 +186,22 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
direction: phrase.scaleDirection,
coverage: phrase.scaleCoverage,
meter: { numerator: phrase.meterNumerator, denominator: 4 },
rhythm: phrase.scaleRhythm,
}, pool);
}
if (phrase.material === 'arpeggio') {
return generateArpeggio({
keyTonic: phrase.keyTonic,
keyMode: (isMode(phrase.keyMode) ? phrase.keyMode : 'major') as ModeId,
degree: (phrase.arpeggioDegree as ArpeggioDegree) || 'I',
pattern: phrase.arpeggioPattern,
coverage: phrase.arpeggioCoverage,
meter: { numerator: phrase.meterNumerator, denominator: 4 },
bars: phrase.arpeggioBars,
progression: phrase.arpeggioProgression,
chordSelection: phrase.arpeggioChordSelection as ArpeggioDegree[],
rhythm: phrase.arpeggioRhythm,
seed: melodySeed,
}, pool);
}
if (phrase.material === 'library') {
@@ -204,7 +215,10 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
}
return null;
}, [phrase.material, phrase.keyTonic, phrase.keyMode, phrase.bars, phrase.meterNumerator,
phrase.rhythmLevel, phrase.scaleDirection, phrase.scaleCoverage, phrase.libraryId,
phrase.rhythmLevel, phrase.scaleDirection, phrase.scaleCoverage, phrase.scaleRhythm, phrase.libraryId,
phrase.arpeggioDegree, phrase.arpeggioPattern, phrase.arpeggioCoverage,
phrase.arpeggioBars, phrase.arpeggioProgression, phrase.arpeggioRhythm,
phrase.arpeggioChordSelection, melodySeed,
melodySeed, pool, importedScore]);
const fullScore: Result<Score> | null = useMemo(() => {
@@ -232,6 +246,7 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
clickSound: phrase.clickSound,
inputMode: phrase.inputMode,
previewVolume: settings.autoPlayVolume ?? 0.4,
autoStartOnNote: phrase.autoStartOnNote,
},
listening,
micError,
@@ -290,7 +305,7 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
}, [scoreOk, fixedMaterial, pool, fullScore]);
const nextAction = useCallback(() => {
if (phrase.material === 'melody') {
if (phrase.material === 'melody' || (phrase.material === 'arpeggio' && phrase.arpeggioBars > 1)) {
setMelodySeed(s => (s + 1) % 999983);
} else if (fixedMaterial && scoreOk) {
const total = fullScore!.value.measures.length;
@@ -440,6 +455,22 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
{rangeWarning && <div className="phrase-warning">{rangeWarning}</div>}
<div className="feedback-area">
{trainer.phase === 'countIn' && (
<span
className="phrase-countin"
style={{
display: 'inline-block',
minWidth: '20px',
padding: '1px 7px',
marginRight: '8px',
borderRadius: '10px',
fontSize: '11px',
opacity: 0.75,
background: 'color-mix(in srgb, var(--color-text-main) 10%, transparent)',
}}
aria-label={`Count-in: ${trainer.countInLeft} beats left`}
>{trainer.countInLeft}</span>
)}
<div className="instruction-text phrase-status">{statusText}</div>
</div>
@@ -463,7 +494,7 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
<RotateCcw size={18} />
Retry
</button>
{(phrase.material === 'melody' || fixedMaterial) && (
{(phrase.material === 'melody' || phrase.material === 'arpeggio' || fixedMaterial) && (
<button className="hint-button" onClick={nextAction} title="New melody / next bars (N)">
<SkipForward size={18} />
{phrase.material === 'melody' ? 'New' : 'Next'}
@@ -484,7 +515,7 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
<RotateCcw size={18} />
Retry
</button>
{(phrase.material === 'melody' || fixedMaterial) && (
{(phrase.material === 'melody' || phrase.material === 'arpeggio' || fixedMaterial) && (
<button className="hint-button" onClick={nextAction} title="New / Next (N)">
<SkipForward size={18} />
{phrase.material === 'melody' ? 'New' : 'Next'}
@@ -523,12 +554,13 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
<select value={phrase.material} onChange={e => setPhrase({ material: e.target.value as PhraseSettings['material'] })}>
<option value="melody">Melodies (generated)</option>
<option value="scale">Scale drills</option>
<option value="arpeggio">Arpeggios (generated)</option>
<option value="library">Exercises</option>
<option value="import">Imported file</option>
</select>
</label>
{(phrase.material === 'melody' || phrase.material === 'scale') && (
{(phrase.material === 'melody' || phrase.material === 'scale' || phrase.material === 'arpeggio') && (
<span style={{ fontSize: '11px', opacity: 0.7, alignSelf: 'center' }}>
Key/mode: use the "Target key" controls below the sheet — shared across modes.
</span>
@@ -548,9 +580,10 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
</select>
</label>
<label>Rhythm
<select value={phrase.rhythmLevel} onChange={e => setPhrase({ rhythmLevel: Number(e.target.value) === 2 ? 2 : 1 })}>
<select value={phrase.rhythmLevel} onChange={e => setPhrase({ rhythmLevel: Math.max(1, Math.min(3, Number(e.target.value))) as 1 | 2 | 3 })}>
<option value={1}>Simple</option>
<option value={2}>Mixed</option>
<option value={3}>Elaborate (16ths)</option>
</select>
</label>
</>
@@ -581,6 +614,98 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
</>
)}
{phrase.material === 'arpeggio' && (
<>
<label>Chord
<select value={phrase.arpeggioDegree} onChange={e => setPhrase({ arpeggioDegree: e.target.value, arpeggioBars: 1 })}>
{(Object.keys(ARPEGGIO_DEGREE_LABELS) as ArpeggioDegree[]).map(d => (
<option key={d} value={d}>{ARPEGGIO_DEGREE_LABELS[d]}</option>
))}
</select>
</label>
<label>Pattern
<select value={phrase.arpeggioPattern} onChange={e => setPhrase({ arpeggioPattern: e.target.value as PhraseSettings['arpeggioPattern'] })}>
<option value="up">Up</option>
<option value="down">Down</option>
<option value="updown">Up &amp; down</option>
<option value="1235">1-2-3-5</option>
<optgroup label="Giuliani studies">
<option value="giuliani-pim">p-i-m</option>
<option value="giuliani-pima">p-i-m-a</option>
<option value="giuliani-pami">p-a-m-i</option>
<option value="giuliani-mami">m-a-m-i</option>
<option value="giuliani-ami">a-m-i</option>
<option value="giuliani-pimamim">p-i-m-a-m-i</option>
<option value="giuliani-papima">p-a-p-i-m-a</option>
<option value="giuliani-amipim">a-m-i-p-i-m</option>
<option value="giuliani-miamim">m-i-a-m-i-m</option>
</optgroup>
</select>
</label>
<label>Coverage
<select value={phrase.arpeggioCoverage} onChange={e => setPhrase({ arpeggioCoverage: e.target.value as PhraseSettings['arpeggioCoverage'] })}>
<option value="one-octave">One octave</option>
<option value="two-octave">Two octaves</option>
</select>
</label>
<label>Length
<select value={phrase.arpeggioBars} onChange={e => setPhrase({ arpeggioBars: Math.max(1, Math.min(8, Number(e.target.value))) })}>
{[1, 2, 4, 6, 8].map(b => <option key={b} value={b}>{b === 1 ? 'Single chord' : `${b} bars`}</option>)}
</select>
</label>
{phrase.arpeggioBars > 1 && (
<label>Chords
<select value={phrase.arpeggioProgression} onChange={e => setPhrase({ arpeggioProgression: e.target.value as PhraseSettings['arpeggioProgression'] })}>
<option value="functional">Functional (I-IV-V...)</option>
<option value="diatonic-cycle">Diatonic cycle</option>
<option value="random">Random</option>
</select>
</label>
)}
{phrase.arpeggioBars > 1 && (
<div style={{ gridColumn: '1 / -1' }}>
<span style={{ fontSize: '11px', opacity: 0.7, display: 'block', marginBottom: '4px' }}>
Chord pool ({phrase.arpeggioChordSelection.length === 0 ? 'all 7' : `${phrase.arpeggioChordSelection.length} selected`}):
</span>
<div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
{(Object.keys(ARPEGGIO_DEGREE_LABELS) as ArpeggioDegree[]).map(d => {
const active = phrase.arpeggioChordSelection.length === 0 || phrase.arpeggioChordSelection.includes(d);
return (
<button
key={d}
className={`control-button small ${active ? 'active' : ''}`}
style={{ minWidth: '42px', padding: '5px 8px', fontSize: '12px' }}
onClick={() => {
// Toggle; empty selection = all back on.
const cur = phrase.arpeggioChordSelection.length === 0
? (Object.keys(ARPEGGIO_DEGREE_LABELS) as ArpeggioDegree[])
: [...phrase.arpeggioChordSelection as ArpeggioDegree[]];
const next = cur.includes(d) ? cur.filter(x => x !== d) : [...cur, d];
setPhrase({ arpeggioChordSelection: next });
}}
>
{ARPEGGIO_DEGREE_LABELS[d]}
</button>
);
})}
</div>
</div>
)}
<label>Rhythm
<select value={phrase.arpeggioRhythm} onChange={e => setPhrase({ arpeggioRhythm: e.target.value as PhraseSettings['arpeggioRhythm'] })}>
<option value="quarters">Quarter notes</option>
<option value="eighths">Eighth notes</option>
</select>
</label>
<label>Meter
<select value={phrase.meterNumerator} onChange={e => setPhrase({ meterNumerator: Number(e.target.value) === 3 ? 3 : 4 })}>
<option value={4}>4/4</option>
<option value={3}>3/4</option>
</select>
</label>
</>
)}
{phrase.material === 'library' && (
<label>Exercise
<select value={phrase.libraryId || EXERCISES[0].id} onChange={e => setPhrase({ libraryId: e.target.value, startBar: 1 })}>
@@ -605,11 +730,13 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
{[1, 2, 4, 6, 8].map(b => <option key={b} value={b}>{b}</option>)}
</select>
</label>
<label>Octave
<label>Transpose
<select value={octaveShift} onChange={e => setOctaveShift(Number(e.target.value))}>
<option value={-1}>-1</option>
<option value={-2}>-2 oct</option>
<option value={-1}>-1 oct</option>
<option value={0}>0</option>
<option value={1}>+1</option>
<option value={1}>+1 oct</option>
<option value={2}>+2 oct</option>
</select>
</label>
</>
@@ -637,9 +764,20 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
)}
<label>Pace
<select value={phrase.pace} onChange={e => setPhrase({ pace: e.target.value as PhraseSettings['pace'] })}>
<select
value={phrase.pace}
onChange={e => {
const pace = e.target.value as PhraseSettings['pace'];
setPhrase({ pace });
// "Sync to metronome" only makes sense with the
// metronome running — switch it on automatically.
if (pace === 'tempo' && !settings.rhythm.active) {
setSettings(s => ({ ...s, rhythm: { ...s.rhythm, active: true } }));
}
}}
>
<option value="step">At your pace</option>
<option value="tempo">With tempo</option>
<option value="tempo">Sync to metronome</option>
</select>
</label>
{phrase.pace === 'tempo' && (
@@ -656,14 +794,9 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
Virtual input only
</label>
{phrase.pace === 'tempo' && (
<label className="phrase-check">
<input
type="checkbox"
checked={phrase.clickSound}
onChange={e => setPhrase({ clickSound: e.target.checked })}
/>
Click sound
</label>
<span style={{ fontSize: '11px', opacity: 0.7, alignSelf: 'center' }}>
Clicks: use the metronome's "Click sound" checkbox (with count-in, synced).
</span>
)}
<label className="phrase-check">
<input
@@ -673,9 +806,17 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
/>
Auto-continue
</label>
<label className="phrase-check">
<input
type="checkbox"
checked={phrase.autoStartOnNote}
onChange={e => setPhrase({ autoStartOnNote: e.target.checked })}
/>
Start on first note (no count-in)
</label>
</div>
{phrase.pace === 'tempo' && phrase.clickSound && (
<p className="phrase-note">Clicks are short noise bursts, not pitched tones — but speaker bleed can still disturb the microphone. Headphones recommended.</p>
{phrase.pace === 'tempo' && (
<p className="phrase-note">The run clicks a full count-in bar, then one click per beat. The metronome pendulum mirrors these beats — set the tempo on the metronome tool.</p>
)}
<p className="phrase-note">
Matching checks pitch, not fingering — several fretboard positions produce the same pitch.

View File

@@ -16,6 +16,7 @@ export interface ScheduleEntry {
readonly at: number;
/** Beat number within the count-in (count-in-beat only). */
readonly beat?: number;
readonly accent?: boolean;
/** Event index (note-end only). */
readonly index?: number;
}
@@ -41,7 +42,7 @@ export function buildSchedule(score: Score, bpm: number, startAt: number, countI
const entries: ScheduleEntry[] = [];
for (let i = 0; i < countInBeats; i++) {
entries.push({ kind: 'count-in-beat', at: startAt + i * spb, beat: i });
entries.push({ kind: 'count-in-beat', at: startAt + i * spb, beat: i, accent: i === 0 });
}
const scoreStart = startAt + countInBeats * spb;
@@ -53,7 +54,7 @@ export function buildSchedule(score: Score, bpm: number, startAt: number, countI
const barTicks = score.meter.numerator * PPQ;
for (let i = 0; i < beatCount; i++) {
const tick = i * PPQ;
entries.push({ kind: 'beat', at: scoreStart + (tick / PPQ) * spb, beat: (tick % barTicks === 0) ? i : undefined, index: i });
entries.push({ kind: 'beat', at: scoreStart + (tick / PPQ) * spb, beat: i, accent: tick % barTicks === 0, index: i });
}
scoreEvents(score).forEach((e, i) => {

View File

@@ -0,0 +1,21 @@
/**
* Beat clock shared between the phrase trainer's scheduler and the global
* metronome widget. The phrase run emits every beat (count-in + score beats)
* here; the metronome widget mirrors them on its pendulum so the visual
* stays in sync with the audible phrase click. Beats carry an absolute
* AudioContext timestamp so the widget can schedule the visual swing at the
* right moment even when callbacks fire ahead of time.
*/
type BeatListener = (beat: number, at: number) => void;
const listeners = new Set<BeatListener>();
export const phraseBeatBus = {
emit(beat: number, at: number): void {
listeners.forEach(l => l(beat, at));
},
subscribe(l: BeatListener): () => void {
listeners.add(l);
return () => { listeners.delete(l); };
},
};

26
src/hooks/phraseRunBus.ts Normal file
View File

@@ -0,0 +1,26 @@
/**
* Tiny pub/sub for the phrase trainer's running state.
*
* Lets the (global) metronome widget gate its pendulum/click on the phrase
* run: in Phrase Mode the metronome should only be active while the trainer
* is counting in or playing, not while idle.
*/
type Listener = (running: boolean) => void;
const listeners = new Set<Listener>();
let running = false;
export const phraseRunBus = {
set(v: boolean): void {
if (v === running) return;
running = v;
listeners.forEach(l => l(v));
},
get(): boolean {
return running;
},
subscribe(l: Listener): () => void {
listeners.add(l);
return () => { listeners.delete(l); };
},
};

View File

@@ -18,6 +18,8 @@ import { buildSchedule, sanitizeBpm, type ScheduleEntry } from '../game/PhraseTr
import { PPQ } from '../score/model';
import { audioEngine } from '../audio/AudioEngine';
import { subscribeRawFrames } from './rawFrameBus';
import { phraseRunBus } from './phraseRunBus';
import { phraseBeatBus } from './phraseBeatBus';
export type PhrasePhase = 'ready' | 'countIn' | 'playing' | 'paused' | 'preview' | 'done';
@@ -32,6 +34,9 @@ export interface PhraseTrainerConfig {
readonly clickSound: boolean;
readonly inputMode: 'mic' | 'virtual';
readonly previewVolume?: number;
/** Auto-start: begin without count-in as soon as the mic detects the
* first note (step pace only — tempo needs the scheduled clock). */
readonly autoStartOnNote?: boolean;
}
export interface PhraseSummary {
@@ -118,6 +123,12 @@ export function usePhraseTrainer(
const setPhaseBoth = useCallback((p: PhrasePhase) => {
phaseRef.current = p;
setPhase(p);
// Gate the shared metronome only in 'sync to metronome' (tempo) pace:
// there the run owns the clock (clicks during count-in/playing only).
// In 'at your pace' (step) the metronome ticks continuously when the
// user has it switched on — like the single-note modes.
const ownsClock = paceRef.current === 'tempo';
phraseRunBus.set(ownsClock && (p === 'countIn' || p === 'playing' || p === 'preview'));
}, []);
useEffect(() => { paceRef.current = config.pace; }, [config.pace]);
@@ -197,7 +208,12 @@ export function usePhraseTrainer(
countInBeatsRef.current > 0 &&
e.at <= scoreStartRef.current + 0.02;
if ((e.kind === 'count-in-beat' || e.kind === 'beat') && !isRedundantDownbeat && configRef.current.clickSound) {
audioEngine.playClickAt(e.at, CLICK_VOLUME, e.kind === 'count-in-beat' ? e.beat === 0 : e.beat !== undefined);
audioEngine.playClickAt(e.at, CLICK_VOLUME, e.kind === 'count-in-beat' ? e.beat === 0 : e.accent === true);
}
// Publish every beat to the shared bus so the metronome widget's
// pendulum stays in sync with the run (click or no click).
if (e.kind === 'count-in-beat' || e.kind === 'beat') {
phraseBeatBus.emit(e.beat ?? 0, e.at);
}
clickIdxRef.current++;
}
@@ -264,7 +280,18 @@ export function usePhraseTrainer(
const unsubscribe = subscribeRawFrames(frame => {
if (configRef.current.inputMode !== 'mic') return;
const p = phaseRef.current;
if (p !== 'countIn' && p !== 'playing') return;
// Auto-start: first detected note begins the run immediately
// (no count-in) — only in step pace, only from 'ready', mic only.
if (
p === 'ready' &&
configRef.current.autoStartOnNote &&
paceRef.current === 'step'
) {
startRef.current?.();
// Fall through: this frame feeds the fresh run below.
}
const p2 = phaseRef.current;
if (p2 !== 'countIn' && p2 !== 'playing') return;
// Pitched speaker output (preview, virtual instruments) must not
// be scored; while audible the matcher sees no frames at all.
if (audioEngine.isAudible()) return;
@@ -478,6 +505,15 @@ export function usePhraseTrainer(
if (!e.pitch) continue;
audioEngine.scheduleNote(e.pitch.midi, t0 + (e.startTick / PPQ) * spb, (e.durationTicks / PPQ) * spb, vol, PREVIEW_GROUP);
}
// Tempo pace: click along with the preview so the rhythm is
// audible while listening (quarter beats over the full span).
if (paceRef.current === 'tempo' && configRef.current.clickSound) {
const totalTicks = events.reduce((a, e) => Math.max(a, e.startTick + e.durationTicks), 0);
const beats = Math.floor(totalTicks / PPQ);
for (let i = 0; i < beats; i++) {
audioEngine.playClickAt(t0 + i * spb, CLICK_VOLUME, i % 4 === 0);
}
}
setPhaseBoth('preview');
const totalSec = (events.reduce((a, e) => Math.max(a, e.startTick + e.durationTicks), 0) / PPQ) * spb;
previewTimerRef.current = setTimeout(() => {

View File

@@ -0,0 +1,138 @@
import { describe, it, expect } from 'vitest';
import { generateArpeggio } from './arpeggioGenerator';
import { scoreEvents, validateScore } from '../score/model';
const strings = [40, 45, 50, 55, 59, 64];
const pool: number[] = [];
for (const open of strings) for (let f = 0; f <= 12; f++) pool.push(open + f);
const base = {
keyTonic: 'C',
keyMode: 'major' as const,
meter: { numerator: 4 as const, denominator: 4 as const },
};
describe('generateArpeggio', () => {
it('builds a C major arpeggio (up, one octave) from the pool', () => {
const r = generateArpeggio({ ...base, degree: 'I', pattern: 'up', coverage: 'one-octave' }, pool);
expect(r.ok).toBe(true);
if (!r.ok) return;
const ev = scoreEvents(r.value);
// C-E-G-C: 4 notes, quarter each (plus final extension)
const midis = ev.map(e => e.pitch!.midi);
expect(midis).toEqual([48, 52, 55, 60]);
expect(validateScore(r.value)).toEqual([]);
expect(r.value.title).toContain('Arpeggio');
expect(r.value.title).toContain('C I');
});
it('down pattern reverses the ascending cycle', () => {
const r = generateArpeggio({ ...base, degree: 'I', pattern: 'down', coverage: 'one-octave' }, pool);
expect(r.ok).toBe(true);
if (!r.ok) return;
const midis = scoreEvents(r.value).map(e => e.pitch!.midi);
expect(midis).toEqual([60, 55, 52, 48]);
});
it('updown returns to the starting root without duplicating the top', () => {
const r = generateArpeggio({ ...base, degree: 'I', pattern: 'updown', coverage: 'one-octave' }, pool);
expect(r.ok).toBe(true);
if (!r.ok) return;
const midis = scoreEvents(r.value).map(e => e.pitch!.midi);
// ascend C-E-G-C then descend back to C; only one C5 (turning point)
expect(midis).toEqual([48, 52, 55, 60, 55, 52, 48]);
expect(midis.filter(m => m === 60)).toHaveLength(1);
});
it('1235 pattern ends on the octave of the root', () => {
const r = generateArpeggio({ ...base, degree: 'I', pattern: '1235', coverage: 'one-octave' }, pool);
expect(r.ok).toBe(true);
if (!r.ok) return;
const midis = scoreEvents(r.value).map(e => e.pitch!.midi);
expect(midis).toEqual([48, 52, 55, 60]);
});
it('two-octave coverage spans 12 semitones beyond the first cycle', () => {
const r = generateArpeggio({ ...base, degree: 'I', pattern: 'up', coverage: 'two-octave' }, pool);
expect(r.ok).toBe(true);
if (!r.ok) return;
const midis = scoreEvents(r.value).map(e => e.pitch!.midi);
expect(midis).toEqual([48, 52, 55, 60, 64, 67, 72]);
});
it('spells the dominant triad G-B-D in C major', () => {
const r = generateArpeggio({ ...base, degree: 'V', pattern: 'up', coverage: 'one-octave' }, pool);
expect(r.ok).toBe(true);
if (!r.ok) return;
const pcs = scoreEvents(r.value).map(e => e.pitch!.midi % 12);
expect(pcs).toEqual([7, 11, 2, 7]); // G B D G
});
it('spells the leading-tone dim triad B-D-F in C major', () => {
const r = generateArpeggio({ ...base, degree: 'vii0', pattern: 'up', coverage: 'one-octave' }, pool);
expect(r.ok).toBe(true);
if (!r.ok) return;
const pcs = scoreEvents(r.value).map(e => e.pitch!.midi % 12);
expect(pcs).toEqual([11, 2, 5, 11]); // B D F B
});
it('fails cleanly when the pool cannot fit a full triad cycle', () => {
// Only frets 0-1 on all strings: no complete C-E-G cycle with octave
const tiny: number[] = [];
for (const open of strings) for (let f = 0; f <= 1; f++) tiny.push(open + f);
const r = generateArpeggio({ ...base, degree: 'I', pattern: 'up', coverage: 'one-octave' }, tiny);
expect(r.ok).toBe(false);
});
it('is deterministic for identical configs', () => {
const a = generateArpeggio({ ...base, degree: 'IV', pattern: 'updown', coverage: 'one-octave' }, pool);
const b = generateArpeggio({ ...base, degree: 'IV', pattern: 'updown', coverage: 'one-octave' }, pool);
expect(a).toEqual(b);
});
});
describe('generateArpeggio — sequence mode', () => {
it('generates one chord per bar with functional progression', () => {
const r = generateArpeggio({ ...base, degree: 'I', pattern: 'up', coverage: 'one-octave', bars: 4, progression: 'functional', seed: 7 }, pool);
expect(r.ok).toBe(true);
if (!r.ok) return;
expect(r.value.measures.length).toBe(4);
expect(r.value.chordSymbols?.length).toBe(4);
expect(r.value.chordSymbols?.[0]).toBe('C'); // starts on I
// bar boundaries: each bar starts on a chord root? (not enforced) — but ticks align
const ev = scoreEvents(r.value);
expect(validateScore(r.value)).toEqual([]);
// 4 beats per bar × 4 bars = 16 notes in quarters mode
expect(ev.length).toBe(16);
// deterministic
const r2 = generateArpeggio({ ...base, degree: 'I', pattern: 'up', coverage: 'one-octave', bars: 4, progression: 'functional', seed: 7 }, pool);
expect(r2.ok && JSON.stringify(scoreEvents(r2.value)) === JSON.stringify(ev)).toBe(true);
});
it('diatonic cycle walks I ii iii IV V vi vii', () => {
const r = generateArpeggio({ ...base, degree: 'I', pattern: 'up', coverage: 'one-octave', bars: 7, progression: 'diatonic-cycle', seed: 1 }, pool);
expect(r.ok).toBe(true);
if (!r.ok) return;
const syms = r.value.chordSymbols!;
expect(syms).toEqual(['C', 'Dm', 'Em', 'F', 'G', 'Am', 'Bdim']);
});
it('eighths rhythm doubles notes per bar', () => {
const r = generateArpeggio({ ...base, degree: 'I', pattern: 'up', coverage: 'one-octave', bars: 2, progression: 'functional', rhythm: 'eighths', seed: 3 }, pool);
expect(r.ok).toBe(true);
if (!r.ok) return;
const ev = scoreEvents(r.value);
expect(ev.length).toBe(16); // 2 bars × 4 beats × 2
expect(ev[0].durationTicks).toBe(240);
expect(validateScore(r.value)).toEqual([]);
});
it('random avoids repeating the same chord back-to-back', () => {
const r = generateArpeggio({ ...base, degree: 'I', pattern: 'up', coverage: 'one-octave', bars: 6, progression: 'random', seed: 11 }, pool);
expect(r.ok).toBe(true);
if (!r.ok) return;
const syms = r.value.chordSymbols!;
for (let i = 1; i < syms.length; i++) {
expect(syms[i]).not.toBe(syms[i - 1]);
}
});
});

View File

@@ -0,0 +1,378 @@
/**
* Arpeggio generator (Phrase Mode material).
*
* Diatonic triads (I, ii, iii, IV, V, vi, vii°) built from the selected
* key/mode; each practice run arpeggiates ONE chord — the user picks the
* degree, the pattern (up / down / up-down / 1-2-3-5) and the coverage
* (one or two octaves). Chord tones are spelled via the key's degree
* spelling (same machinery as melody/scale generators), so spelling and
* validation match the Phrase Mode invariants exactly.
*/
import { PPQ, validateScore, type Result, type Score, type ScoreEvent } from '../score/model';
import { keyFor, type KeyContext, type ModeId } from './scales';
import { STEP_LETTERS, LETTER_PC, type StepLetter } from '../score/model';
import { makeRng } from './melodyGenerator';
export type ArpeggioDegree = 'I' | 'ii' | 'iii' | 'IV' | 'V' | 'vi' | 'vii0';
export type ArpeggioPattern =
| 'up' | 'down' | 'updown' | '1235'
// Giuliani-style right-hand figures over one chord (indices into the
// chord cycle per note; 1=root 2=third 3=fifth 4=octave):
| 'giuliani-pim' // root-third-fifth (p-i-m)
| 'giuliani-pima' // root-third-fifth-octave (p-i-m-a)
| 'giuliani-pami' // root-octave-fifth-third (p-a-m-i)
| 'giuliani-mami' // third-fifth-octave-third (inner-voice feel)
| 'giuliani-ami' // octave-fifth-third (descending from the top)
| 'giuliani-pimamim' // p-i-m-a-m-i (six-note rolling figure)
| 'giuliani-papima' // p-a-p-i-m-a (bass-skip pattern)
| 'giuliani-amipim' // a-m-i-p-i-m (tremolo-adjacent)
| 'giuliani-miamim'; // m-i-a-m-i-m (triple-string figure)
export type ArpeggioCoverage = 'one-octave' | 'two-octave';
/** How the chord per bar is chosen in sequence mode. */
export type ArpeggioProgression = 'random' | 'functional' | 'diatonic-cycle';
/** Rhythm density for arpeggio sequences. */
export type ArpeggioRhythm = 'quarters' | 'eighths';
export interface ArpeggioConfig {
readonly keyTonic: string;
readonly keyMode: ModeId;
readonly degree: ArpeggioDegree;
readonly pattern: ArpeggioPattern;
readonly coverage: ArpeggioCoverage;
readonly meter: { readonly numerator: 3 | 4; readonly denominator: 4 };
/** Sequence mode: bars > 1 with chord progression selection. */
readonly bars?: number;
readonly progression?: ArpeggioProgression;
readonly rhythm?: ArpeggioRhythm;
/** Restrict progression chords to these degrees (empty = all 7).
* The first bar always uses `degree` if it is in the selection. */
readonly chordSelection?: readonly ArpeggioDegree[];
/** Seed for progression selection (deterministic). */
readonly seed?: number;
}
/** Degree index (0-based) into the scale for each arpeggio degree label. */
const DEGREE_INDEX: Record<ArpeggioDegree, number> = {
I: 0, ii: 1, iii: 2, IV: 3, V: 4, vi: 5, 'vii0': 6,
};
export const ARPEGGIO_DEGREE_LABELS: Record<ArpeggioDegree, string> = {
I: 'I', ii: 'ii', iii: 'iii', IV: 'IV', V: 'V', vi: 'vi', 'vii0': 'vii°',
};
export const PATTERN_LABELS: Record<ArpeggioPattern, string> = {
up: 'Up', down: 'Down', updown: 'Up & down', '1235': '1-2-3-5',
'giuliani-pim': 'Giuliani p-i-m',
'giuliani-pima': 'Giuliani p-i-m-a',
'giuliani-pami': 'Giuliani p-a-m-i',
'giuliani-mami': 'Giuliani m-a-m-i',
'giuliani-ami': 'Giuliani a-m-i',
'giuliani-pimamim': 'Giuliani p-i-m-a-m-i',
'giuliani-papima': 'Giuliani p-a-p-i-m-a',
'giuliani-amipim': 'Giuliani a-m-i-p-i-m',
'giuliani-miamim': 'Giuliani m-i-a-m-i-m',
};
/**
* Giuliani figures: chord-cycle index per note (0=root 1=third 2=fifth
* 3=octave). Each figure repeats with an octave register shift per
* repetition, mirroring the p-i-m-a feel of the 120 right-hand studies.
*/
const GIULIANI_FIGURES: Record<string, number[]> = {
'giuliani-pim': [0, 1, 2],
'giuliani-pima': [0, 1, 2, 3],
'giuliani-pami': [0, 3, 2, 1],
'giuliani-mami': [1, 2, 3, 1],
'giuliani-ami': [3, 2, 1],
'giuliani-pimamim': [0, 1, 2, 3, 2, 1],
'giuliani-papima': [0, 3, 0, 1, 2, 3],
'giuliani-amipim': [3, 2, 1, 0, 1, 2],
'giuliani-miamim': [2, 1, 3, 2, 1, 2],
};
/** pc of a spelled degree (step letter + alter). */
const degreePc = (d: { step: StepLetter; alter: number }): number =>
(LETTER_PC[STEP_LETTERS.indexOf(d.step)] + d.alter + 144) % 12;
/** Chord symbol name for a diatonic degree, e.g. "C", "Am", "Bdim". */
function chordNameFor(key: KeyContext, degreeIndex: number): string {
const d = key.degrees[degreeIndex];
const third = key.degrees[(degreeIndex + 2) % 7];
const fifth = key.degrees[(degreeIndex + 4) % 7];
const root = d.step + (d.alter < 0 ? 'b'.repeat(-d.alter) : '#'.repeat(d.alter));
const thirdInterval = (degreePc(third) - degreePc(d) + 12) % 12;
const fifthInterval = (degreePc(fifth) - degreePc(d) + 12) % 12;
let suffix = '';
if (thirdInterval === 3 && fifthInterval === 7) suffix = 'm';
else if (thirdInterval === 3 && fifthInterval === 6) suffix = 'dim';
return root + suffix;
}
/**
* Chord-tone midi notes of the diatonic triad on `degreeIndex` (0-based),
* intersected with the playable pool, ascending.
*/
function chordTonesInPool(key: KeyContext, degreeIndex: number, pool: number[]): number[] {
const steps = [0, 2, 4].map(offset => (degreeIndex + offset) % 7);
const pcs = new Set(steps.map(i => degreePc(key.degrees[i])));
return pool.filter(midi => pcs.has(((midi % 12) + 12) % 12));
}
/** Spelling (step, alter) for a midi note in the key — via scale degrees. */
function spellInKey(key: KeyContext, midi: number): { step: StepLetter; alter: number; octave: number } | null {
const pc = ((midi % 12) + 12) % 12;
const d = key.degrees.find(deg => degreePc(deg) === pc);
if (!d) return null;
const octave = (midi - pc) / 12 - 1;
return { step: d.step, alter: d.alter, octave };
}
/**
* Build the arpeggio path: chord tones ascending from the lowest available
* root (degree tone) that allows a full one/two-octave cycle in the pool.
* Pattern up/down/updown/1235 is applied to one octave cycle.
*/
function buildPath(key: KeyContext, degreeIndex: number, pool: number[], coverage: ArpeggioCoverage, pattern: ArpeggioPattern): number[] | null {
const tones = chordTonesInPool(key, degreeIndex, pool);
if (tones.length < 3) return null; // need at least one full triad
const rootPc = degreePc(key.degrees[degreeIndex]);
const octaveCycle = (startMidi: number): number[] => {
// chord tones >= startMidi within one octave, INCLUDING the octave
// of the root (an arpeggio cycle conventionally ends on the octave)
const cycle: number[] = [];
for (const midi of tones) {
if (midi >= startMidi && midi <= startMidi + 12) cycle.push(midi);
}
if (!cycle.includes(startMidi + 12) && pool.includes(startMidi + 12)) {
cycle.push(startMidi + 12);
}
return cycle.sort((a, b) => a - b);
};
const cycles: number[][] = [];
// candidate roots: chord-tone midis with pc == rootPc, ascending
const roots = tones.filter(m => ((m % 12) + 12) % 12 === rootPc);
const octavesWanted = coverage === 'one-octave' ? 1 : 2;
for (const root of roots) {
const first = octaveCycle(root);
if (first.length < 3 || first[0] !== root) continue;
// second octave: tones one octave above `root`
const second = first.map(m => m + 12).filter(m => pool.includes(m));
if (octavesWanted === 2 && second.length < 4) continue;
cycles.push(first);
break; // lowest fitting root
}
if (cycles.length === 0) return null;
const base = cycles[0];
const up = octavesWanted === 2
// base already ends on the octave of the root — the second octave
// continues from there (drop the duplicated turning root)
? [...base, ...base.map(m => m + 12).slice(1)]
: base;
switch (pattern) {
case 'up': return up;
case 'down': return [...up].reverse();
case 'updown': {
// ascend then descend, dropping the duplicated turning note
const desc = [...up].reverse().slice(1);
return [...up, ...desc];
}
case '1235': {
// root, third, fifth, octave (of the root) — repeated per octave
const path: number[] = [];
for (let oct = 0; oct < octavesWanted; oct++) {
path.push(base[0] + 12 * oct);
path.push(base[1] + 12 * oct);
path.push(base[2] + 12 * oct);
path.push(base[0] + 12 * (oct + 1));
}
return path;
}
default: {
// Giuliani figure: cycle [root, third, fifth, octave] with the
// figure selecting cycle positions per note; the octave wraps so
// e.g. p-i-m over C-E-G becomes C E G | C' E' G' ... (ascending
// octave register shift every figure repetition).
const figure = GIULIANI_FIGURES[pattern];
// 4-note cycle per octave: root, third, fifth, octave
const cycleOct = (oct: number): number[] => [
base[0] + 12 * oct, base[1] + 12 * oct, base[2] + 12 * oct, base[0] + 12 * (oct + 1),
];
const path: number[] = [];
for (let oct = 0; oct < octavesWanted; oct++) {
const c = cycleOct(oct);
for (const idx of figure) {
const note = c[idx];
if (note !== undefined && (oct === 0 || pool.includes(note))) path.push(note);
}
}
return path;
}
}
}
export function generateArpeggio(
config: ArpeggioConfig,
eligiblePitches: number[],
): Result<Score> {
const key = keyFor(config.keyTonic, config.keyMode);
const pool = Array.from(new Set(eligiblePitches.filter(m => Number.isInteger(m)))).sort((a, b) => a - b);
if (pool.length === 0) return { ok: false, error: 'No playable notes in the selected range — widen the note set.' };
const bars = config.bars ?? 1;
const pattern = config.pattern;
const coverage = config.coverage;
// ---- Chord sequence ----------------------------------------------------
// Single-bar mode: the chosen degree for all bars (bars is 1).
// Sequence mode: one chord per bar, chosen by progression rule.
const degreeIndices: number[] = [];
// Sequence chord pool: user selection (restricted to it) or all 7.
const sel = (config.chordSelection ?? []).filter(d => d in DEGREE_INDEX).map(d => DEGREE_INDEX[d as ArpeggioDegree]);
const pool7 = sel.length > 0 ? Array.from(new Set(sel)).sort((a, b) => a - b) : [0, 1, 2, 3, 4, 5, 6];
if (bars === 1) {
degreeIndices.push(DEGREE_INDEX[config.degree]);
} else {
const rng = makeRng(config.seed ?? 1);
const pick = <T,>(arr: T[]): T => arr[Math.floor(rng() * arr.length)];
for (let b = 0; b < bars; b++) {
if (b === 0) {
// First bar: a random chord FROM THE SELECTION — fixed starts
// repeated the exercise identically every time.
degreeIndices.push(pool7.includes(DEGREE_INDEX[config.degree]) && rng() < 0.34
? DEGREE_INDEX[config.degree]
: pick(pool7));
continue;
}
const prev = degreeIndices[b - 1];
if (config.progression === 'diatonic-cycle') {
// Next diatonic degree that is also in the selection
let next = (prev + 1) % 7;
for (let tries = 0; tries < 7 && !pool7.includes(next); tries++) next = (next + 1) % 7;
degreeIndices.push(next);
} else if (config.progression === 'functional') {
// Simple tonal function rules (major-oriented; mirrored for
// minor by degree relationships below):
// I -> {IV, V, vi}
// ii -> {V}
// iii -> {IV, vi}
// IV -> {I, V}
// V -> {I, vi}
// vi -> {ii, IV}
// vii -> {I}
const NEXT: Record<number, number[]> = {
0: [3, 4, 5],
1: [4],
2: [3, 5],
3: [0, 4],
4: [0, 5],
5: [1, 3],
6: [0],
};
// functional: honor the selection — filter rule targets by it
const targets = (NEXT[prev] ?? [0]).filter(d => pool7.includes(d));
degreeIndices.push(pick(targets.length > 0 ? targets : pool7.filter(d => d !== prev)));
} else {
// random: any selected degree, avoid immediate repetition
const candidates = pool7.filter(d => d !== prev);
degreeIndices.push(pick(candidates.length > 0 ? candidates : pool7));
}
}
}
// ---- Path per bar: one arpeggio cycle per chord -------------------------
const full = config.meter.numerator * PPQ;
const perBarSegments: { path: number[]; degreeIndex: number }[] = [];
for (const di of degreeIndices) {
const path = buildPath(key, di, pool, coverage, pattern);
if (!path || path.length === 0) {
return {
ok: false,
error: 'The arpeggio does not fit the playable range — widen the range (strings/fret window) or pick another degree.',
};
}
perBarSegments.push({ path, degreeIndex: di });
}
// ---- Events: fit each segment into one bar ------------------------------
const rhythm = config.rhythm ?? 'quarters';
const events: ScoreEvent[] = [];
const chordSymbols: (string | null)[] = [];
let cursor = 0;
for (let b = 0; b < bars; b++) {
const { path, degreeIndex } = perBarSegments[b];
chordSymbols.push(chordNameFor(key, degreeIndex));
if (bars === 1) {
// Single-bar mode (v1 behavior): whole path, final note extended
// to fill the bar — or, when the path overflows one bar, spread
// over the needed bars with the overflow in the last note.
const barCount = Math.max(1, Math.ceil((path.length * PPQ) / full));
const totalTicks = barCount * full;
const lastDuration = PPQ + (totalTicks - path.length * PPQ);
path.forEach((midi, n) => {
const spelled = spellInKey(key, midi);
if (!spelled) return;
const dur = n === path.length - 1 ? lastDuration : PPQ;
events.push({ id: `a${b}-${n}`, startTick: cursor, durationTicks: dur, pitch: { midi, ...spelled } });
cursor += dur;
});
continue;
}
// Sequence mode: fit the bar exactly. 'quarters': one note per beat,
// cycling up/down through the path. 'eighths': two notes per beat.
const slots = rhythm === 'quarters' ? 1 : 2;
const notesPerBar = config.meter.numerator * slots;
const line: number[] = [];
let dir = 1;
let lastIdx = 0;
while (line.length < notesPerBar) {
line.push(path[lastIdx]);
if (lastIdx + dir < 0 || lastIdx + dir >= path.length) dir = -dir;
else lastIdx += dir;
}
const noteDur = full / notesPerBar;
line.forEach((midi, n) => {
const spelled = spellInKey(key, midi);
if (!spelled) return;
events.push({
id: `a${b}-${n}`,
startTick: cursor,
durationTicks: noteDur,
pitch: { midi, ...spelled },
});
cursor += noteDur;
});
}
const chordName = `${key.tonic} ${ARPEGGIO_DEGREE_LABELS[config.degree]}`;
const patternLabel = PATTERN_LABELS[config.pattern];
// Single-bar paths can overflow into extra bars (updown/two-octave);
// sequence mode always has exactly `bars` measures.
const totalMeasures = bars === 1 ? Math.max(1, Math.ceil((cursor) / full)) : bars;
const title = bars === 1
? `Arpeggio — ${chordName} (${patternLabel}, ${coverage})`
: `Arpeggio — ${key.tonic}: ${bars} bars (${config.progression ?? 'functional'})`;
const score: Score = {
version: 1,
id: `arpeggio-${config.keyTonic}-${config.keyMode}-${config.degree}-${config.pattern}-${config.coverage}-${bars}b-${config.progression ?? 'single'}-${config.seed ?? 0}`,
title,
meter: config.meter,
key: { tonic: config.keyTonic, mode: config.keyMode, signature: key.signature },
measures: Array.from({ length: totalMeasures }, (_, i) => ({
number: i + 1,
startTick: i * full,
durationTicks: full,
})),
chordSymbols: bars === 1
// repeat the single chord symbol across the overflow bars
? Array.from({ length: totalMeasures }, () => chordSymbols[0])
: chordSymbols,
voices: [{ id: 'melody', events }],
};
const problems = validateScore(score);
if (problems.length > 0) return { ok: false, error: `Internal arpeggio error: ${problems[0]}` };
return { ok: true, value: score };
}

View File

@@ -0,0 +1,29 @@
import { describe, it, expect } from 'vitest';
import { generateMelody } from './melodyGenerator';
import { scoreEvents, validateScore } from '../score/model';
// Reproduce user report: "bei 4/4 manchmal 5 Viertel in bar 2"
describe('melody generator bar totals (4/4, level 2)', () => {
const strings = [40, 45, 50, 55, 59, 64];
const pool: number[] = [];
for (const open of strings) for (let f = 0; f <= 12; f++) pool.push(open + f);
it('bar 2 always totals exactly one bar', () => {
let checked = 0;
for (let seed = 1; seed <= 500; seed++) {
const r = generateMelody(
{ keyTonic: 'C', keyMode: 'major', bars: 2, meter: { numerator: 4, denominator: 4 }, rhythmLevel: 2, seed },
pool,
);
if (!r.ok) continue;
checked++;
const ev = scoreEvents(r.value.score);
const problems = validateScore(r.value.score);
expect(problems, `seed ${seed}`).toEqual([]);
const bar2 = ev.filter(e => e.startTick >= 1920 && e.startTick < 3840);
const bar2Len = bar2.reduce((a, e) => a + e.durationTicks, 0);
expect(bar2Len, `seed ${seed} bar2 ticks`).toBe(1920);
}
expect(checked).toBeGreaterThan(400);
});
});

View File

@@ -31,8 +31,9 @@ export interface MelodyConfig {
/** 1..8 */
readonly bars: number;
readonly meter: { readonly numerator: 3 | 4; readonly denominator: 4 };
/** 1 = Simple (quarters/halves/wholes), 2 = Mixed (+ paired eighths, dotted quarters). */
readonly rhythmLevel: 1 | 2;
/** 1 = Simple (quarters/halves/wholes), 2 = Mixed (+ paired eighths, dotted quarters),
* 3 = Elaborate (+ sixteenths, sixteenth groups, dotted eighths). */
readonly rhythmLevel: 1 | 2 | 3;
readonly seed: number;
}
@@ -53,6 +54,17 @@ const TEMPLATES_4_L2: number[][] = [
[720, 720, 480],
[720, 480, 240, 240, 240],
];
// Level 3: sixteenth-note material (120 = 16th, 360 = dotted 8th).
const TEMPLATES_4_L3: number[][] = [
[480, 480, 120, 120, 120, 120, 480],
[120, 120, 120, 120, 480, 480, 480],
[480, 120, 120, 120, 120, 480, 480],
[360, 120, 480, 480, 480],
[480, 360, 120, 480, 480],
[120, 120, 120, 120, 120, 120, 120, 120, 480, 480],
[480, 480, 360, 120, 480],
[720, 120, 120, 120, 120, 480],
];
const TEMPLATES_3_L1: number[][] = [
[480, 480, 480],
[960, 480],
@@ -65,11 +77,19 @@ const TEMPLATES_3_L2: number[][] = [
[720, 720],
[720, 240, 240, 240],
];
// Level 3 for 3/4: sixteenth material filling 1440 ticks.
const TEMPLATES_3_L3: number[][] = [
[480, 120, 120, 120, 120, 480, 480],
[120, 120, 120, 120, 480, 480, 480],
[360, 120, 480, 480, 480],
[480, 360, 120, 480, 480],
[120, 120, 120, 120, 120, 120, 120, 120, 480],
];
function templatesFor(meter: { numerator: 3 | 4 }, level: 1 | 2): number[][] {
function templatesFor(meter: { numerator: 3 | 4 }, level: 1 | 2 | 3): number[][] {
const base = meter.numerator === 4
? (level === 1 ? TEMPLATES_4_L1 : [...TEMPLATES_4_L1, ...TEMPLATES_4_L2])
: (level === 1 ? TEMPLATES_3_L1 : [...TEMPLATES_3_L1, ...TEMPLATES_3_L2]);
? (level === 1 ? TEMPLATES_4_L1 : level === 2 ? [...TEMPLATES_4_L1, ...TEMPLATES_4_L2] : [...TEMPLATES_4_L1, ...TEMPLATES_4_L2, ...TEMPLATES_4_L3])
: (level === 1 ? TEMPLATES_3_L1 : level === 2 ? [...TEMPLATES_3_L1, ...TEMPLATES_3_L2] : [...TEMPLATES_3_L1, ...TEMPLATES_3_L2, ...TEMPLATES_3_L3]);
return base.filter(t => t.reduce((a, b) => a + b, 0) === meter.numerator * PPQ);
}

View File

@@ -12,6 +12,7 @@ import { keyFor, scalePitches, type KeyContext, type ModeId } from './scales';
export type DrillDirection = 'up' | 'down' | 'updown';
export type DrillCoverage = 'one-octave' | 'two-octave' | 'position';
export type DrillRhythm = 'quarters' | 'eighths';
export interface DrillConfig {
readonly keyTonic: string;
@@ -19,6 +20,8 @@ export interface DrillConfig {
readonly direction: DrillDirection;
readonly coverage: DrillCoverage;
readonly meter: { readonly numerator: 3 | 4; readonly denominator: 4 };
/** Note duration: quarters (default) or eighths. */
readonly rhythm?: DrillRhythm;
}
/** Complete ascending scale path from a starting tonic, if it fits the pool. */
@@ -87,14 +90,15 @@ export function generateScaleDrill(
else path = [...up, ...[...up].reverse().slice(1)]; // no duplicate turning tonic
}
// ---- Quarter-note rhythm, final note extended to fill its bar ---------
// ---- Rhythm: quarters (default) or eighths; final note extended ---------
const noteDur = config.rhythm === 'eighths' ? PPQ / 2 : PPQ;
const full = config.meter.numerator * PPQ;
if (path.length * PPQ > 8 * full) {
return { ok: false, error: 'This drill is longer than 8 bars — reduce the coverage or direction.' };
if (path.length * noteDur > 8 * full) {
return { ok: false, error: 'This drill is longer than 8 bars — reduce the coverage, direction or note duration.' };
}
const barCount = Math.max(1, Math.ceil((path.length * PPQ) / full));
const barCount = Math.max(1, Math.ceil((path.length * noteDur) / full));
const totalTicks = barCount * full;
const lastDuration = PPQ + (totalTicks - path.length * PPQ);
const lastDuration = noteDur + (totalTicks - path.length * noteDur);
const events: ScoreEvent[] = [];
let cursor = 0;
@@ -104,7 +108,7 @@ export function generateScaleDrill(
return found ? found.pitch : sp[0]?.pitch ?? null;
};
for (let i = 0; i < path.length; i++) {
const dur = i === path.length - 1 ? lastDuration : PPQ;
const dur = i === path.length - 1 ? lastDuration : noteDur;
const pitch = spellFor(path[i]);
if (!pitch) return { ok: false, error: 'Internal error spelling drill pitch.' };
events.push({ id: `s${i}`, startTick: cursor, durationTicks: dur, pitch });
@@ -113,7 +117,7 @@ export function generateScaleDrill(
const score: Score = {
version: 1,
id: `scale-${config.keyTonic}-${config.keyMode}-${config.coverage}-${config.direction}-${config.meter.numerator}4`,
id: `scale-${config.keyTonic}-${config.keyMode}-${config.coverage}-${config.direction}-${config.rhythm ?? 'quarters'}-${config.meter.numerator}4`,
title: `${key.tonic} scale — ${config.coverage === 'position' ? 'within position' : config.coverage} ${config.direction}`,
meter: config.meter,
key: { tonic: config.keyTonic, mode: config.keyMode, signature: key.signature },

View File

@@ -40,7 +40,10 @@ 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
// 1+2: base pool with string selection and optional fret window.
// For fretted instruments with NO filters the pool is the full fretboard
// (frets 0–12) — the legacy difficulty ranges no longer apply since the
// Note Set dropdown was removed.
let base: number[];
if (fretted) {
const all = tuning!.strings;
@@ -49,7 +52,7 @@ export function computeTargetPool(input: TargetPoolInput): number[] {
: 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;
const hi = input.fretWindowEnabled ? Math.max(lo, Math.min(24, input.fretMax)) : 12;
base = selected.flatMap(open => {
const notes: number[] = [];
for (let fret = lo; fret <= hi; fret++) notes.push(open + fret);

View File

@@ -91,6 +91,9 @@ export interface Score {
readonly measures: ScoreMeasure[];
/** Exactly one voice in v1. */
readonly voices: ReadonlyArray<{ readonly id: 'melody'; readonly events: ScoreEvent[] }>;
/** Optional chord symbol per bar index (0-based), e.g. "C", "Am", "G7".
* Rendered above the staff; absent = no symbol for that bar. */
readonly chordSymbols?: ReadonlyArray<string | null>;
readonly source?: ScoreSource;
}

View File

@@ -34,12 +34,15 @@ export interface RhythmSettings {
bpm: number;
seconds: number;
active: boolean;
/** Phrase Mode: sync the metronome to the exercise (starts with it,
* silent while idle) instead of running freely. */
syncToExercise: boolean;
autoAdvance: boolean;
sound: boolean;
volume: number;
}
export type PhraseMaterial = 'melody' | 'scale' | 'library' | 'import';
export type PhraseMaterial = 'melody' | 'scale' | 'arpeggio' | 'library' | 'import';
export type PhrasePace = 'step' | 'tempo';
export interface PhraseSettings {
@@ -50,9 +53,20 @@ export interface PhraseSettings {
keyMode: string; // ModeId
bars: number; // 1–8 (melodies)
meterNumerator: 3 | 4;
rhythmLevel: 1 | 2;
rhythmLevel: 1 | 2 | 3;
scaleCoverage: 'one-octave' | 'two-octave' | 'position';
scaleDirection: 'up' | 'down' | 'updown';
scaleRhythm: 'quarters' | 'eighths';
/** Arpeggio settings (material = 'arpeggio'). */
arpeggioDegree: string; // ArpeggioDegree (single-chord mode / sequence start)
/** Sequence mode: which degrees may appear (empty = all 7). */
arpeggioChordSelection: string[];
arpeggioPattern: 'up' | 'down' | 'updown' | '1235';
arpeggioCoverage: 'one-octave' | 'two-octave';
/** Sequence mode: bars per exercise (1 = single chord). */
arpeggioBars: number;
arpeggioProgression: 'random' | 'functional' | 'diatonic-cycle';
arpeggioRhythm: 'quarters' | 'eighths';
/** Phrase-local fret window (guitar/bass) — overrides the note set. */
fretWindowEnabled: boolean;
fretMin: number;
@@ -67,6 +81,9 @@ export interface PhraseSettings {
* new melody) after a short pause — keeps practice flowing. */
autoContinue: boolean;
inputMode: 'mic' | 'virtual';
/** Begin the run as soon as the first note is played (no count-in,
* step pace only). */
autoStartOnNote: boolean;
}
export const DEFAULT_PHRASE_SETTINGS: PhraseSettings = {
@@ -79,6 +96,14 @@ export const DEFAULT_PHRASE_SETTINGS: PhraseSettings = {
rhythmLevel: 1,
scaleCoverage: 'one-octave',
scaleDirection: 'updown',
scaleRhythm: 'quarters',
arpeggioDegree: 'I',
arpeggioChordSelection: [],
arpeggioPattern: 'up',
arpeggioCoverage: 'one-octave',
arpeggioBars: 1,
arpeggioProgression: 'functional',
arpeggioRhythm: 'quarters',
fretWindowEnabled: false,
fretMin: 0,
fretMax: 4,
@@ -89,6 +114,7 @@ export const DEFAULT_PHRASE_SETTINGS: PhraseSettings = {
clickSound: false,
autoContinue: true,
inputMode: 'mic',
autoStartOnNote: false,
};
export function getPhraseSettings(s: AppSettings): PhraseSettings {
@@ -141,6 +167,7 @@ export const DEFAULT_SETTINGS: AppSettings = {
bpm: 60,
seconds: 5,
active: false,
syncToExercise: true,
autoAdvance: false,
sound: true,
volume: 0.5