import { flexRender, getCoreRowModel, getSortedRowModel, useReactTable, type ColumnDef, type OnChangeFn, type Row, type SortingState, } from '@tanstack/react-table'; import { TableVirtuoso, type ItemProps, type TableComponents } from 'react-virtuoso'; import { useCallback, useMemo, useState, type CSSProperties, type KeyboardEvent, type ReactNode, } from 'react'; import { cn } from '../utils/cn'; import { SortIcon } from '../utils/sort-icon'; import { monoLabel } from '../utils/mono-label'; import { ColumnResizeHandle, ResizableColgroup, ResizableFillerCell, resizableCellClassName, resizableTableStyle, useColumnResizing, type ColumnResizingProp, } from '../data-table/column-resizing'; const DEFAULT_TABLE_CLASSNAME = 'w-full border-collapse text-sm'; const DEFAULT_SCROLL_CLASSNAME = 'h-full w-full overflow-auto'; const DEFAULT_STYLE: CSSProperties = { height: 400 }; export type VirtualizedDataTableProps = { ariaLabel: string; data: TData[]; columns: ColumnDef[]; /** Stable row id. Defaults to the TanStack row index. */ getRowId?: (item: TData, index: number) => string; getRowTextValue?: (item: TData, index: number) => string; onRowClick?: (item: TData) => void; onStartReached?: (index: number) => void; onEndReached?: (index: number) => void; /** Controlled sorting state. Omit it to use internal sorting. */ sorting?: SortingState; onSortingChange?: OnChangeFn; /** Lets callers delegate sorting to a data source instead of sorting rows locally. */ manualSorting?: boolean; loading?: boolean; emptyMessage?: string; /** Overrides the default centered empty or loading rendering. */ renderEmptyState?: () => ReactNode; /** Applied to the semantic table element. */ className?: string; /** Applied to Virtuoso's scroll container. */ scrollClassName?: string; style?: CSSProperties; /** * Opt in to draggable column borders. Columns start at 150px unless `defaultSize` or a * column's own `size` says otherwise. The table is as wide as its columns or its container, * whichever is larger. A column opts out with `enableResizing: false`. */ columnResizing?: ColumnResizingProp; }; type VirtualizedTableContext = { ariaLabel: string; columnCount: number; emptyMessage: string; getRowTextValue?: (item: TData, index: number) => string; isLoading: boolean; /** Set when columns are resizable: the table is laid out at exactly this width. */ resizableTotalSize: number | null; /** Set when columns are resizable: the width of each visible leaf column. */ resizableColumnSizes: readonly number[] | null; onRowClick?: (item: TData) => void; renderEmptyState?: () => ReactNode; tableClassName: string; }; type TableComponentProps = { children?: ReactNode; context: VirtualizedTableContext; style?: CSSProperties; }; type TableRowComponentProps = ItemProps & { context: VirtualizedTableContext; }; const VirtualizedTableElement = ({ children, context, style }: TableComponentProps) => ( {context.resizableColumnSizes === null ? null : ( )} {children}
); const VirtualizedTableRow = ({ children, context, item, ...props }: TableRowComponentProps) => { const row = item as Row; const isActionable = Boolean(context.onRowClick); const activateRow = () => { context.onRowClick?.(row.original); }; const handleKeyDown = (event: KeyboardEvent) => { // A control inside the row (a button, a field) owns its own keys. if ( !isActionable || event.target !== event.currentTarget || (event.key !== 'Enter' && event.key !== ' ') ) { return; } event.preventDefault(); activateRow(); }; return ( {children} ); }; const VirtualizedEmptyState = ({ context }: { context: VirtualizedTableContext }) => ( // Virtuoso renders the placeholder straight inside the ``, so it brings its own ``. ); // Virtuoso requires component definitions to remain stable between renders. // Dynamic behavior travels through its `context` prop instead. const virtualizedTableComponents: TableComponents> = { EmptyPlaceholder: VirtualizedEmptyState, Table: VirtualizedTableElement, TableRow: VirtualizedTableRow, }; /** A virtualized sortable table for large datasets and incremental loading. */ export const VirtualizedDataTable = ({ ariaLabel, data, columns, getRowId, getRowTextValue, onRowClick, onStartReached, onEndReached, sorting: controlledSorting, onSortingChange, manualSorting = false, loading = false, emptyMessage = 'No data.', renderEmptyState, className, scrollClassName, style, columnResizing, }: VirtualizedDataTableProps) => { const resizing = useColumnResizing(columnResizing); const [uncontrolledSorting, setUncontrolledSorting] = useState([]); const sorting = controlledSorting ?? uncontrolledSorting; const handleSortingChange = useCallback>( (updater) => { const nextSorting = typeof updater === 'function' ? updater(sorting) : updater; if (controlledSorting === undefined) { setUncontrolledSorting(nextSorting); } onSortingChange?.(nextSorting); }, [controlledSorting, onSortingChange, sorting], ); const table = useReactTable({ columns, data, getCoreRowModel: getCoreRowModel(), getRowId, getSortedRowModel: getSortedRowModel(), manualSorting, onSortingChange: handleSortingChange, ...resizing.tableOptions, state: { sorting, ...(resizing.enabled && resizing.state) }, }); const rows = table.getRowModel().rows; // Read per render: `table` is a stable object, so the memo below would never see a resize. const resizableTotalSize = resizing.enabled ? table.getTotalSize() : null; // A string, so the context below only changes when a size does. const columnSizesKey = resizing.enabled ? table .getVisibleLeafColumns() .map((column) => column.getSize()) .join(',') : null; const resizableColumnSizes = useMemo( () => (columnSizesKey === null ? null : columnSizesKey.split(',').map(Number)), [columnSizesKey], ); const context = useMemo>( () => ({ ariaLabel, columnCount: table.getVisibleLeafColumns().length, emptyMessage, getRowTextValue, isLoading: loading, resizableTotalSize, resizableColumnSizes, onRowClick, renderEmptyState, tableClassName: cn(DEFAULT_TABLE_CLASSNAME, className), }), [ ariaLabel, className, emptyMessage, getRowTextValue, loading, onRowClick, renderEmptyState, resizableColumnSizes, resizableTotalSize, table, ], ); const itemContent = useCallback( (_index: number, row: Row) => ( <> {row.getVisibleCells().map((cell) => ( ))} {resizing.enabled && } ), [resizing.enabled], ); const fixedHeaderContent = useCallback( () => table.getHeaderGroups().map((headerGroup) => ( {headerGroup.headers.map((header) => { const canSort = header.column.getCanSort(); const sortDirection = header.column.getIsSorted(); return ( ); })} {resizing.enabled && } )), [resizing.enabled, table], ); const computeItemKey = useCallback((_index: number, row: Row) => row.id, []); return ( , VirtualizedTableContext> className={cn(DEFAULT_SCROLL_CLASSNAME, scrollClassName)} components={ virtualizedTableComponents as TableComponents, VirtualizedTableContext> } computeItemKey={computeItemKey} context={context} data={rows} endReached={onEndReached} fixedHeaderContent={fixedHeaderContent} itemContent={itemContent} startReached={onStartReached} style={style ? { ...DEFAULT_STYLE, ...style } : DEFAULT_STYLE} /> ); };
{context.renderEmptyState?.() ?? (
{context.isLoading ? 'Loading…' : context.emptyMessage}
)}
{flexRender(cell.column.columnDef.cell, cell.getContext())}
{header.isPlaceholder ? null : canSort ? ( ) : ( flexRender(header.column.columnDef.header, header.getContext()) )} {resizing.enabled && }