diff --git a/AGENTS.md b/AGENTS.md index aed8031..9cddaa0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ Instructions for AI coding agents working in this repository. [CONTRIBUTING.md]( ## What this is -`@codemancers/sheets` is a spreadsheet-style data grid for React, built on TanStack Table v8. It's one package with three entry points: +`@codemancers/sheets` is a spreadsheet-style data grid for React, built on TanStack Table v9. It's one package with three entry points: | Import | Source (`packages/sheets/`) | Contents | | -------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------ | diff --git a/apps/playground/package.json b/apps/playground/package.json index 30fcd0d..1ef84c7 100644 --- a/apps/playground/package.json +++ b/apps/playground/package.json @@ -10,6 +10,6 @@ }, "dependencies": { "@codemancers/sheets": "workspace:*", - "@tanstack/react-table": "^8.21.3" + "@tanstack/react-table": "^9.3.1" } } diff --git a/apps/playground/src/app/demos/editing-demo.tsx b/apps/playground/src/app/demos/editing-demo.tsx index 88f88a6..557aec9 100644 --- a/apps/playground/src/app/demos/editing-demo.tsx +++ b/apps/playground/src/app/demos/editing-demo.tsx @@ -1,6 +1,11 @@ import { useState, useContext } from 'react'; import { createColumnHelper } from '@tanstack/react-table'; -import { useCellStatus, useRowChanges, useSheet } from '@codemancers/sheets'; +import { + useCellStatus, + useRowChanges, + useSheet, + type SheetFeatures, +} from '@codemancers/sheets'; import { Sheet, SheetEditableTextCell, @@ -10,9 +15,9 @@ import { import { makeTasks, requiredTitle, saveTask, type Task } from '../data'; import { RtlContext } from '../direction'; -const task = createColumnHelper(); +const task = createColumnHelper(); -const columns = [ +const columns = task.columns([ task.accessor('title', { header: 'Title', size: 320, @@ -43,7 +48,7 @@ const columns = [ header: 'Status', cell: ({ getValue }) => {getValue()}, }), -]; +]); export function EditingDemo() { const rtl = useContext(RtlContext); diff --git a/apps/playground/src/app/demos/large-demo.tsx b/apps/playground/src/app/demos/large-demo.tsx index 0be5ff5..7f51438 100644 --- a/apps/playground/src/app/demos/large-demo.tsx +++ b/apps/playground/src/app/demos/large-demo.tsx @@ -1,39 +1,44 @@ import { useContext } from 'react'; import { createColumnHelper } from '@tanstack/react-table'; -import { textFilter, useSheet, valuesFilter } from '@codemancers/sheets'; +import { + textFilter, + useSheet, + valuesFilter, + type SheetFeatures, +} from '@codemancers/sheets'; import { Sheet } from '@codemancers/sheets/ui'; import { RtlContext } from '../direction'; import { makeTasks, type Task } from '../data'; const TASKS = makeTasks(1000); -const task = createColumnHelper(); +const task = createColumnHelper(); // Group headers, and a header that renders markup instead of a string. -const columns = [ +const columns = task.columns([ task.group({ id: 'task', header: 'Task', - columns: [ + columns: task.columns([ task.accessor('title', { header: 'Title', size: 300, filterFn: textFilter, }), task.accessor('status', { header: 'Status', filterFn: valuesFilter }), - ], + ]), }), task.group({ id: 'assignment', header: 'Assignment', - columns: [ + columns: task.columns([ task.accessor('owner', { header: 'Owner', filterFn: valuesFilter }), task.accessor('due', { header: () => Due, size: 120, }), - ], + ]), }), -]; +]); /** Sorted and filtered in the browser, the default. No virtualization yet. */ export function LargeDemo() { diff --git a/apps/playground/src/app/demos/task-columns.tsx b/apps/playground/src/app/demos/task-columns.tsx index bed29dc..7b03718 100644 --- a/apps/playground/src/app/demos/task-columns.tsx +++ b/apps/playground/src/app/demos/task-columns.tsx @@ -1,5 +1,5 @@ import { createColumnHelper } from '@tanstack/react-table'; -import type { CellCommitResult } from '@codemancers/sheets'; +import type { CellCommitResult, SheetFeatures } from '@codemancers/sheets'; import { SheetEditableTextCell, SheetPrimaryCell, @@ -7,7 +7,7 @@ import { } from '@codemancers/sheets/ui'; import type { Task } from '../data'; -const task = createColumnHelper(); +const task = createColumnHelper(); /** A row being filled in to create a task: its title cell is an editor. */ export type NewTaskRow = { @@ -21,7 +21,7 @@ export function taskColumns( onOpen?: (task: Task) => void, newRow?: NewTaskRow, ) { - return [ + return task.columns([ task.accessor('title', { header: 'Title', size: 300, @@ -52,5 +52,5 @@ export function taskColumns( // Plain values need no cell renderer. task.accessor('owner', { header: 'Owner' }), task.accessor('due', { header: 'Due', size: 120 }), - ]; + ]); } diff --git a/docs/architecture.md b/docs/architecture.md index 1d11100..f5e1e87 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -33,7 +33,7 @@ const sheet = useSheet({ return ; ``` -`useSheet` takes everything `useReactTable` takes, plus `cellStatus` and `rowChanges`. It returns `{ table, cellStatus, rowChanges }`, and `Sheet` renders from that. +`useSheet` takes everything TanStack's `useTable` takes, plus `cellStatus` and `rowChanges`. It returns `{ table, cellStatus, rowChanges }`, and `Sheet` renders from that. The table is built from the sheet's own feature set, `sheetFeatures`. `useCellStatus` and `useRowChanges` are separate hooks, not part of `useSheet`, because the columns refer to them: a cell's handlers are written before the table that uses those columns exists. When the app passes no `cellStatus`, `useSheet` creates its own, so cells always have somewhere to report validation and save failures. @@ -69,7 +69,7 @@ flowchart TD - **One grid for every row.** The root sets `--sheet-columns` to `40px`, then each visible leaf column's size in pixels, then `1fr`: the row-number column, the data columns, and a spacer that fills the rest. Header, body, empty, loading and add-row rows all lay out on `var(--sheet-columns)` (`src/ui/grid.ts`), so the columns line up without a ``. A group header spans its leaf columns with `grid-column: span n`. - **Pinned rows.** The body renders TanStack's pinned top rows, then the rest, then the pinned bottom rows, so a pinned row stays put whatever the sort. Apps pin a new row being filled in to the bottom. TanStack memoises the three lists, so the combined one keeps its identity for `SheetBody`'s memo. -- **Resizing re-renders little.** While a column is dragged, only the header and the root's variable change. `SheetBody` skips re-rendering while `columnSizingInfo.isResizingColumn` is set and its other props are unchanged. This is TanStack's advice for `columnResizeMode: 'onChange'`. It depends on `useCellStatus` and `useRowChanges` returning memoised objects. +- **Resizing re-renders little.** While a column is dragged, only the header and the root's variable change. `SheetBody` skips re-rendering while `columnResizing.isResizingColumn` is set and its other props are unchanged. This is TanStack's advice for `columnResizeMode: 'onChange'`. It depends on `useCellStatus` and `useRowChanges` returning memoised objects. - **Cells.** `SheetCellContent` calls the column's `cell` function itself, without `flexRender`, so a column array that's rebuilt on every render doesn't remount the cells. A string or number result is wrapped in `SheetTextCell` for its padding. Headers do use `flexRender`. - **Headers.** The sort button calls TanStack's toggle handler, and shows on hover or keyboard focus. Leaf columns get a resize handle: a focusable separator that takes the mouse, touch, the arrow keys (10 px a step, 50 px with Shift, flipped for `columnResizeDirection: 'rtl'`), and a double-click to reset the width. - **Filters.** A column whose `filterFn` is `textFilter` or `valuesFilter` gets a filter button (`SheetColumnFilter`). It opens a native popover, which sits in the top layer above the scroll container, placed under the button with CSS anchor positioning. The controls mount only while it's open: a text input, or a checklist built from TanStack's faceted values (`getFacetedUniqueValues`, which counts each value with the other columns' filters applied). Both write to TanStack's `columnFilters` through `column.setFilterValue`, and TanStack's filtered row model does the rest. The body shows "no matches" and a clear button when the column filters leave no rows. diff --git a/docs/decisions.md b/docs/decisions.md index e4b1f4d..67ca19c 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -10,20 +10,21 @@ When you make a choice that a future contributor would question, add it here. - **Built with `tsc` to ES modules, with no bundler.** Each source file becomes one module and keeps its `'use client'` directive, which the Next.js App Router needs. - **No runtime dependencies.** The icons are inlined from Heroicons and Lucide, with their licence notices, and a small `cx` helper replaces `clsx`. - **TanStack Table is a peer dependency.** Apps import `createColumnHelper` and TanStack's types themselves, and extend `ColumnMeta` and `TableMeta` through module augmentation. Under pnpm an app can only augment a module it has installed. A peer dependency also keeps a single copy of TanStack in the app. -- **TanStack Table v8.** Moving to v9 is planned for a later release. +- **TanStack Table v9.** v8 and v9 can't share a peer range: v9's types take the feature set as their first argument, and its tables are built from registered features. `@codemancers/sheets` 0.2 is the last release for v8. - **React 19 only.** The apps that use the package are on React 19, so React 18 isn't tested or supported. - **The components need Tailwind v4.** They're styled with Tailwind classes, and `styles.css` adds those classes to the app's Tailwind build, so there's no separate stylesheet to load or override. An app without Tailwind can add it, or build its own markup on the headless layer. - **The package ships its source.** `styles.css` contains `@source './'`, which makes the app's Tailwind build scan the package's source files for class names. That only works if `src/` is published. ## API -- **Plain TanStack options and column definitions.** `useSheet` takes everything `useReactTable` takes, and columns are TanStack `ColumnDef`s. An earlier custom column type covered only part of TanStack, and had to be translated. With the plain API, every TanStack option and guide applies as it is. +- **Plain TanStack options and column definitions.** `useSheet` takes everything `useTable` takes, and columns are TanStack `ColumnDef`s. An earlier custom column type covered only part of TanStack, and had to be translated. With the plain API, every TanStack option and guide applies as it is. - **Sheet defaults that any option overrides:** - Sorting and filtering run in the browser. TanStack skips them when `manualSorting` or `manualFiltering` is set, which is how an app sorts or filters on the server. - Columns resize live as they're dragged. - TanStack's faceting is on, so a values filter can list a column's values and count them. It costs nothing until a filter asks. - **Options passed as `undefined` are dropped.** TanStack spreads the options over its defaults, so `onSortingChange: undefined` replaced TanStack's internal handler, and sorting and resizing silently did nothing. -- **`autoResetPageIndex` is off.** There's no pagination UI, and resetting the page index on every data change loops forever when an app passes data that isn't memoised. +- **One fixed feature set.** TanStack v9 includes only registered features, and types every table by its feature set. The sheet registers what it renders with (sorting, column filtering and faceting, sizing, resizing, visibility, row pinning) and what v8 gave apps for free that the README documents (global filtering, column order). Apps can't pass their own set: v9's docs type tables and components with one set, and a component can't be typed for any set that includes the sheet's without casting the table's types away. The cost is that features the sheet doesn't register, such as row selection, aren't available, and a `valuesFilter` checklist can't take its values from a server. When an app needs a feature, it's added to the set. +- **Only the sort and filter functions TanStack picks by itself are registered.** v9 resolves a name, and `'auto'`, from the registered functions only, and its full registries are deprecated because they defeat tree-shaking. Registering the ones `'auto'` chooses keeps columns sorting and filtering as they did in v8. Any other function goes straight on the column as its `sortFn` or `filterFn`. - **A column opts into a header filter through its `filterFn`.** Setting `filterFn: textFilter` or `filterFn: valuesFilter` both filters the column and gives its header the matching control, so one property says what the filter does and what the user sees. Filters aren't on for every column, though TanStack allows that: its `'auto'` filter function is picked from the first row's value, which gives a column of objects or numbers a filter that doesn't work. A `ColumnMeta` flag was the other option, but it would need a matching `filterFn` set alongside it, in a second place to keep in step. - **Visual settings are `Sheet` props.** `rowHeight`, `highlightedRowId`, `openRowId` and `labels` only affect the rendering, so they aren't table state. - **Rows are identified by TanStack's `row.id`.** Statuses, staged values, and the highlighted and open rows all use it, so `getRowId` makes them follow a record through sorting and refetches. diff --git a/packages/sheets/README.md b/packages/sheets/README.md index 248f968..40fdcf1 100644 --- a/packages/sheets/README.md +++ b/packages/sheets/README.md @@ -1,6 +1,6 @@ # @codemancers/sheets -A spreadsheet-style data grid for React. It's built on [TanStack Table](https://tanstack.com/table/v8) and comes in two layers: headless hooks that add in-place editing, and ready-made components styled with Tailwind CSS v4. +A spreadsheet-style data grid for React. It's built on [TanStack Table](https://tanstack.com/table/latest) and comes in two layers: headless hooks that add in-place editing, and ready-made components styled with Tailwind CSS v4. ![A sheet with a saved edit, and a refused one showing its reason](https://raw.githubusercontent.com/codemancers/sheets/main/docs/images/sheet.png) @@ -8,7 +8,7 @@ A spreadsheet-style data grid for React. It's built on [TanStack Table](https:// - **In-place editing:** click a cell, type, then Enter to save or Escape to cancel. Each cell shows its own status: unsaved, saving, saved or refused. - **Saving per row:** edits to one row can be batched into a single request. If the server refuses a field, the error appears on that field's cell. - **Validation** with any [Standard Schema](https://standardschema.dev) library (zod, Valibot, ArkType and others). -- **Plain TanStack Table underneath:** columns are TanStack `ColumnDef`s, and `useSheet` takes every `useReactTable` option. +- **Plain TanStack Table underneath:** columns are TanStack `ColumnDef`s, and `useSheet` takes every `useTable` option. - **Accessible:** screen readers see a real table, and sorting, resizing and editing all work from the keyboard. - **Adaptable:** theme tokens, translatable labels, and right-to-left layouts. @@ -31,7 +31,7 @@ A spreadsheet-style data grid for React. It's built on [TanStack Table](https:// ## Install -You need React 19 and TanStack Table v8. The components also need Tailwind CSS v4. The hooks alone don't. +You need React 19 and TanStack Table v9. The components also need Tailwind CSS v4. The hooks alone don't. ```sh pnpm add @codemancers/sheets @tanstack/react-table @@ -58,21 +58,21 @@ This adds the components' classes and theme tokens to your Tailwind build. 'use client'; import { createColumnHelper } from '@tanstack/react-table'; -import { useSheet } from '@codemancers/sheets'; +import { useSheet, type SheetFeatures } from '@codemancers/sheets'; import { Sheet, SheetTextCell } from '@codemancers/sheets/ui'; type Task = { id: string; title: string; status: string; owner: string }; -const task = createColumnHelper(); +const task = createColumnHelper(); -const columns = [ +const columns = task.columns([ task.accessor('title', { header: 'Title', size: 280 }), task.accessor('status', { header: 'Status', cell: ({ getValue }) => {getValue()}, }), task.accessor('owner', { header: 'Owner' }), -]; +]); export function TaskSheet({ tasks }: { tasks: Task[] }) { const sheet = useSheet({ @@ -91,14 +91,17 @@ export function TaskSheet({ tasks }: { tasks: Task[] }) { How the pieces fit together: -- `useSheet` is TanStack's `useReactTable` with a sheet's defaults. It returns `{ table, cellStatus, rowChanges }`. +- `useSheet` is TanStack's `useTable` with a sheet's defaults and features. It returns `{ table, cellStatus, rowChanges }`. +- `SheetFeatures` tells TanStack's types which features the table has. It is the first type argument wherever TanStack asks for one. - `` fills its parent and scrolls inside it, so give the parent a height. - `getRowId` sets each row's id. Always set it to your data's own id: editing state, highlighting and React keys all use the row id. TanStack's default is the row's position, which changes when rows are sorted or added. - Dark mode follows the operating system unless you add the one-line `@custom-variant dark` from [Install](#install). ## Columns and cells -Columns are plain TanStack column definitions, and TanStack's [column docs](https://tanstack.com/table/v8/docs/guide/column-defs) apply as they are. `meta`, `size`/`minSize`/`maxSize`, `enableSorting`, `sortingFn`, `filterFn`, `header` functions and group columns all work. Define columns outside the component, or memoise them, as TanStack recommends. +Columns are plain TanStack column definitions, and TanStack's [column docs](https://tanstack.com/table/latest/docs/guide/column-defs) apply as they are. `meta`, `size`/`minSize`/`maxSize`, `enableSorting`, `sortFn`, `filterFn`, `header` functions and group columns all work. Define columns outside the component, or memoise them, as TanStack recommends. + +Build the array with the helper's `columns()`, as above: it keeps each column's own value type, and TanStack's types reject a plain array of accessor columns. Without a column helper, type the array as `SheetColumnDef[]`. A column without a `cell` renders its value as padded text. For anything else, render one of the built-in cells or your own markup: @@ -132,14 +135,14 @@ task.accessor('title', { **Grouped headers** span their columns: ```tsx -const columns = [ +const columns = task.columns([ task.group({ id: 'task', header: 'Task', - columns: [task.accessor('title', { header: 'Title' }), task.accessor('status', { header: 'Status' })], + columns: task.columns([task.accessor('title', { header: 'Title' }), task.accessor('status', { header: 'Status' })]), }), task.accessor('owner', { header: () => Owner }), -]; +]); ``` ## Sorting and filtering @@ -151,7 +154,7 @@ Sorting and filtering run in the browser by default. Any column with an accessor ```tsx import { textFilter, valuesFilter } from '@codemancers/sheets'; -const columns = [task.accessor('title', { header: 'Title', filterFn: textFilter }), task.accessor('status', { header: 'Status', filterFn: valuesFilter })]; +const columns = task.columns([task.accessor('title', { header: 'Title', filterFn: textFilter }), task.accessor('status', { header: 'Status', filterFn: valuesFilter })]); ``` - `textFilter` keeps the rows that contain the typed text, ignoring case. @@ -168,9 +171,9 @@ Columns without one of these have no filter button. When the filters leave no ro task.accessor((row) => row.project?.name ?? '', { id: 'project', header: 'Project' }); ``` -- For an order that isn't alphabetical, such as statuses in workflow order, give the column a `sortingFn`. +- For an order that isn't alphabetical, such as statuses in workflow order, give the column a `sortFn`. -**Server-side data.** Set TanStack's manual flags (`manualSorting`, `manualFiltering`) and control the state. The sheet then reports the sort and the filters, and your data layer applies them. With `manualFiltering`, a `valuesFilter` checklist lists the values in the rows you've loaded. To list every value from your server, with its count, pass TanStack's `getFacetedUniqueValues` option as `(table, columnId) => () => counts` (see TanStack's [server-side faceting](https://tanstack.com/table/v8/docs/guide/column-faceting#custom-server-side-faceting)). TanStack calls the outer function once per column and keeps the inner one, so have the inner one read your latest counts, from a ref for example, rather than capture them. +**Server-side data.** Set TanStack's manual flags (`manualSorting`, `manualFiltering`) and control the state. The sheet then reports the sort and the filters, and your data layer applies them. With `manualFiltering`, a `valuesFilter` checklist lists the values in the rows you've loaded. ```tsx const [sorting, setSorting] = useState([]); @@ -188,6 +191,20 @@ const sheet = useSheet({ Any state you don't control (column widths, visibility, order) is managed by the table. Change handlers receive TanStack updaters, so a React state setter works as it is. +With `manualFiltering`, a `valuesFilter` checklist lists the values in the rows you've loaded. + +### Feature set + +TanStack Table v9 only includes the features a table registers. A sheet registers sorting, column and global filtering, faceting, column sizing, resizing, visibility and ordering, and row pinning, and that set is fixed: TanStack types a table by its feature set, so the sheet's components can't take a table with another. Other TanStack features, such as row selection or pagination, aren't available yet. + +A column can name the sort and filter functions TanStack picks by itself: `'alphanumeric'`, `'text'`, `'datetime'` and `'basic'` to sort, and `'includesString'`, `'inNumberRange'`, `'inDateRange'`, `'equals'`, `'weakEquals'` and `'arrIncludes'` to filter. Pass any other function straight to the column: + +```tsx +import { sortFn_textCaseSensitive } from '@tanstack/react-table'; + +task.accessor('title', { header: 'Title', sortFn: sortFn_textCaseSensitive }); +``` + ## Editing and saving Editable cells validate a value, hand it on, and show the outcome on the cell itself rather than in a toast. A toast can't say _which_ cell it means. @@ -202,7 +219,7 @@ Cells report to the sheet's `cellStatus`. `useSheet` creates one if you don't pa import { useCellStatus, useRowChanges, useSheet } from '@codemancers/sheets'; import { Sheet, SheetEditableTextCell, SheetPrimaryCell } from '@codemancers/sheets/ui'; -const columns = [ +const columns = task.columns([ task.accessor('title', { header: 'Title', cell: ({ row }) => {row.original.title}, @@ -211,7 +228,7 @@ const columns = [ header: 'Owner', cell: ({ row }) => , }), -]; +]); function TaskSheet({ tasks }: { tasks: Task[] }) { const cellStatus = useCellStatus(); @@ -386,27 +403,28 @@ function TaskSheet({ tasks }: { tasks: Task[] }) { const [adding, setAdding] = useState(false); const columns = useMemo( - () => [ - task.accessor('title', { - header: 'Title', - cell: ({ row }) => - row.id === NEW_ROW ? ( - { - const result = await createTask(title); // { error } if refused - if (!result.error) setAdding(false); - return result; - }} - onCancel={() => setAdding(false)} - /> - ) : ( - {row.original.title} - ), - }), - ], + () => + task.columns([ + task.accessor('title', { + header: 'Title', + cell: ({ row }) => + row.id === NEW_ROW ? ( + { + const result = await createTask(title); // { error } if refused + if (!result.error) setAdding(false); + return result; + }} + onCancel={() => setAdding(false)} + /> + ) : ( + {row.original.title} + ), + }), + ]), [], ); @@ -436,25 +454,26 @@ The package doesn't draw drawers; use the drawer, side panel or dialog from your ```tsx import { useMemo } from 'react'; import { createColumnHelper } from '@tanstack/react-table'; -import { useRowDrawer, useSheet } from '@codemancers/sheets'; +import { useRowDrawer, useSheet, type SheetFeatures } from '@codemancers/sheets'; import { Sheet, SheetPrimaryCell } from '@codemancers/sheets/ui'; -const task = createColumnHelper(); +const task = createColumnHelper(); function Tasks({ tasks }: { tasks: Task[] }) { const drawer = useRowDrawer(); const { open } = drawer; const columns = useMemo( - () => [ - task.accessor('title', { - header: 'Title', - cell: ({ row }) => ( - open(row.id)}> - {row.original.title} - - ), - }), - ], + () => + task.columns([ + task.accessor('title', { + header: 'Title', + cell: ({ row }) => ( + open(row.id)}> + {row.original.title} + + ), + }), + ]), [open], ); const sheet = useSheet({ columns, data: tasks, getRowId: (t) => t.id }); @@ -618,24 +637,24 @@ Not yet supported: moving between cells with the arrow keys (`role="grid"`). - **No column pinning,** and no arrow-key navigation between cells. - **Text editors only.** The built-in editors are for text; other types need your own cells (see [Your own editable cells](#your-own-editable-cells)). - **Two filters:** text, and a checklist of values. A range, such as dates, needs your own control, through TanStack's filter APIs. -- **TanStack Table v8 only.** +- **TanStack Table v9 only.** Use `@codemancers/sheets` 0.2 with TanStack Table v8. - **The error tooltip** on the very last row of a completely full sheet can extend past the bottom edge, and the sheet scrolls to show it. ## API reference ### `@codemancers/sheets` -| Export | What it is | -| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `useSheet(options)` | `useReactTable` plus `cellStatus` and `rowChanges`. Returns `{ table, cellStatus, rowChanges }`, where `cellStatus` is the one you passed or the sheet's own. | -| `useCellStatus()` | Per-cell outcomes: `setCellSaved`, `rejectCellValue`, `rejectFieldErrors`, `clearCellStatus`, `abandonCellValueChange`, `setCellDirty`, `setCellSaving`, `statuses`, `rejectedCellValue`. | -| `useRowChanges(options)` | The per-row save buffer. Options: `onSubmitRow`, `cellStatus`, `flush`, `transportErrorMessage`. Returns `stageCellValue`, `discardCellValue`, `stagedCellValue`, `hasStagedChanges`, `flushAll`. | -| `useInlineEdit(options)` | Edit-in-place state for a text editor: `isEditing`, `beginEdit(draft?)`, `commit`, `cancel`, `inputProps`, `triggerRef`. Calls `onCancel` on Escape, and when an edit ends unchanged. | -| `useRowDrawer(options?)` | Which row is open in a drawer or panel: `openRowId`, `open`, `close`, `toggle`, `isOpen`. Options: `openRowId` and `onOpenRowIdChange` to control it, or `defaultOpenRowId`. | -| `useSheetCellEditing(schema?)` | The editing context for a cell, for building your own (see above). | -| `textFilter`, `valuesFilter` | Filter functions for a column's `filterFn`: the text it contains, or one of a checklist of values. Either one gives the column's header a filter button. | -| `SheetCellProvider`, `useSheetCellScope()` | The row, column and editing context a cell reads. | -| Types | `SheetInstance`, `UseSheetOptions`, `CellStatus`, `CellStatusState`, `RowChanges`, `RowChangesState`, `RowSubmitResult`, `RowFlushPolicy`, `RowDrawerState`, `UseRowDrawerOptions`, `CellCommitResult`, `SheetCellValidator`, `StandardSchemaV1`. | +| Export | What it is | +| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `useSheet(options)` | `useTable` with the sheet's feature set, plus `cellStatus` and `rowChanges`. Returns `{ table, cellStatus, rowChanges }`, where `cellStatus` is the one you passed or the sheet's own. | +| `useCellStatus()` | Per-cell outcomes: `setCellSaved`, `rejectCellValue`, `rejectFieldErrors`, `clearCellStatus`, `abandonCellValueChange`, `setCellDirty`, `setCellSaving`, `statuses`, `rejectedCellValue`. | +| `useRowChanges(options)` | The per-row save buffer. Options: `onSubmitRow`, `cellStatus`, `flush`, `transportErrorMessage`. Returns `stageCellValue`, `discardCellValue`, `stagedCellValue`, `hasStagedChanges`, `flushAll`. | +| `useInlineEdit(options)` | Edit-in-place state for a text editor: `isEditing`, `beginEdit(draft?)`, `commit`, `cancel`, `inputProps`, `triggerRef`. Calls `onCancel` on Escape, and when an edit ends unchanged. | +| `useRowDrawer(options?)` | Which row is open in a drawer or panel: `openRowId`, `open`, `close`, `toggle`, `isOpen`. Options: `openRowId` and `onOpenRowIdChange` to control it, or `defaultOpenRowId`. | +| `useSheetCellEditing(schema?)` | The editing context for a cell, for building your own (see above). | +| `textFilter`, `valuesFilter` | Filter functions for a column's `filterFn`: the text it contains, or one of a checklist of values. Either one gives the column's header a filter button. | +| `SheetCellProvider`, `useSheetCellScope()` | The row, column and editing context a cell reads. | +| Types | `SheetInstance`, `UseSheetOptions`, `SheetFeatures`, `SheetColumnDef`, `CellStatus`, `CellStatusState`, `RowChanges`, `RowChangesState`, `RowSubmitResult`, `RowFlushPolicy`, `RowDrawerState`, `UseRowDrawerOptions`, `CellCommitResult`, `SheetCellValidator`, `StandardSchemaV1`. | ### `@codemancers/sheets/ui` diff --git a/packages/sheets/package.json b/packages/sheets/package.json index 20a70d8..96ffe71 100644 --- a/packages/sheets/package.json +++ b/packages/sheets/package.json @@ -65,7 +65,7 @@ } }, "peerDependencies": { - "@tanstack/react-table": "^8.21.0", + "@tanstack/react-table": "^9.3.1", "react": "^19.0.0", "tailwindcss": "^4.0.0" }, @@ -75,6 +75,6 @@ } }, "devDependencies": { - "@tanstack/react-table": "^8.21.3" + "@tanstack/react-table": "^9.3.1" } } diff --git a/packages/sheets/src/hooks/filters.test.ts b/packages/sheets/src/hooks/filters.test.ts index 479529a..7e853de 100644 --- a/packages/sheets/src/hooks/filters.test.ts +++ b/packages/sheets/src/hooks/filters.test.ts @@ -2,15 +2,15 @@ import { act, renderHook } from '@testing-library/react'; import { describe, expect, it } from 'vitest'; import { createColumnHelper } from '@tanstack/react-table'; import { textFilter, valuesFilter } from './filters.js'; -import { useSheet } from './use-sheet.js'; +import { useSheet, type SheetFeatures } from './use-sheet.js'; type Row = { id: string; name: string; status: string }; -const column = createColumnHelper(); -const columns = [ +const column = createColumnHelper(); +const columns = column.columns([ column.accessor('name', { filterFn: textFilter }), column.accessor('status', { filterFn: valuesFilter }), -]; +]); const data: Row[] = [ { id: '1', name: 'Alpha', status: 'Todo' }, { id: '2', name: 'Beta', status: 'Done' }, @@ -24,7 +24,7 @@ function filterBy(columnId: string, value: unknown) { act(() => result.current.table.getColumn(columnId)?.setFilterValue(value)); return { ids: result.current.table.getRowModel().rows.map((row) => row.id), - filters: result.current.table.getState().columnFilters, + filters: result.current.table.state.columnFilters, }; } diff --git a/packages/sheets/src/hooks/filters.ts b/packages/sheets/src/hooks/filters.ts index dcfd166..dcf1979 100644 --- a/packages/sheets/src/hooks/filters.ts +++ b/packages/sheets/src/hooks/filters.ts @@ -1,24 +1,22 @@ -import { filterFns } from '@tanstack/react-table'; - -/** - * Typed like TanStack's own filter functions, which take rows of any type, so - * one function fits every table's columns. - */ -type SheetFilterFn = typeof filterFns.equals; +import { + constructFilterFn, + filterFn_includesString, +} from '@tanstack/react-table'; /** * Keeps the rows whose value contains the typed text, ignoring case: TanStack's * `includesString`. As a column's `filterFn`, it also gives the column's header * a text filter. */ -export const textFilter: SheetFilterFn = filterFns.includesString; +export const textFilter = filterFn_includesString; /** * Keeps the rows whose value is one of the picked values. As a column's * `filterFn`, it also gives the column's header a checklist of the column's * values, each with its number of rows. */ -export const valuesFilter: SheetFilterFn = (row, columnId, picked: unknown[]) => - picked.includes(row.getValue(columnId)); -// Nothing picked means no filter, not a sheet with every row hidden. -valuesFilter.autoRemove = (picked?: unknown[]) => !picked?.length; +export const valuesFilter = constructFilterFn({ + filter: (value, picked: unknown[]) => picked.includes(value), + // Nothing picked means no filter, not a sheet with every row hidden. + autoRemove: (picked?: unknown[]) => !picked?.length, +}); diff --git a/packages/sheets/src/hooks/use-sheet.test.ts b/packages/sheets/src/hooks/use-sheet.test.ts index 6f6623a..a13f7cd 100644 --- a/packages/sheets/src/hooks/use-sheet.test.ts +++ b/packages/sheets/src/hooks/use-sheet.test.ts @@ -1,19 +1,28 @@ import { act, renderHook } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; -import { createColumnHelper, type SortingState } from '@tanstack/react-table'; +import { + createColumnHelper, + sortFn_textCaseSensitive, + type SortingState, +} from '@tanstack/react-table'; import { useCellStatus } from './use-cell-status.js'; -import { useSheet } from './use-sheet.js'; +import { + useSheet, + type SheetColumnDef, + type SheetFeatures, +} from './use-sheet.js'; type Row = { id: string; name: string }; -const column = createColumnHelper(); -const columns = [column.accessor('name', { header: 'Name' })]; +const column = createColumnHelper(); +const columns = column.columns([column.accessor('name', { header: 'Name' })]); const data: Row[] = [ { id: '1', name: 'b' }, { id: '2', name: 'a' }, ]; -const names = (result: { current: ReturnType> }) => - result.current.table.getRowModel().rows.map((row) => row.original.name); +const names = (result: { + current: { table: { getRowModel: () => { rows: { original: Row }[] } } }; +}) => result.current.table.getRowModel().rows.map((row) => row.original.name); describe('useSheet', () => { it('sorts in the browser by default', () => { @@ -31,7 +40,7 @@ describe('useSheet', () => { act(() => result.current.table.getColumn('name')?.toggleSorting(false)); - expect(result.current.table.getState().sorting).toEqual([ + expect(result.current.table.state.sorting).toEqual([ { id: 'name', desc: false }, ]); expect(names(result)).toEqual(['b', 'a']); @@ -60,6 +69,75 @@ describe('useSheet', () => { ); }); + it('sorts numbers and dates without a sortFn', () => { + type Entry = { id: string; count: number; on: Date }; + const entries: Entry[] = [ + { id: '1', count: 10, on: new Date('2026-03-01') }, + { id: '2', count: 9, on: new Date('2026-01-01') }, + ]; + const entryColumns: SheetColumnDef[] = [ + { accessorKey: 'count' }, + { accessorKey: 'on' }, + ]; + const { result } = renderHook(() => + useSheet({ columns: entryColumns, data: entries }), + ); + const ids = () => + result.current.table.getRowModel().rows.map((row) => row.original.id); + + act(() => result.current.table.getColumn('count')?.toggleSorting(false)); + expect(ids()).toEqual(['2', '1']); + + act(() => result.current.table.getColumn('on')?.toggleSorting(false)); + expect(ids()).toEqual(['2', '1']); + }); + + it('filters across columns with the global filter', () => { + const { result } = renderHook(() => useSheet({ columns, data })); + + act(() => result.current.table.setGlobalFilter('a')); + + expect(names(result)).toEqual(['a']); + }); + + it('reorders columns', () => { + const twoColumns = column.columns([ + column.accessor('id', {}), + column.accessor('name', {}), + ]); + const { result } = renderHook(() => + useSheet({ columns: twoColumns, data }), + ); + + act(() => result.current.table.setColumnOrder(['name', 'id'])); + + expect( + result.current.table.getVisibleLeafColumns().map((leaf) => leaf.id), + ).toEqual(['name', 'id']); + }); + + // A custom sort function goes straight on the column, as v9's docs show: + // the sheet's feature set is fixed, so nothing is registered by name. + it('sorts with a function set on the column', () => { + const mixed: Row[] = [ + { id: '1', name: 'b' }, + { id: '2', name: 'B' }, + { id: '3', name: 'a' }, + ]; + const { result } = renderHook(() => + useSheet({ + columns: column.columns([ + column.accessor('name', { sortFn: sortFn_textCaseSensitive }), + ]), + data: mixed, + }), + ); + + act(() => result.current.table.getColumn('name')?.toggleSorting(false)); + + expect(names(result)).toEqual(['B', 'a', 'b']); + }); + describe('controlled state', () => { it('leaves the state to the app and reports the change', () => { const onSortingChange = vi.fn(); @@ -69,7 +147,7 @@ describe('useSheet', () => { act(() => result.current.table.getColumn('name')?.toggleSorting(false)); - expect(result.current.table.getState().sorting).toEqual([]); + expect(result.current.table.state.sorting).toEqual([]); expect(onSortingChange).toHaveBeenCalledTimes(1); }); @@ -90,7 +168,7 @@ describe('useSheet', () => { act(() => result.current.table.getColumn('name')?.toggleSorting(true)); rerender(); - expect(result.current.table.getState().sorting).toEqual([ + expect(result.current.table.state.sorting).toEqual([ { id: 'name', desc: true }, ]); }); diff --git a/packages/sheets/src/hooks/use-sheet.ts b/packages/sheets/src/hooks/use-sheet.ts index 7f1c2b0..b1363b2 100644 --- a/packages/sheets/src/hooks/use-sheet.ts +++ b/packages/sheets/src/hooks/use-sheet.ts @@ -1,12 +1,32 @@ 'use client'; import { - getCoreRowModel, - getFacetedRowModel, - getFacetedUniqueValues, - getFilteredRowModel, - getSortedRowModel, - useReactTable, + columnFacetingFeature, + columnFilteringFeature, + columnOrderingFeature, + columnResizingFeature, + columnSizingFeature, + columnVisibilityFeature, + createFacetedRowModel, + createFacetedUniqueValues, + createFilteredRowModel, + createSortedRowModel, + filterFn_arrIncludes, + filterFn_equals, + filterFn_inDateRange, + filterFn_inNumberRange, + filterFn_includesString, + filterFn_weakEquals, + globalFilteringFeature, + rowPinningFeature, + rowSortingFeature, + sortFn_alphanumeric, + sortFn_basic, + sortFn_datetime, + sortFn_text, + tableFeatures, + useTable, + type ColumnDef, type RowData, type TableOptions, } from '@tanstack/react-table'; @@ -14,28 +34,73 @@ import { useCellStatus, type CellStatusState } from './use-cell-status.js'; import type { RowChangesState } from './use-row-changes.js'; /** - * Everything `useReactTable` takes — columns are plain TanStack `ColumnDef`s - * — plus the sheet's editing state. `getCoreRowModel` is supplied. + * The TanStack features a sheet is built on, and the sort and filter + * functions TanStack picks from when a column names none. Every sheet uses + * this one set: TanStack v9 types a table by its feature set, so components + * typed for this set can't take a table with another. + */ +const sheetFeatures = tableFeatures({ + columnFilteringFeature, + columnFacetingFeature, + globalFilteringFeature, + columnOrderingFeature, + columnVisibilityFeature, + columnSizingFeature, + columnResizingFeature, + rowPinningFeature, + rowSortingFeature, + filteredRowModel: createFilteredRowModel(), + sortedRowModel: createSortedRowModel(), + // Counted per column only when asked for: when a values filter opens. + facetedRowModel: createFacetedRowModel(), + facetedUniqueValues: createFacetedUniqueValues(), + filterFns: { + arrIncludes: filterFn_arrIncludes, + equals: filterFn_equals, + inDateRange: filterFn_inDateRange, + inNumberRange: filterFn_inNumberRange, + includesString: filterFn_includesString, + weakEquals: filterFn_weakEquals, + }, + sortFns: { + alphanumeric: sortFn_alphanumeric, + basic: sortFn_basic, + datetime: sortFn_datetime, + text: sortFn_text, + }, +}); + +export type SheetFeatures = typeof sheetFeatures; + +/** A TanStack `ColumnDef` for a sheet with the default features. */ +export type SheetColumnDef = ColumnDef< + SheetFeatures, + TData, + TValue +>; + +/** + * Everything `useTable` takes except `features`, which is the sheet's own — + * columns are plain TanStack `ColumnDef`s — plus the sheet's editing state. */ export type UseSheetOptions = Omit< - TableOptions, - 'getCoreRowModel' -> & - Partial, 'getCoreRowModel'>> & { - /** - * The whole `useCellStatus()` state. Not just the map: cells validate - * their own committed values against the column schema, so they need the - * setters. The sheet creates its own when this is omitted; pass one when - * `useRowChanges` or your own handlers report to it. - */ - cellStatus?: CellStatusState; - /** - * From `useRowChanges()`. Pass it to submit per row instead of per cell — - * editable cells then stage their committed values here. Omit to keep each - * cell performing its own write through its `onCommit`. - */ - rowChanges?: RowChangesState; - }; + TableOptions, + 'features' +> & { + /** + * The whole `useCellStatus()` state. Not just the map: cells validate + * their own committed values against the column schema, so they need the + * setters. The sheet creates its own when this is omitted; pass one when + * `useRowChanges` or your own handlers report to it. + */ + cellStatus?: CellStatusState; + /** + * From `useRowChanges()`. Pass it to submit per row instead of per cell — + * editable cells then stage their committed values here. Omit to keep each + * cell performing its own write through its `onCommit`. + */ + rowChanges?: RowChangesState; +}; /** * Drops undefined entries. TanStack spreads options over its defaults, so an @@ -49,10 +114,10 @@ function defined(values: T): T { } /** - * `useReactTable` with a sheet's defaults: sorting and filtering in the - * browser (TanStack skips them when `manualSorting` / `manualFiltering` is - * set, for server-side data), each column's values and counts for its filter, - * and live column resizing. Any option the app passes wins. + * `useTable` with a sheet's defaults: sorting and filtering in the browser + * (TanStack skips them when `manualSorting` / `manualFiltering` is set, for + * server-side data), each column's values and counts for its filter, and + * live column resizing. Any option the app passes wins. */ export function useSheet({ cellStatus, @@ -62,20 +127,12 @@ export function useSheet({ // Cells report validation and save failures through this, so every sheet // has one, not only those that save per row. const ownCellStatus = useCellStatus(); - const table = useReactTable({ - getCoreRowModel: getCoreRowModel(), - getSortedRowModel: getSortedRowModel(), - getFilteredRowModel: getFilteredRowModel(), - // Counted per column only when asked for: when a values filter opens. - getFacetedRowModel: getFacetedRowModel(), - getFacetedUniqueValues: getFacetedUniqueValues(), + const table = useTable({ enableColumnResizing: true, columnResizeMode: 'onChange', - // There is no pagination UI, and resetting the page index on every data - // change would loop forever when an app passes data that is not memoised. - autoResetPageIndex: false, ...defined(options), ...(options.state ? { state: defined(options.state) } : {}), + features: sheetFeatures, }); return { table, cellStatus: cellStatus ?? ownCellStatus, rowChanges }; diff --git a/packages/sheets/src/ui/sheet-column-filter.test.tsx b/packages/sheets/src/ui/sheet-column-filter.test.tsx index 1486cda..140dbe7 100644 --- a/packages/sheets/src/ui/sheet-column-filter.test.tsx +++ b/packages/sheets/src/ui/sheet-column-filter.test.tsx @@ -2,16 +2,16 @@ import { act, fireEvent, render, screen } from '@testing-library/react'; import { beforeAll, describe, expect, it } from 'vitest'; import { createColumnHelper } from '@tanstack/react-table'; import { textFilter, valuesFilter } from '../hooks/filters.js'; -import { useSheet } from '../hooks/use-sheet.js'; +import { useSheet, type SheetFeatures } from '../hooks/use-sheet.js'; import { Sheet } from './sheet.js'; type Task = { id: string; title: string; status: string; owner: string }; -const task = createColumnHelper(); -const columns = [ +const task = createColumnHelper(); +const columns = task.columns([ task.accessor('title', { header: 'Title', filterFn: textFilter }), task.accessor('status', { header: 'Status', filterFn: valuesFilter }), task.accessor('owner', { header: 'Owner' }), -]; +]); const tasks: Task[] = [ { id: '1', title: 'Write docs', status: 'Todo', owner: 'Ada' }, { id: '2', title: 'Fix the docs build', status: 'Done', owner: 'Alan' }, @@ -115,28 +115,6 @@ describe('SheetColumnFilter', () => { expect(screen.getByRole('checkbox', { name: 'Done 1' })).toBeTruthy(); }); - it('lists the values the app supplies, such as counts from a server', () => { - const counts = new Map([ - ['Todo', 12], - ['Done', 30], - ]); - function ServerTasks() { - const sheet = useSheet({ - columns, - data: tasks, - getRowId: (row) => row.id, - manualFiltering: true, - getFacetedUniqueValues: () => () => counts, - }); - return ; - } - render(); - openFilter('Filter Status'); - - expect(screen.getByRole('checkbox', { name: 'Done 30' })).toBeTruthy(); - expect(screen.getByRole('checkbox', { name: 'Todo 12' })).toBeTruthy(); - }); - it('clears its column and closes', () => { render(); openFilter('Filter Status'); diff --git a/packages/sheets/src/ui/sheet-column-filter.tsx b/packages/sheets/src/ui/sheet-column-filter.tsx index f231a15..8eb407d 100644 --- a/packages/sheets/src/ui/sheet-column-filter.tsx +++ b/packages/sheets/src/ui/sheet-column-filter.tsx @@ -1,8 +1,9 @@ 'use client'; import { useId, useRef, useState } from 'react'; -import type { Column } from '@tanstack/react-table'; +import type { Column, RowData } from '@tanstack/react-table'; import { textFilter, valuesFilter } from '../hooks/filters.js'; +import type { SheetFeatures } from '../hooks/use-sheet.js'; import { cx } from './cx.js'; import { FunnelIcon } from './icons.js'; import { useSheetLabels } from './labels.js'; @@ -10,18 +11,20 @@ import { useSheetLabels } from './labels.js'; type FilterKind = 'text' | 'values'; /** The filter control a column asked for through its `filterFn`, if any. */ -export function columnFilterKind( - column: Column, +export function columnFilterKind( + column: Column, ): FilterKind | undefined { if (!column.getCanFilter()) return undefined; - const { filterFn } = column.columnDef; + // Only compared by identity, and TypeScript finds no overlap between a + // column's filter function type and a built-in one's. + const filterFn: unknown = column.columnDef.filterFn; if (filterFn === textFilter) return 'text'; if (filterFn === valuesFilter) return 'values'; return undefined; } -type SheetColumnFilterProps = { - column: Column; +type SheetColumnFilterProps = { + column: Column; kind: FilterKind; /** The column's name, as in "Filter Title". */ label: string; @@ -34,7 +37,7 @@ type SheetColumnFilterProps = { * on a click outside and returns focus to the button. CSS anchor positioning * places it under the button, mirrored in right-to-left layouts. */ -export function SheetColumnFilter({ +export function SheetColumnFilter({ column, kind, label, @@ -116,12 +119,12 @@ export function SheetColumnFilter({ ); } -function TextFilter({ +function TextFilter({ column, label, close, }: { - column: Column; + column: Column; label: string; close: () => void; }) { @@ -147,7 +150,11 @@ function TextFilter({ ); } -function ValuesFilter({ column }: { column: Column }) { +function ValuesFilter({ + column, +}: { + column: Column; +}) { const labels = useSheetLabels(); const value = column.getFilterValue(); const picked = Array.isArray(value) ? value : []; diff --git a/packages/sheets/src/ui/sheet-column.tsx b/packages/sheets/src/ui/sheet-column.tsx index c9b21ee..e07e0b3 100644 --- a/packages/sheets/src/ui/sheet-column.tsx +++ b/packages/sheets/src/ui/sheet-column.tsx @@ -7,20 +7,21 @@ import { FunnelIcon, } from './icons.js'; import { cx } from './cx.js'; -import { flexRender, type Header } from '@tanstack/react-table'; +import { flexRender, type Header, type RowData } from '@tanstack/react-table'; +import type { SheetFeatures } from '../hooks/use-sheet.js'; import { useSheetLabels } from './labels.js'; import { columnFilterKind, SheetColumnFilter } from './sheet-column-filter.js'; /** Pixels per arrow key on the resize handle; Shift moves five steps. */ const RESIZE_STEP = 10; -export type SheetColumnProps = { - header: Header; +export type SheetColumnProps = { + header: Header; isFirstCol?: boolean; className?: string; }; -export function SheetColumn({ +export function SheetColumn({ header, isFirstCol, className, diff --git a/packages/sheets/src/ui/sheet-header.tsx b/packages/sheets/src/ui/sheet-header.tsx index 99905c2..6073391 100644 --- a/packages/sheets/src/ui/sheet-header.tsx +++ b/packages/sheets/src/ui/sheet-header.tsx @@ -1,14 +1,17 @@ -import type { Table } from '@tanstack/react-table'; +import type { RowData, Table } from '@tanstack/react-table'; +import type { SheetFeatures } from '../hooks/use-sheet.js'; import { SheetColumn } from './sheet-column.js'; import { SheetRowNumber } from './sheet-row-number.js'; import { SheetSpacerColumn } from './sheet-spacer-column.js'; import { sheetGrid } from './grid.js'; -export type SheetHeaderProps = { - table: Table; +export type SheetHeaderProps = { + table: Table; }; -export function SheetHeader({ table }: SheetHeaderProps) { +export function SheetHeader({ + table, +}: SheetHeaderProps) { return (
= { - row: Row; +export type SheetRowProps = { + row: Row; rowIndex: number; rowHeight: number; highlight?: boolean; @@ -31,10 +32,10 @@ export type SheetRowProps = { * type, so columns rebuilt on a render (an inline array, or a memo whose deps * changed) remounted every cell and closed any open editor. */ -function SheetCellContent({ +function SheetCellContent({ context, }: { - context: CellContext; + context: CellContext; }) { const render = context.column.columnDef.cell; const content = typeof render === 'function' ? render(context) : render; @@ -47,7 +48,7 @@ function SheetCellContent({ ); } -export function SheetRow({ +export function SheetRow({ row, rowIndex, rowHeight, diff --git a/packages/sheets/src/ui/sheet.test.tsx b/packages/sheets/src/ui/sheet.test.tsx index 265789e..7ead144 100644 --- a/packages/sheets/src/ui/sheet.test.tsx +++ b/packages/sheets/src/ui/sheet.test.tsx @@ -1,14 +1,14 @@ -import { fireEvent, render, screen, within } from '@testing-library/react'; +import { act, fireEvent, render, screen, within } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; import { createColumnHelper } from '@tanstack/react-table'; import { textFilter } from '../hooks/filters.js'; -import { useSheet } from '../hooks/use-sheet.js'; +import { useSheet, type SheetFeatures } from '../hooks/use-sheet.js'; import { Sheet } from './sheet.js'; import { SheetEditableTextCell } from './cells/editable-text-cell.js'; import { useSheetLabels, type SheetLabels } from './labels.js'; type Row = { id: number; name: string }; -const rowColumn = createColumnHelper(); +const rowColumn = createColumnHelper(); function TestSheet({ data, @@ -18,7 +18,9 @@ function TestSheet({ isLoading?: boolean; }) { const sheet = useSheet({ - columns: [rowColumn.accessor('name', { header: 'Name' })], + columns: rowColumn.columns([ + rowColumn.accessor('name', { header: 'Name' }), + ]), data, getRowId: (row) => String(row.id), }); @@ -48,14 +50,14 @@ describe('Sheet', () => { it('keeps an open editor through a render that rebuilds the columns', () => { function InlineColumns() { const sheet = useSheet({ - columns: [ + columns: rowColumn.columns([ rowColumn.accessor('name', { header: 'Name', cell: ({ row }) => ( ), }), - ], + ]), data: [{ id: 1, name: 'Alpha' }], getRowId: (row) => String(row.id), }); @@ -80,20 +82,20 @@ describe('Sheet', () => { it('renders function headers, and group headers spanning their columns', () => { type Person = { id: string; first: string; last: string; age: number }; - const person = createColumnHelper(); + const person = createColumnHelper(); function Grouped() { const sheet = useSheet({ - columns: [ + columns: person.columns([ person.group({ id: 'name', header: 'Name', - columns: [ + columns: person.columns([ person.accessor('first', { header: 'First' }), person.accessor('last', { header: () => Last }), - ], + ]), }), person.accessor('age', { header: 'Age' }), - ], + ]), data: [{ id: '1', first: 'Ada', last: 'Lovelace', age: 36 }], getRowId: (p) => p.id, }); @@ -112,7 +114,9 @@ describe('Sheet', () => { it('marks the row open in a drawer as the current one', () => { function WithOpenRow() { const sheet = useSheet({ - columns: [rowColumn.accessor('name', { header: 'Name' })], + columns: rowColumn.columns([ + rowColumn.accessor('name', { header: 'Name' }), + ]), data: [ { id: 1, name: 'Alpha' }, { id: 2, name: 'Beta' }, @@ -135,7 +139,9 @@ describe('Sheet', () => { function WithNewRow({ data }: { data: Row[] }) { const sheet = useSheet({ - columns: [rowColumn.accessor('name', { header: 'Name' })], + columns: rowColumn.columns([ + rowColumn.accessor('name', { header: 'Name' }), + ]), data, getRowId: (row) => (row.id === 0 ? 'new' : String(row.id)), state: { rowPinning }, @@ -173,7 +179,7 @@ describe('Sheet', () => { describe('accessibility', () => { type Task = { id: string; title: string }; - const taskColumn = createColumnHelper(); + const taskColumn = createColumnHelper(); function TaskSheet({ isLoading = false, @@ -183,7 +189,7 @@ describe('Sheet', () => { labels?: Partial; }) { const sheet = useSheet({ - columns: [ + columns: taskColumn.columns([ taskColumn.accessor('title', { header: 'Title', size: 200, @@ -191,7 +197,7 @@ describe('Sheet', () => { ), }), - ], + ]), data: [{ id: '1', title: 'Alpha' }], getRowId: (task) => task.id, }); @@ -303,7 +309,7 @@ describe('Sheet', () => { it('shows the empty label in a cell of the table', () => { function Empty() { const sheet = useSheet({ - columns: [rowColumn.accessor('name', {})], + columns: rowColumn.columns([rowColumn.accessor('name', {})]), data: [], }); return ; @@ -321,20 +327,20 @@ describe('Sheet', () => { // each row's number cell, re-renders on every frame of a drag. it('keeps label readers still during a drag when labels are inline', () => { type Task = { id: string; title: string }; - const taskColumn = createColumnHelper(); + const taskColumn = createColumnHelper(); const labelReads = vi.fn(); function ReadsLabels() { useSheetLabels(); labelReads(); return null; } - const columns = [ + const columns = taskColumn.columns([ taskColumn.accessor('title', { header: 'Title', size: 200, cell: () => , }), - ]; + ]); const data = [{ id: '1', title: 'Alpha' }]; function DragSheet() { const sheet = useSheet({ columns, data, getRowId: (task) => task.id }); @@ -355,7 +361,9 @@ describe('Sheet', () => { it('updates its labels when their values change', () => { function Labelled({ addRow }: { addRow: string }) { const sheet = useSheet({ - columns: [rowColumn.accessor('name', { header: 'Name' })], + columns: rowColumn.columns([ + rowColumn.accessor('name', { header: 'Name' }), + ]), data: [], }); return ; @@ -371,9 +379,9 @@ describe('Sheet', () => { it('says when the filters hide every row, and clears them', () => { function Filtered() { const sheet = useSheet({ - columns: [ + columns: rowColumn.columns([ rowColumn.accessor('name', { header: 'Name', filterFn: textFilter }), - ], + ]), data: [{ id: 1, name: 'Alpha' }], getRowId: (row) => String(row.id), initialState: { columnFilters: [{ id: 'name', value: 'zzz' }] }, @@ -392,7 +400,9 @@ describe('Sheet', () => { it('marks the highlighted row with data-highlighted', () => { function Highlighted() { const sheet = useSheet({ - columns: [rowColumn.accessor('name', { header: 'Name' })], + columns: rowColumn.columns([ + rowColumn.accessor('name', { header: 'Name' }), + ]), data: [ { id: 1, name: 'Alpha' }, { id: 2, name: 'Beta' }, @@ -408,11 +418,11 @@ describe('Sheet', () => { expect(beta.getAttribute('data-highlighted')).toBe('true'); }); - it('does not re-render the rows while a column is dragged', () => { + it('does not re-render the rows while a column is dragged', async () => { type Task = { id: string; title: string }; - const taskColumn = createColumnHelper(); + const taskColumn = createColumnHelper(); const cellRenders = vi.fn(); - const columns = [ + const columns = taskColumn.columns([ taskColumn.accessor('title', { header: 'Title', size: 200, @@ -421,7 +431,7 @@ describe('Sheet', () => { return getValue(); }, }), - ]; + ]); const data = [{ id: '1', title: 'Alpha' }]; function DragSheet() { const sheet = useSheet({ columns, data, getRowId: (task) => task.id }); @@ -435,6 +445,9 @@ describe('Sheet', () => { const before = cellRenders.mock.calls.length; fireEvent.mouseMove(document, { clientX: 140 }); fireEvent.mouseMove(document, { clientX: 180 }); + await act( + () => new Promise((done) => requestAnimationFrame(() => done())), + ); expect(root.style.getPropertyValue('--sheet-columns')).toContain('280px'); expect(cellRenders.mock.calls.length).toBe(before); diff --git a/packages/sheets/src/ui/sheet.tsx b/packages/sheets/src/ui/sheet.tsx index 47fe046..f39f2a6 100644 --- a/packages/sheets/src/ui/sheet.tsx +++ b/packages/sheets/src/ui/sheet.tsx @@ -9,7 +9,7 @@ import { type ReactNode, } from 'react'; import type { Row, RowData } from '@tanstack/react-table'; -import type { SheetInstance } from '../hooks/use-sheet.js'; +import type { SheetFeatures, SheetInstance } from '../hooks/use-sheet.js'; import type { CellStatusState } from '../hooks/use-cell-status.js'; import type { RowChangesState } from '../hooks/use-row-changes.js'; import { SheetAddRow } from './sheet-add-row.js'; @@ -64,7 +64,7 @@ export type SheetProps = { }; type SheetBodyProps = { - rows: Row[]; + rows: Row[]; rowHeight: number; highlightedRowId?: string; openRowId?: string | null; @@ -198,7 +198,7 @@ export function Sheet({ {/* `emptyState` means there's no data. Here there is, but the filters hide all of it. */} - {table.getState().columnFilters.length > 0 ? ( + {table.state.columnFilters.length > 0 ? ( <> {text.noMatches}{' '}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 456d024..1890032 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -345,8 +345,8 @@ importers: specifier: workspace:* version: link:../../packages/sheets '@tanstack/react-table': - specifier: ^8.21.3 - version: 8.21.3(react-dom@19.0.0(react@19.0.0))(react@19.0.0) + specifier: ^9.3.1 + version: 9.3.1(react-dom@19.0.0(react@19.0.0))(react@19.0.0) apps/playground-e2e: {} @@ -360,8 +360,8 @@ importers: version: 4.3.3 devDependencies: '@tanstack/react-table': - specifier: ^8.21.3 - version: 8.21.3(react-dom@19.0.0(react@19.0.0))(react@19.0.0) + specifier: ^9.3.1 + version: 9.3.1(react-dom@19.0.0(react@19.0.0))(react@19.0.0) packages: @@ -2208,16 +2208,24 @@ packages: peerDependencies: vite: ^5.2.0 || ^6 || ^7 || ^8 - '@tanstack/react-table@8.21.3': - resolution: {integrity: sha512-5nNMTSETP4ykGegmVkhjcS8tTLW6Vl4axfEGQN3v0zdHYbK4UfoqfPChclTrJ4EoK9QynqAu9oUf8VEmrpZ5Ww==} - engines: {node: '>=12'} + '@tanstack/react-store@0.11.2': + resolution: {integrity: sha512-oj5O5DmiMWE+ih+SioX2ayC1kbK7d3fpLx0B75fPJr9nY3zU+hoW010yr64qXsY/9fyiLVE2bn5mGNV3owm8RQ==} peerDependencies: - react: '>=16.8' - react-dom: '>=16.8' + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - '@tanstack/table-core@8.21.3': - resolution: {integrity: sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg==} - engines: {node: '>=12'} + '@tanstack/react-table@9.3.1': + resolution: {integrity: sha512-E6Ya5TnY6EaGyZYIUqig/29Lr/gJSAubQkLJFqiWkUl5nRCr0Xr9hvJot+NiRTtG+TzGxHTiqUW3bnLtQxlHug==} + engines: {node: '>=20'} + peerDependencies: + react: '>=18' + + '@tanstack/store@0.11.2': + resolution: {integrity: sha512-sJ4mjol8uQsHV0gOJzzjwXfh2Fwm+Sz0+8deqiTm4jGbMdjzNSW+xZCFm0kUa870uhd8yi+DpKnZb5Kc4apa0Q==} + + '@tanstack/table-core@9.3.1': + resolution: {integrity: sha512-zQvlxSNi2qGM3L4jh85Z6hqMfdIR5qOfD9KHOU32nuKFJGN0RlJ7UvV1lsPb1fPVhpFYI0VP3jJGxLdLDpTKjQ==} + engines: {node: '>=20'} '@testing-library/dom@10.4.0': resolution: {integrity: sha512-pemlzrSESWbdAloYml3bAJMEfNh1Z7EduzqPKprCH5S341frlpYnUEW0H72dLxa6IsYr+mPno20GiSm+h9dEdQ==} @@ -5502,6 +5510,11 @@ packages: url-parse@1.5.10: resolution: {integrity: sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==} + use-sync-external-store@1.7.0: + resolution: {integrity: sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==} + peerDependencies: + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} @@ -7789,13 +7802,26 @@ snapshots: tailwindcss: 4.3.3 vite: 8.3.0(@types/node@24.13.6)(esbuild@0.27.7)(jiti@2.4.2)(yaml@2.9.0) - '@tanstack/react-table@8.21.3(react-dom@19.0.0(react@19.0.0))(react@19.0.0)': + '@tanstack/react-store@0.11.2(react-dom@19.0.0(react@19.0.0))(react@19.0.0)': dependencies: - '@tanstack/table-core': 8.21.3 + '@tanstack/store': 0.11.2 react: 19.0.0 react-dom: 19.0.0(react@19.0.0) + use-sync-external-store: 1.7.0(react@19.0.0) - '@tanstack/table-core@8.21.3': {} + '@tanstack/react-table@9.3.1(react-dom@19.0.0(react@19.0.0))(react@19.0.0)': + dependencies: + '@tanstack/react-store': 0.11.2(react-dom@19.0.0(react@19.0.0))(react@19.0.0) + '@tanstack/table-core': 9.3.1 + react: 19.0.0 + transitivePeerDependencies: + - react-dom + + '@tanstack/store@0.11.2': {} + + '@tanstack/table-core@9.3.1': + dependencies: + '@tanstack/store': 0.11.2 '@testing-library/dom@10.4.0': dependencies: @@ -11982,6 +12008,10 @@ snapshots: querystringify: 2.2.0 requires-port: 1.0.0 + use-sync-external-store@1.7.0(react@19.0.0): + dependencies: + react: 19.0.0 + util-deprecate@1.0.2: {} utils-merge@1.0.1: