Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 146 additions & 0 deletions apps/playground-e2e/src/playground.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
2 changes: 1 addition & 1 deletion apps/playground/src/app/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ function App() {
<Demo
id="large"
title="1,000 rows"
description="Sorted in the browser, the default. Grouped headers, and a header that renders markup. No virtualization yet, so every row is rendered."
description="Sorted and filtered in the browser, the default: filter Title by its text, and Status and Owner by their values. Grouped headers, and a header that renders markup. No virtualization yet, so every row is rendered."
>
<LargeDemo />
</Demo>
Expand Down
14 changes: 9 additions & 5 deletions apps/playground/src/app/demos/large-demo.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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: () => <abbr title="Due date">Due</abbr>,
size: 120,
Expand All @@ -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({
Expand Down
5 changes: 3 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ Statuses, staged values and the open and highlighted rows are all keyed by TanSt
flowchart TD
Sheet["Sheet (role=table)<br/>sets --sheet-columns and provides the labels"]
Sheet --> Header["SheetHeader<br/>a row per header group"]
Header --> Column["SheetColumn per header<br/>flexRender, sort button, resize handle"]
Header --> Column["SheetColumn per header<br/>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<br/>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<br/>provides the cell context and draws the status"]
Expand All @@ -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`.

Expand Down
4 changes: 4 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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.

Expand Down
Loading
Loading