mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 18:22:53 +01:00
Added playlist folder management
This commit is contained in:
1 parent
efdd0f6203
commit
88737f2b08
9 files changed
+414
-116
No files matched your search
@@ -335,8 +335,14 @@ Two independent apps that talk over HTTP:
|
||||
picker used to be a one-way door with `forcePicker` never set, so changing
|
||||
library meant restarting; switching confirms first when there are unsaved
|
||||
edits, since the adapter holds them in a native model that opening another
|
||||
library replaces — plus the playlist tree +
|
||||
create/rename/delete), `SaveBar` (+ the settings gear beside it), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
|
||||
library replaces — plus the playlist tree. **Creating is right-click
|
||||
only**: a folder's menu offers New Playlist / New Folder inside it, empty
|
||||
space below the rows creates at the top level, and the new node is named
|
||||
in place (Esc or an empty name creates nothing). Rename/Delete are on the
|
||||
same menu and the row's hover buttons, which share one set of actions.
|
||||
A Traktor folder's id is its PATH of names, so the `PATCH`/`DELETE`
|
||||
playlist routes take a `:path` param, a folder name may not contain `/`,
|
||||
and renaming onto a sibling folder's name is refused), `SaveBar` (+ the settings gear beside it), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
|
||||
`TrackTable` (**the one track list** — All Tracks, playlists, exports and
|
||||
devices. TanStack Table + **virtualized** grid; per-row play button,
|
||||
configurable columns, header sorting, inline double-click editing, and
|
||||
|
||||
@@ -236,11 +236,8 @@ class RekordboxAdapter:
|
||||
return self._store.create_playlist(name, parent_id)
|
||||
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
||||
# Rekordbox CAN hold folders (`capabilities.playlists.folders` is
|
||||
# True, and pyrekordbox has `add_playlist_folder`), so this is a
|
||||
# gap rather than a refusal in principle. Traktor is the only
|
||||
# import target for now, so it is the only one that needed it.
|
||||
self._refuse("Creating playlist folders")
|
||||
self._require_writable("Creating playlist folders")
|
||||
return self._store.create_folder(name, parent_id)
|
||||
|
||||
def rename_playlist(self, node_id: str, name: str) -> None:
|
||||
self._require_writable("Renaming playlists")
|
||||
|
||||
@@ -391,6 +391,19 @@ class RekordboxStore:
|
||||
self._journal.record("playlist", "create", name)
|
||||
return str(row.ID)
|
||||
|
||||
def create_folder(self, name: str, parent_id: str | None = None) -> str:
|
||||
name = (name or "").strip()
|
||||
if not name:
|
||||
raise InvalidCommand("A folder needs a name")
|
||||
parent = self._playlist(parent_id) if parent_id else None
|
||||
if parent is not None and int(parent.Attribute or 0) != int(
|
||||
self._tables.PlaylistType.FOLDER
|
||||
):
|
||||
raise InvalidCommand("A folder can only be created inside a folder")
|
||||
row = self._db.create_playlist_folder(name, parent=parent)
|
||||
self._journal.record("playlist", "create-folder", name)
|
||||
return str(row.ID)
|
||||
|
||||
def rename_playlist(self, node_id: str, name: str) -> None:
|
||||
name = (name or "").strip()
|
||||
if not name:
|
||||
|
||||
@@ -168,6 +168,8 @@ class TraktorStore:
|
||||
kind="folder",
|
||||
children=[self._to_model(c, path) for c in self._children(node)],
|
||||
can_contain_children=True,
|
||||
can_rename=True,
|
||||
can_delete=True,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -252,6 +254,7 @@ class TraktorStore:
|
||||
second import from the same stick should land beside the first rather
|
||||
than next to an identically-named twin.
|
||||
"""
|
||||
self._check_folder_name(name)
|
||||
with self._lock:
|
||||
parent = self._find_folder(parent_id)
|
||||
existing = next(
|
||||
@@ -276,8 +279,38 @@ class TraktorStore:
|
||||
self.dirty = True
|
||||
return folder_id
|
||||
|
||||
@staticmethod
|
||||
def _check_folder_name(name: str) -> None:
|
||||
# A folder is addressed by its path of names, so a "/" in one would
|
||||
# split it into two path segments and the folder could never be found.
|
||||
if not name:
|
||||
raise PlaylistError("A folder needs a name")
|
||||
if "/" in name:
|
||||
raise PlaylistError('A folder name cannot contain "/"')
|
||||
|
||||
def _rename_folder(self, folder_id: str, name: str) -> None:
|
||||
"""Rename a folder. Its id is its path, so the id changes with it —
|
||||
and a sibling folder of the same name would make both unaddressable,
|
||||
so that is refused rather than silently merged."""
|
||||
self._check_folder_name(name)
|
||||
node = self._find_folder(folder_id)
|
||||
if node is self._root():
|
||||
raise PlaylistError("Cannot rename the root folder")
|
||||
parent = self._find_parent_of(node)
|
||||
if any(
|
||||
c is not node and (c.type or "FOLDER") == "FOLDER" and c.name == name
|
||||
for c in self._children(parent)
|
||||
):
|
||||
raise PlaylistError(f'There is already a folder called "{name}" here')
|
||||
node.name = name
|
||||
self._note("playlist-rename", name)
|
||||
self.dirty = True
|
||||
|
||||
def rename_playlist(self, playlist_uuid: str, name: str) -> None:
|
||||
with self._lock:
|
||||
if playlist_uuid.startswith("fld:"):
|
||||
self._rename_folder(playlist_uuid, name)
|
||||
return
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
if node is None:
|
||||
raise PlaylistError(f"Playlist not found: {playlist_uuid}")
|
||||
@@ -286,7 +319,19 @@ class TraktorStore:
|
||||
self.dirty = True
|
||||
|
||||
def delete_playlist(self, playlist_uuid: str) -> None:
|
||||
"""Delete a playlist, or a FOLDER and everything nested in it.
|
||||
|
||||
A folder is addressed by its synthetic `fld:` path id. Removing its node
|
||||
removes its subtree with it — the NML nests children inside the parent's
|
||||
SUBNODES, so there is nothing elsewhere to clean up; the tracks stay in
|
||||
the collection.
|
||||
"""
|
||||
with self._lock:
|
||||
if playlist_uuid.startswith("fld:"):
|
||||
if playlist_uuid == "fld:":
|
||||
raise PlaylistError("Cannot delete the root folder")
|
||||
node = self._find_folder(playlist_uuid)
|
||||
else:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
if node is None:
|
||||
raise PlaylistError(f"Playlist not found: {playlist_uuid}")
|
||||
|
||||
@@ -721,13 +721,30 @@ def create_playlist(body: CreatePlaylist) -> PlaylistNode:
|
||||
)
|
||||
|
||||
|
||||
@app.patch("/api/playlists/{playlist_uuid}")
|
||||
@app.post("/api/playlists/folders", response_model=PlaylistNode)
|
||||
def create_folder(body: CreatePlaylist) -> PlaylistNode:
|
||||
name = body.name.strip() or "New Folder"
|
||||
new_id = require_adapter().create_folder(name, body.parent_id)
|
||||
return PlaylistNode(
|
||||
id=new_id,
|
||||
name=name,
|
||||
kind="folder",
|
||||
can_contain_children=True,
|
||||
can_rename=True,
|
||||
can_delete=True,
|
||||
)
|
||||
|
||||
|
||||
# `:path` for the same reason as delete: a folder id is a path of names.
|
||||
@app.patch("/api/playlists/{playlist_uuid:path}")
|
||||
def rename_playlist(playlist_uuid: str, body: RenamePlaylist) -> dict:
|
||||
require_adapter().rename_playlist(playlist_uuid, body.name.strip())
|
||||
return {"status": "renamed", "id": playlist_uuid, "name": body.name}
|
||||
|
||||
|
||||
@app.delete("/api/playlists/{playlist_uuid}")
|
||||
# `:path` because a folder id is a path of names (`fld:a/b`), and the slash
|
||||
# would otherwise end the segment.
|
||||
@app.delete("/api/playlists/{playlist_uuid:path}")
|
||||
def delete_playlist(playlist_uuid: str) -> dict:
|
||||
require_adapter().delete_playlist(playlist_uuid)
|
||||
return {"status": "deleted", "id": playlist_uuid}
|
||||
|
||||
@@ -134,6 +134,44 @@ still = [
|
||||
check("playlist gone after delete+save", len(still) == 0)
|
||||
check("COLLECTION still byte-identical", collection_span(WORK.read_bytes()) == collection_before)
|
||||
|
||||
print("== folders: create, rename, delete (nested ids contain a slash) ==")
|
||||
outer = client.post("/api/playlists/folders", json={"name": "Konduktor Test Folder"}).json()["id"]
|
||||
inner = client.post(
|
||||
"/api/playlists/folders", json={"name": "Inner Draft", "parent_id": outer}
|
||||
).json()["id"]
|
||||
check("nested folder id is its path", inner == "fld:Konduktor Test Folder/Inner Draft")
|
||||
r = client.patch(f"/api/playlists/{inner.replace('/', '%2F')}", json={"name": "Inner"})
|
||||
check("nested folder rename accepted", r.status_code == 200)
|
||||
inner = "fld:Konduktor Test Folder/Inner"
|
||||
nodes = flat(client.get("/api/playlists").json())
|
||||
check("renamed folder found by its new path", any(n["id"] == inner for n in nodes))
|
||||
check("folder name with a slash refused",
|
||||
client.post("/api/playlists/folders", json={"name": "a/b"}).status_code == 400)
|
||||
client.post("/api/playlists/folders", json={"name": "Sibling", "parent_id": outer})
|
||||
check("rename onto a sibling folder's name refused",
|
||||
client.patch(f"/api/playlists/{outer}%2FSibling", json={"name": "Inner"}).status_code == 400)
|
||||
nested_uuid = client.post(
|
||||
"/api/playlists", json={"name": "Nested", "parent_id": inner}
|
||||
).json()["id"]
|
||||
nodes = flat(client.get("/api/playlists").json())
|
||||
check("nested folder offered as deletable",
|
||||
any(n["id"] == inner and n["can_delete"] for n in nodes))
|
||||
r = client.delete(f"/api/playlists/{inner.replace('/', '%2F')}")
|
||||
check("nested folder delete accepted", r.status_code == 200)
|
||||
nodes = flat(client.get("/api/playlists").json())
|
||||
check("folder and its playlist gone",
|
||||
not any(n["id"] in (inner, nested_uuid) for n in nodes))
|
||||
check("parent folder kept", any(n["id"] == outer for n in nodes))
|
||||
client.delete(f"/api/playlists/{outer}")
|
||||
client.post("/api/save")
|
||||
coll3 = TraktorCollection(path=WORK)
|
||||
check("no test folder in saved file",
|
||||
not any(n.name == "Konduktor Test Folder" for n in walk(coll3.nml.playlists.node)))
|
||||
check("COLLECTION still byte-identical after folder delete",
|
||||
collection_span(WORK.read_bytes()) == collection_before)
|
||||
check("unknown folder is 404",
|
||||
client.delete("/api/playlists/fld:No Such Folder").status_code == 404)
|
||||
|
||||
print("== original untouched ==")
|
||||
check(
|
||||
"original collection.nml never modified",
|
||||
|
||||
@@ -237,6 +237,25 @@ with tempfile.TemporaryDirectory() as d:
|
||||
len(final.playlist_tree()) == len(before_tree),
|
||||
f"{len(final.playlist_tree())} vs {len(before_tree)}")
|
||||
|
||||
# A folder, a playlist inside it, and deleting the folder takes both.
|
||||
folder_id = final.create_folder("Konduktor Test Folder")
|
||||
inner_id = final.create_playlist("Konduktor Inner", folder_id)
|
||||
final.save()
|
||||
folder_reopened = RekordboxAdapter(work)
|
||||
folder = next((n for n in folder_reopened.playlist_tree() if n.id == folder_id), None)
|
||||
check("a folder round-trips as a folder",
|
||||
folder is not None and folder.kind == "folder")
|
||||
check("a playlist created inside it is its child",
|
||||
folder is not None and [c.id for c in folder.children] == [inner_id])
|
||||
folder_reopened.delete_playlist(folder_id)
|
||||
folder_reopened.save()
|
||||
after_folder = RekordboxAdapter(work)
|
||||
flat_ids = lambda ns: [x for n in ns for x in [n.id] + flat_ids(n.children)]
|
||||
check("deleting the folder removes it AND its playlist",
|
||||
not {folder_id, inner_id} & set(flat_ids(after_folder.playlist_tree())))
|
||||
folder_reopened.close()
|
||||
after_folder.close()
|
||||
|
||||
# ---- 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])
|
||||
|
||||
@@ -625,6 +625,8 @@ export const api = {
|
||||
state: () => getJSON<EditState>('/api/state'),
|
||||
createPlaylist: (name: string, parentId?: string) =>
|
||||
send<PlaylistNode>('POST', '/api/playlists', { name, parent_id: parentId ?? null }),
|
||||
createFolder: (name: string, parentId?: string) =>
|
||||
send<PlaylistNode>('POST', '/api/playlists/folders', { name, parent_id: parentId ?? null }),
|
||||
renamePlaylist: (nodeId: string, name: string) =>
|
||||
send<{ status: string }>('PATCH', `/api/playlists/${encodeURIComponent(nodeId)}`, { name }),
|
||||
deletePlaylist: (nodeId: string) =>
|
||||
|
||||
+268
-107
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react'
|
||||
import { useRef, useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, type PlaylistKind, type PlaylistNode } from '../api'
|
||||
import { useCaps } from '../lib/capabilities'
|
||||
@@ -6,6 +6,8 @@ import { SaveBar } from './SaveBar'
|
||||
import { SettingsMenu } from './SettingsMenu'
|
||||
import { DevicesSection } from './DevicesSection'
|
||||
import { ExportsSection } from './ExportsSection'
|
||||
import { ConfirmDialog, type ConfirmRequest } from './ConfirmDialog'
|
||||
import { ContextMenu, type MenuItem } from './ContextMenu'
|
||||
|
||||
/**
|
||||
* Which view the main table is showing.
|
||||
@@ -51,76 +53,137 @@ function playlistIdsUnder(node: PlaylistNode): string[] {
|
||||
return [...here, ...(node.children ?? []).flatMap(playlistIdsUnder)]
|
||||
}
|
||||
|
||||
/** The confirm wording for deleting a node. A folder says what goes with it,
|
||||
* since the whole subtree is deleted and the row only shows the folder. */
|
||||
function deleteRequest(node: PlaylistNode) {
|
||||
if (node.kind !== 'folder')
|
||||
return {
|
||||
title: 'Delete playlist',
|
||||
body: `Delete "${node.name}"? Its tracks stay in your collection.`,
|
||||
confirmLabel: 'Delete playlist',
|
||||
}
|
||||
const playlists = playlistIdsUnder(node).length
|
||||
const inside =
|
||||
playlists === 0
|
||||
? 'It is empty.'
|
||||
: `The ${playlists === 1 ? 'playlist' : `${playlists} playlists`} inside it will be deleted too; their tracks stay in your collection.`
|
||||
return {
|
||||
title: 'Delete folder',
|
||||
body: `Delete "${node.name}"? ${inside}`,
|
||||
confirmLabel: 'Delete folder',
|
||||
}
|
||||
}
|
||||
|
||||
const icons: Record<PlaylistKind, string> = {
|
||||
folder: '▸',
|
||||
playlist: '♫',
|
||||
smart: '✦',
|
||||
}
|
||||
|
||||
/** What the sidebar is naming in place: a new node, and the folder it goes in
|
||||
* (`null` = the top level). Nothing is created until the name is committed. */
|
||||
type Draft = { kind: 'playlist' | 'folder'; parentId: string | null }
|
||||
|
||||
/** Actions a row can ask of the sidebar. They live there, not in the row, so
|
||||
* the right-click menu and the hover buttons run the very same code. */
|
||||
interface RowActions {
|
||||
onContextMenu: (e: React.MouseEvent, node: PlaylistNode) => void
|
||||
onRename: (node: PlaylistNode, name: string) => void
|
||||
onDelete: (node: PlaylistNode) => void
|
||||
onAddToExport: (node: PlaylistNode, setId: string) => void
|
||||
onCommitDraft: (name: string) => void
|
||||
onCancelDraft: () => void
|
||||
}
|
||||
|
||||
/** The inline name field for a node being created. Enter or clicking away
|
||||
* commits a non-empty name; Esc (or an empty name) creates nothing. */
|
||||
function DraftRow({
|
||||
draft,
|
||||
depth,
|
||||
actions,
|
||||
}: {
|
||||
draft: Draft
|
||||
depth: number
|
||||
actions: RowActions
|
||||
}) {
|
||||
const [name, setName] = useState('')
|
||||
const done = useRef(false)
|
||||
const finish = (commit: boolean) => {
|
||||
if (done.current) return
|
||||
done.current = true
|
||||
if (commit && name.trim()) actions.onCommitDraft(name.trim())
|
||||
else actions.onCancelDraft()
|
||||
}
|
||||
return (
|
||||
<div
|
||||
className="flex items-center gap-2 py-1 pr-1 text-sm"
|
||||
style={{ paddingLeft: `${8 + depth * 14}px` }}
|
||||
>
|
||||
<span
|
||||
className={`w-3 shrink-0 text-center text-[11px] ${
|
||||
draft.kind === 'folder' ? 'text-faint' : 'text-accent'
|
||||
}`}
|
||||
>
|
||||
{icons[draft.kind]}
|
||||
</span>
|
||||
<input
|
||||
autoFocus
|
||||
value={name}
|
||||
placeholder={draft.kind === 'folder' ? 'Folder name…' : 'Playlist name…'}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') finish(true)
|
||||
else if (e.key === 'Escape') finish(false)
|
||||
}}
|
||||
onBlur={() => finish(true)}
|
||||
className="min-w-0 flex-1 rounded border border-accent bg-ink-950 px-1 py-0 text-sm text-text outline-none"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function NodeRow({
|
||||
node,
|
||||
depth,
|
||||
source,
|
||||
onSelect,
|
||||
onError,
|
||||
renamingId,
|
||||
setRenamingId,
|
||||
draft,
|
||||
exportSets,
|
||||
actions,
|
||||
}: {
|
||||
node: PlaylistNode
|
||||
depth: number
|
||||
source: Source
|
||||
onSelect: (s: Source) => void
|
||||
onError: (msg: string) => void
|
||||
renamingId: string | null
|
||||
setRenamingId: (id: string | null) => void
|
||||
draft: Draft | null
|
||||
exportSets: { id: string; name: string }[]
|
||||
actions: RowActions
|
||||
}) {
|
||||
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 renaming = renamingId === node.id
|
||||
const [renameDraft, setRenameDraft] = useState(node.name)
|
||||
const isFolder = node.kind === 'folder'
|
||||
const selected = source.kind === 'playlist' && source.id === node.id
|
||||
const selectable = node.selectable
|
||||
// A folder being created into shows its children, or the draft would be
|
||||
// typed into a collapsed folder the user cannot see.
|
||||
const draftHere = draft !== null && draft.parentId === node.id
|
||||
const expanded = isFolder && (open || draftHere)
|
||||
|
||||
const invalidate = () => {
|
||||
qc.invalidateQueries({ queryKey: ['playlists'] })
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
const startRename = () => {
|
||||
setRenameDraft(node.name)
|
||||
setRenamingId(node.id)
|
||||
}
|
||||
|
||||
const rename = useMutation({
|
||||
mutationFn: (name: string) => api.renamePlaylist(node.id, name),
|
||||
onSuccess: (_d, name) => {
|
||||
invalidate()
|
||||
if (source.kind === 'playlist' && source.id === node.id)
|
||||
onSelect({ kind: 'playlist', id: node.id, name })
|
||||
},
|
||||
onError: (e: Error) => onError(e.message),
|
||||
})
|
||||
|
||||
const del = useMutation({
|
||||
mutationFn: () => api.deletePlaylist(node.id),
|
||||
onSuccess: () => {
|
||||
invalidate()
|
||||
if (source.kind === 'playlist' && source.id === node.id) onSelect({ kind: 'all' })
|
||||
},
|
||||
onError: (e: Error) => onError(e.message),
|
||||
})
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
onContextMenu={(e) => actions.onContextMenu(e, node)}
|
||||
className={`group flex items-center gap-1 rounded-md pr-1 text-sm transition-colors ${
|
||||
selected ? 'bg-accent-soft text-text' : 'text-muted hover:bg-ink-800 hover:text-text'
|
||||
}`}
|
||||
@@ -138,29 +201,26 @@ function NodeRow({
|
||||
<span
|
||||
className={`w-3 shrink-0 text-center text-[11px] ${
|
||||
isFolder ? 'text-faint' : node.kind === 'smart' ? 'text-pink' : 'text-accent'
|
||||
} ${isFolder && open ? 'rotate-90' : ''} transition-transform`}
|
||||
} ${expanded ? 'rotate-90' : ''} transition-transform`}
|
||||
>
|
||||
{icons[node.kind]}
|
||||
</span>
|
||||
{renaming ? (
|
||||
<input
|
||||
autoFocus
|
||||
value={draft}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
value={renameDraft}
|
||||
onChange={(e) => setRenameDraft(e.target.value)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
setRenaming(false)
|
||||
if (draft.trim() && draft !== node.name) rename.mutate(draft.trim())
|
||||
setRenamingId(null)
|
||||
if (renameDraft.trim() && renameDraft.trim() !== node.name)
|
||||
actions.onRename(node, renameDraft.trim())
|
||||
} else if (e.key === 'Escape') {
|
||||
setRenaming(false)
|
||||
setDraft(node.name)
|
||||
setRenamingId(null)
|
||||
}
|
||||
}}
|
||||
onBlur={() => {
|
||||
setRenaming(false)
|
||||
setDraft(node.name)
|
||||
}}
|
||||
onBlur={() => setRenamingId(null)}
|
||||
className="min-w-0 flex-1 rounded border border-accent bg-ink-950 px-1 py-0 text-sm text-text outline-none"
|
||||
/>
|
||||
) : (
|
||||
@@ -190,7 +250,7 @@ function NodeRow({
|
||||
key={set.id}
|
||||
onClick={() => {
|
||||
setAdding(false)
|
||||
addToExport.mutate(set.id)
|
||||
actions.onAddToExport(node, set.id)
|
||||
}}
|
||||
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm text-muted hover:bg-ink-800 hover:text-text"
|
||||
>
|
||||
@@ -205,10 +265,7 @@ function NodeRow({
|
||||
{!renaming && node.can_rename && (
|
||||
<button
|
||||
title="Rename"
|
||||
onClick={() => {
|
||||
setDraft(node.name)
|
||||
setRenaming(true)
|
||||
}}
|
||||
onClick={startRename}
|
||||
className="hidden shrink-0 rounded px-1 text-xs text-faint hover:text-text group-hover:block"
|
||||
>
|
||||
✎
|
||||
@@ -216,10 +273,8 @@ function NodeRow({
|
||||
)}
|
||||
{!renaming && node.can_delete && (
|
||||
<button
|
||||
title="Delete playlist"
|
||||
onClick={() => {
|
||||
if (confirm(`Delete playlist "${node.name}"?`)) del.mutate()
|
||||
}}
|
||||
title={isFolder ? 'Delete folder' : 'Delete playlist'}
|
||||
onClick={() => actions.onDelete(node)}
|
||||
className="hidden shrink-0 rounded px-1 text-xs text-faint hover:text-pink group-hover:block"
|
||||
>
|
||||
×
|
||||
@@ -235,8 +290,9 @@ function NodeRow({
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{isFolder && open && node.children.length > 0 && (
|
||||
{expanded && (
|
||||
<div>
|
||||
{draftHere && <DraftRow draft={draft} depth={depth + 1} actions={actions} />}
|
||||
{node.children.map((c) => (
|
||||
<NodeRow
|
||||
key={c.id}
|
||||
@@ -244,7 +300,11 @@ function NodeRow({
|
||||
depth={depth + 1}
|
||||
source={source}
|
||||
onSelect={onSelect}
|
||||
onError={onError}
|
||||
renamingId={renamingId}
|
||||
setRenamingId={setRenamingId}
|
||||
draft={draft}
|
||||
exportSets={exportSets}
|
||||
actions={actions}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -283,27 +343,144 @@ export function Sidebar({
|
||||
// There is no per-node flag for "you may create a NEW playlist" — the node
|
||||
// flags describe existing nodes — so this is the library-level gate.
|
||||
const canCreate = useCaps().writable
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [newName, setNewName] = useState('')
|
||||
const foldersSupported = useCaps().playlists.folders
|
||||
const { data: playlists, isLoading } = useQuery({
|
||||
queryKey: ['playlists'],
|
||||
queryFn: api.playlists,
|
||||
})
|
||||
const exportSets = useQuery({ queryKey: ['exports'], queryFn: api.exports }).data ?? []
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: (name: string) => api.createPlaylist(name),
|
||||
onSuccess: (pl) => {
|
||||
const [draft, setDraft] = useState<Draft | null>(null)
|
||||
const [renamingId, setRenamingId] = useState<string | null>(null)
|
||||
const [menu, setMenu] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null)
|
||||
const [confirmReq, setConfirmReq] = useState<ConfirmRequest | null>(null)
|
||||
|
||||
const invalidate = () => {
|
||||
qc.invalidateQueries({ queryKey: ['playlists'] })
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
onSelect({ kind: 'playlist', id: pl.id, name: pl.name })
|
||||
}
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: ({ kind, parentId, name }: Draft & { name: string }) =>
|
||||
kind === 'folder'
|
||||
? api.createFolder(name, parentId ?? undefined)
|
||||
: api.createPlaylist(name, parentId ?? undefined),
|
||||
onSuccess: (node) => {
|
||||
invalidate()
|
||||
if (node.kind === 'playlist') onSelect({ kind: 'playlist', id: node.id, name: node.name })
|
||||
},
|
||||
onError: (e: Error) => onError(e.message),
|
||||
})
|
||||
|
||||
const submitNew = () => {
|
||||
setCreating(false)
|
||||
if (newName.trim()) create.mutate(newName.trim())
|
||||
setNewName('')
|
||||
const rename = useMutation({
|
||||
mutationFn: ({ node, name }: { node: PlaylistNode; name: string }) =>
|
||||
api.renamePlaylist(node.id, name),
|
||||
onSuccess: (_d, { node, name }) => {
|
||||
invalidate()
|
||||
if (source.kind === 'playlist' && source.id === node.id)
|
||||
onSelect({ kind: 'playlist', id: node.id, name })
|
||||
},
|
||||
onError: (e: Error) => onError(e.message),
|
||||
})
|
||||
|
||||
const del = useMutation({
|
||||
mutationFn: (node: PlaylistNode) => api.deletePlaylist(node.id),
|
||||
onSuccess: (_d, node) => {
|
||||
invalidate()
|
||||
// A folder takes its nested playlists with it, so the open view may be
|
||||
// one of those rather than the node itself.
|
||||
if (source.kind === 'playlist' && playlistIdsUnder(node).concat(node.id).includes(source.id))
|
||||
onSelect({ kind: 'all' })
|
||||
},
|
||||
onError: (e: Error) => onError(e.message),
|
||||
})
|
||||
|
||||
// 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: ({ node, setId }: { node: PlaylistNode; 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 startDraft = (kind: Draft['kind'], parentId: string | null) => {
|
||||
setRenamingId(null)
|
||||
setDraft({ kind, parentId })
|
||||
}
|
||||
|
||||
// Creating is the library-level gate (there is no per-node "may create"
|
||||
// flag); WHERE is the node's own `can_contain_children`; and a folder also
|
||||
// needs the platform to have folders at all.
|
||||
const createItems = (parentId: string | null): MenuItem[] =>
|
||||
canCreate
|
||||
? [
|
||||
{ label: 'New Playlist', icon: '♫', onClick: () => startDraft('playlist', parentId) },
|
||||
...(foldersSupported
|
||||
? [{ label: 'New Folder', icon: '▸', onClick: () => startDraft('folder', parentId) }]
|
||||
: []),
|
||||
]
|
||||
: []
|
||||
|
||||
const confirmDelete = (node: PlaylistNode) =>
|
||||
setConfirmReq({ ...deleteRequest(node), onConfirm: async () => void (await del.mutateAsync(node)) })
|
||||
|
||||
const nodeItems = (node: PlaylistNode): MenuItem[] => {
|
||||
const groups: MenuItem[][] = [
|
||||
node.can_contain_children ? createItems(node.id) : [],
|
||||
exportSets.length > 0
|
||||
? [
|
||||
{
|
||||
label: 'Add to export',
|
||||
submenu: exportSets.map((set) => ({
|
||||
label: set.name,
|
||||
icon: '◈',
|
||||
onClick: () => addToExport.mutate({ node, setId: set.id }),
|
||||
})),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
[
|
||||
...(node.can_rename
|
||||
? [{ label: 'Rename', onClick: () => { setDraft(null); setRenamingId(node.id) } }]
|
||||
: []),
|
||||
...(node.can_delete
|
||||
? [
|
||||
{
|
||||
label: node.kind === 'folder' ? 'Delete Folder…' : 'Delete Playlist…',
|
||||
danger: true,
|
||||
onClick: () => confirmDelete(node),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
]
|
||||
return groups
|
||||
.filter((g) => g.length > 0)
|
||||
.flatMap((g, i) => (i === 0 ? g : [{ separator: true } as MenuItem, ...g]))
|
||||
}
|
||||
|
||||
const openMenu = (e: React.MouseEvent, items: MenuItem[]) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (items.length > 0) setMenu({ x: e.clientX, y: e.clientY, items })
|
||||
}
|
||||
|
||||
const actions: RowActions = {
|
||||
onContextMenu: (e, node) => openMenu(e, nodeItems(node)),
|
||||
onRename: (node, name) => rename.mutate({ node, name }),
|
||||
onDelete: confirmDelete,
|
||||
onAddToExport: (node, setId) => addToExport.mutate({ node, setId }),
|
||||
onCommitDraft: (name) => {
|
||||
if (draft) create.mutate({ ...draft, name })
|
||||
setDraft(null)
|
||||
},
|
||||
onCancelDraft: () => setDraft(null),
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -346,42 +523,19 @@ export function Sidebar({
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 flex items-center justify-between px-4">
|
||||
<div className="mt-3 px-4">
|
||||
<span className="text-[10px] font-semibold uppercase tracking-wider text-faint">
|
||||
Playlists
|
||||
</span>
|
||||
{canCreate && (
|
||||
<button
|
||||
title="New playlist"
|
||||
onClick={() => {
|
||||
setCreating(true)
|
||||
setNewName('')
|
||||
}}
|
||||
className="rounded px-1 text-sm text-faint hover:text-text"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-1 flex-1 overflow-y-auto px-2 pb-4">
|
||||
{creating && (
|
||||
<input
|
||||
autoFocus
|
||||
value={newName}
|
||||
placeholder="Playlist name…"
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') submitNew()
|
||||
else if (e.key === 'Escape') {
|
||||
setCreating(false)
|
||||
setNewName('')
|
||||
}
|
||||
}}
|
||||
onBlur={submitNew}
|
||||
className="mb-1 w-full rounded-md border border-accent bg-ink-950 px-2 py-1.5 text-sm text-text outline-none"
|
||||
/>
|
||||
)}
|
||||
{/* Right-click here (below the rows) creates at the top level; rows
|
||||
stop the event so they get their own menu. */}
|
||||
<div
|
||||
className="mt-1 flex-1 overflow-y-auto px-2 pb-4"
|
||||
onContextMenu={(e) => openMenu(e, createItems(null))}
|
||||
>
|
||||
{draft?.parentId === null && <DraftRow draft={draft} depth={0} actions={actions} />}
|
||||
{isLoading && <div className="px-2 py-2 text-sm text-faint">Loading…</div>}
|
||||
{playlists?.map((n) => (
|
||||
<NodeRow
|
||||
@@ -390,11 +544,18 @@ export function Sidebar({
|
||||
depth={0}
|
||||
source={source}
|
||||
onSelect={onSelect}
|
||||
onError={onError}
|
||||
renamingId={renamingId}
|
||||
setRenamingId={setRenamingId}
|
||||
draft={draft}
|
||||
exportSets={exportSets}
|
||||
actions={actions}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{menu && <ContextMenu {...menu} onClose={() => setMenu(null)} />}
|
||||
{confirmReq && <ConfirmDialog {...confirmReq} onClose={() => setConfirmReq(null)} />}
|
||||
|
||||
<ExportsSection source={source} onSelect={onSelect} onDone={onDone} onError={onError} />
|
||||
|
||||
<DevicesSection
|
||||
|
||||
Reference in new issue
Block a user