From 6e24f5ef1d8a84a6851fd9a33439215a5c91e870 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 17 Sep 2026 22:24:56 +0200 Subject: [PATCH] Switched to more generic wording --- CLAUDE.md | 28 ++- backend/konduktor/adapters/traktor/adapter.py | 20 +- .../konduktor/adapters/traktor/cue_types.py | 13 ++ .../konduktor/adapters/traktor/projection.py | 94 +++++++-- backend/konduktor/adapters/traktor/store.py | 14 +- backend/konduktor/core/model.py | 91 +++++++-- backend/konduktor/main.py | 119 +++++++---- backend/konduktor/schemas.py | 29 ++- backend/test_history.py | 2 +- backend/test_phase3.py | 4 +- backend/test_save_fidelity.py | 12 +- backend/test_traktor_adapter.py | 22 +- frontend/src/App.tsx | 31 ++- frontend/src/api.ts | 190 ++++++++++++------ frontend/src/components/CollectionPicker.tsx | 19 +- frontend/src/components/EditTagsDialog.tsx | 24 +-- frontend/src/components/HistoryPanel.tsx | 8 +- frontend/src/components/HotcueBar.tsx | 51 +++-- frontend/src/components/PrepStrip.tsx | 93 ++++++--- frontend/src/components/RatingStars.tsx | 23 ++- frontend/src/components/SaveBar.tsx | 10 +- frontend/src/components/SelectionBar.tsx | 2 +- frontend/src/components/Sidebar.tsx | 22 +- frontend/src/components/Toolbar.tsx | 4 +- frontend/src/lib/capabilities.tsx | 32 +++ frontend/src/lib/cues.ts | 84 ++++++-- frontend/src/lib/format.ts | 20 +- frontend/src/lib/platformCopy.ts | 41 ++++ frontend/src/lib/trackColumns.tsx | 13 +- 29 files changed, 796 insertions(+), 319 deletions(-) create mode 100644 backend/konduktor/adapters/traktor/cue_types.py create mode 100644 frontend/src/lib/capabilities.tsx create mode 100644 frontend/src/lib/platformCopy.ts diff --git a/CLAUDE.md b/CLAUDE.md index 19e0044..25d4e62 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -73,8 +73,20 @@ Two independent apps that talk over HTTP: `KONDUKTOR_NML` auto-loads on startup (dev/tests). - **`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 (keep in sync with backend - `schemas.py`). + - `api.ts` — typed client + all API types. **Generic, not Traktor-shaped**: + cue types are the strings `cue`/`fade_in`/`fade_out`/`load`/`loop`, a cue has + a `role` (`hotcue`/`memory`) and a nullable `slot`, and `editable` + + `readonly_reason` say whether the adapter will accept a command on it — gate + on `editable`, never on a platform-specific reason like `grid_marker`. Keep + in lockstep with `core/model.py`; land both in the same commit. + - `lib/capabilities.tsx` — `useCaps()` over `GET /api/capabilities`. The app + does not render until capabilities resolve, so no first frame can offer an + edit the adapter would reject. Containers call `useCaps()`; presentational + leaves take plain values as props. **No component branches on the platform.** + - `lib/platformCopy.ts` — composes user-facing wording from the *facts* the + 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 + create/rename/delete), `SaveBar`, `Toolbar` (search/filters + `ColumnsMenu`), @@ -113,7 +125,13 @@ Two independent apps that talk over HTTP: analysis + paint), `beatgrid.ts` (the marker-list beat math — every beat/bar/snap/jump calculation goes through it), `cues.ts` (draw cues/loop/beatgrid/cue-point). See "Prep engine" below. - - `lib/trackColumns.tsx` — single source of truth for the library table's + - Capability-gated today: hotcue bank size (`HotcueBar`, the auto-cue guard and + the digit shortcuts all read `cues.hotcue_slots`), the cue-type dropdown + (`cues.types`), the rating scale (`tracks.rating_max`), the grid Lock button + (`grid.lockable`). Carried but deliberately unused until a second adapter + exists: `slot_labels: 'letter'`, `palette`, `loops: 'separate_bank'`, and + memory-cue *editing* (one-platform features stay preserved-but-uneditable). +- `lib/trackColumns.tsx` — single source of truth for the library table's columns (defs, default widths/visibility/order, the Columns-menu list, the inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation). - Data flow: the whole library is fetched once (`/api/tracks?limit=20000`); @@ -264,8 +282,8 @@ that number and nothing else — everything derives from it: commands, piecewise beat math, playhead-derived marker editing). Step 1 of the multi-platform plan in `.claude/discussions/`. - ✅ Generic model + adapter interface (Traktor as the only adapter) — step 2 of - the multi-platform plan. Backend done; the wire format and UI are still - Traktor-shaped (cue type integers, 8 hard-coded hotcue slots) and are next. + the multi-platform plan. Backend, wire format and UI are all generic; nothing + above `adapters/traktor/` knows what Traktor is. - ⬜ Rekordbox adapter; ⬜ Serato adapter; ⬜ export/conversion - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging diff --git a/backend/konduktor/adapters/traktor/adapter.py b/backend/konduktor/adapters/traktor/adapter.py index 0c6267c..dfe4531 100644 --- a/backend/konduktor/adapters/traktor/adapter.py +++ b/backend/konduktor/adapters/traktor/adapter.py @@ -13,6 +13,7 @@ from __future__ import annotations from contextlib import contextmanager from pathlib import Path +from types import SimpleNamespace from ...core.adapter import InvalidCommand, NotFound, Unsupported from ...core.capabilities import Capabilities @@ -21,13 +22,10 @@ from ...core.pathmap import PathMapping from ...core.query import TrackIndex from . import capabilities as caps from . import projection +from .cue_types import CUE_TYPE_TO_NATIVE from .store import PlaylistError, TraktorStore -# Generic cue vocabulary -> Traktor's CUE_V2 TYPE encoding. This table is the -# only place the integers exist outside the store; type 4 is a grid marker and -# is never a cue, so it has no generic name. -CUE_TYPE_TO_NATIVE = {"cue": 0, "fade_in": 1, "fade_out": 2, "load": 3, "loop": 5} -NATIVE_TO_CUE_TYPE = {v: k for k, v in CUE_TYPE_TO_NATIVE.items()} + class TraktorAdapter: @@ -186,8 +184,18 @@ class TraktorAdapter: return self._refresh(track_id) def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: + native = [ + SimpleNamespace( + slot=c.slot, + start=c.start, + name=c.name, + type=self._native_cue_type(getattr(c, "type", "cue")), + length=getattr(c, "length", 0.0), + ) + for c in cues + ] with _translate(): - self._store.place_hotcues(track_id, cues, overwrite=overwrite) + self._store.place_hotcues(track_id, native, overwrite=overwrite) return self._refresh(track_id) # ---- beatgrid --------------------------------------------------------- diff --git a/backend/konduktor/adapters/traktor/cue_types.py b/backend/konduktor/adapters/traktor/cue_types.py new file mode 100644 index 0000000..07b8405 --- /dev/null +++ b/backend/konduktor/adapters/traktor/cue_types.py @@ -0,0 +1,13 @@ +"""Traktor's CUE_V2 TYPE encoding <-> the generic cue vocabulary. + +The only place these integers are given meaning. Type 4 is a grid marker, not a +cue, so it has no generic name — grid markers are projected as beatgrid markers +and never appear in a track's cue list. + +Lives in its own module so the projection and the adapter can both use it +without importing each other. +""" +from __future__ import annotations + +CUE_TYPE_TO_NATIVE = {"cue": 0, "fade_in": 1, "fade_out": 2, "load": 3, "loop": 5} +NATIVE_TO_CUE_TYPE = {v: k for k, v in CUE_TYPE_TO_NATIVE.items()} diff --git a/backend/konduktor/adapters/traktor/projection.py b/backend/konduktor/adapters/traktor/projection.py index c79e435..8421ac0 100644 --- a/backend/konduktor/adapters/traktor/projection.py +++ b/backend/konduktor/adapters/traktor/projection.py @@ -5,8 +5,49 @@ Everything above this file sees generic types exclusively. """ from __future__ import annotations +import re + from ...core.model import CuePoint, GridMarker, Track, TrackCues from . import beatgrid +from .cue_types import NATIVE_TO_CUE_TYPE + +# Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"), +# depending on a user preference — so the library can contain either. Parsing +# notation is platform knowledge and belongs here, not in the UI. +_OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I) +_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I) +_DATE = re.compile(r"^(\d{4})/(\d{1,2})/(\d{1,2})$") + + +def parse_key(key: str | None) -> tuple[int | None, str | None]: + """(Camelot wheel position 1-12, mode) for a Traktor display key. + + Open Key numbers the wheel seven semitones round from Camelot, so + Open Key 1 == Camelot 8 (both are C major / A minor). + """ + if not key: + return None, None + k = key.strip() + if m := _CAMELOT.match(k): + n = int(m.group(1)) + if 1 <= n <= 12: + return n, "minor" if m.group(2).lower() == "a" else "major" + if m := _OPEN_KEY.match(k): + n = int(m.group(1)) + if 1 <= n <= 12: + return ((n + 6) % 12) + 1, "minor" if m.group(2).lower() == "m" else "major" + return None, None + + +def iso_date(value: str | None) -> str | None: + """Traktor writes dates as "YYYY/M/D"; the model carries ISO-8601.""" + if not value: + return None + m = _DATE.match(value.strip()) + if not m: + return value + y, mo, d = m.groups() + return f"{y}-{int(mo):02d}-{int(d):02d}" def primary_key(location) -> str: @@ -38,6 +79,7 @@ def to_track(e) -> Track: 1 for c in cues if c.hotcue is not None and c.hotcue >= 0 ) markers = beatgrid.grid_markers(e) + wheel, mode = parse_key(info.key if info else None) return Track( id=primary_key(loc) if loc else (e.title or ""), artist=e.artist, @@ -51,19 +93,21 @@ def to_track(e) -> Track: comment=info.comment if info else None, bpm=beatgrid.effective_bpm(e), key=info.key if info else None, + key_wheel=wheel, + key_mode=mode, rating=_rating_stars(info.ranking if info else None), playcount=info.playcount if info else None, length=info.playtime if info else None, bitrate=info.bitrate if info else None, - import_date=info.import_date if info else None, - last_played=info.last_played if info else None, - release_date=info.release_date if info else None, + import_date=iso_date(info.import_date if info else None), + last_played=iso_date(info.last_played if info else None), + release_date=iso_date(info.release_date if info else None), filepath=_display_path(loc) if loc else None, cue_count=len(cues), hotcue_count=hotcues, - has_grid=bool(markers), - grid_markers=len(markers), - is_stem=getattr(e, "stems", None) is not None, + grid_marker_count=len(markers), + grid_locked=bool(e.lock), + media_kind="stem" if getattr(e, "stems", None) is not None else "audio", ) @@ -87,19 +131,31 @@ def to_track_cues(entry) -> TrackCues: ) for i, m in enumerate(markers) ] - cues = [ - CuePoint( - name=c.name, - type=c.type if c.type is not None else 0, - start=(c.start or 0.0) / 1000.0, - length=(c.len or 0.0) / 1000.0, - hotcue=c.hotcue if c.hotcue is not None else -1, - color=c.color, - grid_marker=marker_of.get(id(c)), + cues = [] + for c in entry.cue_v2 or []: + if getattr(c, "grid", None) is not None: + continue # a grid marker is projected as a beatgrid marker, not a cue + marker = marker_of.get(id(c)) + slot = c.hotcue if c.hotcue is not None and c.hotcue >= 0 else None + cues.append( + CuePoint( + name=c.name, + # An unknown TYPE is projected as a plain cue rather than dropped: + # preserving a cue we cannot name beats hiding it from the user. + type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"), + # Every Traktor cue lives in the hotcue bank. + role="hotcue", + start=(c.start or 0.0) / 1000.0, + length=(c.len or 0.0) / 1000.0, + slot=slot, + color=c.color, + # A grid marker's companion belongs to the beatgrid: the store + # refuses hotcue commands on it, so say so up front. + editable=marker is None, + readonly_reason="beatgrid_companion" if marker is not None else None, + grid_marker=marker, + ) ) - for c in (entry.cue_v2 or []) - if getattr(c, "grid", None) is None - ] return TrackCues( - grid_markers=grid_markers, locked=bool(entry.lock), cues=cues + grid_markers=grid_markers, grid_locked=bool(entry.lock), cues=cues ) diff --git a/backend/konduktor/adapters/traktor/store.py b/backend/konduktor/adapters/traktor/store.py index f2908c1..db36022 100644 --- a/backend/konduktor/adapters/traktor/store.py +++ b/backend/konduktor/adapters/traktor/store.py @@ -154,20 +154,26 @@ class TraktorStore: return PlaylistNode( id=pl.uuid if pl and pl.uuid else name, name=name, - type="PLAYLIST", - uuid=pl.uuid if pl else None, + kind="playlist", count=len(keys), + selectable=True, + can_add_tracks=True, + can_reorder=True, + can_rename=True, + can_delete=True, ) if ntype == "SMARTLIST" or node.smartplaylist is not None: + # Rule-based, so it has no static entry list to show or edit. return PlaylistNode( - id="sl:" + "/".join(parent_path + [name]), name=name, type="SMARTLIST" + id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart" ) path = parent_path + [name] return PlaylistNode( id="fld:" + "/".join(path), name=name, - type="FOLDER", + kind="folder", children=[self._to_model(c, path) for c in self._children(node)], + can_contain_children=True, ) @staticmethod diff --git a/backend/konduktor/core/model.py b/backend/konduktor/core/model.py index 5eba549..854486e 100644 --- a/backend/konduktor/core/model.py +++ b/backend/konduktor/core/model.py @@ -9,13 +9,17 @@ is the shape a batch cue placement takes in generic terms. """ from __future__ import annotations +from typing import Literal + from pydantic import BaseModel, ConfigDict, Field +from .capabilities import CueRole, CueType, MediaKind, PlaylistKind + class Track(BaseModel): - """A single track, flattened from a Traktor collection ENTRY.""" + """A single track in the library, as the app sees it.""" - id: str # primary key: "", used to join playlist entries + id: str # the adapter's stable track key; opaque above the adapter artist: str | None = None title: str | None = None album: str | None = None @@ -26,20 +30,27 @@ class Track(BaseModel): mix: str | None = None comment: str | None = None bpm: float | None = None - key: str | None = None # Traktor display key, e.g. "10m" + # The platform's own display string, shown verbatim ("10m", "8A", "Am"). + key: str | None = None + # Camelot wheel position 1-12 + mode, parsed BY THE ADAPTER — notation is + # platform knowledge. None when the key is absent or unparseable. + key_wheel: int | None = None + key_mode: Literal["major", "minor"] | None = None rating: int = 0 # 0-5 stars (derived from RANKING/51) playcount: int | None = None length: int | None = None # seconds bitrate: int | None = None + # ISO-8601 "YYYY-MM-DD", normalised by the adapter. import_date: str | None = None last_played: str | None = None release_date: str | None = None filepath: str | None = None # human-readable OS path cue_count: int = 0 hotcue_count: int = 0 - has_grid: bool = False - grid_markers: int = 0 # >1 = a flexible (multi-tempo) beatgrid - is_stem: bool = False # a Stem file ( child) vs a normal audio track + # 0 = no beatgrid, 1 = constant tempo, >1 = a flexible (multi-tempo) grid. + grid_marker_count: int = 0 + grid_locked: bool = False + media_kind: MediaKind = "audio" class TrackPage(BaseModel): @@ -79,15 +90,27 @@ class Stats(BaseModel): class PlaylistNode(BaseModel): - """A node in the playlist tree — either a FOLDER or a PLAYLIST/SMARTLIST.""" + """A node in the playlist tree. - id: str # stable synthetic id ("pl-" / "fld-") + `id` is OPAQUE: the adapter mints it and decodes it, and the UI never + constructs, parses or prefixes one. `kind` is for choosing an icon — every + behavioural question is answered by the flags, so the UI never has to infer + what a node can do from what it is called. + """ + + id: str name: str - type: str # "FOLDER" | "PLAYLIST" | "SMARTLIST" - uuid: str | None = None + kind: PlaylistKind = "playlist" count: int = 0 # track count (for playlists) children: list["PlaylistNode"] = [] + selectable: bool = False # has a static, listable entry set + can_add_tracks: bool = False + can_reorder: bool = False + can_rename: bool = False + can_delete: bool = False + can_contain_children: bool = False # a valid parent for a new playlist + PlaylistNode.model_rebuild() @@ -97,13 +120,20 @@ PlaylistNode.model_rebuild() class CuePoint(BaseModel): name: str | None = None - type: int # Traktor: 0 cue, 1 fade-in, 2 fade-out, 3 load, 4 grid, 5 loop + type: CueType = "cue" + # "memory" cues have no bank slot. Only Rekordbox has them, so they are + # modelled and preserved but not yet editable anywhere. + role: CueRole = "hotcue" start: float # seconds length: float # seconds (>0 for loops) - hotcue: int # -1 if not assigned to a hotcue slot - color: str | None = None # "#RRGGBB" if set - # Index of the grid marker this cue is the companion of, if any. Such a cue - # holds a real hotcue slot but belongs to the beatgrid and is not editable. + slot: int | None = None # bank slot; None for a cue not in a bank + color: str | None = None # "#RRGGBB" as the platform stored it + # False when the adapter refuses commands on this cue — the UI gates on THIS + # rather than on any platform-specific reason. + editable: bool = True + readonly_reason: Literal["beatgrid_companion", "platform_managed"] | None = None + # Index of the grid marker this cue mirrors, where the platform pairs them. + # A display hint only; None on platforms that do not. grid_marker: int | None = None @@ -121,16 +151,39 @@ class TrackCues(BaseModel): # tempo. There is deliberately no scalar bpm/anchor here: a single "the BPM" # is what made flexible grids render and edit wrongly. grid_markers: list[GridMarker] = [] - locked: bool = False # Traktor LOCK flag + grid_locked: bool = False cues: list[CuePoint] = [] # cue/loop markers (grid markers themselves excluded) class AutoHotcue(BaseModel): - slot: int # 0–7 + """One cue in a batch placement (Auto Hotcues).""" + + slot: int start: float # seconds name: str | None = None # positional label (e.g. "Drop") - type: int = 0 # plain cue - length: float = 0.0 # seconds (>0 for a loop hotcue) + type: CueType = "cue" + length: float = 0.0 # seconds (>0 for a loop cue) + + +class LibraryInfo(BaseModel): + """Identity of the loaded library, for display and for composing copy.""" + + platform: str + name: str # the DJ app's name, e.g. "Traktor" + library_label: str # what the user thinks of the artefact as, e.g. "collection.nml" + path: str + display_name: str # short label for the status bar + version: str | None = None + + +class PlatformOption(BaseModel): + """A platform the picker can offer before any library is open.""" + + platform: str + name: str + library_label: str + selects: Literal["file", "directory"] = "file" + installed: bool = False class RemapSample(BaseModel): diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index d3b9300..9adcf7b 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -14,7 +14,6 @@ from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, JSONResponse from . import __version__, history, prefs -from .adapters.traktor.adapter import NATIVE_TO_CUE_TYPE from .adapters.traktor.discovery import describe from .app_state import STATE from .core import auto_hotcues as ah @@ -38,6 +37,8 @@ from .schemas import ( CollectionStatus, CreatePlaylist, EditState, + LibraryInfo, + PlatformOption, EditTrack, Facets, FileTagOutcome, @@ -56,9 +57,9 @@ from .schemas import ( RenamePlaylist, SaveResult, SetEntries, - SetHotcue, - SetHotcueType, - SetLock, + SetCue, + SetCueType, + SetGridLock, Stats, Track, TrackCues, @@ -82,18 +83,6 @@ app.add_middleware( ) -def _cue_type_name(native: int) -> str: - """Map the wire's Traktor cue integer onto the generic vocabulary. - - Transitional: the HTTP contract still carries Traktor's encoding, so the - translation happens here at the boundary rather than in the adapter. - """ - name = NATIVE_TO_CUE_TYPE.get(native) - if name is None: - raise HTTPException(400, f"Unsupported cue type: {native}") - return name - - def require_adapter() -> LibraryAdapter: """The loaded library, or a 409. Routes talk to this and nothing else.""" if not STATE.loaded: @@ -118,7 +107,7 @@ def _adapter_error(_request, exc: AdapterError): # ---- collection selection --------------------------------------------- -@app.get("/api/collection", response_model=CollectionStatus) +@app.get("/api/library", response_model=CollectionStatus) def collection_status() -> CollectionStatus: if not STATE.loaded: return CollectionStatus(loaded=False) @@ -127,10 +116,11 @@ def collection_status() -> CollectionStatus: path=str(STATE.path), tracks=len(require_adapter().tracks), playlists=require_adapter().playlist_count(), + library=_library_info(), ) -@app.post("/api/collection/open", response_model=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(): @@ -145,7 +135,7 @@ def open_collection(body: OpenCollection) -> CollectionStatus: return collection_status() -@app.get("/api/collection/options", response_model=CollectionOptions) +@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).""" @@ -158,7 +148,7 @@ def collection_options() -> CollectionOptions: return CollectionOptions(auto=auto, recent=recent) -@app.get("/api/collection/path-mapping", response_model=PathMappingInfo) +@app.get("/api/library/path-mapping", response_model=PathMappingInfo) def get_path_mapping() -> PathMappingInfo: """The current collection's saved OS-path remapping (blank if none).""" require_adapter() @@ -168,7 +158,7 @@ def get_path_mapping() -> PathMappingInfo: return PathMappingInfo() -@app.put("/api/collection/path-mapping", response_model=PathMappingInfo) +@app.put("/api/library/path-mapping", response_model=PathMappingInfo) def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo: """Set (or, with blank prefixes, clear) the current collection's remapping. Persists to userprefs AND updates the live store so playback/analysis @@ -184,14 +174,14 @@ def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo: ) -@app.get("/api/collection/path-mapping/suggest", response_model=PrefixSuggestions) +@app.get("/api/library/path-mapping/suggest", response_model=PrefixSuggestions) def suggest_path_prefix() -> PrefixSuggestions: """Auto-detected `from` prefix candidates (common directory per volume), so the editor can prefill the stored prefix.""" return PrefixSuggestions.model_validate(require_adapter().path_prefix_suggestions()) -@app.get("/api/collection/path-mapping/preview", response_model=RemapPreview) +@app.get("/api/library/path-mapping/preview", response_model=RemapPreview) def preview_path_mapping( from_: str = Query("", alias="from"), to: str = Query("") ) -> RemapPreview: @@ -202,7 +192,7 @@ def preview_path_mapping( ) -@app.post("/api/collection/remap-paths", response_model=RemapResult) +@app.post("/api/library/remap-paths", response_model=RemapResult) def remap_paths(body: PathMappingInfo) -> RemapResult: """Write-back: permanently rewrite matching track LOCATIONs (and the playlist references that join to them) to the `to` prefix, then save (a @@ -268,6 +258,42 @@ def health() -> dict: return {"status": "ok", "loaded": STATE.loaded, "path": str(STATE.path) if STATE.path else None} +def _library_info() -> LibraryInfo: + """Identity of the loaded library, for display and for composing warnings.""" + caps = require_adapter().capabilities() + 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, + version=caps.version, + ) + + +@app.get("/api/platforms", response_model=list[PlatformOption]) +def platforms() -> list[PlatformOption]: + """Every DJ platform Konduktor can open — used by the picker BEFORE a + library is loaded, where capabilities are not yet available.""" + out = [] + for d in registry.drivers(): + found = [] + try: + found = d.detect() + except OSError: + pass + out.append( + PlatformOption( + platform=d.platform, + name=d.display_name, + library_label=getattr(d, "library_label", ""), + selects="file", + installed=bool(found), + ) + ) + return out + + @app.get("/api/capabilities", response_model=Capabilities) def capabilities() -> Capabilities: """What the loaded library can persist, so the UI can gate its controls.""" @@ -276,7 +302,7 @@ def capabilities() -> Capabilities: @app.get("/api/state", response_model=EditState) def state() -> EditState: - return EditState(dirty=require_adapter().dirty, nml_path=str(STATE.path)) + return EditState(dirty=require_adapter().dirty, library=_library_info()) @app.post("/api/reload") @@ -346,7 +372,17 @@ def create_playlist(body: CreatePlaylist) -> PlaylistNode: new_id = require_adapter().create_playlist( body.name.strip() or "New Playlist", body.parent_id ) - return PlaylistNode(id=new_id, name=body.name, type="PLAYLIST", uuid=new_id, count=0) + return PlaylistNode( + id=new_id, + name=body.name, + kind="playlist", + count=0, + selectable=True, + can_add_tracks=True, + can_reorder=True, + can_rename=True, + can_delete=True, + ) @app.patch("/api/playlists/{playlist_uuid}") @@ -438,20 +474,21 @@ def track_cues(track_id: str) -> TrackCues: return _cues_for(track_id) -@app.post("/api/tracks/hotcue", response_model=TrackCues) -def create_hotcue(body: SetHotcue) -> TrackCues: - """Create (or reposition + retype) the hotcue in a slot at a position.""" +@app.post("/api/tracks/cue", response_model=TrackCues) +def create_cue(body: SetCue) -> TrackCues: + """Create (or reposition + retype) the cue in a slot at a position.""" return require_adapter().set_cue( body.track_id, slot=body.slot, start_sec=body.start, - cue_type=_cue_type_name(body.type), + cue_type=body.type, + role=body.role, length_sec=body.length, name=body.name, ) -@app.post("/api/tracks/auto-hotcues", response_model=TrackCues) +@app.post("/api/tracks/cue/auto", response_model=TrackCues) def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues: """Analyze the track's audio and place structural hotcues into empty slots. @@ -490,7 +527,7 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues: return a.place_cues(body.track_id, [AutoHotcue(**s) for s in specs]) -@app.post("/api/tracks/auto-grid", response_model=TrackCues) +@app.post("/api/tracks/grid/auto", response_model=TrackCues) def auto_grid(body: AutoGridRequest) -> TrackCues: """Detect tempo + first beat and build a beatgrid: sets BPM, sets hotcue 1 (slot 0) to the first beat, and anchors the grid to that position. Octave @@ -510,16 +547,14 @@ def auto_grid(body: AutoGridRequest) -> TrackCues: return a.set_analysed_grid(body.track_id, [(first_beat, bpm)]) -@app.patch("/api/tracks/hotcue", response_model=TrackCues) -def edit_hotcue_type(body: SetHotcueType) -> TrackCues: - """Change the type of an existing hotcue (keeps its position).""" - return require_adapter().set_cue_type( - body.track_id, body.slot, _cue_type_name(body.type) - ) +@app.patch("/api/tracks/cue", response_model=TrackCues) +def edit_cue_type(body: SetCueType) -> TrackCues: + """Change the type of an existing cue (keeps its position).""" + return require_adapter().set_cue_type(body.track_id, body.slot, body.type) -@app.delete("/api/tracks/hotcue", response_model=TrackCues) -def delete_hotcue(track_id: str, slot: int) -> TrackCues: +@app.delete("/api/tracks/cue", response_model=TrackCues) +def delete_cue(track_id: str, slot: int) -> TrackCues: """Remove the hotcue in a slot.""" return require_adapter().delete_cue(track_id, slot) @@ -568,8 +603,8 @@ def remove_grid(track_id: str) -> TrackCues: return require_adapter().delete_grid(track_id) -@app.patch("/api/tracks/lock", response_model=TrackCues) -def edit_lock(body: SetLock) -> TrackCues: +@app.patch("/api/tracks/grid/lock", response_model=TrackCues) +def edit_grid_lock(body: SetGridLock) -> TrackCues: """Toggle Traktor's LOCK flag on a track.""" return require_adapter().set_grid_lock(body.track_id, body.locked) diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index e39bf56..3f4e250 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -3,6 +3,8 @@ from __future__ import annotations from pydantic import BaseModel, ConfigDict, Field +from .core.capabilities import CueRole, CueType + class CreatePlaylist(BaseModel): name: str @@ -61,18 +63,20 @@ class ReplaceGrid(BaseModel): markers: list[GridMarker] = [] # [] is equivalent to deleting the grid -class SetLock(BaseModel): +class SetGridLock(BaseModel): track_id: str locked: bool -class SetHotcue(BaseModel): +class SetCue(BaseModel): track_id: str - slot: int # 0–7 + slot: int # bank slot; capabilities.cues.hotcue_slots bounds it start: float # seconds - type: int # 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop - length: float = 0.0 # seconds (>0 for a loop hotcue) - name: str | None = None # cue label; defaults to Traktor's "n.n." when unset + type: CueType = "cue" + role: CueRole = "hotcue" + length: float = 0.0 # seconds (>0 for a loop cue) + name: str | None = None + color: str | None = None class AutoHotcuesRequest(BaseModel): @@ -84,15 +88,15 @@ class AutoGridRequest(BaseModel): track_id: str -class SetHotcueType(BaseModel): +class SetCueType(BaseModel): track_id: str slot: int - type: int + type: CueType class EditState(BaseModel): - dirty: bool # unsaved in-memory playlist changes exist - nml_path: str + dirty: bool # unsaved in-memory changes exist + library: LibraryInfo # ---- collection selection ---- @@ -103,6 +107,9 @@ class CollectionStatus(BaseModel): path: str | None = None tracks: int | None = None playlists: int | None = None + # Identity of the loaded library, so the UI can name it without parsing the + # path (a Serato library is a directory, not a file). + library: LibraryInfo | None = None class OpenCollection(BaseModel): @@ -157,6 +164,8 @@ class RemapResult(BaseModel): # one import site. The dependency runs schemas -> core, never the reverse. from .core.model import ( # noqa: E402,F401 AutoHotcue, + LibraryInfo, + PlatformOption, CuePoint, Facets, GenreCount, diff --git a/backend/test_history.py b/backend/test_history.py index 9517360..3f6df68 100644 --- a/backend/test_history.py +++ b/backend/test_history.py @@ -49,7 +49,7 @@ client = TestClient(main.app) def first_playlist(nodes): for n in nodes: - if n["type"] == "PLAYLIST": + if n["kind"] == "playlist": return n if n.get("children"): found = first_playlist(n["children"]) diff --git a/backend/test_phase3.py b/backend/test_phase3.py index 1af1255..1bf7f5c 100644 --- a/backend/test_phase3.py +++ b/backend/test_phase3.py @@ -53,7 +53,7 @@ check.failed = False print("== initial read ==") pls = client.get("/api/playlists").json() flat = lambda ns: [x for n in ns for x in [n] + flat(n.get("children", []))] -playlists = [n for n in flat(pls) if n["type"] == "PLAYLIST"] +playlists = [n for n in flat(pls) if n["kind"] == "playlist"] print(f" {len(playlists)} playlists, e.g. {[p['name'] for p in playlists[:3]]}") donor = next(p for p in playlists if p["count"] >= 5) donor_tracks = client.get(f"/api/playlists/{donor['id']}/tracks").json() @@ -64,7 +64,7 @@ collection_before = collection_span(WORK.read_bytes()) print("== create + add + reorder + rename ==") created = client.post("/api/playlists", json={"name": "Konduktor Test"}).json() -new_uuid = created["uuid"] +new_uuid = created["id"] check("create returns uuid", bool(new_uuid)) r = client.put(f"/api/playlists/{new_uuid}/entries", json={"track_ids": track_ids}) diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index 40940ab..fd8c7e4 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -23,6 +23,7 @@ import os import shutil import sys import tempfile +from types import SimpleNamespace import warnings from pathlib import Path @@ -318,9 +319,14 @@ with tempfile.TemporaryDirectory() as d: # ---- Invariant F: batch place_hotcues (Auto Hotcues) ------------------- print("== F. place_hotcues fills empty slots only, names round-trip, localized ==") with tempfile.TemporaryDirectory() as d: - from konduktor.core.model import AutoHotcue from traktor_nml_utils import TraktorCollection + # The store is the NATIVE layer, so its specs carry Traktor's own cue TYPE + # integer. The generic AutoHotcue (string types) is translated by the adapter + # before it gets here — test_traktor_adapter.py covers that path. + def spec(slot, start, name, type=0, length=0.0): + return SimpleNamespace(slot=slot, start=start, name=name, type=type, length=length) + work = Path(d) / "collection.nml" shutil.copy2(REAL, work) @@ -348,8 +354,8 @@ with tempfile.TemporaryDirectory() as d: e2 = store2._nml.collection.entry[0] now_used = {c.hotcue for c in (e2.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0} free = [s for s in range(8) if s not in now_used][:2] - specs = [AutoHotcue(slot=hand_slot, start=99.0, name="SHOULD-NOT-OVERWRITE")] - specs += [AutoHotcue(slot=s, start=30.0 + i * 10, name=f"Auto {i}") for i, s in enumerate(free)] + specs = [spec(slot=hand_slot, start=99.0, name="SHOULD-NOT-OVERWRITE")] + specs += [spec(slot=s, start=30.0 + i * 10, name=f"Auto {i}") for i, s in enumerate(free)] store2.place_hotcues(track_id, specs) store2.save() edited = work.read_bytes() diff --git a/backend/test_traktor_adapter.py b/backend/test_traktor_adapter.py index 9d730c8..d37d77d 100644 --- a/backend/test_traktor_adapter.py +++ b/backend/test_traktor_adapter.py @@ -105,21 +105,21 @@ with tempfile.TemporaryDirectory() as d: # cues — a free slot on a track with a grid, so the companion guard is clear tid2 = next( t.id for t in adapter.tracks - if t.has_grid and (cues := adapter.track_cues(t.id)) - and len({c.hotcue for c in cues.cues if c.hotcue >= 0}) < 7 + if t.grid_marker_count and (cues := adapter.track_cues(t.id)) + and len({c.slot for c in cues.cues if c.slot is not None}) < 7 ) before = adapter.track(tid2).hotcue_count - used = {c.hotcue for c in adapter.track_cues(tid2).cues if c.hotcue >= 0} + used = {c.slot for c in adapter.track_cues(tid2).cues if c.slot is not None} free = next(s for s in range(8) if s not in used) fresh = adapter.set_cue(tid2, slot=free, start_sec=12.5, cue_type="cue") - check("set_cue returns fresh cues", any(c.hotcue == free for c in fresh.cues)) + check("set_cue returns fresh cues", any(c.slot == free for c in fresh.cues)) check("hotcue count in the projection incremented", adapter.track(tid2).hotcue_count == before + 1) # cue type translation, both directions adapter.set_cue_type(tid2, free, "load") - check("generic cue type maps to Traktor's encoding", - next(c.type for c in adapter.track_cues(tid2).cues if c.hotcue == free) == 3) + check("cue type round-trips through the generic vocabulary", + next(c.type for c in adapter.track_cues(tid2).cues if c.slot == free) == "load") try: adapter.set_cue(tid2, slot=free, start_sec=1.0, cue_type="cue", role="memory") check("memory cues are refused on Traktor", False, "no error raised") @@ -132,7 +132,7 @@ with tempfile.TemporaryDirectory() as d: check("grid marker added and projected", len(adapter.track_cues(tid2).grid_markers) == grid_before + 1) check("marker count reached the track projection", - adapter.track(tid2).grid_markers == grid_before + 1) + adapter.track(tid2).grid_marker_count == grid_before + 1) # ---- analysed grid vs plain replace -------------------------------------- print("== set_analysed_grid writes Traktor's own shape, replace_grid does not ==") @@ -140,7 +140,7 @@ with tempfile.TemporaryDirectory() as d: work = Path(d) / "collection.nml" shutil.copy2(REAL, work) adapter = TraktorAdapter(work) - tid = next(t.id for t in adapter.tracks if t.has_grid) + tid = next(t.id for t in adapter.tracks if t.grid_marker_count) cues = adapter.replace_grid(tid, [(1.0, 128.0)]) check("replace_grid sets exactly the markers given", len(cues.grid_markers) == 1) @@ -179,12 +179,12 @@ with tempfile.TemporaryDirectory() as d: adapter = TraktorAdapter(work) tid = next( t.id for t in adapter.tracks - if len({c.hotcue for c in adapter.track_cues(t.id).cues if c.hotcue >= 0}) < 6 + if len({c.slot for c in adapter.track_cues(t.id).cues if c.slot is not None}) < 6 ) - used = {c.hotcue for c in adapter.track_cues(tid).cues if c.hotcue >= 0} + used = {c.slot for c in adapter.track_cues(tid).cues if c.slot is not None} free = [s for s in range(8) if s not in used][:2] adapter.place_cues(tid, [AutoHotcue(slot=free[0], start=30.0, name="Drop")]) - placed = next((c for c in adapter.track_cues(tid).cues if c.hotcue == free[0]), None) + placed = next((c for c in adapter.track_cues(tid).cues if c.slot == free[0]), None) check("batch-placed cue exists with its name", placed is not None and placed.name == "Drop") print("\nRESULT:", "FAILED" if failed else "ALL PASSED") diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index c0047aa..4b0bd55 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,6 +1,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table' +import { CapabilitiesContext } from './lib/capabilities' +import { writeHint } from './lib/platformCopy' import { api, type Track } from './api' import { DEFAULT_COLUMN_ORDER, @@ -113,6 +115,22 @@ export default function App() { } }, [columnVisibility, columnOrder, columnSizing]) + const collection = useQuery({ queryKey: ['collection'], queryFn: api.collection }) + const loaded = collection.data?.loaded ?? false + // What the loaded library can persist. Never stale within a session, and the + // app does not render until it resolves — so no first frame can offer an edit + // the adapter would reject. + const capabilities = useQuery({ + queryKey: ['capabilities'], + queryFn: api.capabilities, + enabled: loaded, + staleTime: Infinity, + }) + const save = capabilities.data?.save + // From the adapter, not a path split: a Serato library is a directory. + const libraryName = collection.data?.library?.display_name ?? null + const writeHintText = save ? writeHint(save) : 'save to write it to disk' + const notify = useCallback((kind: ToastMsg['kind'], text: string) => { setToast({ id: Date.now(), kind, text }) }, []) @@ -128,16 +146,13 @@ export default function App() { qc.invalidateQueries({ queryKey: ['playlist'] }) qc.invalidateQueries({ queryKey: ['state'] }) qc.invalidateQueries({ queryKey: ['facets'] }) - qc.invalidateQueries({ queryKey: ['stats'] }) - notify('success', `Updated ${String(field)} — Save to write to Traktor`) + notify('success', `Updated ${String(field)} — ${writeHintText}`) }) .catch((e) => onError((e as Error).message)) }, - [qc, notify, onError], + [qc, notify, onError, writeHintText], ) - const collection = useQuery({ queryKey: ['collection'], queryFn: api.collection }) - const loaded = collection.data?.loaded ?? false // NOTE: all hooks must run on every render (Rules of Hooks). Data queries are // gated with `enabled: loaded` so they don't fire before a collection is open; @@ -206,7 +221,7 @@ export default function App() { qc.invalidateQueries() // refetch everything for the newly-opened collection } - if (collection.isLoading) { + if (collection.isLoading || (loaded && !capabilities.data)) { return (
Loading… @@ -241,6 +256,7 @@ export default function App() { ) return ( +
setToast(null)} /> {menu && ( @@ -387,11 +403,12 @@ export default function App() { total={tracks.length} sourceName={isAll ? 'All Tracks' : source.name} loading={loading} - collectionName={collection.data?.path?.split('/').pop() ?? null} + collectionName={capabilities.data ? libraryName : null} onChangeCollection={() => setForcePicker(true)} />
+ ) } diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 3639b3d..e6e2a4e 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -12,20 +12,27 @@ export interface Track { mix: string | null comment: string | null bpm: number | null + /** The platform's own display string, shown verbatim: "10m", "8A", "Am". */ key: string | null + /** Camelot wheel position 1-12 + mode, parsed by the ADAPTER — notation is + * platform knowledge, not display formatting. Null when unparseable. */ + key_wheel: number | null + key_mode: 'major' | 'minor' | null rating: number playcount: number | null length: number | null bitrate: number | null + /** ISO-8601 "YYYY-MM-DD", normalised by the adapter. */ import_date: string | null last_played: string | null release_date: string | null filepath: string | null cue_count: number hotcue_count: number - has_grid: boolean - grid_markers: number // >1 = a flexible (multi-tempo) beatgrid - is_stem: boolean + /** 0 = no beatgrid, 1 = constant tempo, >1 = a flexible (multi-tempo) grid. */ + grid_marker_count: number + grid_locked: boolean + media_kind: MediaKind } export interface TrackPage { @@ -48,29 +55,21 @@ export interface Facets { total_tracks: number } -export interface Stats { - total_tracks: number - total_playlists: number - rated: number - unrated: number - missing_key: number - missing_genre: number - missing_bpm: number - no_cues: number - rating_breakdown: Record - bpm_histogram: { bucket: string; count: number }[] - top_genres: GenreCount[] -} - -export type PlaylistType = 'FOLDER' | 'PLAYLIST' | 'SMARTLIST' - export interface PlaylistNode { + /** Opaque, adapter-minted. The UI never constructs, parses or prefixes it. */ id: string name: string - type: PlaylistType - uuid: string | null + /** For choosing an icon only — every behavioural question is answered by the + * flags below, so the UI never infers what a node can do from its kind. */ + kind: PlaylistKind count: number children: PlaylistNode[] + selectable: boolean + can_add_tracks: boolean + can_reorder: boolean + can_rename: boolean + can_delete: boolean + can_contain_children: boolean } export type SortField = @@ -99,19 +98,31 @@ export interface TrackQuery { offset?: number } +export type Platform = string +export type CueRole = 'hotcue' | 'memory' +export type CueType = 'cue' | 'fade_in' | 'fade_out' | 'load' | 'loop' +export type MediaKind = 'audio' | 'stem' | 'video' +export type PlaylistKind = 'folder' | 'playlist' | 'smart' +export type TrackField = + | 'title' | 'artist' | 'album' | 'genre' | 'label' | 'remixer' + | 'producer' | 'mix' | 'release_date' | 'comment' | 'rating' + export interface CuePoint { name: string | null - type: number // 0 cue, 1 fade-in, 2 fade-out, 3 load, 4 grid, 5 loop + type: CueType + /** Memory cues have no bank slot. Only Rekordbox has them, so they are + * preserved and shown but not editable anywhere yet. */ + role: CueRole start: number // seconds length: number // seconds (>0 for loops) - hotcue: number // -1 if not a hotcue - color: string | null // "#RRGGBB" - /** - * Index of the grid marker this cue is the companion of, if any. Traktor - * pairs most grid markers with a white cue that occupies a real hotcue slot; - * it belongs to the beatgrid, so it is shown read-only and the backend - * refuses hotcue edits on it. - */ + slot: number | null // bank slot; null for a cue not in a bank + color: string | null // "#RRGGBB" as the platform stored it + /** False when the adapter refuses commands on this cue. Gate on THIS, never + * on a platform-specific reason like grid_marker. */ + editable: boolean + readonly_reason: 'beatgrid_companion' | 'platform_managed' | null + /** Index of the grid marker this cue mirrors, where the platform pairs them. + * A display hint only; null on platforms that do not. */ grid_marker: number | null } @@ -131,18 +142,74 @@ export interface TrackCues { * render and edit wrongly. */ grid_markers: GridMarker[] - locked: boolean + grid_locked: boolean cues: CuePoint[] } +export interface CueCapabilities { + hotcue_slots: number + slot_labels: 'number' | 'letter' + memory_cues: boolean + max_memory_cues: number | null + types: CueType[] + color: 'none' | 'free' | 'palette' + palette: string[] + named: boolean + loops: 'none' | 'cue_type' | 'separate_bank' + loop_slots: number | null +} + +export interface SaveCapabilities { + /** Structured facts, never finished sentences — the UI composes the wording + * (see lib/platformCopy.ts) so it stays specific without being hard-coded. */ + app_name: string + library_label: string + overwrite_risk: 'none' | 'on_exit' | 'while_running' + history: boolean +} + +export interface Capabilities { + platform: Platform + version: string | null + cues: CueCapabilities + grid: { editable: boolean; flexible: boolean; lockable: boolean } + tracks: { + rating_max: number + editable_fields: TrackField[] + media_kinds: MediaKind[] + artwork: boolean + artwork_note: string | null + } + playlists: { folders: boolean; smart: 'none' | 'read_only'; reorder: boolean } + save: SaveCapabilities +} + +export interface LibraryInfo { + platform: Platform + name: string // the DJ app's name, e.g. "Traktor" + library_label: string // e.g. "collection.nml" + path: string + display_name: string + version: string | null +} + +export interface PlatformOption { + platform: Platform + name: string + library_label: string + selects: 'file' | 'directory' + installed: boolean +} + export interface EditState { dirty: boolean - nml_path: string + library: LibraryInfo } export interface CollectionStatus { loaded: boolean path: string | null + library: LibraryInfo | null tracks: number | null playlists: number | null } @@ -259,28 +326,29 @@ function qs(params: Record): string { export const api = { // ---- collection selection ---- - collection: () => getJSON('/api/collection'), + collection: () => getJSON('/api/library'), openCollection: (path: string) => - send('POST', '/api/collection/open', { path }), - collectionOptions: () => getJSON('/api/collection/options'), + send('POST', '/api/library/open', { path }), + collectionOptions: () => getJSON('/api/library/options'), listDir: (path?: string) => getJSON(`/api/fs/list${path ? `?path=${encodeURIComponent(path)}` : ''}`), // ---- path remapping (per-collection OS-path prefix translation) ---- - getPathMapping: () => getJSON('/api/collection/path-mapping'), + getPathMapping: () => getJSON('/api/library/path-mapping'), suggestPrefix: () => - getJSON('/api/collection/path-mapping/suggest'), + getJSON('/api/library/path-mapping/suggest'), putPathMapping: (m: PathMapping) => - send('PUT', '/api/collection/path-mapping', m), + send('PUT', '/api/library/path-mapping', m), previewRemap: (from: string, to: string) => getJSON( - `/api/collection/path-mapping/preview?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`, + `/api/library/path-mapping/preview?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`, ), // Write-back: permanently rewrite matching LOCATIONs in the .nml (committed to history). remapPaths: (from: string, to: string) => - send('POST', '/api/collection/remap-paths', { from, to }), + send('POST', '/api/library/remap-paths', { from, to }), - stats: () => getJSON('/api/stats'), + capabilities: () => getJSON('/api/capabilities'), + platforms: () => getJSON('/api/platforms'), facets: () => getJSON('/api/facets'), playlists: () => getJSON('/api/playlists'), tracks: (query: TrackQuery) => @@ -292,18 +360,18 @@ export const api = { state: () => getJSON('/api/state'), createPlaylist: (name: string, parentId?: string) => send('POST', '/api/playlists', { name, parent_id: parentId ?? null }), - renamePlaylist: (uuid: string, name: string) => - send<{ status: string }>('PATCH', `/api/playlists/${uuid}`, { name }), - deletePlaylist: (uuid: string) => - send<{ status: string }>('DELETE', `/api/playlists/${uuid}`), - setEntries: (uuid: string, trackIds: string[]) => - send<{ status: string; count: number }>('PUT', `/api/playlists/${uuid}/entries`, { + renamePlaylist: (nodeId: string, name: string) => + send<{ status: string }>('PATCH', `/api/playlists/${encodeURIComponent(nodeId)}`, { name }), + deletePlaylist: (nodeId: string) => + send<{ status: string }>('DELETE', `/api/playlists/${encodeURIComponent(nodeId)}`), + setEntries: (nodeId: string, trackIds: string[]) => + send<{ status: string; count: number }>('PUT', `/api/playlists/${encodeURIComponent(nodeId)}/entries`, { track_ids: trackIds, }), - addEntries: (uuid: string, trackIds: string[]) => + addEntries: (nodeId: string, trackIds: string[]) => send<{ status: string; added: number; count: number }>( 'POST', - `/api/playlists/${uuid}/add`, + `/api/playlists/${encodeURIComponent(nodeId)}/add`, { track_ids: trackIds }, ), getPrefs: () => getJSON>('/api/prefs'), @@ -325,15 +393,15 @@ export const api = { `${API_BASE}/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`, trackCues: (trackId: string) => getJSON(`/api/tracks/cues?track_id=${encodeURIComponent(trackId)}`), - createHotcue: ( + createCue: ( trackId: string, slot: number, start: number, - type: number, + type: CueType, length = 0, name?: string, ) => - send('POST', '/api/tracks/hotcue', { + send('POST', '/api/tracks/cue', { track_id: trackId, slot, start, @@ -342,20 +410,20 @@ export const api = { name, }), // Backend analyses the audio and places structural hotcues into empty slots. - autoHotcues: (trackId: string, maxCues?: number) => - send('POST', '/api/tracks/auto-hotcues', { + autoCues: (trackId: string, maxCues?: number) => + send('POST', '/api/tracks/cue/auto', { track_id: trackId, max_cues: maxCues, }), // Backend detects tempo + first beat: sets BPM, hotcue 1, and grid anchor. autoGrid: (trackId: string) => - send('POST', '/api/tracks/auto-grid', { track_id: trackId }), - setHotcueType: (trackId: string, slot: number, type: number) => - send('PATCH', '/api/tracks/hotcue', { track_id: trackId, slot, type }), - deleteHotcue: (trackId: string, slot: number) => + send('POST', '/api/tracks/grid/auto', { track_id: trackId }), + setCueType: (trackId: string, slot: number, type: CueType) => + send('PATCH', '/api/tracks/cue', { track_id: trackId, slot, type }), + deleteCue: (trackId: string, slot: number) => send( 'DELETE', - `/api/tracks/hotcue?track_id=${encodeURIComponent(trackId)}&slot=${slot}`, + `/api/tracks/cue?track_id=${encodeURIComponent(trackId)}&slot=${slot}`, ), /** Retempo and/or move one marker. `index` is its position in grid_markers; * a move is clamped between its neighbours rather than reordering them. */ @@ -378,8 +446,8 @@ export const api = { send('PUT', '/api/tracks/grid', { track_id: trackId, markers }), deleteGrid: (trackId: string) => send('DELETE', `/api/tracks/grid?track_id=${encodeURIComponent(trackId)}`), - setLock: (trackId: string, locked: boolean) => - send('PATCH', '/api/tracks/lock', { track_id: trackId, locked }), + setGridLock: (trackId: string, locked: boolean) => + send('PATCH', '/api/tracks/grid/lock', { track_id: trackId, locked }), uploadArt: async (trackId: string, file: File) => { const fd = new FormData() fd.append('track_id', trackId) diff --git a/frontend/src/components/CollectionPicker.tsx b/frontend/src/components/CollectionPicker.tsx index 6eefce7..22686c6 100644 --- a/frontend/src/components/CollectionPicker.tsx +++ b/frontend/src/components/CollectionPicker.tsx @@ -52,6 +52,13 @@ export function CollectionPicker({ onOpened, onCancel }: Props) { 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' const listing = useQuery({ queryKey: ['fs', dir ?? '~'], queryFn: () => api.listDir(dir), @@ -76,12 +83,12 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
- Select your Traktor collection + Select your {appName} library
{mode === 'choose' ? 'Open automatically, resume your last one, or browse.' - : 'Choose a collection.nml file to open.'} + : `Choose a ${fileLabel} to open.`}
{mode === 'browse' && ( @@ -112,8 +119,8 @@ export function CollectionPicker({ onOpened, onCancel }: Props) { auto ? `${auto.label} · modified ${formatWhen(auto.modified)}` : options.isLoading - ? 'Searching for a Traktor collection…' - : 'No Traktor collection found in the default location' + ? `Searching for a ${appName} library…` + : `No ${appName} library found in the default location` } disabled={!auto} busy={open.isPending} @@ -136,7 +143,7 @@ export function CollectionPicker({ onOpened, onCancel }: Props) { setMode('browse')} /> @@ -218,7 +225,7 @@ 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 collection.nml" + placeholder={`…or paste a full path to ${fileLabel}`} 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" /> - ))} + {rating > 0 && (

BPM, key and path aren’t editable here. Changes apply in-app; click - Save to Traktor to write them to disk. - New album art is written into the file; Traktor may need a manual + {saveLabel(caps.save)} to write them to disk. + New album art is written into the file.{' '} + {caps.tracks.artwork_note} + {'' /* platform-specific footnote, supplied by the adapter */} “Import Cover Art” to refresh its own cached thumbnail.

diff --git a/frontend/src/components/HistoryPanel.tsx b/frontend/src/components/HistoryPanel.tsx index f312c2b..bd175d4 100644 --- a/frontend/src/components/HistoryPanel.tsx +++ b/frontend/src/components/HistoryPanel.tsx @@ -1,6 +1,8 @@ import { useState } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { api, type HistoryEntry } from '../api' +import { useCaps } from '../lib/capabilities' +import { restoreWarning } from '../lib/platformCopy' import type { ToastMsg } from './Toast' interface Props { @@ -37,9 +39,10 @@ function summaryChips(summary: string): string[] { * a purely-local git repo (see backend history.py); this lists them newest-first * and lets the user restore any past version (written back as a new forward save) * or wipe the entire history. Restore overwrites the collection on disk, so the - * user must close Traktor first (it rewrites the .nml on exit). + * user is warned first, in the loaded platform's own terms. */ export function HistoryPanel({ onClose, onNotify, onError }: Props) { + const caps = useCaps() const qc = useQueryClient() const history = useQuery({ queryKey: ['history'], queryFn: api.history }) const [confirmingId, setConfirmingId] = useState(null) @@ -87,8 +90,7 @@ export function HistoryPanel({ onClose, onNotify, onError }: Props) {
Version History
- Every save is a restorable version of this collection. Close Traktor before - restoring — it overwrites the collection on exit. + Every save is a restorable version of this library. {restoreWarning(caps.save)}
diff --git a/frontend/src/components/HotcueBar.tsx b/frontend/src/components/HotcueBar.tsx index b332d73..c837d0a 100644 --- a/frontend/src/components/HotcueBar.tsx +++ b/frontend/src/components/HotcueBar.tsx @@ -1,14 +1,21 @@ import type { CuePoint } from '../api' -import { contrastText, cueColor, GRID_MARKER_COLOR } from '../lib/cues' +import { contrastText, cueColor, cueGlyph } from '../lib/cues' interface Props { cues: CuePoint[] + /** Bank size, from capabilities — not every platform has eight. */ + slotCount: number + /** How a slot is labelled ("1".."8" or "A".."H"). */ + slotLabel: (slot: number) => string selectedSlot: number | null onSlotPress: (slot: number) => void onSlotRelease: (slot: number) => void } -const SLOTS = [0, 1, 2, 3, 4, 5, 6, 7] // Traktor hotcue slots → labelled 1–8 +const READONLY_LABELS: Record = { + beatgrid_companion: 'Beatgrid marker — managed by the grid controls', + platform_managed: 'Managed by the DJ app — not editable here', +} /** * The 8 hotcue slots, colour-coded by cue type when assigned (gray when empty). @@ -24,14 +31,24 @@ const SLOTS = [0, 1, 2, 3, 4, 5, 6, 7] // Traktor hotcue slots → labelled 1– * the backend refuses hotcue edits on them, and showing that up front is better * than surfacing the refusal as an error. */ -export function HotcueBar({ cues, selectedSlot, onSlotPress, onSlotRelease }: Props) { +export function HotcueBar({ + cues, + slotCount, + slotLabel, + selectedSlot, + onSlotPress, + onSlotRelease, +}: Props) { return (
- {SLOTS.map((slot) => { - const cue = cues.find((c) => c.hotcue === slot) ?? null - const isMarker = cue?.grid_marker != null - const selected = selectedSlot === slot && !isMarker - const color = cue ? (isMarker ? GRID_MARKER_COLOR : cueColor(cue)) : null + {Array.from({ length: slotCount }, (_, i) => i).map((slot) => { + const cue = cues.find((c) => c.role === 'hotcue' && c.slot === slot) ?? null + // Gate on `editable`, never on why: a platform-owned cue is a read-only + // case, not a Traktor-companion case. + const locked = cue != null && !cue.editable + const selected = selectedSlot === slot && !locked + const color = cue ? cueColor(cue) : null + const glyph = cue ? cueGlyph(cue) : '' return ( ) })} diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index 3b5a7bb..4b201c2 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -1,7 +1,9 @@ import { useEffect, useMemo, useRef, useState } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' -import { api, type GridMarker, type Track, type TrackCues } from '../api' +import { api, type CueType, type GridMarker, type Track, type TrackCues } from '../api' import { buildBeatGrid, GRID_EPS } from '../lib/beatgrid' +import { slotLabeller, useCaps } from '../lib/capabilities' +import { CUE_TYPE_LABELS } from '../lib/cues' import { analyzeWaveform, type WaveColumn } from '../lib/waveform' import { ScratchEngine } from '../lib/scratchEngine' import { PlaybackEngine } from '../lib/playbackEngine' @@ -29,13 +31,22 @@ function fmt(secs: number): string { return `${m}:${s.toString().padStart(2, '0')}` } -const CUE_TYPES: { value: number; label: string }[] = [ - { value: 0, label: 'Cue' }, - { value: 1, label: 'Fade-In' }, - { value: 2, label: 'Fade-Out' }, - { value: 3, label: 'Load' }, -] -const LOOP_TYPE = 5 +/** + * Digit key -> bank slot: 1..9 map to slots 0..8 and 0 maps to slot 10. + * + * Ten digits is the physical ceiling, so a bank larger than that simply has no + * shortcut for its tail. Returns null when the key is not a digit or the slot is + * beyond this platform's bank — an 8-slot bank behaves exactly as before. + */ +const DIGIT_RE = /^(?:Digit|Numpad)([0-9])$/ + +function slotForDigit(code: string, slotCount: number): number | null { + const m = code.match(DIGIT_RE) + if (!m) return null + const slot = m[1] === '0' ? 9 : Number(m[1]) - 1 + return slot < slotCount ? slot : null +} + const LOOP_SIZES = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 1 / 2, 1, 2, 4, 8, 16, 32] /** @@ -549,8 +560,17 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) // eslint-disable-next-line react-hooks/exhaustive-deps }, [grid]) + // ---- capability-derived ----------------------------------------------- + const caps = useCaps() + const slotCount = caps.cues.hotcue_slots + const slotLabel = slotLabeller(caps) + // Loops are a cue TYPE on some platforms and a separate bank on others; the + // dropdown only ever offers the point types. + const pointCueTypes = caps.cues.types.filter((t) => t !== 'loop') + // ---- hotcues ---------------------------------------------------------- - const hotcueAt = (slot: number) => cueData?.cues.find((c) => c.hotcue === slot) ?? null + const hotcueAt = (slot: number) => + cueData?.cues.find((c) => c.role === 'hotcue' && c.slot === slot) ?? null const applyCueEdit = (fresh: TrackCues) => { setCueData(fresh) @@ -597,10 +617,10 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) // Setting a hotcue while a loop is active stores it as a loop hotcue. if (loopActive && loopRegion) { const len = loopRegion.end - loopRegion.start - applyCueEdit(await api.createHotcue(track.id, slot, loopRegion.start, LOOP_TYPE, len)) + applyCueEdit(await api.createCue(track.id, slot, loopRegion.start, 'loop', len)) } else { const t = snapTime(playbackRef.current?.getPosition() ?? current) - applyCueEdit(await api.createHotcue(track.id, slot, t, 0)) + applyCueEdit(await api.createCue(track.id, slot, t, 'cue')) } setSelectedSlot(slot) } catch (e) { @@ -613,7 +633,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) if (!eng || !eng.ready) return getCtx() // A loop hotcue jumps to its start AND re-engages a loop of its length. - if (cue.type === LOOP_TYPE && cue.length > 0) { + if (cue.type === 'loop' && cue.length > 0) { seek(cue.start) engagLoop(cue.start, cue.start + cue.length, beatsForLoop(cue.start, cue.length)) } else { @@ -633,15 +653,15 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const runAutoHotcues = async () => { if (!track || !canAutoCue || autoBusy) return const hotcueCount = (c: TrackCues | null) => - c?.cues.filter((x) => x.hotcue >= 0).length ?? 0 - if (hotcueCount(cueData) >= 8) { - onError?.('No free hotcue slots — delete some first') + c?.cues.filter((x) => x.role === 'hotcue' && x.slot != null).length ?? 0 + if (hotcueCount(cueData) >= slotCount) { + onError?.(`No free hotcue slots (${slotCount} of ${slotCount} used) — delete some first`) return } setAutoBusy(true) try { const before = hotcueCount(cueData) - const fresh = await api.autoHotcues(track.id) + const fresh = await api.autoCues(track.id) applyCueEdit(fresh) const placed = Math.max(0, hotcueCount(fresh) - before) if (placed === 0) { @@ -656,10 +676,10 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) } } - const changeSelectedType = async (type: number) => { + const changeSelectedType = async (type: CueType) => { if (!track || selectedSlot == null) return try { - applyCueEdit(await api.setHotcueType(track.id, selectedSlot, type)) + applyCueEdit(await api.setCueType(track.id, selectedSlot, type)) } catch (e) { onError?.((e as Error).message) } @@ -668,7 +688,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const deleteSelected = async () => { if (!track || selectedSlot == null) return try { - applyCueEdit(await api.deleteHotcue(track.id, selectedSlot)) + applyCueEdit(await api.deleteCue(track.id, selectedSlot)) setSelectedSlot(null) } catch (e) { onError?.((e as Error).message) @@ -680,7 +700,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) if (!track || !existing) return // nothing to remove in an empty slot if (existing.grid_marker != null) return // beatgrid-owned: delete the marker instead try { - applyCueEdit(await api.deleteHotcue(track.id, slot)) + applyCueEdit(await api.deleteCue(track.id, slot)) if (selectedSlot === slot) setSelectedSlot(null) } catch (e) { onError?.((e as Error).message) @@ -757,7 +777,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const toggleLock = async () => { if (!track) return try { - applyCueEdit(await api.setLock(track.id, !cueData?.locked)) + applyCueEdit(await api.setGridLock(track.id, !cueData?.grid_locked)) } catch (e) { onError?.((e as Error).message) } @@ -799,6 +819,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) beatJump, prevMarker, nextMarker, + slotCount, }) shortcutsRef.current = { toggle, @@ -810,6 +831,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) beatJump, prevMarker, nextMarker, + slotCount, } useEffect(() => { const onKey = (e: KeyboardEvent) => { @@ -840,10 +862,9 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) else shortcutsRef.current.beatJump(1) return } - const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/) - if (digit) { + const slot = slotForDigit(e.code, shortcutsRef.current.slotCount) + if (slot != null) { e.preventDefault() - const slot = Number(digit[1]) - 1 if (e.shiftKey) void shortcutsRef.current.deleteHotcueSlot(slot) else void shortcutsRef.current.onSlotPress(slot) } @@ -851,8 +872,8 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) // keyup ends a held hotcue's momentary preview (release). const onKeyRelease = (e: KeyboardEvent) => { if (e.code === 'KeyC') shortcutsRef.current.onCueRelease() - const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/) - if (digit) shortcutsRef.current.onSlotRelease(Number(digit[1]) - 1) + const slot = slotForDigit(e.code, shortcutsRef.current.slotCount) + if (slot != null) shortcutsRef.current.onSlotRelease(slot) } window.addEventListener('keydown', onKey) window.addEventListener('keyup', onKeyRelease) @@ -893,7 +914,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) markerStart={activeMarker?.start ?? null} atMarker={atMarker} beforeFirst={beforeFirstMarker} - locked={cueData?.locked ?? false} + locked={cueData?.grid_locked ?? false} canReset={originalGridRef.current != null} onSetBpm={setBpm} onNudgeBpm={nudgeBpm} @@ -1034,24 +1055,32 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
- {selectedCue && selectedCue.type === LOOP_TYPE ? ( + {selectedCue && selectedCue.type === 'loop' ? ( Loop + ) : pointCueTypes.length < 2 ? ( + // One point type means there is nothing to choose between — + // show it rather than a dropdown that cannot change anything. + + {selectedCue ? CUE_TYPE_LABELS[selectedCue.type] : '—'} + ) : ( diff --git a/frontend/src/components/RatingStars.tsx b/frontend/src/components/RatingStars.tsx index 4f17cfd..cdee86d 100644 --- a/frontend/src/components/RatingStars.tsx +++ b/frontend/src/components/RatingStars.tsx @@ -2,22 +2,25 @@ import { useState } from 'react' interface Props { value: number - /** When provided, the stars become clickable to set the rating (0–5). */ + /** Scale length, from capabilities.tracks.rating_max. */ + max?: number + /** When provided, the stars become clickable to set the rating. */ onChange?: (value: number) => void } -// Compact 5-star rating. Read-only by default (shows a dash when unrated). When -// `onChange` is given it's interactive: always shows five stars — hollow (☆) up -// to the rating, solid gold (★) below it — with hover preview. Clicking a star -// sets that rating; clicking the current top star again clears it to 0. -export function RatingStars({ value, onChange }: Props) { +// Compact star rating. Read-only by default (shows a dash when unrated). When +// `onChange` is given it's interactive: hollow (☆) above the rating, solid gold +// (★) up to it, with hover preview. Clicking a star sets that rating; clicking +// the current top star again clears it to 0. +export function RatingStars({ value, max = 5, onChange }: Props) { const [hover, setHover] = useState(0) + const stars = Array.from({ length: max }, (_, i) => i + 1) if (!onChange) { if (!value) return — return ( - - {[1, 2, 3, 4, 5].map((i) => ( + + {stars.map((i) => ( {i <= value ? '★' : '☆'} @@ -28,8 +31,8 @@ export function RatingStars({ value, onChange }: Props) { const shown = hover || value return ( - - {[1, 2, 3, 4, 5].map((i) => ( + + {stars.map((i) => (