From 068e4da08b8e109cb62287482c541f65e534d473 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 22 Oct 2026 09:58:57 +0200 Subject: [PATCH] Implemented subtractive playlist editing --- CLAUDE.md | 10 +++- backend/konduktor/main.py | 23 ++++++++ backend/konduktor/schemas.py | 6 ++ backend/test_phase3.py | 19 +++++++ frontend/src/App.tsx | 67 +++++++++++++++++++++++ frontend/src/api.ts | 8 +++ frontend/src/components/ConfirmDialog.tsx | 9 ++- 7 files changed, 138 insertions(+), 4 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 2dbada9..dc3ae13 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,6 +53,13 @@ Two independent apps that talk over HTTP: inserts among the CURRENT entries (a drop between a table's rows); folder add (`playlist_index`) and device import (`into_playlist_index`) take the same. + `POST /api/playlists/{id}/remove` (`dry_run` counts, changes nothing) + drops EVERY occurrence of the given tracks, other entries kept as they + are — the track menu's **Remove ▸ From playlist ▸** (decided 2026-10-22, + [the discussion](.claude/discussions/discuss-playlist-subtraction-2026-10-22.md)): + tracks picked anywhere leave a playlist that is not open, so "A minus B" + is open B, select all, remove from A. Lists every `can_reorder` + playlist but the open one; the confirm says how many it holds, even 0. - `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 @@ -1517,7 +1524,8 @@ serialization path.** It enforces: - `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays 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, + changes nothing and counts), `/remove` (every copy, order kept, `dry_run` + counts and changes nothing, 404 unknown) 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 diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index fc49692..20e0173 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -104,6 +104,7 @@ from .schemas import ( RenamePlaylist, SaveResult, AddEntries, + RemoveEntries, MovePlaylist, SetEntries, SourceCandidate, @@ -1473,6 +1474,28 @@ def add_entries(playlist_uuid: str, body: AddEntries) -> dict: "duplicates": len(dupes), "count": n} +@app.post("/api/playlists/{playlist_uuid}/remove") +def remove_entries(playlist_uuid: str, body: RemoveEntries) -> dict: + """Remove tracks from a playlist — EVERY occurrence of each — without the + caller holding its entry list (the track menu's Remove ▸ From playlist). + Other entries keep their order, including ones whose track is missing + from the collection. `tracks` = how many of the given tracks it held, + `removed` = entries dropped (more, where a track was there twice).""" + a = require_adapter() + current = a.playlist_entries(playlist_uuid) + if current is None: + raise HTTPException(404, f"Playlist not found: {playlist_uuid}") + gone = set(body.track_ids) + kept = [t for t in current if t not in gone] + held = len(gone & set(current)) + removed = len(current) - len(kept) + n = len(current) + if removed and not body.dry_run: + n = a.set_playlist_entries(playlist_uuid, kept) + return {"status": "counted" if body.dry_run else "removed", "id": playlist_uuid, + "tracks": held, "removed": removed, "count": n} + + @app.patch("/api/tracks") def edit_track(body: EditTrack) -> dict: """Edit a single track's safe metadata fields (in-memory; persisted on save).""" diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 4a479c1..55a1c26 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -32,6 +32,12 @@ class AddEntries(BaseModel): index: int | None = None +class RemoveEntries(BaseModel): + track_ids: list[str] + # Count what would go and change nothing — the confirm dialog's numbers. + dry_run: bool = False + + class MovePlaylist(BaseModel): node_id: str parent_id: str | None = None # None = the top level diff --git a/backend/test_phase3.py b/backend/test_phase3.py index b88f55d..bdfa00c 100644 --- a/backend/test_phase3.py +++ b/backend/test_phase3.py @@ -204,6 +204,25 @@ check("an index past the end appends", after[-1] == more[1]) check("capabilities say Traktor holds duplicates", client.get("/api/capabilities").json()["playlists"]["duplicates"] is True) +before = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()] +outsider = next(t["id"] for t in client.get("/api/tracks", params={"limit": 50}).json()["items"] + if t["id"] not in before) +picked = [first[0], rest[0], outsider] # first[0] is in there twice +r = client.post(f"/api/playlists/{target}/remove", + json={"track_ids": picked, "dry_run": True}).json() +check("a dry-run remove counts tracks held and entries (both copies) and changes nothing", + r["tracks"] == 2 and r["removed"] == 3 + and [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()] == before) +r = client.post(f"/api/playlists/{target}/remove", json={"track_ids": picked}).json() +after = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()] +check("remove drops every copy and keeps the rest in order", + r["removed"] == 3 and r["count"] == len(before) - 3 + and after == [t for t in before if t not in picked]) +r = client.post(f"/api/playlists/{target}/remove", json={"track_ids": [outsider]}).json() +check("removing tracks it does not hold changes nothing", r["removed"] == 0 and r["count"] == len(after)) +check("remove from an unknown playlist is a 404", + client.post("/api/playlists/nope/remove", json={"track_ids": picked}).status_code == 404) + 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) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index f9016d1..1d6dc8d 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -368,6 +368,13 @@ export default function App() { nodes.flatMap((n) => [...(n.can_add_tracks ? [n] : []), ...walk(n.children)]) return walk(playlists.data ?? []) }, [playlists.data]) + // Every playlist Remove ▸ From playlist can take tracks out of: the same + // gate as removing from the open one (its entry list is rewritten). + const removablePlaylists = useMemo(() => { + const walk = (nodes: PlaylistNode[]): PlaylistNode[] => + nodes.flatMap((n) => [...(n.can_reorder ? [n] : []), ...walk(n.children)]) + return canEdit ? walk(playlists.data ?? []) : [] + }, [playlists.data, canEdit]) // Export membership. Both are no-ops on the library itself, so neither dirties // it nor touches version history — an export set is Konduktor's own data. @@ -1094,6 +1101,50 @@ export default function App() { }, }) + // Remove ▸ From playlist ▸ : tracks picked anywhere leave a playlist + // that is not open — every copy of each. Counted first, so the dialog says + // how many of the selection it actually holds (and still answers at 0). + const confirmRemoveFromOther = async (p: PlaylistNode, ids: string[]) => { + let r + try { + r = await api.removeEntries(p.id, ids, true) + } catch (e) { + onError((e as Error).message) + return + } + const name = {p.name} + const held = r.tracks + setConfirmReq({ + title: 'Remove from playlist', + body: !held ? ( +

