import { createPortal } from 'react-dom' import { useEffect, useRef, useState, type ReactNode } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' import { api, type FolderAddPreview, type FolderAddRequest, type JobStatus } from '../api' import { useCaps } from '../lib/capabilities' import { placedAudioSummary } from '../lib/platformCopy' import { FolderPicker } from './FolderPicker' /** * Add browsed files to the collection — and, optionally, to a playlist or export. * * A library that places its own audio (`tracks.places_audio`, a OneLibrary * stick) is the exception: only files already on it can stay in place, so the * dialog STATES what will happen instead of asking (decided 2026-10-01). * * Otherwise copy vs. leave-in-place is ASKED every time, with nothing preselected: the * right answer depends on the drive (a stick is about to be unplugged) and on * how the DJ keeps their music, and a remembered default would quietly apply * last week's answer to a different drive. * * A library held by a server (`tracks.audio_destination === 'library'`) is the * other exception: it cannot see this computer's files, so the only choice is * which folder ON THE SERVER they are uploaded into. * * A playlist or export target still needs the files in the collection first — * both hold collection track ids — so the dialog says so rather than doing it * silently. Files the collection already holds are not added again, but still * go into the target. */ const POLL_MS = 300 function gb(bytes: number): string { if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB` if (bytes >= 1e6) return `${(bytes / 1e6).toFixed(0)} MB` return `${(bytes / 1e3).toFixed(0)} kB` } export interface AddTarget { kind: 'playlist' | 'export' id: string name: string } interface Props { trackIds: string[] target: AddTarget | null onClose: () => void onDone: (msg: string) => void onError: (msg: string) => void } export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: Props) { const qc = useQueryClient() // The LIBRARY's capabilities (this dialog is mounted outside the browsed // view's swapped context). A library that places its own audio — a stick — // decides copy vs in place itself, so there is nothing to ask. const caps = useCaps() const places = caps.tracks.places_audio // Uploaded into a folder on the server: nothing to ask but where. const uploads = !places && caps.tracks.audio_destination === 'library' const [mode, setMode] = useState<'copy' | 'reference' | null>(uploads ? 'copy' : null) const [folder, setFolder] = useState('') const remote = useServerImportFolder(uploads) const [browsing, setBrowsing] = useState(false) const [job, setJob] = useState(null) const [starting, setStarting] = useState(false) const pollRef = useRef(null) // The same import folder as a device import: one place your copied music goes. const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) const prefsLoaded = prefs.isSuccess useEffect(() => { if (!prefsLoaded || folder) return if (uploads) { if (remote.folder) setFolder(remote.folder) return } const p = prefs.data as { importFolder?: string } setFolder(p?.importFolder || '~/Music/Konduktor Imports') }, [prefsLoaded, prefs.data, folder, uploads, remote.folder]) const body: FolderAddRequest = { track_ids: trackIds, // The preview needs A mode to size anything; "reference" costs nothing to // ask about and is replaced as soon as the user picks. mode: places ? 'copy' : (mode ?? 'reference'), destination: !places && mode === 'copy' ? folder : null, playlist_id: target?.kind === 'playlist' ? target.id : null, export_id: target?.kind === 'export' ? target.id : null, } const preview = useQuery({ queryKey: ['folder-add-preview', trackIds, places ? 'placed' : mode, folder, target?.id], queryFn: () => api.folderAddPreview(body), enabled: !job && (places || mode !== 'copy' || !!folder), staleTime: 0, gcTime: 0, }) useEffect(() => { if (!job || job.state !== 'running') return pollRef.current = window.setInterval(async () => { try { const next = await api.job(job.id) setJob(next) if (next.state === 'running') return if (pollRef.current) window.clearInterval(pollRef.current) if (next.state === 'done') { const r = next.result as { tracks?: number; track_ids?: string[] } | null qc.invalidateQueries({ queryKey: ['tracks'] }) qc.invalidateQueries({ queryKey: ['playlists'] }) qc.invalidateQueries({ queryKey: ['playlist'] }) qc.invalidateQueries({ queryKey: ['collection'] }) qc.invalidateQueries({ queryKey: ['state'] }) qc.invalidateQueries({ queryKey: ['facets'] }) qc.invalidateQueries({ queryKey: ['folder-tracks'] }) if (target?.kind === 'export') { qc.invalidateQueries({ queryKey: ['exports'] }) qc.invalidateQueries({ queryKey: ['export-contents', target.id] }) qc.invalidateQueries({ queryKey: ['export-tracks', target.id] }) qc.invalidateQueries({ queryKey: ['export-loose', target.id] }) } const added = r?.tracks ?? 0 const total = r?.track_ids?.length ?? added onDone( target ? `Added ${total} track${total === 1 ? '' : 's'} to ${target.name}` + (added ? ` (${added} new to your collection)` : '') : `Added ${added} track${added === 1 ? '' : 's'} to your collection`, ) } else if (next.state === 'failed') { onError(next.error || 'Adding failed') } } catch (e) { onError((e as Error).message) if (pollRef.current) window.clearInterval(pollRef.current) } }, POLL_MS) return () => { if (pollRef.current) window.clearInterval(pollRef.current) } }, [job, qc, onDone, onError, target]) const start = async () => { setStarting(true) try { setJob(await api.folderAdd(body)) } catch (e) { onError((e as Error).message) } finally { setStarting(false) } } const cancel = async () => { if (!job) return try { await api.cancelJob(job.id) } catch (e) { onError((e as Error).message) } } const p = preview.data const running = job?.state === 'running' const finished = job != null && job.state !== 'running' const pct = job && job.total > 0 ? Math.min(100, (job.done / job.total) * 100) : null const n = trackIds.length const newCount = p?.importable ?? 0 const shown = places ? 'placed' : mode const libraryName = places ? caps.save.app_name : 'your collection' const canAdd = !starting && shown !== null && !!p && (newCount > 0 || (!!target && p.existing.length > 0)) && p.enough_space !== false const title = target ? `Add ${n} track${n === 1 ? '' : 's'} to ${target.name}` : `Add ${n} track${n === 1 ? '' : 's'} to ${libraryName}` const option = (value: 'copy' | 'reference', label: string, detail: ReactNode) => ( ) return createPortal( <> {browsing && ( { setFolder(path) if (uploads) remote.remember(path) else api.patchPrefs({ importFolder: path }).catch(() => {}) }} onClose={() => setBrowsing(false)} /> )}

{title}

{!job && ( <> {target && (
{target.kind === 'playlist' ? 'Playlists' : 'Exports'} hold tracks from your collection, so these are added to the collection first.
)} {places && p && (
{placedAudioSummary(caps.save, p.copied ?? 0, p.in_place ?? 0)}
)} {uploads && (
Uploaded to {remote.serverName} into
{folder ? `\u200E${folder}\u200E` : 'Loading…'}
)} {!places && !uploads && (
{option( 'copy', 'Copy into your import folder', {/* LRM marks: in an rtl box (for left-truncation) a leading "~" would otherwise be moved to the end. */} {folder ? `\u200E${folder}\u200E` : 'Loading…'} , )} {option( 'reference', 'Leave them where they are', 'Your collection points at these files. Nothing is copied.', )}
)} {mode === 'reference' && p?.removable && (
These files are on an external drive. They will go missing from your collection whenever the drive is unplugged.
)} {preview.isError && (
{(preview.error as Error).message}
)} {shown && p && (
{newCount} new to {libraryName} {shown !== 'reference' && p.total_bytes > 0 && ( · {gb(p.total_bytes)} to {uploads ? 'upload' : 'copy'} )}
{shown !== 'reference' && p.free_bytes != null && (
{gb(p.free_bytes)} free{uploads ? ' on the server' : ''} {p.enough_space === false && ' — not enough space'}
)} {p.existing.length > 0 && (
{p.existing.length} {p.existing.length === 1 ? 'is' : 'are'} already in {' '}{libraryName} and will not be added again {target ? ` — but will still go into ${target.name}` : ''}.
)} {p.missing.length > 0 && (
{p.missing.length} file{p.missing.length === 1 ? ' is' : 's are'} no longer there and will be skipped.
)} {shown !== 'reference' && p.duplicates.length > 0 && (
{p.duplicates.length} of these look like tracks your collection already has. The copies will be added as new entries.
)}
)} )} {job && (
{job.message || 'Working…'}
{job.state === 'cancelled' && (
Cancelled. Nothing was added, and any copied files were removed.
)} {job.state === 'failed' &&
{job.error}
} {job.state === 'done' &&
Done.
}
)}
{running ? ( <> ) : ( <> {!finished && ( )} )}
, document.body, ) } /** * A folder ON THE SERVER of a remote library — where uploads go, or where stem * files are written: the one last chosen for THIS remote (remembered per remote * under `key`, since each server has its own folders), else its content folder * (plus `sub`). `serverName` names it in the dialog. */ export function useServerFolder( enabled: boolean, key: 'remoteImportFolders' | 'remoteStemFolders' = 'remoteImportFolders', sub = '', ) { const collection = useQuery({ queryKey: ['collection'], queryFn: api.collection, enabled }) const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs, enabled }) const root = useQuery({ queryKey: ['fs', 'library', '~', null], queryFn: () => api.libraryListDir(), enabled }) const remoteId = collection.data?.library?.remote?.id ?? null const saved = (prefs.data as Record | undefined> | undefined)?.[key] const home = root.data?.home const folder = (remoteId && saved?.[remoteId]) || (home ? (sub ? `${home}/${sub}` : home) : '') return { folder, serverName: collection.data?.library?.display_name ?? 'the server', remember: (path: string) => { if (!remoteId) return api.patchPrefs({ [key]: { ...(saved ?? {}), [remoteId]: path } }).catch(() => {}) }, } } export const useServerImportFolder = (enabled: boolean) => useServerFolder(enabled)