From ff5a8e92a9cf8d7328436b96d6ebefb53649aa7b Mon Sep 17 00:00:00 2001 From: SyedSibtainRazvi Date: Thu, 12 Nov 2026 15:53:07 +0530 Subject: [PATCH 1/5] feat: filter columns from their headers --- packages/sheets/src/hooks/filters.test.ts | 56 +++++ packages/sheets/src/hooks/filters.ts | 24 +++ packages/sheets/src/hooks/index.ts | 1 + packages/sheets/src/hooks/use-sheet.test.ts | 15 ++ packages/sheets/src/hooks/use-sheet.ts | 9 +- packages/sheets/src/ui/labels.tsx | 18 ++ .../src/ui/sheet-column-filter.test.tsx | 128 ++++++++++++ .../sheets/src/ui/sheet-column-filter.tsx | 194 ++++++++++++++++++ packages/sheets/src/ui/sheet-column.tsx | 34 ++- packages/sheets/src/ui/sheet.test.tsx | 22 ++ packages/sheets/src/ui/sheet.tsx | 19 +- 11 files changed, 507 insertions(+), 13 deletions(-) create mode 100644 packages/sheets/src/hooks/filters.test.ts create mode 100644 packages/sheets/src/hooks/filters.ts create mode 100644 packages/sheets/src/ui/sheet-column-filter.test.tsx create mode 100644 packages/sheets/src/ui/sheet-column-filter.tsx diff --git a/packages/sheets/src/hooks/filters.test.ts b/packages/sheets/src/hooks/filters.test.ts new file mode 100644 index 0000000..479529a --- /dev/null +++ b/packages/sheets/src/hooks/filters.test.ts @@ -0,0 +1,56 @@ +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'; + +type Row = { id: string; name: string; status: string }; + +const column = createColumnHelper(); +const 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' }, + { id: '3', name: 'alphabet', status: 'In progress' }, +]; + +function filterBy(columnId: string, value: unknown) { + const { result } = renderHook(() => + useSheet({ columns, data, getRowId: (row) => row.id }), + ); + 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, + }; +} + +describe('textFilter', () => { + it('keeps the rows that contain the text, ignoring case', () => { + expect(filterBy('name', 'ALPHA').ids).toEqual(['1', '3']); + }); + + it('drops the filter when the text is cleared', () => { + expect(filterBy('name', '').filters).toEqual([]); + }); +}); + +describe('valuesFilter', () => { + it('keeps the rows whose value is one of the picked values', () => { + expect(filterBy('status', ['Todo', 'Done']).ids).toEqual(['1', '2']); + }); + + it('matches whole values, not parts of them', () => { + expect(filterBy('status', ['progress']).ids).toEqual([]); + }); + + it('drops the filter when nothing is picked', () => { + const { ids, filters } = filterBy('status', []); + + expect(filters).toEqual([]); + expect(ids).toEqual(['1', '2', '3']); + }); +}); diff --git a/packages/sheets/src/hooks/filters.ts b/packages/sheets/src/hooks/filters.ts new file mode 100644 index 0000000..dcfd166 --- /dev/null +++ b/packages/sheets/src/hooks/filters.ts @@ -0,0 +1,24 @@ +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; + +/** + * 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; + +/** + * 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; diff --git a/packages/sheets/src/hooks/index.ts b/packages/sheets/src/hooks/index.ts index 393bb7f..bb6f9b6 100644 --- a/packages/sheets/src/hooks/index.ts +++ b/packages/sheets/src/hooks/index.ts @@ -6,3 +6,4 @@ export * from './use-sheet.js'; export * from './cell-context.js'; export * from './use-cell-editing.js'; export * from './use-row-drawer.js'; +export * from './filters.js'; diff --git a/packages/sheets/src/hooks/use-sheet.test.ts b/packages/sheets/src/hooks/use-sheet.test.ts index 7631b4c..6f6623a 100644 --- a/packages/sheets/src/hooks/use-sheet.test.ts +++ b/packages/sheets/src/hooks/use-sheet.test.ts @@ -45,6 +45,21 @@ describe('useSheet', () => { expect(result.current.table.getColumn('name')?.getSize()).toBe(240); }); + it("counts a column's values, for its filter", () => { + const { result } = renderHook(() => + useSheet({ columns, data: [...data, { id: '3', name: 'a' }] }), + ); + + expect( + result.current.table.getColumn('name')?.getFacetedUniqueValues(), + ).toEqual( + new Map([ + ['b', 1], + ['a', 2], + ]), + ); + }); + describe('controlled state', () => { it('leaves the state to the app and reports the change', () => { const onSortingChange = vi.fn(); diff --git a/packages/sheets/src/hooks/use-sheet.ts b/packages/sheets/src/hooks/use-sheet.ts index 0b72e7c..7f1c2b0 100644 --- a/packages/sheets/src/hooks/use-sheet.ts +++ b/packages/sheets/src/hooks/use-sheet.ts @@ -2,6 +2,8 @@ import { getCoreRowModel, + getFacetedRowModel, + getFacetedUniqueValues, getFilteredRowModel, getSortedRowModel, useReactTable, @@ -49,8 +51,8 @@ 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) and live column resizing. Any option the app - * passes wins. + * 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, @@ -64,6 +66,9 @@ export function useSheet({ getCoreRowModel: getCoreRowModel(), getSortedRowModel: getSortedRowModel(), getFilteredRowModel: getFilteredRowModel(), + // Counted per column only when asked for: when a values filter opens. + getFacetedRowModel: getFacetedRowModel(), + getFacetedUniqueValues: getFacetedUniqueValues(), enableColumnResizing: true, columnResizeMode: 'onChange', // There is no pagination UI, and resetting the page index on every data diff --git a/packages/sheets/src/ui/labels.tsx b/packages/sheets/src/ui/labels.tsx index 0973919..9378bb5 100644 --- a/packages/sheets/src/ui/labels.tsx +++ b/packages/sheets/src/ui/labels.tsx @@ -14,6 +14,18 @@ export type SheetLabels = { width: (pixels: number) => string; /** Announced on a filtered column's header. */ filtered: string; + /** Names a header's filter button, and the filter it opens. */ + filter: (column: string) => string; + /** Names a text filter's input, and is its placeholder. */ + filterText: (column: string) => string; + /** Stands for an empty value in a filter's checklist. */ + blank: string; + /** Clears one column's filter. */ + clearFilter: string; + /** Shown when the filters leave no rows. */ + noMatches: string; + /** Clears every column's filter. */ + clearFilters: string; /** Cell status, announced to assistive tech. */ unsaved: string; saving: string; @@ -32,6 +44,12 @@ export const defaultSheetLabels: SheetLabels = { resize: (column) => `Resize ${column}`, width: (pixels) => `${pixels} pixels`, filtered: '(filtered)', + filter: (column) => `Filter ${column}`, + filterText: (column) => `${column} contains`, + blank: '(Blank)', + clearFilter: 'Clear', + noMatches: 'No rows match the filters.', + clearFilters: 'Clear filters', unsaved: 'Unsaved', saving: 'Saving', saved: 'Saved', diff --git a/packages/sheets/src/ui/sheet-column-filter.test.tsx b/packages/sheets/src/ui/sheet-column-filter.test.tsx new file mode 100644 index 0000000..4a997aa --- /dev/null +++ b/packages/sheets/src/ui/sheet-column-filter.test.tsx @@ -0,0 +1,128 @@ +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 { Sheet } from './sheet.js'; + +type Task = { id: string; title: string; status: string; owner: string }; +const task = createColumnHelper(); +const 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' }, + { id: '3', title: 'Plan the sprint', status: 'Todo', owner: 'Grace' }, +]; + +function Tasks() { + const sheet = useSheet({ columns, data: tasks, getRowId: (row) => row.id }); + return ; +} + +// jsdom has no Popover API, so these stand in for the browser's side of it: +// it reports opening and closing with a toggle event. +function toggle(element: Element, newState: 'open' | 'closed') { + act(() => { + element.dispatchEvent(Object.assign(new Event('toggle'), { newState })); + }); +} + +beforeAll(() => { + HTMLElement.prototype.hidePopover = function () { + toggle(this, 'closed'); + }; +}); + +/** Clicks a header's filter button, as far as jsdom can: opens its panel. */ +function openFilter(name: string) { + const button = screen.getByRole('button', { name }); + const panel = document.getElementById( + button.getAttribute('popovertarget') ?? '', + ); + if (!panel) throw new Error(`No panel for ${name}`); + toggle(panel, 'open'); + return panel; +} + +const bodyRows = () => screen.getAllByRole('row').slice(1); + +describe('SheetColumnFilter', () => { + it('gives a filter button only to the columns that opt in', () => { + render(); + + expect(screen.getByRole('button', { name: 'Filter Title' })).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Filter Status' })).toBeTruthy(); + expect(screen.queryByRole('button', { name: 'Filter Owner' })).toBeNull(); + }); + + it('filters by the text typed, ignoring case', () => { + render(); + openFilter('Filter Title'); + + const input = screen.getByRole('textbox', { name: 'Title contains' }); + expect(document.activeElement).toBe(input); + fireEvent.change(input, { target: { value: 'DOCS' } }); + + expect(bodyRows()).toHaveLength(2); + expect(screen.getByText('(filtered)')).toBeTruthy(); + }); + + it('closes on Enter, and on Escape without passing it on', () => { + render(); + openFilter('Filter Title'); + fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter' }); + expect(screen.queryByRole('textbox')).toBeNull(); + + openFilter('Filter Title'); + const handled = !fireEvent.keyDown(screen.getByRole('textbox'), { + key: 'Escape', + }); + + expect(handled).toBe(true); + expect(screen.queryByRole('textbox')).toBeNull(); + }); + + it('picks values from a checklist with their counts', () => { + render(); + openFilter('Filter Status'); + + const done = screen.getByRole('checkbox', { name: 'Done 1' }); + expect(document.activeElement).toBe(done); + fireEvent.click(screen.getByRole('checkbox', { name: 'Todo 2' })); + + expect(bodyRows()).toHaveLength(2); + fireEvent.click(done); + expect(bodyRows()).toHaveLength(3); + }); + + it('keeps a picked value listed when other filters hide its rows', () => { + render(); + openFilter('Filter Status'); + fireEvent.click(screen.getByRole('checkbox', { name: 'Todo 2' })); + openFilter('Filter Title'); + fireEvent.change(screen.getByRole('textbox'), { + target: { value: 'build' }, + }); + openFilter('Filter Status'); + + expect( + screen.getByRole('checkbox', { name: 'Todo 0' }).matches(':checked'), + ).toBe(true); + expect(screen.getByRole('checkbox', { name: 'Done 1' })).toBeTruthy(); + }); + + it('clears its column and closes', () => { + render(); + openFilter('Filter Status'); + fireEvent.click(screen.getByRole('checkbox', { name: 'Todo 2' })); + + fireEvent.click(screen.getByRole('button', { name: 'Clear' })); + + expect(bodyRows()).toHaveLength(3); + expect(screen.queryByRole('checkbox')).toBeNull(); + }); +}); diff --git a/packages/sheets/src/ui/sheet-column-filter.tsx b/packages/sheets/src/ui/sheet-column-filter.tsx new file mode 100644 index 0000000..f231a15 --- /dev/null +++ b/packages/sheets/src/ui/sheet-column-filter.tsx @@ -0,0 +1,194 @@ +'use client'; + +import { useId, useRef, useState } from 'react'; +import type { Column } from '@tanstack/react-table'; +import { textFilter, valuesFilter } from '../hooks/filters.js'; +import { cx } from './cx.js'; +import { FunnelIcon } from './icons.js'; +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, +): FilterKind | undefined { + if (!column.getCanFilter()) return undefined; + const { filterFn } = column.columnDef; + if (filterFn === textFilter) return 'text'; + if (filterFn === valuesFilter) return 'values'; + return undefined; +} + +type SheetColumnFilterProps = { + column: Column; + kind: FilterKind; + /** The column's name, as in "Filter Title". */ + label: string; +}; + +/** + * A header's filter: a funnel button, and the panel it opens with the column's + * filter control. The panel is a native popover, so it sits above the sheet's + * scroll container instead of being clipped by it, and the browser closes it + * 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({ + column, + kind, + label, +}: SheetColumnFilterProps) { + const labels = useSheetLabels(); + const id = useId(); + // Anchor names are CSS dashed idents, which can't hold useId's punctuation. + const anchor = `--sheet-filter-${id.replace(/[^\w-]/g, '')}`; + const panel = useRef(null); + // The controls mount only while the panel is open: a values filter counts + // its column's values then, and autoFocus moves focus into the panel. + const [open, setOpen] = useState(false); + const filtered = column.getIsFiltered(); + const name = labels.filter(label); + const close = () => panel.current?.hidePopover(); + + return ( + <> + + + + ); +} + +function TextFilter({ + column, + label, + close, +}: { + column: Column; + label: string; + close: () => void; +}) { + const labels = useSheetLabels(); + const name = labels.filterText(label); + return ( + column.setFilterValue(event.target.value)} + onKeyDown={(event) => { + if (event.key !== 'Enter') return; + // Closing returns focus to the filter button, and the Enter's keypress + // would then press it, opening the panel again. + event.preventDefault(); + close(); + }} + className="w-full rounded border border-sheet-fg/15 bg-sheet-bg px-2 py-1 text-sm text-sheet-fg outline-none placeholder:text-sheet-faint focus:border-sheet-accent dark:border-sheet-fg-dark/15 dark:bg-sheet-bg-dark dark:text-sheet-fg-dark dark:placeholder:text-sheet-faint-dark" + /> + ); +} + +function ValuesFilter({ column }: { column: Column }) { + const labels = useSheetLabels(); + const value = column.getFilterValue(); + const picked = Array.isArray(value) ? value : []; + // Counted with every other column's filter applied, but not this one's. + const counts = new Map(column.getFacetedUniqueValues()); + // A picked value that the other filters have hidden stays listed, or this + // filter could hide itself. + for (const item of picked) if (!counts.has(item)) counts.set(item, 0); + const options = [...counts] + .map(([item, count]) => ({ + item, + count, + text: item == null || item === '' ? labels.blank : String(item), + })) + .sort((a, b) => a.text.localeCompare(b.text, undefined, { numeric: true })); + + return ( +
    + {options.map(({ item, count, text }, index) => ( +
  • + +
  • + ))} +
+ ); +} diff --git a/packages/sheets/src/ui/sheet-column.tsx b/packages/sheets/src/ui/sheet-column.tsx index 29975a9..c9b21ee 100644 --- a/packages/sheets/src/ui/sheet-column.tsx +++ b/packages/sheets/src/ui/sheet-column.tsx @@ -9,6 +9,7 @@ import { import { cx } from './cx.js'; import { flexRender, type Header } from '@tanstack/react-table'; 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; @@ -48,6 +49,7 @@ export function SheetColumn({ const sort = column.getIsSorted(); const canSort = column.getCanSort(); + const filterKind = columnFilterKind(column); const size = header.getSize(); const minSize = column.columnDef.minSize ?? 0; @@ -84,20 +86,32 @@ export function SheetColumn({ {sort === 'desc' && } {column.getIsFiltered() && ( <> - + {/* A column with a filter control shows this on its button. */} + {!filterKind && } {labels.filtered} )} - {canSort && ( - + {(canSort || filterKind) && ( +
+ {canSort && ( + + )} + {filterKind && ( + + )} +
)} {isLeaf && column.getCanResize() && (
{ }); // Tests in apps can find the highlighted row without asserting on a class. + it('says when the filters hide every row, and clears them', () => { + function Filtered() { + const sheet = useSheet({ + columns: [ + rowColumn.accessor('name', { header: 'Name', filterFn: textFilter }), + ], + data: [{ id: 1, name: 'Alpha' }], + getRowId: (row) => String(row.id), + initialState: { columnFilters: [{ id: 'name', value: 'zzz' }] }, + }); + return ; + } + render(); + + expect(screen.queryByText('No rows yet.')).toBeNull(); + expect(screen.getByText(/No rows match the filters\./)).toBeTruthy(); + fireEvent.click(screen.getByRole('button', { name: 'Clear filters' })); + + expect(screen.getByText('Alpha')).toBeTruthy(); + }); + it('marks the highlighted row with data-highlighted', () => { function Highlighted() { const sheet = useSheet({ diff --git a/packages/sheets/src/ui/sheet.tsx b/packages/sheets/src/ui/sheet.tsx index 012b2d5..63382b6 100644 --- a/packages/sheets/src/ui/sheet.tsx +++ b/packages/sheets/src/ui/sheet.tsx @@ -195,7 +195,24 @@ export function Sheet({ /> )) ) : rows.length === 0 ? ( - {emptyState} + + {/* `emptyState` means there's no data. Here there is, but the + filters hide all of it. */} + {table.getState().columnFilters.length > 0 ? ( + <> + {text.noMatches}{' '} + + + ) : ( + emptyState + )} + ) : ( Date: Thu, 12 Nov 2026 15:53:07 +0530 Subject: [PATCH 2/5] feat(playground): filter the 1,000-row demo --- apps/playground-e2e/src/playground.spec.ts | 146 +++++++++++++++++++ apps/playground/src/app/app.tsx | 2 +- apps/playground/src/app/demos/large-demo.tsx | 14 +- 3 files changed, 156 insertions(+), 6 deletions(-) diff --git a/apps/playground-e2e/src/playground.spec.ts b/apps/playground-e2e/src/playground.spec.ts index 9d99a91..8347943 100644 --- a/apps/playground-e2e/src/playground.spec.ts +++ b/apps/playground-e2e/src/playground.spec.ts @@ -306,6 +306,152 @@ test('sorts 1,000 rows in the browser', async ({ page }) => { ).toHaveText('Accessibility pass'); }); +test.describe('filtering', () => { + const region = '1,000 rows'; + // Two header rows (the groups, then the columns), then the data rows. + const rows = (page: Page) => demo(page, region).getByRole('row'); + const filterButton = (page: Page, column: string) => + demo(page, region).getByRole('button', { name: `Filter ${column}` }); + const panel = (page: Page, column: string) => + page.getByRole('dialog', { name: `Filter ${column}` }); + + test('filters by text, ignoring case, then clears', async ({ page }) => { + await filterButton(page, 'Title').click(); + const input = page.getByRole('textbox', { name: 'Title contains' }); + await expect(input).toBeFocused(); + + // "Review the README" and its 99 numbered copies. + await input.fill('readme'); + await expect(rows(page)).toHaveCount(102); + + await page.getByRole('button', { name: 'Clear', exact: true }).click(); + await expect(rows(page)).toHaveCount(1002); + await expect(filterButton(page, 'Title')).toBeFocused(); + }); + + test('picks statuses, with their counts', async ({ page }) => { + await filterButton(page, 'Status').click(); + const statuses = panel(page, 'Status'); + + await statuses.getByRole('checkbox', { name: 'Blocked 250' }).check(); + await expect(rows(page)).toHaveCount(252); + await statuses.getByRole('checkbox', { name: 'Done 250' }).check(); + await expect(rows(page)).toHaveCount(502); + + // Unpicking everything removes the filter instead of hiding every row. + await statuses.getByRole('checkbox', { name: 'Blocked' }).uncheck(); + await statuses.getByRole('checkbox', { name: 'Done' }).uncheck(); + await expect(rows(page)).toHaveCount(1002); + }); + + test('combines filters, and keeps them while sorting', async ({ page }) => { + await filterButton(page, 'Status').click(); + await panel(page, 'Status').getByRole('checkbox', { name: 'Todo' }).check(); + await page.keyboard.press('Escape'); + + // Counted within the Status filter: Ada has 50 of the 250 Todo tasks. + await filterButton(page, 'Owner').click(); + await panel(page, 'Owner') + .getByRole('checkbox', { name: 'Ada 50' }) + .check(); + await page.keyboard.press('Escape'); + await expect(rows(page)).toHaveCount(52); + + await demo(page, region) + .getByRole('button', { name: 'Sort Title' }) + .click(); + await expect(rows(page)).toHaveCount(52); + await expect(rows(page).nth(2).getByRole('cell').first()).toHaveText( + 'Draft the launch post', + ); + }); + + test('works from the keyboard', async ({ page }) => { + const button = filterButton(page, 'Status'); + await button.focus(); + await page.keyboard.press('Enter'); + await expect(page.getByRole('checkbox', { name: 'Blocked' })).toBeFocused(); + + await page.keyboard.press('Space'); + await expect(rows(page)).toHaveCount(252); + + await page.keyboard.press('Escape'); + await expect(panel(page, 'Status')).toBeHidden(); + await expect(button).toBeFocused(); + }); + + test('says when nothing matches, and clears every filter', async ({ + page, + }) => { + await filterButton(page, 'Title').click(); + await page + .getByRole('textbox', { name: 'Title contains' }) + .fill('no such task'); + // Enter closes the filter, and focus goes back to its button. + await page.keyboard.press('Enter'); + await expect(panel(page, 'Title')).toBeHidden(); + await expect(filterButton(page, 'Title')).toBeFocused(); + + const sheet = demo(page, region); + await expect(sheet.getByText('No rows match the filters.')).toBeVisible(); + await sheet.getByRole('button', { name: 'Clear filters' }).click(); + await expect(rows(page)).toHaveCount(1002); + }); + + test('Escape closes a filter and stays full screen', async ({ page }) => { + await page.goto('/?full=large'); + await filterButton(page, 'Owner').click(); + await expect(page.getByRole('checkbox', { name: 'Ada' })).toBeFocused(); + + await page.keyboard.press('Escape'); + + await expect(panel(page, 'Owner')).toBeHidden(); + await expect( + demo(page, region).getByRole('button', { name: 'Exit full screen' }), + ).toBeVisible(); + }); + + test('opens under its button, mirrored right to left', async ({ page }) => { + const button = filterButton(page, 'Status'); + const edges = async () => { + await button.click(); + const [b, p] = await Promise.all([ + button.boundingBox(), + panel(page, 'Status').boundingBox(), + ]); + await page.keyboard.press('Escape'); + if (!b || !p) throw new Error('Nothing to measure'); + expect(p.y).toBeGreaterThan(b.y); + return { button: b, panel: p }; + }; + + // Lined up with the button's trailing edge: the right, then the left. + const ltr = await edges(); + expect( + Math.abs( + ltr.panel.x + ltr.panel.width - (ltr.button.x + ltr.button.width), + ), + ).toBeLessThanOrEqual(1); + await page.getByRole('button', { name: 'Right to left' }).click(); + const rtl = await edges(); + expect(Math.abs(rtl.panel.x - rtl.button.x)).toBeLessThanOrEqual(1); + }); + + test('accessibility scan with a filter open', async ({ page }) => { + await filterButton(page, 'Status').click(); + await expect(panel(page, 'Status')).toBeVisible(); + + // The header row holds the filter buttons and the open panel. + const { violations } = await new AxeBuilder({ page }) + .include( + 'section[aria-labelledby="large"] [role="table"] > [role="rowgroup"]:first-child', + ) + .analyze(); + + expect(violations.map((v) => v.id)).toEqual([]); + }); +}); + test('mirrors for right-to-left layouts', async ({ page }) => { await page.getByRole('button', { name: 'Right to left' }).click(); const region = demo(page, 'Sorting and row actions'); diff --git a/apps/playground/src/app/app.tsx b/apps/playground/src/app/app.tsx index 87127c1..7c8e99a 100644 --- a/apps/playground/src/app/app.tsx +++ b/apps/playground/src/app/app.tsx @@ -249,7 +249,7 @@ function App() { diff --git a/apps/playground/src/app/demos/large-demo.tsx b/apps/playground/src/app/demos/large-demo.tsx index 857f8bc..0be5ff5 100644 --- a/apps/playground/src/app/demos/large-demo.tsx +++ b/apps/playground/src/app/demos/large-demo.tsx @@ -1,6 +1,6 @@ import { useContext } from 'react'; import { createColumnHelper } from '@tanstack/react-table'; -import { useSheet } from '@codemancers/sheets'; +import { textFilter, useSheet, valuesFilter } from '@codemancers/sheets'; import { Sheet } from '@codemancers/sheets/ui'; import { RtlContext } from '../direction'; import { makeTasks, type Task } from '../data'; @@ -14,15 +14,19 @@ const columns = [ id: 'task', header: 'Task', columns: [ - task.accessor('title', { header: 'Title', size: 300 }), - task.accessor('status', { header: 'Status' }), + task.accessor('title', { + header: 'Title', + size: 300, + filterFn: textFilter, + }), + task.accessor('status', { header: 'Status', filterFn: valuesFilter }), ], }), task.group({ id: 'assignment', header: 'Assignment', columns: [ - task.accessor('owner', { header: 'Owner' }), + task.accessor('owner', { header: 'Owner', filterFn: valuesFilter }), task.accessor('due', { header: () => Due, size: 120, @@ -31,7 +35,7 @@ const columns = [ }), ]; -/** Sorted in the browser, the default. No virtualization yet. */ +/** Sorted and filtered in the browser, the default. No virtualization yet. */ export function LargeDemo() { const rtl = useContext(RtlContext); const sheet = useSheet({ From 15a4c41796d2a2cb3781123f3eaf7227c073086f Mon Sep 17 00:00:00 2001 From: SyedSibtainRazvi Date: Thu, 12 Nov 2026 15:53:07 +0530 Subject: [PATCH 3/5] docs: document column filters --- docs/architecture.md | 5 ++-- docs/decisions.md | 4 +++ packages/sheets/README.md | 51 +++++++++++++++++++++++++++------------ 3 files changed, 43 insertions(+), 17 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 86d2b77..932e2b1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -56,10 +56,10 @@ Statuses, staged values and the open and highlighted rows are all keyed by TanSt flowchart TD Sheet["Sheet (role=table)
sets --sheet-columns and provides the labels"] Sheet --> Header["SheetHeader
a row per header group"] - Header --> Column["SheetColumn per header
flexRender, sort button, resize handle"] + Header --> Column["SheetColumn per header
flexRender, sort button, filter, resize handle"] Sheet --> Body["Body rowgroup"] Body -->|isLoading| Loading["loadingState, or SheetLoading"] - Body -->|no rows| Empty["SheetEmpty"] + Body -->|no rows| Empty["SheetEmpty
or, when filters hide every row, a way to clear them"] Body -->|rows| Rows["SheetBody, memoised"] Rows --> Row["SheetRow per row"] Row --> Cell["SheetCell per visible cell
provides the cell context and draws the status"] @@ -72,6 +72,7 @@ flowchart TD - **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. - **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. - **Text.** `Sheet` merges its `labels` prop over `defaultSheetLabels` and provides them through context, keeping the merged object while the values are the same. Components read them with `useSheetLabels()`. - **Roles.** The markup is `div`s with ARIA table roles: `table`, `rowgroup`, `row`, `columnheader`, `rowheader` for row numbers, and `cell`. The loading skeleton is hidden from assistive technology, and the body is marked `aria-busy` instead. The open row is `aria-current`, and the highlighted row has `data-highlighted`. diff --git a/docs/decisions.md b/docs/decisions.md index 163ae94..a6a7c9e 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -21,8 +21,10 @@ When you make a choice that a future contributor would question, add it here. - **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. +- **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. @@ -58,6 +60,8 @@ When you make a choice that a future contributor would question, add it here. - **Labels are compared by value.** Apps pass `labels` inline, a new object on every render. `Sheet` keeps the merged labels while their values are the same, because a new context value would re-render every row's number cell on each frame of a drag. - **The body doesn't re-render while a column is dragged.** This is TanStack's advice for live resizing. It needs `useCellStatus` and `useRowChanges` to return memoised objects, so they do. - **New rows stay put through TanStack's row pinning,** not a new-row API. The body renders pinned top and bottom rows around the rest, and an app pins its new row to the bottom, so a sort can't move it. That keeps the plain TanStack API, and works for any row an app wants fixed. +- **The filter panel is a native popover, placed with CSS anchor positioning.** The top layer keeps it from being clipped by the sheet's scroll container, and the browser closes it on a click outside and returns focus to its button, so there's no portal and no positioning code. Anchor positioning has been in every major browser since January 2026. +- **Filter controls mount only while the panel is open.** A checklist counts its column's values when it mounts, so a sheet with many filterable columns doesn't count them all on every render. Mounting on open also lets `autoFocus` move focus into the panel, which content that's always mounted couldn't do. - **No virtualization yet.** Every row is rendered. The playground's 1,000-row demo shows how that performs. Virtualization is planned for a later release. - **No empty gridlines below the last row.** When the rows don't fill the sheet, the space below them stays blank, since empty cells would look like rows that exist. diff --git a/packages/sheets/README.md b/packages/sheets/README.md index 6791226..abc9286 100644 --- a/packages/sheets/README.md +++ b/packages/sheets/README.md @@ -144,9 +144,22 @@ const columns = [ ## Sorting and filtering -Sorting and filtering run in the browser by default. Any column with an accessor is sortable through its header button; turn that off with `enableSorting: false` on the column or on the table. To filter, use TanStack's column and global filter APIs (`column.setFilterValue`, `table.setGlobalFilter`) from your own controls. +Sorting and filtering run in the browser by default. Any column with an accessor is sortable through its header button; turn that off with `enableSorting: false` on the column or on the table. -**Sort by what the cell shows.** A column sorts by its accessor's value, which isn't always what its cell displays: +**Filters.** Give a column one of the sheet's filter functions, and its header gets a filter button: + +```tsx +import { textFilter, valuesFilter } from '@codemancers/sheets'; + +const 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. +- `valuesFilter` lists the column's values, each with its number of rows, and keeps the rows whose value is checked. The counts take the other columns' filters into account. + +Columns without one of these have no filter button. When the filters leave no rows, the sheet says so, with a button that clears them. The state is TanStack's `columnFilters`: control it with `state.columnFilters` and `onColumnFiltersChange` to keep the filters in the URL, for example. For a search across every column, or controls of your own, use TanStack's APIs directly (`table.setGlobalFilter`, `column.setFilterValue`). + +**Sort by what the cell shows.** A column sorts and filters by its accessor's value, which isn't always what its cell displays: - If the value is an object, such as an assignee or a count object, TanStack can't order it. Set `enableSorting: false` on that column. - If the cell shows something derived, such as a project's name for a `projectId`, sort by that instead with an accessor function: @@ -157,7 +170,7 @@ Sorting and filtering run in the browser by default. Any column with an accessor - For an order that isn't alphabetical, such as statuses in workflow order, give the column a `sortingFn`. -**Server-side data.** Set TanStack's manual flags and control the state. The sheet then reports the sort, and your data layer applies it: +**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 only the values in the rows you've loaded. ```tsx const [sorting, setSorting] = useState([]); @@ -516,17 +529,22 @@ To follow your design system's CSS variables, such as shadcn's, use `@theme inli `` replaces any of the text the sheet renders itself: -| Label | Default | Used for | -| ---------------------------- | ---------------------------------------- | -------------------------------------------- | -| `rowNumber` | `Row` | The name of the row-number column | -| `sort(column)` | `Sort {column}` | Header sort buttons | -| `resize(column)` | `Resize {column}` | Resize handles | -| `width(pixels)` | `{pixels} pixels` | A resize handle's current width, read out | -| `filtered` | `(filtered)` | Announced on a filtered column | -| `unsaved`, `saving`, `saved` | `Unsaved`, `Saving`, `Saved` | Cell statuses, announced | -| `saveFailed` | `Could not save. Check your connection.` | A cell's error when its `onCommit` throws | -| `empty` | `No data.` | The empty state, when `emptyState` isn't set | -| `addRow` | `Add row` | The add-row button | +| Label | Default | Used for | +| ---------------------------- | --------------------------------------------- | -------------------------------------------- | +| `rowNumber` | `Row` | The name of the row-number column | +| `sort(column)` | `Sort {column}` | Header sort buttons | +| `resize(column)` | `Resize {column}` | Resize handles | +| `width(pixels)` | `{pixels} pixels` | A resize handle's current width, read out | +| `filtered` | `(filtered)` | Announced on a filtered column | +| `filter(column)` | `Filter {column}` | Header filter buttons, and their filters | +| `filterText(column)` | `{column} contains` | A text filter's input | +| `blank` | `(Blank)` | An empty value in a filter's checklist | +| `clearFilter` | `Clear` | Clears one column's filter | +| `noMatches`, `clearFilters` | `No rows match the filters.`, `Clear filters` | The state when the filters leave no rows | +| `unsaved`, `saving`, `saved` | `Unsaved`, `Saving`, `Saved` | Cell statuses, announced | +| `saveFailed` | `Could not save. Check your connection.` | A cell's error when its `onCommit` throws | +| `empty` | `No data.` | The empty state, when `emptyState` isn't set | +| `addRow` | `Add row` | The add-row button | Cells and hooks take their own text props: `openLabel` and `detailLabel` on `SheetPrimaryCell`, `placeholder` on editable cells, and `transportErrorMessage` on `useRowChanges`. @@ -578,7 +596,8 @@ const { table } = useSheet({ columns, data, getRowId: (task) => task.id }); - **Table semantics:** the sheet is a table to assistive tech. Headers carry `aria-sort`, and the row-number column is named. Loading rows are marked busy, and the placeholder rows are hidden. - **Keyboard:** - - Tab reaches the sort buttons, resize handles, cells and row actions. Row actions appear on focus as well as hover. + - Tab reaches the sort and filter buttons, resize handles, cells and row actions. Row actions appear on focus as well as hover. + - A filter button opens its filter with focus inside it. Escape, or Enter in a text filter, closes it and returns focus to the button. - Enter or Space opens an editable cell. Enter saves, Escape cancels, and both return focus to the cell. Tab saves and moves on to the next cell. - On a focused resize handle, the arrow keys resize the column (Shift for bigger steps), and a double-click resets it. - **Screen readers:** editors are named after their column. Saving statuses are announced, and refused values are announced as alerts. @@ -597,6 +616,7 @@ Not yet supported: moving between cells with the arrow keys (`role="grid"`). - **No virtualisation yet.** Every row is rendered. Hundreds to a few thousand rows are fine; beyond that, render your own body with `@tanstack/react-virtual` through the headless API. - **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.** - **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. @@ -612,6 +632,7 @@ Not yet supported: moving between cells with the arrow keys (`role="grid"`). | `useInlineEdit(options)` | Edit-in-place state for a text editor: `isEditing`, `beginEdit`, `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`. | From 882284ef1deaa6d187d56d33ab44acf94bdd321f Mon Sep 17 00:00:00 2001 From: SyedSibtainRazvi Date: Thu, 12 Nov 2026 16:18:57 +0530 Subject: [PATCH 4/5] docs: show how a filter's checklist can list values from the server --- packages/sheets/README.md | 2 +- .../src/ui/sheet-column-filter.test.tsx | 22 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/packages/sheets/README.md b/packages/sheets/README.md index abc9286..c48a1e3 100644 --- a/packages/sheets/README.md +++ b/packages/sheets/README.md @@ -170,7 +170,7 @@ Columns without one of these have no filter button. When the filters leave no ro - For an order that isn't alphabetical, such as statuses in workflow order, give the column a `sortingFn`. -**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 only the values in the rows you've loaded. +**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. ```tsx const [sorting, setSorting] = useState([]); diff --git a/packages/sheets/src/ui/sheet-column-filter.test.tsx b/packages/sheets/src/ui/sheet-column-filter.test.tsx index 4a997aa..1486cda 100644 --- a/packages/sheets/src/ui/sheet-column-filter.test.tsx +++ b/packages/sheets/src/ui/sheet-column-filter.test.tsx @@ -115,6 +115,28 @@ 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'); From 1d74e95432b2ed67e0a8da8f82b11b9345bbf568 Mon Sep 17 00:00:00 2001 From: SyedSibtainRazvi Date: Thu, 12 Nov 2026 16:42:23 +0530 Subject: [PATCH 5/5] docs: note the filter's use of the raised and accent colours --- packages/sheets/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/sheets/README.md b/packages/sheets/README.md index c48a1e3..2558f4a 100644 --- a/packages/sheets/README.md +++ b/packages/sheets/README.md @@ -517,11 +517,11 @@ To follow your design system's CSS variables, such as shadcn's, use `@theme inli | --------------------------------------------------------------------- | --------------------------------------------------------------------- | | `sheet-bg`, `sheet-fg` | Background and text. Borders and hover tints are `fg` at low opacity. | | `sheet-muted`, `sheet-faint` | Secondary text, and placeholders | -| `sheet-raised` | The add-row footer on hover | +| `sheet-raised` | The add-row footer on hover, and the filter panel | | `sheet-skeleton` | Loading placeholders | | `sheet-tooltip`, `sheet-tooltip-fg` | The error tooltip | | `sheet-link`, `sheet-link-hover` | Links | -| `sheet-accent` | The column resize handle while it's dragged or focused | +| `sheet-accent` | The resize handle while it's dragged or focused, and an active filter | | `sheet-error`, `sheet-success`, `sheet-warning` | The refused, saved and unsaved status icons | | `sheet-highlight` | The highlighted row |