From 7160fa397802f9a7817be6039ba7af33848e4835 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Wed, 23 Sep 2026 15:04:53 +0200 Subject: [PATCH] Implemented export creation UI --- CLAUDE.md | 22 +- backend/konduktor/main.py | 19 ++ backend/test_exports.py | 13 + frontend/src/App.tsx | 187 +++++++++++++- frontend/src/api.ts | 5 + frontend/src/components/ExportDialog.tsx | 170 +++++++++++++ frontend/src/components/ExportsSection.tsx | 275 +++++++++++++++++++++ frontend/src/components/SelectionBar.tsx | 46 +++- frontend/src/components/Sidebar.tsx | 67 +++++ 9 files changed, 787 insertions(+), 17 deletions(-) create mode 100644 frontend/src/components/ExportDialog.tsx create mode 100644 frontend/src/components/ExportsSection.tsx diff --git a/CLAUDE.md b/CLAUDE.md index 1ea479d..61078db 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -258,7 +258,18 @@ Two independent apps that talk over HTTP: library or commit an import destination. It polls, because drives come and go while a dialog is open, and the volatile Drives group is LAST so an appearing drive cannot shift the rows above a moving cursor), - `CollectionPicker` (**two steps: which PLATFORM, then which + `ExportsSection` + `ExportDialog` (**exports in the sidebar** — each a + named, persisted slice of the library bound to a destination. An export + expands to show its referenced playlists, whose counts come from `contents` + recomputed on every read, because the references are LIVE. Two deliberate + omissions: a referenced playlist has **no per-track remove** — that would + need an exclusion list, i.e. hidden state deciding future exports — and an + export's views use `TrackTable`, **never `PlaylistTable`**, whose `×` removes + from the user's REAL playlist: same pixels, opposite meaning. Removal from an + export is on the context menu, and only on its root view. Adding is not gated + on the library being writable, since an export set is Konduktor's own data. + `ExportDialog` shows unsupported targets **disabled with a reason** rather + than hiding them), `CollectionPicker` (**two steps: which PLATFORM, then which library** — Automatic / Open last / Find manually, the last revealing a file browser. The platform comes first because every later answer depends on it: asked the other way round, "Automatic" had to guess ACROSS platforms and did @@ -618,9 +629,12 @@ that number and nothing else — everything derives from it: is a folder-deletion hazard, so an export writes a `.konduktor-export.json` manifest and **refuses to clear any folder that lacks one** — Konduktor only ever deletes what Konduktor wrote. - **Steps 1–2 done**: `library_id.py`, then `exports.py` + 10 routes + `api.ts`. - Next: the UI, then `core/exporter.py` + the Traktor writer on top of `jobs.py` - and `importer.py`'s copy machinery. Note the OneLibrary work already demonstrated + **Steps 1–3 done**: `library_id.py`; `exports.py` + 10 routes + `api.ts`; and + the UI (`ExportsSection`, `ExportDialog`, export views in `App`, "Add to…" on + `SelectionBar`, the track context menu and each sidebar playlist row). + Next: `core/exporter.py` + the Traktor writer, and the export run itself on top + of `jobs.py` and `importer.py`'s copy machinery — **there is no Export button + 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. - ⬜ Serato adapter diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index fa1d2d4..7ef7cab 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -463,6 +463,25 @@ def export_tracks(set_id: str) -> list[Track]: return [t for t in (adapter.track(tid) for tid in resolved.track_ids) if t is not None] +@app.get("/api/exports/{set_id}/loose", response_model=list[Track]) +def export_loose_tracks(set_id: str) -> list[Track]: + """Only the LOOSE tracks — the ones added individually. + + A separate route rather than a filter on the root view, because the two are + genuinely different questions: the root is everything this export would ship + (playlists included, deduped), and this is the "Other" bucket that becomes + its own playlist in the exported library. A track added loosely AND supplied + by a referenced playlist appears in both, which is honest — it is in the + loose list, and that is what the count beside "Other" reports. + """ + found = _require_set(set_id) + adapter = require_adapter() + resolved = exports.resolve(adapter, found) + return [ + t for t in (adapter.track(tid) for tid in resolved.loose_track_ids) if t is not None + ] + + @app.get("/api/exports/{set_id}/playlists/{playlist_id}/tracks", response_model=list[Track]) def export_playlist_tracks(set_id: str, playlist_id: str) -> list[Track]: """One included playlist, as it stands now. diff --git a/backend/test_exports.py b/backend/test_exports.py index aaddb4e..c0e41ed 100644 --- a/backend/test_exports.py +++ b/backend/test_exports.py @@ -106,6 +106,19 @@ check("the total is the union, not the sum", len(deduped) == len(set(deduped)) and len(deduped) >= len(playlist_tracks)) exports.remove(LIB, s1.id, track_ids=[playlist_tracks[0]]) +# The bug this replaced: the "Other" row selected the export ROOT, so clicking +# it showed every track the export would ship instead of only the loose ones. +# Three views, three genuinely different questions. +loose_view = exports.resolve(adapter, exports.get(LIB, s1.id)).loose_track_ids +root_view = exports.resolve(adapter, exports.get(LIB, s1.id)).track_ids +check("Other holds only the individually-added tracks", + loose_view == exports.get(LIB, s1.id).track_ids, loose_view) +check("which is NOT the same as the root view", + loose_view != root_view and set(loose_view) < set(root_view), + f"{len(loose_view)} vs {len(root_view)}") +check("and the playlist's tracks are absent from it", + not (set(loose_view) & set(playlist_tracks))) + print("== what is gone is SURFACED, never silently dropped ==") exports.add(LIB, s1.id, track_ids=["Macintosh HD/:nowhere/:ghost.mp3"]) gone = exports.resolve(adapter, exports.get(LIB, s1.id)) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 5b4c6dd..f4fa226 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -174,6 +174,39 @@ export default function App() { enabled: loaded && source.kind === 'playlist', }) + // An export set being browsed. Its tracks ARE collection tracks — an export is + // a slice of the loaded library, not another library — so these share the + // collection's capabilities and stay fully editable, unlike a device. + const viewingExport = + source.kind === 'export' || + source.kind === 'export-playlist' || + source.kind === 'export-other' + const exportTracks = useQuery({ + queryKey: ['export-tracks', source.kind === 'export' ? source.id : null], + queryFn: () => api.exportTracks((source as { id: string }).id), + enabled: source.kind === 'export', + }) + const exportPlaylistTracks = useQuery({ + queryKey: [ + 'export-playlist-tracks', + source.kind === 'export-playlist' ? source.exportId : null, + source.kind === 'export-playlist' ? source.id : null, + ], + queryFn: () => + api.exportPlaylistTracks( + (source as { exportId: string }).exportId, + (source as { id: string }).id, + ), + enabled: source.kind === 'export-playlist', + }) + // The loose tracks only. A separate query, not a filter on the root view: the + // root is everything the export would ship, which is a different answer. + const exportLooseTracks = useQuery({ + queryKey: ['export-loose', source.kind === 'export-other' ? source.exportId : null], + queryFn: () => api.exportLooseTracks((source as { exportId: string }).exportId), + enabled: source.kind === 'export-other', + }) + // A browsed device. Separate queries and separate cache keys from the // collection's: the two libraries can hold tracks with identical ids, and one // shared key would serve a stick's track as if it were a collection track. @@ -200,6 +233,42 @@ export default function App() { staleTime: Infinity, }) const openDevice = useQuery({ queryKey: ['source'], queryFn: api.source }) + const exportSets = useQuery({ queryKey: ['exports'], queryFn: api.exports, enabled: loaded }) + + // 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. + const refreshExport = useCallback( + (id: string) => { + qc.invalidateQueries({ queryKey: ['export-contents', id] }) + qc.invalidateQueries({ queryKey: ['export-tracks', id] }) + qc.invalidateQueries({ queryKey: ['export-loose', id] }) + }, + [qc], + ) + const addToExport = useCallback( + async (id: string, ids: string[]) => { + try { + await api.addToExport(id, { track_ids: ids }) + refreshExport(id) + const name = exportSets.data?.find((s) => s.id === id)?.name ?? 'export' + notify('success', `Added ${ids.length} track${ids.length === 1 ? '' : 's'} to ${name}`) + } catch (e) { + onError((e as Error).message) + } + }, + [refreshExport, exportSets.data, notify, onError], + ) + const removeFromExport = useCallback( + async (id: string, ids: string[]) => { + try { + await api.removeFromExport(id, { track_ids: ids }) + refreshExport(id) + } catch (e) { + onError((e as Error).message) + } + }, + [refreshExport, onError], + ) // What the VIEW can do, as opposed to what the loaded collection can do. While // a device is being browsed these are its read-only capabilities, so the @@ -230,16 +299,28 @@ export default function App() { ? source.kind === 'device' ? (deviceTracks.data?.items ?? []) : (devicePlaylistTracks.data ?? []) - : isAll - ? (allTracks.data?.items ?? []) - : (playlistTracks.data ?? []) + : viewingExport + ? source.kind === 'export' + ? (exportTracks.data ?? []) + : source.kind === 'export-other' + ? (exportLooseTracks.data ?? []) + : (exportPlaylistTracks.data ?? []) + : isAll + ? (allTracks.data?.items ?? []) + : (playlistTracks.data ?? []) const loading = viewingDevice ? source.kind === 'device' ? deviceTracks.isLoading : devicePlaylistTracks.isLoading - : isAll - ? allTracks.isLoading - : playlistTracks.isLoading + : viewingExport + ? source.kind === 'export' + ? exportTracks.isLoading + : source.kind === 'export-other' + ? exportLooseTracks.isLoading + : exportPlaylistTracks.isLoading + : isAll + ? allTracks.isLoading + : playlistTracks.isLoading // Search / filters apply to both the library and playlists (the toolbar is // always visible). In a playlist a filtered view disables drag-reorder — see // `canReorder` below — so a partial order can't overwrite the full entry list. @@ -339,6 +420,28 @@ export default function App() { ...(canEdit ? [{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }] : []), + // Adding to an export touches no library data, so it is offered even + // on a read-only one — an export is Konduktor's own curation. + ...(exportSets.data ?? []).map((set) => ({ + label: `Add to “${set.name}”`, + onClick: () => addToExport(set.id, [menu.track.id]), + })), + // 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 contains. Remove the whole playlist, or add tracks instead. + ...(source.kind === 'export' || source.kind === 'export-other' + ? [ + { + label: 'Remove from this export', + onClick: () => + removeFromExport( + source.kind === 'export' ? source.id : source.exportId, + [menu.track.id], + ), + }, + ] + : []), ]} onClose={() => setMenu(null)} /> @@ -398,6 +501,7 @@ export default function App() { onOpenHistory={() => setShowHistory(true)} onImport={() => setImporting(true)} onSwitchLibrary={() => setForcePicker(true)} + onDone={(msg) => notify('success', msg)} /> @@ -413,11 +517,33 @@ export default function App() { /> {(!isAll || viewingDevice) && (
- - {viewingDevice ? '⬒' : '♫'} + + {viewingDevice ? '⬒' : viewingExport ? (source.kind === 'export' ? '◈' : '♫') : '♫'} {viewName} - {viewingDevice ? ( + {viewingExport ? ( + <> + + {filtersActive + ? `${filtered.length} of ${tracks.length} tracks` + : `${tracks.length} tracks`} + {source.kind === 'export' + ? ' · everything this export would ship' + : source.kind === 'export-other' + ? ' · added individually — these become an “Other” playlist' + : ' · live — what ships is whatever this playlist holds at export time'} + + + + Export + + + + ) : viewingDevice ? ( <> {filtersActive @@ -449,6 +575,45 @@ export default function App() {
{loading ? (
Loading…
+ ) : viewingExport ? ( + /* An export uses the plain table, NOT the playlist one. The playlist + table's × removes a track from the user's REAL playlist — same + pixels, opposite meaning — and an export's own removal is offered + through the context menu instead, on its root view only. + Selection stays on, so "Add to…" works from inside an export. */ + filtered.length === 0 ? ( +
+
+ {tracks.length === 0 ? 'Nothing in this export yet' : 'No tracks match'} +
+
+ {tracks.length === 0 + ? 'Select tracks in All Tracks and use “Add to…”, or add a whole playlist.' + : 'Try clearing some filters.'} +
+
+ ) : ( + 0 && selected.size === filtered.length, + }} + onRowContextMenu={(track, x, y) => setMenu({ track, x, y })} + onPlay={playTrack} + onEditField={canEdit ? editField : undefined} + activeTrackId={prepTrack?.id ?? null} + columnVisibility={columnVisibility} + columnOrder={columnOrder} + columnSizing={columnSizing} + onColumnOrderChange={setColumnOrder} + onColumnSizingChange={setColumnSizing} + /> + ) ) : viewingDevice ? ( /* A device uses the plain table, not the playlist one: a stick's playlists cannot be reordered or have entries removed, so the @@ -539,7 +704,9 @@ export default function App() { /> )} - {isAll && ( + {/* Also inside an export: its rows ARE collection tracks, so "Add + to…" means the same thing there as in All Tracks. */} + {(isAll || viewingExport) && ( (`/api/exports/${encodeURIComponent(id)}/contents`), exportTracks: (id: string) => getJSON(`/api/exports/${encodeURIComponent(id)}/tracks`), + // Only the tracks added individually — the "Other" bucket, which becomes its + // own playlist in the exported library. Not a filter on exportTracks: that one + // is everything the export would ship, playlists included and deduped. + exportLooseTracks: (id: string) => + getJSON(`/api/exports/${encodeURIComponent(id)}/loose`), exportPlaylistTracks: (id: string, playlistId: string) => getJSON( `/api/exports/${encodeURIComponent(id)}/playlists/${encodeURIComponent(playlistId)}/tracks`, diff --git a/frontend/src/components/ExportDialog.tsx b/frontend/src/components/ExportDialog.tsx new file mode 100644 index 0000000..08bbc2b --- /dev/null +++ b/frontend/src/components/ExportDialog.tsx @@ -0,0 +1,170 @@ +import { useState } from 'react' +import { useQuery } from '@tanstack/react-query' +import { api, type ExportSet } from '../api' +import { FolderPicker } from './FolderPicker' + +/** + * Create or edit an export: its name, its target platform and where it lands. + * + * All three are settled up front, and the destination especially is NOT a + * detail deferred to export time. A Traktor `` is a volume name plus + * a volume-relative path — both derived from where the export is written — so + * the library file genuinely cannot be built until the destination is known. + */ + +interface Props { + /** The set being edited, or null to create a new one. */ + editing: ExportSet | null + onClose: () => void + onSaved: (set: ExportSet, created: boolean) => void + onError: (msg: string) => void +} + +export function ExportDialog({ editing, onClose, onSaved, onError }: Props) { + const [name, setName] = useState(editing?.name ?? '') + const [target, setTarget] = useState(editing?.target ?? 'traktor') + const [destination, setDestination] = useState(editing?.destination ?? '') + const [browsing, setBrowsing] = useState(false) + const [busy, setBusy] = useState(false) + + // Every platform, with `installed` standing for "can be an export target". + // The unsupported ones are shown DISABLED with a reason rather than hidden: + // an absent option reads as a missing feature, a disabled one as a roadmap. + const targets = useQuery({ queryKey: ['export-targets'], queryFn: api.exportTargets }) + + // Another set writing to the same folder would have its output wiped, because + // an export clears its destination before writing. Caught while the folder is + // being chosen — at run time a warning would already be too late. + const conflict = useQuery({ + queryKey: ['export-conflict', editing?.id ?? null], + queryFn: () => api.exportContents(editing!.id), + enabled: !!editing, + }).data?.destination_conflict + + const valid = name.trim() !== '' && destination.trim() !== '' + + const save = async () => { + setBusy(true) + try { + const body = { name: name.trim(), target, destination: destination.trim() } + const saved = editing + ? await api.updateExport(editing.id, body) + : await api.createExport(body) + onSaved(saved, !editing) + } catch (e) { + onError((e as Error).message) + } finally { + setBusy(false) + } + } + + return ( + <> + {browsing && ( + setBrowsing(false)} + /> + )} +
+
+
+

+ {editing ? `Edit “${editing.name}”` : 'New export'} +

+
+ +
+
+ Name + setName(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' && valid && !busy) save() + }} + className="w-full rounded-md border border-line bg-ink-950 px-2 py-1.5 text-sm text-text outline-none focus:border-accent" + /> +
+ +
+ For +
+ {(targets.data ?? []).map((p) => ( + + ))} +
+
+ +
+ Export to +
+ + {destination || 'Choose a folder…'} + + +
+
+ The folder gets a collection.nml and a copy of + every track, in your own folder structure. +
+ {conflict && ( +
+ “{conflict}” already exports here. Exporting replaces whatever the other one + wrote. +
+ )} +
+
+ +
+ + +
+
+
+ + ) +} diff --git a/frontend/src/components/ExportsSection.tsx b/frontend/src/components/ExportsSection.tsx new file mode 100644 index 0000000..f493953 --- /dev/null +++ b/frontend/src/components/ExportsSection.tsx @@ -0,0 +1,275 @@ +import { useState } from 'react' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { api, type ExportSet } from '../api' +import { ExportDialog } from './ExportDialog' +import type { Source } from './Sidebar' + +/** + * Exports in the sidebar: each one a named, persisted slice of the library + * bound to a destination. + * + * An export expands to show the playlists it references. Those are LIVE links — + * what ships is whatever the playlist holds at export time — which is why the + * counts here come from `contents`, recomputed on every read, rather than from + * anything stored in the set. + * + * The one deliberate omission: a referenced playlist has no per-track remove. + * A live reference and per-track removal are in tension, and honouring both + * would need an exclusion list — hidden state quietly deciding what a future + * export contains. Remove the whole playlist, or add the tracks instead of it. + */ + +interface Props { + source: Source + onSelect: (s: Source) => void + onDone: (msg: string) => void + onError: (msg: string) => void +} + +export function ExportsSection({ source, onSelect, onDone, onError }: Props) { + const qc = useQueryClient() + const [dialog, setDialog] = useState<{ editing: ExportSet | null } | null>(null) + + const sets = useQuery({ queryKey: ['exports'], queryFn: api.exports }) + + const remove = useMutation({ + mutationFn: (id: string) => api.deleteExport(id), + onSuccess: (_r, id) => { + qc.invalidateQueries({ queryKey: ['exports'] }) + if ( + (source.kind === 'export' && source.id === id) || + ((source.kind === 'export-playlist' || source.kind === 'export-other') && + source.exportId === id) + ) + onSelect({ kind: 'all' }) + }, + onError: (e: Error) => onError(e.message), + }) + + const list = sets.data ?? [] + + return ( + <> + {dialog && ( + setDialog(null)} + onSaved={(saved, created) => { + qc.invalidateQueries({ queryKey: ['exports'] }) + qc.invalidateQueries({ queryKey: ['export-contents'] }) + setDialog(null) + onDone(created ? `Created “${saved.name}”` : `Saved “${saved.name}”`) + if (created) onSelect({ kind: 'export', id: saved.id, name: saved.name }) + }} + onError={onError} + /> + )} + +
+ + Exports + + +
+ +
+ {list.length === 0 && ( +
+ A curated set of tracks, copied to a folder with its own library file. +
+ )} + {list.map((set) => ( + setDialog({ editing: set })} + onDelete={() => { + // Deleting a set never touches its destination folder — the files + // already exported are the user's, not Konduktor's to clean up. + if (confirm(`Delete the export “${set.name}”? Nothing already exported is removed.`)) + remove.mutate(set.id) + }} + onError={onError} + /> + ))} +
+ + ) +} + +function ExportRow({ + set, + source, + onSelect, + onEdit, + onDelete, + onError, +}: { + set: ExportSet + source: Source + onSelect: (s: Source) => void + onEdit: () => void + onDelete: () => void + onError: (msg: string) => void +}) { + const qc = useQueryClient() + const selected = source.kind === 'export' && source.id === set.id + const inside = + selected || + ((source.kind === 'export-playlist' || source.kind === 'export-other') && + source.exportId === set.id) + const [open, setOpen] = useState(false) + + // Live: recomputed every read, because a referenced playlist edited after + // curation changes what this export would ship. + const contents = useQuery({ + queryKey: ['export-contents', set.id], + queryFn: () => api.exportContents(set.id), + }) + + const dropPlaylist = useMutation({ + mutationFn: (playlistId: string) => + api.removeFromExport(set.id, { playlist_ids: [playlistId] }), + onSuccess: () => { + qc.invalidateQueries({ queryKey: ['export-contents', set.id] }) + qc.invalidateQueries({ queryKey: ['export-tracks', set.id] }) + }, + onError: (e: Error) => onError(e.message), + }) + + const data = contents.data + const expanded = open || inside + + return ( +
+
+ + + + +
+ + {expanded && ( + <> + {(data?.playlists ?? []).map((p) => { + const chosen = source.kind === 'export-playlist' && source.id === p.id + return ( +
+ + +
+ ) + })} + + {!!data?.loose && ( + + )} + + {!!data?.dangling.length && ( +
+ {data.dangling.length} track{data.dangling.length === 1 ? '' : 's'} no longer in your + library +
+ )} + + {expanded && data && data.tracks === 0 && ( +
+ Empty — select tracks and use “Add to…”. +
+ )} + + )} +
+ ) +} diff --git a/frontend/src/components/SelectionBar.tsx b/frontend/src/components/SelectionBar.tsx index cf1b101..62c57c6 100644 --- a/frontend/src/components/SelectionBar.tsx +++ b/frontend/src/components/SelectionBar.tsx @@ -22,7 +22,27 @@ export function SelectionBar({ count, trackIds, onClear, onDone, onError }: Prop const qc = useQueryClient() const [menuOpen, setMenuOpen] = useState(false) const { data: playlists } = useQuery({ queryKey: ['playlists'], queryFn: api.playlists }) + const { data: exportSets } = useQuery({ queryKey: ['exports'], queryFn: api.exports }) const flat = playlists ? flattenPlaylists(playlists) : [] + const sets = exportSets ?? [] + + // Adding to an EXPORT does not touch the library — an export set is + // Konduktor's own curation — so unlike the playlist mutation this dirties + // nothing and invalidates only the export's own live counts. + const addToExport = useMutation({ + mutationFn: ({ id, ids }: { id: string; ids: string[] }) => + api.addToExport(id, { track_ids: ids }), + onSuccess: (_res, vars) => { + qc.invalidateQueries({ queryKey: ['export-contents', vars.id] }) + qc.invalidateQueries({ queryKey: ['export-tracks', vars.id] }) + qc.invalidateQueries({ queryKey: ['export-loose', vars.id] }) + const set = sets.find((s) => s.id === vars.id) + onDone(`Added ${vars.ids.length} track${vars.ids.length === 1 ? '' : 's'} to ${set?.name ?? 'export'}`) + setMenuOpen(false) + onClear() + }, + onError: (e: Error) => onError(e.message), + }) const add = useMutation({ mutationFn: ({ uuid, ids }: { uuid: string; ids: string[] }) => api.addEntries(uuid, ids), @@ -51,12 +71,15 @@ export function SelectionBar({ count, trackIds, onClear, onDone, onError }: Prop onClick={() => setMenuOpen((o) => !o)} className="rounded-full bg-accent px-3 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110" > - Add to playlist ▾ + Add to… ▾ {menuOpen && ( -
+
+
+ Playlists +
{flat.length === 0 && ( -
No playlists yet
+
No playlists yet
)} {flat.map((p) => ( ))} + +
+ Exports +
+ {sets.length === 0 && ( +
No exports yet
+ )} + {sets.map((set) => ( + + ))}
)}
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index 0acd89c..8c76e7e 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -4,6 +4,7 @@ import { api, type PlaylistKind, type PlaylistNode } from '../api' import { useCaps } from '../lib/capabilities' import { SaveBar } from './SaveBar' import { DevicesSection } from './DevicesSection' +import { ExportsSection } from './ExportsSection' /** * Which view the main table is showing. @@ -20,6 +21,15 @@ export type Source = | { kind: 'playlist'; id: string; name: string } | { kind: 'device' } | { kind: 'device-playlist'; id: string; name: string } + // An export set. `export` is its root — every track it would ship, deduped — + // and `export-playlist` is one referenced playlist inside it, read live from + // the library rather than from the set, which is the reference doing its job. + | { kind: 'export'; id: string; name: string } + | { kind: 'export-playlist'; exportId: string; id: string; name: string } + // The loose tracks — those added individually rather than via a playlist. + // A view of its own, NOT the export root: the root is everything the export + // would ship, which is a different question and a different answer. + | { kind: 'export-other'; exportId: string; name: string } interface Props { source: Source @@ -28,10 +38,17 @@ interface Props { onOpenHistory: () => void onImport: () => void onSwitchLibrary: () => void + onDone: (msg: string) => void } // 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)] +} + const icons: Record = { folder: '▸', playlist: '♫', @@ -54,7 +71,23 @@ function NodeRow({ const qc = useQueryClient() const [open, setOpen] = useState(true) const [renaming, setRenaming] = useState(false) + const [adding, setAdding] = useState(false) const [draft, setDraft] = useState(node.name) + const exportSets = useQuery({ queryKey: ['exports'], queryFn: api.exports }).data ?? [] + + // A FOLDER contributes its nested playlists; a playlist contributes itself. + // Folders are flattened here rather than stored as a folder reference: the + // export stores playlist ids, and a folder is a shape in the tree, not a + // thing with tracks. + const addToExport = useMutation({ + mutationFn: (setId: string) => + api.addToExport(setId, { playlist_ids: playlistIdsUnder(node) }), + onSuccess: (_r, setId) => { + qc.invalidateQueries({ queryKey: ['export-contents', setId] }) + qc.invalidateQueries({ queryKey: ['export-tracks', setId] }) + }, + onError: (e: Error) => onError(e.message), + }) const isFolder = node.kind === 'folder' const selected = source.kind === 'playlist' && source.id === node.id const selectable = node.selectable @@ -136,6 +169,37 @@ function NodeRow({ {/* Each action gates on ITS OWN flag: a platform may allow renaming but not deleting. The count shows either way — it is information, not an action, and hiding it on a read-only library loses real data. */} + {/* Add this playlist (or folder) to an export. Not gated on the + library being writable: an export set is Konduktor's own curation + and adding to one changes nothing in the user's library. */} + {!renaming && exportSets.length > 0 && ( +
+ + {adding && ( +
+ {exportSets.map((set) => ( + + ))} +
+ )} +
+ )} {!renaming && node.can_rename && (