Added analyze dialog

This commit is contained in:
patben8 committed 2026-10-04 17:00:33 +02:00
1 parent 36a6df4d3b
commit e8a53eee07
9 files changed
+322 -146

No files matched your search

+13 -1
View File
@@ -762,6 +762,18 @@ Two independent apps that talk over HTTP:
original files" while conversions are pending (decided: the consequence is original files" while conversions are pending (decided: the consequence is
shown where Save is pressed). `Toast` takes an optional `action`; shown where Save is pressed). `Toast` takes an optional `action`;
`StatusJob.unit: 'bytes'` shows a download in MB. Every background job's status-bar entry reads label + count · a bar SPLIT horizontally when the job reports per-item progress (top = the current item's `fraction`, 0-100 %; bottom = the whole job, (done + fraction) / total, so 99 % into the first of two tracks reads ~50 %) — a single bar otherwise; two colours in one bar was tried and read as confusing · its `status` ("separating 41 %") at its natural width · the item's name LAST (the only part that truncates; full name on hover). The section is a FIXED width (560 px; the view name on the left gives way instead) and everything BEFORE the bar is fixed (count sized for its largest value, "cancelling…" as a status, not a label), so neither a long name nor a phase change moves the bar. The status deliberately has no fixed slot: it is after the bar, and a slot left a gap before the name. `Job.fraction`/`status` come from `JobHandle.progress(fraction=, status=)` and reset whenever `done` advances; a stem conversion maps decode / separate / encode onto a track's 0-1 by measured shares. `StatusJob.unit: 'bytes'` shows a download in MB. Every background job's status-bar entry reads label + count · a bar SPLIT horizontally when the job reports per-item progress (top = the current item's `fraction`, 0-100 %; bottom = the whole job, (done + fraction) / total, so 99 % into the first of two tracks reads ~50 %) — a single bar otherwise; two colours in one bar was tried and read as confusing · its `status` ("separating 41 %") at its natural width · the item's name LAST (the only part that truncates; full name on hover). The section is a FIXED width (560 px; the view name on the left gives way instead) and everything BEFORE the bar is fixed (count sized for its largest value, "cancelling…" as a status, not a label), so neither a long name nor a phase change moves the bar. The status deliberately has no fixed slot: it is after the bar, and a slot left a gap before the name. `Job.fraction`/`status` come from `JobHandle.progress(fraction=, status=)` and reset whenever `done` advances; a stem conversion maps decode / separate / encode onto a track's 0-1 by measured shares.
`AnalyzeDialog` (the context menu's **Analyze…**, decided 2026-10-04:
BPM / Grid / Key ticks, remembered as `analyzeWhat`, each disabled with a
reason where the library cannot store it — offered when EITHER grids or
keys are writable; the Replace questions are inside the dialog, never a
second popup, and never remembered: the grid's only when BPM AND Grid are
ticked, since with one tick adjusting the grid is the point. Every count
and the "Analyze N" button come from `/api/tracks/analyze/preview`, i.e.
the backend's own `plan_grid`. The finished job's toast says what was
written and skipped, by reason. The deck's one-click Analyze writes the
key too, and App hands the deck the fresh copy of its track whenever the
view it came from refetches — the deck otherwise held a load-time
snapshot, so neither an analysed key nor an Edit Tags change reached it),
`AutoCueDialog` (the Auto Hotcues slot template: event + beat offset per `AutoCueDialog` (the Auto Hotcues slot template: event + beat offset per
slot, a per-slot Replace tick for occupied slots — never remembered, since slot, a per-slot Replace tick for occupied slots — never remembered, since
overwriting is a decision about THIS track — and the template itself overwriting is a decision about THIS track — and the template itself
@@ -1102,7 +1114,7 @@ serialization path.** It enforces:
collection — the previous implementation's route returned 500 on every call collection — the previous implementation's route returned 500 on every call
for a week while its helper's tests passed. for a week while its helper's tests passed.
- `test_grid_batch.py` — **batch analysis** from the context menu, both - `test_grid_batch.py` — **batch analysis** from the context menu, both
`jobs.py` jobs shown in the status bar: Analyze Grid & BPM `jobs.py` jobs shown in the status bar: Analyze… (BPM / Grid / Key)
(`POST /api/tracks/grid/auto-batch`) and Auto Hotcues… (`POST /api/tracks/grid/auto-batch`) and Auto Hotcues…
(`POST /api/tracks/cue/auto-batch`, one template for every track). Pins the (`POST /api/tracks/cue/auto-batch`, one template for every track). Pins the
batch-only decisions: locked grids are skipped always, existing grids unless batch-only decisions: locked grids are skipped always, existing grids unless
+2
View File
@@ -1395,6 +1395,8 @@ def analyze_preview(body: AnalyzeRequest) -> AnalyzePreview:
if track.grid_marker_count and not track.grid_locked: if track.grid_marker_count and not track.grid_locked:
out.with_grid += 1 out.with_grid += 1
step = _grid_step(a, track, body, exact=False) step = _grid_step(a, track, body, exact=False)
if step.action in ("full", "bpm", "phase") or _wants_key(track, body):
out.tracks_to_analyze += 1
if step.action in ("full", "bpm", "phase"): if step.action in ("full", "bpm", "phase"):
setattr(out, f"grid_{step.action}", getattr(out, f"grid_{step.action}") + 1) setattr(out, f"grid_{step.action}", getattr(out, f"grid_{step.action}") + 1)
elif step.action == "skip": elif step.action == "skip":
+1
View File
@@ -152,6 +152,7 @@ class AnalyzePreview(BaseModel):
OneLibrary: 1 for any track with a BPM) a flexible grid is only found when OneLibrary: 1 for any track with a BPM) a flexible grid is only found when
the run reads the real grid — it is then skipped and reported.""" the run reads the real grid — it is then skipped and reported."""
total: int total: int
tracks_to_analyze: int = 0 # tracks with anything to do (grid and key overlap)
# Grid: what `plan_grid` decides per track — full / bpm / phase / skipped. # Grid: what `plan_grid` decides per track — full / bpm / phase / skipped.
grid_full: int = 0 grid_full: int = 0
grid_bpm: int = 0 grid_bpm: int = 0
+4
View File
@@ -296,6 +296,10 @@ with tempfile.TemporaryDirectory() as d:
check("preview: BPM+Grid without Replace skips every gridded track", check("preview: BPM+Grid without Replace skips every gridded track",
(pv["grid_existing"], pv["grid_full"], pv["with_grid"]) == (len(single) + 1, len(bare), len(single) + 1), (pv["grid_existing"], pv["grid_full"], pv["with_grid"]) == (len(single) + 1, len(bare), len(single) + 1),
str(pv)) str(pv))
pv = c.post("/api/tracks/analyze/preview",
json={"track_ids": ids, "bpm": True, "grid": True, "key": True, "replace_key": True}).json()
check("preview: tracks_to_analyze counts a track once for grid AND key",
pv["tracks_to_analyze"] == len(ids), str(pv))
# BPM alone, through the run. # BPM alone, through the run.
anchors = {t: a.track_cues(t).grid_markers[0].start for t in single} anchors = {t: a.track_cues(t).grid_markers[0].start for t in single}
+57 -46
View File
@@ -4,7 +4,7 @@ import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack
import { CapabilitiesContext, slotLabeller } from './lib/capabilities' import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
import { removalNote, writeHint } from './lib/platformCopy' import { removalNote, writeHint } from './lib/platformCopy'
import { invalidateTrackLists } from './lib/trackQueries' import { invalidateTrackLists } from './lib/trackQueries'
import { api, type CueBatchResult, type GridBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api' import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api'
import { confirmDiscardUnsaved } from './lib/unsaved' import { confirmDiscardUnsaved } from './lib/unsaved'
import { import {
COLUMN_MENU, COLUMN_MENU,
@@ -19,7 +19,7 @@ import { Toast, type ToastMsg } from './components/Toast'
import { CollectionPicker } from './components/CollectionPicker' import { CollectionPicker } from './components/CollectionPicker'
import { ContextMenu, type MenuItem } from './components/ContextMenu' import { ContextMenu, type MenuItem } from './components/ContextMenu'
import { EditTagsDialog } from './components/EditTagsDialog' import { EditTagsDialog } from './components/EditTagsDialog'
import { AnalyzeGridDialog } from './components/AnalyzeGridDialog' import { AnalyzeDialog } from './components/AnalyzeDialog'
import { AutoCueDialog } from './components/AutoCueDialog' import { AutoCueDialog } from './components/AutoCueDialog'
import { ConfirmDialog, type ConfirmRequest } from './components/ConfirmDialog' import { ConfirmDialog, type ConfirmRequest } from './components/ConfirmDialog'
import { PathMappingDialog } from './components/PathMappingDialog' import { PathMappingDialog } from './components/PathMappingDialog'
@@ -85,9 +85,7 @@ export default function App() {
// job, polled into the status bar. ONE at a time across both kinds — the // job, polled into the status bar. ONE at a time across both kinds — the
// backend refuses a second, since a grid run would move the beats a hotcue // backend refuses a second, since a grid run would move the beats a hotcue
// run is placing cues on. // run is placing cues on.
const [gridConfirm, setGridConfirm] = useState< const [analyzing, setAnalyzing] = useState<string[] | null>(null) // the Analyze dialog's selection
{ ids: string[]; existing: number; locked: number } | null
>(null)
const [cueBatch, setCueBatch] = useState<{ ids: string[]; withoutGrid: number } | null>(null) const [cueBatch, setCueBatch] = useState<{ ids: string[]; withoutGrid: number } | null>(null)
const [batchJob, setBatchJob] = useState<{ id: string; kind: 'grid' | 'cues' | 'stems' } | null>(null) const [batchJob, setBatchJob] = useState<{ id: string; kind: 'grid' | 'cues' | 'stems' } | null>(null)
// Convert to Stems: the dialog's selection, a finished run's Details, and a // Convert to Stems: the dialog's selection, a finished run's Details, and a
@@ -415,6 +413,19 @@ export default function App() {
: isAll : isAll
? (allTracks.data?.items ?? []) ? (allTracks.data?.items ?? [])
: (playlistTracks.data ?? []) : (playlistTracks.data ?? [])
// The deck holds a SNAPSHOT of its track, taken when it was loaded. When the
// view it came from refetches (Analyze wrote its key, Edit Tags its title),
// follow the fresh copy so the deck's KEY readout and header are current.
// PrepStrip keys its audio on the id, so a new object for the same id
// reloads nothing.
useEffect(() => {
if (!prepTrack || viewOriginRef.current !== prepOrigin) return
const fresh = tracks.find((t) => t.id === prepTrack.id)
if (fresh && JSON.stringify(fresh) !== JSON.stringify(prepTrack)) setPrepTrack(fresh)
// Only a refetch of the list matters; prepTrack is read, not tracked.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tracks])
const loading = viewingFolder const loading = viewingFolder
? folderView.isLoading ? folderView.isLoading
: viewingDevice : viewingDevice
@@ -518,7 +529,7 @@ export default function App() {
return return
} }
if (job.state === 'failed') { if (job.state === 'failed') {
const what = kind === 'grid' ? 'Grid analysis' : 'Auto Hotcues' const what = kind === 'grid' ? 'Analysis' : 'Auto Hotcues'
onError(`${what} failed: ${job.error ?? 'unknown error'}`) onError(`${what} failed: ${job.error ?? 'unknown error'}`)
return return
} }
@@ -531,13 +542,27 @@ export default function App() {
let parts: string[] let parts: string[]
let failures: CueBatchResult['failed'] let failures: CueBatchResult['failed']
if (kind === 'grid') { if (kind === 'grid') {
const r = job.result as unknown as GridBatchResult const r = job.result as unknown as AnalyzeResult
touched = r.analysed touched = r.analysed
failures = r.failed failures = r.failed
const g = r.grid
const wrote = [
g.full ? plural(g.full, 'grid') : '',
g.bpm ? `${plural(g.bpm, 'BPM')} (downbeat kept)` : '',
g.phase ? `${plural(g.phase, 'grid')} at its BPM` : '',
r.key.set ? plural(r.key.set, 'key') : '',
].filter(Boolean)
const skipped = [
g.existing ? `${g.existing} with a grid` : '',
g.locked ? `${g.locked} locked` : '',
g.flexible ? `${g.flexible} multi-tempo` : '',
r.key.existing ? `${r.key.existing} with a key` : '',
].filter(Boolean)
parts = [ parts = [
`${cancelled ? 'Cancelled — analyzed' : 'Analyzed'} ${plural(r.analysed.length, 'track')}`, `${cancelled ? 'Cancelled — analyzed' : 'Analyzed'} ${plural(r.analysed.length, 'track')}` +
r.existing ? `skipped ${r.existing} with a grid` : '', (wrote.length ? `: ${wrote.join(', ')}` : ''),
r.locked ? `${r.locked} locked` : '', skipped.length ? `skipped ${skipped.join(', ')}` : '',
r.key.none ? `no key found in ${r.key.none}` : '',
] ]
} else { } else {
const r = job.result as unknown as CueBatchResult const r = job.result as unknown as CueBatchResult
@@ -692,32 +717,17 @@ export default function App() {
y, y,
}) })
const runGridAnalysis = async (ids: string[], replaceExisting: boolean) => { const runAnalysis = async (ids: string[], opts: AnalyzeOptions) => {
setGridConfirm(null) const job = await api.analyze(ids, opts)
try { setAnalyzing(null)
const job = await api.autoGridBatch(ids, replaceExisting) setBatchCancelling(false)
setBatchCancelling(false) setBatchJob({ id: job.id, kind: 'grid' })
setBatchJob({ id: job.id, kind: 'grid' })
} catch (e) {
onError((e as Error).message)
}
} }
// Confirm only when the run would meet existing grids. Counted from the // Offered where ANY of BPM / Grid / Key can be stored; the dialog disables
// view's tracks, which is where the selection came from. // the rest with a reason.
const startGridAnalysis = (ids: string[]) => { const canAnalyzeGrid = !!capabilities.data?.grid.editable
const byId = new Map(tracks.map((t) => [t.id, t])) const canAnalyzeKey = !!capabilities.data?.tracks.key_writable
const sel = ids.map((id) => byId.get(id)).filter((t): t is Track => !!t) const canAnalyze = canEdit && !viewForeign && (canAnalyzeGrid || canAnalyzeKey)
const locked = sel.filter((t) => t.grid_locked).length
const existing = sel.filter((t) => !t.grid_locked && t.grid_marker_count > 0).length
if (locked === ids.length) {
notify('error', `${locked === 1 ? 'That grid is' : `All ${locked} grids are`} locked — nothing to analyze`)
} else if (existing > 0) {
setGridConfirm({ ids, existing, locked })
} else {
void runGridAnalysis(ids, false)
}
}
const canAnalyzeGrid = canEdit && !viewForeign && !!capabilities.data?.grid.editable
const startCueBatch = (ids: string[]) => { const startCueBatch = (ids: string[]) => {
const byId = new Map(tracks.map((t) => [t.id, t])) const byId = new Map(tracks.map((t) => [t.id, t]))
@@ -955,13 +965,13 @@ export default function App() {
...(canEdit && !viewForeign && menu.ids.length === 1 ...(canEdit && !viewForeign && menu.ids.length === 1
? [{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }] ? [{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }]
: []), : []),
...(canAnalyzeGrid ...(canAnalyze
? [ ? [
{ {
label: 'Analyze Grid & BPM', label: 'Analyze…',
hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined, hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
disabled: !!batchJob, disabled: !!batchJob,
onClick: () => startGridAnalysis(menu.ids), onClick: () => setAnalyzing(menu.ids),
}, },
] ]
: []), : []),
@@ -1075,13 +1085,14 @@ export default function App() {
onError={onError} onError={onError}
/> />
)} )}
{gridConfirm && ( {analyzing && (
<AnalyzeGridDialog <AnalyzeDialog
total={gridConfirm.ids.length} ids={analyzing}
existing={gridConfirm.existing} gridEditable={canAnalyzeGrid}
locked={gridConfirm.locked} keyWritable={canAnalyzeKey}
onChoose={(replace) => runGridAnalysis(gridConfirm.ids, replace)} onRun={(opts) => runAnalysis(analyzing, opts)}
onClose={() => setGridConfirm(null)} onClose={() => setAnalyzing(null)}
onError={onError}
/> />
)} )}
{!!relocation.data?.volumes.length && ( {!!relocation.data?.volumes.length && (
@@ -1473,7 +1484,7 @@ export default function App() {
job={ job={
batchJob batchJob
? { ? {
label: batchJob.kind === 'grid' ? 'Analyzing grids' : batchJob.kind === 'stems' ? 'Converting to stems' : 'Placing hotcues', label: batchJob.kind === 'grid' ? 'Analyzing' : batchJob.kind === 'stems' ? 'Converting to stems' : 'Placing hotcues',
done: batchJobStatus.data?.done ?? 0, done: batchJobStatus.data?.done ?? 0,
total: batchJobStatus.data?.total ?? 0, total: batchJobStatus.data?.total ?? 0,
detail: batchJobStatus.data?.message, detail: batchJobStatus.data?.message,
+41 -12
View File
@@ -436,11 +436,41 @@ export interface JobStatus {
} }
/** What a batch grid analysis did, per track outcome. */ /** What a batch grid analysis did, per track outcome. */
export interface GridBatchResult { /** What the Analyze dialog asks for. BPM and Grid are independent halves of
* a beatgrid: BPM alone keeps the downbeat, Grid alone keeps the tempo.
* `replace_grid` only guards a FULL re-analysis (both ticked). */
export interface AnalyzeOptions {
bpm: boolean
grid: boolean
key: boolean
replace_grid: boolean
replace_key: boolean
}
/** What an Analyze run WOULD do — the backend's `plan_grid`, per track. */
export interface AnalyzePreview {
total: number
tracks_to_analyze: number
grid_full: number
grid_bpm: number
grid_phase: number
grid_locked: number
grid_existing: number
grid_flexible: number
/** Unlocked tracks with a grid — the grid Replace tick's count. */
with_grid: number
key_set: number
key_existing: number
/** Tracks with a key — the key Replace tick's count. */
with_key: number
}
/** What an Analyze run did. */
export interface AnalyzeResult {
analysed: string[] analysed: string[]
locked: number
existing: number
failed: { title: string; reason: string }[] failed: { title: string; reason: string }[]
grid: { full: number; bpm: number; phase: number; locked: number; existing: number; flexible: number }
key: { set: number; existing: number; none: number }
} }
/** What a batch Auto Hotcues run did. `tracks` got the template (whatever it /** What a batch Auto Hotcues run did. `tracks` got the template (whatever it
@@ -889,12 +919,11 @@ export const api = {
track_id: trackId, track_id: trackId,
slots, slots,
}), }),
// Backend detects tempo + first beat: sets BPM, hotcue 1, and grid anchor. /** The deck's Analyze: BPM + grid (on Traktor also hotcue 1) and, where the
* library stores one, the key — from one decode. Returns the cues; the key
* lands on the track, so refetch the track lists. */
autoGrid: (trackId: string) => autoGrid: (trackId: string) =>
send<TrackCues>('POST', '/api/tracks/grid/auto', { track_id: trackId }), send<TrackCues>('POST', '/api/tracks/grid/auto', { track_id: trackId }),
/** Many tracks at once, as a job — poll `job()`. Locked grids are always
* skipped; existing ones unless `replaceExisting`. The finished job's
* `result` is a `GridBatchResult`. */
/** Auto Hotcues over many tracks, one template for all, as a job. A track /** Auto Hotcues over many tracks, one template for all, as a job. A track
* without a grid gets one analysed first. The finished job's `result` is a * without a grid gets one analysed first. The finished job's `result` is a
* `CueBatchResult`. */ * `CueBatchResult`. */
@@ -923,11 +952,11 @@ export const api = {
stemSideload: (path: string, kind: 'engine' | 'weights') => stemSideload: (path: string, kind: 'engine' | 'weights') =>
send<StemEngineStatus>('POST', '/api/stems/engine/sideload', { path, kind }), send<StemEngineStatus>('POST', '/api/stems/engine/sideload', { path, kind }),
stemEngineRemove: () => send<StemEngineStatus>('DELETE', '/api/stems/engine'), stemEngineRemove: () => send<StemEngineStatus>('DELETE', '/api/stems/engine'),
autoGridBatch: (trackIds: string[], replaceExisting: boolean) => analyzePreview: (trackIds: string[], opts: AnalyzeOptions) =>
send<JobStatus>('POST', '/api/tracks/grid/auto-batch', { send<AnalyzePreview>('POST', '/api/tracks/analyze/preview', { track_ids: trackIds, ...opts }),
track_ids: trackIds, /** Starts an analysis job; its `result` is an `AnalyzeResult`. */
replace_existing: replaceExisting, analyze: (trackIds: string[], opts: AnalyzeOptions) =>
}), send<JobStatus>('POST', '/api/tracks/analyze', { track_ids: trackIds, ...opts }),
setCueType: (trackId: string, slot: number, type: CueType) => setCueType: (trackId: string, slot: number, type: CueType) =>
send<TrackCues>('PATCH', '/api/tracks/cue', { track_id: trackId, slot, type }), send<TrackCues>('PATCH', '/api/tracks/cue', { track_id: trackId, slot, type }),
/** Recolour a cue from `capabilities.cues.palette`; null = uncoloured. */ /** Recolour a cue from `capabilities.cues.palette`; null = uncoloured. */
+199
View File
@@ -0,0 +1,199 @@
import { createPortal } from 'react-dom'
import { useEffect, useState, type ReactNode } from 'react'
import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type AnalyzeOptions, type AnalyzePreview } from '../api'
interface Props {
/** The selected tracks. */
ids: string[]
/** The library can write beatgrids (BPM and Grid). */
gridEditable: boolean
/** The library can store a key. */
keyWritable: boolean
onRun: (opts: AnalyzeOptions) => Promise<void>
onClose: () => void
onError: (msg: string) => void
}
type What = Pick<AnalyzeOptions, 'bpm' | 'grid' | 'key'>
const PREF_KEY = 'analyzeWhat'
const DEFAULT_WHAT: What = { bpm: true, grid: true, key: true }
/** The remembered ticks; anything malformed falls back to the default. */
function loadWhat(prefs: Record<string, unknown> | undefined): What {
const saved = prefs?.[PREF_KEY] as Partial<What> | undefined
if (!saved || typeof saved !== 'object') return DEFAULT_WHAT
const pick = (k: keyof What) => (typeof saved[k] === 'boolean' ? (saved[k] as boolean) : DEFAULT_WHAT[k])
return { bpm: pick('bpm'), grid: pick('grid'), key: pick('key') }
}
const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
/**
* The context menu's "Analyze…" (decided 2026-10-04): which of BPM / Grid /
* Key to analyse, with the "already has one — replace?" questions folded in so
* there is never a second popup. BPM and Grid are independent halves of a
* beatgrid — BPM alone keeps the downbeat, Grid alone keeps the tempo — and
* the grid Replace tick only guards a FULL re-analysis (both ticked). The
* ticks are remembered; the Replace ticks never are — overwriting is a
* decision about THESE tracks.
*/
export function AnalyzeDialog({ ids, gridEditable, keyWritable, onRun, onClose, onError }: Props) {
const qc = useQueryClient()
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs })
const [what, setWhat] = useState<What | null>(null)
const [replaceGrid, setReplaceGrid] = useState(false)
const [replaceKey, setReplaceKey] = useState(false)
const [busy, setBusy] = useState(false)
// Hydrate once from prefs, masked by what this library can store.
useEffect(() => {
if (what || prefs.isPending) return
const w = loadWhat(prefs.data as Record<string, unknown> | undefined)
setWhat({ bpm: w.bpm && gridEditable, grid: w.grid && gridEditable, key: w.key && keyWritable })
}, [what, prefs.isPending, prefs.data, gridEditable, keyWritable])
const opts: AnalyzeOptions | null = what && {
...what,
replace_grid: what.bpm && what.grid && replaceGrid,
replace_key: what.key && replaceKey,
}
const preview = useQuery({
queryKey: ['analyze-preview', ids, opts],
queryFn: () => api.analyzePreview(ids, opts!),
enabled: !!opts && (opts.bpm || opts.grid || opts.key),
placeholderData: keepPreviousData,
})
const p: AnalyzePreview | undefined = preview.data
const nothingTicked = !!what && !(what.bpm || what.grid || what.key)
const count = nothingTicked ? 0 : (p?.tracks_to_analyze ?? 0)
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !busy && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [busy, onClose])
const run = async () => {
if (!opts || busy || count === 0) return
setBusy(true)
api
.patchPrefs({ [PREF_KEY]: { bpm: opts.bpm, grid: opts.grid, key: opts.key } })
.then((x) => qc.setQueryData(['prefs'], x))
.catch(() => {})
try {
await onRun(opts)
} catch (e) {
onError((e as Error).message)
setBusy(false)
}
}
const toggle = (k: keyof What, label: string, help: string, enabled: boolean, why: string) => (
<label
className={`flex items-start gap-3 rounded-md px-2 py-1.5 ${enabled ? 'cursor-pointer hover:bg-ink-800' : 'opacity-40'}`}
title={enabled ? undefined : why}
>
<input
type="checkbox"
className="mt-0.5"
checked={!!what?.[k]}
disabled={!enabled || !what}
onChange={(e) => setWhat((w) => w && { ...w, [k]: e.target.checked })}
/>
<span className="min-w-0">
<span className="block text-sm text-text">{label}</span>
<span className="block text-xs text-faint">{help}</span>
</span>
</label>
)
// What the grid ticks will do, in the dialog's own words.
const gridLines: ReactNode[] = []
if (p && what && (what.bpm || what.grid)) {
if (what.bpm && what.grid) {
if (p.with_grid > 0)
gridLines.push(
<div key="rg" className="flex items-center justify-between gap-3">
<span>
<span className="tabular-nums text-text">{p.with_grid}</span>{' '}
{p.with_grid === 1 ? 'already has a grid' : 'already have a grid'}
</span>
<label className="flex shrink-0 items-center gap-1.5 text-xs" title="Replacing discards any hand edits to those grids">
<input type="checkbox" checked={replaceGrid} onChange={(e) => setReplaceGrid(e.target.checked)} />
Replace {p.with_grid === 1 ? 'it' : 'them'}
</label>
</div>,
)
} else if (what.bpm) {
if (p.grid_bpm) gridLines.push(<div key="b">{plural(p.grid_bpm, 'grid')}: tempo re-detected, downbeat kept</div>)
if (p.grid_full) gridLines.push(<div key="bf">{plural(p.grid_full, 'track')} without a grid: analyzed in full</div>)
} else {
if (p.grid_phase) gridLines.push(<div key="g">{plural(p.grid_phase, 'track')}: downbeats found at the current BPM</div>)
if (p.grid_full) gridLines.push(<div key="gf">{plural(p.grid_full, 'track')} without a BPM: analyzed in full</div>)
}
if (p.grid_flexible)
gridLines.push(
<div key="fx" className="text-faint" title="One BPM or downbeat for the whole track would flatten its tempo changes">
{plural(p.grid_flexible, 'multi-tempo grid')} — skipped
</div>,
)
if (p.grid_locked) gridLines.push(<div key="lk" className="text-faint">{plural(p.grid_locked, 'locked grid')} — skipped</div>)
}
return createPortal(
<div
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
onClick={() => !busy && onClose()}
>
<div className="w-full max-w-sm overflow-hidden glass-overlay" onClick={(e) => e.stopPropagation()}>
<div className="border-b border-line px-5 py-4">
<div className="text-[15px] font-semibold tracking-tight">Analyze</div>
<div className="text-xs text-muted">{plural(ids.length, 'track')} selected</div>
</div>
<div className="space-y-0.5 px-3 pt-3">
{toggle('bpm', 'BPM', 'Detect the tempo', gridEditable, "This library's beatgrids cannot be edited")}
{toggle('grid', 'Grid', 'Find where the downbeats fall', gridEditable, "This library's beatgrids cannot be edited")}
{toggle('key', 'Key', 'Detect the musical key', keyWritable, "This library cannot store a key")}
</div>
<div className={`space-y-1.5 px-5 py-3 text-sm text-muted ${preview.isFetching ? 'opacity-70' : ''}`}>
{gridLines}
{p && what?.key && p.with_key > 0 && (
<div className="flex items-center justify-between gap-3">
<span>
<span className="tabular-nums text-text">{p.with_key}</span>{' '}
{p.with_key === 1 ? 'already has a key' : 'already have a key'}
</span>
<label className="flex shrink-0 items-center gap-1.5 text-xs">
<input type="checkbox" checked={replaceKey} onChange={(e) => setReplaceKey(e.target.checked)} />
Replace {p.with_key === 1 ? 'it' : 'them'}
</label>
</div>
)}
{nothingTicked && <div className="text-faint">Tick what to analyze.</div>}
</div>
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
<button
onClick={onClose}
disabled={busy}
className="rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
>
Cancel
</button>
<button
onClick={run}
disabled={busy || count === 0 || !p}
className="rounded-full btn-primary px-4 py-1.5 text-sm font-semibold disabled:opacity-40"
>
{count === 0 && p && !nothingTicked ? 'Nothing to analyze' : `Analyze${count ? ` ${count}` : ''}`}
</button>
</div>
</div>
</div>,
document.body,
)
}
@@ -1,85 +0,0 @@
import { createPortal } from 'react-dom'
import { useEffect } from 'react'
interface Props {
/** Tracks the user selected. */
total: number
/** Unlocked tracks that already have a beatgrid. */
existing: number
/** Tracks whose grid is locked — skipped whatever is chosen here. */
locked: number
onChoose: (replaceExisting: boolean) => void
onClose: () => void
}
/** Asked only when a batch analysis would meet existing grids: re-analysing a
* grid someone may have hand-fixed is a decision, not a default. */
export function AnalyzeGridDialog({ total, existing, locked, onChoose, onClose }: Props) {
// "Skip them" would leave nothing to do when every unlocked track has a grid.
const canSkip = existing < total - locked
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
return createPortal(
<div
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
onClick={onClose}
>
<div
className="w-full max-w-sm overflow-hidden glass-overlay"
onClick={(e) => e.stopPropagation()}
>
<div className="border-b border-line px-5 py-4">
<div className="text-[15px] font-semibold tracking-tight">Analyze Grid &amp; BPM</div>
<div className="text-xs text-muted">
{total} track{total === 1 ? '' : 's'} selected
</div>
</div>
<div className="space-y-1 px-5 py-4 text-sm text-muted">
<p>
<span className="tabular-nums text-text">{existing}</span>{' '}
{existing === 1 ? 'already has a beatgrid' : 'already have a beatgrid'}. Replacing
discards any hand edits to {existing === 1 ? 'it' : 'them'}.
</p>
{locked > 0 && (
<p className="text-faint">
{locked} {locked === 1 ? 'is' : 'are'} locked and will be skipped either way.
</p>
)}
</div>
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
<button
onClick={onClose}
className="rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
>
Cancel
</button>
<button
onClick={() => onChoose(true)}
className={
canSkip
? 'rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text'
: 'rounded-md bg-accent px-4 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110'
}
>
Replace {existing === 1 ? 'it' : 'them'}
</button>
{canSkip && (
<button
onClick={() => onChoose(false)}
className="rounded-full btn-primary px-4 py-1.5 text-sm font-semibold"
>
Skip {existing === 1 ? 'it' : 'them'}
</button>
)}
</div>
</div>
</div>,
document.body,
)
}
+5 -2
View File
@@ -1043,14 +1043,17 @@ export function PrepStrip({
onError?.((e as Error).message) onError?.((e as Error).message)
} }
} }
// Analyze: backend detects BPM + first beat, sets the grid anchor and hotcue 1. // Analyze: the backend detects BPM + first beat (setting the grid anchor and,
// on Traktor, hotcue 1) and the key where the library stores one. The key
// lands on the track: `applyCueEdit` refetches the lists, and App hands the
// deck the fresh copy.
const runAnalyzeGrid = async () => { const runAnalyzeGrid = async () => {
if (!track || gridBusy) return if (!track || gridBusy) return
if (refuseGridEdit()) return if (refuseGridEdit()) return
setGridBusy(true) setGridBusy(true)
try { try {
applyCueEdit(await api.autoGrid(track.id)) applyCueEdit(await api.autoGrid(track.id))
onNotify?.('success', 'Analyzed — set BPM, grid, and hotcue 1') onNotify?.('success', caps.tracks.key_writable ? 'Analyzed — set BPM, grid and key' : 'Analyzed — set BPM and grid')
} catch (e) { } catch (e) {
onError?.((e as Error).message) onError?.((e as Error).message)
} finally { } finally {