diff --git a/CLAUDE.md b/CLAUDE.md index 4df8ba7..f817129 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -387,14 +387,31 @@ Two independent apps that talk over HTTP: browser via `@tauri-apps/plugin-shell` `open` — falls back to `window.open` outside Tauri; "Skip this version" persists `skippedUpdateVersion` to userprefs via `/api/prefs`; all failures are silent). - - **Prep strip** (DJ deck across the top of the window): `PrepStrip` owns it — - transport (play/pause, CUE), two waveforms (`MainWaveform` scrolling+zoomable - — its zoom is owned by `PrepStrip` so it survives track switches and persists, - `OverviewWaveform` whole-track), `LoopControls`, `HotcueBar`, `GridControls` - (BPM readout/editor, fine ±0.01 / coarse ±0.25 BPM nudge, /2·×2, tap tempo, - marker nudge, add/delete marker, lock, delete grid (confirmed) — all on the - marker **governing the playhead**, since a beatgrid is a marker list and - there is no separate marker selection; see "Beatgrid" below). + - **Prep strip** (DJ deck across the top of the window): `PrepStrip` owns it, + in three rows. **Header**: cover, title/artist · album · genre, a Read-only + badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` — + click to type an exact BPM), SNAP, Analyze, Auto hotcues. **Waveforms**: + `MainWaveform` (scrolling; zoom +/− in its corner and Cmd/Ctrl+scroll, owned + by `PrepStrip` so it survives track switches and persists) over + `OverviewWaveform`. **Controls**: play, CUE, `LoopControls`, then EITHER + `HotcueBar` OR — in **Grid mode** — `GridEditStrip`, then `TempoControls` + (±0.01 / ±0.25, ÷2 ×2, tap, lock) and the Grid toggle. Every grid control acts + on the marker **governing the playhead**, since a beatgrid is a marker list + and there is no separate marker selection; see "Beatgrid" below. + - **One size for loops AND beat jump** (`beatSize`, 1/32–32, persisted as + `beatSize`; the old `beatJumpBeats` pref is read once on upgrade). + `LoopControls` has a BEAT / MAN switch: BEAT shows `− size +` (the size + key sets or clears a loop of that length; −/+ halve/double, resizing an + engaged beat loop from its locked start), MAN shows IN / OUT / toggle. + **‹ › (and ←/→) MOVE an engaged loop by its own length**, Traktor-style, + and only jump the playhead when no loop is engaged. The move sets the new + loop BEFORE seeking: `PlaybackEngine.seek` honours the loop in force, so + seeking first wraps the playhead back into the old loop. + - **Hotcue edits live on the pad's right-click menu** (type as one-click + choices, Rename…, Delete); there is no standalone type dropdown or delete + button. Rename re-sets the slot with its own start/type/length plus the + new name, since `set_cue` replaces a slot. A non-editable cue gets the + same menu disabled, not no menu. Prep libs live in `src/lib/`: `playbackEngine.ts` (Web Audio, seamless loops), `scratchEngine.ts` (drag-to-scratch), `waveform.ts` (frequency-colored analysis + paint), `beatgrid.ts` (the marker-list beat math — every @@ -752,7 +769,7 @@ that number and nothing else — everything derives from it: - ✅ Track prep — audio playback, frequency-colored scrolling waveform, scratch, beatgrid display + editing, cue/hotcue create/jump/delete, loops; keyboard shortcuts (Space = play/pause, 1–8 = hotcues, Shift+1–8 = delete, Cmd/Ctrl+↑/↓ = - beat jump size). See "Prep engine". + loop/jump size). See "Prep engine". - ✅ Track prep Tier 2 — cue-point fine editing / audio export polish - ✅ Flexible beatgrids — the grid is a marker list end to end (marker-level commands, piecewise beat math, playhead-derived marker editing). Step 1 of the diff --git a/frontend/src/components/BeatJumpControls.tsx b/frontend/src/components/BeatJumpControls.tsx deleted file mode 100644 index f33edfb..0000000 --- a/frontend/src/components/BeatJumpControls.tsx +++ /dev/null @@ -1,80 +0,0 @@ -import { Icon } from '../lib/icons' - -/** Jump-size cycle, in beats. Fractional sizes allow fine micro-nudging. */ -export const BEAT_JUMP_SIZES = [0.25, 0.5, 1, 2, 4, 8, 16, 32] - -interface Props { - /** Current jump size (one of BEAT_JUMP_SIZES). */ - beats: number - /** Step the jump size down (-1) / up (+1) through BEAT_JUMP_SIZES. */ - onStep: (dir: -1 | 1) => void - /** Jump the playhead back (-1) / forward (+1) by `beats`. */ - onJump: (dir: -1 | 1) => void - /** Disabled when the loaded track has no beatgrid. */ - disabled: boolean -} - -const BTN = - 'btn-glass flex h-7 w-7 shrink-0 items-center justify-center rounded-lg ' + - 'font-mono text-xs font-semibold text-text disabled:opacity-30' - -/** Beats-only readout: 0.25 → "1/4", 0.5 → "1/2", else the integer. */ -function sizeLabel(beats: number): string { - if (beats === 0.25) return '1/4' - if (beats === 0.5) return '1/2' - return String(beats) -} - -/** - * Beat-jump control cluster (Traktor/Serato equivalent): step the jump size, - * then jump the playhead forward/back by that many beats — phase-preserving, - * playback-only. Presentational + controlled; PrepStrip owns the size state and - * performs the actual seek. Disabled wholesale when the track is ungridded. - */ -export function BeatJumpControls({ beats, onStep, onJump, disabled }: Props) { - const atMin = beats <= BEAT_JUMP_SIZES[0] - const atMax = beats >= BEAT_JUMP_SIZES[BEAT_JUMP_SIZES.length - 1] - return ( -
- - Jump - - - - {sizeLabel(beats)} - - - - - -
- ) -} diff --git a/frontend/src/components/GridControls.tsx b/frontend/src/components/GridControls.tsx index 12016fc..4aa2bd3 100644 --- a/frontend/src/components/GridControls.tsx +++ b/frontend/src/components/GridControls.tsx @@ -1,45 +1,20 @@ -import { memo, useRef, useState } from 'react' +import { useRef, useState } from 'react' import { Icon } from '../lib/icons' -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 - /** 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 - /** 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 rebuild the grid as a single marker. */ - onAnalyze: () => void - analyzing: boolean -} +// The deck's beatgrid controls, in three pieces that live in three places: +// +// BpmReadout — the header's BPM: shows the governing marker's tempo, and +// is where an exact BPM is typed (click it). +// TempoControls — the everyday tempo tools, always on the control row: +// nudge ±0.01 / ±0.25, ÷2 ×2, tap tempo, lock. +// GridEditStrip — only in Grid mode, in place of the hotcue pads: step +// between markers, nudge the marker ±1 / ±10 ms, add or +// delete a marker, delete the grid, reset it. +// +// A beatgrid is a list of tempo markers, and the one being edited is derived +// from the playhead rather than selected separately — so every control acts on +// the marker governing what you are hearing. Presentational: PrepStrip owns the +// state and sends the commands. /** m:ss.mmm — marker positions need millisecond precision to be useful. */ function markerTime(t: number): string { @@ -48,56 +23,95 @@ function markerTime(t: number): string { return `${m}:${s < 10 ? '0' : ''}${s.toFixed(3)}` } -const BTN = - 'btn-glass flex flex-1 items-center justify-center gap-1 rounded-lg py-1 font-mono text-[11px] ' + - 'font-semibold text-text disabled:opacity-30' - -/** - * 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), 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 const GridControls = memo(function GridControls({ +/** The header readout's BPM cell. Click to type an exact tempo. */ +export function BpmReadout({ bpm, - markerIndex, - markerCount, - markerStart, - atMarker, - beforeFirst, - locked, - canReset, + editable, onSetBpm, - onNudgeBpm, - onHalve, - onDouble, - onNudgeMarker, - onAddMarker, - onDeleteMarker, - onPrevMarker, - onNextMarker, - onReset, - onToggleLock, - onDeleteGrid, - onAnalyze, - analyzing, -}: Props) { - const hasGrid = markerCount > 0 - const flexible = markerCount > 1 +}: { + /** Tempo of the marker governing the playhead; null without a grid. */ + bpm: number | null + editable: boolean + onSetBpm: (bpm: number) => void +}) { const [editing, setEditing] = useState(false) const [val, setVal] = useState('') - const tapsRef = useRef([]) - const commit = () => { const n = parseFloat(val) if (isFinite(n) && n > 0) onSetBpm(Math.round(n * 1000) / 1000) setEditing(false) } + const label = ( + + BPM{editable && bpm != null ? ' ✎' : ''} + + ) + if (editing) { + return ( +
+ {label} + setVal(e.target.value)} + onBlur={commit} + onKeyDown={(e) => { + if (e.key === 'Enter') commit() + if (e.key === 'Escape') setEditing(false) + e.stopPropagation() // Space/arrows must not drive the deck while typing + }} + className="w-[5.5rem] rounded-md bg-ink-800 px-1 font-mono text-[17px] font-semibold text-accent outline-none ring-1 ring-accent" + /> +
+ ) + } + return ( + + ) +} +const T_BTN = + 'flex h-8 items-center justify-center rounded-lg font-mono text-xs text-text transition-colors ' + + 'hover:bg-ink-800 disabled:opacity-30 disabled:hover:bg-transparent' + +/** Nudge / octave / tap / lock — always visible on the control row. */ +export function TempoControls({ + bpm, + locked, + lockable, + flexible, + markerIndex, + onSetBpm, + onNudgeBpm, + onHalve, + onDouble, + onToggleLock, +}: { + bpm: number | null + locked: boolean + lockable: boolean + flexible: boolean + markerIndex: number + onSetBpm: (bpm: number) => void + onNudgeBpm: (delta: number) => void + onHalve: () => void + onDouble: () => void + onToggleLock: () => void +}) { + const tapsRef = useRef([]) const tap = () => { const now = performance.now() const taps = tapsRef.current @@ -105,231 +119,147 @@ export const GridControls = memo(function GridControls({ taps.push(now) if (taps.length > 8) taps.shift() if (taps.length >= 2) { - const first = taps[0] - const avg = (now - first) / (taps.length - 1) + const avg = (now - taps[0]) / (taps.length - 1) onSetBpm(Math.round((60000 / avg) * 1000) / 1000) } } - + const off = bpm == null + const of = flexible ? ` of marker ${markerIndex + 1}` : '' return ( -
- {/* BPM readout / editor */} -
- {editing ? ( - setVal(e.target.value)} - onBlur={commit} - onKeyDown={(e) => { - if (e.key === 'Enter') commit() - if (e.key === 'Escape') setEditing(false) - }} - className="w-32 rounded-lg bg-ink-800 py-0.5 text-center font-mono text-[26px] font-semibold text-accent outline-none" - /> - ) : ( - - )} - {!hasGrid ? ( -
- No grid -
- ) : !flexible ? ( -
BPM
- ) : ( - // Flexible grid: show which marker is in charge and let the user step - // between them (which seeks — there is no separate selection). -
- - - {beforeFirst ? '↤ ' : '⊞ '} - {markerIndex + 1}/{markerCount} - {markerStart != null ? ` · ${markerTime(markerStart)}` : ''} - - -
- )} -
- - {/* BPM nudge — coarse ±0.25 (outer) / fine ±0.01 (inner) */} -
- - BPM - - - - - -
- - {/* halve / double / tap / reset */} -
- - - - -
- - {/* grid-phase nudge + set beat 1 */} -
- - Grid - - {/* Phase nudges move the GOVERNING marker — deliberately not gated on - atMarker, since the drift is heard at the playhead, not at the marker. */} - - - - - -
- - {/* lock / delete grid */} -
+
+ + + + + + + + + {lockable && ( + )} +
+ ) +} + +/** Grid mode: everything that fixes a grid, in place of the pads. */ +export function GridEditStrip({ + markerIndex, + markerCount, + markerStart, + atMarker, + beforeFirst, + canReset, + onPrevMarker, + onNextMarker, + onNudgeMarker, + onAddMarker, + onDeleteMarker, + onDeleteGrid, + onReset, +}: { + markerIndex: number + markerCount: number + markerStart: number | null + atMarker: boolean + beforeFirst: boolean + canReset: boolean + onPrevMarker: () => void + onNextMarker: () => void + onNudgeMarker: (deltaMs: number) => void + onAddMarker: () => void + onDeleteMarker: () => void + onDeleteGrid: () => void + onReset: () => void +}) { + const hasGrid = markerCount > 0 + const flexible = markerCount > 1 + const nudge = 'flex h-10 items-center px-2 font-mono text-[11px] text-text hover:bg-ink-800 disabled:opacity-30' + const pill = 'flex h-[34px] shrink-0 items-center gap-1.5 rounded-full px-3 text-xs disabled:opacity-35' + return ( + // A container, so the three actions on the right can drop their labels + // rather than overflow when the window is narrow. +
+
+ {/* The spare width goes on the LEFT, so the tools sit together at the + right, next to the tempo controls, instead of splitting across the + row with a gap in the middle. */} +
+
- - {locked ? 'Locked' : 'Lock'} - - {/* 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. */} + + + {hasGrid + ? `${beforeFirst ? '↤ ' : ''}Marker ${markerIndex + 1}/${markerCount}${ + markerStart != null ? ` · ${markerTime(markerStart)}` : '' + }` + : 'No grid'} + + +
+ +
+ {/* Phase nudges move the GOVERNING marker — not gated on atMarker, + since the drift is heard at the playhead, not at the marker. */} + + + + + +
+ + {/* Only a marker you are standing on can be deleted, so one scrolled + off-screen can never go by accident. Deleting the last marker is + Delete grid, not a second button doing the same thing. */} -
- - {/* analyze: detect BPM + first beat, set hotcue 1 + grid anchor */} -
-
) -}) +} diff --git a/frontend/src/components/HotcueBar.tsx b/frontend/src/components/HotcueBar.tsx index b9f61d4..e45a274 100644 --- a/frontend/src/components/HotcueBar.tsx +++ b/frontend/src/components/HotcueBar.tsx @@ -1,6 +1,6 @@ -import type { CSSProperties } from 'react' +import { useRef, useState, type CSSProperties } from 'react' import type { CuePoint } from '../api' -import { cueColor, cueGlyph, withAlpha } from '../lib/cues' +import { CUE_TYPE_LABELS, cueColor, cueGlyph, withAlpha } from '../lib/cues' import { Icon } from '../lib/icons' interface Props { @@ -12,6 +12,12 @@ interface Props { selectedSlot: number | null onSlotPress: (slot: number) => void onSlotRelease: (slot: number) => void + /** Right-click on a pad: the deck opens its Type / Rename / Delete menu. */ + onSlotMenu: (slot: number, x: number, y: number) => void + /** The pad whose name is being edited in place, if any. */ + renamingSlot: number | null + onRenameCommit: (slot: number, name: string) => void + onRenameCancel: () => void } const READONLY_LABELS: Record = { @@ -37,9 +43,16 @@ export function HotcueBar({ selectedSlot, onSlotPress, onSlotRelease, + onSlotMenu, + renamingSlot, + onRenameCommit, + onRenameCancel, }: Props) { return ( -
+ // The group takes the row's spare width; each pad is capped, so on a wide + // window the pads keep a pad's proportions and the space is left empty + // rather than stretching them into bars. +
{Array.from({ length: slotCount }, (_, i) => i).map((slot) => { const cue = cues.find((c) => c.role === 'hotcue' && c.slot === slot) ?? null // Gate on `editable`, never on why: a platform-owned cue is a read-only @@ -51,7 +64,13 @@ export function HotcueBar({ return ( + ) return ( -
- - Loop - - -
- {SIZES.map((size) => { - const isActive = active && activeBeats === size - return ( - - ) - })} +
+
+ {tab('beat', 'BEAT', 'Beat loops, sized in beats')} + {tab('manual', 'MAN', 'Manual loops: set IN and OUT')}
- - - - + {mode === 'beat' ? ( +
+ + + +
+ ) : ( +
+ + + +
+ )} + +
+ + +
) } diff --git a/frontend/src/components/MainWaveform.tsx b/frontend/src/components/MainWaveform.tsx index 67cfd5b..3cf71e2 100644 --- a/frontend/src/components/MainWaveform.tsx +++ b/frontend/src/components/MainWaveform.tsx @@ -13,6 +13,8 @@ interface Props { grid: BeatGrid | null /** Marker governing the playhead — drawn gold, its segment tinted. */ activeMarker: number + /** Grid mode is on: draw the beat lines brighter. */ + emphasizeGrid?: boolean 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. */ @@ -44,6 +46,7 @@ export function MainWaveform({ cuePoint, grid, activeMarker, + emphasizeGrid = false, loop, secPerView, onZoomChange, @@ -92,7 +95,7 @@ export function MainWaveform({ drawLoop(ctx, timeToX(loop.start), timeToX(loop.end), h, dpr) } if (grid) { - drawBeatgrid(ctx, grid, startSec, endSec, w, h, dpr, activeMarker) + drawBeatgrid(ctx, grid, startSec, endSec, w, h, dpr, activeMarker, emphasizeGrid) } if (cues.length) { drawCues(ctx, cues, w, h, dpr, timeToX, true) @@ -121,6 +124,29 @@ export function MainWaveform({ return () => ro.disconnect() }, []) + // Cmd/Ctrl + scroll zooms (a trackpad pinch arrives as ctrl+wheel too). + // Attached by hand because React's onWheel is passive, so it could not stop + // the page scrolling. Accumulated so a trackpad's many tiny deltas step the + // zoom as evenly as a mouse wheel's notches do. + const zoomRef = useRef({ secPerView, onZoomChange }) + zoomRef.current = { secPerView, onZoomChange } + useEffect(() => { + const wrap = wrapRef.current + if (!wrap) return + let acc = 0 + const onWheel = (e: WheelEvent) => { + if (!e.ctrlKey && !e.metaKey) return + e.preventDefault() + acc += e.deltaY + if (Math.abs(acc) < 40) return + const { secPerView: sec, onZoomChange: set } = zoomRef.current + set(Math.min(MAX_SEC, Math.max(MIN_SEC, acc > 0 ? sec * 2 : sec / 2))) + acc = 0 + } + wrap.addEventListener('wheel', onWheel, { passive: false }) + return () => wrap.removeEventListener('wheel', onWheel) + }, []) + // A press that doesn't move is a seek (map offset from centre to a time); // a press that moves is a scratch (map movement to a target time). const timeAtClientX = (clientX: number, rect: DOMRect) => { diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index ece0fae..cdbca87 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -11,7 +11,8 @@ import { } from '../api' import { buildBeatGrid, GRID_EPS } from '../lib/beatgrid' import { slotLabeller, useCaps } from '../lib/capabilities' -import { CUE_TYPE_LABELS } from '../lib/cues' +import { CUE_TYPE_LABELS, cueTypeColor } from '../lib/cues' +import { keyColor } from '../lib/format' import { readOnlyShort, readOnlyNotice } from '../lib/platformCopy' import { analyzeWaveform, type WaveColumn } from '../lib/waveform' import { setAmbientFromArt } from '../lib/ambient' @@ -19,10 +20,10 @@ import { Icon } from '../lib/icons' import { ScratchEngine } from '../lib/scratchEngine' import { PlaybackEngine } from '../lib/playbackEngine' import { AutoCueDialog, eventLabel } from './AutoCueDialog' -import { BeatJumpControls, BEAT_JUMP_SIZES } from './BeatJumpControls' -import { GridControls } from './GridControls' +import { ContextMenu, type MenuItem } from './ContextMenu' +import { BpmReadout, GridEditStrip, TempoControls } from './GridControls' import { HotcueBar } from './HotcueBar' -import { LoopControls } from './LoopControls' +import { LoopControls, LOOP_SIZES, type LoopMode } from './LoopControls' import { MainWaveform, MIN_SEC, MAX_SEC, DEFAULT_SEC } from './MainWaveform' import { OverviewWaveform } from './OverviewWaveform' @@ -46,11 +47,13 @@ interface Props { cuesRefresh?: number } -function fmt(secs: number): string { - if (!isFinite(secs) || secs < 0) return '0:00' - const m = Math.floor(secs / 60) - const s = Math.floor(secs % 60) - return `${m}:${s.toString().padStart(2, '0')}` +/** m:ss.t — the deck's readouts show tenths, as a CDJ does. */ +function fmtTenths(secs: number): string { + if (!isFinite(secs) || secs < 0) secs = 0 + const tenths = Math.floor(secs * 10) + const m = Math.floor(tenths / 600) + const s = Math.floor((tenths % 600) / 10) + return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}.${tenths % 10}` } /** @@ -69,7 +72,6 @@ function slotForDigit(code: string, slotCount: number): number | null { return slot < slotCount ? slot : null } -const LOOP_SIZES = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 1 / 2, 1, 2, 4, 8, 16, 32] /** * The DJ-style "prep strip" across the top of the window: transport controls on @@ -102,7 +104,13 @@ export function PrepStrip({ const [selectedSlot, setSelectedSlot] = useState(null) const [cuePoint, setCuePoint] = useState(0) // floating "CUE" point (frontend-only) const [secPerView, setSecPerView] = useState(DEFAULT_SEC) // main-waveform zoom (persisted) - const [jumpBeats, setJumpBeats] = useState(4) // beat-jump size in beats (persisted) + // ONE size, in beats, for beat loops and beat jump alike (persisted). + const [beatSize, setBeatSize] = useState(4) + const [loopMode, setLoopMode] = useState('beat') + // Grid mode swaps the hotcue pads for the grid-editing strip. + const [gridMode, setGridMode] = useState(false) + const [padMenu, setPadMenu] = useState<{ slot: number; x: number; y: number } | null>(null) + const [renamingSlot, setRenamingSlot] = useState(null) // Loop state (transient — persisted only when saved as a hotcue later). const [loopRegion, setLoopRegion] = useState<{ start: number; end: number } | null>(null) @@ -154,25 +162,28 @@ export function PrepStrip({ } }, [secPerView]) - // Beat-jump size persists the same way (survives track switches + restarts). - const jumpHydratedRef = useRef(false) - const jumpSaveTimer = useRef(null) + // The loop/jump size persists the same way (survives track switches + + // restarts). `beatJumpBeats` is its name from when only beat jump had a size; + // it is read once so an upgrade keeps the user's choice. + const sizeHydratedRef = useRef(false) + const sizeSaveTimer = useRef(null) useEffect(() => { - if (jumpHydratedRef.current || !prefsQuery.data) return - jumpHydratedRef.current = true - const b = (prefsQuery.data as { beatJumpBeats?: unknown }).beatJumpBeats - if (typeof b === 'number' && BEAT_JUMP_SIZES.includes(b)) setJumpBeats(b) + if (sizeHydratedRef.current || !prefsQuery.data) return + sizeHydratedRef.current = true + const prefs = prefsQuery.data as { beatSize?: unknown; beatJumpBeats?: unknown } + const b = prefs.beatSize ?? prefs.beatJumpBeats + if (typeof b === 'number' && LOOP_SIZES.includes(b)) setBeatSize(b) }, [prefsQuery.data]) useEffect(() => { - if (!jumpHydratedRef.current) return // don't clobber saved prefs pre-hydration - if (jumpSaveTimer.current) window.clearTimeout(jumpSaveTimer.current) - jumpSaveTimer.current = window.setTimeout(() => { - api.patchPrefs({ beatJumpBeats: jumpBeats }).catch(() => {}) + if (!sizeHydratedRef.current) return // don't clobber saved prefs pre-hydration + if (sizeSaveTimer.current) window.clearTimeout(sizeSaveTimer.current) + sizeSaveTimer.current = window.setTimeout(() => { + api.patchPrefs({ beatSize }).catch(() => {}) }, 500) return () => { - if (jumpSaveTimer.current) window.clearTimeout(jumpSaveTimer.current) + if (sizeSaveTimer.current) window.clearTimeout(sizeSaveTimer.current) } - }, [jumpBeats]) + }, [beatSize]) const getCtx = (): AudioContext => { if (!audioCtxRef.current) { @@ -219,6 +230,8 @@ export function PrepStrip({ setDuration(0) setReady(false) setSelectedSlot(null) + setPadMenu(null) + setRenamingSlot(null) setLoopRegion(null) setLoopActive(false) setActiveBeats(null) @@ -445,29 +458,42 @@ export function PrepStrip({ seek(t) } - // ---- beat jump -------------------------------------------------------- - // Step the jump size through BEAT_JUMP_SIZES, clamping at both ends (no wrap). - const stepJumpSize = (dir: -1 | 1) => { - setJumpBeats((b) => { - const i = BEAT_JUMP_SIZES.indexOf(b) - const next = Math.min(BEAT_JUMP_SIZES.length - 1, Math.max(0, (i < 0 ? 4 : i) + dir)) - return BEAT_JUMP_SIZES[next] - }) - } - - // Move the playhead exactly `jumpBeats` beats fwd/back, preserving sub-beat - // phase (pure translation, no grid snap). Like seekManual, jumping escapes an - // active loop. seek() clamps to [0, duration], preserves play/pause state. - const beatJump = (dir: -1 | 1) => { + // ---- beat jump / loop move ------------------------------------------ + // ‹ › (and ←/→): an engaged loop MOVES by its own length and keeps playing, + // Traktor-style; otherwise the playhead jumps `beatSize` beats. Both preserve + // sub-beat phase (pure translation, no grid snap), and seek() keeps the + // play/pause state. + const moveOrJump = (dir: -1 | 1) => { const eng = playbackRef.current - if (!eng || !grid) return - if (loopActive) { - eng.setLoopEnabled(false) - setLoopActive(false) + if (!eng || !eng.ready) return + if (loopActive && loopRegion) { + const { start, end } = loopRegion + // A beat loop moves in BEATS, so it lands right across a tempo change; a + // manual loop has no beat length, so it moves by its duration. + let nStart: number + let nEnd: number + if (activeBeats != null && grid) { + nStart = grid.advanceBeats(start, dir * activeBeats) + nEnd = grid.advanceBeats(nStart, activeBeats) + } else { + const len = end - start + nStart = start + dir * len + nEnd = nStart + len + } + if (nStart < 0 || nEnd > duration) return // would leave the track + // The playhead travels with the loop, keeping its place inside it. The + // NEW loop is set first: the engine's seek honours the loop in force, so + // seeking first would wrap the playhead straight back into the old one. + const pos = eng.getPosition() + (nStart - start) + engagLoop(nStart, nEnd, activeBeats) + eng.seek(Math.min(nEnd - 0.001, Math.max(nStart, pos))) + setCurrent(eng.getPosition()) + return } + if (!grid) return // 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)) + eng.seek(grid.advanceBeats(eng.getPosition(), dir * beatSize)) setCurrent(eng.getPosition()) } @@ -593,6 +619,21 @@ export function PrepStrip({ setCurrent(eng.getPosition()) } + // − / + (and Cmd/Ctrl+↓/↑): step the shared size, clamping at both ends. An + // engaged BEAT loop follows it — halving or doubling from its locked start, as + // on a CDJ. A manual loop has no beat size to follow, so it is left alone. + const stepSize = (dir: -1 | 1) => { + const i = LOOP_SIZES.indexOf(beatSize) + const next = LOOP_SIZES[Math.min(LOOP_SIZES.length - 1, Math.max(0, (i < 0 ? 7 : i) + dir))] + if (next === beatSize) return + setBeatSize(next) + if (loopActive && activeBeats != null) setBeatLoop(next) + } + + // The size key: a loop of exactly this size switches off; otherwise a loop of + // this size is set (from the playhead, or resized from an engaged loop's start). + const toggleSizeLoop = () => setBeatLoop(beatSize) + // 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. @@ -745,22 +786,26 @@ export function PrepStrip({ onNotify?.(placed ? 'success' : 'error', parts.join(' · ')) } - const changeSelectedType = async (type: CueType) => { - if (!track || selectedSlot == null) return + const setSlotType = async (slot: number, type: CueType) => { + if (!track) return if (refuseCueEdit()) return try { - applyCueEdit(await api.setCueType(track.id, selectedSlot, type)) + applyCueEdit(await api.setCueType(track.id, slot, type)) } catch (e) { onError?.((e as Error).message) } } - const deleteSelected = async () => { - if (!track || selectedSlot == null) return + // Renaming re-sets the slot with its own position, type and length plus the + // new name — the adapter's set_cue replaces a slot, and keeps a name only + // when called without one. An empty name clears it. + const renameSlot = async (slot: number, name: string) => { + setRenamingSlot(null) + const cue = hotcueAt(slot) + if (!track || !cue) return if (refuseCueEdit()) return try { - applyCueEdit(await api.deleteCue(track.id, selectedSlot)) - setSelectedSlot(null) + applyCueEdit(await api.createCue(track.id, slot, cue.start, cue.type, cue.length, name)) } catch (e) { onError?.((e as Error).message) } @@ -788,8 +833,6 @@ export function PrepStrip({ 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 playheadNow = () => playbackRef.current?.getPosition() ?? current @@ -885,8 +928,9 @@ export function PrepStrip({ // ---- keyboard shortcuts ---------------------------------------------- // Space → play/pause; 1–8 → the matching hotcue slot; Shift+1–8 → delete it. - // ←/→ → beat jump; Shift+←/→ → step between grid markers; Cmd/Ctrl+↑/↓ → - // beat jump size (Shift+↑/↓ is the track table's extend-selection). + // ←/→ → beat jump, or move an engaged loop; Shift+←/→ → step between grid + // markers; Cmd/Ctrl+↑/↓ → the loop/jump size, resizing an engaged beat loop + // (Shift+↑/↓ is the track table's extend-selection). // 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({ @@ -896,8 +940,8 @@ export function PrepStrip({ deleteHotcueSlot, onCuePress, onCueRelease, - beatJump, - stepJumpSize, + moveOrJump, + stepSize, prevMarker, nextMarker, slotCount, @@ -909,8 +953,8 @@ export function PrepStrip({ deleteHotcueSlot, onCuePress, onCueRelease, - beatJump, - stepJumpSize, + moveOrJump, + stepSize, prevMarker, nextMarker, slotCount, @@ -925,7 +969,7 @@ export function PrepStrip({ if ((e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && (e.code === 'ArrowUp' || e.code === 'ArrowDown')) { e.preventDefault() - shortcutsRef.current.stepJumpSize(e.code === 'ArrowUp' ? 1 : -1) + shortcutsRef.current.stepSize(e.code === 'ArrowUp' ? 1 : -1) return } if (e.metaKey || e.ctrlKey || e.altKey) return @@ -943,13 +987,13 @@ export function PrepStrip({ if (e.code === 'ArrowLeft') { e.preventDefault() if (e.shiftKey) shortcutsRef.current.prevMarker() - else shortcutsRef.current.beatJump(-1) + else shortcutsRef.current.moveOrJump(-1) return } if (e.code === 'ArrowRight') { e.preventDefault() if (e.shiftKey) shortcutsRef.current.nextMarker() - else shortcutsRef.current.beatJump(1) + else shortcutsRef.current.moveOrJump(1) return } const slot = slotForDigit(e.code, shortcutsRef.current.slotCount) @@ -973,240 +1017,329 @@ export function PrepStrip({ } }, []) - const selectedCue = selectedSlot != null ? hotcueAt(selectedSlot) : null const showWaves = track && cols && waveStatus === 'ready' const activeLoop = loopActive && loopRegion ? loopRegion : null + const markerCount = grid?.count ?? 0 + const subtitle = track + ? [track.artist ?? 'Unknown artist', track.album, track.genre].filter(Boolean).join(' · ') + : '' + + // The pad's right-click menu: its type (as one-click choices, the current one + // ticked), Rename, Delete. A cue the adapter will not edit gets the same menu + // disabled, so the reason is visible instead of the menu silently not opening. + const padMenuItems = (slot: number): MenuItem[] => { + const cue = hotcueAt(slot) + if (!cue) return [] + const locked = !cue.editable + const items: MenuItem[] = [] + if (cue.type === 'loop') { + items.push({ heading: `Hotcue ${slotLabel(slot)} · Loop` }) + } else if (pointCueTypes.length > 1) { + items.push({ heading: `Hotcue ${slotLabel(slot)} · Type` }) + for (const t of pointCueTypes) { + const color = cueTypeColor(t) + items.push({ + label: CUE_TYPE_LABELS[t], + icon: ( + + ), + hint: t === cue.type ? '✓' : undefined, + disabled: locked, + onClick: () => t !== cue.type && void setSlotType(slot, t), + }) + } + } else { + items.push({ heading: `Hotcue ${slotLabel(slot)}` }) + } + if (locked) items.push({ heading: 'Managed by the DJ app — not editable here' }) + items.push({ separator: true }) + items.push({ + label: 'Rename…', + disabled: locked, + onClick: () => !refuseCueEdit() && setRenamingSlot(slot), + }) + items.push({ + label: 'Delete', + danger: true, + disabled: locked, + onClick: () => void deleteHotcueSlot(slot), + }) + return items + } + + const DIVIDER = return ( -
- {/* Controls */} -
-
- -
+
+ {/* ---- Header: the track, its readouts, the analysis actions ---- */} +
+ +
{track ? ( <> -
- {track.title ?? 'Untitled'} +
+ + {track.title ?? 'Untitled'} + + {/* The deck stays usable for listening on a read-only library, + so say which it is rather than leaving the edit controls + looking live. The controls report the reason when pressed. */} + {readOnlyShort(caps) && ( + + {readOnlyShort(caps)} + + )}
-
- {track.artist ?? 'Unknown artist'} +
+ {subtitle}
- {/* The deck stays usable for listening on a read-only library, so - say which it is rather than leaving the edit controls looking - live. The controls themselves report the reason when pressed. */} - {readOnlyShort(caps) && ( -
- {readOnlyShort(caps)} -
- )} ) : (
No track loaded
)} -
- {track && ( - +
+ ELAPSED + {fmtTenths(current)} +
+ +
+ REMAIN + −{fmtTenths(Math.max(0, duration - current))} +
+ +
+ KEY + + {track?.key || '—'} + +
+ + +
+ + + + +
+ + {/* ---- Waveforms ---- */} + {!track ? ( +
+ Load a track to prep it +
+ ) : waveStatus === 'error' ? ( +
+ Could not load audio — file may be missing or an unsupported format. +
+ ) : ( + <> +
+ {showWaves ? ( + + ) : ( +
+ Analysing waveform… +
+ )} +
+
+ {showWaves && ( + + )} +
+ + )} + + {/* ---- Controls: transport · loop/jump · pads or grid · tempo ---- */} +
+ + + {DIVIDER} + stepSize(-1)} + onBigger={() => stepSize(1)} + loopActive={loopActive} + sizeLit={loopActive && activeBeats === beatSize} + onToggleSize={toggleSizeLoop} + canToggle={loopRegion != null} + onLoopIn={loopIn} + onLoopOut={loopOut} + onToggleLoop={toggleLoop} + onMove={moveOrJump} + /> + {DIVIDER} + {gridMode ? ( + + ) : ( + { + setSelectedSlot(slot) + if (hotcueAt(slot)) setPadMenu({ slot, x, y }) + }} + renamingSlot={renamingSlot} + onRenameCommit={renameSlot} + onRenameCancel={() => setRenamingSlot(null)} /> )} - -
- - -
- {fmt(current)} / {fmt(duration)} -
-
- - 1} + markerIndex={activeMarkerIndex} + onSetBpm={setBpm} + onNudgeBpm={nudgeBpm} + onHalve={halveBpm} + onDouble={doubleBpm} + onToggleLock={toggleLock} /> +
- {/* Waveforms + loop/hotcue controls. */} -
- {!track ? ( -
- Load a track to prep it -
- ) : waveStatus === 'error' ? ( -
- Could not load audio — file may be missing or an unsupported format. -
- ) : ( - <> -
- {showWaves ? ( - - ) : ( -
- Analysing waveform… -
- )} -
-
- {showWaves && ( - - )} -
- - setSnap((s) => !s)} - onSetLoop={setBeatLoop} - onLoopIn={loopIn} - onLoopOut={loopOut} - onToggleActive={toggleLoop} - /> - - {/* Hotcue row: label · 8 slots · type of selected cue · delete. */} -
- - Cues - - -
- {selectedCue && selectedCue.type === 'loop' ? ( - Loop - ) : pointCueTypes.length < 2 ? ( - // One point type means there is nothing to choose between — - // show it rather than a dropdown that cannot change anything. - - {selectedCue ? CUE_TYPE_LABELS[selectedCue.type] : '—'} - - ) : ( - - )} -
- - -
- - )} -
+ {padMenu && ( + setPadMenu(null)} + /> + )} {autoOpen && track && ( , plus: , + grid: , } as const export type IconName = keyof typeof PATHS