'use client' import { flexRender, getCoreRowModel, useReactTable, type ColumnDef, type RowData, type SortingState, type VisibilityState, } from '@tanstack/react-table' import { Settings2 } from 'lucide-react' import { SortButton, ariaSort } from '@/app/components/ui/sortable-head' import { Button } from '@/app/components/ui/button' import { Skeleton } from '@/app/components/ui/skeleton' import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuLabel, DropdownMenuTrigger, } from '@/app/components/ui/dropdown-menu' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from '@/app/components/ui/table' import { cn } from '@/app/lib/utils' import { TablePager } from '@/app/components/ui/table-pager' import { useT } from '@/app/lib/i18n/MessagesProvider' declare module '@tanstack/react-table' { // eslint-disable-next-line @typescript-eslint/no-unused-vars interface ColumnMeta { /** Right-aligns the column and renders it with tabular numerals (§2, §7). */ numeric?: boolean } } // The first column stays visible while a wide table scrolls sideways. Its cells need an opaque // background that follows the row's hover/focus/selected state, or scrolled cells show through. // The inset right divider stands in for the left scroll cue, which the opaque column covers. const PINNED_HEAD = 'sticky left-0 z-[1] bg-table-head shadow-[inset_-1px_0_0_var(--border)]' // Clicks on these inside a row act on the control, not the row. const ROW_CONTROLS = 'a, button, input, select, textarea, label, [role="checkbox"]' const PINNED_CELL = 'sticky left-0 z-[1] bg-card shadow-[inset_-1px_0_0_var(--border)] group-hover:bg-muted group-focus-visible:bg-muted group-aria-selected:bg-accent' /** * Data table for server-paginated, server-sorted result sets — which is what * every `src/services/*` list function returns. Pagination and sorting state are * owned by the caller (usually synced to the URL), so a filtered view is * shareable and survives reload, per DASHBOARD-STANDARD.md §7. */ export interface DataTableProps { columns: ColumnDef[] data: TData[] /** Total rows across all pages, from the service's `Page.total`. */ total: number page: number pageSize: number onPageChange: (page: number) => void sorting?: SortingState onSortingChange?: (sorting: SortingState) => void columnVisibility?: VisibilityState onColumnVisibilityChange?: (visibility: VisibilityState) => void isLoading?: boolean /** Rendered in place of rows when `data` is empty and not loading. */ empty?: React.ReactNode /** Accessible name for the table. */ label: string rowKey: (row: TData) => string /** Makes rows clickable (and Enter/Space-activatable) — e.g. to open a detail drawer. */ onRowClick?: (row: TData) => void /** rowKey of the row to highlight as selected (only meaningful with onRowClick). */ selectedKey?: string /** Receives the table's root element, so useFitPageSize can measure where the table starts. */ tableRef?: (el: HTMLElement | null) => void } export function DataTable({ columns, data, total, page, pageSize, onPageChange, sorting = [], onSortingChange, columnVisibility, onColumnVisibilityChange, isLoading = false, empty, label, rowKey, onRowClick, selectedKey, tableRef, }: DataTableProps) { const t = useT() const pageCount = Math.max(1, Math.ceil(total / pageSize)) const table = useReactTable({ data, columns, state: { sorting, columnVisibility: columnVisibility ?? {} }, // The service already sorted and paginated; never re-do it client-side or // the table would only sort the rows on the current page. manualSorting: true, // First click is always ascending; tanstack would otherwise start numeric columns descending. sortDescFirst: false, manualPagination: true, pageCount, onSortingChange: updater => { onSortingChange?.(typeof updater === 'function' ? updater(sorting) : updater) }, onColumnVisibilityChange: updater => { if (!onColumnVisibilityChange) return onColumnVisibilityChange( typeof updater === 'function' ? updater(columnVisibility ?? {}) : updater, ) }, getCoreRowModel: getCoreRowModel(), }) const visibleColumnCount = table.getVisibleLeafColumns().length const hideableColumns = table.getAllLeafColumns().filter(c => c.getCanHide()) return (
{onColumnVisibilityChange && hideableColumns.length > 0 && (
{t("UiVisibleColumns")} {hideableColumns.map(column => ( column.toggleVisibility(!!value)} > {typeof column.columnDef.header === 'string' ? column.columnDef.header : column.id} ))}
)}
{table.getHeaderGroups().map(headerGroup => ( {headerGroup.headers.map((header, index) => { const sortDirection = header.column.getIsSorted() const canSort = header.column.getCanSort() && Boolean(onSortingChange) const numeric = header.column.columnDef.meta?.numeric return ( {canSort ? ( {flexRender(header.column.columnDef.header, header.getContext())} ) : ( flexRender(header.column.columnDef.header, header.getContext()) )} ) })} ))} {isLoading ? ( Array.from({ length: Math.min(pageSize, 8) }).map((_, rowIndex) => ( {Array.from({ length: visibleColumnCount }).map((__, cellIndex) => ( ))} )) ) : ( table.getRowModel().rows.map((row, i, rows) => { const key = rowKey(row.original) // Callers' keys can repeat (wallet ledger refNo); duplicate React keys leave stale rows on refetch. // ponytail: O(n²) over one page (≤100 rows); switch to a Map counter if pages grow large. const seen = rows.slice(0, i).filter(r => rowKey(r.original) === key).length const interactive = Boolean(onRowClick) return ( ) => { // DOM containment keeps out clicks bubbling (via React) from portalled dialogs/menus. const target = e.target as Element if (!e.currentTarget.contains(target)) return const control = target.closest(ROW_CONTROLS) if (control && e.currentTarget.contains(control)) return onRowClick!(row.original) }, onKeyDown: (e: React.KeyboardEvent) => { // Only the focused row itself: Enter/Space on a control in the row belongs to that control. if (e.target !== e.currentTarget) return if (e.key === 'Enter' || e.key === ' ') { e.preventDefault() onRowClick!(row.original) } }, } : {})} > {row.getVisibleCells().map((cell, index) => ( {flexRender(cell.column.columnDef.cell, cell.getContext())} ))} ) }) )}
{!isLoading && data.length === 0 && (
{empty ?? {t("UiNoResults")}}
)}
) }