From a0dfed9a9e3fcbf36e865804c6d0efc84dea094f Mon Sep 17 00:00:00 2001 From: Ben Date: Sun, 5 Jul 2026 23:24:25 +0200 Subject: [PATCH] Unified library list --- CLAUDE.md | 13 +- frontend/src/App.tsx | 101 ++++- frontend/src/components/PlaylistEditor.tsx | 180 -------- frontend/src/components/TrackTable.tsx | 483 ++++++++++++++++----- 4 files changed, 457 insertions(+), 320 deletions(-) delete mode 100644 frontend/src/components/PlaylistEditor.tsx diff --git a/CLAUDE.md b/CLAUDE.md index 452c2a4..8870f6e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,8 +51,17 @@ Two independent apps that talk over HTTP: - `components/` — `CollectionPicker` (startup chooser: Automatic / Open last / Find manually — the last reveals a file browser), `Sidebar` (playlist tree + create/rename/delete), `SaveBar`, `Toolbar` (search/filters + `ColumnsMenu`), - `TrackTable` (TanStack Table + Virtual grid; per-row play button, configurable - columns, inline double-click editing), `PlaylistEditor` (dnd-kit reorder), + `TrackTable` (All Tracks — TanStack Table + **virtualized** grid; per-row play + button, configurable columns, inline double-click editing) and `PlaylistTable` + (playlists — same columns/cells/play/inline-edit via shared `HeaderRow`/ + `RowCells`/`PlayButton`, so the two views look identical, PLUS dnd-kit + drag-to-reorder + a remove button, header sorting disabled so the manual order + stands; `canReorder` is false while a filter/search is active so a partial order + can't overwrite the full entry list). `PlaylistTable` is non-virtualized + (playlists are small) and feeds `useReactTable` a **stable** empty `sorting` + array (`NO_SORTING`): a controlled `state.sorting` that's a fresh `[]` each + render with no `onSortingChange` makes TanStack Table re-sync its internal + state every commit → infinite re-render loop. Keep that reference stable. `SelectionBar` (bulk add-to-playlist), `ContextMenu` + `EditTagsDialog` (right-click → multi-field metadata + album-art edit), `StatusBar`, `RatingStars` (read-only, or click-to-set when given `onChange`), `Toast`. diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 513d595..2fc2322 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -8,8 +8,7 @@ import { } from './lib/trackColumns' 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 { TrackTable, PlaylistTable } from './components/TrackTable' import { SelectionBar } from './components/SelectionBar' import { StatusBar } from './components/StatusBar' import { Toast, type ToastMsg } from './components/Toast' @@ -153,11 +152,46 @@ export default function App() { 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, - ]) + // 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. + const filtered = useMemo(() => applyFilters(tracks, filters), [tracks, filters]) + const filtersActive = + filters.search !== '' || + filters.genre !== '' || + filters.key !== '' || + filters.bpmMin !== '' || + filters.bpmMax !== '' || + filters.ratingMin > 0 || + filters.hasCues !== 'any' + + // Playlist reorder / remove: persist the new entry order via setEntries, and + // optimistically update the cached playlist so the list stays put after a drag + // (the TrackTable re-syncs to this on the next render). + const reorderPlaylist = useCallback( + (ids: string[]) => { + if (source.kind !== 'playlist') return + const id = source.id + qc.setQueryData(['playlist', id], (prev) => { + if (!prev) return prev + const byId = new Map(prev.map((t) => [t.id, t])) + return ids.map((i) => byId.get(i)).filter((t): t is Track => !!t) + }) + api + .setEntries(id, ids) + .then(() => { + qc.invalidateQueries({ queryKey: ['state'] }) + qc.invalidateQueries({ queryKey: ['playlists'] }) // refresh counts + }) + .catch((e) => onError((e as Error).message)) + }, + [source, qc, onError], + ) + const removeFromPlaylist = useCallback( + (trackId: string) => + reorderPlaylist(tracks.filter((t) => t.id !== trackId).map((t) => t.id)), + [reorderPlaylist, tracks], + ) const handleOpened = () => { setForcePicker(false) @@ -232,20 +266,22 @@ export default function App() {
- {isAll ? ( - - ) : ( -
+ {/* Search / filters / column settings — always visible. */} + + {!isAll && ( +
♫ {source.name} - {tracks.length} tracks · drag ⠿ to reorder · × to remove + {filtersActive + ? `${filtered.length} of ${tracks.length} tracks · × to remove · clear the filter to reorder` + : `${tracks.length} tracks · drag ⠿ to reorder · × to remove`}
)} @@ -281,12 +317,33 @@ export default function App() { onColumnSizingChange={setColumnSizing} /> ) + ) : tracks.length === 0 ? ( +
+
This playlist is empty
+
+ Go to All Tracks, select tracks, and add them here. +
+
+ ) : filtered.length === 0 ? ( +
+
No tracks match
+
Try clearing some filters.
+
) : ( - setMenu({ track, x, y })} + onPlay={playTrack} + onEditField={editField} + activeTrackId={prepTrack?.id ?? null} + columnVisibility={columnVisibility} + columnOrder={columnOrder} + columnSizing={columnSizing} + onColumnOrderChange={setColumnOrder} + onColumnSizingChange={setColumnSizing} + onReorder={reorderPlaylist} + onRemove={removeFromPlaylist} + canReorder={!filtersActive} /> )} diff --git a/frontend/src/components/PlaylistEditor.tsx b/frontend/src/components/PlaylistEditor.tsx deleted file mode 100644 index e97606f..0000000 --- a/frontend/src/components/PlaylistEditor.tsx +++ /dev/null @@ -1,180 +0,0 @@ -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 - onRowContextMenu?: (track: Track, x: number, y: number) => void -} - -function Row({ - track, - index, - onRemove, - onContextMenu, -}: { - track: Track - index: number - onRemove: (id: string) => void - onContextMenu?: (track: Track, x: number, y: number) => void -}) { - const { attributes, listeners, setNodeRef, transform, transition, isDragging } = - useSortable({ id: track.id }) - - return ( -
{ - if (!onContextMenu) return - e.preventDefault() - onContextMenu(track, e.clientX, e.clientY) - }} - > - - - {index + 1} - -
-
- {track.title || Untitled} -
-
{track.artist}
-
-
{formatBpm(track.bpm)}
-
- {track.key ? ( - - {track.key} - - ) : ( - — - )} -
-
- -
-
- {formatDuration(track.length)} -
- -
- ) -} - -export function PlaylistEditor({ uuid, tracks, onError, onRowContextMenu }: Props) { - const qc = useQueryClient() - const [items, setItems] = useState(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 ( -
-
This playlist is empty
-
- Go to All Tracks, select tracks, and add them here. -
-
- ) - } - - return ( -
-
- - # - Title - BPM - Key - Rating - Time - -
- - t.id)} strategy={verticalListSortingStrategy}> - {items.map((t, i) => ( - - ))} - - -
- ) -} diff --git a/frontend/src/components/TrackTable.tsx b/frontend/src/components/TrackTable.tsx index 9834ba3..1ba522d 100644 --- a/frontend/src/components/TrackTable.tsx +++ b/frontend/src/components/TrackTable.tsx @@ -1,4 +1,4 @@ -import { useRef } from 'react' +import { useEffect, useRef, useState } from 'react' import { flexRender, getCoreRowModel, @@ -6,6 +6,7 @@ import { useReactTable, type ColumnSizingState, type Header, + type Row, type SortingState, type VisibilityState, } from '@tanstack/react-table' @@ -18,17 +19,24 @@ import { useSensors, type DragEndEvent, } from '@dnd-kit/core' -import { restrictToHorizontalAxis } from '@dnd-kit/modifiers' +import { restrictToHorizontalAxis, restrictToVerticalAxis, restrictToParentElement } from '@dnd-kit/modifiers' import { SortableContext, arrayMove, horizontalListSortingStrategy, + verticalListSortingStrategy, useSortable, } from '@dnd-kit/sortable' import { CSS } from '@dnd-kit/utilities' import type { Track } from '../api' import { TRACK_COLUMNS } from '../lib/trackColumns' +const ROW_HEIGHT = 44 +// Stable reference. A controlled `state.sorting` that's a fresh `[]` each render +// (with no `onSortingChange`) makes TanStack Table re-sync its internal state +// every commit → infinite re-render loop. Playlists never sort, so share one array. +const NO_SORTING: SortingState = [] + interface Selection { selected: Set onToggle: (id: string) => void @@ -36,23 +44,82 @@ interface Selection { allSelected: boolean } -interface Props { - tracks: Track[] - sorting: SortingState - onSortingChange: (s: SortingState) => void +interface CommonProps { columnVisibility: VisibilityState columnOrder: string[] columnSizing: ColumnSizingState onColumnOrderChange: (o: string[]) => void onColumnSizingChange: (s: ColumnSizingState) => void - selection?: Selection onRowContextMenu?: (track: Track, x: number, y: number) => void onPlay?: (track: Track) => void onEditField?: (track: Track, field: keyof Track, value: string | number) => void activeTrackId?: string | null } -/** One draggable + resizable header cell. */ +interface Props extends CommonProps { + tracks: Track[] + sorting: SortingState + onSortingChange: (s: SortingState) => void + selection?: Selection +} + +interface PlaylistProps extends CommonProps { + tracks: Track[] + onReorder: (ids: string[]) => void + onRemove: (id: string) => void + /** False while a filter/search is active: reordering a filtered subset would + * drop the hidden entries, so the drag handle goes inert. */ + canReorder: boolean +} + +/** The per-row play button (shared by the library grid and the playlist list). + * Fades in on row hover; stays lit for the active deck track. */ +function PlayButton({ + track, + isActive, + onPlay, +}: { + track: Track + isActive: boolean + onPlay: (track: Track) => void +}) { + return ( + + ) +} + +/** The configurable data cells for one row — identical in both views. */ +function RowCells({ row }: { row: Row }) { + return ( + <> + {row.getVisibleCells().map((cell) => ( +
+ {flexRender(cell.column.columnDef.cell, cell.getContext())} +
+ ))} + + ) +} + +/** One draggable + resizable header cell. `sortable` is false in playlists, + * where the manual order stands (the header still reorders/resizes columns). */ function SortableHeader({ header }: { header: Header }) { const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: header.column.id, @@ -95,6 +162,62 @@ function SortableHeader({ header }: { header: Header }) { ) } +/** Shared draggable header row (column reorder + resize). */ +function HeaderRow({ + headers, + sensors, + onColumnDragEnd, + lead, + trail, + hasPlay, + selection, +}: { + headers: Header[] + sensors: ReturnType + onColumnDragEnd: (e: DragEndEvent) => void + lead?: boolean // playlist drag-handle spacer + trail?: boolean // playlist remove spacer + hasPlay: boolean + selection?: Selection +}) { + return ( + +
+ {lead && } + {selection ? ( + + + + ) : ( + + )} + {hasPlay && } + h.column.id)} + strategy={horizontalListSortingStrategy} + > + {headers.map((header) => ( + + ))} + + {trail && } +
+
+ ) +} + +/** The virtualized library grid (All Tracks). */ export function TrackTable({ tracks, sorting, @@ -131,17 +254,18 @@ export function TrackTable({ const virtualizer = useVirtualizer({ count: rows.length, getScrollElement: () => parentRef.current, - estimateSize: () => 44, + estimateSize: () => ROW_HEIGHT, overscan: 12, }) const virtualRows = virtualizer.getVirtualItems() const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } })) const headers = table.getHeaderGroups()[0].headers - const leadWidth = 40 + (onPlay ? 36 : 0) + const hasPlay = !!onPlay + const leadWidth = 40 + (hasPlay ? 36 : 0) const totalWidth = table.getTotalSize() + leadWidth - const onDragEnd = (e: DragEndEvent) => { + const onColumnDragEnd = (e: DragEndEvent) => { const { active, over } = e if (!over || active.id === over.id) return const from = columnOrder.indexOf(active.id as string) @@ -152,112 +276,239 @@ export function TrackTable({ return (
- -
- {/* Header */} -
- {selection ? ( - - - - ) : ( - - )} - {onPlay && } - h.column.id)} - strategy={horizontalListSortingStrategy} - > - {headers.map((header) => ( - - ))} - -
- - {/* Virtualized rows */} -
- {virtualRows.map((vr) => { - const row = rows[vr.index] - const isSelected = selection?.selected.has(row.original.id) ?? false - const isActive = activeTrackId === row.original.id - return ( -
{ - if (!onRowContextMenu) return - e.preventDefault() - onRowContextMenu(row.original, e.clientX, e.clientY) - }} - > - {selection ? ( - - selection.onToggle(row.original.id)} - className="accent-accent" - /> - - ) : ( - - {vr.index + 1} - - )} - {onPlay && ( - - - - )} - {row.getVisibleCells().map((cell) => ( -
- {flexRender(cell.column.columnDef.cell, cell.getContext())} -
- ))} -
- ) - })} -
+
+ +
+ {virtualRows.map((vr) => { + const row = rows[vr.index] + const isSelected = selection?.selected.has(row.original.id) ?? false + const isActive = activeTrackId === row.original.id + return ( +
{ + if (!onRowContextMenu) return + e.preventDefault() + onRowContextMenu(row.original, e.clientX, e.clientY) + }} + > + {selection ? ( + + selection.onToggle(row.original.id)} + className="accent-accent" + /> + + ) : ( + + {vr.index + 1} + + )} + {hasPlay && ( + + {onPlay && } + + )} + +
+ ) + })}
- +
+
+ ) +} + +/** One reorderable playlist row — standard (non-virtualized) dnd-kit sortable, + * in normal document flow. This is the proven-stable arrangement; the virtualizer + * is intentionally NOT used here (its flushSync-driven measurement loops when + * wrapped in a sortable context). */ +function PlaylistRow({ + row, + index, + hasPlay, + canReorder, + activeTrackId, + onPlay, + onRemove, + onRowContextMenu, +}: { + row: Row + index: number + hasPlay: boolean + canReorder: boolean + activeTrackId?: string | null + onPlay?: (track: Track) => void + onRemove: (id: string) => void + onRowContextMenu?: (track: Track, x: number, y: number) => void +}) { + const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ + id: row.original.id, + disabled: !canReorder, + }) + const isActive = activeTrackId === row.original.id + return ( +
{ + if (!onRowContextMenu) return + e.preventDefault() + onRowContextMenu(row.original, e.clientX, e.clientY) + }} + > + {canReorder ? ( + + ) : ( + + ⠿ + + )} + + {index + 1} + + {hasPlay && ( + + {onPlay && } + + )} + + +
+ ) +} + +/** The playlist view: the same columns / play button / inline editing as the + * library, plus drag-to-reorder + remove. Non-virtualized (playlists are small), + * which keeps it clear of the react-virtual + dnd-kit re-render loop. */ +export function PlaylistTable({ + tracks, + columnVisibility, + columnOrder, + columnSizing, + onColumnOrderChange, + onColumnSizingChange, + onRowContextMenu, + onPlay, + onEditField, + activeTrackId, + onReorder, + onRemove, + canReorder, +}: PlaylistProps) { + // Local manual order so a drag feels instant; re-syncs when the server data changes. + const [items, setItems] = useState(tracks) + useEffect(() => setItems(tracks), [tracks]) + + const table = useReactTable({ + data: items, + columns: TRACK_COLUMNS, + state: { sorting: NO_SORTING, columnVisibility, columnOrder, columnSizing }, + meta: { onEditField }, + enableSorting: false, // playlist order is manual + onColumnSizingChange: (updater) => + onColumnSizingChange(typeof updater === 'function' ? updater(columnSizing) : updater), + getCoreRowModel: getCoreRowModel(), + getSortedRowModel: getSortedRowModel(), + enableColumnResizing: true, + columnResizeMode: 'onChange', + }) + + const rows = table.getRowModel().rows + const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } })) + const headers = table.getHeaderGroups()[0].headers + const hasPlay = !!onPlay + const leadWidth = 32 + 40 + (hasPlay ? 36 : 0) + const totalWidth = table.getTotalSize() + leadWidth + 40 + + const onColumnDragEnd = (e: DragEndEvent) => { + const { active, over } = e + if (!over || active.id === over.id) return + const from = columnOrder.indexOf(active.id as string) + const to = columnOrder.indexOf(over.id as string) + if (from < 0 || to < 0) return + onColumnOrderChange(arrayMove(columnOrder, from, to)) + } + + const onRowDragEnd = (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 + const next = arrayMove(items, from, to) + setItems(next) + onReorder(next.map((t) => t.id)) + } + + return ( +
+
+ + + r.original.id)} + strategy={verticalListSortingStrategy} + > + {rows.map((row, i) => ( + + ))} + + +
) }