import { Cell, flexRender, Row, Table } from '@tanstack/react-table'; import { IConditionalStyle } from '.'; import SelectRow from './SelectRow'; interface TableBodyProps { table: Table; dense?: boolean; enableRowSelection?: boolean; conditionalRowStyles?: IConditionalStyle[]; lastSelected: string | undefined; setLastSelected: React.Dispatch>; onRowClicked?: (rowData: TData, event: React.MouseEvent) => void; onRowDoubleClicked?: (rowData: TData, event: React.MouseEvent) => void; } function TableBody({ table, dense, enableRowSelection, conditionalRowStyles, lastSelected, setLastSelected, onRowClicked, onRowDoubleClicked }: TableBodyProps) { function handleRowClicked(target: Row, event: React.MouseEvent) { if (onRowClicked) { onRowClicked(target.original, event); } if (enableRowSelection && target.getCanSelect()) { if (event.shiftKey && !!lastSelected && lastSelected !== target.id) { const { rows, rowsById } = table.getRowModel(); const lastIndex = rowsById[lastSelected].index; const currentIndex = target.index; const toggleRows = rows.slice( lastIndex > currentIndex ? currentIndex : lastIndex + 1, lastIndex > currentIndex ? lastIndex : currentIndex + 1 ); const newSelection: { [key: string]: boolean } = {}; toggleRows.forEach(row => { newSelection[row.id] = !target.getIsSelected(); }); table.setRowSelection(prev => ({ ...prev, ...newSelection })); setLastSelected(undefined); } else { setLastSelected(target.id); target.toggleSelected(!target.getIsSelected()); } } } function getRowStyles(row: Row) { return { ...conditionalRowStyles! .filter(item => item.when(row.original)) .reduce((prev, item) => ({ ...prev, ...item.style }), {}) }; } return ( {table.getRowModel().rows.map((row: Row, index) => ( {enableRowSelection ? ( ) : null} {row.getVisibleCells().map((cell: Cell) => ( handleRowClicked(row, event)} onDoubleClick={event => (onRowDoubleClicked ? onRowDoubleClicked(row.original, event) : undefined)} > {flexRender(cell.column.columnDef.cell, cell.getContext())} ))} ))} ); } export default TableBody;