Added reorderable library columns

This commit is contained in:
Ben committed 2026-07-04 22:57:21 +02:00
1 parent d848efaf50
commit db426e351a
8 files changed
+441 -117

No files matched your search

+12
View File
@@ -142,6 +142,18 @@ def collection_options() -> CollectionOptions:
return CollectionOptions(auto=auto, recent=recent) 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) @app.get("/api/fs/list", response_model=FsListing)
def fs_list(path: str | None = None) -> FsListing: def fs_list(path: str | None = None) -> FsListing:
"""List directories and .nml files for the in-app file browser.""" """List directories and .nml files for the in-app file browser."""
+9
View File
@@ -28,6 +28,15 @@ def save_prefs(prefs: dict) -> None:
pass # non-fatal — prefs are a convenience, not a requirement 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: def get_last_collection() -> str | None:
val = load_prefs().get("last_collection") val = load_prefs().get("last_collection")
return val if isinstance(val, str) else None return val if isinstance(val, str) else None
+72 -3
View File
@@ -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 { 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 { api, type Track } from './api'
import {
DEFAULT_COLUMN_ORDER,
DEFAULT_COLUMN_VISIBILITY,
} from './lib/trackColumns'
import { Sidebar, type Source } from './components/Sidebar' import { Sidebar, type Source } from './components/Sidebar'
import { Toolbar, emptyFilters, type Filters } from './components/Toolbar' import { Toolbar, emptyFilters, type Filters } from './components/Toolbar'
import { TrackTable } from './components/TrackTable' import { TrackTable } from './components/TrackTable'
@@ -52,6 +56,60 @@ export default function App() {
setPlayRequest((n) => n + 1) setPlayRequest((n) => n + 1)
}, []) }, [])
// ---- configurable library columns (persisted to userprefs.json) ----
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>(DEFAULT_COLUMN_VISIBILITY)
const [columnOrder, setColumnOrder] = useState<string[]>(DEFAULT_COLUMN_ORDER)
const [columnSizing, setColumnSizing] = useState<ColumnSizingState>({})
const prefsQuery = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs })
const hydratedRef = useRef(false)
const saveTimer = useRef<number | null>(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<string, unknown> }).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) => { const notify = useCallback((kind: ToastMsg['kind'], text: string) => {
setToast({ id: Date.now(), kind, text }) setToast({ id: Date.now(), kind, text })
}, []) }, [])
@@ -157,7 +215,13 @@ export default function App() {
<main className="relative flex min-w-0 flex-1 flex-col"> <main className="relative flex min-w-0 flex-1 flex-col">
{isAll ? ( {isAll ? (
<Toolbar filters={filters} onChange={setFilters} /> <Toolbar
filters={filters}
onChange={setFilters}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
onResetColumns={resetColumns}
/>
) : ( ) : (
<div className="flex items-center gap-3 border-b border-line bg-ink-900 px-4 py-3"> <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="text-[11px] text-accent">♫</span>
@@ -191,6 +255,11 @@ export default function App() {
onRowContextMenu={(track, x, y) => setMenu({ track, x, y })} onRowContextMenu={(track, x, y) => setMenu({ track, x, y })}
onPlay={playTrack} onPlay={playTrack}
activeTrackId={prepTrack?.id ?? null} activeTrackId={prepTrack?.id ?? null}
columnVisibility={columnVisibility}
columnOrder={columnOrder}
columnSizing={columnSizing}
onColumnOrderChange={setColumnOrder}
onColumnSizingChange={setColumnSizing}
/> />
) )
) : ( ) : (
+3
View File
@@ -226,6 +226,9 @@ export const api = {
`/api/playlists/${uuid}/add`, `/api/playlists/${uuid}/add`,
{ track_ids: trackIds }, { track_ids: trackIds },
), ),
getPrefs: () => getJSON<Record<string, unknown>>('/api/prefs'),
patchPrefs: (patch: Record<string, unknown>) =>
send<Record<string, unknown>>('PATCH', '/api/prefs', patch),
save: () => send<SaveResult>('POST', '/api/save'), save: () => send<SaveResult>('POST', '/api/save'),
editTrack: (trackId: string, fields: Record<string, string | number | null>) => editTrack: (trackId: string, fields: Record<string, string | number | null>) =>
send<{ status: string }>('PATCH', '/api/tracks', { track_id: trackId, fields }), send<{ status: string }>('PATCH', '/api/tracks', { track_id: trackId, fields }),
+67
View File
@@ -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<HTMLDivElement>(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 (
<div ref={ref} className="relative">
<button
onClick={() => setOpen((o) => !o)}
className="flex items-center gap-1.5 rounded-md border border-line bg-ink-850 px-2.5 py-1.5 text-sm text-text transition-colors hover:border-ink-600"
title="Choose columns"
>
<span className="text-faint">▦</span> Columns
</button>
{open && (
<div className="absolute right-0 z-30 mt-1 w-52 rounded-md border border-line bg-ink-850 p-1 shadow-2xl">
<div className="max-h-80 overflow-y-auto p-1">
{COLUMN_MENU.map((c) => (
<label
key={c.id}
className="flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm text-text hover:bg-ink-800"
>
<input
type="checkbox"
checked={isVisible(c.id)}
onChange={(e) => onChange({ ...visibility, [c.id]: e.target.checked })}
className="accent-accent"
/>
{c.label}
</label>
))}
</div>
<button
onClick={() => {
onReset()
setOpen(false)
}}
className="mt-1 w-full rounded px-2 py-1.5 text-left text-xs text-muted hover:bg-ink-800 hover:text-text"
>
Reset to defaults
</button>
</div>
)}
</div>
)
}
+20 -2
View File
@@ -1,5 +1,7 @@
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import type { VisibilityState } from '@tanstack/react-table'
import { api } from '../api' import { api } from '../api'
import { ColumnsMenu } from './ColumnsMenu'
export interface Filters { export interface Filters {
search: string search: string
@@ -24,12 +26,21 @@ export const emptyFilters: Filters = {
interface Props { interface Props {
filters: Filters filters: Filters
onChange: (f: Filters) => void onChange: (f: Filters) => void
columnVisibility: VisibilityState
onColumnVisibilityChange: (v: VisibilityState) => void
onResetColumns: () => void
} }
const selectCls = 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' '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 { data: facets } = useQuery({ queryKey: ['facets'], queryFn: api.facets })
const set = (patch: Partial<Filters>) => onChange({ ...filters, ...patch }) const set = (patch: Partial<Filters>) => onChange({ ...filters, ...patch })
const active = const active =
@@ -120,14 +131,21 @@ export function Toolbar({ filters, onChange }: Props) {
<option value="no">No cues</option> <option value="no">No cues</option>
</select> </select>
<div className="ml-auto flex items-center gap-2">
{active && ( {active && (
<button <button
onClick={() => onChange(emptyFilters)} onClick={() => onChange(emptyFilters)}
className="ml-auto rounded-md px-2.5 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text" className="rounded-md px-2.5 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
> >
Clear filters Clear filters
</button> </button>
)} )}
<ColumnsMenu
visibility={columnVisibility}
onChange={onColumnVisibilityChange}
onReset={onResetColumns}
/>
</div>
</div> </div>
) )
} }
+109 -112
View File
@@ -1,100 +1,33 @@
import { useMemo, useRef } from 'react' import { useRef } from 'react'
import { import {
createColumnHelper,
flexRender, flexRender,
getCoreRowModel, getCoreRowModel,
getSortedRowModel, getSortedRowModel,
useReactTable, useReactTable,
type ColumnSizingState,
type Header,
type SortingState, type SortingState,
type VisibilityState,
} from '@tanstack/react-table' } from '@tanstack/react-table'
import { useVirtualizer } from '@tanstack/react-virtual' 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 type { Track } from '../api'
import { formatBpm, formatDuration, keyColor } from '../lib/format' import { TRACK_COLUMNS } from '../lib/trackColumns'
import { RatingStars } from './RatingStars'
const col = createColumnHelper<Track>()
const columns = [
col.accessor('title', {
header: 'Title',
size: 320,
cell: (c) => (
<div className="min-w-0">
<div className="truncate font-medium text-text">
{c.getValue() || <span className="text-faint">Untitled</span>}
</div>
<div className="truncate text-xs text-muted">{c.row.original.artist}</div>
</div>
),
}),
col.accessor('album', {
header: 'Album',
size: 200,
cell: (c) => <span className="truncate text-muted">{c.getValue() || '—'}</span>,
}),
col.accessor('genre', {
header: 'Genre',
size: 150,
cell: (c) => {
const g = c.getValue()?.trim()
return g ? (
<span className="truncate text-muted">{g}</span>
) : (
<span className="text-faint">—</span>
)
},
}),
col.accessor('bpm', {
header: 'BPM',
size: 74,
cell: (c) => <span className="tabular-nums text-text">{formatBpm(c.getValue())}</span>,
}),
col.accessor('key', {
header: 'Key',
size: 64,
cell: (c) => {
const k = c.getValue()
if (!k) return <span className="text-faint">—</span>
return (
<span
className="rounded px-1.5 py-0.5 text-xs font-semibold"
style={{ color: keyColor(k), background: 'color-mix(in srgb, currentColor 14%, transparent)' }}
>
{k}
</span>
)
},
}),
col.accessor('rating', {
header: 'Rating',
size: 92,
cell: (c) => <RatingStars value={c.getValue()} />,
}),
col.accessor('length', {
header: 'Time',
size: 64,
cell: (c) => <span className="tabular-nums text-muted">{formatDuration(c.getValue())}</span>,
}),
col.accessor('cue_count', {
header: 'Cues',
size: 72,
cell: (c) => {
const n = c.getValue()
const grid = c.row.original.has_grid
return (
<span className="flex items-center gap-1 tabular-nums">
<span className={n > 0 ? 'text-text' : 'text-faint'}>{n}</span>
{grid && <span className="text-[10px] text-mint" title="Beatgrid analyzed">⊞</span>}
</span>
)
},
}),
col.accessor('playcount', {
header: 'Plays',
size: 68,
cell: (c) => <span className="tabular-nums text-muted">{c.getValue() || 0}</span>,
}),
]
interface Selection { interface Selection {
selected: Set<string> selected: Set<string>
@@ -107,16 +40,69 @@ interface Props {
tracks: Track[] tracks: Track[]
sorting: SortingState sorting: SortingState
onSortingChange: (s: SortingState) => void onSortingChange: (s: SortingState) => void
columnVisibility: VisibilityState
columnOrder: string[]
columnSizing: ColumnSizingState
onColumnOrderChange: (o: string[]) => void
onColumnSizingChange: (s: ColumnSizingState) => void
selection?: Selection selection?: Selection
onRowContextMenu?: (track: Track, x: number, y: number) => void onRowContextMenu?: (track: Track, x: number, y: number) => void
onPlay?: (track: Track) => void onPlay?: (track: Track) => void
activeTrackId?: string | null activeTrackId?: string | null
} }
/** One draggable + resizable header cell. */
function SortableHeader({ header }: { header: Header<Track, unknown> }) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: header.column.id,
})
const sorted = header.column.getIsSorted()
return (
<div
ref={setNodeRef}
style={{
width: header.getSize(),
transform: CSS.Translate.toString(transform),
transition,
opacity: isDragging ? 0.6 : 1,
zIndex: isDragging ? 20 : undefined,
}}
className="relative flex shrink-0 items-center"
>
<button
{...attributes}
{...listeners}
onClick={header.column.getToggleSortingHandler()}
className="flex flex-1 cursor-grab items-center gap-1 px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wider text-muted hover:text-text active:cursor-grabbing"
>
{flexRender(header.column.columnDef.header, header.getContext())}
<span className="text-accent">
{sorted === 'asc' ? '↑' : sorted === 'desc' ? '↓' : ''}
</span>
</button>
{header.column.getCanResize() && (
<div
onMouseDown={header.getResizeHandler()}
onTouchStart={header.getResizeHandler()}
onPointerDown={(e) => 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"
/>
)}
</div>
)
}
export function TrackTable({ export function TrackTable({
tracks, tracks,
sorting, sorting,
onSortingChange, onSortingChange,
columnVisibility,
columnOrder,
columnSizing,
onColumnOrderChange,
onColumnSizingChange,
selection, selection,
onRowContextMenu, onRowContextMenu,
onPlay, onPlay,
@@ -124,12 +110,16 @@ export function TrackTable({
}: Props) { }: Props) {
const table = useReactTable({ const table = useReactTable({
data: tracks, data: tracks,
columns, columns: TRACK_COLUMNS,
state: { sorting }, state: { sorting, columnVisibility, columnOrder, columnSizing },
onSortingChange: (updater) => onSortingChange: (updater) =>
onSortingChange(typeof updater === 'function' ? updater(sorting) : updater), onSortingChange(typeof updater === 'function' ? updater(sorting) : updater),
onColumnSizingChange: (updater) =>
onColumnSizingChange(typeof updater === 'function' ? updater(columnSizing) : updater),
getCoreRowModel: getCoreRowModel(), getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(), getSortedRowModel: getSortedRowModel(),
enableColumnResizing: true,
columnResizeMode: 'onChange',
}) })
const rows = table.getRowModel().rows const rows = table.getRowModel().rows
@@ -141,16 +131,30 @@ export function TrackTable({
estimateSize: () => 44, estimateSize: () => 44,
overscan: 12, overscan: 12,
}) })
const totalWidth = useMemo(
() => table.getTotalSize(),
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
)
const virtualRows = virtualizer.getVirtualItems() 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 ( return (
<div ref={parentRef} className="h-full overflow-auto"> <div ref={parentRef} className="h-full overflow-auto">
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
modifiers={[restrictToHorizontalAxis]}
onDragEnd={onDragEnd}
>
<div style={{ width: totalWidth, minWidth: '100%' }}> <div style={{ width: totalWidth, minWidth: '100%' }}>
{/* Header */} {/* Header */}
<div className="sticky top-0 z-10 flex border-b border-line bg-ink-850"> <div className="sticky top-0 z-10 flex border-b border-line bg-ink-850">
@@ -168,22 +172,14 @@ export function TrackTable({
<span className="w-10 shrink-0" /> <span className="w-10 shrink-0" />
)} )}
{onPlay && <span className="w-9 shrink-0" />} {onPlay && <span className="w-9 shrink-0" />}
{table.getHeaderGroups()[0].headers.map((header) => { <SortableContext
const sorted = header.column.getIsSorted() items={headers.map((h) => h.column.id)}
return ( strategy={horizontalListSortingStrategy}
<button
key={header.id}
onClick={header.column.getToggleSortingHandler()}
style={{ width: header.getSize() }}
className="flex items-center gap-1 px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wider text-muted hover:text-text"
> >
{flexRender(header.column.columnDef.header, header.getContext())} {headers.map((header) => (
<span className="text-accent"> <SortableHeader key={header.id} header={header} />
{sorted === 'asc' ? '↑' : sorted === 'desc' ? '↓' : ''} ))}
</span> </SortableContext>
</button>
)
})}
</div> </div>
{/* Virtualized rows */} {/* Virtualized rows */}
@@ -248,7 +244,7 @@ export function TrackTable({
<div <div
key={cell.id} key={cell.id}
style={{ width: cell.column.getSize() }} style={{ width: cell.column.getSize() }}
className="flex items-center overflow-hidden px-3" className="flex shrink-0 items-center overflow-hidden px-3"
> >
{flexRender(cell.column.columnDef.cell, cell.getContext())} {flexRender(cell.column.columnDef.cell, cell.getContext())}
</div> </div>
@@ -258,6 +254,7 @@ export function TrackTable({
})} })}
</div> </div>
</div> </div>
</DndContext>
</div> </div>
) )
} }
+149
View File
@@ -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<Track>()
function dash(v: string | null | undefined) {
const s = v?.toString().trim()
return s ? <span className="truncate text-muted">{s}</span> : <span className="text-faint">—</span>
}
// 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<Track, any>[] = [
col.accessor('title', {
id: 'title',
header: 'Title',
size: 300,
cell: (c) => (
<div className="min-w-0">
<div className="truncate font-medium text-text">
{c.getValue() || <span className="text-faint">Untitled</span>}
</div>
<div className="truncate text-xs text-muted">{c.row.original.artist}</div>
</div>
),
}),
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) => <span className="tabular-nums text-text">{formatBpm(c.getValue())}</span>,
}),
col.accessor('key', {
id: 'key',
header: 'Key',
size: 64,
cell: (c) => {
const k = c.getValue()
if (!k) return <span className="text-faint">—</span>
return (
<span
className="rounded px-1.5 py-0.5 text-xs font-semibold"
style={{ color: keyColor(k), background: 'color-mix(in srgb, currentColor 14%, transparent)' }}
>
{k}
</span>
)
},
}),
col.accessor('rating', {
id: 'rating',
header: 'Rating',
size: 92,
cell: (c) => <RatingStars value={c.getValue()} />,
}),
col.accessor('length', {
id: 'length',
header: 'Time',
size: 64,
cell: (c) => <span className="tabular-nums text-muted">{formatDuration(c.getValue())}</span>,
}),
col.accessor('bitrate', {
id: 'bitrate',
header: 'Bitrate',
size: 84,
cell: (c) => {
const b = c.getValue()
return b ? (
<span className="tabular-nums text-muted">{Math.round(b / 1000)}</span>
) : (
<span className="text-faint">—</span>
)
},
}),
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 (
<span className="flex items-center gap-1 tabular-nums">
<span className={n > 0 ? 'text-text' : 'text-faint'}>{n}</span>
{grid && <span className="text-[10px] text-mint" title="Beatgrid analyzed">⊞</span>}
</span>
)
},
}),
col.accessor('playcount', {
id: 'playcount',
header: 'Plays',
size: 68,
cell: (c) => <span className="tabular-nums text-muted">{c.getValue() || 0}</span>,
}),
col.accessor('import_date', {
id: 'import_date',
header: 'Imported',
size: 104,
cell: (c) => <span className="tabular-nums text-muted">{formatDate(c.getValue())}</span>,
}),
col.accessor('last_played', {
id: 'last_played',
header: 'Last played',
size: 108,
cell: (c) => <span className="tabular-nums text-muted">{formatDate(c.getValue())}</span>,
}),
col.accessor('release_date', {
id: 'release_date',
header: 'Released',
size: 104,
cell: (c) => <span className="tabular-nums text-muted">{formatDate(c.getValue())}</span>,
}),
]
/** (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)]),
)