diff --git a/README.md b/README.md index 0f14cf3..b671d68 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,7 @@ OpenStand is an **early but usable** practice tool. What works today: - **A real-looking lead sheet.** Chord symbols in a handwritten jazz hand (Petaluma), rehearsal marks, repeat signs, endings, segno and coda, correct flat/sharp spelling in every key, and the current bar marked with a highlighter stroke as it plays. - **Practice controls:** tempo (40–300 BPM, changes instantly), transpose to any key while playing, number of choruses, and a count-in in the tune's meter (4/4 "1 . 2 . 1 2 3 4", 6/8 two pulses then six eighths). Keyboard shortcuts: Space to play/stop, ↑/↓ for ±5 BPM, →/← to transpose by a half step, and L to clear the loop. Shortcuts are inactive while editing a chart or focusing a form control. - **Practice modes:** loop any bars or a rehearsal section, go round all 12 keys (or step up a half or whole tone each chorus), and speed up a few BPM every chorus. +- **Chord and scale helper:** keyboard, guitar diagrams and fitting scales for any chord. - **Style lab:** change a style's drums (a main groove, a variation the band switches to, and a fill for the end of the form), bass line and chord rhythm on a grid (each with an optional second pattern the band switches to) and hear it while the band plays. Save your styles and pick them from the style menu, share one as a link, or send it to the project as a new style. - **Mixer** with per-instrument volume and mute, a master volume and an output level meter. - **Light and dark themes** that follow your system setting, and a layout that works on phones. @@ -147,7 +148,7 @@ Positions are in beats from the start of the bar or chord. Off-beat eighths are - [x] Chart editor, and export back to iReal Pro - [x] Practice modes: tempo ramp per chorus, loop a section, cycle through all 12 keys - [ ] Export to ChordPro and MusicXML -- [ ] Chord helper: piano keyboard, guitar diagrams, scale suggestions +- [x] Chord helper: piano keyboard, guitar diagrams, scale suggestions - [ ] Export to WAV / MIDI / PDF - [ ] Engine published as a standalone package diff --git a/src/App.tsx b/src/App.tsx index 5d5528b..e2580b0 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -10,12 +10,13 @@ import { chartFromHash, labFromHash, shareUrl, styleShareUrl } from './formats/s import { addTunes, loadTunes, removePlaylist, removeTune, saveTune } from './library/db' import { loadMyStyles, myStyleId, removeMyStyle, saveMyStyle } from './library/myStyles' import type { Chart as ChartData } from './music/chart' -import { keyPrefersFlats, noteName } from './music/chords' +import { keyPrefersFlats, noteName, parseChord, transposeChord, type Chord } from './music/chords' import { emptyChart } from './music/edit' import { EXAMPLES, type Tune } from './music/songs' import { getStyle, STYLES, type StyleDefinition } from './styles' import { labFromStyle, styleFromLab, styleSource, labId, STEPS_PER_BEAT, type LabStyle } from './styles/lab' import { Chart } from './ui/Chart' +import { ChordHelper } from './ui/ChordHelper' import { Editor, EditorHeader } from './ui/Editor' import { ImportDialog, type ImportResult } from './ui/ImportDialog' import { Library } from './ui/Library' @@ -81,6 +82,39 @@ const noteNameFor = (pc: number) => noteName(pc, keyPrefersFlats(pc)).replace('b const compLabel = (program: number) => (program >= 24 && program <= 31 ? 'Guitar' : 'Piano') +function firstChord(chart: ChartData, transpose: number): Chord { + for (const bar of chart.bars) { + for (const c of bar.chords) { + const parsed = c.symbol ? parseChord(c.symbol) : null + if (parsed) return transposeChord(parsed, transpose) + } + } + return transposeChord(parseChord('C')!, transpose) +} + +function playingChord(chart: ChartData, position: Position | null, transpose: number): Chord | null { + if (!position || position.countIn > 0) return null + if (position.ending) return firstChord(chart, transpose) + const bar = chart.bars[position.measure] + if (!bar) return null + if (bar.chords.length > 0) { + let at = 0 + for (const c of bar.chords) { + at += c.beats + if (position.beatInBar < at || c === bar.chords[bar.chords.length - 1]) { + const parsed = c.symbol ? parseChord(c.symbol) : null + return parsed ? transposeChord(parsed, transpose) : null + } + } + } + const held = chart.bars + .slice(0, position.measure) + .flatMap((b) => b.chords) + .findLast((c) => c.symbol)?.symbol + const parsed = held ? parseChord(held) : null + return parsed ? transposeChord(parsed, transpose) : null +} + function positionAt(timeline: Timeline, beat: number): Position | null { if (beat < timeline.countIn) { const barBeats = timeline.countIn @@ -158,6 +192,8 @@ export default function App() { const outputLevel = useCallback(() => playerRef.current?.level() ?? { peak: -100, rms: -100 }, []) const [practice, setPractice] = useState(NO_PRACTICE) const [picking, setPicking] = useState(null) + const [selectedChord, setSelectedChord] = useState(null) + const [chordsOpen, setChordsOpen] = useState(false) const [draft, setDraft] = useState(null) const [editBar, setEditBar] = useState(0) const [irealState, setIrealState] = useState<'idle' | 'copied' | 'failed'>('idle') @@ -178,7 +214,11 @@ export default function App() { // During practice the chorus decides the key on the stand and the tempo const chorus = position ? Math.min(position.chorus, choruses - 1) : 0 const shownTranspose = playing ? chorusTranspose(transpose, practice.keyStep, chorus) : transpose + const shownKeyPc = (chart.key + shownTranspose + 12) % 12 const liveBpm = clampBpm(bpm + practice.ramp * (playing ? chorus : 0)) + const shownChord = selectedChord + ? transposeChord(selectedChord, shownTranspose) + : (playing ? playingChord(chart, position, shownTranspose) : null) ?? firstChord(chart, shownTranspose) useEffect(() => { // The effect may run twice (StrictMode); a discarded player must not update the UI @@ -336,6 +376,7 @@ export default function App() { setBpm(next.chart.bpm) setPractice((p) => ({ ...p, loop: null })) setPicking(null) + setSelectedChord(null) setLibraryOpen(false) try { localStorage.setItem(LAST_TUNE, next.id) @@ -656,6 +697,14 @@ export default function App() { range={picking && picking !== 'first' ? [picking.from, picking.from] : draft ? null : practice.loop} selectedBar={draft ? editBar : null} onBarClick={draft ? setEditBar : picking ? pickBar : undefined} + onChordClick={ + !draft && !picking + ? (c) => { + setSelectedChord(transposeChord(c, -shownTranspose)) + setChordsOpen(true) + } + : undefined + } header={draft ? setDraft({ ...draft, chart: c })} /> : undefined} /> @@ -739,6 +788,14 @@ export default function App() { onChoruses={(n) => changeArrangement({ choruses: n })} > setPicking('first')} /> + setSelectedChord(follow ? null : transposeChord(shownChord, -shownTranspose))} + open={chordsOpen} + onOpenChange={setChordsOpen} + /> f !== null && f > 0) + if (fretted.length <= 4) return true + // 5 or 6 fretted strings need an index-finger barre at minFret and at most 3 other fingers + const firstBarred = frets.findIndex((f) => f === minFret) + const lastPlayed = frets.findLastIndex((f) => f !== null) + for (let s = firstBarred; s <= lastPlayed; s++) { + if (frets[s] === null || frets[s]! < minFret) return false + } + return fretted.filter((f) => f > minFret).length <= 3 +} + +function isContiguousOrShell(played: number[]): boolean { + const span = played[played.length - 1] - played[0] + 1 + if (span === played.length) return true + // Jazz shell / drop-3 with bass on 6th string and 5th string muted + return played[0] === 0 && played[1] === 2 && played[played.length - 1] - 2 + 1 === played.length - 1 +} + +export function guitarShapes(chord: Chord): [FretShape, FretShape] { + const tones = closeVoicingTones(chord) + const tonePcs = new Set(tones.map((t) => (chord.root + t) % 12)) + const required = new Set([ + chord.root, + (chord.root + tones[1]) % 12, + ...(tones.length > 3 ? [(chord.root + tones[3]) % 12] : []), + ...(tones[2] !== 7 ? [(chord.root + tones[2]) % 12] : []), + ]) + + const byKey = new Map() + + for (let bassString = 0; bassString <= 2; bassString++) { + for (let bassFret = 0; bassFret <= 11; bassFret++) { + if ((TUNING[bassString] + bassFret) % 12 !== chord.bass) continue + + const winStarts: number[] = [] + if (bassFret <= 4) winStarts.push(1) + if (bassFret > 0) { + for (let w = Math.max(1, bassFret - 3); w <= Math.min(11, bassFret); w++) { + if (!winStarts.includes(w)) winStarts.push(w) + } + } + + for (const win of winStarts) { + const choices: (number | null)[][] = Array.from({ length: 6 }, (_, s) => { + if (s < bassString) return [null] + if (s === bassString) return [bassFret] + const opts: (number | null)[] = [null] + if (win === 1 && tonePcs.has(TUNING[s])) opts.push(0) + for (let f = win; f <= win + 3; f++) { + if (tonePcs.has((TUNING[s] + f) % 12)) opts.push(f) + } + return opts + }) + + const cur: (number | null)[] = [null, null, null, null, null, null] + const search = (s: number) => { + if (s === 6) { + const played: number[] = [] + for (let i = 0; i < 6; i++) if (cur[i] !== null) played.push(i) + if (played.length < 4 || !isContiguousOrShell(played)) return + + for (let i = 1; i < played.length; i++) { + if (MIDI[played[i]] + cur[played[i]]! <= MIDI[played[i - 1]] + cur[played[i - 1]]!) return + } + + const fretted = played.map((i) => cur[i]!).filter((f) => f > 0) + const minFret = fretted.length ? Math.min(...fretted) : 0 + const maxFret = fretted.length ? Math.max(...fretted) : 0 + if (fretted.length && maxFret - minFret > 3) return + if (played.some((i) => cur[i] === 0) && maxFret > 4) return + if (fretted.length && !isErgonomic(cur, minFret)) return + + const pcs = new Set(played.map((i) => (TUNING[i] + cur[i]!) % 12)) + let reqHits = 0 + for (const r of required) if (pcs.has(r)) reqHits++ + const coverage = reqHits * 30 + pcs.size * 12 + + const contiguous = played[played.length - 1] - played[0] + 1 === played.length + const openCount = played.filter((i) => cur[i] === 0).length + const span = fretted.length ? maxFret - minFret : 0 + const baseFret = maxFret <= 4 ? 1 : minFret + const score = + coverage + + (contiguous ? 16 : 0) + + played.length * 4 + + openCount * 2 - + span * 3 - + baseFret * 1.5 - + bassFret * 0.5 + + const key = cur.map((f) => f ?? 'x').join(',') + const prev = byKey.get(key) + if (!prev || score > prev.score) { + byKey.set(key, { frets: [...cur], baseFret, bassString, bassFret, coverage, score }) + } + return + } + for (const f of choices[s]) { + cur[s] = f + search(s + 1) + } + } + search(0) + } + } + } + + const all = [...byKey.values()] + const maxCoverage = Math.max(0, ...all.map((c) => c.coverage)) + const strong = all.filter((c) => c.coverage >= maxCoverage - 12) + const pool = strong.length >= 2 ? strong : all + + pool.sort((a, b) => a.baseFret - b.baseFret || a.bassFret - b.bassFret || b.score - a.score) + const firstPos = pool[0]?.baseFret ?? 1 + const first = + pool.filter((c) => c.baseFret === firstPos).sort((a, b) => b.score - a.score)[0] ?? + ({ frets: [null, null, 0, 0, 0, 0], baseFret: 1, bassString: 2, bassFret: 0, coverage: 0, score: 0 } as Candidate) + + const higher = pool.filter( + (c) => c.baseFret >= first.baseFret + 2 || (c.bassString !== first.bassString && c.bassFret >= first.bassFret + 2), + ) + const secondPool = higher.length ? higher : pool.filter((c) => c !== first) + const nextPos = secondPool[0]?.baseFret ?? first.baseFret + const second = + secondPool.filter((c) => c.baseFret <= nextPos + 1).sort((a, b) => b.score - a.score)[0] ?? + secondPool[0] ?? + first + + return [ + { frets: first.frets, baseFret: first.baseFret }, + { frets: second.frets, baseFret: second.baseFret }, + ] +} diff --git a/src/music/scales.ts b/src/music/scales.ts new file mode 100644 index 0000000..b8355b0 --- /dev/null +++ b/src/music/scales.ts @@ -0,0 +1,188 @@ +import { keyPrefersFlats, noteName, type Chord, type Quality } from './chords' + +export interface Scale { + id: string + name: string + intervals: number[] + note: string + firstChoice: boolean +} + +type ScaleDef = Omit + +export const SCALES: Record = { + ionian: { + id: 'ionian', + name: 'Ionian', + intervals: [0, 2, 4, 5, 7, 9, 11], + note: 'Major scale; go easy on the 4th over maj7', + }, + lydian: { + id: 'lydian', + name: 'Lydian', + intervals: [0, 2, 4, 6, 7, 9, 11], + note: 'Major with #11; bright, no avoid notes', + }, + 'major-pentatonic': { + id: 'major-pentatonic', + name: 'Major pentatonic', + intervals: [0, 2, 4, 7, 9], + note: 'Five-note major sound', + }, + mixolydian: { + id: 'mixolydian', + name: 'Mixolydian', + intervals: [0, 2, 4, 5, 7, 9, 10], + note: 'Home scale for unaltered dominant 7th chords', + }, + 'bebop-dominant': { + id: 'bebop-dominant', + name: 'Bebop dominant', + intervals: [0, 2, 4, 5, 7, 9, 10, 11], + note: 'Mixolydian with a passing major 7th', + }, + 'lydian-dominant': { + id: 'lydian-dominant', + name: 'Lydian dominant', + intervals: [0, 2, 4, 6, 7, 9, 10], + note: 'Dominant with #11 (melodic minor from the 4th)', + }, + altered: { + id: 'altered', + name: 'Altered', + intervals: [0, 1, 3, 4, 6, 8, 10], + note: 'Every altered tension: b9, #9, b5 and b13', + }, + 'half-whole': { + id: 'half-whole', + name: 'Half-whole diminished', + intervals: [0, 1, 3, 4, 6, 7, 9, 10], + note: 'Symmetric diminished for b9 and #9 with natural 5th and 13th', + }, + 'whole-tone': { + id: 'whole-tone', + name: 'Whole tone', + intervals: [0, 2, 4, 6, 8, 10], + note: 'Six equal whole steps; fits #5 and b5', + }, + 'mixolydian-pentatonic': { + id: 'mixolydian-pentatonic', + name: 'Mixolydian pentatonic', + intervals: [0, 2, 5, 7, 10], + note: 'Root, 9th, 4th, 5th and b7 for sus chords', + }, + dorian: { + id: 'dorian', + name: 'Dorian', + intervals: [0, 2, 3, 5, 7, 9, 10], + note: 'Minor with a natural 6th', + }, + aeolian: { + id: 'aeolian', + name: 'Aeolian', + intervals: [0, 2, 3, 5, 7, 8, 10], + note: 'Natural minor scale (flat 6th)', + }, + phrygian: { + id: 'phrygian', + name: 'Phrygian', + intervals: [0, 1, 3, 5, 7, 8, 10], + note: 'Minor with a flat 2nd', + }, + 'minor-pentatonic': { + id: 'minor-pentatonic', + name: 'Minor pentatonic', + intervals: [0, 3, 5, 7, 10], + note: 'Five-note minor scale', + }, + 'melodic-minor': { + id: 'melodic-minor', + name: 'Melodic minor', + intervals: [0, 2, 3, 5, 7, 9, 11], + note: 'Minor with natural 6th and major 7th', + }, + 'harmonic-minor': { + id: 'harmonic-minor', + name: 'Harmonic minor', + intervals: [0, 2, 3, 5, 7, 8, 11], + note: 'Minor with flat 6th and major 7th', + }, + locrian: { + id: 'locrian', + name: 'Locrian', + intervals: [0, 1, 3, 5, 6, 8, 10], + note: 'Half-diminished scale with b9', + }, + 'locrian-nat2': { + id: 'locrian-nat2', + name: 'Locrian natural 2', + intervals: [0, 2, 3, 5, 6, 8, 10], + note: 'Half-diminished with a natural 9th', + }, + 'whole-half': { + id: 'whole-half', + name: 'Whole-half diminished', + intervals: [0, 2, 3, 5, 6, 8, 9, 11], + note: 'Symmetric diminished starting with a whole step', + }, + 'lydian-augmented': { + id: 'lydian-augmented', + name: 'Lydian augmented', + intervals: [0, 2, 4, 6, 8, 9, 11], + note: 'Major with #4 and #5', + }, +} + +const BY_QUALITY: Record, string[]> = { + maj7: ['ionian', 'lydian'], + maj: ['ionian', 'lydian', 'major-pentatonic'], + maj6: ['ionian', 'lydian', 'major-pentatonic'], + sus7: ['mixolydian', 'mixolydian-pentatonic'], + min: ['dorian', 'aeolian', 'phrygian', 'minor-pentatonic'], + min7: ['dorian', 'aeolian', 'phrygian', 'minor-pentatonic'], + min6: ['dorian', 'melodic-minor'], + minMaj7: ['melodic-minor', 'harmonic-minor'], + half: ['locrian', 'locrian-nat2'], + dim7: ['whole-half'], + aug: ['whole-tone', 'lydian-augmented'], +} + +function dom7ScaleIds(tensions: string[]): string[] { + const ids: string[] = [] + const hasAlt = tensions.some((t) => t === 'alt' || t === 'b9' || t === '#9' || t === 'b13' || t === '#5') + if (tensions.includes('#11') && !tensions.includes('alt')) ids.push('lydian-dominant') + if (hasAlt) ids.push('altered') + if (tensions.includes('#11') && !ids.includes('lydian-dominant')) ids.push('lydian-dominant') + if (tensions.includes('b9')) ids.push('half-whole') + if (tensions.includes('#5') || tensions.includes('b5')) ids.push('whole-tone') + ids.push('mixolydian', 'bebop-dominant') + return ids +} + +export function scalesForChord(chord: Chord): Scale[] { + let ids: string[] + if (chord.quality === 'dom7') { + ids = dom7ScaleIds(chord.tensions) + } else if (chord.quality === 'maj7' && chord.tensions.includes('#11')) { + ids = ['lydian', 'ionian'] + } else { + ids = BY_QUALITY[chord.quality] + } + return ids.map((id, index) => ({ + ...SCALES[id], + firstChoice: index === 0, + })) +} + +export function scaleNotes(root: number, scale: Scale | readonly number[]): number[] { + const intervals = Array.isArray(scale) ? scale : (scale as Scale).intervals + return intervals.map((step) => (((root + step) % 12) + 12) % 12) +} + +export function scaleNoteNames( + root: number, + scale: Scale | readonly number[], + preferFlats = keyPrefersFlats(root), +): string[] { + return scaleNotes(root, scale).map((pc) => noteName(pc, preferFlats)) +} diff --git a/src/ui/Chart.tsx b/src/ui/Chart.tsx index 9273be0..7951089 100644 --- a/src/ui/Chart.tsx +++ b/src/ui/Chart.tsx @@ -17,6 +17,7 @@ interface ChartProps { range?: [number, number] | null // looped bars selectedBar?: number | null // the bar being edited onBarClick?: (index: number) => void + onChordClick?: (chord: Chord) => void header?: ReactNode // replaces the title block, e.g. with inputs in the editor } @@ -74,9 +75,10 @@ interface BarProps { inRange: boolean selected: boolean onClick?: (index: number) => void + onChordClick?: (chord: Chord) => void } -function Bar({ placed, prev, keyPc, active, progress, showTime, inRange, selected, onClick }: BarProps) { +function Bar({ placed, prev, keyPc, active, progress, showTime, inRange, selected, onClick, onChordClick }: BarProps) { const { bar, chords, column, closesRow, index } = placed const classes = ['bar'] if (bar.spacer) classes.push('bar-spacer') @@ -146,7 +148,7 @@ function Bar({ placed, prev, keyPc, active, progress, showTime, inRange, selecte {active && } {chords.map(({ chord, symbol }, j) => chord ? ( - + ) : symbol === null ? ( N.C. @@ -168,7 +170,7 @@ function Bar({ placed, prev, keyPc, active, progress, showTime, inRange, selecte } export function Chart(props: ChartProps) { - const { chart, style, transpose, activeMeasure, beatInBar, barBeats, range, selectedBar, onBarClick, header } = props + const { chart, style, transpose, activeMeasure, beatInBar, barBeats, range, selectedBar, onBarClick, onChordClick, header } = props const keyPc = (chart.key + transpose + 12) % 12 const layout = useMemo(() => rows(chart, transpose), [chart, transpose]) const keyName = prettyKey(noteName(keyPc, keyPrefersFlats(keyPc))) + (chart.minor ? '−' : '') @@ -198,6 +200,7 @@ export function Chart(props: ChartProps) { inRange={!!range && placed.index >= Math.min(...range) && placed.index <= Math.max(...range)} selected={selectedBar === placed.index} onClick={onBarClick} + onChordClick={onChordClick} /> ))} diff --git a/src/ui/ChordHelper.tsx b/src/ui/ChordHelper.tsx new file mode 100644 index 0000000..1db565d --- /dev/null +++ b/src/ui/ChordHelper.tsx @@ -0,0 +1,211 @@ +import { useState } from 'react' +import { closeVoicingTones, keyPrefersFlats, noteName, spellRoot, type Chord } from '../music/chords' +import { guitarShapes, type FretShape } from '../music/fretboard' +import { scaleNoteNames, scalesForChord } from '../music/scales' +import { Popover } from './Popover' +import './chordHelper.css' + +const WHITE_PCS = [0, 2, 4, 5, 7, 9, 11] as const +const BLACK_PCS = [ + { pc: 1, after: 0 }, + { pc: 3, after: 1 }, + { pc: 6, after: 3 }, + { pc: 8, after: 4 }, + { pc: 10, after: 5 }, +] as const + +interface ChordHelperProps { + chord: Chord + keyPc: number + following: boolean + onFollowChange: (follow: boolean) => void + open: boolean + onOpenChange: (open: boolean) => void +} + +function PianoKeyboard({ + label, + toneNames, + chordKeys, + scaleKeys, +}: { + label: string + toneNames: string[] + chordKeys: Set + scaleKeys: Set +}) { + const whites: { semi: number; x: number }[] = [] + const blacks: { semi: number; x: number }[] = [] + for (let oct = 0; oct < 2; oct++) { + WHITE_PCS.forEach((pc, i) => whites.push({ semi: oct * 12 + pc, x: (oct * 7 + i) * 20 })) + BLACK_PCS.forEach(({ pc, after }) => blacks.push({ semi: oct * 12 + pc, x: (oct * 7 + after + 1) * 20 - 6 })) + } + + return ( + + {whites.map(({ semi, x }) => { + const isChord = chordKeys.has(semi) + const isScale = scaleKeys.has(semi) + return ( + + + {isChord && } + {isScale && } + + ) + })} + {blacks.map(({ semi, x }) => { + const isChord = chordKeys.has(semi) + const isScale = scaleKeys.has(semi) + return ( + + + {isChord && } + {isScale && ( + + )} + + ) + })} + + ) +} + +function GuitarDiagram({ label, shape, position }: { label: string; shape: FretShape; position: number }) { + const bassString = shape.frets.findIndex((f) => f !== null) + const fretsLabel = shape.frets.map((f) => f ?? 'x').join(' ') + + return ( + + {shape.baseFret > 1 && ( + + {shape.baseFret}fr + + )} + {[1, 2, 3, 4].map((row) => ( + + ))} + + {shape.frets.map((fret, s) => { + const x = 26 + s * 14 + const row = fret !== null && fret > 0 ? fret - shape.baseFret : -1 + return ( + + + {fret === null && } + {fret === 0 && } + {row >= 0 && row < 4 && ( + + )} + + ) + })} + + ) +} + +export function ChordHelper({ chord, keyPc, following, onFollowChange, open, onOpenChange }: ChordHelperProps) { + const chordKey = `${chord.root}:${chord.bass}:${chord.quality}:${chord.tensions.join(',')}` + const [picked, setPicked] = useState<{ chordKey: string; scaleId: string } | null>(null) + + const scales = scalesForChord(chord) + const activeScale = (picked?.chordKey === chordKey && scales.find((s) => s.id === picked.scaleId)) || scales[0] + + const rootName = spellRoot(chord.root, keyPc) + const bassPart = chord.bass !== chord.root ? `/${spellRoot(chord.bass, keyPc)}` : '' + const label = `${rootName}${chord.suffix}${bassPart}` + + const preferFlats = keyPrefersFlats(chord.root) + const tones = closeVoicingTones(chord) + const toneNames = tones.map((t) => noteName((chord.root + t) % 12, preferFlats)) + const chordKeys = new Set(tones.map((t) => chord.root + t)) + const scaleKeys = new Set(activeScale.intervals.map((i) => chord.root + i)) + const scaleNames = scaleNoteNames(chord.root, activeScale, preferFlats) + const shapes = guitarShapes(chord) + + return ( + + + Chords + + } + > + {() => ( +
+
+
+

{label}

+ {toneNames.join(' ')} +
+ +
+ + + +
+ + +
+ +
+
+ Scales + + {scaleNames.join(' ')} + +
+
+ {scales.map((s) => ( + + ))} +
+
+
+ )} +
+ ) +} diff --git a/src/ui/ChordSymbol.tsx b/src/ui/ChordSymbol.tsx index 3dae6e5..8c20115 100644 --- a/src/ui/ChordSymbol.tsx +++ b/src/ui/ChordSymbol.tsx @@ -35,11 +35,43 @@ function typeset(suffix: string): { quality: string; extensions: string } { return { quality: marker + number, extensions } } -export function ChordSymbol({ chord, keyPc }: { chord: Chord; keyPc: number }) { +export function ChordSymbol({ + chord, + keyPc, + onSelect, +}: { + chord: Chord + keyPc: number + onSelect?: (chord: Chord) => void +}) { const name = spellRoot(chord.root, keyPc) const { quality, extensions } = typeset(chord.suffix) return ( - + { + e.stopPropagation() + onSelect(chord) + } + : undefined + } + onKeyDown={ + onSelect + ? (e) => { + if (e.key !== 'Enter' && e.key !== ' ') return + e.preventDefault() + e.stopPropagation() + onSelect(chord) + } + : undefined + } + > {name[0]} {name[1] && {accidental(name[1])}} {quality && {quality}} diff --git a/src/ui/Popover.tsx b/src/ui/Popover.tsx index ddbe6d9..6c104be 100644 --- a/src/ui/Popover.tsx +++ b/src/ui/Popover.tsx @@ -6,18 +6,26 @@ interface PopoverProps { title?: string active?: boolean // shows a dot on the button when a setting is on className?: string + open?: boolean + onOpenChange?: (open: boolean) => void children: (close: () => void) => ReactNode } // A button with a panel that pops up above it; closes on outside click or Escape -export function Popover({ id, label, title, active, className, children }: PopoverProps) { - const [open, setOpen] = useState(false) +export function Popover({ id, label, title, active, className, open: controlledOpen, onOpenChange, children }: PopoverProps) { + const [uncontrolledOpen, setUncontrolledOpen] = useState(false) + const open = controlledOpen ?? uncontrolledOpen + const setOpen = (next: boolean) => { + setUncontrolledOpen(next) + onOpenChange?.(next) + } const rootRef = useRef(null) useEffect(() => { if (!open) return const onPointer = (e: PointerEvent) => { - if (!rootRef.current?.contains(e.target as Node)) setOpen(false) + const target = e.target as Element | null + if (!rootRef.current?.contains(target) && !target?.closest(`[data-opens="${id}"]`)) setOpen(false) } const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false) window.addEventListener('pointerdown', onPointer) @@ -26,7 +34,7 @@ export function Popover({ id, label, title, active, className, children }: Popov window.removeEventListener('pointerdown', onPointer) window.removeEventListener('keydown', onKey) } - }, [open]) + }) return (
diff --git a/src/ui/chordHelper.css b/src/ui/chordHelper.css new file mode 100644 index 0000000..10d0cd7 --- /dev/null +++ b/src/ui/chordHelper.css @@ -0,0 +1,277 @@ +/* Chord and scale helper popover */ + +.chords { + --mark: var(--highlighter); +} + +.chord-interactive { + cursor: pointer; + border-radius: 4px; +} + +.chord-interactive:hover { + background: color-mix(in srgb, var(--highlighter) 28%, transparent); +} + +.chords-panel { + --mark: var(--highlighter); + display: grid; + gap: 12px; + width: 356px; + padding: 2px 4px; +} + +.chords-head { + display: flex; + flex-wrap: wrap; + align-items: baseline; + justify-content: space-between; + gap: 8px; +} + +.chords-title-group { + display: flex; + align-items: baseline; + gap: 10px; +} + +.chords-name { + margin: 0; + font: 600 20px/1.1 var(--mono); + color: var(--ink); +} + +.chords-tones { + font: 500 12.5px/1 var(--mono); + color: var(--ink-2); +} + +.chords-follow { + height: auto; + font-size: 12px; + color: var(--ink-2); + cursor: pointer; +} + +.chords-piano { + display: block; + width: 100%; + height: auto; + border: 1px solid var(--ink); + border-radius: 4px; + background: var(--paper); +} + +.piano-white { + fill: var(--paper); + stroke: var(--line); + stroke-width: 1; +} + +.piano-white.piano-chord { + fill: color-mix(in srgb, var(--mark) 55%, var(--paper)); +} + +.piano-black { + fill: var(--ink); + stroke: var(--ink); + stroke-width: 1; +} + +.piano-tone-mark { + fill: var(--mark); + stroke: var(--ink); + stroke-width: 1.5; +} + +.piano-tone-mark-black { + fill: var(--mark); + stroke: var(--paper); + stroke-width: 1.4; +} + +.piano-scale-dot { + fill: var(--ink); +} + +.piano-scale-dot-black { + fill: var(--paper); +} + +.piano-scale-dot-on-mark { + fill: var(--ink); +} + +.chords-guitars { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 8px; +} + +.chords-guitar { + display: block; + width: 100%; + height: auto; + border: 1px solid var(--line); + border-radius: 6px; + background: var(--control); +} + +.guitar-grid { + stroke: var(--line); + stroke-width: 1; +} + +.guitar-string { + stroke: var(--ink-2); + stroke-width: 1; +} + +.guitar-nut { + stroke: var(--ink); + stroke-width: 3.2; +} + +.guitar-top { + stroke: var(--ink-2); + stroke-width: 1.2; +} + +.guitar-mute { + stroke: var(--muted); + stroke-width: 1.4; + stroke-linecap: round; +} + +.guitar-open { + fill: none; + stroke: var(--ink); + stroke-width: 1.4; +} + +.guitar-dot { + fill: var(--ink); +} + +.guitar-dot-bass { + fill: var(--mark); + stroke: var(--ink); + stroke-width: 1.6; +} + +.guitar-fret-num { + font: 500 10px/1 var(--mono); + fill: var(--ink-2); +} + +.chords-scales { + display: grid; + gap: 6px; +} + +.chords-scale-bar { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; +} + +.chords-scale-notes { + font: 500 12.5px/1.2 var(--mono); + color: var(--ink); + letter-spacing: 0.03em; +} + +.chords-scale-list { + display: grid; + gap: 4px; +} + +.scale-item { + display: grid; + gap: 2px; + width: 100%; + padding: 6px 9px; + border: 1px solid var(--line); + border-radius: 6px; + background: var(--control); + text-align: left; +} + +.scale-item:hover { + border-color: var(--ink-2); +} + +.scale-item[aria-pressed='true'] { + background: var(--ink); + border-color: var(--ink); + color: var(--on-ink); +} + +.scale-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.scale-name { + font-weight: 600; + font-size: 13px; +} + +.scale-badge { + padding: 1px 5px; + border-radius: 4px; + background: var(--mark); + color: var(--ink); + font: 500 10px/1.3 var(--mono); + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.scale-item[aria-pressed='true'] .scale-badge { + background: var(--paper); + color: var(--ink); +} + +.scale-note { + font-size: 11.5px; + color: var(--muted); +} + +.scale-item[aria-pressed='true'] .scale-note { + color: var(--line); +} + +@media (max-width: 820px) { + .transport { + column-gap: 8px; + } + + .transport .band-toggle { + padding: 0 9px; + gap: 5px; + } + + .chords-panel { + width: auto; + max-height: min(72dvh, 520px); + overflow-y: auto; + } +} + +@media (max-width: 480px) { + .transport .band-toggle svg { + display: none; + } + + .chords-panel { + gap: 10px; + padding: 2px 0; + } + + .chords-guitars { + gap: 6px; + } +} diff --git a/tests/fretboard.test.ts b/tests/fretboard.test.ts new file mode 100644 index 0000000..f6a0305 --- /dev/null +++ b/tests/fretboard.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, test } from 'vitest' +import { chordTones, parseChord } from '../src/music/chords' +import { guitarShapes, TUNING } from '../src/music/fretboard' + +describe('guitarShapes', () => { + test.each(['C', 'G7', 'Dm7', 'Bb^7'])('%s produces 2 valid shapes with chord tones and root in the bass', (symbol) => { + const chord = parseChord(symbol)! + const validPcs = new Set(chordTones(chord).map((t) => (chord.root + t) % 12)) + validPcs.add(chord.bass) + + const shapes = guitarShapes(chord) + expect(shapes).toHaveLength(2) + expect(shapes[0].frets).not.toEqual(shapes[1].frets) + expect(shapes[0].baseFret).toBeLessThanOrEqual(shapes[1].baseFret) + + for (const shape of shapes) { + expect(shape.frets).toHaveLength(6) + const played = shape.frets + .map((fret, string) => (fret === null ? null : { string, fret, pc: (TUNING[string] + fret) % 12 })) + .filter((x): x is { string: number; fret: number; pc: number } => x !== null) + + expect(played.length).toBeGreaterThanOrEqual(4) + expect(played.length).toBeLessThanOrEqual(6) + + // Lowest played string is the root (or slash bass) + expect(played[0].pc).toBe(chord.bass) + + // Every played note belongs to the chord tones + for (const note of played) { + expect(validPcs.has(note.pc)).toBe(true) + } + + // Fretted notes span at most 4 frets (max - min <= 3) + const fretted = played.map((n) => n.fret).filter((f) => f > 0) + if (fretted.length > 0) { + expect(Math.max(...fretted) - Math.min(...fretted)).toBeLessThanOrEqual(3) + } + } + }) + + test('supports slash chords and diminished / augmented qualities', () => { + for (const symbol of ['C/G', 'F#o7', 'Bh7', 'Eb+', 'A-6', 'C-^7', 'F7sus']) { + const chord = parseChord(symbol)! + const validPcs = new Set(chordTones(chord).map((t) => (chord.root + t) % 12)) + validPcs.add(chord.bass) + const shapes = guitarShapes(chord) + for (const shape of shapes) { + const firstString = shape.frets.findIndex((f) => f !== null) + expect(firstString).toBeGreaterThanOrEqual(0) + expect((TUNING[firstString] + shape.frets[firstString]!) % 12).toBe(chord.bass) + for (let s = 0; s < 6; s++) { + if (shape.frets[s] !== null) { + expect(validPcs.has((TUNING[s] + shape.frets[s]!) % 12)).toBe(true) + } + } + } + } + }) +}) diff --git a/tests/scales.test.ts b/tests/scales.test.ts new file mode 100644 index 0000000..ac9dc2f --- /dev/null +++ b/tests/scales.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, test } from 'vitest' +import { parseChord, transposeChord } from '../src/music/chords' +import { scaleNoteNames, scaleNotes, scalesForChord } from '../src/music/scales' + +describe('scalesForChord', () => { + test('dom7+alt chooses altered first', () => { + const chord = parseChord('C7alt')! + const scales = scalesForChord(chord) + expect(scales[0].id).toBe('altered') + expect(scales[0].firstChoice).toBe(true) + expect(scales.slice(1).every((s) => !s.firstChoice)).toBe(true) + }) + + test('dom7 tensions include fitting scales', () => { + expect(scalesForChord(parseChord('C7#11')!)[0].id).toBe('lydian-dominant') + const b9Ids = scalesForChord(parseChord('C7b9')!).map((s) => s.id) + expect(b9Ids).toContain('altered') + expect(b9Ids).toContain('half-whole') + const sharp5Ids = scalesForChord(parseChord('C7#5')!).map((s) => s.id) + expect(sharp5Ids).toContain('altered') + expect(sharp5Ids).toContain('whole-tone') + }) + + test('min7 has Dorian as first choice', () => { + const scales = scalesForChord(parseChord('D-7')!) + expect(scales.map((s) => s.id)).toEqual(['dorian', 'aeolian', 'phrygian', 'minor-pentatonic']) + expect(scales[0].firstChoice).toBe(true) + expect(scales[1].firstChoice).toBe(false) + }) + + test('half-diminished returns Locrian and Locrian natural 2', () => { + const scales = scalesForChord(parseChord('Bh7')!) + expect(scales.map((s) => s.id)).toEqual(['locrian', 'locrian-nat2']) + expect(scales[0].firstChoice).toBe(true) + }) + + test('other chord qualities return their fitting scales', () => { + expect(scalesForChord(parseChord('C^7')!).map((s) => s.id)).toEqual(['ionian', 'lydian']) + expect(scalesForChord(parseChord('C6')!).map((s) => s.id)).toEqual(['ionian', 'lydian', 'major-pentatonic']) + expect(scalesForChord(parseChord('G7sus')!).map((s) => s.id)).toEqual(['mixolydian', 'mixolydian-pentatonic']) + expect(scalesForChord(parseChord('C-6')!).map((s) => s.id)).toEqual(['dorian', 'melodic-minor']) + expect(scalesForChord(parseChord('C-^7')!).map((s) => s.id)).toEqual(['melodic-minor', 'harmonic-minor']) + expect(scalesForChord(parseChord('Co7')!).map((s) => s.id)).toEqual(['whole-half']) + expect(scalesForChord(parseChord('C+')!).map((s) => s.id)).toEqual(['whole-tone', 'lydian-augmented']) + }) + + test('G7 scale notes and transposition', () => { + const g7 = parseChord('G7')! + const [mixolydian, bebop] = scalesForChord(g7) + expect(mixolydian.id).toBe('mixolydian') + expect(scaleNoteNames(g7.root, mixolydian)).toEqual(['G', 'A', 'B', 'C', 'D', 'E', 'F']) + expect(scaleNoteNames(g7.root, bebop)).toEqual(['G', 'A', 'B', 'C', 'D', 'E', 'F', 'F#']) + + // Transpose G7 up a minor third to Bb7 (flat key) and down a fifth to C7 + const bb7 = transposeChord(g7, 3) + expect(scaleNoteNames(bb7.root, mixolydian)).toEqual(['Bb', 'C', 'D', 'Eb', 'F', 'G', 'Ab']) + expect(scaleNotes(bb7.root, mixolydian)).toEqual([10, 0, 2, 3, 5, 7, 8]) + + const dMaj7 = transposeChord(parseChord('C^7')!, 2) + const [ionian] = scalesForChord(dMaj7) + expect(scaleNoteNames(dMaj7.root, ionian)).toEqual(['D', 'E', 'F#', 'G', 'A', 'B', 'C#']) + }) +})