Added context option to multi analyze

This commit is contained in:
patben8 committed 2026-09-25 10:46:31 +02:00
1 parent b71436fad6
commit 532dc5d6ac
11 files changed
+486 -12

No files matched your search

+117 -1
View File
@@ -3,7 +3,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'
import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table'
import { CapabilitiesContext } from './lib/capabilities'
import { writeHint } from './lib/platformCopy'
import { api, type PlaylistNode, type Track } from './api'
import { api, type GridBatchResult, type PlaylistNode, type Track } from './api'
import {
DEFAULT_COLUMN_ORDER,
DEFAULT_COLUMN_VISIBILITY,
@@ -16,6 +16,7 @@ import { Toast, type ToastMsg } from './components/Toast'
import { CollectionPicker } from './components/CollectionPicker'
import { ContextMenu, type MenuItem } from './components/ContextMenu'
import { EditTagsDialog } from './components/EditTagsDialog'
import { AnalyzeGridDialog } from './components/AnalyzeGridDialog'
import { PathMappingDialog } from './components/PathMappingDialog'
import { HistoryPanel } from './components/HistoryPanel'
import { PrepStrip } from './components/PrepStrip'
@@ -58,6 +59,14 @@ export default function App() {
const [prepTrack, setPrepTrack] = useState<Track | null>(null)
const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays
const [importing, setImporting] = useState(false)
// Batch grid analysis: the confirm step (only when some tracks already have
// a grid), then the running job, polled into the status bar.
const [gridConfirm, setGridConfirm] = useState<
{ ids: string[]; existing: number; locked: number } | null
>(null)
const [gridJobId, setGridJobId] = useState<string | null>(null)
const [gridCancelling, setGridCancelling] = useState(false)
const [cuesRefresh, setCuesRefresh] = useState(0) // bump → deck re-reads its cues
const playTrack = useCallback((t: Track) => {
setPrepTrack(t)
@@ -387,10 +396,55 @@ export default function App() {
[reorderPlaylist, tracks],
)
const gridJob = useQuery({
queryKey: ['job', gridJobId],
queryFn: () => api.job(gridJobId!),
enabled: !!gridJobId,
refetchInterval: (q) => (q.state.data && q.state.data.state !== 'running' ? false : 400),
})
const gridDone = gridJob.data?.done ?? 0
useEffect(() => {
// Each finished track is an unsaved edit; let the Save button know as they land.
if (gridDone > 0) qc.invalidateQueries({ queryKey: ['state'] })
}, [gridDone, qc])
useEffect(() => {
const job = gridJob.data
if (!job || job.state === 'running') return
setGridJobId(null)
setGridCancelling(false)
if (job.state === 'failed') {
onError(`Grid analysis failed: ${job.error ?? 'unknown error'}`)
return
}
const r = job.result as unknown as GridBatchResult | null
if (!r) return
qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['tracks'] })
qc.invalidateQueries({ queryKey: ['playlist'] })
qc.invalidateQueries({ queryKey: ['export-tracks'] })
qc.invalidateQueries({ queryKey: ['export-playlist-tracks'] })
qc.invalidateQueries({ queryKey: ['export-loose'] })
qc.invalidateQueries({ queryKey: ['facets'] })
if (prepTrack && r.analysed.includes(prepTrack.id)) setCuesRefresh((n) => n + 1)
const n = r.analysed.length
const parts = [
`${job.state === 'cancelled' ? 'Cancelled — analyzed' : 'Analyzed'} ${n} track${n === 1 ? '' : 's'}`,
r.existing ? `skipped ${r.existing} with a grid` : '',
r.locked ? `${r.locked} locked` : '',
r.failed.length
? `${r.failed.length} failed (${r.failed[0].title}: ${r.failed[0].reason}${r.failed.length > 1 ? ', …' : ''})`
: '',
].filter(Boolean)
notify(r.failed.length && n === 0 ? 'error' : 'success', parts.join(' · '))
// Only the job's finish matters here; prepTrack is read, not tracked.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [gridJob.data])
const handleOpened = () => {
setForcePicker(false)
setSource({ kind: 'all' })
setSelected(new Set())
setGridJobId(null) // the backend cancels it; its result is for the old library
setFilters(emptyFilters)
setSorting([])
qc.invalidateQueries() // refetch everything for the newly-opened collection
@@ -430,6 +484,33 @@ export default function App() {
y,
})
const runGridAnalysis = async (ids: string[], replaceExisting: boolean) => {
setGridConfirm(null)
try {
const job = await api.autoGridBatch(ids, replaceExisting)
setGridCancelling(false)
setGridJobId(job.id)
} catch (e) {
onError((e as Error).message)
}
}
// Confirm only when the run would meet existing grids. Counted from the
// view's tracks, which is where the selection came from.
const startGridAnalysis = (ids: string[]) => {
const byId = new Map(tracks.map((t) => [t.id, t]))
const sel = ids.map((id) => byId.get(id)).filter((t): t is Track => !!t)
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 && !viewingDevice && !!capabilities.data?.grid.editable
// The "Add to" submenu. Exports are listed even on a read-only library:
// adding to one touches no library data — an export is Konduktor's own
// curation. The playlist being viewed is left out; adding a track to the
@@ -473,6 +554,16 @@ export default function App() {
...(canEdit && menu.ids.length === 1
? [{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }]
: []),
...(canAnalyzeGrid
? [
{
label: 'Analyze Grid & BPM',
hint: gridJobId ? 'running' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
disabled: !!gridJobId,
onClick: () => startGridAnalysis(menu.ids),
},
]
: []),
// A device's track ids belong to the stick, not the collection, so
// there is nothing they could be added to.
...(viewingDevice ? [] : [{ label: 'Add to', submenu: addToItems(menu.ids) }]),
@@ -504,6 +595,15 @@ export default function App() {
onError={onError}
/>
)}
{gridConfirm && (
<AnalyzeGridDialog
total={gridConfirm.ids.length}
existing={gridConfirm.existing}
locked={gridConfirm.locked}
onChoose={(replace) => runGridAnalysis(gridConfirm.ids, replace)}
onClose={() => setGridConfirm(null)}
/>
)}
{showPaths && (
<PathMappingDialog
onClose={() => setShowPaths(false)}
@@ -540,6 +640,7 @@ export default function App() {
onError={onError}
onNotify={notify}
fromDevice={viewingDevice}
cuesRefresh={cuesRefresh}
/>
</CapabilitiesContext.Provider>
@@ -751,6 +852,21 @@ export default function App() {
total={tracks.length}
sourceName={viewName}
selected={isAll || viewingExport ? selected.size : 0}
job={
gridJobId
? {
label: 'Analyzing',
done: gridJob.data?.done ?? 0,
total: gridJob.data?.total ?? 0,
detail: gridJob.data?.message,
cancelling: gridCancelling,
onCancel: () => {
setGridCancelling(true)
api.cancelJob(gridJobId).catch((e) => onError((e as Error).message))
},
}
: null
}
loading={loading}
collectionName={capabilities.data ? libraryName : null}
onChangeCollection={() => setForcePicker(true)}
+16
View File
@@ -345,6 +345,14 @@ export interface JobStatus {
finished_at: number | null
}
/** What a batch grid analysis did, per track outcome. */
export interface GridBatchResult {
analysed: string[]
locked: number
existing: number
failed: { title: string; reason: string }[]
}
export interface SourceCandidate {
path: string
/** What a person recognises, e.g. "OneLibrary — Hardy". */
@@ -665,6 +673,14 @@ export const api = {
// Backend detects tempo + first beat: sets BPM, hotcue 1, and grid anchor.
autoGrid: (trackId: string) =>
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`. */
autoGridBatch: (trackIds: string[], replaceExisting: boolean) =>
send<JobStatus>('POST', '/api/tracks/grid/auto-batch', {
track_ids: trackIds,
replace_existing: replaceExisting,
}),
setCueType: (trackId: string, slot: number, type: CueType) =>
send<TrackCues>('PATCH', '/api/tracks/cue', { track_id: trackId, slot, type }),
deleteCue: (trackId: string, slot: number) =>
@@ -0,0 +1,83 @@
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 (
<div
aria-modal="true"
className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-6"
onClick={onClose}
>
<div
className="w-full max-w-sm overflow-hidden rounded-xl border border-line bg-ink-900 shadow-2xl"
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-md bg-accent px-4 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110"
>
Skip {existing === 1 ? 'it' : 'them'}
</button>
)}
</div>
</div>
</div>
)
}
+7 -4
View File
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'
/** One row of a menu: an action, a submenu (`label ▸`), or a section heading. */
export type MenuItem =
| { label: string; onClick: () => void; danger?: boolean; hint?: string; icon?: string }
| { label: string; onClick: () => void; danger?: boolean; hint?: string; icon?: string; disabled?: boolean }
| { label: string; submenu: MenuItem[] }
| { heading: string; empty?: string }
@@ -122,15 +122,18 @@ function MenuPanel({
return (
<button
key={i}
disabled={item.disabled}
onMouseEnter={() => setOpen(null)}
onClick={() => {
item.onClick()
onClose()
}}
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm ${
item.danger
? 'text-pink hover:bg-ink-800'
: 'text-muted hover:bg-ink-800 hover:text-text'
item.disabled
? 'cursor-default text-faint'
: item.danger
? 'text-pink hover:bg-ink-800'
: 'text-muted hover:bg-ink-800 hover:text-text'
}`}
>
{item.icon && <span className="shrink-0 text-[11px] text-gold">{item.icon}</span>}
+24 -1
View File
@@ -39,6 +39,9 @@ interface Props {
* deck gates on those — so this only needs to redirect the two READS.
*/
fromDevice?: boolean
/** Bumped when something outside the deck (batch grid analysis) rewrote the
* loaded track's cues/grid, so the deck re-reads them. */
cuesRefresh?: number
}
function fmt(secs: number): string {
@@ -73,7 +76,14 @@ const LOOP_SIZES = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 1 / 2, 1, 2, 4, 8, 16, 32]
* Web Audio PlaybackEngine (seamless loops); the same decoded buffer feeds the
* scratch engine and both waveform views.
*/
export function PrepStrip({ track, playRequest = 0, onError, onNotify, fromDevice = false }: Props) {
export function PrepStrip({
track,
playRequest = 0,
onError,
onNotify,
fromDevice = false,
cuesRefresh = 0,
}: Props) {
const qc = useQueryClient()
const [playing, setPlaying] = useState(false)
const [previewing, setPreviewing] = useState(false) // momentary hold-to-play active
@@ -287,6 +297,19 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify, fromDevic
}
}, [trackId, fromDevice])
// Re-read after an outside edit. Deliberately NOT the effect above: that one
// resets `originalGridRef`, and "Reset" should still restore the grid the
// track had before the outside edit replaced it.
useEffect(() => {
if (!trackId || !cuesRefresh) return
let cancelled = false
api.trackCues(trackId).then((d) => !cancelled && setCueData(d)).catch(() => {})
return () => {
cancelled = true
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cuesRefresh])
const toggle = () => {
const eng = playbackRef.current
if (!eng || !eng.ready) return
+40 -1
View File
@@ -1,9 +1,22 @@
/** A background job's progress, shown at the right of the bar. */
export interface StatusJob {
label: string
done: number
/** 0 until the job knows its size → indeterminate bar. */
total: number
/** What it is working on right now, e.g. the current track's title. */
detail?: string
cancelling?: boolean
onCancel: () => void
}
interface Props {
showing: number
total: number
sourceName: string
/** Rows currently selected; shown only when non-zero. */
selected?: number
job?: StatusJob | null
loading?: boolean
collectionName?: string | null
onChangeCollection?: () => void
@@ -14,6 +27,7 @@ export function StatusBar({
total,
sourceName,
selected = 0,
job,
loading,
collectionName,
onChangeCollection,
@@ -41,10 +55,35 @@ export function StatusBar({
<span className="tabular-nums text-accent">{selected.toLocaleString()} selected</span>
</>
)}
{job && (
<div className="ml-auto flex min-w-0 items-center gap-2">
<span className="shrink-0 tabular-nums text-text">
{job.cancelling ? 'Cancelling…' : job.label}
{job.total > 0 && ` ${Math.min(job.done + 1, job.total)}/${job.total}`}
</span>
<span className="h-1.5 w-32 shrink-0 overflow-hidden rounded-full bg-ink-800">
<span
className={`block h-full rounded-full bg-accent transition-[width] duration-300 ${
job.total > 0 ? '' : 'w-1/3 animate-pulse'
}`}
style={job.total > 0 ? { width: `${(job.done / job.total) * 100}%` } : undefined}
/>
</span>
{job.detail && <span className="max-w-[240px] truncate text-faint">{job.detail}</span>}
<button
onClick={job.onCancel}
disabled={job.cancelling}
className="shrink-0 rounded px-1.5 text-faint hover:bg-ink-800 hover:text-pink disabled:opacity-40"
title="Cancel"
>
×
</button>
</div>
)}
{collectionName && (
<button
onClick={onChangeCollection}
className="ml-auto flex items-center gap-1.5 rounded px-2 py-0.5 text-faint hover:bg-ink-800 hover:text-text"
className={`${job ? '' : 'ml-auto '}flex items-center gap-1.5 rounded px-2 py-0.5 text-faint hover:bg-ink-800 hover:text-text`}
title="Change collection"
>
<span className="text-[11px]">⎘</span>