import { useMemo, useState, type ChangeEvent, type ReactNode } from 'react'; import { TableContainer as MuiTableContainer, Table as MuiTable, TableHead as MuiTableHead, TableBody as MuiTableBody, TableRow as MuiTableRow, TableCell as MuiTableCell, TablePagination as MuiTablePagination, Paper, type TableProps, Checkbox, Radio, } from '@mui/material'; import SwapVertIcon from '@mui/icons-material/SwapVert'; import clsx from 'clsx'; import './rds-table.scss'; const EMPTY_SELECTED_ROWS: string[] = []; function getRowId(row: { id?: string | number; key?: string | number }, index: number): string { return String(row.id ?? row.key ?? index); } export interface RdsTableColumn { id: string; label: string; minWidth?: number; align?: 'left' | 'right' | 'center'; format?: (value: ReactNode) => string | ReactNode; type?: 'text' | 'checkbox' | 'radio'; sortable?: boolean; } type RdsTableRow = { id?: string | number; key?: string | number; } & Record; export interface RdsTableProps extends Omit { columns: RdsTableColumn[]; rows: RdsTableRow[]; pagination?: boolean; pageSize?: number; page?: number; totalRows?: number; onPageChange?: (page: number) => void; onPageSizeChange?: (pageSize: number) => void; stickyHeader?: boolean; selectable?: boolean; selectedRows?: string[]; onRowSelect?: (selectedRows: string[]) => void; className?: string; sortBy?: string; sortDirection?: 'asc' | 'desc'; onSortChange?: (columnId: string | undefined, direction: 'asc' | 'desc' | undefined) => void; defaultSortBy?: string; defaultSortDirection?: 'asc' | 'desc'; } const RdsTable = ({ columns, rows, pagination = false, pageSize = 10, page = 0, totalRows, onPageChange, onPageSizeChange, stickyHeader = false, selectable = false, selectedRows, onRowSelect, className = '', sortBy: controlledSortBy, sortDirection: controlledSortDirection, onSortChange, defaultSortBy, defaultSortDirection = 'asc', ...props }: RdsTableProps) => { const resolvedSelectedRows = selectedRows ?? EMPTY_SELECTED_ROWS; const [tableState, setTableState] = useState({ internalSelectedRows: [] as string[], cellCheckboxSelected: new Set(), cellRadioSelected: null as string | null, internalPage: 0, internalPageSize: 10, internalSortBy: defaultSortBy as string | undefined, internalSortDirection: (defaultSortBy ? defaultSortDirection : undefined) as 'asc' | 'desc' | undefined, }); const { internalSelectedRows, cellCheckboxSelected, cellRadioSelected, internalPage, internalPageSize, internalSortBy, internalSortDirection, } = tableState; const updateTableState = (updates: Partial | ((prev: typeof tableState) => Partial)) => { setTableState((prev) => ({ ...prev, ...(typeof updates === 'function' ? updates(prev) : updates), })); }; const currentSelectedRows = onRowSelect ? resolvedSelectedRows : internalSelectedRows; const handleRowSelection = onRowSelect || ((nextRows: string[]) => updateTableState({ internalSelectedRows: nextRows })); const sortBy = controlledSortBy !== undefined ? controlledSortBy : internalSortBy; const sortDirection = controlledSortDirection !== undefined ? controlledSortDirection : internalSortDirection; const handleSort = (column: RdsTableColumn) => { if (column.type === 'checkbox' || column.type === 'radio') return; if (!column.sortable) return; let nextDirection: 'asc' | 'desc'; const nextColumn: string = column.id; if (sortBy !== column.id) { nextDirection = 'asc'; } else { nextDirection = sortDirection === 'asc' ? 'desc' : 'asc'; } if (onSortChange) onSortChange(nextColumn, nextDirection); else { updateTableState({ internalSortBy: nextColumn, internalSortDirection: nextDirection }); } }; const sortedRows = useMemo(() => { if (!sortBy || !sortDirection) return rows; const column = columns.find(c => c.id === sortBy); if (!column) return rows; const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); const getValue = (row: RdsTableRow) => { const v = row[sortBy]; if (v === null || v === undefined) return ''; if (typeof v === 'number') return v; if (typeof v === 'string') return v; try { return JSON.stringify(v); } catch { return String(v); } }; return rows.toSorted((a, b) => { const va = getValue(a); const vb = getValue(b); let cmp: number; if (typeof va === 'number' && typeof vb === 'number') cmp = va - vb; else cmp = collator.compare(String(va), String(vb)); return sortDirection === 'asc' ? cmp : -cmp; }); }, [rows, sortBy, sortDirection, columns]); const toggleCellCheckbox = (rowId: string) => { updateTableState(prev => { const next = new Set(prev.cellCheckboxSelected); if (next.has(rowId)) next.delete(rowId); else next.add(rowId); return { cellCheckboxSelected: next }; }); }; const selectCellRadio = (rowId: string) => { updateTableState({ cellRadioSelected: rowId }); }; const checkboxRowIds = useMemo( () => rows.map((r, index) => getRowId(r, index)), [rows] ); const isAllCellCheckboxSelected = checkboxRowIds.length > 0 && checkboxRowIds.every((id) => cellCheckboxSelected.has(id)); const isCellCheckboxIndeterminate = cellCheckboxSelected.size > 0 && !isAllCellCheckboxSelected; const handleChangePage = (event: unknown, newPage: number) => { updateTableState({ internalPage: newPage }); if (onPageChange) onPageChange(newPage); }; const handleChangeRowsPerPage = (event: ChangeEvent) => { const newSize = parseInt(event.target.value, 10); updateTableState({ internalPageSize: newSize, internalPage: 0 }); if (onPageSizeChange) onPageSizeChange(newSize); if (onPageChange) onPageChange(0); }; const handleSelectAll = (event: ChangeEvent) => { if (event.target.checked) { const allRowIds = rows.map((row, index) => getRowId(row, index)); handleRowSelection(allRowIds); } else { handleRowSelection([]); } }; const handleSelectRow = (rowId: string) => { const newSelected = currentSelectedRows.includes(rowId) ? currentSelectedRows.filter(id => id !== rowId) : [...currentSelectedRows, rowId]; handleRowSelection(newSelected); }; const renderCellContent = (column: RdsTableColumn, value: ReactNode, row: RdsTableRow, rowIndex: number): ReactNode => { switch (column.type) { case 'checkbox': { const rowId = getRowId(row, rowIndex); const isChecked = cellCheckboxSelected.has(rowId); return (
toggleCellCheckbox(rowId)} size="small" disableRipple />
); } case 'radio': { const rowId = getRowId(row, rowIndex); const isChecked = cellRadioSelected === rowId; return ( selectCellRadio(rowId)} size="small" disableRipple /> ); } default: if (column.format) return column.format(value); if (typeof value === 'string' || typeof value === 'number') return value; return value == null ? '' : String(value); } }; const isAllSelected = selectable && currentSelectedRows.length === rows.length && rows.length > 0; const isIndeterminate = selectable && currentSelectedRows.length > 0 && currentSelectedRows.length < rows.length; return ( {selectable && ( )} {columns.map((column) => { const active = sortBy === column.id && !!sortDirection; return ( {column.type === 'checkbox' ? (
{ if (e.target.checked) { updateTableState({ cellCheckboxSelected: new Set(checkboxRowIds) }); } else { updateTableState({ cellCheckboxSelected: new Set() }); } }} size="small" disableRipple />
) : column.sortable ? ( ) : (
{column.label}
)}
); })}
{(pagination ? sortedRows.slice(internalPage * internalPageSize, (internalPage + 1) * internalPageSize) : sortedRows).map((row, index) => { const rowId = getRowId(row, index); const isSelected = currentSelectedRows.includes(rowId); return ( {selectable && ( handleSelectRow(rowId)} size="small" disableRipple /> )} {columns.map((column) => { const value = row[column.id] as ReactNode; const cellClass = `rds-table__cell ${column.type ? `rds-table__cell--${column.type}` : ''}`; return ( {renderCellContent(column, value, row, index) as ReactNode} ); })} ); })}
{pagination && ( )}
); }; RdsTable.displayName = 'RdsTable'; export default RdsTable;