"use client" /** * DataTable — generic reusable table (no pagination) * * Column features: * • Resizable — drag trailing-edge handle on any non-locked column * • Drag-to-reorder — drag header cell for free (unpinned) columns * • Pin Left / Pin Right / Unpin — per-column context menu * • Sort Asc / Desc — per-column context menu (sortable columns) * • Wrap Text / Unwrap — per-column context menu * • Per-column quick search * • Row selection (checkboxes + floating bulk action bar) * • Group by (collapsible group rows) * • Hidden columns * * WCAG 2.1 AA: * ✓ aria-sort on sortable * ✓ aria-label on every icon-only button * ✓ Select / Actions columns: sr-only header text + resolved labels for controls * ✓ Row checkboxes: visible on row focus-within, stop row click propagation (default control size; extended hit slop on Checkbox) * ✓ Bulk-action bar: role="status" aria-live="polite" * ✓ Resize handles: `verticalResizeSeparatorAria()` (role="separator" + valuemin/max/now) */ import * as React from "react" import { createPortal } from "react-dom" import { cn } from "../../lib/utils" import { warnIfStackedTableEdgeInset } from "../../lib/table-edge-inset" import { ScrollRegion } from "../ui/scroll-region" import type { ResponsiveAction } from "../ui/responsive-action-row" import { BulkSelectionBar } from "./bulk-selection-bar" import { useSidebarReflowZoom } from "../../hooks/use-sidebar-reflow-zoom" import { type LeoLoadingConfig } from "./leo-loading-row" import type { DataTableProps, ColumnDef } from "./types" import { useTableState } from "./use-table-state" import { DataTableToolbar } from "./data-table-toolbar" import { ColumnHeaderCellContent } from "./column-header-cell" import { DataTableGroupRows } from "./data-table-rows" import { DataTableColgroup, DataTableHeaderRow, DataTableTrailingRows, GroupBarRow, InShellBulkBar, PinnedGroupClone, StickyFootStack, ariaSortFor, floatingPinnedStyle, gridShellClassName, gridWrapperClassName, renderGroupSelect, splitCountFor, theadClassName, useBulkShortcuts, useConditionalRuleColumnKeys, useDataTableRowModel, useEscapeClearsSelection, useFilteredColumnKeys, useGroupDisplay, useHeaderFocusCapture, usePinnedScrollHint, useScrollportSync, useSelectColumnWidth, } from "./data-table-inner-parts" import { useDataTableReorder } from "./use-data-table-reorder" import { useFloatingHeader } from "./use-data-table-floating-header" import { usePinnedGroupHeader } from "./use-data-table-pinned-group" export { DataTableToolbar } from "./data-table-toolbar" export { ROW_DRAG_COLUMN, withRowDragColumn } from "./row-reorder-handle" export { LeoLoadingRow, type LeoLoadingConfig, type LeoLoadingRowProps, type LeoLoadingRowSpec, type LeoLoadingState, } from "./leo-loading-row" // ───────────────────────────────────────────────────────────────────────────── // DataTable // ───────────────────────────────────────────────────────────────────────────── export interface DataTableExtendedProps> extends DataTableProps { /** Slot for a toolbar drawer button + drawer itself (e.g. TablePropertiesDrawer) */ toolbarSlot?: (state: ReturnType>) => React.ReactNode /** Record commands rendered after Properties. See `HubTableProps.toolbarActions`. */ toolbarActions?: ResponsiveAction[] /** Slot rendered inside the floating bulk-action bar (after the count badge) */ bulkActionsSlot?: (selected: Set, rows: TData[]) => React.ReactNode /** * Opt in to manual row order. Each row gets a grip that drags, moves with * Alt+↑/↓, or opens a Move menu. Called with the full dataset in its new order * (rows hidden by search or filters keep their slots); the caller owns `data`. * The grip is inert while the table is sorted or grouped, because a manual * order would be hidden by the sort. */ onRowsReorder?: (next: TData[], change: { rowId: string | number; from: number; to: number }) => void /** Optional "add new row" row text — pass false to hide */ addRowLabel?: string | false /** Custom option-value renderer for filter pills */ renderFilterOptionValue?: (fieldKey: string, value: string) => React.ReactNode /** When set by DataTablePaginated — drives row slicing inside useTableState */ paginationOverride?: { page: number; pageSize: number } /** When true, removes rounded bottom corners so a pagination bar can attach flush */ hasFooter?: boolean /** * Chrome rendered under the grid in a sticky foot stack (bulk bar + this node). * Prefer this over a sibling footer so selection actions stick with pagination. */ stickyFooter?: React.ReactNode /** * When false, table toolbar and grid omit `mx-4 lg:mx-6` / `px-4 lg:px-6` insets. * Use on embedded surfaces where the page shell or content rail already pads horizontally. */ edgeInset?: boolean /** * When false, hides toolbar search/filter chrome (e.g. catalog API prop matrices). * Grid column resize, sort, and header menus still work. */ showQueryControls?: boolean /** Conditional formatting rules — apply bg color to cells based on value */ conditionalRules?: import("./types").ConditionalRule[] /** When false, the column header row is hidden (Display options). */ showColumnHeaders?: boolean /** When set, table uses this state (e.g. shared with board view) instead of internal useTableState. */ state?: ReturnType> /** * Incremental row rendering for very large datasets. Keeps initial paint fast * and appends remaining rows in idle slices while showing a loading hint. */ lazyLoading?: { enabled?: boolean threshold?: number chunkSize?: number intervalMs?: number loadingLabel?: string } /** * Appends Leo loading rows (blob wash + thinking animation) after the data * rows while Leo is generating more. `count` rows, the first carrying `label`. */ leoLoading?: LeoLoadingConfig | boolean } type DataTableInnerProps> = DataTableExtendedProps & { state: ReturnType> } function DataTableInner>({ // `data` / `defaultSort` flow into `useTableState` upstream; the inner table // reads them via `state` and never directly here. Keep the prop slots so // the public `DataTable` API stays unchanged. data, onRowsReorder, columns, getRowId: getRowIdProp, getRowSelectionLabel, selectable = true, searchable = true, emptyState, onRowClick, openRowId, defaultSort: _defaultSort, toolbarSlot, toolbarActions, bulkActionsSlot, addRowLabel = false, renderFilterOptionValue, hasFooter = false, stickyFooter, edgeInset = true, showQueryControls = true, conditionalRules, showColumnHeaders = true, lazyLoading, leoLoading, state, }: DataTableInnerProps) { const reflowZoom = useSidebarReflowZoom() // A defined `openRowId` — `null` included — is the consumer saying "rows open // a rail on this hub". That turns on the open-row marker and exempts rows from // the rail's outside-click dismissal, so clicking a second row retargets the // rail rather than closing it and opening it again a frame later. const rowsOpenRail = openRowId !== undefined const useStickyFootStack = stickyFooter != null const { sortKey, sortDir, activeFilters, groupBy, selected, setSelected, setRowsSelected, getRowId, colWidths, colPins, lockedPins, colOrder, setColOrder, scrollRef, handleScroll, checkOverflow, isOverflowing, rows, effectivePins, displayCols, stickyPinsDisabled, stickyStyle, totalWidth, } = state useScrollportSync({ checkOverflow, scrollRef, totalWidth, columnCount: displayCols.length }) /** Pending action queued from a column-menu item that should run *after* the menu * has fully closed. The Properties drawer is a non-modal Radix Sheet (`modal=false`) * and Radix's DropdownMenu close cycle races with the Sheet's `onInteractOutside` * / focus-return logic if we open the Sheet synchronously from `onSelect` / `onClick`. * `onCloseAutoFocus` on `DropdownMenuContent` is the Radix-native hook that fires * after the menu has unmounted and focus has returned — the safe moment to act. */ const columnMenuPendingActionRef = React.useRef<(() => void) | null>(null) usePinnedScrollHint({ isOverflowing, stickyPinsDisabled, colPins, scrollRef }) const lastLeftPinKey = [...displayCols].reverse().find(c => effectivePins[c.key] === "left")?.key const firstRightPinKey = displayCols.find(c => effectivePins[c.key] === "right")?.key const { displayedGroups, isLazyLoading, lazyLoadingLabel, visibleRowIds, allSelected, someSelected, anySelected, } = useDataTableRowModel({ state, lazyLoading, getRowIdProp }) // The standalone (no `stickyFooter`) bulk bar used to render *inside* the // grid shell, which sets `overflow-hidden` to clip horizontal scroll and // rounded corners — a `position: sticky` descendant of an `overflow-hidden` // ancestor never sticks, it just scrolls off with the rows once the page // (not this component) is what actually scrolls past table-height content. // Rendering it as a sibling *after* the shell closes, exactly like the // `stickyFooter` stack below already does, is what makes `sticky bottom-0` // able to find the page's real scrollport. const showInShellBulkBar = !useStickyFootStack && anySelected // Whether a footer/bulk stack renders below the grid shell at all. When it // does, the shell and the stack are two independent boxes (the stack has to // live outside the shell's `overflow-hidden` — see above) that must still // read as one continuous card. Painting `border-x` + the `mx-*` inset on // each of them separately relies on both boxes laying out to the exact same // sub-pixel width, which a `position: sticky` box isn't guaranteed to match // (browsers can round a sticky box's geometry a hair differently from an // in-flow sibling), producing a visible 1-2px step in the side borders right // at the seam. Owning the side borders + inset on one shared wrapper instead // (see the outer `
` below) makes that impossible by construction. const hasBottomStack = useStickyFootStack || showInShellBulkBar const bulkShortcuts = useBulkShortcuts() useEscapeClearsSelection(anySelected, setSelected) const filteredColumnKeys = useFilteredColumnKeys(activeFilters) const conditionalRuleColumnKeys = useConditionalRuleColumnKeys(conditionalRules, columns) const sortRuleIdRef = React.useRef(0) const { bumpHeaderMenuOpen, effectiveHeaderStuck, floatingHeaderInnerWidth, floatingHeaderTableWidth, floatingHeaderTranslateRef, floatingHeaderWrapperRef, headerIsStuck, headerScrollLeftRef, headerSurfaceActive, isClient, setHeaderKeyboardActive, syncFloatingHeaderScroll, tableHeadRef, tableWrapRef, } = useFloatingHeader({ displayCols, showColumnHeaders, totalWidth, }) const { floatingHeaderBoxRef, groupClipRef, groupSlideRef, pinnedGroup, } = usePinnedGroupHeader({ displayedGroups, effectiveHeaderStuck, tableWrapRef, }) const selectColumnWidth = useSelectColumnWidth(displayCols, colWidths) const groupDisplay = useGroupDisplay(columns, groupBy) const pinnedGroupDisplay = groupDisplay(pinnedGroup?.groupLabel ?? null) const groupSelect = (groupLabel: string | null, groupRows: TData[], interactive = true) => renderGroupSelect({ groupLabel, groupRows, interactive, selectable, state, getRowIdProp }) const tableRootRef = React.useRef(null) const { commitRowMove, moveColumnBy, moveRowBy, onHeaderKeyDown, reorderAnnouncement, reorderTargetFor, rowDrag, rowDragRef, rowReorderDisabledReason, setRowDrag, setRowDragBoth, } = useDataTableReorder({ colOrder, colPins, columns, data, displayCols, getRowId, getRowIdProp, groupBy, lockedPins, onRowsReorder, setColOrder, sortKey, tableRootRef, }) /** * Shared header-cell inner content — label / sort button / select-checkbox * + ⋯ kebab menu (pin, sort, wrap, filter, group, conditional rule, * quick-search). Rendered identically by the inline `` and the * portal sticky ``. The `` shells now also share drag-reorder * attributes and the resize handle, so the only practical difference * between the two thead variants is the `style` prop (sticky uses * `floatingHeaderPinnedStyle`, inline uses `stickyStyle`). */ const renderHeaderCellInner = (col: ColumnDef, tabbable?: boolean): React.ReactNode => ( ) const headerRowShared = { state, lastLeftPinKey, firstRightPinKey, ariaSortFor: (colKey: string) => ariaSortFor(colKey, sortKey, sortDir), onHeaderKeyDown, } const onTheadFocusCapture = useHeaderFocusCapture({ tableHeadRef, headerIsStuck, setHeaderKeyboardActive }) const groupRowsShared = { state, columns, selectable, onRowClick, rowsOpenRail, openRowId, conditionalRules, getRowIdProp, getRowSelectionLabel, onRowsReorder, rowReorderDisabledReason, rowDrag, rowDragRef, setRowDrag, setRowDragBoth, commitRowMove, moveRowBy, cellStyle: (key: string) => stickyStyle(key), splitCountFor: (row: TData) => splitCountFor(row, displayCols), firstRightPinKey, lastLeftPinKey, } const bulkBar = ( setSelected(new Set())} actionsSlot={bulkActionsSlot} exportShortcut={bulkShortcuts.exportShortcut} deleteShortcut={bulkShortcuts.deleteShortcut} /> ) React.useEffect(() => { warnIfStackedTableEdgeInset(tableRootRef.current) }, []) // ─── Render ─────────────────────────────────────────────────────────────── return (
{reorderAnnouncement} {isClient && effectiveHeaderStuck ? createPortal(
floatingPinnedStyle({ pin: effectivePins[key], innerWidth: floatingHeaderInnerWidth, readWrapWidth: () => tableWrapRef.current?.clientWidth, tableWidth: floatingHeaderTableWidth, scrollLeft: headerScrollLeftRef.current, }) } renderInner={col => renderHeaderCellInner(col, false)} />
{pinnedGroup ? ( ) : null}
, document.body, ) : null} {/* ── Table grid shell (horizontal scroll). Bulk bar lives in sticky foot when `stickyFooter` is set so it sticks with pagination. When a footer/bulk stack follows, the shared side border + inset move to the wrapper below (`hasBottomStack` doc comment above); the shell only owns them when it's the whole card by itself. */}
{ tableWrapRef.current = el scrollRef.current = el }} onScroll={e => { handleScroll() syncFloatingHeaderScroll((e.currentTarget as HTMLDivElement).scrollLeft) }} className={cn( "overflow-x-auto", showInShellBulkBar && "border-b border-border", )} > clientWidth` (not scrollWidth) so // `min(100%)` here does not re-break auto-pin on overflow. width: `max(${totalWidth}px, 100%)`, }} > {/* ── Table head ──────────────────────────────────────────────── */} stickyStyle(key, false)} renderInner={col => renderHeaderCellInner(col)} /> {/* ── Table body ───────────────────────────────────────────────── */} {displayedGroups.map(({ groupKey, groupLabel, rows: groupRows }) => { const display = groupDisplay(groupLabel) return ( {display && ( )} ) })} 0} lazyLoadingLabel={lazyLoadingLabel} leoLoading={leoLoading} emptyState={emptyState} addRowLabel={addRowLabel} />
{/* Standalone bulk bar (no `stickyFooter` supplied) — a sibling of the shell, not a child of it, so `sticky bottom-0` has a real scrollport to stick within instead of the shell's own `overflow-hidden`. See `showInShellBulkBar`'s doc comment above. Side border + inset live on the shared wrapper (see `hasBottomStack`), not here. */} {showInShellBulkBar ? ( {bulkBar} ) : null} {useStickyFootStack ? ( ) : null}
) } function DataTableWithInternalState>(props: DataTableExtendedProps) { const state = useTableState(props.data, props.columns, props.defaultSort, props.paginationOverride) return } export function DataTable>(props: DataTableExtendedProps) { if (props.state) { return } return }