diff --git a/CLAUDE.md b/CLAUDE.md index f52243a..c30fdf3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -35,6 +35,21 @@ Two independent apps that talk over HTTP: - `adapter.py` — the `LibraryAdapter` / `LibraryDriver` protocols and the error tree (`NotFound` → 404, `InvalidCommand` → 400, `Unsupported` → 422), mapped to status codes once in `main.py` rather than per route. + **`move_playlist(node_id, parent_id, index)`** (sidebar drag and drop, + `POST /api/playlists/move`) moves any tree node; `index` counts the new + parent's children WITHOUT the node, and it returns the node's id AFTER + the move — a Traktor folder's / smart playlist's id is its path, so it + changes (playlists keep their UUID, so export sets never need + retargeting). Gated per node on `PlaylistNode.can_move`. Traktor refuses a + folder or smart playlist landing beside a namesake (as rename does); + Rekordbox renumbers `Seq` itself (pyrekordbox's version cannot move to the + top level) and keeps `masterPlaylists6.xml`'s `ParentId` in step; + OneLibrary renumbers `sequenceNo` from 0, and the pdb follows at Save. + `POST /api/playlists/{id}/add` takes `duplicates`: `skip` / `add` / `ask` + (nothing changes, the count comes back so the UI can ask and resend); + `add` only where `capabilities.playlists.duplicates` — Traktor only, since + OneLibrary's `playlist_content` is keyed on (playlist, content) and + rekordbox's tolerance of a repeat is unmeasured. - `capabilities.py` — `Capabilities`: what the loaded library can persist, so the UI can gate controls instead of branching on the platform. - `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over @@ -811,6 +826,21 @@ Two independent apps that talk over HTTP: space below the rows creates at the top level, and the new node is named in place (Esc or an empty name creates nothing). Rename/Delete are on the same menu and the row's hover buttons, which share one set of actions. + **Drag and drop** (lib/drag.tsx, below): a row is a drag source and a drop + target with ZONES — a playlist's upper/lower half is before/after; a + folder's top/bottom quarter before/after and its middle INTO (appended), + except the bottom quarter of an OPEN folder, which is "first inside"; the + empty space below the rows is "end of the top level". Never into the + dragged node's own subtree, and a drop that would change nothing shows no + indicator. Holding over a collapsed folder opens it after 0.6 s (tracks + too, so nested playlists are reachable). Tracks dropped on a playlist go + through `lib/addTracks.ts` — shared with the context menu's "Add to" — + which ASKS about duplicates where the platform can hold them (decided: + ask each time), and Option/Alt moves them out of the editable playlist + they came from. A device's or Files folder's tracks open `ImportDialog` + (`trackIds` + `target`) / `AddFilesDialog` with the target filled in + (`onAddForeign`), so copy-vs-reference is still asked. Export rows take the + collection's tracks and any playlist/folder (as "Add to export" does). A Traktor folder's id is its PATH of names, so the `PATCH`/`DELETE` playlist routes take a `:path` param, a folder name may not contain `/`, and renaming onto a sibling folder's name is refused), `QuitGuard` (mounted in `main.tsx`: the desktop shell PREVENTS window close / @@ -838,7 +868,28 @@ Two independent apps that talk over HTTP: not dnd-kit sortable**: a SortableContext around the virtualizer loops on its flushSync-driven measurement — which is why playlists were once a separate, non-virtualized `PlaylistTable`. Fixed 44 px rows make the drop index just - pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.) + pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns. + Every table's rows are a DRAG SOURCE through `lib/drag.tsx` (a selected row + carries the selection, the payload's `lead` is the row grabbed, `dragFrom` + says whose ids they are and which editable playlist an Option-drag leaves); + the in-table reorder is just the table's own drop target.) + **`lib/drag.tsx` — drag and drop across the window** (decided 2026-10-06, + [the discussion](.claude/discussions/discuss-drag-and-drop-2026-10-06.md)): + ONE gesture, the TARGET decides what it means. Pointer events, NOT HTML5 + DnD — Tauri's webview captures native drag events for file drops on + Windows. A source calls `beginDrag` past a 6 px threshold (`usePressToDrag` + for plain elements); targets register with `useDropTarget({ hint, label, + onDrop })` and are found by `elementFromPoint` then up the ancestors, the + innermost whose `hint` is non-null winning, so a target declines a spot by + returning null. A module-level store read through narrow + `useSyncExternalStore` selectors: a move re-renders only the target under + the pointer and the ghost (`DragLayer`, mounted in main.tsx), never the + table. Esc cancels (before every other Esc handler); the click after a drop + is swallowed; `data-drag-scroll=""` makes an element scroll at a + 20 px edge after a 250 ms dwell — any less and the first/last visible row + could not be dropped on. Targets: playlist + export rows (Sidebar, + ExportsSection), the tree's zones, the table's reorder, and the DECK + (App), which loads the grabbed row paused, in its own origin. `ConvertStemsDialog` (**Convert to Stems**, one dialog — decided: Where = Replace the originals (its option STATES that Save deletes them, since the choice is remembered and may be preselected) or Save to a folder; In @@ -884,7 +935,11 @@ Two independent apps that talk over HTTP: `ContextMenu` (supports `▸` submenus, section headings, separators and checkbox items that toggle without closing — the header row's right-click column chooser uses those; "Add to" lists - playlists + exports and acts on the whole selection; "Remove ▸" holds + playlists + exports and acts on the whole selection; in an editable + playlist "Set Position…" (`SetPositionDialog`, `lib/playlistOrder.ts`) + moves the selection as ONE block in playlist order so its first track + lands at #N — allowed while sorted/filtered, unlike drag, because it + reorders the FULL entry list; "Remove ▸" holds From this playlist / From this export / Grids / Hotcues / From collection, each behind a `ConfirmDialog` — as is the playlist Delete key. Enter confirms unless a button has focus, so Tab-to-Cancel + Enter cancels) + `EditTagsDialog` @@ -1051,10 +1106,17 @@ serialization path.** It enforces: KEY attribute and one `` between LOUDNESS and CUE_V2 in Traktor's layout; the encoding matches the real collection; a Camelot collection gets Camelot; an ADDED Pioneer key ("Abm") lands as "6m"; and the - key tag reaches TKEY / `initialkey` in MP3, FLAC and M4A. + key tag reaches TKEY / `initialkey` in MP3, FLAC and M4A. And + **`move_playlist`** (O): the COLLECTION is untouched, a move round-trips and + moving back is byte-identical; a folder moves with its subtree and answers + its new path id; into its own descendant / beside a namesake is refused with + nothing changed; a smart playlist moves by its path id; a no-op is not dirty. 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. + Traktor-valid, backup-first, COLLECTION byte-identical, original untouched; + plus the drag-and-drop routes: `/add`'s three `duplicates` modes (`ask` + changes nothing and counts) and `/api/playlists/move` (path id answered, + 400 into itself, 404 unknown). - `test_timebase.py` — Traktor's MP3 time base: `mp3_gapless` on generated MP3s (header found after a 1 MB ID3 tag; header-less has none), the offset in samples (2257 at 44.1 and 48 kHz, 0 header-less / WAV / missing), every @@ -1122,7 +1184,9 @@ serialization path.** It enforces: against SQLite). Asserts a no-op save changes zero rows; a one-field edit changes exactly two — the track and `agentRegistry.localUpdateCount` — with the counter up by one and the edited row stamped with it; edits are invisible on - disk until save; and playlist create/fill/rename/delete round-trip. And + disk until save; and playlist create/fill/rename/delete round-trip, and + `move_playlist` (E2) changes only `djmdPlaylist` rows + the counter with + `Seq` 1..n in both parents. And **removing a track** deletes exactly the rows Rekordbox 7 deletes (measured 2026-10-01 by diffing a removal made in Rekordbox itself: `djmdContent`, `djmdCue`, `contentCue`, `contentFile`, `djmdMixerParam`, `djmdSongPlaylist` @@ -1161,7 +1225,8 @@ serialization path.** It enforces: changes zero rows, a title edit exactly `content.title` (no counter, as rekordbox), dates as `YYYY-MM-DD` text, lookups found-or-created with `nameForSearch` NULL, a new playlist on top with siblings shifted, entries - from 1; and the stick hazards — another app's write refused, an unplugged + from 1, a move changing only parent + `sequenceNo` (0..n-1 in both + parents); and the stick hazards — another app's write refused, an unplugged drive keeps the edits, stale `-shm` deleted, the backup holds the old rows, the drive never held open, file tags written (title yes, rating no). And `set_key`: an existing key changes only `content.key_id` and reaches TKEY as @@ -1198,6 +1263,9 @@ serialization path.** It enforces: companion cue is invented), that the existing 8,485 entries render byte-identically, that the job registry runs/fails/cancels, and that a cancelled import leaves **no orphaned audio and an untouched collection**. + And the route with chosen `track_ids` + `into_playlist` + `export_id` (a + device drop): only that track, into the playlist and the export, no drive + folder made. - `test_grid_detect.py` — beatgrid detection on **synthetic** audio, so the tempo and first beat are known rather than borrowed from another analyser: exact integer and non-integer BPMs, the 125 BPM the old detector could not @@ -1895,6 +1963,9 @@ that number and nothing else — everything derives from it: yet**, since nothing can be written. Note the OneLibrary work already demonstrated creating an `exportLibrary.db` from nothing, and `fixtures/onelibrary/schema.sql` is the DDL to do it with. +- ✅ **Drag and drop** (2026-10-06) — tracks onto playlists / exports / the + deck, playlists around the tree and onto exports; see `lib/drag.tsx` and + the Sidebar under Architecture. - ✅ **Remote libraries** (2026-10-02) — a Konduktor server in a container (TrueNAS) holds a Traktor or Rekordbox library; the app opens it as "Remote": browse, prep, edit, Save (versioned on the server), export sticks, diff --git a/backend/konduktor/adapters/onelibrary/adapter.py b/backend/konduktor/adapters/onelibrary/adapter.py index 002fdea..46919d8 100644 --- a/backend/konduktor/adapters/onelibrary/adapter.py +++ b/backend/konduktor/adapters/onelibrary/adapter.py @@ -193,6 +193,7 @@ class OneLibraryAdapter: can_rename=writable, can_delete=writable, can_contain_children=kind == "folder", + can_move=writable, ) parent = str(getattr(r, "playlist_id_parent", 0) or 0) parents[node_id] = "root" if parent in ("0", "", "None") else parent @@ -425,6 +426,10 @@ class OneLibraryAdapter: self._require_writable("Deleting playlists") self._store.delete_playlist(node_id) + def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: + self._require_writable("Moving playlists") + return self._store.move_playlist(node_id, parent_id, index) + def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: self._require_writable("Editing playlists") return self._store.set_playlist_entries(node_id, track_ids) diff --git a/backend/konduktor/adapters/onelibrary/store.py b/backend/konduktor/adapters/onelibrary/store.py index 5923390..e36d7ff 100644 --- a/backend/konduktor/adapters/onelibrary/store.py +++ b/backend/konduktor/adapters/onelibrary/store.py @@ -652,6 +652,45 @@ class OneLibraryStore(ReplaceGridCommands): db.flush() self._journal.record("playlist", "delete", name) + def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: + """Move a node to `index` among `parent_id`'s children, renumbering + `sequenceNo` from 0 in both parents as create and delete do. The + Device Library's playlist tree follows at Save (`device_library` + mirrors parent and sort from these rows).""" + db = self._require_db() + row = self._playlist(node_id) + dest = 0 + if parent_id: + folder = self._playlist(parent_id) + if int(folder.attribute or 0) != ATTRIBUTE_FOLDER: + raise InvalidCommand("A playlist can only be moved into a folder") + dest = int(folder.playlist_id) + ancestor = folder + while ancestor is not None: + if int(ancestor.playlist_id) == int(row.playlist_id): + raise InvalidCommand("A folder cannot be moved into itself") + up = int(ancestor.playlist_id_parent or 0) + ancestor = self._playlist(str(up)) if up else None + source = int(row.playlist_id_parent or 0) + siblings = self._siblings(dest, excluding=row.playlist_id) + index = max(0, min(int(index), len(siblings))) + order = siblings[:index] + [row] + siblings[index:] + if source == dest and [r.playlist_id for r in order] == [ + r.playlist_id for r in self._siblings(dest) + ]: + return str(row.playlist_id) + row.playlist_id_parent = dest + for n, r in enumerate(order): + if int(r.sequenceNo or 0) != n: + r.sequenceNo = n + if source != dest: + for n, r in enumerate(self._siblings(source, excluding=row.playlist_id)): + if int(r.sequenceNo or 0) != n: + r.sequenceNo = n + db.flush() + self._journal.record("playlist", "move", row.name) + return str(row.playlist_id) + def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: """Replace a playlist's contents, in order, numbered from 1 (measured).""" from pyrekordbox.devicelib_plus import models diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index df988c3..4f67706 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -172,6 +172,7 @@ class RekordboxAdapter: can_rename=writable, can_delete=writable, can_contain_children=kind == "folder", + can_move=writable, ) parent = str(r.ParentID or "root") parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent @@ -276,6 +277,10 @@ class RekordboxAdapter: self._require_writable("Deleting playlists") self._store.delete_playlist(node_id) + def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: + self._require_writable("Moving playlists") + return self._store.move_playlist(node_id, parent_id, index) + def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: self._require_writable("Editing playlists") return self._store.set_playlist_entries(node_id, track_ids) diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index e676638..7264e32 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -608,6 +608,79 @@ class RekordboxStore(ReplaceGridCommands): self._db.delete_playlist(row) self._journal.record("playlist", "delete", name) + def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: + """Move a node to `index` among `parent_id`'s visible children. + + Not pyrekordbox's `move_playlist`: its `parent=None` means "keep the + parent", so nothing can be moved to the top level with it. The same + writes are made here — `ParentID`, the moved row's `updated_at`, and + `Seq` renumbered from 1 in both parents (only rows whose `Seq` changes + are touched) — plus `masterPlaylists6.xml`'s `ParentId`, which + pyrekordbox's version leaves stale. Rekordbox's hidden working lists + share the table and the numbering, so `index` is placed relative to + the VISIBLE siblings and the hidden ones keep their order around it.""" + import datetime + + from pyrekordbox.masterdb.database import SPECIAL_PLAYLIST_IDS + + t = self._tables + row = self._playlist(node_id) + dest = self._playlist(parent_id) if parent_id else None + if dest is not None and int(dest.Attribute or 0) != int(t.PlaylistType.FOLDER): + raise InvalidCommand("A playlist can only be moved into a folder") + ancestor = dest + while ancestor is not None: + if str(ancestor.ID) == str(row.ID): + raise InvalidCommand("A folder cannot be moved into itself") + up = str(ancestor.ParentID or "root") + ancestor = None if up in ("root", "0", "") else self._playlist(up) + + def children(key: str) -> list: + return ( + self._db.session.query(t.DjmdPlaylist) + .filter(t.DjmdPlaylist.ParentID == key) + .filter(t.DjmdPlaylist.rb_local_deleted == 0) + .order_by(t.DjmdPlaylist.Seq) + .all() + ) + + old_key = str(row.ParentID or "root") + new_key = str(dest.ID) if dest is not None else "root" + siblings = [c for c in children(new_key) if str(c.ID) != str(row.ID)] + visible = [c for c in siblings if str(c.ID) not in SPECIAL_PLAYLIST_IDS] + index = max(0, min(int(index), len(visible))) + if index < len(visible): + at = siblings.index(visible[index]) + else: + at = siblings.index(visible[-1]) + 1 if visible else len(siblings) + order = siblings[:at] + [row] + siblings[at:] + if old_key == new_key and [str(c.ID) for c in order] == [ + str(c.ID) for c in children(new_key) + ]: + return str(row.ID) + + row.ParentID = new_key + with self._db.registry.disabled(): + row.updated_at = datetime.datetime.now() + for n, c in enumerate(order, start=1): + if c.Seq != n: + c.Seq = n + if old_key != new_key: + for n, c in enumerate( + (c for c in children(old_key) if str(c.ID) != str(row.ID)), start=1 + ): + if c.Seq != n: + c.Seq = n + xml = getattr(self._db, "playlist_xml", None) + if xml is not None: + try: + xml.update(row.ID, parent_id=new_key) + except ValueError: + pass # a playlist the XML never listed: nothing to keep in step + self._db.flush() + self._journal.record("playlist", "move", row.Name) + return str(row.ID) + def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: """Replace a playlist's contents, in the given order. diff --git a/backend/konduktor/adapters/remote/adapter.py b/backend/konduktor/adapters/remote/adapter.py index 4619309..949557f 100644 --- a/backend/konduktor/adapters/remote/adapter.py +++ b/backend/konduktor/adapters/remote/adapter.py @@ -194,6 +194,9 @@ class RemoteAdapter: def delete_playlist(self, node_id): return self._call("delete_playlist", node_id=node_id) + def move_playlist(self, node_id, parent_id, index): + return self._call("move_playlist", node_id=node_id, parent_id=parent_id, index=index) + def set_playlist_entries(self, node_id, track_ids): return self._call("set_playlist_entries", node_id=node_id, track_ids=list(track_ids)) diff --git a/backend/konduktor/adapters/traktor/adapter.py b/backend/konduktor/adapters/traktor/adapter.py index 6f74b1b..d49cfaa 100644 --- a/backend/konduktor/adapters/traktor/adapter.py +++ b/backend/konduktor/adapters/traktor/adapter.py @@ -131,6 +131,10 @@ class TraktorAdapter: with _translate(): self._store.delete_playlist(node_id) + def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: + with _translate(): + return self._store.move_playlist(node_id, parent_id, index) + def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: """Replace a playlist's contents. The adapter resolves each id to its native entry kind, so callers never see Traktor's STEM/TRACK split.""" diff --git a/backend/konduktor/adapters/traktor/capabilities.py b/backend/konduktor/adapters/traktor/capabilities.py index e967265..c4c0488 100644 --- a/backend/konduktor/adapters/traktor/capabilities.py +++ b/backend/konduktor/adapters/traktor/capabilities.py @@ -74,7 +74,12 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities: "need a manual Import Cover Art to show up." ), ), - playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True), + playlists=PlaylistCapabilities( + folders=True, smart="read_only", reorder=True, + # A playlist's entries are a plain list of PRIMARYKEYs, and Traktor + # itself adds a track twice when asked. + duplicates=True, + ), save=SaveCapabilities( app_name="Traktor", library_label="collection.nml", diff --git a/backend/konduktor/adapters/traktor/store.py b/backend/konduktor/adapters/traktor/store.py index 670acc5..eb89e28 100644 --- a/backend/konduktor/adapters/traktor/store.py +++ b/backend/konduktor/adapters/traktor/store.py @@ -160,11 +160,13 @@ class TraktorStore: can_reorder=True, can_rename=True, can_delete=True, + can_move=True, ) if ntype == "SMARTLIST" or node.smartplaylist is not None: # Rule-based, so it has no static entry list to show or edit. return PlaylistNode( - id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart" + id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart", + can_move=True, ) path = parent_path + [name] return PlaylistNode( @@ -175,6 +177,7 @@ class TraktorStore: can_contain_children=True, can_rename=True, can_delete=True, + can_move=True, ) @staticmethod @@ -348,6 +351,79 @@ class TraktorStore: self._note("playlist-delete", node.name) self.dirty = True + def _find_node(self, node_id: str) -> Nodetype: + """Any node by its id: a playlist's UUID, a folder's `fld:` path or a + smart playlist's `sl:` path (its folder path plus its own name).""" + if node_id.startswith("fld:"): + return self._find_folder(node_id) + if node_id.startswith("sl:"): + *folders, name = node_id[len("sl:"):].split("/") + parent = self._find_folder("fld:" + "/".join(folders) if folders else None) + match = next( + (c for c in self._children(parent) + if (c.type == "SMARTLIST" or c.smartplaylist is not None) and c.name == name), + None, + ) + if match is None: + raise PlaylistError(f"Smart playlist not found: {node_id}") + return match + node = self._find_playlist_node(node_id) + if node is None: + raise PlaylistError(f"Playlist not found: {node_id}") + return node + + def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: + """Move a node to `index` among `parent_id`'s children (counted without + it) and return its id afterwards — a folder's and a smart playlist's id + is their path of names, so moving one changes it (and its subtree's). + + A folder or smart playlist landing beside a namesake of its own kind is + refused, as rename refuses it: the two paths would be one, and one of + them unaddressable. Playlists are UUIDs, so their names may repeat.""" + with self._lock: + node = self._find_node(node_id) + if node is self._root(): + raise PlaylistError("Cannot move the root folder") + dest = self._find_folder(parent_id) + if dest is node or any(n is dest for n in self._iter_nodes(node)): + raise PlaylistError("A folder cannot be moved into itself") + is_folder = node.playlist is None and node.smartplaylist is None and ( + node.type or "FOLDER") == "FOLDER" + is_smart = node.type == "SMARTLIST" or node.smartplaylist is not None + if is_folder or is_smart: + kind = "folder" if is_folder else "smart playlist" + for c in self._children(dest): + same_kind = ( + (c.type or "FOLDER") == "FOLDER" and c.playlist is None + and c.smartplaylist is None + ) if is_folder else (c.type == "SMARTLIST" or c.smartplaylist is not None) + if c is not node and same_kind and c.name == node.name: + raise PlaylistError(f'There is already a {kind} called "{node.name}" there') + source = self._find_parent_of(node) + if source is None: + raise PlaylistError("Cannot move a top-level node") + siblings = [c for c in self._children(dest) if c is not node] + index = max(0, min(int(index), len(siblings))) + if source is dest and self._children(dest).index(node) == index: + return self._node_id(node, parent_id) # already there + source.subnodes.node.remove(node) + source.subnodes.count = len(source.subnodes.node) + if dest.subnodes is None: + dest.subnodes = Subnodestype(node=[], count=0) + dest.subnodes.node.insert(index, node) + dest.subnodes.count = len(dest.subnodes.node) + self._note("playlist-move", node.name) + self.dirty = True + return self._node_id(node, parent_id) + + def _node_id(self, node: Nodetype, parent_id: str | None) -> str: + """The id `_to_model` gives `node` inside the folder `parent_id`.""" + if node.playlist is not None: + return node.playlist.uuid + prefix = parent_id[len("fld:"):] if parent_id and parent_id.startswith("fld:") else "" + tag = "sl:" if (node.type == "SMARTLIST" or node.smartplaylist is not None) else "fld:" + return tag + "/".join(p for p in (prefix, node.name or "(unnamed)") if p) + def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None: with self._lock: node = self._find_playlist_node(playlist_uuid) diff --git a/backend/konduktor/core/adapter.py b/backend/konduktor/core/adapter.py index 2c24fda..5ccf296 100644 --- a/backend/konduktor/core/adapter.py +++ b/backend/konduktor/core/adapter.py @@ -247,6 +247,12 @@ class LibraryAdapter(Protocol): def create_folder(self, name: str, parent_id: str | None = None) -> str: ... def rename_playlist(self, node_id: str, name: str) -> None: ... def delete_playlist(self, node_id: str) -> None: ... + # Move a node (playlist, folder or smart playlist) to `index` among + # `parent_id`'s children (None = the top level), counted with the moved + # node left out. Returns the node's id AFTER the move: an id is opaque, and + # on a platform that addresses a folder by its path it changes. A folder + # cannot go into itself or a descendant (InvalidCommand). + def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: ... def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: ... # ---- commands: adding tracks ---------------------------------------- diff --git a/backend/konduktor/core/capabilities.py b/backend/konduktor/core/capabilities.py index 1c5d22b..abd065c 100644 --- a/backend/konduktor/core/capabilities.py +++ b/backend/konduktor/core/capabilities.py @@ -106,6 +106,9 @@ class PlaylistCapabilities(BaseModel): folders: bool = False smart: Literal["none", "read_only"] = "none" reorder: bool = False + # A playlist can hold the same track more than once. Where it cannot, a + # drop of tracks already there skips them rather than asking. + duplicates: bool = False class PathCapabilities(BaseModel): diff --git a/backend/konduktor/core/model.py b/backend/konduktor/core/model.py index 4dd720d..c6c9716 100644 --- a/backend/konduktor/core/model.py +++ b/backend/konduktor/core/model.py @@ -130,6 +130,9 @@ class PlaylistNode(BaseModel): can_rename: bool = False can_delete: bool = False can_contain_children: bool = False # a valid parent for a new playlist + # Can be dragged elsewhere in the tree (`move_playlist`): reordered among + # its siblings or moved into another folder. + can_move: bool = False PlaylistNode.model_rebuild() diff --git a/backend/konduktor/core/query.py b/backend/konduktor/core/query.py index 406f95b..e1b290c 100644 --- a/backend/konduktor/core/query.py +++ b/backend/konduktor/core/query.py @@ -105,6 +105,8 @@ class TrackIndex: if (t.artist and ql in t.artist.lower()) or (t.title and ql in t.title.lower()) or (t.album and ql in t.album.lower()) + or (t.comment and ql in t.comment.lower()) + or (t.comment2 and ql in t.comment2.lower()) ] if genre: items = [t for t in items if t.genre == genre] diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 016be99..fd40059 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -92,6 +92,8 @@ from .schemas import ( RemapResult, RenamePlaylist, SaveResult, + AddEntries, + MovePlaylist, SetEntries, SourceCandidate, SourceStatus, @@ -1227,6 +1229,7 @@ def create_playlist(body: CreatePlaylist) -> PlaylistNode: can_reorder=True, can_rename=True, can_delete=True, + can_move=True, ) @@ -1241,6 +1244,7 @@ def create_folder(body: CreatePlaylist) -> PlaylistNode: can_contain_children=True, can_rename=True, can_delete=True, + can_move=True, ) @@ -1265,17 +1269,35 @@ def set_entries(playlist_uuid: str, body: SetEntries) -> dict: return {"status": "updated", "id": playlist_uuid, "count": n} +@app.post("/api/playlists/move") +def move_playlist(body: MovePlaylist) -> dict: + """Move a playlist, folder or smart playlist in the tree. Answers the + node's id AFTER the move, which on some platforms is not the one sent.""" + new_id = require_adapter().move_playlist(body.node_id, body.parent_id, body.index) + return {"status": "moved", "id": new_id} + + @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).""" +def add_entries(playlist_uuid: str, body: AddEntries) -> dict: + """Append tracks to a playlist. Tracks already there are skipped, added + again, or — `duplicates="ask"` — counted with nothing changed (see + `AddEntries`). `duplicates` in the answer is how many there were.""" a = require_adapter() current = a.playlist_entries(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] - n = a.set_playlist_entries(playlist_uuid, current + added) - return {"status": "added", "id": playlist_uuid, "added": len(added), "count": n} + dupes = [tid for tid in body.track_ids if tid in have] + mode = body.duplicates + if mode != "skip" and not a.capabilities().playlists.duplicates: + mode = "skip" + if mode == "ask" and dupes: + return {"status": "duplicates", "id": playlist_uuid, "added": 0, + "duplicates": len(dupes), "count": len(current)} + added = list(body.track_ids) if mode == "add" else [t for t in body.track_ids if t not in have] + n = a.set_playlist_entries(playlist_uuid, current + added) if added else len(current) + return {"status": "added", "id": playlist_uuid, "added": len(added), + "duplicates": len(dupes), "count": n} @app.patch("/api/tracks") @@ -2423,11 +2445,18 @@ def start_import(body: ImportRequest) -> JobStatus: folder_name = body.folder_name if folder_name is None and STATE.source is not None: folder_name = STATE.source.capabilities().save.library_label + library = STATE.library_id - job = JOBS.submit( - "import", - lambda handle: importer.run(source, dest, plan, handle, folder_name=folder_name), - ) + def work(handle): + result = importer.run( + source, dest, plan, handle, folder_name=folder_name, into_playlist=body.into_playlist, + ) + # As folder add: an export set is Konduktor's data, updated afterwards. + if body.export_id is not None and library is not None: + exports.add(library, body.export_id, track_ids=result["track_ids"]) + return result + + job = JOBS.submit("import", work) return JobStatus(**job.as_dict()) diff --git a/backend/konduktor/remote_protocol.py b/backend/konduktor/remote_protocol.py index 30de27e..0198931 100644 --- a/backend/konduktor/remote_protocol.py +++ b/backend/konduktor/remote_protocol.py @@ -34,7 +34,8 @@ from .core.model import AutoHotcue, Track, TrackCues #: (major, minor). A client speaks to a server of the SAME major whose minor is #: at least its own: minors only add. Bump the minor for an added route or #: method, the major for anything an older client would misread. -API_VERSION: tuple[int, int] = (1, 0) +#: 1.1 — `move_playlist` (sidebar drag and drop). +API_VERSION: tuple[int, int] = (1, 1) #: How long a session survives without a heartbeat, and how often the holder #: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback @@ -73,7 +74,7 @@ _READ = ( ) _MUTATING = ( "create_playlist", "create_folder", "rename_playlist", "delete_playlist", - "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue", + "move_playlist", "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue", "set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_grid_marker", "move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", "replace_grid", "set_analysed_grid", "delete_grid", "set_grid_lock", "add_tracks", diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 6f9b55c..aa3e1c0 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -21,6 +21,20 @@ class SetEntries(BaseModel): track_ids: list[str] # ordered; full desired contents of the playlist +class AddEntries(BaseModel): + track_ids: list[str] + # Tracks the playlist already holds: "skip" them, "add" them again (only + # where `playlists.duplicates`, else skipped), or "ask" — change nothing and + # report how many, so the UI can ask and send again with skip/add. + duplicates: Literal["skip", "add", "ask"] = "skip" + + +class MovePlaylist(BaseModel): + node_id: str + parent_id: str | None = None # None = the top level + index: int # among the new parent's children, not counting the node + + class EditTrack(BaseModel): track_id: str fields: dict[str, str | int | None] @@ -493,6 +507,11 @@ class ImportRequest(BaseModel): # Playlists land in a folder named after the drive. Null keeps them at the # root; the default is filled in from the source's label. folder_name: str | None = None + # Device tracks dropped on a collection playlist / an export (drag and + # drop): every imported track — and every one the collection already + # holds — goes into it, as folder add does. + into_playlist: str | None = None + export_id: str | None = None class Drive(BaseModel): diff --git a/backend/test_import.py b/backend/test_import.py index 568090c..ca781c0 100644 --- a/backend/test_import.py +++ b/backend/test_import.py @@ -447,6 +447,43 @@ check("re-importing flags the tracks as already present", check("but does not refuse them — the user chose to add everything", len(plan8.importable) == 2) +print("== import route: chosen tracks into a playlist and an export (drag and drop) ==") +# Device tracks dropped on a collection playlist open Import with that playlist +# as the target: only the chosen tracks, no drive folder, all into the playlist. +nml9, music9, _ = fresh_collection() +drive9 = Path(tempfile.mkdtemp(prefix="konduktor-import-drive-")) / "Dingus" +shutil.copytree(FIXTURE, drive9, ignore=shutil.ignore_patterns("rekordbox-edited")) +from fastapi.testclient import TestClient # noqa: E402 + +import konduktor.main as main # noqa: E402 + +with TestClient(main.app) as c: + check("the collection opens", c.post("/api/library/open", json={"path": str(nml9)}).status_code == 200) + check("the drive opens as a source", c.post("/api/source/open", json={"path": str(drive9)}).status_code == 200) + picked = c.get("/api/source/tracks", params={"limit": 10}).json() + picked = picked["items"][:1] + target = c.post("/api/playlists", json={"name": "Dropped"}).json()["id"] + eset = c.post("/api/exports", json={"name": "Gig", "targets": ["traktor"], + "destination": str(music9.parent / "gig")}).json()["id"] + r = c.post("/api/import", json={"destination": str(music9), "track_ids": [picked[0]["id"]], + "into_playlist": target, "export_id": eset}) + check("the import starts", r.status_code == 200, r.text[:200]) + job = r.json() + for _ in range(200): + job = c.get(f"/api/jobs/{job['id']}").json() + if job["state"] != "running": + break + time.sleep(0.05) + check("…and finishes", job["state"] == "done", str(job)[:300]) + entries = c.get(f"/api/playlists/{target}/tracks").json() + check("the one chosen track lands in the target playlist", + len(entries) == 1 and entries[0]["title"] == picked[0]["title"], str([e["title"] for e in entries])) + names = [n["name"] for n in c.get("/api/playlists").json()] + check("no drive folder is made when no playlist was chosen", "Dingus" not in names, str(names)) + ex = next(e for e in c.get("/api/exports").json() if e["id"] == eset) + check("…and it is added to the export too", ex["track_ids"] == [entries[0]["id"]], str(ex["track_ids"])) + c.delete("/api/source") + print() print("RESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) diff --git a/backend/test_onelibrary_fidelity.py b/backend/test_onelibrary_fidelity.py index 4a8eccf..dfb2c99 100644 --- a/backend/test_onelibrary_fidelity.py +++ b/backend/test_onelibrary_fidelity.py @@ -264,6 +264,44 @@ seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist check("and closes the gap among its siblings", seqs == list(range(len(seqs))), str(seqs)) a.close() +print("== moving playlists (sidebar drag and drop) ==") +drive = fresh_drive() +a = OneLibraryAdapter(drive) +folder = a.create_folder("Gigs") +probe = a.create_playlist("Probe") +a.save() +before = dump(db_of(drive)) +check("every node offers can_move", all(n.can_move for n in a.playlist_tree())) +demos = next(n for n in a.playlist_tree() if n.name == "demos") +a.move_playlist(demos.id, folder, 0) +a.move_playlist(probe, None, 1) +tree = a.playlist_tree() +check("a playlist moved into a folder is its child", + [c.id for c in next(n for n in tree if n.id == folder).children] == [demos.id]) +check("a playlist moves to the index asked for", [n.id for n in tree] == [folder, probe], + str([n.name for n in tree])) +check("a folder cannot be moved into itself", + _raises(lambda: a.move_playlist(folder, folder, 0), InvalidCommand)) +check("nor into a playlist", _raises(lambda: a.move_playlist(probe, demos.id, 0), InvalidCommand)) +a.save() +after = dump(db_of(drive)) +changes = diff(before, after) +check("only playlist rows change, by UPDATE", + {(t, kind) for t, _, kind, _ in changes} == {("playlist", "UPDATE")}, describe(changes)) +check("only parent and sequenceNo columns change", + {c for *_, f in changes for c in f} <= {"playlist_id_parent", "sequenceNo"}, + str([f for *_, f in changes])) +for parent in (0, int(folder)): + seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist_id_parent"] == parent) + check(f"sequenceNo stays 0..n-1 under {parent}", seqs == list(range(len(seqs))), str(seqs)) +a.close() +reopened = OneLibraryAdapter(drive) +check("the move round-trips through a reopen", + [c.id for c in next(n for n in reopened.playlist_tree() if n.id == folder).children] == [demos.id]) +reopened.move_playlist(probe, None, 1) +check("moving a node onto its own place is not an edit", reopened.dirty is False) +reopened.close() + # ---- E: a stick's hazards ------------------------------------------------------------ print("== another app wrote the drive since it was opened ==") drive = fresh_drive() diff --git a/backend/test_phase3.py b/backend/test_phase3.py index 9a966f2..1ffed2c 100644 --- a/backend/test_phase3.py +++ b/backend/test_phase3.py @@ -172,6 +172,43 @@ check("COLLECTION still byte-identical after folder delete", check("unknown folder is 404", client.delete("/api/playlists/fld:No Such Folder").status_code == 404) +print("== drag and drop: add with duplicates, move ==") +target = client.post("/api/playlists", json={"name": "Konduktor Drop"}).json()["id"] +first, rest = track_ids[:2], track_ids[2:4] +r = client.post(f"/api/playlists/{target}/add", json={"track_ids": first}).json() +check("a plain add appends", r["added"] == 2 and r["duplicates"] == 0) +r = client.post(f"/api/playlists/{target}/add", + json={"track_ids": first[:1] + rest, "duplicates": "ask"}).json() +check("'ask' with a duplicate changes nothing and counts it", + r["status"] == "duplicates" and r["duplicates"] == 1 + and client.get(f"/api/playlists/{target}/tracks").json().__len__() == 2) +r = client.post(f"/api/playlists/{target}/add", + json={"track_ids": first[:1] + rest, "duplicates": "skip"}).json() +check("'skip' adds only the new ones", r["added"] == 2 and r["duplicates"] == 1 and r["count"] == 4) +r = client.post(f"/api/playlists/{target}/add", + json={"track_ids": first[:1], "duplicates": "add"}).json() +check("'add' adds it again (Traktor can hold a track twice)", r["added"] == 1 and r["count"] == 5) +r = client.post(f"/api/playlists/{target}/add", + json={"track_ids": track_ids[4:5], "duplicates": "ask"}).json() +check("'ask' with nothing duplicated simply adds", r["status"] == "added" and r["added"] == 1) +check("capabilities say Traktor holds duplicates", + client.get("/api/capabilities").json()["playlists"]["duplicates"] is True) + +box = client.post("/api/playlists/folders", json={"name": "Konduktor Drop Box"}).json()["id"] +r = client.post("/api/playlists/move", json={"node_id": target, "parent_id": box, "index": 0}) +check("move answers the playlist's id", r.status_code == 200 and r.json()["id"] == target) +r = client.post("/api/playlists/move", json={"node_id": box, "parent_id": None, "index": 0}) +check("moving a folder answers its (path) id", r.json()["id"] == box) +check("…and it is first at the top level", client.get("/api/playlists").json()[0]["id"] == box) +r = client.post("/api/playlists/move", json={"node_id": box, "parent_id": box, "index": 0}) +check("a folder into itself is a 400", r.status_code == 400) +r = client.post("/api/playlists/move", json={"node_id": "nope", "parent_id": None, "index": 0}) +check("an unknown node is a 404", r.status_code == 404) +client.delete(f"/api/playlists/{box}") +client.post("/api/save") +check("COLLECTION still byte-identical after drops and moves", + collection_span(WORK.read_bytes()) == collection_before) + print("== original untouched ==") check( "original collection.nml never modified", diff --git a/backend/test_rekordbox_fidelity.py b/backend/test_rekordbox_fidelity.py index 3518f4e..8fd0ae9 100644 --- a/backend/test_rekordbox_fidelity.py +++ b/backend/test_rekordbox_fidelity.py @@ -31,6 +31,7 @@ os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-rbfid-appd from konduktor.adapters.rekordbox import discovery # noqa: E402 from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402 +from konduktor.core.adapter import InvalidCommand # noqa: E402 failed = False @@ -302,6 +303,51 @@ with tempfile.TemporaryDirectory() as d: folder_reopened.close() after_folder.close() + # ---- E2: moving nodes in the tree (sidebar drag and drop) ----------- + print("== E2: move_playlist reorders and reparents, touching only playlist rows ==") + clean_copy(REAL, work, closing=[adapter, again, final, reopened]) + adapter = RekordboxAdapter(work) + folder_id = adapter.create_folder("Konduktor Move Folder") + a_id = adapter.create_playlist("Konduktor Move A") + b_id = adapter.create_playlist("Konduktor Move B") + adapter.save() + adapter.close() + before = dump(work) + adapter = RekordboxAdapter(work) + check("every node offers can_move", all(n.can_move for n in adapter.playlist_tree())) + adapter.move_playlist(b_id, folder_id, 0) + adapter.move_playlist(a_id, None, 0) + tree = adapter.playlist_tree() + check("a playlist moved into a folder is its child", + [c.id for c in next(n for n in tree if n.id == folder_id).children] == [b_id]) + check("a playlist moved to index 0 is first at the top level", tree[0].id == a_id, + [n.name for n in tree[:3]]) + try: + adapter.move_playlist(folder_id, folder_id, 0) + check("a folder cannot be moved into itself", False) + except InvalidCommand: + check("a folder cannot be moved into itself", True) + adapter.save() + changes = diff(before, dump(work)) + check("only djmdPlaylist rows and the counter change", + {t for t, _, _, _ in changes} <= {"djmdPlaylist", "agentRegistry"}, describe(changes)) + rows = dump(work)["djmdPlaylist"] + for parent in ("root", folder_id): + seqs = sorted(int(r["Seq"]) for r in rows.values() + if str(r["ParentID"]) == parent and not r["rb_local_deleted"]) + check(f"Seq stays 1..n under {parent}", seqs == list(range(1, len(seqs) + 1)), seqs) + adapter.close() + reopened = RekordboxAdapter(work) + tree = reopened.playlist_tree() + check("the moves round-trip through a reopen", + tree[0].id == a_id + and [c.id for c in next(n for n in tree if n.id == folder_id).children] == [b_id]) + reopened.move_playlist(b_id, None, len(tree)) + check("a playlist moved out of a folder lands last at the top level", + reopened.playlist_tree()[-1].id == b_id) + reopened.close() + again = final = RekordboxAdapter(work) + # ---- F: a cue write touches the cue row AND its mirror --------------- print("== F: a hot cue write is localized, and keeps the mirror in step ==") clean_copy(REAL, work, closing=[adapter, again, final, reopened]) diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index b21d6c1..1c1af1a 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -1086,5 +1086,110 @@ with tempfile.TemporaryDirectory() as d: check("N: …and written in Camelot", target.info.key == "1A", target.info.key) +# ---- O: moving playlists in the tree ---------------------------------- +# Drag and drop in the sidebar. Moving a node relocates its whole block, so +# the guarantee is: the COLLECTION is untouched, the tree reads back as moved, +# and moving it back reproduces the original bytes exactly. +print("\n== O. move_playlist ==") + + +def _collection_span(data: bytes) -> bytes: + return data[data.find(b"")] + + +def _find(nodes, name): + for n in nodes: + if n.name == name: + return n + hit = _find(n.children, name) + if hit is not None: + return hit + return None + + +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + before = work.read_bytes() + store = TraktorStore(work) + roots = store.tree() + folders = [n for n in roots if n.kind == "folder" and n.children] + loose = [n for n in roots if n.kind == "playlist"] + if len(folders) < 2 or len(loose) < 2: + print(" [SKIP] the reference collection has too few top-level nodes") + else: + src, dst = folders[0], folders[1] + pl = next((c for c in src.children if c.kind == "playlist"), None) or loose[0] + home = _find(roots, pl.name) + home_parent = next((f.id for f in roots if any(c.id == pl.id for c in f.children)), None) + home_index = ([c.id for c in (src.children if home_parent else roots)].index(pl.id)) + check("O: every node offers can_move", all(n.can_move for n in roots)) + + # A playlist into another folder, at a position. + new_id = store.move_playlist(pl.id, dst.id, 1) + tree = store.tree() + moved_into = next(n for n in tree if n.id == dst.id) + check("O: a playlist keeps its id when moved", new_id == pl.id, new_id) + check("O: …and lands at the index asked for", + len(moved_into.children) > 1 and moved_into.children[1].id == pl.id, + [c.name for c in moved_into.children[:3]]) + store.save() + moved = work.read_bytes() + check("O: the COLLECTION is untouched by a move", + _collection_span(moved) == _collection_span(before)) + reread = TraktorStore(work).tree() + check("O: the move round-trips through a save", + any(c.id == pl.id for c in next(n for n in reread if n.id == dst.id).children)) + + # …and back again: byte-identical to the original. + store.move_playlist(pl.id, home_parent, home_index) + store.save() + check("O: moving it back restores the original bytes", work.read_bytes() == before, + f"{diff_count(before, work.read_bytes())} lines differ") + + # A folder moves with its subtree, and its id (a path) changes with it. + new_folder = store.move_playlist(src.id, dst.id, 0) + check("O: a moved folder answers its new path id", + new_folder == f"{dst.id}/{src.name}", new_folder) + inner = next(n for n in store.tree() if n.id == dst.id).children[0] + check("O: …and its subtree moved with it", + inner.id == new_folder and len(inner.children) == len(src.children)) + child_ids = [c.id for c in inner.children] + check("O: …children keep addressable ids", + all(c.startswith((new_folder.replace("fld:", "sl:") + "/", new_folder + "/")) + or not c.startswith(("fld:", "sl:")) for c in child_ids), child_ids[:3]) + + # Into itself: refused, nothing changed. + snapshot = store._render() + try: + store.move_playlist(dst.id, new_folder, 0) + check("O: a folder cannot be moved into its own descendant", False) + except PlaylistError: + check("O: a folder cannot be moved into its own descendant", + store._render() == snapshot) + + # A namesake folder in the target: refused (two paths would be one). + store.create_folder(src.name, None) + snapshot = store._render() + try: + store.move_playlist(new_folder, None, 0) + check("O: a folder cannot land beside a namesake", False) + except PlaylistError: + check("O: a folder cannot land beside a namesake", store._render() == snapshot) + + # A smart playlist moves too, by its path id. + smart = next((c for c in inner.children if c.kind == "smart"), None) + if smart is not None: + sid = store.move_playlist(smart.id, None, 0) + check("O: a smart playlist moves and answers its new id", + sid == f"sl:{smart.name}" and store.tree()[0].id == sid, sid) + + # A no-op move leaves the store clean. + fresh = TraktorStore(work) + first = fresh.tree()[0] + fresh.move_playlist(first.id, None, 0) + check("O: moving a node onto its own place is not an edit", not fresh.dirty) + + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) diff --git a/backend/test_traktor_adapter.py b/backend/test_traktor_adapter.py index b05cd2d..236e2ac 100644 --- a/backend/test_traktor_adapter.py +++ b/backend/test_traktor_adapter.py @@ -106,6 +106,13 @@ with tempfile.TemporaryDirectory() as d: adapter.set_track_metadata(tid, {"genre": "Konduktor Test Genre"}) check("metadata edit is visible in the projection", adapter.track(tid).genre == "Konduktor Test Genre") + # search reaches both comments, case-insensitively + adapter.set_track_metadata(tid, {"comment": "Konduktor Search One", + "comment2": "Konduktor Search Two"}) + for q in ("search one", "SEARCH TWO"): + hits = adapter.query_tracks(q=q, limit=20000).items + check(f"search {q!r} finds the track by its comment", + [x.id for x in hits] == [tid], f"{len(hits)} hits") # key — the projection's wheel, mode AND display text all follow t = adapter.set_key(tid, 4, "minor") # 4A = F minor = Open Key 9m diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 0ee54a1..ce3f938 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -4,6 +4,8 @@ import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack import { CapabilitiesContext, slotLabeller } from './lib/capabilities' import { removalNote, writeHint } from './lib/platformCopy' import { invalidateTrackLists } from './lib/trackQueries' +import { addTracksToPlaylist } from './lib/addTracks' +import { useDropTarget } from './lib/drag' import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api' import { confirmDiscardUnsaved } from './lib/unsaved' import { @@ -30,6 +32,7 @@ import { ImportDialog } from './components/ImportDialog' import { AddFilesDialog, type AddTarget } from './components/AddFilesDialog' import { ConvertStemsDialog } from './components/ConvertStemsDialog' import { StemReportDialog } from './components/StemReportDialog' +import { SetPositionDialog } from './components/SetPositionDialog' import { Icon } from './lib/icons' import { usePrefsWriter } from './lib/prefs' @@ -39,7 +42,7 @@ function applyFilters(tracks: Track[], f: Filters): Track[] { const bpmMax = f.bpmMax ? parseFloat(f.bpmMax) : null return tracks.filter((t) => { if (q) { - const hay = `${t.artist ?? ''} ${t.title ?? ''} ${t.album ?? ''}`.toLowerCase() + const hay = [t.artist, t.title, t.album, t.comment, t.comment2].filter(Boolean).join(' ').toLowerCase() if (!hay.includes(q)) return false } if (f.genre && t.genre !== f.genre) return false @@ -81,6 +84,9 @@ export default function App() { const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null } | null>(null) const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays const [importing, setImporting] = useState(false) + // Device tracks dropped on a collection playlist / export: Import, with + // just those tracks and that target. + const [importDrop, setImportDrop] = useState<{ ids: string[]; target: AddTarget } | null>(null) // Batch analysis (grid, or Auto Hotcues): a confirm step, then the running // job, polled into the status bar. ONE at a time across both kinds — the // backend refuses a second, since a grid run would move the beats a hotcue @@ -91,6 +97,8 @@ export default function App() { // Convert to Stems: the dialog's selection, a finished run's Details, and a // running engine download (which outlives the dialog — decided). const [stemDialog, setStemDialog] = useState(null) + // Set Position…: the tracks being moved within the open playlist. + const [positioning, setPositioning] = useState(null) const [stemReport, setStemReport] = useState(null) const [engineJob, setEngineJob] = useState(null) const [batchCancelling, setBatchCancelling] = useState(false) @@ -98,9 +106,9 @@ export default function App() { // Every Remove ▸ action (and the playlist Delete key) confirms first. const [confirmReq, setConfirmReq] = useState(null) - const loadTrack = useCallback((t: Track) => { + const loadTrack = useCallback((t: Track, origin: TrackOrigin = viewOriginRef.current) => { setPrepTrack(t) - setPrepOrigin(viewOriginRef.current) + setPrepOrigin(origin) }, []) const playTrack = useCallback( (t: Track) => { @@ -339,21 +347,37 @@ export default function App() { }, [refreshExport, exportSets.data, notify, onError], ) + // The same path as a drop on a sidebar playlist (lib/addTracks.ts), so the + // menu and the drag ask about duplicates alike. + const duplicatesAllowed = !!capabilities.data?.playlists.duplicates const addToPlaylist = useCallback( async (uuid: string, ids: string[]) => { try { - const res = await api.addEntries(uuid, ids) - qc.invalidateQueries({ queryKey: ['state'] }) - qc.invalidateQueries({ queryKey: ['playlists'] }) - qc.invalidateQueries({ queryKey: ['playlist', uuid] }) const name = addablePlaylists.find((p) => p.id === uuid)?.name ?? 'playlist' - notify('success', `Added ${res.added} track${res.added === 1 ? '' : 's'} to ${name}`) + const msg = await addTracksToPlaylist({ qc, playlist: { id: uuid, name }, ids, duplicatesAllowed }) + if (msg) notify('success', msg) } catch (e) { onError((e as Error).message) } }, - [qc, addablePlaylists, notify, onError], + [qc, addablePlaylists, duplicatesAllowed, notify, onError], ) + // Tracks from a device or a Files folder dropped on a collection playlist or + // export: they are not in the collection yet, so the drop opens the dialog + // that adds them — with that target filled in, and copy-vs-reference still + // asked (decided 2026-10-06). + const addForeign = useCallback( + (origin: TrackOrigin, ids: string[], target: AddTarget) => { + if (origin === 'folder') setAdding({ ids, target }) + else if (origin === 'device') setImportDrop({ ids, target }) + }, + [], + ) + const [deckDropRef, deckOver] = useDropTarget({ + hint: (p) => (p.kind === 'tracks' ? true : null), + label: (p) => (p.kind === 'tracks' && p.ids.length > 1 ? `Load “${p.lead.title || 'Untitled'}” into the deck` : 'Load into the deck'), + onDrop: (p) => p.kind === 'tracks' && loadTrack(p.lead, p.origin), + }) const removeFromExport = useCallback( async (id: string, ids: string[]) => { try { @@ -1062,6 +1086,11 @@ export default function App() { : viewingDevice ? [] : [{ label: 'Add to', submenu: addToItems(menu.ids) }]), + // Unlike drag-reorder this stays on while sorted or filtered: it + // moves within the playlist's FULL order, which the # column shows. + ...(playlistEditable + ? [{ label: 'Set Position…', onClick: () => setPositioning(menu.ids) }] + : []), ...(() => { const items = removeItems(menu.ids) return items.length ? [{ label: 'Remove', submenu: items }] : [] @@ -1103,6 +1132,14 @@ export default function App() { /> )} {stemReport && setStemReport(null)} />} + {positioning && ( + t.id)} + ids={positioning} + onMove={reorderPlaylist} + onClose={() => setPositioning(null)} + /> + )} {editing && ( )} - {/* Prep strip spans the top of the window; the library sits below it. */} + {importDrop && ( + setImportDrop(null)} + onDone={(msg) => { + setImportDrop(null) + notify('success', msg) + }} + onError={onError} + /> + )} + + {/* Prep strip spans the top of the window; the library sits below it. + A track dropped on it loads (paused) — the row the drag started on. */} +
+ {deckOver && ( +
+ )} +
setForcePicker(true)} onOpenLibrary={(path) => void openForEditing(path)} onDone={(msg) => notify('success', msg)} + onAddForeign={addForeign} onOpenPathMapping={() => setShowPaths(true)} onDiscarded={() => afterBulk(prepTrack ? [prepTrack.id] : [], true)} /> @@ -1396,6 +1455,7 @@ export default function App() { onSortingChange={setSorting} selection={{ selected, onChange: setSelected }} marked={{ ids: heldInFolder, title: 'Already in your collection' }} + dragFrom={{ origin: 'folder' }} onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)} onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })} onPlay={playTrack} @@ -1431,6 +1491,7 @@ export default function App() { sorting={sorting} onSortingChange={setSorting} onRowContextMenu={(track, x, y) => openMenu(track, x, y, false)} + dragFrom={{ origin: 'device' }} onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })} onPlay={playTrack} activeTrackId={prepTrack?.id ?? null} @@ -1492,6 +1553,10 @@ export default function App() { : undefined } onRemove={playlistEditable ? confirmRemoveFromPlaylist : undefined} + dragFrom={{ + origin: 'collection', + playlistId: playlistEditable && source.kind === 'playlist' ? source.id : undefined, + }} onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)} onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })} onPlay={playTrack} diff --git a/frontend/src/api.ts b/frontend/src/api.ts index c967082..338a973 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -83,6 +83,8 @@ export interface PlaylistNode { can_rename: boolean can_delete: boolean can_contain_children: boolean + /** Can be dragged elsewhere in the tree (reordered, or into a folder). */ + can_move: boolean } export type SortField = @@ -270,7 +272,13 @@ export interface Capabilities { /** Added files can be left where they are rather than copied. */ reference: boolean } - playlists: { folders: boolean; smart: 'none' | 'read_only'; reorder: boolean } + playlists: { + folders: boolean + smart: 'none' | 'read_only' + reorder: boolean + /** A playlist can hold the same track twice (else duplicates are skipped). */ + duplicates: boolean + } /** Path mapping / rewriting / the missing-files check apply to this library. */ paths: { remappable: boolean } save: SaveCapabilities @@ -433,6 +441,10 @@ export interface ImportRequest { playlist_ids?: string[] /** Playlists land in a folder named this; null keeps them at the root. */ folder_name?: string | null + /** Every imported track (and any already held) also goes into this + * collection playlist / export — a drop of device tracks on one. */ + into_playlist?: string | null + export_id?: string | null } export interface ImportPreview { @@ -988,12 +1000,23 @@ export const api = { send<{ status: string; count: number }>('PUT', `/api/playlists/${encodeURIComponent(nodeId)}/entries`, { track_ids: trackIds, }), - addEntries: (nodeId: string, trackIds: string[]) => - send<{ status: string; added: number; count: number }>( + /** Append tracks. `duplicates` decides tracks already there: skip them, + * add them again (where `playlists.duplicates`), or `ask` — nothing changes + * and the answer's `status: 'duplicates'` says how many, to ask and resend. */ + addEntries: (nodeId: string, trackIds: string[], duplicates: 'skip' | 'add' | 'ask' = 'skip') => + send<{ status: 'added' | 'duplicates'; added: number; duplicates: number; count: number }>( 'POST', `/api/playlists/${encodeURIComponent(nodeId)}/add`, - { track_ids: trackIds }, + { track_ids: trackIds, duplicates }, ), + /** Move a tree node to `index` among `parentId`'s children (null = top + * level), counted without it. Answers its id AFTER the move. */ + movePlaylist: (nodeId: string, parentId: string | null, index: number) => + send<{ status: string; id: string }>('POST', '/api/playlists/move', { + node_id: nodeId, + parent_id: parentId, + index, + }), getPrefs: () => getJSON>('/api/prefs'), patchPrefs: (patch: Record) => send>('PATCH', '/api/prefs', patch), diff --git a/frontend/src/components/ConfirmDialog.tsx b/frontend/src/components/ConfirmDialog.tsx index 62dcb22..dc8444b 100644 --- a/frontend/src/components/ConfirmDialog.tsx +++ b/frontend/src/components/ConfirmDialog.tsx @@ -10,6 +10,10 @@ export interface ConfirmRequest { /** `danger` (default) for destructive actions — a pink button; `primary` * for a caution that is not destruction, e.g. switching library. */ tone?: 'danger' | 'primary' + /** A second way to go ahead, as a plain button beside the confirm one + * (e.g. "Add them again" next to "Add 6 new"). Enter still means confirm. */ + altLabel?: string + onAlt?: () => void onConfirm: () => Promise | void } @@ -19,7 +23,7 @@ interface Props extends ConfirmRequest { /** A yes/no confirmation for destructive actions. Enter confirms and Esc * cancels, so a confirmed Delete key stays a two-keystroke action. */ -export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', onConfirm, onClose }: Props) { +export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altLabel, onAlt, onConfirm, onClose }: Props) { const [busy, setBusy] = useState(false) const confirm = async () => { @@ -69,6 +73,18 @@ export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', onCo > Cancel + {altLabel && onAlt && ( + + )} + +
+ +
, + document.body, + ) +} diff --git a/frontend/src/components/ShortcutsDialog.tsx b/frontend/src/components/ShortcutsDialog.tsx index 25671f4..84bd1e5 100644 --- a/frontend/src/components/ShortcutsDialog.tsx +++ b/frontend/src/components/ShortcutsDialog.tsx @@ -58,11 +58,17 @@ function sections(slots: number): Section[] { { keys: [[MOD, 'Click']], action: 'Add to / remove from the selection' }, { keys: [['Double-click']], action: 'Edit a cell' }, { keys: [['Right-click']], action: 'Track menu (header: choose columns)' }, + { keys: [['Drag rows']], action: 'Onto a playlist or export to add, onto the deck to load, within a playlist to reorder' }, + { keys: [[ALT_KEY, 'Drag']], action: 'Move tracks to another playlist (out of this one)' }, + { keys: [['Esc']], action: 'While dragging: cancel the drag' }, ], }, { title: 'Sidebar', - rows: [{ keys: [['Right-click']], action: 'New playlist or folder, rename, delete' }], + rows: [ + { keys: [['Right-click']], action: 'New playlist or folder, rename, delete' }, + { keys: [['Drag']], action: 'Rearrange playlists and folders; onto an export to add one' }, + ], }, { title: 'Fields & dialogs', diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index 1ce3e94..53295c8 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -1,6 +1,7 @@ -import { useRef, useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { api, type PlaylistKind, type PlaylistNode } from '../api' +import { api, type PlaylistKind, type PlaylistNode, type TrackOrigin } from '../api' +import type { AddTarget } from './AddFilesDialog' import { useCaps } from '../lib/capabilities' import { SaveBar } from './SaveBar' import { confirmDiscardUnsaved } from '../lib/unsaved' @@ -11,6 +12,9 @@ import { ConfirmDialog, type ConfirmRequest } from './ConfirmDialog' import { ContextMenu, type MenuItem } from './ContextMenu' import { Icon, type IconName } from '../lib/icons' import { PlatformIcon } from '../lib/platformIcons' +import { addTracksToPlaylist } from '../lib/addTracks' +import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload } from '../lib/drag' +import { nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree' /** * Which view the main table is showing. @@ -50,6 +54,9 @@ interface Props { /** Open a drive's library as THE library (Devices' "Open for editing…"). */ onOpenLibrary: (path: string) => void onDone: (msg: string) => void + /** Tracks not in the collection yet (a device's, a folder's) dropped on a + * playlist or export: open the dialog that adds them, target filled in. */ + onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void onOpenPathMapping: () => void /** After unsaved edits were discarded (SaveBar). */ onDiscarded?: () => void @@ -57,11 +64,6 @@ interface Props { // Kind picks the icon; every behavioural question is answered by the node's own // flags, so nothing here infers what a node can do from what it is called. -/** Every selectable playlist at or under a node, in tree order. */ -function playlistIdsUnder(node: PlaylistNode): string[] { - const here = node.kind === 'folder' ? [] : [node.id] - return [...here, ...(node.children ?? []).flatMap(playlistIdsUnder)] -} /** The confirm wording for deleting a node. A folder says what goes with it, * since the whole subtree is deleted and the row only shows the folder. */ @@ -105,8 +107,27 @@ interface RowActions { onPickExport: (e: React.MouseEvent, node: PlaylistNode) => void onCommitDraft: (name: string) => void onCancelDraft: () => void + /** Whether a drag of tracks may drop on this playlist. */ + acceptsTracks: (node: PlaylistNode, p: Extract) => boolean + /** Tracks dropped on a playlist; `alt` (Option) moves them out of the + * playlist they came from. */ + onDropTracks: (node: PlaylistNode, p: Extract, alt: boolean) => void + /** Whether a node may be dragged elsewhere in the tree. */ + canMove: (node: PlaylistNode) => boolean + /** A node dropped in the tree: `index` among `parentId`'s children, + * counted without it (what `move_playlist` takes). */ + onMoveNode: (node: PlaylistNode, parentId: string | null, index: number, into: PlaylistNode | null) => void } +/** Where a dragged node would land, relative to the row under the pointer: + * `before`/`after` it, `into` it (a folder; appended), or `first` inside it — + * the lower edge of an EXPANDED folder, where the line sits above its first + * child. `tracks` is a track drop on a playlist; `peek` is tracks held over a + * collapsed folder, which opens it and drops nothing. */ +type RowHint = + | { zone: 'tracks' | 'peek' } + | { zone: 'before' | 'after' | 'into' | 'first'; parentId: string | null; index: number } + /** The inline name field for a node being created. Enter or clicking away * commits a non-empty name; Esc (or an empty name) creates nothing. */ function DraftRow({ @@ -156,6 +177,8 @@ function DraftRow({ function NodeRow({ node, + parentId, + siblings, depth, source, onSelect, @@ -166,6 +189,10 @@ function NodeRow({ actions, }: { node: PlaylistNode + /** The folder this node sits in; null = the top level. */ + parentId: string | null + /** That folder's children, this node included, in order. */ + siblings: PlaylistNode[] depth: number source: Source onSelect: (s: Source) => void @@ -191,14 +218,100 @@ function NodeRow({ setRenamingId(node.id) } + // A row is a drag SOURCE (onto an export, or elsewhere in the tree) and a + // drop TARGET for tracks. Whether it takes them is the node's own + // `can_add_tracks` plus the library being writable, decided by the sidebar. + const startDrag = usePressToDrag(() => (renaming ? null : { kind: 'node', node, parentId })) + const moves = (p: DragPayload, alt: boolean) => + p.kind === 'tracks' && alt && !!p.fromPlaylist && p.fromPlaylist !== node.id + + // A node held over this row: which zone, and where that puts it. Never into + // itself or anything nested in it; a drop that would leave it exactly where + // it is shows nothing. + const placeNode = (p: Extract, y: number, el: HTMLElement): RowHint | null => { + if (!actions.canMove(p.node) || nodeIdsUnder(p.node).has(node.id)) return null + const r = el.getBoundingClientRect() + const f = (y - r.top) / r.height + const opened = expanded && node.children.length > 0 + const zone: 'before' | 'after' | 'into' | 'first' = node.can_contain_children + ? f < 0.25 ? 'before' : f > 0.75 ? (opened ? 'first' : 'after') : 'into' + : f < 0.5 ? 'before' : 'after' + let target: string | null + let index: number + let current: PlaylistNode[] + if (zone === 'into' || zone === 'first') { + target = node.id + current = node.children + index = zone === 'first' ? 0 : node.children.filter((c) => c.id !== p.node.id).length + } else { + target = parentId + current = siblings + const i = siblings.filter((c) => c.id !== p.node.id).findIndex((c) => c.id === node.id) + index = zone === 'before' ? i : i + 1 + } + if (target === p.parentId && current.findIndex((c) => c.id === p.node.id) === index) return null + return { zone, parentId: target, index } + } + const [dropRef, over] = useDropTarget({ + hint: (p, at, el) => { + if (p.kind === 'node') return placeNode(p, at.y, el) + if (actions.acceptsTracks(node, p)) return { zone: 'tracks' } + return isFolder && !expanded ? { zone: 'peek' } : null + }, + label: (p, h, at) => { + if (h.zone === 'tracks') { + if (p.kind === 'tracks' && p.origin === 'device') return `Import into ${node.name}…` + if (p.kind === 'tracks' && p.origin === 'folder') return `Add to ${node.name}…` + return `${moves(p, at.alt) ? 'Move' : 'Add'} to ${node.name}` + } + if (h.zone === 'peek') return null + return h.zone === 'into' || h.zone === 'first' ? `Move into ${node.name}` : `Move ${h.zone} ${node.name}` + }, + onDrop: (p, h, at) => { + if (p.kind === 'tracks') { + if (h.zone === 'tracks') actions.onDropTracks(node, p, at.alt) + } else if ('parentId' in h) { + actions.onMoveNode(p.node, h.parentId, h.index, h.zone === 'into' && !expanded ? node : null) + } + }, + }) + // Holding a drag over a collapsed folder opens it, so a playlist nested in + // it can be reached without letting go. + const opening = over?.zone === 'into' || over?.zone === 'peek' + useEffect(() => { + if (!opening || expanded) return + const t = setTimeout(() => setOpen(true), 600) + return () => clearTimeout(t) + }, [opening, expanded]) + const ringed = over?.zone === 'tracks' || over?.zone === 'into' + const dragging = useDragPayload() + const beingMoved = dragging?.kind === 'node' && dragging.node.id === node.id + const line = over?.zone === 'before' || over?.zone === 'after' || over?.zone === 'first' ? over.zone : null + return ( -
+
actions.onContextMenu(e, node)} - className={`group flex items-center gap-1 rounded-[10px] pr-1 text-sm transition-colors ${ - selected ? 'is-selected font-medium text-text' : 'text-muted hover:bg-ink-800 hover:text-text' + className={`group relative flex items-center gap-1 rounded-[10px] pr-1 text-sm transition-colors ${ + ringed + ? 'bg-accent-soft/40 text-text ring-1 ring-accent' + : selected + ? 'is-selected font-medium text-text' + : 'text-muted hover:bg-ink-800 hover:text-text' }`} > + {line && ( + + )}