Added OneLibrary USB loading

This commit is contained in:
patben8 committed 2026-09-22 21:27:33 +02:00
1 parent ed9dfc9d6b
commit 36cfb96c05
5 files changed
+659 -19

No files matched your search

+204
View File
@@ -0,0 +1,204 @@
import { useEffect } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type PlaylistNode } from '../api'
import type { Source } from './Sidebar'
/**
* Plugged-in libraries, in the sidebar, the way rekordbox and Traktor show them.
*
* The list genuinely changes while the app is open — a device is whatever stick
* is mounted — so unlike everything else in the sidebar this POLLS. It is a
* directory stat per mount point, which is cheap enough to do every few seconds
* and the only way a drive can appear without the user reloading.
*
* Browsing a device reuses the ordinary track table and deck: the adapter
* projects a drive into the same generic model the collection uses, so there is
* nothing here that needs its own table, its own row or its own player.
*/
const POLL_MS = 4000
interface Props {
source: Source
onSelect: (s: Source) => void
onError: (msg: string) => void
onImport: () => void
}
export function DevicesSection({ source, onSelect, onError, onImport }: Props) {
const qc = useQueryClient()
const devices = useQuery({
queryKey: ['sources'],
queryFn: api.sources,
refetchInterval: POLL_MS,
})
const open = useQuery({ queryKey: ['source'], queryFn: api.source })
const openPath = open.data?.loaded ? open.data.path : null
const playlists = useQuery({
queryKey: ['source-playlists'],
queryFn: api.sourcePlaylists,
enabled: !!openPath,
})
const openDevice = useMutation({
mutationFn: (path: string) => api.openSource(path),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['source'] })
qc.invalidateQueries({ queryKey: ['source-playlists'] })
onSelect({ kind: 'device' })
},
onError: (e: Error) => onError(e.message),
})
const eject = useMutation({
mutationFn: () => api.closeSource(),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['source'] })
qc.removeQueries({ queryKey: ['source-tracks'] })
qc.removeQueries({ queryKey: ['source-playlists'] })
onSelect({ kind: 'all' })
},
onError: (e: Error) => onError(e.message),
})
// A drive can be physically unplugged while it is open. Nothing crashes — the
// routes just start failing — but leaving it selected would show a library
// that is not there, so fall back to the collection.
const stillPresent =
!openPath || (devices.data ?? []).some((d) => d.path === openPath)
useEffect(() => {
if (!openPath || stillPresent || eject.isPending) return
eject.mutate()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [openPath, stillPresent])
const list = devices.data ?? []
if (list.length === 0 && !openPath) return null
const viewingDevice = source.kind === 'device' || source.kind === 'device-playlist'
return (
<>
<div className="mt-3 flex items-center justify-between px-4">
<span className="text-[10px] font-semibold uppercase tracking-wider text-faint">
Devices
</span>
{openPath && (
<button
title="Close the device and release the drive so it can be ejected"
onClick={() => eject.mutate()}
className="rounded px-1 text-xs text-faint hover:text-text"
>
⏏
</button>
)}
</div>
<div className="mt-1 px-2">
{list.map((d) => {
const isOpen = d.path === openPath
return (
<div key={d.path}>
<button
onClick={() =>
isOpen ? onSelect({ kind: 'device' }) : openDevice.mutate(d.path)
}
className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors ${
isOpen && source.kind === 'device'
? 'bg-accent-soft text-text'
: 'text-muted hover:bg-ink-800 hover:text-text'
}`}
>
<span className="w-3 text-center text-[11px] text-gold">⬒</span>
<span className="flex-1 truncate" title={d.path}>
{d.label}
</span>
{isOpen && open.data?.tracks != null && (
<span className="text-[10px] text-faint">{open.data.tracks}</span>
)}
</button>
{isOpen &&
(playlists.data ?? []).map((n) => (
<DevicePlaylistRow
key={n.id}
node={n}
depth={1}
source={source}
onSelect={onSelect}
/>
))}
</div>
)
})}
{openDevice.isPending && (
<div className="px-2 py-1.5 text-xs text-faint">Opening…</div>
)}
{viewingDevice && openPath && (
<button
onClick={onImport}
className="mt-2 mb-1 w-full rounded-md bg-accent px-2 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110"
>
Import to collection…
</button>
)}
</div>
</>
)
}
/**
* A playlist on the device. Deliberately NOT `NodeRow`: that one carries rename
* and delete, and every one of a device's nodes reports those as false, so
* reusing it would mean rendering controls that exist only to be disabled.
*/
function DevicePlaylistRow({
node,
depth,
source,
onSelect,
}: {
node: PlaylistNode
depth: number
source: Source
onSelect: (s: Source) => void
}) {
const selected = source.kind === 'device-playlist' && source.id === node.id
const isFolder = node.kind === 'folder'
return (
<>
<button
disabled={!node.selectable}
onClick={() =>
node.selectable && onSelect({ kind: 'device-playlist', id: node.id, name: node.name })
}
style={{ paddingLeft: 8 + depth * 12 }}
className={`flex w-full items-center gap-2 rounded-md py-1 pr-2 text-left text-sm transition-colors ${
selected
? 'bg-accent-soft text-text'
: node.selectable
? 'text-muted hover:bg-ink-800 hover:text-text'
: 'text-faint'
}`}
>
<span className="w-3 text-center text-[11px] text-faint">
{isFolder ? '▸' : '♫'}
</span>
<span className="flex-1 truncate">{node.name}</span>
{!isFolder && <span className="text-[10px] text-faint">{node.count}</span>}
</button>
{(node.children ?? []).map((c) => (
<DevicePlaylistRow
key={c.id}
node={c}
depth={depth + 1}
source={source}
onSelect={onSelect}
/>
))}
</>
)
}
+263
View File
@@ -0,0 +1,263 @@
import { useEffect, useRef, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type ImportPreview, type JobStatus } from '../api'
/**
* Import a browsed device into the loaded collection.
*
* Two phases in one dialog, because they are one decision: a confirm step that
* says what is about to happen, and a progress step that shows it happening.
*
* The preview is fetched fresh every time this opens and whenever the
* destination changes. It is never cached: a stick can be re-exported between
* looking and importing, and a stale preview is worse than none.
*/
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`
}
interface Props {
/** Playlist to import, or null for the whole device. */
playlistId: string | null
deviceLabel: string
onClose: () => void
onDone: (msg: string) => void
onError: (msg: string) => void
}
export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError }: Props) {
const qc = useQueryClient()
const [destination, setDestination] = useState('')
const [job, setJob] = useState<JobStatus | null>(null)
const [starting, setStarting] = useState(false)
const pollRef = useRef<number | null>(null)
// A sensible default the user can override. `~` is expanded server-side.
useEffect(() => {
if (!destination) setDestination(`~/Music/Konduktor Imports/${deviceLabel}`)
}, [deviceLabel, destination])
const body = {
destination,
playlist_ids: playlistId ? [playlistId] : [],
track_ids: [],
folder_name: deviceLabel,
}
const preview = useQuery<ImportPreview>({
queryKey: ['import-preview', destination, playlistId],
queryFn: () => api.importPreview(body),
enabled: !!destination && !job,
staleTime: 0,
gcTime: 0,
})
// Poll while the job runs. Cleared on unmount so closing mid-import does not
// leave a timer firing at a dead component — the import itself keeps going,
// which is the point of it being a job.
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') {
if (pollRef.current) window.clearInterval(pollRef.current)
if (next.state === 'done') {
const r = next.result as { tracks?: number; playlists?: number } | null
// The collection changed underneath every cached view of it.
qc.invalidateQueries({ queryKey: ['tracks'] })
qc.invalidateQueries({ queryKey: ['playlists'] })
qc.invalidateQueries({ queryKey: ['collection'] })
qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['facets'] })
onDone(
`Imported ${r?.tracks ?? 0} track${r?.tracks === 1 ? '' : 's'}` +
(r?.playlists ? ` and ${r.playlists} playlist${r.playlists === 1 ? '' : 's'}` : ''),
)
} else if (next.state === 'failed') {
onError(next.error || 'Import 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])
const start = async () => {
setStarting(true)
try {
setJob(await api.startImport(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
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
<div className="w-full max-w-lg rounded-lg border border-line bg-ink-900 shadow-xl">
<div className="border-b border-line px-5 py-3">
<h2 className="text-sm font-semibold text-text">
Import from {deviceLabel}
{playlistId ? '' : ' — everything'}
</h2>
</div>
<div className="space-y-4 px-5 py-4 text-sm">
{!job && (
<>
<label className="block">
<span className="mb-1 block text-xs text-muted">Copy audio into</span>
<input
value={destination}
onChange={(e) => setDestination(e.target.value)}
className="w-full rounded-md border border-line bg-ink-950 px-2 py-1.5 text-sm text-text outline-none focus:border-accent"
/>
</label>
{preview.isLoading && <div className="text-faint">Checking…</div>}
{preview.isError && (
<div className="text-pink">{(preview.error as Error).message}</div>
)}
{p && (
<div className="space-y-2">
<div className="text-text">
{p.importable} track{p.importable === 1 ? '' : 's'}
{p.playlists.length > 0 &&
` · ${p.playlists.length} playlist${p.playlists.length === 1 ? '' : 's'}`}
<span className="text-muted"> · {gb(p.total_bytes)} to copy</span>
</div>
{p.free_bytes != null && (
<div className={p.enough_space === false ? 'text-pink' : 'text-faint'}>
{gb(p.free_bytes)} free
{p.enough_space === false && ' — not enough space'}
</div>
)}
{/* Reported and then skipped, rather than failing the whole
import halfway through a multi-minute copy. */}
{p.missing.length > 0 && (
<div className="rounded border border-line bg-ink-950 px-3 py-2 text-xs text-pink">
{p.missing.length} track{p.missing.length === 1 ? '' : 's'} will be skipped —
the audio file is not on the drive:
<div className="mt-1 text-faint">{p.missing.slice(0, 4).join(', ')}</div>
</div>
)}
{/* A warning, not a block: everything is imported as a new
entry, so a re-import legitimately duplicates. */}
{p.duplicates.length > 0 && (
<div className="rounded border border-line bg-ink-950 px-3 py-2 text-xs text-gold">
{p.duplicates.length} of these look like tracks your collection already has.
They will be added again as new entries.
</div>
)}
<div className="text-xs text-faint">
Playlists land in a folder called “{deviceLabel}”.
</div>
</div>
)}
</>
)}
{job && (
<div className="space-y-3">
<div className="text-text">{job.message || 'Working…'}</div>
<div className="h-2 overflow-hidden rounded-full bg-ink-950">
<div
className={`h-full transition-[width] duration-200 ${
job.state === 'failed' ? 'bg-pink' : 'bg-accent'
} ${pct == null ? 'animate-pulse w-1/3' : ''}`}
style={pct == null ? undefined : { width: `${pct}%` }}
/>
</div>
{pct != null && running && (
<div className="text-xs text-faint">
{gb(job.done)} of {gb(job.total)}
</div>
)}
{job.state === 'cancelled' && (
<div className="text-xs text-muted">
Cancelled. Nothing was added, and the copied files were removed.
</div>
)}
{job.state === 'failed' && <div className="text-xs text-pink">{job.error}</div>}
{job.state === 'done' && (
<div className="text-xs text-mint">Done — the tracks are in your collection.</div>
)}
</div>
)}
</div>
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
{running ? (
<>
<button
onClick={cancel}
className="rounded-md border border-line px-3 py-1.5 text-sm text-muted hover:text-text"
>
Cancel import
</button>
<button
onClick={onClose}
className="rounded-md px-3 py-1.5 text-sm text-faint hover:text-text"
title="The import keeps running"
>
Hide
</button>
</>
) : (
<>
<button
onClick={onClose}
className="rounded-md border border-line px-3 py-1.5 text-sm text-muted hover:text-text"
>
{finished ? 'Close' : 'Cancel'}
</button>
{!finished && (
<button
disabled={
starting || !p || p.importable === 0 || p.enough_space === false
}
onClick={start}
className="rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110 disabled:opacity-40"
>
{starting ? 'Starting…' : `Import ${p?.importable ?? ''}`.trim()}
</button>
)}
</>
)}
</div>
</div>
</div>
)
}
+12 -6
View File
@@ -23,6 +23,13 @@ interface Props {
onError?: (msg: string) => void
/** Neutral/success feedback (e.g. Auto Hotcues result). */
onNotify?: (kind: 'success' | 'error', msg: string) => void
/**
* The track came from a browsed DEVICE, not the loaded library, so its audio
* and cues must be read from the source endpoints. Every EDIT control is
* already inert here — a device's capabilities say `writable: false`, and the
* deck gates on those — so this only needs to redirect the two READS.
*/
fromDevice?: boolean
}
function fmt(secs: number): string {
@@ -57,7 +64,7 @@ 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 }: Props) {
export function PrepStrip({ track, playRequest = 0, onError, onNotify, fromDevice = false }: Props) {
const qc = useQueryClient()
const [playing, setPlaying] = useState(false)
const [previewing, setPreviewing] = useState(false) // momentary hold-to-play active
@@ -214,7 +221,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
let cancelled = false
setCols(null)
setWaveStatus('loading')
analyzeWaveform(api.audioUrl(trackId))
analyzeWaveform(fromDevice ? api.sourceAudioUrl(trackId) : api.audioUrl(trackId))
.then((res) => {
if (cancelled) return
setCols(res.cols)
@@ -245,7 +252,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
return () => {
cancelled = true
}
}, [trackId])
}, [trackId, fromDevice])
// Fetch beatgrid + cue markers for the loaded track.
useEffect(() => {
@@ -255,8 +262,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
}
let cancelled = false
setCueData(null)
api
.trackCues(trackId)
;(fromDevice ? api.sourceTrackCues(trackId) : api.trackCues(trackId))
.then((d) => {
if (cancelled) return
setCueData(d)
@@ -271,7 +277,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
return () => {
cancelled = true
}
}, [trackId])
}, [trackId, fromDevice])
const toggle = () => {
const eng = playbackRef.current
+25 -2
View File
@@ -3,14 +3,30 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type PlaylistKind, type PlaylistNode } from '../api'
import { useCaps } from '../lib/capabilities'
import { SaveBar } from './SaveBar'
import { DevicesSection } from './DevicesSection'
export type Source = { kind: 'all' } | { kind: 'playlist'; id: string; name: string }
/**
* Which view the main table is showing.
*
* `device*` variants are a browsed import SOURCE — a plugged-in stick — rather
* than the loaded collection. They are a view like any other, so the table, the
* toolbar and the deck need no special case; what differs is that a device is
* read-only, and that is carried by its CAPABILITIES rather than by this type,
* so no component has to ask "am I looking at a device?" before deciding what to
* offer.
*/
export type Source =
| { kind: 'all' }
| { kind: 'playlist'; id: string; name: string }
| { kind: 'device' }
| { kind: 'device-playlist'; id: string; name: string }
interface Props {
source: Source
onSelect: (s: Source) => void
onError: (msg: string) => void
onOpenHistory: () => void
onImport: () => void
}
// Kind picks the icon; every behavioural question is answered by the node's own
@@ -170,7 +186,7 @@ function NodeRow({
)
}
export function Sidebar({ source, onSelect, onError, onOpenHistory }: Props) {
export function Sidebar({ source, onSelect, onError, onOpenHistory, onImport }: Props) {
const qc = useQueryClient()
// There is no per-node flag for "you may create a NEW playlist" — the node
// flags describe existing nodes — so this is the library-level gate.
@@ -263,6 +279,13 @@ export function Sidebar({ source, onSelect, onError, onOpenHistory }: Props) {
))}
</div>
<DevicesSection
source={source}
onSelect={onSelect}
onError={onError}
onImport={onImport}
/>
<button
onClick={onOpenHistory}
className="flex items-center justify-center gap-2 border-t border-line px-4 py-2 text-center text-xs text-muted hover:bg-ink-800 hover:text-text"