aplance-ui 1.5.2 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/README.md +1 -1
  2. package/dist/api.d.ts +2 -1
  3. package/dist/api.js +103 -68
  4. package/dist/api.js.map +1 -1
  5. package/dist/frameworks/vite-react/vite.config.ts.template +1 -1
  6. package/dist/index.js +103 -68
  7. package/dist/index.js.map +1 -1
  8. package/package.json +12 -6
  9. package/registry/components/primitives/modal/modal.module.css +9 -3
  10. package/registry/components/primitives/popover/popover-context.ts +2 -0
  11. package/registry/components/primitives/popover/popover.tsx +47 -2
  12. package/registry/components/ui/chart/chart.tsx +51 -30
  13. package/registry/components/ui/chart/types.ts +5 -1
  14. package/registry/components/ui/data-table/checkbox-column.tsx +12 -8
  15. package/registry/components/ui/data-table/data-table.module.css +41 -19
  16. package/registry/components/ui/data-table/data-table.tsx +1285 -1238
  17. package/registry/components/ui/data-table/filter-bar.tsx +56 -13
  18. package/registry/components/ui/data-table/filter-modal.tsx +16 -82
  19. package/registry/components/ui/data-table/filter-sheet.tsx +97 -0
  20. package/registry/components/ui/data-table/filters.tsx +21 -21
  21. package/registry/components/ui/data-table/pagination-bar.tsx +4 -6
  22. package/registry/components/ui/data-table/types.ts +149 -80
  23. package/registry/components/ui/data-table/useDataTable.tsx +35 -16
  24. package/registry/components/ui/data-table/utils.ts +691 -471
  25. package/registry/components/ui/input-fields/date-picker/calendar.tsx +7 -15
  26. package/registry/components/ui/input-fields/date-picker/date-picker.tsx +1 -1
  27. package/registry/components/ui/input-fields/date-picker/types.ts +3 -3
  28. package/registry/components/ui/input-fields/emoji-picker/emoji-palette.tsx +1 -1
  29. package/registry/registry.json +16 -11
