import React, { ReactNode, useMemo } from 'react'; import { RBTableCellProps } from './tableBody.types'; import type { RBTColumnDefs, RBTRow } from '../common'; import { CompareRBTRow } from '../common'; export const RBTableBody = >({ columns, data, name, }: RBTableCellProps) => { const columnPrefix = useMemo(() => (name && name.length > 0 ? name + '.table.body' : 'table.body'), [name]); const displayed: RBTRow[] = useMemo(() => { const results: RBTRow[] = data.filter((record) => record.filters.length === 0); return results.sort(CompareRBTRow); }, [data]); /** * This will process the Cell atribute (if set) * @param column * @param row * @returns */ const GenerateCell = (index: number, column: RBTColumnDefs, row: RBTRow): ReactNode => { let id = columnPrefix; if (column.id && column.id.length > 0) { id = column.id; } let result: ReactNode; if (typeof column.Cell === 'function') { result = ( {column.Cell({ column: id, originalRow: row.data })} ); } // If there was no Id or Cell then result should be undefined if (!result && typeof column.accessorFn === 'function') { const keyOrValue = column.accessorFn(row.data); if (keyOrValue in row.data) { const data = row.data[keyOrValue]; if (typeof data === 'string' || typeof data === 'number') { result = {data}; } } else if (typeof keyOrValue === 'string' || typeof keyOrValue === 'number') { result = {keyOrValue}; } else { console.log('GenerateAccessorFN - Unable to convert data into table AccessorFN: ' + JSON.stringify(keyOrValue)); } } // If there was no Id or AccessorFN then result should be undefined if (!result && column.accessorKey) { const data = row.data[column.accessorKey]; if (typeof data === 'string' || typeof data === 'number') { result = {data}; } else { console.log('GenerateAccessorFN - Unable to convert data into table AccessorFN: ' + JSON.stringify(data)); } } return result; }; return ( {displayed.map((row: RBTRow): ReactNode => { return ( {columns.map((column: RBTColumnDefs, index: number): ReactNode => { return GenerateCell(index, column, row); })} ); })} ); };