From 93ec2ef42540b8158a6b2f7176c8db7fb600b924 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Wed, 23 Sep 2026 11:19:58 +0200 Subject: [PATCH] Improved file browser --- CLAUDE.md | 34 +++- .../adapters/onelibrary/discovery.py | 40 +--- backend/konduktor/core/places.py | 142 ++++++++++++++ backend/konduktor/main.py | 43 ++++- backend/konduktor/schemas.py | 13 ++ backend/test_picker.py | 48 ++++- frontend/src/api.ts | 9 + frontend/src/components/CollectionPicker.tsx | 113 +++-------- frontend/src/components/FileBrowser.tsx | 179 ++++++++++++++++++ frontend/src/components/FolderPicker.tsx | 123 +++++------- 10 files changed, 540 insertions(+), 204 deletions(-) create mode 100644 backend/konduktor/core/places.py create mode 100644 frontend/src/components/FileBrowser.tsx diff --git a/CLAUDE.md b/CLAUDE.md index 69cc0f3..344aeeb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -47,6 +47,16 @@ Two independent apps that talk over HTTP: - `registry.py` — adapter selection by **`can_open()` probe**, not extension (Rekordbox is a `.db`, Serato is a directory). - `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. - `store.py` (`TraktorStore`) — the retained native model: owns the parsed 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 platform's detections + its own last-opened) and `/api/fs/list` (that 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 OneLibrary library is a drive. `prefs` keeps last-opened **per platform**: 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 "Close Traktor before saving — it overwrites collection.nml on exit" stays 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 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 @@ -353,7 +380,8 @@ serialization path.** It enforces: 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. 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 the user's last-opened library. - `test_layering.py` — `core/` imports nothing platform-specific, and no adapter diff --git a/backend/konduktor/adapters/onelibrary/discovery.py b/backend/konduktor/adapters/onelibrary/discovery.py index 86ee0b2..b5a3b62 100644 --- a/backend/konduktor/adapters/onelibrary/discovery.py +++ b/backend/konduktor/adapters/onelibrary/discovery.py @@ -14,49 +14,17 @@ app feel broken. from __future__ import annotations import logging -import os -import string -import sys 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 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: """A candidate record for a drive or database path, shaped for the picker.""" path = Path(path) diff --git a/backend/konduktor/core/places.py b/backend/konduktor/core/places.py new file mode 100644 index 0000000..180154d --- /dev/null +++ b/backend/konduktor/core/places.py @@ -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 diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 13c06cc..e0c75ac 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -17,7 +17,7 @@ from . import __version__, history, prefs from .app_state import STATE from .core import auto_hotcues as ah from . import importer -from .core import registry +from .core import places, registry from .core.adapter import ( AdapterError, InvalidCommand, @@ -45,6 +45,7 @@ from .schemas import ( FileTagOutcome, FsEntry, FsListing, + FsPlace, AddGridMarker, GridMarkerEdit, ReplaceGrid, @@ -245,6 +246,46 @@ def patch_prefs(patch: dict) -> dict: 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) def fs_list(path: str | None = None, platform: str | None = None) -> FsListing: """List directories and openable library files for the in-app file browser. diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 8c31f6a..0f1ad57 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -135,6 +135,19 @@ class CollectionOptions(BaseModel): 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): name: str path: str diff --git a/backend/test_picker.py b/backend/test_picker.py index e506f0d..dd520fb 100644 --- a/backend/test_picker.py +++ b/backend/test_picker.py @@ -23,8 +23,8 @@ _TMP = tempfile.TemporaryDirectory() prefs._PREFS_PATH = Path(_TMP.name) / "userprefs.json" prefs._LEGACY_PREFS_PATH = Path(_TMP.name) / "absent.json" -from konduktor.core import registry # noqa: E402 -from konduktor.main import collection_options, fs_list, platforms # noqa: E402 +from konduktor.core import places, registry # noqa: E402 +from konduktor.main import collection_options, fs_list, fs_places, platforms # noqa: E402 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"} 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 ==") drives = registry.detect_for("onelibrary") if drives: diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 22340b5..5c65a1d 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -324,6 +324,13 @@ export interface SourceStatus { 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 { name: string path: string @@ -432,6 +439,8 @@ export const api = { getJSON(`/api/library/options${qs({ platform })}`), listDir: (path?: string, platform?: string) => getJSON(`/api/fs/list${qs({ path, platform })}`), + // Re-asked rather than cached: drives come and go while a dialog is open. + places: (platform?: string) => getJSON(`/api/fs/places${qs({ platform })}`), // ---- path remapping (per-collection OS-path prefix translation) ---- getPathMapping: () => getJSON('/api/library/path-mapping'), diff --git a/frontend/src/components/CollectionPicker.tsx b/frontend/src/components/CollectionPicker.tsx index 718edb3..2c55b5d 100644 --- a/frontend/src/components/CollectionPicker.tsx +++ b/frontend/src/components/CollectionPicker.tsx @@ -1,6 +1,7 @@ import { useState } from 'react' import { useMutation, useQuery } from '@tanstack/react-query' import { api, type CollectionCandidate, type CollectionStatus, type PlatformOption } from '../api' +import { FileBrowser, useFsListing } from './FileBrowser' import { browsePrompt, platformAvailability } from '../lib/platformCopy' /** @@ -79,18 +80,15 @@ export function CollectionPicker({ onOpened, onCancel }: Props) { enabled: !!platform, }) - const listing = useQuery({ - queryKey: ['fs', dir ?? '~', platform?.platform], - queryFn: () => api.listDir(dir, platform?.platform), - enabled: step === 'browse', - }) + // Shares FileBrowser's query, so the confirm row below cannot disagree with + // what is on screen about where the user is standing. + const here = useFsListing(dir, platform?.platform).data?.path ?? '' const open = useMutation({ mutationFn: (path: string) => api.openCollection(path), onSuccess: (status) => onOpened(status), }) - const data = listing.data const opt = options.data const auto = opt?.auto ?? null const recent = opt?.recent ?? null @@ -257,82 +255,33 @@ export function CollectionPicker({ onOpened, onCancel }: Props) { ) : ( /* ---- Step 3: browse for it ---- */ <> - {/* Path bar */} -
- - - - {data?.path ?? 'Loading…'} - -
- - {/* Listing. Files are filtered server-side to this platform's own, - so a Traktor browse never offers a master.db it cannot open — and - a drive-selecting platform gets no files at all. */} -
- {listing.isLoading &&
Loading…
} - {data && data.dirs.length === 0 && data.files.length === 0 && ( -
- {picksDirectory ? 'No folders here.' : 'Nothing openable here.'} -
- )} - {data?.dirs.map((d) => ( - - ))} - {data?.files.map((f) => ( - - ))} -
- - {/* 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 && ( -
- - Open {data?.path ?? '…'} as a{' '} - {platform!.name} library - - -
- )} + open.mutate(p)} + footer={ + /* 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 ? ( +
+ + Open {here || '…'} as a{' '} + {platform!.name} library + + +
+ ) : null + } + /> {/* Manual path + errors */}
diff --git a/frontend/src/components/FileBrowser.tsx b/frontend/src/components/FileBrowser.tsx new file mode 100644 index 0000000..d348d70 --- /dev/null +++ b/frontend/src/components/FileBrowser.tsx @@ -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 = { + 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 ( +
+ {/* ---- 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. ---- */} +
+ {groups.map((g) => ( +
+
+ {g.label} +
+ {g.rows.map((p) => { + const active = here === p.path + return ( + + ) + })} +
+ ))} +
+ + {/* ---- Path bar + listing ---- */} +
+
+ + + + {here || 'Loading…'} + +
+ +
+ {listing.isLoading &&
Loading…
} + {data && data.dirs.length === 0 && data.files.length === 0 && ( +
+ {mode === 'directory' ? 'No folders here.' : 'Nothing openable here.'} +
+ )} + {data?.dirs.map((d) => ( + + ))} + {/* 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) => ( + + ))} +
+ + {footer} +
+
+ ) +} diff --git a/frontend/src/components/FolderPicker.tsx b/frontend/src/components/FolderPicker.tsx index 1d42526..b77f890 100644 --- a/frontend/src/components/FolderPicker.tsx +++ b/frontend/src/components/FolderPicker.tsx @@ -1,19 +1,13 @@ import { useState } from 'react' -import { useQuery } from '@tanstack/react-query' -import { api } from '../api' +import { FileBrowser, useFsListing } from './FileBrowser' /** * Pick a FOLDER, by browsing. * - * `/api/fs/list` already returns both directories and openable library files — - * it was built for the collection picker — so this reuses it and simply ignores - * the files. A folder browser that listed `.nml` files would be offering - * something that cannot be chosen. - * - * 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. + * The browsing itself is `FileBrowser` — the same one the collection picker + * uses. All this adds is the modal frame and the confirm row, which is the part + * that genuinely differs: here you are choosing somewhere to PUT files, so the + * target can be a folder that does not exist yet. */ 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 // need to know that path to open on it. const [dir, setDir] = useState(value || undefined) - const listing = useQuery({ - queryKey: ['fs', dir ?? 'home'], - queryFn: () => api.listDir(dir), - }) - const data = listing.data 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 (
-
+

Choose a folder

-
- - - - {here || 'Loading…'} + + New folder + setNewFolder(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' && newFolder.trim() && here) confirm() + }} + 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" + /> +
+ } + /> + +
+ {/* Always show where the files will actually land, so the effect of + typing a new-folder name never has to be inferred. */} + + {here ? (newFolder.trim() ? `${here}/${newFolder.trim()}` : here) : ''} -
- -
- {listing.isLoading &&
Loading…
} - {data && data.dirs.length === 0 && ( -
No folders here.
- )} - {data?.dirs.map((d) => ( - - ))} -
- - {/* 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. */} -
- New folder - 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" - /> -
- -