@@ -1,1238 +1,1285 @@
1
- import {
2
- flexRender,
3
- getCoreRowModel,
4
- getExpandedRowModel,
5
- getGroupedRowModel,
6
- getPaginationRowModel,
7
- getSortedRowModel,
8
- useReactTable,
9
- type Column,
10
- type ColumnPinningState,
11
- type PaginationState as TanstackPaginationState,
12
- type Updater,
13
- } from "@tanstack/react-table";
14
- import {
15
- useCallback,
16
- useEffect,
17
- useLayoutEffect,
18
- useMemo,
19
- useRef,
20
- useState,
21
- type CSSProperties,
22
- type DragEvent as ReactDragEvent,
23
- type MouseEvent as ReactMouseEvent,
24
- type ReactNode,
25
- } from "react";
26
- import clsx from "clsx";
27
- import { Filters } from "./filters";
28
- import { PaginationBar } from "./pagination-bar";
29
- import { Loader } from "../loader/loader";
30
- import type {
31
- BodyCellProps,
32
- BodyRowProps,
33
- DataTableMeta,
34
- DataTableProps,
35
- HeaderActionButtonProps,
36
- HeaderCellProps,
37
- } from "./types";
38
- import {
39
- columnId,
40
- formatAggregated,
41
- getColumnStyle,
42
- isLastPinned,
43
- normalizeColumnPinningState,
44
- reorderColumnOrder,
45
- resolveUpdater,
46
- SELECT_COLUMN_ID,
47
- } from "./utils";
48
- import s from "./data-table.module.css";
49
- import { Tooltip } from "../tooltip/tooltip";
50
- import {
51
- IconArrowsUpDown,
52
- IconArrowUp,
53
- IconArrowDown,
54
- IconChevronRight,
55
- IconGripVertical,
56
- IconStack2,
57
- IconStack3,
58
- IconPinnedOff,
59
- IconArrowLeft,
60
- IconArrowRight,
61
- } from "@tabler/icons-react";
62
- import { getScrollbarWidth } from "../../../lib/dom";
63
- import { Button } from "../button/button";
64
-
65
- const DEFAULT_PAGE_SIZE_OPTIONS = [10, 20, 50, 100];
66
- const DEFAULT_PAGINATION = { pageIndex: 0, pageSize: 20 };
67
- // Stable refs for optional handlers. Inline `= () => {}` defaults allocate a
68
- // fresh function each render, invalidating any memo that depends on them
69
- // (notably `meta` below, which passes `onUpdateData` through tanstack).
70
- const NOOP_FILTER = () => {};
71
- const NOOP_PAGINATION = () => {};
72
- const NOOP_UPDATE = () => {};
73
- const POINTER_STYLE = { cursor: "pointer" } as const;
74
- // Controls a row can hold. A click on one is that control's, not the row's.
75
- const ROW_CONTROLS =
76
- 'a, button, input, select, textarea, label, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [role="menuitem"], [role="checkbox"], [role="radio"], [role="switch"], [role="option"], [role="tab"]';
77
- const EMPTY_FILTER_VALUES: Record<string, string> = {};
78
- const ICON_SIZE = 15;
79
- const SORT_ICON_SIZE = 13;
80
- const ICON_STROKE = 1.6;
81
- const EMPTY_COLUMN_EXTRA_WIDTHS: Record<string, number> = {};
82
- // Grace period after `isLoading` flips false before committing to the empty
83
- // state. Eliminates the flash when consumers set isLoading=false a render
84
- // before populating rows, without making genuinely-empty results feel sluggish.
85
- const EMPTY_STATE_GRACE_MS = 150;
86
-
87
- const MIN_SKELETON_ROWS = 1;
88
- const useIsomorphicLayoutEffect =
89
- typeof window === "undefined" ? useEffect : useLayoutEffect;
90
-
91
- export const DataTable = <TData extends { id: string }>({
92
- data,
93
- columns,
94
- isLoading = false,
95
- emptyMessage = "No results found.",
96
-
97
- filters = [],
98
- filterValues = EMPTY_FILTER_VALUES,
99
- onFilterChange = NOOP_FILTER,
100
-
101
- sorting,
102
- onSortingChange,
103
- manualSorting = false,
104
-
105
- showPagination = true,
106
- pagination = DEFAULT_PAGINATION,
107
- onPaginationChange = NOOP_PAGINATION,
108
- totalPages,
109
- totalCount,
110
- pageSizeOptions = DEFAULT_PAGE_SIZE_OPTIONS,
111
- showPageSizeSelect = true,
112
- rowLabel = "row",
113
-
114
- rowsSelectable = false,
115
- getRowCanSelect,
116
- rowSelection = {},
117
- onRowSelectionChange,
118
-
119
- editingRowId = null,
120
- onUpdateData = NOOP_UPDATE,
121
-
122
- enableColumnOrdering = false,
123
- columnOrder,
124
- onColumnOrderChange,
125
- enableColumnResizing = false,
126
- columnSizing,
127
- onColumnSizingChange,
128
- enableColumnPinning = false,
129
- columnPinning,
130
- onColumnPinningChange,
131
- enableRowOrdering = false,
132
- onRowOrderChange,
133
- columnVisibility,
134
- onColumnVisibilityChange,
135
-
136
- enableGrouping = false,
137
- grouping,
138
- onGroupingChange,
139
- expanded,
140
- onExpandedChange,
141
-
142
- defaultColumnPinning,
143
-
144
- showVerticalBorders = false,
145
-
146
- onRow,
147
- paginationExtra,
148
- paginationLabel,
149
- className,
150
- }: DataTableProps<TData>) => {
151
- // Collapse the filter row into a button + modal once it no longer fits inline.
152
-
153
- // ── Table meta ──────────────────────────────────────────────────────────────
154
- const meta: DataTableMeta<TData> = useMemo(
155
- () => ({ editingRowId, updateData: onUpdateData }),
156
- [editingRowId, onUpdateData],
157
- );
158
-
159
- const shouldPinSelectionColumn =
160
- rowsSelectable &&
161
- columns.some((columnDef) => columnId(columnDef) === SELECT_COLUMN_ID);
162
-
163
- const resolvedControlledColumnPinning = useMemo(
164
- () =>
165
- columnPinning === undefined
166
- ? undefined
167
- : normalizeColumnPinningState(
168
- columnPinning,
169
- shouldPinSelectionColumn,
170
- defaultColumnPinning,
171
- ),
172
- [columnPinning, shouldPinSelectionColumn, defaultColumnPinning],
173
- );
174
-
175
- const initialColumnPinning = useMemo(
176
- () =>
177
- enableColumnPinning && columnPinning === undefined
178
- ? normalizeColumnPinningState(
179
- undefined,
180
- shouldPinSelectionColumn,
181
- defaultColumnPinning,
182
- )
183
- : undefined,
184
- [
185
- enableColumnPinning,
186
- columnPinning,
187
- shouldPinSelectionColumn,
188
- defaultColumnPinning,
189
- ],
190
- );
191
-
192
- const handleColumnPinningChange = useCallback(
193
- (updater: Updater<ColumnPinningState>) => {
194
- if (!onColumnPinningChange) return;
195
-
196
- onColumnPinningChange((prev) => {
197
- const normalizedPrev =
198
- normalizeColumnPinningState(
199
- prev,
200
- shouldPinSelectionColumn,
201
- defaultColumnPinning,
202
- ) ?? {};
203
- const next = resolveUpdater(updater, normalizedPrev);
204
-
205
- // Newly right-pinned columns are inserted on the inner edge (closer
206
- // to the center) so the recently-pinned column visually slides in
207
- // next to the body, leaving previously-pinned columns flush against
208
- // the viewport edge.
209
- const prevRight = normalizedPrev.right ?? [];
210
- const nextRight = next.right ?? [];
211
- const addedToRight = nextRight.filter((id) => !prevRight.includes(id));
212
- const keptInRight = nextRight.filter((id) => prevRight.includes(id));
213
-
214
- return (
215
- normalizeColumnPinningState(
216
- { left: next.left, right: [...addedToRight, ...keptInRight] },
217
- shouldPinSelectionColumn,
218
- defaultColumnPinning,
219
- ) ?? {}
220
- );
221
- });
222
- },
223
- [onColumnPinningChange, shouldPinSelectionColumn, defaultColumnPinning],
224
- );
225
-
226
- // ── TanStack table instance ─────────────────────────────────────────────────
227
- // Filtering is delegated to the consumer (see `useDataTable.filterFn`), so we
228
- // don't wire any tanstack filter row-model here - rows arrive pre-filtered.
229
- // eslint-disable-next-line react-hooks/incompatible-library -- TanStack Table relies on function-returning APIs by design.
230
- const table = useReactTable<TData>({
231
- data,
232
- columns,
233
- enableRowSelection: rowsSelectable ? (getRowCanSelect ?? true) : false,
234
- enableColumnResizing,
235
- enableColumnPinning,
236
- enableGrouping,
237
- columnResizeMode: "onChange",
238
- state: {
239
- sorting,
240
- ...(showPagination && {
241
- pagination: pagination as TanstackPaginationState,
242
- }),
243
- ...(rowsSelectable && { rowSelection }),
244
- ...(enableColumnOrdering && columnOrder && { columnOrder }),
245
- ...(enableColumnResizing && columnSizing && { columnSizing }),
246
- ...(enableColumnPinning &&
247
- resolvedControlledColumnPinning && {
248
- columnPinning: resolvedControlledColumnPinning,
249
- }),
250
- ...(columnVisibility && { columnVisibility }),
251
- ...(enableGrouping && grouping && { grouping }),
252
- ...(enableGrouping && expanded !== undefined && { expanded }),
253
- },
254
- initialState: {
255
- ...(enableColumnPinning &&
256
- initialColumnPinning && {
257
- columnPinning: initialColumnPinning,
258
- }),
259
- },
260
- onSortingChange,
261
- ...(showPagination && {
262
- onPaginationChange: (updater) => {
263
- const cur = pagination as TanstackPaginationState;
264
- const next = typeof updater === "function" ? updater(cur) : updater;
265
- onPaginationChange(next);
266
- },
267
- }),
268
- ...(rowsSelectable && onRowSelectionChange && { onRowSelectionChange }),
269
- ...(enableColumnOrdering && onColumnOrderChange && { onColumnOrderChange }),
270
- ...(enableColumnResizing &&
271
- onColumnSizingChange && { onColumnSizingChange }),
272
- ...(enableColumnPinning &&
273
- onColumnPinningChange && {
274
- onColumnPinningChange: handleColumnPinningChange,
275
- }),
276
- ...(onColumnVisibilityChange && { onColumnVisibilityChange }),
277
- ...(enableGrouping && onGroupingChange && { onGroupingChange }),
278
- ...(enableGrouping && onExpandedChange && { onExpandedChange }),
279
- getRowId: (row) => row.id,
280
- getCoreRowModel: getCoreRowModel(),
281
- ...(!manualSorting && { getSortedRowModel: getSortedRowModel() }),
282
- ...(showPagination && {
283
- getPaginationRowModel: getPaginationRowModel(),
284
- pageCount: totalPages ?? -1,
285
- }),
286
- ...(enableGrouping && {
287
- // Keep grouped columns in place so header controls stay spatially stable.
288
- groupedColumnMode: false,
289
- getGroupedRowModel: getGroupedRowModel(),
290
- getExpandedRowModel: getExpandedRowModel(),
291
- }),
292
- manualSorting,
293
- manualPagination: showPagination,
294
- meta,
295
- });
296
-
297
- // ── Column drag-and-drop reorder (HTML5 native, no extra deps) ──────────────
298
- const [draggedColumnId, setDraggedColumnId] = useState<string | null>(null);
299
- const [dropTargetColumnId, setDropTargetColumnId] = useState<string | null>(
300
- null,
301
- );
302
-
303
- const handleColumnDrop = useCallback(
304
- (sourceId: string, targetId: string) => {
305
- if (sourceId === targetId) return;
306
- const targetCol = table.getColumn(targetId);
307
- // Refuse drops onto fixed columns (e.g. the row-select column) so they
308
- // stay anchored in their position.
309
- if (targetCol && targetCol.getCanHide() === false) return;
310
- const current =
311
- columnOrder && columnOrder.length
312
- ? columnOrder
313
- : table.getAllLeafColumns().map((c) => c.id);
314
- const next = reorderColumnOrder(current, sourceId, targetId);
315
- table.setColumnOrder(next);
316
- },
317
- [columnOrder, table],
318
- );
319
-
320
- const handleDragEnd = useCallback(() => {
321
- setDraggedColumnId(null);
322
- setDropTargetColumnId(null);
323
- }, []);
324
-
325
- const [draggedRowId, setDraggedRowId] = useState<string | null>(null);
326
- const [dropTargetRowId, setDropTargetRowId] = useState<string | null>(null);
327
-
328
- const handleDragStartRow = useCallback((id: string) => {
329
- setDraggedRowId(id);
330
- }, []);
331
-
332
- const handleDragOverRow = useCallback((id: string | null) => {
333
- setDropTargetRowId(id);
334
- }, []);
335
-
336
- const handleDragEndRow = useCallback(() => {
337
- setDraggedRowId(null);
338
- setDropTargetRowId(null);
339
- }, []);
340
-
341
- const handleDropRow = useCallback(
342
- (draggedId: string, targetId: string) => {
343
- const draggedRow = table.getRow(draggedId);
344
- const targetRow = table.getRow(targetId);
345
- if (draggedRow && targetRow) {
346
- onRowOrderChange?.(draggedRow.original, targetRow.original);
347
- }
348
- },
349
- [onRowOrderChange, table],
350
- );
351
-
352
- // ── Sync header/body scrolling ──────────────────────────────────────────────
353
- // The header lives in its own `overflow:hidden` container; we drive its
354
- // scrollLeft from the body's scrollLeft on every scroll event so pinned
355
- // columns stay perfectly aligned with their body counterparts.
356
- const headerRef = useRef<HTMLDivElement>(null);
357
- const bodyRef = useRef<HTMLDivElement>(null);
358
- const bodyTableRef = useRef<HTMLTableElement>(null);
359
- const skeletonRowRef = useRef<HTMLTableRowElement>(null);
360
- const rows = table.getRowModel().rows;
361
- const headerCount = table.getFlatHeaders().length;
362
- const totalWidth = table.getTotalSize();
363
- const tableState = table.getState();
364
- const tableColumnPinning = tableState.columnPinning;
365
- const tableColumnSizing = tableState.columnSizing;
366
- const tableColumnOrder = tableState.columnOrder;
367
- const tableColumnVisibility = tableState.columnVisibility;
368
- const tableGrouping = tableState.grouping;
369
- const [bodyViewportWidth, setBodyViewportWidth] = useState(0);
370
- const bodyViewportWidthRef = useRef(0);
371
- // Body wrap height tracked separately so the loading skeleton can render
372
- // exactly the count of rows that fits the visible body. Avoids the
373
- // "skeleton overflows + body wrap scrolls" feel during cold load.
374
- const [bodyViewportHeight, setBodyViewportHeight] = useState(0);
375
- const bodyViewportHeightRef = useRef(0);
376
- const [skeletonRowHeight, setSkeletonRowHeight] = useState(0);
377
- const skeletonRowHeightRef = useRef(0);
378
-
379
- const commitBodyViewportWidth = useCallback((nextWidth: number) => {
380
- if (bodyViewportWidthRef.current === nextWidth) return;
381
- bodyViewportWidthRef.current = nextWidth;
382
- setBodyViewportWidth(nextWidth);
383
- }, []);
384
-
385
- const commitBodyViewportHeight = useCallback((nextHeight: number) => {
386
- if (bodyViewportHeightRef.current === nextHeight) return;
387
- bodyViewportHeightRef.current = nextHeight;
388
- setBodyViewportHeight(nextHeight);
389
- }, []);
390
-
391
- const commitSkeletonRowHeight = useCallback((nextHeight: number) => {
392
- if (nextHeight <= 0 || skeletonRowHeightRef.current === nextHeight) return;
393
- skeletonRowHeightRef.current = nextHeight;
394
- setSkeletonRowHeight(nextHeight);
395
- }, []);
396
-
397
- const syncHeaderMetrics = useCallback(() => {
398
- const body = bodyRef.current;
399
- const header = headerRef.current;
400
- if (!body || !header) return;
401
-
402
- const scrollbarW = getScrollbarWidth();
403
- const hasScroll = body.scrollHeight > body.clientHeight;
404
- const paddingRight = hasScroll ? `${scrollbarW}px` : "0px";
405
-
406
- header.style.paddingRight = paddingRight;
407
- header.parentElement?.style.setProperty(
408
- "--header-padding-right",
409
- paddingRight,
410
- );
411
- header.parentElement?.setAttribute("data-has-scroll", hasScroll.toString());
412
- // Mirror onto the body wrap so CSS can release the reserved scrollbar gutter
413
- // when there's no vertical overflow (no blank strip on a few-row table).
414
- body.setAttribute("data-has-scroll", hasScroll.toString());
415
-
416
- // Re-sync horizontal scroll position after width changes so pinned
417
- // columns stay perfectly aligned with their body counterparts.
418
- header.scrollLeft = body.scrollLeft;
419
- commitBodyViewportWidth(body.clientWidth);
420
- commitBodyViewportHeight(body.clientHeight);
421
- }, [commitBodyViewportWidth, commitBodyViewportHeight]);
422
-
423
- useIsomorphicLayoutEffect(() => {
424
- syncHeaderMetrics();
425
- }, [
426
- rows.length,
427
- headerCount,
428
- totalWidth,
429
- tableColumnPinning,
430
- tableColumnSizing,
431
- tableColumnOrder,
432
- tableColumnVisibility,
433
- tableGrouping,
434
- syncHeaderMetrics,
435
- ]);
436
-
437
- useIsomorphicLayoutEffect(() => {
438
- const body = bodyRef.current;
439
- if (!body) return;
440
- if (typeof ResizeObserver === "undefined") return;
441
-
442
- const observer = new ResizeObserver(syncHeaderMetrics);
443
- observer.observe(body);
444
- if (bodyTableRef.current) observer.observe(bodyTableRef.current);
445
-
446
- return () => {
447
- observer.disconnect();
448
- };
449
- }, [syncHeaderMetrics, rows.length, isLoading]);
450
-
451
- useEffect(() => {
452
- const body = bodyRef.current;
453
- const header = headerRef.current;
454
- if (!body || !header) return;
455
-
456
- const syncFromBody = () => {
457
- if (header.scrollLeft !== body.scrollLeft) {
458
- header.scrollLeft = body.scrollLeft;
459
- }
460
- };
461
-
462
- const syncFromHeader = () => {
463
- if (body.scrollLeft !== header.scrollLeft) {
464
- body.scrollLeft = header.scrollLeft;
465
- }
466
- };
467
-
468
- body.addEventListener("scroll", syncFromBody, { passive: true });
469
- header.addEventListener("scroll", syncFromHeader, { passive: true });
470
-
471
- return () => {
472
- body.removeEventListener("scroll", syncFromBody);
473
- header.removeEventListener("scroll", syncFromHeader);
474
- };
475
- }, []);
476
-
477
- // ── Derived UI state ────────────────────────────────────────────────────────
478
- // Defer the empty state by a tick after a loading-to-idle transition so the
479
- // loader doesn't flicker into "no results" for one paint before rows land.
480
- // Genuinely empty results (no in-flight load) commit immediately on mount.
481
- const isRowsEmpty = rows.length === 0;
482
- const [showEmptyState, setShowEmptyState] = useState(
483
- () => !isLoading && isRowsEmpty,
484
- );
485
- const wasLoadingRef = useRef(isLoading);
486
-
487
- // wasLoadingRef is intentionally omitted from the dep array: it's a ref used
488
- // to track the previous value of isLoading across renders without triggering
489
- // re-runs. React guarantees ref objects are stable across the component lifetime.
490
- useEffect(() => {
491
- const wasLoading = wasLoadingRef.current;
492
- wasLoadingRef.current = isLoading;
493
-
494
- if (isLoading || !isRowsEmpty) {
495
- setShowEmptyState(false);
496
- return;
497
- }
498
- if (!wasLoading) {
499
- setShowEmptyState(true);
500
- return;
501
- }
502
- const id = window.setTimeout(
503
- () => setShowEmptyState(true),
504
- EMPTY_STATE_GRACE_MS,
505
- );
506
- return () => window.clearTimeout(id);
507
- }, [isLoading, isRowsEmpty]);
508
-
509
- // Single tab-like discriminator drives the body - loader, empty, or content.
510
- // While loading OR while bridging the loading-to-empty grace window, the
511
- // loader stays visible to avoid the brief "no results" flash.
512
- const view: "loader" | "empty" | "content" =
513
- isLoading || (isRowsEmpty && !showEmptyState)
514
- ? "loader"
515
- : isRowsEmpty
516
- ? "empty"
517
- : "content";
518
-
519
- useIsomorphicLayoutEffect(() => {
520
- if (view !== "loader") return;
521
- const row = skeletonRowRef.current;
522
- if (!row) return;
523
-
524
- const measureRow = () => {
525
- commitSkeletonRowHeight(Math.ceil(row.getBoundingClientRect().height));
526
- };
527
-
528
- measureRow();
529
- if (typeof ResizeObserver === "undefined") return;
530
-
531
- const observer = new ResizeObserver(measureRow);
532
- observer.observe(row);
533
-
534
- return () => {
535
- observer.disconnect();
536
- };
537
- }, [commitSkeletonRowHeight, view]);
538
-
539
- const selectedCount = rowsSelectable
540
- ? table.getSelectedRowModel().flatRows.length
541
- : 0;
542
- const headerGroups = table.getHeaderGroups();
543
- const visibleLeafColumns = table.getVisibleLeafColumns();
544
-
545
- const skeletonRowCount =
546
- bodyViewportHeight > 0 && skeletonRowHeight > 0
547
- ? Math.max(
548
- MIN_SKELETON_ROWS,
549
- Math.floor(bodyViewportHeight / skeletonRowHeight),
550
- )
551
- : MIN_SKELETON_ROWS;
552
-
553
- const columnExtraWidths = useMemo<Record<string, number>>(() => {
554
- const extraSpace = Math.max(0, bodyViewportWidth - totalWidth);
555
- if (extraSpace <= 0) return EMPTY_COLUMN_EXTRA_WIDTHS;
556
-
557
- // Never add responsive width onto pinned columns because tanstack computes
558
- // sticky offsets from base sizes; changing pinned visual width would desync
559
- // left/right offsets and reintroduce overlap.
560
- const growColumns = visibleLeafColumns.filter(
561
- (column) => !column.getIsPinned() && column.id !== SELECT_COLUMN_ID,
562
- );
563
- if (growColumns.length === 0) return EMPTY_COLUMN_EXTRA_WIDTHS;
564
-
565
- const baseExtra = Math.floor(extraSpace / growColumns.length);
566
- let remainder = extraSpace - baseExtra * growColumns.length;
567
-
568
- const next: Record<string, number> = {};
569
- for (const column of growColumns) {
570
- const grow = baseExtra + (remainder > 0 ? 1 : 0);
571
- if (grow > 0) {
572
- next[column.id] = grow;
573
- }
574
- if (remainder > 0) {
575
- remainder -= 1;
576
- }
577
- }
578
-
579
- return next;
580
- }, [bodyViewportWidth, totalWidth, visibleLeafColumns]);
581
-
582
- const tableWidth = Math.max(totalWidth, bodyViewportWidth);
583
-
584
- // Columns that fit the body never scroll it sideways. The body's width is
585
- // read from clientWidth, which rounds to the nearest pixel, so on a
586
- // fractional layout (page zoom, display scaling) the table can overhang the
587
- // body by under a pixel. Left to `overflow-x: auto`, that sliver shows a
588
- // horizontal scrollbar, which shortens the body, flips its scrollbar gutter
589
- // and starts another resize.
590
- const columnsFit = bodyViewportWidth > 0 && totalWidth <= bodyViewportWidth;
591
-
592
- // Match the table element width to the measured column widths. This keeps
593
- // header, body, and skeleton rows on the same sizing contract during resize.
594
- const tableSizingStyle: CSSProperties = useMemo(
595
- () => ({ width: `${tableWidth}px`, minWidth: `${totalWidth}px` }),
596
- [tableWidth, totalWidth],
597
- );
598
-
599
- const bodySkeletonStyle: CSSProperties = {
600
- height: "var(--spacing-9)",
601
- };
602
-
603
- const selectSkeletonStyle: CSSProperties = {
604
- width: "var(--data-table-selection-control-size, var(--spacing-9))",
605
- height: "var(--data-table-selection-control-size, var(--spacing-9))",
606
- };
607
-
608
- const tableClass = clsx(
609
- s.table,
610
- showVerticalBorders && s.table_vertical_borders,
611
- );
612
-
613
- return (
614
- <div className={clsx(s.root, className)}>
615
- {/* Filters - inline row on desktop; a "Filters" button + modal once the
616
- row no longer fits (so phones aren't buried under stacked fields). */}
617
- {filters.length > 0 && (
618
- <Filters
619
- fields={filters}
620
- values={filterValues}
621
- onChange={onFilterChange}
622
- />
623
- )}
624
-
625
- {/* Content wrap - grows to fill remaining height.
626
- table_shell fills it; pagination pins to the bottom via margin-top:auto */}
627
- <div className={s.content_wrap}>
628
- {/* Table: detached header pill + scrollable body */}
629
- <div
630
- className={clsx(
631
- s.table_shell,
632
- !showPagination && s.table_shell_no_pagination,
633
- )}
634
- >
635
- {/* Pinned header pill - scroll synced to body via JS */}
636
- <div className={s.table_header_container}>
637
- <div className={s.table_header_wrap} ref={headerRef}>
638
- <table className={tableClass} style={tableSizingStyle}>
639
- <thead>
640
- {headerGroups.map((hg) => (
641
- <tr key={hg.id}>
642
- {hg.headers.map((header) => (
643
- <HeaderCell<TData>
644
- key={header.id}
645
- header={header}
646
- extraWidth={columnExtraWidths[header.column.id] ?? 0}
647
- enableColumnOrdering={enableColumnOrdering}
648
- enableColumnResizing={enableColumnResizing}
649
- enableColumnPinning={enableColumnPinning}
650
- enableGrouping={enableGrouping}
651
- draggedColumnId={draggedColumnId}
652
- dropTargetColumnId={dropTargetColumnId}
653
- onDragStartCol={setDraggedColumnId}
654
- onDragEndCol={handleDragEnd}
655
- onDragOverCol={setDropTargetColumnId}
656
- onDropCol={handleColumnDrop}
657
- />
658
- ))}
659
- </tr>
660
- ))}
661
- </thead>
662
- </table>
663
- </div>
664
- <div className={s.header_padding_mask} />
665
- </div>
666
-
667
- {/* Scrollable body - only this element scrolls. The body is a
668
- single switch over `view`: at most one branch ever renders, the
669
- other two are unmounted entirely. */}
670
- <div
671
- className={s.table_body_wrap}
672
- style={{ pointerEvents: isLoading ? "none" : undefined }}
673
- data-fits={columnsFit}
674
- ref={bodyRef}
675
- >
676
- {view === "loader" && (
677
- <table className={tableClass} style={tableSizingStyle}>
678
- <tbody>
679
- {Array.from({ length: skeletonRowCount }).map(
680
- (_, rowIndex) => (
681
- <tr
682
- key={`skeleton-${rowIndex}`}
683
- ref={rowIndex === 0 ? skeletonRowRef : undefined}
684
- >
685
- {visibleLeafColumns.map((column) => {
686
- const isPinned = column.getIsPinned();
687
- const isLastPinnedCol =
688
- isPinned && isLastPinned(column);
689
- const isSelectColumn = column.id === SELECT_COLUMN_ID;
690
-
691
- return (
692
- <td
693
- key={column.id}
694
- className={clsx(
695
- isSelectColumn && s.col_select,
696
- isPinned === "left" && s.col_pinned_left,
697
- isPinned === "right" && s.col_pinned_right,
698
- isLastPinnedCol && s.col_pinned_last,
699
- )}
700
- style={getColumnStyle(
701
- column,
702
- column.getSize(),
703
- columnExtraWidths[column.id] ?? 0,
704
- )}
705
- >
706
- <div className={s.td_inner}>
707
- <Loader
708
- variant="skeleton"
709
- className={
710
- isSelectColumn
711
- ? s.loading_select_skeleton
712
- : undefined
713
- }
714
- style={
715
- isSelectColumn
716
- ? selectSkeletonStyle
717
- : bodySkeletonStyle
718
- }
719
- />
720
- </div>
721
- </td>
722
- );
723
- })}
724
- </tr>
725
- ),
726
- )}
727
- </tbody>
728
- </table>
729
- )}
730
- {view === "empty" && (
731
- <div className={s.state_overlay}>
732
- <p className={s.empty_msg}>{emptyMessage}</p>
733
- </div>
734
- )}
735
- {view === "content" && (
736
- <table
737
- className={tableClass}
738
- style={tableSizingStyle}
739
- ref={bodyTableRef}
740
- >
741
- <tbody>
742
- {rows.map((row) => (
743
- <BodyRow<TData>
744
- key={row.id}
745
- row={row}
746
- editingRowId={editingRowId}
747
- onRow={onRow}
748
- enableGrouping={enableGrouping}
749
- columnExtraWidths={columnExtraWidths}
750
- enableRowOrdering={enableRowOrdering}
751
- draggedRowId={draggedRowId}
752
- dropTargetRowId={dropTargetRowId}
753
- onDragStartRow={handleDragStartRow}
754
- onDragOverRow={handleDragOverRow}
755
- onDragEndRow={handleDragEndRow}
756
- onDropRow={handleDropRow}
757
- />
758
- ))}
759
- </tbody>
760
- </table>
761
- )}
762
- </div>
763
- </div>
764
-
765
- {/* Pagination - margin-top:auto pins it to the bottom of content_wrap */}
766
- {showPagination && (
767
- <PaginationBar
768
- table={table}
769
- pagination={pagination}
770
- onPaginationChange={onPaginationChange}
771
- pageSizeOptions={pageSizeOptions}
772
- showPageSizeSelect={showPageSizeSelect}
773
- isLoading={view === "loader"}
774
- totalCount={totalCount}
775
- rowLabel={rowLabel}
776
- rowsSelectable={rowsSelectable}
777
- selectedCount={selectedCount}
778
- label={paginationLabel}
779
- extra={paginationExtra}
780
- />
781
- )}
782
- </div>
783
- </div>
784
- );
785
- };
786
-
787
- // ─────────────────────────────────────────────────────────────────────────────
788
- // HeaderActionButton - local compact icon button for the table header.
789
- // Keeps the header tight (no library Button padding) without depending on the
790
- // Button component while still mirroring its hover/focus visuals.
791
- // ─────────────────────────────────────────────────────────────────────────────
792
-
793
- const HeaderActionButton = ({
794
- onClick,
795
- ariaLabel,
796
- ariaPressed,
797
- active = false,
798
- children,
799
- }: HeaderActionButtonProps) => {
800
- return (
801
- <Button
802
- type="button"
803
- variant="ghost"
804
- size="sm"
805
- layout="box"
806
- className={s.icon_btn}
807
- onClick={onClick}
808
- aria-label={ariaLabel}
809
- aria-pressed={ariaPressed}
810
- draggable={false}
811
- isActive={active}
812
- >
813
- {children}
814
- </Button>
815
- );
816
- };
817
-
818
- // ─────────────────────────────────────────────────────────────────────────────
819
- // HeaderCell - one <th> with sort, group, pin, drag, and resize affordances.
820
- // ─────────────────────────────────────────────────────────────────────────────
821
-
822
- const HeaderCell = <TData,>({
823
- header,
824
- extraWidth,
825
- enableColumnOrdering,
826
- enableColumnResizing,
827
- enableColumnPinning,
828
- enableGrouping,
829
- draggedColumnId,
830
- dropTargetColumnId,
831
- onDragStartCol,
832
- onDragEndCol,
833
- onDragOverCol,
834
- onDropCol,
835
- }: HeaderCellProps<TData>) => {
836
- const column = header.column;
837
- const colMeta = column.columnDef.meta;
838
- const align = colMeta?.align ?? "left";
839
- // Fixed columns (e.g. row-select) opt out of hide-ability AND of being a
840
- // drag source / drop target so they stay anchored in their position.
841
- const isFixed = column.getCanHide() === false;
842
- const canDrag = enableColumnOrdering && !isFixed;
843
- const canResize = enableColumnResizing && column.getCanResize();
844
- const canPin = enableColumnPinning && column.getCanPin() && !isFixed;
845
- const canGroup = enableGrouping && column.getCanGroup() && !isFixed;
846
- const canSort = column.getCanSort();
847
- const isPinned = column.getIsPinned();
848
- const isLastPinnedCol = isPinned && isLastPinned(column);
849
- const isBeingDragged = draggedColumnId === column.id;
850
- const isDropTarget =
851
- dropTargetColumnId === column.id &&
852
- draggedColumnId !== column.id &&
853
- !isFixed;
854
- const isGrouped = enableGrouping && column.getIsGrouped();
855
- const isSelectColumn = column.id === SELECT_COLUMN_ID;
856
- const sortState = column.getIsSorted();
857
- const hasHeaderActions = canSort || canGroup || canPin;
858
- const sortTooltip =
859
- sortState === "asc"
860
- ? "Sort descending"
861
- : sortState === "desc"
862
- ? "Clear sorting"
863
- : "Sort ascending";
864
-
865
- const handleDragStart = (e: ReactDragEvent<HTMLTableCellElement>) => {
866
- e.dataTransfer.effectAllowed = "move";
867
- e.dataTransfer.setData("text/plain", column.id);
868
- onDragStartCol(column.id);
869
- };
870
-
871
- const handleDragOver = (e: ReactDragEvent<HTMLTableCellElement>) => {
872
- if (!draggedColumnId || draggedColumnId === column.id || isFixed) return;
873
- e.preventDefault();
874
- e.dataTransfer.dropEffect = "move";
875
- if (dropTargetColumnId !== column.id) onDragOverCol(column.id);
876
- };
877
-
878
- const handleDragLeave = () => {
879
- if (dropTargetColumnId === column.id) onDragOverCol(null);
880
- };
881
-
882
- const handleDrop = (e: ReactDragEvent<HTMLTableCellElement>) => {
883
- e.preventDefault();
884
- if (!draggedColumnId || isFixed) return;
885
- onDropCol(draggedColumnId, column.id);
886
- onDragEndCol();
887
- };
888
-
889
- const sortIcon = !sortState ? (
890
- <IconArrowsUpDown size={SORT_ICON_SIZE} stroke={ICON_STROKE} />
891
- ) : sortState === "asc" ? (
892
- <IconArrowUp size={SORT_ICON_SIZE} stroke={ICON_STROKE} />
893
- ) : (
894
- <IconArrowDown size={SORT_ICON_SIZE} stroke={ICON_STROKE} />
895
- );
896
-
897
- return (
898
- <th
899
- colSpan={header.colSpan}
900
- onDragOver={canDrag ? handleDragOver : undefined}
901
- onDragLeave={canDrag ? handleDragLeave : undefined}
902
- onDrop={canDrag ? handleDrop : undefined}
903
- className={clsx(
904
- colMeta?.headerClassName,
905
- s[`align_${align}`],
906
- isSelectColumn && s.col_select,
907
- isPinned === "left" && s.col_pinned_left,
908
- isPinned === "right" && s.col_pinned_right,
909
- isLastPinnedCol && s.col_pinned_last,
910
- isBeingDragged && s.col_dragging,
911
- isDropTarget && s.col_drop_target,
912
- )}
913
- style={getColumnStyle(column, header.getSize(), extraWidth)}
914
- >
915
- {!header.isPlaceholder && (
916
- <div className={s.th_inner}>
917
- {canDrag && (
918
- <span
919
- className={s.drag_handle}
920
- aria-hidden
921
- draggable
922
- onDragStart={handleDragStart}
923
- onDragEnd={onDragEndCol}
924
- >
925
- <IconGripVertical size={ICON_SIZE} stroke={ICON_STROKE} />
926
- </span>
927
- )}
928
- {isSelectColumn ? (
929
- flexRender(column.columnDef.header, header.getContext())
930
- ) : (
931
- <span className={s.th_label}>
932
- {flexRender(column.columnDef.header, header.getContext())}
933
- </span>
934
- )}
935
- {hasHeaderActions && (
936
- <span className={s.th_actions}>
937
- {canSort && (
938
- <Tooltip content={sortTooltip}>
939
- <HeaderActionButton
940
- onClick={column.getToggleSortingHandler()}
941
- ariaLabel={`Sort by ${column.id}`}
942
- ariaPressed={!!sortState}
943
- active={!!sortState}
944
- >
945
- {sortIcon}
946
- </HeaderActionButton>
947
- </Tooltip>
948
- )}
949
- {canGroup && (
950
- <Tooltip
951
- content={isGrouped ? "Ungroup column" : "Group by column"}
952
- >
953
- <HeaderActionButton
954
- onClick={column.getToggleGroupingHandler()}
955
- ariaLabel={
956
- isGrouped ? "Ungroup column" : "Group by this column"
957
- }
958
- ariaPressed={isGrouped}
959
- active={isGrouped}
960
- >
961
- {isGrouped ? (
962
- <IconStack3 size={ICON_SIZE} stroke={ICON_STROKE} />
963
- ) : (
964
- <IconStack2 size={ICON_SIZE} stroke={ICON_STROKE} />
965
- )}
966
- </HeaderActionButton>
967
- </Tooltip>
968
- )}
969
- {canPin && !isPinned && (
970
- <>
971
- <Tooltip content="Pin left">
972
- <HeaderActionButton
973
- onClick={() => column.pin("left")}
974
- ariaLabel="Pin left"
975
- >
976
- <IconArrowLeft size={ICON_SIZE} stroke={ICON_STROKE} />
977
- </HeaderActionButton>
978
- </Tooltip>
979
- <Tooltip content="Pin right">
980
- <HeaderActionButton
981
- onClick={() => column.pin("right")}
982
- ariaLabel="Pin right"
983
- >
984
- <IconArrowRight size={ICON_SIZE} stroke={ICON_STROKE} />
985
- </HeaderActionButton>
986
- </Tooltip>
987
- </>
988
- )}
989
- {canPin && isPinned && (
990
- <Tooltip content="Unpin column">
991
- <HeaderActionButton
992
- onClick={() => column.pin(false)}
993
- ariaLabel="Unpin column"
994
- ariaPressed
995
- active
996
- >
997
- <IconPinnedOff size={ICON_SIZE} stroke={ICON_STROKE} />
998
- </HeaderActionButton>
999
- </Tooltip>
1000
- )}
1001
- </span>
1002
- )}
1003
- {canResize && (
1004
- <span
1005
- role="separator"
1006
- aria-orientation="vertical"
1007
- className={clsx(
1008
- s.resize_handle,
1009
- column.getIsResizing() && s.resize_handle_active,
1010
- )}
1011
- onMouseDown={header.getResizeHandler()}
1012
- onTouchStart={header.getResizeHandler()}
1013
- onClick={(e) => e.stopPropagation()}
1014
- onDoubleClick={() => column.resetSize()}
1015
- draggable={false}
1016
- />
1017
- )}
1018
- </div>
1019
- )}
1020
- </th>
1021
- );
1022
- };
1023
-
1024
- // ─────────────────────────────────────────────────────────────────────────────
1025
- // BodyRow - one <tr> + its visible cells.
1026
- // ─────────────────────────────────────────────────────────────────────────────
1027
-
1028
- const BodyRow = <TData extends { id: string }>({
1029
- row,
1030
- editingRowId,
1031
- onRow,
1032
- enableGrouping,
1033
- columnExtraWidths,
1034
- enableRowOrdering,
1035
- draggedRowId,
1036
- dropTargetRowId,
1037
- onDragStartRow,
1038
- onDragOverRow,
1039
- onDragEndRow,
1040
- onDropRow,
1041
- }: BodyRowProps<TData>) => {
1042
- const isGroup = enableGrouping && row.getIsGrouped();
1043
- const visibleCells = row.getVisibleCells();
1044
- const groupSourceCell = isGroup
1045
- ? visibleCells.find((cell) => cell.getIsGrouped())
1046
- : undefined;
1047
- const groupAnchorCellId = isGroup
1048
- ? (visibleCells.find((cell) => cell.column.id !== SELECT_COLUMN_ID)?.id ??
1049
- groupSourceCell?.id ??
1050
- null)
1051
- : null;
1052
- const isEditingThisRow =
1053
- !isGroup && editingRowId !== null && row.original.id === editingRowId;
1054
-
1055
- // Editing rows host inputs/selects; their clicks must not bubble to row click.
1056
- // Only a click on the row itself opens it: not one on a control inside it
1057
- // (a link, a copy button), nor one that reaches it through a portal (a row's
1058
- // action menu), which React bubbles here from outside the row.
1059
- const handleRowClick =
1060
- !isGroup && !isEditingThisRow && onRow
1061
- ? (event: ReactMouseEvent<HTMLTableRowElement>) => {
1062
- const target = event.target as Element;
1063
- if (!event.currentTarget.contains(target)) return;
1064
- const control = target.closest(ROW_CONTROLS);
1065
- if (control && event.currentTarget.contains(control)) return;
1066
- onRow(row.original);
1067
- }
1068
- : undefined;
1069
-
1070
- const canDrag = enableRowOrdering && !isGroup && !isEditingThisRow;
1071
- const isBeingDragged = draggedRowId === row.id;
1072
- const isDropTarget =
1073
- dropTargetRowId === row.id && draggedRowId !== row.id && !isGroup;
1074
-
1075
- return (
1076
- <tr
1077
- draggable={canDrag}
1078
- onDragStart={(e) => {
1079
- if (!canDrag) return;
1080
- e.dataTransfer.effectAllowed = "move";
1081
- e.dataTransfer.setData("text/plain", row.id);
1082
- onDragStartRow?.(row.id);
1083
- }}
1084
- onDragOver={(e) => {
1085
- if (!canDrag || !draggedRowId || draggedRowId === row.id) return;
1086
- e.preventDefault();
1087
- e.dataTransfer.dropEffect = "move";
1088
- if (dropTargetRowId !== row.id) onDragOverRow?.(row.id);
1089
- }}
1090
- onDragLeave={() => {
1091
- if (!canDrag) return;
1092
- if (dropTargetRowId === row.id) onDragOverRow?.(null);
1093
- }}
1094
- onDragEnd={() => {
1095
- if (!canDrag) return;
1096
- onDragEndRow?.();
1097
- }}
1098
- onDrop={(e) => {
1099
- if (!canDrag) return;
1100
- e.preventDefault();
1101
- if (!draggedRowId || draggedRowId === row.id) return;
1102
- onDropRow?.(draggedRowId, row.id);
1103
- onDragEndRow?.();
1104
- }}
1105
- className={clsx(
1106
- row.getIsSelected() && s.row_selected,
1107
- isEditingThisRow && s.row_editing,
1108
- isGroup && s.row_group,
1109
- isBeingDragged && s.row_dragging,
1110
- isDropTarget && s.row_drop_target,
1111
- )}
1112
- onClick={handleRowClick}
1113
- style={handleRowClick ? POINTER_STYLE : undefined}
1114
- >
1115
- {visibleCells.map((cell) => (
1116
- <BodyCell<TData>
1117
- key={cell.id}
1118
- cell={cell}
1119
- extraWidth={columnExtraWidths[cell.column.id] ?? 0}
1120
- groupSourceCell={groupSourceCell}
1121
- isGroupAnchorCell={groupAnchorCellId === cell.id}
1122
- />
1123
- ))}
1124
- </tr>
1125
- );
1126
- };
1127
-
1128
- // ─────────────────────────────────────────────────────────────────────────────
1129
- // BodyCell - one <td>. Routes to the right body for grouped/aggregated/normal
1130
- // cells and applies meta-driven align + truncate + pin classes.
1131
- // ─────────────────────────────────────────────────────────────────────────────
1132
-
1133
- const BodyCell = <TData,>({
1134
- cell,
1135
- extraWidth,
1136
- groupSourceCell,
1137
- isGroupAnchorCell,
1138
- }: BodyCellProps<TData>) => {
1139
- const column: Column<TData, unknown> = cell.column;
1140
- const colMeta = column.columnDef.meta;
1141
- const align = colMeta?.align ?? "left";
1142
- const truncate = colMeta?.truncate ?? true;
1143
- const isPinned = column.getIsPinned();
1144
- const isLastPinnedCol = isPinned && isLastPinned(column);
1145
- const isSelectColumn = column.id === SELECT_COLUMN_ID;
1146
- const groupedRenderCell =
1147
- groupSourceCell ?? (cell.getIsGrouped() ? cell : undefined);
1148
- const groupDepth = groupedRenderCell?.row.depth ?? 0;
1149
-
1150
- let body: ReactNode;
1151
- if (groupedRenderCell && isGroupAnchorCell) {
1152
- const groupedColumn = groupedRenderCell.column;
1153
- body = (
1154
- <button
1155
- type="button"
1156
- className={s.group_toggle}
1157
- onClick={groupedRenderCell.row.getToggleExpandedHandler()}
1158
- aria-expanded={groupedRenderCell.row.getIsExpanded()}
1159
- aria-label={
1160
- groupedRenderCell.row.getIsExpanded()
1161
- ? "Collapse group"
1162
- : "Expand group"
1163
- }
1164
- style={
1165
- groupDepth > 0
1166
- ? { paddingInlineStart: `calc(${groupDepth} * var(--spacing-4))` }
1167
- : undefined
1168
- }
1169
- >
1170
- <IconChevronRight
1171
- size={ICON_SIZE}
1172
- stroke={ICON_STROKE}
1173
- className={clsx(
1174
- s.group_chevron,
1175
- groupedRenderCell.row.getIsExpanded() && s.group_chevron_open,
1176
- )}
1177
- />
1178
- <span className={s.group_value}>
1179
- {flexRender(
1180
- groupedColumn.columnDef.cell,
1181
- groupedRenderCell.getContext(),
1182
- )}
1183
- </span>
1184
- <span className={s.group_count}>
1185
- ({groupedRenderCell.row.subRows.length})
1186
- </span>
1187
- </button>
1188
- );
1189
- } else if (groupedRenderCell && groupedRenderCell.id === cell.id) {
1190
- body = null;
1191
- } else if (cell.getIsAggregated()) {
1192
- body = column.columnDef.aggregatedCell ? (
1193
- flexRender(column.columnDef.aggregatedCell, cell.getContext())
1194
- ) : column.columnDef.aggregationFn ? (
1195
- <span className={s.cell_aggregated}>
1196
- {formatAggregated(cell.getValue())}
1197
- </span>
1198
- ) : null;
1199
- } else if (cell.getIsPlaceholder()) {
1200
- body = null;
1201
- } else {
1202
- body = flexRender(column.columnDef.cell, cell.getContext());
1203
- }
1204
-
1205
- // Group rows are full-width summary rows; sticky pinning makes no sense
1206
- // on them. We strip BOTH the pinned CSS classes AND the left/right inline
1207
- // offsets. Without this, td:focus-within (which sets position:relative)
1208
- // would combine with left:Xpx from getColumnStyle and physically shift
1209
- // the cell when the user clicks the group-toggle chevron.
1210
- const isGroupRow = !!groupedRenderCell;
1211
- const baseStyle = getColumnStyle(column, column.getSize(), extraWidth);
1212
- const cellStyle: CSSProperties = isGroupRow
1213
- ? {
1214
- width: baseStyle.width,
1215
- minWidth: baseStyle.minWidth,
1216
- maxWidth: baseStyle.maxWidth,
1217
- }
1218
- : baseStyle;
1219
-
1220
- return (
1221
- <td
1222
- className={clsx(
1223
- colMeta?.cellClassName,
1224
- s[`align_${align}`],
1225
- isGroupAnchorCell && s.group_anchor_cell,
1226
- !isGroupRow && isSelectColumn && s.col_select,
1227
- !isGroupRow && isPinned === "left" && s.col_pinned_left,
1228
- !isGroupRow && isPinned === "right" && s.col_pinned_right,
1229
- !isGroupRow && isLastPinnedCol && s.col_pinned_last,
1230
- )}
1231
- style={cellStyle}
1232
- >
1233
- <div className={clsx(s.td_inner, !truncate && s.td_inner_no_truncate)}>
1234
- {body}
1235
- </div>
1236
- </td>
1237
- );
1238
- };
1
+ import {
2
+ FlexRender,
3
+ useTable,
4
+ type ColumnPinningState,
5
+ type RowData,
6
+ type Updater,
7
+ } from "@tanstack/react-table";
8
+ import {
9
+ useCallback,
10
+ useEffect,
11
+ useLayoutEffect,
12
+ useMemo,
13
+ useRef,
14
+ useState,
15
+ type CSSProperties,
16
+ type DragEvent as ReactDragEvent,
17
+ type MouseEvent as ReactMouseEvent,
18
+ type ReactNode,
19
+ } from "react";
20
+ import clsx from "clsx";
21
+ import { Filters } from "./filters";
22
+ import { PaginationBar } from "./pagination-bar";
23
+ import { Loader } from "../loader/loader";
24
+ import type {
25
+ BodyCellProps,
26
+ BodyRowProps,
27
+ DataTableFeatures,
28
+ DataTableMeta,
29
+ DataTableProps,
30
+ FooterCellProps,
31
+ HeaderActionButtonProps,
32
+ HeaderCellProps,
33
+ } from "./types";
34
+ import {
35
+ columnId,
36
+ dataTableFeatures,
37
+ formatAggregated,
38
+ getColumnStyle,
39
+ growColumnWidths,
40
+ isLastPinned,
41
+ normalizeColumnPinningState,
42
+ reorderColumnOrder,
43
+ resolveUpdater,
44
+ SELECT_COLUMN_ID,
45
+ } from "./utils";
46
+ import s from "./data-table.module.css";
47
+ import { Tooltip } from "../tooltip/tooltip";
48
+ import {
49
+ IconArrowsUpDown,
50
+ IconArrowUp,
51
+ IconArrowDown,
52
+ IconChevronRight,
53
+ IconGripVertical,
54
+ IconStack2,
55
+ IconStack3,
56
+ IconPinnedOff,
57
+ IconArrowLeft,
58
+ IconArrowRight,
59
+ } from "@tabler/icons-react";
60
+ import { getScrollbarWidth } from "../../../lib/dom";
61
+ import { Button } from "../button/button";
62
+
63
+ const DEFAULT_PAGE_SIZE_OPTIONS = [10, 20, 50, 100];
64
+ const DEFAULT_PAGINATION = { pageIndex: 0, pageSize: 20 };
65
+ // Stable refs for optional handlers. Inline `= () => {}` defaults allocate a
66
+ // fresh function each render, invalidating any memo that depends on them
67
+ // (notably `meta` below, which passes `onUpdateData` through tanstack).
68
+ const NOOP_FILTER = () => {};
69
+ const NOOP_PAGINATION = () => {};
70
+ const NOOP_UPDATE = () => {};
71
+ const POINTER_STYLE = { cursor: "pointer" } as const;
72
+ // Controls a row can hold. A click on one is that control's, not the row's.
73
+ const ROW_CONTROLS =
74
+ 'a, button, input, select, textarea, label, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [role="menuitem"], [role="checkbox"], [role="radio"], [role="switch"], [role="option"], [role="tab"]';
75
+ const EMPTY_FILTER_VALUES: Record<string, string> = {};
76
+ const ICON_SIZE = 15;
77
+ const SORT_ICON_SIZE = 13;
78
+ const ICON_STROKE = 1.6;
79
+ // Grace period after `isLoading` flips false before committing to the empty
80
+ // state. Eliminates the flash when consumers set isLoading=false a render
81
+ // before populating rows, without making genuinely-empty results feel sluggish.
82
+ const EMPTY_STATE_GRACE_MS = 150;
83
+
84
+ const MIN_SKELETON_ROWS = 1;
85
+ const useIsomorphicLayoutEffect =
86
+ typeof window === "undefined" ? useEffect : useLayoutEffect;
87
+
88
+ /**
89
+ * A group row's aggregate for a column without its own `aggregatedCell`.
90
+ * Module-level so the table's `defaultColumn` stays one reference: a new one
91
+ * each render would rebuild every column. The context is typed on the two
92
+ * fields it reads, so it fits every table's rows despite tanstack's invariant
93
+ * row type.
94
+ */
95
+ const DEFAULT_COLUMN = {
96
+ aggregatedCell: ({
97
+ column,
98
+ getValue,
99
+ }: {
100
+ column: { columnDef: { aggregationFn?: unknown } };
101
+ getValue: () => unknown;
102
+ }) => {
103
+ const text = formatAggregated(getValue(), column.columnDef.aggregationFn);
104
+ return text === null ? null : (
105
+ <span className={s.cell_aggregated}>{text}</span>
106
+ );
107
+ },
108
+ };
109
+
110
+ export const DataTable = <TData extends { id: string }>({
111
+ data,
112
+ columns,
113
+ isLoading = false,
114
+ emptyMessage = "No results found.",
115
+
116
+ filters = [],
117
+ filterValues = EMPTY_FILTER_VALUES,
118
+ onFilterChange = NOOP_FILTER,
119
+
120
+ sorting,
121
+ onSortingChange,
122
+ manualSorting = false,
123
+
124
+ showPagination = true,
125
+ pagination = DEFAULT_PAGINATION,
126
+ onPaginationChange = NOOP_PAGINATION,
127
+ manualPagination = true,
128
+ totalPages,
129
+ totalCount,
130
+ pageSizeOptions = DEFAULT_PAGE_SIZE_OPTIONS,
131
+ showPageSizeSelect = true,
132
+ rowLabel = "row",
133
+
134
+ rowsSelectable = false,
135
+ getRowCanSelect,
136
+ rowSelection = {},
137
+ onRowSelectionChange,
138
+
139
+ editingRowId = null,
140
+ onUpdateData = NOOP_UPDATE,
141
+
142
+ enableColumnOrdering = false,
143
+ columnOrder,
144
+ onColumnOrderChange,
145
+ enableColumnResizing = false,
146
+ columnSizing,
147
+ onColumnSizingChange,
148
+ enableColumnPinning = false,
149
+ columnPinning,
150
+ onColumnPinningChange,
151
+ enableRowOrdering = false,
152
+ onRowOrderChange,
153
+ columnVisibility,
154
+ onColumnVisibilityChange,
155
+
156
+ enableGrouping = false,
157
+ grouping,
158
+ onGroupingChange,
159
+ expanded,
160
+ onExpandedChange,
161
+
162
+ defaultColumnPinning,
163
+
164
+ showVerticalBorders = false,
165
+
166
+ onRow,
167
+ paginationExtra,
168
+ paginationLabel,
169
+ className,
170
+ }: DataTableProps<TData>) => {
171
+ // Collapse the filter row into a button + modal once it no longer fits inline.
172
+
173
+ // ── Table meta ──────────────────────────────────────────────────────────────
174
+ const meta: DataTableMeta = useMemo(
175
+ () => ({ editingRowId, updateData: onUpdateData }),
176
+ [editingRowId, onUpdateData],
177
+ );
178
+
179
+ const shouldPinSelectionColumn =
180
+ rowsSelectable &&
181
+ columns.some((columnDef) => columnId(columnDef) === SELECT_COLUMN_ID);
182
+
183
+ const resolvedControlledColumnPinning = useMemo(
184
+ () =>
185
+ columnPinning === undefined
186
+ ? undefined
187
+ : normalizeColumnPinningState(
188
+ columnPinning,
189
+ shouldPinSelectionColumn,
190
+ defaultColumnPinning,
191
+ ),
192
+ [columnPinning, shouldPinSelectionColumn, defaultColumnPinning],
193
+ );
194
+
195
+ // Uncontrolled pinning starts from the default pins.
196
+ const initialColumnPinning = useMemo(
197
+ () =>
198
+ enableColumnPinning && columnPinning === undefined
199
+ ? normalizeColumnPinningState(
200
+ {
201
+ start: defaultColumnPinning?.start ?? [],
202
+ end: defaultColumnPinning?.end ?? [],
203
+ },
204
+ shouldPinSelectionColumn,
205
+ defaultColumnPinning,
206
+ )
207
+ : undefined,
208
+ [
209
+ enableColumnPinning,
210
+ columnPinning,
211
+ shouldPinSelectionColumn,
212
+ defaultColumnPinning,
213
+ ],
214
+ );
215
+
216
+ const handleColumnPinningChange = useCallback(
217
+ (updater: Updater<ColumnPinningState>) => {
218
+ if (!onColumnPinningChange) return;
219
+
220
+ onColumnPinningChange((prev) => {
221
+ const normalizedPrev = normalizeColumnPinningState(
222
+ prev,
223
+ shouldPinSelectionColumn,
224
+ defaultColumnPinning,
225
+ ) ?? { start: [], end: [] };
226
+ const next = resolveUpdater(updater, normalizedPrev);
227
+
228
+ // Newly end-pinned columns are inserted on the inner edge (closer
229
+ // to the center) so the recently-pinned column visually slides in
230
+ // next to the body, leaving previously-pinned columns flush against
231
+ // the viewport edge.
232
+ const addedToEnd = next.end.filter(
233
+ (id) => !normalizedPrev.end.includes(id),
234
+ );
235
+ const keptInEnd = next.end.filter((id) =>
236
+ normalizedPrev.end.includes(id),
237
+ );
238
+
239
+ return (
240
+ normalizeColumnPinningState(
241
+ { start: next.start, end: [...addedToEnd, ...keptInEnd] },
242
+ shouldPinSelectionColumn,
243
+ defaultColumnPinning,
244
+ ) ?? { start: [], end: [] }
245
+ );
246
+ });
247
+ },
248
+ [onColumnPinningChange, shouldPinSelectionColumn, defaultColumnPinning],
249
+ );
250
+
251
+ // ── TanStack table instance ─────────────────────────────────────────────────
252
+ // Filtering is delegated to the consumer (see `useDataTable.filterFn`), so
253
+ // `dataTableFeatures` registers no filtering - rows arrive pre-filtered.
254
+ const table = useTable<DataTableFeatures, TData>({
255
+ features: dataTableFeatures,
256
+ data,
257
+ columns,
258
+ defaultColumn: DEFAULT_COLUMN,
259
+ enableRowSelection: rowsSelectable ? (getRowCanSelect ?? true) : false,
260
+ enableColumnResizing,
261
+ enableColumnPinning,
262
+ enableGrouping,
263
+ columnResizeMode: "onChange",
264
+ state: {
265
+ sorting,
266
+ ...(showPagination && { pagination }),
267
+ ...(rowsSelectable && { rowSelection }),
268
+ ...(enableColumnOrdering && columnOrder && { columnOrder }),
269
+ ...(enableColumnResizing && columnSizing && { columnSizing }),
270
+ ...(enableColumnPinning &&
271
+ resolvedControlledColumnPinning && {
272
+ columnPinning: resolvedControlledColumnPinning,
273
+ }),
274
+ ...(columnVisibility && { columnVisibility }),
275
+ ...(enableGrouping && grouping && { grouping }),
276
+ ...(enableGrouping && expanded !== undefined && { expanded }),
277
+ },
278
+ initialState: {
279
+ ...(enableColumnPinning &&
280
+ initialColumnPinning && {
281
+ columnPinning: initialColumnPinning,
282
+ }),
283
+ },
284
+ onSortingChange,
285
+ ...(showPagination && {
286
+ onPaginationChange: (updater) =>
287
+ onPaginationChange(resolveUpdater(updater, pagination)),
288
+ }),
289
+ ...(rowsSelectable && onRowSelectionChange && { onRowSelectionChange }),
290
+ ...(enableColumnOrdering && onColumnOrderChange && { onColumnOrderChange }),
291
+ ...(enableColumnResizing &&
292
+ onColumnSizingChange && { onColumnSizingChange }),
293
+ ...(enableColumnPinning &&
294
+ onColumnPinningChange && {
295
+ onColumnPinningChange: handleColumnPinningChange,
296
+ }),
297
+ ...(onColumnVisibilityChange && { onColumnVisibilityChange }),
298
+ ...(enableGrouping && onGroupingChange && { onGroupingChange }),
299
+ ...(enableGrouping && onExpandedChange && { onExpandedChange }),
300
+ getRowId: (row) => row.id,
301
+ // A page at a time: the table counts pages from what it is told - the page
302
+ // count, else the row count, else unknown (-1, which keeps "next" open).
303
+ // Every row: it pages them itself. Without pagination, nothing is paged.
304
+ manualPagination: !showPagination || manualPagination,
305
+ ...(showPagination &&
306
+ manualPagination && {
307
+ pageCount: totalPages ?? (totalCount === undefined ? -1 : undefined),
308
+ rowCount: totalCount,
309
+ }),
310
+ // The page and the open groups are the user's: an edit, a refetch, or a
311
+ // new grouping must not send them back to page one or close every group.
312
+ autoResetPageIndex: false,
313
+ autoResetExpanded: false,
314
+ // Keep grouped columns in place so header controls stay spatially stable.
315
+ groupedColumnMode: false,
316
+ manualSorting,
317
+ meta,
318
+ });
319
+
320
+ // ── Column drag-and-drop reorder (HTML5 native, no extra deps) ──────────────
321
+ const [draggedColumnId, setDraggedColumnId] = useState<string | null>(null);
322
+ const [dropTargetColumnId, setDropTargetColumnId] = useState<string | null>(
323
+ null,
324
+ );
325
+
326
+ const handleColumnDrop = useCallback(
327
+ (sourceId: string, targetId: string) => {
328
+ if (sourceId === targetId) return;
329
+ const targetCol = table.getColumn(targetId);
330
+ // Refuse drops onto fixed columns (e.g. the row-select column) so they
331
+ // stay anchored in their position.
332
+ if (targetCol && targetCol.getCanHide() === false) return;
333
+ const current =
334
+ columnOrder && columnOrder.length
335
+ ? columnOrder
336
+ : table.getAllLeafColumns().map((c) => c.id);
337
+ const next = reorderColumnOrder(current, sourceId, targetId);
338
+ table.setColumnOrder(next);
339
+ },
340
+ [columnOrder, table],
341
+ );
342
+
343
+ const handleDragEnd = useCallback(() => {
344
+ setDraggedColumnId(null);
345
+ setDropTargetColumnId(null);
346
+ }, []);
347
+
348
+ const [draggedRowId, setDraggedRowId] = useState<string | null>(null);
349
+ const [dropTargetRowId, setDropTargetRowId] = useState<string | null>(null);
350
+
351
+ const handleDragStartRow = useCallback((id: string) => {
352
+ setDraggedRowId(id);
353
+ }, []);
354
+
355
+ const handleDragOverRow = useCallback((id: string | null) => {
356
+ setDropTargetRowId(id);
357
+ }, []);
358
+
359
+ const handleDragEndRow = useCallback(() => {
360
+ setDraggedRowId(null);
361
+ setDropTargetRowId(null);
362
+ }, []);
363
+
364
+ const handleDropRow = useCallback(
365
+ (draggedId: string, targetId: string) => {
366
+ const draggedRow = table.getRow(draggedId);
367
+ const targetRow = table.getRow(targetId);
368
+ if (draggedRow && targetRow) {
369
+ onRowOrderChange?.(draggedRow.original, targetRow.original);
370
+ }
371
+ },
372
+ [onRowOrderChange, table],
373
+ );
374
+
375
+ // ── Sync header/body scrolling ──────────────────────────────────────────────
376
+ // The header lives in its own `overflow:hidden` container; we drive its
377
+ // scrollLeft from the body's scrollLeft on every scroll event so pinned
378
+ // columns stay perfectly aligned with their body counterparts.
379
+ const headerRef = useRef<HTMLDivElement>(null);
380
+ const bodyRef = useRef<HTMLDivElement>(null);
381
+ const bodyTableRef = useRef<HTMLTableElement>(null);
382
+ const skeletonRowRef = useRef<HTMLTableRowElement>(null);
383
+ const rows = table.getRowModel().rows;
384
+ const headerCount = table.getFlatHeaders().length;
385
+ const totalWidth = table.getTotalSize();
386
+ const {
387
+ columnPinning: tableColumnPinning,
388
+ columnSizing: tableColumnSizing,
389
+ columnOrder: tableColumnOrder,
390
+ columnVisibility: tableColumnVisibility,
391
+ grouping: tableGrouping,
392
+ } = table.state;
393
+ const [bodyViewportWidth, setBodyViewportWidth] = useState(0);
394
+ const bodyViewportWidthRef = useRef(0);
395
+ // Body wrap height tracked separately so the loading skeleton can render
396
+ // exactly the count of rows that fits the visible body. Avoids the
397
+ // "skeleton overflows + body wrap scrolls" feel during cold load.
398
+ const [bodyViewportHeight, setBodyViewportHeight] = useState(0);
399
+ const bodyViewportHeightRef = useRef(0);
400
+ const [skeletonRowHeight, setSkeletonRowHeight] = useState(0);
401
+ const skeletonRowHeightRef = useRef(0);
402
+
403
+ const commitBodyViewportWidth = useCallback((nextWidth: number) => {
404
+ if (bodyViewportWidthRef.current === nextWidth) return;
405
+ bodyViewportWidthRef.current = nextWidth;
406
+ setBodyViewportWidth(nextWidth);
407
+ }, []);
408
+
409
+ const commitBodyViewportHeight = useCallback((nextHeight: number) => {
410
+ if (bodyViewportHeightRef.current === nextHeight) return;
411
+ bodyViewportHeightRef.current = nextHeight;
412
+ setBodyViewportHeight(nextHeight);
413
+ }, []);
414
+
415
+ const commitSkeletonRowHeight = useCallback((nextHeight: number) => {
416
+ if (nextHeight <= 0 || skeletonRowHeightRef.current === nextHeight) return;
417
+ skeletonRowHeightRef.current = nextHeight;
418
+ setSkeletonRowHeight(nextHeight);
419
+ }, []);
420
+
421
+ const syncHeaderMetrics = useCallback(() => {
422
+ const body = bodyRef.current;
423
+ const header = headerRef.current;
424
+ if (!body || !header) return;
425
+
426
+ const scrollbarW = getScrollbarWidth();
427
+ const hasScroll = body.scrollHeight > body.clientHeight;
428
+ const paddingRight = hasScroll ? `${scrollbarW}px` : "0px";
429
+
430
+ header.style.paddingRight = paddingRight;
431
+ header.parentElement?.style.setProperty(
432
+ "--header-padding-right",
433
+ paddingRight,
434
+ );
435
+ header.parentElement?.setAttribute("data-has-scroll", hasScroll.toString());
436
+ // Mirror onto the body wrap so CSS can release the reserved scrollbar gutter
437
+ // when there's no vertical overflow (no blank strip on a few-row table).
438
+ body.setAttribute("data-has-scroll", hasScroll.toString());
439
+
440
+ // Re-sync horizontal scroll position after width changes so pinned
441
+ // columns stay perfectly aligned with their body counterparts.
442
+ header.scrollLeft = body.scrollLeft;
443
+ commitBodyViewportWidth(body.clientWidth);
444
+ commitBodyViewportHeight(body.clientHeight);
445
+ }, [commitBodyViewportWidth, commitBodyViewportHeight]);
446
+
447
+ useIsomorphicLayoutEffect(() => {
448
+ syncHeaderMetrics();
449
+ }, [
450
+ rows.length,
451
+ headerCount,
452
+ totalWidth,
453
+ tableColumnPinning,
454
+ tableColumnSizing,
455
+ tableColumnOrder,
456
+ tableColumnVisibility,
457
+ tableGrouping,
458
+ syncHeaderMetrics,
459
+ ]);
460
+
461
+ useIsomorphicLayoutEffect(() => {
462
+ const body = bodyRef.current;
463
+ if (!body) return;
464
+ if (typeof ResizeObserver === "undefined") return;
465
+
466
+ const observer = new ResizeObserver(syncHeaderMetrics);
467
+ observer.observe(body);
468
+ if (bodyTableRef.current) observer.observe(bodyTableRef.current);
469
+
470
+ return () => {
471
+ observer.disconnect();
472
+ };
473
+ }, [syncHeaderMetrics, rows.length, isLoading]);
474
+
475
+ useEffect(() => {
476
+ const body = bodyRef.current;
477
+ const header = headerRef.current;
478
+ if (!body || !header) return;
479
+
480
+ const syncFromBody = () => {
481
+ if (header.scrollLeft !== body.scrollLeft) {
482
+ header.scrollLeft = body.scrollLeft;
483
+ }
484
+ };
485
+
486
+ const syncFromHeader = () => {
487
+ if (body.scrollLeft !== header.scrollLeft) {
488
+ body.scrollLeft = header.scrollLeft;
489
+ }
490
+ };
491
+
492
+ body.addEventListener("scroll", syncFromBody, { passive: true });
493
+ header.addEventListener("scroll", syncFromHeader, { passive: true });
494
+
495
+ return () => {
496
+ body.removeEventListener("scroll", syncFromBody);
497
+ header.removeEventListener("scroll", syncFromHeader);
498
+ };
499
+ }, []);
500
+
501
+ // ── Derived UI state ────────────────────────────────────────────────────────
502
+ // Defer the empty state by a tick after a loading-to-idle transition so the
503
+ // loader doesn't flicker into "no results" for one paint before rows land.
504
+ // Genuinely empty results (no in-flight load) commit immediately on mount.
505
+ const isRowsEmpty = rows.length === 0;
506
+ const [showEmptyState, setShowEmptyState] = useState(
507
+ () => !isLoading && isRowsEmpty,
508
+ );
509
+ const wasLoadingRef = useRef(isLoading);
510
+
511
+ // wasLoadingRef is intentionally omitted from the dep array: it's a ref used
512
+ // to track the previous value of isLoading across renders without triggering
513
+ // re-runs. React guarantees ref objects are stable across the component lifetime.
514
+ useEffect(() => {
515
+ const wasLoading = wasLoadingRef.current;
516
+ wasLoadingRef.current = isLoading;
517
+
518
+ if (isLoading || !isRowsEmpty) {
519
+ setShowEmptyState(false);
520
+ return;
521
+ }
522
+ if (!wasLoading) {
523
+ setShowEmptyState(true);
524
+ return;
525
+ }
526
+ const id = window.setTimeout(
527
+ () => setShowEmptyState(true),
528
+ EMPTY_STATE_GRACE_MS,
529
+ );
530
+ return () => window.clearTimeout(id);
531
+ }, [isLoading, isRowsEmpty]);
532
+
533
+ // Single tab-like discriminator drives the body - loader, empty, or content.
534
+ // While loading OR while bridging the loading-to-empty grace window, the
535
+ // loader stays visible to avoid the brief "no results" flash.
536
+ const view: "loader" | "empty" | "content" =
537
+ isLoading || (isRowsEmpty && !showEmptyState)
538
+ ? "loader"
539
+ : isRowsEmpty
540
+ ? "empty"
541
+ : "content";
542
+
543
+ useIsomorphicLayoutEffect(() => {
544
+ if (view !== "loader") return;
545
+ const row = skeletonRowRef.current;
546
+ if (!row) return;
547
+
548
+ const measureRow = () => {
549
+ commitSkeletonRowHeight(Math.ceil(row.getBoundingClientRect().height));
550
+ };
551
+
552
+ measureRow();
553
+ if (typeof ResizeObserver === "undefined") return;
554
+
555
+ const observer = new ResizeObserver(measureRow);
556
+ observer.observe(row);
557
+
558
+ return () => {
559
+ observer.disconnect();
560
+ };
561
+ }, [commitSkeletonRowHeight, view]);
562
+
563
+ const selectedCount = rowsSelectable
564
+ ? table.getSelectedRowModel().flatRows.length
565
+ : 0;
566
+ const headerGroups = table.getHeaderGroups();
567
+ const visibleLeafColumns = table.getVisibleLeafColumns();
568
+ // The rows of footers columns define, e.g. a total from
569
+ // `column.getAggregationValue()`; none when no column has a footer.
570
+ const footerGroups = table
571
+ .getFooterGroups()
572
+ .filter((group) =>
573
+ group.headers.some(
574
+ (header) =>
575
+ !header.isPlaceholder && header.column.columnDef.footer !== undefined,
576
+ ),
577
+ );
578
+
579
+ const skeletonRowCount =
580
+ bodyViewportHeight > 0 && skeletonRowHeight > 0
581
+ ? Math.max(
582
+ MIN_SKELETON_ROWS,
583
+ Math.floor(bodyViewportHeight / skeletonRowHeight),
584
+ )
585
+ : MIN_SKELETON_ROWS;
586
+
587
+ const columnExtraWidths = growColumnWidths(
588
+ visibleLeafColumns,
589
+ bodyViewportWidth - totalWidth,
590
+ );
591
+
592
+ const tableWidth = Math.max(totalWidth, bodyViewportWidth);
593
+
594
+ // Columns that fit the body never scroll it sideways. The body's width is
595
+ // read from clientWidth, which rounds to the nearest pixel, so on a
596
+ // fractional layout (page zoom, display scaling) the table can overhang the
597
+ // body by under a pixel. Left to `overflow-x: auto`, that sliver shows a
598
+ // horizontal scrollbar, which shortens the body, flips its scrollbar gutter
599
+ // and starts another resize.
600
+ const columnsFit = bodyViewportWidth > 0 && totalWidth <= bodyViewportWidth;
601
+
602
+ // Match the table element width to the measured column widths. This keeps
603
+ // header, body, and skeleton rows on the same sizing contract during resize.
604
+ const tableSizingStyle: CSSProperties = {
605
+ width: `${tableWidth}px`,
606
+ minWidth: `${totalWidth}px`,
607
+ };
608
+
609
+ const bodySkeletonStyle: CSSProperties = {
610
+ height: "var(--spacing-9)",
611
+ };
612
+
613
+ const selectSkeletonStyle: CSSProperties = {
614
+ width: "var(--data-table-selection-control-size, var(--spacing-9))",
615
+ height: "var(--data-table-selection-control-size, var(--spacing-9))",
616
+ };
617
+
618
+ const tableClass = clsx(
619
+ s.table,
620
+ showVerticalBorders && s.table_vertical_borders,
621
+ );
622
+
623
+ return (
624
+ <div className={clsx(s.root, className)}>
625
+ {/* Filters - inline row on desktop; a "Filters" button + modal once the
626
+ row no longer fits (so phones aren't buried under stacked fields). */}
627
+ {filters.length > 0 && (
628
+ <Filters
629
+ fields={filters}
630
+ values={filterValues}
631
+ onChange={onFilterChange}
632
+ />
633
+ )}
634
+
635
+ {/* Content wrap - grows to fill remaining height.
636
+ table_shell fills it; pagination pins to the bottom via margin-top:auto */}
637
+ <div className={s.content_wrap}>
638
+ {/* Table: detached header pill + scrollable body */}
639
+ <div
640
+ className={clsx(
641
+ s.table_shell,
642
+ !showPagination && s.table_shell_no_pagination,
643
+ )}
644
+ >
645
+ {/* Pinned header pill - scroll synced to body via JS */}
646
+ <div className={s.table_header_container}>
647
+ <div className={s.table_header_wrap} ref={headerRef}>
648
+ <table className={tableClass} style={tableSizingStyle}>
649
+ <thead>
650
+ {headerGroups.map((hg) => (
651
+ <tr key={hg.id}>
652
+ {hg.headers.map((header) => (
653
+ <HeaderCell<TData>
654
+ key={header.id}
655
+ header={header}
656
+ extraWidth={columnExtraWidths[header.column.id] ?? 0}
657
+ enableColumnOrdering={enableColumnOrdering}
658
+ enableColumnResizing={enableColumnResizing}
659
+ enableColumnPinning={enableColumnPinning}
660
+ enableGrouping={enableGrouping}
661
+ draggedColumnId={draggedColumnId}
662
+ dropTargetColumnId={dropTargetColumnId}
663
+ onDragStartCol={setDraggedColumnId}
664
+ onDragEndCol={handleDragEnd}
665
+ onDragOverCol={setDropTargetColumnId}
666
+ onDropCol={handleColumnDrop}
667
+ />
668
+ ))}
669
+ </tr>
670
+ ))}
671
+ </thead>
672
+ </table>
673
+ </div>
674
+ <div className={s.header_padding_mask} />
675
+ </div>
676
+
677
+ {/* Scrollable body - only this element scrolls. The body is a
678
+ single switch over `view`: at most one branch ever renders, the
679
+ other two are unmounted entirely. */}
680
+ <div
681
+ className={s.table_body_wrap}
682
+ style={{ pointerEvents: isLoading ? "none" : undefined }}
683
+ data-fits={columnsFit}
684
+ ref={bodyRef}
685
+ >
686
+ {view === "loader" && (
687
+ <table className={tableClass} style={tableSizingStyle}>
688
+ <tbody>
689
+ {Array.from({ length: skeletonRowCount }).map(
690
+ (_, rowIndex) => (
691
+ <tr
692
+ key={`skeleton-${rowIndex}`}
693
+ ref={rowIndex === 0 ? skeletonRowRef : undefined}
694
+ >
695
+ {visibleLeafColumns.map((column) => {
696
+ const isPinned = column.getIsPinned();
697
+ const isLastPinnedCol =
698
+ isPinned && isLastPinned(column);
699
+ const isSelectColumn = column.id === SELECT_COLUMN_ID;
700
+
701
+ return (
702
+ <td
703
+ key={column.id}
704
+ className={clsx(
705
+ isSelectColumn && s.col_select,
706
+ isPinned === "start" && s.col_pinned_start,
707
+ isPinned === "end" && s.col_pinned_end,
708
+ isLastPinnedCol && s.col_pinned_last,
709
+ )}
710
+ style={getColumnStyle(
711
+ column,
712
+ column.getSize(),
713
+ columnExtraWidths[column.id] ?? 0,
714
+ )}
715
+ >
716
+ <div className={s.td_inner}>
717
+ <Loader
718
+ variant="skeleton"
719
+ className={
720
+ isSelectColumn
721
+ ? s.loading_select_skeleton
722
+ : undefined
723
+ }
724
+ style={
725
+ isSelectColumn
726
+ ? selectSkeletonStyle
727
+ : bodySkeletonStyle
728
+ }
729
+ />
730
+ </div>
731
+ </td>
732
+ );
733
+ })}
734
+ </tr>
735
+ ),
736
+ )}
737
+ </tbody>
738
+ </table>
739
+ )}
740
+ {view === "empty" && (
741
+ <div className={s.state_overlay}>
742
+ <p className={s.empty_msg}>{emptyMessage}</p>
743
+ </div>
744
+ )}
745
+ {view === "content" && (
746
+ <table
747
+ className={tableClass}
748
+ style={tableSizingStyle}
749
+ ref={bodyTableRef}
750
+ >
751
+ <tbody>
752
+ {rows.map((row) => (
753
+ <BodyRow<TData>
754
+ key={row.id}
755
+ row={row}
756
+ editingRowId={editingRowId}
757
+ onRow={onRow}
758
+ enableGrouping={enableGrouping}
759
+ columnExtraWidths={columnExtraWidths}
760
+ enableRowOrdering={enableRowOrdering}
761
+ draggedRowId={draggedRowId}
762
+ dropTargetRowId={dropTargetRowId}
763
+ onDragStartRow={handleDragStartRow}
764
+ onDragOverRow={handleDragOverRow}
765
+ onDragEndRow={handleDragEndRow}
766
+ onDropRow={handleDropRow}
767
+ />
768
+ ))}
769
+ </tbody>
770
+ {footerGroups.length > 0 && (
771
+ <tfoot>
772
+ {footerGroups.map((group) => (
773
+ <tr key={group.id}>
774
+ {group.headers.map((header) => (
775
+ <FooterCell<TData>
776
+ key={header.id}
777
+ header={header}
778
+ extraWidth={
779
+ columnExtraWidths[header.column.id] ?? 0
780
+ }
781
+ />
782
+ ))}
783
+ </tr>
784
+ ))}
785
+ </tfoot>
786
+ )}
787
+ </table>
788
+ )}
789
+ </div>
790
+ </div>
791
+
792
+ {/* Pagination - margin-top:auto pins it to the bottom of content_wrap */}
793
+ {showPagination && (
794
+ <PaginationBar
795
+ table={table}
796
+ pagination={pagination}
797
+ onPaginationChange={onPaginationChange}
798
+ pageSizeOptions={pageSizeOptions}
799
+ showPageSizeSelect={showPageSizeSelect}
800
+ isLoading={view === "loader"}
801
+ totalCount={totalCount}
802
+ rowLabel={rowLabel}
803
+ rowsSelectable={rowsSelectable}
804
+ selectedCount={selectedCount}
805
+ label={paginationLabel}
806
+ extra={paginationExtra}
807
+ />
808
+ )}
809
+ </div>
810
+ </div>
811
+ );
812
+ };
813
+
814
+ // ─────────────────────────────────────────────────────────────────────────────
815
+ // HeaderActionButton - local compact icon button for the table header.
816
+ // Keeps the header tight (no library Button padding) without depending on the
817
+ // Button component while still mirroring its hover/focus visuals.
818
+ // ─────────────────────────────────────────────────────────────────────────────
819
+
820
+ const HeaderActionButton = ({
821
+ onClick,
822
+ ariaLabel,
823
+ ariaPressed,
824
+ active = false,
825
+ children,
826
+ }: HeaderActionButtonProps) => {
827
+ return (
828
+ <Button
829
+ type="button"
830
+ variant="ghost"
831
+ size="sm"
832
+ layout="box"
833
+ className={s.icon_btn}
834
+ onClick={onClick}
835
+ aria-label={ariaLabel}
836
+ aria-pressed={ariaPressed}
837
+ draggable={false}
838
+ isActive={active}
839
+ >
840
+ {children}
841
+ </Button>
842
+ );
843
+ };
844
+
845
+ // ─────────────────────────────────────────────────────────────────────────────
846
+ // HeaderCell - one <th> with sort, group, pin, drag, and resize affordances.
847
+ // ─────────────────────────────────────────────────────────────────────────────
848
+
849
+ const HeaderCell = <TData extends RowData>({
850
+ header,
851
+ extraWidth,
852
+ enableColumnOrdering,
853
+ enableColumnResizing,
854
+ enableColumnPinning,
855
+ enableGrouping,
856
+ draggedColumnId,
857
+ dropTargetColumnId,
858
+ onDragStartCol,
859
+ onDragEndCol,
860
+ onDragOverCol,
861
+ onDropCol,
862
+ }: HeaderCellProps<TData>) => {
863
+ const column = header.column;
864
+ const colMeta = column.columnDef.meta;
865
+ const align = colMeta?.align ?? "left";
866
+ // Fixed columns (e.g. row-select) opt out of hide-ability AND of being a
867
+ // drag source / drop target so they stay anchored in their position.
868
+ const isFixed = column.getCanHide() === false;
869
+ const canDrag = enableColumnOrdering && !isFixed;
870
+ const canResize = enableColumnResizing && column.getCanResize();
871
+ const canPin = enableColumnPinning && column.getCanPin() && !isFixed;
872
+ const canGroup = enableGrouping && column.getCanGroup() && !isFixed;
873
+ const canSort = column.getCanSort();
874
+ const isPinned = column.getIsPinned();
875
+ const isLastPinnedCol = isPinned && isLastPinned(column);
876
+ const isBeingDragged = draggedColumnId === column.id;
877
+ const isDropTarget =
878
+ dropTargetColumnId === column.id &&
879
+ draggedColumnId !== column.id &&
880
+ !isFixed;
881
+ const isGrouped = enableGrouping && column.getIsGrouped();
882
+ const isSelectColumn = column.id === SELECT_COLUMN_ID;
883
+ const sortState = column.getIsSorted();
884
+ const hasHeaderActions = canSort || canGroup || canPin;
885
+ const sortTooltip =
886
+ sortState === "asc"
887
+ ? "Sort descending"
888
+ : sortState === "desc"
889
+ ? "Clear sorting"
890
+ : "Sort ascending";
891
+
892
+ const handleDragStart = (e: ReactDragEvent<HTMLTableCellElement>) => {
893
+ e.dataTransfer.effectAllowed = "move";
894
+ e.dataTransfer.setData("text/plain", column.id);
895
+ onDragStartCol(column.id);
896
+ };
897
+
898
+ const handleDragOver = (e: ReactDragEvent<HTMLTableCellElement>) => {
899
+ if (!draggedColumnId || draggedColumnId === column.id || isFixed) return;
900
+ e.preventDefault();
901
+ e.dataTransfer.dropEffect = "move";
902
+ if (dropTargetColumnId !== column.id) onDragOverCol(column.id);
903
+ };
904
+
905
+ const handleDragLeave = () => {
906
+ if (dropTargetColumnId === column.id) onDragOverCol(null);
907
+ };
908
+
909
+ const handleDrop = (e: ReactDragEvent<HTMLTableCellElement>) => {
910
+ e.preventDefault();
911
+ if (!draggedColumnId || isFixed) return;
912
+ onDropCol(draggedColumnId, column.id);
913
+ onDragEndCol();
914
+ };
915
+
916
+ const sortIcon = !sortState ? (
917
+ <IconArrowsUpDown size={SORT_ICON_SIZE} stroke={ICON_STROKE} />
918
+ ) : sortState === "asc" ? (
919
+ <IconArrowUp size={SORT_ICON_SIZE} stroke={ICON_STROKE} />
920
+ ) : (
921
+ <IconArrowDown size={SORT_ICON_SIZE} stroke={ICON_STROKE} />
922
+ );
923
+
924
+ return (
925
+ <th
926
+ colSpan={header.colSpan}
927
+ onDragOver={canDrag ? handleDragOver : undefined}
928
+ onDragLeave={canDrag ? handleDragLeave : undefined}
929
+ onDrop={canDrag ? handleDrop : undefined}
930
+ className={clsx(
931
+ colMeta?.headerClassName,
932
+ s[`align_${align}`],
933
+ isSelectColumn && s.col_select,
934
+ isPinned === "start" && s.col_pinned_start,
935
+ isPinned === "end" && s.col_pinned_end,
936
+ isLastPinnedCol && s.col_pinned_last,
937
+ isBeingDragged && s.col_dragging,
938
+ isDropTarget && s.col_drop_target,
939
+ )}
940
+ style={getColumnStyle(column, header.getSize(), extraWidth)}
941
+ >
942
+ {!header.isPlaceholder && (
943
+ <div className={s.th_inner}>
944
+ {canDrag && (
945
+ <span
946
+ className={s.drag_handle}
947
+ aria-hidden
948
+ draggable
949
+ onDragStart={handleDragStart}
950
+ onDragEnd={onDragEndCol}
951
+ >
952
+ <IconGripVertical size={ICON_SIZE} stroke={ICON_STROKE} />
953
+ </span>
954
+ )}
955
+ {isSelectColumn ? (
956
+ <FlexRender header={header} />
957
+ ) : (
958
+ <span className={s.th_label}>
959
+ <FlexRender header={header} />
960
+ </span>
961
+ )}
962
+ {hasHeaderActions && (
963
+ <span className={s.th_actions}>
964
+ {canSort && (
965
+ <Tooltip content={sortTooltip}>
966
+ <HeaderActionButton
967
+ onClick={column.getToggleSortingHandler()}
968
+ ariaLabel={`Sort by ${column.id}`}
969
+ ariaPressed={!!sortState}
970
+ active={!!sortState}
971
+ >
972
+ {sortIcon}
973
+ </HeaderActionButton>
974
+ </Tooltip>
975
+ )}
976
+ {canGroup && (
977
+ <Tooltip
978
+ content={isGrouped ? "Ungroup column" : "Group by column"}
979
+ >
980
+ <HeaderActionButton
981
+ onClick={column.getToggleGroupingHandler()}
982
+ ariaLabel={
983
+ isGrouped ? "Ungroup column" : "Group by this column"
984
+ }
985
+ ariaPressed={isGrouped}
986
+ active={isGrouped}
987
+ >
988
+ {isGrouped ? (
989
+ <IconStack3 size={ICON_SIZE} stroke={ICON_STROKE} />
990
+ ) : (
991
+ <IconStack2 size={ICON_SIZE} stroke={ICON_STROKE} />
992
+ )}
993
+ </HeaderActionButton>
994
+ </Tooltip>
995
+ )}
996
+ {canPin && !isPinned && (
997
+ <>
998
+ <Tooltip content="Pin left">
999
+ <HeaderActionButton
1000
+ onClick={() => column.pin("start")}
1001
+ ariaLabel="Pin left"
1002
+ >
1003
+ <IconArrowLeft size={ICON_SIZE} stroke={ICON_STROKE} />
1004
+ </HeaderActionButton>
1005
+ </Tooltip>
1006
+ <Tooltip content="Pin right">
1007
+ <HeaderActionButton
1008
+ onClick={() => column.pin("end")}
1009
+ ariaLabel="Pin right"
1010
+ >
1011
+ <IconArrowRight size={ICON_SIZE} stroke={ICON_STROKE} />
1012
+ </HeaderActionButton>
1013
+ </Tooltip>
1014
+ </>
1015
+ )}
1016
+ {canPin && isPinned && (
1017
+ <Tooltip content="Unpin column">
1018
+ <HeaderActionButton
1019
+ onClick={() => column.pin(false)}
1020
+ ariaLabel="Unpin column"
1021
+ ariaPressed
1022
+ active
1023
+ >
1024
+ <IconPinnedOff size={ICON_SIZE} stroke={ICON_STROKE} />
1025
+ </HeaderActionButton>
1026
+ </Tooltip>
1027
+ )}
1028
+ </span>
1029
+ )}
1030
+ {canResize && (
1031
+ <span
1032
+ role="separator"
1033
+ aria-orientation="vertical"
1034
+ className={clsx(
1035
+ s.resize_handle,
1036
+ column.getIsResizing() && s.resize_handle_active,
1037
+ )}
1038
+ onMouseDown={header.getResizeHandler()}
1039
+ onTouchStart={header.getResizeHandler()}
1040
+ onClick={(e) => e.stopPropagation()}
1041
+ onDoubleClick={() => column.resetSize()}
1042
+ draggable={false}
1043
+ />
1044
+ )}
1045
+ </div>
1046
+ )}
1047
+ </th>
1048
+ );
1049
+ };
1050
+
1051
+ // ─────────────────────────────────────────────────────────────────────────────
1052
+ // FooterCell - one footer <td>, sized and pinned like the column's body cells.
1053
+ // ─────────────────────────────────────────────────────────────────────────────
1054
+
1055
+ const FooterCell = <TData extends RowData>({
1056
+ header,
1057
+ extraWidth,
1058
+ }: FooterCellProps<TData>) => {
1059
+ const column = header.column;
1060
+ const isPinned = column.getIsPinned();
1061
+ return (
1062
+ <td
1063
+ colSpan={header.colSpan}
1064
+ className={clsx(
1065
+ s[`align_${column.columnDef.meta?.align ?? "left"}`],
1066
+ column.id === SELECT_COLUMN_ID && s.col_select,
1067
+ isPinned === "start" && s.col_pinned_start,
1068
+ isPinned === "end" && s.col_pinned_end,
1069
+ isPinned && isLastPinned(column) && s.col_pinned_last,
1070
+ )}
1071
+ style={getColumnStyle(column, header.getSize(), extraWidth)}
1072
+ >
1073
+ <div className={s.td_inner}>
1074
+ {header.isPlaceholder ? null : <FlexRender footer={header} />}
1075
+ </div>
1076
+ </td>
1077
+ );
1078
+ };
1079
+
1080
+ // ─────────────────────────────────────────────────────────────────────────────
1081
+ // BodyRow - one <tr> + its visible cells.
1082
+ // ─────────────────────────────────────────────────────────────────────────────
1083
+
1084
+ const BodyRow = <TData extends { id: string }>({
1085
+ row,
1086
+ editingRowId,
1087
+ onRow,
1088
+ enableGrouping,
1089
+ columnExtraWidths,
1090
+ enableRowOrdering,
1091
+ draggedRowId,
1092
+ dropTargetRowId,
1093
+ onDragStartRow,
1094
+ onDragOverRow,
1095
+ onDragEndRow,
1096
+ onDropRow,
1097
+ }: BodyRowProps<TData>) => {
1098
+ const isGroup = enableGrouping && row.getIsGrouped();
1099
+ const visibleCells = row.getVisibleCells();
1100
+ const groupSourceCell = isGroup
1101
+ ? visibleCells.find((cell) => cell.getIsGrouped())
1102
+ : undefined;
1103
+ const groupAnchorCellId = isGroup
1104
+ ? (visibleCells.find((cell) => cell.column.id !== SELECT_COLUMN_ID)?.id ??
1105
+ groupSourceCell?.id ??
1106
+ null)
1107
+ : null;
1108
+ const isEditingThisRow =
1109
+ !isGroup && editingRowId !== null && row.original.id === editingRowId;
1110
+
1111
+ // Editing rows host inputs/selects; their clicks must not bubble to row click.
1112
+ // Only a click on the row itself opens it: not one on a control inside it
1113
+ // (a link, a copy button), nor one that reaches it through a portal (a row's
1114
+ // action menu), which React bubbles here from outside the row.
1115
+ const handleRowClick =
1116
+ !isGroup && !isEditingThisRow && onRow
1117
+ ? (event: ReactMouseEvent<HTMLTableRowElement>) => {
1118
+ const target = event.target as Element;
1119
+ if (!event.currentTarget.contains(target)) return;
1120
+ const control = target.closest(ROW_CONTROLS);
1121
+ if (control && event.currentTarget.contains(control)) return;
1122
+ onRow(row.original);
1123
+ }
1124
+ : undefined;
1125
+
1126
+ const canDrag = enableRowOrdering && !isGroup && !isEditingThisRow;
1127
+ const isBeingDragged = draggedRowId === row.id;
1128
+ const isDropTarget =
1129
+ dropTargetRowId === row.id && draggedRowId !== row.id && !isGroup;
1130
+
1131
+ return (
1132
+ <tr
1133
+ draggable={canDrag}
1134
+ onDragStart={(e) => {
1135
+ if (!canDrag) return;
1136
+ e.dataTransfer.effectAllowed = "move";
1137
+ e.dataTransfer.setData("text/plain", row.id);
1138
+ onDragStartRow?.(row.id);
1139
+ }}
1140
+ onDragOver={(e) => {
1141
+ if (!canDrag || !draggedRowId || draggedRowId === row.id) return;
1142
+ e.preventDefault();
1143
+ e.dataTransfer.dropEffect = "move";
1144
+ if (dropTargetRowId !== row.id) onDragOverRow?.(row.id);
1145
+ }}
1146
+ onDragLeave={() => {
1147
+ if (!canDrag) return;
1148
+ if (dropTargetRowId === row.id) onDragOverRow?.(null);
1149
+ }}
1150
+ onDragEnd={() => {
1151
+ if (!canDrag) return;
1152
+ onDragEndRow?.();
1153
+ }}
1154
+ onDrop={(e) => {
1155
+ if (!canDrag) return;
1156
+ e.preventDefault();
1157
+ if (!draggedRowId || draggedRowId === row.id) return;
1158
+ onDropRow?.(draggedRowId, row.id);
1159
+ onDragEndRow?.();
1160
+ }}
1161
+ className={clsx(
1162
+ row.getIsSelected() && s.row_selected,
1163
+ isEditingThisRow && s.row_editing,
1164
+ isGroup && s.row_group,
1165
+ isBeingDragged && s.row_dragging,
1166
+ isDropTarget && s.row_drop_target,
1167
+ )}
1168
+ onClick={handleRowClick}
1169
+ style={handleRowClick ? POINTER_STYLE : undefined}
1170
+ >
1171
+ {visibleCells.map((cell) => (
1172
+ <BodyCell<TData>
1173
+ key={cell.id}
1174
+ cell={cell}
1175
+ extraWidth={columnExtraWidths[cell.column.id] ?? 0}
1176
+ groupSourceCell={groupSourceCell}
1177
+ isGroupAnchorCell={groupAnchorCellId === cell.id}
1178
+ />
1179
+ ))}
1180
+ </tr>
1181
+ );
1182
+ };
1183
+
1184
+ // ─────────────────────────────────────────────────────────────────────────────
1185
+ // BodyCell - one <td>. The group row's anchor cell hosts the expand toggle and
1186
+ // the grouped value; every other cell renders through `FlexRender`, which
1187
+ // picks the aggregated, placeholder, or normal body. Applies meta-driven
1188
+ // align + truncate + pin classes.
1189
+ // ─────────────────────────────────────────────────────────────────────────────
1190
+
1191
+ const BodyCell = <TData extends RowData>({
1192
+ cell,
1193
+ extraWidth,
1194
+ groupSourceCell,
1195
+ isGroupAnchorCell,
1196
+ }: BodyCellProps<TData>) => {
1197
+ const column = cell.column;
1198
+ const colMeta = column.columnDef.meta;
1199
+ const align = colMeta?.align ?? "left";
1200
+ const truncate = colMeta?.truncate ?? true;
1201
+ const isPinned = column.getIsPinned();
1202
+ const isLastPinnedCol = isPinned && isLastPinned(column);
1203
+ const isSelectColumn = column.id === SELECT_COLUMN_ID;
1204
+ const groupedRenderCell =
1205
+ groupSourceCell ?? (cell.getIsGrouped() ? cell : undefined);
1206
+ const groupDepth = groupedRenderCell?.row.depth ?? 0;
1207
+
1208
+ let body: ReactNode;
1209
+ if (groupedRenderCell && isGroupAnchorCell) {
1210
+ body = (
1211
+ <button
1212
+ type="button"
1213
+ className={s.group_toggle}
1214
+ onClick={groupedRenderCell.row.getToggleExpandedHandler()}
1215
+ aria-expanded={groupedRenderCell.row.getIsExpanded()}
1216
+ aria-label={
1217
+ groupedRenderCell.row.getIsExpanded()
1218
+ ? "Collapse group"
1219
+ : "Expand group"
1220
+ }
1221
+ style={
1222
+ groupDepth > 0
1223
+ ? { paddingInlineStart: `calc(${groupDepth} * var(--spacing-4))` }
1224
+ : undefined
1225
+ }
1226
+ >
1227
+ <IconChevronRight
1228
+ size={ICON_SIZE}
1229
+ stroke={ICON_STROKE}
1230
+ className={clsx(
1231
+ s.group_chevron,
1232
+ groupedRenderCell.row.getIsExpanded() && s.group_chevron_open,
1233
+ )}
1234
+ />
1235
+ <span className={s.group_value}>
1236
+ <FlexRender cell={groupedRenderCell} />
1237
+ </span>
1238
+ <span className={s.group_count}>
1239
+ ({groupedRenderCell.row.subRows.length})
1240
+ </span>
1241
+ </button>
1242
+ );
1243
+ } else if (groupedRenderCell && !cell.getIsAggregated()) {
1244
+ // A group row shows its toggle and its aggregates only. Any other column
1245
+ // (the grouped one, or one with nothing to aggregate, like text under
1246
+ // `auto`) stays empty instead of calling its `cell` with no row value.
1247
+ body = null;
1248
+ } else {
1249
+ body = <FlexRender cell={cell} />;
1250
+ }
1251
+
1252
+ // Group rows are full-width summary rows; sticky pinning makes no sense
1253
+ // on them. We strip BOTH the pinned CSS classes AND the inline sticky
1254
+ // offsets. Without this, td:focus-within (which sets position:relative)
1255
+ // would combine with the offset from getColumnStyle and physically shift
1256
+ // the cell when the user clicks the group-toggle chevron.
1257
+ const isGroupRow = !!groupedRenderCell;
1258
+ const baseStyle = getColumnStyle(column, column.getSize(), extraWidth);
1259
+ const cellStyle: CSSProperties = isGroupRow
1260
+ ? {
1261
+ width: baseStyle.width,
1262
+ minWidth: baseStyle.minWidth,
1263
+ maxWidth: baseStyle.maxWidth,
1264
+ }
1265
+ : baseStyle;
1266
+
1267
+ return (
1268
+ <td
1269
+ className={clsx(
1270
+ colMeta?.cellClassName,
1271
+ s[`align_${align}`],
1272
+ isGroupAnchorCell && s.group_anchor_cell,
1273
+ !isGroupRow && isSelectColumn && s.col_select,
1274
+ !isGroupRow && isPinned === "start" && s.col_pinned_start,
1275
+ !isGroupRow && isPinned === "end" && s.col_pinned_end,
1276
+ !isGroupRow && isLastPinnedCol && s.col_pinned_last,
1277
+ )}
1278
+ style={cellStyle}
1279
+ >
1280
+ <div className={clsx(s.td_inner, !truncate && s.td_inner_no_truncate)}>
1281
+ {body}
1282
+ </div>
1283
+ </td>
1284
+ );
1285
+ };