From db426e351abd9602a2f7ec3a0e6bafc536174f04 Mon Sep 17 00:00:00 2001 From: Ben Date: Sat, 4 Jul 2026 22:57:21 +0200 Subject: [PATCH] Added reorderable library columns --- backend/konduktor/main.py | 12 + backend/konduktor/prefs.py | 9 + frontend/src/App.tsx | 75 ++++- frontend/src/api.ts | 3 + frontend/src/components/ColumnsMenu.tsx | 67 ++++ frontend/src/components/Toolbar.tsx | 36 ++- frontend/src/components/TrackTable.tsx | 397 ++++++++++++------------ frontend/src/lib/trackColumns.tsx | 149 +++++++++ 8 files changed, 536 insertions(+), 212 deletions(-) create mode 100644 frontend/src/components/ColumnsMenu.tsx create mode 100644 frontend/src/lib/trackColumns.tsx diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index da4d53f..bb54b09 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -142,6 +142,18 @@ def collection_options() -> CollectionOptions: return CollectionOptions(auto=auto, recent=recent) +@app.get("/api/prefs") +def get_prefs() -> dict: + """The full persisted user-preferences blob (UI layout, last collection…).""" + return prefs.load_prefs() + + +@app.patch("/api/prefs") +def patch_prefs(patch: dict) -> dict: + """Shallow-merge the given keys into the stored prefs; returns the result.""" + return prefs.update_prefs(patch) + + @app.get("/api/fs/list", response_model=FsListing) def fs_list(path: str | None = None) -> FsListing: """List directories and .nml files for the in-app file browser.""" diff --git a/backend/konduktor/prefs.py b/backend/konduktor/prefs.py index 4c60dcc..7b3ff22 100644 --- a/backend/konduktor/prefs.py +++ b/backend/konduktor/prefs.py @@ -28,6 +28,15 @@ def save_prefs(prefs: dict) -> None: pass # non-fatal — prefs are a convenience, not a requirement +def update_prefs(patch: dict) -> dict: + """Shallow-merge `patch` into the stored prefs and persist. Returns the + full updated prefs dict.""" + prefs = load_prefs() + prefs.update(patch) + save_prefs(prefs) + return prefs + + def get_last_collection() -> str | None: val = load_prefs().get("last_collection") return val if isinstance(val, str) else None diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 4c65f46..67f6997 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,7 +1,11 @@ -import { useCallback, useMemo, useState } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' -import type { SortingState } from '@tanstack/react-table' +import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table' import { api, type Track } from './api' +import { + DEFAULT_COLUMN_ORDER, + DEFAULT_COLUMN_VISIBILITY, +} from './lib/trackColumns' import { Sidebar, type Source } from './components/Sidebar' import { Toolbar, emptyFilters, type Filters } from './components/Toolbar' import { TrackTable } from './components/TrackTable' @@ -52,6 +56,60 @@ export default function App() { setPlayRequest((n) => n + 1) }, []) + // ---- configurable library columns (persisted to userprefs.json) ---- + const [columnVisibility, setColumnVisibility] = useState(DEFAULT_COLUMN_VISIBILITY) + const [columnOrder, setColumnOrder] = useState(DEFAULT_COLUMN_ORDER) + const [columnSizing, setColumnSizing] = useState({}) + const prefsQuery = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) + const hydratedRef = useRef(false) + const saveTimer = useRef(null) + + const resetColumns = useCallback(() => { + setColumnVisibility(DEFAULT_COLUMN_VISIBILITY) + setColumnOrder(DEFAULT_COLUMN_ORDER) + setColumnSizing({}) + }, []) + + // Hydrate the saved layout once, tolerating partial / stale (new columns + // added since) data by merging against the current defaults. + useEffect(() => { + if (hydratedRef.current || !prefsQuery.data) return + hydratedRef.current = true + const cols = (prefsQuery.data as { columns?: Record }).columns + if (!cols) return + if (cols.visibility) { + setColumnVisibility({ ...DEFAULT_COLUMN_VISIBILITY, ...(cols.visibility as VisibilityState) }) + } + if (Array.isArray(cols.order) && cols.order.length) { + const saved = cols.order as string[] + const known = new Set(DEFAULT_COLUMN_ORDER) + setColumnOrder([ + ...saved.filter((id) => known.has(id)), + ...DEFAULT_COLUMN_ORDER.filter((id) => !saved.includes(id)), + ]) + } + if (cols.sizing && typeof cols.sizing === 'object') { + setColumnSizing(cols.sizing as ColumnSizingState) + } + }, [prefsQuery.data]) + + // Persist layout changes (debounced), but not before hydration so we never + // clobber saved prefs with the initial defaults. + useEffect(() => { + if (!hydratedRef.current) return + if (saveTimer.current) window.clearTimeout(saveTimer.current) + saveTimer.current = window.setTimeout(() => { + api + .patchPrefs({ + columns: { visibility: columnVisibility, order: columnOrder, sizing: columnSizing }, + }) + .catch(() => {}) + }, 500) + return () => { + if (saveTimer.current) window.clearTimeout(saveTimer.current) + } + }, [columnVisibility, columnOrder, columnSizing]) + const notify = useCallback((kind: ToastMsg['kind'], text: string) => { setToast({ id: Date.now(), kind, text }) }, []) @@ -157,7 +215,13 @@ export default function App() {
{isAll ? ( - + ) : (
♫ @@ -191,6 +255,11 @@ export default function App() { onRowContextMenu={(track, x, y) => setMenu({ track, x, y })} onPlay={playTrack} activeTrackId={prepTrack?.id ?? null} + columnVisibility={columnVisibility} + columnOrder={columnOrder} + columnSizing={columnSizing} + onColumnOrderChange={setColumnOrder} + onColumnSizingChange={setColumnSizing} /> ) ) : ( diff --git a/frontend/src/api.ts b/frontend/src/api.ts index b9e0431..c47953c 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -226,6 +226,9 @@ export const api = { `/api/playlists/${uuid}/add`, { track_ids: trackIds }, ), + getPrefs: () => getJSON>('/api/prefs'), + patchPrefs: (patch: Record) => + send>('PATCH', '/api/prefs', patch), save: () => send('POST', '/api/save'), editTrack: (trackId: string, fields: Record) => send<{ status: string }>('PATCH', '/api/tracks', { track_id: trackId, fields }), diff --git a/frontend/src/components/ColumnsMenu.tsx b/frontend/src/components/ColumnsMenu.tsx new file mode 100644 index 0000000..18b20fd --- /dev/null +++ b/frontend/src/components/ColumnsMenu.tsx @@ -0,0 +1,67 @@ +import { useEffect, useRef, useState } from 'react' +import type { VisibilityState } from '@tanstack/react-table' +import { COLUMN_MENU } from '../lib/trackColumns' + +interface Props { + visibility: VisibilityState + onChange: (v: VisibilityState) => void + onReset: () => void +} + +/** Dropdown of checkboxes to show/hide library columns, plus a layout reset. */ +export function ColumnsMenu({ visibility, onChange, onReset }: Props) { + const [open, setOpen] = useState(false) + const ref = useRef(null) + + useEffect(() => { + if (!open) return + const onDoc = (e: MouseEvent) => { + if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false) + } + document.addEventListener('mousedown', onDoc) + return () => document.removeEventListener('mousedown', onDoc) + }, [open]) + + const isVisible = (id: string) => visibility[id] !== false // default-visible unless explicitly false + + return ( +
+ + {open && ( +
+
+ {COLUMN_MENU.map((c) => ( + + ))} +
+ +
+ )} +
+ ) +} diff --git a/frontend/src/components/Toolbar.tsx b/frontend/src/components/Toolbar.tsx index 5d0068f..3e5009e 100644 --- a/frontend/src/components/Toolbar.tsx +++ b/frontend/src/components/Toolbar.tsx @@ -1,5 +1,7 @@ import { useQuery } from '@tanstack/react-query' +import type { VisibilityState } from '@tanstack/react-table' import { api } from '../api' +import { ColumnsMenu } from './ColumnsMenu' export interface Filters { search: string @@ -24,12 +26,21 @@ export const emptyFilters: Filters = { interface Props { filters: Filters onChange: (f: Filters) => void + columnVisibility: VisibilityState + onColumnVisibilityChange: (v: VisibilityState) => void + onResetColumns: () => void } const selectCls = 'rounded-md border border-line bg-ink-850 px-2.5 py-1.5 text-sm text-text outline-none focus:border-accent hover:border-ink-600 transition-colors' -export function Toolbar({ filters, onChange }: Props) { +export function Toolbar({ + filters, + onChange, + columnVisibility, + onColumnVisibilityChange, + onResetColumns, +}: Props) { const { data: facets } = useQuery({ queryKey: ['facets'], queryFn: api.facets }) const set = (patch: Partial) => onChange({ ...filters, ...patch }) const active = @@ -120,14 +131,21 @@ export function Toolbar({ filters, onChange }: Props) { - {active && ( - - )} +
+ {active && ( + + )} + +
) } diff --git a/frontend/src/components/TrackTable.tsx b/frontend/src/components/TrackTable.tsx index d0de73c..cddf8f5 100644 --- a/frontend/src/components/TrackTable.tsx +++ b/frontend/src/components/TrackTable.tsx @@ -1,100 +1,33 @@ -import { useMemo, useRef } from 'react' +import { useRef } from 'react' import { - createColumnHelper, flexRender, getCoreRowModel, getSortedRowModel, useReactTable, + type ColumnSizingState, + type Header, type SortingState, + type VisibilityState, } from '@tanstack/react-table' import { useVirtualizer } from '@tanstack/react-virtual' +import { + DndContext, + PointerSensor, + closestCenter, + useSensor, + useSensors, + type DragEndEvent, +} from '@dnd-kit/core' +import { restrictToHorizontalAxis } from '@dnd-kit/modifiers' +import { + SortableContext, + arrayMove, + horizontalListSortingStrategy, + useSortable, +} from '@dnd-kit/sortable' +import { CSS } from '@dnd-kit/utilities' import type { Track } from '../api' -import { formatBpm, formatDuration, keyColor } from '../lib/format' -import { RatingStars } from './RatingStars' - -const col = createColumnHelper() - -const columns = [ - col.accessor('title', { - header: 'Title', - size: 320, - cell: (c) => ( -
-
- {c.getValue() || Untitled} -
-
{c.row.original.artist}
-
- ), - }), - col.accessor('album', { - header: 'Album', - size: 200, - cell: (c) => {c.getValue() || '—'}, - }), - col.accessor('genre', { - header: 'Genre', - size: 150, - cell: (c) => { - const g = c.getValue()?.trim() - return g ? ( - {g} - ) : ( - — - ) - }, - }), - col.accessor('bpm', { - header: 'BPM', - size: 74, - cell: (c) => {formatBpm(c.getValue())}, - }), - col.accessor('key', { - header: 'Key', - size: 64, - cell: (c) => { - const k = c.getValue() - if (!k) return — - return ( - - {k} - - ) - }, - }), - col.accessor('rating', { - header: 'Rating', - size: 92, - cell: (c) => , - }), - col.accessor('length', { - header: 'Time', - size: 64, - cell: (c) => {formatDuration(c.getValue())}, - }), - col.accessor('cue_count', { - header: 'Cues', - size: 72, - cell: (c) => { - const n = c.getValue() - const grid = c.row.original.has_grid - return ( - - 0 ? 'text-text' : 'text-faint'}>{n} - {grid && ⊞} - - ) - }, - }), - col.accessor('playcount', { - header: 'Plays', - size: 68, - cell: (c) => {c.getValue() || 0}, - }), -] +import { TRACK_COLUMNS } from '../lib/trackColumns' interface Selection { selected: Set @@ -107,16 +40,69 @@ interface Props { tracks: Track[] sorting: SortingState onSortingChange: (s: SortingState) => void + 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 activeTrackId?: string | null } +/** One draggable + resizable header cell. */ +function SortableHeader({ header }: { header: Header }) { + const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ + id: header.column.id, + }) + const sorted = header.column.getIsSorted() + return ( +
+ + {header.column.getCanResize() && ( +
e.stopPropagation()} + onClick={(e) => e.stopPropagation()} + className="absolute right-0 top-0 h-full w-1.5 cursor-col-resize touch-none select-none hover:bg-accent/40" + title="Drag to resize" + /> + )} +
+ ) +} + export function TrackTable({ tracks, sorting, onSortingChange, + columnVisibility, + columnOrder, + columnSizing, + onColumnOrderChange, + onColumnSizingChange, selection, onRowContextMenu, onPlay, @@ -124,12 +110,16 @@ export function TrackTable({ }: Props) { const table = useReactTable({ data: tracks, - columns, - state: { sorting }, + columns: TRACK_COLUMNS, + state: { sorting, columnVisibility, columnOrder, columnSizing }, onSortingChange: (updater) => onSortingChange(typeof updater === 'function' ? updater(sorting) : updater), + onColumnSizingChange: (updater) => + onColumnSizingChange(typeof updater === 'function' ? updater(columnSizing) : updater), getCoreRowModel: getCoreRowModel(), getSortedRowModel: getSortedRowModel(), + enableColumnResizing: true, + columnResizeMode: 'onChange', }) const rows = table.getRowModel().rows @@ -141,123 +131,130 @@ export function TrackTable({ estimateSize: () => 44, overscan: 12, }) - - const totalWidth = useMemo( - () => table.getTotalSize(), - // eslint-disable-next-line react-hooks/exhaustive-deps - [], - ) 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 totalWidth = table.getTotalSize() + leadWidth + + const onDragEnd = (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)) + } + return (
-
- {/* Header */} -
- {selection ? ( - - - - ) : ( - - )} - {onPlay && } - {table.getHeaderGroups()[0].headers.map((header) => { - const sorted = header.column.getIsSorted() - 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) => ( +
- - - - - - )} - {row.getVisibleCells().map((cell) => ( -
- {flexRender(cell.column.columnDef.cell, cell.getContext())} -
- ))} -
- ) - })} + {flexRender(cell.column.columnDef.cell, cell.getContext())} +
+ ))} +
+ ) + })} +
-
+
) } diff --git a/frontend/src/lib/trackColumns.tsx b/frontend/src/lib/trackColumns.tsx new file mode 100644 index 0000000..1b2552d --- /dev/null +++ b/frontend/src/lib/trackColumns.tsx @@ -0,0 +1,149 @@ +// Central definition of the library table's columns: the TanStack column defs, +// their default widths/visibility/order, and the (id,label) list the "Columns" +// menu renders. Both TrackTable and the Toolbar menu read from here so they stay +// in sync. Column layout (visibility, order, sizing) is persisted to userprefs. +import { createColumnHelper, type ColumnDef, type VisibilityState } from '@tanstack/react-table' +import type { Track } from '../api' +import { formatBpm, formatDuration, keyColor } from './format' +import { RatingStars } from '../components/RatingStars' + +const col = createColumnHelper() + +function dash(v: string | null | undefined) { + const s = v?.toString().trim() + return s ? {s} : — +} + +// Traktor dates arrive as "YYYY/M/D" strings; show them compactly (or raw). +function formatDate(v: string | null): string { + if (!v) return '—' + const m = v.match(/(\d{4})\/(\d{1,2})\/(\d{1,2})/) + if (!m) return v + return `${m[1]}-${m[2].padStart(2, '0')}-${m[3].padStart(2, '0')}` +} + +export const TRACK_COLUMNS: ColumnDef[] = [ + col.accessor('title', { + id: 'title', + header: 'Title', + size: 300, + cell: (c) => ( +
+
+ {c.getValue() || Untitled} +
+
{c.row.original.artist}
+
+ ), + }), + col.accessor('album', { id: 'album', header: 'Album', size: 180, cell: (c) => dash(c.getValue()) }), + col.accessor('genre', { id: 'genre', header: 'Genre', size: 140, cell: (c) => dash(c.getValue()) }), + col.accessor('label', { id: 'label', header: 'Label', size: 140, cell: (c) => dash(c.getValue()) }), + col.accessor('remixer', { id: 'remixer', header: 'Remixer', size: 140, cell: (c) => dash(c.getValue()) }), + col.accessor('producer', { id: 'producer', header: 'Producer', size: 140, cell: (c) => dash(c.getValue()) }), + col.accessor('mix', { id: 'mix', header: 'Mix', size: 120, cell: (c) => dash(c.getValue()) }), + col.accessor('comment', { id: 'comment', header: 'Comment', size: 200, cell: (c) => dash(c.getValue()) }), + col.accessor('bpm', { + id: 'bpm', + header: 'BPM', + size: 74, + cell: (c) => {formatBpm(c.getValue())}, + }), + col.accessor('key', { + id: 'key', + header: 'Key', + size: 64, + cell: (c) => { + const k = c.getValue() + if (!k) return — + return ( + + {k} + + ) + }, + }), + col.accessor('rating', { + id: 'rating', + header: 'Rating', + size: 92, + cell: (c) => , + }), + col.accessor('length', { + id: 'length', + header: 'Time', + size: 64, + cell: (c) => {formatDuration(c.getValue())}, + }), + col.accessor('bitrate', { + id: 'bitrate', + header: 'Bitrate', + size: 84, + cell: (c) => { + const b = c.getValue() + return b ? ( + {Math.round(b / 1000)} + ) : ( + — + ) + }, + }), + col.accessor('cue_count', { + id: 'cue_count', + header: 'Cues', + size: 72, + cell: (c) => { + const n = c.getValue() + const grid = c.row.original.has_grid + return ( + + 0 ? 'text-text' : 'text-faint'}>{n} + {grid && ⊞} + + ) + }, + }), + col.accessor('playcount', { + id: 'playcount', + header: 'Plays', + size: 68, + cell: (c) => {c.getValue() || 0}, + }), + col.accessor('import_date', { + id: 'import_date', + header: 'Imported', + size: 104, + cell: (c) => {formatDate(c.getValue())}, + }), + col.accessor('last_played', { + id: 'last_played', + header: 'Last played', + size: 108, + cell: (c) => {formatDate(c.getValue())}, + }), + col.accessor('release_date', { + id: 'release_date', + header: 'Released', + size: 104, + cell: (c) => {formatDate(c.getValue())}, + }), +] + +/** (id, label) pairs for the Columns menu, in the canonical definition order. */ +export const COLUMN_MENU: { id: string; label: string }[] = TRACK_COLUMNS.map((c) => ({ + id: c.id as string, + label: typeof c.header === 'string' ? c.header : (c.id as string), +})) + +export const DEFAULT_COLUMN_ORDER: string[] = TRACK_COLUMNS.map((c) => c.id as string) + +// Columns shown out of the box; the rest are opt-in via the menu. +const DEFAULT_VISIBLE = new Set([ + 'title', 'album', 'genre', 'bpm', 'key', 'rating', 'length', 'cue_count', 'playcount', +]) +export const DEFAULT_COLUMN_VISIBILITY: VisibilityState = Object.fromEntries( + DEFAULT_COLUMN_ORDER.map((id) => [id, DEFAULT_VISIBLE.has(id)]), +)