Implemented deck transport controls

This commit is contained in:
patben8 committed 2026-11-03 08:40:38 +01:00
1 parent 9df73ddcd2
commit fe91a46bae
15 files changed
+1748 -41

No files matched your search

+152 -12
View File
@@ -5,14 +5,20 @@ import { useDeckKeys, type DeckKeyTargets } from '../lib/deckKeys'
import { useDropTarget, type DragPayload } from '../lib/drag'
import { Icon } from '../lib/icons'
import { usePrefsWriter } from '../lib/prefs'
import { mixer } from '../lib/audio/mixer'
import { alignedPosition, effectiveBpm, octaveFor, phaseOffset, syncRate, type DeckTempo as Tempo } from '../lib/sync'
import { DeckControls } from './deck/DeckControls'
import { DeckHeader } from './deck/DeckHeader'
import { DeckOverlays } from './deck/DeckOverlays'
import { DeckTempo } from './deck/DeckTempo'
import { DeckMainWave, DeckOverview, type DeckView } from './deck/DeckWaves'
import { useDeck, type Deck } from './deck/useDeck'
import { MIN_SEC, MAX_SEC, DEFAULT_SEC } from './MainWaveform'
import { MixerPanel } from './mixer/MixerPanel'
export type DeckId = 'A' | 'B'
/** `performance.now()` — the global, which this file's `performance` prop shadows. */
const performance_now = () => globalThis.performance.now()
export const DECK_IDS: DeckId[] = ['A', 'B']
export const otherDeck = (id: DeckId): DeckId => (id === 'A' ? 'B' : 'A')
@@ -92,7 +98,7 @@ function useDeckView(): DeckView {
* One deck normally. PERFORMANCE MODE (P, or the button beside Auto hotcues)
* adds deck B: the two headers side by side, the two main waveforms stacked at
* one zoom past one playhead line, the overviews side by side, then each
* deck's controls (the mixer goes between them). Keys go to the FOCUSED deck
* deck's controls with the mixer between them. Keys go to the FOCUSED deck
* (click a deck), Alt/Option to the other. Deck B stays mounted while hidden,
* so leaving and coming back finds it as it was — paused on the way out.
*/
@@ -119,6 +125,8 @@ export function PrepStrip({
...common,
...decks.A,
caps: caps.A,
channel: 'A',
tempoActive: performance,
onPlayingChange: playingA,
onEditTags: editTags(decks.A),
persist: true,
@@ -128,6 +136,8 @@ export function PrepStrip({
...common,
...decks.B,
caps: caps.B,
channel: 'B',
tempoActive: performance,
onPlayingChange: playingB,
onEditTags: editTags(decks.B),
persist: false,
@@ -142,6 +152,105 @@ export function PrepStrip({
if (!performance) pauseB.current()
}, [performance])
// The mixer: in circuit only in performance mode (prep listening stays as it
// was), each channel's trim starting at its track's own auto gain, and each
// deck's tempo for the echo.
useEffect(() => mixer().setActive(performance), [performance])
const gainA = decks.A.track?.auto_gain_db ?? null
const gainB = decks.B.track?.auto_gain_db ?? null
useEffect(() => mixer().setAutoGain('A', gainA ?? 0), [gainA])
useEffect(() => mixer().setAutoGain('B', gainB ?? 0), [gainB])
const bpmA = (a.activeMarker?.bpm ?? 0) * a.rate
const bpmB = (b.activeMarker?.bpm ?? 0) * b.rate
useEffect(() => mixer().setTempo('A', bpmA), [bpmA])
useEffect(() => mixer().setTempo('B', bpmB), [bpmB])
// ---- tempo master + SYNC -------------------------------------------------
// A synced deck follows the MASTER's tempo (at the nearer octave) and, while
// both play, its beats: re-aligned whenever they drift past 3% of a beat —
// after a hotcue, a jump, the follower starting. Moving its pitch fader by
// hand releases it. All from the grids (lib/sync.ts).
const [master, setMaster] = useState<DeckId>('A')
const [synced, setSynced] = useState<Record<DeckId, boolean>>({ A: false, B: false })
const live = useRef({ a, b, master, synced })
live.current = { a, b, master, synced }
const lastAlign = useRef<Record<DeckId, number>>({ A: 0, B: 0 })
const tempoOf = (d: Deck): Tempo => ({ grid: d.grid, pos: d.playheadNow(), rate: d.rate })
/** Bring follower `id` onto master `m`'s tempo, and its beats onto the
* master's when both play and `phase` (or a drift past the threshold). */
const follow = useCallback((id: DeckId, m: DeckId, force: boolean) => {
const { a, b } = live.current
const f = id === 'A' ? a : b
const md = m === 'A' ? a : b
const r = syncRate(tempoOf(md), tempoOf(f))
if (!r) return
if (Math.abs(r.rate - f.rate) > 1e-6) f.setRate(r.rate)
if (!f.playing || !md.playing) return
const now = performance_now()
if (!force && now - lastAlign.current[id] < 400) return
const ft = tempoOf(f)
const off = phaseOffset(tempoOf(md), ft, r.octave)
if (off == null || Math.abs(off) < (force ? 0.005 : 0.03)) return
lastAlign.current[id] = now
f.seek(alignedPosition(ft, off, r.octave))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
if (!performance) return
const t = setInterval(() => {
const { master, synced } = live.current
for (const id of DECK_IDS) if (synced[id] && id !== master) follow(id, master, false)
}, 150)
return () => clearInterval(t)
}, [performance, follow])
// A follower that starts playing lines up at once, not on the next tick.
useEffect(() => {
const { master, synced } = live.current
for (const id of DECK_IDS) if (synced[id] && id !== master) follow(id, master, true)
}, [a.playing, b.playing, follow])
// Leaving performance mode releases SYNC (the decks go back to their own tempo).
useEffect(() => {
if (!performance) setSynced({ A: false, B: false })
}, [performance])
const toggleSync = (id: DeckId) => {
if (synced[id]) {
setSynced((s) => ({ ...s, [id]: false }))
return
}
// SYNC on the master hands the master to the other deck.
const m = master === id ? otherDeck(id) : master
if (m !== master) setMaster(m)
setSynced({ [id]: true, [m]: false } as Record<DeckId, boolean>)
follow(id, m, true)
}
const makeMaster = (id: DeckId) => {
setMaster(id)
setSynced((s) => ({ ...s, [id]: false }))
}
const syncBlocked = (id: DeckId): string | null => {
const m = master === id ? otherDeck(id) : master
if (!deckOf(id).grid) return 'This track has no beatgrid — Analyze it to sync'
if (!deckOf(m).track) return `Deck ${m} has nothing loaded to sync to`
if (!deckOf(m).grid) return `Deck ${m}'s track has no beatgrid to sync to`
return null
}
/** This deck's beats against the other's, for the phase meter. */
const phaseOf = (id: DeckId) => () => {
const { a, b } = live.current
const me = id === 'A' ? a : b
const other = id === 'A' ? b : a
if (!me.playing || !other.playing) return null
const mine = tempoOf(me)
const theirs = tempoOf(other)
const em = effectiveBpm(mine)
const eo = effectiveBpm(theirs)
if (em == null || eo == null) return null
return phaseOffset(theirs, mine, octaveFor(eo, em))
}
const keys = useRef<DeckKeyTargets>({ focused: null, other: null })
keys.current = {
focused: deckOf(lead).shortcuts,
@@ -193,10 +302,8 @@ export function PrepStrip({
{id}
</span>
)
// The centre column: the toggle above, the mixer (phase 4) below.
const centre = 'w-9 shrink-0'
return (
<div className="glass flex h-[29rem] shrink-0 flex-col gap-2 p-4">
<div className="glass flex h-[32rem] shrink-0 flex-col gap-2 p-4">
<div className="flex shrink-0 items-center gap-3">
{pane('A', <DeckHeader deck={a} compact badge={badge('A')} />)}
{toggle}
@@ -205,15 +312,48 @@ export function PrepStrip({
{DECK_IDS.map((id) => (
<DeckLane key={id} id={id} deck={deckOf(id)} view={view} focused={id === focused} drop={drop} onFocus={onFocus} />
))}
<div className="flex h-7 shrink-0 gap-3">
{pane('A', <DeckOverview deck={a} view={view} />)}
<div className={centre} />
{pane('B', <DeckOverview deck={b} view={view} />)}
</div>
<div className="flex shrink-0 gap-3">
{pane('A', <DeckControls deck={a} stacked />, 'flex min-w-0 flex-1')}
<div className={centre} />
{pane('B', <DeckControls deck={b} stacked />, 'flex min-w-0 flex-1')}
{pane(
'A',
<>
<div className="h-7">
<DeckOverview deck={a} view={view} />
</div>
<DeckControls deck={a} stacked />
<DeckTempo
deck={a}
master={master === 'A'}
synced={synced.A}
syncBlocked={syncBlocked('A')}
onSync={() => toggleSync('A')}
onMaster={() => makeMaster('A')}
onManualPitch={() => synced.A && setSynced((s) => ({ ...s, A: false }))}
phase={phaseOf('A')}
/>
</>,
'flex min-w-0 flex-1 flex-col gap-2',
)}
<MixerPanel autoGain={{ A: gainA, B: gainB }} />
{pane(
'B',
<>
<div className="h-7">
<DeckOverview deck={b} view={view} />
</div>
<DeckControls deck={b} stacked />
<DeckTempo
deck={b}
master={master === 'B'}
synced={synced.B}
syncBlocked={syncBlocked('B')}
onSync={() => toggleSync('B')}
onMaster={() => makeMaster('B')}
onManualPitch={() => synced.B && setSynced((s) => ({ ...s, B: false }))}
phase={phaseOf('B')}
/>
</>,
'flex min-w-0 flex-1 flex-col gap-2',
)}
</div>
<DeckOverlays deck={a} />
<DeckOverlays deck={b} />
+11 -9
View File
@@ -18,10 +18,10 @@ const DIVIDER = <span aria-hidden className="h-7 w-px shrink-0 bg-line" />
* bank would hit its minimum (with a lockable grid's extra Lock button, and the
* Hot / Mem toggle's ~3rem with its gap), so move it with the controls.
*
* `stacked` (half-width, in performance mode) gives the pads — or the grid or
* memory strip — a row of their own under the rest, which then folds the tempo
* group below 52rem (measured in the app: row one needs ~50rem before the
* tempo group overflows).
* `stacked` (beside the mixer, in performance mode) puts the pads — or the grid
* or memory strip — on a second row with the two mode switches, and folds the
* tempo group below 44rem (measured in the app: transport + loops + the tempo
* group need ~42rem).
*/
export function DeckControls({ deck, stacked = false }: { deck: Deck; stacked?: boolean }) {
const {
@@ -240,14 +240,16 @@ export function DeckControls({ deck, stacked = false }: { deck: Deck; stacked?:
{DIVIDER}
{loopControls}
<span className="flex-1" />
{bankSwitch}
{modeSwitch}
<TempoControls {...tempoProps} className="@max-[52rem]:hidden" />
<TempoFold locked={tempoProps.locked} className="hidden @max-[52rem]:flex">
<TempoControls {...tempoProps} className="@max-[44rem]:hidden" />
<TempoFold locked={tempoProps.locked} className="hidden @max-[44rem]:flex">
<TempoControls {...tempoProps} />
</TempoFold>
</div>
<div className="flex h-11 shrink-0 items-center">{strip}</div>
<div className="flex h-11 shrink-0 items-center gap-2">
{modeSwitch}
{bankSwitch}
{strip}
</div>
</div>
)
}
+170
View File
@@ -0,0 +1,170 @@
import { useEffect, useRef } from 'react'
import { bendFor, PITCH_RANGES } from '../../lib/sync'
import { Fader } from '../mixer/Controls'
import type { Deck } from './useDeck'
interface Props {
deck: Deck
/** This deck is the tempo master (the one SYNC follows). */
master: boolean
synced: boolean
/** Why SYNC cannot engage (no grid on a deck), else null. */
syncBlocked: string | null
onSync: () => void
onMaster: () => void
/** Moving the pitch fader — or bending — by hand takes the deck out of SYNC. */
onManualPitch: () => void
/** This deck's beats against the other deck's, in beats (-0.5..0.5); null
* when either has no grid or is not playing. Read every frame. */
phase: () => number | null
}
const lit = 'is-selected text-text'
const unlit = 'btn-glass text-muted'
/**
* A deck's tempo row in performance mode (decided 2026-11-02): keylock, SYNC,
* MASTER, the phase meter, the pitch fader with its range, and the tempo as
* heard. The pitch fader is the deck's SPEED — the grid's BPM is still edited
* in the header and Grid mode.
*/
export function DeckTempo({ deck, master, synced, syncBlocked, onSync, onMaster, onManualPitch, phase }: Props) {
const { pitch, setPitch, pitchRange, changeRange, rate, setBend, keylock, setKeylock, keylockAvailable, activeMarker, track } = deck
const bpm = activeMarker ? activeMarker.bpm * rate : null
const pct = pitch * pitchRange * 100
const nextRange = PITCH_RANGES[(PITCH_RANGES.indexOf(pitchRange) + 1) % PITCH_RANGES.length]
return (
<div className="flex h-9 shrink-0 items-center gap-2">
<button
onClick={() => setKeylock(!keylock)}
disabled={!keylockAvailable}
aria-pressed={keylock}
title={
keylockAvailable
? keylock
? 'Keylock on: a tempo change keeps the pitch'
: 'Keylock off: the pitch moves with the tempo, like a turntable'
: 'Keylock is unavailable (the time-stretcher did not load)'
}
className={`h-8 shrink-0 rounded-full px-3 text-[11px] font-semibold tracking-[0.08em] disabled:opacity-40 ${keylock ? lit : unlit}`}
>
KEY
</button>
<button
onClick={onSync}
disabled={!track || (!synced && syncBlocked != null)}
aria-pressed={synced}
title={syncBlocked ?? (synced ? 'Synced: following the master’s tempo and beats — click to release' : 'Match the master’s tempo and line the beats up')}
className={`h-8 shrink-0 rounded-full px-3 text-[11px] font-semibold tracking-[0.08em] disabled:opacity-40 ${synced ? lit : unlit}`}
>
SYNC
</button>
<button
onClick={onMaster}
disabled={!track}
aria-pressed={master}
title={master ? 'Tempo master: a synced deck follows this one' : 'Make this deck the tempo master'}
className={`h-8 shrink-0 rounded-full px-3 text-[11px] font-semibold tracking-[0.08em] disabled:opacity-40 ${
master ? 'bg-gold/20 text-gold shadow-[inset_0_0_0_1px_rgb(255_200_97/0.6)]' : unlit
}`}
>
MASTER
</button>
<PhaseMeter
phase={phase}
disabled={!track}
onBend={(b) => {
if (b !== 1) onManualPitch()
setBend(b)
}}
/>
<Fader
orientation="horizontal"
value={pitch}
min={-1}
max={1}
defaultValue={0}
onChange={(v) => {
setPitch(Math.abs(v) < 0.01 ? 0 : v)
onManualPitch()
}}
label="Pitch"
describe={() => `Pitch ${fmtPct(pct)} (range ±${Math.round(pitchRange * 100)}%) — double-click to reset`}
className="min-w-16 flex-1"
/>
<button
onClick={() => changeRange(nextRange)}
title={`Pitch range ±${Math.round(pitchRange * 100)}% — click for ±${Math.round(nextRange * 100)}%`}
className="btn-glass h-8 w-11 shrink-0 rounded-full font-mono text-[11px] text-muted"
>
±{Math.round(pitchRange * 100)}
</button>
<div className="well flex h-8 w-[6.5rem] shrink-0 flex-col items-end justify-center rounded-lg px-2 leading-none">
<span className="font-mono text-[13px] font-medium text-text">{bpm ? bpm.toFixed(2) : '—'}</span>
<span className={`font-mono text-[10px] ${pct === 0 ? 'text-faint' : 'text-muted'}`}>{fmtPct(pct)}</span>
</div>
</div>
)
}
const fmtPct = (p: number) => `${p > 0 ? '+' : p < 0 ? '−' : '±'}${Math.abs(p).toFixed(2)}%`
/** Where this deck's beats fall against the other deck's: centre = in phase,
* right = ahead. Drawn every frame straight to the DOM. DRAG it to bend the
* deck's speed — right faster, left slower — and let go to spring back, the
* way a DJ nudges a platter to bring the beats together. */
function PhaseMeter({
phase,
onBend,
disabled,
}: {
phase: () => number | null
onBend: (bend: number) => void
disabled: boolean
}) {
const markRef = useRef<HTMLSpanElement>(null)
const dragX = useRef<number | null>(null)
const release = () => {
if (dragX.current == null) return
dragX.current = null
onBend(1)
}
const read = useRef(phase)
read.current = phase
useEffect(() => {
let raf = 0
const tick = () => {
const el = markRef.current
const p = read.current()
if (el) {
el.style.opacity = p == null ? '0' : '1'
if (p != null) {
el.style.left = `${(p + 0.5) * 100}%`
el.style.background = Math.abs(p) < 0.03 ? 'var(--color-mint)' : 'var(--color-gold)'
}
}
raf = requestAnimationFrame(tick)
}
raf = requestAnimationFrame(tick)
return () => cancelAnimationFrame(raf)
}, [])
return (
<div
onPointerDown={(e) => {
if (disabled || e.button !== 0) return
e.preventDefault()
e.currentTarget.setPointerCapture(e.pointerId)
dragX.current = e.clientX
}}
onPointerMove={(e) => dragX.current != null && onBend(bendFor(e.clientX - dragX.current, e.shiftKey))}
onPointerUp={release}
onPointerCancel={release}
onLostPointerCapture={release}
className={`well relative h-3 w-20 shrink-0 touch-none overflow-hidden rounded-full ${disabled ? '' : 'cursor-ew-resize'}`}
title="Phase: where this deck's beats fall against the other deck's (centre = together). Drag to bend the speed — right faster, left slower (Shift: finer)"
>
<span aria-hidden className="absolute inset-y-0.5 left-1/2 w-px bg-white/25" />
<span ref={markRef} className="absolute inset-y-0 w-1.5 -translate-x-1/2 rounded-full opacity-0" />
</div>
)
}
+56 -1
View File
@@ -36,8 +36,11 @@ import { analyzeStems, analyzeWaveform, type WaveColumn } from '../../lib/wavefo
import type { RawWave } from '../../lib/rawWave'
import { setAmbientFromArt } from '../../lib/ambient'
import { DeckEngine } from '../../lib/audio/deckEngine'
import { mixer } from '../../lib/audio/mixer'
import type { Channel } from '../../lib/audio/mixerState'
import { resumeAudio } from '../../lib/audio/context'
import { STEM_KEYS, type DeckShortcuts } from '../../lib/deckKeys'
import { PITCH_RANGES, rangeFor } from '../../lib/sync'
import { invalidateTrackLists } from '../../lib/trackQueries'
import { eventLabel } from '../AutoCueDialog'
import type { MenuItem } from '../ContextMenu'
@@ -73,6 +76,11 @@ export interface DeckOptions {
/** Opens Edit Tags for the loaded track — passed only where the library
* will accept the edit, so the cover popup offers it only then. */
onEditTags?: (track: Track) => void
/** Performance mode: the pitch fader and keylock apply (else the deck plays
* at the file's own tempo). */
tempoActive?: boolean
/** The mixer channel this deck plays into (default A). */
channel?: Channel
/** Persist this deck's loop size and cue bank (deck A; default true). */
persist?: boolean
/** Recolour the app from this deck's cover art (default true). */
@@ -90,6 +98,8 @@ export function useDeck({
cuesRefresh = 0,
onPlayingChange,
onEditTags,
tempoActive = false,
channel = 'A',
persist = true,
leadsAmbient = true,
}: DeckOptions) {
@@ -198,7 +208,7 @@ export function useDeck({
const getEngine = (): Promise<DeckEngine> => {
if (!enginePromiseRef.current) {
enginePromiseRef.current = DeckEngine.create().then((eng) => {
enginePromiseRef.current = DeckEngine.create(mixer().input(channel)).then((eng) => {
playbackRef.current = eng
eng.setOnEnded(() => setPlaying(false))
// The deck hands itself back after a scratch's coast settles.
@@ -1181,6 +1191,39 @@ export function useDeck({
}
}
// ---- tempo (performance mode) ---------------------------------------------
// The pitch fader (-1..1 of its range), the range, and keylock. Applied only
// while `tempoActive`: the prep deck always plays at the file's own tempo, so
// grid edits are made against the music as it is. Kept while hidden, so
// coming back to performance mode finds the fader where it was.
const [pitch, setPitchState] = useState(0)
const [pitchRange, setPitchRange] = useState(PITCH_RANGES[0])
const [keylock, setKeylock] = useState(true)
// A pitch BEND: a momentary push or drag on top of the fader (the phase
// meter's drag), 1 = none. Part of `rate`, so the readout and a follower see it.
const [bend, setBend] = useState(1)
const rate = tempoActive ? (1 + pitch * pitchRange) * bend : 1
useEffect(() => {
playbackRef.current?.setRate(rate)
}, [rate, ready])
useEffect(() => {
playbackRef.current?.setKeylock(keylock)
}, [keylock, ready])
const setPitch = (p: number) => setPitchState(Math.max(-1, Math.min(1, p)))
/** An exact rate (SYNC), widening the range when the fader cannot reach it.
* Never called mid-bend: a bend releases the deck's SYNC. */
const setRate = (r: number) => {
const range = rangeFor(r, pitchRange)
setPitchRange(range)
setPitchState((r - 1) / range)
}
/** A new range keeps the tempo where the fader can still reach it. */
const changeRange = (range: number) => {
setPitchState(Math.max(-1, Math.min(1, (pitch * pitchRange) / range)))
setPitchRange(range)
}
const keylockAvailable = playbackRef.current?.keylockAvailable ?? true
// ---- stems: mute / solo ------------------------------------------------------
// What each stem plays at: a muted stem is 0. Both engines follow it (the
// scratch engine re-sums).
@@ -1418,6 +1461,18 @@ export function useDeck({
runAnalyzeGrid,
toggleStem,
shortcuts,
seek,
pitch,
setPitch,
pitchRange,
changeRange,
rate,
setRate,
bend,
setBend,
keylock,
setKeylock,
keylockAvailable,
}
}
+166
View File
@@ -0,0 +1,166 @@
// The mixer's controls: a rotary knob and a fader. Mouse-driven — drag (Shift
// for fine), scroll, double-click to reset — and NOT focusable, so the deck's
// keys (←/→, Space) never land on them by accident.
import { useRef, type PointerEvent, type WheelEvent } from 'react'
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v))
/** Pixels of drag for the whole travel (Shift: five times finer). */
const DRAG_PX = 150
interface KnobProps {
value: number
min: number
max: number
/** Reset value (double-click); also where the arc starts on a bipolar knob. */
defaultValue: number
/** The arc grows from the centre (EQ, colour) rather than from the left. */
bipolar?: boolean
onChange: (v: number) => void
label: string
/** The tooltip, for the value it would show. */
describe: (v: number) => string
color?: string
size?: number
}
/** A point on the knob's circle at angle `deg` (0 = straight up). */
function polar(r: number, deg: number, c: number): [number, number] {
const rad = ((deg - 90) * Math.PI) / 180
return [c + r * Math.cos(rad), c + r * Math.sin(rad)]
}
function arc(r: number, from: number, to: number, c: number): string {
if (Math.abs(to - from) < 0.5) return ''
const [a, b] = from < to ? [from, to] : [to, from]
const [x1, y1] = polar(r, a, c)
const [x2, y2] = polar(r, b, c)
return `M ${x1} ${y1} A ${r} ${r} 0 ${b - a > 180 ? 1 : 0} 1 ${x2} ${y2}`
}
export function Knob({
value,
min,
max,
defaultValue,
bipolar = false,
onChange,
label,
describe,
color = 'var(--color-accent)',
size = 26,
}: KnobProps) {
const drag = useRef<{ y: number; v: number } | null>(null)
const range = max - min
const angle = -135 + ((clamp(value, min, max) - min) / range) * 270
const start = bipolar ? -135 + ((defaultValue - min) / range) * 270 : -135
const c = size / 2
const r = c - 3
const [px, py] = polar(r - 4, angle, c)
const onPointerDown = (e: PointerEvent<HTMLDivElement>) => {
if (e.button !== 0) return
e.preventDefault()
e.currentTarget.setPointerCapture(e.pointerId)
drag.current = { y: e.clientY, v: value }
}
const onPointerMove = (e: PointerEvent<HTMLDivElement>) => {
const d = drag.current
if (!d) return
const px = e.shiftKey ? DRAG_PX * 5 : DRAG_PX
onChange(clamp(d.v + ((d.y - e.clientY) / px) * range, min, max))
}
const onWheel = (e: WheelEvent<HTMLDivElement>) => {
onChange(clamp(value - (e.deltaY / (e.shiftKey ? 2000 : 400)) * range, min, max))
}
return (
<div className="flex flex-col items-center gap-0.5" title={describe(value)}>
<div
role="slider"
aria-label={label}
aria-valuemin={min}
aria-valuemax={max}
aria-valuenow={value}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={() => (drag.current = null)}
onPointerCancel={() => (drag.current = null)}
onDoubleClick={() => onChange(defaultValue)}
onWheel={onWheel}
className="cursor-ns-resize touch-none select-none"
style={{ width: size, height: size }}
>
<svg width={size} height={size}>
<circle cx={c} cy={c} r={r} fill="rgb(0 0 0 / 0.36)" stroke="rgb(255 255 255 / 0.08)" />
<path d={arc(r, -135, 135, c)} fill="none" stroke="rgb(255 255 255 / 0.1)" strokeWidth={2.5} strokeLinecap="round" />
<path
d={arc(r, start, angle, c)}
fill="none"
stroke={color}
strokeWidth={2.5}
strokeLinecap="round"
style={{ filter: `drop-shadow(0 0 3px ${color})` }}
/>
<line x1={c} y1={c} x2={px} y2={py} stroke="var(--color-text)" strokeWidth={2} strokeLinecap="round" />
</svg>
</div>
<span className="text-[8.5px] font-semibold uppercase leading-none tracking-[0.08em] text-faint">{label}</span>
</div>
)
}
interface FaderProps {
value: number
min: number
max: number
defaultValue: number
onChange: (v: number) => void
orientation: 'vertical' | 'horizontal'
label: string
describe: (v: number) => string
className?: string
}
/** A fader: grab anywhere on it and the cap follows the pointer. */
export function Fader({ value, min, max, defaultValue, onChange, orientation, label, describe, className = '' }: FaderProps) {
const vertical = orientation === 'vertical'
const t = (clamp(value, min, max) - min) / (max - min)
const set = (e: PointerEvent<HTMLDivElement>) => {
const box = e.currentTarget.getBoundingClientRect()
const f = vertical ? 1 - (e.clientY - box.top) / box.height : (e.clientX - box.left) / box.width
onChange(min + clamp(f, 0, 1) * (max - min))
}
return (
<div
role="slider"
aria-label={label}
aria-orientation={orientation}
aria-valuemin={min}
aria-valuemax={max}
aria-valuenow={value}
title={describe(value)}
onPointerDown={(e) => {
if (e.button !== 0) return
e.preventDefault()
e.currentTarget.setPointerCapture(e.pointerId)
set(e)
}}
onPointerMove={(e) => e.currentTarget.hasPointerCapture(e.pointerId) && set(e)}
onDoubleClick={() => onChange(defaultValue)}
className={`relative touch-none select-none ${vertical ? 'w-6 cursor-ns-resize' : 'h-6 cursor-ew-resize'} ${className}`}
>
<div
className={`well absolute rounded-full ${vertical ? 'inset-y-1.5 left-1/2 w-1.5 -translate-x-1/2' : 'inset-x-1.5 top-1/2 h-1.5 -translate-y-1/2'}`}
/>
<div
className={`btn-glass pointer-events-none absolute rounded-md ${
vertical ? 'left-0 h-3 w-6 -translate-y-1/2' : 'top-0 h-6 w-3 -translate-x-1/2'
}`}
style={vertical ? { top: `calc(0.375rem + ${(1 - t) * 100}% - ${(1 - t) * 0.75}rem)` } : { left: `calc(0.375rem + ${t * 100}% - ${t * 0.75}rem)` }}
>
<span className={`absolute bg-text/80 ${vertical ? 'inset-x-1 top-1/2 h-px' : 'inset-y-1 left-1/2 w-px'}`} />
</div>
</div>
)
}
@@ -0,0 +1,275 @@
import { useEffect, useRef, useState, type RefObject } from 'react'
import { mixer } from '../../lib/audio/mixer'
import { faderGain, filterSweep, echoBeats, eqGain, gainToDb, TRIM_RANGE_DB, EQ_CUT_DB } from '../../lib/audio/mixerMath'
import {
DEFAULT_CHANNEL,
FX_LABELS,
FX_PARAM,
FX_TYPES,
setChannel,
setMixer,
useMixer,
type Channel,
type FxType,
} from '../../lib/audio/mixerState'
import { Icon } from '../../lib/icons'
import { ContextMenu } from '../ContextMenu'
import { Fader, Knob } from './Controls'
/** The meters' scale (dBFS). */
const METER_FLOOR = -48
const METER_TOP = 3
const fmtDb = (db: number, places = 1) =>
!isFinite(db) ? '−∞ dB' : `${db > 0 ? '+' : db < 0 ? '−' : ''}${Math.abs(db).toFixed(places)} dB`
function describeFx(fx: FxType, c: number, param: number): string {
const a = Math.round(Math.abs(c) * 100)
if (Math.abs(c) < 0.02) return `${FX_LABELS[fx]}: off (turn left or right)`
switch (fx) {
case 'filter': {
const s = filterSweep(c)!
const hz = s.freq >= 1000 ? `${(s.freq / 1000).toFixed(1)} kHz` : `${Math.round(s.freq)} Hz`
return `Filter: ${s.type === 'lowpass' ? 'low-pass' : 'high-pass'} at ${hz}`
}
case 'echo':
return `Echo ${a}% · ${beatsLabel(echoBeats(param))} · ${c < 0 ? 'darker' : 'thinner'} repeats`
case 'space':
return `Space ${a}% · ${c < 0 ? 'darker' : 'thinner'}`
case 'noise':
return `Noise ${a}% · ${c < 0 ? 'low-pass' : 'high-pass'} sweep`
case 'crush':
return `Crush ${a}%`
}
}
function beatsLabel(b: number): string {
return b === 1 ? '1 beat' : b === 0.75 ? '3/4 beat' : b === 0.5 ? '1/2 beat' : b === 0.25 ? '1/4 beat' : '1/8 beat'
}
/**
* The mixer, between the decks in performance mode (decided 2026-11-02): per
* channel TRIM (on top of the track's auto gain), HI / MID / LOW, a colour
* effect with its own selector and parameter, a fader and its meter; between
* them the master meter and the limiter's light; the crossfader beneath. The
* values live in `mixerState` and the audio in `mixer.ts`.
*/
export function MixerPanel({ autoGain }: { autoGain: Record<Channel, number | null> }) {
const meterRefs = {
A: useRef<HTMLDivElement>(null),
B: useRef<HTMLDivElement>(null),
master: useRef<HTMLDivElement>(null),
}
const limitRef = useRef<HTMLSpanElement>(null)
// One frame loop for every meter, writing the DOM directly — sixty React
// renders a second for three bars would be waste.
useEffect(() => {
let raf = 0
const held = { A: METER_FLOOR, B: METER_FLOOR, master: METER_FLOOR }
let limitUntil = 0
const tick = (now: number) => {
const lv = mixer().levels()
for (const k of ['A', 'B', 'master'] as const) {
const db = Math.max(METER_FLOOR, lv[k])
held[k] = db >= held[k] ? db : Math.max(db, held[k] - 0.6) // fall back ~36 dB/s
const el = meterRefs[k].current
if (el) {
el.style.height = `${((held[k] - METER_FLOOR) / (METER_TOP - METER_FLOOR)) * 100}%`
el.style.background =
held[k] > -1 ? 'var(--color-pink)' : held[k] > -9 ? 'var(--color-gold)' : 'var(--color-mint)'
}
}
if (lv.limiting > 0.5) limitUntil = now + 600
if (limitRef.current) limitRef.current.dataset.on = String(now < limitUntil)
raf = requestAnimationFrame(tick)
}
raf = requestAnimationFrame(tick)
return () => cancelAnimationFrame(raf)
// The refs are stable.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const crossfader = useMixer((s) => s.crossfader)
const curve = useMixer((s) => s.curve)
return (
<div className="well flex w-[24rem] shrink-0 flex-col gap-1.5 rounded-2xl px-2.5 pb-1.5 pt-2.5">
<div className="flex min-h-0 flex-1 items-stretch gap-2">
<Strip ch="A" autoGain={autoGain.A} meterRef={meterRefs.A} />
<div className="flex w-3 flex-col items-center gap-1" title="Master — after the limiter">
<MeterBar fillRef={meterRefs.master} />
<span
ref={limitRef}
data-on="false"
title="The limiter is holding the master below clipping"
className="text-[7.5px] font-bold leading-none tracking-[0.04em] text-faint/50 data-[on=true]:text-pink data-[on=true]:[text-shadow:0_0_6px_var(--color-pink)]"
>
LIM
</span>
</div>
<Strip ch="B" autoGain={autoGain.B} meterRef={meterRefs.B} mirrored />
</div>
<div className="flex h-6 shrink-0 items-center gap-2 px-1">
<span className="font-mono text-[11px] font-semibold text-muted">A</span>
<Fader
orientation="horizontal"
value={crossfader}
min={-1}
max={1}
defaultValue={0}
onChange={(v) => setMixer({ crossfader: Math.abs(v) < 0.03 ? 0 : v })}
label="Crossfader"
describe={(v) =>
`Crossfader (${curve === 'smooth' ? 'smooth' : 'sharp'} curve) — ${
Math.abs(v) < 0.03 ? 'centre' : v < 0 ? `toward A ${Math.round(-v * 100)}%` : `toward B ${Math.round(v * 100)}%`
}`
}
className="flex-1"
/>
<span className="font-mono text-[11px] font-semibold text-muted">B</span>
</div>
</div>
)
}
function MeterBar({ fillRef }: { fillRef: RefObject<HTMLDivElement | null> }) {
return (
<div className="relative w-1.5 flex-1 overflow-hidden rounded-full bg-black/40">
<div ref={fillRef} className="absolute inset-x-0 bottom-0 h-0 rounded-full transition-[background-color] duration-150" />
</div>
)
}
/** One channel: its knobs, then (toward the middle) its fader and meter. */
function Strip({
ch,
autoGain,
meterRef,
mirrored = false,
}: {
ch: Channel
autoGain: number | null
meterRef: RefObject<HTMLDivElement | null>
mirrored?: boolean
}) {
const s = useMixer((m) => m[ch])
const eqKill = useMixer((m) => m.eqKill)
const [fxMenu, setFxMenu] = useState<{ x: number; y: number } | null>(null)
const set = (patch: Parameters<typeof setChannel>[1]) => setChannel(ch, patch)
const describeEq = (band: string) => (v: number) => {
const g = eqGain(v, eqKill)
return `${band} ${Math.abs(v) < 0.01 ? 'flat' : g === 0 ? 'killed' : fmtDb(gainToDb(g))}${
v < 0 ? ` (full left: ${eqKill ? 'kill' : `${EQ_CUT_DB} dB`})` : ''
}`
}
const eq = (band: 'high' | 'mid' | 'low', label: string, name: string) => (
<Knob
value={s[band]}
min={-1}
max={1}
defaultValue={0}
bipolar
onChange={(v) => set({ [band]: Math.abs(v) < 0.03 ? 0 : v })}
label={label}
describe={describeEq(name)}
/>
)
const knobs = (
<div className="grid grid-cols-4 content-between gap-x-1.5">
<Knob
value={s.trim}
min={-TRIM_RANGE_DB}
max={TRIM_RANGE_DB}
defaultValue={0}
bipolar
color="var(--color-text)"
onChange={(v) => set({ trim: Math.abs(v) < 0.3 ? 0 : v })}
label="Trim"
describe={(v) =>
`Trim ${fmtDb(v)}${autoGain != null ? ` on the track's auto gain (${fmtDb(autoGain)})` : ' (this track has no auto gain)'}`
}
/>
{eq('high', 'Hi', 'High')}
{eq('mid', 'Mid', 'Mid')}
{eq('low', 'Low', 'Low')}
<button
onClick={(e) => {
const r = e.currentTarget.getBoundingClientRect()
setFxMenu({ x: r.left, y: r.bottom + 4 })
}}
title="Which effect the COLOR knob drives"
className="btn-glass col-span-2 mt-0.5 flex h-6 items-center justify-center gap-0.5 self-start rounded-md text-[10px] font-semibold uppercase tracking-[0.06em] text-text"
>
{FX_LABELS[s.fx]}
<Icon name="chevronDown" size={11} />
</button>
<Knob
value={s.color}
min={-1}
max={1}
defaultValue={0}
bipolar
color="var(--color-gold)"
onChange={(v) => set({ color: Math.abs(v) < 0.02 ? 0 : v })}
label="Color"
describe={(v) => describeFx(s.fx, v, s.param)}
/>
<Knob
value={s.param}
min={0}
max={1}
defaultValue={DEFAULT_CHANNEL.param}
color="var(--color-gold)"
onChange={(v) => set({ param: v })}
label="Prm"
describe={(v) =>
`${FX_PARAM[s.fx]}: ${s.fx === 'echo' ? beatsLabel(echoBeats(v)) : `${Math.round(v * 100)}%`}`
}
/>
</div>
)
const fader = (
<div className="flex flex-col items-center gap-0.5">
<Fader
orientation="vertical"
value={s.fader}
min={0}
max={1}
defaultValue={1}
onChange={(v) => set({ fader: v })}
label={`Channel ${ch} fader`}
describe={(v) => `Channel ${ch}: ${fmtDb(gainToDb(faderGain(v)))}`}
className="flex-1"
/>
<span className="font-mono text-[10px] font-semibold leading-none text-muted">{ch}</span>
</div>
)
const meter = (
<div className="flex flex-col pb-3" title={`Channel ${ch} level (after its fader)`}>
<MeterBar fillRef={meterRef} />
</div>
)
return (
<div className={`flex min-w-0 flex-1 items-stretch gap-1.5 ${mirrored ? 'flex-row-reverse' : ''}`}>
{knobs}
{fader}
{meter}
{fxMenu && (
<ContextMenu
x={fxMenu.x}
y={fxMenu.y}
onClose={() => setFxMenu(null)}
items={[
{ heading: `Channel ${ch} · colour effect` },
...FX_TYPES.map((t) => ({
label: FX_LABELS[t],
hint: t === s.fx ? '✓' : undefined,
onClick: () => set({ fx: t }),
})),
]}
/>
)}
</div>
)
}