Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | 1x 1x 1x 1x 1x 3x 3x 3x 1x 16x 16x 16x 46x 16x 33x 16x 3x 3x 1x 6x 20x 20x 17x 16x 1x 26x 26x 23x 6x 17x 26x 26x 26x 26x 26x 57x 56x 117x 1x | import * as React from "react";
import {
type ColumnDef,
flexRender,
getCoreRowModel,
getSortedRowModel,
type SortingState,
useReactTable,
} from "@tanstack/react-table";
import { Icon } from "@sproutsocial/seeds-react-icon";
import {
TableWrapper,
TableRoot,
TableCaption,
TableHeader,
TableBody,
TableRow,
TableHeaderCell,
TableCell,
} from "@sproutsocial/seeds-react-table/v2";
import type { DataTableProps } from "./DataTableTypes";
/**
* Converts a header string to camelCase
* "First Name" -> "firstName"
*/
const toCamelCase = (str: string): string => {
return str
.trim()
.replace(/[-_\s]+(.)/g, (_, ch) => String(ch).toUpperCase())
.replace(/^[A-Z]/, (m) => m.toLowerCase());
};
/**
* Finds the best matching accessor key for a header string
* Tries: exact match -> case-insensitive -> camelCase -> lowercase fallback
*/
const findAccessorKey = <T extends Record<string, unknown>>(
header: string,
sampleRow?: T
): keyof T | string => {
Iif (!sampleRow) return toCamelCase(header);
const keys = Object.keys(sampleRow);
const lower = header.toLowerCase();
// Try exact match
let found = keys.find((k) => k === header);
Iif (found) return found as keyof T;
// Try case-insensitive match
found = keys.find((k) => k.toLowerCase() === lower);
if (found) return found as keyof T;
// Try camelCase conversion
const camel = toCamelCase(header);
if (camel in sampleRow) return camel as keyof T;
// Fallback to camelCase
return camel;
};
/**
* Converts string array to ColumnDef array
*/
const buildColumnsFromStrings = <T extends Record<string, unknown>>(
headers: string[],
sampleRow?: T,
customCellRenderer?: ColumnDef<T, unknown>["cell"]
): ColumnDef<T, unknown>[] => {
const defaultCellRenderer: ColumnDef<T, unknown>["cell"] = (info) => {
const value = info.getValue();
if (React.isValidElement(value)) return value;
return String(value ?? "");
};
return headers.map((header) => ({
accessorKey: findAccessorKey(header, sampleRow) as string,
header,
cell: customCellRenderer || defaultCellRenderer,
}));
};
/**
* DataTable component with TanStack Table integration
*
* Features:
* - String array columns with automatic camelCase mapping
* - TanStack ColumnDef[] for typed data with full control
* - Sorting functionality
* - Custom cell and header renderers
* - Accessible with required caption
*
* For simple tables with string/ReactNode arrays, use TableV2 directly.
* For large datasets requiring virtualization, use DataTableVirtualized.
*/
export function DataTable<
TData extends Record<string, unknown> = Record<string, unknown>
>({
columns,
data,
caption,
displayCaption,
emptyMessage,
renderCell,
renderCaption,
}: DataTableProps<TData>) {
const [sorting, setSorting] = React.useState<SortingState>([]);
// Convert string columns to ColumnDef if needed
const columnDefs = React.useMemo<ColumnDef<TData, unknown>[]>(() => {
if (typeof columns[0] === "string") {
return buildColumnsFromStrings<TData>(
columns as string[],
data[0],
renderCell
);
}
return columns as ColumnDef<TData, unknown>[];
}, [columns, renderCell]);
const table = useReactTable<TData>({
data,
columns: columnDefs,
state: {
sorting,
},
onSortingChange: setSorting,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
});
const rows = table.getRowModel().rows;
const renderedCaption = renderCaption ? renderCaption(caption) : caption;
return (
<TableWrapper>
<TableRoot>
<TableCaption isVisible={displayCaption ?? true}>
{renderedCaption as React.ReactNode}
</TableCaption>
<TableHeader>
{table.getHeaderGroups().map((hg) => (
<TableRow key={hg.id}>
{hg.headers.map((header) => (
<TableHeaderCell
key={header.id}
id={header.id}
style={{
cursor: header.column.getCanSort() ? "pointer" : "default",
userSelect: "none",
}}
onClick={header.column.getToggleSortingHandler()}
>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
{header.column.getCanSort() && (
<Icon
size="mini"
name={
header.column.getIsSorted() === "asc"
? "caret-up-solid"
: header.column.getIsSorted() === "desc"
? "caret-down-solid"
: "caret-up-down-outline"
}
style={{ padding: "0 4px" }}
/>
)}
</TableHeaderCell>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{rows.length === 0 ? (
<TableRow>
<TableCell
id="no-data"
colSpan={table.getAllLeafColumns().length}
>
{emptyMessage as React.ReactNode}
</TableCell>
</TableRow>
) : (
rows.map((row) => (
<TableRow key={row.id}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id} id={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
)}
</TableBody>
</TableRoot>
</TableWrapper>
);
}
export default DataTable;
|