mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented basic playlist editing
This commit is contained in:
1 parent
fceaab6d78
commit
3ace90179b
20 files changed
+1523
-105
No files matched your search
@@ -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 `<PLAYLISTS>…</PLAYLISTS>` 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:<name>/<name>`). 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.
|
||||
@@ -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 `<PLAYLISTS>` 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.
|
||||
@@ -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,
|
||||
|
||||
+123
-31
@@ -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())
|
||||
@@ -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
|
||||
<PLAYLISTS> 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
|
||||
<PLAYLISTS>…</PLAYLISTS> span, and splice it into the untouched original bytes.
|
||||
|
||||
Playlists are identified by their stable UUID; folders by a synthetic path id
|
||||
(``fld:<name>/<name>``). 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[ >]")
|
||||
_PLAYLISTS_CLOSE = re.compile(rb"</PLAYLISTS>")
|
||||
|
||||
|
||||
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 <PLAYLISTS> 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
|
||||
@@ -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
|
||||
Executable
+21
@@ -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"
|
||||
@@ -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"<COLLECTION[ >]", data).start()
|
||||
e = re.search(rb"</COLLECTION>", 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)
|
||||
@@ -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 <PLAYLIST …UUID="…">…</PLAYLIST> block."""
|
||||
i = data.find(f'UUID="{uuid}"'.encode())
|
||||
start = data.rfind(b"<PLAYLIST ", 0, i)
|
||||
end = data.find(b"</PLAYLIST>", i) + len(b"</PLAYLIST>")
|
||||
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)
|
||||
Generated
+72
-3
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
+87
-27
@@ -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<Source>({ kind: 'all' })
|
||||
const [filters, setFilters] = useState<Filters>(emptyFilters)
|
||||
const [sorting, setSorting] = useState<SortingState>([])
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set())
|
||||
const [toast, setToast] = useState<ToastMsg | null>(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 (
|
||||
<div className="flex h-screen w-screen overflow-hidden bg-ink-950">
|
||||
<Sidebar
|
||||
source={source}
|
||||
onSelect={(s) => {
|
||||
setSource(s)
|
||||
// Playlists carry a deliberate order; reset sort to preserve it.
|
||||
setSorting([])
|
||||
}}
|
||||
/>
|
||||
<main className="flex min-w-0 flex-1 flex-col">
|
||||
<Toolbar filters={filters} onChange={setFilters} />
|
||||
<Toast toast={toast} onClose={() => setToast(null)} />
|
||||
<Sidebar source={source} onSelect={selectSource} onError={onError} />
|
||||
|
||||
<main className="relative flex min-w-0 flex-1 flex-col">
|
||||
{isAll ? (
|
||||
<Toolbar filters={filters} onChange={setFilters} />
|
||||
) : (
|
||||
<div className="flex items-center gap-3 border-b border-line bg-ink-900 px-4 py-3">
|
||||
<span className="text-[11px] text-accent">♫</span>
|
||||
<span className="font-semibold text-text">{source.name}</span>
|
||||
<span className="text-xs text-faint">
|
||||
{tracks.length} tracks · drag ⠿ to reorder · × to remove
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="min-h-0 flex-1">
|
||||
{loading ? (
|
||||
<div className="flex h-full items-center justify-center text-muted">
|
||||
Loading library…
|
||||
</div>
|
||||
) : filtered.length === 0 ? (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-1 text-muted">
|
||||
<div className="text-lg">No tracks match</div>
|
||||
<div className="text-sm text-faint">Try clearing some filters.</div>
|
||||
</div>
|
||||
<div className="flex h-full items-center justify-center text-muted">Loading…</div>
|
||||
) : isAll ? (
|
||||
filtered.length === 0 ? (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-1 text-muted">
|
||||
<div className="text-lg">No tracks match</div>
|
||||
<div className="text-sm text-faint">Try clearing some filters.</div>
|
||||
</div>
|
||||
) : (
|
||||
<TrackTable
|
||||
tracks={filtered}
|
||||
sorting={sorting}
|
||||
onSortingChange={setSorting}
|
||||
selection={{
|
||||
selected,
|
||||
onToggle: toggle,
|
||||
onToggleAll: toggleAll,
|
||||
allSelected: selected.size > 0 && selected.size === filtered.length,
|
||||
}}
|
||||
/>
|
||||
)
|
||||
) : (
|
||||
<TrackTable tracks={filtered} sorting={sorting} onSortingChange={setSorting} />
|
||||
<PlaylistEditor
|
||||
uuid={(source as { id: string }).id}
|
||||
tracks={tracks}
|
||||
onError={onError}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isAll && (
|
||||
<SelectionBar
|
||||
count={selected.size}
|
||||
trackIds={[...selected]}
|
||||
onClear={() => setSelected(new Set())}
|
||||
onDone={(msg) => notify('success', msg)}
|
||||
onError={onError}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<StatusBar
|
||||
showing={filtered.length}
|
||||
total={tracks.length}
|
||||
sourceName={sourceName}
|
||||
sourceName={isAll ? 'All Tracks' : source.name}
|
||||
loading={loading}
|
||||
/>
|
||||
</main>
|
||||
|
||||
@@ -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<T>(url: string): Promise<T> {
|
||||
const res = await fetch(url)
|
||||
if (!res.ok) throw new Error(`${res.status} ${res.statusText} — ${url}`)
|
||||
return res.json() as Promise<T>
|
||||
}
|
||||
|
||||
async function send<T>(method: string, url: string, body?: unknown): Promise<T> {
|
||||
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<T>
|
||||
}
|
||||
|
||||
function qs(params: Record<string, unknown>): string {
|
||||
const p = new URLSearchParams()
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
@@ -119,4 +149,24 @@ export const api = {
|
||||
getJSON<TrackPage>(`/api/tracks${qs(query as Record<string, unknown>)}`),
|
||||
playlistTracks: (id: string) =>
|
||||
getJSON<Track[]>(`/api/playlists/${id}/tracks`),
|
||||
|
||||
// ---- writes ----
|
||||
state: () => getJSON<EditState>('/api/state'),
|
||||
createPlaylist: (name: string, parentId?: string) =>
|
||||
send<PlaylistNode>('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<SaveResult>('POST', '/api/save'),
|
||||
}
|
||||
@@ -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 (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
style={{ transform: CSS.Transform.toString(transform), transition }}
|
||||
className={`flex items-center border-b border-ink-850 text-sm ${
|
||||
isDragging ? 'z-10 bg-ink-800 shadow-lg' : 'hover:bg-ink-850'
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
title="Drag to reorder"
|
||||
className="w-8 shrink-0 cursor-grab px-2 text-center text-faint hover:text-text active:cursor-grabbing"
|
||||
>
|
||||
⠿
|
||||
</button>
|
||||
<span className="w-8 shrink-0 text-right text-xs tabular-nums text-faint">
|
||||
{index + 1}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1 px-3 py-2">
|
||||
<div className="truncate font-medium text-text">
|
||||
{track.title || <span className="text-faint">Untitled</span>}
|
||||
</div>
|
||||
<div className="truncate text-xs text-muted">{track.artist}</div>
|
||||
</div>
|
||||
<div className="w-16 shrink-0 px-2 text-right tabular-nums">{formatBpm(track.bpm)}</div>
|
||||
<div className="w-14 shrink-0 px-2 text-center">
|
||||
{track.key ? (
|
||||
<span className="text-xs font-semibold" style={{ color: keyColor(track.key) }}>
|
||||
{track.key}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-faint">—</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="w-24 shrink-0 px-2">
|
||||
<RatingStars value={track.rating} />
|
||||
</div>
|
||||
<div className="w-14 shrink-0 px-2 text-right tabular-nums text-muted">
|
||||
{formatDuration(track.length)}
|
||||
</div>
|
||||
<button
|
||||
title="Remove from playlist"
|
||||
onClick={() => onRemove(track.id)}
|
||||
className="w-10 shrink-0 px-2 text-center text-faint hover:text-pink"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function PlaylistEditor({ uuid, tracks, onError }: Props) {
|
||||
const qc = useQueryClient()
|
||||
const [items, setItems] = useState<Track[]>(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 (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-2 text-muted">
|
||||
<div className="text-lg">This playlist is empty</div>
|
||||
<div className="text-sm text-faint">
|
||||
Go to <span className="text-text">All Tracks</span>, select tracks, and add them here.
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full overflow-auto">
|
||||
<div className="sticky top-0 z-10 flex border-b border-line bg-ink-850 text-[11px] font-semibold uppercase tracking-wider text-muted">
|
||||
<span className="w-8 shrink-0" />
|
||||
<span className="w-8 shrink-0 text-right">#</span>
|
||||
<span className="flex-1 px-3 py-2.5">Title</span>
|
||||
<span className="w-16 shrink-0 px-2 text-right">BPM</span>
|
||||
<span className="w-14 shrink-0 px-2 text-center">Key</span>
|
||||
<span className="w-24 shrink-0 px-2">Rating</span>
|
||||
<span className="w-14 shrink-0 px-2 text-right">Time</span>
|
||||
<span className="w-10 shrink-0" />
|
||||
</div>
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={onDragEnd}
|
||||
modifiers={[restrictToVerticalAxis, restrictToParentElement]}
|
||||
>
|
||||
<SortableContext items={items.map((t) => t.id)} strategy={verticalListSortingStrategy}>
|
||||
{items.map((t, i) => (
|
||||
<Row key={t.id} track={t} index={i} onRemove={remove} />
|
||||
))}
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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<string | null>(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 (
|
||||
<div className="border-t border-line bg-ink-900 px-3 py-3">
|
||||
{dirty && (
|
||||
<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.
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
disabled={!dirty || save.isPending}
|
||||
onClick={() => save.mutate()}
|
||||
className={`flex w-full items-center justify-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-colors ${
|
||||
dirty
|
||||
? 'bg-accent text-ink-950 hover:brightness-110'
|
||||
: 'cursor-not-allowed bg-ink-800 text-faint'
|
||||
}`}
|
||||
>
|
||||
{save.isPending ? (
|
||||
'Saving…'
|
||||
) : dirty ? (
|
||||
<>
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-ink-950/60" />
|
||||
Save to Traktor
|
||||
</>
|
||||
) : (
|
||||
'No unsaved changes'
|
||||
)}
|
||||
</button>
|
||||
{justSaved && (
|
||||
<div className="mt-2 text-center text-[11px] text-mint">{justSaved}</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="pointer-events-none absolute inset-x-0 bottom-4 z-20 flex justify-center">
|
||||
<div className="pointer-events-auto flex items-center gap-3 rounded-full border border-line bg-ink-800 py-2 pl-4 pr-2 shadow-xl">
|
||||
<span className="text-sm text-text">
|
||||
<span className="font-semibold tabular-nums">{count}</span> selected
|
||||
</span>
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={() => setMenuOpen((o) => !o)}
|
||||
className="rounded-full bg-accent px-3 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110"
|
||||
>
|
||||
Add to playlist ▾
|
||||
</button>
|
||||
{menuOpen && (
|
||||
<div className="absolute bottom-full right-0 mb-2 max-h-72 w-56 overflow-y-auto rounded-lg border border-line bg-ink-850 p-1 shadow-2xl">
|
||||
{flat.length === 0 && (
|
||||
<div className="px-3 py-2 text-sm text-faint">No playlists yet</div>
|
||||
)}
|
||||
{flat.map((p) => (
|
||||
<button
|
||||
key={p.id}
|
||||
onClick={() => add.mutate({ uuid: p.id, ids: trackIds })}
|
||||
className="flex w-full items-center justify-between gap-2 rounded-md px-3 py-1.5 text-left text-sm text-muted hover:bg-ink-800 hover:text-text"
|
||||
>
|
||||
<span className="truncate">{p.name}</span>
|
||||
<span className="shrink-0 text-[10px] tabular-nums text-faint">{p.count}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={onClear}
|
||||
className="rounded-full px-2 py-1.5 text-sm text-muted hover:bg-ink-700 hover:text-text"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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<string, string> = {
|
||||
@@ -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 (
|
||||
<div>
|
||||
<button
|
||||
onClick={() => {
|
||||
if (isFolder) setOpen((o) => !o)
|
||||
else if (selectable) onSelect({ kind: 'playlist', id: node.id, name: node.name })
|
||||
}}
|
||||
className={`group flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors ${
|
||||
selected
|
||||
? 'bg-accent-soft text-text'
|
||||
: 'text-muted hover:bg-ink-800 hover:text-text'
|
||||
} ${!selectable && !isFolder ? 'cursor-default opacity-70' : ''}`}
|
||||
style={{ paddingLeft: `${8 + depth * 14}px` }}
|
||||
<div
|
||||
className={`group flex items-center gap-1 rounded-md pr-1 text-sm transition-colors ${
|
||||
selected ? 'bg-accent-soft text-text' : 'text-muted hover:bg-ink-800 hover:text-text'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`w-3 shrink-0 text-center text-[11px] ${
|
||||
isFolder ? 'text-faint' : node.type === 'SMARTLIST' ? 'text-pink' : 'text-accent'
|
||||
} ${isFolder && open ? 'rotate-90' : ''} transition-transform`}
|
||||
<button
|
||||
onClick={() => {
|
||||
if (isFolder) setOpen((o) => !o)
|
||||
else if (selectable) onSelect({ kind: 'playlist', id: node.id, name: node.name })
|
||||
}}
|
||||
className={`flex min-w-0 flex-1 items-center gap-2 py-1.5 pl-2 text-left ${
|
||||
!selectable && !isFolder ? 'cursor-default opacity-70' : ''
|
||||
}`}
|
||||
style={{ paddingLeft: `${8 + depth * 14}px` }}
|
||||
>
|
||||
{icons[node.type]}
|
||||
</span>
|
||||
<span className="flex-1 truncate">{node.name}</span>
|
||||
{node.type === 'PLAYLIST' && (
|
||||
<span className="shrink-0 rounded bg-ink-800 px-1.5 py-0.5 text-[10px] tabular-nums text-faint group-hover:bg-ink-700">
|
||||
{node.count}
|
||||
<span
|
||||
className={`w-3 shrink-0 text-center text-[11px] ${
|
||||
isFolder ? 'text-faint' : node.type === 'SMARTLIST' ? 'text-pink' : 'text-accent'
|
||||
} ${isFolder && open ? 'rotate-90' : ''} transition-transform`}
|
||||
>
|
||||
{icons[node.type]}
|
||||
</span>
|
||||
{renaming ? (
|
||||
<input
|
||||
autoFocus
|
||||
value={draft}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
setRenaming(false)
|
||||
if (draft.trim() && draft !== node.name) rename.mutate(draft.trim())
|
||||
} else if (e.key === 'Escape') {
|
||||
setRenaming(false)
|
||||
setDraft(node.name)
|
||||
}
|
||||
}}
|
||||
onBlur={() => {
|
||||
setRenaming(false)
|
||||
setDraft(node.name)
|
||||
}}
|
||||
className="min-w-0 flex-1 rounded border border-accent bg-ink-950 px-1 py-0 text-sm text-text outline-none"
|
||||
/>
|
||||
) : (
|
||||
<span className="flex-1 truncate">{node.name}</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{node.type === 'PLAYLIST' && !renaming && (
|
||||
<>
|
||||
<button
|
||||
title="Rename"
|
||||
onClick={() => {
|
||||
setDraft(node.name)
|
||||
setRenaming(true)
|
||||
}}
|
||||
className="hidden shrink-0 rounded px-1 text-xs text-faint hover:text-text group-hover:block"
|
||||
>
|
||||
✎
|
||||
</button>
|
||||
<button
|
||||
title="Delete playlist"
|
||||
onClick={() => {
|
||||
if (confirm(`Delete playlist "${node.name}"?`)) del.mutate()
|
||||
}}
|
||||
className="hidden shrink-0 rounded px-1 text-xs text-faint hover:text-pink group-hover:block"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
<span className="shrink-0 rounded bg-ink-800 px-1.5 py-0.5 text-[10px] tabular-nums text-faint group-hover:hidden">
|
||||
{node.count}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
{isFolder && open && node.children.length > 0 && (
|
||||
<div>
|
||||
{node.children.map((c) => (
|
||||
@@ -68,6 +148,7 @@ function NodeRow({
|
||||
depth={depth + 1}
|
||||
source={source}
|
||||
onSelect={onSelect}
|
||||
onError={onError}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -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 (
|
||||
<aside className="flex h-full w-64 shrink-0 flex-col border-r border-line bg-ink-900">
|
||||
<div className="flex items-center gap-2 px-4 py-4">
|
||||
@@ -105,10 +205,40 @@ export function Sidebar({ source, onSelect }: Props) {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 px-4 text-[10px] font-semibold uppercase tracking-wider text-faint">
|
||||
Playlists
|
||||
<div className="mt-3 flex items-center justify-between px-4">
|
||||
<span className="text-[10px] font-semibold uppercase tracking-wider text-faint">
|
||||
Playlists
|
||||
</span>
|
||||
<button
|
||||
title="New playlist"
|
||||
onClick={() => {
|
||||
setCreating(true)
|
||||
setNewName('')
|
||||
}}
|
||||
className="rounded px-1 text-sm text-faint hover:text-text"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-1 flex-1 overflow-y-auto px-2 pb-4">
|
||||
{creating && (
|
||||
<input
|
||||
autoFocus
|
||||
value={newName}
|
||||
placeholder="Playlist name…"
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') submitNew()
|
||||
else if (e.key === 'Escape') {
|
||||
setCreating(false)
|
||||
setNewName('')
|
||||
}
|
||||
}}
|
||||
onBlur={submitNew}
|
||||
className="mb-1 w-full rounded-md border border-accent bg-ink-950 px-2 py-1.5 text-sm text-text outline-none"
|
||||
/>
|
||||
)}
|
||||
{isLoading && <div className="px-2 py-2 text-sm text-faint">Loading…</div>}
|
||||
{playlists?.map((n) => (
|
||||
<NodeRow
|
||||
@@ -117,9 +247,12 @@ export function Sidebar({ source, onSelect }: Props) {
|
||||
depth={0}
|
||||
source={source}
|
||||
onSelect={onSelect}
|
||||
onError={onError}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<SaveBar onError={onError} />
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
@@ -23,7 +23,7 @@ export function StatusBar({ showing, total, sourceName, loading }: Props) {
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<span className="ml-auto text-faint">konduktor · phase 2</span>
|
||||
<span className="ml-auto text-faint">konduktor · phase 3</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="pointer-events-none fixed inset-x-0 top-4 z-50 flex justify-center">
|
||||
<div
|
||||
className={`pointer-events-auto max-w-lg rounded-lg border px-4 py-2.5 text-sm shadow-xl ${
|
||||
toast.kind === 'error'
|
||||
? 'border-pink/40 bg-ink-800 text-pink'
|
||||
: 'border-mint/40 bg-ink-800 text-mint'
|
||||
}`}
|
||||
>
|
||||
{toast.text}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -96,15 +96,21 @@ const columns = [
|
||||
}),
|
||||
]
|
||||
|
||||
interface Selection {
|
||||
selected: Set<string>
|
||||
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) {
|
||||
<div style={{ width: totalWidth, minWidth: '100%' }}>
|
||||
{/* Header */}
|
||||
<div className="sticky top-0 z-10 flex border-b border-line bg-ink-850">
|
||||
<span className="w-10 shrink-0" />
|
||||
{selection ? (
|
||||
<span className="flex w-10 shrink-0 items-center justify-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selection.allSelected}
|
||||
onChange={selection.onToggleAll}
|
||||
className="accent-accent"
|
||||
title="Select all"
|
||||
/>
|
||||
</span>
|
||||
) : (
|
||||
<span className="w-10 shrink-0" />
|
||||
)}
|
||||
{table.getHeaderGroups()[0].headers.map((header) => {
|
||||
const sorted = header.column.getIsSorted()
|
||||
return (
|
||||
@@ -160,10 +178,13 @@ export function TrackTable({ tracks, sorting, onSortingChange }: Props) {
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
|
||||
{virtualRows.map((vr) => {
|
||||
const row = rows[vr.index]
|
||||
const isSelected = selection?.selected.has(row.original.id) ?? false
|
||||
return (
|
||||
<div
|
||||
key={row.id}
|
||||
className="absolute left-0 flex items-center border-b border-ink-850 text-sm hover:bg-ink-850"
|
||||
className={`absolute left-0 flex items-center border-b border-ink-850 text-sm ${
|
||||
isSelected ? 'bg-accent-soft/50' : 'hover:bg-ink-850'
|
||||
}`}
|
||||
style={{
|
||||
top: 0,
|
||||
transform: `translateY(${vr.start}px)`,
|
||||
@@ -171,9 +192,20 @@ export function TrackTable({ tracks, sorting, onSortingChange }: Props) {
|
||||
width: '100%',
|
||||
}}
|
||||
>
|
||||
<span className="w-10 shrink-0 pr-2 text-right text-xs tabular-nums text-faint">
|
||||
{vr.index + 1}
|
||||
</span>
|
||||
{selection ? (
|
||||
<span className="flex w-10 shrink-0 items-center justify-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isSelected}
|
||||
onChange={() => selection.onToggle(row.original.id)}
|
||||
className="accent-accent"
|
||||
/>
|
||||
</span>
|
||||
) : (
|
||||
<span className="w-10 shrink-0 pr-2 text-right text-xs tabular-nums text-faint">
|
||||
{vr.index + 1}
|
||||
</span>
|
||||
)}
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<div
|
||||
key={cell.id}
|
||||
|
||||
Reference in new issue
Block a user