import { useEffect, useState } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' import { api, type AutoCueEvent, type AutoCueSlot, type AutoHotcuesResult, type CuePoint, type Track, } from '../api' import { formatDuration } from '../lib/format' import { Modal } from './Modal' /** * Auto Hotcues: bind each hotcue slot to a structural event plus an offset in * beats, then analyse the track and place them all in one go. * * The template (event + offset per slot) is remembered in userprefs — a DJ cues * every track the same way — but the per-slot "replace" ticks are NOT: whether * to overwrite a hand-placed cue is a decision about THIS track, and a * remembered tick would silently clobber the next track's cues. * * Batch mode (`batch` instead of `track`) edits the same remembered template but * does not run it: it hands the slots to `onRun`, which starts a job. There is * no single track to show existing cues for, so each slot's tick reads "Replace * existing" and applies to every track in the batch — still never remembered. */ export const AUTO_CUE_EVENTS: { id: AutoCueEvent; label: string }[] = [ { id: 'first_beat', label: 'First beat' }, { id: 'intro_end', label: 'Intro end' }, { id: 'build_1', label: 'Build 1' }, { id: 'drop_1', label: 'Drop 1' }, { id: 'breakdown_1', label: 'Breakdown 1' }, { id: 'build_2', label: 'Build 2' }, { id: 'drop_2', label: 'Drop 2' }, { id: 'breakdown_2', label: 'Breakdown 2' }, { id: 'build_3', label: 'Build 3' }, { id: 'drop_3', label: 'Drop 3' }, { id: 'breakdown_3', label: 'Breakdown 3' }, { id: 'outro', label: 'Outro start' }, { id: 'last_beat', label: 'Last beat' }, ] const EVENT_IDS = new Set(AUTO_CUE_EVENTS.map((e) => e.id)) export const eventLabel = (id: AutoCueEvent) => AUTO_CUE_EVENTS.find((e) => e.id === id)?.label ?? id interface Row { event: AutoCueEvent | null offset: number // beats } const DEFAULT_TEMPLATE: AutoCueEvent[] = [ 'first_beat', 'build_1', 'drop_1', 'breakdown_1', 'build_2', 'drop_2', 'outro', 'last_beat', ] const PREF_KEY = 'autoCueTemplate' const MAX_OFFSET = 256 /** The remembered template, padded/truncated to this library's bank size. * Anything malformed in prefs falls back to the default for that slot. */ function loadTemplate(prefs: Record | undefined, slots: number): Row[] { const saved = Array.isArray(prefs?.[PREF_KEY]) ? (prefs![PREF_KEY] as unknown[]) : null return Array.from({ length: slots }, (_, i) => { const r = saved?.[i] as { event?: unknown; offset_beats?: unknown } | undefined if (saved && r && typeof r === 'object') { const event = r.event === null ? null : EVENT_IDS.has(String(r.event)) ? (r.event as AutoCueEvent) : null const off = typeof r.offset_beats === 'number' && isFinite(r.offset_beats) ? Math.round(r.offset_beats) : 0 return { event, offset: Math.max(-MAX_OFFSET, Math.min(MAX_OFFSET, off)) } } return { event: DEFAULT_TEMPLATE[i] ?? null, offset: 0 } }) } type Props = { slotCount: number slotLabel: (slot: number) => string onClose: () => void onError: (msg: string) => void } & ( | { track: Track /** The track's current hotcues by slot, to mark occupied rows. */ existing: Map onDone: (result: AutoHotcuesResult) => void batch?: undefined onRun?: undefined } | { track?: undefined existing?: undefined onDone?: undefined /** How many tracks the template will be applied to. */ batch: { count: number; withoutGrid: number } /** Start the batch; resolve once it has started. */ onRun: (slots: AutoCueSlot[]) => Promise } ) export function AutoCueDialog(props: Props) { const { slotCount, slotLabel, onClose, onError } = props const qc = useQueryClient() const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) const [rows, setRows] = useState(null) const [replace, setReplace] = useState>(new Set()) const [busy, setBusy] = useState(false) // Hydrate once from prefs (the query is normally already cached by PrepStrip). useEffect(() => { if (rows === null && (prefs.data || prefs.isError)) setRows(loadTemplate(prefs.data, slotCount)) }, [prefs.data, prefs.isError, rows, slotCount]) const setRow = (i: number, patch: Partial) => setRows((rs) => rs && rs.map((r, j) => (j === i ? { ...r, ...patch } : r))) const nudge = (i: number, by: number) => setRows((rs) => rs && rs.map((r, j) => (j === i ? { ...r, offset: Math.max(-MAX_OFFSET, Math.min(MAX_OFFSET, r.offset + by)) } : r)), ) const active = (rows ?? []).filter((r) => r.event !== null).length const confirm = async () => { if (!rows || busy || active === 0) return setBusy(true) const template = rows.map((r) => ({ event: r.event, offset_beats: r.offset })) // Remember the template whatever the analysis finds: it describes how the // user cues, not this track. api .patchPrefs({ [PREF_KEY]: template }) .then((p) => qc.setQueryData(['prefs'], p)) .catch(() => {}) const slots: AutoCueSlot[] = rows.flatMap((r, slot) => r.event ? [{ slot, event: r.event, offset_beats: r.offset, overwrite: replace.has(slot) }] : [], ) try { if (props.batch) { await props.onRun(slots) } else { props.onDone(await api.autoCues(props.track.id, slots)) } onClose() } catch (e) { onError((e as Error).message) setBusy(false) } } return (
Auto Hotcues
{props.batch ? `${props.batch.count} tracks — the same slots on every one` : `${props.track.artist} — ${props.track.title}`}
Slot Event Offset (beats) {props.batch ? 'Occupied slot' : 'Existing cue'}
{rows === null ? (
Loading…
) : ( rows.map((r, slot) => { const cue = props.existing?.get(slot) const tick = (label: string, title?: string) => ( ) return (
{slotLabel(slot)}
{ const v = Math.round(Number(e.target.value)) if (isFinite(v)) setRow(slot, { offset: Math.max(-MAX_OFFSET, Math.min(MAX_OFFSET, v)) }) }} className="h-7 w-12 rounded-md border border-line bg-ink-850 px-1 text-center text-sm tabular-nums text-text" />
{props.batch ? ( tick('Replace', 'Replace the cue in this slot on every track that has one') ) : cue ? ( cue.editable ? ( tick(`Replace ${cue.name || formatDuration(cue.start)}`, cue.name ?? '') ) : ( Grid cue (kept) ) ) : ( Empty )}
) }) )} {props.batch && props.batch.withoutGrid > 0 && (

{props.batch.withoutGrid} of these {props.batch.withoutGrid === 1 ? 'has' : 'have'} no beatgrid — {props.batch.withoutGrid === 1 ? 'it' : 'they'}’ll get one analyzed first.

)}

Events are found on the beatgrid, counting bar 1 from its first marker — if drops land a bar or two off, move the grid marker onto the first downbeat. Occupied slots are kept unless you tick Replace. A slot is skipped if its beat already has a cue — one you keep, or a new one in a lower slot. Your slot setup is remembered for the next track.

) }