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