-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathrenderers.tsx
More file actions
368 lines (339 loc) · 11.4 KB
/
Copy pathrenderers.tsx
File metadata and controls
368 lines (339 loc) · 11.4 KB
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/* Copyright 2026 Marimo. All rights reserved. */
"use no memo";
import {
type Cell,
type Column,
type ColumnDef,
flexRender,
type HeaderGroup,
type Row,
type Table,
} from "@tanstack/react-table";
import { useVirtualizer } from "@tanstack/react-virtual";
import { type JSX, useLayoutEffect, useRef, useState } from "react";
import useEvent from "react-use-event-hook";
import {
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { cn } from "@/utils/cn";
import { getCellDomProps } from "./cell-utils";
import { COLUMN_WRAPPING_STYLES } from "./column-wrapping/feature";
import { DataTableContextMenu } from "./context-menu";
import { CellRangeSelectionIndicator } from "./range-focus/cell-selection-indicator";
import { useCellRangeSelection } from "./range-focus/use-cell-range-selection";
import { useScrollIntoViewOnFocus } from "./range-focus/use-scroll-into-view";
import { AUTO_WIDTH_MAX_COLUMNS, TABLE_ROW_HEIGHT_PX } from "./types";
import { stringifyUnknownValue } from "./utils";
export function renderTableHeader<TData>(
table: Table<TData>,
isSticky?: boolean,
): JSX.Element | null {
if (!table.getRowModel().rows?.length) {
return null;
}
const renderHeaderGroup = (headerGroups: HeaderGroup<TData>[]) => {
return headerGroups.map((headerGroup) =>
headerGroup.headers.map((header) => {
const { className, style } = getPinningStyles(header.column);
return (
<TableHead
key={header.id}
className={cn(
"h-auto min-h-10 whitespace-pre align-top border-r border-r-border/75",
className,
)}
style={style}
ref={(thead) => {
columnSizingHandler({ table, column: header.column, thead });
}}
>
{header.isPlaceholder
? null
: flexRender(header.column.columnDef.header, header.getContext())}
</TableHead>
);
}),
);
};
return (
<TableHeader className={cn(isSticky && "sticky top-0 z-10")}>
<TableRow>
{renderHeaderGroup(table.getLeftHeaderGroups())}
{renderHeaderGroup(table.getCenterHeaderGroups())}
{renderHeaderGroup(table.getRightHeaderGroups())}
{table.getAllColumns().length <= AUTO_WIDTH_MAX_COLUMNS && (
<th
className="w-full border-0"
aria-hidden="true"
role="presentation"
/>
)}
</TableRow>
</TableHeader>
);
}
interface DataTableBodyProps<TData> {
table: Table<TData>;
columns: ColumnDef<TData>[];
rowViewerPanelOpen: boolean;
getRowIndex?: (row: TData, idx: number) => number;
viewedRowIdx?: number;
virtualize?: boolean;
}
export const DataTableBody = <TData,>({
table,
columns,
rowViewerPanelOpen,
getRowIndex,
viewedRowIdx,
virtualize = false,
}: DataTableBodyProps<TData>) => {
const rows = table.getRowModel().rows;
// Find the scroll container (tbody -> table -> overflow-auto wrapper div).
// Using useState so that when the element becomes available after mount,
// useVirtualizer re-observes the correct element.
const [scrollElement, setScrollElement] = useState<HTMLElement | null>(null);
const tableRef = useRef<HTMLTableSectionElement>(null);
useLayoutEffect(() => {
// tbody.parentElement = table, table.parentElement = overflow wrapper
setScrollElement(tableRef.current?.parentElement?.parentElement ?? null);
}, []);
// Always call useVirtualizer (rules of hooks); count=0 when not virtualizing
const virtualizer = useVirtualizer({
count: virtualize ? rows.length : 0,
getScrollElement: () => scrollElement,
estimateSize: () => TABLE_ROW_HEIGHT_PX,
overscan: 10,
});
// Automatically scroll focused cells into view.
// In virtual mode, off-screen cells won't be in the DOM so this silently no-ops for them.
useScrollIntoViewOnFocus(tableRef);
const {
handleCellMouseDown,
handleCellMouseUp,
handleCellMouseOver,
handleCellsKeyDown,
handleCopy: handleCopyAllCells,
} = useCellRangeSelection({ table });
const contextMenuCell = useRef<Cell<TData, unknown> | null>(null);
const handleContextMenu = useEvent((cell: Cell<TData, unknown>) => {
contextMenuCell.current = cell;
});
function applyHoverTemplate(
template: string,
cells: Cell<TData, unknown>[],
): string {
const variableRegex = /{{(\w+)}}/g;
// Map column id -> stringified value
const idToValue = new Map<string, string>();
for (const c of cells) {
const v = c.getValue();
// Prefer empty string for nulls to keep tooltip clean
const s = stringifyUnknownValue({ value: v, nullAsEmptyString: true });
idToValue.set(c.column.id, s);
}
return template.replaceAll(variableRegex, (_substr, varName: string) => {
const val = idToValue.get(varName);
return val === undefined ? `{{${varName}}}` : val;
});
}
const renderCells = (cells: Cell<TData, unknown>[]) => {
return cells.map((cell) => {
const { className, style: pinningstyle } = getPinningStyles(cell.column);
const style = Object.assign(
{},
cell.getUserStyling?.() || {},
pinningstyle,
);
const title = cell.getHoverTitle?.() ?? undefined;
const isCellSelected = cell.getIsSelected?.() || false;
return (
<TableCell
tabIndex={0}
{...getCellDomProps(cell.id)}
key={cell.id}
className={cn(
"whitespace-pre truncate max-w-[300px] border-r border-r-border/75",
isCellSelected
? "outline outline-2 outline-(--blue-7) -outline-offset-2"
: "outline-hidden",
cell.column.getColumnWrapping &&
cell.column.getColumnWrapping?.() === "wrap" &&
COLUMN_WRAPPING_STYLES,
"px-1.5 py-[0.18rem]",
className,
)}
style={style}
title={title}
onMouseDown={(e) => handleCellMouseDown(e, cell)}
onMouseUp={handleCellMouseUp}
onMouseOver={(e) => handleCellMouseOver(e, cell)}
onContextMenu={() => handleContextMenu(cell)}
>
<CellRangeSelectionIndicator cellId={cell.id} />
<div className="relative">
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</div>
</TableCell>
);
});
};
const handleRowClick = (row: Row<TData>) => {
if (rowViewerPanelOpen) {
const rowIndex = getRowIndex?.(row.original, row.index) ?? row.index;
row.focusRow?.(rowIndex);
}
};
const hoverTemplate = table.getState().cellHoverTemplate || null;
const renderRow = (row: Row<TData>) => {
// Only find the row index if the row viewer panel is open
const rowIndex = rowViewerPanelOpen
? (getRowIndex?.(row.original, row.index) ?? row.index)
: undefined;
const isRowViewedInPanel = rowViewerPanelOpen && viewedRowIdx === rowIndex;
// Compute hover title once per row using all visible cells
let rowTitle: string | undefined;
if (hoverTemplate) {
const visibleCells = row.getVisibleCells?.() ?? [
...row.getLeftVisibleCells(),
...row.getCenterVisibleCells(),
...row.getRightVisibleCells(),
];
rowTitle = applyHoverTemplate(hoverTemplate, visibleCells);
}
return (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
title={rowTitle}
// These classes ensure that empty rows (nulls) still render
className={cn(
"border-t h-6",
rowViewerPanelOpen && "cursor-pointer",
isRowViewedInPanel &&
"bg-(--blue-3) hover:bg-(--blue-3) data-[state=selected]:bg-(--blue-4)",
)}
onClick={() => handleRowClick(row)}
>
{renderCells(row.getLeftVisibleCells())}
{renderCells(row.getCenterVisibleCells())}
{renderCells(row.getRightVisibleCells())}
{columns.length <= AUTO_WIDTH_MAX_COLUMNS && (
<td className="border-0" aria-hidden="true" role="presentation" />
)}
</TableRow>
);
};
const hasFillerColumn = columns.length <= AUTO_WIDTH_MAX_COLUMNS;
const totalColSpan = columns.length + (hasFillerColumn ? 1 : 0);
const renderRows = () => {
if (rows.length === 0) {
return (
<TableRow>
<TableCell colSpan={totalColSpan} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
);
}
if (virtualize) {
const virtualItems = virtualizer.getVirtualItems();
const totalSize = virtualizer.getTotalSize();
return (
<>
{virtualItems[0]?.start > 0 && (
<tr
data-virtual-spacer=""
style={{ height: virtualItems[0].start }}
>
<td colSpan={totalColSpan} />
</tr>
)}
{virtualItems.map((vItem) => renderRow(rows[vItem.index]))}
{virtualItems.length > 0 && (
<tr
data-virtual-spacer=""
style={{
height: totalSize - (virtualItems.at(-1)?.end ?? totalSize),
}}
>
<td colSpan={totalColSpan} />
</tr>
)}
</>
);
}
return rows.map((row) => renderRow(row));
};
const tableBody = (
<TableBody onKeyDown={handleCellsKeyDown} ref={tableRef}>
{renderRows()}
</TableBody>
);
return (
<DataTableContextMenu
tableBody={tableBody}
contextMenuRef={contextMenuCell}
tableRef={tableRef}
copyAllCells={handleCopyAllCells}
/>
);
};
function getPinningStyles<TData>(
column: Column<TData>,
): React.HTMLAttributes<HTMLElement> {
const isPinned = column.getIsPinned();
const isLastLeftPinnedColumn =
isPinned === "left" && column.getIsLastColumn("left");
const isFirstRightPinnedColumn =
isPinned === "right" && column.getIsFirstColumn("right");
return {
className: cn(isPinned && "bg-inherit", "shadow-r z-10"),
style: {
boxShadow:
isLastLeftPinnedColumn && column.id !== "__select__"
? "-4px 0 4px -4px var(--slate-8) inset"
: isFirstRightPinnedColumn
? "4px 0 4px -4px var(--slate-8) inset"
: undefined,
left: isPinned === "left" ? `${column.getStart("left")}px` : undefined,
right: isPinned === "right" ? `${column.getAfter("right")}px` : undefined,
opacity: 1,
position: isPinned ? "sticky" : "relative",
zIndex: isPinned ? 1 : 0,
width: column.getSize(),
},
};
}
// Update column sizes in table state for column pinning offsets
// https://github.com/TanStack/table/discussions/3947#discussioncomment-9564867
function columnSizingHandler<TData>({
table,
column,
thead,
}: {
table: Table<TData>;
column: Column<TData>;
thead: HTMLTableCellElement | null;
}): void {
if (!thead) {
return;
}
// Round to avoid infinite re-render loops: the browser's table layout
// algorithm may render a <th> at a slightly different width than the
// CSS `width` we set via column.getSize(), so a strict float === float
// comparison never stabilizes. Rounding to integers ensures convergence
// after at most one cycle.
const measuredWidth = Math.round(thead.getBoundingClientRect().width);
if (table.getState().columnSizing[column.id] === measuredWidth) {
return;
}
table.setColumnSizing((prevSizes) => ({
...prevSizes,
[column.id]: measuredWidth,
}));
}