Added support for flexible beatgrids

This commit is contained in:
patben8 committed 2026-09-17 15:14:07 +02:00
1 parent 3f51444e2a
commit dd97f27ac7
20 files changed
+2176 -346

No files matched your search

+170 -23
View File
@@ -1,23 +1,52 @@
import { useRef, useState } from 'react'
import { memo, useRef, useState } from 'react'
interface Props {
/** Tempo of the marker governing the playhead — what the tempo controls act
* on. Null when the track has no grid. */
bpm: number | null
/** Index of that marker; -1 when there is no grid. */
markerIndex: number
/** 0 = no grid, 1 = constant tempo, >1 = a flexible (multi-tempo) grid. */
markerCount: number
/** Position (s) of the governing marker; null when there is no grid. */
markerStart: number | null
/** The playhead is sitting on the governing marker. */
atMarker: boolean
/** The playhead precedes the first marker (whose tempo extrapolates back). */
beforeFirst: boolean
locked: boolean
hasGrid: boolean
/** A snapshot of the grid as loaded exists to restore. */
canReset: boolean
onSetBpm: (bpm: number) => void
onNudgeBpm: (delta: number) => void
/** Octave fix for the governing marker (halve / double its BPM). */
onHalve: () => void
onDouble: () => void
onNudge: (deltaMs: number) => void
onSetHere: () => void
/** Move the governing marker by ±ms. */
onNudgeMarker: (deltaMs: number) => void
/** Add a marker at the playhead (creates the grid when there is none). */
onAddMarker: () => void
/** Delete the governing marker (offered only while standing on it). */
onDeleteMarker: () => void
/** Seek to the adjacent marker — under playhead-derived selection this is
* how the user changes which marker they are editing. */
onPrevMarker: () => void
onNextMarker: () => void
onReset: () => void
onToggleLock: () => void
onDeleteGrid: () => void
/** Detect BPM + first beat and build the grid (sets hotcue 1 + anchor). */
/** Detect BPM + first beat and rebuild the grid as a single marker. */
onAnalyze: () => void
analyzing: boolean
}
/** m:ss.mmm — marker positions need millisecond precision to be useful. */
function markerTime(t: number): string {
const m = Math.floor(t / 60)
const s = t - m * 60
return `${m}:${s < 10 ? '0' : ''}${s.toFixed(3)}`
}
const BTN =
'flex flex-1 items-center justify-center rounded border border-line bg-ink-850 py-1 text-xs ' +
'font-semibold text-text transition-colors hover:border-accent disabled:opacity-30 ' +
@@ -26,25 +55,39 @@ const BTN =
/**
* Beatgrid / tempo panel (Traktor grid-control equivalent): editable BPM, BPM
* nudge (fine ±0.01 / coarse ±0.25), half/double, tap tempo, grid-phase nudge
* (±1/±10 ms), set beat 1 at the playhead, reset to the loaded values, lock,
* and delete grid.
* (±1/±10 ms), add/delete markers, reset to the loaded grid, lock, delete grid.
*
* A beatgrid is a list of tempo markers, and the one being edited is derived
* from the playhead rather than selected separately — so the tempo controls
* always act on the marker governing what you are hearing. Memoised because the
* playhead updates every frame and most of those frames change nothing here.
*/
export function GridControls({
export const GridControls = memo(function GridControls({
bpm,
markerIndex,
markerCount,
markerStart,
atMarker,
beforeFirst,
locked,
hasGrid,
canReset,
onSetBpm,
onNudgeBpm,
onHalve,
onDouble,
onNudge,
onSetHere,
onNudgeMarker,
onAddMarker,
onDeleteMarker,
onPrevMarker,
onNextMarker,
onReset,
onToggleLock,
onDeleteGrid,
onAnalyze,
analyzing,
}: Props) {
const hasGrid = markerCount > 0
const flexible = markerCount > 1
const [editing, setEditing] = useState(false)
const [val, setVal] = useState('')
const tapsRef = useRef<number[]>([])
@@ -96,7 +139,39 @@ export function GridControls({
{bpm != null ? bpm.toFixed(2) : '––'}
</button>
)}
<div className="text-[10px] font-semibold uppercase tracking-wider text-faint">BPM</div>
{!hasGrid ? (
<div className="text-[10px] font-semibold uppercase tracking-wider text-faint">
No grid
</div>
) : !flexible ? (
<div className="text-[10px] font-semibold uppercase tracking-wider text-faint">BPM</div>
) : (
// Flexible grid: show which marker is in charge and let the user step
// between them (which seeks — there is no separate selection).
<div
className={
'flex items-center justify-center gap-1 text-[10px] font-semibold tabular-nums ' +
(beforeFirst ? 'text-faint' : 'text-gold')
}
title={
beforeFirst
? "Playhead is before the first marker — marker 1's tempo extrapolates backwards"
: `Editing marker ${markerIndex + 1} of ${markerCount}`
}
>
<button onClick={onPrevMarker} className="px-1 hover:text-accent" title="Previous marker">
‹
</button>
<span>
{beforeFirst ? '↤ ' : '⊞ '}
{markerIndex + 1}/{markerCount}
{markerStart != null ? ` · ${markerTime(markerStart)}` : ''}
</span>
<button onClick={onNextMarker} className="px-1 hover:text-accent" title="Next marker">
›
</button>
</div>
)}
</div>
{/* BPM nudge — coarse ±0.25 (outer) / fine ±0.01 (inner) */}
@@ -140,16 +215,31 @@ export function GridControls({
{/* halve / double / tap / reset */}
<div className="flex gap-1">
<button className={BTN} onClick={onHalve} disabled={bpm == null} title="Halve BPM">
<button
className={BTN}
onClick={onHalve}
disabled={bpm == null}
title={flexible ? `Halve BPM of marker ${markerIndex + 1}` : 'Halve BPM'}
>
/2
</button>
<button className={BTN} onClick={onDouble} disabled={bpm == null} title="Double BPM">
<button
className={BTN}
onClick={onDouble}
disabled={bpm == null}
title={flexible ? `Double BPM of marker ${markerIndex + 1}` : 'Double BPM'}
>
×2
</button>
<button className={BTN} onClick={tap} title="Tap tempo">
TAP
</button>
<button className={BTN} onClick={onReset} title="Reset to loaded values">
<button
className={BTN}
onClick={onReset}
disabled={!canReset}
title="Restore the beatgrid as loaded"
>
Reset
</button>
</div>
@@ -159,19 +249,49 @@ export function GridControls({
<span className="mr-0.5 text-[10px] font-semibold uppercase tracking-wider text-faint">
Grid
</span>
<button className={BTN} onClick={() => onNudge(-10)} disabled={!hasGrid} title="−10 ms">
{/* Phase nudges move the GOVERNING marker — deliberately not gated on
atMarker, since the drift is heard at the playhead, not at the marker. */}
<button
className={BTN}
onClick={() => onNudgeMarker(-10)}
disabled={!hasGrid}
title="Move this marker −10 ms"
>
◀◀
</button>
<button className={BTN} onClick={() => onNudge(-1)} disabled={!hasGrid} title="−1 ms">
<button
className={BTN}
onClick={() => onNudgeMarker(-1)}
disabled={!hasGrid}
title="Move this marker −1 ms"
>
◀
</button>
<button className={BTN} onClick={onSetHere} title="Set beat 1 at the playhead">
SET
<button
className={BTN}
onClick={onAddMarker}
title={
hasGrid
? 'Add a grid marker at the playhead'
: 'Set the beatgrid at the playhead'
}
>
{hasGrid ? '+ Mrk' : 'SET'}
</button>
<button className={BTN} onClick={() => onNudge(1)} disabled={!hasGrid} title="+1 ms">
<button
className={BTN}
onClick={() => onNudgeMarker(1)}
disabled={!hasGrid}
title="Move this marker +1 ms"
>
▶
</button>
<button className={BTN} onClick={() => onNudge(10)} disabled={!hasGrid} title="+10 ms">
<button
className={BTN}
onClick={() => onNudgeMarker(10)}
disabled={!hasGrid}
title="Move this marker +10 ms"
>
▶▶
</button>
</div>
@@ -190,9 +310,36 @@ export function GridControls({
>
{locked ? '🔒 Locked' : '🔓 Lock'}
</button>
{/* Only a marker you are standing on can be deleted, so one that is
scrolled off-screen can never go by accident. Deleting the last
marker is "delete grid", not a second button doing the same thing. */}
<button
className={BTN}
onClick={onDeleteGrid}
onClick={onDeleteMarker}
disabled={!atMarker || !flexible}
title={
!flexible
? 'Use Delete grid to remove the last marker'
: atMarker
? `Delete grid marker ${markerIndex + 1}`
: 'Park the playhead on a marker to delete it (‹ › to step)'
}
>
🗑 Mrk
</button>
<button
className={BTN}
onClick={() => {
if (
confirm(
flexible
? `Delete this track's beatgrid? All ${markerCount} grid markers will be removed.`
: "Delete this track's beatgrid?",
)
) {
onDeleteGrid()
}
}}
disabled={!hasGrid}
title="Delete beatgrid"
>
@@ -213,4 +360,4 @@ export function GridControls({
</div>
</div>
)
}
})
+18 -9
View File
@@ -1,5 +1,5 @@
import type { CuePoint } from '../api'
import { contrastText, cueColor } from '../lib/cues'
import { contrastText, cueColor, GRID_MARKER_COLOR } from '../lib/cues'
interface Props {
cues: CuePoint[]
@@ -17,14 +17,21 @@ const SLOTS = [0, 1, 2, 3, 4, 5, 6, 7] // Traktor hotcue slots → labelled 1–
* (pointer capture, so a release outside the button still fires) so the parent
* can implement momentary "cue preview" (play while held). Press creates when
* empty and jumps/triggers when assigned; release ends any preview.
*
* A slot may be held by a grid marker's companion cue (Traktor writes one beside
* most of its own markers). Those belong to the beatgrid, so they are shown with
* the marker colour and a ⊞ instead of a number, and pressing one only seeks —
* the backend refuses hotcue edits on them, and showing that up front is better
* than surfacing the refusal as an error.
*/
export function HotcueBar({ cues, selectedSlot, onSlotPress, onSlotRelease }: Props) {
return (
<div className="flex flex-1 items-stretch gap-px">
{SLOTS.map((slot) => {
const cue = cues.find((c) => c.hotcue === slot) ?? null
const selected = selectedSlot === slot
const color = cue ? cueColor(cue) : null
const isMarker = cue?.grid_marker != null
const selected = selectedSlot === slot && !isMarker
const color = cue ? (isMarker ? GRID_MARKER_COLOR : cueColor(cue)) : null
return (
<button
key={slot}
@@ -38,11 +45,13 @@ export function HotcueBar({ cues, selectedSlot, onSlotPress, onSlotRelease }: Pr
onPointerUp={() => onSlotRelease(slot)}
onPointerCancel={() => onSlotRelease(slot)}
title={
cue
? cue.name && cue.name !== 'n.n.'
? `${slot + 1}: ${cue.name}`
: `Hotcue ${slot + 1}`
: `Hotcue ${slot + 1} — click to set at playhead`
isMarker
? `Beatgrid marker ${(cue!.grid_marker ?? 0) + 1} — managed by the grid controls`
: cue
? cue.name && cue.name !== 'n.n.'
? `${slot + 1}: ${cue.name}`
: `Hotcue ${slot + 1}`
: `Hotcue ${slot + 1} — click to set at playhead`
}
style={color ? { backgroundColor: color, color: contrastText(color) } : undefined}
className={
@@ -51,7 +60,7 @@ export function HotcueBar({ cues, selectedSlot, onSlotPress, onSlotRelease }: Pr
(selected ? ' ring-2 ring-inset ring-white/80' : '')
}
>
{slot + 1}
{isMarker ? '⊞' : slot + 1}
</button>
)
})}
+2 -3
View File
@@ -1,5 +1,5 @@
interface Props {
bpm: number | null // beat-loops need a grid; buttons disable without one
hasGrid: boolean // beat-loops need a beatgrid; buttons disable without one
active: boolean // a loop is currently engaged
activeBeats: number | null // size of the active loop (null for a manual loop)
canToggle: boolean // a loop region exists to enable/disable
@@ -23,7 +23,7 @@ const IDLE = 'bg-ink-900 text-text hover:bg-ink-800'
const OFF = 'disabled:opacity-30 disabled:hover:bg-ink-900'
export function LoopControls({
bpm,
hasGrid,
active,
activeBeats,
canToggle,
@@ -34,7 +34,6 @@ export function LoopControls({
onLoopOut,
onToggleActive,
}: Props) {
const hasGrid = !!bpm && bpm > 0
return (
<div className="flex h-10 shrink-0 items-stretch gap-px border-t border-line bg-ink-950">
+8 -6
View File
@@ -1,5 +1,6 @@
import { useEffect, useRef } from 'react'
import type { CuePoint } from '../api'
import type { BeatGrid } from '../lib/beatgrid'
import { drawBeatgrid, drawCuePoint, drawCues, drawLoop } from '../lib/cues'
import { paintWave, type WaveColumn } from '../lib/waveform'
@@ -9,8 +10,9 @@ interface Props {
duration: number
cues: CuePoint[]
cuePoint: number | null
bpm: number | null
gridAnchor: number | null
grid: BeatGrid | null
/** Marker governing the playhead — drawn gold, its segment tinted. */
activeMarker: number
loop: { start: number; end: number } | null
/** Seconds across the view — the zoom level, owned by the parent so it
survives track switches and persists to prefs. */
@@ -40,8 +42,8 @@ export function MainWaveform({
duration,
cues,
cuePoint,
bpm,
gridAnchor,
grid,
activeMarker,
loop,
secPerView,
onZoomChange,
@@ -84,8 +86,8 @@ export function MainWaveform({
if (loop) {
drawLoop(ctx, timeToX(loop.start), timeToX(loop.end), h, dpr)
}
if (bpm && gridAnchor != null) {
drawBeatgrid(ctx, bpm, gridAnchor, startSec, endSec, w, h, dpr)
if (grid) {
drawBeatgrid(ctx, grid, startSec, endSec, w, h, dpr, activeMarker)
}
if (cues.length) {
drawCues(ctx, cues, w, h, dpr, timeToX, true)
+198 -121
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type Track, type TrackCues } from '../api'
import { api, type GridMarker, type Track, type TrackCues } from '../api'
import { buildBeatGrid, GRID_EPS } from '../lib/beatgrid'
import { analyzeWaveform, type WaveColumn } from '../lib/waveform'
import { ScratchEngine } from '../lib/scratchEngine'
import { PlaybackEngine } from '../lib/playbackEngine'
@@ -54,6 +55,9 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const [cols, setCols] = useState<WaveColumn[] | null>(null)
const [waveStatus, setWaveStatus] = useState<'loading' | 'ready' | 'error'>('loading')
const [cueData, setCueData] = useState<TrackCues | null>(null)
// The beatgrid, rebuilt whenever the cue data is replaced (every edit returns
// a fresh TrackCues, so this stays in step automatically). Null = no grid.
const grid = useMemo(() => buildBeatGrid(cueData?.grid_markers), [cueData?.grid_markers])
const [snap, setSnap] = useState(true)
const [selectedSlot, setSelectedSlot] = useState<number | null>(null)
const [cuePoint, setCuePoint] = useState(0) // floating "CUE" point (frontend-only)
@@ -65,7 +69,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const [loopActive, setLoopActive] = useState(false)
const [activeBeats, setActiveBeats] = useState<number | null>(null)
const loopInRef = useRef<number | null>(null) // armed manual loop-in point
const originalGridRef = useRef<{ bpm: number | null; anchor: number | null } | null>(null)
const originalGridRef = useRef<GridMarker[] | null>(null)
const audioCtxRef = useRef<AudioContext | null>(null) // playback
const scratchCtxRef = useRef<AudioContext | null>(null) // scratch (kept separate!)
@@ -244,8 +248,10 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
.then((d) => {
if (cancelled) return
setCueData(d)
// Remember the loaded grid values for "Reset".
originalGridRef.current = { bpm: d.bpm, anchor: d.grid_anchor }
// Remember the grid as loaded, for "Reset". Flexible-grid editing is
// multi-step and destructive, so restoring exactly what Traktor had is
// the safety net. Set only here (keyed on trackId), never by an edit.
originalGridRef.current = d.grid_markers
})
.catch(() => {
if (!cancelled) setCueData(null)
@@ -397,13 +403,14 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
// active loop. seek() clamps to [0, duration], preserves play/pause state.
const beatJump = (dir: -1 | 1) => {
const eng = playbackRef.current
const bpm = cueData?.bpm ?? null
if (!eng || !bpm || bpm <= 0) return
if (!eng || !grid) return
if (loopActive) {
eng.setLoopEnabled(false)
setLoopActive(false)
}
eng.seek(eng.getPosition() + dir * jumpBeats * (60 / bpm))
// Phase is preserved in BEAT space, so a jump crossing a tempo change lands
// on the musically right beat rather than a fixed number of seconds away.
eng.seek(grid.advanceBeats(eng.getPosition(), dir * jumpBeats))
setCurrent(eng.getPosition())
}
@@ -475,13 +482,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
// ---- loops ------------------------------------------------------------
// Snap a time to the nearest beat when Snap is on (needs a beatgrid).
const snapTime = (t: number) => {
const bpm = cueData?.bpm ?? null
const anchor = cueData?.grid_anchor ?? null
if (!snap || !bpm || bpm <= 0 || anchor == null) return Math.max(0, t)
const beat = 60 / bpm
return Math.max(0, anchor + Math.round((t - anchor) / beat) * beat)
}
const snapTime = (t: number) => (snap && grid ? grid.snapToBeat(t) : Math.max(0, t))
const engagLoop = (start: number, end: number, beats: number | null) => {
const eng = playbackRef.current
@@ -496,8 +497,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const setBeatLoop = (beats: number) => {
const eng = playbackRef.current
const bpm = cueData?.bpm ?? null
if (!eng || !eng.ready || !bpm || bpm <= 0) return
if (!eng || !eng.ready || !grid) return
// Pressing the size of the loop that's already playing disables it.
if (loopActive && activeBeats === beats) {
eng.setLoopEnabled(false)
@@ -508,7 +508,9 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
// Resizing an active loop keeps its start locked; only a fresh loop starts
// at the current playhead.
const start = loopActive && loopRegion ? loopRegion.start : snapTime(eng.getPosition())
engagLoop(start, start + beats * (60 / bpm), beats)
// Measured from the loop's own start, so a loop spanning a tempo change
// still covers the right number of beats.
engagLoop(start, grid.advanceBeats(start, beats), beats)
}
const loopIn = () => {
@@ -534,6 +536,19 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
setCurrent(eng.getPosition())
}
// A beat loop's end is stored in seconds, so editing the tempo of a marker
// inside it would silently detune it. Re-derive the end whenever the grid
// changes, keeping the loop the beat length the user actually asked for.
useEffect(() => {
if (!grid || !loopActive || !loopRegion || activeBeats == null) return
const end = grid.advanceBeats(loopRegion.start, activeBeats)
if (Math.abs(end - loopRegion.end) < 1e-4) return
playbackRef.current?.setLoop(loopRegion.start, end, true)
setLoopRegion({ start: loopRegion.start, end })
// Only the grid should trigger this; loop state changes set the end already.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [grid])
// ---- hotcues ----------------------------------------------------------
const hotcueAt = (slot: number) => cueData?.cues.find((c) => c.hotcue === slot) ?? null
@@ -546,10 +561,11 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
// Map a loop length (seconds) back to a preset beat count for the size
// highlight, snapping to the nearest preset when it's close (float tolerance).
const beatsForLength = (length: number): number | null => {
const bpm = cueData?.bpm ?? null
if (!bpm || bpm <= 0) return null
const beats = length / (60 / bpm)
// Needs the start as well as the length: under a marker list a duration
// alone no longer identifies a beat count.
const beatsForLoop = (start: number, length: number): number | null => {
if (!grid) return null
const beats = grid.beatsBetween(start, start + length)
let best: number | null = null
let bestDiff = Infinity
for (const s of LOOP_SIZES) {
@@ -570,6 +586,12 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const onSlotPress = async (slot: number) => {
if (!track) return
const cue = hotcueAt(slot)
// A grid marker's companion cue holds this slot. It belongs to the beatgrid,
// so pressing it only seeks — never create, retype, select or preview.
if (cue?.grid_marker != null) {
seekManual(cue.start)
return
}
if (!cue) {
try {
// Setting a hotcue while a loop is active stores it as a loop hotcue.
@@ -593,7 +615,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
// A loop hotcue jumps to its start AND re-engages a loop of its length.
if (cue.type === LOOP_TYPE && cue.length > 0) {
seek(cue.start)
engagLoop(cue.start, cue.start + cue.length, beatsForLength(cue.length))
engagLoop(cue.start, cue.start + cue.length, beatsForLoop(cue.start, cue.length))
} else {
seek(cue.start)
}
@@ -607,7 +629,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
// Auto Hotcues: the backend analyses the track's audio (librosa structural
// segmentation), snaps boundaries to the beatgrid, and fills empty slots only.
// Requires a beatgrid (button disabled otherwise).
const canAutoCue = !!(cueData?.bpm && cueData.bpm > 0 && cueData.grid_anchor != null)
const canAutoCue = grid != null
const runAutoHotcues = async () => {
if (!track || !canAutoCue || autoBusy) return
const hotcueCount = (c: TrackCues | null) =>
@@ -654,7 +676,9 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
}
const deleteHotcueSlot = async (slot: number) => {
if (!track || !hotcueAt(slot)) return // nothing to remove in an empty slot
const existing = hotcueAt(slot)
if (!track || !existing) return // nothing to remove in an empty slot
if (existing.grid_marker != null) return // beatgrid-owned: delete the marker instead
try {
applyCueEdit(await api.deleteHotcue(track.id, slot))
if (selectedSlot === slot) setSelectedSlot(null)
@@ -663,105 +687,72 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
}
}
// ---- keyboard shortcuts ----------------------------------------------
// Space → play/pause; 1–8 → the matching hotcue slot; Shift+1–8 → delete it.
// Digits are read from e.code (layout-/Shift-independent) and a ref holds the
// latest handlers so the listener attaches once and never goes stale.
const shortcutsRef = useRef({
toggle,
onSlotPress,
onSlotRelease,
deleteHotcueSlot,
onCuePress,
onCueRelease,
beatJump,
})
shortcutsRef.current = {
toggle,
onSlotPress,
onSlotRelease,
deleteHotcueSlot,
onCuePress,
onCueRelease,
beatJump,
}
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
// Ignore while typing in a field or with a non-Shift modifier held.
const t = e.target as HTMLElement | null
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return
if (e.metaKey || e.ctrlKey || e.altKey) return
if (e.repeat) return // held key auto-repeats — treat as one press+hold
if (e.code === 'Space') {
e.preventDefault()
shortcutsRef.current.toggle()
return
}
if (e.code === 'KeyC') {
e.preventDefault()
shortcutsRef.current.onCuePress()
return
}
if (e.code === 'ArrowLeft') {
e.preventDefault()
shortcutsRef.current.beatJump(-1)
return
}
if (e.code === 'ArrowRight') {
e.preventDefault()
shortcutsRef.current.beatJump(1)
return
}
const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/)
if (digit) {
e.preventDefault()
const slot = Number(digit[1]) - 1
if (e.shiftKey) void shortcutsRef.current.deleteHotcueSlot(slot)
else void shortcutsRef.current.onSlotPress(slot)
}
}
// keyup ends a held hotcue's momentary preview (release).
const onKeyRelease = (e: KeyboardEvent) => {
if (e.code === 'KeyC') shortcutsRef.current.onCueRelease()
const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/)
if (digit) shortcutsRef.current.onSlotRelease(Number(digit[1]) - 1)
}
window.addEventListener('keydown', onKey)
window.addEventListener('keyup', onKeyRelease)
return () => {
window.removeEventListener('keydown', onKey)
window.removeEventListener('keyup', onKeyRelease)
}
}, [])
// ---- beatgrid ---------------------------------------------------------
const gridBpm = cueData?.bpm ?? null
const gridAnchor = cueData?.grid_anchor ?? null
// Beat jump needs a tempo to size beats; disabled on ungridded tracks.
const canBeatJump = ready && gridBpm != null && gridBpm > 0
// Which marker the grid controls act on is derived from the playhead — there
// is no separate selection state to keep in sync.
const activeMarkerIndex = grid ? grid.markerIndexAt(current) : -1
const activeMarker = activeMarkerIndex >= 0 ? grid!.markers[activeMarkerIndex] : null
// ~4px of the current zoom, so "on the marker" stays usable at 2s and 64s/view.
const markerHitSec = Math.max(0.01, secPerView / 250)
const atMarker = !!grid && grid.isOnMarker(current, markerHitSec)
const beforeFirstMarker = !!grid && current < grid.markers[0].start - GRID_EPS
// Beat jump needs a grid to size beats; disabled on ungridded tracks.
const canBeatJump = ready && grid != null
const editGrid = async (patch: { bpm?: number; anchor?: number }) => {
if (!track) return
const playheadNow = () => playbackRef.current?.getPosition() ?? current
const editMarker = async (index: number, patch: { bpm?: number; start?: number }) => {
if (!track || index < 0) return
try {
applyCueEdit(await api.setGrid(track.id, patch))
applyCueEdit(await api.setGridMarker(track.id, index, patch))
} catch (e) {
onError?.((e as Error).message)
}
}
const setBpm = (bpm: number) => editGrid({ bpm })
const nudgeBpm = (delta: number) =>
gridBpm && editGrid({ bpm: Math.round((gridBpm + delta) * 1000) / 1000 })
const halveBpm = () => gridBpm && editGrid({ bpm: gridBpm / 2 })
const doubleBpm = () => gridBpm && editGrid({ bpm: gridBpm * 2 })
const setBpm = (bpm: number) =>
editMarker(activeMarkerIndex, { bpm: Math.round(bpm * 1000) / 1000 })
const nudgeBpm = (delta: number) => activeMarker && setBpm(activeMarker.bpm + delta)
// /2 and x2 retempo the governing marker only, like every other tempo control
// in this panel — a section can be octave-wrong on its own.
const halveBpm = () => activeMarker && setBpm(activeMarker.bpm / 2)
const doubleBpm = () => activeMarker && setBpm(activeMarker.bpm * 2)
const nudgeGrid = (deltaMs: number) => {
if (gridAnchor == null) return
editGrid({ anchor: Math.max(0, gridAnchor + deltaMs / 1000) })
if (!activeMarker) return
editMarker(activeMarkerIndex, { start: Math.max(0, activeMarker.start + deltaMs / 1000) })
}
const setGridHere = () => editGrid({ anchor: playbackRef.current?.getPosition() ?? current })
const resetGrid = () => {
// Adds a marker at the playhead — and creates the grid when there is none.
// Uses the raw playhead, not snapTime: a marker defines where beats are.
const addMarkerHere = async () => {
if (!track) return
try {
applyCueEdit(await api.addGridMarker(track.id, playheadNow()))
} catch (e) {
onError?.((e as Error).message)
}
}
const deleteMarkerHere = async () => {
if (!track || activeMarkerIndex < 0) return
try {
applyCueEdit(await api.deleteGridMarker(track.id, activeMarkerIndex))
} catch (e) {
onError?.((e as Error).message)
}
}
// Seeking between markers IS how the user changes which marker is active.
const seekToMarker = (index: number) => {
if (!grid || index < 0 || index >= grid.count) return
seekManual(grid.markers[index].start)
}
const prevMarker = () => seekToMarker(grid ? grid.prevMarkerIndex(current, markerHitSec) : -1)
const nextMarker = () => seekToMarker(grid ? grid.nextMarkerIndex(current, markerHitSec) : -1)
const resetGrid = async () => {
const o = originalGridRef.current
if (!o) return
editGrid({ bpm: o.bpm ?? undefined, anchor: o.anchor ?? undefined })
if (!track || !o) return
try {
applyCueEdit(await api.replaceGridMarkers(track.id, o))
} catch (e) {
onError?.((e as Error).message)
}
}
const toggleLock = async () => {
if (!track) return
@@ -793,6 +784,84 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
}
}
// ---- keyboard shortcuts ----------------------------------------------
// Space → play/pause; 1–8 → the matching hotcue slot; Shift+1–8 → delete it.
// ←/→ → beat jump; Shift+←/→ → step between grid markers.
// Digits are read from e.code (layout-/Shift-independent) and a ref holds the
// latest handlers so the listener attaches once and never goes stale.
const shortcutsRef = useRef({
toggle,
onSlotPress,
onSlotRelease,
deleteHotcueSlot,
onCuePress,
onCueRelease,
beatJump,
prevMarker,
nextMarker,
})
shortcutsRef.current = {
toggle,
onSlotPress,
onSlotRelease,
deleteHotcueSlot,
onCuePress,
onCueRelease,
beatJump,
prevMarker,
nextMarker,
}
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
// Ignore while typing in a field or with a non-Shift modifier held.
const t = e.target as HTMLElement | null
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return
if (e.metaKey || e.ctrlKey || e.altKey) return
if (e.repeat) return // held key auto-repeats — treat as one press+hold
if (e.code === 'Space') {
e.preventDefault()
shortcutsRef.current.toggle()
return
}
if (e.code === 'KeyC') {
e.preventDefault()
shortcutsRef.current.onCuePress()
return
}
if (e.code === 'ArrowLeft') {
e.preventDefault()
if (e.shiftKey) shortcutsRef.current.prevMarker()
else shortcutsRef.current.beatJump(-1)
return
}
if (e.code === 'ArrowRight') {
e.preventDefault()
if (e.shiftKey) shortcutsRef.current.nextMarker()
else shortcutsRef.current.beatJump(1)
return
}
const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/)
if (digit) {
e.preventDefault()
const slot = Number(digit[1]) - 1
if (e.shiftKey) void shortcutsRef.current.deleteHotcueSlot(slot)
else void shortcutsRef.current.onSlotPress(slot)
}
}
// keyup ends a held hotcue's momentary preview (release).
const onKeyRelease = (e: KeyboardEvent) => {
if (e.code === 'KeyC') shortcutsRef.current.onCueRelease()
const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/)
if (digit) shortcutsRef.current.onSlotRelease(Number(digit[1]) - 1)
}
window.addEventListener('keydown', onKey)
window.addEventListener('keyup', onKeyRelease)
return () => {
window.removeEventListener('keydown', onKey)
window.removeEventListener('keyup', onKeyRelease)
}
}, [])
const selectedCue = selectedSlot != null ? hotcueAt(selectedSlot) : null
const showWaves = track && cols && waveStatus === 'ready'
const activeLoop = loopActive && loopRegion ? loopRegion : null
@@ -818,15 +887,23 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
{track && (
<GridControls
bpm={gridBpm}
bpm={activeMarker?.bpm ?? null}
markerIndex={activeMarkerIndex}
markerCount={grid?.count ?? 0}
markerStart={activeMarker?.start ?? null}
atMarker={atMarker}
beforeFirst={beforeFirstMarker}
locked={cueData?.locked ?? false}
hasGrid={gridAnchor != null}
canReset={originalGridRef.current != null}
onSetBpm={setBpm}
onNudgeBpm={nudgeBpm}
onHalve={halveBpm}
onDouble={doubleBpm}
onNudge={nudgeGrid}
onSetHere={setGridHere}
onNudgeMarker={nudgeGrid}
onAddMarker={addMarkerHere}
onDeleteMarker={deleteMarkerHere}
onPrevMarker={prevMarker}
onNextMarker={nextMarker}
onReset={resetGrid}
onToggleLock={toggleLock}
onDeleteGrid={deleteGrid}
@@ -907,8 +984,8 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
duration={duration}
cues={cueData?.cues ?? []}
cuePoint={cuePoint}
bpm={cueData?.bpm ?? null}
gridAnchor={cueData?.grid_anchor ?? null}
grid={grid}
activeMarker={activeMarkerIndex}
loop={activeLoop}
secPerView={secPerView}
onZoomChange={setSecPerView}
@@ -938,7 +1015,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
</div>
<LoopControls
bpm={cueData?.bpm ?? null}
hasGrid={grid != null}
active={loopActive}
activeBeats={activeBeats}
canToggle={loopRegion != null}