Documentation menu
Getting Started
Components
Primitives
- Agent Thinking
- Alert
- Alert Dialog
- Avatar
- Badge
- Breadcrumb
- Button
- Button Group
- Calendar
- Card
- Checkbox
- Command
- Command Palette
- Context Menu
- Data Table
- Dialog
- Dropdown Menu
- Empty
- Field
- Glow Cloud
- Input
- Label
- Medication Schedule
- Period Tabs
- Popover
- Rainbow Button
- Scroll Area
- Select
- Selectable Card
- Separator
- Sheet
- Sidebar
- Skeleton
- Slider
- Sonner
- Spinner
- Switch
- Table
- Tabs
- Tag
- Textarea
- Timeline
- Tooltip
- Use Count Up
Charts and metrics
Patterns
- Confirm Button
- Date Picker
- Embedded
- Empty State
- Entity Drawer
- Error Boundary
- Field Row
- File Dropzone
- Form Dialog
- Kv
- List Editor
- List Page
- Live Time
- Mini Table
- Money
- Note Field
- Note Text
- Page Card
- Page Header
- Page Tabs
- Page Toolbar
- Person Cell
- Picture Field
- Print Card
- Range Switcher
- Row Actions
- Search Input
- Search Select
- Selected Box
- Signature Pad
- Status Badge
- Sub Nav Layout
- Suggest Input
- Tab Icons
- Table Footer
- Theme Accent Picker
- Time Picker
- View All Link
Dashboard cards
Advanced
Device frames
Website widgets
Website screens
Website panels
Advanced
Data Grid
A spreadsheet-like grid: cell selection, editing, virtual scrolling, drag to reorder rows and columns, and pagination.
import {
cellSelectionFeature,
columnFacetingFeature,
columnOrderingFeature,
columnPinningFeature,
columnResizingFeature,
columnSizingFeature,
createFacetedUniqueValues,
rowPinningFeature,
columnVisibilityFeature,
createPaginatedRowModel,
createSortedRowModel,
rowExpandingFeature,
rowPaginationFeature,
rowSelectionFeature,
rowSortingFeature,
sortFn_alphanumeric,
sortFn_basic,
tableFeatures,
useTable,
type ColumnDef,
} from "@tanstack/react-table"
import { DataGrid, DataGridContainer } from "@/registry/vcare/ui/data-grid/data-grid"
import { DataGridPagination } from "@/registry/vcare/ui/data-grid/data-grid-pagination"
import { DataGridTable } from "@/registry/vcare/ui/data-grid/data-grid-table"
type Item = { id: string; name: string; batch: string; stock: number; mrp: number; expiry: string }
const data: Item[] = [
{ id: "1", name: "Paracetamol 650", batch: "PC2401", stock: 1200, mrp: 2.1, expiry: "2027-03" },
{ id: "2", name: "Amoxicillin 500", batch: "AX2311", stock: 84, mrp: 9.8, expiry: "2026-12" },
{ id: "3", name: "Metformin 500", batch: "MF2405", stock: 640, mrp: 1.6, expiry: "2027-08" },
{ id: "4", name: "Amlodipine 5", batch: "AM2402", stock: 310, mrp: 2.4, expiry: "2027-01" },
{ id: "5", name: "Pantoprazole 40", batch: "PT2312", stock: 22, mrp: 6.5, expiry: "2026-11" },
{ id: "6", name: "Cetirizine 10", batch: "CT2408", stock: 540, mrp: 1.2, expiry: "2027-09" },
]
const features = tableFeatures({
cellSelectionFeature,
columnFacetingFeature,
columnOrderingFeature,
columnPinningFeature,
columnResizingFeature,
columnSizingFeature,
rowPinningFeature,
facetedUniqueValues: createFacetedUniqueValues(),
columnVisibilityFeature,
rowExpandingFeature,
rowPaginationFeature,
rowSelectionFeature,
rowSortingFeature,
paginatedRowModel: createPaginatedRowModel(),
sortedRowModel: createSortedRowModel(),
sortFns: { alphanumeric: sortFn_alphanumeric, basic: sortFn_basic },
})
const columns: ColumnDef<typeof features, Item, any>[] = [
{ accessorKey: "name", header: "Item", size: 200 },
{ accessorKey: "batch", header: "Batch", size: 110 },
{ accessorKey: "stock", header: "Stock", size: 90 },
{ accessorKey: "mrp", header: "MRP", size: 90, cell: ({ getValue }) => `₹${(getValue() as number).toFixed(2)}` },
{ accessorKey: "expiry", header: "Expiry", size: 100 },
]
export default function DataGridDemo() {
const table = useTable({ features, columns, data, getRowId: (r) => r.id, initialState: { pagination: { pageIndex: 0, pageSize: 5 } } })
return (
<DataGrid table={table} recordCount={data.length}>
<div className="w-full space-y-2.5">
<DataGridContainer>
<DataGridTable />
</DataGridContainer>
<DataGridPagination />
</div>
</DataGrid>
)
}Installation
npx shadcn@latest add @vcare/data-gridOr install directly from the URL: https://ui.vcarehms.com/r/data-grid.json
- Install the dependencies:
npm i @base-ui/react @dnd-kit/core @dnd-kit/modifiers @dnd-kit/sortable @dnd-kit/utilities @tanstack/react-table @tanstack/react-virtual lucide-react - Add the registry items it uses: button, checkbox, dropdown-menu, input, popover, reui-badge, select, separator, skeleton, spinner, utils.
- Copy these 12 files into your project and change the
@/registry/vcare/…imports to your own paths.
components/ui/data-grid/data-grid-cell-selection.tsx
'use client';
import { useEffect, useRef, useState } from 'react';
import type { CSSProperties, KeyboardEvent as ReactKeyboardEvent, ReactNode, RefObject } from 'react';
import { createPortal } from 'react-dom';
import { useDataGrid } from '@/registry/vcare/ui/data-grid/data-grid';
import type {
DataGridCellChange,
DataGridCellRejection,
DataGridCellsChangeDetails,
DataGridColumnCellEdit,
DataGridTableInstance,
} from '@/registry/vcare/ui/data-grid/data-grid';
import { Subscribe } from '@tanstack/react-table';
import { cn } from '@/registry/vcare/lib/utils';
import { Button } from '@/registry/vcare/ui/button';
/** Where a finished edit sends the focused cell, or null to stay. */
type DataGridEditorAdvance = 'down' | 'up' | 'right' | 'left' | null;
interface DataGridFocusCellOptions {
/** Also open the cell's editor, the way Enter would. */
edit?: boolean;
}
/** Imperative surface of the cell-selection controller. */
interface DataGridCellSelectionApi {
/**
* Moves the grid's cell focus AND the document focus together, retrying
* briefly while the row mounts, so a freshly created row is typeable
* without an extra click. `edit: true` also opens the cell's editor the
* way Enter would. Registered once the controller is wired; null while
* cell selection is off.
*/
focusCell: (rowId: string, columnId: string, options?: DataGridFocusCellOptions) => void;
/** Clears every range and the focused cell. */
clearSelection: () => void;
/** Scrolls a rendered cell into view without moving focus. */
scrollToCell: (rowId: string, columnId: string) => void;
}
/** One open built-in editor: which cell, which control, and its text. */
interface DataGridEditorSession {
rowId: string;
columnId: string;
control: 'text' | 'textarea';
/** What the editor opens with: the typed seed or the formatted value. */
initialValue: string;
/** The formatted current value; an unchanged commit dispatches nothing. */
baseline: string;
/** Accessible name for the overlay control, from the column's header. */
label: string;
}
/* ------------------------------------------------------------------------- *
* Clipboard text: pure, node-testable.
* ------------------------------------------------------------------------- */
function serializeDataGridClipboardField(field: string): string {
// Excel and Sheets quote a field containing a delimiter and double inner
// quotes; everything else ships bare.
return /[\t\n\r"]/.test(field) ? '"' + field.replaceAll('"', '""') + '"' : field;
}
/** Row-major grid to TSV, CRLF rows, Excel-style quoting. */
function serializeDataGridClipboardText(grid: string[][]): string {
return grid.map((line) => line.map(serializeDataGridClipboardField).join('\t')).join('\r\n');
}
/**
* TSV to a row-major grid. A stateful scan, not a split: a quoted field may
* contain tabs, quotes and both newline flavors, which is exactly what Excel
* emits for a multi-line cell.
*/
function parseDataGridClipboardText(text: string): string[][] {
const rows: string[][] = [];
let row: string[] = [];
let field = '';
let quoted = false;
let i = 0;
while (i < text.length) {
const ch = text[i]!;
if (quoted) {
if (ch === '"') {
if (text[i + 1] === '"') {
field += '"';
i += 2;
continue;
}
quoted = false;
i += 1;
continue;
}
field += ch;
i += 1;
continue;
}
if (ch === '"' && field === '') {
quoted = true;
i += 1;
continue;
}
if (ch === '\t') {
row.push(field);
field = '';
i += 1;
continue;
}
if (ch === '\r' || ch === '\n') {
if (ch === '\r' && text[i + 1] === '\n') i += 1;
row.push(field);
rows.push(row);
row = [];
field = '';
i += 1;
continue;
}
field += ch;
i += 1;
}
row.push(field);
rows.push(row);
// Excel terminates the payload with one newline; that final empty line is
// an artifact of the format, not a data row.
const last = rows[rows.length - 1];
if (rows.length > 1 && last?.length === 1 && last[0] === '') rows.pop();
return rows;
}
/** Repeats a block cyclically to fill rowCount x columnCount. */
function tileDataGridClipboardBlock(block: string[][], rowCount: number, columnCount: number): string[][] {
const tiled: string[][] = [];
for (let r = 0; r < rowCount; r++) {
const source = block[r % block.length] ?? [];
const line: string[] = [];
for (let c = 0; c < columnCount; c++) {
line.push(source[c % (source.length || 1)] ?? '');
}
tiled.push(line);
}
return tiled;
}
function escapeDataGridClipboardHtml(value: string): string {
return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');
}
// A minimal text/html flavor alongside the TSV keeps type fidelity when the
// paste target is Excel or Sheets. Newlines inside a field become <br>, the
// HTML representation of a multi-line cell; raw newlines would collapse to
// spaces on paste.
function renderDataGridClipboardHtml(grid: string[][]): string {
const body = grid
.map(
(line) => '<tr>' + line.map((field) => '<td>' + escapeDataGridClipboardHtml(field).replace(/\r\n|\r|\n/g, '<br>') + '</td>').join('') + '</tr>',
)
.join('');
return '<table><tbody>' + body + '</tbody></table>';
}
/* ------------------------------------------------------------------------- *
* Selection geometry: walks in the feature's own index space.
* ------------------------------------------------------------------------- */
/**
* Columns in render order, the same [start, center, end] space
* cellSelectionFeature resolves its bounds against.
*/
function getDataGridDisplayOrderedColumns<TData extends object>(table: DataGridTableInstance<TData>) {
return [...table.getStartVisibleLeafColumns(), ...table.getCenterVisibleLeafColumns(), ...table.getEndVisibleLeafColumns()];
}
function getDataGridWritableCellEdit<TData extends object>(
column: {
columnDef: { meta?: { cellEdit?: DataGridColumnCellEdit<TData> } };
},
/**
* The row a write targets. Function-form `editable` is evaluated against
* it; without a row the column counts as writable in principle, the
* coarse check the fill preview's column filter uses.
*/
row?: TData,
): DataGridColumnCellEdit<TData> | null {
const cellEdit = column.columnDef.meta?.cellEdit;
if (!cellEdit || cellEdit.editable === false) return null;
if (typeof cellEdit.editable === 'function' && row !== undefined && !cellEdit.editable(row)) {
return null;
}
return cellEdit;
}
/**
* Ids of the rows the view can actually show: the page slice plus rows the
* DOM renders outside it (pinned rows under keepPinnedRows). Selection
* bounds live in pre-paginated display order, so a range whose corners are
* both visible can still span off-page rows in between - a page-boundary
* range to a bottom-pinned draft is the standing example. Every batch walk
* (copy, clear, paste, fill) filters rows through this set so the cells a
* batch touches are exactly the cells the selection paints.
*/
function getDataGridRenderedRowIds<TData extends object>(
table: DataGridTableInstance<TData>,
viewport: HTMLElement | null | undefined,
): Set<string> | null {
if (!viewport) return null;
// When the page slice covers the whole display order (manual pagination,
// virtualization, no pagination) no row can be off-page: skip the walk.
if (table.getRowModel().rows.length === table.getRowsInDisplayOrder().length) {
return null;
}
const rendered = new Set<string>(table.getRowModel().rows.map((row: { id: string }) => row.id));
for (const rowEl of Array.from(viewport.querySelectorAll('tbody tr[data-row-id]'))) {
const id = rowEl.getAttribute('data-row-id');
if (id) rendered.add(id);
}
return rendered;
}
/**
* Cells of the current selection the view can actually show, under the
* same row filter the batch builders use, so a count shown next to the
* selection always matches what is painted and what a batch will touch.
* The feature's own getSelectedCellCount spans off-page rows instead.
*/
function getDataGridVisibleSelectedCellCount<TData extends object>(
table: DataGridTableInstance<TData>,
/** The grid's body viewport; null falls back to the full-range count. */
viewport: HTMLElement | null,
): number {
const bounds = table.getCellSelectionBounds();
if (!bounds.length) return 0;
const rows = table.getRowsInDisplayOrder();
const columns = getDataGridDisplayOrderedColumns(table);
const rendered = getDataGridRenderedRowIds(table, viewport);
let count = 0;
for (const bound of bounds) {
let rowCount = 0;
for (let r = bound.minRowIndex; r <= bound.maxRowIndex; r++) {
const row = rows[r];
if (row && (!rendered || rendered.has(row.id))) rowCount += 1;
}
let columnCount = 0;
for (let c = bound.minColumnIndex; c <= bound.maxColumnIndex; c++) {
const column = columns[c];
if (column && column.columnDef.enableCellSelection !== false) {
columnCount += 1;
}
}
count += rowCount * columnCount;
}
return count;
}
/**
* The bound of the ACTIVE (most recent) region. getCellSelectionBounds()
* sorts geometrically, so its last entry is merely the bottom-right
* rectangle; the focused cell anchors the newest range, so the bound
* containing it is the active one. Falls back to the geometric last when
* the focused cell sits in no bound (the newest range was an exclude).
*/
function getDataGridActiveBound<TData extends object>(table: DataGridTableInstance<TData>) {
const bounds = table.getCellSelectionBounds();
if (!bounds.length) return null;
const focused = table.getFocusedCell();
if (focused) {
// O(1): v9 caches the display index on the row itself.
const rowIndex = focused.row.getDisplayIndex();
const columnIndex = getDataGridDisplayOrderedColumns(table).findIndex((column) => column.id === focused.column.id);
const containing = bounds.find(
(bound) =>
rowIndex >= bound.minRowIndex && rowIndex <= bound.maxRowIndex && columnIndex >= bound.minColumnIndex && columnIndex <= bound.maxColumnIndex,
);
if (containing) return containing;
}
return bounds[bounds.length - 1] ?? null;
}
/**
* Resolves the cell one visual step away from a given cell: selectable
* columns for horizontal, RENDERED row order for vertical. The feature's
* own move/extend resolve rows through the page slice and stall on pinned
* rows (a bottom-pinned draft), while id-addressed cells work everywhere.
* "edge" means the step is at the grid boundary; null means the position
* is not resolvable here and the caller should use the feature's move.
*/
function getDataGridStepTarget<TData extends object>(
table: DataGridTableInstance<TData>,
viewport: HTMLElement,
from: { rowId: string; columnId: string },
direction: 'up' | 'down' | 'left' | 'right',
): { rowId: string; columnId: string } | 'edge' | null {
if (direction === 'left' || direction === 'right') {
const selectable = getDataGridDisplayOrderedColumns(table).filter((column) => column.columnDef.enableCellSelection !== false);
const index = selectable.findIndex((column) => column.id === from.columnId);
if (index === -1) return null;
const next = selectable[index + (direction === 'right' ? 1 : -1)];
return next ? { rowId: from.rowId, columnId: next.id } : 'edge';
}
const renderedIds = Array.from(viewport.querySelectorAll('tbody tr[data-row-id]')).map((row) => row.getAttribute('data-row-id'));
const index = renderedIds.indexOf(from.rowId);
if (index === -1) return null;
const nextId = renderedIds[index + (direction === 'down' ? 1 : -1)];
return nextId ? { rowId: nextId, columnId: from.columnId } : 'edge';
}
/**
* Shift+Arrow: the feature keeps focus on the anchor and grows the range
* from its active corner. When its own extend cannot resolve the step
* (the active corner sits on a pinned row, or the next visual row is a
* pinned row outside the page slice), re-derive the active corner from
* the bounds and step it in visual space through selectCellRange.
*/
function extendDataGridSelection<TData extends object>(
table: DataGridTableInstance<TData>,
viewport: HTMLElement,
direction: 'up' | 'down' | 'left' | 'right',
): { rowId: string; columnId: string } | null {
// The range's active corner: focus stays the anchor, so the corner is
// the bound's opposite one. Returned to the caller so the view can
// follow the growing edge rather than the anchor.
const activeCorner = () => {
const focused = table.getFocusedCell();
if (!focused) return null;
const bound = getDataGridActiveBound(table);
if (!bound) return null;
const rows = table.getRowsInDisplayOrder();
const allColumns = getDataGridDisplayOrderedColumns(table);
const rowIndex = focused.row.getDisplayIndex();
const columnIndex = allColumns.findIndex((column) => column.id === focused.column.id);
return {
rowId: rows[rowIndex === bound.minRowIndex ? bound.maxRowIndex : bound.minRowIndex]?.id ?? focused.row.id,
columnId: allColumns[columnIndex === bound.minColumnIndex ? bound.maxColumnIndex : bound.minColumnIndex]?.id ?? focused.column.id,
};
};
const boundKey = () => {
const bounds = table.getCellSelectionBounds();
const bound = bounds[bounds.length - 1];
return bound ? `${bounds.length}:${bound.minRowIndex}-${bound.maxRowIndex}:${bound.minColumnIndex}-${bound.maxColumnIndex}` : 'none';
};
const before = boundKey();
table.extendCellSelection(direction);
if (boundKey() !== before) return activeCorner();
const focused = table.getFocusedCell();
if (!focused) return null;
const active = activeCorner() ?? {
rowId: focused.row.id,
columnId: focused.column.id,
};
const target = getDataGridStepTarget(table, viewport, active, direction);
if (!target || target === 'edge') return null;
table.selectCellRange(
{
anchorRowId: focused.row.id,
anchorColumnId: focused.column.id,
focusRowId: target.rowId,
focusColumnId: target.columnId,
},
{ mode: 'replace' },
);
return target;
}
/**
* The active region as formatted strings, row-major. Columns opted out of
* selection are compacted away, matching the feature's own ranges-data
* behavior, and rows the view cannot show are skipped when a viewport is
* given. Null when nothing is selected.
*/
function getDataGridActiveRegionGrid<TData extends object>(table: DataGridTableInstance<TData>, viewport?: HTMLElement | null): string[][] | null {
const bound = getDataGridActiveBound(table);
if (!bound) return null;
const rows = table.getRowsInDisplayOrder();
const columns = getDataGridDisplayOrderedColumns(table);
const rendered = getDataGridRenderedRowIds(table, viewport);
const grid: string[][] = [];
for (let r = bound.minRowIndex; r <= bound.maxRowIndex; r++) {
const row = rows[r];
if (!row || (rendered && !rendered.has(row.id))) continue;
const cells = row.getAllCellsByColumnId();
const line: string[] = [];
for (let c = bound.minColumnIndex; c <= bound.maxColumnIndex; c++) {
const column = columns[c];
if (!column || column.columnDef.enableCellSelection === false) continue;
const value = cells[column.id]?.getValue();
const format = column.columnDef.meta?.cellEdit?.format;
line.push(format ? format(value, row.original) : String(value ?? ''));
}
grid.push(line);
}
return grid.length ? grid : null;
}
/**
* A clear/cut batch over the selection's writable cells. Non-writable columns
* are skipped silently: clearing is an intent over what the grid owns, and a
* rejection per read-only cell would be noise. Null when nothing clears.
*/
function buildDataGridClearDetails<TData extends object>(
table: DataGridTableInstance<TData>,
source: 'clear' | 'cut',
activeRegionOnly: boolean,
viewport?: HTMLElement | null,
): DataGridCellsChangeDetails<TData> | null {
const allBounds = table.getCellSelectionBounds();
const activeBound = getDataGridActiveBound(table);
const bounds = activeRegionOnly ? (activeBound ? [activeBound] : []) : allBounds;
if (!bounds.length) return null;
const rows = table.getRowsInDisplayOrder();
const columns = getDataGridDisplayOrderedColumns(table);
const rendered = getDataGridRenderedRowIds(table, viewport);
const changes: DataGridCellChange<TData>[] = [];
for (const bound of bounds) {
for (let r = bound.minRowIndex; r <= bound.maxRowIndex; r++) {
const row = rows[r];
if (!row || (rendered && !rendered.has(row.id))) continue;
const cells = row.getAllCellsByColumnId();
for (let c = bound.minColumnIndex; c <= bound.maxColumnIndex; c++) {
const column = columns[c];
if (!column || column.columnDef.enableCellSelection === false) continue;
const cellEdit = getDataGridWritableCellEdit<TData>(column, row.original);
if (!cellEdit) continue;
changes.push({
rowId: row.id,
columnId: column.id,
row: row.original,
previousValue: cells[column.id]?.getValue(),
value: cellEdit.clearValue ?? null,
});
}
}
}
return changes.length ? { source, changes, rejected: [] } : null;
}
type DataGridPasteTarget = {
/** Display indexes of the pasted region's first and last row. */
startRowIndex: number;
endRowIndex: number;
/** How many rows a paste actually wrote (hidden rows are skipped). */
rowCount?: number;
/** Display indexes of the pasted region's first and last column. */
startColumnIndex: number;
endColumnIndex: number;
};
/**
* Resolves a parsed clipboard block into a paste batch, Excel semantics:
* a 1x1 block fills the whole selected region; a block tiles when the region
* is an exact multiple of it; otherwise it pastes once from the region's
* top-left, clamped at the grid edges (rows are never grown).
*/
function buildDataGridPasteDetails<TData extends object>(
table: DataGridTableInstance<TData>,
block: string[][],
viewport?: HTMLElement | null,
): {
details: DataGridCellsChangeDetails<TData>;
target: DataGridPasteTarget;
} | null {
if (!block.length) return null;
const bound = getDataGridActiveBound(table);
if (!bound) return null;
const rows = table.getRowsInDisplayOrder();
const columns = getDataGridDisplayOrderedColumns(table);
const rendered = getDataGridRenderedRowIds(table, viewport);
// Copy COMPACTS opt-out columns away, so paste maps block columns over the
// same compacted space: selectable columns only, starting at the region's
// first selectable column and running past the region for a wider block,
// clamped at the grid edge. Walking raw display offsets instead would let
// an interior opt-out column swallow a block column silently.
const targetColumns: Array<{
column: (typeof columns)[number];
displayIndex: number;
}> = [];
let regionColumns = 0;
for (let c = bound.minColumnIndex; c < columns.length; c++) {
const column = columns[c];
if (!column || column.columnDef.enableCellSelection === false) continue;
targetColumns.push({ column, displayIndex: c });
if (c <= bound.maxColumnIndex) regionColumns += 1;
}
if (!regionColumns) return null;
const blockRows = block.length;
const blockColumns = block.reduce((max, line) => Math.max(max, line.length), 1);
const regionRows = bound.maxRowIndex - bound.minRowIndex + 1;
let rowCount: number;
let columnCount: number;
if (blockRows === 1 && blockColumns === 1) {
rowCount = regionRows;
columnCount = regionColumns;
} else if (regionRows % blockRows === 0 && regionColumns % blockColumns === 0) {
rowCount = regionRows;
columnCount = regionColumns;
} else {
rowCount = blockRows;
columnCount = blockColumns;
}
const tiled = tileDataGridClipboardBlock(block, rowCount, columnCount);
const startRowIndex = bound.minRowIndex;
// Rows the block maps onto: the next rowCount rows the view can show,
// starting at the region's top. Off-page rows between a page's tail and
// a pinned draft are skipped rather than silently written.
const targetRows: Array<{
row: (typeof rows)[number];
displayIndex: number;
}> = [];
for (let r = startRowIndex; r < rows.length; r++) {
if (targetRows.length === rowCount) break;
const row = rows[r];
if (!row || (rendered && !rendered.has(row.id))) continue;
targetRows.push({ row, displayIndex: r });
}
const changes: DataGridCellChange<TData>[] = [];
const rejected: DataGridCellRejection[] = [];
for (let r = 0; r < targetRows.length; r++) {
const row = targetRows[r]!.row;
const cells = row.getAllCellsByColumnId();
for (let c = 0; c < columnCount; c++) {
const column = targetColumns[c]?.column;
if (!column) continue;
const raw = tiled[r]?.[c] ?? '';
const cellEdit = getDataGridWritableCellEdit<TData>(column, row.original);
if (!cellEdit) {
rejected.push({
rowId: row.id,
columnId: column.id,
raw,
reason: 'readonly',
});
continue;
}
const value = cellEdit.parse ? cellEdit.parse(raw, row.original) : raw;
if (value === undefined) {
rejected.push({
rowId: row.id,
columnId: column.id,
raw,
reason: 'invalid',
});
continue;
}
changes.push({
rowId: row.id,
columnId: column.id,
row: row.original,
previousValue: cells[column.id]?.getValue(),
value,
});
}
}
if (!changes.length && !rejected.length) return null;
const lastTarget = targetColumns[Math.min(columnCount, targetColumns.length) - 1];
return {
details: { source: 'paste', changes, rejected },
target: {
startRowIndex,
endRowIndex: targetRows[targetRows.length - 1]?.displayIndex ?? startRowIndex,
rowCount: targetRows.length,
startColumnIndex: targetColumns[0]!.displayIndex,
endColumnIndex: lastTarget!.displayIndex,
},
};
}
/**
* The inverse batch: every change's value and previousValue swapped and
* rejections dropped. Feed it through the same state update onCellsChange
* uses to implement undo; inverting the inverse is redo.
*/
function invertDataGridCellsChange<TData extends object>(details: DataGridCellsChangeDetails<TData>): DataGridCellsChangeDetails<TData> {
return {
source: details.source,
changes: details.changes.map((change) => ({
...change,
value: change.previousValue,
previousValue: change.value,
})),
rejected: [],
};
}
function selectDataGridRegion<TData extends object>(table: DataGridTableInstance<TData>, target: DataGridPasteTarget) {
const rows = table.getRowsInDisplayOrder();
const columns = getDataGridDisplayOrderedColumns(table);
const anchorRow = rows[target.startRowIndex];
const anchorColumn = columns[target.startColumnIndex];
const focusRow = rows[Math.min(target.endRowIndex, rows.length - 1)];
const focusColumn = columns[target.endColumnIndex];
if (!anchorRow || !anchorColumn || !focusRow || !focusColumn) return;
table.selectCellRange(
{
anchorRowId: anchorRow.id,
anchorColumnId: anchorColumn.id,
focusRowId: focusRow.id,
focusColumnId: focusColumn.id,
},
{ mode: 'replace' },
);
}
/* ------------------------------------------------------------------------- *
* Fill handle drag session.
* ------------------------------------------------------------------------- */
/**
* Imperative document-level session, the column-resize pattern: preview state
* is written as `data-cell-fill-target` attributes outside React, so the drag
* costs zero re-renders until release. v1 fills down or right (dominant axis)
* by repeating the source region's values; rows outside the rendered
* viewport of a virtualized body cannot be targeted mid-drag.
*
* Vertical distance is measured over the rows the view can show, so a drag
* onto a pinned draft fills exactly the rows the preview marked and never
* the off-page rows between. A cross-column fill round-trips through the
* source's format and the target's parse - the paste contract - because
* adjacent grid columns are heterogeneous; a parse rejection lands in the
* batch's rejected list, while cells that cannot be written are skipped
* and never tinted by the preview.
*/
// The fill drag's feedback: ONE dashed border (the Sheets fill marquee)
// around the whole pending region - the source PLUS the extension - so the
// drag reads as one growing region, never as a second box glued under the
// source. While the session runs
// the viewport carries data-cell-filling and the source cells' own
// selection chrome rests, so this element is the only painter and nothing
// can double at the junction. z-[35]: above the sticky pinned cells
// (z 30) so the border survives crossing a pinned column; below the
// sticky header (z-40).
const dataGridGestureOutlineClasses = 'outline-primary pointer-events-none absolute z-[35] outline-1 outline-dashed -outline-offset-1';
function startDataGridFillSession<TData extends object>(options: {
table: DataGridTableInstance<TData>;
viewport: HTMLElement;
onCellsChange: ((details: DataGridCellsChangeDetails<TData>) => void) | null;
}) {
const { table, viewport, onCellsChange } = options;
// Fill over a multi-region selection is undefined territory; Excel refuses
// it too.
if (table.getCellSelectionBounds().length > 1) return;
const bound = getDataGridActiveBound(table);
if (!bound) return;
const rows = table.getRowsInDisplayOrder();
const columns = getDataGridDisplayOrderedColumns(table);
// The vertical walk space: rows the view can show, in display order. The
// DOM ids seed it (a drag can only target rendered rows), and one pass
// over the cached display array resolves them without building per-row
// wrappers for a 50k-row model.
const domRowIds = new Set<string>();
for (const rowEl of Array.from(viewport.querySelectorAll('tbody tr[data-row-id]'))) {
const id = rowEl.getAttribute('data-row-id');
if (id) domRowIds.add(id);
}
const visibleRows: Array<{
row: (typeof rows)[number];
displayIndex: number;
}> = [];
for (let i = 0; i < rows.length; i++) {
const row = rows[i]!;
if (domRowIds.has(row.id)) {
visibleRows.push({ row, displayIndex: i });
}
}
const visibleIndexById = new Map(visibleRows.map((entry, index) => [entry.row.id, index]));
// The source region and its last row, both in visible space.
const sourceRows = visibleRows.filter(({ displayIndex }) => displayIndex >= bound.minRowIndex && displayIndex <= bound.maxRowIndex);
const sourceEndVisibleIndex = sourceRows.length ? visibleIndexById.get(sourceRows[sourceRows.length - 1]!.row.id)! : -1;
if (sourceEndVisibleIndex === -1) return;
const columnIndexById = new Map(columns.map((column, index) => [column.id, index]));
const isFillableColumn = (column: (typeof columns)[number]) =>
column.columnDef.enableCellSelection !== false && !!getDataGridWritableCellEdit<TData>(column);
let extension: { axis: 'row' | 'column'; count: number } | null = null;
let previewCells: Element[] = [];
const previewOutline = viewport.ownerDocument.createElement('div');
previewOutline.setAttribute('data-slot', 'data-grid-cell-fill-preview');
previewOutline.className = dataGridGestureOutlineClasses;
previewOutline.style.display = 'none';
viewport.appendChild(previewOutline);
viewport.setAttribute('data-cell-filling', '');
// The region border wraps source plus extension: its corners are the
// source region's first cell and the farthest cell the drag reaches
// (the source's own last cell while nothing is extended).
const sourceCorner = (rowId: string, columnId: string | undefined) =>
columnId ? viewport.querySelector(`tr[data-row-id="${CSS.escape(rowId)}"] td[data-col-id="${CSS.escape(columnId)}"]`) : null;
const positionPreviewOutline = () => {
const first = sourceRows.length ? sourceCorner(sourceRows[0]!.row.id, columns[bound.minColumnIndex]?.id) : null;
const lastSource = sourceRows.length ? sourceCorner(sourceRows[sourceRows.length - 1]!.row.id, columns[bound.maxColumnIndex]?.id) : null;
const far = previewCells.length ? previewCells[previewCells.length - 1]! : lastSource;
if (!first || !far) {
previewOutline.style.display = 'none';
return;
}
const firstRect = first.getBoundingClientRect();
const farRect = far.getBoundingClientRect();
const viewportRect = viewport.getBoundingClientRect();
const left = Math.min(firstRect.left, farRect.left);
const top = Math.min(firstRect.top, farRect.top);
previewOutline.style.display = 'block';
previewOutline.style.left = `${left - viewportRect.left + viewport.scrollLeft}px`;
previewOutline.style.top = `${top - viewportRect.top + viewport.scrollTop}px`;
previewOutline.style.width = `${Math.max(firstRect.right, farRect.right) - left}px`;
previewOutline.style.height = `${Math.max(firstRect.bottom, farRect.bottom) - top}px`;
};
const clearPreview = () => {
for (const cell of previewCells) cell.removeAttribute('data-cell-fill-target');
previewCells = [];
positionPreviewOutline();
};
// Target rows and columns for the current extension: rows in visible
// space, and only the columns the commit would actually write, so the
// preview never tints a cell the release will skip.
const getExtensionTargets = () => {
if (!extension) return null;
const columnEntries = columns.map((column, displayIndex) => ({
column,
displayIndex,
}));
return extension.axis === 'row'
? {
rowEntries: visibleRows.slice(sourceEndVisibleIndex + 1, sourceEndVisibleIndex + 1 + extension.count),
columnEntries: columnEntries.slice(bound.minColumnIndex, bound.maxColumnIndex + 1).filter(({ column }) => isFillableColumn(column)),
}
: {
rowEntries: sourceRows,
columnEntries: columnEntries
.slice(bound.maxColumnIndex + 1, bound.maxColumnIndex + 1 + extension.count)
.filter(({ column }) => isFillableColumn(column)),
};
};
const applyPreview = () => {
clearPreview();
const targets = getExtensionTargets();
if (!targets) return;
for (const { row } of targets.rowEntries) {
const rowElement = viewport.querySelector(`tr[data-row-id="${CSS.escape(row.id)}"]`);
if (!rowElement) continue;
for (const { column } of targets.columnEntries) {
if (!getDataGridWritableCellEdit<TData>(column, row.original)) continue;
const cellElement = rowElement.querySelector(`td[data-col-id="${CSS.escape(column.id)}"]`);
if (!cellElement) continue;
cellElement.setAttribute('data-cell-fill-target', 'true');
previewCells.push(cellElement);
}
}
positionPreviewOutline();
};
const handleMove = (event: MouseEvent) => {
const element = document.elementFromPoint(event.clientX, event.clientY);
const cellElement = element?.closest?.('td[data-col-id]');
const rowElement = cellElement?.closest?.('tr[data-row-id]');
if (!cellElement || !rowElement || !viewport.contains(cellElement)) return;
const rowVisibleIndex = visibleIndexById.get(rowElement.getAttribute('data-row-id') ?? '');
const columnIndex = columnIndexById.get(cellElement.getAttribute('data-col-id') ?? '');
if (rowVisibleIndex === undefined || columnIndex === undefined) return;
const rowsDelta = Math.max(0, rowVisibleIndex - sourceEndVisibleIndex);
const columnsDelta = Math.max(0, columnIndex - bound.maxColumnIndex);
const next: typeof extension =
rowsDelta === 0 && columnsDelta === 0
? null
: rowsDelta >= columnsDelta
? { axis: 'row', count: rowsDelta }
: { axis: 'column', count: columnsDelta };
if (next?.axis === extension?.axis && next?.count === extension?.count) {
return;
}
extension = next;
applyPreview();
};
const finish = (commit: boolean) => {
document.removeEventListener('mousemove', handleMove);
document.removeEventListener('mouseup', handleUp);
document.removeEventListener('keydown', handleKey, true);
clearPreview();
previewOutline.remove();
viewport.removeAttribute('data-cell-filling');
if (!commit || !extension || !onCellsChange) return;
const targets = getExtensionTargets();
if (!targets || !targets.rowEntries.length) return;
const changes: DataGridCellChange<TData>[] = [];
const rejected: DataGridCellRejection[] = [];
if (extension.axis === 'row') {
for (let offset = 0; offset < targets.rowEntries.length; offset++) {
const targetRow = targets.rowEntries[offset]!.row;
const sourceRow = sourceRows[offset % sourceRows.length]!.row;
const targetCells = targetRow.getAllCellsByColumnId();
const sourceCells = sourceRow.getAllCellsByColumnId();
for (const { column } of targets.columnEntries) {
if (!getDataGridWritableCellEdit<TData>(column, targetRow.original)) {
continue;
}
changes.push({
rowId: targetRow.id,
columnId: column.id,
row: targetRow.original,
previousValue: targetCells[column.id]?.getValue(),
value: sourceCells[column.id]?.getValue(),
});
}
}
} else {
const regionColumns = bound.maxColumnIndex - bound.minColumnIndex + 1;
for (const { row } of targets.rowEntries) {
const cells = row.getAllCellsByColumnId();
for (const { column: targetColumn, displayIndex } of targets.columnEntries) {
const offset = displayIndex - (bound.maxColumnIndex + 1);
const sourceColumn = columns[bound.minColumnIndex + (offset % regionColumns)];
if (!sourceColumn) continue;
const targetEdit = getDataGridWritableCellEdit<TData>(targetColumn, row.original);
if (!targetEdit) continue;
const sourceValue = cells[sourceColumn.id]?.getValue();
let value: unknown = sourceValue;
// Crossing columns is a type boundary: round-trip through the
// source's format and the target's parse, exactly what pasting
// the same cells would do. Same-column fills keep raw values.
if (targetColumn.id !== sourceColumn.id && targetEdit.parse) {
const sourceFormat = sourceColumn.columnDef.meta?.cellEdit?.format;
const raw = sourceFormat ? sourceFormat(sourceValue, row.original) : String(sourceValue ?? '');
const parsed = targetEdit.parse(raw, row.original);
if (parsed === undefined) {
rejected.push({
rowId: row.id,
columnId: targetColumn.id,
raw,
reason: 'invalid',
});
continue;
}
value = parsed;
}
changes.push({
rowId: row.id,
columnId: targetColumn.id,
row: row.original,
previousValue: cells[targetColumn.id]?.getValue(),
value,
});
}
}
}
if (changes.length || rejected.length) {
onCellsChange({ source: 'fill', changes, rejected });
}
// Grow the selection over source plus filled cells, Excel's post-fill
// shape.
selectDataGridRegion(table, {
startRowIndex: bound.minRowIndex,
endRowIndex: extension.axis === 'row' ? targets.rowEntries[targets.rowEntries.length - 1]!.displayIndex : bound.maxRowIndex,
startColumnIndex: bound.minColumnIndex,
endColumnIndex: bound.maxColumnIndex + (extension.axis === 'column' ? extension.count : 0),
});
};
const handleUp = () => finish(true);
// Capture phase so a cancel cannot also reach the grid's own Escape
// handling and clear the selection underneath the drag.
const handleKey = (event: KeyboardEvent) => {
if (event.key !== 'Escape') return;
event.stopPropagation();
finish(false);
};
document.addEventListener('mousemove', handleMove);
document.addEventListener('mouseup', handleUp);
document.addEventListener('keydown', handleKey, true);
}
/* ------------------------------------------------------------------------- *
* Controller.
* ------------------------------------------------------------------------- */
function isDataGridEditableTarget(target: EventTarget | null): boolean {
// data-cell-interactive is the same opt-out the mousedown guard honors, so
// a custom widget keeps its own keys and clipboard as well as its clicks.
return target instanceof Element && target.closest('input, textarea, select, [contenteditable], [data-cell-interactive]') != null;
}
// Keys belong to a focused in-cell control the same way clicks do: the
// button, link and checkbox set the mousedown guard exempts must keep its
// native Enter, Space and Tab, or an in-cell button is keyboard-dead.
// Clipboard stays on the narrower guard: copying the grid selection while a
// button happens to hold focus is what a spreadsheet user expects.
function isDataGridInteractiveKeyTarget(target: EventTarget | null): boolean {
return isDataGridEditableTarget(target) || (target instanceof Element && target.closest('button, a, [role="checkbox"]') != null);
}
/**
* Headless spreadsheet controller: keyboard navigation, clipboard, clear and
* the fill-handle drag. Mount once inside `<DataGrid>`, next to the table.
* Renders only a hidden anchor; the real listeners attach to the grid's own
* body viewport, which also receives focus (container-focus model), so a
* virtualized row unmounting can never strand `document.activeElement`.
*/
function DataGridCellSelection<TData extends object>({
apiRef,
clipboard = true,
keyboard = true,
}: {
/** Receives the controller's imperative API, e.g. for create-row flows. */
apiRef?: RefObject<DataGridCellSelectionApi | null>;
/** Native copy, cut and paste handling. Defaults to true. */
clipboard?: boolean;
/**
* Arrows (with Ctrl/Cmd edge jumps), Home/End, PageUp/PageDown, Enter,
* F2, type-to-edit, Tab, Ctrl/Cmd+A, Delete, Escape. Defaults to true.
*/
keyboard?: boolean;
}) {
// The context value serves `table` and `props` through getters over the
// provider's own refs, so a context object captured at mount keeps handing
// out the CURRENT instances; no ref mirror is needed here.
const context = useDataGrid<TData>();
const anchorRef = useRef<HTMLSpanElement | null>(null);
// The body viewport, once the wiring effect resolves it; the built-in
// editor overlay portals into it so it scrolls with the cells.
const [viewportEl, setViewportEl] = useState<HTMLElement | null>(null);
const [editorSession, setEditorSession] = useState<DataGridEditorSession | null>(null);
const { table } = context;
const enabled = !!context.props.tableLayout?.cellSelection && table.atoms.cellSelection != null;
useEffect(() => {
if (!enabled) return;
const anchor = anchorRef.current;
if (!anchor) return;
const root = (anchor.closest('[data-slot="data-grid"]') ?? anchor.parentElement) as HTMLElement | null;
if (!root) return;
// Split header/body grids render two viewports; the body one owns focus.
const viewports = Array.from(root.querySelectorAll<HTMLElement>('[data-slot="data-grid-table-viewport"]'));
const viewport = viewports.find((node) => node.querySelector('[data-slot="data-grid-table-body"]')) ?? viewports[0];
if (!viewport) return;
const getTable = () => context.table;
const getOnCellsChange = () => context.props.onCellsChange ?? null;
// "single" collapses every grow gesture to the focused cell.
const isRangeSelectionEnabled = () => context.props.tableLayout?.cellSelectionMode !== 'single';
// The focusable element of the container-focus model. The table carries
// role="grid", so putting DOM focus (and aria-activedescendant) on it is
// what lets a screen reader follow the focused cell.
const focusTarget = viewport.querySelector<HTMLElement>('table[data-slot="data-grid-table"]') ?? viewport;
const scrollTdIntoView = (cell: Element | null) =>
// Optional call: jsdom and some embedded contexts ship elements
// without scrollIntoView.
cell?.scrollIntoView?.({
block: 'nearest',
inline: 'nearest',
behavior: 'instant',
});
// Points assistive tech at the virtually focused cell.
const syncActiveDescendant = () => {
const cell = viewport.querySelector<HTMLElement>('td[data-cell-focused]');
if (cell?.id) focusTarget.setAttribute('aria-activedescendant', cell.id);
else focusTarget.removeAttribute('aria-activedescendant');
};
const scrollFocusedIntoView = (
targetRowIndex?: number,
rowCount?: number,
// A Shift-extend grows away from the focused cell, which stays the
// anchor; the caller names the range's active corner so the view
// follows the growing edge instead of snapping back to the anchor.
explicitCell?: { rowId: string; columnId: string },
) => {
const queryScrollCell = () =>
explicitCell
? viewport.querySelector(`tr[data-row-id="${CSS.escape(explicitCell.rowId)}"] td[data-col-id="${CSS.escape(explicitCell.columnId)}"]`)
: viewport.querySelector('td[data-cell-focused]');
// After the atom write React still has to commit the data attributes;
// rAF lands after that commit. Instant, because the app-level
// scroll-smooth would otherwise animate every keystroke.
requestAnimationFrame(() => {
const cell = queryScrollCell();
syncActiveDescendant();
if (cell || targetRowIndex == null || !rowCount) {
scrollTdIntoView(cell);
return;
}
// Virtualization: the jump target is not mounted, so there is no td
// to scroll to. The spacer rows keep scrollHeight proportional to
// the row count, so estimate the offset, let the virtualizer mount
// the region, then finish with a precise nearest-scroll.
let scroller: HTMLElement | null = viewport;
while (scroller && scroller.scrollHeight <= scroller.clientHeight) {
scroller = scroller.parentElement;
}
if (!scroller) return;
scroller.scrollTop = ((targetRowIndex + 0.5) / rowCount) * scroller.scrollHeight - scroller.clientHeight / 2;
requestAnimationFrame(() => {
scrollTdIntoView(queryScrollCell());
syncActiveDescendant();
});
});
};
// Opens an editor for the focused writable cell: the grid's own overlay
// for a column with a built-in `control`, the consumer's via
// `onCellEditRequest` otherwise, and as a last resort the cell's own
// interactive content (activated the way a mouse would). Returns false
// when nothing can open so the caller falls back to plain navigation.
const requestCellEdit = (initialText?: string): boolean => {
const table = getTable();
const cell = table.getFocusedCell();
if (!cell) return false;
const cellEdit = getDataGridWritableCellEdit<TData>(cell.column, cell.row.original);
if (cellEdit?.control) {
const baseline = cellEdit.format ? cellEdit.format(cell.getValue(), cell.row.original) : String(cell.getValue() ?? '');
const headerTitle = cell.column.columnDef.meta?.headerTitle;
const header = cell.column.columnDef.header;
setEditorSession({
rowId: cell.row.id,
columnId: cell.column.id,
control: cellEdit.control,
initialValue: initialText ?? baseline,
baseline,
label: typeof headerTitle === 'string' ? headerTitle : typeof header === 'string' ? header : cell.column.id,
});
return true;
}
const onCellEditRequest = context.props.onCellEditRequest;
if (cellEdit && onCellEditRequest) {
onCellEditRequest({
rowId: cell.row.id,
columnId: cell.column.id,
row: cell.row.original,
previousValue: cell.getValue(),
initialText,
});
return true;
}
// Generic activation: a custom control rendered in the cell (a
// select trigger, a combobox input, a button) toggles from the
// keyboard without any consumer wiring - focus it and click it,
// the same gesture the mouse performs. The lookup is ORDERED so an
// incidental button (a chip's remove button before a combobox
// input) never outranks the cell's primary control.
// Deliberate activation only (Enter, F2, double-click): typing a
// printable character must never toggle a control it cannot type
// into, and there is nowhere to put the character.
if (initialText !== undefined) return false;
const focusedCell = viewport.querySelector('td[data-cell-focused]');
const control = focusedCell
? ['[role="combobox"]', 'select', 'input, textarea', 'button, a, [role="checkbox"], [tabindex]:not([tabindex="-1"])']
.map((candidate) => focusedCell.querySelector<HTMLElement>(candidate))
.find(Boolean)
: null;
if (!control) return false;
control.focus();
control.click();
return true;
};
// The imperative surface. A consumer that creates a row cannot focus
// its cell through state alone: setFocusedCell needs the row in the
// table model, DOM focus needs the focus target, and both race the
// commit that mounts the row. One bounded timer retry (timers, unlike
// animation frames, run in background tabs) settles all of it in order.
let focusRetryTimer: ReturnType<typeof setTimeout> | undefined;
const focusCell: DataGridCellSelectionApi['focusCell'] = (rowId, columnId, options) => {
// A newer call supersedes any chain still polling for an older row.
clearTimeout(focusRetryTimer);
let attempts = 12;
const attempt = () => {
// The grid can unmount mid-retry; a stale timer must go quiet.
if (!viewport.isConnected) return;
const cell = viewport.querySelector<HTMLElement>(`tr[data-row-id="${CSS.escape(rowId)}"] td[data-col-id="${CSS.escape(columnId)}"]`);
if (!cell) {
if (attempts-- > 0) focusRetryTimer = setTimeout(attempt, 32);
return;
}
getTable().setFocusedCell(rowId, columnId);
focusTarget.focus();
// The cell's id is static, so assistive tech can point at it ahead
// of the data-cell-focused commit the rAF sync waits for.
if (cell.id) focusTarget.setAttribute('aria-activedescendant', cell.id);
scrollTdIntoView(cell);
if (!options?.edit) return;
// The built-in overlay measures td[data-cell-focused], so the edit
// request waits for that attribute to land.
let editAttempts = 12;
const attemptEdit = () => {
if (!cell.isConnected) return;
if (cell.hasAttribute('data-cell-focused')) requestCellEdit();
else if (editAttempts-- > 0) {
focusRetryTimer = setTimeout(attemptEdit, 32);
}
};
attemptEdit();
};
attempt();
};
const clearSelection = () => {
getTable().resetCellSelection(true);
requestAnimationFrame(syncActiveDescendant);
};
const scrollToCell = (rowId: string, columnId: string) => {
scrollTdIntoView(viewport.querySelector(`tr[data-row-id="${CSS.escape(rowId)}"] td[data-col-id="${CSS.escape(columnId)}"]`));
};
if (apiRef) apiRef.current = { focusCell, clearSelection, scrollToCell };
// Resolves jump targets (Home, End, Ctrl+Arrows, PageUp/PageDown) in the
// feature's display-index space and lands them through the range API:
// plain jumps collapse to the target cell, Shift jumps keep the active
// range's opposite corner as the anchor, the Excel model.
const jumpFocus = (
rowTarget: 'first' | 'last' | 'same' | { delta: number },
columnTarget: 'first' | 'last' | 'same',
extend: boolean,
): boolean => {
const table = getTable();
const focused = table.getFocusedCell();
if (!focused) return false;
const rows = table.getRowsInDisplayOrder();
const allColumns = getDataGridDisplayOrderedColumns(table);
const selectable = allColumns.filter((column) => column.columnDef.enableCellSelection !== false);
if (!rows.length || !selectable.length) return false;
const rowIndex = focused.row.getDisplayIndex();
const targetRowIndex =
rowTarget === 'first'
? 0
: rowTarget === 'last'
? rows.length - 1
: rowTarget === 'same'
? rowIndex
: Math.min(rows.length - 1, Math.max(0, rowIndex + rowTarget.delta));
// Pagination renders a window of the display order; walk the target
// back toward the focus until it lands on a rendered row, so a jump
// can never focus an off-page row the view cannot show. DOM rows
// join the set so pinned rows outside the page slice stay reachable.
let clampedRowIndex = targetRowIndex;
// With the whole display order in the page slice nothing is off-page
// and the clamp cannot move, so skip building the id set.
if (table.getRowModel().rows.length !== rows.length) {
const rendered = new Set<string | null>(table.getRowModel().rows.map((row: { id: string }) => row.id));
for (const rowEl of Array.from(viewport.querySelectorAll('tbody tr[data-row-id]'))) {
rendered.add(rowEl.getAttribute('data-row-id'));
}
const step = clampedRowIndex >= rowIndex ? -1 : 1;
while (clampedRowIndex !== rowIndex && rows[clampedRowIndex] && !rendered.has(rows[clampedRowIndex].id)) {
clampedRowIndex += step;
}
}
const targetRow = rows[clampedRowIndex];
const targetColumn = columnTarget === 'first' ? selectable[0] : columnTarget === 'last' ? selectable[selectable.length - 1] : focused.column;
if (!targetRow || !targetColumn) return false;
if (extend) {
const bound = getDataGridActiveBound(table);
const columnIndex = allColumns.findIndex((column) => column.id === focused.column.id);
let anchorRowId = focused.row.id;
let anchorColumnId = focused.column.id;
if (bound) {
anchorRowId = rows[rowIndex === bound.minRowIndex ? bound.maxRowIndex : bound.minRowIndex]?.id ?? anchorRowId;
anchorColumnId = allColumns[columnIndex === bound.minColumnIndex ? bound.maxColumnIndex : bound.minColumnIndex]?.id ?? anchorColumnId;
}
table.selectCellRange(
{
anchorRowId,
anchorColumnId,
focusRowId: targetRow.id,
focusColumnId: targetColumn.id,
},
{ mode: 'replace' },
);
} else {
table.setFocusedCell(targetRow.id, targetColumn.id);
}
scrollFocusedIntoView(
clampedRowIndex,
rows.length,
// The extend keeps focus on the anchor; follow the jump target.
extend ? { rowId: targetRow.id, columnId: targetColumn.id } : undefined,
);
return true;
};
// One visual-space focus step with the feature's move as the fallback
// for unresolvable positions; at an edge the focus stays put.
const moveFocusVisual = (direction: 'up' | 'down' | 'left' | 'right'): void => {
const table = getTable();
const focused = table.getFocusedCell();
const target = focused ? getDataGridStepTarget(table, viewport, { rowId: focused.row.id, columnId: focused.column.id }, direction) : null;
if (target === 'edge') return;
if (target) {
table.setFocusedCell(target.rowId, target.columnId);
return;
}
table.moveCellSelection(direction);
};
// One viewport's worth of rows for PageUp/PageDown, measured from the
// live layout; 10 when nothing is measurable (jsdom). Data rows only:
// the virtual table's spacer rows carry the whole scroll offset as
// height and would collapse the page size to a single row.
const getPageJumpSize = (): number => {
const row = viewport.querySelector('tbody tr[data-row-id]');
// The nearest ancestor that actually scrolls; in the scroll-area
// layout the viewport's parent is a full-height content wrapper
// whose clientHeight would make the page span the whole table.
let scroller: HTMLElement | null = viewport;
while (scroller && scroller.scrollHeight <= scroller.clientHeight) {
scroller = scroller.parentElement;
}
const rowHeight = row?.getBoundingClientRect().height || 0;
const viewHeight = scroller?.clientHeight || viewport.clientHeight;
if (!rowHeight || !viewHeight) return 10;
return Math.max(1, Math.floor(viewHeight / rowHeight) - 1);
};
// The rows appended after the data rows: the add-row affordance and a
// consumer appendRow draft. Positional, because an id-less tr is not
// enough - expanded-detail rows interleave BETWEEN data rows and the
// empty-state row stands alone, and neither belongs to this region.
// Virtual spacer rows are aria-hidden and never match.
const getAppendedRows = (): HTMLElement[] => {
const body = viewport.querySelector('tbody');
const appended: HTMLElement[] = [];
// Backwards from the end, stopping at the first data row: O(appended)
// instead of an array of every rendered row per keystroke.
let rowEl = body?.lastElementChild;
while (rowEl && !rowEl.hasAttribute('data-row-id')) {
if (rowEl instanceof HTMLElement && !rowEl.hasAttribute('aria-hidden')) {
appended.unshift(rowEl);
}
rowEl = rowEl.previousElementSibling;
}
return appended;
};
const focusFirstIn = (row: HTMLElement | undefined): boolean => {
const focusable = row?.querySelector<HTMLElement>('button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])');
if (!focusable) return false;
focusable.focus();
// A control that refuses focus (hidden, inert) must not report
// success, or the arrow key that called this dead-ends.
return row!.ownerDocument.activeElement === focusable;
};
const handleKeyDown = (event: KeyboardEvent) => {
if (event.defaultPrevented) return;
// Unified keyboard for the appended region: ArrowDown/ArrowUp walk
// between its rows, and ArrowUp from its first row returns to the
// grid's cell navigation. Every other key stays native there.
const appendedRow = event.target instanceof Element ? (event.target.closest('tbody > tr:not([data-row-id])') as HTMLElement | null) : null;
if (appendedRow && viewport.contains(appendedRow)) {
const appended = getAppendedRows();
const index = appended.indexOf(appendedRow);
// An id-less row that is NOT appended (expanded detail content,
// the empty-state row) keeps every key native.
if (index === -1) return;
if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return;
if (event.key === 'ArrowDown') {
if (focusFirstIn(appended[index + 1])) event.preventDefault();
return;
}
if (index > 0 && focusFirstIn(appended[index - 1])) {
event.preventDefault();
return;
}
// Back into the grid, on whatever cell was focused last.
focusTarget.focus();
syncActiveDescendant();
event.preventDefault();
return;
}
if (isDataGridInteractiveKeyTarget(event.target)) {
// The ARIA grid pattern's exit gesture: Escape on an in-cell
// control hands DOM focus back to the grid so navigation resumes.
// A control that consumed the key first (closing its own popup)
// never lets it reach here unprevented, and portal-rendered
// popups keep their Escape entirely outside the viewport.
if (event.key === 'Escape') {
const cell = (event.target as Element).closest?.('td[data-col-id]');
if (cell && viewport.contains(cell)) {
event.preventDefault();
event.stopPropagation();
focusTarget.focus();
syncActiveDescendant();
}
}
return;
}
const table = getTable();
const rtl = getComputedStyle(viewport).direction === 'rtl';
const horizontal = (direction: 'left' | 'right') => (rtl ? (direction === 'left' ? 'right' : 'left') : direction);
// Ahead of the switch so plain letters still reach the type-to-edit
// fall-through below. Matched by code as well as key, so non-Latin
// layouts (where the key is the layout's own character) still work.
if (
(event.key === 'a' || event.key === 'A' || event.code === 'KeyA') &&
(event.metaKey || event.ctrlKey) &&
// AltGr arrives as Ctrl+Alt; that chord types a character on
// central-European layouts and is not a select-all.
!event.altKey
) {
if (isRangeSelectionEnabled()) {
table.selectAllCells();
// Select-all moves the feature's focus to the range corner,
// which can sit off-page; keep assistive tech pointed right.
requestAnimationFrame(syncActiveDescendant);
}
event.preventDefault();
return;
}
// Explicit copy and cut chords; see writeSelectionToClipboard for
// why the native copy event cannot carry these. Paste stays on the
// native event, which browsers do fire at the focused element.
if ((event.metaKey || event.ctrlKey) && !event.altKey && clipboard) {
const isCopy = event.key === 'c' || event.key === 'C' || event.code === 'KeyC';
const isCut = event.key === 'x' || event.key === 'X' || event.code === 'KeyX';
if (isCopy || isCut) {
event.preventDefault();
void writeSelectionToClipboard().then((written) => {
if (!written) return;
context.props.onCellsCopy?.({ ...written, cut: isCut });
if (!isCut) return;
const onCellsChange = getOnCellsChange();
if (!onCellsChange) return;
const details = buildDataGridClearDetails<TData>(getTable(), 'cut', true, viewport);
if (details) onCellsChange(details);
});
return;
}
}
switch (event.key) {
case 'ArrowUp':
case 'ArrowDown':
case 'ArrowLeft':
case 'ArrowRight': {
const direction =
event.key === 'ArrowUp'
? ('up' as const)
: event.key === 'ArrowDown'
? ('down' as const)
: horizontal(event.key === 'ArrowLeft' ? 'left' : 'right');
if (event.metaKey || event.ctrlKey) {
// Ctrl/Cmd+Arrow jumps to the grid edge in that direction.
const jumped =
direction === 'up'
? jumpFocus('first', 'same', event.shiftKey && isRangeSelectionEnabled())
: direction === 'down'
? jumpFocus('last', 'same', event.shiftKey && isRangeSelectionEnabled())
: jumpFocus('same', direction === 'left' ? 'first' : 'last', event.shiftKey && isRangeSelectionEnabled());
if (jumped) event.preventDefault();
return;
}
// ArrowDown on the last rendered row steps into the appended
// region (a draft row, or the add-row affordance), keeping one
// keyboard model across the whole table.
if (direction === 'down' && !event.shiftKey) {
const focused = table.getFocusedCell();
const renderedRows = viewport.querySelectorAll('tbody tr[data-row-id]');
const lastRenderedId = renderedRows[renderedRows.length - 1]?.getAttribute('data-row-id');
if (focused && lastRenderedId && focused.row.id === lastRenderedId && focusFirstIn(getAppendedRows()[0])) {
event.preventDefault();
return;
}
}
if (event.shiftKey && isRangeSelectionEnabled()) {
const corner = extendDataGridSelection(table, viewport, direction);
event.preventDefault();
scrollFocusedIntoView(undefined, undefined, corner ?? undefined);
return;
}
// Plain arrows step in visual space so navigation crosses
// pinned rows and pagination windows the feature's own move
// cannot resolve; at a visual edge the focus stays put.
const focused = table.getFocusedCell();
const target = focused ? getDataGridStepTarget(table, viewport, { rowId: focused.row.id, columnId: focused.column.id }, direction) : null;
if (target === 'edge') {
event.preventDefault();
return;
}
if (target) {
table.setFocusedCell(target.rowId, target.columnId);
event.preventDefault();
scrollFocusedIntoView();
return;
}
table.moveCellSelection(direction);
event.preventDefault();
scrollFocusedIntoView();
return;
}
case 'Home':
case 'End': {
// Home/End: row start or end; with Ctrl/Cmd, the grid's corners.
const edge = event.key === 'Home' ? ('first' as const) : ('last' as const);
const jumped =
event.metaKey || event.ctrlKey
? jumpFocus(edge, edge, event.shiftKey && isRangeSelectionEnabled())
: jumpFocus('same', edge, event.shiftKey && isRangeSelectionEnabled());
if (jumped) event.preventDefault();
return;
}
case 'PageUp':
case 'PageDown': {
const delta = (event.key === 'PageUp' ? -1 : 1) * getPageJumpSize();
if (jumpFocus({ delta }, 'same', event.shiftKey && isRangeSelectionEnabled())) {
event.preventDefault();
}
return;
}
case 'Enter': {
// The Notion/Airtable flow: Enter opens the editor when one is
// wired; the Excel move-down stays the fallback.
if (!event.shiftKey && requestCellEdit()) {
event.preventDefault();
return;
}
moveFocusVisual(event.shiftKey ? 'up' : 'down');
event.preventDefault();
scrollFocusedIntoView();
return;
}
case 'F2': {
if (requestCellEdit()) event.preventDefault();
return;
}
case 'Tab': {
const before = table.getFocusedCell();
// Logical directions, no RTL swap: Tab means "next cell" in both
// reading directions, exactly like DOM tab order.
moveFocusVisual(event.shiftKey ? 'left' : 'right');
const after = table.getFocusedCell();
// Trap Tab only while it moved; at the edges focus leaves the grid,
// which keyboard users need to escape it at all.
if (after && after.id !== before?.id) {
event.preventDefault();
scrollFocusedIntoView();
}
return;
}
case 'Delete':
case 'Backspace': {
const onCellsChange = getOnCellsChange();
if (!onCellsChange) return;
const details = buildDataGridClearDetails<TData>(table, 'clear', false, viewport);
if (details) onCellsChange(details);
event.preventDefault();
return;
}
case 'Escape': {
// Consume the key only while it has a selection to clear, so a
// grid inside a dialog still lets Escape close the dialog.
if (table.getCellSelectionBounds().length) {
table.resetCellSelection(true);
// The focused-cell attribute is gone after the commit;
// aria-activedescendant must not keep naming it.
requestAnimationFrame(syncActiveDescendant);
event.preventDefault();
event.stopPropagation();
}
return;
}
}
// Space on a cell whose content is a checkbox toggles it, the
// row-select idiom, so the selection column works by keyboard too.
if (event.key === ' ') {
const checkbox = viewport.querySelector('td[data-cell-focused]')?.querySelector<HTMLElement>('[role="checkbox"], input[type="checkbox"]');
if (checkbox) {
checkbox.click();
event.preventDefault();
return;
}
}
// Type-to-edit: a printable character on the focused cell opens the
// editor seeded with it, replacing the value the way Notion and
// Airtable do. Plain Ctrl/Cmd chords stay shortcuts, but Ctrl+Alt is
// AltGr and bare Alt is the macOS Option layer - both type characters.
if (event.key.length === 1 && !event.metaKey && !(event.ctrlKey && !event.altKey) && requestCellEdit(event.key)) {
event.preventDefault();
return;
}
// Space that opened nothing (read-only cell) must not scroll the page
// out from under the focused cell.
if (event.key === ' ' && table.getFocusedCell()) {
event.preventDefault();
}
};
// Writes the active region to the system clipboard in both flavors.
// Needed because a native copy event only fires for a text selection
// or an editable target, and a focused grid is neither - Cmd/Ctrl+C
// would silently do nothing on macOS, Windows and Linux alike. The
// async API needs a secure context; the execCommand fallback covers
// the rest with the TSV flavor alone.
const writeSelectionToClipboard = async (): Promise<{
text: string;
grid: string[][];
} | null> => {
const grid = getDataGridActiveRegionGrid(getTable(), viewport);
if (!grid) return null;
const text = serializeDataGridClipboardText(grid);
try {
if (typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {
await navigator.clipboard.write([
new ClipboardItem({
'text/plain': new Blob([text], { type: 'text/plain' }),
'text/html': new Blob([renderDataGridClipboardHtml(grid)], {
type: 'text/html',
}),
}),
]);
return { text, grid };
}
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
return { text, grid };
}
} catch {
// Denied or unavailable; the legacy path below still applies.
}
const doc = viewport.ownerDocument;
const scratch = doc.createElement('textarea');
scratch.value = text;
scratch.style.position = 'fixed';
scratch.style.opacity = '0';
doc.body.appendChild(scratch);
scratch.select();
let copied = false;
try {
copied = doc.execCommand('copy');
} catch {
copied = false;
}
scratch.remove();
focusTarget.focus();
return copied ? { text, grid } : null;
};
const copySelection = (event: ClipboardEvent, cut: boolean): boolean => {
const grid = getDataGridActiveRegionGrid(getTable(), viewport);
if (!grid || !event.clipboardData) return false;
event.preventDefault();
const text = serializeDataGridClipboardText(grid);
event.clipboardData.setData('text/plain', text);
event.clipboardData.setData('text/html', renderDataGridClipboardHtml(grid));
context.props.onCellsCopy?.({ text, grid, cut });
return true;
};
const handleCopy = (event: ClipboardEvent) => {
if (isDataGridEditableTarget(event.target)) return;
copySelection(event, false);
};
const handleCut = (event: ClipboardEvent) => {
if (isDataGridEditableTarget(event.target)) return;
if (!copySelection(event, true)) return;
const onCellsChange = getOnCellsChange();
if (!onCellsChange) return;
const details = buildDataGridClearDetails<TData>(getTable(), 'cut', true, viewport);
if (details) onCellsChange(details);
};
const handlePaste = (event: ClipboardEvent) => {
if (isDataGridEditableTarget(event.target)) return;
const onCellsChange = getOnCellsChange();
if (!onCellsChange) return;
const text = event.clipboardData?.getData('text/plain');
if (!text) return;
event.preventDefault();
const table = getTable();
const result = buildDataGridPasteDetails<TData>(table, parseDataGridClipboardText(text), viewport);
if (!result) return;
onCellsChange(result.details);
// The pasted region becomes the selection, the documented contract;
// single mode keeps just the focused cell instead.
if (isRangeSelectionEnabled()) {
selectDataGridRegion(table, result.target);
}
};
// Custom-control cells follow the same two-step gesture as editor
// cells: the first click on an UNFOCUSED cell only focuses it, the
// second activates the control, so moving the focus around can never
// fire actions. Radix triggers open on pointerdown and Base UI ones
// on click, so the press is intercepted at both; checkboxes keep
// their one-click toggle (the row-select idiom), data-cell-interactive
// widgets own all their gestures, and single-click edit mode skips
// the interception outright.
let pressedUnfocusedControl = false;
const getTwoStepControl = (target: EventTarget | null): Element | null => {
if (!(target instanceof Element)) return null;
if (target.closest('[data-cell-interactive]')) return null;
if (target.closest('[role="checkbox"], input[type="checkbox"]')) {
return null;
}
// Opt-in for widgets whose ACTIVE surface is bigger than any generic
// selector can know - a combobox whose whole blank chips strip opens
// it, a canvas editor. Marking the wrapper data-cell-control makes a
// press anywhere on it two-step, exactly like a bare button.
const marked = target.closest('[data-cell-control]');
if (marked) return marked;
return target.closest('button, a, select, input, textarea, [contenteditable], [role="combobox"]');
};
const handleControlPointerDown = (event: PointerEvent) => {
pressedUnfocusedControl = false;
if (event.button !== 0) return;
if (event.shiftKey || event.ctrlKey || event.metaKey) return;
if (context.props.tableLayout?.cellEditMode === 'click') return;
const control = getTwoStepControl(event.target);
const cell = control?.closest('td[data-col-id]');
if (!control || !cell || !viewport.contains(cell)) return;
if (cell.hasAttribute('data-cell-focused')) return;
const column = getTable().getColumn(cell.getAttribute('data-col-id') ?? '');
if (!column || column.columnDef.enableCellSelection === false) return;
pressedUnfocusedControl = true;
// Stops a Radix trigger's pointerdown open before React's root
// delegation sees it; the mouse events that focus the cell ride on.
event.stopPropagation();
};
const handleControlClick = (event: MouseEvent) => {
if (!pressedUnfocusedControl) return;
pressedUnfocusedControl = false;
// Swallows the activation click a Base UI trigger listens for.
event.preventDefault();
event.stopPropagation();
};
const handleControlMouseDown = (event: MouseEvent) => {
if (!pressedUnfocusedControl) return;
// A Base UI trigger opens on the React-delegated mousedown, and all
// root-delegated handlers die together when the event stops here -
// including the td's own focus logic, so the selection start runs
// imperatively: same feature handler, same drag session.
event.stopPropagation();
event.preventDefault();
const cell = (event.target as Element | null)?.closest?.('td[data-col-id]');
const rowId = cell?.closest('tr[data-row-id]')?.getAttribute('data-row-id');
const columnId = cell?.getAttribute('data-col-id');
if (!rowId || !columnId) return;
const tableNow = getTable();
const cellApi = tableNow
.getRowsInDisplayOrder()
.find((row) => row.id === rowId)
?.getAllCellsByColumnId()[columnId];
if (!cellApi) return;
if (isRangeSelectionEnabled()) {
cellApi.getSelectionStartHandler()(event);
} else {
tableNow.setFocusedCell(rowId, columnId);
}
focusTarget.focus();
requestAnimationFrame(syncActiveDescendant);
};
// Drag-to-select outranks in-cell controls: when a drag grew the
// range, the click that fires on release is swallowed in capture so a
// trigger under the pointer never opens. The selection key comparison
// is what distinguishes a drag from a motionless click made while a
// multi-cell selection already exists (a press on "+ Add row" or an
// in-cell control changes nothing, and its click must go through).
let dragStartedOnCell = false;
let dragStartSelectionKey = '';
const getSelectionKey = () => {
const table = getTable();
const bounds = table.getCellSelectionBounds();
const bound = bounds[bounds.length - 1];
return `${table.getSelectedCellCount()}:${bounds.length}:${
bound ? `${bound.minRowIndex},${bound.minColumnIndex},${bound.maxRowIndex},${bound.maxColumnIndex}` : ''
}`;
};
const handleDragMouseUp = () => {
const wasDrag = dragStartedOnCell && getTable().getSelectedCellCount() > 1 && getSelectionKey() !== dragStartSelectionKey;
dragStartedOnCell = false;
viewport.removeAttribute('data-cell-selecting');
if (!wasDrag) return;
const squelch = (clickEvent: MouseEvent) => {
clickEvent.stopPropagation();
clickEvent.preventDefault();
};
viewport.addEventListener('click', squelch, { capture: true });
setTimeout(() => viewport.removeEventListener('click', squelch, true), 0);
};
const handleMouseDown = (event: MouseEvent) => {
if (event.button !== 0) return;
// The cell a click focuses reaches assistive tech once React commits.
requestAnimationFrame(syncActiveDescendant);
const target = event.target as Element | null;
// A modifier press is a selection gesture all the way through, the
// Sheets contract: extending must not hand the keyboard to whatever
// control sits under the pointer, or the follow-up Shift+arrows land
// in a date button or a combobox input instead of growing the range.
// The extension itself runs through the cell's own React handlers, so
// the event must NOT be defaultPrevented - the delegated handlers
// treat that as consumed and the extension never happens. Only the
// browser's focus default is unwanted; it runs after the listeners,
// so the grid reclaims focus one task later.
if ((event.shiftKey || event.metaKey || event.ctrlKey) && isRangeSelectionEnabled() && target?.closest?.('td[data-col-id]')) {
setTimeout(() => focusTarget.focus(), 0);
}
// Any td press can become a drag; the squelch only arms when the
// range actually grew by release time. The attribute hides the fill
// handle for the session, so its overhang never sits in the drag
// path or churns from cell to cell while the range grows.
dragStartedOnCell = !!target?.closest?.('td');
if (dragStartedOnCell) {
dragStartSelectionKey = getSelectionKey();
viewport.setAttribute('data-cell-selecting', '');
}
if (!target?.closest?.('[data-slot="data-grid-cell-fill-handle"]')) return;
// Ahead of React's root delegation, so the td underneath never starts a
// plain range drag from the handle.
event.preventDefault();
event.stopPropagation();
startDataGridFillSession<TData>({
table: getTable(),
viewport,
onCellsChange: getOnCellsChange(),
});
};
// Single-click editing, the opt-in mode: a plain click that landed
// on the (now) focused cell opens its editor immediately. Drags were
// squelched in capture before this bubble listener, and modifier
// clicks are selection gestures.
const handleClickToEdit = (event: MouseEvent) => {
if (context.props.tableLayout?.cellEditMode !== 'click') return;
if (event.shiftKey || event.ctrlKey || event.metaKey) return;
if (isDataGridInteractiveKeyTarget(event.target)) return;
const cell = (event.target as HTMLElement | null)?.closest?.('td');
if (!cell?.hasAttribute('data-cell-focused')) return;
requestCellEdit();
};
// Double-click opens the editor on the cell the first click focused,
// matching Sheets. Interactive content keeps its own double-clicks, and
// the clicked cell must BE the focused one, or a double-click on a
// non-selectable cell would edit whichever cell held focus before.
const handleDoubleClick = (event: MouseEvent) => {
if (isDataGridInteractiveKeyTarget(event.target)) return;
const target = event.target as HTMLElement | null;
const cell = target?.closest?.('td');
if (!cell?.hasAttribute('data-cell-focused')) return;
requestCellEdit();
};
const previousTabIndex = focusTarget.getAttribute('tabindex');
const previousOutline = focusTarget.style.outline;
if (keyboard) {
focusTarget.tabIndex = 0;
// The focused CELL ring is the indicator; the browser's outline around
// the whole grid on focus() would double it.
focusTarget.style.outline = 'none';
viewport.addEventListener('keydown', handleKeyDown);
}
if (clipboard) {
viewport.addEventListener('copy', handleCopy);
viewport.addEventListener('cut', handleCut);
viewport.addEventListener('paste', handlePaste);
}
viewport.addEventListener('pointerdown', handleControlPointerDown);
viewport.addEventListener('mousedown', handleControlMouseDown);
viewport.addEventListener('click', handleControlClick);
viewport.addEventListener('mousedown', handleMouseDown);
viewport.addEventListener('click', handleClickToEdit);
viewport.addEventListener('dblclick', handleDoubleClick);
viewport.ownerDocument.addEventListener('mouseup', handleDragMouseUp);
// Selection-change notifications, read through the context getter so
// the latest callback fires without re-running this effect. The
// snapshot is only built when a callback is actually wired.
const toBound = (bound: { minRowIndex: number; maxRowIndex: number; minColumnIndex: number; maxColumnIndex: number }) => ({
minRowIndex: bound.minRowIndex,
maxRowIndex: bound.maxRowIndex,
minColumnIndex: bound.minColumnIndex,
maxColumnIndex: bound.maxColumnIndex,
});
const selectionSubscription = table.atoms.cellSelection?.subscribe(() => {
const onCellSelectionChange = context.props.onCellSelectionChange;
if (!onCellSelectionChange) return;
const tableNow = getTable();
const focusedCell = tableNow.getFocusedCell();
const activeBound = getDataGridActiveBound(tableNow);
onCellSelectionChange({
focused: focusedCell ? { rowId: focusedCell.row.id, columnId: focusedCell.column.id } : null,
bounds: tableNow.getCellSelectionBounds().map(toBound),
activeBound: activeBound ? toBound(activeBound) : null,
visibleCellCount: getDataGridVisibleSelectedCellCount(tableNow, viewport),
});
});
setViewportEl(viewport);
return () => {
if (keyboard) {
if (previousTabIndex === null) focusTarget.removeAttribute('tabindex');
else focusTarget.setAttribute('tabindex', previousTabIndex);
focusTarget.style.outline = previousOutline;
focusTarget.removeAttribute('aria-activedescendant');
viewport.removeEventListener('keydown', handleKeyDown);
}
if (clipboard) {
viewport.removeEventListener('copy', handleCopy);
viewport.removeEventListener('cut', handleCut);
viewport.removeEventListener('paste', handlePaste);
}
viewport.removeEventListener('pointerdown', handleControlPointerDown);
viewport.removeEventListener('mousedown', handleControlMouseDown);
viewport.removeEventListener('click', handleControlClick);
viewport.removeEventListener('mousedown', handleMouseDown);
viewport.removeEventListener('click', handleClickToEdit);
viewport.removeEventListener('dblclick', handleDoubleClick);
viewport.ownerDocument.removeEventListener('mouseup', handleDragMouseUp);
viewport.removeAttribute('data-cell-selecting');
selectionSubscription?.unsubscribe();
clearTimeout(focusRetryTimer);
if (apiRef) apiRef.current = null;
setViewportEl(null);
setEditorSession(null);
};
// Context getters serve fresh table/props inside every handler, so the
// effect re-runs only when the table itself is replaced. apiRef is only
// read and written here: keeping it out of the deps means an inline ref
// object cannot tear the listeners down every render.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [enabled, keyboard, clipboard, table.store]);
// The editor overlay covers the cell but not the fill handle's
// straddling half, which would poke out beneath it; the viewport flags
// the session so the handle hides, as it does during a drag.
useEffect(() => {
if (!viewportEl || !editorSession) return;
viewportEl.setAttribute('data-cell-editing', '');
return () => viewportEl.removeAttribute('data-cell-editing');
}, [viewportEl, editorSession]);
// Closing an editor the user finished with keys hands focus back to the
// viewport so navigation continues where the edit left off; a commit can
// advance first (Tab across, and Enter down or up when
// cellEditEnterAdvance opts into the Sheets flow). A blur-initiated close
// must NOT refocus: the browser already moved focus where the user
// clicked, and yanking it back would reroute their next keystrokes into
// the grid.
const closeEditorSession = (advance: DataGridEditorAdvance, refocus = true) => {
setEditorSession(null);
if (advance) {
// Same visual-space step as keyboard navigation, so a commit on a
// pinned row advances like any other row.
const tableNow = context.table;
const focused = tableNow.getFocusedCell();
const target =
focused && viewportEl ? getDataGridStepTarget(tableNow, viewportEl, { rowId: focused.row.id, columnId: focused.column.id }, advance) : null;
if (target && target !== 'edge') {
tableNow.setFocusedCell(target.rowId, target.columnId);
} else if (!target) {
tableNow.moveCellSelection(advance);
}
}
if (!refocus) return;
requestAnimationFrame(() => {
const focusEl = viewportEl?.querySelector<HTMLElement>('table[data-slot="data-grid-table"]') ?? viewportEl;
focusEl?.focus();
const cell = viewportEl?.querySelector<HTMLElement>('td[data-cell-focused]');
if (cell?.id) focusEl?.setAttribute('aria-activedescendant', cell.id);
cell?.scrollIntoView?.({
block: 'nearest',
inline: 'nearest',
behavior: 'instant',
});
});
};
// An unchanged commit dispatches nothing, the Excel model; a parse
// rejection reports through the batch's rejected list instead of writing.
const commitEditorSession = (raw: string, advance: DataGridEditorAdvance, refocus = true) => {
const session = editorSession;
closeEditorSession(advance, refocus);
const onCellsChange = context.props.onCellsChange;
if (!session || !onCellsChange || raw === session.baseline) return;
const tableNow = context.table;
const row = tableNow.getRowsInDisplayOrder().find((candidate) => candidate.id === session.rowId);
const column = tableNow.getColumn(session.columnId);
const cellEdit = column && row ? getDataGridWritableCellEdit<TData>(column, row.original) : null;
if (!row || !column || !cellEdit) return;
const previousValue = row.getAllCellsByColumnId()[column.id]?.getValue();
let value: unknown = raw;
if (cellEdit.parse) {
const parsed = cellEdit.parse(raw, row.original);
if (parsed === undefined) {
onCellsChange({
source: 'edit',
changes: [],
rejected: [
{
rowId: session.rowId,
columnId: session.columnId,
raw,
reason: 'invalid',
},
],
});
return;
}
value = parsed;
}
onCellsChange({
source: 'edit',
changes: [
{
rowId: session.rowId,
columnId: session.columnId,
row: row.original,
previousValue,
value,
},
],
rejected: [],
});
};
return (
<>
<span ref={anchorRef} hidden data-slot="data-grid-cell-selection" />
{enabled && viewportEl && editorSession ? (
<DataGridCellEditorOverlay
key={`${editorSession.rowId}:${editorSession.columnId}`}
viewport={viewportEl}
session={editorSession}
enterAdvance={context.props.tableLayout?.cellEditEnterAdvance === true}
onCommit={commitEditorSession}
onCancel={() => closeEditorSession(null)}
/>
) : null}
</>
);
}
/**
* The built-in free-text editor: a portal into the body viewport, positioned
* flush over the focused cell with the cell's own font, alignment and
* padding, so the text keeps its exact place - the Sheets model. The
* `textarea` control grows downward over the rows below as the text wraps.
*/
function measureDataGridCellEditorStyle(viewport: HTMLElement): CSSProperties | null {
const cell = viewport.querySelector<HTMLElement>('td[data-cell-focused]');
if (!cell) return null;
const cellRect = cell.getBoundingClientRect();
const viewportRect = viewport.getBoundingClientRect();
const cellStyle = getComputedStyle(cell);
// The td centers its one line vertically (align-middle); the editor must
// put the text in exactly the same place or opening it shifts the value.
// Symmetric block padding sized to center one line does that for the
// textarea too, and keeps holding as it grows line by line.
const lineHeight = Number.parseFloat(cellStyle.lineHeight) || Number.parseFloat(cellStyle.fontSize) * 1.5 || 20;
const centeredBlockPadding = Math.max(Number.parseFloat(cellStyle.paddingTop) || 0, (cellRect.height - lineHeight) / 2);
return {
// Rect deltas are visual; when the viewport itself is the scroll
// container (the standalone virtual layout), absolute children live in
// content coordinates, so the scroll offset must be added back. The box
// matches the cell exactly - editing must not change the cell's
// geometry - and the cell's own overlay chrome hides for the session
// (data-cell-editing), so the editor's outline is the ONE border.
left: cellRect.left - viewportRect.left + viewport.scrollLeft,
top: cellRect.top - viewportRect.top + viewport.scrollTop,
width: cellRect.width,
minHeight: cellRect.height,
// The font shorthand can serialize empty (Firefox); the longhands after
// it win where set and cover that case.
font: cellStyle.font || undefined,
fontFamily: cellStyle.fontFamily,
fontSize: cellStyle.fontSize,
fontWeight: cellStyle.fontWeight,
fontStyle: cellStyle.fontStyle,
lineHeight: cellStyle.lineHeight,
letterSpacing: cellStyle.letterSpacing,
textAlign: cellStyle.textAlign as CSSProperties['textAlign'],
paddingLeft: cellStyle.paddingLeft,
paddingRight: cellStyle.paddingRight,
paddingTop: centeredBlockPadding,
paddingBottom: centeredBlockPadding,
};
}
function DataGridCellEditorOverlay({
viewport,
session,
enterAdvance,
onCommit,
onCancel,
}: {
viewport: HTMLElement;
session: DataGridEditorSession;
enterAdvance: boolean;
onCommit: (raw: string, advance: DataGridEditorAdvance, refocus?: boolean) => void;
onCancel: () => void;
}) {
// Measured lazily at first render: the focused td was committed before the
// session opened, and the overlay remounts per cell via its key, so one
// measurement holds for the editor's lifetime.
const [style] = useState<CSSProperties | null>(() => measureDataGridCellEditorStyle(viewport));
const finishedRef = useRef(false);
// The caret belongs at the END of the value (the Excel F2 convention);
// a textarea would otherwise open with it at position 0. Set on mount,
// before autoFocus lands, so the stored selection is already right.
const placeCaretAtEnd = (element: HTMLInputElement | HTMLTextAreaElement | null) => {
if (!element) return;
const end = element.value.length;
element.setSelectionRange?.(end, end);
};
useEffect(() => {
if (!style) onCancel();
}, [style, onCancel]);
// External row changes mid-edit (a live update, a re-sort) move or remove
// the cell underneath the overlay; the measured position is then a lie and
// a commit could land visually elsewhere. Cancel instead: predictable, and
// nothing is written that the user cannot see.
useEffect(() => {
const body = viewport.querySelector('tbody');
if (!body) return;
const observer = new MutationObserver(() => {
if (!finishedRef.current) onCancel();
});
observer.observe(body, { childList: true, subtree: true });
return () => observer.disconnect();
}, [viewport, onCancel]);
if (!style) return null;
const finish = (element: HTMLInputElement | HTMLTextAreaElement, commit: boolean, advance: DataGridEditorAdvance = null, refocus = true) => {
// One finish per session: an Enter commit can be chased by the blur the
// unmount produces, and a doubled commit would write twice.
if (finishedRef.current) return;
finishedRef.current = true;
if (commit) onCommit(element.value, advance, refocus);
else onCancel();
};
const handleKeyDown = (event: ReactKeyboardEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const element = event.currentTarget;
if (event.key === 'Escape') {
event.preventDefault();
event.stopPropagation();
finish(element, false);
return;
}
if (event.key === 'Tab') {
event.preventDefault();
finish(element, true, event.shiftKey ? 'left' : 'right');
return;
}
if (event.key !== 'Enter') return;
// A textarea keeps Shift/Alt+Enter as a newline, the Sheets convention.
if (session.control === 'textarea' && (event.shiftKey || event.altKey)) {
return;
}
event.preventDefault();
// The default keeps focus on the edited cell, so a corrected value can
// be reviewed in place; enterAdvance restores the Sheets move-down.
finish(element, true, enterAdvance ? (event.shiftKey ? 'up' : 'down') : null);
};
// z-[35]: above the sticky pinned cells (zIndex 30), or editing a pinned
// cell renders invisibly underneath them; below the sticky header (z-40).
// Primary outline at the same 1px weight as the focused cell's box: with
// the overlay covering that box, opening the editor reads as the same
// border becoming editable.
const sharedClassName =
'text-foreground bg-background outline-primary absolute z-[35] box-border resize-none outline-1 outline-solid -outline-offset-1';
return createPortal(
session.control === 'textarea' ? (
<textarea
data-slot="data-grid-cell-editor"
ref={placeCaretAtEnd}
autoFocus
aria-label={session.label}
defaultValue={session.initialValue}
rows={1}
style={style}
className={cn(sharedClassName, 'field-sizing-content overflow-hidden')}
onKeyDown={handleKeyDown}
onBlur={(event) => finish(event.currentTarget, true, null, false)}
/>
) : (
<input
data-slot="data-grid-cell-editor"
ref={placeCaretAtEnd}
autoFocus
aria-label={session.label}
defaultValue={session.initialValue}
style={style}
className={sharedClassName}
onKeyDown={handleKeyDown}
onBlur={(event) => finish(event.currentTarget, true, null, false)}
/>
),
viewport,
);
}
/* ------------------------------------------------------------------------- *
* Bulk edit bar.
* ------------------------------------------------------------------------- */
/**
* Thin shell over row selection for bulk actions: selected count, a slot for
* the consumer's controls, and a clear action. Hidden while nothing is
* selected. What the controls do stays consumer-owned.
*
* Presented as a floating toolbar, the Google Sheets way: auto width,
* centered, elevated, and sticky to the viewport bottom with breathing room,
* so bulk actions stay reachable while the grid scrolls.
*/
function DataGridSelectionBar({
children,
className,
label,
clearLabel = 'Clear',
onClear,
}: {
children?: ReactNode;
className?: string;
label?: (count: number) => ReactNode;
clearLabel?: ReactNode;
onClear?: () => void;
}) {
const context = useDataGrid();
const rowSelectionAtom = context.table.atoms.rowSelection;
if (rowSelectionAtom == null) return null;
return (
<Subscribe source={rowSelectionAtom}>
{() => {
// Read through the context getter: this closure re-runs on atom
// writes without re-rendering the component, and a captured v9
// wrapper would keep reporting the state it was built with.
const table = context.table;
const count = table.getSelectedRowModel().rows.length;
if (count === 0) return null;
return (
<div
data-slot="data-grid-selection-bar"
className={cn(
'bg-background rounded-lg sticky inset-x-0 bottom-4 z-40 mx-auto flex w-fit max-w-[calc(100%-2rem)] flex-wrap items-center gap-3 border px-4 py-2.5 shadow-lg',
className,
)}
>
<span className="text-foreground text-sm font-medium">{label ? label(count) : `${count} selected`}</span>
<div className="flex flex-1 flex-wrap items-center justify-end gap-2.5">
{children}
<Button
variant="ghost"
size="sm"
onClick={() => {
context.table.resetRowSelection();
onClear?.();
}}
>
{clearLabel}
</Button>
</div>
</div>
);
}}
</Subscribe>
);
}
export {
DataGridCellSelection,
DataGridSelectionBar,
buildDataGridClearDetails,
buildDataGridPasteDetails,
getDataGridActiveRegionGrid,
getDataGridVisibleSelectedCellCount,
invertDataGridCellsChange,
parseDataGridClipboardText,
serializeDataGridClipboardText,
tileDataGridClipboardBlock,
};
export type { DataGridCellSelectionApi, DataGridFocusCellOptions, DataGridPasteTarget };components/ui/data-grid/data-grid-column-filter.tsx
import { useMemo, useState } from 'react';
import { Badge } from '@/registry/vcare/ui/reui-badge';
import { useDataGrid } from '@/registry/vcare/ui/data-grid/data-grid';
import type { DataGridFeatures } from '@/registry/vcare/ui/data-grid/data-grid';
import type { Column } from '@tanstack/react-table';
import { cn } from '@/registry/vcare/lib/utils';
import { Button } from '@/registry/vcare/ui/button';
import { Input } from '@/registry/vcare/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/registry/vcare/ui/popover';
import { Separator } from '@/registry/vcare/ui/separator';
import { CirclePlusIcon, CheckIcon } from 'lucide-react';
interface DataGridColumnFilterProps<TData extends object, TValue> {
column?: Column<DataGridFeatures, TData, TValue>;
title?: string;
options: {
label: string;
value: string;
icon?: React.ComponentType<{ className?: string }>;
}[];
}
function DataGridColumnFilter<TData extends object, TValue>({ column, title, options }: DataGridColumnFilterProps<TData, TValue>) {
const { i18n } = useDataGrid();
const facets = column?.getFacetedUniqueValues();
const filterValue = column?.getFilterValue();
const selectedValues = new Set(Array.isArray(filterValue) ? (filterValue as string[]) : []);
const [searchQuery, setSearchQuery] = useState('');
const filteredOptions = useMemo(() => {
if (!searchQuery) return options;
return options.filter((option) => option.label.toLowerCase().includes(searchQuery.toLowerCase()));
}, [options, searchQuery]);
return (
<Popover>
<PopoverTrigger
render={
<Button variant="outline" size="sm">
<CirclePlusIcon className="size-4" />
{title}
{selectedValues?.size > 0 && (
<>
<Separator orientation="vertical" className="mx-2 h-4" />
<Badge variant="secondary" className="px-1 font-normal lg:hidden">
{selectedValues.size}
</Badge>
<div className="hidden space-x-1 lg:flex">
{selectedValues.size > 2 ? (
<Badge variant="secondary" className="px-1 font-normal">
{i18n.labels.filterSelectedCount(selectedValues.size)}
</Badge>
) : (
options
.filter((option) => selectedValues.has(option.value))
.map((option) => (
<Badge variant="secondary" key={option.value} className="px-1 font-normal">
{option.label}
</Badge>
))
)}
</div>
</>
)}
</Button>
}
/>
<PopoverContent className="w-[200px] p-0" align="start">
<div className="p-2">
<Input placeholder={title} value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="h-8" />
</div>
<div className="max-h-[300px] overflow-y-auto">
{filteredOptions.length === 0 ? (
<div className="text-muted-foreground py-6 text-center text-sm">{i18n.labels.filterNoResults}</div>
) : (
<div className="p-1">
{filteredOptions.map((option) => {
const isSelected = selectedValues.has(option.value);
const facetCount = facets?.get(option.value);
const toggleOption = () => {
if (isSelected) {
selectedValues.delete(option.value);
} else {
selectedValues.add(option.value);
}
const filterValues = Array.from(selectedValues);
column?.setFilterValue(filterValues.length ? filterValues : undefined);
};
return (
<div
key={option.value}
role="button"
tabIndex={0}
aria-pressed={isSelected}
onClick={toggleOption}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
toggleOption();
}
}}
className={cn(
'rounded-md relative flex cursor-pointer items-center gap-2 px-2 py-1.5 text-sm outline-hidden select-none',
'hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground',
)}
>
<div
className={cn(
'border-primary rounded-sm flex h-4 w-4 items-center justify-center border',
isSelected ? 'bg-primary text-primary-foreground' : 'opacity-50 [&_svg]:invisible',
)}
>
<CheckIcon className="h-4 w-4" />
</div>
{option.icon && <option.icon className="text-muted-foreground h-4 w-4" />}
<span>{option.label}</span>
{facetCount !== undefined && (
<span className="ms-auto flex h-4 w-4 items-center justify-center font-mono text-xs">{facetCount}</span>
)}
</div>
);
})}
</div>
)}
{selectedValues.size > 0 && (
<>
<div className="bg-border -mx-1 my-1 h-px" />
<div className="p-1">
<div
role="button"
tabIndex={0}
onClick={() => column?.setFilterValue(undefined)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
column?.setFilterValue(undefined);
}
}}
className="hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground rounded-md relative flex cursor-pointer items-center justify-center px-2 py-1.5 text-sm outline-hidden select-none"
>
{i18n.labels.filterClear}
</div>
</div>
</>
)}
</div>
</PopoverContent>
</Popover>
);
}
export { DataGridColumnFilter, type DataGridColumnFilterProps };components/ui/data-grid/data-grid-column-header.tsx
'use client';
import { memo, useMemo } from 'react';
import type { HTMLAttributes, ReactNode } from 'react';
import { getColumnHeaderLabel, useDataGrid } from '@/registry/vcare/ui/data-grid/data-grid';
import type { DataGridFeatures } from '@/registry/vcare/ui/data-grid/data-grid';
import { Subscribe } from '@tanstack/react-table';
import type { Column } from '@tanstack/react-table';
import { cn } from '@/registry/vcare/lib/utils';
import { Button } from '@/registry/vcare/ui/button';
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from '@/registry/vcare/ui/dropdown-menu';
import {
ArrowDownIcon,
ArrowUpIcon,
ChevronsUpDownIcon,
CheckIcon,
ArrowLeftToLineIcon,
ArrowRightToLineIcon,
ArrowLeftIcon,
ArrowRightIcon,
Settings2Icon,
PinOffIcon,
} from 'lucide-react';
interface DataGridColumnHeaderProps<TData extends object, TValue> extends HTMLAttributes<HTMLDivElement> {
column: Column<DataGridFeatures, TData, TValue>;
/** When omitted, uses `column.columnDef.meta.headerTitle`, then a string `columnDef.header`, then `column.id`. */
title?: string;
icon?: ReactNode;
/** Reserved; pin controls are gated by tableLayout.columnsPinnable + column.getCanPin(). */
pinnable?: boolean;
filter?: ReactNode;
visibility?: boolean;
}
function DataGridColumnHeaderInner<TData extends object, TValue>({
column,
title,
icon,
className,
filter,
visibility = false,
}: DataGridColumnHeaderProps<TData, TValue>) {
const { i18n, isLoading, table, props } = useDataGrid();
const resolvedTitle = title ?? getColumnHeaderLabel(column);
// The order a move rewrites: the consumer's columnOrder (TanStack defaults it
// to []), then every leaf it leaves out, in definition order - the same
// completion TanStack applies when rendering, so a rendered neighbour is
// always present to re-seat beside, even after columns are added later.
const columnOrderState = table.state.columnOrder;
const definitionOrder = table
.getAllColumns()
.flatMap((topColumn) => topColumn.getLeafColumns())
.map((leafColumn) => leafColumn.id);
const columnOrder = [...columnOrderState, ...definitionOrder.filter((id) => !columnOrderState.includes(id))];
const columnVisibilityKey = props.tableLayout?.columnsVisibility && visibility ? JSON.stringify(table.state.columnVisibility) : '';
const isSorted = column.getIsSorted();
const isPinned = column.getIsPinned();
const canSort = column.getCanSort();
const canPin = column.getCanPin();
const canResize = column.getCanResize();
// Move neighbours come from what is RENDERED: the column's own pin bucket,
// visible columns only. Stepping through the raw columnOrder would trade
// places with a hidden or pinned column - an enabled click that moves nothing.
// With grouping in TanStack's default "reorder" mode, grouped columns render
// first whatever columnOrder says: they neither move nor serve as a target.
const groupedColumnMode = (table.options as { groupedColumnMode?: false | 'reorder' | 'remove' }).groupedColumnMode;
const isHoistedByGrouping = (target: object) =>
groupedColumnMode !== false &&
typeof (target as { getIsGrouped?: unknown }).getIsGrouped === 'function' &&
(target as { getIsGrouped: () => boolean }).getIsGrouped();
const renderedPeers = (
isPinned === 'start'
? table.getStartVisibleLeafColumns()
: isPinned === 'end'
? table.getEndVisibleLeafColumns()
: table.getCenterVisibleLeafColumns()
)
.filter((leafColumn) => !isHoistedByGrouping(leafColumn))
.map((leafColumn) => leafColumn.id);
const renderedIndex = renderedPeers.indexOf(column.id);
const leftNeighbour = renderedIndex > 0 ? renderedPeers[renderedIndex - 1] : undefined;
const rightNeighbour = renderedIndex !== -1 && renderedIndex < renderedPeers.length - 1 ? renderedPeers[renderedIndex + 1] : undefined;
const canMoveLeft = leftNeighbour !== undefined;
const canMoveRight = rightNeighbour !== undefined;
/** Re-seats this column beside a rendered neighbour; every other column,
* hidden or pinned ones included, keeps its place in the full order. */
const moveBeside = (neighbourId: string, side: 'before' | 'after') => {
const newOrder = columnOrder.filter((id) => id !== column.id);
const at = newOrder.indexOf(neighbourId);
if (at === -1) return;
newOrder.splice(side === 'before' ? at : at + 1, 0, column.id);
table.setColumnOrder(newOrder);
};
const handleSort = () => {
if (isSorted === 'asc') {
column.toggleSorting(true);
} else if (isSorted === 'desc') {
column.clearSorting();
} else {
column.toggleSorting(false);
}
};
const headerLabelClassName = cn(
'text-secondary-foreground/80 inline-flex h-full items-center gap-1.5 font-normal [&_svg]:opacity-60 text-[0.8125rem] leading-[calc(1.125/0.8125)] [&_svg]:size-3.5',
className,
);
const headerButtonClassName = cn(
'text-secondary-foreground/80 hover:bg-secondary data-[state=open]:bg-secondary hover:text-foreground data-[state=open]:text-foreground px-2 font-normal h-6 rounded-lg',
className,
);
const sortIcon =
canSort &&
(isSorted === 'desc' ? (
<ArrowDownIcon className="size-3.25" aria-hidden="true" />
) : isSorted === 'asc' ? (
<ArrowUpIcon className="size-3.25" aria-hidden="true" />
) : (
<ChevronsUpDownIcon className="mt-px size-3.25" aria-hidden="true" />
));
const hasControls =
props.tableLayout?.columnsMovable ||
(props.tableLayout?.columnsVisibility && visibility) ||
(props.tableLayout?.columnsPinnable && canPin) ||
filter;
const menuItems = useMemo(() => {
const items: ReactNode[] = [];
let hasPreviousSection = false;
// Filter section
if (filter) {
items.push(
<DropdownMenuGroup key="group-filter">
<DropdownMenuLabel key="filter">{filter}</DropdownMenuLabel>
</DropdownMenuGroup>,
);
hasPreviousSection = true;
}
// Sort section
if (canSort) {
if (hasPreviousSection) {
items.push(<DropdownMenuSeparator key="sep-sort" />);
}
items.push(
<DropdownMenuItem
key="sort-asc"
onClick={() => {
if (isSorted === 'asc') {
column.clearSorting();
} else {
column.toggleSorting(false);
}
}}
disabled={!canSort}
>
<ArrowUpIcon className="size-3.5!" />
<span className="grow">{i18n.labels.sortAscending}</span>
{isSorted === 'asc' && <CheckIcon className="text-primary size-4 opacity-100!" />}
</DropdownMenuItem>,
<DropdownMenuItem
key="sort-desc"
onClick={() => {
if (isSorted === 'desc') {
column.clearSorting();
} else {
column.toggleSorting(true);
}
}}
disabled={!canSort}
>
<ArrowDownIcon className="size-3.5!" />
<span className="grow">{i18n.labels.sortDescending}</span>
{isSorted === 'desc' && <CheckIcon className="text-primary size-4 opacity-100!" />}
</DropdownMenuItem>,
);
hasPreviousSection = true;
}
// Pin section
if (props.tableLayout?.columnsPinnable && canPin) {
if (hasPreviousSection) {
items.push(<DropdownMenuSeparator key="sep-pin" />);
}
items.push(
<DropdownMenuItem key="pin-left" onClick={() => column.pin(isPinned === 'start' ? false : 'start')}>
<ArrowLeftToLineIcon className="size-3.5!" aria-hidden="true" />
<span className="grow">{i18n.labels.pinColumnStart}</span>
{isPinned === 'start' && <CheckIcon className="text-primary size-4 opacity-100!" />}
</DropdownMenuItem>,
<DropdownMenuItem key="pin-right" onClick={() => column.pin(isPinned === 'end' ? false : 'end')}>
<ArrowRightToLineIcon className="size-3.5!" aria-hidden="true" />
<span className="grow">{i18n.labels.pinColumnEnd}</span>
{isPinned === 'end' && <CheckIcon className="text-primary size-4 opacity-100!" />}
</DropdownMenuItem>,
);
hasPreviousSection = true;
}
// Move section
if (props.tableLayout?.columnsMovable) {
if (hasPreviousSection) {
items.push(<DropdownMenuSeparator key="sep-move" />);
}
items.push(
<DropdownMenuItem
key="move-left"
onClick={() => {
if (leftNeighbour) moveBeside(leftNeighbour, 'before');
}}
disabled={!canMoveLeft || isPinned !== false}
>
<ArrowLeftIcon className="size-3.5!" aria-hidden="true" />
<span>{i18n.labels.moveColumnStart}</span>
</DropdownMenuItem>,
<DropdownMenuItem
key="move-right"
onClick={() => {
if (rightNeighbour) moveBeside(rightNeighbour, 'after');
}}
disabled={!canMoveRight || isPinned !== false}
>
<ArrowRightIcon className="size-3.5!" aria-hidden="true" />
<span>{i18n.labels.moveColumnEnd}</span>
</DropdownMenuItem>,
);
hasPreviousSection = true;
}
// Visibility section
if (props.tableLayout?.columnsVisibility && visibility) {
if (hasPreviousSection) {
items.push(<DropdownMenuSeparator key="sep-visibility" />);
}
items.push(
<DropdownMenuSub key="visibility">
<DropdownMenuSubTrigger>
<Settings2Icon className="size-3.5!" />
<span>{i18n.labels.columnsMenu}</span>
</DropdownMenuSubTrigger>
<DropdownMenuSubContent side="right">
{table
.getAllColumns()
.filter((col) => col.getCanHide())
.map((col) => (
<DropdownMenuCheckboxItem
key={col.id}
checked={col.getIsVisible()}
onSelect={(event) => event.preventDefault()}
onCheckedChange={(value) => col.toggleVisibility(!!value)}
className="capitalize"
>
{getColumnHeaderLabel(col)}
</DropdownMenuCheckboxItem>
))}
</DropdownMenuSubContent>
</DropdownMenuSub>,
);
}
return items;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
filter,
canSort,
isSorted,
column,
props.tableLayout?.columnsPinnable,
props.tableLayout?.columnsMovable,
props.tableLayout?.columnsVisibility,
canPin,
isPinned,
canMoveLeft,
canMoveRight,
visibility,
table,
leftNeighbour,
rightNeighbour,
columnOrder,
columnVisibilityKey, // Needed to update checkbox states when visibility changes
]);
if (hasControls) {
return (
<div className="-ms-2 flex h-full items-center justify-between gap-1.5">
<DropdownMenu>
<DropdownMenuTrigger
render={
<Button variant="ghost" className={headerButtonClassName} disabled={isLoading}>
{icon && icon}
{resolvedTitle}
{sortIcon}
</Button>
}
/>
<DropdownMenuContent className="w-40" align="start">
{menuItems}
</DropdownMenuContent>
</DropdownMenu>
{props.tableLayout?.columnsPinnable && canPin && isPinned && (
<Button
size="icon-sm"
variant="ghost"
className="rounded-lg -me-1 size-7"
onClick={() => column.pin(false)}
aria-label={i18n.labels.unpinColumn(resolvedTitle)}
title={i18n.labels.unpinColumn(resolvedTitle)}
>
<PinOffIcon className="size-3.5! opacity-50!" aria-hidden="true" />
</Button>
)}
</div>
);
}
if (canSort || (props.tableLayout?.columnsResizable && canResize)) {
return (
<div className="-ms-2 flex h-full items-center">
<Button variant="ghost" className={headerButtonClassName} disabled={isLoading} onClick={handleSort}>
{icon && icon}
{resolvedTitle}
{sortIcon}
</Button>
</div>
);
}
return (
<div className={headerLabelClassName}>
{icon && icon}
{resolvedTitle}
</div>
);
}
const DataGridColumnHeaderMemo = memo(DataGridColumnHeaderInner) as <TData extends object, TValue>(
props: DataGridColumnHeaderProps<TData, TValue> & {
/** Internal: the state slices the header re-renders on. Not part of the public API. */
subscribedState?: unknown;
},
) => ReactNode;
/**
* Sort and pin state reaches this header through builder calls on `column`
* (`getIsSorted()`, `getIsPinned()`), and `column` is a stable reference. That
* combination is the one v9's fresh-table-per-state-change does NOT cover:
* React Compiler is free to memoize against the stable column and never
* re-evaluate those reads, which shows up as frozen sort arrows and pin
* controls. The `Subscribe` below turns the slices this header actually reads
* into a real reactive dependency, and threading the selection through as a
* prop is what lets it past the `memo` - which would otherwise see unchanged
* props and skip the render anyway.
*/
function DataGridColumnHeader<TData extends object, TValue>(props: DataGridColumnHeaderProps<TData, TValue>) {
const { table } = useDataGrid();
return (
<Subscribe
source={table.store}
selector={(state) => ({
sorting: state.sorting,
columnPinning: state.columnPinning,
columnOrder: state.columnOrder,
columnVisibility: state.columnVisibility,
})}
>
{(subscribed) => <DataGridColumnHeaderMemo {...props} subscribedState={subscribed} />}
</Subscribe>
);
}
export { DataGridColumnHeader, type DataGridColumnHeaderProps };components/ui/data-grid/data-grid-column-visibility.tsx
import type { ReactElement } from 'react';
import { getColumnHeaderLabel, useDataGrid } from '@/registry/vcare/ui/data-grid/data-grid';
import type { DataGridFeatures } from '@/registry/vcare/ui/data-grid/data-grid';
import type { Table } from '@tanstack/react-table';
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuTrigger,
} from '@/registry/vcare/ui/dropdown-menu';
function DataGridColumnVisibility<TData extends object>({
table,
trigger,
}: {
table: Table<DataGridFeatures, TData>;
trigger: ReactElement<Record<string, unknown>>;
}) {
const { i18n } = useDataGrid();
return (
<DropdownMenu>
<DropdownMenuTrigger render={trigger} />
<DropdownMenuContent align="end" className="min-w-[150px]">
<DropdownMenuGroup>
<DropdownMenuLabel className="font-medium">{i18n.labels.toggleColumns}</DropdownMenuLabel>
{table
.getAllColumns()
.filter((column) => column.getCanHide())
.map((column) => {
return (
<DropdownMenuCheckboxItem
key={column.id}
className="capitalize"
checked={column.getIsVisible()}
onSelect={(event) => event.preventDefault()}
onCheckedChange={(value) => column.toggleVisibility(!!value)}
>
{getColumnHeaderLabel(column)}
</DropdownMenuCheckboxItem>
);
})}
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
);
}
export { DataGridColumnVisibility };components/ui/data-grid/data-grid-i18n.tsx
export interface DataGridI18nLabels {
/* The column header menu. */
sortAscending: string;
sortDescending: string;
pinColumnStart: string;
pinColumnEnd: string;
moveColumnStart: string;
moveColumnEnd: string;
columnsMenu: string;
unpinColumn: (title: string) => string;
toggleColumns: string;
/* Row and cell affordances. */
rowCreate: string;
pinRow: string;
unpinRow: string;
selectRow: string;
selectAll: string;
expandRow: string;
collapseRow: string;
dragToReorder: string;
dragToReorderRow: string;
reorderingUnavailable: string;
/* Grid states. */
loading: string;
empty: string;
allRowsLoaded: string;
/* Pagination. */
rowsPerPage: string;
paginationInfo: (info: { from: number; to: number; count: number }) => string;
previousPage: string;
nextPage: string;
goToPage: (page: number) => string;
paginationEllipsis: string;
/* The faceted column filter. */
filterSelectedCount: (count: number) => string;
filterNoResults: string;
filterClear: string;
}
export interface DataGridI18nConfig {
labels: DataGridI18nLabels;
}
export type DataGridI18nOverrides = {
labels?: Partial<DataGridI18nLabels>;
};
const DEFAULT_DATA_GRID_LABELS: DataGridI18nLabels = {
sortAscending: 'Asc',
sortDescending: 'Desc',
pinColumnStart: 'Pin to left',
pinColumnEnd: 'Pin to right',
moveColumnStart: 'Move to left',
moveColumnEnd: 'Move to right',
columnsMenu: 'Columns',
unpinColumn: (title) => `Unpin ${title} column`,
toggleColumns: 'Toggle Columns',
rowCreate: 'Add row',
pinRow: 'Pin row',
unpinRow: 'Unpin row',
selectRow: 'Select row',
selectAll: 'Select all',
expandRow: 'Expand row',
collapseRow: 'Collapse row',
dragToReorder: 'Drag to reorder',
dragToReorderRow: 'Drag to reorder row',
reorderingUnavailable: 'Reordering unavailable',
loading: 'Loading...',
empty: 'No data available',
allRowsLoaded: 'All records loaded',
rowsPerPage: 'Rows per page',
paginationInfo: ({ from, to, count }) => `${from} - ${to} of ${count}`,
previousPage: 'Go to previous page',
nextPage: 'Go to next page',
goToPage: (page) => `Go to page ${page}`,
paginationEllipsis: '...',
filterSelectedCount: (count) => `${count} selected`,
filterNoResults: 'No results found.',
filterClear: 'Clear filters',
};
const DEFAULT_DATA_GRID_I18N: DataGridI18nConfig = Object.freeze({
labels: Object.freeze(DEFAULT_DATA_GRID_LABELS),
});
/**
* A shallow merge per section, deliberately: a deep merge would leak a
* default back into a function-valued label the consumer replaced. With no
* overrides the frozen default is returned as-is, so the merge is free to
* run on every render without producing a new identity.
*/
export function mergeDataGridI18n(overrides?: DataGridI18nOverrides): DataGridI18nConfig {
if (!overrides?.labels) return DEFAULT_DATA_GRID_I18N;
return {
labels: { ...DEFAULT_DATA_GRID_LABELS, ...overrides.labels },
};
}components/ui/data-grid/data-grid-pagination.tsx
'use client';
import type { JSX, ReactNode } from 'react';
import { useDataGrid } from '@/registry/vcare/ui/data-grid/data-grid';
import { cn } from '@/registry/vcare/lib/utils';
import { Button } from '@/registry/vcare/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/registry/vcare/ui/select';
import { Skeleton } from '@/registry/vcare/ui/skeleton';
import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';
interface DataGridPaginationProps {
sizes?: number[];
sizesInfo?: string;
sizesLabel?: string;
sizesDescription?: string;
sizesSkeleton?: ReactNode;
more?: boolean;
/** Page buttons the truncated middle shows; the row adds first, last and
* an ellipsis for each hidden stretch. Clamped to a minimum of 3. */
moreLimit?: number;
info?: string;
infoSkeleton?: ReactNode;
className?: string;
rowsPerPageLabel?: string;
previousPageLabel?: string;
nextPageLabel?: string;
ellipsisText?: string;
}
/**
* One slot in the page row: a page button, or an ellipsis that jumps over the
* pages it stands for.
*/
type DataGridPaginationItem =
| { type: 'page'; index: number }
| { type: 'ellipsis'; direction: 'previous'; target: number }
| { type: 'ellipsis'; direction: 'next'; target: number };
/**
* The adaptive window: first page, the run around the current one, last page,
* with an ellipsis standing in for each hidden stretch. It replaced fixed
* BLOCKS (1-5, then 6-10) because a block never shows the last page, so on a
* 50-page grid there was no way to reach the end - the primitive wires only
* `previousPage()` / `nextPage()`, so there is no last-page arrow either.
*
* `limit` is `moreLimit`: how many page buttons the truncated middle shows.
* At the default of 5 this emits exactly the same rows as the block version
* did at `moreLimit: 5`, so the prop keeps both its meaning and its default.
* An ellipsis never stands for a single page, because the early return covers
* every count a full row could hold.
*/
function getDataGridPaginationItems(pageIndex: number, pageCount: number, limit: number): DataGridPaginationItem[] {
// Pages flanking the current one, per side. The run is rebuilt from it so
// the count is always odd: an even `limit` would make the head and tail
// rows one slot wider than the middle, and the footer would twitch as the
// user pages through.
const sibling = Math.max(0, Math.floor(((Math.floor(limit) || 3) - 3) / 2));
const pages = sibling * 2 + 3;
// Two ellipses cost the width of two pages, so below this there is nothing
// to gain by hiding any.
if (pageCount <= pages + 2) {
return Array.from({ length: pageCount }, (_, index) => ({
type: 'page' as const,
index,
}));
}
if (pageIndex <= sibling + 2) {
return [
...Array.from({ length: pages }, (_, index) => ({
type: 'page' as const,
index,
})),
{ type: 'ellipsis', direction: 'next', target: pages },
{ type: 'page', index: pageCount - 1 },
];
}
if (pageIndex >= pageCount - sibling - 3) {
return [
{ type: 'page', index: 0 },
{
type: 'ellipsis',
direction: 'previous',
target: pageCount - pages - 1,
},
...Array.from({ length: pages }, (_, offset) => ({
type: 'page' as const,
index: pageCount - pages + offset,
})),
];
}
return [
{ type: 'page', index: 0 },
{
type: 'ellipsis',
direction: 'previous',
target: pageIndex - sibling - 1,
},
...Array.from({ length: sibling * 2 + 1 }, (_, offset) => ({
type: 'page' as const,
index: pageIndex - sibling + offset,
})),
{ type: 'ellipsis', direction: 'next', target: pageIndex + sibling + 1 },
{ type: 'page', index: pageCount - 1 },
];
}
/**
* A page button is square at one digit and grows from there, so the row does
* not reflow when the count crosses 10 or 100. The floor is each style's own
* `icon-sm` square, which is also its `sm` HEIGHT, so the numbers stay square
* and keep the arrows' height. Hardcoding one value would be right in three
* styles and wrong in five.
*/
const PAGE_BUTTON_WIDTH_CLASS = 'min-w-7';
function DataGridPagination(props: DataGridPaginationProps): JSX.Element {
const { i18n, table, recordCount, isLoading } = useDataGrid();
const defaultProps: Partial<DataGridPaginationProps> = {
sizes: [5, 10, 25, 50, 100],
sizesSkeleton: <Skeleton className="h-8 w-44" />,
moreLimit: 5,
infoSkeleton: <Skeleton className="h-8 w-60" />,
rowsPerPageLabel: i18n.labels.rowsPerPage,
previousPageLabel: i18n.labels.previousPage,
nextPageLabel: i18n.labels.nextPage,
ellipsisText: i18n.labels.paginationEllipsis,
};
const mergedProps: DataGridPaginationProps = { ...defaultProps, ...props };
const btnBaseClasses = 'p-0 text-sm';
const btnArrowClasses = btnBaseClasses + ' rtl:transform rtl:rotate-180';
const pageIndex = table.state.pagination.pageIndex;
const pageSize = table.state.pagination.pageSize;
const from = recordCount === 0 ? 0 : pageIndex * pageSize + 1;
const to = Math.min((pageIndex + 1) * pageSize, recordCount);
const pageCount = table.getPageCount();
// A supplied `info` keeps its placeholder-template contract; the default
// routes through the i18n label function, where word order is free.
const paginationInfo = mergedProps.info
? mergedProps.info.replaceAll('{from}', from.toString()).replaceAll('{to}', to.toString()).replaceAll('{count}', recordCount.toString())
: i18n.labels.paginationInfo({ from, to, count: recordCount });
const paginationItems = getDataGridPaginationItems(pageIndex, pageCount, mergedProps.moreLimit ?? 5);
return (
<div
data-slot="data-grid-pagination"
className={cn('flex grow flex-col flex-wrap items-center justify-between gap-2.5 py-2.5 sm:flex-row sm:py-0', mergedProps.className)}
>
<div className="order-2 flex flex-wrap items-center space-x-2.5 pb-2.5 sm:order-1 sm:pb-0">
{isLoading ? (
mergedProps.sizesSkeleton
) : (
<>
<div className="text-muted-foreground text-sm">{mergedProps.rowsPerPageLabel}</div>
<Select
value={`${pageSize}`}
onValueChange={(value) => {
const newPageSize = Number(value);
table.setPageSize(newPageSize);
}}
>
{/* w-fit with a min, never a fixed width: a fixed w-16 clipped
the value "100" by 1px at nova's paddings, while fit-content
grows the trigger for 3-digit sizes and the min keeps the
1-2 digit ones from collapsing narrower than 64px. */}
<SelectTrigger aria-label={mergedProps.rowsPerPageLabel} className="w-fit min-w-16" size="sm">
<SelectValue />
</SelectTrigger>
<SelectContent align="start" alignItemWithTrigger={false} className="min-w-(--anchor-width)">
{mergedProps.sizes?.map((size: number) => (
<SelectItem key={size} value={`${size}`}>
{size}
</SelectItem>
))}
</SelectContent>
</Select>
</>
)}
</div>
<div className="order-1 flex flex-col items-center justify-center gap-2.5 pt-2.5 sm:order-2 sm:flex-row sm:justify-end sm:pt-0">
{isLoading ? (
mergedProps.infoSkeleton
) : (
<>
<div className="text-muted-foreground order-2 text-sm text-nowrap sm:order-1">{paginationInfo}</div>
{pageCount > 1 && (
<div className="order-1 flex flex-wrap items-center justify-center gap-1 sm:flex-nowrap">
<Button
size="icon-sm"
variant="ghost"
className={btnArrowClasses}
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">{mergedProps.previousPageLabel}</span>
<ChevronLeftIcon className="size-4" />
</Button>
{paginationItems.map((item) =>
item.type === 'page' ? (
<Button
key={`page-${item.index}`}
size="sm"
variant="ghost"
aria-label={i18n.labels.goToPage(item.index + 1)}
aria-current={pageIndex === item.index ? 'page' : undefined}
className={cn(PAGE_BUTTON_WIDTH_CLASS, 'px-1.5 text-sm', 'text-muted-foreground', {
'bg-accent text-accent-foreground': pageIndex === item.index,
})}
onClick={() => {
if (pageIndex !== item.index) {
table.setPageIndex(item.index);
}
}}
>
{item.index + 1}
</Button>
) : (
/* Clickable, unlike the shadcn PaginationEllipsis, which is
an aria-hidden span. This one MOVES the user, so it needs
a name saying where. */
<Button
key={`ellipsis-${item.direction}`}
size="icon-sm"
className={btnBaseClasses}
variant="ghost"
aria-label={i18n.labels.goToPage(item.target + 1)}
onClick={() => table.setPageIndex(item.target)}
>
{mergedProps.ellipsisText}
</Button>
),
)}
<Button
size="icon-sm"
variant="ghost"
className={btnArrowClasses}
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">{mergedProps.nextPageLabel}</span>
<ChevronRightIcon className="size-4" />
</Button>
</div>
)}
</>
)}
</div>
</div>
);
}
export { DataGridPagination, type DataGridPaginationProps };components/ui/data-grid/data-grid-scroll-area.tsx
import { useCallback, useEffect, useRef, useState } from 'react';
import type { PointerEvent, ReactNode } from 'react';
import { useDataGrid } from '@/registry/vcare/ui/data-grid/data-grid';
import { ScrollArea as ScrollAreaPrimitive } from '@base-ui/react/scroll-area';
import { cn } from '@/registry/vcare/lib/utils';
const MIN_THUMB_SIZE = 24;
const FALLBACK_SCROLLBAR_SIZE = 12;
const INITIAL_METRICS = {
hasVerticalOverflow: false,
headerHeight: 0,
horizontalScrollbarSize: 0,
thumbHeight: 0,
thumbTop: 0,
trackHeight: 0,
} as const;
// Track footprint, measured: horizontal is 8px tall and vertical 6px wide, and
// each loses 1px to its transparent border plus 2px to p-px, so the thumbs land
// at 5px and 3px. Shrink these further and the thumb stops being a grab target.
const SCROLLBAR_CLASSNAME =
'flex touch-none p-px transition-colors select-none data-[orientation=horizontal]:h-2 data-[orientation=horizontal]:flex-col data-[orientation=horizontal]:border-t data-[orientation=horizontal]:border-t-transparent data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5 data-[orientation=vertical]:border-s data-[orientation=vertical]:border-s-transparent';
const SCROLLBAR_THUMB_CLASSNAME = 'bg-border rounded-full relative flex-1';
type DataGridScrollAreaOrientation = 'horizontal' | 'vertical' | 'both';
type ScrollbarMetrics = {
hasVerticalOverflow: boolean;
headerHeight: number;
horizontalScrollbarSize: number;
thumbHeight: number;
thumbTop: number;
trackHeight: number;
};
type ObservedElements = {
header: HTMLElement | null;
horizontalScrollbar: HTMLElement | null;
table: HTMLElement | null;
tableViewport: HTMLElement | null;
};
type DataGridScrollAreaProps = Omit<ScrollAreaPrimitive.Root.Props, 'children'> & {
children: ReactNode;
orientation?: DataGridScrollAreaOrientation;
};
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
function areMetricsEqual(next: ScrollbarMetrics, prev: ScrollbarMetrics) {
return (
next.hasVerticalOverflow === prev.hasVerticalOverflow &&
next.headerHeight === prev.headerHeight &&
next.horizontalScrollbarSize === prev.horizontalScrollbarSize &&
next.thumbHeight === prev.thumbHeight &&
next.thumbTop === prev.thumbTop &&
next.trackHeight === prev.trackHeight
);
}
function applyMetrics(element: HTMLElement, metrics: ScrollbarMetrics) {
element.style.setProperty('--data-grid-scrollbar-header-height', `${metrics.headerHeight}px`);
element.style.setProperty('--data-grid-scrollbar-thumb-height', `${metrics.thumbHeight}px`);
element.style.setProperty('--data-grid-scrollbar-thumb-top', `${metrics.thumbTop}px`);
element.style.setProperty('--data-grid-scrollbar-track-height', `${metrics.trackHeight}px`);
}
function DataGridScrollArea({ children, className, orientation = 'both', ...props }: DataGridScrollAreaProps) {
const { props: dataGridProps, table } = useDataGrid();
const containerRef = useRef<HTMLDivElement>(null);
const overlayRef = useRef<HTMLDivElement | null>(null);
const viewportRef = useRef<HTMLDivElement | null>(null);
const dragRef = useRef<{
pointerId: number;
startScrollTop: number;
startY: number;
} | null>(null);
const metricsRef = useRef<ScrollbarMetrics>(INITIAL_METRICS);
const observedElementsRef = useRef<ObservedElements>({
header: null,
horizontalScrollbar: null,
table: null,
tableViewport: null,
});
const showHorizontal = orientation !== 'vertical';
const showVertical = orientation !== 'horizontal';
const usesCustomVerticalScrollbar = showVertical && !!dataGridProps.tableLayout?.headerSticky;
// Pinned columns are sticky and never scroll, so the horizontal scrollbar
// track is inset to span only the scrollable center region between them.
const isColumnsPinnable = !!dataGridProps.tableLayout?.columnsPinnable;
const scrollbarInsetStart = isColumnsPinnable ? table.getStartTotalSize() : 0;
const scrollbarInsetEnd = isColumnsPinnable ? table.getEndTotalSize() : 0;
const [hasCustomVerticalOverflow, setHasCustomVerticalOverflow] = useState(false);
const clearDragState = useCallback(() => {
dragRef.current = null;
document.body.style.userSelect = '';
document.body.style.webkitUserSelect = '';
}, []);
// The overlay is mounted one commit after the sync that detected overflow,
// so it misses that sync's write. Seeding it from the ref callback lands the
// geometry during commit, before the browser paints the track.
const setOverlayRef = useCallback((node: HTMLDivElement | null) => {
overlayRef.current = node;
if (node) applyMetrics(node, metricsRef.current);
}, []);
const resetMetrics = useCallback(() => {
if (!areMetricsEqual(INITIAL_METRICS, metricsRef.current)) {
metricsRef.current = INITIAL_METRICS;
if (overlayRef.current) applyMetrics(overlayRef.current, INITIAL_METRICS);
}
setHasCustomVerticalOverflow((prev) => (prev ? false : prev));
}, []);
const syncCustomVerticalScrollbar = useCallback(() => {
const container = containerRef.current;
const viewport = viewportRef.current;
if (!container || !viewport || !usesCustomVerticalScrollbar) {
resetMetrics();
return;
}
const { header, horizontalScrollbar } = observedElementsRef.current;
const headerHeight = header?.getBoundingClientRect().height ?? 0;
const viewportHeight = viewport.clientHeight;
const viewportWidth = viewport.clientWidth;
const scrollHeight = viewport.scrollHeight;
const scrollWidth = viewport.scrollWidth;
const hasHorizontalOverflow = showHorizontal && scrollWidth > viewportWidth + 0.5;
const horizontalScrollbarSize = hasHorizontalOverflow ? horizontalScrollbar?.offsetHeight || FALLBACK_SCROLLBAR_SIZE : 0;
const trackHeight = Math.max(0, viewportHeight - headerHeight - horizontalScrollbarSize);
const maxScroll = Math.max(0, scrollHeight - viewportHeight);
let nextMetrics: ScrollbarMetrics;
if (trackHeight === 0 || maxScroll === 0) {
nextMetrics = {
hasVerticalOverflow: false,
headerHeight,
horizontalScrollbarSize,
thumbHeight: trackHeight,
thumbTop: 0,
trackHeight,
};
} else {
const bodyContentHeight = Math.max(trackHeight, scrollHeight - headerHeight);
const thumbHeight = clamp(trackHeight * (trackHeight / bodyContentHeight), MIN_THUMB_SIZE, trackHeight);
const maxThumbTop = Math.max(0, trackHeight - thumbHeight);
const thumbTop = maxThumbTop > 0 ? (viewport.scrollTop / maxScroll) * maxThumbTop : 0;
nextMetrics = {
hasVerticalOverflow: true,
headerHeight,
horizontalScrollbarSize,
thumbHeight,
thumbTop,
trackHeight,
};
}
if (!areMetricsEqual(nextMetrics, metricsRef.current)) {
metricsRef.current = nextMetrics;
// Scoped to the overlay, never to the container. These four properties
// inherit, and thumbTop changes on essentially every scroll frame, so
// writing them on the element that wraps the whole grid invalidates
// computed style for every row and cell each frame. The overlay subtree
// is their only reader.
if (overlayRef.current) applyMetrics(overlayRef.current, nextMetrics);
}
setHasCustomVerticalOverflow((prev) => (prev === nextMetrics.hasVerticalOverflow ? prev : nextMetrics.hasVerticalOverflow));
}, [resetMetrics, showHorizontal, usesCustomVerticalScrollbar]);
useEffect(() => {
const container = containerRef.current;
const viewport = viewportRef.current;
if (!container || !viewport) return;
if (!usesCustomVerticalScrollbar) {
resetMetrics();
return;
}
let frame = 0;
const scheduleSync = () => {
cancelAnimationFrame(frame);
frame = window.requestAnimationFrame(syncCustomVerticalScrollbar);
};
const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(scheduleSync);
const observed = new Set<HTMLElement>();
const observeElement = (element: HTMLElement | null) => {
if (element && observer && !observed.has(element)) {
observer.observe(element);
observed.add(element);
}
};
const resolveObservedElements = () => {
observedElementsRef.current = {
header: container.querySelector('[data-slot="data-grid-table"] thead') as HTMLElement | null,
horizontalScrollbar: container.querySelector('[data-slot="data-grid-scrollbar"][data-orientation="horizontal"]') as HTMLElement | null,
table: container.querySelector('[data-slot="data-grid-table"]') as HTMLElement | null,
tableViewport: container.querySelector('[data-slot="data-grid-table-viewport"]') as HTMLElement | null,
};
observeElement(observedElementsRef.current.header);
observeElement(observedElementsRef.current.table);
observeElement(observedElementsRef.current.tableViewport);
return !!(observedElementsRef.current.header && observedElementsRef.current.table);
};
observeElement(viewport);
const resolvedOnMount = resolveObservedElements();
scheduleSync();
viewport.addEventListener('scroll', scheduleSync, { passive: true });
// A table that mounts after this effect (empty state swapped for data)
// would otherwise never be observed and the custom scrollbar would
// overlap the sticky header. One-shot: disconnects once resolved.
let mutationObserver: MutationObserver | null = null;
if (!resolvedOnMount && typeof MutationObserver !== 'undefined') {
mutationObserver = new MutationObserver(() => {
if (resolveObservedElements()) {
mutationObserver?.disconnect();
mutationObserver = null;
scheduleSync();
}
});
mutationObserver.observe(container, { childList: true, subtree: true });
}
return () => {
cancelAnimationFrame(frame);
observer?.disconnect();
mutationObserver?.disconnect();
viewport.removeEventListener('scroll', scheduleSync);
clearDragState();
};
}, [clearDragState, resetMetrics, syncCustomVerticalScrollbar, usesCustomVerticalScrollbar]);
const scrollToThumbOffset = (nextThumbTop: number) => {
const viewport = viewportRef.current;
const { thumbHeight, trackHeight } = metricsRef.current;
if (!viewport) return;
const maxScroll = Math.max(0, viewport.scrollHeight - viewport.clientHeight);
const maxThumbTop = Math.max(0, trackHeight - thumbHeight);
if (maxScroll === 0 || maxThumbTop === 0) {
viewport.scrollTop = 0;
return;
}
const ratio = clamp(nextThumbTop, 0, maxThumbTop) / maxThumbTop;
viewport.scrollTop = ratio * maxScroll;
};
const handleThumbPointerDown = (event: PointerEvent<HTMLDivElement>) => {
const viewport = viewportRef.current;
if (!viewport) return;
event.preventDefault();
event.stopPropagation();
event.currentTarget.setPointerCapture(event.pointerId);
dragRef.current = {
pointerId: event.pointerId,
startScrollTop: viewport.scrollTop,
startY: event.clientY,
};
document.body.style.userSelect = 'none';
document.body.style.webkitUserSelect = 'none';
};
const handleThumbPointerMove = (event: PointerEvent<HTMLDivElement>) => {
const viewport = viewportRef.current;
const dragState = dragRef.current;
const { thumbHeight, trackHeight } = metricsRef.current;
if (!viewport || !dragState || dragState.pointerId !== event.pointerId) {
return;
}
const maxThumbTop = Math.max(0, trackHeight - thumbHeight);
const maxScroll = Math.max(0, viewport.scrollHeight - viewport.clientHeight);
if (maxThumbTop === 0 || maxScroll === 0) return;
const deltaY = event.clientY - dragState.startY;
const nextScrollTop = dragState.startScrollTop + (deltaY / maxThumbTop) * maxScroll;
viewport.scrollTop = clamp(nextScrollTop, 0, maxScroll);
};
const handleThumbPointerUp = (event: PointerEvent<HTMLDivElement>) => {
if (dragRef.current?.pointerId !== event.pointerId) return;
clearDragState();
};
const handleTrackPointerDown = (event: PointerEvent<HTMLDivElement>) => {
const { thumbHeight } = metricsRef.current;
if (event.target !== event.currentTarget) return;
event.preventDefault();
event.stopPropagation();
const rect = event.currentTarget.getBoundingClientRect();
const offsetY = event.clientY - rect.top - thumbHeight / 2;
scrollToThumbOffset(offsetY);
};
return (
<div ref={containerRef} className="relative">
<ScrollAreaPrimitive.Root
data-slot="data-grid-scroll-area"
// Styling hook: present while the sticky-header scroll mode detects
// vertical overflow, so consumers can style scrollable vs short
// grids with a plain ancestor attribute selector.
data-overflow-vertical={hasCustomVerticalOverflow ? 'true' : undefined}
className={cn('relative', className)}
{...props}
>
<ScrollAreaPrimitive.Viewport ref={viewportRef} data-slot="scroll-area-viewport" className="size-full">
<ScrollAreaPrimitive.Content data-slot="scroll-area-content">{children}</ScrollAreaPrimitive.Content>
</ScrollAreaPrimitive.Viewport>
{showHorizontal && (
<ScrollAreaPrimitive.Scrollbar
data-slot="data-grid-scrollbar"
data-orientation="horizontal"
orientation="horizontal"
className={SCROLLBAR_CLASSNAME}
style={
scrollbarInsetStart > 0 || scrollbarInsetEnd > 0
? {
marginInlineStart: scrollbarInsetStart || undefined,
marginInlineEnd: scrollbarInsetEnd || undefined,
}
: undefined
}
>
<ScrollAreaPrimitive.Thumb data-slot="data-grid-thumb" className={SCROLLBAR_THUMB_CLASSNAME} />
</ScrollAreaPrimitive.Scrollbar>
)}
{showVertical && !usesCustomVerticalScrollbar && (
<ScrollAreaPrimitive.Scrollbar
data-slot="data-grid-scrollbar"
data-orientation="vertical"
orientation="vertical"
className={SCROLLBAR_CLASSNAME}
>
<ScrollAreaPrimitive.Thumb data-slot="data-grid-thumb" className={SCROLLBAR_THUMB_CLASSNAME} />
</ScrollAreaPrimitive.Scrollbar>
)}
</ScrollAreaPrimitive.Root>
{usesCustomVerticalScrollbar && hasCustomVerticalOverflow && (
<div
ref={setOverlayRef}
aria-hidden="true"
className="pointer-events-none absolute inset-e-0 top-(--data-grid-scrollbar-header-height) z-20 h-(--data-grid-scrollbar-track-height)"
>
<div className="pointer-events-auto relative h-full w-1.5 touch-none p-px" onPointerDown={handleTrackPointerDown}>
<div
className={cn(
'bg-border absolute end-px w-1.5',
'top-(--data-grid-scrollbar-thumb-top) h-(--data-grid-scrollbar-thumb-height)',
'rounded-full',
)}
onLostPointerCapture={clearDragState}
onPointerCancel={handleThumbPointerUp}
onPointerDown={handleThumbPointerDown}
onPointerMove={handleThumbPointerMove}
onPointerUp={handleThumbPointerUp}
/>
</div>
</div>
)}
</div>
);
}
export { DataGridScrollArea };
export type { DataGridScrollAreaOrientation, DataGridScrollAreaProps };components/ui/data-grid/data-grid-table-dnd-rows.tsx
'use client';
import { createContext, memo, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from 'react';
import type { CSSProperties, ReactNode } from 'react';
import { useDataGrid } from '@/registry/vcare/ui/data-grid/data-grid';
import type { DataGridFeatures, DataGridTableInstance } from '@/registry/vcare/ui/data-grid/data-grid';
import {
DataGridTableBase,
DataGridTableBody,
DataGridTableBodyRow,
DataGridTableBodyRowCell,
DataGridTableBodyRowExpandded,
DataGridTableBodyRowSkeleton,
DataGridTableBodyRowSkeletonCell,
DataGridTableEmpty,
DataGridTableFillBodyCell,
DataGridTableFillHeadCell,
DataGridTableFoot,
DataGridTableHead,
DataGridTableHeadRow,
DataGridTableHeadRowCell,
DataGridTableHeadRowCellResize,
DataGridTableRowSpacer,
DataGridTableViewport,
} from '@/registry/vcare/ui/data-grid/data-grid-table';
import {
closestCenter,
DndContext,
DragOverlay,
KeyboardSensor,
MouseSensor,
TouchSensor,
useSensor,
useSensors,
type CollisionDetection,
type DragCancelEvent,
type DragEndEvent,
type DragMoveEvent,
type DragOverEvent,
type DragStartEvent,
type Modifier,
type UniqueIdentifier,
} from '@dnd-kit/core';
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import { SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy, type SortingStrategy } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { flexRender } from '@tanstack/react-table';
import type { Cell, HeaderGroup, Row, Table } from '@tanstack/react-table';
import { createPortal } from 'react-dom';
import { cn } from '@/registry/vcare/lib/utils';
import { Button } from '@/registry/vcare/ui/button';
import { GripHorizontalIcon } from 'lucide-react';
// Context to share sortable listeners from row to handle
type SortableContextValue = ReturnType<typeof useSortable>;
const SortableRowContext = createContext<Pick<SortableContextValue, 'attributes' | 'listeners'> | null>(null);
/**
* Tree metadata attached to every sortable row, readable from
* `active.data.current` / `over.data.current` in any drag event. Cross-parent
* drops can be resolved from it without re-deriving the shape of the table.
*/
type DataGridTableDndRowData = {
type: 'data-grid-row';
/** Tree depth, 0 for root rows. */
depth: number;
/** Index within the parent's children, or within the root rows. */
index: number;
/** Parent row id, or null for root rows. */
parentId: string | null;
};
/**
* Per-row render slot for drop indicators and depth guides. The returned node
* is positioned over the row, so it never adds a column, shifts striping, or
* gets clipped by a truncating resizable cell.
*/
type DataGridTableDndRowDecoration<TData extends object> = (context: {
row: Row<DataGridFeatures, TData>;
isDragging: boolean;
isOver: boolean;
}) => ReactNode;
function DataGridTableDndRowHandle({
className,
disabled,
disabledLabel,
}: {
className?: string;
/**
* Renders the grip inert instead of withdrawing it. A grid that reorders on
* one truth (manual order) and sorts on another cannot honour both at once,
* but dropping the handle entirely collapses the gutter and reads as broken
* rather than as unavailable. Keep the column's shape, mute the control.
*/
disabled?: boolean;
/** Announced and shown on hover in place of the drag affordance. */
disabledLabel?: string;
}) {
const { i18n } = useDataGrid();
const context = useContext(SortableRowContext);
const resolvedDisabledLabel = disabledLabel ?? i18n.labels.reorderingUnavailable;
if (!context || disabled) {
return (
<Button
variant="ghost"
size="icon-sm"
className={cn(
'size-7 cursor-grab opacity-70 hover:bg-transparent hover:opacity-100 active:cursor-grabbing',
// The Button's own disabled treatment supplies the muting; only the
// cursor needs saying, so the grip reads as unavailable rather than
// merely unresponsive.
disabled && 'cursor-not-allowed',
className,
)}
aria-label={disabled ? resolvedDisabledLabel : i18n.labels.dragToReorderRow}
title={disabled ? resolvedDisabledLabel : undefined}
disabled
>
<GripHorizontalIcon aria-hidden="true" />
</Button>
);
}
return (
<Button
variant="ghost"
size="icon-sm"
className={cn('size-7 cursor-grab opacity-70 hover:bg-transparent hover:opacity-100 active:cursor-grabbing', className)}
aria-label={i18n.labels.dragToReorderRow}
{...context.attributes}
{...context.listeners}
>
<GripHorizontalIcon aria-hidden="true" />
</Button>
);
}
/**
* The rows do not move while one is being carried.
*
* Sliding the siblings apart opens a gap the carried row could go into, which
* reads well in a list of identical rows and badly in a table: the gap is the
* height of the row you are holding, so with rows of unequal height it never
* matches the slot it claims to be, and the row you picked up slides away from
* where it started - which is exactly the position you need to remember if you
* decide not to drop it.
*
* Holding everything still keeps the origin legible, and nothing is lost: the
* DragOverlay clone follows the pointer and the drop indicator names the seam.
* Pass `verticalListSortingStrategy` as `sortingStrategy` for the old feel.
*/
const holdRowsInPlaceStrategy: SortingStrategy = () => null;
function DataGridTableDndRow<TData extends object>({
row,
renderRowDecoration,
dropIndicator = true,
}: {
row: Row<DataGridFeatures, TData>;
renderRowDecoration?: DataGridTableDndRowDecoration<TData>;
dropIndicator?: boolean;
}) {
const rowData: DataGridTableDndRowData = {
type: 'data-grid-row',
depth: row.depth,
index: row.index,
parentId: row.getParentRow()?.id ?? null,
};
const { transform, setNodeRef, isDragging, isOver, attributes, listeners, index, activeIndex, overIndex } = useSortable({
id: row.id,
data: rowData,
});
// Which edge of THIS row the carried row would land on, or null when it is
// not the drop target. Nothing slides apart any more, so the bar is the only
// thing that says where the drop goes: it marks the row at the destination
// index, on the side the carried row comes to rest.
//
// Dragging down it lands after the target, dragging up before it, so the
// edge follows the direction of travel.
const dropEdge = dropIndicator && activeIndex !== -1 && index === overIndex && !isDragging ? (activeIndex < overIndex ? 'bottom' : 'top') : null;
const style: CSSProperties = {
transform: CSS.Transform.toString(transform),
// dnd-kit's transition is deliberately dropped. A transition on a transform
// property of a `tr` does not merely fail to animate in Chrome, it stops the
// transform applying at all: the element sits at the start value forever.
// The drag source escapes it because dnd-kit disables its own transition
// while it is being dragged, which is why the carried row used to be the
// ONLY one that moved and every other row silently refused to open a gap.
// Displacement therefore lands in one step, which is what a table wants.
zIndex: isDragging ? 1 : 0,
position: 'relative',
cursor: isDragging ? 'grabbing' : undefined,
// The row you are holding is drawn by the DragOverlay, so the one left
// behind is not a second copy of it - it is the slot you came from, and it
// stays exactly where it was. Fading alone read as "this row is busy";
// the outline says "this is the space you are moving out of", which is the
// thing you need if you change your mind mid-drag.
...(isDragging && {
opacity: 0.4,
// Inset so the dashes sit inside the row box and cannot be clipped by
// the neighbouring row's border.
outline: '1px dashed var(--border)',
outlineOffset: '-1px',
}),
};
const decoration = renderRowDecoration?.({ row, isDragging, isOver });
return (
<SortableRowContext.Provider value={{ attributes, listeners }}>
<DataGridTableBodyRow row={row} dndRef={setNodeRef} dndStyle={style}>
{row.getVisibleCells().map((cell: Cell<DataGridFeatures, TData, unknown>, index, cells) => {
return (
<DataGridTableBodyRowCell cell={cell} key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
{decoration && index === cells.length - 1 ? (
// Rides inside the last cell rather than in a `td` of its own.
// An absolutely positioned `td` is still a cell as far as table
// layout is concerned, so it added a NINTH column with no width
// of its own, and under `table-layout: fixed` that new column
// swallowed the whole surplus the real columns had been sharing
// — every column snapped back to its declared size and the row's
// content visibly narrowed the moment a drag began. A plain
// element adds no column. It still anchors to the ROW, because
// the row is the nearest positioned ancestor, so the decoration
// spans the full width and is not clipped by the cell.
<div aria-hidden="true" data-slot="data-grid-table-row-decoration" className="pointer-events-none absolute inset-0">
{decoration}
</div>
) : null}
{dropEdge && index === cells.length - 1 ? (
// Same anchoring trick as the decoration above: a plain
// element inside the last cell, so it adds no column and
// cannot disturb `table-layout: fixed`. It spans the row
// because the row is the nearest positioned ancestor.
<div
aria-hidden="true"
data-slot="data-grid-table-row-drop-indicator"
data-edge={dropEdge}
className="pointer-events-none absolute inset-0 z-20"
>
{/* Two solid pixels down the leading edge, the same marker
the tree drag uses for its drop target. A wash across
the row has to stay faint enough not to read as a
selected row, and in the achromatic styles primary
carries no chroma at all, so faint plus colourless is
just grey. The bar reads at any weight and leaves the
row's own background to hover and selection.
The bar is the whole indicator: the gap the rows have
already opened says which side, so a rule across the
seam as well only competes with the row borders it sits
between. `data-edge` still carries the direction for
anyone styling their own. */}
<span className="bg-primary absolute inset-y-0 start-0 w-0.5" />
</div>
) : null}
</DataGridTableBodyRowCell>
);
})}
<DataGridTableFillBodyCell />
</DataGridTableBodyRow>
{row.getIsExpanded() && <DataGridTableBodyRowExpandded row={row} />}
</SortableRowContext.Provider>
);
}
function DataGridTableDndRowsBody<TData extends object>({
table,
dataIds,
renderRowDecoration,
dropIndicator,
sortingStrategy,
}: {
table: DataGridTableInstance<TData>;
dataIds: UniqueIdentifier[];
renderRowDecoration?: DataGridTableDndRowDecoration<TData>;
dropIndicator?: boolean;
sortingStrategy: SortingStrategy;
}) {
const { isLoading, props } = useDataGrid();
const pagination = table.state.pagination;
if (props.loadingMode === 'skeleton' && isLoading && pagination?.pageSize) {
return (
<>
{Array.from({ length: pagination.pageSize }).map((_, rowIndex) => (
<DataGridTableBodyRowSkeleton key={rowIndex}>
{table.getVisibleFlatColumns().map((column, colIndex) => {
return (
<DataGridTableBodyRowSkeletonCell column={column} key={colIndex}>
{column.columnDef.meta?.skeleton}
</DataGridTableBodyRowSkeletonCell>
);
})}
<DataGridTableFillBodyCell />
</DataGridTableBodyRowSkeleton>
))}
</>
);
}
if (!table.getRowModel().rows.length) return <DataGridTableEmpty />;
return (
<SortableContext items={dataIds} strategy={sortingStrategy}>
{table.getRowModel().rows.map((row: Row<DataGridFeatures, TData>) => {
return <DataGridTableDndRow row={row} renderRowDecoration={renderRowDecoration} dropIndicator={dropIndicator} key={row.id} />;
})}
</SortableContext>
);
}
/**
* Memoized body rows: skip re-renders during active column resize.
* Column widths update via CSS variables on the <table> element,
* so the browser handles width changes without React re-renders.
*/
const MemoizedDataGridTableDndRowsBody = memo(
DataGridTableDndRowsBody,
(_prev, next) => !!next.table.state.columnResizing.isResizingColumn,
) as typeof DataGridTableDndRowsBody;
function DataGridTableDndRows<TData extends object>({
handleDragEnd,
dataIds,
footerContent,
collisionDetection = closestCenter,
modifiers,
sortingStrategy = holdRowsInPlaceStrategy,
renderRowDecoration,
dropIndicator = true,
onDragStart,
onDragMove,
onDragOver,
onDragCancel,
}: {
handleDragEnd: (event: DragEndEvent) => void;
dataIds: UniqueIdentifier[];
footerContent?: ReactNode;
/** Overrides the default `closestCenter` strategy. */
collisionDetection?: CollisionDetection;
/**
* Replaces the default axis restriction, e.g. drop `restrictToVerticalAxis`
* to allow the horizontal gesture that tree re-parenting relies on. The
* table container clamp is always applied after these, so a dragged row
* cannot leave the grid.
*/
modifiers?: Modifier[];
/**
* Replaces the default `verticalListSortingStrategy`. Return null from a
* strategy to leave every row exactly where it is. A tree needs that: its drop
* is either INTO the hovered row or BETWEEN two rows, and which one it is
* flips as the pointer crosses a single row, so a gap that opens for one and
* shuts for the other flickers the whole surface. Such a caller draws its own
* insertion line instead, and pairs this with a modifier that holds the
* carried row still, since a gap nothing moves into is just a hole.
*/
sortingStrategy?: SortingStrategy;
/** Per-row slot for drop indicators and depth guides. */
renderRowDecoration?: DataGridTableDndRowDecoration<TData>;
/**
* Draws a line on the seam the carried row would land on. On by default;
* pass `false` when `renderRowDecoration` paints its own insertion affordance
* and the two would compete.
*/
dropIndicator?: boolean;
onDragStart?: (event: DragStartEvent) => void;
onDragMove?: (event: DragMoveEvent) => void;
onDragOver?: (event: DragOverEvent) => void;
onDragCancel?: (event: DragCancelEvent) => void;
}) {
const { table, props } = useDataGrid<TData>();
const tableContainerRef = useRef<HTMLDivElement>(null);
const [isDraggingRow, setIsDraggingRow] = useState(false);
// The overlay is portalled to the document body. dnd-kit renders DragOverlay
// in place, and it positions with `position: fixed` against viewport
// coordinates - so any ancestor that establishes a containing block for fixed
// descendants silently re-anchors it. `content-visibility`, `contain`,
// `transform`, `filter` and `will-change` all do that, and the first two are
// exactly what a card grid uses to defer off-screen work. The clone then
// lands offset by that ancestor's own top/left, and the container clamp
// below mis-clamps too, because its rects are measured in viewport space.
//
// Resolved in an effect rather than read at render so the server and the
// first client render agree. A drag cannot start before hydration, so the
// overlay being absent for one frame costs nothing.
const [portalTarget, setPortalTarget] = useState<HTMLElement | null>(null);
useEffect(() => {
setPortalTarget(document.body);
}, []);
// The row being carried, plus the column widths measured off the header the
// moment the drag starts. The clone lives outside the table, so it has no
// columns of its own and has to be told what they are.
const [carried, setCarried] = useState<{
id: UniqueIdentifier;
width: number;
height: number;
columns: number[];
} | null>(null);
const pickUpRow = useCallback((id: UniqueIdentifier) => {
const container = tableContainerRef.current;
const head = container?.querySelector('thead tr');
if (!container || !head) {
setCarried(null);
return;
}
// The clone has to be exactly as tall as the row it was lifted from.
// A fixed height reads as the grid growing under the pointer the moment
// you pick a row up, and it is wrong in both directions: rows whose
// content wraps are taller than any constant, and dense rows are shorter.
const source = Array.from(container.querySelectorAll<HTMLElement>('tbody tr[data-row-id]')).find(
(candidate) => candidate.dataset.rowId === String(id),
);
const height = source?.getBoundingClientRect().height ?? 0;
// The fill cell is a header-only spacer that soaks up the surplus a column
// resize leaves behind, and the clone renders data cells only. Measuring it
// in would make the clone's table wider than the cells it actually holds,
// and `table-fixed` hands that orphaned width back out across every column
// -- the carried row comes out visibly wider than the row it was lifted
// from. So the width is the sum of what we render, never the header's own.
const columns = Array.from(head.children)
.filter((cell) => cell.getAttribute('data-slot') !== 'data-grid-table-fill-head-cell')
.map((cell) => cell.getBoundingClientRect().width);
setCarried({
id,
width: columns.reduce((total, width) => total + width, 0),
height,
columns,
});
}, []);
const carriedRow = carried ? table.getRowModel().rows.find((row: Row<DataGridFeatures, TData>) => row.id === carried.id) : undefined;
const sensors = useSensors(
useSensor(MouseSensor, {}),
useSensor(TouchSensor, {}),
// Keyboard reordering moves one sortable position per keypress instead
// of the sensor's raw 25px default.
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
}),
);
useEffect(() => {
if (!isDraggingRow) return;
const { body, documentElement } = document;
const previousBodyCursor = body.style.cursor;
const previousDocumentCursor = documentElement.style.cursor;
body.style.cursor = 'grabbing';
documentElement.style.cursor = 'grabbing';
return () => {
body.style.cursor = previousBodyCursor;
documentElement.style.cursor = previousDocumentCursor;
};
}, [isDraggingRow]);
const resolvedModifiers = useMemo(() => {
const restrictToTableContainer: Modifier = ({ transform, draggingNodeRect }) => {
if (!tableContainerRef.current || !draggingNodeRect) {
return transform;
}
const containerRect = tableContainerRef.current.getBoundingClientRect();
const { x, y } = transform;
const minX = containerRect.left - draggingNodeRect.left;
const maxX = containerRect.right - draggingNodeRect.right;
const minY = containerRect.top - draggingNodeRect.top;
const maxY = containerRect.bottom - draggingNodeRect.bottom;
return {
...transform,
// The horizontal rail only engages while the default axis restriction
// is in force. A row is exactly as wide as the viewport, so minX and
// maxX both collapse to 0 and clamping x erases it entirely: harmless
// under restrictToVerticalAxis, which zeroes x anyway, but fatal for a
// caller that replaced the restriction precisely to READ x, as a tree
// does to resolve drop depth. Vertical is railed either way, which is
// what actually keeps a dragged row inside the grid.
x: modifiers ? x : Math.max(minX, Math.min(maxX, x)),
y: Math.max(minY, Math.min(maxY, y)),
};
};
// The container clamp is a safety rail rather than a policy, so it stays
// applied even when the caller replaces the axis restriction.
return [...(modifiers ?? [restrictToVerticalAxis]), restrictToTableContainer];
}, [modifiers]);
return (
<DndContext
id={useId()}
collisionDetection={collisionDetection}
modifiers={resolvedModifiers}
onDragCancel={(event) => {
setIsDraggingRow(false);
setCarried(null);
onDragCancel?.(event);
}}
onDragEnd={(event) => {
setIsDraggingRow(false);
setCarried(null);
handleDragEnd(event);
}}
onDragMove={onDragMove}
onDragOver={onDragOver}
onDragStart={(event) => {
setIsDraggingRow(true);
pickUpRow(event.active.id);
onDragStart?.(event);
}}
sensors={sensors}
>
<DataGridTableViewport
viewportRef={tableContainerRef}
className={isDraggingRow ? 'relative cursor-grabbing [&_*]:cursor-grabbing!' : 'relative'}
>
<DataGridTableBase>
<DataGridTableHead>
{table.getHeaderGroups().map((headerGroup: HeaderGroup<DataGridFeatures, TData>, index) => {
return (
<DataGridTableHeadRow key={index} rowId={headerGroup.id}>
{headerGroup.headers.map((header, index) => {
const { column } = header;
return (
<DataGridTableHeadRowCell header={header} key={index}>
{header.isPlaceholder ? null : props.tableLayout?.columnsResizable && column.getCanResize() ? (
<>{flexRender(header.column.columnDef.header, header.getContext())}</>
) : (
flexRender(header.column.columnDef.header, header.getContext())
)}
{props.tableLayout?.columnsResizable && column.getCanResize() && <DataGridTableHeadRowCellResize header={header} />}
</DataGridTableHeadRowCell>
);
})}
<DataGridTableFillHeadCell />
</DataGridTableHeadRow>
);
})}
</DataGridTableHead>
{(props.tableLayout?.stripped || !props.tableLayout?.rowBorder) && <DataGridTableRowSpacer />}
<DataGridTableBody>
<MemoizedDataGridTableDndRowsBody
table={table}
dataIds={dataIds}
renderRowDecoration={renderRowDecoration}
dropIndicator={dropIndicator}
sortingStrategy={sortingStrategy}
/>
</DataGridTableBody>
{footerContent && <DataGridTableFoot>{footerContent}</DataGridTableFoot>}
</DataGridTableBase>
</DataGridTableViewport>
{/* The row you are actually holding. It is a real clone rendered outside
the table, which is the only way a dragged row can follow the pointer
without disturbing the grid: it adds no cell, so it cannot alter the
column widths, and it floats above the rows rather than through them.
Its presence also tells dnd-kit to stop translating the source row, so
the row left behind simply dims in place.
Portalled to the body so the fixed positioning resolves against the
viewport wherever the grid is mounted. React context crosses a portal,
so DndContext still reaches it. */}
{portalTarget
? createPortal(
<DragOverlay dropAnimation={null}>
{carried && carriedRow ? (
<table
aria-hidden="true"
style={{ width: carried.width, tableLayout: 'fixed' }}
className="bg-background border-border pointer-events-none cursor-grabbing rounded-md border shadow-lg"
>
<tbody>
{/* Padding rides on the inner element, not the cell. A `td` can
never render narrower than its own horizontal padding, so a
column resized below that would silently widen here and the
clone would stop matching the row it came from. Height comes
from the measured source row for the same reason the widths
do: the clone has no row of its own to inherit it from. */}
<tr style={{ height: carried.height || undefined }} className="[&>td]:p-0 [&>td]:align-middle">
{carriedRow.getVisibleCells().map((cell: Cell<DataGridFeatures, TData, unknown>, index: number) => (
<td
key={cell.id}
// Falls back to the column's own size so an unforeseen
// header/cell count mismatch degrades to a real width
// rather than to `auto`.
style={{
width: carried.columns[index] ?? cell.column.getSize(),
}}
>
<div className="truncate px-3">{flexRender(cell.column.columnDef.cell, cell.getContext())}</div>
</td>
))}
</tr>
</tbody>
</table>
) : null}
</DragOverlay>,
portalTarget,
)
: null}
</DndContext>
);
}
export { DataGridTableDndRowHandle, DataGridTableDndRows };
export type { DataGridTableDndRowData, DataGridTableDndRowDecoration };components/ui/data-grid/data-grid-table-dnd.tsx
import { Fragment, memo, useEffect, useId, useMemo, useRef, useState } from 'react';
import type { CSSProperties, ReactNode } from 'react';
import { useDataGrid } from '@/registry/vcare/ui/data-grid/data-grid';
import type { DataGridFeatures, DataGridTableInstance } from '@/registry/vcare/ui/data-grid/data-grid';
import {
DataGridTableBase,
DataGridTableBody,
DataGridTableBodyRow,
DataGridTableBodyRowCell,
DataGridTableBodyRowExpandded,
DataGridTableBodyRowSkeleton,
DataGridTableBodyRowSkeletonCell,
DataGridTableEmpty,
DataGridTableFillBodyCell,
DataGridTableFillHeadCell,
DataGridTableFoot,
DataGridTableHead,
DataGridTableHeadRow,
DataGridTableHeadRowCell,
DataGridTableHeadRowCellResize,
DataGridTableRowSpacer,
DataGridTableViewport,
} from '@/registry/vcare/ui/data-grid/data-grid-table';
import {
closestCenter,
DndContext,
KeyboardSensor,
MouseSensor,
TouchSensor,
useSensor,
useSensors,
type DragEndEvent,
type Modifier,
} from '@dnd-kit/core';
import { horizontalListSortingStrategy, SortableContext, sortableKeyboardCoordinates, useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { flexRender } from '@tanstack/react-table';
import type { Cell, Header, HeaderGroup, Row, Table } from '@tanstack/react-table';
import { Button } from '@/registry/vcare/ui/button';
import { GripVerticalIcon } from 'lucide-react';
function DataGridTableDndHeader<TData extends object>({ header }: { header: Header<DataGridFeatures, TData, unknown> }) {
const { i18n, props } = useDataGrid();
const { column } = header;
// Check if column ordering is enabled for this column
const canOrder = (column.columnDef as { enableColumnOrdering?: boolean }).enableColumnOrdering !== false;
const { attributes, isDragging, listeners, setNodeRef, transform, transition } = useSortable({
id: header.column.id,
});
const style: CSSProperties = {
opacity: isDragging ? 0.8 : 1,
position: 'relative',
transform: CSS.Translate.toString(transform),
transition,
cursor: isDragging ? 'grabbing' : undefined,
whiteSpace: 'nowrap',
width: props.tableLayout?.columnsResizable ? `calc(var(--header-${header.id}-size) * 1px)` : header.column.getSize(),
zIndex: isDragging ? 1 : 0,
};
return (
<DataGridTableHeadRowCell header={header} dndStyle={style} dndRef={setNodeRef}>
<div className="flex items-center justify-start gap-0.5">
{canOrder && (
<Button
size="icon-sm"
variant="ghost"
className={`-ms-2 size-6 ${isDragging ? 'cursor-grabbing' : 'cursor-grab active:cursor-grabbing'}`}
{...attributes}
{...listeners}
aria-label={i18n.labels.dragToReorder}
>
<GripVerticalIcon className="opacity-60 hover:opacity-100" aria-hidden="true" />
</Button>
)}
<div className="grow">{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}</div>
{props.tableLayout?.columnsResizable && column.getCanResize() && <DataGridTableHeadRowCellResize header={header} />}
</div>
</DataGridTableHeadRowCell>
);
}
function DataGridTableDndCell<TData extends object>({ cell }: { cell: Cell<DataGridFeatures, TData, unknown> }) {
const { props } = useDataGrid();
const { isDragging, setNodeRef, transform, transition } = useSortable({
id: cell.column.id,
});
const style: CSSProperties = {
opacity: isDragging ? 0.8 : 1,
position: 'relative',
transform: CSS.Translate.toString(transform),
transition,
cursor: isDragging ? 'grabbing' : undefined,
width: props.tableLayout?.columnsResizable ? `calc(var(--col-${cell.column.id}-size) * 1px)` : cell.column.getSize(),
zIndex: isDragging ? 1 : 0,
};
return (
<DataGridTableBodyRowCell cell={cell} dndStyle={style} dndRef={setNodeRef}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</DataGridTableBodyRowCell>
);
}
function DataGridTableDndBodyRows<TData extends object>({ table }: { table: DataGridTableInstance<TData> }) {
const { isLoading, props } = useDataGrid();
const pagination = table.state.pagination;
if (props.loadingMode === 'skeleton' && isLoading && pagination?.pageSize) {
return (
<>
{Array.from({ length: pagination.pageSize }).map((_, rowIndex) => (
<DataGridTableBodyRowSkeleton key={rowIndex}>
{table.getVisibleFlatColumns().map((column, colIndex) => {
return (
<DataGridTableBodyRowSkeletonCell column={column} key={colIndex}>
{column.columnDef.meta?.skeleton}
</DataGridTableBodyRowSkeletonCell>
);
})}
<DataGridTableFillBodyCell />
</DataGridTableBodyRowSkeleton>
))}
</>
);
}
if (!table.getRowModel().rows.length) return <DataGridTableEmpty />;
return (
<>
{table.getRowModel().rows.map((row: Row<DataGridFeatures, TData>) => {
return (
<Fragment key={row.id}>
<DataGridTableBodyRow row={row}>
<SortableContext items={table.state.columnOrder} strategy={horizontalListSortingStrategy}>
{row.getVisibleCells().map((cell: Cell<DataGridFeatures, TData, unknown>) => (
<DataGridTableDndCell cell={cell} key={cell.id} />
))}
</SortableContext>
<DataGridTableFillBodyCell />
</DataGridTableBodyRow>
{row.getIsExpanded() && <DataGridTableBodyRowExpandded row={row} />}
</Fragment>
);
})}
</>
);
}
/**
* Memoized body rows: skip re-renders during active column resize.
* Column widths update via CSS variables on the <table> element,
* so the browser handles width changes without React re-renders.
*/
const MemoizedDataGridTableDndBodyRows = memo(
DataGridTableDndBodyRows,
(_prev, next) => !!next.table.state.columnResizing.isResizingColumn,
) as typeof DataGridTableDndBodyRows;
function DataGridTableDnd<TData extends object>({
handleDragEnd,
footerContent,
}: {
handleDragEnd: (event: DragEndEvent) => void;
footerContent?: ReactNode;
}) {
const { table, props } = useDataGrid();
const containerRef = useRef<HTMLDivElement>(null);
const [isDraggingColumn, setIsDraggingColumn] = useState(false);
const sensors = useSensors(
useSensor(MouseSensor, {}),
useSensor(TouchSensor, {}),
// Keyboard reordering moves one sortable position per keypress instead
// of the sensor's raw 25px default.
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
}),
);
useEffect(() => {
if (!isDraggingColumn) return;
const { body, documentElement } = document;
const previousBodyCursor = body.style.cursor;
const previousDocumentCursor = documentElement.style.cursor;
body.style.cursor = 'grabbing';
documentElement.style.cursor = 'grabbing';
return () => {
body.style.cursor = previousBodyCursor;
documentElement.style.cursor = previousDocumentCursor;
};
}, [isDraggingColumn]);
// Custom modifier to restrict dragging within table bounds with edge offset
const modifiers = useMemo(() => {
const restrictToTableBounds: Modifier = ({ draggingNodeRect, transform }) => {
if (!draggingNodeRect || !containerRef.current) {
return { ...transform, y: 0 };
}
const containerRect = containerRef.current.getBoundingClientRect();
const edgeOffset = 0;
const minX = containerRect.left - draggingNodeRect.left - edgeOffset;
const maxX = containerRect.right - draggingNodeRect.left - draggingNodeRect.width + edgeOffset;
return {
...transform,
x: Math.min(Math.max(transform.x, minX), maxX),
y: 0, // Lock vertical movement
};
};
return [restrictToTableBounds];
}, []);
return (
<DndContext
collisionDetection={closestCenter}
id={useId()}
modifiers={modifiers}
onDragCancel={() => setIsDraggingColumn(false)}
onDragEnd={(event) => {
setIsDraggingColumn(false);
handleDragEnd(event);
}}
onDragStart={() => setIsDraggingColumn(true)}
sensors={sensors}
>
<DataGridTableViewport viewportRef={containerRef} className={isDraggingColumn ? 'relative cursor-grabbing [&_*]:cursor-grabbing!' : 'relative'}>
<DataGridTableBase>
<DataGridTableHead>
{table.getHeaderGroups().map((headerGroup: HeaderGroup<DataGridFeatures, TData>, index) => {
return (
<DataGridTableHeadRow key={index} rowId={headerGroup.id}>
<SortableContext items={table.state.columnOrder} strategy={horizontalListSortingStrategy}>
{headerGroup.headers.map((header) => (
<DataGridTableDndHeader header={header} key={header.id} />
))}
</SortableContext>
<DataGridTableFillHeadCell />
</DataGridTableHeadRow>
);
})}
</DataGridTableHead>
{(props.tableLayout?.stripped || !props.tableLayout?.rowBorder) && <DataGridTableRowSpacer />}
<DataGridTableBody>
<MemoizedDataGridTableDndBodyRows table={table} />
</DataGridTableBody>
{footerContent && <DataGridTableFoot>{footerContent}</DataGridTableFoot>}
</DataGridTableBase>
</DataGridTableViewport>
</DndContext>
);
}
export { DataGridTableDnd };components/ui/data-grid/data-grid-table-virtual.tsx
'use client';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { CSSProperties, ReactNode } from 'react';
import { useDataGrid } from '@/registry/vcare/ui/data-grid/data-grid';
import type { DataGridFeatures, DataGridTableInstance } from '@/registry/vcare/ui/data-grid/data-grid';
import {
DataGridTableAddRow,
DataGridTableBase,
DataGridTableBody,
DataGridTableEmpty,
DataGridTableFillBodyCell,
DataGridTableFillHeadCell,
DataGridTableFoot,
DataGridTableHead,
DataGridTableHeadRow,
DataGridTableHeadRowCell,
DataGridTableHeadRowCellResize,
DataGridTableRenderedRow,
DataGridTableRowSpacer,
DataGridTableViewport,
getDataGridScrollAreaViewport,
getDataGridTableMergedHeaderGroups,
getDataGridTableRowSections,
getPinningStyles,
hasDataGridTableRightPinnedColumns,
} from '@/registry/vcare/ui/data-grid/data-grid-table';
import { flexRender } from '@tanstack/react-table';
import type { Column, Row, Table } from '@tanstack/react-table';
import { useVirtualizer } from '@tanstack/react-virtual';
import type { VirtualItem, Virtualizer, VirtualizerOptions } from '@tanstack/react-virtual';
import { cn } from '@/registry/vcare/lib/utils';
import { Spinner } from '@/registry/vcare/ui/spinner';
type DataGridTableVirtualScrollElements = {
containerElement: HTMLDivElement | null;
scrollElement: HTMLElement | null;
};
type DataGridTableVirtualizerInstance = Virtualizer<HTMLElement, HTMLTableRowElement>;
type DataGridTableVirtualScrollAlignment = 'auto' | 'center' | 'start' | 'end';
interface DataGridTableColumnVirtualizerOptions {
/** Off unless explicitly true; a column window is opt-in. */
enabled?: boolean;
overscan?: number;
}
type DataGridTableColumnScrollRequest = {
align: DataGridTableVirtualScrollAlignment;
behavior: ScrollBehavior;
columnId: string | undefined;
columnIndex: number;
scrollElement: HTMLElement;
};
function isSameDataGridTableColumnScrollRequest(previous: DataGridTableColumnScrollRequest | null, next: DataGridTableColumnScrollRequest) {
return (
previous?.align === next.align &&
previous.behavior === next.behavior &&
previous.columnId === next.columnId &&
previous.columnIndex === next.columnIndex &&
previous.scrollElement === next.scrollElement
);
}
type DataGridTableVirtualScrollRequest = {
align: DataGridTableVirtualScrollAlignment;
behavior: ScrollBehavior;
containerElement: HTMLDivElement;
headerSticky: boolean;
isVirtualizationEnabled: boolean;
rowId: string | undefined;
rowIndex: number;
scrollElement: HTMLElement;
};
function isSameDataGridTableScrollRequest(previous: DataGridTableVirtualScrollRequest | null, next: DataGridTableVirtualScrollRequest) {
return (
previous?.align === next.align &&
previous.behavior === next.behavior &&
previous.containerElement === next.containerElement &&
previous.headerSticky === next.headerSticky &&
previous.isVirtualizationEnabled === next.isVirtualizationEnabled &&
previous.rowId === next.rowId &&
previous.rowIndex === next.rowIndex &&
previous.scrollElement === next.scrollElement
);
}
function getDataGridTableScrollTarget({
align,
clientHeight,
rowBottom,
rowHeight,
rowTop,
scrollHeight,
scrollTop,
viewportTopOffset = 0,
}: {
align: DataGridTableVirtualScrollAlignment;
clientHeight: number;
rowBottom: number;
rowHeight: number;
rowTop: number;
scrollHeight: number;
scrollTop: number;
viewportTopOffset?: number;
}) {
const visibleHeight = Math.max(0, clientHeight - viewportTopOffset);
const viewportTop = scrollTop + viewportTopOffset;
const viewportBottom = scrollTop + clientHeight;
const targetTop =
align === 'auto'
? rowTop < viewportTop
? rowTop - viewportTopOffset
: rowBottom > viewportBottom
? rowBottom - clientHeight
: null
: align === 'start'
? rowTop - viewportTopOffset
: align === 'end'
? rowBottom - clientHeight
: rowTop - viewportTopOffset - Math.max(0, (visibleHeight - rowHeight) / 2);
if (targetTop === null) return null;
return Math.min(Math.max(0, targetTop), Math.max(0, scrollHeight - clientHeight));
}
function getDataGridTableHeaderOffset({
containerElement,
headerSticky,
scrollElement,
}: {
containerElement: HTMLDivElement;
headerSticky: boolean;
scrollElement: HTMLElement;
}) {
if (!headerSticky) return 0;
const headerElement = containerElement.querySelector<HTMLElement>(':scope > [data-slot="data-grid-table"] > thead');
if (!headerElement) return 0;
const scrollRect = scrollElement.getBoundingClientRect();
const headerRect = headerElement.getBoundingClientRect();
const headerBottomOffset = headerRect.bottom - scrollRect.top;
const overlapsViewportTop = headerRect.top <= scrollRect.top + 0.5 && headerBottomOffset > 0;
if (!overlapsViewportTop) return 0;
return Math.min(scrollElement.clientHeight, Math.max(0, headerBottomOffset));
}
function scrollDataGridTableToOffset({
behavior,
scrollElement,
targetTop,
virtualizer,
}: {
behavior: ScrollBehavior;
scrollElement: HTMLElement;
targetTop: number;
virtualizer?: DataGridTableVirtualizerInstance;
}) {
if (virtualizer) {
virtualizer.scrollToOffset(targetTop, { align: 'start', behavior });
} else if (typeof scrollElement.scrollTo === 'function') {
scrollElement.scrollTo({ behavior, top: targetTop });
} else {
scrollElement.scrollTop = targetTop;
}
}
function scrollDataGridTableRowIntoView({
align,
behavior,
cancelPendingScroll = false,
containerElement,
headerSticky,
rowIndex,
scrollElement,
virtualizer,
}: {
align: DataGridTableVirtualScrollAlignment;
behavior: ScrollBehavior;
cancelPendingScroll?: boolean;
containerElement: HTMLDivElement | null;
headerSticky: boolean;
rowIndex: number;
scrollElement: HTMLElement | null;
virtualizer?: DataGridTableVirtualizerInstance;
}) {
if (!containerElement || !scrollElement) return false;
const rowElement = containerElement.querySelector<HTMLTableRowElement>(
`:scope > [data-slot="data-grid-table"] > tbody > tr[data-index="${rowIndex}"]`,
);
if (!rowElement) return false;
const scrollRect = scrollElement.getBoundingClientRect();
const rowRect = rowElement.getBoundingClientRect();
const viewportTopOffset = getDataGridTableHeaderOffset({
containerElement,
headerSticky,
scrollElement,
});
const rowTop = scrollElement.scrollTop + rowRect.top - scrollRect.top;
const rowBottom = scrollElement.scrollTop + rowRect.bottom - scrollRect.top;
const targetTop = getDataGridTableScrollTarget({
align,
clientHeight: scrollElement.clientHeight,
rowBottom,
rowHeight: rowRect.height || rowElement.offsetHeight,
rowTop,
scrollHeight: scrollElement.scrollHeight,
scrollTop: scrollElement.scrollTop,
viewportTopOffset,
});
if (targetTop === null || Math.abs(targetTop - scrollElement.scrollTop) < 0.5) {
if (cancelPendingScroll) {
scrollDataGridTableToOffset({
behavior: 'auto',
scrollElement,
targetTop: scrollElement.scrollTop,
virtualizer,
});
}
return true;
}
scrollDataGridTableToOffset({
behavior,
scrollElement,
targetTop,
virtualizer,
});
return true;
}
type DataGridTableVirtualizerOptions<TData extends object> = Omit<
VirtualizerOptions<HTMLElement, HTMLTableRowElement>,
'count' | 'estimateSize' | 'getItemKey' | 'getScrollElement'
> & {
estimateSize?: (index: number, row: Row<DataGridFeatures, TData>) => number;
getItemKey?: (index: number, row: Row<DataGridFeatures, TData>) => string | number;
getScrollElement?: (elements: DataGridTableVirtualScrollElements) => HTMLElement | null;
};
interface DataGridTableVirtualProps<TData extends object> {
height?: number | string;
estimateSize?: number;
overscan?: number;
/** Scroll animation used when revealing a controlled target row. */
scrollBehavior?: ScrollBehavior;
/** Alignment used when revealing a controlled target row. Defaults to auto. */
scrollToRowAlign?: DataGridTableVirtualScrollAlignment;
/** Index within the center (non-pinned) row section to reveal. */
scrollToRowIndex?: number;
/**
* Opt-in horizontal virtualization of the CENTER columns. Activates only
* under a fixed table layout with a single ungrouped header row; pinned
* columns stay mounted, and anything else falls back to full-column
* rendering. `scrollBehavior` is shared with controlled row scrolling.
*/
columnVirtualizerOptions?: DataGridTableColumnVirtualizerOptions;
/** Alignment used when revealing a controlled target column. */
scrollToColumnAlign?: DataGridTableVirtualScrollAlignment;
/** Index within the center (non-pinned) visible leaf columns to reveal. */
scrollToColumnIndex?: number;
footerContent?: ReactNode;
renderHeader?: boolean;
onFetchMore?: () => void;
isFetchingMore?: boolean;
hasMore?: boolean;
fetchMoreOffset?: number;
virtualizerOptions?: DataGridTableVirtualizerOptions<TData>;
}
interface VirtualBodyProps<TData extends object> {
table: DataGridTableInstance<TData>;
topRows: Row<DataGridFeatures, TData>[];
centerRows: Row<DataGridFeatures, TData>[];
bottomRows: Row<DataGridFeatures, TData>[];
virtualItems: VirtualItem[];
totalSize: number;
isVirtualizationEnabled: boolean;
isInfiniteMode: boolean;
isFetchingMore: boolean;
hasMore?: boolean;
loadingMoreMessage: ReactNode;
allRowsLoadedMessage: ReactNode;
measureRowRef?: (element: HTMLTableRowElement | null) => void;
centerColumnWindow?: { start: number; end: number };
}
function DataGridTableVirtualPinnedPlaceholderCell<TData extends object>({ column }: { column: Column<DataGridFeatures, TData, unknown> }) {
const { props } = useDataGrid();
const isPinned = column.getIsPinned();
const isLastStartPinned = isPinned === 'start' && column.getIsLastColumn('start');
const isFirstEndPinned = isPinned === 'end' && column.getIsFirstColumn('end');
return (
<td
aria-hidden="true"
style={{
...(props.tableLayout?.columnsPinnable && column.getCanPin() && getPinningStyles(column)),
...(props.tableLayout?.columnsResizable && {
width: `calc(var(--col-${column.id}-size) * 1px)`,
}),
}}
data-pinned={isPinned || undefined}
data-last-col={isLastStartPinned ? 'start' : isFirstEndPinned ? 'end' : undefined}
className={cn(
'p-0',
props.tableLayout?.cellBorder && 'border-e',
props.tableLayout?.columnsPinnable &&
column.getCanPin() &&
'data-pinned:bg-background data-pinned:isolate [&[data-pinned=end][data-last-col=end]]:shadow-[inset_1px_0_0_0_var(--border)] [&[data-pinned=start][data-last-col=start]]:shadow-[inset_-1px_0_0_0_var(--border)]',
)}
/>
);
}
function DataGridTableVirtualUtilityRow<TData extends object>({
table,
children,
centerCellClassName,
centerCellStyle,
rowClassName,
ariaHidden,
}: {
table: DataGridTableInstance<TData>;
children: ReactNode;
centerCellClassName?: string;
centerCellStyle?: CSSProperties;
rowClassName?: string;
ariaHidden?: boolean;
}) {
const { props } = useDataGrid();
const leftVisibleColumns = table.getStartVisibleLeafColumns();
const centerVisibleColumns = table.getCenterVisibleLeafColumns();
const rightVisibleColumns = table.getEndVisibleLeafColumns();
const hasRightPinnedColumns = hasDataGridTableRightPinnedColumns(table);
return (
<tr aria-hidden={ariaHidden || undefined} className={rowClassName}>
{leftVisibleColumns.map((column) => (
<DataGridTableVirtualPinnedPlaceholderCell column={column} key={column.id} />
))}
<td colSpan={Math.max(centerVisibleColumns.length, 1)} className={centerCellClassName} style={centerCellStyle}>
{children}
</td>
{props.tableLayout?.columnsResizable && hasRightPinnedColumns ? <DataGridTableFillBodyCell /> : null}
{rightVisibleColumns.map((column) => (
<DataGridTableVirtualPinnedPlaceholderCell column={column} key={column.id} />
))}
{props.tableLayout?.columnsResizable && !hasRightPinnedColumns ? <DataGridTableFillBodyCell /> : null}
</tr>
);
}
function DataGridTableVirtualSpacer<TData extends object>({ table, height }: { table: DataGridTableInstance<TData>; height: number }) {
if (height <= 0) return null;
return (
<DataGridTableVirtualUtilityRow table={table} ariaHidden centerCellClassName="p-0" centerCellStyle={{ height, padding: 0 }}>
{null}
</DataGridTableVirtualUtilityRow>
);
}
function DataGridTableVirtualStatusRow<TData extends object>({
table,
children,
className,
}: {
table: DataGridTableInstance<TData>;
children: ReactNode;
className?: string;
}) {
return (
<DataGridTableVirtualUtilityRow table={table} centerCellClassName={cn('text-muted-foreground py-4 text-center text-sm', className)}>
{children}
</DataGridTableVirtualUtilityRow>
);
}
/**
* A scroll frame only shifts the window, so every surviving row's inputs are
* identical and its last render is reused; the per-frame cost is the rows
* entering the window, not all mounted rows. Cell-level state (selection,
* focus, row checks) repaints through each cell's own Subscribe, and any real
* data change rebuilds the row wrappers, so identity comparison is safe.
*/
const MemoizedRenderedRow = memo(
DataGridTableRenderedRow,
(prev, next) =>
prev.row === next.row &&
prev.rowIndex === next.rowIndex &&
prev.rowRef === next.rowRef &&
prev.pinnedBoundary === next.pinnedBoundary &&
prev.centerWindow?.start === next.centerWindow?.start &&
prev.centerWindow?.end === next.centerWindow?.end,
) as typeof DataGridTableRenderedRow;
function DataGridTableVirtualBody<TData extends object>({
table,
topRows,
centerRows,
bottomRows,
virtualItems,
totalSize,
isVirtualizationEnabled,
isInfiniteMode,
isFetchingMore,
hasMore,
loadingMoreMessage,
allRowsLoadedMessage,
measureRowRef,
centerColumnWindow,
}: VirtualBodyProps<TData>) {
const { isLoading } = useDataGrid();
const totalRows = topRows.length + centerRows.length + bottomRows.length;
if (!totalRows) {
// Initial load must not flash the empty state as if the query returned
// nothing.
if (isLoading) {
return (
<DataGridTableVirtualStatusRow table={table}>
<div className="flex items-center justify-center gap-2">
<Spinner className="size-4 opacity-60" />
{loadingMoreMessage}
</div>
</DataGridTableVirtualStatusRow>
);
}
return <DataGridTableEmpty />;
}
const hasCenterRows = centerRows.length > 0;
const showFetchingRow = isInfiniteMode && isFetchingMore;
const showCompleteRow = isInfiniteMode && hasMore === false && totalRows > 0;
const hasMiddleSection = hasCenterRows || showFetchingRow || showCompleteRow;
const leadingSpacerHeight = isVirtualizationEnabled && hasCenterRows && virtualItems.length > 0 ? (virtualItems[0]?.start ?? 0) : 0;
const trailingSpacerHeight =
isVirtualizationEnabled && hasCenterRows && virtualItems.length > 0
? Math.max(0, totalSize - (virtualItems[virtualItems.length - 1]?.end ?? 0))
: 0;
const renderedRows: ReactNode[] = [];
topRows.forEach((row, index) => {
renderedRows.push(
<MemoizedRenderedRow
key={row.id}
row={row}
centerWindow={centerColumnWindow}
pinnedBoundary={index === topRows.length - 1 && hasMiddleSection ? 'top' : undefined}
/>,
);
});
if (isVirtualizationEnabled) {
if (leadingSpacerHeight > 0) {
renderedRows.push(<DataGridTableVirtualSpacer key="virtual-spacer-start" table={table} height={leadingSpacerHeight} />);
}
virtualItems.forEach((virtualRow) => {
const row = centerRows[virtualRow.index];
if (!row) return;
renderedRows.push(
<MemoizedRenderedRow key={row.id} row={row} rowRef={measureRowRef} rowIndex={virtualRow.index} centerWindow={centerColumnWindow} />,
);
});
if (trailingSpacerHeight > 0) {
renderedRows.push(<DataGridTableVirtualSpacer key="virtual-spacer-end" table={table} height={trailingSpacerHeight} />);
}
} else {
centerRows.forEach((row, rowIndex) => {
renderedRows.push(<MemoizedRenderedRow key={row.id} row={row} rowIndex={rowIndex} centerWindow={centerColumnWindow} />);
});
}
if (showFetchingRow) {
renderedRows.push(
<DataGridTableVirtualStatusRow key="virtual-status-loading" table={table}>
<div className="flex items-center justify-center gap-2">
<Spinner className="size-4 opacity-60" />
{loadingMoreMessage}
</div>
</DataGridTableVirtualStatusRow>,
);
}
if (showCompleteRow) {
renderedRows.push(
<DataGridTableVirtualStatusRow key="virtual-status-complete" table={table} className="py-3 text-xs">
{allRowsLoadedMessage}
</DataGridTableVirtualStatusRow>,
);
}
bottomRows.forEach((row, index) => {
renderedRows.push(
<MemoizedRenderedRow
key={row.id}
row={row}
centerWindow={centerColumnWindow}
pinnedBoundary={index === 0 && (topRows.length > 0 || hasMiddleSection) ? 'bottom' : undefined}
/>,
);
});
return <>{renderedRows}</>;
}
/**
* Memoized virtual body: skip re-renders during active column resize.
* Column widths update via CSS variables on the <table> element,
* so the browser handles width changes without React re-renders.
* A cell-selection drag gets the same treatment: painting goes through each
* cell's own Subscribe, and the virtualizer re-renders itself from inside the
* memo boundary, so parent-driven reconciliation during the drag is waste.
*/
const MemoizedVirtualBody = memo(
DataGridTableVirtualBody,
(_prev, next) => !!next.table.state.columnResizing.isResizingColumn || next.table._isSelectingCells === true,
) as typeof DataGridTableVirtualBody;
function DataGridTableVirtual<TData extends object>({
height,
estimateSize = 48,
overscan = 10,
scrollBehavior = 'auto',
scrollToRowAlign = 'auto',
scrollToRowIndex,
columnVirtualizerOptions,
scrollToColumnAlign = 'auto',
scrollToColumnIndex,
footerContent,
renderHeader = true,
onFetchMore,
isFetchingMore = false,
hasMore,
fetchMoreOffset = 0,
virtualizerOptions,
}: DataGridTableVirtualProps<TData>) {
const { i18n, table, props } = useDataGrid<TData>();
const mergedHeaderGroups = getDataGridTableMergedHeaderGroups(table);
const hasRightPinnedColumns = hasDataGridTableRightPinnedColumns(table);
const centerVisibleColumns = table.getCenterVisibleLeafColumns();
// Column windows only where the geometry is provable: a fixed table
// layout (undefined defaults to fixed; the colgroup then owns every
// width, so colSpan spacers cannot drift) and a single ungrouped header
// row (a colSpan group cannot be windowed). Anything else falls back to
// full-column rendering silently, the same posture as row virtualization
// toward unsupported shapes.
const columnVirtualizationActive =
columnVirtualizerOptions?.enabled === true &&
props.tableLayout?.width !== 'auto' &&
mergedHeaderGroups.length === 1 &&
(mergedHeaderGroups[0]?.headers.every((header) => header.colSpan <= 1) ?? false);
const { topRows, centerRows, bottomRows } = getDataGridTableRowSections(table, props.tableLayout?.rowsPinnable);
const isInfiniteMode = typeof onFetchMore === 'function';
const [viewportElements, setViewportElements] = useState<DataGridTableVirtualScrollElements>({
containerElement: null,
scrollElement: null,
});
const {
estimateSize: customEstimateSize,
getItemKey: customGetItemKey,
getScrollElement: customGetScrollElement,
measureElement: customMeasureElement,
overscan: customOverscan,
...virtualizerOptionsRest
} = virtualizerOptions ?? {};
const isVirtualizationEnabled = virtualizerOptions?.enabled !== false;
const loadingMoreMessage = props.fetchingMoreMessage || props.loadingMessage || i18n.labels.loading;
const allRowsLoadedMessage = props.allRowsLoadedMessage || i18n.labels.allRowsLoaded;
const handleViewportRef = useCallback((node: HTMLDivElement | null) => {
setViewportElements({
containerElement: node,
scrollElement: node ? (getDataGridScrollAreaViewport(node) ?? node) : null,
});
}, []);
const usesExternalScrollArea = viewportElements.scrollElement !== null && viewportElements.scrollElement !== viewportElements.containerElement;
const resolveScrollElement = useCallback(() => {
if (customGetScrollElement) {
return customGetScrollElement(viewportElements);
}
return viewportElements.scrollElement;
}, [customGetScrollElement, viewportElements]);
const resolveItemKey = useCallback(
(index: number) => {
const row = centerRows[index];
if (!row) return index;
return customGetItemKey?.(index, row) ?? row.id ?? index;
},
[centerRows, customGetItemKey],
);
const resolveEstimateSize = useCallback(
(index: number) => {
const row = centerRows[index];
return row ? (customEstimateSize?.(index, row) ?? estimateSize) : estimateSize;
},
[centerRows, customEstimateSize, estimateSize],
);
const virtualizer = useVirtualizer({
count: centerRows.length,
getScrollElement: resolveScrollElement,
getItemKey: resolveItemKey,
estimateSize: resolveEstimateSize,
overscan: customOverscan ?? overscan,
measureElement: customMeasureElement,
...virtualizerOptionsRest,
}) as DataGridTableVirtualizerInstance;
// Horizontal offsets invert in RTL; the virtualizer must be told.
const isRtl = useMemo(
() => (viewportElements.containerElement ? getComputedStyle(viewportElements.containerElement).direction === 'rtl' : false),
[viewportElements.containerElement],
);
const resolveColumnKey = useCallback((index: number) => centerVisibleColumns[index]?.id ?? index, [centerVisibleColumns]);
const resolveColumnEstimateSize = useCallback((index: number) => centerVisibleColumns[index]?.getSize() ?? 0, [centerVisibleColumns]);
const columnVirtualizer = useVirtualizer({
horizontal: true,
isRtl,
count: columnVirtualizationActive ? centerVisibleColumns.length : 0,
getScrollElement: resolveScrollElement,
getItemKey: resolveColumnKey,
estimateSize: resolveColumnEstimateSize,
overscan: columnVirtualizerOptions?.overscan ?? 3,
});
// Column sizes are exact reads of getSize(), never DOM-measured, so a
// resize commit or a visibility/order/pinning change must resync the
// virtualizer's cached sizes by hand.
useEffect(() => {
if (columnVirtualizationActive) columnVirtualizer.measure();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
columnVirtualizationActive,
columnVirtualizer,
// eslint-disable-next-line react-hooks/exhaustive-deps
table.state.columnSizing,
// eslint-disable-next-line react-hooks/exhaustive-deps
table.state.columnVisibility,
// eslint-disable-next-line react-hooks/exhaustive-deps
table.state.columnOrder,
// eslint-disable-next-line react-hooks/exhaustive-deps
table.state.columnPinning,
]);
const virtualColumns = columnVirtualizationActive ? columnVirtualizer.getVirtualItems() : [];
// The window is a contiguous inclusive [start, end] over the center
// columns; before the scroll element resolves the item list is empty and
// the grid renders full-width for that first frame.
const centerColumnWindow =
columnVirtualizationActive && virtualColumns.length > 0
? {
start: virtualColumns[0]!.index,
end: virtualColumns[virtualColumns.length - 1]!.index,
}
: undefined;
const virtualItems = isVirtualizationEnabled ? virtualizer.getVirtualItems() : [];
const totalSize = isVirtualizationEnabled ? virtualizer.getTotalSize() : 0;
const measureRowRef = isVirtualizationEnabled && customMeasureElement ? virtualizer.measureElement : undefined;
const resolvedFetchMoreOffset = Math.max(0, fetchMoreOffset);
const scrollToRowId = scrollToRowIndex !== undefined ? centerRows[scrollToRowIndex]?.id : undefined;
const scrollToRowVirtualItem =
isVirtualizationEnabled && scrollToRowIndex !== undefined ? virtualItems.find((item) => item.index === scrollToRowIndex) : undefined;
const pendingScrollToRowIndexRef = useRef<number | null>(null);
const lastScrollRequestRef = useRef<DataGridTableVirtualScrollRequest | null>(null);
// Latch onFetchMore per row count: virtualItems gets a new identity every
// scroll frame, so without it the effect fires duplicate page requests
// before the consumer flips isFetchingMore, and loops at end-of-data when
// hasMore is never set.
const fetchMoreFiredAtCountRef = useRef<number | null>(null);
const lastColumnScrollRequestRef = useRef<DataGridTableColumnScrollRequest | null>(null);
// Controlled column reveal: same dedupe posture as the row request - the
// signature keeps ordinary renders from re-scrolling, and exact column
// sizes mean no post-measure follow-up pass is needed.
useEffect(() => {
if (
!columnVirtualizationActive ||
scrollToColumnIndex === undefined ||
scrollToColumnIndex < 0 ||
scrollToColumnIndex >= centerVisibleColumns.length ||
!viewportElements.scrollElement
) {
return;
}
const request: DataGridTableColumnScrollRequest = {
align: scrollToColumnAlign,
behavior: scrollBehavior,
columnId: centerVisibleColumns[scrollToColumnIndex]?.id,
columnIndex: scrollToColumnIndex,
scrollElement: viewportElements.scrollElement,
};
if (isSameDataGridTableColumnScrollRequest(lastColumnScrollRequestRef.current, request)) {
return;
}
lastColumnScrollRequestRef.current = request;
columnVirtualizer.scrollToIndex(scrollToColumnIndex, {
align: scrollToColumnAlign,
behavior: scrollBehavior === 'smooth' ? 'smooth' : 'auto',
});
}, [
columnVirtualizationActive,
columnVirtualizer,
centerVisibleColumns,
scrollToColumnAlign,
scrollToColumnIndex,
scrollBehavior,
viewportElements.scrollElement,
]);
// Resolve after every commit so a stable getter can expose a replaced ref;
// the request signature prevents duplicate scrolling on ordinary renders.
useEffect(() => {
const previousRequest = lastScrollRequestRef.current;
if (scrollToRowIndex === undefined || scrollToRowIndex < 0 || scrollToRowIndex >= centerRows.length) {
pendingScrollToRowIndexRef.current = null;
lastScrollRequestRef.current = null;
if (previousRequest) {
const scrollElement = resolveScrollElement();
if (scrollElement) {
scrollDataGridTableToOffset({
behavior: 'auto',
scrollElement,
targetTop: scrollElement.scrollTop,
virtualizer: isVirtualizationEnabled ? virtualizer : undefined,
});
}
}
return;
}
const scrollElement = resolveScrollElement();
const containerElement = viewportElements.containerElement;
if (!containerElement || !scrollElement) return;
const headerSticky = renderHeader && !!props.tableLayout?.headerSticky;
const nextRequest: DataGridTableVirtualScrollRequest = {
align: scrollToRowAlign,
behavior: scrollBehavior,
containerElement,
headerSticky,
isVirtualizationEnabled,
rowId: scrollToRowId,
rowIndex: scrollToRowIndex,
scrollElement,
};
if (isSameDataGridTableScrollRequest(previousRequest, nextRequest)) return;
pendingScrollToRowIndexRef.current = null;
const rowWasHandled = scrollDataGridTableRowIntoView({
align: scrollToRowAlign,
behavior: scrollBehavior,
cancelPendingScroll: previousRequest !== null,
containerElement,
headerSticky,
rowIndex: scrollToRowIndex,
scrollElement,
virtualizer: isVirtualizationEnabled ? virtualizer : undefined,
});
if (rowWasHandled) {
lastScrollRequestRef.current = nextRequest;
return;
}
if (!isVirtualizationEnabled) return;
pendingScrollToRowIndexRef.current = scrollToRowIndex;
lastScrollRequestRef.current = nextRequest;
virtualizer.scrollToIndex(scrollToRowIndex, {
align: scrollToRowAlign,
behavior: scrollBehavior,
});
});
useEffect(() => {
if (
!isVirtualizationEnabled ||
scrollToRowIndex === undefined ||
pendingScrollToRowIndexRef.current !== scrollToRowIndex ||
!scrollToRowVirtualItem
) {
return;
}
const rowWasHandled = scrollDataGridTableRowIntoView({
align: scrollToRowAlign,
behavior: 'auto',
cancelPendingScroll: true,
containerElement: viewportElements.containerElement,
headerSticky: renderHeader && !!props.tableLayout?.headerSticky,
rowIndex: scrollToRowIndex,
scrollElement: resolveScrollElement(),
virtualizer,
});
if (rowWasHandled) {
pendingScrollToRowIndexRef.current = null;
}
}, [
isVirtualizationEnabled,
props.tableLayout?.headerSticky,
renderHeader,
resolveScrollElement,
scrollToRowAlign,
scrollToRowIndex,
scrollToRowVirtualItem,
virtualizer,
viewportElements.containerElement,
]);
useEffect(() => {
if (!isVirtualizationEnabled || !isInfiniteMode || hasMore === false || isFetchingMore) {
return;
}
const lastItem = virtualItems[virtualItems.length - 1];
if (!lastItem) return;
if (fetchMoreFiredAtCountRef.current === centerRows.length) return;
if (lastItem.index >= centerRows.length - 1 - resolvedFetchMoreOffset) {
fetchMoreFiredAtCountRef.current = centerRows.length;
onFetchMore?.();
}
}, [centerRows.length, hasMore, isFetchingMore, isInfiniteMode, isVirtualizationEnabled, onFetchMore, resolvedFetchMoreOffset, virtualItems]);
// The header re-renders only when its real inputs move: the table
// wrapper (any table state change recreates it), the layout props, and
// the column window. A scroll frame changes none of them, so the whole
// sortable-header subtree is reused instead of rebuilt per frame.
// eslint-disable-next-line react-hooks/exhaustive-deps
const headerNode = useMemo(
() =>
renderHeader && (
<DataGridTableHead>
{mergedHeaderGroups.map((headerGroup) => (
<DataGridTableHeadRow key={headerGroup.id} rowId={headerGroup.id}>
{/* Under an active column window the single ungrouped header
row is bucketed start / windowed center / end, with each
off-window flank one colSpan spacer sized by the intact
colgroup - the same shape the body rows take. */}
{centerColumnWindow
? headerGroup.headers
.filter((header) => header.column.getIsPinned() === 'start')
.map((header) => (
<DataGridTableHeadRowCell header={header} key={header.id}>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
{props.tableLayout?.columnsResizable && header.column.getCanResize() && <DataGridTableHeadRowCellResize header={header} />}
</DataGridTableHeadRowCell>
))
: null}
{centerColumnWindow && centerColumnWindow.start > 0 ? (
<th aria-hidden="true" data-slot="data-grid-table-virtual-col-spacer" colSpan={centerColumnWindow.start} className="p-0" />
) : null}
{centerColumnWindow
? headerGroup.headers
.filter((header) => !header.column.getIsPinned())
.slice(centerColumnWindow.start, centerColumnWindow.end + 1)
.map((header) => (
<DataGridTableHeadRowCell header={header} key={header.id}>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
{props.tableLayout?.columnsResizable && header.column.getCanResize() && <DataGridTableHeadRowCellResize header={header} />}
</DataGridTableHeadRowCell>
))
: null}
{centerColumnWindow && centerVisibleColumns.length - 1 - centerColumnWindow.end > 0 ? (
<th
aria-hidden="true"
data-slot="data-grid-table-virtual-col-spacer"
colSpan={centerVisibleColumns.length - 1 - centerColumnWindow.end}
className="p-0"
/>
) : null}
{!centerColumnWindow &&
headerGroup.headers
.filter((header) => header.column.getIsPinned() !== 'end')
.map((header) => {
const { column } = header;
return (
<DataGridTableHeadRowCell header={header} key={header.id}>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
{props.tableLayout?.columnsResizable && column.getCanResize() && <DataGridTableHeadRowCellResize header={header} />}
</DataGridTableHeadRowCell>
);
})}
{props.tableLayout?.columnsResizable && hasRightPinnedColumns ? <DataGridTableFillHeadCell /> : null}
{headerGroup.headers
.filter((header) => header.column.getIsPinned() === 'end')
.map((header) => {
const { column } = header;
return (
<DataGridTableHeadRowCell header={header} key={header.id}>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
{props.tableLayout?.columnsResizable && column.getCanResize() && <DataGridTableHeadRowCellResize header={header} />}
</DataGridTableHeadRowCell>
);
})}
{props.tableLayout?.columnsResizable && !hasRightPinnedColumns ? <DataGridTableFillHeadCell /> : null}
</DataGridTableHeadRow>
))}
</DataGridTableHead>
),
// eslint-disable-next-line react-hooks/exhaustive-deps
[renderHeader, table, props.tableLayout, centerColumnWindow, hasRightPinnedColumns],
);
return (
<DataGridTableViewport
viewportRef={handleViewportRef}
className={!usesExternalScrollArea ? 'block' : undefined}
style={
usesExternalScrollArea
? undefined
: {
height,
overflow: 'auto',
position: 'relative',
// Standalone mode: this node IS the scroll container, so it
// must stay at its parent's width (not the resizable table
// width) or horizontal scrolling becomes impossible.
width: 'auto',
}
}
>
<DataGridTableBase>
{headerNode}
{renderHeader && (props.tableLayout?.stripped || !props.tableLayout?.rowBorder) && <DataGridTableRowSpacer />}
<DataGridTableBody>
<MemoizedVirtualBody
table={table}
topRows={topRows}
centerRows={centerRows}
bottomRows={bottomRows}
virtualItems={virtualItems}
totalSize={totalSize}
isVirtualizationEnabled={isVirtualizationEnabled}
isInfiniteMode={isInfiniteMode}
isFetchingMore={isFetchingMore}
hasMore={hasMore}
loadingMoreMessage={loadingMoreMessage}
allRowsLoadedMessage={allRowsLoadedMessage}
measureRowRef={measureRowRef}
centerColumnWindow={centerColumnWindow}
/>
{/* Same appended region as the standard body, so onRowCreate and
a consumer draft work in the virtual layout too. */}
{props.appendRow}
<DataGridTableAddRow />
</DataGridTableBody>
{footerContent && <DataGridTableFoot>{footerContent}</DataGridTableFoot>}
</DataGridTableBase>
</DataGridTableViewport>
);
}
export { DataGridTableVirtual };
export type { DataGridTableVirtualScrollAlignment, DataGridTableVirtualProps, DataGridTableVirtualScrollElements, DataGridTableVirtualizerOptions };components/ui/data-grid/data-grid-table.tsx
import { Fragment, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react';
import type { CSSProperties, MouseEvent as ReactMouseEvent, ReactNode, TouchEvent as ReactTouchEvent, Ref, RefObject } from 'react';
import {
dataGridCellSelectionCellClasses,
getDataGridCellSelectionCellAttrs,
toDataGridDomId,
useDataGrid,
} from '@/registry/vcare/ui/data-grid/data-grid';
import type { DataGridFeatures, DataGridTableInstance } from '@/registry/vcare/ui/data-grid/data-grid';
import { flexRender, Subscribe } from '@tanstack/react-table';
import type { Cell, Column, Header, Row, Table } from '@tanstack/react-table';
import { cn } from '@/registry/vcare/lib/utils';
import { Button } from '@/registry/vcare/ui/button';
import { Checkbox } from '@/registry/vcare/ui/checkbox';
import { Spinner } from '@/registry/vcare/ui/spinner';
import { PlusIcon } from 'lucide-react';
// Static spacing lookups; called once per cell, so they stay plain string
// picks instead of runtime variant machinery.
const headerCellSpacingVariants = ({ size }: { size?: 'dense' | 'default' }) => (size === 'dense' ? 'px-2 h-8' : 'px-3');
const bodyCellSpacingVariants = ({ size }: { size?: 'dense' | 'default' }) => (size === 'dense' ? 'px-2 py-1.5' : 'px-3 py-2');
// The truncation wrapper used when cell selection is on: it consumes the
// td padding with negative margins and restores it as its own, so its
// overflow clips at exactly the boundary the td's `truncate` used to clip
// at - including custom cells that pull into the padding the same way.
const bodyCellTruncateWrapVariants = ({ size }: { size?: 'dense' | 'default' }) =>
size === 'dense' ? '-mx-2 -my-1.5 truncate px-2 py-1.5' : '-mx-3 -my-2 truncate px-3 py-2';
const footerCellSpacingVariants = ({ size }: { size?: 'dense' | 'default' }) => (size === 'dense' ? 'px-2 py-1.5' : 'px-3 py-2');
function getPinningStyles<TData extends object>(column: Column<DataGridFeatures, TData, unknown>): CSSProperties {
const isPinned = column.getIsPinned();
return {
// Logical offsets: TanStack's "left"/"right" buckets are start/end
// semantics, so pinned columns stick to the correct edge in RTL too
// (identical to left/right in LTR).
insetInlineStart: isPinned === 'start' ? `${column.getStart('start')}px` : undefined,
insetInlineEnd: isPinned === 'end' ? `${column.getAfter('end')}px` : undefined,
position: isPinned ? 'sticky' : undefined,
transform: isPinned ? 'translateZ(0)' : undefined,
contain: isPinned ? 'paint' : undefined,
width: column.getSize(),
zIndex: isPinned ? 30 : undefined,
backgroundClip: isPinned ? 'padding-box' : undefined,
};
}
// Shared indent contract for tree rows: DataGridTableRowExpand consumes it,
// and fully custom cells can reuse it for depth alignment without the
// built-in toggle.
function getDataGridTreeIndentStyle<TData extends object>(row: Row<DataGridFeatures, TData>, indent: number = 20): CSSProperties {
return {
'--data-grid-tree-padding': `${row.depth * indent}px`,
} as CSSProperties;
}
function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {
if (!ref) return;
if (typeof ref === 'function') {
ref(value);
return;
}
(ref as { current: T | null }).current = value;
}
/**
* Nearest scroll-area viewport that belongs to THIS grid. A viewport outside
* the grid's own container (e.g. a page-level ScrollArea) would make the
* width measurement - and the virtualizer - bind the wrong box.
*/
function getDataGridScrollAreaViewport(node: HTMLElement): HTMLElement | null {
const scrollViewport = node.closest('[data-slot="scroll-area-viewport"]') as HTMLElement | null;
if (!scrollViewport) return null;
const gridContainer = node.closest('[data-slot="data-grid"]');
if (gridContainer && !gridContainer.contains(scrollViewport)) return null;
return scrollViewport;
}
type DataGridResizeStartEvent = ReactMouseEvent<HTMLElement> | ReactTouchEvent<HTMLElement>;
type DataGridResizeDocumentEvent = globalThis.MouseEvent | globalThis.TouchEvent;
function isDataGridTouchEvent(
event: DataGridResizeStartEvent | DataGridResizeDocumentEvent,
): event is ReactTouchEvent<HTMLElement> | globalThis.TouchEvent {
return 'touches' in event;
}
type DataGridTouchListLike = {
length: number;
item: (index: number) => { identifier: number; clientX: number } | null;
};
function findTouchClientX(list: DataGridTouchListLike, identifier: number) {
for (let i = 0; i < list.length; i++) {
const touch = list.item(i);
if (touch && touch.identifier === identifier) return touch.clientX;
}
return undefined;
}
function getDataGridResizeEventClientX(event: DataGridResizeStartEvent | DataGridResizeDocumentEvent, touchIdentifier?: number) {
if (isDataGridTouchEvent(event)) {
if (typeof touchIdentifier === 'number') {
return findTouchClientX(event.touches, touchIdentifier) ?? findTouchClientX(event.changedTouches, touchIdentifier);
}
return event.touches[0]?.clientX ?? event.changedTouches[0]?.clientX;
}
return event.clientX;
}
function startDataGridColumnResizeOnEnd<TData extends object>(
event: DataGridResizeStartEvent,
header: Header<DataGridFeatures, TData, unknown>,
table: DataGridTableInstance<TData>,
/**
* Live mode: per-move width updates go straight to the table element's
* `--col/--header` variables, so cells track the pointer with ZERO React
* renders; state is written twice per drag (start marker, release commit)
* instead of per mousemove - which re-renders the consumer's whole tree.
*/
live = false,
): (() => void) | undefined {
const column = table.getColumn(header.column.id);
if (!column || !column.getCanResize()) return;
const isTouchSession = isDataGridTouchEvent(event);
if (isTouchSession && event.touches.length > 1) return;
event.persist?.();
const ownerDocument = event.currentTarget.ownerDocument;
const ownerWindow = ownerDocument.defaultView;
const previousBodyCursor = ownerDocument.body.style.cursor;
const previousDocumentCursor = ownerDocument.documentElement.style.cursor;
const startSize = header.getSize();
// Track the initiating finger so a second touch cannot move or commit the
// resize with the wrong clientX.
const touchIdentifier = isTouchSession ? event.touches[0]?.identifier : undefined;
const dragStartClientX = getDataGridResizeEventClientX(event, touchIdentifier);
const headerCell = event.currentTarget.closest('th');
const headerRect = headerCell?.getBoundingClientRect();
const liveTableElement = live ? headerCell?.closest('table') : null;
// An end-pinned column is anchored at its end edge and grows from its
// START edge, so its whole resize geometry runs mirrored, exactly like
// RTL: the anchor is the opposite edge and the drag direction inverts.
const resizeRtl = (table.options.columnResizeDirection === 'rtl') !== (column.getIsPinned() === 'end');
const startOffset =
headerRect && Number.isFinite(resizeRtl ? headerRect.left : headerRect.right)
? resizeRtl
? headerRect.left
: headerRect.right
: dragStartClientX;
if (typeof dragStartClientX !== 'number' || typeof startOffset !== 'number') {
return;
}
ownerDocument.body.style.cursor = 'col-resize';
ownerDocument.documentElement.style.cursor = 'col-resize';
const columnSizingStart = header.getLeafHeaders().map((leafHeader) => [leafHeader.column.id, leafHeader.column.getSize()] as [string, number]);
const directionMultiplier = resizeRtl ? -1 : 1;
// Clamp the drag to the leaf columns' min/max sizes so the preview
// indicator matches what the commit will produce (no overshoot followed by
// a snap-back on release). columnDef always carries resolved defaults.
let minDeltaPercentage = -0.999999;
let maxDeltaPercentage = Number.POSITIVE_INFINITY;
columnSizingStart.forEach(([columnId, headerSize]) => {
if (headerSize <= 0) return;
const leafColumn = table.getColumn(columnId);
const minSize = leafColumn?.columnDef.minSize;
const maxSize = leafColumn?.columnDef.maxSize;
if (typeof minSize === 'number') {
minDeltaPercentage = Math.max(minDeltaPercentage, minSize / headerSize - 1);
}
if (typeof maxSize === 'number' && Number.isFinite(maxSize)) {
maxDeltaPercentage = Math.min(maxDeltaPercentage, maxSize / headerSize - 1);
}
});
let lastClientX = dragStartClientX;
let ended = false;
const stopListeners: Array<() => void> = [];
const updateOffset = (clientXPos?: number, commit = false) => {
if (typeof clientXPos !== 'number') return;
lastClientX = clientXPos;
const nextColumnSizing: Record<string, number> = {};
const deltaPercentage = Math.min(
Math.max(((clientXPos - dragStartClientX) * directionMultiplier) / startSize, minDeltaPercentage),
maxDeltaPercentage,
);
const deltaOffset = deltaPercentage * startSize;
columnSizingStart.forEach(([columnId, headerSize]) => {
nextColumnSizing[columnId] = Math.round(Math.max(headerSize + headerSize * deltaPercentage, 0) * 100) / 100;
});
if (liveTableElement) {
columnSizingStart.forEach(([columnId]) => {
const nextSize = nextColumnSizing[columnId];
if (typeof nextSize !== 'number') return;
liveTableElement.style.setProperty(`--col-${columnId}-size`, String(nextSize));
liveTableElement.style.setProperty(`--header-${columnId}-size`, String(nextSize));
});
} else {
table.setColumnResizing((old) => ({
...old,
startOffset,
startSize,
deltaOffset,
deltaPercentage,
columnSizingStart,
isResizingColumn: column.id,
}));
}
if (commit) {
table.setColumnSizing((old) => ({
...old,
...nextColumnSizing,
}));
}
};
// Single teardown path: commits at the given position, removes every
// document/window listener, and restores cursors. Safe to call more than
// once (blur + mouseup + unmount can race).
const endResize = (clientXPos?: number) => {
if (ended) return;
ended = true;
stopListeners.forEach((stop) => stop());
updateOffset(clientXPos, true);
table.setColumnResizing((old) => ({
...old,
isResizingColumn: false,
startOffset: null,
startSize: null,
deltaOffset: null,
deltaPercentage: null,
columnSizingStart: [],
}));
ownerDocument.body.style.cursor = previousBodyCursor;
ownerDocument.documentElement.style.cursor = previousDocumentCursor;
};
const mouseMoveHandler = (moveEvent: globalThis.MouseEvent) => {
updateOffset(moveEvent.clientX);
};
const mouseUpHandler = (upEvent: globalThis.MouseEvent) => {
endResize(upEvent.clientX);
};
const touchMoveHandler = (moveEvent: globalThis.TouchEvent) => {
if (moveEvent.cancelable) {
moveEvent.preventDefault();
moveEvent.stopPropagation();
}
updateOffset(getDataGridResizeEventClientX(moveEvent, touchIdentifier));
};
const touchEndHandler = (endEvent: globalThis.TouchEvent) => {
// Ignore other fingers lifting; only the initiating touch ends the drag.
const clientXPos =
typeof touchIdentifier === 'number' ? findTouchClientX(endEvent.changedTouches, touchIdentifier) : getDataGridResizeEventClientX(endEvent);
if (typeof clientXPos !== 'number') return;
if (endEvent.cancelable) {
endEvent.preventDefault();
endEvent.stopPropagation();
}
endResize(clientXPos);
};
// System-interrupted gestures and window focus loss would otherwise leave
// the session (and its document listeners) live with no pointer held.
const touchCancelHandler = () => {
endResize(lastClientX);
};
const windowBlurHandler = () => {
endResize(lastClientX);
};
const passiveIfSupported = { passive: false } as const;
if (isTouchSession) {
ownerDocument.addEventListener('touchmove', touchMoveHandler, passiveIfSupported);
ownerDocument.addEventListener('touchend', touchEndHandler, passiveIfSupported);
ownerDocument.addEventListener('touchcancel', touchCancelHandler);
stopListeners.push(() => {
ownerDocument.removeEventListener('touchmove', touchMoveHandler);
ownerDocument.removeEventListener('touchend', touchEndHandler);
ownerDocument.removeEventListener('touchcancel', touchCancelHandler);
});
} else {
ownerDocument.addEventListener('mousemove', mouseMoveHandler, passiveIfSupported);
ownerDocument.addEventListener('mouseup', mouseUpHandler, passiveIfSupported);
stopListeners.push(() => {
ownerDocument.removeEventListener('mousemove', mouseMoveHandler);
ownerDocument.removeEventListener('mouseup', mouseUpHandler);
});
}
if (ownerWindow) {
ownerWindow.addEventListener('blur', windowBlurHandler);
stopListeners.push(() => ownerWindow.removeEventListener('blur', windowBlurHandler));
}
table.setColumnResizing((old) => ({
...old,
startOffset,
startSize,
deltaOffset: 0,
deltaPercentage: 0,
columnSizingStart,
isResizingColumn: column.id,
}));
return () => endResize(lastClientX);
}
type DataGridTablePinnedBoundary = 'top' | 'bottom';
function getDataGridTableRowSections<TData extends object>(table: DataGridTableInstance<TData>, rowsPinnable?: boolean) {
if (!rowsPinnable) {
return {
topRows: [] as Row<DataGridFeatures, TData>[],
centerRows: table.getRowModel().rows as Row<DataGridFeatures, TData>[],
bottomRows: [] as Row<DataGridFeatures, TData>[],
};
}
return {
topRows: table.getTopRows() as Row<DataGridFeatures, TData>[],
centerRows: table.getCenterRows() as Row<DataGridFeatures, TData>[],
bottomRows: table.getBottomRows() as Row<DataGridFeatures, TData>[],
};
}
function getDataGridTableResolvedRows<TData extends object>(table: DataGridTableInstance<TData>, rowsPinnable?: boolean) {
const { topRows, centerRows, bottomRows } = getDataGridTableRowSections(table, rowsPinnable);
const resolvedRows: Array<{
row: Row<DataGridFeatures, TData>;
pinnedBoundary?: DataGridTablePinnedBoundary;
}> = [];
topRows.forEach((row, index) => {
resolvedRows.push({
row,
pinnedBoundary: index === topRows.length - 1 && (centerRows.length > 0 || bottomRows.length > 0) ? 'top' : undefined,
});
});
centerRows.forEach((row) => {
resolvedRows.push({ row });
});
bottomRows.forEach((row, index) => {
resolvedRows.push({
row,
pinnedBoundary: index === 0 && (centerRows.length > 0 || topRows.length > 0) ? 'bottom' : undefined,
});
});
return resolvedRows;
}
function getDataGridTableOrderedVisibleColumns<TData extends object>(table: DataGridTableInstance<TData>) {
return [...table.getStartVisibleLeafColumns(), ...table.getCenterVisibleLeafColumns(), ...table.getEndVisibleLeafColumns()] as Column<
DataGridFeatures,
TData,
unknown
>[];
}
function getDataGridTableOrderedVisibleCells<TData extends object>(row: Row<DataGridFeatures, TData>) {
return [...row.getStartVisibleCells(), ...row.getCenterVisibleCells(), ...row.getEndVisibleCells()] as Cell<DataGridFeatures, TData, unknown>[];
}
function getDataGridTableMergedHeaderGroups<TData extends object>(table: DataGridTableInstance<TData>) {
const leftHeaderGroups = table.getStartHeaderGroups();
const centerHeaderGroups = table.getCenterHeaderGroups();
const rightHeaderGroups = table.getEndHeaderGroups();
const headerGroupCount = Math.max(leftHeaderGroups.length, centerHeaderGroups.length, rightHeaderGroups.length);
return Array.from({ length: headerGroupCount }, (_, index) => {
const leftGroup = leftHeaderGroups[index];
const centerGroup = centerHeaderGroups[index];
const rightGroup = rightHeaderGroups[index];
return {
id: [leftGroup?.id, centerGroup?.id, rightGroup?.id].filter(Boolean).join(':') || `header-group-${index}`,
headers: [...(leftGroup?.headers ?? []), ...(centerGroup?.headers ?? []), ...(rightGroup?.headers ?? [])] as Header<
DataGridFeatures,
TData,
unknown
>[],
};
});
}
function hasDataGridTableRightPinnedColumns<TData extends object>(table: DataGridTableInstance<TData>) {
return (table.state.columnPinning.end?.length ?? 0) > 0;
}
// A meta.fillWidth column absorbs the free space itself, so the fill cells
// must collapse or the strip would be counted twice.
function hasDataGridFillColumn<TData extends object>(table: DataGridTableInstance<TData>) {
return table.getVisibleLeafColumns().some((column) => column.columnDef.meta?.fillWidth);
}
function DataGridTableFillCol() {
const { props, table } = useDataGrid();
if (!props.tableLayout?.columnsResizable) return null;
return (
<col
data-slot="data-grid-table-fill-col"
style={{
width: hasDataGridFillColumn(table) ? 0 : 'var(--data-grid-fill-size, 0px)',
}}
/>
);
}
function DataGridTableFillHeadCell() {
const { props, table } = useDataGrid();
if (!props.tableLayout?.columnsResizable) return null;
return (
<th
aria-hidden="true"
data-slot="data-grid-table-fill-head-cell"
style={{
width: hasDataGridFillColumn(table) ? 0 : 'var(--data-grid-fill-size, 0px)',
}}
className={cn('p-0', props.tableLayout?.headerBackground && 'bg-muted')}
/>
);
}
function DataGridTableFillBodyCell() {
const { props, table } = useDataGrid();
if (!props.tableLayout?.columnsResizable) return null;
return (
<td
aria-hidden="true"
data-slot="data-grid-table-fill-body-cell"
style={{
width: hasDataGridFillColumn(table) ? 0 : 'var(--data-grid-fill-size, 0px)',
}}
className="p-0"
/>
);
}
function DataGridTableFillFootCell() {
const { props, table } = useDataGrid();
if (!props.tableLayout?.columnsResizable) return null;
return (
<td
aria-hidden="true"
data-slot="data-grid-table-fill-foot-cell"
style={{
width: hasDataGridFillColumn(table) ? 0 : 'var(--data-grid-fill-size, 0px)',
}}
className="p-0"
/>
);
}
/**
* The quick-create affordance, rendered as the body's last row when
* `onRowCreate` is set: one full-width ghost button, the Notion/Airtable
* "+ New" idiom. What the click creates stays consumer-owned.
*/
function DataGridTableAddRow() {
const { i18n, props, table } = useDataGrid();
if (!props.onRowCreate) return null;
return (
<tr
data-slot="data-grid-table-add-row"
className={cn('hover:bg-muted/40 [thead+tbody_&:first-child]:border-t', props.tableClassNames?.rowCreate)}
>
<td
// The extra column is the filler strip, rendered only when columns
// are resizable.
colSpan={table.getVisibleLeafColumns().length + (props.tableLayout?.columnsResizable ? 1 : 0)}
className="p-0"
>
<Button
type="button"
variant="ghost"
size="sm"
// Block-level flex: inline-flex would sit on the cell's text
// baseline and push the icon and label off vertical center.
className={cn(
'text-muted-foreground flex w-full items-center justify-start rounded-none px-3',
props.tableLayout?.dense ? 'h-8 px-2' : 'h-9',
)}
onClick={(event) => {
// Creating often unmounts this affordance (a draft row takes
// its place); focus would fall to the body and strand the
// keyboard. Hand it to the grid's focus target instead - but
// only when it was actually lost, so a consumer that keeps
// the button mounted keeps repeated Enter presses working.
// A timer, not rAF: timers also run in background tabs.
const button = event.currentTarget;
const grid = button.closest('table');
props.onRowCreate?.();
setTimeout(() => {
if (
!button.isConnected &&
grid?.isConnected &&
grid.tabIndex >= 0 &&
(document.activeElement === document.body || !document.activeElement)
) {
grid.focus();
}
}, 0);
}}
>
<PlusIcon className="size-4" aria-hidden="true" />
{props.rowCreateLabel ?? i18n.labels.rowCreate}
</Button>
</td>
</tr>
);
}
function DataGridTableBase({ children }: { children: ReactNode }) {
const { props, table, recordCount } = useDataGrid();
const leftVisibleColumns = table.getStartVisibleLeafColumns();
const centerVisibleColumns = table.getCenterVisibleLeafColumns();
const rightVisibleColumns = table.getEndVisibleLeafColumns();
const hasRightPinnedColumns = hasDataGridTableRightPinnedColumns(table);
/**
* Compute column widths as CSS custom properties once upfront (memoized).
* Cells reference these via calc(var(--col-X-size) * 1px) so the browser
* handles width propagation without per-cell getSize() calls or React
* re-renders of the body.
*/
const columnSizeVars = useMemo(() => {
if (!props.tableLayout?.columnsResizable) return undefined;
const headers = table.getFlatHeaders();
// A meta.fillWidth column absorbs the filler strip: its size variable
// carries the unitless fill amount, so every consumer of
// calc(var(--col-X-size) * 1px) stretches with the container while the
// fill cells collapse to zero.
const fillColumnId = table.getVisibleLeafColumns().find((column) => column.columnDef.meta?.fillWidth)?.id;
const colSizes: Record<string, number | string> = {};
for (let i = 0; i < headers.length; i++) {
const header = headers[i]!;
colSizes[`--header-${header.id}-size`] = header.getSize();
colSizes[`--col-${header.column.id}-size`] =
header.column.id === fillColumnId ? `calc(${header.column.getSize()} + var(--data-grid-fill, 0))` : header.column.getSize();
}
return colSizes;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
props.tableLayout?.columnsResizable,
// Visibility/order/pinning change the flat header set, so a column shown
// after mount must get its size variable even though sizing is untouched.
// eslint-disable-next-line react-hooks/exhaustive-deps
table.state.columnSizing,
// eslint-disable-next-line react-hooks/exhaustive-deps
table.state.columnVisibility,
// eslint-disable-next-line react-hooks/exhaustive-deps
table.state.columnOrder,
// eslint-disable-next-line react-hooks/exhaustive-deps
table.state.columnPinning,
// A def swap can change a column's `size` without touching sizing
// STATE; without this dep the CSS variables keep the old widths. For a
// consumer defining columns inline the memo degrades to per-render
// recompute, which is the safe direction.
// eslint-disable-next-line react-hooks/exhaustive-deps
table.options.columns,
]);
// With cell selection on, the table announces as a grid so the tds compute
// as gridcells and aria-selected applies; existing grids keep their plain
// semantic table untouched.
const cellSelectionOn = !!props.tableLayout?.cellSelection && table.atoms.cellSelection != null;
return (
<table
data-slot="data-grid-table"
role={cellSelectionOn ? 'grid' : undefined}
aria-multiselectable={cellSelectionOn && props.tableLayout?.cellSelectionMode !== 'single' ? true : undefined}
// recordCount can undercount the rows actually present (a pinned
// draft row a consumer keeps out of its totals), and aria-rowindex
// is computed from the full display order; the union keeps every
// announced index inside the announced count.
aria-rowcount={cellSelectionOn ? Math.max(recordCount, table.getRowsInDisplayOrder().length) + 1 : undefined}
className={cn(
'text-foreground caption-bottom text-left align-middle text-sm font-normal rtl:text-right',
props.tableLayout?.columnsResizable ? 'min-w-0' : 'w-full min-w-full',
props.tableLayout?.width === 'auto' ? 'table-auto' : 'table-fixed',
!props.tableLayout?.columnsResizable && '',
!props.tableLayout?.columnsDraggable && 'border-separate border-spacing-0',
props.tableClassNames?.base,
)}
style={
props.tableLayout?.columnsResizable
? {
...columnSizeVars,
width: `calc(${table.getTotalSize()}px + var(--data-grid-fill-size, 0px))`,
}
: undefined
}
>
<colgroup>
{[...leftVisibleColumns, ...centerVisibleColumns].map((column) => (
<col
key={column.id}
style={
props.tableLayout?.columnsResizable
? { width: `calc(var(--col-${column.id}-size) * 1px)` }
: props.tableLayout?.width === 'fixed'
? { width: column.getSize() }
: undefined
}
/>
))}
{hasRightPinnedColumns ? <DataGridTableFillCol /> : null}
{rightVisibleColumns.map((column) => (
<col
key={column.id}
style={
props.tableLayout?.columnsResizable
? { width: `calc(var(--col-${column.id}-size) * 1px)` }
: props.tableLayout?.width === 'fixed'
? { width: column.getSize() }
: undefined
}
/>
))}
{!hasRightPinnedColumns ? <DataGridTableFillCol /> : null}
</colgroup>
{children}
</table>
);
}
function DataGridTableViewport({
children,
className,
viewportRef,
style,
}: {
children: ReactNode;
className?: string;
viewportRef?: Ref<HTMLDivElement>;
style?: CSSProperties;
}) {
const { props, table, autoSize } = useDataGrid();
const isColumnsResizable = !!props.tableLayout?.columnsResizable;
const viewportNodeRef = useRef<HTMLDivElement | null>(null);
const fillStateRef = useRef({ containerWidth: 0, appliedFill: -1 });
const stopContainerObserverRef = useRef<(() => void) | null>(null);
// Free space is written as a CSS variable directly on the viewport node
// instead of React state, so container resizes and column-size commits
// reach the fill column without re-rendering the grid.
const syncFillWidth = useCallback(() => {
const node = viewportNodeRef.current;
if (!node) return;
const freeSpace = fillStateRef.current.containerWidth - table.getTotalSize();
const fillWidth = Math.max(0, freeSpace);
if (fillStateRef.current.appliedFill !== fillWidth) {
fillStateRef.current.appliedFill = fillWidth;
node.style.setProperty('--data-grid-fill-size', `${fillWidth}px`);
// Unitless twin for the meta.fillWidth column, whose size variable
// participates in a calc that multiplies by 1px afterwards.
node.style.setProperty('--data-grid-fill', String(fillWidth));
}
// Signed on purpose: a shrinking container drives the free space
// NEGATIVE, which is exactly what tells a meta.autoSize column to hand
// its absorbed width back.
autoSize?.apply(freeSpace);
}, [autoSize, table]);
const handleViewportRef = useCallback(
(node: HTMLDivElement | null) => {
stopContainerObserverRef.current?.();
stopContainerObserverRef.current = null;
viewportNodeRef.current = node;
assignRef(viewportRef, node);
if (!node) return;
if (!isColumnsResizable) {
fillStateRef.current.appliedFill = -1;
node.style.removeProperty('--data-grid-fill-size');
node.style.removeProperty('--data-grid-fill');
return;
}
const scrollViewport = getDataGridScrollAreaViewport(node) ?? node.parentElement;
const measurementTarget = scrollViewport ?? node;
const measure = () => {
fillStateRef.current.containerWidth = measurementTarget.clientWidth;
syncFillWidth();
};
// First measure runs inside the mount commit, before paint, so the fill
// column and any meta.autoSize growth land in the first painted frame.
measure();
if (typeof ResizeObserver !== 'undefined') {
const observer = new ResizeObserver(measure);
observer.observe(measurementTarget);
stopContainerObserverRef.current = () => observer.disconnect();
}
},
[isColumnsResizable, syncFillWidth, viewportRef],
);
// Column sizing commits and visibility changes alter the table's total size
// without moving the container, so the fill var must re-sync after renders
// the ResizeObserver never sees. No-ops when the value is unchanged.
useLayoutEffect(() => {
if (!isColumnsResizable) return;
syncFillWidth();
});
return (
<div
data-slot="data-grid-table-viewport"
ref={handleViewportRef}
className={cn('relative min-w-full align-top', className)}
style={{
...(isColumnsResizable
? {
width: `calc(${table.getTotalSize()}px + var(--data-grid-fill-size, 0px))`,
}
: undefined),
...style,
}}
>
{children}
<DataGridTableResizeIndicator viewportNodeRef={viewportNodeRef} />
</div>
);
}
function DataGridTableHead({ children }: { children: ReactNode }) {
const { props } = useDataGrid();
return (
<thead className={cn(props.tableClassNames?.header, props.tableLayout?.headerSticky && props.tableClassNames?.headerSticky)}>{children}</thead>
);
}
function DataGridTableHeadRow({ children, rowId }: { children: ReactNode; rowId: string }) {
const { props } = useDataGrid();
return (
<tr
aria-rowindex={props.tableLayout?.cellSelection ? 1 : undefined}
className={cn(
props.tableLayout?.headerBorder && '[&>th]:border-b',
props.tableLayout?.cellBorder && '*:last:border-e-0',
props.tableLayout?.stripped && 'bg-transparent',
props.tableLayout?.headerBackground === false && 'bg-transparent',
props.tableClassNames?.headerRow,
)}
>
{children}
</tr>
);
}
function DataGridTableHeadRowCell<TData extends object>({
children,
header,
dndRef,
dndStyle,
}: {
children: ReactNode;
header: Header<DataGridFeatures, TData, unknown>;
dndRef?: React.Ref<HTMLTableCellElement>;
dndStyle?: CSSProperties;
}) {
const { props, table } = useDataGrid();
const { column } = header;
const isPinned = column.getIsPinned();
const isFirstStartPinned = isPinned === 'start' && column.getIsFirstColumn('start');
const isLastStartPinned = isPinned === 'start' && column.getIsLastColumn('start');
const isFirstEndPinned = isPinned === 'end' && column.getIsFirstColumn('end');
const isLastEndPinned = isPinned === 'end' && column.getIsLastColumn('end');
const isLastVisibleColumn = column.getIndex() === header.getContext().table.getVisibleLeafColumns().length - 1;
const headerCellSpacing = headerCellSpacingVariants({
size: props.tableLayout?.dense ? 'dense' : 'default',
});
const sortDirection = column.getIsSorted();
return (
<th
ref={dndRef}
scope="col"
colSpan={header.colSpan > 1 ? header.colSpan : undefined}
aria-sort={sortDirection === 'asc' ? 'ascending' : sortDirection === 'desc' ? 'descending' : column.getCanSort() ? 'none' : undefined}
aria-colindex={props.tableLayout?.cellSelection ? column.getIndex() + 1 : undefined}
data-col-id={column.id}
style={{
...(props.tableLayout?.width === 'fixed' &&
!props.tableLayout?.columnsResizable && {
width: header.getSize(),
}),
...(props.tableLayout?.columnsPinnable && column.getCanPin() && getPinningStyles(column)),
// A sticky child does not ride a sticky ancestor: under a sticky
// header the pinned cell's own position:sticky (horizontal) opts it
// out of the thead's vertical stickiness, and the corner scrolls
// away while its non-positioned siblings stick. Pin both axes on
// the cell itself.
...(props.tableLayout?.headerSticky && isPinned && { top: 0 }),
...(props.tableLayout?.columnsResizable && {
width: `calc(var(--header-${header.id}-size) * 1px)`,
}),
...(dndStyle ? dndStyle : null),
}}
data-pinned={isPinned || undefined}
data-outer-pinned-col={isFirstStartPinned ? 'start' : isLastEndPinned ? 'end' : undefined}
data-last-col={isLastStartPinned ? 'start' : isFirstEndPinned ? 'end' : undefined}
className={cn(
'text-foreground relative h-10 text-left align-middle font-medium rtl:text-right [&:has([role=checkbox])]:pe-0',
headerCellSpacing,
props.tableLayout?.headerBackground && 'bg-muted',
props.tableLayout?.cellBorder && 'border-e',
// The resize filler column follows the center group, and a border on
// the last center cell would float against that empty strip.
props.tableLayout?.cellBorder &&
props.tableLayout?.columnsResizable &&
// With end-pinned columns but no pin affordance, the pinned edge
// draws no separator of its own; keep the border then.
(props.tableLayout?.columnsPinnable || !hasDataGridTableRightPinnedColumns(table)) &&
!isPinned &&
column.getIsLastColumn('center') &&
'border-e-0',
props.tableLayout?.columnsResizable && column.getCanResize() && (isPinned ? 'overflow-hidden' : 'overflow-visible'),
props.tableLayout?.columnsResizable && column.getCanResize() && isLastVisibleColumn && 'pe-8',
props.tableLayout?.columnsPinnable &&
column.getCanPin() &&
cn(
'data-pinned:bg-muted data-outer-pinned-col:bg-clip-padding data-pinned:isolate',
'[&[data-pinned=end]:last-child_div.cursor-col-resize:last-child]:opacity-0 [&[data-pinned=end][data-last-col=end]]:shadow-[inset_1px_0_0_0_var(--border)] [&[data-pinned=start][data-last-col=start]]:shadow-[inset_-1px_0_0_0_var(--border)]',
'[&:not([data-pinned]):has(+[data-pinned])_div.cursor-col-resize:last-child]:opacity-0 [&[data-last-col=start]_div.cursor-col-resize:last-child]:opacity-0',
),
header.column.columnDef.meta?.headerClassName,
// Edge detection spans the full visible leaf order; the header's own
// group only covers one pinning bucket.
column.getIndex() === 0 || isLastVisibleColumn ? props.tableClassNames?.edgeCell : '',
)}
>
{children}
</th>
);
}
/**
* TanStack's own default, restated here on purpose.
*
* v8 merged each feature's default table options into `table.options`, so
* reading `table.options.columnResizeMode` gave you `"onEnd"` even when the
* consumer never set it. v9 resolves feature defaults internally and leaves
* the option `undefined` on the instance, so the old `?? table.options...`
* fallback quietly produced `undefined` - and every grid that had not opted
* into a mode explicitly lost the onEnd drag session: no cursor lock, no
* vertical indicator, and an immediate commit instead of a deferred one.
*/
const DATA_GRID_DEFAULT_COLUMN_RESIZE_MODE = 'onEnd' as const;
function getDataGridColumnResizeMode(layoutMode: 'onChange' | 'onEnd' | undefined, tableMode: 'onChange' | 'onEnd' | undefined) {
return layoutMode ?? tableMode ?? DATA_GRID_DEFAULT_COLUMN_RESIZE_MODE;
}
function DataGridTableHeadRowCellResize<TData extends object>({ header }: { header: Header<DataGridFeatures, TData, unknown> }) {
const { props, table } = useDataGrid<TData>();
const { column } = header;
const isPinned = column.getIsPinned();
const isLastVisibleColumn = column.getIndex() === header.getContext().table.getVisibleLeafColumns().length - 1;
const isResizeModeOnEnd = getDataGridColumnResizeMode(props.tableLayout?.columnsResizeMode, table.options.columnResizeMode) === 'onEnd';
const stopResizeSessionRef = useRef<(() => void) | undefined>(undefined);
// End a live drag if the handle unmounts mid-resize so document listeners
// and the app-wide col-resize cursor don't outlive the grid.
useEffect(() => {
return () => {
stopResizeSessionRef.current?.();
stopResizeSessionRef.current = undefined;
};
}, []);
const handleMouseDown = (event: ReactMouseEvent<HTMLElement>) => {
// Only the primary button starts a resize; guard before preventDefault so
// right-click still opens the context menu.
if (event.button !== 0) return;
event.preventDefault();
event.stopPropagation();
stopResizeSessionRef.current?.();
stopResizeSessionRef.current = startDataGridColumnResizeOnEnd(event, header, table, !isResizeModeOnEnd);
};
const handleTouchStart = (event: ReactTouchEvent<HTMLElement>) => {
event.preventDefault();
event.stopPropagation();
stopResizeSessionRef.current?.();
stopResizeSessionRef.current = startDataGridColumnResizeOnEnd(event, header, table, !isResizeModeOnEnd);
};
return (
// A span, deliberately: consumers stretch end-aligned header CONTENT
// with `[&>div]:w-full` on headerClassName, and that compiled child
// selector (0,1,1) beats the handle's own w-5 (0,1,0) - a div handle
// then covers the whole cell and swallows the menu click. Hardening
// w-5 with ! was rejected: the tag change removes the fight instead
// of escalating it.
<span
data-slot="data-grid-table-resize-handle"
{...{
onDoubleClick: () => column.resetSize(),
onMouseDown: handleMouseDown,
onTouchStart: handleTouchStart,
className: cn(
'absolute top-0 h-full cursor-col-resize touch-none select-none z-10 flex',
isPinned === 'end'
? cn(
// An end-pinned column grows from its START edge (its end is
// anchored), so the handle lives there, inside the sticky
// cell.
'start-0 w-5 justify-start',
props.tableLayout?.columnsPinnable ? 'before:hidden' : 'before:absolute before:inset-y-0 before:start-0 before:w-px before:bg-border',
)
: isLastVisibleColumn
? 'end-0 w-5 justify-end before:hidden'
: isPinned
? cn(
// A pinned column is sticky, so the handle sits inside the
// cell instead of straddling the boundary, where the next
// sticky cell would paint over it.
'end-0 w-5 justify-end',
// With the pin affordance on, the pinned edge already draws
// its own separator and a resize line would double it. But
// pinning is also usable purely as an ordering lock, with no
// affordance and no separator -- and there this line is the
// only thing marking the edge, so hiding it left a resizable
// column showing a resize cursor and no indicator at all.
props.tableLayout?.columnsPinnable
? 'before:hidden'
: 'before:absolute before:inset-y-0 before:end-0 before:w-px before:bg-border',
)
: cn(
'-end-2 w-5 justify-center',
// With cell borders on, the th border-e already marks every
// boundary and this always-on line would double it; the wide
// hit area and resize cursor stay.
props.tableLayout?.cellBorder
? 'before:hidden'
: 'before:absolute before:inset-y-0 before:w-px before:-translate-x-px before:bg-border',
),
column.getIsResizing() &&
(isResizeModeOnEnd
? 'opacity-100'
: isLastVisibleColumn
? 'before:absolute before:end-0 before:block before:inset-y-0 before:w-0.5 before:bg-primary opacity-100'
: 'before:block before:bg-primary before:w-0.5 opacity-100'),
),
}}
/>
);
}
function DataGridTableResizeIndicator({ viewportNodeRef }: { viewportNodeRef: RefObject<HTMLDivElement | null> }) {
const { props, table } = useDataGrid();
const indicatorRef = useRef<HTMLDivElement | null>(null);
const indicatorHeadRef = useRef<HTMLDivElement | null>(null);
// Header height is stable for the duration of a drag; caching it per
// session avoids a forced layout (querySelector + getBoundingClientRect)
// on every mousemove.
const headerHeightCacheRef = useRef<{
key: string | false;
value: number;
}>({ key: false, value: 0 });
const columnResizing = table.state.columnResizing;
const resizingColumnId = columnResizing.isResizingColumn;
const resizeMode = getDataGridColumnResizeMode(props.tableLayout?.columnsResizeMode, table.options.columnResizeMode);
const isActive = !!(props.tableLayout?.columnsResizable && resizeMode === 'onEnd' && resizingColumnId);
// Positioning happens imperatively after each drag-frame render: layout
// reads (viewport rect, thead height) and ref access belong outside render,
// and writing styles directly avoids holding the viewport node in React
// state, which would cost every grid a second render pass at mount.
useLayoutEffect(() => {
const indicator = indicatorRef.current;
const indicatorHead = indicatorHeadRef.current;
const viewportElement = viewportNodeRef.current;
if (!isActive || !indicator || !indicatorHead || !resizingColumnId) return;
const resizingHeader = table.getFlatHeaders().find((header) => header.column.id === resizingColumnId || header.id === resizingColumnId);
if (!resizingHeader) return;
// deltaOffset is a logical delta (already direction-adjusted); translate
// by the physical pointer movement so the indicator follows the cursor
// instead of mirroring it. End-pinned columns resize mirrored (see the
// session), so the multiplier matches theirs.
const directionMultiplier = (table.options.columnResizeDirection === 'rtl') !== (resizingHeader.column.getIsPinned() === 'end') ? -1 : 1;
const deltaOffset = (columnResizing.deltaOffset ?? 0) * directionMultiplier;
if (headerHeightCacheRef.current.key !== resizingColumnId) {
headerHeightCacheRef.current = {
key: resizingColumnId,
value: viewportElement?.querySelector('[data-slot="data-grid-table"] thead')?.getBoundingClientRect().height ?? 0,
};
}
const headerHeight = headerHeightCacheRef.current.value;
// Anchor on the live header cell: content math (getStart) cannot place a
// STICKY pinned column, while the DOM rect is right for every column at
// any scroll position. The state offset and content math stay as
// fallbacks for a header that is not in the DOM.
const viewportRoot = viewportElement ?? indicator.closest<HTMLElement>('[data-slot="data-grid-table-viewport"]');
const headerCellElement = viewportRoot?.querySelector<HTMLElement>(`thead th[data-col-id="${CSS.escape(resizingHeader.column.id)}"]`);
let indicatorLeft: number;
if (headerCellElement && viewportRoot) {
const anchorRect = headerCellElement.getBoundingClientRect();
const edgeClientX =
(table.options.columnResizeDirection === 'rtl') !== (resizingHeader.column.getIsPinned() === 'end') ? anchorRect.left : anchorRect.right;
indicatorLeft = edgeClientX - viewportRoot.getBoundingClientRect().left;
} else if (typeof columnResizing.startOffset === 'number' && viewportElement) {
indicatorLeft = columnResizing.startOffset - viewportElement.getBoundingClientRect().left;
} else {
indicatorLeft = resizingHeader.getStart() + resizingHeader.getSize();
}
indicator.style.left = `${indicatorLeft}px`;
indicator.style.transform = `translateX(${deltaOffset}px)`;
indicatorHead.style.height = `${Math.max(headerHeight, 6)}px`;
});
if (!isActive) return null;
return (
<div ref={indicatorRef} aria-hidden="true" data-slot="data-grid-table-resize-indicator" className="pointer-events-none absolute inset-y-0 z-50">
<div className="bg-primary/85 absolute inset-y-0 left-0 w-px -translate-x-1/2" />
<div ref={indicatorHeadRef} className="bg-primary rounded-b-sm absolute top-0 left-0 -translate-x-1/2 shadow-xs" style={{ width: 5 }} />
</div>
);
}
function DataGridTableRowSpacer() {
return <tbody aria-hidden="true" className="h-2" data-slot="data-grid-table-body-spacer"></tbody>;
}
function DataGridTableBody({ children }: { children: ReactNode }) {
const { props } = useDataGrid();
return (
<tbody
data-slot="data-grid-table-body"
className={cn(
props.tableLayout?.rowRounded && '[&_td:first-child]:rounded-l-lg',
props.tableLayout?.rowRounded && '[&_td:last-child]:rounded-r-lg',
props.tableClassNames?.body,
)}
>
{children}
</tbody>
);
}
function DataGridTableFoot({ children }: { children: ReactNode }) {
const { props } = useDataGrid();
return (
<tfoot
data-slot="data-grid-table-foot"
className={cn(
// The rule between the body and the footer. It used to be drawn by the
// last body row through an ancestor :has(), which made every style
// invalidation re-match the whole grid.
props.tableLayout?.rowBorder && '[&>tr:first-child>td]:border-t',
props.tableClassNames?.footer,
)}
>
{children}
</tfoot>
);
}
function DataGridTableFootRow({ children }: { children: ReactNode }) {
const { props, table } = useDataGrid();
const footRowBottomBorderClasses = '[&:not(:last-child)>td]:border-b';
return (
<tr
data-slot="data-grid-table-foot-row"
className={cn(
props.tableLayout?.footerBackground && 'bg-muted/40 dark:bg-background',
props.tableLayout?.rowBorder && footRowBottomBorderClasses,
props.tableLayout?.cellBorder && '*:last:border-e-0',
// The fill foot cell is the :last child, so the rule above only
// strips the filler; the real last cell needs the same treatment or
// its border floats into the strip while thead and tbody suppress
// theirs. Same pin-affordance gate as the cell-level suppressors.
props.tableLayout?.cellBorder &&
props.tableLayout?.columnsResizable &&
(props.tableLayout?.columnsPinnable || !hasDataGridTableRightPinnedColumns(table)) &&
'[&>td:has(+td[data-slot=data-grid-table-fill-foot-cell])]:border-e-0',
)}
>
{children}
<DataGridTableFillFootCell />
</tr>
);
}
function DataGridTableFootRowCell({ children, colSpan, className }: { children?: ReactNode; colSpan?: number; className?: string }) {
const { props } = useDataGrid();
const spacing = footerCellSpacingVariants({
size: props.tableLayout?.dense ? 'dense' : 'default',
});
return (
<td
colSpan={colSpan}
className={cn(
'text-secondary-foreground/80 align-middle font-medium',
spacing,
props.tableLayout?.footerBackground && 'bg-muted/40 dark:bg-background',
props.tableLayout?.cellBorder && 'border-e',
className,
)}
>
{children}
</td>
);
}
function DataGridTableBodyRowSkeleton({ children }: { children: ReactNode }) {
const { table, props } = useDataGrid();
return (
<tr
className={cn(
'hover:bg-muted/40 data-[state=selected]:bg-muted/50',
props.onRowClick && 'cursor-pointer',
!props.tableLayout?.stripped && props.tableLayout?.rowBorder && 'border-border border-b [&:not(:last-child)>td]:border-b',
props.tableLayout?.cellBorder && '*:last:border-e-0',
props.tableLayout?.stripped && 'odd:bg-muted/90 odd:hover:bg-muted hover:bg-transparent',
props.tableClassNames?.bodyRow,
)}
>
{children}
</tr>
);
}
function DataGridTableBodyRowSkeletonCell<TData extends object>({
children,
column,
}: {
children: ReactNode;
column: Column<DataGridFeatures, TData, unknown>;
}) {
const { props, table } = useDataGrid();
const bodyCellSpacing = bodyCellSpacingVariants({
size: props.tableLayout?.dense ? 'dense' : 'default',
});
return (
<td
style={props.tableLayout?.columnsResizable ? { width: `calc(var(--col-${column.id}-size) * 1px)` } : undefined}
className={cn(
'align-middle',
bodyCellSpacing,
props.tableLayout?.cellBorder && 'border-e',
props.tableLayout?.cellBorder &&
props.tableLayout?.columnsResizable &&
// With end-pinned columns but no pin affordance, the pinned edge
// draws no separator of its own; keep the border then.
(props.tableLayout?.columnsPinnable || !hasDataGridTableRightPinnedColumns(table)) &&
!column.getIsPinned() &&
column.getIsLastColumn('center') &&
'border-e-0',
props.tableLayout?.columnsResizable && column.getCanResize() && 'truncate',
column.columnDef.meta?.cellClassName,
props.tableLayout?.columnsPinnable &&
column.getCanPin() &&
'data-pinned:bg-background data-pinned:isolate [&[data-pinned=end][data-last-col=end]]:shadow-[inset_1px_0_0_0_var(--border)] [&[data-pinned=start][data-last-col=start]]:shadow-[inset_-1px_0_0_0_var(--border)]',
column.getIndex() === 0 || column.getIndex() === table.getVisibleLeafColumns().length - 1 ? props.tableClassNames?.edgeCell : '',
)}
>
{children}
</td>
);
}
function DataGridTableBodyRow<TData extends object>({
children,
row,
pinnedBoundary,
rowRef,
dndRef,
dndStyle,
dataIndex,
}: {
children: ReactNode;
row: Row<DataGridFeatures, TData>;
pinnedBoundary?: DataGridTablePinnedBoundary;
rowRef?: React.Ref<HTMLTableRowElement>;
dndRef?: React.Ref<HTMLTableRowElement>;
dndStyle?: CSSProperties;
dataIndex?: number;
}) {
const { props, table } = useDataGrid();
const isRowPinned = row.getIsPinned();
const rowStatus = props.getRowStatus?.(row.original);
const bodyRowBottomBorderClasses = '[&:not(:last-child)>td]:border-b';
return (
<tr
ref={(node) => {
assignRef(rowRef, node);
assignRef(dndRef, node);
}}
style={{ ...(dndStyle ? dndStyle : null) }}
data-state={table.options.enableRowSelection && row.getIsSelected() ? 'selected' : undefined}
data-index={dataIndex}
data-row-id={row.id}
data-depth={row.depth || undefined}
data-row-pinned={isRowPinned || undefined}
data-row-pinned-boundary={pinnedBoundary}
data-row-status={rowStatus}
// 1-based after the header row; row.index is the position in the data,
// so the announced index stays absolute across pagination.
aria-rowindex={props.tableLayout?.cellSelection ? row.index + 2 : undefined}
onClick={() => props.onRowClick && props.onRowClick(row.original)}
className={cn(
'hover:bg-muted/40 data-[state=selected]:bg-muted/50',
/* With the pin affordance on, pinned cells hide scrolled content
behind an OPAQUE background, which also hides the row's translucent
hover and selected tints; they get the same tints premixed over the
background instead, the row-status treatment. Pinning used only as
an ordering lock leaves cells transparent, so the premix would paint
a second, different hover colour: gate it on the same flag. */
props.tableLayout?.columnsPinnable &&
'hover:[&>td[data-pinned]]:bg-[color-mix(in_oklab,var(--muted)_40%,var(--background))] data-[state=selected]:[&>td[data-pinned]]:bg-[color-mix(in_oklab,var(--muted)_50%,var(--background))]',
props.onRowClick && 'cursor-pointer',
// Optional CRUD indications, active only when getRowStatus is
// wired; the warning-muted defaults yield to tableClassNames
// overrides per status. Pinned cells must stay OPAQUE (they hide
// scrolled content), so they get the same tint pre-mixed over the
// background instead of inheriting the translucent row fill.
props.getRowStatus &&
'data-[row-status=deleted]:bg-destructive/5 data-[row-status=deleted]:opacity-60 data-[row-status=dirty]:bg-amber-500/5 data-[row-status=new]:bg-green-500/5 data-[row-status=deleted]:[&_td]:line-through',
props.getRowStatus &&
props.tableLayout?.columnsPinnable &&
'data-[row-status=deleted]:[&>td[data-pinned]]:bg-[color-mix(in_oklab,var(--destructive)_5%,var(--background))] data-[row-status=dirty]:[&>td[data-pinned]]:bg-[color-mix(in_oklab,var(--color-amber-500)_5%,var(--background))] data-[row-status=new]:[&>td[data-pinned]]:bg-[color-mix(in_oklab,var(--color-green-500)_5%,var(--background))]',
rowStatus === 'new' && props.tableClassNames?.rowNew,
rowStatus === 'dirty' && props.tableClassNames?.rowDirty,
rowStatus === 'deleted' && props.tableClassNames?.rowDeleted,
!props.tableLayout?.stripped && props.tableLayout?.rowBorder && bodyRowBottomBorderClasses,
props.tableLayout?.cellBorder && `*:last:border-e-0 ${bodyRowBottomBorderClasses}`,
// Virtualized rows stripe by absolute row index (CSS :nth-child
// parity flips as spacer rows resize while scrolling).
props.tableLayout?.stripped &&
(typeof dataIndex === 'number'
? cn('hover:bg-transparent', dataIndex % 2 === 0 && 'bg-muted/90 hover:bg-muted')
: 'odd:bg-muted/90 odd:hover:bg-muted hover:bg-transparent'),
props.tableLayout?.rowsPinnable && isRowPinned && 'bg-muted/30 hover:bg-muted/50',
pinnedBoundary === 'top' && '[&>td]:shadow-[0_2px_0_rgba(0,0,0,0.03)] dark:[&>td]:shadow-[0_2px_0_rgba(255,255,255,0.06)]',
// A bottom-pinned row borders scrolled content along its TOP edge,
// so its separator shadow casts upward.
pinnedBoundary === 'bottom' && '[&>td]:shadow-[0_-2px_0_rgba(0,0,0,0.03)] dark:[&>td]:shadow-[0_-2px_0_rgba(255,255,255,0.06)]',
props.tableLayout?.rowsPinnable && isRowPinned && props.tableClassNames?.rowPinned,
props.tableClassNames?.bodyRow,
)}
>
{children}
</tr>
);
}
function DataGridTableBodyRowExpandded<TData extends object>({ row }: { row: Row<DataGridFeatures, TData> }) {
const { props, table } = useDataGrid();
const expandedContent = table.getAllColumns().find((column) => column.columnDef.meta?.expandedContent)?.columnDef.meta?.expandedContent;
// Tree and grouped rows share row.getIsExpanded() with detail expansion.
// Without a detail column there is nothing to render, and an empty <tr>
// would break striping parity, rowBorder, and virtual row measurement.
if (!expandedContent) return null;
const bodyRowBottomBorderClasses = '[&:not(:last-child)>td]:border-b';
return (
<tr className={cn(props.tableLayout?.rowBorder && bodyRowBottomBorderClasses)}>
<td colSpan={getDataGridTableOrderedVisibleCells(row).length + (props.tableLayout?.columnsResizable ? 1 : 0)}>
{expandedContent(row.original)}
</td>
</tr>
);
}
/**
* Interactive descendants keep their own mousedown semantics: a click on a
* button, link, editor or checkbox inside a cell must never start or replace
* a range. One selector also covers the row-dnd grip (a button), the expand
* toggle, and `data-cell-interactive` - the documented opt-out for custom
* widgets built from elements the tag list cannot know about.
*/
function isDataGridCellInteractiveTarget(target: EventTarget | null): boolean {
return (
target instanceof Element &&
target.closest(
'button, a, input, select, textarea, [contenteditable], [role="checkbox"], [data-cell-interactive], [data-slot="data-grid-table-row-expand"], [data-slot="data-grid-cell-fill-handle"]',
) != null
);
}
function DataGridTableBodyRowCell<TData extends object>({
children,
cell,
dndRef,
dndStyle,
columnIndex,
}: {
children: ReactNode;
cell: Cell<DataGridFeatures, TData, unknown>;
dndRef?: React.Ref<HTMLTableCellElement>;
dndStyle?: CSSProperties;
/** Center-column index under column virtualization; data-column-index. */
columnIndex?: number;
}) {
const { props, table, gridId } = useDataGrid();
const { column, row } = cell;
const isPinned = column.getIsPinned();
const isLastStartPinned = isPinned === 'start' && column.getIsLastColumn('start');
const isFirstEndPinned = isPinned === 'end' && column.getIsFirstColumn('end');
const bodyCellSpacing = bodyCellSpacingVariants({
size: props.tableLayout?.dense ? 'dense' : 'default',
});
// The atom check backs up the flag: consumers may hand the grid a leaner
// bundle without cellSelectionFeature, and the flag alone must not make the
// renderer call prototype APIs that were never assigned.
const cellSelectionOn = !!props.tableLayout?.cellSelection && table.atoms.cellSelection != null;
const rangeSelectionOn = cellSelectionOn && props.tableLayout?.cellSelectionMode !== 'single';
const renderTd = (selection: ReturnType<typeof getDataGridCellSelectionCellAttrs> | null) => (
<td
ref={dndRef}
// The id is what the controller's aria-activedescendant points at, so
// a screen reader tracks the focused cell through the container-focus
// model.
id={cellSelectionOn ? `${gridId}c-${toDataGridDomId(row.id)}-${toDataGridDomId(column.id)}` : undefined}
aria-colindex={cellSelectionOn ? column.getIndex() + 1 : undefined}
style={{
...(props.tableLayout?.columnsPinnable && column.getCanPin() && getPinningStyles(column)),
// Paint containment clips at the padding edge, which would erase
// the ::before selection chrome on pinned cells.
...(cellSelectionOn ? { contain: undefined } : null),
...(props.tableLayout?.columnsResizable && {
width: `calc(var(--col-${column.id}-size) * 1px)`,
}),
...(dndStyle ? dndStyle : null),
}}
data-pinned={isPinned || undefined}
data-last-col={isLastStartPinned ? 'start' : isFirstEndPinned ? 'end' : undefined}
data-cell-status={props.getCellStatus?.(row.original, column.id)}
data-column-index={columnIndex}
{...(selection ? selection : null)}
onMouseDown={
selection
? (event) => {
if (event.button !== 0) return;
if (isDataGridCellInteractiveTarget(event.target)) {
// A modifier click is a SELECTION gesture even on a control:
// Shift extends and Ctrl/Cmd adds, exactly as on a plain
// cell, so no column is unreachable for ranges.
if (rangeSelectionOn && (event.shiftKey || event.metaKey || event.ctrlKey) && cell.getCanSelect()) {
event.preventDefault();
cell.getSelectionStartHandler()(event);
return;
}
// The press starts the range session exactly like a plain
// cell: the cell focuses, a drag extends from it, and a
// motionless press still ends in the control's own click
// (this is why drag releases are squelched upstream, in the
// controller, once a drag actually grew the range).
if (cell.getCanSelect()) {
if (rangeSelectionOn) {
cell.getSelectionStartHandler()(event);
} else {
table.setFocusedCell(row.id, column.id);
}
}
return;
}
if (!rangeSelectionOn) {
// Single mode: every gesture collapses to the one cell.
if (cell.getCanSelect()) {
table.setFocusedCell(row.id, column.id);
}
return;
}
cell.getSelectionStartHandler()(event);
}
: undefined
}
onMouseEnter={rangeSelectionOn ? (event) => cell.getSelectionExtendHandler()(event) : undefined}
className={cn(
'align-middle',
bodyCellSpacing,
// The classic edited-cell corner mark, active only when
// getCellStatus is wired: amber for "dirty", destructive for
// "invalid".
props.getCellStatus &&
"data-[cell-status=invalid]:after:border-t-destructive data-[cell-status]:relative data-[cell-status]:after:absolute data-[cell-status]:after:end-0 data-[cell-status]:after:top-0 data-[cell-status]:after:size-0 data-[cell-status]:after:border-s-[5px] data-[cell-status]:after:border-t-[5px] data-[cell-status]:after:border-s-transparent data-[cell-status]:after:content-[''] data-[cell-status=dirty]:after:border-t-amber-500",
props.tableLayout?.cellBorder && 'border-e',
// Mirror of the head cell rule: no floating border against the
// resize filler strip.
props.tableLayout?.cellBorder &&
props.tableLayout?.columnsResizable &&
// With end-pinned columns but no pin affordance, the pinned edge
// draws no separator of its own; keep the border then.
(props.tableLayout?.columnsPinnable || !hasDataGridTableRightPinnedColumns(table)) &&
!isPinned &&
column.getIsLastColumn('center') &&
'border-e-0',
props.tableLayout?.columnsResizable && column.getCanResize() && !cellSelectionOn && 'truncate',
cell.column.columnDef.meta?.cellClassName,
props.tableLayout?.columnsPinnable &&
column.getCanPin() &&
cn(
'data-pinned:bg-background data-pinned:isolate',
'[&[data-pinned=start][data-last-col=start]]:shadow-[inset_-1px_0_0_0_var(--border)]',
'[&[data-pinned=end][data-last-col=end]]:shadow-[inset_1px_0_0_0_var(--border)]',
),
column.getIndex() === 0 || column.getIndex() === row.getVisibleCells().length - 1 ? props.tableClassNames?.edgeCell : '',
selection && dataGridCellSelectionCellClasses,
)}
>
{/* With cell selection on, the td must not clip (its ::before paints
the selection chrome 1px outside the cell), so the resize
truncation moves to an inner wrapper that clips at the same
boundary the td used to. */}
{cellSelectionOn && props.tableLayout?.columnsResizable && column.getCanResize() ? (
<div
className={bodyCellTruncateWrapVariants({
size: props.tableLayout?.dense ? 'dense' : 'default',
})}
>
{children}
</div>
) : (
children
)}
{props.tableLayout?.cellFillHandle && selection?.['data-cell-edge-bottom'] && selection['data-cell-edge-right'] && (
<span
data-slot="data-grid-cell-fill-handle"
/* "dot" stays fully inside the cell corner; "ring" rides the
corner point the way Sheets draws it. Either way the handle
clamps where straddling would break: at the grid's own
boundary (last row, last cell, a last cell followed only by
the filler strip), where an overhang would extend the scroll
content and clip the selection chrome, and beside a PINNED
column, whose sticky layer (z 30) would otherwise paint over
the straddling half - raising the handle instead would float
it above the pinned column during horizontal scroll. */
className={cn(
'absolute z-10 cursor-crosshair in-data-[cell-editing]:hidden in-data-[cell-selecting]:hidden',
props.tableLayout?.cellFillHandleVariant === 'ring'
? 'border-primary bg-background -end-[5px] -bottom-[5px] size-[11px] rounded-full border-2 in-[td:has(+[data-slot=data-grid-table-fill-body-cell]+td[data-pinned])]:end-0 in-[td:has(+[data-slot=data-grid-table-fill-body-cell]:last-child)]:end-0 in-[td:has(+td[data-pinned])]:end-0 in-[td:last-child]:end-0 in-[tr:last-child]:bottom-0'
: props.tableLayout?.cellFillHandleVariant === 'square'
? /* Abutting the cell borders from inside: no gap and no
overlap, so the square cannot merge with a gridline
into a wider-than-tall blob, and it can never leave
the grid, which is why it needs no boundary clamps. */
'bg-primary end-0 bottom-0 size-[5px]'
: 'bg-primary border-background end-0 bottom-0 size-[9px] rounded-full border',
props.tableClassNames?.cellFillHandle,
)}
/>
)}
</td>
);
if (!cellSelectionOn) return renderTd(null);
// Per-cell subscription with a projecting selector: the atom writes once
// per cell crossed during a drag, and shallow-comparing this tuple limits
// the re-render to cells whose selection state actually changed.
return (
<Subscribe source={table.atoms.cellSelection} selector={() => getDataGridCellSelectionCellAttrs(cell)}>
{(selection) => renderTd(selection)}
</Subscribe>
);
}
function DataGridTableRenderedRow<TData extends object>({
row,
pinnedBoundary,
rowRef,
rowIndex,
centerWindow,
}: {
row: Row<DataGridFeatures, TData>;
pinnedBoundary?: DataGridTablePinnedBoundary;
rowRef?: React.Ref<HTMLTableRowElement>;
/** Virtualized list index, rendered as data-index for measureElement. */
rowIndex?: number;
/**
* Column-virtualization window over the CENTER cells: only the inclusive
* [start, end] slice renders, and each flank collapses into one colSpan
* spacer. The spacers carry no width of their own - the colgroup stays
* complete, so under table-fixed the browser sizes them from the col
* elements they span and the layout cannot drift.
*/
centerWindow?: { start: number; end: number };
}) {
const { props, table } = useDataGrid();
const startVisibleCells = row.getStartVisibleCells();
const centerVisibleCells = row.getCenterVisibleCells();
const endVisibleCells = row.getEndVisibleCells();
const hasRightPinnedColumns = hasDataGridTableRightPinnedColumns(table);
const windowedCenterCells = centerWindow ? centerVisibleCells.slice(centerWindow.start, centerWindow.end + 1) : centerVisibleCells;
const leadingSpacerSpan = centerWindow ? centerWindow.start : 0;
const trailingSpacerSpan = centerWindow ? Math.max(0, centerVisibleCells.length - 1 - centerWindow.end) : 0;
return (
<Fragment>
<DataGridTableBodyRow row={row} pinnedBoundary={pinnedBoundary} rowRef={rowRef} dataIndex={rowIndex}>
{startVisibleCells.map((cell: Cell<DataGridFeatures, TData, unknown>) => (
<DataGridTableBodyRowCell cell={cell} key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</DataGridTableBodyRowCell>
))}
{leadingSpacerSpan > 0 && <td aria-hidden="true" data-slot="data-grid-table-virtual-col-spacer" colSpan={leadingSpacerSpan} />}
{windowedCenterCells.map((cell: Cell<DataGridFeatures, TData, unknown>, cellIndex) => (
<DataGridTableBodyRowCell cell={cell} key={cell.id} columnIndex={centerWindow ? centerWindow.start + cellIndex : undefined}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</DataGridTableBodyRowCell>
))}
{trailingSpacerSpan > 0 && <td aria-hidden="true" data-slot="data-grid-table-virtual-col-spacer" colSpan={trailingSpacerSpan} />}
{props.tableLayout?.columnsResizable && hasRightPinnedColumns ? <DataGridTableFillBodyCell /> : null}
{endVisibleCells.map((cell: Cell<DataGridFeatures, TData, unknown>) => (
<DataGridTableBodyRowCell cell={cell} key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</DataGridTableBodyRowCell>
))}
{props.tableLayout?.columnsResizable && !hasRightPinnedColumns ? <DataGridTableFillBodyCell /> : null}
</DataGridTableBodyRow>
{row.getIsExpanded() && <DataGridTableBodyRowExpandded row={row} />}
</Fragment>
);
}
function DataGridTableEmpty() {
const { i18n, table, props } = useDataGrid();
const visibleColumnCount = getDataGridTableOrderedVisibleColumns(table).length + (props.tableLayout?.columnsResizable ? 1 : 0);
return (
<tr>
<td colSpan={Math.max(visibleColumnCount, 1)} className="text-muted-foreground py-6 text-center text-sm">
{props.emptyMessage || i18n.labels.empty}
</td>
</tr>
);
}
function DataGridTableLoader() {
const { i18n, props } = useDataGrid();
return (
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2">
<div className="text-muted-foreground bg-card rounded-lg flex items-center gap-2 border px-4 py-2 text-sm leading-none font-medium">
<Spinner className="size-5 opacity-60" />
{props.loadingMessage || i18n.labels.loading}
</div>
</div>
);
}
function DataGridTableRowPin<TData extends object>({ row }: { row: Row<DataGridFeatures, TData> }) {
const { i18n } = useDataGrid();
const isPinned = row.getIsPinned();
return (
<button
type="button"
aria-label={isPinned ? i18n.labels.unpinRow : i18n.labels.pinRow}
onClick={(event) => {
// Pinning must not bubble into the row's onRowClick handler.
event.stopPropagation();
if (isPinned) {
row.pin(false);
} else {
row.pin('top');
}
}}
className={cn(
'text-muted-foreground hover:text-foreground rounded-lg inline-flex size-7 items-center justify-center transition-colors',
isPinned && 'text-primary hover:text-primary/80',
)}
>
{isPinned ? (
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" stroke="none">
<path d="M16 2l4.585 4.586-2.122 2.121L17.05 7.293l-3.535 3.536 1.413 5.658-2.12 2.121-4.244-4.243L4.322 18.6l-1.414-1.41 4.242-4.244-4.243-4.243 2.122-2.121 5.656 1.414 3.536-3.536-1.414-1.414z" />
</svg>
) : (
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<line x1="12" y1="17" x2="12" y2="22" />
<path d="M5 17h14v-1.76a2 2 0 00-1.11-1.79l-1.78-.9A2 2 0 0115 10.76V6h1a2 2 0 000-4H8a2 2 0 000 4h1v4.76a2 2 0 01-1.11 1.79l-1.78.9A2 2 0 005 15.24z" />
</svg>
)}
</button>
);
}
/**
* Selection cell.
*
* The `Subscribe` wrapper is the v9 fix for React Compiler, and it is why this
* file no longer needs `"use no memo"`. `useTable` hands back a fresh table on
* every state change, which covers anything read through `table`, but this
* component reads selection through `row.getIsSelected()` - a builder call
* that hides its state dependency from the compiler. Rendered inside a column
* `cell` template it receives a *stable* row, so the compiler is free to
* memoize this JSX and never re-run those reads, which shows up as checkboxes
* that do not respond to clicks.
*
* Subscribing to the row-selection atom gives the compiler a dependency it can
* see. Note the standalone `Subscribe` rather than `table.Subscribe`: inside a
* cell template the `table` handed to the column def is the core `Table`, which
* has no `Subscribe` attached.
*/
function DataGridTableRowSelect<TData extends object>({ row }: { row: Row<DataGridFeatures, TData> }) {
const { i18n } = useDataGrid();
return (
<Subscribe source={row.table.atoms.rowSelection}>
{() => (
<>
<Checkbox
checked={row.getIsSelected()}
indeterminate={row.getIsSomeSelected() && !row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
onClick={(event) => {
// Selection must not bubble into the row's onRowClick handler.
event.stopPropagation();
}}
aria-label={i18n.labels.selectRow}
className="align-[inherit]"
/>
</>
)}
</Subscribe>
);
}
function DataGridTableRowSelectAll() {
const { i18n, table, recordCount, isLoading } = useDataGrid();
// `getIsSomePageRowsSelected()` means "at least one" in v9, where v8 meant
// "some but not all", so the all-selected case has to be excluded explicitly
// or the header checkbox stays indeterminate once every row is checked.
return (
<Subscribe source={table.atoms.rowSelection}>
{() => {
const isAllSelected = table.getIsAllPageRowsSelected();
const isSomeSelected = table.getIsSomePageRowsSelected();
return (
<Checkbox
checked={isAllSelected}
indeterminate={isSomeSelected && !isAllSelected}
disabled={isLoading || recordCount === 0}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label={i18n.labels.selectAll}
className="align-[inherit]"
/>
);
}}
</Subscribe>
);
}
function DataGridTableRowExpand<TData extends object>({
row,
indent = 20,
className,
children,
}: {
row: Row<DataGridFeatures, TData>;
/** Horizontal offset in px applied per tree depth level. */
indent?: number;
className?: string;
/** Custom toggle icon; replaces the default chevron. */
children?: ReactNode;
}) {
const { i18n, props } = useDataGrid();
const isExpanded = row.getIsExpanded();
const controlSize = props.tableLayout?.dense ? 'size-6' : 'size-7';
return (
<span
data-slot="data-grid-table-row-expand"
style={getDataGridTreeIndentStyle(row, indent)}
className={cn('inline-flex shrink-0 items-center ps-(--data-grid-tree-padding) align-middle', className)}
>
{row.getCanExpand() ? (
<button
type="button"
aria-expanded={isExpanded}
aria-label={isExpanded ? i18n.labels.collapseRow : i18n.labels.expandRow}
onClick={(event) => {
// Expansion must not bubble into the row's onRowClick handler.
event.stopPropagation();
row.toggleExpanded();
}}
className={cn(
'text-muted-foreground hover:text-foreground rounded-lg inline-flex items-center justify-center transition-colors',
controlSize,
)}
>
{children ?? (
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
className="transition-transform duration-200 in-aria-[expanded=false]:-rotate-90 rtl:in-aria-[expanded=false]:rotate-90"
>
<path d="m6 9 6 6 6-6" />
</svg>
)}
</button>
) : (
// Leaf spacer: compact by design so leaf content sits near the
// parent label instead of a full toggle width deeper.
<span aria-hidden="true" className="w-2 shrink-0" />
)}
</span>
);
}
function DataGridTableBodyRows<TData extends object>({ table }: { table: DataGridTableInstance<TData> }) {
const { i18n, isLoading, props } = useDataGrid();
const pagination = table.state.pagination;
if (isLoading && props.loadingMode === 'skeleton' && pagination?.pageSize) {
const leftVisibleColumns = table.getStartVisibleLeafColumns();
const centerVisibleColumns = table.getCenterVisibleLeafColumns();
const rightVisibleColumns = table.getEndVisibleLeafColumns();
const hasRightPinnedColumns = hasDataGridTableRightPinnedColumns(table);
return (
<>
{Array.from({ length: pagination.pageSize }).map((_, rowIndex) => (
<DataGridTableBodyRowSkeleton key={rowIndex}>
{[...leftVisibleColumns, ...centerVisibleColumns].map((column) => (
<DataGridTableBodyRowSkeletonCell column={column} key={column.id}>
{column.columnDef.meta?.skeleton}
</DataGridTableBodyRowSkeletonCell>
))}
{props.tableLayout?.columnsResizable && hasRightPinnedColumns ? <DataGridTableFillBodyCell /> : null}
{rightVisibleColumns.map((column) => (
<DataGridTableBodyRowSkeletonCell column={column} key={column.id}>
{column.columnDef.meta?.skeleton}
</DataGridTableBodyRowSkeletonCell>
))}
{props.tableLayout?.columnsResizable && !hasRightPinnedColumns ? <DataGridTableFillBodyCell /> : null}
</DataGridTableBodyRowSkeleton>
))}
</>
);
}
if (isLoading && props.loadingMode === 'spinner') {
return (
<tr>
<td colSpan={table.getVisibleFlatColumns().length + (props.tableLayout?.columnsResizable ? 1 : 0)} className="p-8">
<div className="flex items-center justify-center">
<svg className="text-muted-foreground mr-3 -ml-1 h-5 w-5 animate-spin" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
{props.loadingMessage || i18n.labels.loading}
</div>
</td>
</tr>
);
}
const resolvedRows = getDataGridTableResolvedRows(table, props.tableLayout?.rowsPinnable);
if (!resolvedRows.length) return <DataGridTableEmpty />;
return (
<>
{resolvedRows.map(({ row, pinnedBoundary }) => (
<DataGridTableRenderedRow key={row.id} row={row} pinnedBoundary={pinnedBoundary} />
))}
</>
);
}
/**
* Memoized body rows: skip re-renders during active column resize.
* Column widths update via CSS variables on the <table> element,
* so the browser handles width changes without React re-renders.
* A cell-selection drag gets the same treatment: the root re-renders once per
* cell crossed, but painting goes through each cell's own Subscribe, so row
* reconciliation during the drag is pure waste.
*/
const MemoizedDataGridTableBodyRows = memo(
DataGridTableBodyRows,
(_prev, next) => !!next.table.state.columnResizing.isResizingColumn || next.table._isSelectingCells === true,
) as typeof DataGridTableBodyRows;
function DataGridTableHeader<TData extends object>() {
const { table, props } = useDataGrid();
const mergedHeaderGroups = getDataGridTableMergedHeaderGroups(table);
const hasRightPinnedColumns = hasDataGridTableRightPinnedColumns(table);
return (
<DataGridTableViewport>
<DataGridTableBase>
<DataGridTableHead>
{mergedHeaderGroups.map((headerGroup) => {
return (
<DataGridTableHeadRow key={headerGroup.id} rowId={headerGroup.id}>
{headerGroup.headers
.filter((header) => header.column.getIsPinned() !== 'end')
.map((header) => {
const { column } = header;
return (
<DataGridTableHeadRowCell header={header} key={header.id}>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
{props.tableLayout?.columnsResizable && column.getCanResize() && <DataGridTableHeadRowCellResize header={header} />}
</DataGridTableHeadRowCell>
);
})}
{props.tableLayout?.columnsResizable && hasRightPinnedColumns ? <DataGridTableFillHeadCell /> : null}
{headerGroup.headers
.filter((header) => header.column.getIsPinned() === 'end')
.map((header) => {
const { column } = header;
return (
<DataGridTableHeadRowCell header={header} key={header.id}>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
{props.tableLayout?.columnsResizable && column.getCanResize() && <DataGridTableHeadRowCellResize header={header} />}
</DataGridTableHeadRowCell>
);
})}
{props.tableLayout?.columnsResizable && !hasRightPinnedColumns ? <DataGridTableFillHeadCell /> : null}
</DataGridTableHeadRow>
);
})}
</DataGridTableHead>
</DataGridTableBase>
</DataGridTableViewport>
);
}
function DataGridTable<TData extends object>({ footerContent, renderHeader = true }: { footerContent?: ReactNode; renderHeader?: boolean }) {
const { table, props } = useDataGrid();
const mergedHeaderGroups = getDataGridTableMergedHeaderGroups(table);
const hasRightPinnedColumns = hasDataGridTableRightPinnedColumns(table);
return (
<DataGridTableViewport>
<DataGridTableBase>
{renderHeader && (
<DataGridTableHead>
{mergedHeaderGroups.map((headerGroup) => {
return (
<DataGridTableHeadRow key={headerGroup.id} rowId={headerGroup.id}>
{headerGroup.headers
.filter((header) => header.column.getIsPinned() !== 'end')
.map((header) => {
const { column } = header;
return (
<DataGridTableHeadRowCell header={header} key={header.id}>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
{props.tableLayout?.columnsResizable && column.getCanResize() && <DataGridTableHeadRowCellResize header={header} />}
</DataGridTableHeadRowCell>
);
})}
{props.tableLayout?.columnsResizable && hasRightPinnedColumns ? <DataGridTableFillHeadCell /> : null}
{headerGroup.headers
.filter((header) => header.column.getIsPinned() === 'end')
.map((header) => {
const { column } = header;
return (
<DataGridTableHeadRowCell header={header} key={header.id}>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
{props.tableLayout?.columnsResizable && column.getCanResize() && <DataGridTableHeadRowCellResize header={header} />}
</DataGridTableHeadRowCell>
);
})}
{props.tableLayout?.columnsResizable && !hasRightPinnedColumns ? <DataGridTableFillHeadCell /> : null}
</DataGridTableHeadRow>
);
})}
</DataGridTableHead>
)}
{renderHeader && (props.tableLayout?.stripped || !props.tableLayout?.rowBorder) && <DataGridTableRowSpacer />}
<DataGridTableBody>
<MemoizedDataGridTableBodyRows table={table} />
{props.appendRow}
<DataGridTableAddRow />
</DataGridTableBody>
{footerContent && <DataGridTableFoot>{footerContent}</DataGridTableFoot>}
</DataGridTableBase>
</DataGridTableViewport>
);
}
export {
DataGridTable,
DataGridTableAddRow,
DataGridTableBase,
DataGridTableBody,
DataGridTableBodyRow,
DataGridTableBodyRowCell,
DataGridTableBodyRowExpandded,
DataGridTableRenderedRow,
DataGridTableBodyRowSkeleton,
DataGridTableBodyRowSkeletonCell,
DataGridTableEmpty,
DataGridTableFillBodyCell,
DataGridTableFillHeadCell,
DataGridTableFoot,
DataGridTableFootRow,
DataGridTableFootRowCell,
DataGridTableHeader,
DataGridTableHead,
DataGridTableHeadRow,
DataGridTableHeadRowCell,
DataGridTableHeadRowCellResize,
DataGridTableLoader,
DataGridTableRowExpand,
DataGridTableRowPin,
DataGridTableRowSelect,
DataGridTableRowSelectAll,
DataGridTableRowSpacer,
DataGridTableViewport,
getDataGridScrollAreaViewport,
getDataGridTableMergedHeaderGroups,
getPinningStyles,
getDataGridTableResolvedRows,
getDataGridTableRowSections,
getDataGridTreeIndentStyle,
hasDataGridTableRightPinnedColumns,
};
export type { DataGridTablePinnedBoundary };components/ui/data-grid/data-grid.tsx
'use client';
import { createContext, useContext, useEffect, useId, useMemo, useRef } from 'react';
import type { ReactNode } from 'react';
import { mergeDataGridI18n, type DataGridI18nConfig, type DataGridI18nOverrides } from '@/registry/vcare/ui/data-grid/data-grid-i18n';
import {
cellSelectionFeature,
columnFacetingFeature,
columnFilteringFeature,
columnOrderingFeature,
columnPinningFeature,
columnResizingFeature,
columnSizingFeature,
columnVisibilityFeature,
createExpandedRowModel,
createFacetedRowModel,
createFacetedUniqueValues,
createFilteredRowModel,
createPaginatedRowModel,
createSortedRowModel,
globalFilteringFeature,
metaHelper,
rowExpandingFeature,
rowPaginationFeature,
rowPinningFeature,
rowSelectionFeature,
rowSortingFeature,
sortFn_alphanumeric,
sortFn_alphanumericCaseSensitive,
sortFn_basic,
sortFn_datetime,
sortFn_text,
sortFn_textCaseSensitive,
tableFeatures,
} from '@tanstack/react-table';
import type { Cell, Column, ColumnFiltersState, ReactTable, RowData, SortingState, Table, TableFeatures } from '@tanstack/react-table';
import { cn } from '@/registry/vcare/lib/utils';
/**
* Per-column extras the grid reads off `columnDef.meta`.
*
* TanStack v9 resolves this through the `columnMeta` slot on the feature
* bundle below instead of a global `declare module` augmentation, so
* installing the data grid no longer widens `ColumnMeta` for every other
* table in the consuming app.
*/
/**
* Per-column write contract for the spreadsheet operations (paste, fill,
* clear, cut). Presence marks the column writable; every write still flows
* through `onCellsChange`, so the consumer's state stays the only data owner.
*/
export interface DataGridColumnCellEdit<TData> {
/**
* Set false for a column that formats clipboard output but is never
* written; a function decides per row, so locked rows (archived, another
* user's, a totals row) reject like any read-only cell. Defaults to true.
*/
editable?: boolean | ((row: TData) => boolean);
/**
* Clipboard or fill string to typed value. Return undefined to reject the
* cell into `rejected`. Without it the raw string passes through unchanged -
* a deliberate non-coercion, so a number column receives strings only when
* the consumer chose not to parse.
*/
parse?: (raw: string, row: TData) => unknown;
/** Typed value to clipboard string. Fallback: String(value ?? ""). */
format?: (value: unknown, row: TData) => string;
/** Value dispatched by Delete/Backspace and cut. Defaults to null. */
clearValue?: unknown;
/**
* Opt into the grid's built-in free-text editor: an overlay input (or
* auto-growing textarea) flush over the focused cell, opened by Enter, F2,
* typing, or double-click, committing through `onCellsChange` as source
* `"edit"` with `parse` applied. Columns without it stay consumer-edited
* via `onCellEditRequest` or their own cell renderers.
*/
control?: 'text' | 'textarea';
}
export interface DataGridColumnMeta<TData> {
headerTitle?: string;
headerClassName?: string;
cellClassName?: string;
skeleton?: ReactNode;
expandedContent?: (row: TData) => ReactNode;
autoSize?: boolean;
cellEdit?: DataGridColumnCellEdit<TData>;
/**
* Under `columnsResizable`, this column absorbs the free space the filler
* strip would otherwise hold, so the grid always reads full-width and the
* built-in editor covers the whole cell. One column per grid; while free
* space remains, manual resizing of this column is visually a no-op (the
* absorbed space compensates), the flex-column trade-off.
*/
fillWidth?: boolean;
}
/**
* The batteries-included feature bundle every ReUI data-grid example builds
* on. v9 requires each table to declare its features up front, and the grid's
* render path needs the ones registered here: `columnVisibilityFeature` alone
* gates `row.getVisibleCells()`, so even a grid that never hides a column
* needs it to render at all.
*
* Pass it straight through for the full grid:
*
* ```tsx
* const table = useTable({ features: dataGridFeatures, columns, data })
* ```
*
* Extend it when a grid needs more, keeping each prerequisite feature ahead of
* the slot that depends on it:
*
* ```tsx
* const features = tableFeatures({
* ...dataGridFeatures,
* columnGroupingFeature,
* groupedRowModel: createGroupedRowModel(),
* })
* ```
*
* Or drop it entirely and hand `<DataGrid>` a leaner table - the components
* accept any bundle, so you keep full ownership of the TanStack core.
*/
export const dataGridFeatures = tableFeatures({
columnVisibilityFeature,
columnOrderingFeature,
columnPinningFeature,
columnSizingFeature,
// columnResizingFeature requires columnSizingFeature, declared above.
columnResizingFeature,
columnFilteringFeature,
// Powers DataGridColumnFilter's column.getFacetedUniqueValues(). On v8 an
// unregistered facet silently returned an empty map; on v9 the method would
// not exist at all, so the faceted row models below are required, not
// optional.
columnFacetingFeature,
// globalFilteringFeature requires columnFilteringFeature, declared above.
globalFilteringFeature,
rowSortingFeature,
rowPaginationFeature,
rowSelectionFeature,
rowExpandingFeature,
rowPinningFeature,
// Registration alone is inert: it seeds a `cellSelection: []` slice and
// prototype methods but binds no DOM handlers, so grids without
// `tableLayout.cellSelection` render and behave exactly as before.
cellSelectionFeature,
sortedRowModel: createSortedRowModel(),
filteredRowModel: createFilteredRowModel(),
paginatedRowModel: createPaginatedRowModel(),
expandedRowModel: createExpandedRowModel(),
facetedRowModel: createFacetedRowModel(),
facetedUniqueValues: createFacetedUniqueValues(),
// Every built-in v9 ships. A string `sortFn` resolves against this map
// alone, and `sortFn: "auto"` infers a name ("alphanumeric", "text" or
// "datetime") from the first row's value - so a partial map makes auto
// sorting warn and silently fall back on ordinary string columns.
sortFns: {
alphanumeric: sortFn_alphanumeric,
alphanumericCaseSensitive: sortFn_alphanumericCaseSensitive,
basic: sortFn_basic,
datetime: sortFn_datetime,
text: sortFn_text,
textCaseSensitive: sortFn_textCaseSensitive,
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
columnMeta: metaHelper<DataGridColumnMeta<any>>(),
});
/** The feature set `dataGridFeatures` registers. */
export type DataGridFeatures = typeof dataGridFeatures;
/**
* The grid's internal view of the table.
*
* `TFeatures` is invariant in v9 and an unresolved generic one collapses to a
* union that includes the bare core arm, so no generic signature can call
* `getVisibleCells()`, `getStartVisibleLeafColumns()` and friends. The public
* components stay generic so consumers can pass any bundle they like; the
* table is widened to this concrete type exactly once, on the way into
* context, and every internal component reads it from there.
*/
export type DataGridTableInstance<TData extends object> = ReactTable<DataGridFeatures, TData>;
/** Label for headers / column visibility: `meta.headerTitle`, string `columnDef.header`, or `column.id`. */
export function getColumnHeaderLabel<TData extends RowData, TValue>(column: Column<DataGridFeatures, TData, TValue>): string {
const meta = column.columnDef.meta as { headerTitle?: string } | undefined;
if (typeof meta?.headerTitle === 'string') return meta.headerTitle;
const defHeader = column.columnDef.header;
if (typeof defHeader === 'string') return defHeader;
return String(column.id);
}
/**
* The td contract for spreadsheet selection. Call inside a
* `Subscribe source={table.atoms.cellSelection}` render only: the reads are
* builder calls whose state dependency React Compiler cannot see, exactly the
* trap the row-selection checkbox documents.
*/
export function getDataGridCellSelectionCellAttrs<TData extends object>(
cell: Cell<DataGridFeatures, TData, unknown>,
): {
'aria-selected': boolean;
'data-col-id': string;
'data-cell-selected': true | undefined;
'data-cell-focused': true | undefined;
'data-cell-edge-top': true | undefined;
'data-cell-edge-right': true | undefined;
'data-cell-edge-bottom': true | undefined;
'data-cell-edge-left': true | undefined;
} {
const selected = cell.getIsSelected();
const edges = cell.getSelectionEdges();
return {
'aria-selected': selected,
'data-col-id': cell.column.id,
'data-cell-selected': selected || undefined,
'data-cell-focused': cell.getIsFocused() || undefined,
'data-cell-edge-top': edges.top || undefined,
'data-cell-edge-right': edges.right || undefined,
'data-cell-edge-bottom': edges.bottom || undefined,
'data-cell-edge-left': edges.left || undefined,
};
}
/**
* Selection chrome for a body td, activated by the data attributes above plus
* the imperatively toggled `data-cell-fill-target` (fill-drag preview, written
* outside React like the resize indicator). A ::before overlay, not outline
* or box-shadow: an outline ring hugs the cell box and cannot line up with
* the gridlines the perimeter paints on, and the pinned-column dividers
* already own the cell's shadow slot (tailwind-merge would collapse a second
* shadow-[...] into it).
*/
export const dataGridCellSelectionCellClasses = cn(
'relative select-none',
// A light tint: the selection must read as a range without drowning the
// gridlines under a heavy fill. The focused cell stays unfilled. Pinned
// cells must stay OPAQUE (they hide scrolled content), so they get the
// tint pre-mixed over the background, and the focused pinned cell keeps
// a solid background instead of turning transparent.
'data-[cell-selected]:bg-primary/4',
'data-[cell-selected]:data-pinned:bg-[color-mix(in_oklab,var(--primary)_4%,var(--background))]',
'data-[cell-focused]:bg-transparent!',
'data-[cell-focused]:data-pinned:bg-background!',
// Every selection line is one layout-free ::before overlay per cell. It
// reaches 1px BEYOND the cell so each line paints exactly ON the shared
// gridline it replaces: the range perimeter and the interior dividers
// share this geometry, so where they meet they coincide instead of
// stacking into a wider edge, every side stays exactly 1px, and
// selecting never adds real borders that shift layout. At the table's
// own boundary there is no shared gridline and the overshoot leaves the
// scrollable content box, where it is CLIPPED - the perimeter simply
// vanished on the first column, last column and last row. So every
// overshoot that can hit a boundary goes through a variable the
// boundary cells zero out. Longhand inset utilities only, logical
// start/end
// so RTL mirrors for free; a separate override rule cannot do this,
// equal-specificity variants leave shorthand-vs-longhand to sort order.
"data-[cell-selected]:before:pointer-events-none data-[cell-selected]:before:absolute data-[cell-selected]:before:top-[var(--data-grid-overlay-top,-1px)] data-[cell-selected]:before:start-[var(--data-grid-overlay-start,-1px)] data-[cell-selected]:before:end-[var(--data-grid-overlay-end,-1px)] data-[cell-selected]:before:bottom-[var(--data-grid-overlay-bottom,-1px)] data-[cell-selected]:before:border-primary data-[cell-selected]:before:content-['']",
"data-[cell-focused]:before:pointer-events-none data-[cell-focused]:before:absolute data-[cell-focused]:before:top-[var(--data-grid-overlay-top,-1px)] data-[cell-focused]:before:start-[var(--data-grid-overlay-start,-1px)] data-[cell-focused]:before:end-[var(--data-grid-overlay-end,-1px)] data-[cell-focused]:before:bottom-[var(--data-grid-overlay-bottom,-1px)] data-[cell-focused]:before:border-primary data-[cell-focused]:before:content-['']",
// Interior dividers: selected cells repaint their own end and bottom
// gridlines on the overlay, so gridline-less grids still divide a range.
// The gray color is guarded by not- variants (higher specificity), so a
// side that belongs to the range perimeter deterministically stays
// primary.
'data-[cell-selected]:before:border-e data-[cell-selected]:before:border-b',
'data-[cell-selected]:not-data-[cell-edge-right]:before:border-e-border',
'data-[cell-selected]:not-data-[cell-edge-bottom]:before:border-b-border',
// The Sheets model: a single selected cell IS its own range, so the four
// edge attributes below already draw its full primary box; inside a
// larger range the anchor reads by its unfilled background alone. The
// explicit ring only covers a focused cell with no selection at all.
// Edge sides are logical (border-e/border-s): the feature derives edges
// from display-order column indexes, which mirror in RTL.
'data-[cell-focused]:not-data-[cell-selected]:before:border',
'data-[cell-edge-top]:before:border-t data-[cell-edge-right]:before:border-e data-[cell-edge-bottom]:before:border-b data-[cell-edge-left]:before:border-s',
// While a fill drag is live the preview border is the ONE painter for
// the whole pending region, so the source cells' own chrome rests -
// otherwise its lines double against the region border at every shared
// edge. display is the no-cascade-fight switch (see below).
'in-data-[cell-filling]:data-[cell-selected]:before:hidden',
'in-data-[cell-filling]:data-[cell-focused]:before:hidden',
// While the built-in editor is open its outline is the one border; the
// edited cell's own overlay chrome hides so nothing peeks around the
// flush editor. display is the switch because no other before: rule
// sets it, so there is no cascade order to lose.
'in-data-[cell-editing]:data-[cell-focused]:before:hidden',
// Clamped to the cell edge at the grid's own boundary, the overlay's
// lines sit flush against the container border instead of being clipped
// away outside the scrollable content. A custom property has no cascade
// fight to lose. First/last-child cover the boundary columns: when a
// filler td follows the last data column, that cell's overshoot lands
// INSIDE the table and needs no clamp, and the td:first/last-child of a
// row are its logical start/end in RTL too.
'in-[tr:last-child]:[--data-grid-overlay-bottom:0px]',
// The top overshoot lands under a sticky header, which is positioned and
// paints over it - so the first row's perimeter lost its top line. Clamp
// inside the cell there, exactly like the other three boundaries.
'in-[tr:first-child]:[--data-grid-overlay-top:0px]',
'first:[--data-grid-overlay-start:0px]',
'last:[--data-grid-overlay-end:0px]',
// A pinned column is a boundary like the grid's own edges: the sticky
// neighbor would cover an on-gridline overlay line, and re-painting it
// from the pinned side doubles into a 2px blur whenever subpixel
// positions disagree (browser zoom, fractional fill widths). One
// painter instead: the overlay clamps inside its own cell there, the
// same custom-property clamp the first and last cells use.
'[&:has(+td[data-pinned])]:[--data-grid-overlay-end:0px]',
'[&:has(+[data-slot=data-grid-table-fill-body-cell]:last-child)]:[--data-grid-overlay-end:0px]',
'[&:has(+[data-slot=data-grid-table-fill-body-cell]+td[data-pinned])]:[--data-grid-overlay-end:0px]',
'[td[data-pinned]+&]:[--data-grid-overlay-start:0px]',
// Tint only: the dashed region outline is one overlay element drawn by
// the fill session, so neighboring target cells never double their edges.
'data-[cell-fill-target]:bg-primary/4',
'data-[cell-fill-target]:data-pinned:bg-[color-mix(in_oklab,var(--primary)_4%,var(--background))]',
);
export type DataGridApiFetchParams = {
pageIndex: number;
pageSize: number;
sorting?: SortingState;
filters?: ColumnFiltersState;
searchQuery?: string;
};
export type DataGridApiResponse<T> = {
data: T[];
empty: boolean;
pagination: {
total: number;
page: number;
};
};
/**
* Everything `<DataGrid>` accepts except the two props the provider consumes
* itself. Kept feature-agnostic: layout and messaging never depend on which
* TanStack features the consumer registered.
*/
export type DataGridLayoutProps<TData extends object> = Omit<DataGridProps<TableFeatures, TData>, 'table' | 'children'>;
export interface DataGridContextProps<TData extends object> {
props: DataGridLayoutProps<TData>;
table: DataGridTableInstance<TData>;
recordCount: number;
isLoading: boolean;
/** Stable per-grid prefix for the DOM ids ARIA relations point at. */
gridId: string;
/** The merged label set; components read `i18n.labels.<key>`. */
i18n: DataGridI18nConfig;
/**
* Internal coordinator for `meta.autoSize` columns. Lives at the core level
* so every table variant and viewport instance shares one application state.
*/
autoSize?: DataGridAutoSizeController;
}
/**
* Row and column ids are consumer strings; DOM ids cannot carry spaces or
* quotes. One shared sanitizer so `aria-activedescendant` writers and the id
* renderers always agree on the same encoding.
*/
export function toDataGridDomId(value: string): string {
return value.replace(/[^\w-]/g, '_');
}
export type DataGridAutoSizeController = {
/**
* Feeds the controller one viewport measurement: the SIGNED free space
* between the scroll container and the table, negative while the table
* overflows. The first sight of a `meta.autoSize` column absorbs the
* free space into its width; after that, every measurement REFLOWS the
* same growth - a wider window widens the column, a narrower one gives
* the space back down to the column's `minSize` (or its starting width
* when none is set) - so the grid tracks its container live. Commits
* are coalesced for performance: sub-pixel deltas are dropped, a
* streaming resize gets one leading commit plus one trailing commit at
* settle, and a width the user dragged is never touched. Safe to call
* from every viewport measurement; returns true when a sizing update
* was dispatched.
*/
apply: (freeSpace: number) => boolean;
};
type DataGridAutoSizeReflowState = {
applied: { columnId: string; base: number; grown: number } | null;
settleTimer: ReturnType<typeof setTimeout> | null;
pendingFreeSpace: number;
lastCommitAt: number;
};
/**
* Bookkeeping keyed on the TABLE STORE, never on a React instance: dev
* StrictMode double-mounts the tree, so two controller instances serve one
* page and only the first would remember what it absorbed - the second
* reads the grown width as a user drag and freezes the column. The store
* object is the one identity that provably survives that dance (the
* absorbed sizing rides inside it), and the WeakMap lets a discarded
* table take its bookkeeping with it.
*/
const dataGridAutoSizeStates = new WeakMap<object, DataGridAutoSizeReflowState>();
function getDataGridAutoSizeState(store: object): DataGridAutoSizeReflowState {
let state = dataGridAutoSizeStates.get(store);
if (!state) {
state = {
applied: null,
settleTimer: null,
pendingFreeSpace: 0,
lastCommitAt: 0,
};
dataGridAutoSizeStates.set(store, state);
}
return state;
}
function createDataGridAutoSizeController<TData extends object>(
/**
* A getter, not the table itself.
*
* v8 handed back one stable table whose state mutated in place, so a
* controller could close over it. v9 returns a NEW table wrapper on every
* state change, and a captured one keeps reporting the state it was built
* with - here that meant `columnSizing` looked permanently empty, the
* applied-once guard re-armed on every measurement, and the fill overwrote
* whatever width the user had just dragged the column to.
*/
getTable: () => DataGridTableInstance<TData>,
): DataGridAutoSizeController {
// Reflow coalescing: a live window drag streams a measurement per frame,
// and every accepted commit re-renders the table. One leading commit
// keeps single snaps (a maximize) instant; the rest of the stream parks
// its latest value behind one trailing timer, so a continuous drag costs
// two commits instead of sixty a second. The trailing timer may fire
// after the grid unmounts; it re-reads the table then, and a sizing
// write to the consumer's store is inert once nothing renders it.
const SETTLE_MS = 150;
const reflow = (freeSpace: number): boolean => {
const table = getTable();
const state = getDataGridAutoSizeState(table.store);
// LIVE state, never the render snapshot: a measurement can run between
// our own sizing commit and React's re-render, and the stale snapshot
// would hide the width this controller just wrote.
const columnSizing = table.atoms.columnSizing?.get() ?? table.state.columnSizing;
if (!state.applied) return false;
const autoSizeColumn = table.getVisibleLeafColumns().find((column) => column.columnDef.meta?.autoSize && column.getCanResize());
if (!autoSizeColumn || autoSizeColumn.id !== state.applied.columnId) return false;
// A width this coordinator did not write belongs to the user's drag;
// reflow stands down until a reset re-arms the column.
const currentSize = columnSizing[state.applied.columnId];
if (currentSize !== undefined && currentSize !== state.applied.grown) {
return false;
}
// The free space as it would measure with our growth removed; the
// target re-absorbs exactly that, floored at minSize so a narrow
// window hands space back without ever crushing the column (no
// explicit minSize floors at the starting width instead).
const freeAtBase = freeSpace + (state.applied.grown - state.applied.base);
const floor = autoSizeColumn.columnDef.minSize ?? state.applied.base;
const target = Math.max(floor, state.applied.base + freeAtBase);
if (Math.abs(target - state.applied.grown) < 1) return false;
state.applied = { ...state.applied, grown: target };
table.setColumnSizing((old) => ({
...old,
[state.applied!.columnId]: target,
}));
return true;
};
return {
apply(freeSpace: number) {
const table = getTable();
const state = getDataGridAutoSizeState(table.store);
// Same live read as `reflow`; the snapshot race is what made the
// re-arm check clear the bookkeeping right after the first absorb.
const columnSizing = table.atoms.columnSizing?.get() ?? table.state.columnSizing;
// Re-arm after reset flows (double-click resetSize, resetColumnSizing,
// controlled state replacement) so the column re-fills instead of
// leaving a dead blank strip.
if (state.applied && columnSizing[state.applied.columnId] === undefined) {
state.applied = null;
}
const autoSizeColumn = table.getVisibleLeafColumns().find((column) => column.columnDef.meta?.autoSize && column.getCanResize());
if (autoSizeColumn && state.applied?.columnId === autoSizeColumn.id) {
state.pendingFreeSpace = freeSpace;
const now = Date.now();
if (now - state.lastCommitAt > SETTLE_MS) {
state.lastCommitAt = now;
return reflow(freeSpace);
}
if (state.settleTimer !== null) clearTimeout(state.settleTimer);
state.settleTimer = setTimeout(() => {
state.settleTimer = null;
state.lastCommitAt = Date.now();
reflow(state.pendingFreeSpace);
}, SETTLE_MS);
return false;
}
const fillWidth = Math.max(0, freeSpace);
if (fillWidth <= 0) return false;
if (!autoSizeColumn) {
return false;
}
// A width this coordinator did not write belongs to someone else -
// almost always the user, who just dragged the column's resize handle.
// Filling over it is what made a `meta.autoSize` column look
// un-resizable: the drag committed, the next viewport measurement
// stamped the fill back on top, and the column snapped to its old width.
//
// Deliberately keyed on observed state rather than on `state.applied`, which
// is per-coordinator memory: anything that rebuilds the coordinator
// (a remount, a new table store) forgets what it did, and the guard has
// to survive that. An explicit reset clears the entry and re-arms the
// fill, which is what makes double-click-to-reset still work.
const currentSize = columnSizing[autoSizeColumn.id];
if (currentSize !== undefined && currentSize !== state.applied?.grown) {
return false;
}
// Candidate switched (e.g. the grown column was hidden and another
// meta.autoSize column took over): revert the previous growth if the
// user hasn't manually resized that column since, so visibility
// toggles cannot ratchet the table wider than its container forever.
const revert = state.applied && columnSizing[state.applied.columnId] === state.applied.grown ? state.applied : null;
const base = columnSizing[autoSizeColumn.id] ?? autoSizeColumn.getSize();
const grown = base + fillWidth;
state.applied = { columnId: autoSizeColumn.id, base, grown };
table.setColumnSizing((old) => {
const next = { ...old, [autoSizeColumn.id]: grown };
if (revert && next[revert.columnId] === revert.grown) {
next[revert.columnId] = revert.base;
}
return next;
});
return true;
},
};
}
export type DataGridRequestParams = {
pageIndex: number;
pageSize: number;
sorting?: SortingState;
columnFilters?: ColumnFiltersState;
};
/** Which spreadsheet operation produced a cell change batch. */
export type DataGridCellsChangeSource = 'paste' | 'cut' | 'clear' | 'fill' | 'edit';
export interface DataGridCellChange<TData> {
rowId: string;
columnId: string;
/** The consumer's row object, so immutable write-back needs no second lookup. */
row: TData;
/** Accessor value at dispatch time; enables consumer-side undo stacks. */
previousValue: unknown;
/** Typed value produced by `meta.cellEdit.parse`, or `clearValue` for clear/cut. */
value: unknown;
}
/** What onCellsCopy receives after the grid writes the clipboard. */
export interface DataGridCopyDetails {
/** The TSV text that reached the clipboard. */
text: string;
/** The same content as a row-major grid of formatted fields. */
grid: string[][];
/** True when the write came from a cut, which clears the region next. */
cut: boolean;
}
/** One resolved positive region, in pre-paginated display indexes. */
export interface DataGridCellSelectionBound {
minRowIndex: number;
maxRowIndex: number;
minColumnIndex: number;
maxColumnIndex: number;
}
/** What onCellSelectionChange receives, resolved from the live selection. */
export interface DataGridCellSelectionSnapshot {
/** The virtually focused cell, the active range's anchor. Null when clear. */
focused: { rowId: string; columnId: string } | null;
/** Every positive region, geometric order. */
bounds: DataGridCellSelectionBound[];
/** The most recent region, the one copy and paste act on. */
activeBound: DataGridCellSelectionBound | null;
/**
* Cells of the selection the view can show - the count that matches the
* painted range and what a batch will touch.
*/
visibleCellCount: number;
}
export interface DataGridCellRejection {
rowId: string;
columnId: string;
raw: string;
reason: 'readonly' | 'invalid';
}
/**
* Lifecycle of a row for the optional CRUD indications: "new" and "dirty"
* tint the row, "deleted" mutes and strikes it. Purely presentational - the
* consumer's state stays the only owner of what the statuses mean.
*/
export type DataGridRowStatus = 'new' | 'dirty' | 'deleted';
/**
* Lifecycle of a cell for the optional CRUD indications: a corner mark in
* the amber tone for "dirty", the destructive tone for "invalid".
*/
export type DataGridCellStatus = 'dirty' | 'invalid';
/**
* Asks the consumer to open its editor for the focused cell: Enter or F2, or
* a typed printable character (then `initialText` carries it, the
* Notion/Airtable type-to-replace flow). Dispatched only for cells whose
* column is writable via `meta.cellEdit`.
*/
export interface DataGridCellEditRequest<TData> {
rowId: string;
columnId: string;
row: TData;
previousValue: unknown;
/** The typed character that started the edit; absent for Enter and F2. */
initialText?: string;
}
/**
* One batch per operation, however many cells it spans: a 10k-cell paste is
* one callback, one consumer setState, one table rebuild. The grid never
* writes data itself.
*/
export interface DataGridCellsChangeDetails<TData> {
source: DataGridCellsChangeSource;
changes: DataGridCellChange<TData>[];
rejected: DataGridCellRejection[];
}
export interface DataGridProps<TFeatures extends TableFeatures, TData extends object> {
className?: string;
table?: Table<TFeatures, TData>;
recordCount: number;
children?: ReactNode;
onRowClick?: (row: TData) => void;
/**
* Receives every spreadsheet write batch (paste, cut, clear, fill, edit).
* Served through the props getter like `onRowClick`, so an inline identity
* never republishes the context. Absent: copy still works, writes no-op.
*/
onCellsChange?: (details: DataGridCellsChangeDetails<TData>) => void;
/**
* Opens the consumer's editor from the keyboard: Enter, F2, or typing on
* the focused cell. Absent: Enter keeps moving down, typing does nothing.
*/
onCellEditRequest?: (request: DataGridCellEditRequest<TData>) => void;
/**
* Fires on every cell-selection change (focus moves, ranges grow or
* clear) with a resolved snapshot, so a selection count, formula bar or
* context panel needs no reach into TanStack internals.
*/
onCellSelectionChange?: (snapshot: DataGridCellSelectionSnapshot) => void;
/**
* Fires after the grid writes the clipboard (Cmd/Ctrl+C or X, or the
* native copy and cut events), e.g. to confirm with a toast.
*/
onCellsCopy?: (details: DataGridCopyDetails) => void;
/**
* Renders an "Add row" affordance as the table body's last row; clicking
* it is the consumer's cue to start creating a row. Absent: no row.
*/
onRowCreate?: () => void;
/** Label of the onRowCreate affordance. Defaults to "Add row". */
rowCreateLabel?: ReactNode;
/**
* Rendered inside the table body after the data rows: the slot a DRAFT
* row lives in while it is being created, before it joins `data` and the
* pagination math. Supply a `<tr>` of cells; the colgroup sizes them.
*/
appendRow?: ReactNode;
/**
* Optional CRUD indication per row. Return undefined for no indication;
* omit the prop entirely to render none anywhere.
*/
getRowStatus?: (row: TData) => DataGridRowStatus | undefined;
/**
* Optional CRUD indication per cell: the classic corner mark on cells the
* consumer tracks as edited or invalid.
*/
getCellStatus?: (row: TData, columnId: string) => DataGridCellStatus | undefined;
isLoading?: boolean;
/**
* Overrides for every built-in string: menu items, aria labels,
* pagination copy, state messages. Merged over the defaults; a more
* specific component prop (`rowCreateLabel`, `loadingMessage`, the
* pagination label props) still wins over its `i18n` counterpart.
*/
i18n?: DataGridI18nOverrides;
loadingMode?: 'skeleton' | 'spinner';
loadingMessage?: ReactNode | string;
fetchingMoreMessage?: ReactNode | string;
allRowsLoadedMessage?: ReactNode | string;
emptyMessage?: ReactNode | string;
tableLayout?: {
dense?: boolean;
cellBorder?: boolean;
rowBorder?: boolean;
rowRounded?: boolean;
stripped?: boolean;
headerBackground?: boolean;
footerBackground?: boolean;
headerBorder?: boolean;
headerSticky?: boolean;
width?: 'auto' | 'fixed';
columnsVisibility?: boolean;
columnsResizable?: boolean;
columnsResizeMode?: 'onChange' | 'onEnd';
columnsPinnable?: boolean;
columnsMovable?: boolean;
columnsDraggable?: boolean;
rowsDraggable?: boolean;
rowsPinnable?: boolean;
/** Spreadsheet cell range selection: mouse ranges, keyboard, clipboard chrome. */
cellSelection?: boolean;
/**
* "range" (default): drag, Shift and Ctrl/Cmd gestures and Shift+keys
* grow multi-cell regions. "single": one focused cell only - every
* gesture collapses to it and Ctrl/Cmd+A is inert.
*/
cellSelectionMode?: 'single' | 'range';
/** Drag-to-fill handle on the selection corner. Requires cellSelection. */
cellFillHandle?: boolean;
/**
* How a cell opens its editor from the mouse: "dblclick" (default,
* the spreadsheet standard - first click focuses, second edits) or
* "click", opening the editor as soon as a plain click lands on the
* focused cell; modifier clicks and drags still select.
*/
cellEditMode?: 'dblclick' | 'click';
/**
* When true, committing an edit with Enter moves focus down (Shift+Enter
* up), the Sheets and Excel convention. Off by default: the commit keeps
* focus on the edited cell. Tab always commits and moves across.
*/
cellEditEnterAdvance?: boolean;
/**
* The handle's look: "dot" is a solid primary dot kept inside the
* cell corner; "ring" is the Sheets-style hollow circle riding the
* corner point, clamped at the grid's own boundary; "square" is the
* Excel-style solid square inside the corner. Default "dot".
*/
cellFillHandleVariant?: 'dot' | 'ring' | 'square';
};
tableClassNames?: {
base?: string;
header?: string;
headerRow?: string;
headerSticky?: string;
body?: string;
bodyRow?: string;
footer?: string;
edgeCell?: string;
/** Override the getRowStatus tints; defaults are the warning-muted set. */
rowNew?: string;
rowDirty?: string;
rowDeleted?: string;
/**
* Override the pinned-row chrome (muted tint, boundary shadow). A grid
* that pins a draft row for quick-create wants it to read as an active
* row, not a muted one.
*/
rowPinned?: string;
/** The onRowCreate affordance row, e.g. to match the grid's row height. */
rowCreate?: string;
/** The fill handle, e.g. to restyle or resize it beyond the built-in variants. */
cellFillHandle?: string;
};
}
const DataGridContext = createContext<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
DataGridContextProps<any> | undefined
>(undefined);
/**
* Reads the grid context. Pass `TData` from the calling component when the
* table, a row or a cell is handed on to something typed against that row
* shape: v9 declares `TData` invariant, so the default `any` no longer
* unifies with a concrete row type the way it did on v8.
*/
function useDataGrid<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TData extends object = any,
>(): DataGridContextProps<TData> {
const context = useContext(DataGridContext) as DataGridContextProps<TData> | undefined;
if (!context) {
throw new Error('useDataGrid must be used within a DataGridProvider');
}
return context;
}
function DataGridProvider<TData extends object>({
children,
table,
...props
}: DataGridLayoutProps<TData> & {
table: DataGridTableInstance<TData>;
children?: ReactNode;
}) {
// Latest-props ref: context reads always resolve fresh props through the
// getter below without the memoized context value depending on unstable
// Stable for the grid's lifetime; ARIA ids and relations hang off it.
const gridId = useId();
// ReactNode/function prop identities (inline emptyMessage/onRowClick would
// otherwise publish a new context value on every consumer render - at
// mousemove rate during a resize drag, piercing the body-rows memo).
const propsRef = useRef(props);
propsRef.current = props;
const i18n = mergeDataGridI18n(props.i18n);
const i18nRef = useRef(i18n);
i18nRef.current = i18n;
// Same treatment for the table itself, which v9 - unlike v8 - re-creates on
// every state change. Depending on it directly would republish the context
// on each resize tick, which is exactly what the memo below exists to
// prevent; the getter still hands every consumer the current instance.
const tableRef = useRef(table);
tableRef.current = table;
// Re-assert an explicit tableLayout resize mode so consumer-level useTable
// options cannot flip it back between drags. v9 makes `table.options`
// readonly, so this goes through setOptions in an effect rather than a
// render-phase mutation. Without an explicit mode, the consumer's own
// tanstack columnResizeMode (default "onEnd") is honored.
const resizeMode = props.tableLayout?.columnsResizable && props.tableLayout.columnsResizeMode ? props.tableLayout.columnsResizeMode : undefined;
useEffect(() => {
if (!resizeMode) return;
if (table.options.columnResizeMode === resizeMode) return;
table.setOptions((old) => ({ ...old, columnResizeMode: resizeMode }));
}, [table, resizeMode]);
// With the selection UI on, every paste/fill/clear batch replaces `data`,
// and the feature's default autoResetCellSelection would wipe the selection
// after each write. Ranges are row-id based and unresolvable ids drop out
// of the bounds safely, so keeping state across data edits is the correct
// default here.
const cellSelectionOn = !!props.tableLayout?.cellSelection;
useEffect(() => {
if (!cellSelectionOn || table.atoms.cellSelection == null) return;
if (table.options.autoResetCellSelection === false) return;
table.setOptions((old) => ({ ...old, autoResetCellSelection: false }));
}, [table, cellSelectionOn]);
// Rendered row indexes re-base per page, so a range kept across a page flip
// re-lights the same positions over different rows. A page change clears
// the selection instead - the rule Excel-family grids apply to paginated
// range selection.
const pageKey = `${table.state.pagination?.pageIndex}:${table.state.pagination?.pageSize}`;
const previousPageKeyRef = useRef(pageKey);
useEffect(() => {
if (previousPageKeyRef.current === pageKey) return;
previousPageKeyRef.current = pageKey;
if (!cellSelectionOn || table.atoms.cellSelection == null) return;
tableRef.current.resetCellSelection(true);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pageKey, cellSelectionOn]);
// One autoSize coordinator per table instance so split header/body viewports
// cannot apply the growth twice. Keyed on `table.store`, which v9 keeps
// stable for the life of the table, rather than on `table` itself: the
// wrapper is re-created on every state change, and re-creating the
// controller with it would reset its applied-once bookkeeping mid-drag.
const autoSize = useMemo(() => createDataGridAutoSizeController(() => tableRef.current), [table.store]);
const tableState = table.state;
// Memoize context value so consumers don't re-render during column resize.
// Column sizing state is intentionally excluded from deps -- CSS variables
// on the <table> element handle width updates without React re-renders.
// ReactNode/function props (messages, onRowClick) are also excluded: they
// are served fresh through the props getter, so unstable inline identities
// cannot invalidate the context value.
// `cellSelection` state is excluded on purpose too: a drag writes it once
// per cell crossed, and nothing reads it through context - cells and the
// selection bar subscribe to `table.atoms.cellSelection` directly.
const value = useMemo(
() => ({
get props() {
return propsRef.current;
},
get table() {
return tableRef.current;
},
get i18n() {
return i18nRef.current;
},
recordCount: props.recordCount,
isLoading: props.isLoading || false,
gridId,
autoSize,
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[
autoSize,
props.recordCount,
props.isLoading,
props.loadingMode,
props.className,
// eslint-disable-next-line react-hooks/exhaustive-deps
JSON.stringify(props.tableLayout),
// eslint-disable-next-line react-hooks/exhaustive-deps
JSON.stringify(props.tableClassNames),
tableState.sorting,
tableState.pagination,
tableState.columnFilters,
tableState.rowSelection,
tableState.rowPinning,
tableState.expanded,
tableState.columnVisibility,
tableState.columnOrder,
tableState.columnPinning,
tableState.globalFilter,
],
);
return (
// One React context serves every TData, but v9 declares both TFeatures and
// TData invariant, so a `DataGridContextProps<any>` context cannot accept a
// `DataGridContextProps<TData>` value structurally. The erasure happens
// here and is undone by the TData generic on each consumer component.
<DataGridContext.Provider value={value as unknown as DataGridContextProps<TData>}>{children}</DataGridContext.Provider>
);
}
function DataGrid<TFeatures extends TableFeatures, TData extends object>({ children, table, ...props }: DataGridProps<TFeatures, TData>) {
const defaultProps: Partial<DataGridProps<TFeatures, TData>> = {
loadingMode: 'skeleton',
tableLayout: {
dense: false,
cellBorder: false,
rowBorder: true,
rowRounded: false,
stripped: false,
headerSticky: false,
headerBackground: false,
footerBackground: false,
headerBorder: true,
width: 'fixed',
columnsVisibility: false,
columnsResizable: false,
// columnsResizeMode has no default on purpose: when unset, the
// consumer's tanstack columnResizeMode (default "onEnd") is honored.
columnsPinnable: false,
columnsMovable: false,
columnsDraggable: false,
rowsDraggable: false,
rowsPinnable: false,
cellSelection: false,
cellFillHandle: false,
},
tableClassNames: {
base: '',
header: '',
headerRow: '',
// z-40 keeps the sticky header above pinned body cells (zIndex 30 in
// getPinningStyles), which would otherwise paint over it while
// scrolling vertically with columnsPinnable enabled.
headerSticky: 'sticky top-0 z-40 bg-background/90 backdrop-blur-xs',
body: '',
bodyRow: '',
footer: '',
edgeCell: '',
},
};
const mergedProps: DataGridProps<TFeatures, TData> = {
...defaultProps,
...props,
tableLayout: {
...defaultProps.tableLayout,
...(props.tableLayout || {}),
},
tableClassNames: {
...defaultProps.tableClassNames,
...(props.tableClassNames || {}),
},
};
// Ensure table is provided
if (!table) {
throw new Error('DataGrid requires a "table" prop');
}
// The single widening point. Consumers own the TanStack core and may hand
// over any feature bundle; internals need a concrete one to resolve the
// feature-gated APIs they call, and v9's invariant TFeatures rules out
// expressing that with a generic constraint.
const internalTable = table as unknown as DataGridTableInstance<TData>;
const internalProps = mergedProps as unknown as DataGridLayoutProps<TData>;
return (
<DataGridProvider table={internalTable} {...internalProps}>
{children}
</DataGridProvider>
);
}
function DataGridContainer({
children,
className,
}: {
children: ReactNode;
className?: string;
/** Accepted for backwards compatibility; currently has no effect. */
border?: boolean;
}) {
return (
<div
data-slot="data-grid"
// relative: anchors floating chrome composed inside the container,
// like the fill-drag preview outline.
className={cn('relative w-full overflow-hidden', className)}
>
{children}
</div>
);
}
export { useDataGrid, DataGridProvider, DataGrid, DataGridContainer };Usage
import { useDataGrid, DataGridProvider, DataGrid, DataGridContainer } from "@/components/ui/data-grid/data-grid"Exports
useDataGrid, DataGridProvider, DataGrid, DataGridContainer
Dependencies
@base-ui/react@^1.9.0(npm)@dnd-kit/core@^6.3.1(npm)@dnd-kit/modifiers@^9.0.0(npm)@dnd-kit/sortable@^10.0.0(npm)@dnd-kit/utilities@^3.2.2(npm)@tanstack/react-table@^9.3.1(npm)@tanstack/react-virtual@^3.14.28(npm)lucide-react@^1.80.0(npm)@vcare/button(registry)@vcare/checkbox(registry)@vcare/dropdown-menu(registry)@vcare/input(registry)@vcare/popover(registry)@vcare/reui-badge(registry)@vcare/select(registry)@vcare/separator(registry)@vcare/skeleton(registry)@vcare/spinner(registry)@vcare/utils(registry)
Raw item: /r/data-grid.json