From 3ace90179b430ce2e8b0aca87f8d0c8d3ae51fac Mon Sep 17 00:00:00 2001 From: Ben Date: Fri, 3 Jul 2026 13:21:35 +0200 Subject: [PATCH] Implemented basic playlist editing --- CLAUDE.md | 40 +++- README.md | 21 +- backend/konduktor/collection_service.py | 21 +- backend/konduktor/main.py | 154 ++++++++++--- backend/konduktor/playlist_store.py | 250 +++++++++++++++++++++ backend/konduktor/schemas.py | 27 +++ backend/run_tests.sh | 21 ++ backend/test_phase3.py | 141 ++++++++++++ backend/test_save_fidelity.py | 133 +++++++++++ frontend/package-lock.json | 75 ++++++- frontend/package.json | 4 + frontend/src/App.tsx | 114 +++++++--- frontend/src/api.ts | 50 +++++ frontend/src/components/PlaylistEditor.tsx | 166 ++++++++++++++ frontend/src/components/SaveBar.tsx | 63 ++++++ frontend/src/components/SelectionBar.tsx | 83 +++++++ frontend/src/components/Sidebar.tsx | 185 ++++++++++++--- frontend/src/components/StatusBar.tsx | 2 +- frontend/src/components/Toast.tsx | 30 +++ frontend/src/components/TrackTable.tsx | 48 +++- 20 files changed, 1523 insertions(+), 105 deletions(-) create mode 100644 backend/konduktor/playlist_store.py create mode 100755 backend/run_tests.sh create mode 100644 backend/test_phase3.py create mode 100644 backend/test_save_fidelity.py create mode 100644 frontend/src/components/PlaylistEditor.tsx create mode 100644 frontend/src/components/SaveBar.tsx create mode 100644 frontend/src/components/SelectionBar.tsx create mode 100644 frontend/src/components/Toast.tsx diff --git a/CLAUDE.md b/CLAUDE.md index e6dcbcb..97dbf26 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -47,9 +47,17 @@ npm run dev # dev server (proxies /api -> :8000) npm run build # tsc -b && vite build — run this to typecheck ``` -There is no test suite yet. Validate the backend with the Swagger UI at -`http://localhost:8000/docs`; validate the frontend by loading -`http://localhost:5173`. +**Tests:** `cd backend && ./run_tests.sh` (runs against a temp copy of the real +collection). **ALWAYS run this before changing anything in the save / +serialization path.** It enforces: +- `test_save_fidelity.py` — a no-op save is byte-identical, and an edit changes + only the edited playlist's block (this is the guard that catches serialization + regressions like the lxml reformatting bug). +- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays + Traktor-valid, backup-first, COLLECTION byte-identical, original untouched. + +Also validate the backend interactively at `http://localhost:8000/docs` and the +frontend at `http://localhost:5173`. ## Critical gotchas — read these @@ -94,5 +102,29 @@ There is no test suite yet. Validate the backend with the Swagger UI at - ✅ Phase 1 — backend core + read-only API - ✅ Phase 2 — track explorer UI -- ⬜ Phase 3 — playlist editing/creation + safe (backup-first, surgical) saves +- ✅ Phase 3 — playlist editing/creation + safe (backup-first, surgical) saves - ⬜ Phase 4 — polish + optional Tauri desktop packaging + +## Phase 3 write path (playlists) + +- `playlist_store.py` (`PlaylistStore`) edits the **traktor-nml-utils dataclass + model** in memory (create/rename/delete/set-entries). On `save()` it renders + the model, extracts only the freshly rendered `…` span, + and splices it into the original file bytes — COLLECTION stays byte-identical, + and a timestamped `.bak` is written first. +- **Minimal-diff is load-bearing — do NOT re-serialize with lxml.** lxml + reformats the whole PLAYLISTS section (~2500 changed lines). The render MUST + use the library's pipeline: `XmlSerializer().render(nml)` → + `restore_traktor_float_format(s, nml)` → `format_traktor_layout(s)` (both + imported from `traktor_nml_utils`). That reproduces Traktor's exact layout, so + unedited playlists stay byte-identical and only edited entries diff (verified: + a 13-track reorder changes exactly 24 lines). +- Playlists are keyed by their stable `UUID`; folders by synthetic path id + (`fld:/`). PRIMARYKEY `TYPE` is `STEM` if the track has a STEMS + child (`CollectionService.stem_keys`, resolved via `entries_for`), else + `TRACK`. +- `POST /api/save` always writes (backup-first); no write gate. Endpoints: + `POST/PATCH/DELETE /api/playlists[...]`, `PUT .../entries` (replace), + `POST .../add` (append), `POST /api/save`. +- Test: `backend/test_phase3.py` (runs against a temp copy; asserts surgical + + backup + Traktor-valid). Run: `python test_phase3.py` in the backend venv. diff --git a/README.md b/README.md index ada7441..a89263e 100644 --- a/README.md +++ b/README.md @@ -70,8 +70,23 @@ KONDUKTOR_NML=/path/to/collection.nml uvicorn konduktor.main:app --port 8000 - ✅ **Phase 1** — backend core + read-only API - ✅ **Phase 2** — track explorer UI (grid, search, filters, playlist browsing) -- ⬜ **Phase 3** — playlist editing / creation, with backup-first safe saves +- ✅ **Phase 3** — playlist editing/creation (drag-reorder, add/remove, rename, + delete) with surgical, backup-first saves - ⬜ **Phase 4** — polish + optional Tauri desktop packaging -**Safety:** the app never writes to your `.nml`. Writing arrives in Phase 3 and -will always back up first. +## Editing & saving (Phase 3) + +Playlist edits (create/rename/delete, add/remove, drag-reorder) are live in the +UI. Click **Save to Traktor** to write them to `collection.nml`. + +> **Close Traktor before saving** — it overwrites `collection.nml` on exit, so +> it would clobber your changes otherwise. + +**Safety guarantees:** +- Every save writes a timestamped `.bak` backup first. +- Saves are *surgical* — only the `` section is rewritten; the track + `COLLECTION` stays byte-for-byte identical. +- To try it against a copy, point `KONDUKTOR_NML` at one. + +The backend test `backend/test_phase3.py` exercises the full write path against +a temp copy and asserts these guarantees. diff --git a/backend/konduktor/collection_service.py b/backend/konduktor/collection_service.py index b92e3d1..9b36f52 100644 --- a/backend/konduktor/collection_service.py +++ b/backend/konduktor/collection_service.py @@ -48,6 +48,7 @@ class CollectionService: self._lock = threading.Lock() self.tracks: list[Track] = [] self.by_key: dict[str, Track] = {} + self.stem_keys: set[str] = set() self._playlist_entries: dict[str, list[str]] = {} # id -> ordered primary keys self._tree: list[PlaylistNode] = [] self._playlist_count = 0 @@ -59,6 +60,13 @@ class CollectionService: collection = TraktorCollection(path=self.nml_path) self.tracks = [self._to_track(e) for e in collection.nml.collection.entry] self.by_key = {t.id: t for t in self.tracks} + # Tracks with stems use PRIMARYKEY TYPE="STEM" in playlists (verified + # 945/945 against the real collection); all others use "TRACK". + self.stem_keys = { + _primary_key(e.location) + for e in collection.nml.collection.entry + if e.location and getattr(e, "stems", None) is not None + } self._playlist_entries = {} self._playlist_count = 0 counter = {"n": 0} @@ -228,7 +236,16 @@ class CollectionService: total_tracks=len(self.tracks), ) - def stats(self) -> Stats: + def entries_for(self, track_ids: list[str]) -> list[tuple[str, str]]: + """Map track ids to (key, PRIMARYKEY-type) pairs for playlist writing. + Unknown ids are skipped (can't reference a track not in the collection).""" + out = [] + for tid in track_ids: + if tid in self.by_key: + out.append((tid, "STEM" if tid in self.stem_keys else "TRACK")) + return out + + def stats(self, playlist_count: int | None = None) -> Stats: rating_breakdown = {i: 0 for i in range(6)} genres: dict[str, int] = {} bpm_buckets: dict[str, int] = {} @@ -259,7 +276,7 @@ class CollectionService: top = sorted(genres.items(), key=lambda x: -x[1])[:10] return Stats( total_tracks=total, - total_playlists=self._playlist_count, + total_playlists=self._playlist_count if playlist_count is None else playlist_count, rated=rated, unrated=total - rated, missing_key=missing_key, diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index ed56e3f..c75ff81 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -1,4 +1,8 @@ -"""Konduktor FastAPI app — Phase 1 (read-only collection API).""" +"""Konduktor FastAPI app. + +Phase 1-2: read-only collection API. Phase 3: playlist editing with +surgical, backup-first saves (see playlist_store.py). +""" from __future__ import annotations import os @@ -8,27 +12,35 @@ from fastapi import FastAPI, HTTPException, Query from fastapi.middleware.cors import CORSMiddleware from .collection_service import CollectionService -from .schemas import Facets, PlaylistNode, Stats, Track, TrackPage +from .playlist_store import PlaylistError, PlaylistStore +from .schemas import ( + CreatePlaylist, + EditState, + Facets, + PlaylistNode, + RenamePlaylist, + SaveResult, + SetEntries, + Stats, + Track, + TrackPage, +) -# The collection to read. Defaults to the repo-root collection.nml. -# Reading is safe/non-destructive; writes (later phases) always use a copy. +# The collection to read/edit. Defaults to the repo-root collection.nml. DEFAULT_NML = Path(__file__).resolve().parents[2] / "collection.nml" NML_PATH = Path(os.environ.get("KONDUKTOR_NML", DEFAULT_NML)) -app = FastAPI(title="Konduktor API", version="0.1.0") +app = FastAPI(title="Konduktor API", version="0.3.0") -# Vite dev server runs on 5173; allow local dev origins. app.add_middleware( CORSMiddleware, - allow_origins=[ - "http://localhost:5173", - "http://127.0.0.1:5173", - ], + allow_origins=["http://localhost:5173", "http://127.0.0.1:5173"], allow_methods=["*"], allow_headers=["*"], ) _service: CollectionService | None = None +_store: PlaylistStore | None = None def get_service() -> CollectionService: @@ -40,27 +52,46 @@ def get_service() -> CollectionService: return _service +def get_store() -> PlaylistStore: + global _store + if _store is None: + if not NML_PATH.exists(): + raise HTTPException(500, f"NML file not found: {NML_PATH}") + _store = PlaylistStore(NML_PATH) + return _store + + +# ---- health / state --------------------------------------------------- + + @app.get("/api/health") def health() -> dict: - exists = NML_PATH.exists() return { "status": "ok", "nml_path": str(NML_PATH), - "nml_exists": exists, + "nml_exists": NML_PATH.exists(), "loaded": _service is not None, } +@app.get("/api/state", response_model=EditState) +def state() -> EditState: + return EditState(dirty=get_store().dirty, nml_path=str(NML_PATH)) + + @app.post("/api/reload") def reload_collection() -> dict: - svc = get_service() - svc.load() - return {"status": "reloaded", "tracks": len(svc.tracks)} + get_service().load() + get_store()._load() + return {"status": "reloaded", "tracks": len(get_service().tracks)} + + +# ---- read: stats / facets / tracks ------------------------------------ @app.get("/api/stats", response_model=Stats) def stats() -> Stats: - return get_service().stats() + return get_service().stats(playlist_count=get_store().count_playlists()) @app.get("/api/facets", response_model=Facets) @@ -83,28 +114,89 @@ def tracks( offset: int = Query(0, ge=0), ) -> TrackPage: return get_service().query_tracks( - q=q, - genre=genre, - key=key, - bpm_min=bpm_min, - bpm_max=bpm_max, - rating_min=rating_min, - has_cues=has_cues, - sort=sort, - order=order, - limit=limit, - offset=offset, + q=q, genre=genre, key=key, bpm_min=bpm_min, bpm_max=bpm_max, + rating_min=rating_min, has_cues=has_cues, sort=sort, order=order, + limit=limit, offset=offset, ) +# ---- read: playlists (served from the editable store) ----------------- + + @app.get("/api/playlists", response_model=list[PlaylistNode]) def playlists() -> list[PlaylistNode]: - return get_service().playlist_tree() + return get_store().tree() @app.get("/api/playlists/{playlist_id}/tracks", response_model=list[Track]) def playlist_tracks(playlist_id: str) -> list[Track]: - result = get_service().playlist_tracks(playlist_id) - if result is None: + keys = get_store().entry_keys(playlist_id) + if keys is None: raise HTTPException(404, f"Playlist not found: {playlist_id}") - return result + svc = get_service() + return [svc.by_key[k] for k in keys if k in svc.by_key] + + +# ---- write: playlist editing ------------------------------------------ + + +@app.post("/api/playlists", response_model=PlaylistNode) +def create_playlist(body: CreatePlaylist) -> PlaylistNode: + store = get_store() + try: + new_uuid = store.create_playlist(body.name.strip() or "New Playlist", body.parent_id) + except PlaylistError as ex: + raise HTTPException(400, str(ex)) + return PlaylistNode(id=new_uuid, name=body.name, type="PLAYLIST", uuid=new_uuid, count=0) + + +@app.patch("/api/playlists/{playlist_uuid}") +def rename_playlist(playlist_uuid: str, body: RenamePlaylist) -> dict: + try: + get_store().rename_playlist(playlist_uuid, body.name.strip()) + except PlaylistError as ex: + raise HTTPException(404, str(ex)) + return {"status": "renamed", "id": playlist_uuid, "name": body.name} + + +@app.delete("/api/playlists/{playlist_uuid}") +def delete_playlist(playlist_uuid: str) -> dict: + try: + get_store().delete_playlist(playlist_uuid) + except PlaylistError as ex: + raise HTTPException(404, str(ex)) + return {"status": "deleted", "id": playlist_uuid} + + +@app.put("/api/playlists/{playlist_uuid}/entries") +def set_entries(playlist_uuid: str, body: SetEntries) -> dict: + store = get_store() + entries = get_service().entries_for(body.track_ids) + try: + store.set_entries(playlist_uuid, entries) + except PlaylistError as ex: + raise HTTPException(404, str(ex)) + return {"status": "updated", "id": playlist_uuid, "count": len(entries)} + + +@app.post("/api/playlists/{playlist_uuid}/add") +def add_entries(playlist_uuid: str, body: SetEntries) -> dict: + """Append tracks to a playlist (skips ids already present).""" + store = get_store() + current = store.entry_keys(playlist_uuid) + if current is None: + raise HTTPException(404, f"Playlist not found: {playlist_uuid}") + have = set(current) + added = [tid for tid in body.track_ids if tid not in have] + entries = get_service().entries_for(current + added) + store.set_entries(playlist_uuid, entries) + return {"status": "added", "id": playlist_uuid, "added": len(added), "count": len(entries)} + + +@app.post("/api/save", response_model=SaveResult) +def save() -> SaveResult: + store = get_store() + if not store.dirty: + return SaveResult(saved=False, backup=None, playlists=store.count_playlists()) + backup = store.save() + return SaveResult(saved=True, backup=str(backup), playlists=store.count_playlists()) diff --git a/backend/konduktor/playlist_store.py b/backend/konduktor/playlist_store.py new file mode 100644 index 0000000..cd4a98d --- /dev/null +++ b/backend/konduktor/playlist_store.py @@ -0,0 +1,250 @@ +"""Editable playlist store backed by the traktor-nml-utils dataclass model. + +Design goals: + * minimal diff — unedited playlists must serialize byte-for-byte as Traktor + wrote them (the xsdata serializer used by the library reproduces Traktor's + exact formatting; lxml does not), + * surgical — the ~14 MB COLLECTION stays byte-identical (we splice only the + span back into the original file bytes), + * safe — a timestamped .bak is written before every save. + +We edit the parsed dataclass model in memory (create/rename/delete/set-entries), +then on save render the full model, extract just the freshly-rendered +… span, and splice it into the untouched original bytes. + +Playlists are identified by their stable UUID; folders by a synthetic path id +(``fld:/``). Smart playlists are read-only. +""" +from __future__ import annotations + +import re +import shutil +import threading +import time +import uuid as uuidlib +from pathlib import Path + +from traktor_nml_utils import ( + TraktorCollection, + format_traktor_layout, + restore_traktor_float_format, +) +from traktor_nml_utils.models.collection import ( + Entrytype, + Nodetype, + Playlisttype, + Primarykeytype, + Subnodestype, +) +from xsdata.formats.dataclass.serializers import XmlSerializer + +from .schemas import PlaylistNode + +_PLAYLISTS_OPEN = re.compile(rb"]") +_PLAYLISTS_CLOSE = re.compile(rb"") + + +class PlaylistError(Exception): + pass + + +class PlaylistStore: + def __init__(self, nml_path: Path): + self.nml_path = Path(nml_path) + self._lock = threading.RLock() + self.dirty = False + self._load() + + # ---- load ---------------------------------------------------------- + def _load(self) -> None: + self._raw = self.nml_path.read_bytes() + mo = _PLAYLISTS_OPEN.search(self._raw) + mc = _PLAYLISTS_CLOSE.search(self._raw) + if not mo or not mc: + raise PlaylistError("Could not locate section in NML") + self._span = (mo.start(), mc.end()) + self._collection = TraktorCollection(path=self.nml_path) + self._nml = self._collection.nml + self.dirty = False + + def _root(self) -> Nodetype: + node = self._nml.playlists.node if self._nml.playlists else None + if node is None: + raise PlaylistError("PLAYLISTS has no root NODE") + return node + + @staticmethod + def _children(node: Nodetype) -> list[Nodetype]: + return list(node.subnodes.node) if node.subnodes else [] + + # ---- tree walking -------------------------------------------------- + def tree(self) -> list[PlaylistNode]: + with self._lock: + return [self._to_model(c, []) for c in self._children(self._root())] + + def _to_model(self, node: Nodetype, parent_path: list[str]) -> PlaylistNode: + ntype = node.type or "FOLDER" + name = node.name or "(unnamed)" + if ntype == "PLAYLIST" or node.playlist is not None: + pl = node.playlist + keys = self._entry_keys_of(pl) if pl is not None else [] + return PlaylistNode( + id=pl.uuid if pl and pl.uuid else name, + name=name, + type="PLAYLIST", + uuid=pl.uuid if pl else None, + count=len(keys), + ) + if ntype == "SMARTLIST" or node.smartplaylist is not None: + return PlaylistNode( + id="sl:" + "/".join(parent_path + [name]), name=name, type="SMARTLIST" + ) + path = parent_path + [name] + return PlaylistNode( + id="fld:" + "/".join(path), + name=name, + type="FOLDER", + children=[self._to_model(c, path) for c in self._children(node)], + ) + + @staticmethod + def _entry_keys_of(pl: Playlisttype) -> list[str]: + return [ + e.primarykey.key + for e in (pl.entry or []) + if e.primarykey and e.primarykey.key + ] + + # ---- lookups ------------------------------------------------------- + def _iter_nodes(self, node: Nodetype): + yield node + for c in self._children(node): + yield from self._iter_nodes(c) + + def _find_playlist_node(self, playlist_uuid: str) -> Nodetype | None: + for n in self._iter_nodes(self._root()): + if n.playlist is not None and n.playlist.uuid == playlist_uuid: + return n + return None + + def _find_parent_of(self, target: Nodetype) -> Nodetype | None: + for n in self._iter_nodes(self._root()): + if n.subnodes and target in n.subnodes.node: + return n + return None + + def _find_folder(self, folder_id: str | None) -> Nodetype: + root = self._root() + if folder_id in (None, "", "fld:"): + return root + if not folder_id.startswith("fld:"): + raise PlaylistError(f"Not a folder id: {folder_id}") + cur = root + for name in folder_id[len("fld:") :].split("/"): + match = next( + ( + c + for c in self._children(cur) + if (c.type or "FOLDER") == "FOLDER" and c.name == name + ), + None, + ) + if match is None: + raise PlaylistError(f"Folder not found: {folder_id}") + cur = match + return cur + + def entry_keys(self, playlist_uuid: str) -> list[str] | None: + with self._lock: + node = self._find_playlist_node(playlist_uuid) + return None if node is None else self._entry_keys_of(node.playlist) + + # ---- edits --------------------------------------------------------- + def create_playlist(self, name: str, parent_id: str | None = None) -> str: + with self._lock: + folder = self._find_folder(parent_id) + if folder.subnodes is None: + folder.subnodes = Subnodestype(node=[], count=0) + new_uuid = uuidlib.uuid4().hex + node = Nodetype( + type="PLAYLIST", + name=name, + playlist=Playlisttype(entry=[], entries=0, type="LIST", uuid=new_uuid), + ) + folder.subnodes.node.append(node) + folder.subnodes.count = len(folder.subnodes.node) + self.dirty = True + return new_uuid + + def rename_playlist(self, playlist_uuid: str, name: str) -> None: + with self._lock: + node = self._find_playlist_node(playlist_uuid) + if node is None: + raise PlaylistError(f"Playlist not found: {playlist_uuid}") + node.name = name + self.dirty = True + + def delete_playlist(self, playlist_uuid: str) -> None: + with self._lock: + node = self._find_playlist_node(playlist_uuid) + if node is None: + raise PlaylistError(f"Playlist not found: {playlist_uuid}") + parent = self._find_parent_of(node) + if parent is None: + raise PlaylistError("Cannot delete a top-level node") + parent.subnodes.node.remove(node) + parent.subnodes.count = len(parent.subnodes.node) + self.dirty = True + + def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None: + with self._lock: + node = self._find_playlist_node(playlist_uuid) + if node is None: + raise PlaylistError(f"Playlist not found: {playlist_uuid}") + pl = node.playlist + pl.entry = [ + Entrytype(primarykey=Primarykeytype(type=ptype or "TRACK", key=key)) + for key, ptype in entries + ] + pl.entries = len(pl.entry) + self.dirty = True + + def count_playlists(self) -> int: + with self._lock: + return sum(1 for n in self._iter_nodes(self._root()) if n.playlist is not None) + + # ---- persistence --------------------------------------------------- + def save(self) -> Path: + with self._lock: + backup = self._backup() + # Render the full model exactly as the library's save() does — the + # two post-processing steps restore Traktor's precise layout (expanded + # empty tags, 6-decimal floats, newlines), so unedited playlists come + # out byte-for-byte identical and only edited ones diff. + serialized = XmlSerializer().render(self._nml) + serialized = restore_traktor_float_format(serialized, self._nml) + serialized = format_traktor_layout(serialized) + rendered = serialized.encode("utf-8") + ro = _PLAYLISTS_OPEN.search(rendered) + rc = _PLAYLISTS_CLOSE.search(rendered) + if not ro or not rc: + raise PlaylistError("Rendered output missing PLAYLISTS section") + new_pl = rendered[ro.start() : rc.end()] + + s, e = self._span + new_data = self._raw[:s] + new_pl + self._raw[e:] + tmp = self.nml_path.with_suffix(self.nml_path.suffix + ".tmp") + tmp.write_bytes(new_data) + tmp.replace(self.nml_path) + self._load() + return backup + + def _backup(self) -> Path: + stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime()) + backup = self.nml_path.with_name(f"{self.nml_path.name}.{stamp}.bak") + n = 1 + while backup.exists(): + backup = self.nml_path.with_name(f"{self.nml_path.name}.{stamp}-{n}.bak") + n += 1 + shutil.copy2(self.nml_path, backup) + return backup diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 445af97..936f82f 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -79,3 +79,30 @@ class PlaylistNode(BaseModel): PlaylistNode.model_rebuild() + + +# ---- write request bodies ---- + + +class CreatePlaylist(BaseModel): + name: str + parent_id: str | None = None # folder id ("fld:..."); None = root + + +class RenamePlaylist(BaseModel): + name: str + + +class SetEntries(BaseModel): + track_ids: list[str] # ordered; full desired contents of the playlist + + +class SaveResult(BaseModel): + saved: bool + backup: str | None = None + playlists: int + + +class EditState(BaseModel): + dirty: bool # unsaved in-memory playlist changes exist + nml_path: str diff --git a/backend/run_tests.sh b/backend/run_tests.sh new file mode 100755 index 0000000..48c6e2c --- /dev/null +++ b/backend/run_tests.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Run Konduktor's backend tests against a copy of the real collection. +# ALWAYS run this before changing anything in the save/serialization path. +set -uo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")" +source .venv/bin/activate + +fail=0 +for t in test_save_fidelity.py test_phase3.py; do + echo "──────────────────────────────────────────" + echo "▶ $t" + echo "──────────────────────────────────────────" + python "$t" || fail=1 + echo +done + +if [ "$fail" -ne 0 ]; then + echo "❌ TESTS FAILED" + exit 1 +fi +echo "✅ ALL TESTS PASSED" diff --git a/backend/test_phase3.py b/backend/test_phase3.py new file mode 100644 index 0000000..c0837cb --- /dev/null +++ b/backend/test_phase3.py @@ -0,0 +1,141 @@ +"""End-to-end write test for Phase 3. + +Runs against a COPY of the collection (never the original). Verifies: + * create / add-tracks / reorder / rename / delete all work + * save creates a backup and produces a Traktor-parseable file + * the COLLECTION section is byte-identical after save (truly surgical) + * changes survive a reload +""" +import os +import re +import shutil +import sys +import tempfile +import warnings +from pathlib import Path + +warnings.filterwarnings("ignore") + +REAL = Path(__file__).resolve().parents[1] / "collection.nml" +work_dir = Path(tempfile.mkdtemp(prefix="konduktor-test-")) +WORK = work_dir / "collection.nml" +shutil.copy2(REAL, WORK) + +# Snapshot the real file up front; the test only ever touches the copy, so the +# real file must be untouched at the end (regardless of its absolute size). +REAL_STAT = (REAL.stat().st_size, REAL.stat().st_mtime) + +os.environ["KONDUKTOR_NML"] = str(WORK) + +from fastapi.testclient import TestClient # noqa: E402 +from traktor_nml_utils import TraktorCollection # noqa: E402 +import konduktor.main as m # noqa: E402 + +client = TestClient(m.app) + + +def collection_span(data: bytes) -> bytes: + s = re.search(rb"]", data).start() + e = re.search(rb"", data).end() + return data[s:e] + + +def check(label, cond): + print(f" [{'PASS' if cond else 'FAIL'}] {label}") + if not cond: + check.failed = True + + +check.failed = False + +print("== initial read ==") +pls = client.get("/api/playlists").json() +flat = lambda ns: [x for n in ns for x in [n] + flat(n.get("children", []))] +playlists = [n for n in flat(pls) if n["type"] == "PLAYLIST"] +print(f" {len(playlists)} playlists, e.g. {[p['name'] for p in playlists[:3]]}") +donor = next(p for p in playlists if p["count"] >= 5) +donor_tracks = client.get(f"/api/playlists/{donor['id']}/tracks").json() +track_ids = [t["id"] for t in donor_tracks[:5]] +print(f" donor '{donor['name']}' -> using {len(track_ids)} track ids") + +collection_before = collection_span(WORK.read_bytes()) + +print("== create + add + reorder + rename ==") +created = client.post("/api/playlists", json={"name": "Konduktor Test"}).json() +new_uuid = created["uuid"] +check("create returns uuid", bool(new_uuid)) + +r = client.put(f"/api/playlists/{new_uuid}/entries", json={"track_ids": track_ids}) +check("add 5 entries", r.json().get("count") == 5) + +reordered = list(reversed(track_ids)) +client.put(f"/api/playlists/{new_uuid}/entries", json={"track_ids": reordered}) + +client.patch(f"/api/playlists/{new_uuid}", json={"name": "Konduktor Test 2"}) + +st = client.get("/api/state").json() +check("state is dirty before save", st["dirty"] is True) + +print("== save ==") +res = client.post("/api/save").json() +check("saved", res["saved"] is True) +backup = Path(res["backup"]) +check("backup file exists", backup.exists()) +check("backup matches original size", backup.stat().st_size == REAL.stat().st_size) +st = client.get("/api/state").json() +check("state clean after save", st["dirty"] is False) + +print("== verify saved file ==") +data_after = WORK.read_bytes() +check( + "COLLECTION section byte-identical (surgical write)", + collection_span(data_after) == collection_before, +) +# Re-parse with the real Traktor library (proves it stays v4-valid). +coll = TraktorCollection(path=WORK) +check("file re-parses with traktor-nml-utils", len(coll.nml.collection.entry) == 8485) + + +def walk(n): + yield n + if n.subnodes: + for s in n.subnodes.node: + yield from walk(s) + + +found = [ + n + for n in walk(coll.nml.playlists.node) + if n.type == "PLAYLIST" and n.playlist and n.playlist.uuid == new_uuid +] +check("new playlist present in saved file", len(found) == 1) +if found: + node = found[0] + check("renamed correctly", node.name == "Konduktor Test 2") + check("ENTRIES attr synced to 5", node.playlist.entries == 5) + saved_keys = [e.primarykey.key for e in node.playlist.entry] + check("entries reordered correctly", saved_keys == reordered) + +print("== reload + delete ==") +client.post("/api/reload") +pls2 = flat(client.get("/api/playlists").json()) +check("new playlist visible after reload", any(n["id"] == new_uuid for n in pls2)) +client.delete(f"/api/playlists/{new_uuid}") +res2 = client.post("/api/save").json() +coll2 = TraktorCollection(path=WORK) +still = [ + n for n in walk(coll2.nml.playlists.node) + if n.type == "PLAYLIST" and n.playlist and n.playlist.uuid == new_uuid +] +check("playlist gone after delete+save", len(still) == 0) +check("COLLECTION still byte-identical", collection_span(WORK.read_bytes()) == collection_before) + +print("== original untouched ==") +check( + "original collection.nml never modified", + (REAL.stat().st_size, REAL.stat().st_mtime) == REAL_STAT, +) + +shutil.rmtree(work_dir, ignore_errors=True) +print("\nRESULT:", "FAILED" if check.failed else "ALL PASSED") +sys.exit(1 if check.failed else 0) diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py new file mode 100644 index 0000000..e4d4e7d --- /dev/null +++ b/backend/test_save_fidelity.py @@ -0,0 +1,133 @@ +"""Regression guard for save fidelity — keeps playlist diffs minimal. + +This is the test that would have caught the lxml reformatting bug. It asserts +two invariants against a COPY of the real collection: + + A. NO-OP SAVE IS BYTE-IDENTICAL. + Loading and saving with zero edits must reproduce the file exactly. Any + serialization change (lxml, a different render pipeline, dropped + float-format/layout post-processing) breaks this immediately. + + B. AN EDIT IS FULLY LOCALIZED. + Editing one playlist must change ONLY that playlist's block. Everything + else in the file — other playlists, folders, smart playlists, and the + entire COLLECTION — must stay byte-for-byte identical. + +Run: `python test_save_fidelity.py` in the backend venv (see run_tests.sh). +""" +import shutil +import sys +import tempfile +import warnings +from pathlib import Path + +warnings.filterwarnings("ignore") + +REAL = Path(__file__).resolve().parents[1] / "collection.nml" + +from konduktor.collection_service import CollectionService # noqa: E402 +from konduktor.playlist_store import PlaylistStore # noqa: E402 + +failed = False + + +def check(label, cond, detail=""): + global failed + print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else "")) + if not cond: + failed = True + + +def playlist_block_span(data: bytes, uuid: str): + """Byte span of a playlist's … block.""" + i = data.find(f'UUID="{uuid}"'.encode()) + start = data.rfind(b"", i) + len(b"") + return start, end + + +def tag_lines(b: bytes) -> list[str]: + return b.replace(b"><", b">\n<").decode("utf-8", "replace").splitlines() + + +def diff_count(a: bytes, b: bytes) -> int: + import difflib + + la, lb = tag_lines(a), tag_lines(b) + return sum( + 1 + for d in difflib.unified_diff(la, lb, n=0) + if d[:1] in "+-" and not d.startswith(("+++", "---")) + ) + + +# ---- Invariant A: no-op save is byte-identical ------------------------ +print("== A. no-op save is byte-identical ==") +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + before = work.read_bytes() + store = PlaylistStore(work) + store.save() # no edits + after = work.read_bytes() + check("whole file identical after no-op save", before == after) + if before != after: + for i, (x, y) in enumerate(zip(before, after)): + if x != y: + check.detail = i + print(f" first byte diff @ {i}") + print(" before:", before[max(0, i - 50) : i + 50]) + print(" after :", after[max(0, i - 50) : i + 50]) + break + +# ---- Invariant B: an edit is fully localized -------------------------- +print("== B. edit touches only the edited playlist ==") +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + original = work.read_bytes() + + svc = CollectionService(work) + store = PlaylistStore(work) + + def walk(n): + yield n + if n.subnodes: + for c in n.subnodes.node: + yield from walk(c) + + target = next( + n for n in walk(store._root()) if n.playlist and n.playlist.uuid and len(n.playlist.entry or []) >= 5 + ) + uuid = target.playlist.uuid + keys = store.entry_keys(uuid) + + store.set_entries(uuid, svc.entries_for(list(reversed(keys)))) + store.save() + edited = work.read_bytes() + + check("file actually changed", original != edited) + + # Blank out the edited playlist's block in both; the remainder must match. + os_, oe = playlist_block_span(original, uuid) + es_, ee = playlist_block_span(edited, uuid) + rest_original = original[:os_] + b"@@BLOCK@@" + original[oe:] + rest_edited = edited[:es_] + b"@@BLOCK@@" + edited[ee:] + check( + "everything outside the edited playlist is byte-identical", + rest_original == rest_edited, + ) + + # A pure reorder must preserve the exact set of lines in the block (only + # their order changes). If the block were reformatted, the multiset differs. + before_lines = sorted(tag_lines(original[os_:oe])) + after_lines = sorted(tag_lines(edited[es_:ee])) + check( + "edited block is a pure reorder (line multiset unchanged, no reformat)", + before_lines == after_lines, + ) + n = diff_count(original[os_:oe], edited[es_:ee]) + print(f" edited-block changed lines: {n} (reordered {len(keys)} entries)") + +print("\nRESULT:", "FAILED" if failed else "ALL PASSED") +sys.exit(1 if failed else 0) diff --git a/frontend/package-lock.json b/frontend/package-lock.json index e8fe867..436efc3 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -8,6 +8,10 @@ "name": "frontend", "version": "0.0.0", "dependencies": { + "@dnd-kit/core": "^6.3.1", + "@dnd-kit/modifiers": "^9.0.0", + "@dnd-kit/sortable": "^10.0.0", + "@dnd-kit/utilities": "^3.2.2", "@tanstack/react-query": "^5.101.2", "@tanstack/react-table": "^8.21.3", "@tanstack/react-virtual": "^3.14.5", @@ -41,6 +45,73 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/@dnd-kit/accessibility": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz", + "integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/core": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz", + "integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==", + "license": "MIT", + "dependencies": { + "@dnd-kit/accessibility": "^3.1.1", + "@dnd-kit/utilities": "^3.2.2", + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/modifiers": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/@dnd-kit/modifiers/-/modifiers-9.0.0.tgz", + "integrity": "sha512-ybiLc66qRGuZoC20wdSSG6pDXFikui/dCNGthxv4Ndy8ylErY0N3KVxY2bgo7AWwIbxDmXDg3ylAFmnrjcbVvw==", + "license": "MIT", + "dependencies": { + "@dnd-kit/utilities": "^3.2.2", + "tslib": "^2.0.0" + }, + "peerDependencies": { + "@dnd-kit/core": "^6.3.0", + "react": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/sortable": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz", + "integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==", + "license": "MIT", + "dependencies": { + "@dnd-kit/utilities": "^3.2.2", + "tslib": "^2.0.0" + }, + "peerDependencies": { + "@dnd-kit/core": "^6.3.0", + "react": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/utilities": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz", + "integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, "node_modules/@emnapi/core": { "version": "1.11.1", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz", @@ -1966,9 +2037,7 @@ "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "dev": true, - "license": "0BSD", - "optional": true + "license": "0BSD" }, "node_modules/typescript": { "version": "6.0.3", diff --git a/frontend/package.json b/frontend/package.json index 9732a79..2b6a272 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -10,6 +10,10 @@ "preview": "vite preview" }, "dependencies": { + "@dnd-kit/core": "^6.3.1", + "@dnd-kit/modifiers": "^9.0.0", + "@dnd-kit/sortable": "^10.0.0", + "@dnd-kit/utilities": "^3.2.2", "@tanstack/react-query": "^5.101.2", "@tanstack/react-table": "^8.21.3", "@tanstack/react-virtual": "^3.14.5", diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index a80ea6c..7a93266 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,11 +1,14 @@ -import { useMemo, useState } from 'react' +import { useCallback, useMemo, useState } from 'react' import { useQuery } from '@tanstack/react-query' import type { SortingState } from '@tanstack/react-table' import { api, type Track } from './api' import { Sidebar, type Source } from './components/Sidebar' import { Toolbar, emptyFilters, type Filters } from './components/Toolbar' import { TrackTable } from './components/TrackTable' +import { PlaylistEditor } from './components/PlaylistEditor' +import { SelectionBar } from './components/SelectionBar' import { StatusBar } from './components/StatusBar' +import { Toast, type ToastMsg } from './components/Toast' function applyFilters(tracks: Track[], f: Filters): Track[] { const q = f.search.trim().toLowerCase() @@ -31,57 +34,114 @@ export default function App() { const [source, setSource] = useState({ kind: 'all' }) const [filters, setFilters] = useState(emptyFilters) const [sorting, setSorting] = useState([]) + const [selected, setSelected] = useState>(new Set()) + const [toast, setToast] = useState(null) + + const notify = useCallback((kind: ToastMsg['kind'], text: string) => { + setToast({ id: Date.now(), kind, text }) + }, []) + const onError = useCallback((msg: string) => notify('error', msg), [notify]) const allTracks = useQuery({ queryKey: ['tracks', 'all'], queryFn: () => api.tracks({ limit: 20000, sort: 'artist' }), enabled: source.kind === 'all', }) - const playlistTracks = useQuery({ queryKey: ['playlist', source.kind === 'playlist' ? source.id : null], queryFn: () => api.playlistTracks((source as { id: string }).id), enabled: source.kind === 'playlist', }) - const tracks: Track[] = - source.kind === 'all' ? (allTracks.data?.items ?? []) : (playlistTracks.data ?? []) - const loading = source.kind === 'all' ? allTracks.isLoading : playlistTracks.isLoading + const isAll = source.kind === 'all' + const tracks: Track[] = isAll ? (allTracks.data?.items ?? []) : (playlistTracks.data ?? []) + const loading = isAll ? allTracks.isLoading : playlistTracks.isLoading + const filtered = useMemo(() => (isAll ? applyFilters(tracks, filters) : tracks), [ + isAll, + tracks, + filters, + ]) - const filtered = useMemo(() => applyFilters(tracks, filters), [tracks, filters]) + const selectSource = (s: Source) => { + setSource(s) + setSorting([]) + setSelected(new Set()) + } - const sourceName = source.kind === 'all' ? 'All Tracks' : source.name + const toggle = (id: string) => + setSelected((prev) => { + const next = new Set(prev) + next.has(id) ? next.delete(id) : next.add(id) + return next + }) + const toggleAll = () => + setSelected((prev) => + prev.size === filtered.length ? new Set() : new Set(filtered.map((t) => t.id)), + ) return (
- { - setSource(s) - // Playlists carry a deliberate order; reset sort to preserve it. - setSorting([]) - }} - /> -
- + setToast(null)} /> + + +
+ {isAll ? ( + + ) : ( +
+ ♫ + {source.name} + + {tracks.length} tracks · drag ⠿ to reorder · × to remove + +
+ )} +
{loading ? ( -
- Loading library… -
- ) : filtered.length === 0 ? ( -
-
No tracks match
-
Try clearing some filters.
-
+
Loading…
+ ) : isAll ? ( + filtered.length === 0 ? ( +
+
No tracks match
+
Try clearing some filters.
+
+ ) : ( + 0 && selected.size === filtered.length, + }} + /> + ) ) : ( - + + )} + + {isAll && ( + setSelected(new Set())} + onDone={(msg) => notify('success', msg)} + onError={onError} + /> )}
+
diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 659069f..597ed08 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -96,12 +96,42 @@ export interface TrackQuery { offset?: number } +export interface EditState { + dirty: boolean + nml_path: string +} + +export interface SaveResult { + saved: boolean + backup: string | null + playlists: number +} + async function getJSON(url: string): Promise { const res = await fetch(url) if (!res.ok) throw new Error(`${res.status} ${res.statusText} — ${url}`) return res.json() as Promise } +async function send(method: string, url: string, body?: unknown): Promise { + const res = await fetch(url, { + method, + headers: body ? { 'Content-Type': 'application/json' } : undefined, + body: body ? JSON.stringify(body) : undefined, + }) + if (!res.ok) { + let detail = `${res.status} ${res.statusText}` + try { + const j = await res.json() + if (j.detail) detail = j.detail + } catch { + /* ignore */ + } + throw new Error(detail) + } + return res.json() as Promise +} + function qs(params: Record): string { const p = new URLSearchParams() for (const [k, v] of Object.entries(params)) { @@ -119,4 +149,24 @@ export const api = { getJSON(`/api/tracks${qs(query as Record)}`), playlistTracks: (id: string) => getJSON(`/api/playlists/${id}/tracks`), + + // ---- writes ---- + state: () => getJSON('/api/state'), + createPlaylist: (name: string, parentId?: string) => + send('POST', '/api/playlists', { name, parent_id: parentId ?? null }), + renamePlaylist: (uuid: string, name: string) => + send<{ status: string }>('PATCH', `/api/playlists/${uuid}`, { name }), + deletePlaylist: (uuid: string) => + send<{ status: string }>('DELETE', `/api/playlists/${uuid}`), + setEntries: (uuid: string, trackIds: string[]) => + send<{ status: string; count: number }>('PUT', `/api/playlists/${uuid}/entries`, { + track_ids: trackIds, + }), + addEntries: (uuid: string, trackIds: string[]) => + send<{ status: string; added: number; count: number }>( + 'POST', + `/api/playlists/${uuid}/add`, + { track_ids: trackIds }, + ), + save: () => send('POST', '/api/save'), } diff --git a/frontend/src/components/PlaylistEditor.tsx b/frontend/src/components/PlaylistEditor.tsx new file mode 100644 index 0000000..5a0e7b0 --- /dev/null +++ b/frontend/src/components/PlaylistEditor.tsx @@ -0,0 +1,166 @@ +import { useEffect, useState } from 'react' +import { useMutation, useQueryClient } from '@tanstack/react-query' +import { + DndContext, + closestCenter, + PointerSensor, + useSensor, + useSensors, + type DragEndEvent, +} from '@dnd-kit/core' +import { + SortableContext, + useSortable, + verticalListSortingStrategy, + arrayMove, +} from '@dnd-kit/sortable' +import { CSS } from '@dnd-kit/utilities' +import { restrictToVerticalAxis, restrictToParentElement } from '@dnd-kit/modifiers' +import { api, type Track } from '../api' +import { formatBpm, formatDuration, keyColor } from '../lib/format' +import { RatingStars } from './RatingStars' + +interface Props { + uuid: string + tracks: Track[] + onError: (msg: string) => void +} + +function Row({ + track, + index, + onRemove, +}: { + track: Track + index: number + onRemove: (id: string) => void +}) { + const { attributes, listeners, setNodeRef, transform, transition, isDragging } = + useSortable({ id: track.id }) + + return ( +
+ + + {index + 1} + +
+
+ {track.title || Untitled} +
+
{track.artist}
+
+
{formatBpm(track.bpm)}
+
+ {track.key ? ( + + {track.key} + + ) : ( + — + )} +
+
+ +
+
+ {formatDuration(track.length)} +
+ +
+ ) +} + +export function PlaylistEditor({ uuid, tracks, onError }: Props) { + const qc = useQueryClient() + const [items, setItems] = useState(tracks) + + // Re-sync when the server data changes (initial load, or tracks added elsewhere). + useEffect(() => setItems(tracks), [tracks]) + + const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 4 } })) + + const persist = useMutation({ + mutationFn: (ids: string[]) => api.setEntries(uuid, ids), + onSuccess: () => { + qc.invalidateQueries({ queryKey: ['state'] }) + qc.invalidateQueries({ queryKey: ['playlists'] }) // refresh counts + }, + onError: (e: Error) => onError(e.message), + }) + + const commit = (next: Track[]) => { + setItems(next) + // Keep the cached playlist query in sync so navigating away/back is stable. + qc.setQueryData(['playlist', uuid], next) + persist.mutate(next.map((t) => t.id)) + } + + const onDragEnd = (e: DragEndEvent) => { + const { active, over } = e + if (!over || active.id === over.id) return + const from = items.findIndex((t) => t.id === active.id) + const to = items.findIndex((t) => t.id === over.id) + if (from < 0 || to < 0) return + commit(arrayMove(items, from, to)) + } + + const remove = (id: string) => commit(items.filter((t) => t.id !== id)) + + if (items.length === 0) { + return ( +
+
This playlist is empty
+
+ Go to All Tracks, select tracks, and add them here. +
+
+ ) + } + + return ( +
+
+ + # + Title + BPM + Key + Rating + Time + +
+ + t.id)} strategy={verticalListSortingStrategy}> + {items.map((t, i) => ( + + ))} + + +
+ ) +} diff --git a/frontend/src/components/SaveBar.tsx b/frontend/src/components/SaveBar.tsx new file mode 100644 index 0000000..1be5a09 --- /dev/null +++ b/frontend/src/components/SaveBar.tsx @@ -0,0 +1,63 @@ +import { useState } from 'react' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { api } from '../api' + +interface Props { + onError: (msg: string) => void +} + +// Bottom-of-sidebar save control. Shows unsaved-changes state and writes to the +// NML (backup-first). On-disk saving is gated server-side by KONDUKTOR_ALLOW_WRITE. +export function SaveBar({ onError }: Props) { + const qc = useQueryClient() + const [justSaved, setJustSaved] = useState(null) + const { data: state } = useQuery({ queryKey: ['state'], queryFn: api.state }) + + const save = useMutation({ + mutationFn: api.save, + onSuccess: (res) => { + qc.invalidateQueries({ queryKey: ['state'] }) + if (res.saved && res.backup) { + const name = res.backup.split('/').pop() + setJustSaved(`Saved · backup ${name}`) + setTimeout(() => setJustSaved(null), 6000) + } + }, + onError: (e: Error) => onError(e.message), + }) + + const dirty = state?.dirty ?? false + + return ( +
+ {dirty && ( +
+ ⚠ Close Traktor before saving — it overwrites the collection on exit. +
+ )} + + {justSaved && ( +
{justSaved}
+ )} +
+ ) +} diff --git a/frontend/src/components/SelectionBar.tsx b/frontend/src/components/SelectionBar.tsx new file mode 100644 index 0000000..3e038f8 --- /dev/null +++ b/frontend/src/components/SelectionBar.tsx @@ -0,0 +1,83 @@ +import { useState } from 'react' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { api, type PlaylistNode } from '../api' + +interface Props { + count: number + trackIds: string[] + onClear: () => void + onDone: (msg: string) => void + onError: (msg: string) => void +} + +function flattenPlaylists(nodes: PlaylistNode[]): PlaylistNode[] { + return nodes.flatMap((n) => [ + ...(n.type === 'PLAYLIST' ? [n] : []), + ...flattenPlaylists(n.children), + ]) +} + +// Floating action bar shown when tracks are selected in the explorer. +export function SelectionBar({ count, trackIds, onClear, onDone, onError }: Props) { + const qc = useQueryClient() + const [menuOpen, setMenuOpen] = useState(false) + const { data: playlists } = useQuery({ queryKey: ['playlists'], queryFn: api.playlists }) + const flat = playlists ? flattenPlaylists(playlists) : [] + + const add = useMutation({ + mutationFn: ({ uuid, ids }: { uuid: string; ids: string[] }) => api.addEntries(uuid, ids), + onSuccess: (res, vars) => { + qc.invalidateQueries({ queryKey: ['state'] }) + qc.invalidateQueries({ queryKey: ['playlists'] }) + qc.invalidateQueries({ queryKey: ['playlist', vars.uuid] }) + const pl = flat.find((p) => p.id === vars.uuid) + onDone(`Added ${res.added} track${res.added === 1 ? '' : 's'} to ${pl?.name ?? 'playlist'}`) + setMenuOpen(false) + onClear() + }, + onError: (e: Error) => onError(e.message), + }) + + if (count === 0) return null + + return ( +
+
+ + {count} selected + +
+ + {menuOpen && ( +
+ {flat.length === 0 && ( +
No playlists yet
+ )} + {flat.map((p) => ( + + ))} +
+ )} +
+ +
+
+ ) +} diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index 90d292d..cbce89f 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -1,12 +1,14 @@ import { useState } from 'react' -import { useQuery } from '@tanstack/react-query' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { api, type PlaylistNode } from '../api' +import { SaveBar } from './SaveBar' export type Source = { kind: 'all' } | { kind: 'playlist'; id: string; name: string } interface Props { source: Source onSelect: (s: Source) => void + onError: (msg: string) => void } const icons: Record = { @@ -20,45 +22,123 @@ function NodeRow({ depth, source, onSelect, + onError, }: { node: PlaylistNode depth: number source: Source onSelect: (s: Source) => void + onError: (msg: string) => void }) { + const qc = useQueryClient() const [open, setOpen] = useState(true) + const [renaming, setRenaming] = useState(false) + const [draft, setDraft] = useState(node.name) const isFolder = node.type === 'FOLDER' const selected = source.kind === 'playlist' && source.id === node.id const selectable = node.type === 'PLAYLIST' + const invalidate = () => { + qc.invalidateQueries({ queryKey: ['playlists'] }) + qc.invalidateQueries({ queryKey: ['state'] }) + } + + const rename = useMutation({ + mutationFn: (name: string) => api.renamePlaylist(node.id, name), + onSuccess: (_d, name) => { + invalidate() + if (source.kind === 'playlist' && source.id === node.id) + onSelect({ kind: 'playlist', id: node.id, name }) + }, + onError: (e: Error) => onError(e.message), + }) + + const del = useMutation({ + mutationFn: () => api.deletePlaylist(node.id), + onSuccess: () => { + invalidate() + if (source.kind === 'playlist' && source.id === node.id) onSelect({ kind: 'all' }) + }, + onError: (e: Error) => onError(e.message), + }) + return (
- + + {node.type === 'PLAYLIST' && !renaming && ( + <> + + + + {node.count} + + )} - +
{isFolder && open && node.children.length > 0 && (
{node.children.map((c) => ( @@ -68,6 +148,7 @@ function NodeRow({ depth={depth + 1} source={source} onSelect={onSelect} + onError={onError} /> ))}
@@ -76,12 +157,31 @@ function NodeRow({ ) } -export function Sidebar({ source, onSelect }: Props) { +export function Sidebar({ source, onSelect, onError }: Props) { + const qc = useQueryClient() + const [creating, setCreating] = useState(false) + const [newName, setNewName] = useState('') const { data: playlists, isLoading } = useQuery({ queryKey: ['playlists'], queryFn: api.playlists, }) + const create = useMutation({ + mutationFn: (name: string) => api.createPlaylist(name), + onSuccess: (pl) => { + qc.invalidateQueries({ queryKey: ['playlists'] }) + qc.invalidateQueries({ queryKey: ['state'] }) + onSelect({ kind: 'playlist', id: pl.id, name: pl.name }) + }, + onError: (e: Error) => onError(e.message), + }) + + const submitNew = () => { + setCreating(false) + if (newName.trim()) create.mutate(newName.trim()) + setNewName('') + } + return ( ) } diff --git a/frontend/src/components/StatusBar.tsx b/frontend/src/components/StatusBar.tsx index ba60599..61ca7af 100644 --- a/frontend/src/components/StatusBar.tsx +++ b/frontend/src/components/StatusBar.tsx @@ -23,7 +23,7 @@ export function StatusBar({ showing, total, sourceName, loading }: Props) { )} )} - konduktor · phase 2 + konduktor · phase 3
) } diff --git a/frontend/src/components/Toast.tsx b/frontend/src/components/Toast.tsx new file mode 100644 index 0000000..7aac3d3 --- /dev/null +++ b/frontend/src/components/Toast.tsx @@ -0,0 +1,30 @@ +import { useEffect } from 'react' + +export interface ToastMsg { + id: number + kind: 'success' | 'error' + text: string +} + +export function Toast({ toast, onClose }: { toast: ToastMsg | null; onClose: () => void }) { + useEffect(() => { + if (!toast) return + const t = setTimeout(onClose, toast.kind === 'error' ? 6000 : 4000) + return () => clearTimeout(t) + }, [toast, onClose]) + + if (!toast) return null + return ( +
+
+ {toast.text} +
+
+ ) +} diff --git a/frontend/src/components/TrackTable.tsx b/frontend/src/components/TrackTable.tsx index cd5e9e0..a81629d 100644 --- a/frontend/src/components/TrackTable.tsx +++ b/frontend/src/components/TrackTable.tsx @@ -96,15 +96,21 @@ const columns = [ }), ] +interface Selection { + selected: Set + onToggle: (id: string) => void + onToggleAll: () => void + allSelected: boolean +} + interface Props { tracks: Track[] sorting: SortingState onSortingChange: (s: SortingState) => void - // Playlists have a meaningful order; disable default sort to preserve it. - ordered?: boolean + selection?: Selection } -export function TrackTable({ tracks, sorting, onSortingChange }: Props) { +export function TrackTable({ tracks, sorting, onSortingChange, selection }: Props) { const table = useReactTable({ data: tracks, columns, @@ -137,7 +143,19 @@ export function TrackTable({ tracks, sorting, onSortingChange }: Props) {
{/* Header */}
- + {selection ? ( + + + + ) : ( + + )} {table.getHeaderGroups()[0].headers.map((header) => { const sorted = header.column.getIsSorted() return ( @@ -160,10 +178,13 @@ export function TrackTable({ tracks, sorting, onSortingChange }: Props) {
{virtualRows.map((vr) => { const row = rows[vr.index] + const isSelected = selection?.selected.has(row.original.id) ?? false return (
- - {vr.index + 1} - + {selection ? ( + + selection.onToggle(row.original.id)} + className="accent-accent" + /> + + ) : ( + + {vr.index + 1} + + )} {row.getVisibleCells().map((cell) => (