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, type TrackOrigin } from '../api' interface Props { /** The selected tracks. */ ids: string[] /** Whose ids they are: a device's or a folder's loose files can only have * their loudness measured. */ origin: TrackOrigin /** Why BPM and Grid cannot be analysed here; null = they can. */ gridWhy: string | null /** Why a key cannot be stored here; null = it can. */ keyWhy: string | null /** Why the DJ app's auto gain cannot be written here; null = it can. */ gainWhy: string | null /** Opened for ONE option (the context menu's Mastering ▸ Auto gain… / * Measure loudness): only it is ticked, and the remembered ticks are left * as they were. */ preset?: keyof What onRun: (opts: AnalyzeOptions) => Promise onClose: () => void onError: (msg: string) => void } type What = Pick const PREF_KEY = 'analyzeWhat' // Loudness and gain off unless asked for once: they add a decode per track. const DEFAULT_WHAT: What = { bpm: true, grid: true, key: true, loudness: false, gain: false } /** The remembered ticks; anything malformed falls back to the default. */ function loadWhat(prefs: Record | undefined): What { const saved = prefs?.[PREF_KEY] as Partial | 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'), loudness: pick('loudness'), gain: pick('gain') } } 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 / Loudness 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). Loudness goes to Konduktor's own store, so it is never disabled * (decided 2026-10-19). Gain writes the DJ app's own auto gain from the * loudness, only where a track has none unless Replace. The ticks are * remembered; the Replace ticks never are — overwriting is a decision about * THESE tracks. */ export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, gainWhy, preset, onRun, onClose, onError }: Props) { const qc = useQueryClient() const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) const [what, setWhat] = useState(null) const [replaceGrid, setReplaceGrid] = useState(false) const [replaceKey, setReplaceKey] = useState(false) const [replaceLoudness, setReplaceLoudness] = useState(false) const [replaceGain, setReplaceGain] = useState(false) const [busy, setBusy] = useState(false) const gridEditable = gridWhy === null const keyWritable = keyWhy === null const gainWritable = gainWhy === null // Hydrate once from prefs, masked by what can be stored here. Where loudness // is ALL that can be done (a device, loose files), it is ticked. useEffect(() => { if (what || prefs.isPending) return if (preset) { setWhat({ bpm: false, grid: false, key: false, loudness: false, gain: false, [preset]: true }) return } const w = loadWhat(prefs.data as Record | undefined) setWhat({ bpm: w.bpm && gridEditable, grid: w.grid && gridEditable, key: w.key && keyWritable, gain: w.gain && gainWritable, loudness: w.loudness || (!gridEditable && !keyWritable && !gainWritable), }) }, [what, preset, prefs.isPending, prefs.data, gridEditable, keyWritable, gainWritable]) const opts: AnalyzeOptions | null = what && { ...what, replace_grid: what.bpm && what.grid && replaceGrid, replace_key: what.key && replaceKey, replace_loudness: what.loudness && replaceLoudness, replace_gain: what.gain && replaceGain, origin, } const preview = useQuery({ queryKey: ['analyze-preview', ids, opts], queryFn: () => api.analyzePreview(ids, opts!), enabled: !!opts && (opts.bpm || opts.grid || opts.key || opts.loudness || opts.gain), placeholderData: keepPreviousData, }) const p: AnalyzePreview | undefined = preview.data const nothingTicked = !!what && !(what.bpm || what.grid || what.key || what.loudness || what.gain) 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) // A tick that was disabled here keeps what it was: analysing a device's // loudness must not forget that the collection's keys are wanted. A // one-option run (a preset) remembers nothing. const saved = loadWhat(prefs.data as Record | undefined) if (!preset) api .patchPrefs({ [PREF_KEY]: { bpm: gridEditable ? opts.bpm : saved.bpm, grid: gridEditable ? opts.grid : saved.grid, key: keyWritable ? opts.key : saved.key, gain: gainWritable ? opts.gain : saved.gain, loudness: opts.loudness, }, }) .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) => ( ) // 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(
{p.with_grid}{' '} {p.with_grid === 1 ? 'already has a grid' : 'already have a grid'}
, ) } else if (what.bpm) { if (p.grid_bpm) gridLines.push(
{plural(p.grid_bpm, 'grid')}: tempo re-detected, downbeat kept
) if (p.grid_full) gridLines.push(
{plural(p.grid_full, 'track')} without a grid: analyzed in full
) } else { if (p.grid_phase) gridLines.push(
{plural(p.grid_phase, 'track')}: downbeats found at the current BPM
) if (p.grid_full) gridLines.push(
{plural(p.grid_full, 'track')} without a BPM: analyzed in full
) } if (p.grid_flexible) gridLines.push(
{plural(p.grid_flexible, 'multi-tempo grid')} — skipped
, ) if (p.grid_locked) gridLines.push(
{plural(p.grid_locked, 'locked grid')} — skipped
) } return createPortal(
!busy && onClose()} >
e.stopPropagation()}>
Analyze
{plural(ids.length, 'track')} selected
{toggle('bpm', 'BPM', 'Detect the tempo', gridEditable, gridWhy ?? '')} {toggle('grid', 'Grid', 'Find where the downbeats fall', gridEditable, gridWhy ?? '')} {toggle('key', 'Key', 'Detect the musical key', keyWritable, keyWhy ?? '')} {toggle('loudness', 'Loudness', 'Measure LUFS, RMS, true peak and dynamics', true, '')} {toggle('gain', 'Auto gain', "Set the DJ app's own gain from the loudness (measured first if needed)", gainWritable, gainWhy ?? '')}
{gridLines} {p && what?.key && p.with_key > 0 && (
{p.with_key}{' '} {p.with_key === 1 ? 'already has a key' : 'already have a key'}
)} {p && what?.loudness && p.with_loudness > 0 && (
{p.with_loudness} already measured
)} {p && what?.gain && p.with_gain > 0 && (
{p.with_gain}{' '} {p.with_gain === 1 ? 'already has an auto gain' : 'already have an auto gain'}
)} {nothingTicked &&
Tick what to analyze.
}
, document.body, ) }