Unified library list

This commit is contained in:
Ben committed 2026-07-05 23:24:25 +02:00
1 parent c3768f816a
commit a0dfed9a9e
4 files changed
+457 -320

No files matched your search

+367 -116
View File
@@ -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<string>
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 (
<button
onClick={(e) => {
e.stopPropagation()
onPlay(track)
}}
className={`flex h-6 w-6 items-center justify-center rounded-full transition-colors hover:bg-accent hover:text-ink-950 ${
isActive ? 'text-accent opacity-100' : 'text-faint opacity-0 group-hover:opacity-100'
}`}
title="Play in deck"
>
<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
<path d="M8 5.14v13.72a1 1 0 0 0 1.54.84l10.29-6.86a1 1 0 0 0 0-1.68L9.54 4.3A1 1 0 0 0 8 5.14z" />
</svg>
</button>
)
}
/** The configurable data cells for one row — identical in both views. */
function RowCells({ row }: { row: Row<Track> }) {
return (
<>
{row.getVisibleCells().map((cell) => (
<div
key={cell.id}
style={{ width: cell.column.getSize() }}
className="flex shrink-0 items-center overflow-hidden px-3"
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</div>
))}
</>
)
}
/** 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<Track, unknown> }) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: header.column.id,
@@ -95,6 +162,62 @@ function SortableHeader({ header }: { header: Header<Track, unknown> }) {
)
}
/** Shared draggable header row (column reorder + resize). */
function HeaderRow({
headers,
sensors,
onColumnDragEnd,
lead,
trail,
hasPlay,
selection,
}: {
headers: Header<Track, unknown>[]
sensors: ReturnType<typeof useSensors>
onColumnDragEnd: (e: DragEndEvent) => void
lead?: boolean // playlist drag-handle spacer
trail?: boolean // playlist remove spacer
hasPlay: boolean
selection?: Selection
}) {
return (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
modifiers={[restrictToHorizontalAxis]}
onDragEnd={onColumnDragEnd}
>
<div className="sticky top-0 z-10 flex border-b border-line bg-ink-850">
{lead && <span className="w-8 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" />
)}
{hasPlay && <span className="w-9 shrink-0" />}
<SortableContext
items={headers.map((h) => h.column.id)}
strategy={horizontalListSortingStrategy}
>
{headers.map((header) => (
<SortableHeader key={header.id} header={header} />
))}
</SortableContext>
{trail && <span className="w-10 shrink-0" />}
</div>
</DndContext>
)
}
/** 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 (
<div ref={parentRef} className="h-full overflow-auto">
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
modifiers={[restrictToHorizontalAxis]}
onDragEnd={onDragEnd}
>
<div style={{ width: totalWidth, minWidth: '100%' }}>
{/* Header */}
<div className="sticky top-0 z-10 flex border-b border-line bg-ink-850">
{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" />
)}
{onPlay && <span className="w-9 shrink-0" />}
<SortableContext
items={headers.map((h) => h.column.id)}
strategy={horizontalListSortingStrategy}
>
{headers.map((header) => (
<SortableHeader key={header.id} header={header} />
))}
</SortableContext>
</div>
{/* Virtualized rows */}
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
{virtualRows.map((vr) => {
const row = rows[vr.index]
const isSelected = selection?.selected.has(row.original.id) ?? false
const isActive = activeTrackId === row.original.id
return (
<div
key={row.id}
className={`group 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)`,
height: vr.size,
width: '100%',
}}
onContextMenu={(e) => {
if (!onRowContextMenu) return
e.preventDefault()
onRowContextMenu(row.original, e.clientX, e.clientY)
}}
>
{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>
)}
{onPlay && (
<span className="flex w-9 shrink-0 items-center justify-center">
<button
onClick={(e) => {
e.stopPropagation()
onPlay(row.original)
}}
className={`flex h-6 w-6 items-center justify-center rounded-full transition-colors hover:bg-accent hover:text-ink-950 ${
isActive
? 'text-accent opacity-100'
: 'text-faint opacity-0 group-hover:opacity-100'
}`}
title="Play in deck"
>
<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
<path d="M8 5.14v13.72a1 1 0 0 0 1.54.84l10.29-6.86a1 1 0 0 0 0-1.68L9.54 4.3A1 1 0 0 0 8 5.14z" />
</svg>
</button>
</span>
)}
{row.getVisibleCells().map((cell) => (
<div
key={cell.id}
style={{ width: cell.column.getSize() }}
className="flex shrink-0 items-center overflow-hidden px-3"
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</div>
))}
</div>
)
})}
</div>
<div style={{ width: totalWidth, minWidth: '100%' }}>
<HeaderRow
headers={headers}
sensors={sensors}
onColumnDragEnd={onColumnDragEnd}
hasPlay={hasPlay}
selection={selection}
/>
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
{virtualRows.map((vr) => {
const row = rows[vr.index]
const isSelected = selection?.selected.has(row.original.id) ?? false
const isActive = activeTrackId === row.original.id
return (
<div
key={row.id}
className={`group 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)`, height: vr.size, width: '100%' }}
onContextMenu={(e) => {
if (!onRowContextMenu) return
e.preventDefault()
onRowContextMenu(row.original, e.clientX, e.clientY)
}}
>
{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>
)}
{hasPlay && (
<span className="flex w-9 shrink-0 items-center justify-center">
{onPlay && <PlayButton track={row.original} isActive={isActive} onPlay={onPlay} />}
</span>
)}
<RowCells row={row} />
</div>
)
})}
</div>
</DndContext>
</div>
</div>
)
}
/** 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<Track>
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 (
<div
ref={setNodeRef}
style={{ transform: CSS.Transform.toString(transform), transition, height: ROW_HEIGHT }}
className={`group flex items-center border-b border-ink-850 text-sm ${
isDragging ? 'relative z-10 bg-ink-800 shadow-lg' : 'hover:bg-ink-850'
}`}
onContextMenu={(e) => {
if (!onRowContextMenu) return
e.preventDefault()
onRowContextMenu(row.original, e.clientX, e.clientY)
}}
>
{canReorder ? (
<button
{...attributes}
{...listeners}
title="Drag to reorder"
className="flex w-8 shrink-0 cursor-grab items-center justify-center text-faint hover:text-text active:cursor-grabbing"
>
⠿
</button>
) : (
<span
title="Clear the search / filters to reorder"
className="flex w-8 shrink-0 cursor-default items-center justify-center text-faint/25"
>
⠿
</span>
)}
<span className="w-10 shrink-0 pr-2 text-right text-xs tabular-nums text-faint">
{index + 1}
</span>
{hasPlay && (
<span className="flex w-9 shrink-0 items-center justify-center">
{onPlay && <PlayButton track={row.original} isActive={isActive} onPlay={onPlay} />}
</span>
)}
<RowCells row={row} />
<button
title="Remove from playlist"
onClick={() => onRemove(row.original.id)}
className="flex w-10 shrink-0 items-center justify-center text-faint hover:text-pink"
>
×
</button>
</div>
)
}
/** 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<Track[]>(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 (
<div className="h-full overflow-auto">
<div style={{ width: totalWidth, minWidth: '100%' }}>
<HeaderRow
headers={headers}
sensors={sensors}
onColumnDragEnd={onColumnDragEnd}
hasPlay={hasPlay}
lead
trail
/>
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
modifiers={[restrictToVerticalAxis, restrictToParentElement]}
onDragEnd={onRowDragEnd}
>
<SortableContext
items={rows.map((r) => r.original.id)}
strategy={verticalListSortingStrategy}
>
{rows.map((row, i) => (
<PlaylistRow
key={row.original.id}
row={row}
index={i}
hasPlay={hasPlay}
canReorder={canReorder}
activeTrackId={activeTrackId}
onPlay={onPlay}
onRemove={onRemove}
onRowContextMenu={onRowContextMenu}
/>
))}
</SortableContext>
</DndContext>
</div>
</div>
)
}