Improved file browser

This commit is contained in:
patben8 committed 2026-09-23 11:19:58 +02:00
1 parent 8d11acd783
commit 93ec2ef425
10 files changed
+540 -204

No files matched your search

+31 -3
View File
@@ -47,6 +47,16 @@ Two independent apps that talk over HTTP:
- `registry.py` — adapter selection by **`can_open()` probe**, not extension - `registry.py` — adapter selection by **`can_open()` probe**, not extension
(Rekordbox is a `.db`, Serato is a directory). (Rekordbox is a `.db`, Serato is a directory).
- `audio_tags.py`, `pathmap.py`, `auto_hotcues.py` — format-agnostic helpers. - `audio_tags.py`, `pathmap.py`, `auto_hotcues.py` — format-agnostic helpers.
- `places.py` — where a person keeps things on THIS computer: the user's own
folders (via `platformdirs` — hardcoding is wrong on every OS differently:
`~/Videos` is `Movies` on macOS, Linux's are user-configurable localised
XDG dirs, and Windows Known Folders are routinely relocated by OneDrive)
and mounted volumes. The mount scanner lives here rather than in the
OneLibrary adapter, where it grew: "where does this OS mount things" is
not adapter knowledge, the file browser needs the same answer, and two
scanners would drift. `is_boot_volume()` compares **st_dev against `/`**,
not the name, because macOS lists the startup disk in `/Volumes` next to
real removable media and `Macintosh HD` is only its default name.
- `adapters/traktor/` — everything that knows NML exists. - `adapters/traktor/` — everything that knows NML exists.
- `store.py` (`TraktorStore`) — the retained native model: owns the parsed - `store.py` (`TraktorStore`) — the retained native model: owns the parsed
dataclass NML, applies every edit, renders + saves. See "Write path". dataclass NML, applies every edit, renders + saves. See "Write path".
@@ -183,7 +193,12 @@ Two independent apps that talk over HTTP:
does not reshuffle between launches), `/api/library/options` (that does not reshuffle between launches), `/api/library/options` (that
platform's detections + its own last-opened) and `/api/fs/list` (that platform's detections + its own last-opened) and `/api/fs/list` (that
platform's suffixes; a directory-selecting platform contributes none, so its platform's suffixes; a directory-selecting platform contributes none, so its
browse shows folders only). `/api/library/open` checks `exists()`, **not browse shows folders only) and `/api/fs/places` (the browser's sidebar —
the user's folders, then drives, plus that platform's own location when it
keeps one at a fixed path; a place that does not exist is **omitted, never
disabled**, since a greyed-out Music folder reads as breakage where its
absence reads as an accurate description of the machine).
`/api/library/open` checks `exists()`, **not
`is_file()`** — which shapes are valid is `can_open()`'s business, and a `is_file()`** — which shapes are valid is `can_open()`'s business, and a
OneLibrary library is a drive. `prefs` keeps last-opened **per platform**: OneLibrary library is a drive. `prefs` keeps last-opened **per platform**:
offering a Rekordbox `master.db` to someone who just chose Traktor is an offering a Rekordbox `master.db` to someone who just chose Traktor is an
@@ -204,7 +219,19 @@ Two independent apps that talk over HTTP:
adapter supplies (`app_name`, `library_label`, `overwrite_risk`), so adapter supplies (`app_name`, `library_label`, `overwrite_risk`), so
"Close Traktor before saving — it overwrites collection.nml on exit" stays "Close Traktor before saving — it overwrites collection.nml on exit" stays
specific without being hard-coded. Never put finished sentences in the API. specific without being hard-coded. Never put finished sentences in the API.
- `components/` — `CollectionPicker` (**two steps: which PLATFORM, then which - `components/` — `FileBrowser` (**the one file browser**: places rail + path
bar + listing, `mode: 'file' | 'directory'`. Deliberately NOT the chrome or
the confirm footer — its two callers frame it very differently, one as a step
inside a full-screen card and one as a modal over the import dialog, and a
shared wrapper would put a modal inside a modal. `path` is controlled,
because the caller needs to know where you are standing to label its footer;
`useFsListing()` is exported so the caller reads the RESOLVED path through
the same query key rather than being told it by an effect. The rail
**navigates, never selects** — one click there must not be able to open a
library or commit an import destination. It polls, because drives come and
go while a dialog is open, and the volatile Drives group is LAST so an
appearing drive cannot shift the rows above a moving cursor),
`CollectionPicker` (**two steps: which PLATFORM, then which
library** — Automatic / Open last / Find manually, the last revealing a file library** — Automatic / Open last / Find manually, the last revealing a file
browser. The platform comes first because every later answer depends on it: browser. The platform comes first because every later answer depends on it:
asked the other way round, "Automatic" had to guess ACROSS platforms and did asked the other way round, "Automatic" had to guess ACROSS platforms and did
@@ -353,7 +380,8 @@ serialization path.** It enforces:
detections and returned `[0]`, so a plugged-in USB stick could be offered as detections and returned `[0]`, so a plugged-in USB stick could be offered as
the user's collection and nothing failed — it just opened the wrong library. the user's collection and nothing failed — it just opened the wrong library.
Also pins that a drive is named the same whichever of its two valid paths was Also pins that a drive is named the same whichever of its two valid paths was
opened. Needs nothing installed: every assertion is about the SHAPE of the opened, that every offered place exists, that the boot volume is not offered
as a drive, and that the adapter and the browser share ONE mount scanner. Needs nothing installed: every assertion is about the SHAPE of the
answer, and prefs are redirected to a temp file so a test can never rewrite answer, and prefs are redirected to a temp file so a test can never rewrite
the user's last-opened library. the user's last-opened library.
- `test_layering.py` — `core/` imports nothing platform-specific, and no adapter - `test_layering.py` — `core/` imports nothing platform-specific, and no adapter
@@ -14,49 +14,17 @@ app feel broken.
from __future__ import annotations from __future__ import annotations
import logging import logging
import os
import string
import sys
from pathlib import Path from pathlib import Path
# Where this OS mounts drives is not adapter knowledge — the file browser needs
# the same answer, and two scanners would drift. It grew here because this is
# the platform whose libraries ARE drives; it lives in core now.
from ...core.places import mount_points as _mount_points
from .layout import DriveLayout from .layout import DriveLayout
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
def _mount_points() -> list[Path]:
"""Plausible removable-media mount points for this OS."""
out: list[Path] = []
if sys.platform == "darwin":
out.append(Path("/Volumes"))
elif sys.platform.startswith("linux"):
out.extend([Path("/media"), Path("/mnt"), Path("/run/media")])
user = os.environ.get("USER")
if user:
out.append(Path("/media") / user)
out.append(Path("/run/media") / user)
roots: list[Path] = []
for base in out:
try:
if not base.is_dir():
continue
roots.extend(p for p in base.iterdir() if p.is_dir())
except OSError:
continue
if sys.platform == "win32":
# No mount-point directory to list: check the drive letters directly.
for letter in string.ascii_uppercase:
drive = Path(f"{letter}:\\")
try:
if drive.is_dir():
roots.append(drive)
except OSError:
continue
return roots
def describe(path: Path) -> dict: def describe(path: Path) -> dict:
"""A candidate record for a drive or database path, shaped for the picker.""" """A candidate record for a drive or database path, shaped for the picker."""
path = Path(path) path = Path(path)
+142
View File
@@ -0,0 +1,142 @@
"""Where a person keeps things on this computer.
Two jobs, both of them "ask the OS rather than assume":
* **Mounted volumes.** Where a drive appears is per-OS and nothing else in the
app can work it out. This lives here rather than in the OneLibrary adapter —
which is where it grew, because that is the platform whose libraries ARE
drives — because "where does this OS mount things" is not adapter knowledge.
The file browser needs the same answer, and two scanners would drift.
* **The user's own folders.** `platformdirs` answers these, and hardcoding
them would be wrong on every OS in a different way: `~/Videos` is `Movies`
on macOS, Linux's are XDG user-dirs which are user-configurable AND
localised, and Windows Known Folders are routinely **relocated by OneDrive**
so Documents and Desktop are often not under the home directory at all.
A place that does not exist is never returned. A file browser offering a Music
folder that is not there reads as breakage, whereas its absence reads as an
accurate description of the machine.
"""
from __future__ import annotations
import logging
import os
import string
import sys
from pathlib import Path
import platformdirs
log = logging.getLogger(__name__)
def mount_points() -> list[Path]:
"""Every mounted volume's root directory, for this OS.
Only the ROOTS: a drive can hold tens of thousands of files, and walking a
slow USB stick to answer "what is plugged in" is exactly the kind of thing
that makes an app feel broken.
"""
bases: list[Path] = []
if sys.platform == "darwin":
bases.append(Path("/Volumes"))
elif sys.platform.startswith("linux"):
bases.extend([Path("/media"), Path("/mnt"), Path("/run/media")])
user = os.environ.get("USER")
if user:
bases.append(Path("/media") / user)
bases.append(Path("/run/media") / user)
roots: list[Path] = []
for base in bases:
try:
if not base.is_dir():
continue
roots.extend(p for p in base.iterdir() if p.is_dir())
except OSError:
continue
if sys.platform == "win32":
# No mount-point directory to list: check the drive letters directly.
for letter in string.ascii_uppercase:
drive = Path(f"{letter}:\\")
try:
if drive.is_dir():
roots.append(drive)
except OSError:
continue
return roots
def _boot_device() -> int | None:
try:
return Path("/").stat().st_dev
except OSError:
return None
def is_boot_volume(path: Path) -> bool:
"""Whether `path` is the volume the OS itself booted from.
macOS lists the startup disk in `/Volumes` alongside real removable media,
so a "Drives" list that does not filter it leads with a path back to where
the user already is. Compared by DEVICE id rather than by name, because
`Macintosh HD` is only the default name and is freely renamed.
"""
boot = _boot_device()
if boot is None:
return False
try:
return path.stat().st_dev == boot
except OSError:
return False
def volumes(*, include_boot: bool = False) -> list[Path]:
"""Mounted volumes, newest-mounted order not guaranteed. Sorted by name."""
found = [v for v in mount_points() if include_boot or not is_boot_volume(v)]
return sorted(set(found), key=lambda p: p.name.lower())
# The user's own folders, in the order a file browser should show them. Music
# sits high because this is a DJ app: it is the likeliest destination by far.
_USER_DIRS: tuple[tuple[str, str, str], ...] = (
("home", "Home", ""),
("music", "Music", "user_music_dir"),
("desktop", "Desktop", "user_desktop_dir"),
("documents", "Documents", "user_documents_dir"),
("downloads", "Downloads", "user_downloads_dir"),
)
def user_places() -> list[dict]:
"""The user's own folders that actually exist on this machine."""
out: list[dict] = []
seen: set[str] = set()
for kind, name, getter in _USER_DIRS:
try:
path = Path.home() if not getter else Path(getattr(platformdirs, getter)())
if not path.is_dir():
continue
key = str(path)
# Windows can resolve two Known Folders to one place; listing it
# twice under different names would just look like a bug.
if key in seen:
continue
seen.add(key)
out.append({"kind": kind, "name": name, "path": key})
except (OSError, AttributeError):
continue
return out
def volume_places() -> list[dict]:
"""Mounted drives, named as the user sees them."""
out: list[dict] = []
for vol in volumes():
try:
out.append({"kind": "volume", "name": vol.name or str(vol), "path": str(vol)})
except OSError:
continue
return out
+42 -1
View File
@@ -17,7 +17,7 @@ from . import __version__, history, prefs
from .app_state import STATE from .app_state import STATE
from .core import auto_hotcues as ah from .core import auto_hotcues as ah
from . import importer from . import importer
from .core import registry from .core import places, registry
from .core.adapter import ( from .core.adapter import (
AdapterError, AdapterError,
InvalidCommand, InvalidCommand,
@@ -45,6 +45,7 @@ from .schemas import (
FileTagOutcome, FileTagOutcome,
FsEntry, FsEntry,
FsListing, FsListing,
FsPlace,
AddGridMarker, AddGridMarker,
GridMarkerEdit, GridMarkerEdit,
ReplaceGrid, ReplaceGrid,
@@ -245,6 +246,46 @@ def patch_prefs(patch: dict) -> dict:
return prefs.update_prefs(patch) return prefs.update_prefs(patch)
@app.get("/api/fs/places", response_model=list[FsPlace])
def fs_places(platform: str | None = None) -> list[FsPlace]:
"""Sidebar shortcuts for the file browser: the user's folders, then drives.
Answered by the server because only it can stat a filesystem, and re-asked
by the client rather than cached: drives come and go while a dialog is open,
and a browser that exists to find a stick you just plugged in has to show it.
`platform` adds that platform's own default location, which is the likeliest
destination when browsing for one of its libraries. Only for platforms whose
library sits at a fixed path — a removable one's libraries ARE the drives,
which are already listed.
"""
out = [FsPlace(**p) for p in places.user_places()]
out += [FsPlace(**p) for p in places.volume_places()]
if platform:
try:
driver = registry.driver_by_platform(platform)
except LibraryNotSupported:
driver = None
if driver is not None and not getattr(driver, "removable", False):
seen = {p.path for p in out}
try:
found = driver.detect()
except OSError:
found = []
for candidate in found:
# The place is the folder CONTAINING the library, because a
# place is somewhere you navigate to, not something you pick.
folder = Path(candidate["path"]).parent
if str(folder) in seen or not folder.is_dir():
continue
seen.add(str(folder))
out.append(
FsPlace(kind="library", name=candidate.get("label") or folder.name,
path=str(folder))
)
return out
@app.get("/api/fs/list", response_model=FsListing) @app.get("/api/fs/list", response_model=FsListing)
def fs_list(path: str | None = None, platform: str | None = None) -> FsListing: def fs_list(path: str | None = None, platform: str | None = None) -> FsListing:
"""List directories and openable library files for the in-app file browser. """List directories and openable library files for the in-app file browser.
+13
View File
@@ -135,6 +135,19 @@ class CollectionOptions(BaseModel):
recent: CollectionCandidate | None = None # last opened (from userprefs) recent: CollectionCandidate | None = None # last opened (from userprefs)
class FsPlace(BaseModel):
"""A shortcut in the file browser's sidebar.
`kind` groups it and picks its icon; it is never a finished sentence, and
the browser decides what "volume" looks like. A place is always a DIRECTORY
that exists right now — one that does not is omitted rather than disabled.
"""
kind: str # home | music | desktop | documents | downloads | volume | library
name: str
path: str
class FsEntry(BaseModel): class FsEntry(BaseModel):
name: str name: str
path: str path: str
+46 -2
View File
@@ -23,8 +23,8 @@ _TMP = tempfile.TemporaryDirectory()
prefs._PREFS_PATH = Path(_TMP.name) / "userprefs.json" prefs._PREFS_PATH = Path(_TMP.name) / "userprefs.json"
prefs._LEGACY_PREFS_PATH = Path(_TMP.name) / "absent.json" prefs._LEGACY_PREFS_PATH = Path(_TMP.name) / "absent.json"
from konduktor.core import registry # noqa: E402 from konduktor.core import places, registry # noqa: E402
from konduktor.main import collection_options, fs_list, platforms # noqa: E402 from konduktor.main import collection_options, fs_list, fs_places, platforms # noqa: E402
failed = False failed = False
@@ -120,6 +120,50 @@ check("folders are listed for every platform",
all({d.name for d in fs_list(str(root), p).dirs} == {"SomeDrive"} all({d.name for d in fs_list(str(root), p).dirs} == {"SomeDrive"}
for p in (None, "traktor", "rekordbox", "onelibrary"))) for p in (None, "traktor", "rekordbox", "onelibrary")))
print("== /api/fs/places: the browser's sidebar ==")
rows = fs_places()
check("there is always somewhere to go", len(rows) > 0)
# A greyed-out Music folder on a machine that has none reads as breakage; its
# absence reads as an accurate description of the machine.
check("every place exists and is a directory",
all(Path(r.path).is_dir() for r in rows),
[r.path for r in rows if not Path(r.path).is_dir()])
check("home is always offered", any(r.kind == "home" for r in rows))
check("no duplicate paths", len({r.path for r in rows}) == len(rows))
check("nothing is unnamed", all(r.name for r in rows))
# macOS lists the startup disk in /Volumes next to real removable media, so a
# Drives list that does not filter it leads with a path back to where you are.
# Compared by DEVICE, because "Macintosh HD" is only the default name.
check("the boot volume is not offered as a drive",
not any(places.is_boot_volume(Path(r.path)) for r in rows if r.kind == "volume"),
[r.path for r in rows if r.kind == "volume" and places.is_boot_volume(Path(r.path))])
lib_places = lambda plat: [r for r in fs_places(plat) if r.kind == "library"] # noqa: E731
check("no library shortcut without a platform", lib_places(None) == [])
for plat in ("traktor", "rekordbox"):
found = registry.detect_for(plat)
expected = {str(Path(c["path"]).parent) for c in found}
got = {r.path for r in lib_places(plat)}
# The shortcut is the folder CONTAINING the library: a place is somewhere
# you navigate to, not something you pick.
check(f"{plat}: shortcut points at the containing folder", got <= expected, f"{got} vs {expected}")
if found:
check(f"{plat}: the shortcut is offered", len(got) > 0)
# A removable platform's libraries ARE the drives, which the Drives group
# already lists — a second row for the same place would just be noise.
check("no library shortcut for a removable platform", lib_places("onelibrary") == [])
check("an unknown platform does not raise", isinstance(fs_places("nonesuch"), list))
print("== the mount scanner is shared, not duplicated ==")
# It grew inside the OneLibrary adapter, because that is the platform whose
# libraries are drives. "Where does this OS mount things" is not adapter
# knowledge, though, and two scanners would drift.
import konduktor.adapters.onelibrary.discovery as onelib_discovery # noqa: E402
check("the adapter uses core's scanner, not its own",
onelib_discovery._mount_points is places.mount_points)
check("volumes() drops the boot volume, mount_points() does not",
set(places.volumes()) <= set(places.mount_points()))
print("== a library may be a DIRECTORY, not just a file ==") print("== a library may be a DIRECTORY, not just a file ==")
drives = registry.detect_for("onelibrary") drives = registry.detect_for("onelibrary")
if drives: if drives:
+9
View File
@@ -324,6 +324,13 @@ export interface SourceStatus {
playlists: number | null playlists: number | null
} }
export interface FsPlace {
/** Groups the row and picks its icon. Never a finished sentence. */
kind: 'home' | 'music' | 'desktop' | 'documents' | 'downloads' | 'volume' | 'library'
name: string
path: string
}
export interface FsEntry { export interface FsEntry {
name: string name: string
path: string path: string
@@ -432,6 +439,8 @@ export const api = {
getJSON<CollectionOptions>(`/api/library/options${qs({ platform })}`), getJSON<CollectionOptions>(`/api/library/options${qs({ platform })}`),
listDir: (path?: string, platform?: string) => listDir: (path?: string, platform?: string) =>
getJSON<FsListing>(`/api/fs/list${qs({ path, platform })}`), getJSON<FsListing>(`/api/fs/list${qs({ path, platform })}`),
// Re-asked rather than cached: drives come and go while a dialog is open.
places: (platform?: string) => getJSON<FsPlace[]>(`/api/fs/places${qs({ platform })}`),
// ---- path remapping (per-collection OS-path prefix translation) ---- // ---- path remapping (per-collection OS-path prefix translation) ----
getPathMapping: () => getJSON<PathMapping>('/api/library/path-mapping'), getPathMapping: () => getJSON<PathMapping>('/api/library/path-mapping'),
+31 -82
View File
@@ -1,6 +1,7 @@
import { useState } from 'react' import { useState } from 'react'
import { useMutation, useQuery } from '@tanstack/react-query' import { useMutation, useQuery } from '@tanstack/react-query'
import { api, type CollectionCandidate, type CollectionStatus, type PlatformOption } from '../api' import { api, type CollectionCandidate, type CollectionStatus, type PlatformOption } from '../api'
import { FileBrowser, useFsListing } from './FileBrowser'
import { browsePrompt, platformAvailability } from '../lib/platformCopy' import { browsePrompt, platformAvailability } from '../lib/platformCopy'
/** /**
@@ -79,18 +80,15 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
enabled: !!platform, enabled: !!platform,
}) })
const listing = useQuery({ // Shares FileBrowser's query, so the confirm row below cannot disagree with
queryKey: ['fs', dir ?? '~', platform?.platform], // what is on screen about where the user is standing.
queryFn: () => api.listDir(dir, platform?.platform), const here = useFsListing(dir, platform?.platform).data?.path ?? ''
enabled: step === 'browse',
})
const open = useMutation({ const open = useMutation({
mutationFn: (path: string) => api.openCollection(path), mutationFn: (path: string) => api.openCollection(path),
onSuccess: (status) => onOpened(status), onSuccess: (status) => onOpened(status),
}) })
const data = listing.data
const opt = options.data const opt = options.data
const auto = opt?.auto ?? null const auto = opt?.auto ?? null
const recent = opt?.recent ?? null const recent = opt?.recent ?? null
@@ -257,82 +255,33 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
) : ( ) : (
/* ---- Step 3: browse for it ---- */ /* ---- Step 3: browse for it ---- */
<> <>
{/* Path bar */} <FileBrowser
<div className="flex items-center gap-2 border-b border-line bg-ink-850 px-4 py-2"> mode={picksDirectory ? 'directory' : 'file'}
<button platform={platform!.platform}
title="Home" path={dir}
onClick={() => setDir(data?.home)} onNavigate={setDir}
className="rounded px-2 py-1 text-sm text-muted hover:bg-ink-800 hover:text-text" onPickFile={(p) => open.mutate(p)}
> footer={
⌂ /* Confirm-the-folder bar, for a platform whose library IS a
</button> folder. There is nothing in the listing to click, so the
<button target is the place you have navigated to. */
title="Up one level" picksDirectory ? (
disabled={!data?.parent} <div className="flex items-center gap-2 border-t border-line px-4 py-2">
onClick={() => data?.parent && setDir(data.parent)} <span className="min-w-0 flex-1 truncate text-xs text-faint">
className="rounded px-2 py-1 text-sm text-muted hover:bg-ink-800 hover:text-text disabled:cursor-not-allowed disabled:opacity-40" Open <span className="font-mono text-muted">{here || '…'}</span> as a{' '}
> {platform!.name} library
↑ </span>
</button> <button
<span className="truncate font-mono text-xs text-faint" dir="rtl"> disabled={!here || open.isPending}
{data?.path ?? 'Loading…'} onClick={() => here && open.mutate(here)}
</span> className="shrink-0 rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-40"
</div> >
{open.isPending ? 'Opening…' : 'Open this folder'}
{/* Listing. Files are filtered server-side to this platform's own, </button>
so a Traktor browse never offers a master.db it cannot open — and </div>
a drive-selecting platform gets no files at all. */} ) : null
<div className="min-h-0 flex-1 overflow-y-auto p-2"> }
{listing.isLoading && <div className="p-4 text-sm text-faint">Loading…</div>} />
{data && data.dirs.length === 0 && data.files.length === 0 && (
<div className="p-4 text-sm text-faint">
{picksDirectory ? 'No folders here.' : 'Nothing openable here.'}
</div>
)}
{data?.dirs.map((d) => (
<button
key={d.path}
onClick={() => setDir(d.path)}
className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm text-muted hover:bg-ink-800 hover:text-text"
>
<span className="text-faint">📁</span>
<span className="truncate">{d.name}</span>
</button>
))}
{data?.files.map((f) => (
<button
key={f.path}
onClick={() => open.mutate(f.path)}
disabled={open.isPending}
className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm text-text hover:bg-accent-soft"
>
<span className="text-accent">♫</span>
<span className="truncate">{f.name}</span>
<span className="ml-auto text-[10px] uppercase tracking-wider text-faint">
open
</span>
</button>
))}
</div>
{/* Confirm-the-folder bar, for a platform whose library IS a folder.
There is nothing in the listing to click, so the target is the
place you have navigated to. */}
{picksDirectory && (
<div className="flex items-center gap-2 border-t border-line px-4 py-2">
<span className="min-w-0 flex-1 truncate text-xs text-faint">
Open <span className="font-mono text-muted">{data?.path ?? '…'}</span> as a{' '}
{platform!.name} library
</span>
<button
disabled={!data?.path || open.isPending}
onClick={() => data?.path && open.mutate(data.path)}
className="shrink-0 rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-40"
>
{open.isPending ? 'Opening…' : 'Open this folder'}
</button>
</div>
)}
{/* Manual path + errors */} {/* Manual path + errors */}
<div className="border-t border-line px-4 py-3"> <div className="border-t border-line px-4 py-3">
+179
View File
@@ -0,0 +1,179 @@
import type { ReactNode } from 'react'
import { useQuery } from '@tanstack/react-query'
import { api, type FsListing, type FsPlace } from '../api'
/**
* The one file browser. A places rail, a path bar, a listing.
*
* Deliberately NOT the surrounding chrome. Its two callers frame it very
* differently — the collection picker shows it as a step inside an existing
* full-screen card, the folder picker as a modal stacked on the import dialog —
* and a shared wrapper would put a modal inside a modal. So each caller keeps
* its own frame and passes its own confirm affordance as `footer`.
*
* `path` is controlled for the same reason: the caller has to know where you
* are standing to label that footer ("Open this folder", "Use this folder"), so
* the current directory belongs to the caller and not to this component.
*/
/**
* The listing, keyed once.
*
* Exported because a caller needs the RESOLVED path — the server turns
* `undefined` into home — and reading it through the same query is honest
* sharing: TanStack dedupes the request, and there is exactly one definition of
* the cache key. Passing it back up through a callback would mean an effect
* firing on every navigation to tell the parent what it already asked for.
*/
export function useFsListing(path: string | undefined, platform?: string) {
return useQuery({
queryKey: ['fs', path ?? '~', platform ?? null],
queryFn: () => api.listDir(path, platform),
})
}
// Volumes come and go while a dialog is open, so the rail polls. Slower than
// the sidebar's device poll: this is a shortcut list, not the thing you came for.
const PLACES_POLL_MS = 5000
const ICONS: Record<FsPlace['kind'], string> = {
home: '⌂',
music: '♫',
desktop: '🖥',
documents: '🗎',
downloads: '⬇',
volume: '⬒',
library: '◈',
}
interface Props {
/** Whether files are listed at all. `directory` shows folders only. */
mode: 'file' | 'directory'
/** Narrows which files are openable, and adds that platform's own location. */
platform?: string
/** Current directory; `undefined` means "wherever the server calls home". */
path: string | undefined
onNavigate: (path: string) => void
/** Called when a listed FILE is chosen. Unused in `directory` mode. */
onPickFile?: (path: string) => void
/** The caller's confirm row, pinned under the listing. */
footer?: ReactNode
}
export function FileBrowser({ mode, platform, path, onNavigate, onPickFile, footer }: Props) {
const listing = useFsListing(path, platform)
const places = useQuery({
queryKey: ['fs-places', platform ?? null],
queryFn: () => api.places(platform),
refetchInterval: PLACES_POLL_MS,
})
const data: FsListing | undefined = listing.data
const here = data?.path ?? ''
const rows = places.data ?? []
// Volatile section LAST: a drive appearing or vanishing must not shift the
// rows above it under a cursor that is already moving towards one.
const groups: { label: string; rows: FsPlace[] }[] = [
{ label: 'Places', rows: rows.filter((p) => p.kind !== 'volume' && p.kind !== 'library') },
{ label: 'Library', rows: rows.filter((p) => p.kind === 'library') },
{ label: 'Drives', rows: rows.filter((p) => p.kind === 'volume') },
].filter((g) => g.rows.length > 0)
return (
<div className="flex min-h-0 flex-1">
{/* ---- Places rail. Navigates, never selects: one click here must not be
able to open a library or commit an import destination, because a
sidebar does not look like something that does that. ---- */}
<div className="w-44 shrink-0 overflow-y-auto border-r border-line bg-ink-950/40 py-2">
{groups.map((g) => (
<div key={g.label} className="mb-2">
<div className="px-3 pb-1 text-[10px] font-semibold uppercase tracking-wider text-faint">
{g.label}
</div>
{g.rows.map((p) => {
const active = here === p.path
return (
<button
key={p.path}
onClick={() => onNavigate(p.path)}
title={p.path}
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors ${
active
? 'bg-accent-soft text-text'
: 'text-muted hover:bg-ink-800 hover:text-text'
}`}
>
<span className="w-3 shrink-0 text-center text-faint">{ICONS[p.kind]}</span>
<span className="truncate">{p.name}</span>
</button>
)
})}
</div>
))}
</div>
{/* ---- Path bar + listing ---- */}
<div className="flex min-w-0 flex-1 flex-col">
<div className="flex items-center gap-2 border-b border-line bg-ink-850 px-4 py-2">
<button
title="Home"
onClick={() => data?.home && onNavigate(data.home)}
className="rounded px-2 py-1 text-sm text-muted hover:bg-ink-800 hover:text-text"
>
⌂
</button>
<button
title="Up one level"
disabled={!data?.parent}
onClick={() => data?.parent && onNavigate(data.parent)}
className="rounded px-2 py-1 text-sm text-muted hover:bg-ink-800 hover:text-text disabled:cursor-not-allowed disabled:opacity-40"
>
↑
</button>
<span className="truncate font-mono text-xs text-faint" dir="rtl">
{here || 'Loading…'}
</span>
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-2">
{listing.isLoading && <div className="p-4 text-sm text-faint">Loading…</div>}
{data && data.dirs.length === 0 && data.files.length === 0 && (
<div className="p-4 text-sm text-faint">
{mode === 'directory' ? 'No folders here.' : 'Nothing openable here.'}
</div>
)}
{data?.dirs.map((d) => (
<button
key={d.path}
onClick={() => onNavigate(d.path)}
className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm text-muted hover:bg-ink-800 hover:text-text"
>
<span className="text-faint">📁</span>
<span className="truncate">{d.name}</span>
</button>
))}
{/* The server already filtered these to the chosen platform's own, so
a Traktor browse never offers a master.db it cannot open — and a
directory-selecting platform is sent no files at all. */}
{mode === 'file' &&
data?.files.map((f) => (
<button
key={f.path}
onClick={() => onPickFile?.(f.path)}
className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm text-text hover:bg-accent-soft"
>
<span className="text-accent">♫</span>
<span className="truncate">{f.name}</span>
<span className="ml-auto text-[10px] uppercase tracking-wider text-faint">
open
</span>
</button>
))}
</div>
{footer}
</div>
</div>
)
}
+43 -80
View File
@@ -1,19 +1,13 @@
import { useState } from 'react' import { useState } from 'react'
import { useQuery } from '@tanstack/react-query' import { FileBrowser, useFsListing } from './FileBrowser'
import { api } from '../api'
/** /**
* Pick a FOLDER, by browsing. * Pick a FOLDER, by browsing.
* *
* `/api/fs/list` already returns both directories and openable library files — * The browsing itself is `FileBrowser` — the same one the collection picker
* it was built for the collection picker — so this reuses it and simply ignores * uses. All this adds is the modal frame and the confirm row, which is the part
* the files. A folder browser that listed `.nml` files would be offering * that genuinely differs: here you are choosing somewhere to PUT files, so the
* something that cannot be chosen. * target can be a folder that does not exist yet.
*
* Navigating into a folder also SELECTS it. There is no separate "choose"
* click, because the thing being picked is the place you are standing: a picker
* that made you navigate in and then confirm would read as two decisions when
* there is one.
*/ */
interface Props { interface Props {
@@ -26,92 +20,61 @@ export function FolderPicker({ value, onChange, onClose }: Props) {
// `undefined` means "wherever the server thinks home is" — the picker does not // `undefined` means "wherever the server thinks home is" — the picker does not
// need to know that path to open on it. // need to know that path to open on it.
const [dir, setDir] = useState<string | undefined>(value || undefined) const [dir, setDir] = useState<string | undefined>(value || undefined)
const listing = useQuery({
queryKey: ['fs', dir ?? 'home'],
queryFn: () => api.listDir(dir),
})
const data = listing.data
const [newFolder, setNewFolder] = useState('') const [newFolder, setNewFolder] = useState('')
// Shares FileBrowser's query, so "where am I" cannot disagree with what is
// on screen — and the confirm row below needs it to name its target.
const here = useFsListing(dir).data?.path ?? ''
const here = data?.path ?? '' const confirm = () => {
onChange(newFolder.trim() ? `${here}/${newFolder.trim()}` : here)
onClose()
}
return ( return (
<div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 p-4"> <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 p-4">
<div className="flex h-[70vh] w-full max-w-lg flex-col rounded-lg border border-line bg-ink-900 shadow-xl"> <div className="flex h-[70vh] w-full max-w-2xl flex-col overflow-hidden rounded-lg border border-line bg-ink-900 shadow-xl">
<div className="border-b border-line px-5 py-3"> <div className="border-b border-line px-5 py-3">
<h2 className="text-sm font-semibold text-text">Choose a folder</h2> <h2 className="text-sm font-semibold text-text">Choose a folder</h2>
</div> </div>
<div className="flex items-center gap-2 border-b border-line bg-ink-850 px-4 py-2"> <FileBrowser
<button mode="directory"
title="Home" path={dir}
onClick={() => setDir(data?.home)} onNavigate={setDir}
className="rounded px-2 py-1 text-sm text-muted hover:bg-ink-800 hover:text-text" footer={
> /* A folder that does not exist yet is a normal thing to want — the
⌂ import creates it, so it only has to be named, not made here. */
</button> <div className="flex items-center gap-2 border-t border-line px-4 py-2">
<button <span className="shrink-0 text-xs text-faint">New folder</span>
title="Up one level" <input
disabled={!data?.parent} value={newFolder}
onClick={() => data?.parent && setDir(data.parent)} placeholder="name…"
className="rounded px-2 py-1 text-sm text-muted hover:bg-ink-800 hover:text-text disabled:cursor-not-allowed disabled:opacity-40" onChange={(e) => setNewFolder(e.target.value)}
> onKeyDown={(e) => {
↑ if (e.key === 'Enter' && newFolder.trim() && here) confirm()
</button> }}
<span className="truncate font-mono text-xs text-faint" dir="rtl"> className="min-w-0 flex-1 rounded-md border border-line bg-ink-950 px-2 py-1 text-xs text-text outline-none focus:border-accent"
{here || 'Loading…'} />
</div>
}
/>
<div className="flex items-center gap-2 border-t border-line px-5 py-3">
{/* Always show where the files will actually land, so the effect of
typing a new-folder name never has to be inferred. */}
<span className="min-w-0 flex-1 truncate font-mono text-[11px] text-faint" dir="rtl">
{here ? (newFolder.trim() ? `${here}/${newFolder.trim()}` : here) : ''}
</span> </span>
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-2">
{listing.isLoading && <div className="p-4 text-sm text-faint">Loading…</div>}
{data && data.dirs.length === 0 && (
<div className="p-4 text-sm text-faint">No folders here.</div>
)}
{data?.dirs.map((d) => (
<button
key={d.path}
onClick={() => setDir(d.path)}
className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm text-muted hover:bg-ink-800 hover:text-text"
>
<span className="text-faint">📁</span>
<span className="truncate">{d.name}</span>
</button>
))}
</div>
{/* A folder that does not exist yet is a normal thing to want — the
import creates it, so it only has to be named, not made here. */}
<div className="flex items-center gap-2 border-t border-line px-4 py-2">
<span className="text-xs text-faint">New folder</span>
<input
value={newFolder}
placeholder="name…"
onChange={(e) => setNewFolder(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && newFolder.trim() && here) {
onChange(`${here}/${newFolder.trim()}`)
onClose()
}
}}
className="min-w-0 flex-1 rounded-md border border-line bg-ink-950 px-2 py-1 text-xs text-text outline-none focus:border-accent"
/>
</div>
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
<button <button
onClick={onClose} onClick={onClose}
className="rounded-md border border-line px-3 py-1.5 text-sm text-muted hover:text-text" className="shrink-0 rounded-md border border-line px-3 py-1.5 text-sm text-muted hover:text-text"
> >
Cancel Cancel
</button> </button>
<button <button
disabled={!here} disabled={!here}
onClick={() => { onClick={confirm}
onChange(newFolder.trim() ? `${here}/${newFolder.trim()}` : here) className="shrink-0 rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110 disabled:opacity-40"
onClose()
}}
className="rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110 disabled:opacity-40"
> >
Use this folder Use this folder
</button> </button>