import { useEffect, useRef, useState } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' import { api, type RemapPreview } from '../api' import type { ToastMsg } from './Toast' interface Props { onClose: () => void onNotify: (kind: ToastMsg['kind'], text: string) => void onError: (msg: string) => void } const inputCls = 'w-full rounded-md border border-line bg-ink-850 px-2.5 py-1.5 text-sm text-text outline-none focus:border-accent placeholder:text-faint' /** * Per-collection OS-path remapping editor. Lets the user translate the stored * audio-file path prefix to a locally-reachable one (portable USB / relocated * library). Saving the mapping is non-destructive — the .nml is never touched; * only how Konduktor resolves files for playback/analysis/tags changes. */ export function PathMappingDialog({ onClose, onNotify, onError }: Props) { const qc = useQueryClient() const saved = useQuery({ queryKey: ['pathMapping'], queryFn: api.getPathMapping }) const suggest = useQuery({ queryKey: ['prefixSuggest'], queryFn: api.suggestPrefix }) const [from, setFrom] = useState('') const [to, setTo] = useState('') const hydrated = useRef(false) const [preview, setPreview] = useState(null) const [saving, setSaving] = useState(false) const [browsing, setBrowsing] = useState(false) const [confirming, setConfirming] = useState(false) const [committing, setCommitting] = useState(false) // Hydrate once: prefer the saved mapping; otherwise prefill `from` with the // auto-detected prefix. Defer until the suggestion resolves when we'd need it. useEffect(() => { if (hydrated.current || !saved.data) return if (!saved.data.from && suggest.isLoading) return hydrated.current = true setTo(saved.data.to) setFrom(saved.data.from || suggest.data?.primary || '') }, [saved.data, suggest.isLoading, suggest.data]) // Live validation preview (debounced) — how many tracks match / exist. useEffect(() => { if (!from.trim() || !to.trim()) { setPreview(null) return } const t = window.setTimeout(() => { api .previewRemap(from.trim(), to.trim()) .then(setPreview) .catch(() => setPreview(null)) }, 350) return () => window.clearTimeout(t) }, [from, to]) const saveMapping = async () => { setSaving(true) try { await api.putPathMapping({ from: from.trim(), to: to.trim() }) // Re-resolve everything that depends on the file path. qc.invalidateQueries({ queryKey: ['pathMapping'] }) qc.invalidateQueries({ queryKey: ['tracks'] }) const cleared = !from.trim() || !to.trim() onNotify('success', cleared ? 'Path mapping cleared.' : 'Path mapping saved.') onClose() } catch (e) { onError(e instanceof Error ? e.message : 'Failed to save mapping') } finally { setSaving(false) } } const commit = async () => { setCommitting(true) try { const res = await api.remapPaths(from.trim(), to.trim()) // Locations changed, so track ids changed — refetch library + state. qc.invalidateQueries({ queryKey: ['tracks'] }) qc.invalidateQueries({ queryKey: ['state'] }) if (res.rewritten === 0) { onNotify('warning', 'No tracks matched — nothing was rewritten.') } else { onNotify( 'success', `Rewrote ${res.rewritten} track path${res.rewritten === 1 ? '' : 's'}.` + (res.commit ? ` Version: ${res.commit.slice(0, 8)}` : ''), ) onClose() } } catch (e) { onError(e instanceof Error ? e.message : 'Failed to rewrite paths') } finally { setCommitting(false) setConfirming(false) } } const canCommit = !!from.trim() && !!to.trim() return (
e.stopPropagation()} >
Path Remapping
Translate the collection's stored file paths to where they live on this machine.
setFrom(e.target.value)} placeholder="/Volumes/OLD_USB/Music" className={inputCls} />
The path prefix as saved in the collection (may not exist on this machine).
{suggest.data && suggest.data.groups.length > 0 && (
Detected: {suggest.data.groups .filter((g) => g.prefix && g.prefix !== from) .map((g) => ( ))}
)}
setTo(e.target.value)} placeholder="/Users/you/Music" className={inputCls} />
{browsing && ( { setTo(path) setBrowsing(false) }} /> )}
{/* Validation preview */} {preview && (
{preview.matched === 0 ? ( No tracks match “{from.trim()}”. Check the stored prefix. ) : ( {preview.matched} of {preview.total} tracks match; {preview.existing} of{' '} {preview.matched} exist at the target. )}
)} {/* Write-back: permanent, destructive move. Clearly separated. */}
Make permanent

Rewrites the matching file paths directly in the collection (saved to version history). Use this only when you've moved the library for good — it bakes in this machine's paths and will break the collection on other machines/OSes.

{confirming ? (
Rewrite {preview?.matched ?? 0} paths?
) : ( )}
) } /** A compact directory-only browser for choosing the local prefix. */ function FolderBrowser({ initial, onPick, }: { initial?: string onPick: (path: string) => void }) { const [dir, setDir] = useState(initial) const listing = useQuery({ queryKey: ['fs', dir ?? '~'], queryFn: () => api.listDir(dir) }) const data = listing.data return (
{data?.path ?? '…'}
{data?.dirs.length ? ( data.dirs.map((d) => ( )) ) : (
No subfolders.
)}
) }