+ {ids.length === 1 ? <>{trackNoun(ids)} is not : <>None of these {ids.length} tracks are} in {name}. +

+ ) : ( + <> +

+ Remove {held === ids.length ? trackNoun(ids) : `${held} of the ${ids.length} selected tracks`} from {name}? + The {held === 1 ? 'track stays' : 'tracks stay'} in the collection. +

+ {held < ids.length && ( +

The other {nTracks(ids.length - held)} {ids.length - held === 1 ? 'is' : 'are'} not in it.

+ )} + {r.removed > held &&

Some are in it more than once; every copy goes.

} + + ), + confirmLabel: held ? `Remove ${nTracks(held)}` : 'Remove', + confirmDisabled: !held, + onConfirm: () => + guard(async () => { + const done = await api.removeEntries(p.id, ids) + qc.invalidateQueries({ queryKey: ['playlist', p.id] }) + qc.invalidateQueries({ queryKey: ['playlists'] }) + qc.invalidateQueries({ queryKey: ['state'] }) + notify('success', `Removed ${nTracks(done.tracks)} from ${p.name}`) + }), + }) + } + const confirmRemoveFromExport = (exportId: string, ids: string[]) => { const name = exportSets.data?.find((x) => x.id === exportId)?.name ?? 'this export' setConfirmReq({ @@ -1231,6 +1282,22 @@ export default function App() { ...(playlistEditable ? [{ label: 'From this playlist…', onClick: () => confirmRemoveFromPlaylist(ids) }] : []), + // Any other editable playlist — "A minus B" is: open B, select all, here A. + ...(() => { + // A device's ids mean nothing to the collection's playlists. + if (viewingDevice) return [] + const lists = removablePlaylists.filter((p) => !(source.kind === 'playlist' && p.id === source.id)) + return lists.length + ? [{ + label: 'From playlist', + submenu: lists.map((p) => ({ + label: p.name, + hint: String(p.count), + onClick: () => void confirmRemoveFromOther(p, ids), + })), + }] + : [] + })(), // Only on the export's ROOT view. Inside a referenced playlist there is // nothing to remove: the reference is live, and per-track removal would // need an exclusion list — hidden state deciding what a future export diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 31111ee..b2d2809 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -1272,6 +1272,14 @@ export const api = { `/api/playlists/${encodeURIComponent(nodeId)}/add`, { track_ids: trackIds, duplicates, index }, ), + /** Remove every occurrence of these tracks. `dryRun` changes nothing and + * counts: `tracks` = how many of them it holds, `removed` = entries. */ + removeEntries: (nodeId: string, trackIds: string[], dryRun = false) => + send<{ status: 'removed' | 'counted'; tracks: number; removed: number; count: number }>( + 'POST', + `/api/playlists/${encodeURIComponent(nodeId)}/remove`, + { track_ids: trackIds, dry_run: dryRun }, + ), /** 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) => diff --git a/frontend/src/components/ConfirmDialog.tsx b/frontend/src/components/ConfirmDialog.tsx index dc8444b..4eb9bc6 100644 --- a/frontend/src/components/ConfirmDialog.tsx +++ b/frontend/src/components/ConfirmDialog.tsx @@ -14,6 +14,9 @@ export interface ConfirmRequest { * (e.g. "Add them again" next to "Add 6 new"). Enter still means confirm. */ altLabel?: string onAlt?: () => void + /** Nothing to confirm (e.g. none of the tracks are there): the dialog + * still answers, with the confirm button — and Enter — off. */ + confirmDisabled?: boolean onConfirm: () => Promise | void } @@ -23,11 +26,11 @@ 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', altLabel, onAlt, onConfirm, onClose }: Props) { +export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altLabel, onAlt, confirmDisabled, onConfirm, onClose }: Props) { const [busy, setBusy] = useState(false) const confirm = async () => { - if (busy) return + if (busy || confirmDisabled) return setBusy(true) try { await onConfirm() @@ -87,7 +90,7 @@ export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altL )}