From c8b86100f04726b42a658cbff35fc81ae0ba36f2 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Mon, 5 Oct 2026 21:01:25 +0200 Subject: [PATCH 1/8] Track position in playlist can now be typed --- CLAUDE.md | 6 +- frontend/src/App.tsx | 16 +++ frontend/src/components/SetPositionDialog.tsx | 106 ++++++++++++++++++ frontend/src/lib/playlistOrder.test.ts | 36 ++++++ frontend/src/lib/playlistOrder.ts | 17 +++ 5 files changed, 180 insertions(+), 1 deletion(-) create mode 100644 frontend/src/components/SetPositionDialog.tsx create mode 100644 frontend/src/lib/playlistOrder.test.ts create mode 100644 frontend/src/lib/playlistOrder.ts diff --git a/CLAUDE.md b/CLAUDE.md index f52243a..a1de5e5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -884,7 +884,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` diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 0ee54a1..c9d5f7b 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -30,6 +30,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' @@ -91,6 +92,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) @@ -1062,6 +1065,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 +1111,14 @@ export default function App() { /> )} {stemReport && setStemReport(null)} />} + {positioning && ( + t.id)} + ids={positioning} + onMove={reorderPlaylist} + onClose={() => setPositioning(null)} + /> + )} {editing && ( void + onClose: () => void +} + +/** "Set Position…": type where the first selected track should end up. */ +export function SetPositionDialog({ order, ids, onMove, onClose }: Props) { + const moving = new Set(ids) + const count = order.filter((id) => moving.has(id)).length + const max = maxPosition(order, moving) + const current = order.findIndex((id) => moving.has(id)) + 1 + const [value, setValue] = useState(String(current)) + const input = useRef(null) + + useEffect(() => input.current?.select(), []) + + const typed = Number.parseInt(value, 10) + const position = Number.isFinite(typed) ? Math.min(Math.max(typed, 1), max) : null + + const submit = () => { + if (position === null) return + const next = moveToPosition(order, moving, position) + if (next.some((id, i) => id !== order[i])) onMove(next) + onClose() + } + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape') onClose() + } + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [onClose]) + + const span = (p: number) => (count > 1 ? `#${p}–${p + count - 1}` : `#${p}`) + + return createPortal( +
+
e.stopPropagation()} + onSubmit={(e) => { + e.preventDefault() + submit() + }} + > +
+ Set position +
+
+ +
+ {position === null + ? 'Type a position.' + : count > 1 + ? `Will occupy ${span(position)}` + : `Now ${span(current)} · will be ${span(position)}`} +
+
+
+ + +
+
+
, + document.body, + ) +} diff --git a/frontend/src/lib/playlistOrder.test.ts b/frontend/src/lib/playlistOrder.test.ts new file mode 100644 index 0000000..2767047 --- /dev/null +++ b/frontend/src/lib/playlistOrder.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest' + +import { maxPosition, moveToPosition } from './playlistOrder' + +const order = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] +const move = (ids: string[], position: number) => moveToPosition(order, new Set(ids), position).join('') + +describe('moveToPosition', () => { + it('puts the track AT the position, moving down or up', () => { + expect(move(['B'], 5)).toBe('ACDEBFG') + expect(move(['F'], 2)).toBe('AFBCDEG') + expect(move(['A'], 1)).toBe('ABCDEFG') + }) + + it('moves a selection as one block in playlist order', () => { + expect(move(['F', 'B'], 2)).toBe('ABFCDEG') + expect(move(['G', 'A', 'D'], 3)).toBe('BCADGEF') + }) + + it('clamps past either end', () => { + expect(move(['B', 'C'], 99)).toBe('ADEFGBC') + expect(move(['C'], 0)).toBe('CABDEFG') + }) + + it('moves every entry of a track listed twice', () => { + expect(moveToPosition(['A', 'B', 'A', 'C'], new Set(['A']), 2).join('')).toBe('BAAC') + }) +}) + +describe('maxPosition', () => { + it('leaves room for the block behind its first track', () => { + expect(maxPosition(order, new Set(['B']))).toBe(7) + expect(maxPosition(order, new Set(['B', 'C', 'D']))).toBe(5) + expect(move(['B', 'C', 'D'], 5)).toBe('AEFGBCD') + }) +}) diff --git a/frontend/src/lib/playlistOrder.ts b/frontend/src/lib/playlistOrder.ts new file mode 100644 index 0000000..7d2894a --- /dev/null +++ b/frontend/src/lib/playlistOrder.ts @@ -0,0 +1,17 @@ +/** A playlist's entry order with `moving` lifted out as one block, kept in + * their PLAYLIST order, and put back so the block's first track lands at the + * 1-based `position` of the result. A position past the end puts the block + * last. A track listed twice in the playlist moves with both entries, since a + * selection is by track id. */ +export function moveToPosition(order: string[], moving: ReadonlySet, position: number): string[] { + const block = order.filter((id) => moving.has(id)) + const rest = order.filter((id) => !moving.has(id)) + const at = Math.min(Math.max(Math.floor(position), 1) - 1, rest.length) + return [...rest.slice(0, at), ...block, ...rest.slice(at)] +} + +/** The highest position the block's first track can take: the block's own + * length is what sits behind it. */ +export function maxPosition(order: string[], moving: ReadonlySet): number { + return order.length - order.filter((id) => moving.has(id)).length + 1 +} From 9f79f5a8499f8801e4cbdc9b1dcbf220c77b1ed1 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Mon, 5 Oct 2026 23:16:12 +0200 Subject: [PATCH 2/8] Search now includes comments --- backend/konduktor/core/query.py | 2 ++ backend/test_traktor_adapter.py | 7 +++++++ frontend/src/App.tsx | 2 +- frontend/src/components/Toolbar.tsx | 2 +- 4 files changed, 11 insertions(+), 2 deletions(-) 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/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 c9d5f7b..1314995 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -40,7 +40,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 diff --git a/frontend/src/components/Toolbar.tsx b/frontend/src/components/Toolbar.tsx index bb30846..abc1c8c 100644 --- a/frontend/src/components/Toolbar.tsx +++ b/frontend/src/components/Toolbar.tsx @@ -59,7 +59,7 @@ export function Toolbar({ value={filters.search} onChange={(e) => set({ search: e.target.value })} ref={searchRef} - placeholder="Search artist, title, album…" + placeholder="Artist, title, album, comment…" className="well w-72 rounded-full py-1.5 pl-9 pr-8 text-sm text-text outline-none placeholder:text-faint focus:ring-1 focus:ring-accent" /> {filters.search && ( From e5c7b67626d707216b899280c555b2a562993643 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Tue, 6 Oct 2026 22:25:01 +0200 Subject: [PATCH 3/8] Implemented playlist reorganizing --- .../konduktor/adapters/onelibrary/adapter.py | 5 + .../konduktor/adapters/onelibrary/store.py | 39 +++++++ .../konduktor/adapters/rekordbox/adapter.py | 5 + backend/konduktor/adapters/rekordbox/store.py | 73 ++++++++++++ backend/konduktor/adapters/remote/adapter.py | 3 + backend/konduktor/adapters/traktor/adapter.py | 4 + .../adapters/traktor/capabilities.py | 7 +- backend/konduktor/adapters/traktor/store.py | 78 ++++++++++++- backend/konduktor/core/adapter.py | 6 + backend/konduktor/core/capabilities.py | 3 + backend/konduktor/core/model.py | 3 + backend/konduktor/main.py | 32 +++++- backend/konduktor/remote_protocol.py | 2 +- backend/konduktor/schemas.py | 14 +++ backend/test_onelibrary_fidelity.py | 38 +++++++ backend/test_phase3.py | 37 ++++++ backend/test_rekordbox_fidelity.py | 46 ++++++++ backend/test_save_fidelity.py | 105 ++++++++++++++++++ frontend/src/api.ts | 27 ++++- 19 files changed, 515 insertions(+), 12 deletions(-) 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/main.py b/backend/konduktor/main.py index 016be99..ae70bdf 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") diff --git a/backend/konduktor/remote_protocol.py b/backend/konduktor/remote_protocol.py index 30de27e..9a9b3f3 100644 --- a/backend/konduktor/remote_protocol.py +++ b/backend/konduktor/remote_protocol.py @@ -73,7 +73,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..0ddbf7f 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] 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/frontend/src/api.ts b/frontend/src/api.ts index c967082..d5a4186 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 @@ -988,12 +996,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), From b154df430aba969f3fdf5f358bb975f9589a3331 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Tue, 6 Oct 2026 22:32:31 +0200 Subject: [PATCH 4/8] Implemented drag core and song reorganizing --- frontend/src/App.tsx | 6 + frontend/src/components/TrackTable.tsx | 181 +++++++++-------- frontend/src/index.css | 7 + frontend/src/lib/drag.tsx | 261 +++++++++++++++++++++++++ frontend/src/main.tsx | 3 + 5 files changed, 364 insertions(+), 94 deletions(-) create mode 100644 frontend/src/lib/drag.tsx diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 1314995..a50b2ea 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1412,6 +1412,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} @@ -1447,6 +1448,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} @@ -1508,6 +1510,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/components/TrackTable.tsx b/frontend/src/components/TrackTable.tsx index e61e2aa..89608fc 100644 --- a/frontend/src/components/TrackTable.tsx +++ b/frontend/src/components/TrackTable.tsx @@ -1,4 +1,4 @@ -import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject } from 'react' +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject } from 'react' import { flexRender, getCoreRowModel, @@ -29,7 +29,8 @@ import { useSortable, } from '@dnd-kit/sortable' import { CSS } from '@dnd-kit/utilities' -import type { Track } from '../api' +import type { Track, TrackOrigin } from '../api' +import { beginDrag, useDragPayload, useDropTarget } from '../lib/drag' import { TRACK_COLUMNS } from '../lib/trackColumns' /** Fields this platform can persist, for the table's per-cell edit gating. @@ -71,6 +72,9 @@ interface Props { /** A view with a manual order. `enabled` is false while a sort or filter is * active: reordering a partial or re-sorted list would lose the real order. */ reorder?: { enabled: boolean; onReorder: (ids: string[]) => void } + /** Where dragged rows come from: whose ids they are, and the editable + * playlist they leave on an Option-drag (move). Defaults to the collection. */ + dragFrom?: { origin: TrackOrigin; playlistId?: string } /** Delete/Backspace removes the selected tracks from this view. */ onRemove?: (ids: string[]) => void onRowContextMenu?: (track: Track, x: number, y: number) => void @@ -277,6 +281,7 @@ export function TrackTable({ positions, marked, reorder, + dragFrom, onRemove, onRowContextMenu, onHeaderContextMenu, @@ -363,7 +368,7 @@ export function TrackTable({ } const clickRow = (index: number, e: { shiftKey: boolean; metaKey: boolean; ctrlKey: boolean }) => { - if (!selection || justDraggedRef.current) return + if (!selection) return const id = rows[index].original.id const toggle = e.metaKey || e.ctrlKey const anchor = indexOf(anchorRef.current) @@ -381,102 +386,87 @@ export function TrackTable({ } } - // ---- row drag-to-reorder ---------------------------------------------- - // `drop` is the gap the dragged rows would land in (0 = above the first row). - const [drag, setDrag] = useState<{ moving: Set; drop: number } | null>(null) + // ---- dragging rows ------------------------------------------------------ + // Every table's rows are a drag SOURCE (onto playlists, exports, the deck — + // lib/drag.tsx); a view with a manual order is also its own drop TARGET, the + // in-table reorder. `drop` is the gap the rows would land in (0 = above the + // first row). const pressRef = useRef<{ x: number; y: number; index: number } | null>(null) - const justDraggedRef = useRef(false) - const canDrag = !!reorder?.enabled + const tableKey = useRef({}).current + const dragging = useDragPayload() + const ownDrag = dragging?.kind === 'tracks' && dragging.source === tableKey ? dragging : null + const movingIds = useMemo(() => new Set(ownDrag?.ids ?? []), [ownDrag]) useEffect(() => { - if (!canDrag) return - let raf = 0 - let lastY = 0 - let active: { moving: Set; drop: number } | null = null - - const dropAt = (clientY: number) => { - const top = bodyRef.current?.getBoundingClientRect().top ?? 0 - return Math.max(0, Math.min(rowsRef.current.length, Math.round((clientY - top) / ROW_HEIGHT))) - } - // Hold near the top/bottom edge to scroll while dragging. - const autoScroll = () => { - const el = parentRef.current - if (el && active) { - const r = el.getBoundingClientRect() - const edge = 48 - const dy = - lastY < r.top + edge + ROW_HEIGHT ? -12 : lastY > r.bottom - edge ? 12 : 0 - if (dy) { - el.scrollTop += dy - active = { ...active, drop: dropAt(lastY) } - setDrag(active) - } - } - raf = requestAnimationFrame(autoScroll) - } const onMove = (e: PointerEvent) => { const press = pressRef.current - if (!press) return - lastY = e.clientY - if (!active) { - if (Math.hypot(e.clientX - press.x, e.clientY - press.y) < 6) return - // Dragging a selected row moves the whole selection; any other row - // moves alone (and becomes the selection, so what moves is visible). - const rs = rowsRef.current - const sel = selectionRef.current - const pressedId = rs[press.index].original.id - let moving: Set - if (sel?.selected.has(pressedId)) { - moving = new Set(rs.flatMap((r, i) => (sel.selected.has(r.original.id) ? [i] : []))) - } else { - moving = new Set([press.index]) - sel?.onChange(new Set([pressedId])) - anchorRef.current = leadRef.current = pressedId - } - active = { moving, drop: dropAt(e.clientY) } - document.body.style.userSelect = 'none' - document.body.style.cursor = 'grabbing' - window.getSelection()?.removeAllRanges() - raf = requestAnimationFrame(autoScroll) - } else { - active = { ...active, drop: dropAt(e.clientY) } - } - setDrag(active) - } - const end = () => { + if (!press || Math.hypot(e.clientX - press.x, e.clientY - press.y) < 6) return pressRef.current = null - if (!active) return - const { moving, drop } = active - active = null - cancelAnimationFrame(raf) - document.body.style.userSelect = '' - document.body.style.cursor = '' - setDrag(null) - // Swallow the click that follows the pointerup, so a drop is not also a - // click that re-selects the row it ended on. - justDraggedRef.current = true - setTimeout(() => (justDraggedRef.current = false), 0) + // Dragging a selected row carries the whole selection (in the table's + // order); any other row goes alone and becomes the selection, so what is + // being dragged is visible. + const rs = rowsRef.current + const sel = selectionRef.current + const pressed = rs[press.index]?.original + if (!pressed) return + let carried: Track[] + if (sel?.selected.has(pressed.id)) { + carried = rs.filter((r) => sel.selected.has(r.original.id)).map((r) => r.original) + } else { + carried = [pressed] + sel?.onChange(new Set([pressed.id])) + anchorRef.current = leadRef.current = pressed.id + } + const from = dragFromRef.current + beginDrag( + { + kind: 'tracks', + ids: [...new Set(carried.map((t) => t.id))], + tracks: carried, + origin: from?.origin ?? 'collection', + fromPlaylist: from?.playlistId, + source: tableKey, + }, + { x: e.clientX, y: e.clientY, alt: e.altKey }, + ) + } + const release = () => (pressRef.current = null) + window.addEventListener('pointermove', onMove) + window.addEventListener('pointerup', release) + window.addEventListener('pointercancel', release) + return () => { + window.removeEventListener('pointermove', onMove) + window.removeEventListener('pointerup', release) + window.removeEventListener('pointercancel', release) + } + }, [tableKey]) + + const [dropRef, dropHint] = useDropTarget<{ drop: number }>({ + hint: (p, at) => { + if (p.kind !== 'tracks' || p.source !== tableKey || !reorderRef.current?.enabled) return null + const top = bodyRef.current?.getBoundingClientRect().top ?? 0 + return { drop: Math.max(0, Math.min(rowsRef.current.length, Math.round((at.y - top) / ROW_HEIGHT))) } + }, + onDrop: (p, { drop }) => { + if (p.kind !== 'tracks') return + const ids = new Set(p.ids) const rs = rowsRef.current.map((r) => r.original) - const kept = rs.filter((_, i) => !moving.has(i)) - const block = rs.filter((_, i) => moving.has(i)) - const at = drop - [...moving].filter((i) => i < drop).length + const kept = rs.filter((t) => !ids.has(t.id)) + const block = rs.filter((t) => ids.has(t.id)) + const at = drop - rs.slice(0, drop).filter((t) => ids.has(t.id)).length const next = [...kept.slice(0, at), ...block, ...kept.slice(at)] if (next.every((t, i) => t === rs[i])) return setData(next) reorderRef.current?.onReorder(next.map((t) => t.id)) - } - window.addEventListener('pointermove', onMove) - window.addEventListener('pointerup', end) - window.addEventListener('pointercancel', end) - return () => { - cancelAnimationFrame(raf) - window.removeEventListener('pointermove', onMove) - window.removeEventListener('pointerup', end) - window.removeEventListener('pointercancel', end) - document.body.style.userSelect = '' - document.body.style.cursor = '' - } - }, [canDrag]) + }, + }) + const scrollerRef = useCallback( + (el: HTMLDivElement | null) => { + parentRef.current = el + dropRef(el) + }, + [dropRef], + ) // Latest values for the once-attached window listeners. const rowsRef = useRef(rows) @@ -485,6 +475,8 @@ export function TrackTable({ selectionRef.current = selection const reorderRef = useRef(reorder) reorderRef.current = reorder + const dragFromRef = useRef(dragFrom) + dragFromRef.current = dragFrom // Keyboard: ↑/↓ move the selection (Shift extends it), Cmd/Ctrl+A selects // every visible row, Esc clears, Delete/Backspace removes (where the view @@ -547,7 +539,8 @@ export function TrackTable({ return (
{ // A click in the empty space below the rows clears the selection. @@ -568,13 +561,13 @@ export function TrackTable({ const row = rows[vr.index] const isSelected = selection?.selected.has(row.original.id) ?? false const isActive = activeTrackId === row.original.id - const isMoving = drag?.moving.has(vr.index) ?? false + const isMoving = movingIds.has(row.original.id) return (
{ @@ -582,7 +575,7 @@ export function TrackTable({ if (selection && (e.shiftKey || e.metaKey || e.ctrlKey)) e.preventDefault() }} onPointerDown={(e) => { - if (!canDrag || e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return + if (e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return // Not from a control inside the row (play, stars, an edit field). if ((e.target as HTMLElement).closest('button, input, textarea, select, a')) return pressRef.current = { x: e.clientX, y: e.clientY, index: vr.index } @@ -620,10 +613,10 @@ export function TrackTable({
) })} - {drag && ( + {dropHint && (
)}
diff --git a/frontend/src/index.css b/frontend/src/index.css index 98059af..77d4004 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -87,6 +87,13 @@ body, overscroll-behavior: none; } +/* While something is being dragged (lib/drag.tsx), the cursor is the hand + everywhere — buttons and links would otherwise show their own. */ +html.is-dragging, +html.is-dragging * { + cursor: grabbing !important; +} + body { margin: 0; background: var(--color-ink-950); diff --git a/frontend/src/lib/drag.tsx b/frontend/src/lib/drag.tsx new file mode 100644 index 0000000..1e6f754 --- /dev/null +++ b/frontend/src/lib/drag.tsx @@ -0,0 +1,261 @@ +import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react' +import { createPortal } from 'react-dom' +import type { PlaylistNode, Track, TrackOrigin } from '../api' +import { Icon } from './icons' + +/** + * Drag and drop across the whole window: track rows onto sidebar playlists, + * exports and the deck; playlists around the sidebar tree. + * + * ONE gesture, and the drop TARGET decides what it means. A source calls + * `beginDrag` once the pointer has moved past its threshold; targets register + * with `useDropTarget` and are found by hit-testing (`elementFromPoint`, then up + * through the ancestors), so the virtualized table, the sidebar and the deck + * need no shared React tree — and the innermost target that accepts wins, with + * the search falling through to an enclosing one where it declines. + * + * Pointer events, NOT HTML5 drag and drop: Tauri's webview captures native drag + * events for its own file drop on Windows, so HTML5 DnD silently dies in the + * packaged app. + * + * The state lives in a module-level store read through useSyncExternalStore + * with narrow selectors, so a pointer move re-renders only the target under it + * (and the ghost) — never the table. + */ + +export type DragPayload = + | { + kind: 'tracks' + ids: string[] + tracks: Track[] + /** Which library the ids belong to — a device's or a folder's are not + * the collection's, so collection targets must not take them as such. */ + origin: TrackOrigin + /** The editable playlist they were dragged out of, for Option = move. */ + fromPlaylist?: string + /** Identity of the table that started the drag (its own reorder target). */ + source: object + } + | { kind: 'node'; node: PlaylistNode; parentId: string | null } + +export interface DropPoint { + x: number + y: number + /** Option/Alt held: tracks dragged out of a playlist MOVE instead of copy. */ + alt: boolean +} + +export interface DropSpec { + /** The hint for a pointer at `at` over this target — anything the target + * needs to draw and to drop (an insertion index, a before/into/after zone) — + * or null where it does not accept this drop, so the search continues to an + * enclosing target. */ + hint: (p: DragPayload, at: DropPoint, el: HTMLElement) => H | null + /** What a drop here would do, shown on the ghost ("Add to Warmup"). */ + label?: (p: DragPayload, hint: H, at: DropPoint) => string | null + onDrop: (p: DragPayload, hint: H, at: DropPoint) => void +} + +interface State { + payload: DragPayload | null + x: number + y: number + alt: boolean + target: HTMLElement | null + hint: unknown + label: string | null +} + +const IDLE: State = { payload: null, x: 0, y: 0, alt: false, target: null, hint: null, label: null } +let state: State = IDLE +const listeners = new Set<() => void>() +const targets = new Map }>() + +function set(next: Partial) { + state = { ...state, ...next } + listeners.forEach((l) => l()) +} +function subscribe(l: () => void) { + listeners.add(l) + return () => listeners.delete(l) +} + +/** Keep the previous hint object when the new one has the same fields, so a + * target re-renders only when what it draws changes, not on every move. */ +function sameHint(a: unknown, b: unknown): boolean { + if (a === b) return true + if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false + const ka = Object.keys(a) + return ( + ka.length === Object.keys(b).length && + ka.every((k) => (a as Record)[k] === (b as Record)[k]) + ) +} + +/** Find the innermost target under the pointer that accepts, and record its hint. */ +function evaluate() { + const { payload, x, y, alt } = state + if (!payload) return + const at = { x, y, alt } + let el = document.elementFromPoint(x, y) as HTMLElement | null + while (el) { + const spec = targets.get(el) + if (spec) { + const hint = spec.current.hint(payload, at, el) + if (hint != null) { + const keep = state.target === el && sameHint(state.hint, hint) ? state.hint : hint + set({ target: el, hint: keep, label: spec.current.label?.(payload, keep, at) ?? null }) + return + } + } + el = el.parentElement + } + set({ target: null, hint: null, label: null }) +} + +let detach: (() => void) | null = null + +/** Start a drag. Call it once the press has moved past the source's threshold. */ +export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt: boolean }) { + detach?.() + set({ ...IDLE, payload, ...at }) + document.documentElement.classList.add('is-dragging') + window.getSelection()?.removeAllRanges() + + const onMove = (e: PointerEvent) => { + // One notification per move: evaluate() publishes the position with the hint. + state = { ...state, x: e.clientX, y: e.clientY, alt: e.altKey } + evaluate() + } + const finish = (drop: boolean) => { + const { payload: p, target, hint, x, y, alt } = state + detach?.() + if (!drop || !p || !target) return + const spec = targets.get(target) + try { + spec?.current.onDrop(p, hint, { x, y, alt }) + } catch (err) { + console.error('drop failed', err) + } + } + const onUp = () => finish(true) + const onCancel = () => finish(false) + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape' && e.type === 'keydown') { + // Before every other Esc handler: cancelling the drag is all Esc does. + e.preventDefault() + e.stopImmediatePropagation() + finish(false) + return + } + if (e.key === 'Alt' && state.alt !== (e.type === 'keydown')) { + set({ alt: e.type === 'keydown' }) + evaluate() + } + } + // Hold near the edge of a `data-drag-scroll` element to scroll it. Its + // value is the height covered at the top (a sticky header). + let raf = 0 + const autoScroll = () => { + const { x, y } = state + let scrolled = false + document.querySelectorAll('[data-drag-scroll]').forEach((el) => { + const r = el.getBoundingClientRect() + if (x < r.left || x > r.right || y < r.top - 24 || y > r.bottom + 24) return + const top = r.top + Number(el.dataset.dragScroll || 0) + const edge = 40 + const dy = y < top + edge ? -Math.ceil((top + edge - y) / 4) : y > r.bottom - edge ? Math.ceil((y - r.bottom + edge) / 4) : 0 + if (!dy) return + const before = el.scrollTop + el.scrollTop += Math.max(-20, Math.min(20, dy)) + scrolled ||= el.scrollTop !== before + }) + if (scrolled) evaluate() + raf = requestAnimationFrame(autoScroll) + } + raf = requestAnimationFrame(autoScroll) + + window.addEventListener('pointermove', onMove) + window.addEventListener('pointerup', onUp) + window.addEventListener('pointercancel', onCancel) + window.addEventListener('keydown', onKey, true) + window.addEventListener('keyup', onKey, true) + window.addEventListener('blur', onCancel) + detach = () => { + detach = null + cancelAnimationFrame(raf) + window.removeEventListener('pointermove', onMove) + window.removeEventListener('pointerup', onUp) + window.removeEventListener('pointercancel', onCancel) + window.removeEventListener('keydown', onKey, true) + window.removeEventListener('keyup', onKey, true) + window.removeEventListener('blur', onCancel) + document.documentElement.classList.remove('is-dragging') + // The pointerup that ended the drag is followed by a click on whatever + // is under it; that click is part of the drop, not a click of its own. + const swallow = (e: MouseEvent) => { + e.stopPropagation() + e.preventDefault() + } + window.addEventListener('click', swallow, true) + setTimeout(() => window.removeEventListener('click', swallow, true), 0) + set(IDLE) + } + evaluate() +} + +/** The drag in progress, or null. Changes only when a drag starts or ends. */ +export function useDragPayload(): DragPayload | null { + return useSyncExternalStore(subscribe, () => state.payload) +} + +/** Register an element as a drop target. Returns the ref to attach and the + * current hint while the pointer is over it (null otherwise). */ +export function useDropTarget(spec: DropSpec): [(el: HTMLElement | null) => void, H | null] { + const specRef = useRef(spec as DropSpec) + specRef.current = spec as DropSpec + const elRef = useRef(null) + const ref = useCallback((el: HTMLElement | null) => { + if (elRef.current) targets.delete(elRef.current) + elRef.current = el + if (el) targets.set(el, specRef) + }, []) + useEffect(() => () => { + if (elRef.current) targets.delete(elRef.current) + }, []) + const hint = useSyncExternalStore(subscribe, () => + state.target !== null && state.target === elRef.current ? state.hint : null, + ) + return [ref, hint as H | null] +} + +/** What the ghost says it is carrying. */ +function describe(p: DragPayload): { icon: 'music' | 'playlist' | 'folder' | 'smart'; text: string } { + if (p.kind === 'node') + return { icon: p.node.kind === 'folder' ? 'folder' : p.node.kind === 'smart' ? 'smart' : 'playlist', text: p.node.name } + if (p.ids.length === 1) { + const t = p.tracks[0] + return { icon: 'music', text: t ? [t.artist, t.title].filter(Boolean).join(' – ') || 'Untitled' : '1 track' } + } + return { icon: 'music', text: `${p.ids.length} tracks` } +} + +/** The ghost under the cursor. Mounted once, in main.tsx. */ +export function DragLayer() { + const s = useSyncExternalStore(subscribe, () => state) + if (!s.payload) return null + const { icon, text } = describe(s.payload) + return createPortal( +
+ + + {text} + + {s.label && {s.label}} +
, + document.body, + ) +} diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index 80074f8..0e961fe 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -8,6 +8,7 @@ import App from './App.tsx' import { UpdateCheck } from './components/UpdateDialog.tsx' import { AmbientBackdrop } from './components/AmbientBackdrop.tsx' import { ConfirmHost } from './lib/confirm.tsx' +import { DragLayer } from './lib/drag.tsx' import { QuitGuard } from './components/QuitGuard.tsx' import { preventHistoryNavigation } from './lib/noNavigation.ts' @@ -34,6 +35,8 @@ createRoot(document.getElementById('root')!).render( {/* Save · Discard · Cancel when quitting with unsaved changes. */} + {/* The ghost under the cursor while dragging tracks or playlists. */} + , ) From 89c7dade25f492f4697e5922724c058319752b31 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Tue, 6 Oct 2026 22:41:29 +0200 Subject: [PATCH 5/8] Tracks can be added to playlists via drag --- frontend/src/App.tsx | 13 ++-- frontend/src/components/ConfirmDialog.tsx | 18 +++++- frontend/src/components/ExportsSection.tsx | 47 ++++++++++++++- frontend/src/components/Sidebar.tsx | 62 ++++++++++++++++--- frontend/src/lib/addTracks.ts | 69 ++++++++++++++++++++++ frontend/src/lib/confirm.tsx | 22 ++++--- frontend/src/lib/drag.tsx | 28 +++++++++ frontend/src/lib/playlistTree.ts | 10 ++++ 8 files changed, 246 insertions(+), 23 deletions(-) create mode 100644 frontend/src/lib/addTracks.ts create mode 100644 frontend/src/lib/playlistTree.ts diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index a50b2ea..3bf86d7 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -4,6 +4,7 @@ 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 { 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 { @@ -342,20 +343,20 @@ 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], ) const removeFromExport = useCallback( async (id: string, ids: string[]) => { 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 && ( + + )}