From bc3b56d6159ef79b8985cd20b9424fdae1f5c275 Mon Sep 17 00:00:00 2001 From: Albert Nimtz Date: Thu, 26 Nov 2026 23:02:56 +0100 Subject: [PATCH 01/12] feat(table-core): add opt-in sparseRowsFeature for remote tables A remote table can now show row 99,999 without loading the rows before it. With `sparseRowsFeature` registered, `data` holds the loaded rows at their absolute index and `rowCount` is the total. The core row model has `rowCount` rows, and each index without data gets a placeholder row, so `getCoreRowModel().rows[i].index === i`. - `row.getIsPlaceholder()` tells a placeholder row from a loaded row. - `table.getMissingRowRanges({ startIndex, endIndex, blockSize? })` returns the ranges to load. `blockSize` aligns them to block bounds. - A placeholder row has a temporary id and no values. Row selection, cell selection, pinning, and expanding keep no state for it. - The default `getColumnCanGlobalFilter` reads loaded rows only, so it does not build the cells of placeholder rows. - The sparse row model does not run the `autoReset*` behaviors when more rows are loaded. - Development warnings report client-side filtered, grouped, or sorted row models and duplicate `getRowId` results among loaded rows. The feature is not part of `stockFeatures`, so tables that do not register it keep their behavior. Discussion: https://github.com/TanStack/table/discussions/6657 Co-Authored-By: Claude Fable 5.2 --- .changeset/sparse-rows-feature.md | 5 + docs/config.json | 1 + docs/guide/features.md | 6 + docs/guide/sparse-rows.md | 173 +++ packages/table-core/src/core/featureStubs.ts | 34 + .../row-models/coreRowModelsFeature.utils.ts | 6 +- .../src/core/rows/coreRowsFeature.utils.ts | 6 +- .../cellSelectionFeature.utils.ts | 78 +- .../globalFilteringFeature.ts | 5 +- .../rowExpandingFeature.utils.ts | 7 + .../row-pinning/rowPinningFeature.utils.ts | 9 +- .../rowSelectionFeature.utils.ts | 14 +- .../features/sparse-rows/sparseRowsFeature.ts | 35 + .../sparse-rows/sparseRowsFeature.types.ts | 63 + .../sparse-rows/sparseRowsFeature.utils.ts | 219 +++ packages/table-core/src/index.ts | 4 + packages/table-core/src/static-functions.ts | 1 + packages/table-core/src/types/Row.ts | 2 + packages/table-core/src/types/Table.ts | 2 + .../table-core/src/types/TableFeatures.ts | 17 +- packages/table-core/src/types/TableOptions.ts | 4 + .../sparse-rows/sparseRowsFeature.test.ts | 1193 +++++++++++++++++ .../sparseRowsFeature.utils.test.ts | 311 +++++ 23 files changed, 2176 insertions(+), 19 deletions(-) create mode 100644 .changeset/sparse-rows-feature.md create mode 100644 docs/guide/sparse-rows.md create mode 100644 packages/table-core/src/features/sparse-rows/sparseRowsFeature.ts create mode 100644 packages/table-core/src/features/sparse-rows/sparseRowsFeature.types.ts create mode 100644 packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts create mode 100644 packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts create mode 100644 packages/table-core/tests/unit/features/sparse-rows/sparseRowsFeature.utils.test.ts diff --git a/.changeset/sparse-rows-feature.md b/.changeset/sparse-rows-feature.md new file mode 100644 index 0000000000..d97e3f40ee --- /dev/null +++ b/.changeset/sparse-rows-feature.md @@ -0,0 +1,5 @@ +--- +'@tanstack/table-core': minor +--- + +Add the opt-in `sparseRowsFeature` for remote tables: `data` holds the loaded rows by their absolute index, `rowCount` is the total, missing rows become placeholder rows (`row.getIsPlaceholder()`), and `table.getMissingRowRanges()` returns the ranges to load. diff --git a/docs/config.json b/docs/config.json index 2625aaeae7..27e6426fa9 100644 --- a/docs/config.json +++ b/docs/config.json @@ -101,6 +101,7 @@ { "label": "Table Instance", "to": "guide/tables" }, { "label": "Row Models", "to": "guide/row-models" }, { "label": "Worker Row Models (Experimental)", "to": "guide/worker-row-models" }, + { "label": "Sparse Rows", "to": "guide/sparse-rows" }, { "label": "Rows", "to": "guide/rows" }, { "label": "Cells", "to": "guide/cells" }, { "label": "Header Groups", "to": "guide/header-groups" }, diff --git a/docs/guide/features.md b/docs/guide/features.md index 8b21d0d9b5..0044facfc3 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -131,4 +131,10 @@ Because this imports the complete collection, it includes all stock feature code These are the features included by `stockFeatures`. Fuzzy filtering is a filtering recipe built from the filtering and sorting features, while virtualization is provided by TanStack Virtual rather than a Table feature. +## Opt-In Features + +- `sparseRowsFeature`: [Sparse Rows](./sparse-rows) lets `data` hold only the loaded rows of a remote table and fills the gaps with placeholder rows. + +`stockFeatures` does not include this feature, because it changes how the table reads `data` and `rowCount`. Register it by name. + To build and type your own plugin, see the framework-specific [Custom Plugins guide](../framework/react/guide/custom-features). diff --git a/docs/guide/sparse-rows.md b/docs/guide/sparse-rows.md new file mode 100644 index 0000000000..16a363929d --- /dev/null +++ b/docs/guide/sparse-rows.md @@ -0,0 +1,173 @@ +--- +title: Sparse Rows Guide +--- + +## What It Does + +A remote table usually loads its rows from the start: the first page, then the second page, and so on. `data` cannot have gaps, so to show row 99,999 of 100,000 the app must first load every row before it. + +`sparseRowsFeature` removes that limit. `data` holds only the rows that are loaded, each at its absolute index on the server, and `rowCount` is the total. The core row model then has `rowCount` rows, and each index without data gets a placeholder row. `table.getCoreRowModel().rows[i]` is always row `i` on the server, and so is `table.getRowModel().rows[i]` when the table does not cut pages or add expanded sub-rows. A virtualizer gets the correct scrollbar length, the user can jump to any position, and the app loads only the rows in view. + +The table does not load data. It tells you which ranges are missing, and you load them, for example with [TanStack Query](https://tanstack.com/query/latest). + +## When To Use It + +- The server returns the total row count and can return rows by offset. +- Sorting and filtering run on the server (`manualSorting` and `manualFiltering`). The usual setup is a virtualized table that also sets `manualPagination`. +- Users must be able to jump to any position, for example by dragging the scrollbar of a virtualized table. + +If the server only supports cursors, or cannot return a total, keep the [infinite scrolling pattern](./client-side-vs-server-side#cursor-based-pagination-with-useinfinitequery). If users only move page by page, normal [server-side pagination](./client-side-vs-server-side) is simpler. + +## Quick Start + +```ts +import { + sparseRowsFeature, + tableFeatures, + useTable, +} from '@tanstack/react-table' + +const features = tableFeatures({ sparseRowsFeature }) + +const table = useTable({ + features, + columns, + data: loadedRowsByIndex, + rowCount: 100_000, + getRowId: (row) => row.id, +}) + +table.getRowModel().rows.length // 100_000 +table.getRowModel().rows[99_999].index // 99_999 +table.getRowModel().rows[99_999].getIsPlaceholder() // true until the row is loaded +table.getMissingRowRanges({ startIndex: 99_950, endIndex: 99_999 }) +// [{ startIndex: 99_950, endIndex: 99_999 }] +``` + +`sparseRowsFeature` is exported from every framework adapter and from `@tanstack/table-core`. It is not part of `stockFeatures`, because it changes how the table reads `data` and `rowCount`. Register it by name. + +The broad `Table` and `Row` types do not include the API of this feature. Use the type of your `features` object, for example `Row`, to call `row.getIsPlaceholder()`. + +## Put Loaded Rows at Their Index + +`data` is a sparse array. Put each loaded row at the index that it has on the server: + +```ts +const data: Array = [] + +for (const block of loadedBlocks) { + block.rows.forEach((row, offset) => { + data[block.startIndex + offset] = row + }) +} +``` + +- A row is missing when its entry in `data` is a hole or `undefined`, or when its index is `data.length` or more. +- `rowCount` is the total number of rows. Without it, the table uses `data.length`. Rows in `data` at index `rowCount` or more are ignored. +- The table builds the core row model again for each new `data` array. This work grows with `rowCount`. Placeholder rows are made only once, so a new block costs much less than the first build. Make a new array only when rows arrive or leave, not on each render. +- To limit memory, you can remove rows that are far from the viewport. They become placeholder rows again. + +## Render Placeholder Rows + +A placeholder row is a normal row object. It has the server `index` and the same cells as a loaded row, so it can render a skeleton with the correct column layout: + +```tsx +const rows = table.getRowModel().rows + +virtualRows.map((virtualRow) => { + const row = rows[virtualRow.index] + + return row.getIsPlaceholder() ? ( + + ) : ( + + ) +}) +``` + +A placeholder row has no data: + +- `row.original` is `undefined`. Its type is still `TData`, so check `row.getIsPlaceholder()` before you read it. +- `row.getValue()` and `cell.getValue()` return `undefined`. The table does not call the column accessors. +- Do not render the `cell` templates of your columns for a placeholder row if they read `row.original`. +- `row.id` is temporary. It starts with `__placeholder_` and changes to the `getRowId` result when the row is loaded. Do not store it. + +## Load the Missing Ranges + +`table.getMissingRowRanges({ startIndex, endIndex })` returns the ranges that `data` has no rows for. Both bounds are included, and the table limits them to the rows that exist. Call it with the visible range when the user scrolls: + +```ts +const BLOCK_SIZE = 50 + +function loadVisibleRows(startIndex: number, endIndex: number) { + const ranges = table.getMissingRowRanges({ + startIndex, + endIndex, + blockSize: BLOCK_SIZE, + }) + + for (const range of ranges) { + // Your code: request the rows, then put them into `data` by index. + loadBlock(range.startIndex, range.endIndex) + } +} +``` + +Without `blockSize`, the result is the exact gaps: `[{ startIndex: 120, endIndex: 160 }]`. + +With `blockSize`, the result has one range for each block that has a missing row in the requested range. Block `n` starts at index `n * blockSize`, so the same block always has the same bounds: `[{ startIndex: 100, endIndex: 149 }, { startIndex: 150, endIndex: 199 }]`. This makes `range.startIndex` a stable cache key, for example `queryKey: ['people', sorting, columnFilters, range.startIndex]`. A block range can be larger than the requested range, but it never goes past the last row. + +A block stays missing until its rows are in `data`, so the same range can be returned again while its request is in progress. Use the cache key to make each request only once. + +`getMissingRowRanges` reads `data` directly. Its cost depends on the size of the requested range, not on `rowCount`. + +## Sorting and Filtering Change the Index Space + +Row 99,999 under one sort order is a different row under another sort order. The loaded rows are only correct for the sorting and filters that they were loaded with. + +- Sort, filter, and group on the server. Set `manualSorting`, `manualFiltering`, and `manualGrouping`, or do not register the client-side row models. A client-side row model only sees the loaded rows, so its result is wrong. The table logs a warning in development when one is active. `manualPagination` is different: client-side pagination keeps the index space, see [Pagination](#pagination). +- When sorting or a filter changes, start again with an empty `data` array and the new `rowCount`. If you load blocks with TanStack Query, put the sorting and filter state into the query key. +- With this feature, a new `data` array does not run the `autoResetPageIndex`, `autoResetExpanded`, and other `autoReset*` behaviors, because a new array usually means that more rows are loaded. Reset the page index or the scroll position yourself when sorting or a filter changes. +- Do not let the table read column behavior from row values, because placeholder rows have no values. Set `sortDescFirst` on the table or on your columns; without it, the first sort direction of a column comes from the values of the first rows. If you use `column.getCanGlobalFilter()`, set `enableGlobalFilter: true` on the columns that the server can search; without it, the table reads the loaded rows until it finds a value, and the result is `false` while no row is loaded. + +## Pagination + +`rowCount` is the same option that `rowPaginationFeature` reads for `table.getRowCount()` and `table.getPageCount()`. The table can show the rows in two ways: + +- **All rows, for a virtualized table.** Set `manualPagination: true`, or do not register `paginatedRowModel`. The table cuts no pages, and `table.getRowModel().rows` has `rowCount` rows. +- **Pages cut on the client.** Register `paginatedRowModel` and leave `manualPagination` off. The paginated row model cuts each page out of the sparse row model, so page 2,000 shows placeholder rows until you load its range. `row.index` is still the server index, but `table.getRowModel().rows[0]` is the first row of the page. + +This changes what normal server-side pagination means. Without this feature, `data` is the current page. With it, `data` is always indexed from row 0, so a `data` array that holds one page means that rows `0` to `pageSize - 1` are loaded and all other rows are placeholder rows. Put each page at its index, as shown in [Put Loaded Rows at Their Index](#put-loaded-rows-at-their-index). + +## Row Selection, Pinning, and Expanding + +Row state is stored by row ID, and a placeholder row only has a temporary ID. The table keeps no state for it: + +- `getCanSelect()`, `getCanMultiSelect()`, `getCanPin()`, and `getCanExpand()` return `false`, and `getIsExpanded()` returns `false`. Option callbacks such as `enableRowSelection` and `getRowCanExpand` are not called with a placeholder row. +- `toggleSelected()`, `pin()`, and `toggleExpanded()` do nothing. +- `toggleAllRowsSelected()` selects the loaded rows only, and `getIsAllRowsSelected()` is about the loaded rows. + +The state of a loaded row stays when you remove the row from `data`. The row is selected, pinned, or expanded again when it is loaded again. `getSelectedRowModel()`, `getTopRows()`, and `getBottomRows()` contain loaded rows only. `getIsAllRowsSelected()` returns `false` while no row is loaded. + +## Cell Selection + +`cellSelectionFeature` stores the two corners of each range by row ID, so a placeholder row cannot be a corner: + +- `cell.getCanSelect()` returns `false` for the cells of a placeholder row, and their selection handlers do nothing. The `enableCellSelection` callback is not called with such a cell. +- `selectCellRange()` and `setFocusedCell()` do nothing when a row ID belongs to a placeholder row. +- `moveCellSelection()` and `extendCellSelection()` stop at a placeholder row. Load the next rows before the user gets to them. +- `selectAllCells()` selects from the first loaded row to the last loaded row. + +A range can span rows that are not loaded. Its corners are loaded rows, and the placeholder rows between them are not selected: `getSelectedCellIds()`, `getSelectedCellCount()`, and `getCellSelectionRowIds()` leave them out. `getSelectedCellRangesData()` keeps the position of each row, so the grid of a range has an empty entry for each placeholder row; skip these entries when you copy the data. The rows become part of the selection when they are loaded. A range whose corner row is removed from `data` stays in state and selects nothing until that row is loaded again. + +## Offset Drift + +If rows are added or removed on the server between two requests, the blocks no longer fit together. They overlap or leave a gap, and the same row can be at two indexes. In development, the table logs a warning when `getRowId` returns the same ID for two loaded rows. + +If your data changes often, send a snapshot or cursor ID with each block request so that all blocks come from the same version of the data, or load the blocks again when you see the warning. + +## Constraints and Behavior + +- A custom `coreRowModel` slot replaces the sparse row model. The table then makes no placeholder rows. +- `getSubRows` is read for loaded rows only. Sub-rows are not part of the server index space. +- `data` has the type `ReadonlyArray`, so build it with holes as shown above. `undefined` entries are also read as missing rows. diff --git a/packages/table-core/src/core/featureStubs.ts b/packages/table-core/src/core/featureStubs.ts index 505ac684e7..af6fe7a575 100644 --- a/packages/table-core/src/core/featureStubs.ts +++ b/packages/table-core/src/core/featureStubs.ts @@ -22,6 +22,10 @@ import type { } from '../features/row-expanding/rowExpandingFeature.types' import type { Table_RowPagination } from '../features/row-pagination/rowPaginationFeature.types' import type { Table_RowSorting } from '../features/row-sorting/rowSortingFeature.types' +import type { + Row_SparseRows, + Table_SparseRows, +} from '../features/sparse-rows/sparseRowsFeature.types' import type { Cell } from '../types/Cell' import type { Column } from '../types/Column' import type { Row } from '../types/Row' @@ -282,3 +286,33 @@ export function getAggregateColumnValue< ): Table_RowAggregation['_aggregateColumnValue'] | undefined { return (table as Partial)._aggregateColumnValue } + +// Sparse rows + +/** + * The core row model of the sparse rows feature, or `undefined` when the + * feature is not registered. + */ +export function createSparseRowModel< + TFeatures extends TableFeatures, + TData extends RowData, +>( + table: Table_Internal, +): (() => RowModel) | undefined { + return ( + table as Partial> + )._createSparseRowModel?.() +} + +/** + * Whether a row stands in for a row that is not loaded; no row does without + * the feature. + */ +export function getIsPlaceholderRow(row: object): boolean { + return (row as Partial).getIsPlaceholder?.() ?? false +} + +/** Whether the table can have placeholder rows; it cannot without the feature. */ +export function getCanHavePlaceholderRows(table: object): boolean { + return !!(table as Partial>)._createSparseRowModel +} diff --git a/packages/table-core/src/core/row-models/coreRowModelsFeature.utils.ts b/packages/table-core/src/core/row-models/coreRowModelsFeature.utils.ts index 4fbd56d49d..b9908d11a0 100644 --- a/packages/table-core/src/core/row-models/coreRowModelsFeature.utils.ts +++ b/packages/table-core/src/core/row-models/coreRowModelsFeature.utils.ts @@ -1,3 +1,4 @@ +import { createSparseRowModel } from '../featureStubs' import { createCoreRowModel } from './createCoreRowModel' import type { Table_Internal } from '../../types/Table' import type { TableFeatures } from '../../types/TableFeatures' @@ -7,8 +8,8 @@ import type { RowModel } from './coreRowModelsFeature.types' /** * Resolves the table's unmodified core row model. * - * The factory is created once per table, either from the `coreRowModel` slot on the `features` option - * or the built-in `createCoreRowModel()`, then reused for later calls. + * The factory is created once per table, either from the `coreRowModel` slot on the `features` option, + * the sparse rows feature, or the built-in `createCoreRowModel()`, then reused for later calls. * * @example * ```ts @@ -22,6 +23,7 @@ export function table_getCoreRowModel< if (!table._rowModels.coreRowModel) { table._rowModels.coreRowModel = table.options.features.coreRowModel?.(table) ?? + createSparseRowModel(table) ?? createCoreRowModel()(table) } diff --git a/packages/table-core/src/core/rows/coreRowsFeature.utils.ts b/packages/table-core/src/core/rows/coreRowsFeature.utils.ts index 7aeb866172..62a5f65b42 100644 --- a/packages/table-core/src/core/rows/coreRowsFeature.utils.ts +++ b/packages/table-core/src/core/rows/coreRowsFeature.utils.ts @@ -1,6 +1,6 @@ import { flattenBy, hasOwn, makeObjectMap } from '../../utils' import { constructCell } from '../cells/constructCell' -import { expandRowModel } from '../featureStubs' +import { expandRowModel, getIsPlaceholderRow } from '../featureStubs' import type { Table_Internal } from '../../types/Table' import type { RowData } from '../../types/type-utils' import type { TableFeatures } from '../../types/TableFeatures' @@ -68,6 +68,8 @@ export function row_getValue< return row._valuesCache[columnId] } + if (getIsPlaceholderRow(row)) return undefined + const column = row.table.getColumn(columnId) if (!column?.accessorFn) { @@ -98,6 +100,8 @@ export function row_getUniqueValues< return row._uniqueValuesCache[columnId] } + if (getIsPlaceholderRow(row)) return [] + const column = row.table.getColumn(columnId) if (!column?.accessorFn) { diff --git a/packages/table-core/src/features/cell-selection/cellSelectionFeature.utils.ts b/packages/table-core/src/features/cell-selection/cellSelectionFeature.utils.ts index 12a9a64a5f..3179787653 100644 --- a/packages/table-core/src/features/cell-selection/cellSelectionFeature.utils.ts +++ b/packages/table-core/src/features/cell-selection/cellSelectionFeature.utils.ts @@ -5,6 +5,8 @@ import { setStateSlice, } from '../../utils' import { + getCanHavePlaceholderRows, + getIsPlaceholderRow, getVisibleLeafColumns, orderByColumnPinning, } from '../../core/featureStubs' @@ -473,7 +475,8 @@ function isWithinBounds( * Checks whether this cell can currently be selected. * * A column def opting out with `enableCellSelection: false` wins over the table - * option, matching how the other per-column enable flags resolve. + * option, matching how the other per-column enable flags resolve. A cell of a + * placeholder row can never be selected. * * @example * ```ts @@ -485,6 +488,8 @@ export function cell_getCanSelect< TData extends RowData, TValue extends CellData = CellData, >(cell: Cell): boolean { + if (getIsPlaceholderRow(cell.row)) return false + const columnDef = cell.column.columnDef as Partial if (columnDef.enableCellSelection === false) return false @@ -765,9 +770,26 @@ export function table_setFocusedCell< // Selection writes +/** + * Tests whether a row id is the temporary id of a placeholder row. + */ +function isPlaceholderRowId< + TFeatures extends TableFeatures, + TData extends RowData, +>(table: Table_Internal, rowId: string): boolean { + if (!getCanHavePlaceholderRows(table)) return false + + const row = table.getCoreRowModel().rowsById[rowId] + + return !!row && getIsPlaceholderRow(row) +} + /** * Selects a rectangle using replace, include, or exclude semantics. * + * A range that starts or ends on a placeholder row is ignored, because the id + * of that row changes when the row is loaded. + * * @example * ```ts * table_selectCellRange(table, range, { mode: 'exclude' }) @@ -781,6 +803,13 @@ export function table_selectCellRange< range: CellSelectionRange, opts?: SelectCellRangeOptions, ) { + if ( + isPlaceholderRowId(table, range.anchorRowId) || + isPlaceholderRowId(table, range.focusRowId) + ) { + return + } + const mode = opts?.mode ?? (opts?.additive ? 'include' : 'replace') const { operation: _operation, ...coordinates } = range const nextRange: CellSelectionRange = @@ -830,12 +859,30 @@ export function table_selectAllCells< const rows = table.getRowsInDisplayOrder() const columns = getSelectableColumns(table) - if (!rows.length || !columns.length) return + // Placeholder rows cannot hold a corner, so the range runs from the first + // to the last loaded row. + let firstRowIndex = 0 + let lastRowIndex = rows.length - 1 + + while ( + firstRowIndex <= lastRowIndex && + getIsPlaceholderRow(rows[firstRowIndex]!) + ) { + firstRowIndex++ + } + while ( + lastRowIndex > firstRowIndex && + getIsPlaceholderRow(rows[lastRowIndex]!) + ) { + lastRowIndex-- + } + + if (firstRowIndex > lastRowIndex || !columns.length) return table_selectCellRange(table, { - anchorRowId: rows[0]!.id, + anchorRowId: rows[firstRowIndex]!.id, anchorColumnId: columns[0]!.id, - focusRowId: rows[rows.length - 1]!.id, + focusRowId: rows[lastRowIndex]!.id, focusColumnId: columns[columns.length - 1]!.id, }) } @@ -985,7 +1032,9 @@ function stepCoordinate( const landingRow = rows[landingRowIndex] const landingColumn = columns[landingColumnIndex] - if (!landingRow || !landingColumn) return null + if (!landingRow || !landingColumn || getIsPlaceholderRow(landingRow)) { + return null + } return { rowId: landingRow.id, @@ -1012,12 +1061,14 @@ export function table_moveCellSelection< const active = ranges?.[ranges.length - 1] if (!active) { - const rows = table.getRowModel().rows + const firstRow = table + .getRowModel() + .rows.find((row) => !getIsPlaceholderRow(row)) const columns = getSelectableColumns(table) - if (!rows.length || !columns.length) return + if (!firstRow || !columns.length) return - table_setFocusedCell(table, rows[0]!.id, columns[0]!.id) + table_setFocusedCell(table, firstRow.id, columns[0]!.id) return } @@ -1121,7 +1172,8 @@ function forEachSelectedCell< rowIndex++ ) { const row = rows[rowIndex] - if (!row) continue + // A placeholder row is skipped before its cells are built. + if (!row || getIsPlaceholderRow(row)) continue const cellsByColumnId = row.getAllCellsByColumnId() @@ -1251,10 +1303,12 @@ export function table_getSelectedCellCount< // A per-cell predicate requires enumeration, and so do merged cells: a // merge counts once, and after subtraction a merge can straddle several - // final rectangles, which breaks per-rectangle arithmetic. + // final rectangles, which breaks per-rectangle arithmetic. Placeholder rows + // inside a rectangle have no selectable cells, so they need it too. if ( typeof table.options.enableCellSelection === 'function' || - merges.length + merges.length || + getCanHavePlaceholderRows(table) ) { const ids = new Set() forEachSelectedCell(table, (cell) => ids.add(cell.id), true) @@ -1309,7 +1363,7 @@ export function table_getCellSelectionRowIds< const bound = bounds[i]! for (let index = bound.minRowIndex; index <= bound.maxRowIndex; index++) { const row = rows[index] - if (!row || seen.has(row.id)) continue + if (!row || seen.has(row.id) || getIsPlaceholderRow(row)) continue seen.add(row.id) ids.push(row.id) } diff --git a/packages/table-core/src/features/global-filtering/globalFilteringFeature.ts b/packages/table-core/src/features/global-filtering/globalFilteringFeature.ts index 4ac7f4fc03..02884863bb 100644 --- a/packages/table-core/src/features/global-filtering/globalFilteringFeature.ts +++ b/packages/table-core/src/features/global-filtering/globalFilteringFeature.ts @@ -3,6 +3,7 @@ import { assignTableAPIs, makeStateUpdater, } from '../../utils' +import { getIsPlaceholderRow } from '../../core/featureStubs' import { column_getCanGlobalFilter, table_getGlobalAutoFilterFn, @@ -38,7 +39,9 @@ export const globalFilteringFeature: TableFeature = { const row = table .getCoreRowModel() .flatRows.find( - (row) => row.getAllCellsByColumnId()[column.id]?.getValue() != null, + (row) => + !getIsPlaceholderRow(row) && + row.getAllCellsByColumnId()[column.id]?.getValue() != null, ) const value = row?.getAllCellsByColumnId()[column.id]?.getValue() diff --git a/packages/table-core/src/features/row-expanding/rowExpandingFeature.utils.ts b/packages/table-core/src/features/row-expanding/rowExpandingFeature.utils.ts index 8d84be5cfb..ab876bbbe0 100644 --- a/packages/table-core/src/features/row-expanding/rowExpandingFeature.utils.ts +++ b/packages/table-core/src/features/row-expanding/rowExpandingFeature.utils.ts @@ -1,4 +1,5 @@ import { cloneState, hasOwn, makeObjectMap, setStateSlice } from '../../utils' +import { getIsPlaceholderRow } from '../../core/featureStubs' import type { RowData, Updater } from '../../types/type-utils' import type { TableFeatures } from '../../types/TableFeatures' import type { Table_Internal } from '../../types/Table' @@ -290,6 +291,8 @@ export function row_toggleExpanded< TFeatures extends TableFeatures, TData extends RowData, >(row: Row, expanded?: boolean) { + if (getIsPlaceholderRow(row)) return + const currentExpanded = row.table.atoms.expanded?.get() ?? {} const currentExists = currentExpanded === true || isExpandedRowId(currentExpanded, row.id) @@ -349,6 +352,8 @@ export function row_getIsExpanded< TFeatures extends TableFeatures, TData extends RowData, >(row: Row) { + if (getIsPlaceholderRow(row)) return false + const expanded: ExpandedState = row.table.atoms.expanded?.get() ?? {} return !!( @@ -384,6 +389,8 @@ export function row_getCanExpand< TFeatures extends TableFeatures, TData extends RowData, >(row: Row) { + if (getIsPlaceholderRow(row)) return false + return ( row.table.options.getRowCanExpand?.(row) ?? ((row.table.options.enableExpanding ?? true) && !!row.subRows.length) diff --git a/packages/table-core/src/features/row-pinning/rowPinningFeature.utils.ts b/packages/table-core/src/features/row-pinning/rowPinningFeature.utils.ts index 4c31be8ef6..878bfbd95a 100644 --- a/packages/table-core/src/features/row-pinning/rowPinningFeature.utils.ts +++ b/packages/table-core/src/features/row-pinning/rowPinningFeature.utils.ts @@ -1,4 +1,7 @@ -import { getIsAllParentsExpanded } from '../../core/featureStubs' +import { + getIsAllParentsExpanded, + getIsPlaceholderRow, +} from '../../core/featureStubs' import { callMemoOrStaticFn, cloneState, setStateSlice } from '../../utils' import type { RowData, Updater } from '../../types/type-utils' import type { TableFeatures } from '../../types/TableFeatures' @@ -215,6 +218,8 @@ export function row_getCanPin< TFeatures extends TableFeatures, TData extends RowData, >(row: Row): boolean { + if (getIsPlaceholderRow(row)) return false + const { enableRowPinning } = row.table.options if (typeof enableRowPinning === 'function') { return enableRowPinning(row) @@ -290,6 +295,8 @@ export function row_pin( includeLeafRows?: boolean, includeParentRows?: boolean, ): void { + if (getIsPlaceholderRow(row)) return + const leafRowIds = includeLeafRows ? row.getLeafRows().map(({ id }) => id) : [] diff --git a/packages/table-core/src/features/row-selection/rowSelectionFeature.utils.ts b/packages/table-core/src/features/row-selection/rowSelectionFeature.utils.ts index c90758f7b9..d465256b7e 100644 --- a/packages/table-core/src/features/row-selection/rowSelectionFeature.utils.ts +++ b/packages/table-core/src/features/row-selection/rowSelectionFeature.utils.ts @@ -5,6 +5,7 @@ import { hasOwn, makeObjectMap, } from '../../utils' +import { getIsPlaceholderRow } from '../../core/featureStubs' import type { RowData, Updater } from '../../types/type-utils' import type { TableFeatures } from '../../types/TableFeatures' import type { RowModel } from '../../core/row-models/coreRowModelsFeature.types' @@ -375,7 +376,8 @@ export function table_getIsAllRowsSelected< (row) => !isRowSelected(row, rowSelection) && isRowSelectableInSelectAll(row, subtreeCache), - ) + ) || + preGroupedFlatRows.every(getIsPlaceholderRow) ) { isAllRowsSelected = false } @@ -535,6 +537,8 @@ export function row_toggleSelected< TFeatures extends TableFeatures, TData extends RowData, >(row: Row, value?: boolean, opts?: ToggleSelectedOptions) { + if (getIsPlaceholderRow(row)) return + const isSelected = row_getIsSelected(row) table_setRowSelection(row.table, (old) => { @@ -625,6 +629,8 @@ export function row_getCanSelect< TFeatures extends TableFeatures, TData extends RowData, >(row: Row) { + if (getIsPlaceholderRow(row)) return false + const options = row.table.options if (typeof options.enableRowSelection === 'function') { return options.enableRowSelection(row) @@ -648,6 +654,8 @@ export function row_getCanSelectSubRows< TFeatures extends TableFeatures, TData extends RowData, >(row: Row) { + if (getIsPlaceholderRow(row)) return false + const options = row.table.options if (typeof options.enableSubRowSelection === 'function') { return options.enableSubRowSelection(row) @@ -671,6 +679,8 @@ export function row_getCanMultiSelect< TFeatures extends TableFeatures, TData extends RowData, >(row: Row) { + if (getIsPlaceholderRow(row)) return false + const options = row.table.options if (typeof options.enableMultiRowSelection === 'function') { return options.enableMultiRowSelection(row) @@ -814,6 +824,8 @@ function mutateRowIsSelected< ): void { const row = table.getRow(rowId, true) + if (getIsPlaceholderRow(row)) return + if (value) { if (!row_getCanMultiSelect(row)) { Object.keys(rowSelection).forEach((key) => delete rowSelection[key]) diff --git a/packages/table-core/src/features/sparse-rows/sparseRowsFeature.ts b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.ts new file mode 100644 index 0000000000..753346747a --- /dev/null +++ b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.ts @@ -0,0 +1,35 @@ +import { assignPrototypeAPIs, assignTableAPIs } from '../../utils' +import { + row_getIsPlaceholder, + table_createSparseRowModel, + table_getMissingRowRanges, +} from './sparseRowsFeature.utils' +import type { TableFeature } from '../../types/TableFeatures' + +/** + * Feature that reads `data` as a sparse array of loaded rows and fills the core + * row model with placeholder rows up to `rowCount`. + * + * It is not part of `stockFeatures`, because it changes how the table reads + * `data` and `rowCount`. + */ +export const sparseRowsFeature: TableFeature = { + assignRowPrototype: (prototype, table) => { + assignPrototypeAPIs('sparseRowsFeature', prototype, table, { + row_getIsPlaceholder: { + fn: (row) => row_getIsPlaceholder(row), + }, + }) + }, + + constructTableAPIs: (table) => { + assignTableAPIs('sparseRowsFeature', table, { + table__createSparseRowModel: { + fn: () => table_createSparseRowModel(table), + }, + table_getMissingRowRanges: { + fn: (options) => table_getMissingRowRanges(table, options), + }, + }) + }, +} diff --git a/packages/table-core/src/features/sparse-rows/sparseRowsFeature.types.ts b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.types.ts new file mode 100644 index 0000000000..b9156c9d10 --- /dev/null +++ b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.types.ts @@ -0,0 +1,63 @@ +import type { RowModel } from '../../core/row-models/coreRowModelsFeature.types' +import type { RowData } from '../../types/type-utils' +import type { TableFeatures } from '../../types/TableFeatures' + +export interface SparseRowRange { + /** + * The index of the first row in the range. + */ + startIndex: number + /** + * The index of the last row in the range. The range includes this row. + */ + endIndex: number +} + +export interface MissingRowRangesOptions extends SparseRowRange { + /** + * Returns whole blocks of this many rows instead of exact gaps: one range for + * each block that has a missing row between `startIndex` and `endIndex`. + * Block `n` starts at index `n * blockSize`, so the same block always has + * the same bounds. + */ + blockSize?: number +} + +export interface TableOptions_SparseRows { + /** + * The total number of rows on the server. The core row model has this many + * rows, and each index that `data` has no row for gets a placeholder row. + * Defaults to `data.length`. + */ + rowCount?: number +} + +export interface Row_SparseRows { + /** + * Checks whether this row stands in for a row that is not loaded. A + * placeholder row has a temporary id, its `original` is `undefined`, and all + * of its values are `undefined`. + */ + getIsPlaceholder: () => boolean +} + +export interface Table_SparseRows< + in out TFeatures extends TableFeatures, + in out TData extends RowData, +> { + /** + * Creates the core row model that holds `rowCount` rows. The core row model + * getter uses it in place of `createCoreRowModel()`. + * + * @internal + */ + _createSparseRowModel: () => () => RowModel + /** + * Returns the ranges between `startIndex` and `endIndex` (both included) that + * `data` has no rows for. The table does not load rows; request these ranges + * and put the rows into `data` at their index. + */ + getMissingRowRanges: ( + options: MissingRowRangesOptions, + ) => Array +} diff --git a/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts new file mode 100644 index 0000000000..9b9c7255dd --- /dev/null +++ b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts @@ -0,0 +1,219 @@ +import { constructRow } from '../../core/rows/constructRow' +import { makeObjectMap, tableMemo } from '../../utils' +import type { RowModel } from '../../core/row-models/coreRowModelsFeature.types' +import type { Row } from '../../types/Row' +import type { Table_Internal } from '../../types/Table' +import type { TableFeatures } from '../../types/TableFeatures' +import type { RowData } from '../../types/type-utils' +import type { + MissingRowRangesOptions, + SparseRowRange, +} from './sparseRowsFeature.types' + +const placeholderRowIdPrefix = '__placeholder_' + +function getSparseRowCount< + TFeatures extends TableFeatures, + TData extends RowData, +>(table: Table_Internal): number { + const { data, rowCount } = table.options + + return rowCount !== undefined && rowCount >= 0 && rowCount < Infinity + ? Math.floor(rowCount) + : data.length +} + +function accessSubRows( + table: Table_Internal, + rowModel: RowModel, + parentRow: Row, +): void { + const originalSubRows = table.options.getSubRows!( + parentRow.original, + parentRow.index, + ) + parentRow.originalSubRows = originalSubRows + + if (!originalSubRows) return + + for (let i = 0; i < originalSubRows.length; i++) { + const originalRow = originalSubRows[i]! + const row = constructRow( + table, + table.getRowId(originalRow, i, parentRow), + originalRow, + i, + parentRow.depth + 1, + undefined, + parentRow.id, + ) + + rowModel.flatRows.push(row) + rowModel.rowsById[row.id] = row + parentRow.subRows.push(row) + accessSubRows(table, rowModel, row) + } +} + +/** + * Creates the memoized core row model for a table with sparse rows. + * + * It does not run the `autoReset*` behaviors when `data` changes, because a + * change usually means that more rows are loaded, not that the rows are new. + */ +export function table_createSparseRowModel< + TFeatures extends TableFeatures, + TData extends RowData, +>(table: Table_Internal): () => RowModel { + // A placeholder row depends only on its index, so each one is made once and + // used again each time `data` changes. + const placeholderRows: Array> = [] + let hasWarnedClientRowModels = false + let lastWarnedDuplicateId: string | undefined + + return tableMemo({ + feature: 'sparseRowsFeature', + table, + fnName: 'table.getCoreRowModel', + memoDeps: () => [table.options.data, getSparseRowCount(table)], + fn: (data, rowCount) => { + const rowModel: RowModel = { + rows: [], + flatRows: [], + rowsById: makeObjectMap(), + } + const { getSubRows } = table.options + let duplicateId: string | undefined + + placeholderRows.length = Math.min(placeholderRows.length, rowCount) + + for (let i = 0; i < rowCount; i++) { + const originalRow = data[i] + let row: Row + + if (originalRow === undefined) { + row = placeholderRows[i] ??= constructRow( + table, + placeholderRowIdPrefix + i, + undefined as unknown as TData, + i, + 0, + ) + } else { + row = constructRow( + table, + table.getRowId(originalRow, i), + originalRow, + i, + 0, + ) + if ( + process.env.NODE_ENV === 'development' && + rowModel.rowsById[row.id] + ) { + duplicateId ??= row.id + } + } + + rowModel.rows.push(row) + rowModel.flatRows.push(row) + rowModel.rowsById[row.id] = row + + if (getSubRows && originalRow !== undefined) { + accessSubRows(table, rowModel, row) + } + } + + if (process.env.NODE_ENV === 'development') { + const { features, manualFiltering, manualGrouping, manualSorting } = + table.options + + if ( + !hasWarnedClientRowModels && + ((features.filteredRowModel && !manualFiltering) || + (features.groupedRowModel && !manualGrouping) || + (features.sortedRowModel && !manualSorting)) + ) { + hasWarnedClientRowModels = true + console.warn( + 'sparseRowsFeature: a client-side filtered, grouped, or sorted row model only sees the rows that are loaded, so its result is wrong. Filter, group, and sort on the server and set manualFiltering, manualGrouping, and manualSorting.', + ) + } + + if ( + duplicateId !== undefined && + duplicateId !== lastWarnedDuplicateId + ) { + console.warn( + `sparseRowsFeature: getRowId returned '${duplicateId}' for more than one loaded row. The loaded ranges probably overlap because rows were added or removed on the server between two requests.`, + ) + } + lastWarnedDuplicateId = duplicateId + } + + return rowModel + }, + }) +} + +/** + * Returns the ranges between `startIndex` and `endIndex` (both included) that + * `data` has no rows for. + * + * With `blockSize`, the result has one range for each block that has a missing + * row in the requested range. A block range can be larger than the requested + * range, but it never goes past the last row. + * + * @example + * ```ts + * table_getMissingRowRanges(table, { startIndex: 120, endIndex: 160, blockSize: 50 }) + * // [{ startIndex: 100, endIndex: 149 }, { startIndex: 150, endIndex: 199 }] + * ``` + */ +export function table_getMissingRowRanges< + TFeatures extends TableFeatures, + TData extends RowData, +>( + table: Table_Internal, + { startIndex, endIndex, blockSize }: MissingRowRangesOptions, +): Array { + const data = table.options.data + const lastIndex = getSparseRowCount(table) - 1 + const first = Math.max(0, Math.ceil(startIndex)) + const last = Math.min(lastIndex, Math.floor(endIndex)) + const size = + blockSize !== undefined && blockSize >= 1 && blockSize < Infinity + ? Math.floor(blockSize) + : 0 + const ranges: Array = [] + + for (let i = first; i <= last; i++) { + if (data[i] !== undefined) continue + + let rangeStart = i + let rangeEnd = i + + if (size) { + rangeStart = i - (i % size) + rangeEnd = Math.min(rangeStart + size - 1, lastIndex) + } else { + while (rangeEnd < last && data[rangeEnd + 1] === undefined) rangeEnd++ + } + + ranges.push({ startIndex: rangeStart, endIndex: rangeEnd }) + i = rangeEnd + } + + return ranges +} + +/** + * Checks whether a row stands in for a row that is not loaded. `data` has no + * row for an index when the entry is a hole or `undefined`. + */ +export function row_getIsPlaceholder< + TFeatures extends TableFeatures, + TData extends RowData, +>(row: Row): boolean { + return (row.original as TData | undefined) === undefined +} diff --git a/packages/table-core/src/index.ts b/packages/table-core/src/index.ts index 0ac1acec37..59a5d118ba 100755 --- a/packages/table-core/src/index.ts +++ b/packages/table-core/src/index.ts @@ -143,4 +143,8 @@ export * from './features/row-sorting/rowSortingFeature.types' export * from './features/row-sorting/createSortedRowModel' export * from './features/row-sorting/sortFns' +// sparseRowsFeature +export * from './features/sparse-rows/sparseRowsFeature' +export * from './features/sparse-rows/sparseRowsFeature.types' + // force diff --git a/packages/table-core/src/static-functions.ts b/packages/table-core/src/static-functions.ts index f8243f4a63..ca2c33e4af 100644 --- a/packages/table-core/src/static-functions.ts +++ b/packages/table-core/src/static-functions.ts @@ -32,3 +32,4 @@ export * from './features/row-pagination/rowPaginationFeature.utils' export * from './features/row-pinning/rowPinningFeature.utils' export * from './features/row-selection/rowSelectionFeature.utils' export * from './features/row-sorting/rowSortingFeature.utils' +export * from './features/sparse-rows/sparseRowsFeature.utils' diff --git a/packages/table-core/src/types/Row.ts b/packages/table-core/src/types/Row.ts index 5834a6d46e..291cabf907 100644 --- a/packages/table-core/src/types/Row.ts +++ b/packages/table-core/src/types/Row.ts @@ -7,6 +7,7 @@ import type { RowData } from './type-utils' import type { Row_RowExpanding } from '../features/row-expanding/rowExpandingFeature.types' import type { Row_RowPinning } from '../features/row-pinning/rowPinningFeature.types' import type { Row_RowSelection } from '../features/row-selection/rowSelectionFeature.types' +import type { Row_SparseRows } from '../features/sparse-rows/sparseRowsFeature.types' import type { ExtractFeatureMapTypes, TableFeatures } from './TableFeatures' import type { Row_Row } from '../core/rows/coreRowsFeature.types' @@ -27,6 +28,7 @@ export interface Row_FeatureMap< rowExpandingFeature: Row_RowExpanding rowPinningFeature: Row_RowPinning rowSelectionFeature: Row_RowSelection + sparseRowsFeature: Row_SparseRows } export type Row< diff --git a/packages/table-core/src/types/Table.ts b/packages/table-core/src/types/Table.ts index 19bf4626d0..64ab5aabba 100644 --- a/packages/table-core/src/types/Table.ts +++ b/packages/table-core/src/types/Table.ts @@ -16,6 +16,7 @@ import type { Table_RowExpanding } from '../features/row-expanding/rowExpandingF import type { Table_RowPagination } from '../features/row-pagination/rowPaginationFeature.types' import type { Table_RowSelection } from '../features/row-selection/rowSelectionFeature.types' import type { Table_RowSorting } from '../features/row-sorting/rowSortingFeature.types' +import type { Table_SparseRows } from '../features/sparse-rows/sparseRowsFeature.types' import type { Table_RowModels } from '../core/row-models/coreRowModelsFeature.types' import type { CachedRowModel_All } from './RowModel' import type { RowModelFns_All } from './RowModelFns' @@ -71,6 +72,7 @@ export interface Table_FeatureMap< rowPinningFeature: Table_RowPinning rowSelectionFeature: Table_RowSelection rowSortingFeature: Table_RowSorting + sparseRowsFeature: Table_SparseRows } /** diff --git a/packages/table-core/src/types/TableFeatures.ts b/packages/table-core/src/types/TableFeatures.ts index aacbeda37e..f570133129 100644 --- a/packages/table-core/src/types/TableFeatures.ts +++ b/packages/table-core/src/types/TableFeatures.ts @@ -28,6 +28,8 @@ export type IsAny = 0 extends 1 & T ? true : false * * This keeps empty feature-map lookups usable as an intersection member. */ +type OptInOnlyFeatureKeys = 'sparseRowsFeature' + type UnionToIntersectionOrEmpty = [T] extends [never] ? {} : UnionToIntersection & {} @@ -39,13 +41,18 @@ type UnionToIntersectionOrEmpty = [T] extends [never] * `TFeatures` is `any`, all feature-map entries are included to preserve the * permissive behavior expected by broad table types. Otherwise, only entries * whose keys are present in `TFeatures` are intersected together. + * + * Built-in features that are not in `stockFeatures` are left out of the `any` + * case. A stock table can then still be cast to `Table`. */ export type ExtractFeatureMapTypes< TFeatures extends TableFeatures, TFeatureMap extends object, > = IsAny extends true - ? UnionToIntersection + ? UnionToIntersection< + TFeatureMap[Exclude] + > : UnionToIntersectionOrEmpty< TFeatureMap[Extract] > @@ -296,6 +303,14 @@ export interface TableFeatures * sorting function in your bundle. */ sortFns?: Record> + /** + * Opt-in feature that reads `data` as a sparse array of loaded rows and fills + * the core row model with placeholder rows up to `rowCount`. + * + * It is not part of `stockFeatures`, because it changes how the table reads + * `data` and `rowCount`. Import `sparseRowsFeature` and register it by name. + */ + sparseRowsFeature?: TableFeature /** * Type-only slot for declaring the type of this table's `options.meta`. * diff --git a/packages/table-core/src/types/TableOptions.ts b/packages/table-core/src/types/TableOptions.ts index 55946e49f1..65730f168b 100644 --- a/packages/table-core/src/types/TableOptions.ts +++ b/packages/table-core/src/types/TableOptions.ts @@ -19,6 +19,7 @@ import type { TableOptions_RowPagination } from '../features/row-pagination/rowP import type { TableOptions_RowPinning } from '../features/row-pinning/rowPinningFeature.types' import type { TableOptions_RowSelection } from '../features/row-selection/rowSelectionFeature.types' import type { TableOptions_RowSorting } from '../features/row-sorting/rowSortingFeature.types' +import type { TableOptions_SparseRows } from '../features/sparse-rows/sparseRowsFeature.types' import type { RowData, UnionToIntersection } from './type-utils' import type { ExtractFeatureMapTypes, @@ -79,6 +80,7 @@ export interface TableOptions_FeatureMap< rowPinningFeature: TableOptions_RowPinning rowSelectionFeature: TableOptions_RowSelection rowSortingFeature: TableOptions_RowSorting + sparseRowsFeature: TableOptions_SparseRows } type TableOptions_StockFeatureKeys = @@ -98,6 +100,7 @@ type TableOptions_StockFeatureKeys = | 'rowPinningFeature' | 'rowSelectionFeature' | 'rowSortingFeature' + | 'sparseRowsFeature' /** * Plugin entries declaration-merged into `TableOptions_FeatureMap`, i.e. keys @@ -160,5 +163,6 @@ export type TableOptions_All< TableOptions_RowPinning & TableOptions_RowSelection & TableOptions_RowSorting & + TableOptions_SparseRows & TableOptions_PluginFeatureMapTypes > diff --git a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts new file mode 100644 index 0000000000..75fd7ad9d5 --- /dev/null +++ b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts @@ -0,0 +1,1193 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + cellSelectionFeature, + columnFilteringFeature, + columnGroupingFeature, + constructTable, + createExpandedRowModel, + createFilteredRowModel, + createGroupedRowModel, + createPaginatedRowModel, + createSortedRowModel, + filterFns, + globalFilteringFeature, + rowExpandingFeature, + rowPaginationFeature, + rowPinningFeature, + rowSelectionFeature, + rowSortingFeature, + sortFns, + sparseRowsFeature, + stockFeatures, + tableFeatures, +} from '../../../../src' +import { + row_getUniqueValues, + row_getValue, +} from '../../../../src/static-functions' +import { testFeatures } from '../../../fixtures/features' +import type { + Cell, + CellSelectionRange, + ColumnDef, + FilterFn, + Row, + RowData, + SparseRowRange, + Table, + TableOptions, +} from '../../../../src' + +interface Person { + id: string + name: string + age: number + children?: Array +} + +type Equal = + (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 + ? true + : false +type Expect = T + +const features = testFeatures({ + rowExpandingFeature, + rowPaginationFeature, + rowPinningFeature, + rowSelectionFeature, + sparseRowsFeature, + expandedRowModel: createExpandedRowModel(), +}) + +const paginatedFeatures = { + ...features, + paginatedRowModel: createPaginatedRowModel(), +} as typeof features + +const columns: Array> = [ + { accessorKey: 'name', id: 'name' }, + { accessorFn: (person) => person.age * 2, id: 'doubleAge' }, +] + +function makePerson(index: number): Person { + return { id: `person-${index}`, name: `Person ${index}`, age: 20 + index } +} + +function makeSparseData(...ranges: Array<[number, number]>): Array { + const data: Array = [] + for (const [startIndex, endIndex] of ranges) { + for (let i = startIndex; i <= endIndex; i++) { + data[i] = makePerson(i) + } + } + return data +} + +function makeTable( + options?: Partial>, +): Table { + return constructTable({ + features, + columns, + data: makeSparseData([2, 4]), + rowCount: 10, + getRowId: (person) => person.id, + manualPagination: true, + ...options, + }) +} + +function setData(table: Table, data: Array) { + table.setOptions((old) => ({ ...old, data })) +} + +const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 0)) + +function spyOnDevWarnings() { + vi.stubEnv('NODE_ENV', 'development') + return vi.spyOn(console, 'warn').mockImplementation(() => {}) +} + +afterEach(() => { + vi.unstubAllEnvs() + vi.restoreAllMocks() +}) + +describe('sparseRowsFeature types', () => { + it('should type the API of the proposal when only the feature is registered', () => { + const sparseFeatures = tableFeatures({ sparseRowsFeature }) + type Options = TableOptions + type SparseTable = Table + type SparseRow = Row + + true satisfies Expect> + true satisfies Expect< + Equal, boolean> + > + true satisfies Expect< + Equal< + ReturnType, + Array + > + > + + const options: Omit = { + columns: [], + data: makeSparseData([99_950, 99_999]), + rowCount: 100_000, + getRowId: (row) => row.id, + } + expect(options.rowCount).toBe(100_000) + }) + + it('should keep rowCount typed when row pagination is registered too', () => { + const combinedFeatures = tableFeatures({ + rowPaginationFeature, + sparseRowsFeature, + }) + true satisfies Expect< + Equal< + TableOptions['rowCount'], + number | undefined + > + > + expect(Object.keys(combinedFeatures)).toContain('sparseRowsFeature') + }) + + it('should not type the row API without the feature', () => { + const coreOnlyFeatures = tableFeatures({}) + const getIsPlaceholder = (row: Row) => + // @ts-expect-error - getIsPlaceholder needs sparseRowsFeature + row.getIsPlaceholder + expect(getIsPlaceholder).toBeTypeOf('function') + }) + + it('should let any-typed filter functions be cast for a table without the feature', () => { + function getStockFilterFns() { + return { ...filterFns } as Record< + string, + FilterFn + > + } + expect(getStockFilterFns()).toHaveProperty('includesString') + }) +}) + +describe('sparse core row model', () => { + it('should hold rowCount rows with the absolute index of each row', () => { + const table = makeTable() + const { rows, flatRows, rowsById } = table.getRowModel() + + expect(rows).toHaveLength(10) + expect(flatRows).toHaveLength(10) + expect(Object.keys(rowsById)).toHaveLength(10) + rows.forEach((row, index) => expect(row.index).toBe(index)) + expect(table.getCoreRowModel()).toBe(table.getRowModel()) + }) + + it('should make placeholder rows for the indexes without data', () => { + const table = makeTable() + const { rows } = table.getRowModel() + + expect(rows.map((row) => row.getIsPlaceholder())).toEqual([ + true, + true, + false, + false, + false, + true, + true, + true, + true, + true, + ]) + expect(rows[3]!.original).toEqual(makePerson(3)) + expect(rows[0]!.original).toBeUndefined() + expect(rows[9]!.original).toBeUndefined() + }) + + it('should treat holes and undefined entries as missing rows', () => { + const data = makeSparseData([0, 3]) + delete data[1] + data[2] = undefined as unknown as Person + const table = makeTable({ data, rowCount: 4 }) + + expect( + table.getRowModel().rows.map((row) => row.getIsPlaceholder()), + ).toEqual([false, true, true, false]) + }) + + it('should give placeholder rows a temporary id and loaded rows the id from getRowId', () => { + const getRowId = vi.fn((person: Person) => person.id) + const table = makeTable({ getRowId }) + const { rows, rowsById } = table.getRowModel() + + expect(rows.map((row) => row.id)).toEqual([ + '__placeholder_0', + '__placeholder_1', + 'person-2', + 'person-3', + 'person-4', + '__placeholder_5', + '__placeholder_6', + '__placeholder_7', + '__placeholder_8', + '__placeholder_9', + ]) + expect(rowsById['__placeholder_7']).toBe(rows[7]) + expect(table.getRow('person-3')).toBe(rows[3]) + expect(getRowId).toHaveBeenCalledTimes(3) + }) + + it('should not collide with the default index ids', () => { + const table = makeTable({ getRowId: undefined }) + + expect(table.getRowModel().rows.map((row) => row.id)).toEqual([ + '__placeholder_0', + '__placeholder_1', + '2', + '3', + '4', + '__placeholder_5', + '__placeholder_6', + '__placeholder_7', + '__placeholder_8', + '__placeholder_9', + ]) + }) + + it('should jump to the last rows of a large table without the rows before them', () => { + const table = makeTable({ + data: makeSparseData([99_950, 99_999]), + rowCount: 100_000, + }) + const { rows } = table.getRowModel() + + expect(rows).toHaveLength(100_000) + expect(rows[99_999]!.getIsPlaceholder()).toBe(false) + expect(rows[99_999]!.index).toBe(99_999) + expect(rows[99_999]!.original).toEqual(makePerson(99_999)) + expect(rows[99_949]!.getIsPlaceholder()).toBe(true) + expect( + table.getMissingRowRanges({ startIndex: 99_950, endIndex: 99_999 }), + ).toEqual([]) + }) + + it('should default rowCount to data.length', () => { + const table = makeTable({ rowCount: undefined }) + + expect(table.getRowModel().rows).toHaveLength(5) + }) + + it.each([Number.NaN, Infinity, -1])( + 'should fall back to data.length when rowCount is %s', + (rowCount) => { + const table = makeTable({ rowCount }) + + expect(table.getRowModel().rows).toHaveLength(5) + }, + ) + + it('should round a fractional rowCount down', () => { + const table = makeTable({ rowCount: 3.7 }) + + expect(table.getRowModel().rows.map((row) => row.index)).toEqual([0, 1, 2]) + }) + + it('should ignore data after rowCount', () => { + const table = makeTable({ data: makeSparseData([0, 9]), rowCount: 4 }) + + expect(table.getRowModel().rows.map((row) => row.id)).toEqual([ + 'person-0', + 'person-1', + 'person-2', + 'person-3', + ]) + }) + + it('should return the same row model until data or rowCount changes', () => { + const table = makeTable() + const rowModel = table.getRowModel() + + expect(table.getRowModel()).toBe(rowModel) + + table.setOptions((old) => ({ ...old, rowCount: 12 })) + expect(table.getRowModel()).not.toBe(rowModel) + expect(table.getRowModel().rows).toHaveLength(12) + }) + + it('should replace placeholder rows when their data is loaded', () => { + const table = makeTable() + const before = table.getRowModel().rows + + setData(table, makeSparseData([2, 4], [7, 8])) + const after = table.getRowModel().rows + + expect(after[7]!.getIsPlaceholder()).toBe(false) + expect(after[7]!.id).toBe('person-7') + expect(after[7]).not.toBe(before[7]) + expect(after[6]!.getIsPlaceholder()).toBe(true) + }) + + it('should use the same placeholder row again when data changes', () => { + const table = makeTable() + const before = table.getRowModel().rows + + setData(table, makeSparseData([2, 4], [7, 8])) + const loaded = table.getRowModel().rows + setData(table, makeSparseData([2, 4])) + const evicted = table.getRowModel().rows + + expect(loaded[0]).toBe(before[0]) + expect(loaded[9]).toBe(before[9]) + expect(evicted[7]).toBe(before[7]) + expect(evicted[7]!.getIsPlaceholder()).toBe(true) + }) + + it('should build sub rows for loaded rows only', () => { + const data = makeSparseData([1, 1]) + data[1]!.children = [makePerson(100), makePerson(101)] + const getSubRows = vi.fn((person: Person) => person.children) + const table = makeTable({ data, rowCount: 3, getSubRows }) + const { rows, flatRows, rowsById } = table.getRowModel() + + expect(getSubRows).toHaveBeenCalledTimes(3) + expect(rows).toHaveLength(3) + expect(flatRows.map((row) => row.id)).toEqual([ + '__placeholder_0', + 'person-1', + 'person-100', + 'person-101', + '__placeholder_2', + ]) + expect(rows[1]!.subRows.map((row) => row.id)).toEqual([ + 'person-100', + 'person-101', + ]) + expect(rowsById['person-101']!.depth).toBe(1) + expect(rowsById['person-101']!.parentId).toBe('person-1') + expect(rowsById['person-101']!.getIsPlaceholder()).toBe(false) + }) + + it('should not reset the page index or expanded state when rows load', async () => { + const table = makeTable({ + features: paginatedFeatures, + manualPagination: false, + getRowCanExpand: () => true, + initialState: { pagination: { pageIndex: 2, pageSize: 2 } }, + }) + table.getRowModel() + await flushMicrotasks() + table.getRowModel().rows[0]!.toggleExpanded(true) + + setData(table, makeSparseData([2, 7])) + table.getRowModel() + await flushMicrotasks() + + expect(table.atoms.pagination.get().pageIndex).toBe(2) + expect(table.atoms.expanded.get()).toEqual({ 'person-4': true }) + }) + + it('should paginate the sparse rows on the client', () => { + const table = makeTable({ + features: paginatedFeatures, + manualPagination: false, + initialState: { pagination: { pageIndex: 2, pageSize: 2 } }, + }) + + expect(table.getRowCount()).toBe(10) + expect(table.getPageCount()).toBe(5) + expect(table.getRowModel().rows.map((row) => row.id)).toEqual([ + 'person-4', + '__placeholder_5', + ]) + expect(table.getRowModel().rows.map((row) => row.index)).toEqual([4, 5]) + }) + + it('should not cut pages when pagination is manual', () => { + const table = makeTable({ + features: paginatedFeatures, + manualPagination: true, + initialState: { pagination: { pageIndex: 2, pageSize: 2 } }, + }) + + expect(table.getRowModel().rows.map((row) => row.index)).toEqual([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + ]) + expect(table.getPageCount()).toBe(5) + }) + + it('should let a custom coreRowModel slot replace the sparse row model', () => { + const customRowModel = { rows: [], flatRows: [], rowsById: {} } + const customFeatures = { + ...features, + coreRowModel: () => () => customRowModel, + } as typeof features + const table = makeTable({ features: customFeatures }) + + expect(table.getCoreRowModel()).toBe(customRowModel) + }) +}) + +describe('placeholder row values', () => { + it('should return undefined without calling the accessor', () => { + const accessorFn = vi.fn((person: Person) => person.name.toUpperCase()) + const table = makeTable({ + columns: [...columns, { accessorFn, id: 'upperName' }], + }) + const [placeholderRow, , loadedRow] = table.getRowModel().rows + + expect(placeholderRow!.getValue('name')).toBeUndefined() + expect(placeholderRow!.getValue('doubleAge')).toBeUndefined() + expect(placeholderRow!.getValue('upperName')).toBeUndefined() + expect(accessorFn).not.toHaveBeenCalled() + expect(loadedRow!.getValue('name')).toBe('Person 2') + expect(loadedRow!.getValue('doubleAge')).toBe(44) + expect(loadedRow!.getValue('upperName')).toBe('PERSON 2') + }) + + it('should give placeholder cells for each column', () => { + const table = makeTable({ renderFallbackValue: '...' }) + const placeholderRow = table.getRowModel().rows[0]! + const cells = placeholderRow.getAllCells() + + expect(cells.map((cell) => cell.column.id)).toEqual(['name', 'doubleAge']) + expect(cells.map((cell) => cell.getValue())).toEqual([undefined, undefined]) + expect(cells.map((cell) => cell.renderValue())).toEqual(['...', '...']) + expect(placeholderRow.renderValue('name')).toBe('...') + }) + + it('should not call getUniqueValues for a placeholder row', () => { + const getUniqueValues = vi.fn((person: Person) => [person.name]) + const table = makeTable({ + columns: [{ accessorKey: 'name', id: 'name', getUniqueValues }], + }) + const [placeholderRow, , loadedRow] = table.getRowModel().rows + + expect(placeholderRow!.getUniqueValues('name')).toEqual([]) + expect(getUniqueValues).not.toHaveBeenCalled() + expect(loadedRow!.getUniqueValues('name')).toEqual(['Person 2']) + }) + + it('should give the static row functions the same results', () => { + const getUniqueValues = vi.fn((person: Person) => [person.name]) + const table = makeTable({ + columns: [ + { accessorKey: 'name', id: 'name' }, + { accessorKey: 'age', id: 'age', getUniqueValues }, + ], + }) + const [placeholderRow, , loadedRow] = table.getRowModel().rows + + expect(row_getValue(placeholderRow!, 'name')).toBeUndefined() + expect(row_getUniqueValues(placeholderRow!, 'name')).toEqual([]) + expect(row_getUniqueValues(placeholderRow!, 'age')).toEqual([]) + expect(getUniqueValues).not.toHaveBeenCalled() + expect(row_getValue(loadedRow!, 'name')).toBe('Person 2') + expect(row_getUniqueValues(loadedRow!, 'name')).toEqual(['Person 2']) + }) +}) + +describe('row selection with placeholder rows', () => { + it('should not let a placeholder row be selected or pass it to the predicates', () => { + const enableRowSelection = vi.fn((row: Row) => + row.original.name.startsWith('Person'), + ) + const enableMultiRowSelection = vi.fn( + (row: Row) => row.original.age > 0, + ) + const enableSubRowSelection = vi.fn( + (row: Row) => row.original.age > 0, + ) + const table = makeTable({ + enableRowSelection, + enableMultiRowSelection, + enableSubRowSelection, + }) + const [placeholderRow, , loadedRow] = table.getRowModel().rows + + expect(placeholderRow!.getCanSelect()).toBe(false) + expect(placeholderRow!.getCanMultiSelect()).toBe(false) + expect(placeholderRow!.getCanSelectSubRows()).toBe(false) + expect(enableRowSelection).not.toHaveBeenCalled() + expect(enableMultiRowSelection).not.toHaveBeenCalled() + expect(enableSubRowSelection).not.toHaveBeenCalled() + expect(loadedRow!.getCanSelect()).toBe(true) + expect(loadedRow!.getCanMultiSelect()).toBe(true) + expect(loadedRow!.getCanSelectSubRows()).toBe(true) + }) + + it('should keep no selection state when a placeholder row is toggled', () => { + const onRowSelectionChange = vi.fn() + const table = makeTable({ onRowSelectionChange }) + const placeholderRow = table.getRowModel().rows[0]! + + placeholderRow.toggleSelected() + placeholderRow.toggleSelected(true) + placeholderRow.getToggleSelectedHandler()({ target: { checked: true } }) + + expect(onRowSelectionChange).not.toHaveBeenCalled() + expect(placeholderRow.getIsSelected()).toBe(false) + }) + + it('should not clear a single selection when a placeholder row is toggled', () => { + const table = makeTable({ + enableMultiRowSelection: false, + initialState: { rowSelection: { 'person-3': true } }, + }) + + table.getRowModel().rows[0]!.toggleSelected(true) + + expect(table.atoms.rowSelection.get()).toEqual({ 'person-3': true }) + }) + + it('should select only the loaded rows with select all', () => { + const table = makeTable() + + table.toggleAllRowsSelected(true) + + expect(table.atoms.rowSelection.get()).toEqual({ + 'person-2': true, + 'person-3': true, + 'person-4': true, + }) + expect(table.getIsAllRowsSelected()).toBe(true) + expect(table.getSelectedRowModel().rows.map((row) => row.id)).toEqual([ + 'person-2', + 'person-3', + 'person-4', + ]) + + table.toggleAllRowsSelected(false) + expect(table.atoms.rowSelection.get()).toEqual({}) + }) + + it('should select only the loaded rows of the page with select all on the page', () => { + const table = makeTable({ enableMultiRowSelection: false }) + + table.toggleAllPageRowsSelected(true) + + expect(table.atoms.rowSelection.get()).toEqual({ 'person-4': true }) + }) + + it('should keep the selection of a row that is no longer loaded', () => { + const table = makeTable({ + initialState: { rowSelection: { 'person-3': true } }, + }) + expect(table.getRowModel().rows[3]!.getIsSelected()).toBe(true) + + setData(table, makeSparseData([7, 8])) + + expect(table.atoms.rowSelection.get()).toEqual({ 'person-3': true }) + expect(table.getRowModel().rows[3]!.getIsSelected()).toBe(false) + expect(table.getSelectedRowModel().rows).toEqual([]) + expect(table.getIsSomeRowsSelected()).toBe(true) + + setData(table, makeSparseData([2, 4])) + + expect(table.getRowModel().rows[3]!.getIsSelected()).toBe(true) + expect(table.getSelectedRowModel().rows.map((row) => row.id)).toEqual([ + 'person-3', + ]) + }) + + it('should not report all rows selected when no row is loaded', () => { + const table = makeTable({ + initialState: { rowSelection: { 'person-3': true } }, + }) + expect(table.getIsAllRowsSelected()).toBe(false) + + table.toggleAllRowsSelected(true) + expect(table.getIsAllRowsSelected()).toBe(true) + + setData(table, []) + + expect(table.getRowModel().rows).toHaveLength(10) + expect(table.getIsAllRowsSelected()).toBe(false) + expect(table.getIsAllPageRowsSelected()).toBe(false) + expect(table.getIsSomeRowsSelected()).toBe(true) + }) +}) + +describe('row pinning with placeholder rows', () => { + it('should not let a placeholder row be pinned or pass it to the predicate', () => { + const enableRowPinning = vi.fn( + (row: Row) => row.original.age > 0, + ) + const table = makeTable({ enableRowPinning }) + const [placeholderRow, , loadedRow] = table.getRowModel().rows + + expect(placeholderRow!.getCanPin()).toBe(false) + expect(enableRowPinning).not.toHaveBeenCalled() + expect(loadedRow!.getCanPin()).toBe(true) + }) + + it('should keep no pinning state when a placeholder row is pinned', () => { + const onRowPinningChange = vi.fn() + const table = makeTable({ onRowPinningChange }) + const placeholderRow = table.getRowModel().rows[0]! + + placeholderRow.pin('top') + placeholderRow.pin('bottom') + placeholderRow.pin(false) + + expect(onRowPinningChange).not.toHaveBeenCalled() + expect(placeholderRow.getIsPinned()).toBe(false) + }) + + it('should leave out a pinned row while it is not loaded', () => { + const table = makeTable() + table.getRowModel().rows[3]!.pin('top') + expect(table.getTopRows().map((row) => row.id)).toEqual(['person-3']) + + setData(table, makeSparseData([7, 8])) + + expect(table.atoms.rowPinning.get()).toEqual({ + top: ['person-3'], + bottom: [], + }) + expect(table.getTopRows()).toEqual([]) + expect(table.getCenterRows()).toHaveLength(10) + + setData(table, makeSparseData([2, 4])) + + expect(table.getTopRows().map((row) => row.id)).toEqual(['person-3']) + }) +}) + +describe('row expanding with placeholder rows', () => { + it('should not let a placeholder row expand or pass it to the predicates', () => { + const getRowCanExpand = vi.fn( + (row: Row) => row.original.age > 0, + ) + const getIsRowExpanded = vi.fn( + (row: Row) => row.original.age > 0, + ) + const table = makeTable({ getRowCanExpand, getIsRowExpanded }) + const [placeholderRow, , loadedRow] = table.getRowModel().rows + + expect(placeholderRow!.getCanExpand()).toBe(false) + expect(placeholderRow!.getIsExpanded()).toBe(false) + expect(getRowCanExpand).not.toHaveBeenCalled() + expect(getIsRowExpanded).not.toHaveBeenCalled() + expect(loadedRow!.getCanExpand()).toBe(true) + expect(loadedRow!.getIsExpanded()).toBe(true) + }) + + it('should keep no expanded state when a placeholder row is toggled', () => { + const onExpandedChange = vi.fn() + const table = makeTable({ + getRowCanExpand: () => true, + onExpandedChange, + }) + const placeholderRow = table.getRowModel().rows[0]! + + placeholderRow.toggleExpanded() + placeholderRow.toggleExpanded(true) + placeholderRow.getToggleExpandedHandler()() + + expect(onExpandedChange).not.toHaveBeenCalled() + }) + + it('should not expand placeholder rows when all rows are expanded', () => { + const table = makeTable({ getRowCanExpand: () => true }) + + table.toggleAllRowsExpanded(true) + expect(table.atoms.expanded.get()).toBe(true) + + const [placeholderRow, , loadedRow] = table.getRowModel().rows + expect(placeholderRow!.getIsExpanded()).toBe(false) + expect(loadedRow!.getIsExpanded()).toBe(true) + + placeholderRow!.toggleExpanded(false) + expect(table.atoms.expanded.get()).toBe(true) + + loadedRow!.toggleExpanded(false) + expect(table.atoms.expanded.get()).toEqual({ + 'person-3': true, + 'person-4': true, + }) + }) +}) + +describe('cell selection with placeholder rows', () => { + const cellFeatures = testFeatures({ + cellSelectionFeature, + sparseRowsFeature, + }) + + function makeCellTable( + options?: Partial>, + ) { + return constructTable({ + features: cellFeatures, + columns: [ + { accessorKey: 'name', id: 'name' }, + { accessorKey: 'age', id: 'age' }, + ], + data: makeSparseData([2, 4], [7, 8]), + rowCount: 10, + getRowId: (person) => person.id, + ...options, + }) + } + + function rangeOf( + anchorRowId: string, + anchorColumnId: string, + focusRowId: string, + focusColumnId: string, + ): CellSelectionRange { + return { anchorRowId, anchorColumnId, focusRowId, focusColumnId } + } + + function makeFakeDocument() { + return { + addEventListener: () => {}, + removeEventListener: () => {}, + } as unknown as Document + } + + it('should not let a placeholder cell be selected or pass it to the predicate', () => { + const enableCellSelection = vi.fn( + (cell: Cell) => + cell.row.original.name.startsWith('Person'), + ) + const table = makeCellTable({ enableCellSelection }) + const [placeholderRow, , loadedRow] = table.getRowModel().rows + + expect(placeholderRow!.getAllCells()[0]!.getCanSelect()).toBe(false) + expect(enableCellSelection).not.toHaveBeenCalled() + expect(loadedRow!.getAllCells()[0]!.getCanSelect()).toBe(true) + }) + + it('should keep no selection state when a placeholder cell gets a pointer event', () => { + const table = makeCellTable() + const { rows } = table.getRowModel() + const fakeDocument = makeFakeDocument() + + rows[5]!.getAllCells()[0]!.getSelectionStartHandler(fakeDocument)({}) + expect(table.atoms.cellSelection.get()).toEqual([]) + + rows[4]!.getAllCells()[0]!.getSelectionStartHandler(fakeDocument)({}) + rows[5]!.getAllCells()[1]!.getSelectionExtendHandler()({}) + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('person-4', 'name', 'person-4', 'name'), + ]) + + rows[3]!.getAllCells()[1]!.getSelectionExtendHandler()({}) + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('person-4', 'name', 'person-3', 'age'), + ]) + }) + + it('should not select a range that starts or ends on a placeholder row', () => { + const table = makeCellTable() + const placeholderId = table.getRowModel().rows[6]!.id + + table.selectCellRange(rangeOf('person-3', 'name', placeholderId, 'age')) + table.selectCellRange(rangeOf(placeholderId, 'name', 'person-3', 'age')) + table.setFocusedCell(placeholderId, 'name') + + expect(table.atoms.cellSelection.get()).toEqual([]) + + table.selectCellRange(rangeOf('person-3', 'name', 'person-4', 'age')) + table.selectCellRange(rangeOf('person-7', 'name', placeholderId, 'age'), { + additive: true, + }) + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('person-3', 'name', 'person-4', 'age'), + ]) + }) + + it('should leave out the placeholder rows of a range that spans a gap', () => { + const table = makeCellTable() + const { rows } = table.getRowModel() + const getPlaceholderCells = vi.spyOn(rows[5]!, 'getAllCellsByColumnId') + + table.selectCellRange(rangeOf('person-3', 'name', 'person-7', 'age')) + + const selectedCellIds = [ + 'person-3_name', + 'person-3_age', + 'person-4_name', + 'person-4_age', + 'person-7_name', + 'person-7_age', + ] + expect(table.getSelectedCellIds()).toEqual(selectedCellIds) + expect(table.getSelectedCellCount()).toBe(selectedCellIds.length) + expect(table.getCellSelectionRowIds()).toEqual([ + 'person-3', + 'person-4', + 'person-7', + ]) + const [grid] = table.getSelectedCellRangesData() + expect(grid).toHaveLength(5) + expect(Object.entries(grid!)).toEqual([ + ['0', ['Person 3', 23]], + ['1', ['Person 4', 24]], + ['4', ['Person 7', 27]], + ]) + expect(getPlaceholderCells).not.toHaveBeenCalled() + expect(rows[5]!.getAllCells()[0]!.getIsSelected()).toBe(false) + expect(rows[4]!.getAllCells()[0]!.getIsSelected()).toBe(true) + + table.setOptions((old) => ({ ...old, data: makeSparseData([2, 8]) })) + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('person-3', 'name', 'person-7', 'age'), + ]) + expect(table.getSelectedCellCount()).toBe(10) + expect(table.getSelectedCellIds()).toHaveLength(10) + }) + + it('should stop keyboard navigation at a placeholder row', () => { + const table = makeCellTable() + + table.moveCellSelection('down') + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('person-2', 'name', 'person-2', 'name'), + ]) + + table.setFocusedCell('person-4', 'name') + table.moveCellSelection('down') + table.extendCellSelection('down') + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('person-4', 'name', 'person-4', 'name'), + ]) + + table.extendCellSelection('up') + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('person-4', 'name', 'person-3', 'name'), + ]) + }) + + it('should select from the first to the last loaded row with select all', () => { + const table = makeCellTable() + + table.selectAllCells() + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('person-2', 'name', 'person-8', 'age'), + ]) + expect(table.getSelectedCellCount()).toBe(10) + + table.resetCellSelection(true) + table.setOptions((old) => ({ ...old, data: [] })) + table.selectAllCells() + table.moveCellSelection('down') + + expect(table.atoms.cellSelection.get()).toEqual([]) + }) + + it('should keep the cell selection of a row that is no longer loaded', async () => { + const table = makeCellTable() + + table.selectCellRange(rangeOf('person-3', 'name', 'person-4', 'age')) + table.setOptions((old) => ({ ...old, data: makeSparseData([7, 8]) })) + table.getRowModel() + await flushMicrotasks() + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('person-3', 'name', 'person-4', 'age'), + ]) + expect(table.getSelectedCellCount()).toBe(0) + expect(table.getSelectedCellIds()).toEqual([]) + + table.setOptions((old) => ({ ...old, data: makeSparseData([2, 4]) })) + + expect(table.getSelectedCellCount()).toBe(4) + }) +}) + +describe('global filtering with placeholder rows', () => { + const globalFeatures = testFeatures({ + columnFilteringFeature, + globalFilteringFeature, + sparseRowsFeature, + }) + + function makeGlobalTable( + options?: Partial>, + ) { + return constructTable({ + features: globalFeatures, + columns: [ + { accessorKey: 'name', id: 'name' }, + { accessorKey: 'children', id: 'children' }, + ], + data: makeSparseData([2, 4]), + rowCount: 10, + getRowId: (person) => person.id, + manualFiltering: true, + ...options, + }) + } + + it('should read the column value of the first loaded row without the cells of placeholder rows', () => { + const table = makeGlobalTable() + const getPlaceholderCells = vi.spyOn( + table.getCoreRowModel().rows[0]!, + 'getAllCellsByColumnId', + ) + + expect(table.getColumn('name')!.getCanGlobalFilter()).toBe(true) + expect(table.getColumn('children')!.getCanGlobalFilter()).toBe(false) + expect(getPlaceholderCells).not.toHaveBeenCalled() + }) + + it('should not let a column be filtered globally when no row is loaded', () => { + const table = makeGlobalTable({ data: [] }) + + expect(table.getColumn('name')!.getCanGlobalFilter()).toBe(false) + }) +}) + +describe('sparseRowsFeature development warnings', () => { + const clientFeatures = testFeatures({ + columnFilteringFeature, + rowSortingFeature, + sparseRowsFeature, + filteredRowModel: createFilteredRowModel(), + sortedRowModel: createSortedRowModel(), + filterFns, + sortFns, + }) + + function makeClientTable( + options?: Partial>, + ) { + return constructTable({ + features: clientFeatures, + columns: [{ accessorKey: 'name', id: 'name' }], + data: makeSparseData([2, 4]), + rowCount: 10, + getRowId: (person) => person.id, + ...options, + }) + } + + it('should warn once when a client-side row model is active', () => { + const warn = spyOnDevWarnings() + const table = makeClientTable({ manualFiltering: true }) + + table.getRowModel() + table.setOptions((old) => ({ ...old, data: makeSparseData([2, 6]) })) + table.getRowModel() + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0]![0]).toContain('manualSorting') + }) + + it('should warn when only the filtered row model runs on the client', () => { + const warn = spyOnDevWarnings() + const table = makeClientTable({ manualSorting: true }) + + table.getRowModel() + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0]![0]).toContain('manualFiltering') + }) + + it('should warn when only the grouped row model runs on the client', () => { + const groupedFeatures = testFeatures({ + columnGroupingFeature, + sparseRowsFeature, + groupedRowModel: createGroupedRowModel(), + }) + const makeGroupedTable = (manualGrouping: boolean) => + constructTable({ + features: groupedFeatures, + columns: [{ accessorKey: 'name', id: 'name' }], + data: makeSparseData([2, 4]), + rowCount: 10, + getRowId: (person) => person.id, + manualGrouping, + }) + const warn = spyOnDevWarnings() + + makeGroupedTable(true).getRowModel() + expect(warn).not.toHaveBeenCalled() + + makeGroupedTable(false).getRowModel() + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0]![0]).toContain('manualGrouping') + }) + + it('should not warn when filtering, grouping and sorting are manual', () => { + const allClientFeatures = testFeatures({ + columnFilteringFeature, + columnGroupingFeature, + rowSortingFeature, + sparseRowsFeature, + filteredRowModel: createFilteredRowModel(), + groupedRowModel: createGroupedRowModel(), + sortedRowModel: createSortedRowModel(), + filterFns, + sortFns, + }) + const warn = spyOnDevWarnings() + const table = constructTable({ + features: allClientFeatures, + columns: [{ accessorKey: 'name', id: 'name' }], + data: makeSparseData([2, 4]), + rowCount: 10, + getRowId: (person) => person.id, + manualFiltering: true, + manualGrouping: true, + manualSorting: true, + }) + + expect(table.getRowModel().rows).toHaveLength(10) + expect(warn).not.toHaveBeenCalled() + }) + + it('should not warn when filtering and sorting are manual', () => { + const warn = spyOnDevWarnings() + const table = makeClientTable({ + manualFiltering: true, + manualSorting: true, + }) + + expect(table.getRowModel().rows).toHaveLength(10) + expect(warn).not.toHaveBeenCalled() + }) + + it('should warn when getRowId returns the same id for two loaded rows', () => { + const warn = spyOnDevWarnings() + const data = makeSparseData([2, 4]) + data[6] = makePerson(3) + const table = makeTable({ data }) + + table.getRowModel() + setData(table, [...data]) + table.getRowModel() + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0]![0]).toContain("'person-3'") + + setData(table, makeSparseData([2, 4])) + table.getRowModel() + setData(table, data) + table.getRowModel() + + expect(warn).toHaveBeenCalledTimes(2) + }) + + it('should not warn outside of development', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const data = makeSparseData([2, 4]) + data[6] = makePerson(3) + + makeClientTable({ data }).getRowModel() + + expect(warn).not.toHaveBeenCalled() + }) +}) + +describe('tables without sparseRowsFeature', () => { + it('should not be part of stockFeatures', () => { + expect(Object.keys(stockFeatures)).not.toContain('sparseRowsFeature') + }) + + it('should keep rowCount out of the core row model', () => { + const table = constructTable({ + features: testFeatures(stockFeatures), + columns: [{ accessorKey: 'name', id: 'name' }], + data: [makePerson(0), makePerson(1), makePerson(2)], + rowCount: 100, + manualPagination: true, + getRowId: (person: Person) => person.id, + }) + const { rows } = table.getRowModel() + + expect(rows.map((row) => row.id)).toEqual([ + 'person-0', + 'person-1', + 'person-2', + ]) + expect(table.getRowCount()).toBe(100) + expect('getIsPlaceholder' in rows[0]!).toBe(false) + expect('getMissingRowRanges' in table).toBe(false) + }) + + it('should keep the selection, pinning and expanding APIs of stock tables', () => { + const table = constructTable({ + features: testFeatures(stockFeatures), + columns: [{ accessorKey: 'name', id: 'name' }], + data: [makePerson(0), makePerson(1)], + getRowId: (person: Person) => person.id, + getRowCanExpand: () => true, + }) + const row = table.getRowModel().rows[0]! + + expect(row.getCanSelect()).toBe(true) + expect(row.getCanMultiSelect()).toBe(true) + expect(row.getCanSelectSubRows()).toBe(true) + expect(row.getCanPin()).toBe(true) + expect(row.getCanExpand()).toBe(true) + + row.toggleSelected(true) + row.pin('top') + row.toggleExpanded(true) + + expect(table.atoms.rowSelection.get()).toEqual({ 'person-0': true }) + expect(table.atoms.rowPinning.get()).toEqual({ + top: ['person-0'], + bottom: [], + }) + expect(table.atoms.expanded.get()).toEqual({ 'person-0': true }) + expect(row.getIsExpanded()).toBe(true) + }) + + it('should not read the row model when a cell range is selected', () => { + const table = constructTable({ + features: testFeatures({ cellSelectionFeature }), + columns: [{ accessorKey: 'name', id: 'name' }], + data: [makePerson(0), makePerson(1)], + getRowId: (person: Person) => person.id, + }) + const getCoreRowModel = vi.spyOn(table, 'getCoreRowModel') + const range = { + anchorRowId: 'person-0', + anchorColumnId: 'name', + focusRowId: 'person-1', + focusColumnId: 'name', + } + + table.setFocusedCell('person-0', 'name') + table.selectCellRange(range) + + expect(getCoreRowModel).not.toHaveBeenCalled() + expect(table.atoms.cellSelection.get()).toEqual([range]) + expect(table.getSelectedCellCount()).toBe(2) + }) + + it('should run the auto resets of the default core row model', async () => { + const denseFeatures = testFeatures({ + rowPaginationFeature, + paginatedRowModel: createPaginatedRowModel(), + }) + const table = constructTable({ + features: denseFeatures, + columns: [{ accessorKey: 'name', id: 'name' }], + data: makeSparseData([0, 9]), + initialState: { pagination: { pageIndex: 2, pageSize: 2 } }, + }) + table.getRowModel() + await flushMicrotasks() + + table.setOptions((old) => ({ ...old, data: makeSparseData([0, 9]) })) + table.getRowModel() + await flushMicrotasks() + + expect(table.atoms.pagination.get().pageIndex).toBe(0) + }) +}) diff --git a/packages/table-core/tests/unit/features/sparse-rows/sparseRowsFeature.utils.test.ts b/packages/table-core/tests/unit/features/sparse-rows/sparseRowsFeature.utils.test.ts new file mode 100644 index 0000000000..90dcc9e03a --- /dev/null +++ b/packages/table-core/tests/unit/features/sparse-rows/sparseRowsFeature.utils.test.ts @@ -0,0 +1,311 @@ +import { describe, expect, it } from 'vitest' +import { + row_getIsPlaceholder, + table_createSparseRowModel, + table_getMissingRowRanges, +} from '../../../../src/static-functions' +import { constructTable, sparseRowsFeature } from '../../../../src' +import { testFeatures } from '../../../fixtures/features' +import type { Table, TableOptions, Table_Internal } from '../../../../src' + +interface Person { + id: string + name: string +} + +const features = testFeatures({ sparseRowsFeature }) + +// Core-only tables exercise the static functions on tables that never +// registered sparseRowsFeature. +const coreOnlyFeatures = testFeatures({}) + +function makeSparseData(...ranges: Array<[number, number]>): Array { + const data: Array = [] + for (const [startIndex, endIndex] of ranges) { + for (let i = startIndex; i <= endIndex; i++) { + data[i] = { id: `person-${i}`, name: `Person ${i}` } + } + } + return data +} + +function makeTable( + options?: Partial>, +): Table { + return constructTable({ + features, + columns: [{ accessorKey: 'name', id: 'name' }], + data: makeSparseData([10, 19], [40, 59]), + rowCount: 100, + getRowId: (person) => person.id, + ...options, + }) +} + +function asInternal(table: Table) { + return table as unknown as Table_Internal +} + +describe('table_getMissingRowRanges', () => { + it('should return the exact gaps with both bounds included', () => { + const table = makeTable() + + expect( + table_getMissingRowRanges(asInternal(table), { + startIndex: 0, + endIndex: 99, + }), + ).toEqual([ + { startIndex: 0, endIndex: 9 }, + { startIndex: 20, endIndex: 39 }, + { startIndex: 60, endIndex: 99 }, + ]) + expect(table.getMissingRowRanges({ startIndex: 5, endIndex: 20 })).toEqual([ + { startIndex: 5, endIndex: 9 }, + { startIndex: 20, endIndex: 20 }, + ]) + expect(table.getMissingRowRanges({ startIndex: 9, endIndex: 9 })).toEqual([ + { startIndex: 9, endIndex: 9 }, + ]) + }) + + it('should return no ranges when all rows in the range are loaded', () => { + const table = makeTable() + + expect(table.getMissingRowRanges({ startIndex: 10, endIndex: 19 })).toEqual( + [], + ) + expect(table.getMissingRowRanges({ startIndex: 45, endIndex: 45 })).toEqual( + [], + ) + }) + + it('should clamp the range to the rows of the table', () => { + const table = makeTable() + + expect( + table.getMissingRowRanges({ startIndex: -20, endIndex: 12 }), + ).toEqual([{ startIndex: 0, endIndex: 9 }]) + expect( + table.getMissingRowRanges({ startIndex: 95, endIndex: 500 }), + ).toEqual([{ startIndex: 95, endIndex: 99 }]) + expect( + table.getMissingRowRanges({ startIndex: 55, endIndex: Infinity }), + ).toEqual([{ startIndex: 60, endIndex: 99 }]) + expect( + table.getMissingRowRanges({ startIndex: 100, endIndex: 200 }), + ).toEqual([]) + }) + + it('should return no ranges for a range that has no rows', () => { + const table = makeTable() + + expect(table.getMissingRowRanges({ startIndex: 30, endIndex: 20 })).toEqual( + [], + ) + expect( + table.getMissingRowRanges({ startIndex: Number.NaN, endIndex: 20 }), + ).toEqual([]) + expect( + table.getMissingRowRanges({ startIndex: 0, endIndex: Number.NaN }), + ).toEqual([]) + }) + + it('should read fractional bounds as the whole rows between them', () => { + const table = makeTable() + + expect( + table.getMissingRowRanges({ startIndex: 4.2, endIndex: 7.9 }), + ).toEqual([{ startIndex: 5, endIndex: 7 }]) + }) + + it('should treat undefined entries as missing rows', () => { + const data = makeSparseData([0, 5]) + data[2] = undefined as unknown as Person + const table = makeTable({ data, rowCount: 6 }) + + expect(table.getMissingRowRanges({ startIndex: 0, endIndex: 5 })).toEqual([ + { startIndex: 2, endIndex: 2 }, + ]) + }) + + it('should use data.length when rowCount is not set', () => { + const table = makeTable({ rowCount: undefined }) + + expect(table.getMissingRowRanges({ startIndex: 0, endIndex: 500 })).toEqual( + [ + { startIndex: 0, endIndex: 9 }, + { startIndex: 20, endIndex: 39 }, + ], + ) + }) + + it('should return one whole block for each block with a missing row', () => { + const table = makeTable() + + expect( + table.getMissingRowRanges({ + startIndex: 15, + endIndex: 65, + blockSize: 25, + }), + ).toEqual([ + { startIndex: 0, endIndex: 24 }, + { startIndex: 25, endIndex: 49 }, + { startIndex: 50, endIndex: 74 }, + ]) + }) + + it('should skip a block when its rows in the range are loaded', () => { + const table = makeTable() + + expect( + table.getMissingRowRanges({ + startIndex: 12, + endIndex: 18, + blockSize: 25, + }), + ).toEqual([]) + expect( + table.getMissingRowRanges({ + startIndex: 40, + endIndex: 62, + blockSize: 10, + }), + ).toEqual([{ startIndex: 60, endIndex: 69 }]) + }) + + it('should return the same block for different ranges inside it', () => { + const table = makeTable() + const block = [{ startIndex: 60, endIndex: 79 }] + + expect( + table.getMissingRowRanges({ + startIndex: 61, + endIndex: 70, + blockSize: 20, + }), + ).toEqual(block) + expect( + table.getMissingRowRanges({ + startIndex: 68, + endIndex: 79, + blockSize: 20, + }), + ).toEqual(block) + }) + + it('should end the last block at the last row', () => { + const table = makeTable({ rowCount: 95 }) + + expect( + table.getMissingRowRanges({ + startIndex: 85, + endIndex: 94, + blockSize: 30, + }), + ).toEqual([ + { startIndex: 60, endIndex: 89 }, + { startIndex: 90, endIndex: 94 }, + ]) + }) + + it.each([0, -5, Number.NaN, Infinity])( + 'should return exact gaps when blockSize is %s', + (blockSize) => { + const table = makeTable() + + expect( + table.getMissingRowRanges({ startIndex: 5, endIndex: 25, blockSize }), + ).toEqual([ + { startIndex: 5, endIndex: 9 }, + { startIndex: 20, endIndex: 25 }, + ]) + }, + ) + + it('should not build the core row model', () => { + const table = makeTable({ + rowCount: 100_000, + getRowId: () => { + throw new Error('The core row model was built') + }, + }) + + expect( + table.getMissingRowRanges({ startIndex: 99_950, endIndex: 99_999 }), + ).toEqual([{ startIndex: 99_950, endIndex: 99_999 }]) + }) + + it('should read the data of a table without the feature', () => { + const table = constructTable({ + features: coreOnlyFeatures, + columns: [], + data: makeSparseData([0, 4]), + }) + + expect( + table_getMissingRowRanges( + table as unknown as Table_Internal, + { startIndex: 0, endIndex: 20 }, + ), + ).toEqual([]) + }) +}) + +describe('row_getIsPlaceholder', () => { + it('should return true only for rows without data', () => { + const { rows } = makeTable().getRowModel() + + expect(row_getIsPlaceholder(rows[9]!)).toBe(true) + expect(row_getIsPlaceholder(rows[10]!)).toBe(false) + }) + + it('should return false for the rows of a table without the feature', () => { + const table = constructTable({ + features: coreOnlyFeatures, + columns: [], + data: makeSparseData([0, 1]), + }) + + expect(row_getIsPlaceholder(table.getRowModel().rows[0]!)).toBe(false) + }) +}) + +describe('table_createSparseRowModel', () => { + it('should create a memoized row model with rowCount rows', () => { + const table = makeTable() + const getRowModel = table_createSparseRowModel(asInternal(table)) + const rowModel = getRowModel() + + expect(rowModel.rows).toHaveLength(100) + expect(rowModel.rows[10]!.id).toBe('person-10') + expect(rowModel.rows[9]!.id).toBe('__placeholder_9') + expect(getRowModel()).toBe(rowModel) + }) + + it('should build an empty row model for an empty table', () => { + const table = makeTable({ data: [], rowCount: 0 }) + + expect(table.getRowModel()).toEqual({ + rows: [], + flatRows: [], + rowsById: {}, + }) + }) + + it('should drop the placeholder rows after rowCount when the table shrinks', () => { + const table = makeTable({ data: [], rowCount: 5 }) + const before = table.getRowModel().rows + + table.setOptions((old) => ({ ...old, rowCount: 2 })) + expect(table.getRowModel().rows).toHaveLength(2) + + table.setOptions((old) => ({ ...old, rowCount: 5 })) + const after = table.getRowModel().rows + + expect(after[1]).toBe(before[1]) + expect(after[4]).not.toBe(before[4]) + expect(after[4]!.id).toBe('__placeholder_4') + }) +}) From 2cc41234a9326226c35d482b6afe450bd6c5d2d5 Mon Sep 17 00:00:00 2001 From: Albert Nimtz Date: Fri, 27 Nov 2026 13:03:47 +0100 Subject: [PATCH 02/12] fix(table-core): warn about client-side row models only with placeholder rows The development warning of sparseRowsFeature for a client-side filtered, grouped, or sorted row model was logged for each table that registers one of these row models without its manual* flag. A table that has every row loaded has a correct client-side result, so the warning was wrong there. The warning is now logged only when the built row model has a placeholder row. It is still logged once for each table. Co-Authored-By: Claude Fable 5.2 --- docs/guide/sparse-rows.md | 2 +- .../sparse-rows/sparseRowsFeature.utils.ts | 3 +++ .../sparse-rows/sparseRowsFeature.test.ts | 15 +++++++++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/docs/guide/sparse-rows.md b/docs/guide/sparse-rows.md index 16a363929d..aa00ee1341 100644 --- a/docs/guide/sparse-rows.md +++ b/docs/guide/sparse-rows.md @@ -125,7 +125,7 @@ A block stays missing until its rows are in `data`, so the same range can be ret Row 99,999 under one sort order is a different row under another sort order. The loaded rows are only correct for the sorting and filters that they were loaded with. -- Sort, filter, and group on the server. Set `manualSorting`, `manualFiltering`, and `manualGrouping`, or do not register the client-side row models. A client-side row model only sees the loaded rows, so its result is wrong. The table logs a warning in development when one is active. `manualPagination` is different: client-side pagination keeps the index space, see [Pagination](#pagination). +- Sort, filter, and group on the server. Set `manualSorting`, `manualFiltering`, and `manualGrouping`, or do not register the client-side row models. A client-side row model only sees the loaded rows, so its result is wrong. The table logs a warning in development when one is active and a row is not loaded. `manualPagination` is different: client-side pagination keeps the index space, see [Pagination](#pagination). - When sorting or a filter changes, start again with an empty `data` array and the new `rowCount`. If you load blocks with TanStack Query, put the sorting and filter state into the query key. - With this feature, a new `data` array does not run the `autoResetPageIndex`, `autoResetExpanded`, and other `autoReset*` behaviors, because a new array usually means that more rows are loaded. Reset the page index or the scroll position yourself when sorting or a filter changes. - Do not let the table read column behavior from row values, because placeholder rows have no values. Set `sortDescFirst` on the table or on your columns; without it, the first sort direction of a column comes from the values of the first rows. If you use `column.getCanGlobalFilter()`, set `enableGlobalFilter: true` on the columns that the server can search; without it, the table reads the loaded rows until it finds a value, and the result is `false` while no row is loaded. diff --git a/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts index 9b9c7255dd..5d0c51efff 100644 --- a/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts +++ b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts @@ -84,6 +84,7 @@ export function table_createSparseRowModel< } const { getSubRows } = table.options let duplicateId: string | undefined + let hasPlaceholderRow = false placeholderRows.length = Math.min(placeholderRows.length, rowCount) @@ -92,6 +93,7 @@ export function table_createSparseRowModel< let row: Row if (originalRow === undefined) { + hasPlaceholderRow = true row = placeholderRows[i] ??= constructRow( table, placeholderRowIdPrefix + i, @@ -129,6 +131,7 @@ export function table_createSparseRowModel< table.options if ( + hasPlaceholderRow && !hasWarnedClientRowModels && ((features.filteredRowModel && !manualFiltering) || (features.groupedRowModel && !manualGrouping) || diff --git a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts index 75fd7ad9d5..756b72c0e5 100644 --- a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts +++ b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts @@ -1081,6 +1081,21 @@ describe('sparseRowsFeature development warnings', () => { expect(warn).toHaveBeenCalledTimes(2) }) + it('should not warn about a client-side row model while every row is loaded', () => { + const warn = spyOnDevWarnings() + const table = makeClientTable({ data: makeSparseData([0, 9]) }) + + table.getRowModel() + + expect(warn).not.toHaveBeenCalled() + + table.setOptions((old) => ({ ...old, data: makeSparseData([0, 4]) })) + table.getRowModel() + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0]![0]).toContain('manualFiltering') + }) + it('should not warn outside of development', () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const data = makeSparseData([2, 4]) From 579502dc45ad67dc78ce6e8eaa6f8201820c501d Mon Sep 17 00:00:00 2001 From: Albert Nimtz Date: Fri, 27 Nov 2026 13:03:57 +0100 Subject: [PATCH 03/12] fix(table-core): warn when getRowId returns a reserved placeholder id A placeholder row of sparseRowsFeature has the id '__placeholder_'. When getRowId returned such an id for a loaded row, the two rows shared one entry in rowsById. The table gave no warning, or it gave the warning for overlapping ranges, which did not name the cause. In development, the table now logs one warning when the id of a loaded row starts with the placeholder prefix. The guide says that the prefix is reserved. Co-Authored-By: Claude Fable 5.2 --- docs/guide/sparse-rows.md | 1 + .../sparse-rows/sparseRowsFeature.utils.ts | 20 ++++++++++---- .../sparse-rows/sparseRowsFeature.test.ts | 26 +++++++++++++++++++ 3 files changed, 42 insertions(+), 5 deletions(-) diff --git a/docs/guide/sparse-rows.md b/docs/guide/sparse-rows.md index aa00ee1341..2d7be92f68 100644 --- a/docs/guide/sparse-rows.md +++ b/docs/guide/sparse-rows.md @@ -91,6 +91,7 @@ A placeholder row has no data: - `row.getValue()` and `cell.getValue()` return `undefined`. The table does not call the column accessors. - Do not render the `cell` templates of your columns for a placeholder row if they read `row.original`. - `row.id` is temporary. It starts with `__placeholder_` and changes to the `getRowId` result when the row is loaded. Do not store it. +- The `__placeholder_` prefix is reserved. `getRowId` must not return an ID that starts with it, or the table can mistake the loaded row for a placeholder row. In development, the table logs a warning for such an ID. ## Load the Missing Ranges diff --git a/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts index 5d0c51efff..fedce467c0 100644 --- a/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts +++ b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts @@ -69,6 +69,7 @@ export function table_createSparseRowModel< // used again each time `data` changes. const placeholderRows: Array> = [] let hasWarnedClientRowModels = false + let hasWarnedReservedId = false let lastWarnedDuplicateId: string | undefined return tableMemo({ @@ -84,6 +85,7 @@ export function table_createSparseRowModel< } const { getSubRows } = table.options let duplicateId: string | undefined + let reservedId: string | undefined let hasPlaceholderRow = false placeholderRows.length = Math.min(placeholderRows.length, rowCount) @@ -109,11 +111,12 @@ export function table_createSparseRowModel< i, 0, ) - if ( - process.env.NODE_ENV === 'development' && - rowModel.rowsById[row.id] - ) { - duplicateId ??= row.id + if (process.env.NODE_ENV === 'development') { + if (row.id.startsWith(placeholderRowIdPrefix)) { + reservedId ??= row.id + } else if (rowModel.rowsById[row.id]) { + duplicateId ??= row.id + } } } @@ -143,6 +146,13 @@ export function table_createSparseRowModel< ) } + if (reservedId !== undefined && !hasWarnedReservedId) { + hasWarnedReservedId = true + console.warn( + `sparseRowsFeature: getRowId returned '${reservedId}' for a loaded row. Row ids that start with '${placeholderRowIdPrefix}' are reserved for placeholder rows, so the table can mistake this row for a placeholder row. Return a different id.`, + ) + } + if ( duplicateId !== undefined && duplicateId !== lastWarnedDuplicateId diff --git a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts index 756b72c0e5..58c14f6d18 100644 --- a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts +++ b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts @@ -1096,6 +1096,32 @@ describe('sparseRowsFeature development warnings', () => { expect(warn.mock.calls[0]![0]).toContain('manualFiltering') }) + it('should warn once when a loaded row has an id with the placeholder prefix', () => { + const warn = spyOnDevWarnings() + const data = makeSparseData([2, 4]) + data[3] = { ...makePerson(3), id: '__placeholder_7' } + const table = makeTable({ data }) + + table.getRowModel() + setData(table, [...data]) + table.getRowModel() + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0]![0]).toContain("'__placeholder_7'") + expect(warn.mock.calls[0]![0]).toContain('reserved') + }) + + it('should not report an id with the placeholder prefix as an overlap of loaded ranges', () => { + const warn = spyOnDevWarnings() + const data = makeSparseData([2, 4]) + data[3] = { ...makePerson(3), id: '__placeholder_1' } + + makeTable({ data }).getRowModel() + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0]![0]).toContain('reserved') + }) + it('should not warn outside of development', () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const data = makeSparseData([2, 4]) From 1fc675eaaacc231aa741760c3884962b4a2be8d1 Mon Sep 17 00:00:00 2001 From: Albert Nimtz Date: Fri, 27 Nov 2026 13:08:27 +0100 Subject: [PATCH 04/12] feat(table-core): let the focused cell sit on a placeholder row With sparseRowsFeature, moveCellSelection() stopped at a placeholder row and setFocusedCell() ignored one. A grid that uses these functions could not move with the keyboard into rows that are not loaded, so the keyboard could not start the load of the next block. The focused cell can now be in a placeholder row. A corner of a range still cannot. - moveCellSelection() and setFocusedCell() put the focus on a placeholder row. The state holds it as the last range, which is one cell with the placeholder id. No cell is selected, and cell.getCanSelect() is still false. - When the row is loaded, the focus follows it. A placeholder id holds the index, so getFocusedCell(), cell.getIsFocused(), and the selection read the loaded row at that index. The next write replaces the placeholder id with the id of the loaded row. - extendCellSelection() stops at the last loaded row, and does nothing while the focused cell is in a placeholder row. A Shift click then starts a new selection. - setCellSelection() removes a range with a corner on a placeholder row, and getCellSelectionBounds() does not resolve such a range. Before, only selectCellRange() had this guard. Tables without sparseRowsFeature keep their behavior, and their writes still do not read the row model. Co-Authored-By: Claude Fable 5.2 --- .changeset/sparse-rows-feature.md | 2 +- docs/guide/sparse-rows.md | 23 +- packages/table-core/src/core/featureStubs.ts | 16 ++ .../cellSelectionFeature.utils.ts | 228 +++++++++++++---- .../features/sparse-rows/sparseRowsFeature.ts | 4 + .../sparse-rows/sparseRowsFeature.types.ts | 8 + .../sparse-rows/sparseRowsFeature.utils.ts | 22 ++ .../sparse-rows/sparseRowsFeature.test.ts | 229 +++++++++++++++++- 8 files changed, 473 insertions(+), 59 deletions(-) diff --git a/.changeset/sparse-rows-feature.md b/.changeset/sparse-rows-feature.md index d97e3f40ee..f9f15808ee 100644 --- a/.changeset/sparse-rows-feature.md +++ b/.changeset/sparse-rows-feature.md @@ -2,4 +2,4 @@ '@tanstack/table-core': minor --- -Add the opt-in `sparseRowsFeature` for remote tables: `data` holds the loaded rows by their absolute index, `rowCount` is the total, missing rows become placeholder rows (`row.getIsPlaceholder()`), and `table.getMissingRowRanges()` returns the ranges to load. +Add the opt-in `sparseRowsFeature` for remote tables: `data` holds the loaded rows by their absolute index, `rowCount` is the total, missing rows become placeholder rows (`row.getIsPlaceholder()`), and `table.getMissingRowRanges()` returns the ranges to load. With `cellSelectionFeature`, the focused cell can be in a placeholder row, so keyboard navigation can move into rows that are not loaded. diff --git a/docs/guide/sparse-rows.md b/docs/guide/sparse-rows.md index 2d7be92f68..9f8291b81b 100644 --- a/docs/guide/sparse-rows.md +++ b/docs/guide/sparse-rows.md @@ -152,13 +152,30 @@ The state of a loaded row stays when you remove the row from `data`. The row is ## Cell Selection -`cellSelectionFeature` stores the two corners of each range by row ID, so a placeholder row cannot be a corner: +`cellSelectionFeature` stores the two corners of each range by row ID, so a placeholder row cannot be a corner of a range. The focused cell is different. It can be in a placeholder row, so the user can move with the keyboard into rows that are not loaded. - `cell.getCanSelect()` returns `false` for the cells of a placeholder row, and their selection handlers do nothing. The `enableCellSelection` callback is not called with such a cell. -- `selectCellRange()` and `setFocusedCell()` do nothing when a row ID belongs to a placeholder row. -- `moveCellSelection()` and `extendCellSelection()` stop at a placeholder row. Load the next rows before the user gets to them. +- `moveCellSelection()` moves the focus onto a placeholder row as it does onto a loaded row. `setFocusedCell()` also accepts the ID of a placeholder row, for example to jump to the last row. +- While the focused cell is in a placeholder row, no cell is selected. `cell.getIsFocused()` returns `true` and `cell.getTabIndex()` returns `0` for that cell, and `cell.getIsSelected()` returns `false`. +- When the row of the focused cell is loaded, the focus follows the row. `table.getFocusedCell()` returns the cell of the loaded row at the same index and in the same column. This cell is then selected, like the focused cell of any loaded row. +- `extendCellSelection()` stops at the last loaded row, so a range does not grow onto a placeholder row. It does nothing while the focused cell is in a placeholder row. A range event on a loaded cell, which is a Shift click by default, then starts a new selection at that cell. +- `selectCellRange()` ignores a range that starts or ends on a placeholder row, unless the range is one cell. `setCellSelection()` removes such a range from the new state. - `selectAllCells()` selects from the first loaded row to the last loaded row. +The table does not load rows when the focus moves. Use the index of the focused row to load the rows around it: + +```ts +table.moveCellSelection('down') + +const focusedRow = table.getFocusedCell()?.row + +if (focusedRow?.getIsPlaceholder()) { + loadVisibleRows(focusedRow.index, focusedRow.index) +} +``` + +While the focused cell is in a placeholder row, the last range in the `cellSelection` state is that one cell, and it holds the placeholder ID of the row. This is the only state in which the table stores a placeholder ID. The table reads this ID as "the row at this index". The ID stays in the state after the row is loaded. The next change of the cell selection replaces it with the ID of the loaded row. Call `table.getFocusedCell()` to get the row that has the focus now. + A range can span rows that are not loaded. Its corners are loaded rows, and the placeholder rows between them are not selected: `getSelectedCellIds()`, `getSelectedCellCount()`, and `getCellSelectionRowIds()` leave them out. `getSelectedCellRangesData()` keeps the position of each row, so the grid of a range has an empty entry for each placeholder row; skip these entries when you copy the data. The rows become part of the selection when they are loaded. A range whose corner row is removed from `data` stays in state and selects nothing until that row is loaded again. ## Offset Drift diff --git a/packages/table-core/src/core/featureStubs.ts b/packages/table-core/src/core/featureStubs.ts index af6fe7a575..61e8839f39 100644 --- a/packages/table-core/src/core/featureStubs.ts +++ b/packages/table-core/src/core/featureStubs.ts @@ -316,3 +316,19 @@ export function getIsPlaceholderRow(row: object): boolean { export function getCanHavePlaceholderRows(table: object): boolean { return !!(table as Partial>)._createSparseRowModel } + +/** + * The row at the index that a placeholder row id holds. `undefined` for all + * other ids, and without the feature. + */ +export function getRowByPlaceholderId< + TFeatures extends TableFeatures, + TData extends RowData, +>( + table: Table_Internal, + rowId: string, +): Row | undefined { + return ( + table as Partial> + )._getRowByPlaceholderId?.(rowId) +} diff --git a/packages/table-core/src/features/cell-selection/cellSelectionFeature.utils.ts b/packages/table-core/src/features/cell-selection/cellSelectionFeature.utils.ts index 3179787653..a68280da1c 100644 --- a/packages/table-core/src/features/cell-selection/cellSelectionFeature.utils.ts +++ b/packages/table-core/src/features/cell-selection/cellSelectionFeature.utils.ts @@ -1,12 +1,14 @@ import { callMemoOrStaticFn, cloneState, + functionalUpdate, makeObjectMap, setStateSlice, } from '../../utils' import { getCanHavePlaceholderRows, getIsPlaceholderRow, + getRowByPlaceholderId, getVisibleLeafColumns, orderByColumnPinning, } from '../../core/featureStubs' @@ -51,6 +53,10 @@ export function getDefaultCellSelectionState(): CellSelectionState { /** * Routes a cell selection updater through the table's selection change handler. * + * In a table that can have placeholder rows, a range with a corner on a + * placeholder row is removed from the result. Only the last range can stay, + * when it is one cell: it is the focused cell. + * * @example * ```ts * table_setCellSelection(table, (old) => old.slice(0, -1)) @@ -65,7 +71,87 @@ export function table_setCellSelection< ) { // Unguarded: selection updates are pointer-driven and ranges can be large. // Keep the hot path direct; the auto-reset path guards in reset below. - table.options.onCellSelectionChange?.(updater) + table.options.onCellSelectionChange?.( + getCanHavePlaceholderRows(table) + ? (old) => removePlaceholderCorners(table, functionalUpdate(updater, old)) + : updater, + ) +} + +function isOneCellRange(range: CellSelectionRange): boolean { + return ( + range.anchorRowId === range.focusRowId && + range.anchorColumnId === range.focusColumnId + ) +} + +/** + * Changes the id of a placeholder row to the id of the row that is at its + * index now. All other ids stay the same. + */ +function resolveRowId( + table: Table_Internal, + rowId: string, +): string { + return getRowByPlaceholderId(table, rowId)?.id ?? rowId +} + +/** + * Tests whether a row id is the id of a placeholder row. This is also true + * after the row is loaded, because the row then has a different id. + */ +function isPlaceholderRowId< + TFeatures extends TableFeatures, + TData extends RowData, +>(table: Table_Internal, rowId: string): boolean { + if (!getCanHavePlaceholderRows(table)) return false + + const row = table.getCoreRowModel().rowsById[rowId] + + return row ? getIsPlaceholderRow(row) : !!getRowByPlaceholderId(table, rowId) +} + +/** + * Removes the ranges that a placeholder row id makes invalid. + * + * A placeholder row id can only stay in a range of one cell. When its row is + * loaded, the range gets the id of that row. When its row is not loaded, the + * range stays only as the last range, where it is the focused cell. + */ +function removePlaceholderCorners< + TFeatures extends TableFeatures, + TData extends RowData, +>( + table: Table_Internal, + ranges: CellSelectionState, +): CellSelectionState { + const next: CellSelectionState = [] + let isChanged = false + + for (let i = ranges.length - 1; i >= 0; i--) { + const range = ranges[i]! + let nextRange: CellSelectionRange | undefined = range + + if ( + isPlaceholderRowId(table, range.anchorRowId) || + isPlaceholderRowId(table, range.focusRowId) + ) { + const rowId = resolveRowId(table, range.anchorRowId) + + if (!isOneCellRange(range)) { + nextRange = undefined + } else if (rowId !== range.anchorRowId) { + nextRange = { ...range, anchorRowId: rowId, focusRowId: rowId } + } else if (next.length) { + nextRange = undefined + } + } + + if (nextRange !== range) isChanged = true + if (nextRange) next.push(nextRange) + } + + return isChanged ? next.reverse() : ranges } /** @@ -336,9 +422,26 @@ function findMergeBoundsAt( return undefined } +/** + * Resolves a stored row id to its row. With `canUsePlaceholderId`, the id of a + * placeholder row also finds the row that is loaded at its index now. + */ +function resolveRow( + table: Table_Internal, + rowId: string, + canUsePlaceholderId: boolean, +): Row | undefined { + return ( + table.getPrePaginatedRowModel().rowsById[rowId] ?? + table.getCoreRowModel().rowsById[rowId] ?? + (canUsePlaceholderId ? getRowByPlaceholderId(table, rowId) : undefined) + ) +} + /** * Resolves a row id to its display-order index, or `-1` when it no longer - * identifies a row in the current order. + * identifies a row in the current order. A placeholder row has no index here, + * because it cannot be a corner of a range. * * Callers must have already called `table.getRowsInDisplayOrder()`, which is * what populates the display index cache each row reads. @@ -350,16 +453,15 @@ function resolveRowIndex< table: Table_Internal, rows: ReadonlyArray>, rowId: string, + canUsePlaceholderId: boolean, ): number { - const row = - table.getPrePaginatedRowModel().rowsById[rowId] ?? - table.getCoreRowModel().rowsById[rowId] + const row = resolveRow(table, rowId, canUsePlaceholderId) - if (!row) return -1 + if (!row || getIsPlaceholderRow(row)) return -1 const index = row.getDisplayIndex() - if (index < 0 || index >= rows.length || rows[index]?.id !== rowId) { + if (index < 0 || index >= rows.length || rows[index]?.id !== row.id) { return -1 } @@ -400,8 +502,16 @@ export function table_getCellSelectionBounds< for (let i = 0; i < ranges.length; i++) { const range = ranges[i]! - const anchorRowIndex = resolveRowIndex(table, rows, range.anchorRowId) - const focusRowIndex = resolveRowIndex(table, rows, range.focusRowId) + const isOneCell = isOneCellRange(range) + const anchorRowIndex = resolveRowIndex( + table, + rows, + range.anchorRowId, + isOneCell, + ) + const focusRowIndex = isOneCell + ? anchorRowIndex + : resolveRowIndex(table, rows, range.focusRowId, false) const anchorColumnIndex = columnIndexes[range.anchorColumnId] ?? -1 const focusColumnIndex = columnIndexes[range.focusColumnId] ?? -1 @@ -578,6 +688,9 @@ export function cell_getIsSelected< /** * Checks whether this cell is the active cell. * + * When the active cell was set on a placeholder row and that row is loaded + * now, the cell of the loaded row is the active cell. + * * @example * ```ts * const isFocused = cell_getIsFocused(cell) @@ -591,11 +704,11 @@ export function cell_getIsFocused< const ranges = cell.table.atoms.cellSelection?.get() const active = ranges?.[ranges.length - 1] - if (!active) return false + if (!active || active.anchorColumnId !== cell.column.id) return false return ( - active.anchorRowId === cell.row.id && - active.anchorColumnId === cell.column.id + active.anchorRowId === cell.row.id || + resolveRowId(cell.table, active.anchorRowId) === cell.row.id ) } @@ -725,6 +838,9 @@ function isStripOutside( * A1 to C5 leaves the active cell at A1, so the active range's anchor already * is the active cell. * + * The active cell can be a cell of a placeholder row. When that row is loaded, + * the cell at the same index and column is the active cell. + * * @example * ```ts * const cell = table_getFocusedCell(table) @@ -741,16 +857,17 @@ export function table_getFocusedCell< if (!active) return undefined - const row = - table.getPrePaginatedRowModel().rowsById[active.anchorRowId] ?? - table.getCoreRowModel().rowsById[active.anchorRowId] - - return row?.getAllCellsByColumnId()[active.anchorColumnId] + return resolveRow(table, active.anchorRowId, true)?.getAllCellsByColumnId()[ + active.anchorColumnId + ] } /** * Collapses the selection to a single cell at the given coordinates. * + * The cell can be in a placeholder row. It is then the focused cell, but it + * is not selected until its row is loaded. + * * @example * ```ts * table_setFocusedCell(table, '3', 'firstName') @@ -770,25 +887,12 @@ export function table_setFocusedCell< // Selection writes -/** - * Tests whether a row id is the temporary id of a placeholder row. - */ -function isPlaceholderRowId< - TFeatures extends TableFeatures, - TData extends RowData, ->(table: Table_Internal, rowId: string): boolean { - if (!getCanHavePlaceholderRows(table)) return false - - const row = table.getCoreRowModel().rowsById[rowId] - - return !!row && getIsPlaceholderRow(row) -} - /** * Selects a rectangle using replace, include, or exclude semantics. * * A range that starts or ends on a placeholder row is ignored, because the id - * of that row changes when the row is loaded. + * of that row changes when the row is loaded. A range of one cell is not + * ignored: it puts the focus on that cell. * * @example * ```ts @@ -804,8 +908,9 @@ export function table_selectCellRange< opts?: SelectCellRangeOptions, ) { if ( - isPlaceholderRowId(table, range.anchorRowId) || - isPlaceholderRowId(table, range.focusRowId) + !isOneCellRange(range) && + (isPlaceholderRowId(table, range.anchorRowId) || + isPlaceholderRowId(table, range.focusRowId)) ) { return } @@ -911,13 +1016,16 @@ function getDirectionDelta(direction: CellSelectionDirection): { * * Columns that cannot be selected are skipped over rather than landed on, so * arrow navigation never parks on an opted-out column. Returns `null` when the - * step would leave the grid or find no selectable column. + * step would leave the grid or find no selectable column. Without + * `canLandOnPlaceholderRow`, it also returns `null` when the step would land + * on a placeholder row. */ function stepCoordinate( table: Table_Internal, rowId: string, columnId: string, direction: CellSelectionDirection, + canLandOnPlaceholderRow: boolean, ): { rowId: string; columnId: string } | null { // Navigation is constrained to the final row model. In particular, the // pre-pagination display-order model contains rows from every page and @@ -1032,7 +1140,11 @@ function stepCoordinate( const landingRow = rows[landingRowIndex] const landingColumn = columns[landingColumnIndex] - if (!landingRow || !landingColumn || getIsPlaceholderRow(landingRow)) { + if ( + !landingRow || + !landingColumn || + (!canLandOnPlaceholderRow && getIsPlaceholderRow(landingRow)) + ) { return null } @@ -1046,7 +1158,8 @@ function stepCoordinate( * Moves the selection one step in a direction, collapsing it to a single cell. * * With nothing selected, this selects the first selectable cell so keyboard - * navigation has somewhere to start. + * navigation has somewhere to start. The step can land on a placeholder row, + * so the focus can move into rows that are not loaded. * * @example * ```ts @@ -1061,22 +1174,21 @@ export function table_moveCellSelection< const active = ranges?.[ranges.length - 1] if (!active) { - const firstRow = table - .getRowModel() - .rows.find((row) => !getIsPlaceholderRow(row)) + const rows = table.getRowModel().rows const columns = getSelectableColumns(table) - if (!firstRow || !columns.length) return + if (!rows.length || !columns.length) return - table_setFocusedCell(table, firstRow.id, columns[0]!.id) + table_setFocusedCell(table, rows[0]!.id, columns[0]!.id) return } const next = stepCoordinate( table, - active.anchorRowId, + resolveRowId(table, active.anchorRowId), active.anchorColumnId, direction, + true, ) if (!next) return @@ -1087,6 +1199,10 @@ export function table_moveCellSelection< /** * Extends the active range one step in a direction, keeping its anchor fixed. * + * A placeholder row cannot be a corner of a range. The range does not grow + * onto a placeholder row, and it does not start from a focused cell in a + * placeholder row. + * * @example * ```ts * table_extendCellSelection(table, 'right') @@ -1104,11 +1220,16 @@ export function table_extendCellSelection< return } + const anchorRowId = resolveRowId(table, active.anchorRowId) + + if (isPlaceholderRowId(table, anchorRowId)) return + const next = stepCoordinate( table, - active.focusRowId, + resolveRowId(table, active.focusRowId), active.focusColumnId, direction, + false, ) if (!next) return @@ -1117,9 +1238,11 @@ export function table_extendCellSelection< if (!old.length) return old const nextRanges = old.slice(0, -1) + const oldActive = old[old.length - 1]! nextRanges.push({ - ...old[old.length - 1]!, + ...oldActive, + anchorRowId: resolveRowId(table, oldActive.anchorRowId), focusRowId: next.rowId, focusColumnId: next.columnId, }) @@ -1479,9 +1602,18 @@ export function cell_getSelectionStartHandler< // shift-extend keeps the active anchor and moves only its focus if (isRangeEvent && active) { - const ranges = old.slice(0, -1) - ranges.push({ ...active, focusRowId: rowId, focusColumnId: columnId }) - return ranges + const anchorRowId = resolveRowId(table, active.anchorRowId) + + if (!isPlaceholderRowId(table, anchorRowId)) { + const ranges = old.slice(0, -1) + ranges.push({ + ...active, + anchorRowId, + focusRowId: rowId, + focusColumnId: columnId, + }) + return ranges + } } const range: CellSelectionRange = { diff --git a/packages/table-core/src/features/sparse-rows/sparseRowsFeature.ts b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.ts index 753346747a..de763c44ef 100644 --- a/packages/table-core/src/features/sparse-rows/sparseRowsFeature.ts +++ b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.ts @@ -3,6 +3,7 @@ import { row_getIsPlaceholder, table_createSparseRowModel, table_getMissingRowRanges, + table_getRowByPlaceholderId, } from './sparseRowsFeature.utils' import type { TableFeature } from '../../types/TableFeatures' @@ -27,6 +28,9 @@ export const sparseRowsFeature: TableFeature = { table__createSparseRowModel: { fn: () => table_createSparseRowModel(table), }, + table__getRowByPlaceholderId: { + fn: (rowId) => table_getRowByPlaceholderId(table, rowId), + }, table_getMissingRowRanges: { fn: (options) => table_getMissingRowRanges(table, options), }, diff --git a/packages/table-core/src/features/sparse-rows/sparseRowsFeature.types.ts b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.types.ts index b9156c9d10..ea461460ec 100644 --- a/packages/table-core/src/features/sparse-rows/sparseRowsFeature.types.ts +++ b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.types.ts @@ -1,4 +1,5 @@ import type { RowModel } from '../../core/row-models/coreRowModelsFeature.types' +import type { Row } from '../../types/Row' import type { RowData } from '../../types/type-utils' import type { TableFeatures } from '../../types/TableFeatures' @@ -52,6 +53,13 @@ export interface Table_SparseRows< * @internal */ _createSparseRowModel: () => () => RowModel + /** + * Returns the row at the index that a placeholder row id holds, also after + * that row is loaded. Returns `undefined` for all other ids. + * + * @internal + */ + _getRowByPlaceholderId: (rowId: string) => Row | undefined /** * Returns the ranges between `startIndex` and `endIndex` (both included) that * `data` has no rows for. The table does not load rows; request these ranges diff --git a/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts index fedce467c0..f490f819b3 100644 --- a/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts +++ b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts @@ -220,6 +220,28 @@ export function table_getMissingRowRanges< return ranges } +/** + * Returns the row at the index that a placeholder row id holds. The id of a + * placeholder row still finds its row after the row is loaded and has the id + * from `getRowId`. Returns `undefined` for all other ids. + */ +export function table_getRowByPlaceholderId< + TFeatures extends TableFeatures, + TData extends RowData, +>( + table: Table_Internal, + rowId: string, +): Row | undefined { + if (!rowId.startsWith(placeholderRowIdPrefix)) return undefined + + const indexText = rowId.slice(placeholderRowIdPrefix.length) + const index = Number(indexText) + + return String(index) === indexText + ? table.getCoreRowModel().rows[index] + : undefined +} + /** * Checks whether a row stands in for a row that is not loaded. `data` has no * row for an index when the entry is a hole or `undefined`. diff --git a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts index 58c14f6d18..5938129383 100644 --- a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts +++ b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts @@ -790,7 +790,7 @@ describe('cell selection with placeholder rows', () => { table.selectCellRange(rangeOf('person-3', 'name', placeholderId, 'age')) table.selectCellRange(rangeOf(placeholderId, 'name', 'person-3', 'age')) - table.setFocusedCell(placeholderId, 'name') + table.selectCellRange(rangeOf(placeholderId, 'name', placeholderId, 'age')) expect(table.atoms.cellSelection.get()).toEqual([]) @@ -846,26 +846,242 @@ describe('cell selection with placeholder rows', () => { expect(table.getSelectedCellIds()).toHaveLength(10) }) - it('should stop keyboard navigation at a placeholder row', () => { + it('should remove a range with a placeholder corner from setCellSelection', () => { const table = makeCellTable() + const placeholderId = table.getRowModel().rows[6]!.id + const loadedRange = rangeOf('person-2', 'name', 'person-3', 'age') + + table.setCellSelection([ + rangeOf('person-3', 'name', placeholderId, 'age'), + rangeOf(placeholderId, 'name', placeholderId, 'name'), + loadedRange, + ]) + + expect(table.atoms.cellSelection.get()).toEqual([loadedRange]) + + table.setCellSelection((old) => [ + ...old, + rangeOf(placeholderId, 'name', 'person-7', 'age'), + ]) + + expect(table.atoms.cellSelection.get()).toEqual([loadedRange]) + expect(table.getSelectedCellCount()).toBe(4) + + table.setCellSelection((old) => [ + ...old, + rangeOf(placeholderId, 'age', placeholderId, 'age'), + ]) + + expect(table.atoms.cellSelection.get()).toEqual([ + loadedRange, + rangeOf(placeholderId, 'age', placeholderId, 'age'), + ]) + expect(table.getSelectedCellCount()).toBe(4) + }) + + it('should not resolve a placeholder corner that is in the state', () => { + const placeholderRange = rangeOf( + 'person-3', + 'name', + '__placeholder_6', + 'age', + ) + const table = makeCellTable({ + initialState: { cellSelection: [placeholderRange] }, + }) + expect(table.getCellSelectionBounds()).toEqual([]) + expect(table.getSelectedCellCount()).toBe(0) + expect(table.getSelectedCellIds()).toEqual([]) + + table.setOptions((old) => ({ ...old, data: makeSparseData([2, 8]) })) + + expect(table.atoms.cellSelection.get()).toEqual([placeholderRange]) + expect(table.getCellSelectionBounds()).toEqual([]) + expect(table.getSelectedCellCount()).toBe(0) + }) + + it('should move the focus from the last loaded row onto placeholder rows', () => { + const table = makeCellTable() + const { rows } = table.getRowModel() + + table.setFocusedCell('person-4', 'age') table.moveCellSelection('down') + expect(table.atoms.cellSelection.get()).toEqual([ - rangeOf('person-2', 'name', 'person-2', 'name'), + rangeOf('__placeholder_5', 'age', '__placeholder_5', 'age'), + ]) + expect(table.getFocusedCell()).toBe(rows[5]!.getAllCells()[1]) + expect(rows[5]!.getAllCells()[1]!.getIsFocused()).toBe(true) + expect(rows[5]!.getAllCells()[1]!.getTabIndex()).toBe(0) + expect(rows[5]!.getAllCells()[0]!.getIsFocused()).toBe(false) + expect(rows[5]!.getAllCells()[1]!.getCanSelect()).toBe(false) + expect(rows[5]!.getAllCells()[1]!.getIsSelected()).toBe(false) + expect(table.getCellSelectionBounds()).toEqual([]) + expect(table.getSelectedCellCount()).toBe(0) + + table.moveCellSelection('down') + table.moveCellSelection('left') + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('__placeholder_6', 'name', '__placeholder_6', 'name'), + ]) + + table.moveCellSelection('down') + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('person-7', 'name', 'person-7', 'name'), + ]) + expect(table.getSelectedCellCount()).toBe(1) + }) + + it('should start keyboard navigation on the first row when it is a placeholder row', () => { + const table = makeCellTable() + + table.moveCellSelection('down') + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('__placeholder_0', 'name', '__placeholder_0', 'name'), + ]) + + table.moveCellSelection('up') + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('__placeholder_0', 'name', '__placeholder_0', 'name'), + ]) + }) + + it('should jump the focus to a placeholder row', () => { + const table = makeCellTable() + const { rows } = table.getRowModel() + + table.selectCellRange(rangeOf('person-2', 'name', 'person-4', 'age')) + table.setFocusedCell(rows[9]!.id, 'age') + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('__placeholder_9', 'age', '__placeholder_9', 'age'), + ]) + expect(table.getFocusedCell()!.row.index).toBe(9) + expect(table.getSelectedCellCount()).toBe(0) + + table.moveCellSelection('down') + table.setFocusedCell(rows[0]!.id, 'name') + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('__placeholder_0', 'name', '__placeholder_0', 'name'), ]) + }) + + it('should let the focus follow the row when the row is loaded', () => { + const table = makeCellTable() + const focusRange = rangeOf( + '__placeholder_5', + 'age', + '__placeholder_5', + 'age', + ) + + table.setFocusedCell('__placeholder_5', 'age') + table.setOptions((old) => ({ ...old, data: makeSparseData([2, 8]) })) + + const loadedCell = table.getRowModel().rows[5]!.getAllCells()[1]! + + expect(table.atoms.cellSelection.get()).toEqual([focusRange]) + expect(loadedCell.row.id).toBe('person-5') + expect(table.getFocusedCell()).toBe(loadedCell) + expect(loadedCell.getIsFocused()).toBe(true) + expect(loadedCell.getTabIndex()).toBe(0) + expect(loadedCell.getIsSelected()).toBe(true) + expect(table.getSelectedCellIds()).toEqual(['person-5_age']) - table.setFocusedCell('person-4', 'name') table.moveCellSelection('down') + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('person-6', 'age', 'person-6', 'age'), + ]) + }) + + it('should use the id of the loaded row when a range starts at a focus that followed its row', () => { + const fakeDocument = makeFakeDocument() + const table = makeCellTable() + + table.setFocusedCell('__placeholder_5', 'age') + table.setOptions((old) => ({ ...old, data: makeSparseData([2, 8]) })) table.extendCellSelection('down') expect(table.atoms.cellSelection.get()).toEqual([ - rangeOf('person-4', 'name', 'person-4', 'name'), + rangeOf('person-5', 'age', 'person-6', 'age'), + ]) + + table.setOptions((old) => ({ ...old, data: makeSparseData([2, 4]) })) + table.setFocusedCell('__placeholder_5', 'age') + table.setOptions((old) => ({ ...old, data: makeSparseData([2, 8]) })) + table + .getRowModel() + .rows[7]!.getAllCells()[0]! + .getSelectionStartHandler(fakeDocument)({ shiftKey: true }) + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('person-5', 'age', 'person-7', 'name'), + ]) + + table.setOptions((old) => ({ ...old, data: makeSparseData([2, 4]) })) + table.setFocusedCell('__placeholder_5', 'age') + table.setOptions((old) => ({ ...old, data: makeSparseData([2, 8]) })) + table.selectCellRange(rangeOf('person-2', 'name', 'person-2', 'name'), { + additive: true, + }) + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('person-5', 'age', 'person-5', 'age'), + rangeOf('person-2', 'name', 'person-2', 'name'), + ]) + }) + + it('should stop a keyboard extension at the last loaded row', () => { + const table = makeCellTable() + + table.setFocusedCell('person-3', 'name') + table.extendCellSelection('down') + table.extendCellSelection('down') + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('person-3', 'name', 'person-4', 'name'), ]) + table.extendCellSelection('up') + table.extendCellSelection('up') table.extendCellSelection('up') expect(table.atoms.cellSelection.get()).toEqual([ - rangeOf('person-4', 'name', 'person-3', 'name'), + rangeOf('person-3', 'name', 'person-2', 'name'), + ]) + }) + + it('should not start a range from a focused cell in a placeholder row', () => { + const fakeDocument = makeFakeDocument() + const table = makeCellTable() + const { rows } = table.getRowModel() + const focusRange = rangeOf( + '__placeholder_6', + 'name', + '__placeholder_6', + 'name', + ) + + table.setFocusedCell('__placeholder_6', 'name') + table.extendCellSelection('up') + table.extendCellSelection('down') + table.extendCellSelection('right') + + expect(table.atoms.cellSelection.get()).toEqual([focusRange]) + + rows[7]!.getAllCells()[1]!.getSelectionStartHandler(fakeDocument)({ + shiftKey: true, + }) + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('person-7', 'age', 'person-7', 'age'), ]) }) @@ -882,7 +1098,6 @@ describe('cell selection with placeholder rows', () => { table.resetCellSelection(true) table.setOptions((old) => ({ ...old, data: [] })) table.selectAllCells() - table.moveCellSelection('down') expect(table.atoms.cellSelection.get()).toEqual([]) }) From d84744e77dd84243be2d48b2b77ff613aa2cbd6e Mon Sep 17 00:00:00 2001 From: Albert Nimtz Date: Fri, 27 Nov 2026 13:08:39 +0100 Subject: [PATCH 05/12] docs: explain that a placeholder id is a different row after a reset A placeholder id holds only the index of its row. After the app starts again with a new data array, for a new sort order or filter, state that holds a placeholder id points at a different row. The sparse rows guide now gives the rule: reset such state when you start again. The table stores a placeholder id in one state only, the focused cell of cellSelectionFeature. Row selection, row pinning, and expanding hold none. Two tests pin this: the anchor of a Shift row range is never a placeholder row, and a focused placeholder id is read as an index. Co-Authored-By: Claude Fable 5.2 --- docs/guide/sparse-rows.md | 12 ++++++-- .../sparse-rows/sparseRowsFeature.test.ts | 30 +++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/docs/guide/sparse-rows.md b/docs/guide/sparse-rows.md index 9f8291b81b..fb16ceae62 100644 --- a/docs/guide/sparse-rows.md +++ b/docs/guide/sparse-rows.md @@ -90,7 +90,7 @@ A placeholder row has no data: - `row.original` is `undefined`. Its type is still `TData`, so check `row.getIsPlaceholder()` before you read it. - `row.getValue()` and `cell.getValue()` return `undefined`. The table does not call the column accessors. - Do not render the `cell` templates of your columns for a placeholder row if they read `row.original`. -- `row.id` is temporary. It starts with `__placeholder_` and changes to the `getRowId` result when the row is loaded. Do not store it. +- `row.id` is temporary. It starts with `__placeholder_`, holds only the index of the row, and changes to the `getRowId` result when the row is loaded. Do not store it. - The `__placeholder_` prefix is reserved. `getRowId` must not return an ID that starts with it, or the table can mistake the loaded row for a placeholder row. In development, the table logs a warning for such an ID. ## Load the Missing Ranges @@ -131,6 +131,14 @@ Row 99,999 under one sort order is a different row under another sort order. The - With this feature, a new `data` array does not run the `autoResetPageIndex`, `autoResetExpanded`, and other `autoReset*` behaviors, because a new array usually means that more rows are loaded. Reset the page index or the scroll position yourself when sorting or a filter changes. - Do not let the table read column behavior from row values, because placeholder rows have no values. Set `sortDescFirst` on the table or on your columns; without it, the first sort direction of a column comes from the values of the first rows. If you use `column.getCanGlobalFilter()`, set `enableGlobalFilter: true` on the columns that the server can search; without it, the table reads the loaded rows until it finds a value, and the result is `false` while no row is loaded. +### Reset State When You Start Again + +A placeholder ID holds only the index of its row. After you start again with a new `data` array, the same placeholder ID is a different row on the server. State that holds a placeholder ID then points at that different row. + +- The table stores a placeholder ID in one state only: the focused cell of `cellSelectionFeature`, while that cell is in a placeholder row. See [Cell Selection](#cell-selection). Call `table.resetCellSelection()` when you start again, or the focus stays at the same index. +- Row selection, row pinning, and expanding keep no state for a placeholder row, so they hold no placeholder ID. +- Do not put a placeholder ID into your own state, for example the ID of the row that a context menu is open for. If you must, reset that state when you start again. + ## Pagination `rowCount` is the same option that `rowPaginationFeature` reads for `table.getRowCount()` and `table.getPageCount()`. The table can show the rows in two ways: @@ -174,7 +182,7 @@ if (focusedRow?.getIsPlaceholder()) { } ``` -While the focused cell is in a placeholder row, the last range in the `cellSelection` state is that one cell, and it holds the placeholder ID of the row. This is the only state in which the table stores a placeholder ID. The table reads this ID as "the row at this index". The ID stays in the state after the row is loaded. The next change of the cell selection replaces it with the ID of the loaded row. Call `table.getFocusedCell()` to get the row that has the focus now. +While the focused cell is in a placeholder row, the last range in the `cellSelection` state is that one cell, and it holds the placeholder ID of the row. This is the only state in which the table stores a placeholder ID. The table reads this ID as "the row at this index". The ID stays in the state after the row is loaded. The next change of the cell selection replaces it with the ID of the loaded row. Call `table.getFocusedCell()` to get the row that has the focus now. See also [Reset State When You Start Again](#reset-state-when-you-start-again). A range can span rows that are not loaded. Its corners are loaded rows, and the placeholder rows between them are not selected: `getSelectedCellIds()`, `getSelectedCellCount()`, and `getCellSelectionRowIds()` leave them out. `getSelectedCellRangesData()` keeps the position of each row, so the grid of a range has an empty entry for each placeholder row; skip these entries when you copy the data. The rows become part of the selection when they are loaded. A range whose corner row is removed from `data` stays in state and selects nothing until that row is loaded again. diff --git a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts index 5938129383..454a50a681 100644 --- a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts +++ b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts @@ -571,6 +571,20 @@ describe('row selection with placeholder rows', () => { expect(table.atoms.rowSelection.get()).toEqual({ 'person-4': true }) }) + it('should not keep a placeholder row as the anchor of a Shift range', () => { + const table = makeTable() + const { rows } = table.getRowModel() + + rows[3]!.getToggleSelectedHandler()({ target: { checked: true } }) + rows[6]!.getToggleSelectedHandler()({ + target: { checked: true }, + shiftKey: true, + }) + + expect(table._lastSelectedRowId).toBe('person-3') + expect(table.atoms.rowSelection.get()).toEqual({ 'person-3': true }) + }) + it('should keep the selection of a row that is no longer loaded', () => { const table = makeTable({ initialState: { rowSelection: { 'person-3': true } }, @@ -1085,6 +1099,22 @@ describe('cell selection with placeholder rows', () => { ]) }) + it('should read a focused placeholder id as an index after data is replaced', () => { + const table = makeCellTable() + + table.setFocusedCell('__placeholder_5', 'age') + table.setOptions((old) => ({ + ...old, + data: Array.from({ length: 10 }, (_, index) => makePerson(index + 100)), + })) + + expect(table.getFocusedCell()!.row.id).toBe('person-105') + + table.resetCellSelection(true) + + expect(table.getFocusedCell()).toBeUndefined() + }) + it('should select from the first to the last loaded row with select all', () => { const table = makeCellTable() From 0290807780f26054617a912a91d3d0c8045a4ec3 Mon Sep 17 00:00:00 2001 From: Albert Nimtz Date: Fri, 27 Nov 2026 13:08:45 +0100 Subject: [PATCH 06/12] docs: note that rowCount is also the total that other features read With sparseRowsFeature, rowCount is the length of the row model. It is also the total that pagination and count calculations read. An app that pads rowCount because the total is not known changes these numbers too. The sparse rows guide now says this and tells the reader to set the exact total. Co-Authored-By: Claude Fable 5.2 --- docs/guide/sparse-rows.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/guide/sparse-rows.md b/docs/guide/sparse-rows.md index fb16ceae62..1870300b25 100644 --- a/docs/guide/sparse-rows.md +++ b/docs/guide/sparse-rows.md @@ -148,6 +148,12 @@ A placeholder ID holds only the index of its row. After you start again with a n This changes what normal server-side pagination means. Without this feature, `data` is the current page. With it, `data` is always indexed from row 0, so a `data` array that holds one page means that rows `0` to `pageSize - 1` are loaded and all other rows are placeholder rows. Put each page at its index, as shown in [Put Loaded Rows at Their Index](#put-loaded-rows-at-their-index). +### `rowCount` Is Also the Total + +`rowCount` has two jobs. It is the length of the sparse row model, and it is the total that other features read: `table.getRowCount()` and `table.getPageCount()` of `rowPaginationFeature`, and each feature or app code that calculates a count from the total, such as "all rows minus the deselected rows" for a "select all" on the server. + +Set `rowCount` to the exact total of the server. If the total is not known and you set `rowCount` to more than the rows that you know of, to get placeholder rows after the last loaded row, each of these features reads the padded number. Do not show their counts as a total then, and set the exact `rowCount` when you get it. + ## Row Selection, Pinning, and Expanding Row state is stored by row ID, and a placeholder row only has a temporary ID. The table keeps no state for it: From 55476bef9e27e5cc4441bd09808ada20c87dde12 Mon Sep 17 00:00:00 2001 From: Albert Nimtz Date: Fri, 27 Nov 2026 13:14:49 +0100 Subject: [PATCH 07/12] docs(table-core): say that a focused placeholder id also selects after a reset A focused placeholder id is read as the row at its index. After the data is replaced, the loaded row at that index has the focused cell and also its one-cell selection. The guide said only that the focus stays. A test now pins the selection too. A second test covers the focus that follows its row on a page that the client cuts. The comments of the new cell selection helpers are shorter. Co-Authored-By: Claude Fable 5.2 --- docs/guide/sparse-rows.md | 2 +- .../cellSelectionFeature.utils.ts | 22 ++++------ .../sparse-rows/sparseRowsFeature.test.ts | 41 +++++++++++++++++++ 3 files changed, 49 insertions(+), 16 deletions(-) diff --git a/docs/guide/sparse-rows.md b/docs/guide/sparse-rows.md index 1870300b25..443605811f 100644 --- a/docs/guide/sparse-rows.md +++ b/docs/guide/sparse-rows.md @@ -135,7 +135,7 @@ Row 99,999 under one sort order is a different row under another sort order. The A placeholder ID holds only the index of its row. After you start again with a new `data` array, the same placeholder ID is a different row on the server. State that holds a placeholder ID then points at that different row. -- The table stores a placeholder ID in one state only: the focused cell of `cellSelectionFeature`, while that cell is in a placeholder row. See [Cell Selection](#cell-selection). Call `table.resetCellSelection()` when you start again, or the focus stays at the same index. +- The table stores a placeholder ID in one state only: the focused cell of `cellSelectionFeature`, while that cell is in a placeholder row. See [Cell Selection](#cell-selection). Call `table.resetCellSelection()` when you start again. If you do not, the focus stays at the same index, and the loaded row at that index has the focused cell and its selection. - Row selection, row pinning, and expanding keep no state for a placeholder row, so they hold no placeholder ID. - Do not put a placeholder ID into your own state, for example the ID of the row that a context menu is open for. If you must, reset that state when you start again. diff --git a/packages/table-core/src/features/cell-selection/cellSelectionFeature.utils.ts b/packages/table-core/src/features/cell-selection/cellSelectionFeature.utils.ts index a68280da1c..703e1ec65d 100644 --- a/packages/table-core/src/features/cell-selection/cellSelectionFeature.utils.ts +++ b/packages/table-core/src/features/cell-selection/cellSelectionFeature.utils.ts @@ -71,6 +71,7 @@ export function table_setCellSelection< ) { // Unguarded: selection updates are pointer-driven and ranges can be large. // Keep the hot path direct; the auto-reset path guards in reset below. + // Only a table that can have placeholder rows checks the new ranges. table.options.onCellSelectionChange?.( getCanHavePlaceholderRows(table) ? (old) => removePlaceholderCorners(table, functionalUpdate(updater, old)) @@ -85,10 +86,7 @@ function isOneCellRange(range: CellSelectionRange): boolean { ) } -/** - * Changes the id of a placeholder row to the id of the row that is at its - * index now. All other ids stay the same. - */ +/** Changes a placeholder row id to the id of the row at its index now. */ function resolveRowId( table: Table_Internal, rowId: string, @@ -96,10 +94,7 @@ function resolveRowId( return getRowByPlaceholderId(table, rowId)?.id ?? rowId } -/** - * Tests whether a row id is the id of a placeholder row. This is also true - * after the row is loaded, because the row then has a different id. - */ +/** Tests whether a row id is a placeholder row id, also after its row is loaded. */ function isPlaceholderRowId< TFeatures extends TableFeatures, TData extends RowData, @@ -112,11 +107,8 @@ function isPlaceholderRowId< } /** - * Removes the ranges that a placeholder row id makes invalid. - * - * A placeholder row id can only stay in a range of one cell. When its row is - * loaded, the range gets the id of that row. When its row is not loaded, the - * range stays only as the last range, where it is the focused cell. + * Keeps a placeholder row id only in a range of one cell. If its row is not + * loaded, that range must also be the last range: it is the focused cell. */ function removePlaceholderCorners< TFeatures extends TableFeatures, @@ -423,8 +415,8 @@ function findMergeBoundsAt( } /** - * Resolves a stored row id to its row. With `canUsePlaceholderId`, the id of a - * placeholder row also finds the row that is loaded at its index now. + * Resolves a stored row id to its row. With `canUsePlaceholderId`, a + * placeholder row id also finds the row that is loaded at its index now. */ function resolveRow( table: Table_Internal, diff --git a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts index 454a50a681..84e1ce9e00 100644 --- a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts +++ b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts @@ -1109,10 +1109,51 @@ describe('cell selection with placeholder rows', () => { })) expect(table.getFocusedCell()!.row.id).toBe('person-105') + expect(table.getSelectedCellIds()).toEqual(['person-105_age']) table.resetCellSelection(true) expect(table.getFocusedCell()).toBeUndefined() + expect(table.getSelectedCellIds()).toEqual([]) + }) + + it('should let the focus follow the row on a page that is cut on the client', () => { + const pageFeatures = testFeatures({ + cellSelectionFeature, + rowPaginationFeature, + sparseRowsFeature, + paginatedRowModel: createPaginatedRowModel(), + }) + const table = constructTable({ + features: pageFeatures, + columns: [{ accessorKey: 'name', id: 'name' }], + data: makeSparseData([2, 4]), + rowCount: 10, + getRowId: (person) => person.id, + initialState: { pagination: { pageIndex: 1, pageSize: 5 } }, + }) + + table.moveCellSelection('down') + table.moveCellSelection('down') + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('__placeholder_6', 'name', '__placeholder_6', 'name'), + ]) + + table.setOptions((old) => ({ ...old, data: makeSparseData([2, 9]) })) + + const loadedCell = table.getRowModel().rows[1]!.getAllCells()[0]! + + expect(loadedCell.row.id).toBe('person-6') + expect(table.getFocusedCell()).toBe(loadedCell) + expect(loadedCell.getIsFocused()).toBe(true) + expect(loadedCell.getIsSelected()).toBe(true) + + table.moveCellSelection('up') + + expect(table.atoms.cellSelection.get()).toEqual([ + rangeOf('person-5', 'name', 'person-5', 'name'), + ]) }) it('should select from the first to the last loaded row with select all', () => { From 218dbdceb4d748db68b3e61dfbc6f7efe9106730 Mon Sep 17 00:00:00 2001 From: Albert Nimtz Date: Fri, 27 Nov 2026 14:32:50 +0100 Subject: [PATCH 08/12] fix(table-core): leave placeholder rows out of the selected row models A rowSelection key that is a placeholder id no longer puts the placeholder row into getSelectedRowModel(), getFilteredSelectedRowModel() or getGroupedSelectedRowModel(). Co-Authored-By: Claude Opus 5.5 --- .../row-selection/rowSelectionFeature.utils.ts | 3 ++- .../sparse-rows/sparseRowsFeature.test.ts | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/packages/table-core/src/features/row-selection/rowSelectionFeature.utils.ts b/packages/table-core/src/features/row-selection/rowSelectionFeature.utils.ts index d465256b7e..fc2c4265e0 100644 --- a/packages/table-core/src/features/row-selection/rowSelectionFeature.utils.ts +++ b/packages/table-core/src/features/row-selection/rowSelectionFeature.utils.ts @@ -931,7 +931,8 @@ function selectRowsRecursively< for (let i = 0; i < rows.length; i++) { const row = rows[i]! - const isSelected = isRowSelected(row, rowSelection) + const isSelected = + !getIsPlaceholderRow(row) && isRowSelected(row, rowSelection) if (isSelected) { selectedFlatRows.push(row) diff --git a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts index 84e1ce9e00..b3e79712cd 100644 --- a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts +++ b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts @@ -606,6 +606,24 @@ describe('row selection with placeholder rows', () => { ]) }) + it('should leave a placeholder id in the state out of the selected row models', () => { + const table = makeTable({ + initialState: { + rowSelection: { __placeholder_5: true, 'person-3': true }, + }, + }) + + expect(table.getRowModel().rows[5]!.getIsPlaceholder()).toBe(true) + expect(table.getSelectedRowModel().rows.map((row) => row.id)).toEqual([ + 'person-3', + ]) + expect(table.getSelectedRowModel().rowsById).not.toHaveProperty( + '__placeholder_5', + ) + expect(table.getFilteredSelectedRowModel().flatRows).toHaveLength(1) + expect(table.getGroupedSelectedRowModel().flatRows).toHaveLength(1) + }) + it('should not report all rows selected when no row is loaded', () => { const table = makeTable({ initialState: { rowSelection: { 'person-3': true } }, From ba65437bdfdbf6e6dcc5fdded90b9247dc85e32a Mon Sep 17 00:00:00 2001 From: Albert Nimtz Date: Sat, 28 Nov 2026 12:29:47 +0100 Subject: [PATCH 09/12] fix(table-core): warn when a loaded sub-row has a reserved placeholder id Co-Authored-By: Claude Opus 5.5 --- .../sparse-rows/sparseRowsFeature.utils.ts | 21 +++++++++++++++---- .../sparse-rows/sparseRowsFeature.test.ts | 21 +++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts index f490f819b3..0bd47ca419 100644 --- a/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts +++ b/packages/table-core/src/features/sparse-rows/sparseRowsFeature.utils.ts @@ -27,14 +27,16 @@ function accessSubRows( table: Table_Internal, rowModel: RowModel, parentRow: Row, -): void { +): string | undefined { const originalSubRows = table.options.getSubRows!( parentRow.original, parentRow.index, ) parentRow.originalSubRows = originalSubRows - if (!originalSubRows) return + if (!originalSubRows) return undefined + + let reservedId: string | undefined for (let i = 0; i < originalSubRows.length; i++) { const originalRow = originalSubRows[i]! @@ -48,11 +50,21 @@ function accessSubRows( parentRow.id, ) + if ( + process.env.NODE_ENV === 'development' && + row.id.startsWith(placeholderRowIdPrefix) + ) { + reservedId ??= row.id + } + rowModel.flatRows.push(row) rowModel.rowsById[row.id] = row parentRow.subRows.push(row) - accessSubRows(table, rowModel, row) + const subRowReservedId = accessSubRows(table, rowModel, row) + reservedId ??= subRowReservedId } + + return reservedId } /** @@ -125,7 +137,8 @@ export function table_createSparseRowModel< rowModel.rowsById[row.id] = row if (getSubRows && originalRow !== undefined) { - accessSubRows(table, rowModel, row) + const subRowReservedId = accessSubRows(table, rowModel, row) + reservedId ??= subRowReservedId } } diff --git a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts index b3e79712cd..1aaa754678 100644 --- a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts +++ b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts @@ -1415,6 +1415,27 @@ describe('sparseRowsFeature development warnings', () => { expect(warn.mock.calls[0]![0]).toContain('reserved') }) + it('should warn when a loaded sub-row has an id with the placeholder prefix', () => { + const warn = spyOnDevWarnings() + const data = makeSparseData([2, 4]) + data[3] = { + ...makePerson(3), + children: [ + makePerson(30), + { + ...makePerson(31), + children: [{ ...makePerson(32), id: '__placeholder_0' }], + }, + ], + } + const table = makeTable({ data, getSubRows: (person) => person.children }) + + expect(table.getCoreRowModel().rowsById['__placeholder_0']?.depth).toBe(2) + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0]![0]).toContain("'__placeholder_0'") + expect(warn.mock.calls[0]![0]).toContain('reserved') + }) + it('should not report an id with the placeholder prefix as an overlap of loaded ranges', () => { const warn = spyOnDevWarnings() const data = makeSparseData([2, 4]) From 0612e3f2a402ddcab2295e1f225fac4b12702f0c Mon Sep 17 00:00:00 2001 From: Albert Nimtz Date: Sat, 28 Nov 2026 12:29:47 +0100 Subject: [PATCH 10/12] test(table-core): run the sparse page selection test on a cut page Co-Authored-By: Claude Opus 5.5 --- .../sparse-rows/sparseRowsFeature.test.ts | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts index 1aaa754678..3616e77d4b 100644 --- a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts +++ b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts @@ -564,6 +564,31 @@ describe('row selection with placeholder rows', () => { }) it('should select only the loaded rows of the page with select all on the page', () => { + const table = makeTable({ + features: paginatedFeatures, + data: makeSparseData([2, 3], [7, 7]), + manualPagination: false, + initialState: { pagination: { pageIndex: 0, pageSize: 5 } }, + }) + + expect(table.getRowModel().rows.map((row) => row.id)).toEqual([ + '__placeholder_0', + '__placeholder_1', + 'person-2', + 'person-3', + '__placeholder_4', + ]) + + table.toggleAllPageRowsSelected(true) + + expect(table.atoms.rowSelection.get()).toEqual({ + 'person-2': true, + 'person-3': true, + }) + expect(table.getIsAllPageRowsSelected()).toBe(true) + }) + + it('should not let a placeholder row clear a single selection with select all on the page', () => { const table = makeTable({ enableMultiRowSelection: false }) table.toggleAllPageRowsSelected(true) From efe7da91625fb3fc45aba45938b51b728b2daafc Mon Sep 17 00:00:00 2001 From: Albert Nimtz Date: Sat, 28 Nov 2026 12:29:48 +0100 Subject: [PATCH 11/12] docs: correct cache key, reset, and selection details in the sparse rows guide Co-Authored-By: Claude Opus 5.5 --- docs/guide/sparse-rows.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/guide/sparse-rows.md b/docs/guide/sparse-rows.md index 443605811f..64f02672ad 100644 --- a/docs/guide/sparse-rows.md +++ b/docs/guide/sparse-rows.md @@ -6,7 +6,7 @@ title: Sparse Rows Guide A remote table usually loads its rows from the start: the first page, then the second page, and so on. `data` cannot have gaps, so to show row 99,999 of 100,000 the app must first load every row before it. -`sparseRowsFeature` removes that limit. `data` holds only the rows that are loaded, each at its absolute index on the server, and `rowCount` is the total. The core row model then has `rowCount` rows, and each index without data gets a placeholder row. `table.getCoreRowModel().rows[i]` is always row `i` on the server, and so is `table.getRowModel().rows[i]` when the table does not cut pages or add expanded sub-rows. A virtualizer gets the correct scrollbar length, the user can jump to any position, and the app loads only the rows in view. +`sparseRowsFeature` removes that limit. `data` holds only the rows that are loaded, each at its absolute index on the server, and `rowCount` is the total. The core row model then has `rowCount` rows, and each index without data gets a placeholder row. `table.getCoreRowModel().rows[i]` is always row `i` on the server, and so is `table.getRowModel().rows[i]` when sorting, filtering, and grouping run on the server and the table does not cut pages or add expanded sub-rows. A virtualizer gets the correct scrollbar length, the user can jump to any position, and the app loads only the rows in view. The table does not load data. It tells you which ranges are missing, and you load them, for example with [TanStack Query](https://tanstack.com/query/latest). @@ -116,7 +116,7 @@ function loadVisibleRows(startIndex: number, endIndex: number) { Without `blockSize`, the result is the exact gaps: `[{ startIndex: 120, endIndex: 160 }]`. -With `blockSize`, the result has one range for each block that has a missing row in the requested range. Block `n` starts at index `n * blockSize`, so the same block always has the same bounds: `[{ startIndex: 100, endIndex: 149 }, { startIndex: 150, endIndex: 199 }]`. This makes `range.startIndex` a stable cache key, for example `queryKey: ['people', sorting, columnFilters, range.startIndex]`. A block range can be larger than the requested range, but it never goes past the last row. +With `blockSize`, the result has one range for each block that has a missing row in the requested range. Block `n` starts at index `n * blockSize`, so the same block always has the same bounds: `[{ startIndex: 100, endIndex: 149 }, { startIndex: 150, endIndex: 199 }]`. A block range can be larger than the requested range, but it never goes past the last row. So the last block is the exception: its `endIndex` grows when `rowCount` grows. Use both bounds as the cache key, for example `queryKey: ['people', sorting, columnFilters, range.startIndex, range.endIndex]`, so that a larger last block is a new request. A block stays missing until its rows are in `data`, so the same range can be returned again while its request is in progress. Use the cache key to make each request only once. @@ -128,14 +128,14 @@ Row 99,999 under one sort order is a different row under another sort order. The - Sort, filter, and group on the server. Set `manualSorting`, `manualFiltering`, and `manualGrouping`, or do not register the client-side row models. A client-side row model only sees the loaded rows, so its result is wrong. The table logs a warning in development when one is active and a row is not loaded. `manualPagination` is different: client-side pagination keeps the index space, see [Pagination](#pagination). - When sorting or a filter changes, start again with an empty `data` array and the new `rowCount`. If you load blocks with TanStack Query, put the sorting and filter state into the query key. -- With this feature, a new `data` array does not run the `autoResetPageIndex`, `autoResetExpanded`, and other `autoReset*` behaviors, because a new array usually means that more rows are loaded. Reset the page index or the scroll position yourself when sorting or a filter changes. +- With this feature, the core row model does not run the `autoResetPageIndex`, `autoResetExpanded`, and other `autoReset*` behaviors when `data` changes, because a new array usually means that more rows are loaded. A client-side filtered, grouped, or sorted row model still runs its own `autoReset*` behaviors when its rows change. Reset the page index or the scroll position yourself when sorting or a filter changes. - Do not let the table read column behavior from row values, because placeholder rows have no values. Set `sortDescFirst` on the table or on your columns; without it, the first sort direction of a column comes from the values of the first rows. If you use `column.getCanGlobalFilter()`, set `enableGlobalFilter: true` on the columns that the server can search; without it, the table reads the loaded rows until it finds a value, and the result is `false` while no row is loaded. ### Reset State When You Start Again A placeholder ID holds only the index of its row. After you start again with a new `data` array, the same placeholder ID is a different row on the server. State that holds a placeholder ID then points at that different row. -- The table stores a placeholder ID in one state only: the focused cell of `cellSelectionFeature`, while that cell is in a placeholder row. See [Cell Selection](#cell-selection). Call `table.resetCellSelection()` when you start again. If you do not, the focus stays at the same index, and the loaded row at that index has the focused cell and its selection. +- The table stores a placeholder ID in one state only: the focused cell of `cellSelectionFeature`, while that cell is in a placeholder row. See [Cell Selection](#cell-selection). Call `table.resetCellSelection(true)` when you start again. If you do not, the focus stays at the same index, and the loaded row at that index has the focused cell and its selection. Pass `true`, because without it the table restores `initialState.cellSelection`, which can also hold a placeholder ID. - Row selection, row pinning, and expanding keep no state for a placeholder row, so they hold no placeholder ID. - Do not put a placeholder ID into your own state, for example the ID of the row that a context menu is open for. If you must, reset that state when you start again. @@ -170,7 +170,7 @@ The state of a loaded row stays when you remove the row from `data`. The row is - `cell.getCanSelect()` returns `false` for the cells of a placeholder row, and their selection handlers do nothing. The `enableCellSelection` callback is not called with such a cell. - `moveCellSelection()` moves the focus onto a placeholder row as it does onto a loaded row. `setFocusedCell()` also accepts the ID of a placeholder row, for example to jump to the last row. -- While the focused cell is in a placeholder row, no cell is selected. `cell.getIsFocused()` returns `true` and `cell.getTabIndex()` returns `0` for that cell, and `cell.getIsSelected()` returns `false`. +- While the focused cell is in a placeholder row, that cell is not selected. `cell.getIsFocused()` returns `true` and `cell.getTabIndex()` returns `0` for that cell, and `cell.getIsSelected()` returns `false`. Other ranges in the state stay selected. - When the row of the focused cell is loaded, the focus follows the row. `table.getFocusedCell()` returns the cell of the loaded row at the same index and in the same column. This cell is then selected, like the focused cell of any loaded row. - `extendCellSelection()` stops at the last loaded row, so a range does not grow onto a placeholder row. It does nothing while the focused cell is in a placeholder row. A range event on a loaded cell, which is a Shift click by default, then starts a new selection at that cell. - `selectCellRange()` ignores a range that starts or ends on a placeholder row, unless the range is one cell. `setCellSelection()` removes such a range from the new state. From aa5d4bd7d673b3664d1d3db27274212322927c94 Mon Sep 17 00:00:00 2001 From: Albert Nimtz Date: Sat, 28 Nov 2026 13:39:10 +0100 Subject: [PATCH 12/12] test(table-core): drop sparse rows tests that pin implementation details Co-Authored-By: Claude Opus 5.5 --- .../sparse-rows/sparseRowsFeature.test.ts | 23 +--------------- .../sparseRowsFeature.utils.test.ts | 27 ------------------- 2 files changed, 1 insertion(+), 49 deletions(-) diff --git a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts index 3616e77d4b..bb5e45c6ae 100644 --- a/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts +++ b/packages/table-core/tests/implementation/features/sparse-rows/sparseRowsFeature.test.ts @@ -30,9 +30,7 @@ import type { Cell, CellSelectionRange, ColumnDef, - FilterFn, Row, - RowData, SparseRowRange, Table, TableOptions, @@ -162,16 +160,6 @@ describe('sparseRowsFeature types', () => { row.getIsPlaceholder expect(getIsPlaceholder).toBeTypeOf('function') }) - - it('should let any-typed filter functions be cast for a table without the feature', () => { - function getStockFilterFns() { - return { ...filterFns } as Record< - string, - FilterFn - > - } - expect(getStockFilterFns()).toHaveProperty('includesString') - }) }) describe('sparse core row model', () => { @@ -219,8 +207,7 @@ describe('sparse core row model', () => { }) it('should give placeholder rows a temporary id and loaded rows the id from getRowId', () => { - const getRowId = vi.fn((person: Person) => person.id) - const table = makeTable({ getRowId }) + const table = makeTable() const { rows, rowsById } = table.getRowModel() expect(rows.map((row) => row.id)).toEqual([ @@ -237,7 +224,6 @@ describe('sparse core row model', () => { ]) expect(rowsById['__placeholder_7']).toBe(rows[7]) expect(table.getRow('person-3')).toBe(rows[3]) - expect(getRowId).toHaveBeenCalledTimes(3) }) it('should not collide with the default index ids', () => { @@ -606,7 +592,6 @@ describe('row selection with placeholder rows', () => { shiftKey: true, }) - expect(table._lastSelectedRowId).toBe('person-3') expect(table.atoms.rowSelection.get()).toEqual({ 'person-3': true }) }) @@ -864,7 +849,6 @@ describe('cell selection with placeholder rows', () => { it('should leave out the placeholder rows of a range that spans a gap', () => { const table = makeCellTable() const { rows } = table.getRowModel() - const getPlaceholderCells = vi.spyOn(rows[5]!, 'getAllCellsByColumnId') table.selectCellRange(rangeOf('person-3', 'name', 'person-7', 'age')) @@ -890,7 +874,6 @@ describe('cell selection with placeholder rows', () => { ['1', ['Person 4', 24]], ['4', ['Person 7', 27]], ]) - expect(getPlaceholderCells).not.toHaveBeenCalled() expect(rows[5]!.getAllCells()[0]!.getIsSelected()).toBe(false) expect(rows[4]!.getAllCells()[0]!.getIsSelected()).toBe(true) @@ -1484,10 +1467,6 @@ describe('sparseRowsFeature development warnings', () => { }) describe('tables without sparseRowsFeature', () => { - it('should not be part of stockFeatures', () => { - expect(Object.keys(stockFeatures)).not.toContain('sparseRowsFeature') - }) - it('should keep rowCount out of the core row model', () => { const table = constructTable({ features: testFeatures(stockFeatures), diff --git a/packages/table-core/tests/unit/features/sparse-rows/sparseRowsFeature.utils.test.ts b/packages/table-core/tests/unit/features/sparse-rows/sparseRowsFeature.utils.test.ts index 90dcc9e03a..49089bc19e 100644 --- a/packages/table-core/tests/unit/features/sparse-rows/sparseRowsFeature.utils.test.ts +++ b/packages/table-core/tests/unit/features/sparse-rows/sparseRowsFeature.utils.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from 'vitest' import { row_getIsPlaceholder, - table_createSparseRowModel, table_getMissingRowRanges, } from '../../../../src/static-functions' import { constructTable, sparseRowsFeature } from '../../../../src' @@ -273,17 +272,6 @@ describe('row_getIsPlaceholder', () => { }) describe('table_createSparseRowModel', () => { - it('should create a memoized row model with rowCount rows', () => { - const table = makeTable() - const getRowModel = table_createSparseRowModel(asInternal(table)) - const rowModel = getRowModel() - - expect(rowModel.rows).toHaveLength(100) - expect(rowModel.rows[10]!.id).toBe('person-10') - expect(rowModel.rows[9]!.id).toBe('__placeholder_9') - expect(getRowModel()).toBe(rowModel) - }) - it('should build an empty row model for an empty table', () => { const table = makeTable({ data: [], rowCount: 0 }) @@ -293,19 +281,4 @@ describe('table_createSparseRowModel', () => { rowsById: {}, }) }) - - it('should drop the placeholder rows after rowCount when the table shrinks', () => { - const table = makeTable({ data: [], rowCount: 5 }) - const before = table.getRowModel().rows - - table.setOptions((old) => ({ ...old, rowCount: 2 })) - expect(table.getRowModel().rows).toHaveLength(2) - - table.setOptions((old) => ({ ...old, rowCount: 5 })) - const after = table.getRowModel().rows - - expect(after[1]).toBe(before[1]) - expect(after[4]).not.toBe(before[4]) - expect(after[4]!.id).toBe('__placeholder_4') - }) })