mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Improved library selection flow
This commit is contained in:
1 parent
a081a7a44d
commit
8d11acd783
17 files changed
+609
-71
No files matched your search
@@ -168,7 +168,8 @@ Two independent apps that talk over HTTP:
|
||||
History is app-level: the adapter returns the bytes it wrote plus a summary,
|
||||
and `AppState.save()` versions them. Every write path must go through it.
|
||||
- `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data
|
||||
dir). Last-opened collection, library column layout, prep-deck zoom. Best-effort.
|
||||
dir). Last-opened collection (global AND per-platform), library column
|
||||
layout, prep-deck zoom, import destination. Best-effort.
|
||||
- `schemas.py` — HTTP request bodies + envelopes; re-exports `core.model`.
|
||||
- `main.py` — thin FastAPI routes (all under `/api`), talking only to the
|
||||
adapter. Starts **unloaded**; the library is chosen at runtime via
|
||||
@@ -176,6 +177,17 @@ Two independent apps that talk over HTTP:
|
||||
`GET /api/capabilities` feeds the UI's gating; `GET /api/fs/list` powers the
|
||||
file browser; `GET`/`PATCH /api/prefs` persist UI prefs. Setting
|
||||
`KONDUKTOR_NML` auto-loads on startup (dev/tests).
|
||||
The picker's three routes are all **scoped by `?platform=`**, because it
|
||||
asks which platform first: `/api/platforms` (the pre-load equivalent of
|
||||
capabilities — reports `selects`, `removable` and `found`, sorted so a menu
|
||||
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
|
||||
`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
|
||||
offer that cannot be taken.
|
||||
- **`frontend/`** — React + TypeScript + Vite. A dark, virtualized track
|
||||
explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx).
|
||||
- `api.ts` — typed client + all API types. **Generic, not Traktor-shaped**:
|
||||
@@ -192,8 +204,21 @@ 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` (startup chooser: Automatic / Open last /
|
||||
Find manually — the last reveals a file browser), `Sidebar` (playlist tree +
|
||||
- `components/` — `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
|
||||
it by adapter registration order, so a plugged-in stick could be opened as
|
||||
the user's collection. Scoping removes that by construction rather than by
|
||||
ranking candidates better. Nothing is remembered between launches — the
|
||||
platform list is where every session starts. `selects` decides whether the
|
||||
browser offers files or a folder to confirm, because a library is a file on
|
||||
some platforms and a DIRECTORY on others), `Sidebar` (a header naming the
|
||||
open library, which is also the only way to switch to another one — the
|
||||
picker used to be a one-way door with `forcePicker` never set, so changing
|
||||
library meant restarting; switching confirms first when there are unsaved
|
||||
edits, since the adapter holds them in a native model that opening another
|
||||
library replaces — plus the playlist tree +
|
||||
create/rename/delete), `SaveBar`, `Toolbar` (search/filters + `ColumnsMenu`),
|
||||
`TrackTable` (All Tracks — TanStack Table + **virtualized** grid; per-row play
|
||||
button, configurable columns, inline double-click editing) and `PlaylistTable`
|
||||
@@ -323,6 +348,14 @@ serialization path.** It enforces:
|
||||
companion cue is invented), that the existing 8,485 entries render
|
||||
byte-identically, that the job registry runs/fails/cancels, and that a
|
||||
cancelled import leaves **no orphaned audio and an untouched collection**.
|
||||
- `test_picker.py` — the picker's routes. Pins the scoping, because the bug it
|
||||
replaced was invisible: `/api/library/options` flattened every driver's
|
||||
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
|
||||
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
|
||||
imports another platform's library (checked on real imports via AST, so merely
|
||||
naming a platform in a comment is fine). Rekordbox and OneLibrary deliberately
|
||||
|
||||
@@ -21,6 +21,11 @@ class OneLibraryDriver:
|
||||
removable = True
|
||||
suffixes = (".db",)
|
||||
library_label = "exportLibrary.db"
|
||||
# What a user PICKS is the mount point, not the database buried three levels
|
||||
# down inside it — `DriveLayout.locate()` accepts either, but only one of
|
||||
# them is a thing anybody browses to. The file browser reads this to offer
|
||||
# folders rather than files.
|
||||
selects = "directory"
|
||||
|
||||
def can_open(self, path: Path) -> bool:
|
||||
"""Recognise a OneLibrary drive, by layout and then by schema.
|
||||
@@ -77,6 +82,17 @@ class OneLibraryDriver:
|
||||
def describe(self, path: Path) -> dict:
|
||||
return discovery.describe(path)
|
||||
|
||||
def display_name_for(self, path: Path) -> str:
|
||||
"""What to call this library on screen: the DRIVE's name.
|
||||
|
||||
The filename is not a stable answer here. A OneLibrary library can be
|
||||
opened by its mount point OR by the database three levels inside it —
|
||||
`DriveLayout.locate()` accepts both on purpose — so the same stick would
|
||||
be "Hardy" opened one way and "exportLibrary.db" opened the other.
|
||||
"""
|
||||
layout = DriveLayout.locate(Path(path))
|
||||
return layout.root.name if layout is not None else Path(path).name
|
||||
|
||||
def restore(self, path: Path, data: bytes) -> None:
|
||||
"""Not supported: a drive is a database plus analysis files plus audio.
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ class RekordboxDriver:
|
||||
display_name = "Rekordbox"
|
||||
suffixes = (".db",)
|
||||
library_label = "master.db"
|
||||
selects = "file"
|
||||
|
||||
def can_open(self, path: Path) -> bool:
|
||||
"""Recognise an encrypted Rekordbox database.
|
||||
|
||||
@@ -12,6 +12,7 @@ class TraktorDriver:
|
||||
display_name = "Traktor"
|
||||
suffixes = (".nml",)
|
||||
library_label = "collection.nml"
|
||||
selects = "file"
|
||||
|
||||
def can_open(self, path: Path) -> bool:
|
||||
"""Recognise an NML without parsing 14 MB of it."""
|
||||
|
||||
@@ -192,8 +192,19 @@ class LibraryDriver(Protocol):
|
||||
# can offer them as import SOURCES. Optional, and False for a platform that
|
||||
# does not set it, because most keep one library in a known place.
|
||||
removable: bool
|
||||
# Whether a user picks a FILE or a DIRECTORY for this platform. Both exist:
|
||||
# Traktor's library is `collection.nml`, OneLibrary's is the drive, and
|
||||
# Serato's will be a `_Serato_` folder. The file browser and the open route
|
||||
# both read this rather than assuming everything is a file. Defaults to
|
||||
# "file" for a driver that does not set it.
|
||||
selects: str
|
||||
|
||||
def can_open(self, path: Path) -> bool: ...
|
||||
def open(self, path: Path) -> LibraryAdapter: ...
|
||||
# OPTIONAL. What to call an opened library on screen. Only the adapter can
|
||||
# answer for a platform where one library has more than one valid path —
|
||||
# the filename is otherwise assumed, and that assumption is wrong for a
|
||||
# library that is a drive. Omitted means "the path's own name".
|
||||
def display_name_for(self, path: Path) -> str: ...
|
||||
def detect(self) -> list: ...
|
||||
def describe(self, path: Path) -> object: ...
|
||||
@@ -177,13 +177,23 @@ class LibraryInfo(BaseModel):
|
||||
|
||||
|
||||
class PlatformOption(BaseModel):
|
||||
"""A platform the picker can offer before any library is open."""
|
||||
"""A platform the picker can offer before any library is open.
|
||||
|
||||
Facts only, never finished sentences: `lib/platformCopy.ts` composes the
|
||||
wording. The distinction that matters is `removable` — a platform with no
|
||||
library found is "not installed" for Traktor and "nothing plugged in" for
|
||||
OneLibrary, and only the driver knows which of those is true.
|
||||
"""
|
||||
|
||||
platform: str
|
||||
name: str
|
||||
library_label: str
|
||||
selects: Literal["file", "directory"] = "file"
|
||||
installed: bool = False
|
||||
#: How many libraries this platform has right now; `installed` is `found > 0`.
|
||||
found: int = 0
|
||||
#: The library lives on a plugged-in drive, so `found` changes between calls.
|
||||
removable: bool = False
|
||||
|
||||
|
||||
class RemapSample(BaseModel):
|
||||
|
||||
@@ -25,6 +25,14 @@ def drivers() -> list[LibraryDriver]:
|
||||
return list(_DRIVERS)
|
||||
|
||||
|
||||
def driver_by_platform(platform: str) -> LibraryDriver:
|
||||
"""The driver for a platform name, e.g. ``"traktor"``."""
|
||||
for d in _DRIVERS:
|
||||
if d.platform == platform:
|
||||
return d
|
||||
raise LibraryNotSupported(f"No adapter registered for platform {platform!r}")
|
||||
|
||||
|
||||
def driver_for(path: Path) -> LibraryDriver:
|
||||
"""The first registered driver that recognises `path`."""
|
||||
for d in _DRIVERS:
|
||||
@@ -64,6 +72,21 @@ def describe(path: Path) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def detect_for(platform: str) -> list:
|
||||
"""Every library one platform has right now, best first.
|
||||
|
||||
The picker asks which platform FIRST, so detection is scoped to the answer.
|
||||
Unscoped detection (``detect_all``) concatenates drivers in registration
|
||||
order, which made "the best candidate" mean "whatever the first-registered
|
||||
driver found" — with a removable drive registered first, a plugged-in stick
|
||||
could be offered as the user's collection.
|
||||
"""
|
||||
try:
|
||||
return driver_by_platform(platform).detect()
|
||||
except (LibraryNotSupported, OSError):
|
||||
return []
|
||||
|
||||
|
||||
def detect_all() -> list:
|
||||
"""Every library found in the platforms' default install locations."""
|
||||
out: list = []
|
||||
@@ -75,10 +98,21 @@ def detect_all() -> list:
|
||||
return out
|
||||
|
||||
|
||||
def browsable_suffixes() -> tuple[str, ...]:
|
||||
"""File extensions the in-app browser should show, across all platforms."""
|
||||
def browsable_suffixes(platform: str | None = None) -> tuple[str, ...]:
|
||||
"""File extensions the in-app browser should show, for one platform or all.
|
||||
|
||||
A platform that selects a DIRECTORY contributes nothing, even though it has
|
||||
suffixes: its libraries are not the thing a user picks, so listing them
|
||||
would offer a file the browser's Open cannot act on.
|
||||
"""
|
||||
try:
|
||||
targets = [driver_by_platform(platform)] if platform else _DRIVERS
|
||||
except LibraryNotSupported:
|
||||
targets = []
|
||||
seen: list[str] = []
|
||||
for d in _DRIVERS:
|
||||
for d in targets:
|
||||
if getattr(d, "selects", "file") != "file":
|
||||
continue
|
||||
for suffix in d.suffixes:
|
||||
if suffix not in seen:
|
||||
seen.append(suffix)
|
||||
|
||||
+56
-15
@@ -129,29 +129,46 @@ def collection_status() -> CollectionStatus:
|
||||
@app.post("/api/library/open", response_model=CollectionStatus)
|
||||
def open_collection(body: OpenCollection) -> CollectionStatus:
|
||||
path = Path(body.path).expanduser()
|
||||
if not path.exists() or not path.is_file():
|
||||
raise HTTPException(400, f"File not found: {path}")
|
||||
# Deliberately NOT `is_file()`. A library is a file on some platforms and a
|
||||
# DIRECTORY on others — OneLibrary's is the drive, Serato's will be a
|
||||
# `_Serato_` folder — and which shapes are valid is the driver's business.
|
||||
# This checks only that the path is there at all; `can_open()` decides.
|
||||
if not path.exists():
|
||||
raise HTTPException(400, f"Not found: {path}")
|
||||
try:
|
||||
STATE.open(path)
|
||||
except AdapterError as ex:
|
||||
raise HTTPException(400, f"Not a valid collection: {ex}")
|
||||
except Exception as ex: # noqa: BLE001
|
||||
raise HTTPException(400, f"Could not open that collection: {ex}")
|
||||
prefs.set_last_collection(str(path))
|
||||
prefs.set_last_collection(str(path), require_adapter().capabilities().platform)
|
||||
return collection_status()
|
||||
|
||||
|
||||
@app.get("/api/library/options", response_model=CollectionOptions)
|
||||
def collection_options() -> CollectionOptions:
|
||||
"""Startup shortcuts for the picker: the best auto-detected Traktor
|
||||
collection and the last one opened (may no longer exist → exists=False)."""
|
||||
detected = registry.detect_all()
|
||||
auto = CollectionCandidate(**detected[0]) if detected else None
|
||||
def collection_options(platform: str | None = None) -> CollectionOptions:
|
||||
"""Startup shortcuts for the picker, scoped to one platform.
|
||||
|
||||
Scoped because the picker asks which platform first, and both shortcuts are
|
||||
only meaningful inside that answer: unscoped, "auto" meant "whatever the
|
||||
first-registered driver happened to find" — so a plugged-in USB stick could
|
||||
be offered as the user's collection — and "last opened" could name a library
|
||||
of the platform they had just declined.
|
||||
|
||||
`recent` may no longer exist (→ `exists=False`), which the picker shows
|
||||
rather than hides: a library that has moved is worth saying so about.
|
||||
"""
|
||||
detected = registry.detect_for(platform) if platform else registry.detect_all()
|
||||
candidates = [CollectionCandidate(**d) for d in detected]
|
||||
recent = None
|
||||
last = prefs.get_last_collection()
|
||||
last = prefs.get_last_collection(platform)
|
||||
if last:
|
||||
recent = CollectionCandidate(**registry.describe(Path(last)))
|
||||
return CollectionOptions(auto=auto, recent=recent)
|
||||
return CollectionOptions(
|
||||
auto=candidates[0] if candidates else None,
|
||||
detected=candidates,
|
||||
recent=recent,
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/library/path-mapping", response_model=PathMappingInfo)
|
||||
@@ -229,12 +246,19 @@ def patch_prefs(patch: dict) -> dict:
|
||||
|
||||
|
||||
@app.get("/api/fs/list", response_model=FsListing)
|
||||
def fs_list(path: str | None = None) -> FsListing:
|
||||
"""List directories and .nml files for the in-app file browser."""
|
||||
def fs_list(path: str | None = None, platform: str | None = None) -> FsListing:
|
||||
"""List directories and openable library files for the in-app file browser.
|
||||
|
||||
`platform` narrows the files to that platform's own: a Traktor browse that
|
||||
also listed `master.db` would be offering a file the chosen adapter cannot
|
||||
open. A platform whose library is a directory contributes no suffixes at
|
||||
all, so its browse shows folders only.
|
||||
"""
|
||||
base = Path(path).expanduser() if path else Path.home()
|
||||
if not base.exists() or not base.is_dir():
|
||||
base = Path.home()
|
||||
base = base.resolve()
|
||||
suffixes = registry.browsable_suffixes(platform)
|
||||
dirs: list[FsEntry] = []
|
||||
files: list[FsEntry] = []
|
||||
try:
|
||||
@@ -244,7 +268,7 @@ def fs_list(path: str | None = None) -> FsListing:
|
||||
try:
|
||||
if entry.is_dir():
|
||||
dirs.append(FsEntry(name=entry.name, path=str(entry)))
|
||||
elif entry.suffix.lower() in registry.browsable_suffixes():
|
||||
elif entry.suffix.lower() in suffixes:
|
||||
files.append(FsEntry(name=entry.name, path=str(entry)))
|
||||
except OSError:
|
||||
continue
|
||||
@@ -267,12 +291,22 @@ def health() -> dict:
|
||||
def _library_info() -> LibraryInfo:
|
||||
"""Identity of the loaded library, for display and for composing warnings."""
|
||||
caps = require_adapter().capabilities()
|
||||
path = Path(str(STATE.path))
|
||||
# A library's on-screen name is the driver's to give when it cares: a drive
|
||||
# has one library reachable by two valid paths, and the filename would name
|
||||
# it differently depending on which one the user happened to pick.
|
||||
driver = next((d for d in registry.drivers() if d.platform == caps.platform), None)
|
||||
namer = getattr(driver, "display_name_for", None)
|
||||
try:
|
||||
display_name = namer(path) if namer else path.name
|
||||
except OSError:
|
||||
display_name = path.name
|
||||
return LibraryInfo(
|
||||
platform=caps.platform,
|
||||
name=caps.save.app_name,
|
||||
library_label=caps.save.library_label,
|
||||
path=str(STATE.path),
|
||||
display_name=Path(str(STATE.path)).name,
|
||||
display_name=display_name,
|
||||
version=caps.version,
|
||||
)
|
||||
|
||||
@@ -293,10 +327,17 @@ def platforms() -> list[PlatformOption]:
|
||||
platform=d.platform,
|
||||
name=d.display_name,
|
||||
library_label=getattr(d, "library_label", ""),
|
||||
selects="file",
|
||||
selects=getattr(d, "selects", "file"),
|
||||
installed=bool(found),
|
||||
found=len(found),
|
||||
removable=bool(getattr(d, "removable", False)),
|
||||
)
|
||||
)
|
||||
# Registration order is an import-order accident, and this list is a MENU —
|
||||
# it must not reshuffle itself between two launches. Sorted so the platforms
|
||||
# that keep a library in a known place come before the ones that are a
|
||||
# plugged-in drive, which is the real distinction a chooser is making.
|
||||
out.sort(key=lambda o: (o.removable, o.name.lower()))
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -81,12 +81,36 @@ def set_path_mapping(
|
||||
save_prefs(prefs)
|
||||
|
||||
|
||||
def get_last_collection() -> str | None:
|
||||
val = load_prefs().get("last_collection")
|
||||
def get_last_collection(platform: str | None = None) -> str | None:
|
||||
"""The last library opened — overall, or on one platform.
|
||||
|
||||
Per-platform because the picker asks which platform FIRST: offering a
|
||||
Rekordbox ``master.db`` under "Open last" to someone who just chose Traktor
|
||||
is an offer that cannot be taken. A platform with no record returns None
|
||||
rather than falling back to the global one, for the same reason.
|
||||
|
||||
The flat ``last_collection`` stays: it is the global answer, and it is what
|
||||
libraries opened before this existed are recorded in.
|
||||
"""
|
||||
prefs = load_prefs()
|
||||
if platform:
|
||||
by_platform = prefs.get("last_collection_by_platform")
|
||||
if isinstance(by_platform, dict):
|
||||
val = by_platform.get(platform)
|
||||
return val if isinstance(val, str) else None
|
||||
return None
|
||||
val = prefs.get("last_collection")
|
||||
return val if isinstance(val, str) else None
|
||||
|
||||
|
||||
def set_last_collection(path: str) -> None:
|
||||
def set_last_collection(path: str, platform: str | None = None) -> None:
|
||||
"""Record a library as the last opened, globally and for its platform."""
|
||||
prefs = load_prefs()
|
||||
prefs["last_collection"] = path
|
||||
if platform:
|
||||
by_platform = prefs.get("last_collection_by_platform")
|
||||
if not isinstance(by_platform, dict):
|
||||
by_platform = {}
|
||||
by_platform[platform] = path
|
||||
prefs["last_collection_by_platform"] = by_platform
|
||||
save_prefs(prefs)
|
||||
@@ -126,6 +126,12 @@ class CollectionCandidate(BaseModel):
|
||||
|
||||
class CollectionOptions(BaseModel):
|
||||
auto: CollectionCandidate | None = None # best auto-detected (latest version)
|
||||
# EVERY library detected, best first. `auto` is simply the first of these.
|
||||
# Carried in full because one platform can genuinely have several at once —
|
||||
# two Traktor versions installed, or two sticks plugged in — and silently
|
||||
# anointing one of them is how the old single-candidate route could open a
|
||||
# USB drive as the user's collection.
|
||||
detected: list[CollectionCandidate] = []
|
||||
recent: CollectionCandidate | None = None # last opened (from userprefs)
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
|
||||
source .venv/bin/activate
|
||||
|
||||
fail=0
|
||||
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_phase3.py test_history.py; do
|
||||
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_picker.py test_phase3.py test_history.py; do
|
||||
echo "──────────────────────────────────────────"
|
||||
echo "▶ $t"
|
||||
echo "──────────────────────────────────────────"
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
"""The library picker's routes: platform first, then library.
|
||||
|
||||
Worth pinning because the bug this flow replaced was invisible. `/api/library/
|
||||
options` used to flatten every driver's detections and return `[0]`, so "the
|
||||
best candidate" actually meant "whatever the first-registered driver found" —
|
||||
and since adapters register in import order, a plugged-in USB stick could be
|
||||
offered as the user's *collection*. Nothing failed; it just opened the wrong
|
||||
library. The guarantee now is scoping, and scoping is easy to lose again the
|
||||
next time a route grows a shortcut.
|
||||
|
||||
Runs on whatever this machine has: every assertion is about the SHAPE of the
|
||||
answer, so a laptop with no Traktor, no Rekordbox and nothing plugged in still
|
||||
exercises the same rules. Prefs are redirected to a temp file — a test must
|
||||
never rewrite the user's last-opened library.
|
||||
"""
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from konduktor import prefs
|
||||
|
||||
# Redirect prefs BEFORE anything reads them.
|
||||
_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
|
||||
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
opts = platforms()
|
||||
by_name = {p.platform: p for p in opts}
|
||||
|
||||
print("== /api/platforms reports the facts the platform step needs ==")
|
||||
check("every registered driver is offered", len(opts) == len(registry.drivers()),
|
||||
f"{len(opts)} of {len(registry.drivers())}")
|
||||
check("all three platforms present", {"traktor", "rekordbox", "onelibrary"} <= set(by_name))
|
||||
check("selects is per-platform, not assumed",
|
||||
by_name["traktor"].selects == "file"
|
||||
and by_name["rekordbox"].selects == "file"
|
||||
# A OneLibrary library is the DRIVE. Getting this wrong sends the browser
|
||||
# hunting for a file three levels down that nobody would navigate to.
|
||||
and by_name["onelibrary"].selects == "directory",
|
||||
{p: by_name[p].selects for p in by_name})
|
||||
check("only OneLibrary is removable",
|
||||
by_name["onelibrary"].removable
|
||||
and not by_name["traktor"].removable
|
||||
and not by_name["rekordbox"].removable)
|
||||
check("installed agrees with found", all((p.found > 0) == p.installed for p in opts))
|
||||
# The list is a MENU. Registration order is an import-order accident, so sorting
|
||||
# is what stops it reshuffling between two launches.
|
||||
check("ordered fixed-location first, then by name",
|
||||
[p.platform for p in opts] == [p.platform for p in
|
||||
sorted(opts, key=lambda o: (o.removable, o.name.lower()))],
|
||||
[p.platform for p in opts])
|
||||
check("a second call gives the same order", [p.platform for p in platforms()] == [p.platform for p in opts])
|
||||
|
||||
print("== /api/library/options is scoped to ONE platform ==")
|
||||
for plat in ("traktor", "rekordbox", "onelibrary"):
|
||||
o = collection_options(plat)
|
||||
driver = registry.driver_by_platform(plat)
|
||||
own = {c["path"] for c in registry.detect_for(plat)}
|
||||
got = {c.path for c in o.detected}
|
||||
check(f"{plat}: detected is exactly that platform's own", got == own, f"{got} vs {own}")
|
||||
check(f"{plat}: auto is the first detected",
|
||||
(o.auto.path if o.auto else None) == (o.detected[0].path if o.detected else None))
|
||||
# The old bug, stated directly: nothing removable may surface under a
|
||||
# platform that keeps its library in a fixed place.
|
||||
if not getattr(driver, "removable", False):
|
||||
removable_paths = {c["path"] for d in registry.drivers()
|
||||
if getattr(d, "removable", False) for c in d.detect()}
|
||||
check(f"{plat}: no removable drive leaks in", not (got & removable_paths))
|
||||
|
||||
check("unscoped still answers (nothing depends on it, but it must not raise)",
|
||||
collection_options() is not None)
|
||||
check("an unknown platform detects nothing rather than raising",
|
||||
collection_options("nonesuch").detected == [])
|
||||
|
||||
print("== per-platform 'open last' does not cross platforms ==")
|
||||
prefs.set_last_collection("/tmp/a/collection.nml", "traktor")
|
||||
prefs.set_last_collection("/tmp/b/master.db", "rekordbox")
|
||||
check("traktor remembers its own", prefs.get_last_collection("traktor") == "/tmp/a/collection.nml")
|
||||
check("rekordbox remembers its own", prefs.get_last_collection("rekordbox") == "/tmp/b/master.db")
|
||||
# Offering a Rekordbox master.db to someone who just chose Traktor is an offer
|
||||
# that cannot be taken, so an unknown platform gets None, NOT the global value.
|
||||
check("a platform with no record gets None, not the global one",
|
||||
prefs.get_last_collection("onelibrary") is None
|
||||
and prefs.get_last_collection() == "/tmp/b/master.db")
|
||||
check("the picker surfaces it as `recent`",
|
||||
(collection_options("traktor").recent or None) is not None
|
||||
and collection_options("traktor").recent.path == "/tmp/a/collection.nml")
|
||||
check("a remembered library that has gone is offered as exists=False",
|
||||
collection_options("traktor").recent.exists is False)
|
||||
|
||||
print("== /api/fs/list only lists what the chosen platform can open ==")
|
||||
root = Path(tempfile.mkdtemp())
|
||||
(root / "collection.nml").write_text("x")
|
||||
(root / "master.db").write_bytes(b"x")
|
||||
(root / "notes.txt").write_text("x")
|
||||
(root / "SomeDrive").mkdir()
|
||||
|
||||
names = lambda plat: {f.name for f in fs_list(str(root), plat).files} # noqa: E731
|
||||
check("traktor sees only .nml", names("traktor") == {"collection.nml"}, names("traktor"))
|
||||
check("rekordbox sees only .db", names("rekordbox") == {"master.db"}, names("rekordbox"))
|
||||
# Not "the .db files it might contain": its library is a folder, so listing any
|
||||
# file would offer something the Open action cannot act on.
|
||||
check("onelibrary, which picks a folder, sees no files at all", names("onelibrary") == set())
|
||||
check("unscoped still sees the union", names(None) == {"collection.nml", "master.db"})
|
||||
check("never the unopenable", all("notes.txt" not in names(p)
|
||||
for p in (None, "traktor", "rekordbox", "onelibrary")))
|
||||
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("== a library may be a DIRECTORY, not just a file ==")
|
||||
drives = registry.detect_for("onelibrary")
|
||||
if drives:
|
||||
# `describe()` returns the database, but the drive root is what a user picks
|
||||
# in the browser. Both must name the same library or the picker and the
|
||||
# last-opened shortcut would disagree about what is valid.
|
||||
db = Path(drives[0]["path"])
|
||||
root_dir = db.parent.parent.parent
|
||||
driver = registry.driver_by_platform("onelibrary")
|
||||
check("the mount point opens", driver.can_open(root_dir), str(root_dir))
|
||||
check("so does the database it points at", driver.can_open(db))
|
||||
# ...and both must be CALLED the same thing. The sidebar names the open
|
||||
# library, and a filename would call one stick two different names purely
|
||||
# by which end of it the user happened to click.
|
||||
check("both ends of the drive give one display name",
|
||||
driver.display_name_for(root_dir) == driver.display_name_for(db) == root_dir.name,
|
||||
f"{driver.display_name_for(root_dir)!r} vs {driver.display_name_for(db)!r}")
|
||||
check("a path that is not a drive falls back to its own name",
|
||||
driver.display_name_for(Path("/nope/whatever.db")) == "whatever.db")
|
||||
else:
|
||||
print(" [SKIP] no OneLibrary drive connected")
|
||||
|
||||
print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
|
||||
_TMP.cleanup()
|
||||
raise SystemExit(1 if failed else 0)
|
||||
@@ -397,6 +397,7 @@ export default function App() {
|
||||
onError={onError}
|
||||
onOpenHistory={() => setShowHistory(true)}
|
||||
onImport={() => setImporting(true)}
|
||||
onSwitchLibrary={() => setForcePicker(true)}
|
||||
/>
|
||||
|
||||
<CapabilitiesContext.Provider value={viewCaps}>
|
||||
|
||||
+17
-4
@@ -212,8 +212,14 @@ export interface PlatformOption {
|
||||
platform: Platform
|
||||
name: string
|
||||
library_label: string
|
||||
/** Whether picking this platform's library means picking a file or a folder. */
|
||||
selects: 'file' | 'directory'
|
||||
installed: boolean
|
||||
/** How many libraries this platform has right now; `installed` is `found > 0`. */
|
||||
found: number
|
||||
/** The library lives on plugged-in media, so `found` changes between calls —
|
||||
* and `found === 0` means "nothing plugged in", not "not installed". */
|
||||
removable: boolean
|
||||
}
|
||||
|
||||
export interface EditState {
|
||||
@@ -238,7 +244,11 @@ export interface CollectionCandidate {
|
||||
}
|
||||
|
||||
export interface CollectionOptions {
|
||||
auto: CollectionCandidate | null // best auto-detected (latest Traktor version)
|
||||
auto: CollectionCandidate | null // best auto-detected; the first of `detected`
|
||||
/** EVERY library detected for the platform, best first. One platform can
|
||||
* genuinely have several at once — two Traktor versions, two sticks — and
|
||||
* the picker offers the choice rather than anointing one. */
|
||||
detected: CollectionCandidate[]
|
||||
recent: CollectionCandidate | null // last opened (may no longer exist)
|
||||
}
|
||||
|
||||
@@ -416,9 +426,12 @@ export const api = {
|
||||
collection: () => getJSON<CollectionStatus>('/api/library'),
|
||||
openCollection: (path: string) =>
|
||||
send<CollectionStatus>('POST', '/api/library/open', { path }),
|
||||
collectionOptions: () => getJSON<CollectionOptions>('/api/library/options'),
|
||||
listDir: (path?: string) =>
|
||||
getJSON<FsListing>(`/api/fs/list${path ? `?path=${encodeURIComponent(path)}` : ''}`),
|
||||
// Both take the chosen platform, because the picker asks for it FIRST: the
|
||||
// shortcuts and the browsable files are only meaningful inside that answer.
|
||||
collectionOptions: (platform?: string) =>
|
||||
getJSON<CollectionOptions>(`/api/library/options${qs({ platform })}`),
|
||||
listDir: (path?: string, platform?: string) =>
|
||||
getJSON<FsListing>(`/api/fs/list${qs({ path, platform })}`),
|
||||
|
||||
// ---- path remapping (per-collection OS-path prefix translation) ----
|
||||
getPathMapping: () => getJSON<PathMapping>('/api/library/path-mapping'),
|
||||
|
||||
@@ -1,10 +1,27 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery } from '@tanstack/react-query'
|
||||
import { api, type CollectionStatus } from '../api'
|
||||
import { api, type CollectionCandidate, type CollectionStatus, type PlatformOption } from '../api'
|
||||
import { browsePrompt, platformAvailability } from '../lib/platformCopy'
|
||||
|
||||
/**
|
||||
* Choose a library to open, in two steps: WHICH PLATFORM, then which library.
|
||||
*
|
||||
* The platform comes first because it is the question every later answer
|
||||
* depends on. Asked the other way round — one flat list of everything found —
|
||||
* "Automatic" had to guess across platforms, and it guessed by adapter
|
||||
* REGISTRATION ORDER: a plugged-in USB stick could be offered as the user's
|
||||
* collection because its driver happened to be imported first. Scoping the
|
||||
* shortcuts to a chosen platform removes that class of mistake by construction
|
||||
* rather than by ranking candidates more cleverly.
|
||||
*
|
||||
* Nothing is remembered between launches. The platform list is where every
|
||||
* session starts, so the choice is always visible and never inherited from a
|
||||
* decision made days ago.
|
||||
*/
|
||||
|
||||
interface Props {
|
||||
onOpened: (status: CollectionStatus) => void
|
||||
onCancel?: () => void // shown only when switching from an already-loaded collection
|
||||
onCancel?: () => void // shown only when switching from an already-loaded library
|
||||
}
|
||||
|
||||
function formatWhen(sec: number | null): string {
|
||||
@@ -47,22 +64,25 @@ function OptionCard({
|
||||
}
|
||||
|
||||
export function CollectionPicker({ onOpened, onCancel }: Props) {
|
||||
const [mode, setMode] = useState<'choose' | 'browse'>('choose')
|
||||
const [step, setStep] = useState<'platform' | 'library' | 'browse'>('platform')
|
||||
const [platform, setPlatform] = useState<PlatformOption | null>(null)
|
||||
const [dir, setDir] = useState<string | undefined>(undefined) // undefined => home
|
||||
const [manual, setManual] = useState('')
|
||||
|
||||
const options = useQuery({ queryKey: ['collectionOptions'], queryFn: api.collectionOptions })
|
||||
// The picker runs BEFORE a library is open, so capabilities do not exist yet —
|
||||
// /api/platforms is the pre-load equivalent.
|
||||
const { data: platforms } = useQuery({ queryKey: ['platforms'], queryFn: api.platforms })
|
||||
// One platform today, so name it; with more, stay general rather than listing.
|
||||
const only = platforms?.length === 1 ? platforms[0] : null
|
||||
const appName = only?.name ?? 'DJ'
|
||||
const fileLabel = only?.library_label ?? 'library file'
|
||||
// /api/platforms is the pre-load equivalent, and it is the whole of step one.
|
||||
const platforms = useQuery({ queryKey: ['platforms'], queryFn: api.platforms })
|
||||
|
||||
const options = useQuery({
|
||||
queryKey: ['collectionOptions', platform?.platform],
|
||||
queryFn: () => api.collectionOptions(platform!.platform),
|
||||
enabled: !!platform,
|
||||
})
|
||||
|
||||
const listing = useQuery({
|
||||
queryKey: ['fs', dir ?? '~'],
|
||||
queryFn: () => api.listDir(dir),
|
||||
enabled: mode === 'browse',
|
||||
queryKey: ['fs', dir ?? '~', platform?.platform],
|
||||
queryFn: () => api.listDir(dir, platform?.platform),
|
||||
enabled: step === 'browse',
|
||||
})
|
||||
|
||||
const open = useMutation({
|
||||
@@ -75,30 +95,59 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
|
||||
const auto = opt?.auto ?? null
|
||||
const recent = opt?.recent ?? null
|
||||
const recentAvailable = !!recent && recent.exists
|
||||
// `auto` is the first of these, so the rest are the ones a single "Automatic"
|
||||
// card would have thrown away. Two Traktor versions, or two sticks, is normal.
|
||||
const alsoFound = (opt?.detected ?? []).slice(1)
|
||||
// A drive is not a file: its browse lists folders and confirms the one you are
|
||||
// standing in, the way the import folder picker does.
|
||||
const picksDirectory = platform?.selects === 'directory'
|
||||
|
||||
const goPlatform = () => {
|
||||
setStep('platform')
|
||||
setPlatform(null)
|
||||
setDir(undefined)
|
||||
setManual('')
|
||||
open.reset()
|
||||
}
|
||||
|
||||
const subtitle =
|
||||
step === 'platform'
|
||||
? 'Konduktor opens libraries from each of these.'
|
||||
: step === 'library'
|
||||
? 'Open automatically, resume your last one, or browse.'
|
||||
: platform
|
||||
? browsePrompt(platform)
|
||||
: ''
|
||||
|
||||
const openError = open.isError ? (open.error as Error).message : null
|
||||
|
||||
return (
|
||||
<div className="flex h-screen w-screen items-center justify-center bg-ink-950 p-6">
|
||||
<div className="flex h-[600px] w-full max-w-2xl flex-col overflow-hidden rounded-xl border border-line bg-ink-900 shadow-2xl">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3 border-b border-line px-5 py-4">
|
||||
<div className="flex-1">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[15px] font-semibold tracking-tight">
|
||||
Select your {appName} library
|
||||
{platform ? `Select your ${platform.name} library` : 'Select your DJ platform'}
|
||||
</div>
|
||||
<div className="text-xs text-muted">
|
||||
{mode === 'choose'
|
||||
? 'Open automatically, resume your last one, or browse.'
|
||||
: `Choose a ${fileLabel} to open.`}
|
||||
<div className="truncate text-xs text-muted">{subtitle}</div>
|
||||
</div>
|
||||
</div>
|
||||
{mode === 'browse' && (
|
||||
{step === 'browse' && (
|
||||
<button
|
||||
onClick={() => setMode('choose')}
|
||||
onClick={() => setStep('library')}
|
||||
className="rounded-md px-2.5 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
|
||||
>
|
||||
‹ Back
|
||||
</button>
|
||||
)}
|
||||
{step === 'library' && (
|
||||
<button
|
||||
onClick={goPlatform}
|
||||
className="rounded-md px-2.5 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
|
||||
>
|
||||
‹ Platforms
|
||||
</button>
|
||||
)}
|
||||
{onCancel && (
|
||||
<button
|
||||
onClick={onCancel}
|
||||
@@ -109,8 +158,28 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{mode === 'choose' ? (
|
||||
/* ---- Chooser ---- */
|
||||
{step === 'platform' ? (
|
||||
/* ---- Step 1: which platform ---- */
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto p-5">
|
||||
{platforms.isLoading && <div className="text-sm text-faint">Loading…</div>}
|
||||
{/* Every platform stays clickable, including the ones with nothing
|
||||
found: a library kept somewhere unusual is still openable by
|
||||
browsing, and a disabled row would say otherwise. */}
|
||||
{platforms.data?.map((p) => (
|
||||
<OptionCard
|
||||
key={p.platform}
|
||||
icon={p.removable ? '⬒' : p.found > 0 ? '●' : '○'}
|
||||
title={p.name}
|
||||
subtitle={platformAvailability(p)}
|
||||
onClick={() => {
|
||||
setPlatform(p)
|
||||
setStep('library')
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : step === 'library' ? (
|
||||
/* ---- Step 2: which library of that platform ---- */
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto p-5">
|
||||
<OptionCard
|
||||
icon="✨"
|
||||
@@ -119,8 +188,10 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
|
||||
auto
|
||||
? `${auto.label} · modified ${formatWhen(auto.modified)}`
|
||||
: options.isLoading
|
||||
? `Searching for a ${appName} library…`
|
||||
: `No ${appName} library found in the default location`
|
||||
? `Searching for a ${platform!.name} library…`
|
||||
: platform!.removable
|
||||
? `No ${platform!.name} drive is connected`
|
||||
: `No ${platform!.name} library in the default location`
|
||||
}
|
||||
disabled={!auto}
|
||||
busy={open.isPending}
|
||||
@@ -128,13 +199,13 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
|
||||
/>
|
||||
<OptionCard
|
||||
icon="🕘"
|
||||
title="Open last collection"
|
||||
title="Open last library"
|
||||
subtitle={
|
||||
recent
|
||||
? recent.exists
|
||||
? recent.path
|
||||
: `${recent.path} · no longer exists`
|
||||
: 'No previously opened collection'
|
||||
: `No previously opened ${platform!.name} library`
|
||||
}
|
||||
disabled={!recentAvailable}
|
||||
busy={open.isPending}
|
||||
@@ -142,20 +213,49 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
|
||||
/>
|
||||
<OptionCard
|
||||
icon="📂"
|
||||
title="Find collection manually"
|
||||
subtitle={`Browse for a ${fileLabel}`}
|
||||
title="Find library manually"
|
||||
subtitle={
|
||||
picksDirectory
|
||||
? 'Browse for the drive'
|
||||
: `Browse for a ${platform!.library_label}`
|
||||
}
|
||||
busy={open.isPending}
|
||||
onClick={() => setMode('browse')}
|
||||
onClick={() => setStep('browse')}
|
||||
/>
|
||||
|
||||
{open.isError && (
|
||||
{/* Anything else detected. Listed rather than ranked away, because
|
||||
"the newest one" is a guess and two of these are a real setup. */}
|
||||
{alsoFound.length > 0 && (
|
||||
<div className="mt-1">
|
||||
<div className="mb-2 text-[10px] font-semibold uppercase tracking-wider text-faint">
|
||||
Also found
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
{alsoFound.map((c: CollectionCandidate) => (
|
||||
<button
|
||||
key={c.path}
|
||||
disabled={open.isPending}
|
||||
onClick={() => open.mutate(c.path)}
|
||||
className="flex w-full items-center gap-2 rounded-md border border-line bg-ink-850 px-3 py-2 text-left text-sm text-muted hover:border-accent hover:text-text disabled:opacity-40"
|
||||
>
|
||||
<span className="truncate">{c.label}</span>
|
||||
<span className="ml-auto shrink-0 text-[11px] text-faint">
|
||||
{formatWhen(c.modified)}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{openError && (
|
||||
<div className="rounded-md border border-pink/40 bg-ink-850 px-3 py-2 text-xs text-pink">
|
||||
{(open.error as Error).message}
|
||||
{openError}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
/* ---- Manual browser ---- */
|
||||
/* ---- Step 3: browse for it ---- */
|
||||
<>
|
||||
{/* Path bar */}
|
||||
<div className="flex items-center gap-2 border-b border-line bg-ink-850 px-4 py-2">
|
||||
@@ -179,11 +279,15 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Listing */}
|
||||
{/* 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. */}
|
||||
<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">No folders or .nml files here.</div>
|
||||
<div className="p-4 text-sm text-faint">
|
||||
{picksDirectory ? 'No folders here.' : 'Nothing openable here.'}
|
||||
</div>
|
||||
)}
|
||||
{data?.dirs.map((d) => (
|
||||
<button
|
||||
@@ -211,11 +315,30 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
|
||||
))}
|
||||
</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 */}
|
||||
<div className="border-t border-line px-4 py-3">
|
||||
{open.isError && (
|
||||
{openError && (
|
||||
<div className="mb-2 rounded-md border border-pink/40 bg-ink-850 px-3 py-2 text-xs text-pink">
|
||||
{(open.error as Error).message}
|
||||
{openError}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -225,7 +348,11 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && manual.trim()) open.mutate(manual.trim())
|
||||
}}
|
||||
placeholder={`…or paste a full path to ${fileLabel}`}
|
||||
placeholder={
|
||||
picksDirectory
|
||||
? '…or paste a full path to the drive'
|
||||
: `…or paste a full path to ${platform!.library_label}`
|
||||
}
|
||||
className="min-w-0 flex-1 rounded-md border border-line bg-ink-850 px-3 py-2 font-mono text-xs text-text outline-none placeholder:text-faint focus:border-accent"
|
||||
/>
|
||||
<button
|
||||
|
||||
@@ -27,6 +27,7 @@ interface Props {
|
||||
onError: (msg: string) => void
|
||||
onOpenHistory: () => void
|
||||
onImport: () => void
|
||||
onSwitchLibrary: () => void
|
||||
}
|
||||
|
||||
// Kind picks the icon; every behavioural question is answered by the node's own
|
||||
@@ -186,8 +187,31 @@ function NodeRow({
|
||||
)
|
||||
}
|
||||
|
||||
export function Sidebar({ source, onSelect, onError, onOpenHistory, onImport }: Props) {
|
||||
export function Sidebar({
|
||||
source,
|
||||
onSelect,
|
||||
onError,
|
||||
onOpenHistory,
|
||||
onImport,
|
||||
onSwitchLibrary,
|
||||
}: Props) {
|
||||
const qc = useQueryClient()
|
||||
// Both share a cache entry with App and SaveBar, so the header never
|
||||
// disagrees with what is loaded or with whether it has been saved.
|
||||
const library = useQuery({ queryKey: ['collection'], queryFn: api.collection }).data?.library
|
||||
const dirty = useQuery({ queryKey: ['state'], queryFn: api.state }).data?.dirty ?? false
|
||||
|
||||
// Switching library throws away every unsaved edit — the adapter holds them in
|
||||
// its native model, and opening another library replaces it. Worth a confirm:
|
||||
// until now there was no way to switch at all, so this hazard is new.
|
||||
const switchLibrary = () => {
|
||||
if (
|
||||
dirty &&
|
||||
!confirm('You have unsaved changes. Opening a different library will discard them.')
|
||||
)
|
||||
return
|
||||
onSwitchLibrary()
|
||||
}
|
||||
// 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.
|
||||
const canCreate = useCaps().writable
|
||||
@@ -216,6 +240,30 @@ export function Sidebar({ source, onSelect, onError, onOpenHistory, onImport }:
|
||||
|
||||
return (
|
||||
<aside className="flex h-full w-64 shrink-0 flex-col border-r border-line bg-ink-900">
|
||||
{/* Which library is open — and the way to open a different one. Until
|
||||
this existed the picker was a one-way door: it ran once at startup and
|
||||
nothing could summon it again, so changing library meant restarting.
|
||||
It doubles as the only place the app says what it currently has open. */}
|
||||
<button
|
||||
onClick={switchLibrary}
|
||||
title={library ? `${library.path} — click to open a different library` : undefined}
|
||||
className="group flex items-center gap-2 border-b border-line px-3 py-2.5 text-left hover:bg-ink-800"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-medium text-text">
|
||||
{library?.display_name ?? 'No library'}
|
||||
</div>
|
||||
<div className="truncate text-[11px] text-faint">
|
||||
{library
|
||||
? `${library.name}${library.version ? ` ${library.version}` : ''}`
|
||||
: 'Choose one'}
|
||||
</div>
|
||||
</div>
|
||||
<span className="shrink-0 text-xs text-faint transition-colors group-hover:text-accent">
|
||||
⇄
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div className="px-2 pt-3">
|
||||
<button
|
||||
onClick={() => onSelect({ kind: 'all' })}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* staying genuinely specific — the pre-save warning is a real, per-platform
|
||||
* hazard and must not be watered down into something vague.
|
||||
*/
|
||||
import type { Capabilities, SaveCapabilities } from '../api'
|
||||
import type { Capabilities, PlatformOption, SaveCapabilities } from '../api'
|
||||
|
||||
export function saveLabel(save: SaveCapabilities): string {
|
||||
return `Save to ${save.app_name}`
|
||||
@@ -64,3 +64,28 @@ export function readOnlyShort(caps: Capabilities): string | null {
|
||||
if (caps.writable) return null
|
||||
return caps.readonly_cause === 'cloud_synced' ? 'Read-only · cloud-synced' : 'Read-only'
|
||||
}
|
||||
|
||||
// ---- picker: choosing a platform, before any library is open ----------------
|
||||
//
|
||||
// These take a PlatformOption rather than Capabilities: the picker runs before
|
||||
// an adapter exists, so there are no capabilities to read yet.
|
||||
|
||||
/**
|
||||
* What this platform has to offer right now.
|
||||
*
|
||||
* "Nothing found" means two genuinely different things, and which one it is
|
||||
* decides what the user should do about it: a fixed-location platform is not
|
||||
* installed, or keeps its library somewhere unusual, and wants browsing —
|
||||
* whereas a removable one simply has nothing plugged in, and wants a USB port.
|
||||
* Someone told "not found" about OneLibrary would go hunting for a missing app.
|
||||
*/
|
||||
export function platformAvailability(p: PlatformOption): string {
|
||||
if (p.found > 1) return p.removable ? `${p.found} drives connected` : `${p.found} found`
|
||||
if (p.found === 1) return p.removable ? '1 drive connected' : `${p.library_label} found`
|
||||
return p.removable ? 'No drive connected' : `No ${p.library_label} in the usual place`
|
||||
}
|
||||
|
||||
/** What the manual browser is asking the user to pick out. */
|
||||
export function browsePrompt(p: PlatformOption): string {
|
||||
return p.selects === 'directory' ? 'Find the drive to open.' : `Choose a ${p.library_label} to open.`
|
||||
}
|
||||
Reference in new issue
Block a user