mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented basic playlist editing
This commit is contained in:
1 parent
fceaab6d78
commit
3ace90179b
20 files changed
+1523
-105
No files matched your search
+87
-27
@@ -1,11 +1,14 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useCallback, useMemo, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import type { SortingState } from '@tanstack/react-table'
|
||||
import { api, type Track } from './api'
|
||||
import { Sidebar, type Source } from './components/Sidebar'
|
||||
import { Toolbar, emptyFilters, type Filters } from './components/Toolbar'
|
||||
import { TrackTable } from './components/TrackTable'
|
||||
import { PlaylistEditor } from './components/PlaylistEditor'
|
||||
import { SelectionBar } from './components/SelectionBar'
|
||||
import { StatusBar } from './components/StatusBar'
|
||||
import { Toast, type ToastMsg } from './components/Toast'
|
||||
|
||||
function applyFilters(tracks: Track[], f: Filters): Track[] {
|
||||
const q = f.search.trim().toLowerCase()
|
||||
@@ -31,57 +34,114 @@ export default function App() {
|
||||
const [source, setSource] = useState<Source>({ kind: 'all' })
|
||||
const [filters, setFilters] = useState<Filters>(emptyFilters)
|
||||
const [sorting, setSorting] = useState<SortingState>([])
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set())
|
||||
const [toast, setToast] = useState<ToastMsg | null>(null)
|
||||
|
||||
const notify = useCallback((kind: ToastMsg['kind'], text: string) => {
|
||||
setToast({ id: Date.now(), kind, text })
|
||||
}, [])
|
||||
const onError = useCallback((msg: string) => notify('error', msg), [notify])
|
||||
|
||||
const allTracks = useQuery({
|
||||
queryKey: ['tracks', 'all'],
|
||||
queryFn: () => api.tracks({ limit: 20000, sort: 'artist' }),
|
||||
enabled: source.kind === 'all',
|
||||
})
|
||||
|
||||
const playlistTracks = useQuery({
|
||||
queryKey: ['playlist', source.kind === 'playlist' ? source.id : null],
|
||||
queryFn: () => api.playlistTracks((source as { id: string }).id),
|
||||
enabled: source.kind === 'playlist',
|
||||
})
|
||||
|
||||
const tracks: Track[] =
|
||||
source.kind === 'all' ? (allTracks.data?.items ?? []) : (playlistTracks.data ?? [])
|
||||
const loading = source.kind === 'all' ? allTracks.isLoading : playlistTracks.isLoading
|
||||
const isAll = source.kind === 'all'
|
||||
const tracks: Track[] = isAll ? (allTracks.data?.items ?? []) : (playlistTracks.data ?? [])
|
||||
const loading = isAll ? allTracks.isLoading : playlistTracks.isLoading
|
||||
const filtered = useMemo(() => (isAll ? applyFilters(tracks, filters) : tracks), [
|
||||
isAll,
|
||||
tracks,
|
||||
filters,
|
||||
])
|
||||
|
||||
const filtered = useMemo(() => applyFilters(tracks, filters), [tracks, filters])
|
||||
const selectSource = (s: Source) => {
|
||||
setSource(s)
|
||||
setSorting([])
|
||||
setSelected(new Set())
|
||||
}
|
||||
|
||||
const sourceName = source.kind === 'all' ? 'All Tracks' : source.name
|
||||
const toggle = (id: string) =>
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev)
|
||||
next.has(id) ? next.delete(id) : next.add(id)
|
||||
return next
|
||||
})
|
||||
const toggleAll = () =>
|
||||
setSelected((prev) =>
|
||||
prev.size === filtered.length ? new Set() : new Set(filtered.map((t) => t.id)),
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex h-screen w-screen overflow-hidden bg-ink-950">
|
||||
<Sidebar
|
||||
source={source}
|
||||
onSelect={(s) => {
|
||||
setSource(s)
|
||||
// Playlists carry a deliberate order; reset sort to preserve it.
|
||||
setSorting([])
|
||||
}}
|
||||
/>
|
||||
<main className="flex min-w-0 flex-1 flex-col">
|
||||
<Toolbar filters={filters} onChange={setFilters} />
|
||||
<Toast toast={toast} onClose={() => setToast(null)} />
|
||||
<Sidebar source={source} onSelect={selectSource} onError={onError} />
|
||||
|
||||
<main className="relative flex min-w-0 flex-1 flex-col">
|
||||
{isAll ? (
|
||||
<Toolbar filters={filters} onChange={setFilters} />
|
||||
) : (
|
||||
<div className="flex items-center gap-3 border-b border-line bg-ink-900 px-4 py-3">
|
||||
<span className="text-[11px] text-accent">♫</span>
|
||||
<span className="font-semibold text-text">{source.name}</span>
|
||||
<span className="text-xs text-faint">
|
||||
{tracks.length} tracks · drag ⠿ to reorder · × to remove
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="min-h-0 flex-1">
|
||||
{loading ? (
|
||||
<div className="flex h-full items-center justify-center text-muted">
|
||||
Loading library…
|
||||
</div>
|
||||
) : filtered.length === 0 ? (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-1 text-muted">
|
||||
<div className="text-lg">No tracks match</div>
|
||||
<div className="text-sm text-faint">Try clearing some filters.</div>
|
||||
</div>
|
||||
<div className="flex h-full items-center justify-center text-muted">Loading…</div>
|
||||
) : isAll ? (
|
||||
filtered.length === 0 ? (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-1 text-muted">
|
||||
<div className="text-lg">No tracks match</div>
|
||||
<div className="text-sm text-faint">Try clearing some filters.</div>
|
||||
</div>
|
||||
) : (
|
||||
<TrackTable
|
||||
tracks={filtered}
|
||||
sorting={sorting}
|
||||
onSortingChange={setSorting}
|
||||
selection={{
|
||||
selected,
|
||||
onToggle: toggle,
|
||||
onToggleAll: toggleAll,
|
||||
allSelected: selected.size > 0 && selected.size === filtered.length,
|
||||
}}
|
||||
/>
|
||||
)
|
||||
) : (
|
||||
<TrackTable tracks={filtered} sorting={sorting} onSortingChange={setSorting} />
|
||||
<PlaylistEditor
|
||||
uuid={(source as { id: string }).id}
|
||||
tracks={tracks}
|
||||
onError={onError}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isAll && (
|
||||
<SelectionBar
|
||||
count={selected.size}
|
||||
trackIds={[...selected]}
|
||||
onClear={() => setSelected(new Set())}
|
||||
onDone={(msg) => notify('success', msg)}
|
||||
onError={onError}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<StatusBar
|
||||
showing={filtered.length}
|
||||
total={tracks.length}
|
||||
sourceName={sourceName}
|
||||
sourceName={isAll ? 'All Tracks' : source.name}
|
||||
loading={loading}
|
||||
/>
|
||||
</main>
|
||||
|
||||
@@ -96,12 +96,42 @@ export interface TrackQuery {
|
||||
offset?: number
|
||||
}
|
||||
|
||||
export interface EditState {
|
||||
dirty: boolean
|
||||
nml_path: string
|
||||
}
|
||||
|
||||
export interface SaveResult {
|
||||
saved: boolean
|
||||
backup: string | null
|
||||
playlists: number
|
||||
}
|
||||
|
||||
async function getJSON<T>(url: string): Promise<T> {
|
||||
const res = await fetch(url)
|
||||
if (!res.ok) throw new Error(`${res.status} ${res.statusText} — ${url}`)
|
||||
return res.json() as Promise<T>
|
||||
}
|
||||
|
||||
async function send<T>(method: string, url: string, body?: unknown): Promise<T> {
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
headers: body ? { 'Content-Type': 'application/json' } : undefined,
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
})
|
||||
if (!res.ok) {
|
||||
let detail = `${res.status} ${res.statusText}`
|
||||
try {
|
||||
const j = await res.json()
|
||||
if (j.detail) detail = j.detail
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
throw new Error(detail)
|
||||
}
|
||||
return res.json() as Promise<T>
|
||||
}
|
||||
|
||||
function qs(params: Record<string, unknown>): string {
|
||||
const p = new URLSearchParams()
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
@@ -119,4 +149,24 @@ export const api = {
|
||||
getJSON<TrackPage>(`/api/tracks${qs(query as Record<string, unknown>)}`),
|
||||
playlistTracks: (id: string) =>
|
||||
getJSON<Track[]>(`/api/playlists/${id}/tracks`),
|
||||
|
||||
// ---- writes ----
|
||||
state: () => getJSON<EditState>('/api/state'),
|
||||
createPlaylist: (name: string, parentId?: string) =>
|
||||
send<PlaylistNode>('POST', '/api/playlists', { name, parent_id: parentId ?? null }),
|
||||
renamePlaylist: (uuid: string, name: string) =>
|
||||
send<{ status: string }>('PATCH', `/api/playlists/${uuid}`, { name }),
|
||||
deletePlaylist: (uuid: string) =>
|
||||
send<{ status: string }>('DELETE', `/api/playlists/${uuid}`),
|
||||
setEntries: (uuid: string, trackIds: string[]) =>
|
||||
send<{ status: string; count: number }>('PUT', `/api/playlists/${uuid}/entries`, {
|
||||
track_ids: trackIds,
|
||||
}),
|
||||
addEntries: (uuid: string, trackIds: string[]) =>
|
||||
send<{ status: string; added: number; count: number }>(
|
||||
'POST',
|
||||
`/api/playlists/${uuid}/add`,
|
||||
{ track_ids: trackIds },
|
||||
),
|
||||
save: () => send<SaveResult>('POST', '/api/save'),
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type DragEndEvent,
|
||||
} from '@dnd-kit/core'
|
||||
import {
|
||||
SortableContext,
|
||||
useSortable,
|
||||
verticalListSortingStrategy,
|
||||
arrayMove,
|
||||
} from '@dnd-kit/sortable'
|
||||
import { CSS } from '@dnd-kit/utilities'
|
||||
import { restrictToVerticalAxis, restrictToParentElement } from '@dnd-kit/modifiers'
|
||||
import { api, type Track } from '../api'
|
||||
import { formatBpm, formatDuration, keyColor } from '../lib/format'
|
||||
import { RatingStars } from './RatingStars'
|
||||
|
||||
interface Props {
|
||||
uuid: string
|
||||
tracks: Track[]
|
||||
onError: (msg: string) => void
|
||||
}
|
||||
|
||||
function Row({
|
||||
track,
|
||||
index,
|
||||
onRemove,
|
||||
}: {
|
||||
track: Track
|
||||
index: number
|
||||
onRemove: (id: string) => void
|
||||
}) {
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } =
|
||||
useSortable({ id: track.id })
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
style={{ transform: CSS.Transform.toString(transform), transition }}
|
||||
className={`flex items-center border-b border-ink-850 text-sm ${
|
||||
isDragging ? 'z-10 bg-ink-800 shadow-lg' : 'hover:bg-ink-850'
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
title="Drag to reorder"
|
||||
className="w-8 shrink-0 cursor-grab px-2 text-center text-faint hover:text-text active:cursor-grabbing"
|
||||
>
|
||||
⠿
|
||||
</button>
|
||||
<span className="w-8 shrink-0 text-right text-xs tabular-nums text-faint">
|
||||
{index + 1}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1 px-3 py-2">
|
||||
<div className="truncate font-medium text-text">
|
||||
{track.title || <span className="text-faint">Untitled</span>}
|
||||
</div>
|
||||
<div className="truncate text-xs text-muted">{track.artist}</div>
|
||||
</div>
|
||||
<div className="w-16 shrink-0 px-2 text-right tabular-nums">{formatBpm(track.bpm)}</div>
|
||||
<div className="w-14 shrink-0 px-2 text-center">
|
||||
{track.key ? (
|
||||
<span className="text-xs font-semibold" style={{ color: keyColor(track.key) }}>
|
||||
{track.key}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-faint">—</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="w-24 shrink-0 px-2">
|
||||
<RatingStars value={track.rating} />
|
||||
</div>
|
||||
<div className="w-14 shrink-0 px-2 text-right tabular-nums text-muted">
|
||||
{formatDuration(track.length)}
|
||||
</div>
|
||||
<button
|
||||
title="Remove from playlist"
|
||||
onClick={() => onRemove(track.id)}
|
||||
className="w-10 shrink-0 px-2 text-center text-faint hover:text-pink"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function PlaylistEditor({ uuid, tracks, onError }: Props) {
|
||||
const qc = useQueryClient()
|
||||
const [items, setItems] = useState<Track[]>(tracks)
|
||||
|
||||
// Re-sync when the server data changes (initial load, or tracks added elsewhere).
|
||||
useEffect(() => setItems(tracks), [tracks])
|
||||
|
||||
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 4 } }))
|
||||
|
||||
const persist = useMutation({
|
||||
mutationFn: (ids: string[]) => api.setEntries(uuid, ids),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
qc.invalidateQueries({ queryKey: ['playlists'] }) // refresh counts
|
||||
},
|
||||
onError: (e: Error) => onError(e.message),
|
||||
})
|
||||
|
||||
const commit = (next: Track[]) => {
|
||||
setItems(next)
|
||||
// Keep the cached playlist query in sync so navigating away/back is stable.
|
||||
qc.setQueryData(['playlist', uuid], next)
|
||||
persist.mutate(next.map((t) => t.id))
|
||||
}
|
||||
|
||||
const onDragEnd = (e: DragEndEvent) => {
|
||||
const { active, over } = e
|
||||
if (!over || active.id === over.id) return
|
||||
const from = items.findIndex((t) => t.id === active.id)
|
||||
const to = items.findIndex((t) => t.id === over.id)
|
||||
if (from < 0 || to < 0) return
|
||||
commit(arrayMove(items, from, to))
|
||||
}
|
||||
|
||||
const remove = (id: string) => commit(items.filter((t) => t.id !== id))
|
||||
|
||||
if (items.length === 0) {
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-2 text-muted">
|
||||
<div className="text-lg">This playlist is empty</div>
|
||||
<div className="text-sm text-faint">
|
||||
Go to <span className="text-text">All Tracks</span>, select tracks, and add them here.
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full overflow-auto">
|
||||
<div className="sticky top-0 z-10 flex border-b border-line bg-ink-850 text-[11px] font-semibold uppercase tracking-wider text-muted">
|
||||
<span className="w-8 shrink-0" />
|
||||
<span className="w-8 shrink-0 text-right">#</span>
|
||||
<span className="flex-1 px-3 py-2.5">Title</span>
|
||||
<span className="w-16 shrink-0 px-2 text-right">BPM</span>
|
||||
<span className="w-14 shrink-0 px-2 text-center">Key</span>
|
||||
<span className="w-24 shrink-0 px-2">Rating</span>
|
||||
<span className="w-14 shrink-0 px-2 text-right">Time</span>
|
||||
<span className="w-10 shrink-0" />
|
||||
</div>
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={onDragEnd}
|
||||
modifiers={[restrictToVerticalAxis, restrictToParentElement]}
|
||||
>
|
||||
<SortableContext items={items.map((t) => t.id)} strategy={verticalListSortingStrategy}>
|
||||
{items.map((t, i) => (
|
||||
<Row key={t.id} track={t} index={i} onRemove={remove} />
|
||||
))}
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api } from '../api'
|
||||
|
||||
interface Props {
|
||||
onError: (msg: string) => void
|
||||
}
|
||||
|
||||
// Bottom-of-sidebar save control. Shows unsaved-changes state and writes to the
|
||||
// NML (backup-first). On-disk saving is gated server-side by KONDUKTOR_ALLOW_WRITE.
|
||||
export function SaveBar({ onError }: Props) {
|
||||
const qc = useQueryClient()
|
||||
const [justSaved, setJustSaved] = useState<string | null>(null)
|
||||
const { data: state } = useQuery({ queryKey: ['state'], queryFn: api.state })
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: api.save,
|
||||
onSuccess: (res) => {
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
if (res.saved && res.backup) {
|
||||
const name = res.backup.split('/').pop()
|
||||
setJustSaved(`Saved · backup ${name}`)
|
||||
setTimeout(() => setJustSaved(null), 6000)
|
||||
}
|
||||
},
|
||||
onError: (e: Error) => onError(e.message),
|
||||
})
|
||||
|
||||
const dirty = state?.dirty ?? false
|
||||
|
||||
return (
|
||||
<div className="border-t border-line bg-ink-900 px-3 py-3">
|
||||
{dirty && (
|
||||
<div className="mb-2 rounded-md bg-gold/10 px-2 py-1.5 text-[11px] leading-snug text-gold">
|
||||
⚠ Close Traktor before saving — it overwrites the collection on exit.
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
disabled={!dirty || save.isPending}
|
||||
onClick={() => save.mutate()}
|
||||
className={`flex w-full items-center justify-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-colors ${
|
||||
dirty
|
||||
? 'bg-accent text-ink-950 hover:brightness-110'
|
||||
: 'cursor-not-allowed bg-ink-800 text-faint'
|
||||
}`}
|
||||
>
|
||||
{save.isPending ? (
|
||||
'Saving…'
|
||||
) : dirty ? (
|
||||
<>
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-ink-950/60" />
|
||||
Save to Traktor
|
||||
</>
|
||||
) : (
|
||||
'No unsaved changes'
|
||||
)}
|
||||
</button>
|
||||
{justSaved && (
|
||||
<div className="mt-2 text-center text-[11px] text-mint">{justSaved}</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, type PlaylistNode } from '../api'
|
||||
|
||||
interface Props {
|
||||
count: number
|
||||
trackIds: string[]
|
||||
onClear: () => void
|
||||
onDone: (msg: string) => void
|
||||
onError: (msg: string) => void
|
||||
}
|
||||
|
||||
function flattenPlaylists(nodes: PlaylistNode[]): PlaylistNode[] {
|
||||
return nodes.flatMap((n) => [
|
||||
...(n.type === 'PLAYLIST' ? [n] : []),
|
||||
...flattenPlaylists(n.children),
|
||||
])
|
||||
}
|
||||
|
||||
// Floating action bar shown when tracks are selected in the explorer.
|
||||
export function SelectionBar({ count, trackIds, onClear, onDone, onError }: Props) {
|
||||
const qc = useQueryClient()
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
const { data: playlists } = useQuery({ queryKey: ['playlists'], queryFn: api.playlists })
|
||||
const flat = playlists ? flattenPlaylists(playlists) : []
|
||||
|
||||
const add = useMutation({
|
||||
mutationFn: ({ uuid, ids }: { uuid: string; ids: string[] }) => api.addEntries(uuid, ids),
|
||||
onSuccess: (res, vars) => {
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
qc.invalidateQueries({ queryKey: ['playlists'] })
|
||||
qc.invalidateQueries({ queryKey: ['playlist', vars.uuid] })
|
||||
const pl = flat.find((p) => p.id === vars.uuid)
|
||||
onDone(`Added ${res.added} track${res.added === 1 ? '' : 's'} to ${pl?.name ?? 'playlist'}`)
|
||||
setMenuOpen(false)
|
||||
onClear()
|
||||
},
|
||||
onError: (e: Error) => onError(e.message),
|
||||
})
|
||||
|
||||
if (count === 0) return null
|
||||
|
||||
return (
|
||||
<div className="pointer-events-none absolute inset-x-0 bottom-4 z-20 flex justify-center">
|
||||
<div className="pointer-events-auto flex items-center gap-3 rounded-full border border-line bg-ink-800 py-2 pl-4 pr-2 shadow-xl">
|
||||
<span className="text-sm text-text">
|
||||
<span className="font-semibold tabular-nums">{count}</span> selected
|
||||
</span>
|
||||
<div className="relative">
|
||||
<button
|
||||
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 ▾
|
||||
</button>
|
||||
{menuOpen && (
|
||||
<div className="absolute bottom-full right-0 mb-2 max-h-72 w-56 overflow-y-auto rounded-lg border border-line bg-ink-850 p-1 shadow-2xl">
|
||||
{flat.length === 0 && (
|
||||
<div className="px-3 py-2 text-sm text-faint">No playlists yet</div>
|
||||
)}
|
||||
{flat.map((p) => (
|
||||
<button
|
||||
key={p.id}
|
||||
onClick={() => add.mutate({ uuid: p.id, ids: trackIds })}
|
||||
className="flex w-full items-center justify-between gap-2 rounded-md px-3 py-1.5 text-left text-sm text-muted hover:bg-ink-800 hover:text-text"
|
||||
>
|
||||
<span className="truncate">{p.name}</span>
|
||||
<span className="shrink-0 text-[10px] tabular-nums text-faint">{p.count}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={onClear}
|
||||
className="rounded-full px-2 py-1.5 text-sm text-muted hover:bg-ink-700 hover:text-text"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, type PlaylistNode } from '../api'
|
||||
import { SaveBar } from './SaveBar'
|
||||
|
||||
export type Source = { kind: 'all' } | { kind: 'playlist'; id: string; name: string }
|
||||
|
||||
interface Props {
|
||||
source: Source
|
||||
onSelect: (s: Source) => void
|
||||
onError: (msg: string) => void
|
||||
}
|
||||
|
||||
const icons: Record<string, string> = {
|
||||
@@ -20,45 +22,123 @@ function NodeRow({
|
||||
depth,
|
||||
source,
|
||||
onSelect,
|
||||
onError,
|
||||
}: {
|
||||
node: PlaylistNode
|
||||
depth: number
|
||||
source: Source
|
||||
onSelect: (s: Source) => void
|
||||
onError: (msg: string) => void
|
||||
}) {
|
||||
const qc = useQueryClient()
|
||||
const [open, setOpen] = useState(true)
|
||||
const [renaming, setRenaming] = useState(false)
|
||||
const [draft, setDraft] = useState(node.name)
|
||||
const isFolder = node.type === 'FOLDER'
|
||||
const selected = source.kind === 'playlist' && source.id === node.id
|
||||
const selectable = node.type === 'PLAYLIST'
|
||||
|
||||
const invalidate = () => {
|
||||
qc.invalidateQueries({ queryKey: ['playlists'] })
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
}
|
||||
|
||||
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>
|
||||
<button
|
||||
onClick={() => {
|
||||
if (isFolder) setOpen((o) => !o)
|
||||
else if (selectable) onSelect({ kind: 'playlist', id: node.id, name: node.name })
|
||||
}}
|
||||
className={`group flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors ${
|
||||
selected
|
||||
? 'bg-accent-soft text-text'
|
||||
: 'text-muted hover:bg-ink-800 hover:text-text'
|
||||
} ${!selectable && !isFolder ? 'cursor-default opacity-70' : ''}`}
|
||||
style={{ paddingLeft: `${8 + depth * 14}px` }}
|
||||
<div
|
||||
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'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`w-3 shrink-0 text-center text-[11px] ${
|
||||
isFolder ? 'text-faint' : node.type === 'SMARTLIST' ? 'text-pink' : 'text-accent'
|
||||
} ${isFolder && open ? 'rotate-90' : ''} transition-transform`}
|
||||
<button
|
||||
onClick={() => {
|
||||
if (isFolder) setOpen((o) => !o)
|
||||
else if (selectable) onSelect({ kind: 'playlist', id: node.id, name: node.name })
|
||||
}}
|
||||
className={`flex min-w-0 flex-1 items-center gap-2 py-1.5 pl-2 text-left ${
|
||||
!selectable && !isFolder ? 'cursor-default opacity-70' : ''
|
||||
}`}
|
||||
style={{ paddingLeft: `${8 + depth * 14}px` }}
|
||||
>
|
||||
{icons[node.type]}
|
||||
</span>
|
||||
<span className="flex-1 truncate">{node.name}</span>
|
||||
{node.type === 'PLAYLIST' && (
|
||||
<span className="shrink-0 rounded bg-ink-800 px-1.5 py-0.5 text-[10px] tabular-nums text-faint group-hover:bg-ink-700">
|
||||
{node.count}
|
||||
<span
|
||||
className={`w-3 shrink-0 text-center text-[11px] ${
|
||||
isFolder ? 'text-faint' : node.type === 'SMARTLIST' ? 'text-pink' : 'text-accent'
|
||||
} ${isFolder && open ? 'rotate-90' : ''} transition-transform`}
|
||||
>
|
||||
{icons[node.type]}
|
||||
</span>
|
||||
{renaming ? (
|
||||
<input
|
||||
autoFocus
|
||||
value={draft}
|
||||
onChange={(e) => setDraft(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())
|
||||
} else if (e.key === 'Escape') {
|
||||
setRenaming(false)
|
||||
setDraft(node.name)
|
||||
}
|
||||
}}
|
||||
onBlur={() => {
|
||||
setRenaming(false)
|
||||
setDraft(node.name)
|
||||
}}
|
||||
className="min-w-0 flex-1 rounded border border-accent bg-ink-950 px-1 py-0 text-sm text-text outline-none"
|
||||
/>
|
||||
) : (
|
||||
<span className="flex-1 truncate">{node.name}</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{node.type === 'PLAYLIST' && !renaming && (
|
||||
<>
|
||||
<button
|
||||
title="Rename"
|
||||
onClick={() => {
|
||||
setDraft(node.name)
|
||||
setRenaming(true)
|
||||
}}
|
||||
className="hidden shrink-0 rounded px-1 text-xs text-faint hover:text-text group-hover:block"
|
||||
>
|
||||
✎
|
||||
</button>
|
||||
<button
|
||||
title="Delete playlist"
|
||||
onClick={() => {
|
||||
if (confirm(`Delete playlist "${node.name}"?`)) del.mutate()
|
||||
}}
|
||||
className="hidden shrink-0 rounded px-1 text-xs text-faint hover:text-pink group-hover:block"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
<span className="shrink-0 rounded bg-ink-800 px-1.5 py-0.5 text-[10px] tabular-nums text-faint group-hover:hidden">
|
||||
{node.count}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
{isFolder && open && node.children.length > 0 && (
|
||||
<div>
|
||||
{node.children.map((c) => (
|
||||
@@ -68,6 +148,7 @@ function NodeRow({
|
||||
depth={depth + 1}
|
||||
source={source}
|
||||
onSelect={onSelect}
|
||||
onError={onError}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -76,12 +157,31 @@ function NodeRow({
|
||||
)
|
||||
}
|
||||
|
||||
export function Sidebar({ source, onSelect }: Props) {
|
||||
export function Sidebar({ source, onSelect, onError }: Props) {
|
||||
const qc = useQueryClient()
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [newName, setNewName] = useState('')
|
||||
const { data: playlists, isLoading } = useQuery({
|
||||
queryKey: ['playlists'],
|
||||
queryFn: api.playlists,
|
||||
})
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: (name: string) => api.createPlaylist(name),
|
||||
onSuccess: (pl) => {
|
||||
qc.invalidateQueries({ queryKey: ['playlists'] })
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
onSelect({ kind: 'playlist', id: pl.id, name: pl.name })
|
||||
},
|
||||
onError: (e: Error) => onError(e.message),
|
||||
})
|
||||
|
||||
const submitNew = () => {
|
||||
setCreating(false)
|
||||
if (newName.trim()) create.mutate(newName.trim())
|
||||
setNewName('')
|
||||
}
|
||||
|
||||
return (
|
||||
<aside className="flex h-full w-64 shrink-0 flex-col border-r border-line bg-ink-900">
|
||||
<div className="flex items-center gap-2 px-4 py-4">
|
||||
@@ -105,10 +205,40 @@ export function Sidebar({ source, onSelect }: Props) {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 px-4 text-[10px] font-semibold uppercase tracking-wider text-faint">
|
||||
Playlists
|
||||
<div className="mt-3 flex items-center justify-between px-4">
|
||||
<span className="text-[10px] font-semibold uppercase tracking-wider text-faint">
|
||||
Playlists
|
||||
</span>
|
||||
<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"
|
||||
/>
|
||||
)}
|
||||
{isLoading && <div className="px-2 py-2 text-sm text-faint">Loading…</div>}
|
||||
{playlists?.map((n) => (
|
||||
<NodeRow
|
||||
@@ -117,9 +247,12 @@ export function Sidebar({ source, onSelect }: Props) {
|
||||
depth={0}
|
||||
source={source}
|
||||
onSelect={onSelect}
|
||||
onError={onError}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<SaveBar onError={onError} />
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
@@ -23,7 +23,7 @@ export function StatusBar({ showing, total, sourceName, loading }: Props) {
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<span className="ml-auto text-faint">konduktor · phase 2</span>
|
||||
<span className="ml-auto text-faint">konduktor · phase 3</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useEffect } from 'react'
|
||||
|
||||
export interface ToastMsg {
|
||||
id: number
|
||||
kind: 'success' | 'error'
|
||||
text: string
|
||||
}
|
||||
|
||||
export function Toast({ toast, onClose }: { toast: ToastMsg | null; onClose: () => void }) {
|
||||
useEffect(() => {
|
||||
if (!toast) return
|
||||
const t = setTimeout(onClose, toast.kind === 'error' ? 6000 : 4000)
|
||||
return () => clearTimeout(t)
|
||||
}, [toast, onClose])
|
||||
|
||||
if (!toast) return null
|
||||
return (
|
||||
<div className="pointer-events-none fixed inset-x-0 top-4 z-50 flex justify-center">
|
||||
<div
|
||||
className={`pointer-events-auto max-w-lg rounded-lg border px-4 py-2.5 text-sm shadow-xl ${
|
||||
toast.kind === 'error'
|
||||
? 'border-pink/40 bg-ink-800 text-pink'
|
||||
: 'border-mint/40 bg-ink-800 text-mint'
|
||||
}`}
|
||||
>
|
||||
{toast.text}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -96,15 +96,21 @@ const columns = [
|
||||
}),
|
||||
]
|
||||
|
||||
interface Selection {
|
||||
selected: Set<string>
|
||||
onToggle: (id: string) => void
|
||||
onToggleAll: () => void
|
||||
allSelected: boolean
|
||||
}
|
||||
|
||||
interface Props {
|
||||
tracks: Track[]
|
||||
sorting: SortingState
|
||||
onSortingChange: (s: SortingState) => void
|
||||
// Playlists have a meaningful order; disable default sort to preserve it.
|
||||
ordered?: boolean
|
||||
selection?: Selection
|
||||
}
|
||||
|
||||
export function TrackTable({ tracks, sorting, onSortingChange }: Props) {
|
||||
export function TrackTable({ tracks, sorting, onSortingChange, selection }: Props) {
|
||||
const table = useReactTable({
|
||||
data: tracks,
|
||||
columns,
|
||||
@@ -137,7 +143,19 @@ export function TrackTable({ tracks, sorting, onSortingChange }: Props) {
|
||||
<div style={{ width: totalWidth, minWidth: '100%' }}>
|
||||
{/* Header */}
|
||||
<div className="sticky top-0 z-10 flex border-b border-line bg-ink-850">
|
||||
<span className="w-10 shrink-0" />
|
||||
{selection ? (
|
||||
<span className="flex w-10 shrink-0 items-center justify-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selection.allSelected}
|
||||
onChange={selection.onToggleAll}
|
||||
className="accent-accent"
|
||||
title="Select all"
|
||||
/>
|
||||
</span>
|
||||
) : (
|
||||
<span className="w-10 shrink-0" />
|
||||
)}
|
||||
{table.getHeaderGroups()[0].headers.map((header) => {
|
||||
const sorted = header.column.getIsSorted()
|
||||
return (
|
||||
@@ -160,10 +178,13 @@ export function TrackTable({ tracks, sorting, onSortingChange }: Props) {
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
|
||||
{virtualRows.map((vr) => {
|
||||
const row = rows[vr.index]
|
||||
const isSelected = selection?.selected.has(row.original.id) ?? false
|
||||
return (
|
||||
<div
|
||||
key={row.id}
|
||||
className="absolute left-0 flex items-center border-b border-ink-850 text-sm hover:bg-ink-850"
|
||||
className={`absolute left-0 flex items-center border-b border-ink-850 text-sm ${
|
||||
isSelected ? 'bg-accent-soft/50' : 'hover:bg-ink-850'
|
||||
}`}
|
||||
style={{
|
||||
top: 0,
|
||||
transform: `translateY(${vr.start}px)`,
|
||||
@@ -171,9 +192,20 @@ export function TrackTable({ tracks, sorting, onSortingChange }: Props) {
|
||||
width: '100%',
|
||||
}}
|
||||
>
|
||||
<span className="w-10 shrink-0 pr-2 text-right text-xs tabular-nums text-faint">
|
||||
{vr.index + 1}
|
||||
</span>
|
||||
{selection ? (
|
||||
<span className="flex w-10 shrink-0 items-center justify-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isSelected}
|
||||
onChange={() => selection.onToggle(row.original.id)}
|
||||
className="accent-accent"
|
||||
/>
|
||||
</span>
|
||||
) : (
|
||||
<span className="w-10 shrink-0 pr-2 text-right text-xs tabular-nums text-faint">
|
||||
{vr.index + 1}
|
||||
</span>
|
||||
)}
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<div
|
||||
key={cell.id}
|
||||
|
||||
Reference in new issue
Block a user