import { useMemo, useState } from 'react'; import { useReactTable, getCoreRowModel, getSortedRowModel, getExpandedRowModel, type ColumnDef, type OnChangeFn, type RowSelectionState, type SortingState, type Table, type Row, type ExpandedState, } from '@tanstack/react-table'; import { type ColumnDefinition, type ColumnState } from '../types'; /** * Options for the {@link useTable} hook. * * @typeParam TData - The row data type */ export interface UseTableOptions { /** Array of row data to display. */ data: TData[]; /** Column definitions for the table. */ columns: ColumnDefinition[]; /** Returns a unique, stable string ID for a given row. */ getRowId: (row: TData) => string; /** Current column state (visibility, order, sort). */ columnState: ColumnState; /** Updater for column state. */ setColumnState: (state: ColumnState) => void; /** Responsive column visibility map from `useResponsiveColumns`. */ responsiveColumnVisibility: Record; /** Enables client-side sorting. */ enableSorting?: boolean; /** Enables expandable rows. */ enableExpansion?: boolean; /** Enables row selection checkboxes. */ enableRowSelection?: boolean; /** Callback fired when row selection changes with the selected row data. */ onRowSelectionChange?: (selectedRows: TData[]) => void; /** Enables row grouping. Reserved for future use. */ enableGrouping?: boolean; /** Arbitrary metadata passed to TanStack Table's `meta` option. */ meta?: Record; /** External expansion state (for controlled expansion). */ expanded?: ExpandedState; /** Callback when expansion state changes. */ onExpandedChange?: OnChangeFn; } /** * Return value of the {@link useTable} hook. * * @typeParam TData - The row data type */ export interface UseTableResult { /** The TanStack Table instance. */ table: Table; /** The current row model (post-sort, post-filter). */ rows: Row[]; } /** Maps `ColumnDefinition` to TanStack `ColumnDef`, translating our API to theirs. */ function mapColumns(columns: ColumnDefinition[]): ColumnDef[] { return columns.map((col) => ({ id: col.id, header: typeof col.header === 'string' ? col.header : () => col.header, ...(col.accessorFn ? { accessorFn: col.accessorFn } : {}), ...(col.cell ? { cell: col.cell } : {}), size: col.size, enableSorting: col.sortable ?? false, ...(col.sortFn ? { sortingFn: col.sortFn } : {}), enableResizing: col.enableResizing, ...(col.filterFn ? { filterFn: col.filterFn } : {}), })); } /** * Merges user column visibility (from column state) with responsive visibility * (from breakpoint matching). A column is visible only if both the user and * the responsive check agree it should be shown. */ function mergeColumnVisibility( columns: ColumnDefinition[], columnState: ColumnState, responsiveVisibility: Record, ): Record { const userVisible = new Set(columnState.visibleColumns); const visibility: Record = {}; for (const col of columns) { const inUserSet = userVisible.has(col.id); const responsiveVal = responsiveVisibility[col.id]; // If responsive says hidden, column is hidden regardless of user state // If responsive has no opinion (undefined), defer to user visibility const isResponsiveVisible = responsiveVal === undefined ? true : responsiveVal; visibility[col.id] = inUserSet && isResponsiveVisible; } return visibility; } /** * Core hook that wraps TanStack's `useReactTable` with TableV2 conventions. * * Handles: * - Mapping `ColumnDefinition` to TanStack `ColumnDef` * - Merging user and responsive column visibility * - Applying column order from `ColumnState` * - Deriving `SortingState` from `ColumnState` * - Conditionally enabling sorted/expanded row models * * @typeParam TData - The row data type * @param options - Configuration for the table instance * @returns The TanStack table instance and the current row model * * @example * ```tsx * const { table, rows } = useTable({ * data, * columns, * getRowId: (row) => row.id, * columnState, * setColumnState, * responsiveColumnVisibility: columnVisibility, * enableSorting: true, * }); * ``` */ export function useTable(options: UseTableOptions): UseTableResult { const { data, columns, getRowId, columnState, responsiveColumnVisibility, enableSorting, enableExpansion, enableRowSelection, meta, expanded, onExpandedChange, } = options; const columnDefs = useMemo(() => mapColumns(columns), [columns]); const columnVisibility = useMemo( () => mergeColumnVisibility( columns as ColumnDefinition[], columnState, responsiveColumnVisibility, ), [columns, columnState, responsiveColumnVisibility], ); const columnOrder = columnState.columnOrder; const [rowSelection, setRowSelection] = useState({}); const handleRowSelectionChange: OnChangeFn = (updaterOrValue) => { const next = typeof updaterOrValue === 'function' ? updaterOrValue(rowSelection) : updaterOrValue; setRowSelection(next); if (options.onRowSelectionChange) { const selectedIds = Object.keys(next).filter((k) => next[k]); const selectedRows = data.filter((row) => selectedIds.includes(getRowId(row))); options.onRowSelectionChange(selectedRows); } }; const sorting: SortingState | undefined = useMemo(() => { if (!enableSorting || !columnState.sortColumn) return undefined; return [{ id: columnState.sortColumn, desc: columnState.sortDirection === 'desc' }]; }, [enableSorting, columnState.sortColumn, columnState.sortDirection]); const table = useReactTable({ data, columns: columnDefs, getRowId, getCoreRowModel: getCoreRowModel(), ...(enableSorting ? { getSortedRowModel: getSortedRowModel() } : {}), ...(enableExpansion ? { getExpandedRowModel: getExpandedRowModel(), getRowCanExpand: () => true, } : {}), enableRowSelection: !!enableRowSelection, ...(enableRowSelection ? { enableMultiRowSelection: true, onRowSelectionChange: handleRowSelectionChange, } : {}), state: { columnVisibility, columnOrder, ...(sorting ? { sorting } : {}), ...(enableRowSelection ? { rowSelection } : {}), ...(expanded !== undefined ? { expanded } : {}), }, ...(onExpandedChange ? { onExpandedChange } : {}), meta, }); const rows = table.getRowModel().rows; return { table, rows }; }