import { useEffect, useState, type ReactNode } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { api, type Drive, type PlaylistNode } from '../api' import type { Source } from './Sidebar' import { Icon } from '../lib/icons' import { ContextMenu, type MenuItem } from './ContextMenu' /** * Every drive, in the sidebar: plugged-in ones under Devices, and the computer's * own under an expandable Local Storage. * * A drive carrying a OneLibrary library opens as a device, the way rekordbox and * Traktor show a stick: its playlists appear under it and the ordinary track * table browses it. EVERY drive — library or not — also has a Files tree, and * selecting a folder there shows the audio directly in it (not its subfolders: * the tree is how you get to those, and a click on a drive root must never walk * the whole drive). * * The list genuinely changes while the app is open, so unlike everything else in * the sidebar this POLLS. Folder levels are fetched only when expanded. * * A device here is BROWSED, read-only, beside the loaded library. Editing one * means opening it as THE library ("Open for editing…": the drive row's * right-click menu, and a button while a device that can be edited is being * browsed) — one library, one dirty state, one SaveBar (decided 2026-10-01). */ const POLL_MS = 4000 interface Props { source: Source onSelect: (s: Source) => void onError: (msg: string) => void onImport: () => void /** Open a drive's library as THE library, to edit it. */ onOpenLibrary: (path: string) => void } export function DevicesSection({ source, onSelect, onError, onImport, onOpenLibrary }: Props) { const qc = useQueryClient() // Which rows are expanded, by a key per row kind. Not persisted: a tree // reopening deep inside a drive that is no longer plugged in helps nobody. const [expanded, setExpanded] = useState>(new Set()) const isOpenRow = (key: string) => expanded.has(key) const setRow = (key: string, open: boolean) => setExpanded((prev) => { const next = new Set(prev) if (open) next.add(key) else next.delete(key) return next }) const drives = useQuery({ queryKey: ['drives'], queryFn: api.drives, 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), }) const list = drives.data ?? [] const external = list.filter((d) => d.kind === 'external') const local = list.filter((d) => d.kind === 'local') // 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. The same goes for a // folder on it being browsed. const stillPresent = !openPath || list.some((d) => d.library?.path === openPath) useEffect(() => { if (!drives.isSuccess || !openPath || stillPresent || eject.isPending) return eject.mutate() // eslint-disable-next-line react-hooks/exhaustive-deps }, [openPath, stillPresent, drives.isSuccess]) const folderGone = source.kind === 'folder' && drives.isSuccess && !list.some((d) => d.path === '/' || isInside(source.path, d.path)) useEffect(() => { if (folderGone) onSelect({ kind: 'all' }) // eslint-disable-next-line react-hooks/exhaustive-deps }, [folderGone]) const viewingDevice = source.kind === 'device' || source.kind === 'device-playlist' const [menu, setMenu] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null) // Whether the browsed device could be edited if opened as the library: a // FACT from its capabilities (`browsing`), never the platform's name. const deviceCaps = useQuery({ queryKey: ['source-capabilities'], queryFn: api.sourceCapabilities, enabled: !!openPath, staleTime: Infinity, }) const editable = deviceCaps.data?.readonly_cause === 'browsing' const driveRow = (d: Drive, depth: number) => { const key = `drive:${d.path}` const expandedHere = isOpenRow(key) const isOpen = !!d.library && d.library.path === openPath const onClick = () => { if (d.library) { setRow(key, true) if (isOpen) onSelect({ kind: 'device' }) else openDevice.mutate(d.library.path) } else { setRow(key, !expandedHere) } } return (
} label={d.name} title={d.path} expanded={expandedHere} onToggle={() => setRow(key, !expandedHere)} onClick={onClick} onContextMenu={ d.library ? (e) => { e.preventDefault() const path = d.library!.path setMenu({ x: e.clientX, y: e.clientY, items: [{ label: 'Open for editing…', onClick: () => onOpenLibrary(path) }] }) } : undefined } selected={isOpen && source.kind === 'device'} trailing={ isOpen && open.data?.tracks != null ? ( {open.data.tracks} ) : undefined } /> {expandedHere && ( <> {isOpen && (playlists.data ?? []).map((n) => ( ))} )}
) } const localKey = 'local-storage' const localOpen = isOpenRow(localKey) // Shrinkable and self-scrolling, capped at 40%: a deep Files tree must give // way before the playlists do, never push them off the sidebar. return (
Devices {openPath && ( )}
{external.map((d) => driveRow(d, 0))} {local.length > 0 && ( <> } label="Local Storage" expanded={localOpen} onToggle={() => setRow(localKey, !localOpen)} onClick={() => setRow(localKey, !localOpen)} /> {localOpen && local.map((d) => driveRow(d, 1))} )} {openDevice.isPending && (
Opening…
)} {viewingDevice && openPath && ( )} {viewingDevice && openPath && editable && ( )} {menu && setMenu(null)} />}
) } function isInside(path: string, root: string): boolean { const r = root.endsWith('/') || root.endsWith('\\') ? root : `${root}/` return path === root || path.startsWith(r) || path.startsWith(root + '\\') } /** Indent per level, capped so a deep folder still has room for its name. */ function indent(depth: number): number { return 4 + Math.min(depth, 8) * 12 } /** One row of the tree: a chevron that expands, and a label that acts. */ function TreeRow({ depth, icon, label, title, expanded, onToggle, onClick, onContextMenu, selected = false, trailing, }: { depth: number icon: ReactNode label: string title?: string expanded: boolean onToggle: () => void onClick: () => void onContextMenu?: (e: React.MouseEvent) => void selected?: boolean trailing?: ReactNode }) { return (
) } /** * A folder in a Files tree. Clicking it shows its audio in the table (and * expands it); the chevron only expands. Its subfolders are fetched the first * time it opens, one level at a time. */ function FolderRow({ path, name, viewName, icon, depth, source, onSelect, isOpenRow, setRow, }: { path: string name: string /** What the table's header calls this folder, when not its own name. */ viewName?: string icon: 'folder' depth: number source: Source onSelect: (s: Source) => void isOpenRow: (key: string) => boolean setRow: (key: string, open: boolean) => void }) { const key = `folder:${path}` const expanded = isOpenRow(key) const children = useQuery({ queryKey: ['fs-folders', path], queryFn: () => api.folders(path), enabled: expanded, staleTime: 10_000, }) const selected = source.kind === 'folder' && source.path === path return ( <> } label={name} title={path} expanded={expanded} onToggle={() => setRow(key, !expanded)} onClick={() => { setRow(key, true) onSelect({ kind: 'folder', path, name: viewName ?? name }) }} selected={selected} /> {expanded && ( <> {children.isLoading && (
Loading…
)} {children.isError && (
Can’t read this folder
)} {(children.data ?? []).map((c) => ( ))} )} ) } /** * 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 ( <> {(node.children ?? []).map((c) => ( ))} ) }