Switched to more generic wording

This commit is contained in:
patben8 committed 2026-09-17 22:24:56 +02:00
1 parent c9e85bbdb5
commit 6e24f5ef1d
29 files changed
+790 -313

No files matched your search

+22 -4
View File
@@ -73,8 +73,20 @@ Two independent apps that talk over HTTP:
`KONDUKTOR_NML` auto-loads on startup (dev/tests). `KONDUKTOR_NML` auto-loads on startup (dev/tests).
- **`frontend/`** — React + TypeScript + Vite. A dark, virtualized track - **`frontend/`** — React + TypeScript + Vite. A dark, virtualized track
explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx). explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx).
- `api.ts` — typed client + all API types (keep in sync with backend - `api.ts` — typed client + all API types. **Generic, not Traktor-shaped**:
`schemas.py`). 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 / - `components/` — `CollectionPicker` (startup chooser: Automatic / Open last /
Find manually — the last reveals a file browser), `Sidebar` (playlist tree + Find manually — the last reveals a file browser), `Sidebar` (playlist tree +
create/rename/delete), `SaveBar`, `Toolbar` (search/filters + `ColumnsMenu`), create/rename/delete), `SaveBar`, `Toolbar` (search/filters + `ColumnsMenu`),
@@ -113,6 +125,12 @@ Two independent apps that talk over HTTP:
analysis + paint), `beatgrid.ts` (the marker-list beat math — every analysis + paint), `beatgrid.ts` (the marker-list beat math — every
beat/bar/snap/jump calculation goes through it), `cues.ts` (draw beat/bar/snap/jump calculation goes through it), `cues.ts` (draw
cues/loop/beatgrid/cue-point). See "Prep engine" below. cues/loop/beatgrid/cue-point). See "Prep engine" below.
- 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 - `lib/trackColumns.tsx` — single source of truth for the library table's
columns (defs, default widths/visibility/order, the Columns-menu list, the columns (defs, default widths/visibility/order, the Columns-menu list, the
inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation). inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation).
@@ -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 commands, piecewise beat math, playhead-derived marker editing). Step 1 of the
multi-platform plan in `.claude/discussions/`. multi-platform plan in `.claude/discussions/`.
- ✅ Generic model + adapter interface (Traktor as the only adapter) — step 2 of - ✅ 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 the multi-platform plan. Backend, wire format and UI are all generic; nothing
Traktor-shaped (cue type integers, 8 hard-coded hotcue slots) and are next. above `adapters/traktor/` knows what Traktor is.
- ⬜ Rekordbox adapter; ⬜ Serato adapter; ⬜ export/conversion - ⬜ Rekordbox adapter; ⬜ Serato adapter; ⬜ export/conversion
- ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging - ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging
+14 -6
View File
@@ -13,6 +13,7 @@ from __future__ import annotations
from contextlib import contextmanager from contextlib import contextmanager
from pathlib import Path from pathlib import Path
from types import SimpleNamespace
from ...core.adapter import InvalidCommand, NotFound, Unsupported from ...core.adapter import InvalidCommand, NotFound, Unsupported
from ...core.capabilities import Capabilities from ...core.capabilities import Capabilities
@@ -21,13 +22,10 @@ from ...core.pathmap import PathMapping
from ...core.query import TrackIndex from ...core.query import TrackIndex
from . import capabilities as caps from . import capabilities as caps
from . import projection from . import projection
from .cue_types import CUE_TYPE_TO_NATIVE
from .store import PlaylistError, TraktorStore 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: class TraktorAdapter:
@@ -186,8 +184,18 @@ class TraktorAdapter:
return self._refresh(track_id) return self._refresh(track_id)
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: 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(): 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) return self._refresh(track_id)
# ---- beatgrid --------------------------------------------------------- # ---- beatgrid ---------------------------------------------------------
@@ -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()}
@@ -5,8 +5,49 @@ Everything above this file sees generic types exclusively.
""" """
from __future__ import annotations from __future__ import annotations
import re
from ...core.model import CuePoint, GridMarker, Track, TrackCues from ...core.model import CuePoint, GridMarker, Track, TrackCues
from . import beatgrid 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: 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 1 for c in cues if c.hotcue is not None and c.hotcue >= 0
) )
markers = beatgrid.grid_markers(e) markers = beatgrid.grid_markers(e)
wheel, mode = parse_key(info.key if info else None)
return Track( return Track(
id=primary_key(loc) if loc else (e.title or ""), id=primary_key(loc) if loc else (e.title or ""),
artist=e.artist, artist=e.artist,
@@ -51,19 +93,21 @@ def to_track(e) -> Track:
comment=info.comment if info else None, comment=info.comment if info else None,
bpm=beatgrid.effective_bpm(e), bpm=beatgrid.effective_bpm(e),
key=info.key if info else None, key=info.key if info else None,
key_wheel=wheel,
key_mode=mode,
rating=_rating_stars(info.ranking if info else None), rating=_rating_stars(info.ranking if info else None),
playcount=info.playcount if info else None, playcount=info.playcount if info else None,
length=info.playtime if info else None, length=info.playtime if info else None,
bitrate=info.bitrate if info else None, bitrate=info.bitrate if info else None,
import_date=info.import_date if info else None, import_date=iso_date(info.import_date if info else None),
last_played=info.last_played if info else None, last_played=iso_date(info.last_played if info else None),
release_date=info.release_date if info else None, release_date=iso_date(info.release_date if info else None),
filepath=_display_path(loc) if loc else None, filepath=_display_path(loc) if loc else None,
cue_count=len(cues), cue_count=len(cues),
hotcue_count=hotcues, hotcue_count=hotcues,
has_grid=bool(markers), grid_marker_count=len(markers),
grid_markers=len(markers), grid_locked=bool(e.lock),
is_stem=getattr(e, "stems", None) is not None, 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) for i, m in enumerate(markers)
] ]
cues = [ 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( CuePoint(
name=c.name, name=c.name,
type=c.type if c.type is not None else 0, # 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, start=(c.start or 0.0) / 1000.0,
length=(c.len or 0.0) / 1000.0, length=(c.len or 0.0) / 1000.0,
hotcue=c.hotcue if c.hotcue is not None else -1, slot=slot,
color=c.color, color=c.color,
grid_marker=marker_of.get(id(c)), # 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( return TrackCues(
grid_markers=grid_markers, locked=bool(entry.lock), cues=cues grid_markers=grid_markers, grid_locked=bool(entry.lock), cues=cues
) )
+10 -4
View File
@@ -154,20 +154,26 @@ class TraktorStore:
return PlaylistNode( return PlaylistNode(
id=pl.uuid if pl and pl.uuid else name, id=pl.uuid if pl and pl.uuid else name,
name=name, name=name,
type="PLAYLIST", kind="playlist",
uuid=pl.uuid if pl else None,
count=len(keys), 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: if ntype == "SMARTLIST" or node.smartplaylist is not None:
# Rule-based, so it has no static entry list to show or edit.
return PlaylistNode( 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] path = parent_path + [name]
return PlaylistNode( return PlaylistNode(
id="fld:" + "/".join(path), id="fld:" + "/".join(path),
name=name, name=name,
type="FOLDER", kind="folder",
children=[self._to_model(c, path) for c in self._children(node)], children=[self._to_model(c, path) for c in self._children(node)],
can_contain_children=True,
) )
@staticmethod @staticmethod
+72 -19
View File
@@ -9,13 +9,17 @@ is the shape a batch cue placement takes in generic terms.
""" """
from __future__ import annotations from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field from pydantic import BaseModel, ConfigDict, Field
from .capabilities import CueRole, CueType, MediaKind, PlaylistKind
class Track(BaseModel): 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: "<VOLUME><DIR><FILE>", used to join playlist entries id: str # the adapter's stable track key; opaque above the adapter
artist: str | None = None artist: str | None = None
title: str | None = None title: str | None = None
album: str | None = None album: str | None = None
@@ -26,20 +30,27 @@ class Track(BaseModel):
mix: str | None = None mix: str | None = None
comment: str | None = None comment: str | None = None
bpm: float | 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) rating: int = 0 # 0-5 stars (derived from RANKING/51)
playcount: int | None = None playcount: int | None = None
length: int | None = None # seconds length: int | None = None # seconds
bitrate: int | None = None bitrate: int | None = None
# ISO-8601 "YYYY-MM-DD", normalised by the adapter.
import_date: str | None = None import_date: str | None = None
last_played: str | None = None last_played: str | None = None
release_date: str | None = None release_date: str | None = None
filepath: str | None = None # human-readable OS path filepath: str | None = None # human-readable OS path
cue_count: int = 0 cue_count: int = 0
hotcue_count: int = 0 hotcue_count: int = 0
has_grid: bool = False # 0 = no beatgrid, 1 = constant tempo, >1 = a flexible (multi-tempo) grid.
grid_markers: int = 0 # >1 = a flexible (multi-tempo) beatgrid grid_marker_count: int = 0
is_stem: bool = False # a Stem file (<STEMS> child) vs a normal audio track grid_locked: bool = False
media_kind: MediaKind = "audio"
class TrackPage(BaseModel): class TrackPage(BaseModel):
@@ -79,15 +90,27 @@ class Stats(BaseModel):
class PlaylistNode(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-<n>" / "fld-<n>") `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 name: str
type: str # "FOLDER" | "PLAYLIST" | "SMARTLIST" kind: PlaylistKind = "playlist"
uuid: str | None = None
count: int = 0 # track count (for playlists) count: int = 0 # track count (for playlists)
children: list["PlaylistNode"] = [] 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() PlaylistNode.model_rebuild()
@@ -97,13 +120,20 @@ PlaylistNode.model_rebuild()
class CuePoint(BaseModel): class CuePoint(BaseModel):
name: str | None = None 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 start: float # seconds
length: float # seconds (>0 for loops) length: float # seconds (>0 for loops)
hotcue: int # -1 if not assigned to a hotcue slot slot: int | None = None # bank slot; None for a cue not in a bank
color: str | None = None # "#RRGGBB" if set color: str | None = None # "#RRGGBB" as the platform stored it
# Index of the grid marker this cue is the companion of, if any. Such a cue # False when the adapter refuses commands on this cue — the UI gates on THIS
# holds a real hotcue slot but belongs to the beatgrid and is not editable. # 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 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" # tempo. There is deliberately no scalar bpm/anchor here: a single "the BPM"
# is what made flexible grids render and edit wrongly. # is what made flexible grids render and edit wrongly.
grid_markers: list[GridMarker] = [] grid_markers: list[GridMarker] = []
locked: bool = False # Traktor LOCK flag grid_locked: bool = False
cues: list[CuePoint] = [] # cue/loop markers (grid markers themselves excluded) cues: list[CuePoint] = [] # cue/loop markers (grid markers themselves excluded)
class AutoHotcue(BaseModel): class AutoHotcue(BaseModel):
slot: int # 0–7 """One cue in a batch placement (Auto Hotcues)."""
slot: int
start: float # seconds start: float # seconds
name: str | None = None # positional label (e.g. "Drop") name: str | None = None # positional label (e.g. "Drop")
type: int = 0 # plain cue type: CueType = "cue"
length: float = 0.0 # seconds (>0 for a loop hotcue) 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): class RemapSample(BaseModel):
+77 -42
View File
@@ -14,7 +14,6 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse from fastapi.responses import FileResponse, JSONResponse
from . import __version__, history, prefs from . import __version__, history, prefs
from .adapters.traktor.adapter import NATIVE_TO_CUE_TYPE
from .adapters.traktor.discovery import describe from .adapters.traktor.discovery import describe
from .app_state import STATE from .app_state import STATE
from .core import auto_hotcues as ah from .core import auto_hotcues as ah
@@ -38,6 +37,8 @@ from .schemas import (
CollectionStatus, CollectionStatus,
CreatePlaylist, CreatePlaylist,
EditState, EditState,
LibraryInfo,
PlatformOption,
EditTrack, EditTrack,
Facets, Facets,
FileTagOutcome, FileTagOutcome,
@@ -56,9 +57,9 @@ from .schemas import (
RenamePlaylist, RenamePlaylist,
SaveResult, SaveResult,
SetEntries, SetEntries,
SetHotcue, SetCue,
SetHotcueType, SetCueType,
SetLock, SetGridLock,
Stats, Stats,
Track, Track,
TrackCues, 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: def require_adapter() -> LibraryAdapter:
"""The loaded library, or a 409. Routes talk to this and nothing else.""" """The loaded library, or a 409. Routes talk to this and nothing else."""
if not STATE.loaded: if not STATE.loaded:
@@ -118,7 +107,7 @@ def _adapter_error(_request, exc: AdapterError):
# ---- collection selection --------------------------------------------- # ---- collection selection ---------------------------------------------
@app.get("/api/collection", response_model=CollectionStatus) @app.get("/api/library", response_model=CollectionStatus)
def collection_status() -> CollectionStatus: def collection_status() -> CollectionStatus:
if not STATE.loaded: if not STATE.loaded:
return CollectionStatus(loaded=False) return CollectionStatus(loaded=False)
@@ -127,10 +116,11 @@ def collection_status() -> CollectionStatus:
path=str(STATE.path), path=str(STATE.path),
tracks=len(require_adapter().tracks), tracks=len(require_adapter().tracks),
playlists=require_adapter().playlist_count(), 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: def open_collection(body: OpenCollection) -> CollectionStatus:
path = Path(body.path).expanduser() path = Path(body.path).expanduser()
if not path.exists() or not path.is_file(): if not path.exists() or not path.is_file():
@@ -145,7 +135,7 @@ def open_collection(body: OpenCollection) -> CollectionStatus:
return collection_status() return collection_status()
@app.get("/api/collection/options", response_model=CollectionOptions) @app.get("/api/library/options", response_model=CollectionOptions)
def collection_options() -> CollectionOptions: def collection_options() -> CollectionOptions:
"""Startup shortcuts for the picker: the best auto-detected Traktor """Startup shortcuts for the picker: the best auto-detected Traktor
collection and the last one opened (may no longer exist → exists=False).""" 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) 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: def get_path_mapping() -> PathMappingInfo:
"""The current collection's saved OS-path remapping (blank if none).""" """The current collection's saved OS-path remapping (blank if none)."""
require_adapter() require_adapter()
@@ -168,7 +158,7 @@ def get_path_mapping() -> PathMappingInfo:
return 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: def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo:
"""Set (or, with blank prefixes, clear) the current collection's remapping. """Set (or, with blank prefixes, clear) the current collection's remapping.
Persists to userprefs AND updates the live store so playback/analysis 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: def suggest_path_prefix() -> PrefixSuggestions:
"""Auto-detected `from` prefix candidates (common directory per volume), """Auto-detected `from` prefix candidates (common directory per volume),
so the editor can prefill the stored prefix.""" so the editor can prefill the stored prefix."""
return PrefixSuggestions.model_validate(require_adapter().path_prefix_suggestions()) 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( def preview_path_mapping(
from_: str = Query("", alias="from"), to: str = Query("") from_: str = Query("", alias="from"), to: str = Query("")
) -> RemapPreview: ) -> 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: def remap_paths(body: PathMappingInfo) -> RemapResult:
"""Write-back: permanently rewrite matching track LOCATIONs (and the """Write-back: permanently rewrite matching track LOCATIONs (and the
playlist references that join to them) to the `to` prefix, then save (a 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} 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) @app.get("/api/capabilities", response_model=Capabilities)
def capabilities() -> Capabilities: def capabilities() -> Capabilities:
"""What the loaded library can persist, so the UI can gate its controls.""" """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) @app.get("/api/state", response_model=EditState)
def state() -> 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") @app.post("/api/reload")
@@ -346,7 +372,17 @@ def create_playlist(body: CreatePlaylist) -> PlaylistNode:
new_id = require_adapter().create_playlist( new_id = require_adapter().create_playlist(
body.name.strip() or "New Playlist", body.parent_id 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}") @app.patch("/api/playlists/{playlist_uuid}")
@@ -438,20 +474,21 @@ def track_cues(track_id: str) -> TrackCues:
return _cues_for(track_id) return _cues_for(track_id)
@app.post("/api/tracks/hotcue", response_model=TrackCues) @app.post("/api/tracks/cue", response_model=TrackCues)
def create_hotcue(body: SetHotcue) -> TrackCues: def create_cue(body: SetCue) -> TrackCues:
"""Create (or reposition + retype) the hotcue in a slot at a position.""" """Create (or reposition + retype) the cue in a slot at a position."""
return require_adapter().set_cue( return require_adapter().set_cue(
body.track_id, body.track_id,
slot=body.slot, slot=body.slot,
start_sec=body.start, start_sec=body.start,
cue_type=_cue_type_name(body.type), cue_type=body.type,
role=body.role,
length_sec=body.length, length_sec=body.length,
name=body.name, 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: def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues:
"""Analyze the track's audio and place structural hotcues into empty slots. """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]) 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: def auto_grid(body: AutoGridRequest) -> TrackCues:
"""Detect tempo + first beat and build a beatgrid: sets BPM, sets hotcue 1 """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 (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)]) return a.set_analysed_grid(body.track_id, [(first_beat, bpm)])
@app.patch("/api/tracks/hotcue", response_model=TrackCues) @app.patch("/api/tracks/cue", response_model=TrackCues)
def edit_hotcue_type(body: SetHotcueType) -> TrackCues: def edit_cue_type(body: SetCueType) -> TrackCues:
"""Change the type of an existing hotcue (keeps its position).""" """Change the type of an existing cue (keeps its position)."""
return require_adapter().set_cue_type( return require_adapter().set_cue_type(body.track_id, body.slot, body.type)
body.track_id, body.slot, _cue_type_name(body.type)
)
@app.delete("/api/tracks/hotcue", response_model=TrackCues) @app.delete("/api/tracks/cue", response_model=TrackCues)
def delete_hotcue(track_id: str, slot: int) -> TrackCues: def delete_cue(track_id: str, slot: int) -> TrackCues:
"""Remove the hotcue in a slot.""" """Remove the hotcue in a slot."""
return require_adapter().delete_cue(track_id, 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) return require_adapter().delete_grid(track_id)
@app.patch("/api/tracks/lock", response_model=TrackCues) @app.patch("/api/tracks/grid/lock", response_model=TrackCues)
def edit_lock(body: SetLock) -> TrackCues: def edit_grid_lock(body: SetGridLock) -> TrackCues:
"""Toggle Traktor's LOCK flag on a track.""" """Toggle Traktor's LOCK flag on a track."""
return require_adapter().set_grid_lock(body.track_id, body.locked) return require_adapter().set_grid_lock(body.track_id, body.locked)
+19 -10
View File
@@ -3,6 +3,8 @@ from __future__ import annotations
from pydantic import BaseModel, ConfigDict, Field from pydantic import BaseModel, ConfigDict, Field
from .core.capabilities import CueRole, CueType
class CreatePlaylist(BaseModel): class CreatePlaylist(BaseModel):
name: str name: str
@@ -61,18 +63,20 @@ class ReplaceGrid(BaseModel):
markers: list[GridMarker] = [] # [] is equivalent to deleting the grid markers: list[GridMarker] = [] # [] is equivalent to deleting the grid
class SetLock(BaseModel): class SetGridLock(BaseModel):
track_id: str track_id: str
locked: bool locked: bool
class SetHotcue(BaseModel): class SetCue(BaseModel):
track_id: str track_id: str
slot: int # 0–7 slot: int # bank slot; capabilities.cues.hotcue_slots bounds it
start: float # seconds start: float # seconds
type: int # 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop type: CueType = "cue"
length: float = 0.0 # seconds (>0 for a loop hotcue) role: CueRole = "hotcue"
name: str | None = None # cue label; defaults to Traktor's "n.n." when unset length: float = 0.0 # seconds (>0 for a loop cue)
name: str | None = None
color: str | None = None
class AutoHotcuesRequest(BaseModel): class AutoHotcuesRequest(BaseModel):
@@ -84,15 +88,15 @@ class AutoGridRequest(BaseModel):
track_id: str track_id: str
class SetHotcueType(BaseModel): class SetCueType(BaseModel):
track_id: str track_id: str
slot: int slot: int
type: int type: CueType
class EditState(BaseModel): class EditState(BaseModel):
dirty: bool # unsaved in-memory playlist changes exist dirty: bool # unsaved in-memory changes exist
nml_path: str library: LibraryInfo
# ---- collection selection ---- # ---- collection selection ----
@@ -103,6 +107,9 @@ class CollectionStatus(BaseModel):
path: str | None = None path: str | None = None
tracks: int | None = None tracks: int | None = None
playlists: 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): class OpenCollection(BaseModel):
@@ -157,6 +164,8 @@ class RemapResult(BaseModel):
# one import site. The dependency runs schemas -> core, never the reverse. # one import site. The dependency runs schemas -> core, never the reverse.
from .core.model import ( # noqa: E402,F401 from .core.model import ( # noqa: E402,F401
AutoHotcue, AutoHotcue,
LibraryInfo,
PlatformOption,
CuePoint, CuePoint,
Facets, Facets,
GenreCount, GenreCount,
+1 -1
View File
@@ -49,7 +49,7 @@ client = TestClient(main.app)
def first_playlist(nodes): def first_playlist(nodes):
for n in nodes: for n in nodes:
if n["type"] == "PLAYLIST": if n["kind"] == "playlist":
return n return n
if n.get("children"): if n.get("children"):
found = first_playlist(n["children"]) found = first_playlist(n["children"])
+2 -2
View File
@@ -53,7 +53,7 @@ check.failed = False
print("== initial read ==") print("== initial read ==")
pls = client.get("/api/playlists").json() pls = client.get("/api/playlists").json()
flat = lambda ns: [x for n in ns for x in [n] + flat(n.get("children", []))] 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]]}") 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 = next(p for p in playlists if p["count"] >= 5)
donor_tracks = client.get(f"/api/playlists/{donor['id']}/tracks").json() 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 ==") print("== create + add + reorder + rename ==")
created = client.post("/api/playlists", json={"name": "Konduktor Test"}).json() 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)) check("create returns uuid", bool(new_uuid))
r = client.put(f"/api/playlists/{new_uuid}/entries", json={"track_ids": track_ids}) r = client.put(f"/api/playlists/{new_uuid}/entries", json={"track_ids": track_ids})
+9 -3
View File
@@ -23,6 +23,7 @@ import os
import shutil import shutil
import sys import sys
import tempfile import tempfile
from types import SimpleNamespace
import warnings import warnings
from pathlib import Path from pathlib import Path
@@ -318,9 +319,14 @@ with tempfile.TemporaryDirectory() as d:
# ---- Invariant F: batch place_hotcues (Auto Hotcues) ------------------- # ---- Invariant F: batch place_hotcues (Auto Hotcues) -------------------
print("== F. place_hotcues fills empty slots only, names round-trip, localized ==") print("== F. place_hotcues fills empty slots only, names round-trip, localized ==")
with tempfile.TemporaryDirectory() as d: with tempfile.TemporaryDirectory() as d:
from konduktor.core.model import AutoHotcue
from traktor_nml_utils import TraktorCollection 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" work = Path(d) / "collection.nml"
shutil.copy2(REAL, work) shutil.copy2(REAL, work)
@@ -348,8 +354,8 @@ with tempfile.TemporaryDirectory() as d:
e2 = store2._nml.collection.entry[0] 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} 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] 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 = [spec(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=s, start=30.0 + i * 10, name=f"Auto {i}") for i, s in enumerate(free)]
store2.place_hotcues(track_id, specs) store2.place_hotcues(track_id, specs)
store2.save() store2.save()
edited = work.read_bytes() edited = work.read_bytes()
+11 -11
View File
@@ -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 # cues — a free slot on a track with a grid, so the companion guard is clear
tid2 = next( tid2 = next(
t.id for t in adapter.tracks t.id for t in adapter.tracks
if t.has_grid and (cues := adapter.track_cues(t.id)) if t.grid_marker_count and (cues := adapter.track_cues(t.id))
and len({c.hotcue for c in cues.cues if c.hotcue >= 0}) < 7 and len({c.slot for c in cues.cues if c.slot is not None}) < 7
) )
before = adapter.track(tid2).hotcue_count 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) 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") 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", check("hotcue count in the projection incremented",
adapter.track(tid2).hotcue_count == before + 1) adapter.track(tid2).hotcue_count == before + 1)
# cue type translation, both directions # cue type translation, both directions
adapter.set_cue_type(tid2, free, "load") adapter.set_cue_type(tid2, free, "load")
check("generic cue type maps to Traktor's encoding", check("cue type round-trips through the generic vocabulary",
next(c.type for c in adapter.track_cues(tid2).cues if c.hotcue == free) == 3) next(c.type for c in adapter.track_cues(tid2).cues if c.slot == free) == "load")
try: try:
adapter.set_cue(tid2, slot=free, start_sec=1.0, cue_type="cue", role="memory") 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") 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", check("grid marker added and projected",
len(adapter.track_cues(tid2).grid_markers) == grid_before + 1) len(adapter.track_cues(tid2).grid_markers) == grid_before + 1)
check("marker count reached the track projection", 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 -------------------------------------- # ---- analysed grid vs plain replace --------------------------------------
print("== set_analysed_grid writes Traktor's own shape, replace_grid does not ==") 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" work = Path(d) / "collection.nml"
shutil.copy2(REAL, work) shutil.copy2(REAL, work)
adapter = TraktorAdapter(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)]) cues = adapter.replace_grid(tid, [(1.0, 128.0)])
check("replace_grid sets exactly the markers given", len(cues.grid_markers) == 1) 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) adapter = TraktorAdapter(work)
tid = next( tid = next(
t.id for t in adapter.tracks 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] 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")]) 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") check("batch-placed cue exists with its name", placed is not None and placed.name == "Drop")
print("\nRESULT:", "FAILED" if failed else "ALL PASSED") print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
+24 -7
View File
@@ -1,6 +1,8 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query' import { useQuery, useQueryClient } from '@tanstack/react-query'
import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table' 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 { api, type Track } from './api'
import { import {
DEFAULT_COLUMN_ORDER, DEFAULT_COLUMN_ORDER,
@@ -113,6 +115,22 @@ export default function App() {
} }
}, [columnVisibility, columnOrder, columnSizing]) }, [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) => { const notify = useCallback((kind: ToastMsg['kind'], text: string) => {
setToast({ id: Date.now(), kind, text }) setToast({ id: Date.now(), kind, text })
}, []) }, [])
@@ -128,16 +146,13 @@ export default function App() {
qc.invalidateQueries({ queryKey: ['playlist'] }) qc.invalidateQueries({ queryKey: ['playlist'] })
qc.invalidateQueries({ queryKey: ['state'] }) qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['facets'] }) qc.invalidateQueries({ queryKey: ['facets'] })
qc.invalidateQueries({ queryKey: ['stats'] }) notify('success', `Updated ${String(field)} — ${writeHintText}`)
notify('success', `Updated ${String(field)} — Save to write to Traktor`)
}) })
.catch((e) => onError((e as Error).message)) .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 // 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; // 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 qc.invalidateQueries() // refetch everything for the newly-opened collection
} }
if (collection.isLoading) { if (collection.isLoading || (loaded && !capabilities.data)) {
return ( return (
<div className="flex h-screen w-screen items-center justify-center bg-ink-950 text-muted"> <div className="flex h-screen w-screen items-center justify-center bg-ink-950 text-muted">
Loading… Loading…
@@ -241,6 +256,7 @@ export default function App() {
) )
return ( return (
<CapabilitiesContext.Provider value={capabilities.data!}>
<div className="flex h-screen w-screen flex-col overflow-hidden bg-ink-950"> <div className="flex h-screen w-screen flex-col overflow-hidden bg-ink-950">
<Toast toast={toast} onClose={() => setToast(null)} /> <Toast toast={toast} onClose={() => setToast(null)} />
{menu && ( {menu && (
@@ -387,11 +403,12 @@ export default function App() {
total={tracks.length} total={tracks.length}
sourceName={isAll ? 'All Tracks' : source.name} sourceName={isAll ? 'All Tracks' : source.name}
loading={loading} loading={loading}
collectionName={collection.data?.path?.split('/').pop() ?? null} collectionName={capabilities.data ? libraryName : null}
onChangeCollection={() => setForcePicker(true)} onChangeCollection={() => setForcePicker(true)}
/> />
</main> </main>
</div> </div>
</div> </div>
</CapabilitiesContext.Provider>
) )
} }
+129 -61
View File
@@ -12,20 +12,27 @@ export interface Track {
mix: string | null mix: string | null
comment: string | null comment: string | null
bpm: number | null bpm: number | null
/** The platform's own display string, shown verbatim: "10m", "8A", "Am". */
key: string | null 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 rating: number
playcount: number | null playcount: number | null
length: number | null length: number | null
bitrate: number | null bitrate: number | null
/** ISO-8601 "YYYY-MM-DD", normalised by the adapter. */
import_date: string | null import_date: string | null
last_played: string | null last_played: string | null
release_date: string | null release_date: string | null
filepath: string | null filepath: string | null
cue_count: number cue_count: number
hotcue_count: number hotcue_count: number
has_grid: boolean /** 0 = no beatgrid, 1 = constant tempo, >1 = a flexible (multi-tempo) grid. */
grid_markers: number // >1 = a flexible (multi-tempo) beatgrid grid_marker_count: number
is_stem: boolean grid_locked: boolean
media_kind: MediaKind
} }
export interface TrackPage { export interface TrackPage {
@@ -48,29 +55,21 @@ export interface Facets {
total_tracks: number 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<string, number>
bpm_histogram: { bucket: string; count: number }[]
top_genres: GenreCount[]
}
export type PlaylistType = 'FOLDER' | 'PLAYLIST' | 'SMARTLIST'
export interface PlaylistNode { export interface PlaylistNode {
/** Opaque, adapter-minted. The UI never constructs, parses or prefixes it. */
id: string id: string
name: string name: string
type: PlaylistType /** For choosing an icon only — every behavioural question is answered by the
uuid: string | null * flags below, so the UI never infers what a node can do from its kind. */
kind: PlaylistKind
count: number count: number
children: PlaylistNode[] children: PlaylistNode[]
selectable: boolean
can_add_tracks: boolean
can_reorder: boolean
can_rename: boolean
can_delete: boolean
can_contain_children: boolean
} }
export type SortField = export type SortField =
@@ -99,19 +98,31 @@ export interface TrackQuery {
offset?: number 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 { export interface CuePoint {
name: string | null 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 start: number // seconds
length: number // seconds (>0 for loops) length: number // seconds (>0 for loops)
hotcue: number // -1 if not a hotcue slot: number | null // bank slot; null for a cue not in a bank
color: string | null // "#RRGGBB" color: string | null // "#RRGGBB" as the platform stored it
/** /** False when the adapter refuses commands on this cue. Gate on THIS, never
* Index of the grid marker this cue is the companion of, if any. Traktor * on a platform-specific reason like grid_marker. */
* pairs most grid markers with a white cue that occupies a real hotcue slot; editable: boolean
* it belongs to the beatgrid, so it is shown read-only and the backend readonly_reason: 'beatgrid_companion' | 'platform_managed' | null
* refuses hotcue edits on it. /** 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 grid_marker: number | null
} }
@@ -131,18 +142,74 @@ export interface TrackCues {
* render and edit wrongly. * render and edit wrongly.
*/ */
grid_markers: GridMarker[] grid_markers: GridMarker[]
locked: boolean grid_locked: boolean
cues: CuePoint[] 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 { export interface EditState {
dirty: boolean dirty: boolean
nml_path: string library: LibraryInfo
} }
export interface CollectionStatus { export interface CollectionStatus {
loaded: boolean loaded: boolean
path: string | null path: string | null
library: LibraryInfo | null
tracks: number | null tracks: number | null
playlists: number | null playlists: number | null
} }
@@ -259,28 +326,29 @@ function qs(params: Record<string, unknown>): string {
export const api = { export const api = {
// ---- collection selection ---- // ---- collection selection ----
collection: () => getJSON<CollectionStatus>('/api/collection'), collection: () => getJSON<CollectionStatus>('/api/library'),
openCollection: (path: string) => openCollection: (path: string) =>
send<CollectionStatus>('POST', '/api/collection/open', { path }), send<CollectionStatus>('POST', '/api/library/open', { path }),
collectionOptions: () => getJSON<CollectionOptions>('/api/collection/options'), collectionOptions: () => getJSON<CollectionOptions>('/api/library/options'),
listDir: (path?: string) => listDir: (path?: string) =>
getJSON<FsListing>(`/api/fs/list${path ? `?path=${encodeURIComponent(path)}` : ''}`), getJSON<FsListing>(`/api/fs/list${path ? `?path=${encodeURIComponent(path)}` : ''}`),
// ---- path remapping (per-collection OS-path prefix translation) ---- // ---- path remapping (per-collection OS-path prefix translation) ----
getPathMapping: () => getJSON<PathMapping>('/api/collection/path-mapping'), getPathMapping: () => getJSON<PathMapping>('/api/library/path-mapping'),
suggestPrefix: () => suggestPrefix: () =>
getJSON<PrefixSuggestions>('/api/collection/path-mapping/suggest'), getJSON<PrefixSuggestions>('/api/library/path-mapping/suggest'),
putPathMapping: (m: PathMapping) => putPathMapping: (m: PathMapping) =>
send<PathMapping>('PUT', '/api/collection/path-mapping', m), send<PathMapping>('PUT', '/api/library/path-mapping', m),
previewRemap: (from: string, to: string) => previewRemap: (from: string, to: string) =>
getJSON<RemapPreview>( getJSON<RemapPreview>(
`/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). // Write-back: permanently rewrite matching LOCATIONs in the .nml (committed to history).
remapPaths: (from: string, to: string) => remapPaths: (from: string, to: string) =>
send<RemapResult>('POST', '/api/collection/remap-paths', { from, to }), send<RemapResult>('POST', '/api/library/remap-paths', { from, to }),
stats: () => getJSON<Stats>('/api/stats'), capabilities: () => getJSON<Capabilities>('/api/capabilities'),
platforms: () => getJSON<PlatformOption[]>('/api/platforms'),
facets: () => getJSON<Facets>('/api/facets'), facets: () => getJSON<Facets>('/api/facets'),
playlists: () => getJSON<PlaylistNode[]>('/api/playlists'), playlists: () => getJSON<PlaylistNode[]>('/api/playlists'),
tracks: (query: TrackQuery) => tracks: (query: TrackQuery) =>
@@ -292,18 +360,18 @@ export const api = {
state: () => getJSON<EditState>('/api/state'), state: () => getJSON<EditState>('/api/state'),
createPlaylist: (name: string, parentId?: string) => createPlaylist: (name: string, parentId?: string) =>
send<PlaylistNode>('POST', '/api/playlists', { name, parent_id: parentId ?? null }), send<PlaylistNode>('POST', '/api/playlists', { name, parent_id: parentId ?? null }),
renamePlaylist: (uuid: string, name: string) => renamePlaylist: (nodeId: string, name: string) =>
send<{ status: string }>('PATCH', `/api/playlists/${uuid}`, { name }), send<{ status: string }>('PATCH', `/api/playlists/${encodeURIComponent(nodeId)}`, { name }),
deletePlaylist: (uuid: string) => deletePlaylist: (nodeId: string) =>
send<{ status: string }>('DELETE', `/api/playlists/${uuid}`), send<{ status: string }>('DELETE', `/api/playlists/${encodeURIComponent(nodeId)}`),
setEntries: (uuid: string, trackIds: string[]) => setEntries: (nodeId: string, trackIds: string[]) =>
send<{ status: string; count: number }>('PUT', `/api/playlists/${uuid}/entries`, { send<{ status: string; count: number }>('PUT', `/api/playlists/${encodeURIComponent(nodeId)}/entries`, {
track_ids: trackIds, track_ids: trackIds,
}), }),
addEntries: (uuid: string, trackIds: string[]) => addEntries: (nodeId: string, trackIds: string[]) =>
send<{ status: string; added: number; count: number }>( send<{ status: string; added: number; count: number }>(
'POST', 'POST',
`/api/playlists/${uuid}/add`, `/api/playlists/${encodeURIComponent(nodeId)}/add`,
{ track_ids: trackIds }, { track_ids: trackIds },
), ),
getPrefs: () => getJSON<Record<string, unknown>>('/api/prefs'), getPrefs: () => getJSON<Record<string, unknown>>('/api/prefs'),
@@ -325,15 +393,15 @@ export const api = {
`${API_BASE}/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`, `${API_BASE}/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`,
trackCues: (trackId: string) => trackCues: (trackId: string) =>
getJSON<TrackCues>(`/api/tracks/cues?track_id=${encodeURIComponent(trackId)}`), getJSON<TrackCues>(`/api/tracks/cues?track_id=${encodeURIComponent(trackId)}`),
createHotcue: ( createCue: (
trackId: string, trackId: string,
slot: number, slot: number,
start: number, start: number,
type: number, type: CueType,
length = 0, length = 0,
name?: string, name?: string,
) => ) =>
send<TrackCues>('POST', '/api/tracks/hotcue', { send<TrackCues>('POST', '/api/tracks/cue', {
track_id: trackId, track_id: trackId,
slot, slot,
start, start,
@@ -342,20 +410,20 @@ export const api = {
name, name,
}), }),
// Backend analyses the audio and places structural hotcues into empty slots. // Backend analyses the audio and places structural hotcues into empty slots.
autoHotcues: (trackId: string, maxCues?: number) => autoCues: (trackId: string, maxCues?: number) =>
send<TrackCues>('POST', '/api/tracks/auto-hotcues', { send<TrackCues>('POST', '/api/tracks/cue/auto', {
track_id: trackId, track_id: trackId,
max_cues: maxCues, max_cues: maxCues,
}), }),
// Backend detects tempo + first beat: sets BPM, hotcue 1, and grid anchor. // Backend detects tempo + first beat: sets BPM, hotcue 1, and grid anchor.
autoGrid: (trackId: string) => autoGrid: (trackId: string) =>
send<TrackCues>('POST', '/api/tracks/auto-grid', { track_id: trackId }), send<TrackCues>('POST', '/api/tracks/grid/auto', { track_id: trackId }),
setHotcueType: (trackId: string, slot: number, type: number) => setCueType: (trackId: string, slot: number, type: CueType) =>
send<TrackCues>('PATCH', '/api/tracks/hotcue', { track_id: trackId, slot, type }), send<TrackCues>('PATCH', '/api/tracks/cue', { track_id: trackId, slot, type }),
deleteHotcue: (trackId: string, slot: number) => deleteCue: (trackId: string, slot: number) =>
send<TrackCues>( send<TrackCues>(
'DELETE', '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; /** Retempo and/or move one marker. `index` is its position in grid_markers;
* a move is clamped between its neighbours rather than reordering them. */ * a move is clamped between its neighbours rather than reordering them. */
@@ -378,8 +446,8 @@ export const api = {
send<TrackCues>('PUT', '/api/tracks/grid', { track_id: trackId, markers }), send<TrackCues>('PUT', '/api/tracks/grid', { track_id: trackId, markers }),
deleteGrid: (trackId: string) => deleteGrid: (trackId: string) =>
send<TrackCues>('DELETE', `/api/tracks/grid?track_id=${encodeURIComponent(trackId)}`), send<TrackCues>('DELETE', `/api/tracks/grid?track_id=${encodeURIComponent(trackId)}`),
setLock: (trackId: string, locked: boolean) => setGridLock: (trackId: string, locked: boolean) =>
send<TrackCues>('PATCH', '/api/tracks/lock', { track_id: trackId, locked }), send<TrackCues>('PATCH', '/api/tracks/grid/lock', { track_id: trackId, locked }),
uploadArt: async (trackId: string, file: File) => { uploadArt: async (trackId: string, file: File) => {
const fd = new FormData() const fd = new FormData()
fd.append('track_id', trackId) fd.append('track_id', trackId)
+13 -6
View File
@@ -52,6 +52,13 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
const [manual, setManual] = useState('') const [manual, setManual] = useState('')
const options = useQuery({ queryKey: ['collectionOptions'], queryFn: api.collectionOptions }) 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({ const listing = useQuery({
queryKey: ['fs', dir ?? '~'], queryKey: ['fs', dir ?? '~'],
queryFn: () => api.listDir(dir), queryFn: () => api.listDir(dir),
@@ -76,12 +83,12 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
<div className="flex items-center gap-3 border-b border-line px-5 py-4"> <div className="flex items-center gap-3 border-b border-line px-5 py-4">
<div className="flex-1"> <div className="flex-1">
<div className="text-[15px] font-semibold tracking-tight"> <div className="text-[15px] font-semibold tracking-tight">
Select your Traktor collection Select your {appName} library
</div> </div>
<div className="text-xs text-muted"> <div className="text-xs text-muted">
{mode === 'choose' {mode === 'choose'
? 'Open automatically, resume your last one, or browse.' ? 'Open automatically, resume your last one, or browse.'
: 'Choose a collection.nml file to open.'} : `Choose a ${fileLabel} to open.`}
</div> </div>
</div> </div>
{mode === 'browse' && ( {mode === 'browse' && (
@@ -112,8 +119,8 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
auto auto
? `${auto.label} · modified ${formatWhen(auto.modified)}` ? `${auto.label} · modified ${formatWhen(auto.modified)}`
: options.isLoading : options.isLoading
? 'Searching for a Traktor collection…' ? `Searching for a ${appName} library…`
: 'No Traktor collection found in the default location' : `No ${appName} library found in the default location`
} }
disabled={!auto} disabled={!auto}
busy={open.isPending} busy={open.isPending}
@@ -136,7 +143,7 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
<OptionCard <OptionCard
icon="📂" icon="📂"
title="Find collection manually" title="Find collection manually"
subtitle="Browse for a collection.nml file" subtitle={`Browse for a ${fileLabel}`}
busy={open.isPending} busy={open.isPending}
onClick={() => setMode('browse')} onClick={() => setMode('browse')}
/> />
@@ -218,7 +225,7 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === 'Enter' && manual.trim()) open.mutate(manual.trim()) 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" 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 <button
+12 -12
View File
@@ -2,6 +2,9 @@ import { useRef, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type Track } from '../api' import { api, type Track } from '../api'
import { formatBpm, formatDuration } from '../lib/format' import { formatBpm, formatDuration } from '../lib/format'
import { useCaps } from '../lib/capabilities'
import { RatingStars } from './RatingStars'
import { saveLabel, writeHint } from '../lib/platformCopy'
interface Props { interface Props {
track: Track track: Track
@@ -25,6 +28,7 @@ const TEXT_FIELDS: { key: keyof Track; label: string; textarea?: boolean }[] = [
] ]
export function EditTagsDialog({ track, onClose, onApplied, onError }: Props) { export function EditTagsDialog({ track, onClose, onApplied, onError }: Props) {
const caps = useCaps()
const qc = useQueryClient() const qc = useQueryClient()
const { data: facets } = useQuery({ queryKey: ['facets'], queryFn: api.facets }) const { data: facets } = useQuery({ queryKey: ['facets'], queryFn: api.facets })
@@ -61,7 +65,9 @@ export function EditTagsDialog({ track, onClose, onApplied, onError }: Props) {
qc.invalidateQueries({ queryKey: ['state'] }) qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['facets'] }) qc.invalidateQueries({ queryKey: ['facets'] })
qc.invalidateQueries({ queryKey: ['stats'] }) qc.invalidateQueries({ queryKey: ['stats'] })
onApplied(`Updated “${form.title || track.title || 'track'}” — Save to write to Traktor`) onApplied(
`Updated “${form.title || track.title || 'track'}” — ${writeHint(caps.save)}`,
)
onClose() onClose()
}, },
onError: (e: Error) => onError(e.message), onError: (e: Error) => onError(e.message),
@@ -170,15 +176,7 @@ export function EditTagsDialog({ track, onClose, onApplied, onError }: Props) {
Rating Rating
</span> </span>
<div className="flex items-center gap-1 text-xl"> <div className="flex items-center gap-1 text-xl">
{[1, 2, 3, 4, 5].map((i) => ( <RatingStars value={rating} max={caps.tracks.rating_max} onChange={setRating} />
<button
key={i}
onClick={() => setRating(i === rating ? 0 : i)}
className={i <= rating ? 'text-gold' : 'text-ink-600 hover:text-faint'}
>
★
</button>
))}
{rating > 0 && ( {rating > 0 && (
<button <button
onClick={() => setRating(0)} onClick={() => setRating(0)}
@@ -204,8 +202,10 @@ export function EditTagsDialog({ track, onClose, onApplied, onError }: Props) {
</div> </div>
<p className="text-[11px] leading-snug text-faint"> <p className="text-[11px] leading-snug text-faint">
BPM, key and path aren’t editable here. Changes apply in-app; click BPM, key and path aren’t editable here. Changes apply in-app; click
<span className="text-muted"> Save to Traktor</span> to write them to disk. <span className="text-muted"> {saveLabel(caps.save)}</span> to write them to disk.
New album art is written into the file; Traktor may need a manual 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. “Import Cover Art” to refresh its own cached thumbnail.
</p> </p>
</div> </div>
+5 -3
View File
@@ -1,6 +1,8 @@
import { useState } from 'react' import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type HistoryEntry } from '../api' import { api, type HistoryEntry } from '../api'
import { useCaps } from '../lib/capabilities'
import { restoreWarning } from '../lib/platformCopy'
import type { ToastMsg } from './Toast' import type { ToastMsg } from './Toast'
interface Props { 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 * 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) * 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 * 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) { export function HistoryPanel({ onClose, onNotify, onError }: Props) {
const caps = useCaps()
const qc = useQueryClient() const qc = useQueryClient()
const history = useQuery({ queryKey: ['history'], queryFn: api.history }) const history = useQuery({ queryKey: ['history'], queryFn: api.history })
const [confirmingId, setConfirmingId] = useState<string | null>(null) const [confirmingId, setConfirmingId] = useState<string | null>(null)
@@ -87,8 +90,7 @@ export function HistoryPanel({ onClose, onNotify, onError }: Props) {
<div className="border-b border-line px-5 py-4"> <div className="border-b border-line px-5 py-4">
<div className="text-[15px] font-semibold tracking-tight">Version History</div> <div className="text-[15px] font-semibold tracking-tight">Version History</div>
<div className="text-xs text-muted"> <div className="text-xs text-muted">
Every save is a restorable version of this collection. Close Traktor before Every save is a restorable version of this library. {restoreWarning(caps.save)}
restoring — it overwrites the collection on exit.
</div> </div>
</div> </div>
+37 -14
View File
@@ -1,14 +1,21 @@
import type { CuePoint } from '../api' import type { CuePoint } from '../api'
import { contrastText, cueColor, GRID_MARKER_COLOR } from '../lib/cues' import { contrastText, cueColor, cueGlyph } from '../lib/cues'
interface Props { interface Props {
cues: CuePoint[] 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 selectedSlot: number | null
onSlotPress: (slot: number) => void onSlotPress: (slot: number) => void
onSlotRelease: (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<string, string> = {
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). * 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 * the backend refuses hotcue edits on them, and showing that up front is better
* than surfacing the refusal as an error. * 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 ( return (
<div className="flex flex-1 items-stretch gap-px"> <div className="flex flex-1 items-stretch gap-px">
{SLOTS.map((slot) => { {Array.from({ length: slotCount }, (_, i) => i).map((slot) => {
const cue = cues.find((c) => c.hotcue === slot) ?? null const cue = cues.find((c) => c.role === 'hotcue' && c.slot === slot) ?? null
const isMarker = cue?.grid_marker != null // Gate on `editable`, never on why: a platform-owned cue is a read-only
const selected = selectedSlot === slot && !isMarker // case, not a Traktor-companion case.
const color = cue ? (isMarker ? GRID_MARKER_COLOR : cueColor(cue)) : null const locked = cue != null && !cue.editable
const selected = selectedSlot === slot && !locked
const color = cue ? cueColor(cue) : null
const glyph = cue ? cueGlyph(cue) : ''
return ( return (
<button <button
key={slot} key={slot}
@@ -45,13 +62,14 @@ export function HotcueBar({ cues, selectedSlot, onSlotPress, onSlotRelease }: Pr
onPointerUp={() => onSlotRelease(slot)} onPointerUp={() => onSlotRelease(slot)}
onPointerCancel={() => onSlotRelease(slot)} onPointerCancel={() => onSlotRelease(slot)}
title={ title={
isMarker locked
? `Beatgrid marker ${(cue!.grid_marker ?? 0) + 1} — managed by the grid controls` ? (cue!.readonly_reason && READONLY_LABELS[cue!.readonly_reason]) ??
'Not editable here'
: cue : cue
? cue.name && cue.name !== 'n.n.' ? cue.name && cue.name !== 'n.n.'
? `${slot + 1}: ${cue.name}` ? `${slotLabel(slot)}: ${cue.name}`
: `Hotcue ${slot + 1}` : `Hotcue ${slotLabel(slot)}`
: `Hotcue ${slot + 1} — click to set at playhead` : `Hotcue ${slotLabel(slot)} — click to set at playhead`
} }
style={color ? { backgroundColor: color, color: contrastText(color) } : undefined} style={color ? { backgroundColor: color, color: contrastText(color) } : undefined}
className={ className={
@@ -60,7 +78,12 @@ export function HotcueBar({ cues, selectedSlot, onSlotPress, onSlotRelease }: Pr
(selected ? ' ring-2 ring-inset ring-white/80' : '') (selected ? ' ring-2 ring-inset ring-white/80' : '')
} }
> >
{isMarker ? '⊞' : slot + 1} {locked ? '🔒' : slotLabel(slot)}
{glyph && (
<span className="absolute right-0.5 top-0 text-[9px] leading-none opacity-80">
{glyph}
</span>
)}
</button> </button>
) )
})} })}
+61 -32
View File
@@ -1,7 +1,9 @@
import { useEffect, useMemo, useRef, useState } from 'react' import { useEffect, useMemo, useRef, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query' 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 { 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 { analyzeWaveform, type WaveColumn } from '../lib/waveform'
import { ScratchEngine } from '../lib/scratchEngine' import { ScratchEngine } from '../lib/scratchEngine'
import { PlaybackEngine } from '../lib/playbackEngine' import { PlaybackEngine } from '../lib/playbackEngine'
@@ -29,13 +31,22 @@ function fmt(secs: number): string {
return `${m}:${s.toString().padStart(2, '0')}` return `${m}:${s.toString().padStart(2, '0')}`
} }
const CUE_TYPES: { value: number; label: string }[] = [ /**
{ value: 0, label: 'Cue' }, * Digit key -> bank slot: 1..9 map to slots 0..8 and 0 maps to slot 10.
{ value: 1, label: 'Fade-In' }, *
{ value: 2, label: 'Fade-Out' }, * Ten digits is the physical ceiling, so a bank larger than that simply has no
{ value: 3, label: 'Load' }, * 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 LOOP_TYPE = 5 */
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] 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 // eslint-disable-next-line react-hooks/exhaustive-deps
}, [grid]) }, [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 ---------------------------------------------------------- // ---- 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) => { const applyCueEdit = (fresh: TrackCues) => {
setCueData(fresh) 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. // Setting a hotcue while a loop is active stores it as a loop hotcue.
if (loopActive && loopRegion) { if (loopActive && loopRegion) {
const len = loopRegion.end - loopRegion.start 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 { } else {
const t = snapTime(playbackRef.current?.getPosition() ?? current) 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) setSelectedSlot(slot)
} catch (e) { } catch (e) {
@@ -613,7 +633,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
if (!eng || !eng.ready) return if (!eng || !eng.ready) return
getCtx() getCtx()
// A loop hotcue jumps to its start AND re-engages a loop of its length. // 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) seek(cue.start)
engagLoop(cue.start, cue.start + cue.length, beatsForLoop(cue.start, cue.length)) engagLoop(cue.start, cue.start + cue.length, beatsForLoop(cue.start, cue.length))
} else { } else {
@@ -633,15 +653,15 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const runAutoHotcues = async () => { const runAutoHotcues = async () => {
if (!track || !canAutoCue || autoBusy) return if (!track || !canAutoCue || autoBusy) return
const hotcueCount = (c: TrackCues | null) => const hotcueCount = (c: TrackCues | null) =>
c?.cues.filter((x) => x.hotcue >= 0).length ?? 0 c?.cues.filter((x) => x.role === 'hotcue' && x.slot != null).length ?? 0
if (hotcueCount(cueData) >= 8) { if (hotcueCount(cueData) >= slotCount) {
onError?.('No free hotcue slots — delete some first') onError?.(`No free hotcue slots (${slotCount} of ${slotCount} used) — delete some first`)
return return
} }
setAutoBusy(true) setAutoBusy(true)
try { try {
const before = hotcueCount(cueData) const before = hotcueCount(cueData)
const fresh = await api.autoHotcues(track.id) const fresh = await api.autoCues(track.id)
applyCueEdit(fresh) applyCueEdit(fresh)
const placed = Math.max(0, hotcueCount(fresh) - before) const placed = Math.max(0, hotcueCount(fresh) - before)
if (placed === 0) { 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 if (!track || selectedSlot == null) return
try { try {
applyCueEdit(await api.setHotcueType(track.id, selectedSlot, type)) applyCueEdit(await api.setCueType(track.id, selectedSlot, type))
} catch (e) { } catch (e) {
onError?.((e as Error).message) onError?.((e as Error).message)
} }
@@ -668,7 +688,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const deleteSelected = async () => { const deleteSelected = async () => {
if (!track || selectedSlot == null) return if (!track || selectedSlot == null) return
try { try {
applyCueEdit(await api.deleteHotcue(track.id, selectedSlot)) applyCueEdit(await api.deleteCue(track.id, selectedSlot))
setSelectedSlot(null) setSelectedSlot(null)
} catch (e) { } catch (e) {
onError?.((e as Error).message) 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 (!track || !existing) return // nothing to remove in an empty slot
if (existing.grid_marker != null) return // beatgrid-owned: delete the marker instead if (existing.grid_marker != null) return // beatgrid-owned: delete the marker instead
try { try {
applyCueEdit(await api.deleteHotcue(track.id, slot)) applyCueEdit(await api.deleteCue(track.id, slot))
if (selectedSlot === slot) setSelectedSlot(null) if (selectedSlot === slot) setSelectedSlot(null)
} catch (e) { } catch (e) {
onError?.((e as Error).message) onError?.((e as Error).message)
@@ -757,7 +777,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const toggleLock = async () => { const toggleLock = async () => {
if (!track) return if (!track) return
try { try {
applyCueEdit(await api.setLock(track.id, !cueData?.locked)) applyCueEdit(await api.setGridLock(track.id, !cueData?.grid_locked))
} catch (e) { } catch (e) {
onError?.((e as Error).message) onError?.((e as Error).message)
} }
@@ -799,6 +819,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
beatJump, beatJump,
prevMarker, prevMarker,
nextMarker, nextMarker,
slotCount,
}) })
shortcutsRef.current = { shortcutsRef.current = {
toggle, toggle,
@@ -810,6 +831,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
beatJump, beatJump,
prevMarker, prevMarker,
nextMarker, nextMarker,
slotCount,
} }
useEffect(() => { useEffect(() => {
const onKey = (e: KeyboardEvent) => { const onKey = (e: KeyboardEvent) => {
@@ -840,10 +862,9 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
else shortcutsRef.current.beatJump(1) else shortcutsRef.current.beatJump(1)
return return
} }
const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/) const slot = slotForDigit(e.code, shortcutsRef.current.slotCount)
if (digit) { if (slot != null) {
e.preventDefault() e.preventDefault()
const slot = Number(digit[1]) - 1
if (e.shiftKey) void shortcutsRef.current.deleteHotcueSlot(slot) if (e.shiftKey) void shortcutsRef.current.deleteHotcueSlot(slot)
else void shortcutsRef.current.onSlotPress(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). // keyup ends a held hotcue's momentary preview (release).
const onKeyRelease = (e: KeyboardEvent) => { const onKeyRelease = (e: KeyboardEvent) => {
if (e.code === 'KeyC') shortcutsRef.current.onCueRelease() if (e.code === 'KeyC') shortcutsRef.current.onCueRelease()
const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/) const slot = slotForDigit(e.code, shortcutsRef.current.slotCount)
if (digit) shortcutsRef.current.onSlotRelease(Number(digit[1]) - 1) if (slot != null) shortcutsRef.current.onSlotRelease(slot)
} }
window.addEventListener('keydown', onKey) window.addEventListener('keydown', onKey)
window.addEventListener('keyup', onKeyRelease) window.addEventListener('keyup', onKeyRelease)
@@ -893,7 +914,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
markerStart={activeMarker?.start ?? null} markerStart={activeMarker?.start ?? null}
atMarker={atMarker} atMarker={atMarker}
beforeFirst={beforeFirstMarker} beforeFirst={beforeFirstMarker}
locked={cueData?.locked ?? false} locked={cueData?.grid_locked ?? false}
canReset={originalGridRef.current != null} canReset={originalGridRef.current != null}
onSetBpm={setBpm} onSetBpm={setBpm}
onNudgeBpm={nudgeBpm} onNudgeBpm={nudgeBpm}
@@ -1034,24 +1055,32 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
</span> </span>
<HotcueBar <HotcueBar
cues={cueData?.cues ?? []} cues={cueData?.cues ?? []}
slotCount={slotCount}
slotLabel={slotLabel}
selectedSlot={selectedSlot} selectedSlot={selectedSlot}
onSlotPress={onSlotPress} onSlotPress={onSlotPress}
onSlotRelease={onSlotRelease} onSlotRelease={onSlotRelease}
/> />
<div className="flex w-28 items-center justify-center bg-ink-900 px-1"> <div className="flex w-28 items-center justify-center bg-ink-900 px-1">
{selectedCue && selectedCue.type === LOOP_TYPE ? ( {selectedCue && selectedCue.type === 'loop' ? (
<span className="text-sm font-semibold text-mint">Loop</span> <span className="text-sm font-semibold text-mint">Loop</span>
) : pointCueTypes.length < 2 ? (
// One point type means there is nothing to choose between —
// show it rather than a dropdown that cannot change anything.
<span className="text-sm font-semibold text-text">
{selectedCue ? CUE_TYPE_LABELS[selectedCue.type] : '—'}
</span>
) : ( ) : (
<select <select
value={selectedCue ? selectedCue.type : ''} value={selectedCue ? selectedCue.type : ''}
disabled={!selectedCue} disabled={!selectedCue}
onChange={(e) => changeSelectedType(Number(e.target.value))} onChange={(e) => changeSelectedType(e.target.value as CueType)}
className="w-full bg-transparent text-center text-sm font-semibold text-text outline-none disabled:opacity-40" className="w-full bg-transparent text-center text-sm font-semibold text-text outline-none disabled:opacity-40"
> >
{!selectedCue && <option value="">—</option>} {!selectedCue && <option value="">—</option>}
{CUE_TYPES.map((t) => ( {pointCueTypes.map((t) => (
<option key={t.value} value={t.value}> <option key={t} value={t}>
{t.label} {CUE_TYPE_LABELS[t]}
</option> </option>
))} ))}
</select> </select>
+13 -10
View File
@@ -2,22 +2,25 @@ import { useState } from 'react'
interface Props { interface Props {
value: number 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 onChange?: (value: number) => void
} }
// Compact 5-star rating. Read-only by default (shows a dash when unrated). When // Compact star rating. Read-only by default (shows a dash when unrated). When
// `onChange` is given it's interactive: always shows five stars — hollow (☆) up // `onChange` is given it's interactive: hollow (☆) above the rating, solid gold
// to the rating, solid gold (★) below it — with hover preview. Clicking a star // (★) up to it, with hover preview. Clicking a star sets that rating; clicking
// sets that rating; clicking the current top star again clears it to 0. // the current top star again clears it to 0.
export function RatingStars({ value, onChange }: Props) { export function RatingStars({ value, max = 5, onChange }: Props) {
const [hover, setHover] = useState(0) const [hover, setHover] = useState(0)
const stars = Array.from({ length: max }, (_, i) => i + 1)
if (!onChange) { if (!onChange) {
if (!value) return <span className="text-faint">—</span> if (!value) return <span className="text-faint">—</span>
return ( return (
<span className="whitespace-nowrap tracking-tight" title={`${value} / 5`}> <span className="whitespace-nowrap tracking-tight" title={`${value} / ${max}`}>
{[1, 2, 3, 4, 5].map((i) => ( {stars.map((i) => (
<span key={i} className={i <= value ? 'text-gold' : 'text-ink-600'}> <span key={i} className={i <= value ? 'text-gold' : 'text-ink-600'}>
{i <= value ? '★' : '☆'} {i <= value ? '★' : '☆'}
</span> </span>
@@ -28,8 +31,8 @@ export function RatingStars({ value, onChange }: Props) {
const shown = hover || value const shown = hover || value
return ( return (
<span className="whitespace-nowrap tracking-tight" title={`${value} / 5`}> <span className="whitespace-nowrap tracking-tight" title={`${value} / ${max}`}>
{[1, 2, 3, 4, 5].map((i) => ( {stars.map((i) => (
<button <button
key={i} key={i}
onClick={(e) => { onClick={(e) => {
+7 -3
View File
@@ -1,6 +1,8 @@
import { useState } from 'react' import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from '../api' import { api } from '../api'
import { useCaps } from '../lib/capabilities'
import { overwriteWarning, saveLabel } from '../lib/platformCopy'
interface Props { interface Props {
onError: (msg: string) => void onError: (msg: string) => void
@@ -26,13 +28,15 @@ export function SaveBar({ onError }: Props) {
onError: (e: Error) => onError(e.message), onError: (e: Error) => onError(e.message),
}) })
const caps = useCaps()
const warning = overwriteWarning(caps.save)
const dirty = state?.dirty ?? false const dirty = state?.dirty ?? false
return ( return (
<div className="border-t border-line bg-ink-900 px-3 py-3"> <div className="border-t border-line bg-ink-900 px-3 py-3">
{dirty && ( {dirty && warning && (
<div className="mb-2 rounded-md bg-gold/10 px-2 py-1.5 text-[11px] leading-snug text-gold"> <div className="mb-2 rounded-md bg-gold/10 px-2 py-1.5 text-[11px] leading-snug text-gold">
⚠ Close Traktor before saving — it overwrites the collection on exit. ⚠ {warning}
</div> </div>
)} )}
<button <button
@@ -49,7 +53,7 @@ export function SaveBar({ onError }: Props) {
) : dirty ? ( ) : dirty ? (
<> <>
<span className="h-1.5 w-1.5 rounded-full bg-ink-950/60" /> <span className="h-1.5 w-1.5 rounded-full bg-ink-950/60" />
Save to Traktor {saveLabel(caps.save)}
</> </>
) : ( ) : (
'No unsaved changes' 'No unsaved changes'
+1 -1
View File
@@ -12,7 +12,7 @@ interface Props {
function flattenPlaylists(nodes: PlaylistNode[]): PlaylistNode[] { function flattenPlaylists(nodes: PlaylistNode[]): PlaylistNode[] {
return nodes.flatMap((n) => [ return nodes.flatMap((n) => [
...(n.type === 'PLAYLIST' ? [n] : []), ...(n.can_add_tracks ? [n] : []),
...flattenPlaylists(n.children), ...flattenPlaylists(n.children),
]) ])
} }
+12 -10
View File
@@ -1,6 +1,6 @@
import { useState } from 'react' import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type PlaylistNode } from '../api' import { api, type PlaylistKind, type PlaylistNode } from '../api'
import { SaveBar } from './SaveBar' import { SaveBar } from './SaveBar'
export type Source = { kind: 'all' } | { kind: 'playlist'; id: string; name: string } export type Source = { kind: 'all' } | { kind: 'playlist'; id: string; name: string }
@@ -12,10 +12,12 @@ interface Props {
onOpenHistory: () => void onOpenHistory: () => void
} }
const icons: Record<string, string> = { // Kind picks the icon; every behavioural question is answered by the node's own
FOLDER: '▸', // flags, so nothing here infers what a node can do from what it is called.
PLAYLIST: '♫', const icons: Record<PlaylistKind, string> = {
SMARTLIST: '✦', folder: '▸',
playlist: '♫',
smart: '✦',
} }
function NodeRow({ function NodeRow({
@@ -35,9 +37,9 @@ function NodeRow({
const [open, setOpen] = useState(true) const [open, setOpen] = useState(true)
const [renaming, setRenaming] = useState(false) const [renaming, setRenaming] = useState(false)
const [draft, setDraft] = useState(node.name) const [draft, setDraft] = useState(node.name)
const isFolder = node.type === 'FOLDER' const isFolder = node.kind === 'folder'
const selected = source.kind === 'playlist' && source.id === node.id const selected = source.kind === 'playlist' && source.id === node.id
const selectable = node.type === 'PLAYLIST' const selectable = node.selectable
const invalidate = () => { const invalidate = () => {
qc.invalidateQueries({ queryKey: ['playlists'] }) qc.invalidateQueries({ queryKey: ['playlists'] })
@@ -82,10 +84,10 @@ function NodeRow({
> >
<span <span
className={`w-3 shrink-0 text-center text-[11px] ${ className={`w-3 shrink-0 text-center text-[11px] ${
isFolder ? 'text-faint' : node.type === 'SMARTLIST' ? 'text-pink' : 'text-accent' isFolder ? 'text-faint' : node.kind === 'smart' ? 'text-pink' : 'text-accent'
} ${isFolder && open ? 'rotate-90' : ''} transition-transform`} } ${isFolder && open ? 'rotate-90' : ''} transition-transform`}
> >
{icons[node.type]} {icons[node.kind]}
</span> </span>
{renaming ? ( {renaming ? (
<input <input
@@ -113,7 +115,7 @@ function NodeRow({
)} )}
</button> </button>
{node.type === 'PLAYLIST' && !renaming && ( {node.can_rename && !renaming && (
<> <>
<button <button
title="Rename" title="Rename"
+3 -1
View File
@@ -1,6 +1,7 @@
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import type { VisibilityState } from '@tanstack/react-table' import type { VisibilityState } from '@tanstack/react-table'
import { api } from '../api' import { api } from '../api'
import { useCaps } from '../lib/capabilities'
import { ColumnsMenu } from './ColumnsMenu' import { ColumnsMenu } from './ColumnsMenu'
import { SettingsMenu } from './SettingsMenu' import { SettingsMenu } from './SettingsMenu'
@@ -44,6 +45,7 @@ export function Toolbar({
onResetColumns, onResetColumns,
onOpenPathMapping, onOpenPathMapping,
}: Props) { }: Props) {
const caps = useCaps()
const { data: facets } = useQuery({ queryKey: ['facets'], queryFn: api.facets }) const { data: facets } = useQuery({ queryKey: ['facets'], queryFn: api.facets })
const set = (patch: Partial<Filters>) => onChange({ ...filters, ...patch }) const set = (patch: Partial<Filters>) => onChange({ ...filters, ...patch })
const active = const active =
@@ -117,7 +119,7 @@ export function Toolbar({
className={selectCls} className={selectCls}
> >
<option value={0}>Any rating</option> <option value={0}>Any rating</option>
{[1, 2, 3, 4, 5].map((r) => ( {Array.from({ length: caps.tracks.rating_max }, (_, i) => i + 1).map((r) => (
<option key={r} value={r}> <option key={r} value={r}>
{'★'.repeat(r)}+ {'★'.repeat(r)}+
</option> </option>
+32
View File
@@ -0,0 +1,32 @@
import { createContext, useContext } from 'react'
import type { Capabilities } from '../api'
/**
* What the loaded library can persist.
*
* Components read this instead of branching on the platform, so a control is
* never offered for an edit that would silently vanish on save. There is no
* default value on purpose: the app does not render until capabilities have
* resolved, which removes any chance of a permissive first frame offering an
* edit the adapter would reject.
*
* Containers call `useCaps()`; presentational leaves take plain values as props
* so they stay trivially testable.
*/
export const CapabilitiesContext = createContext<Capabilities | null>(null)
export function useCaps(): Capabilities {
const caps = useContext(CapabilitiesContext)
if (!caps) {
throw new Error('useCaps() used outside <CapabilitiesContext.Provider>')
}
return caps
}
/** Label for a bank slot: "1".."8" or "A".."H", per the platform's convention. */
export function slotLabeller(caps: Capabilities): (slot: number) => string {
return caps.cues.slot_labels === 'letter'
? (slot) => String.fromCharCode(65 + slot)
: (slot) => String(slot + 1)
}
+62 -22
View File
@@ -1,21 +1,56 @@
import type { CuePoint } from '../api' import type { CuePoint, CueType } from '../api'
import { BEATS_PER_BAR, type BeatGrid } from './beatgrid' import { BEATS_PER_BAR, type BeatGrid } from './beatgrid'
// Marker colour by Traktor cue type. Type is authoritative here (the NML's // Fallback colour by cue type, used when the platform stored none.
// stored per-cue colour is intentionally ignored) so each type reads consistently. const TYPE_COLORS: Record<CueType, string> = {
// There is deliberately no entry for type 4 (grid): grid markers are not cues — cue: '#3b82f6', // blue
// they arrive as TrackCues.grid_markers and are drawn by drawBeatgrid. fade_in: '#ff8c2f', // orange
const TYPE_COLORS: Record<number, string> = { fade_out: '#ff8c2f', // orange
0: '#3b82f6', // cue — blue load: '#ffd60a', // yellow
1: '#ff8c2f', // fade-in — orange loop: '#22c55e', // green
2: '#ff8c2f', // fade-out — orange
3: '#ffd60a', // load — yellow
5: '#22c55e', // loop — green
} }
const OTHER_COLOR = '#8b93a3' // gray const MEMORY_COLOR = '#8b93a3' // gray
export const CUE_TYPE_LABELS: Record<CueType, string> = {
cue: 'Cue',
fade_in: 'Fade-In',
fade_out: 'Fade-Out',
load: 'Load',
loop: 'Loop',
}
// A second, always-present channel for type. Colour used to be type-derived and
// therefore always carried it; now that a user's stored colour wins, the glyph
// is what keeps a fade-in distinguishable from a plain cue.
const TYPE_GLYPHS: Record<CueType, string> = {
cue: '',
fade_in: '▶',
fade_out: '◀',
load: '⏏',
loop: '⟳',
}
/**
* Colour for a cue marker or button.
*
* Stored colour wins where the platform has one: on Rekordbox and Serato it is
* the attribute the user actually set, and overriding it with a type palette
* would discard their own organisation. Traktor rarely stores one, so in a
* Traktor library the type palette still drives virtually every cue and the
* existing look is preserved.
*/
export function cueColor(cue: CuePoint): string { export function cueColor(cue: CuePoint): string {
return TYPE_COLORS[cue.type] ?? OTHER_COLOR if (cue.color) return cue.color
if (cue.role === 'memory') return MEMORY_COLOR
return TYPE_COLORS[cue.type] ?? MEMORY_COLOR
}
export function cueTypeColor(type: CueType): string {
return TYPE_COLORS[type] ?? MEMORY_COLOR
}
export function cueGlyph(cue: CuePoint): string {
return TYPE_GLYPHS[cue.type] ?? ''
} }
function withAlpha(hex: string, a: number): string { function withAlpha(hex: string, a: number): string {
@@ -46,6 +81,8 @@ export function drawCues(
dpr: number, dpr: number,
timeToX: (t: number) => number, timeToX: (t: number) => number,
labels: boolean, labels: boolean,
/** How a bank slot is labelled — "1".."8" or "A".."H", per the platform. */
slotLabel: (slot: number) => string = (slot) => String(slot + 1),
): void { ): void {
const lineW = Math.max(2, Math.round(2 * dpr)) const lineW = Math.max(2, Math.round(2 * dpr))
const outline = Math.max(1, Math.round(dpr)) const outline = Math.max(1, Math.round(dpr))
@@ -53,10 +90,9 @@ export function drawCues(
const flagH = Math.round(14 * dpr) const flagH = Math.round(14 * dpr)
const half = Math.floor(lineW / 2) const half = Math.floor(lineW / 2)
for (const cue of cues) { for (const cue of cues) {
// Grid markers and their companion cues belong to the beatgrid and are // A grid marker's companion cue is drawn by drawBeatgrid; painting it here
// drawn by drawBeatgrid; painting them here too would stack a grey line and // too would stack a flag on top of every marker line.
// a numbered flag on top of every marker. if (cue.grid_marker != null) continue
if (cue.type === 4 || cue.grid_marker != null) continue
const color = cueColor(cue) const color = cueColor(cue)
const x = Math.round(timeToX(cue.start)) const x = Math.round(timeToX(cue.start))
@@ -78,16 +114,20 @@ export function drawCues(
ctx.fillRect(x - half, 0, lineW, h) ctx.fillRect(x - half, 0, lineW, h)
if (labels) { if (labels) {
// A flag tab at the top for every cue (outlined), with the hotcue number. // A flag tab at the top for every cue (outlined). A banked cue carries its
// slot label; one without a slot (a memory cue) gets a half-height tab, so
// it still reads as a real object rather than an anonymous line.
const banked = cue.slot != null
const tabH = banked ? flagH : Math.round(flagH / 2)
ctx.fillStyle = 'rgba(0,0,0,0.7)' ctx.fillStyle = 'rgba(0,0,0,0.7)'
ctx.fillRect(x - half - outline, 0, flagW + outline * 2, flagH + outline * 2) ctx.fillRect(x - half - outline, 0, flagW + outline * 2, tabH + outline * 2)
ctx.fillStyle = color ctx.fillStyle = color
ctx.fillRect(x - half, 0, flagW, flagH) ctx.fillRect(x - half, 0, flagW, tabH)
if (cue.hotcue >= 0) { if (banked) {
ctx.fillStyle = contrastText(color) ctx.fillStyle = contrastText(color)
ctx.font = `bold ${Math.round(10 * dpr)}px system-ui, sans-serif` ctx.font = `bold ${Math.round(10 * dpr)}px system-ui, sans-serif`
ctx.textBaseline = 'top' ctx.textBaseline = 'top'
ctx.fillText(String(cue.hotcue + 1), x - half + Math.round(2 * dpr), Math.round(2 * dpr)) ctx.fillText(slotLabel(cue.slot!), x - half + Math.round(2 * dpr), Math.round(2 * dpr))
} }
} }
} }
+10 -10
View File
@@ -12,14 +12,14 @@ export function formatBpm(bpm: number | null): string {
return bpm.toFixed(1) return bpm.toFixed(1)
} }
// Traktor stores keys like "10m" / "8d" (Open Key notation) or classic "8A". /**
// Give each of the 12 pitch classes a stable hue so harmonic groups read at a * Hue by wheel position, so harmonically adjacent keys sit adjacent in colour.
// glance — adjacent/compatible keys land near each other on the color wheel. *
export function keyColor(key: string | null): string | undefined { * Takes the parsed Camelot position rather than the key string: "10m" vs "Am"
if (!key) return undefined * vs "8A" is platform notation, and parsing it is the adapter's job. Doing it
const m = key.match(/(\d+)/) * here used to mean every non-Traktor key lost its colour.
if (!m) return undefined */
const n = parseInt(m[1], 10) % 12 export function keyColor(wheel: number | null): string | undefined {
const hue = (n / 12) * 360 if (wheel == null) return undefined
return `hsl(${hue} 65% 62%)` return `hsl(${((wheel % 12) / 12) * 360} 65% 62%)`
} }
+41
View File
@@ -0,0 +1,41 @@
/**
* Wording that names the loaded platform.
*
* The adapter supplies structured facts, never finished sentences, and these
* compose them. That keeps the copy (and any future translation) in the UI while
* staying genuinely specific — the pre-save warning is a real, per-platform
* hazard and must not be watered down into something vague.
*/
import type { SaveCapabilities } from '../api'
export function saveLabel(save: SaveCapabilities): string {
return `Save to ${save.app_name}`
}
/** Shown while there are unsaved changes. Null when the platform has no hazard. */
export function overwriteWarning(save: SaveCapabilities): string | null {
switch (save.overwrite_risk) {
case 'none':
return null
case 'on_exit':
return `Close ${save.app_name} before saving — it overwrites ${save.library_label} on exit.`
case 'while_running':
return `${save.app_name} is open — it may overwrite or re-sync ${save.library_label} while running. Close it before saving.`
}
}
export function restoreWarning(save: SaveCapabilities): string | null {
switch (save.overwrite_risk) {
case 'none':
return null
case 'on_exit':
return `Close ${save.app_name} before restoring — it overwrites ${save.library_label} on exit.`
case 'while_running':
return `${save.app_name} is open — close it before restoring, or it may overwrite ${save.library_label}.`
}
}
/** Trailing hint after an in-memory edit. */
export function writeHint(save: SaveCapabilities): string {
return `Save to ${save.app_name} to write it to disk`
}
+8 -5
View File
@@ -122,12 +122,12 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
) )
}, },
}), }),
col.accessor('is_stem', { col.accessor('media_kind', {
id: 'type', id: 'type',
header: 'Type', header: 'Type',
size: 64, size: 64,
cell: (c) => cell: (c) =>
c.getValue() ? ( c.getValue() === 'stem' ? (
// Stem file → stacked lines ("burger"), the usual stem glyph. // Stem file → stacked lines ("burger"), the usual stem glyph.
<span title="Stem file" className="text-accent"> <span title="Stem file" className="text-accent">
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-label="Stem"> <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-label="Stem">
@@ -168,7 +168,10 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
return ( return (
<span <span
className="rounded px-1.5 py-0.5 text-xs font-semibold" className="rounded px-1.5 py-0.5 text-xs font-semibold"
style={{ color: keyColor(k), background: 'color-mix(in srgb, currentColor 14%, transparent)' }} style={{
color: keyColor(c.row.original.key_wheel),
background: 'color-mix(in srgb, currentColor 14%, transparent)',
}}
> >
{k} {k}
</span> </span>
@@ -211,12 +214,12 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
size: 72, size: 72,
cell: (c) => { cell: (c) => {
const n = c.getValue() const n = c.getValue()
const markers = c.row.original.grid_markers const markers = c.row.original.grid_marker_count
// Gold marks a flexible (multi-tempo) grid, mint an ordinary constant one. // Gold marks a flexible (multi-tempo) grid, mint an ordinary constant one.
return ( return (
<span className="flex items-center gap-1 tabular-nums"> <span className="flex items-center gap-1 tabular-nums">
<span className={n > 0 ? 'text-text' : 'text-faint'}>{n}</span> <span className={n > 0 ? 'text-text' : 'text-faint'}>{n}</span>
{c.row.original.has_grid && ( {markers > 0 && (
<span <span
className={markers > 1 ? 'text-[10px] text-gold' : 'text-[10px] text-mint'} className={markers > 1 ? 'text-[10px] text-gold' : 'text-[10px] text-mint'}
title={markers > 1 ? `Flexible beatgrid (${markers} markers)` : 'Beatgrid analyzed'} title={markers > 1 ? `Flexible beatgrid (${markers} markers)` : 'Beatgrid analyzed'}