An open source design system that's fully customizable and agent ready
TypeScript
docs(TableSelectionToolbar): a recipe for selecting every matching row across server pages (#10271)
Cindy Zhanga0a09f9c2f3a
diff --git a/.changeset/table-select-all-matching-recipe.md b/.changeset/table-select-all-matching-recipe.mdnew file mode 100644index 0000000000..916f0d8482--- /dev/null+++ b/.changeset/table-select-all-matching-recipe.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[docs] `TableSelectionToolbar` documents how to select every row that matches a query across server pages with today's API: the app keeps "every matching row minus exclusions" and passes the toolbar its own count and label. In this mode the toolbar's `selectedKeys` holds only the loaded rows.++@cixzhangdiff --git a/apps/storybook/stories/TableSelection.stories.tsx b/apps/storybook/stories/TableSelection.stories.tsxindex 12f0788266..1f5b9a38f9 100644--- a/apps/storybook/stories/TableSelection.stories.tsx+++ b/apps/storybook/stories/TableSelection.stories.tsx@@ -5,6 +5,7 @@ import type {Meta, StoryObj} from '@storybook/react';import {expect, userEvent, waitFor, within} from 'storybook/test';import * as stylex from '@stylexjs/stylex';import {Button} from '@astryxdesign/core/Button';+import {Pagination} from '@astryxdesign/core/Pagination';import {ScrollableArea} from '@astryxdesign/core/ScrollableArea';import {Table,@@ -548,3 +549,237 @@ export const BulkActionsFloating: Story = {scrollRegion.scrollTop = 0;},};++// =============================================================================+// Recipe: select every matching row across server pages+// =============================================================================++const MATCHING_TOTAL = 248;+const MATCHING_PAGE_SIZE = 5;+const MATCHING_ROLES = ['Engineer', 'Designer', 'Manager', 'Admin'];++/** Stands in for a server that returns one page of the matching rows. */+function fetchMatchingPage(page: number): User[] {+ const start = (page - 1) * MATCHING_PAGE_SIZE;+ const count = Math.min(MATCHING_PAGE_SIZE, MATCHING_TOTAL - start);+ return Array.from({length: count}, (_, index) => {+ const number = start + index + 1;+ return {+ id: `record-${number}`,+ name: `Record ${number}`,+ email: `record${number}@example.com`,+ role: MATCHING_ROLES[number % MATCHING_ROLES.length],+ isLocked: false,+ };+ });+}++/**+ * The app's own selection model. `picked` holds the rows chosen one by one;+ * when `isAllMatching` is true, every matching row is selected except+ * `excluded`, including rows on pages that were never loaded.+ */+interface MatchingSelection {+ isAllMatching: boolean;+ picked: ReadonlySet<string>;+ excluded: ReadonlySet<string>;+}++const NO_SELECTION: MatchingSelection = {+ isAllMatching: false,+ picked: new Set(),+ excluded: new Set(),+};++function SelectAllMatchingExample() {+ const [page, setPage] = useState(1);+ const [selection, setSelection] = useState<MatchingSelection>(NO_SELECTION);+ const rows = fetchMatchingPage(page);++ const isSelected = (row: User) =>+ selection.isAllMatching+ ? !selection.excluded.has(row.id)+ : selection.picked.has(row.id);+ const isPageSelected = rows.every(isSelected);+ const selectedCount = selection.isAllMatching+ ? MATCHING_TOTAL - selection.excluded.size+ : selection.picked.size;++ const setRows = (pageRows: User[], selected: boolean) => {+ setSelection(current => {+ const ids = pageRows.map(row => row.id);+ if (current.isAllMatching) {+ const excluded = new Set(current.excluded);+ for (const id of ids) {+ if (selected) {+ excluded.delete(id);+ } else {+ excluded.add(id);+ }+ }+ return {...current, excluded};+ }+ const picked = new Set(current.picked);+ for (const id of ids) {+ if (selected) {+ picked.add(id);+ } else {+ picked.delete(id);+ }+ }+ return {...current, picked};+ });+ };++ const selectionPlugin = useTableSelection<User>({+ getIsItemSelected: isSelected,+ onSelectItem: ({item, isSelected: selected}) => setRows([item], selected),+ onSelectAll: ({isAllSelected}) => setRows(rows, isAllSelected),+ getIsAllSelected: () => isPageSelected,+ getIsIndeterminate: () => !isPageSelected && rows.some(isSelected),+ getRowLabel: row => row.name,+ });++ // The toolbar only shows the app's model. `selectedKeys` can hold only the+ // loaded rows; the count comes from the app.+ const toolbarSelection: TableSelectionState = {+ selectedKeys: new Set(rows.filter(isSelected).map(row => row.id)),+ selectedCount,+ hasSelection: selectedCount > 0,+ clearSelection: () => setSelection(NO_SELECTION),+ };++ const renderSelectionLabel = (count: number) => {+ if (!selection.isAllMatching) {+ return `${count} selected`;+ }+ return selection.excluded.size === 0+ ? `All ${MATCHING_TOTAL} matching selected`+ : `${count} of ${MATCHING_TOTAL} matching selected`;+ };++ return (+ <div {...stylex.props(bulkActionsStyles.page)}>+ <TableSelectionToolbar+ selection={toolbarSelection}+ renderSelectionLabel={renderSelectionLabel}+ startContent={+ <>+ <Button label="Archive" variant="ghost" onClick={() => {}} />+ {/* Beside the action, not in its place. Once used, the offer+ stays as the command that undoes it, so focus stays on it+ and a second press can never run Archive. */}+ {selection.isAllMatching || isPageSelected ? (+ <Button+ label={+ selection.isAllMatching+ ? 'Select only this page'+ : `Select all ${MATCHING_TOTAL} matching`+ }+ variant="ghost"+ onClick={() =>+ setSelection(+ selection.isAllMatching+ ? {+ isAllMatching: false,+ // Every row on this page, so the label stays true+ // and the focused button stays mounted.+ picked: new Set(rows.map(row => row.id)),+ excluded: new Set(),+ }+ : {+ isAllMatching: true,+ picked: new Set(),+ excluded: new Set(),+ },+ )+ }+ />+ ) : null}+ </>+ }+ />+ <Table+ data={rows}+ columns={columns}+ idKey="id"+ hasHover+ plugins={{selection: selectionPlugin}}+ />+ <Pagination+ page={page}+ onChange={setPage}+ totalItems={MATCHING_TOTAL}+ pageSize={MATCHING_PAGE_SIZE}+ />+ </div>+ );+}++/**+ * Recipe: select every row that matches a query across server pages, then+ * untick a few, with today's API. The app keeps "all matching minus+ * exclusions" and passes its own count and label to the toolbar. In this mode+ * the toolbar's `selectedKeys` holds only the loaded rows.+ */+export const SelectAllMatching: Story = {+ render: () => <SelectAllMatchingExample />,+ play: async ({canvasElement}) => {+ const canvas = within(canvasElement);+ await userEvent.click(canvas.getByLabelText('Select all rows'));+ await expect(canvas.getByText('5 selected')).toBeInTheDocument();++ await userEvent.click(+ canvas.getByRole('button', {name: 'Select all 248 matching'}),+ );+ await expect(+ canvas.getByText('All 248 matching selected'),+ ).toBeInTheDocument();+ // The used offer stays as the command that undoes it and keeps focus,+ // so a second Enter returns to this page and never reaches Archive.+ const undo = canvas.getByRole('button', {name: 'Select only this page'});+ await expect(undo).toHaveFocus();+ await userEvent.keyboard('{Enter}');+ await expect(canvas.getByText('5 selected')).toBeInTheDocument();+ await expect(+ canvas.getByRole('button', {name: 'Select all 248 matching'}),+ ).toHaveFocus();+ await userEvent.keyboard('{Enter}');+ await expect(+ canvas.getByText('All 248 matching selected'),+ ).toBeInTheDocument();++ // With a row unticked, "Select only this page" selects the whole page+ // and keeps focus on the button.+ await userEvent.click(canvas.getByLabelText('Select Record 2'));+ await expect(+ canvas.getByText('247 of 248 matching selected'),+ ).toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole('button', {name: 'Select only this page'}),+ );+ await expect(canvas.getByText('5 selected')).toBeInTheDocument();+ await expect(+ canvas.getByRole('button', {name: 'Select all 248 matching'}),+ ).toHaveFocus();+ await userEvent.keyboard('{Enter}');++ await userEvent.click(canvas.getByLabelText('Select Record 2'));+ await expect(+ canvas.getByText('247 of 248 matching selected'),+ ).toBeInTheDocument();++ // Rows on a page never loaded before are already selected.+ await userEvent.click(+ canvas.getByRole('button', {name: 'Go to next page'}),+ );+ await waitFor(() =>+ expect(canvas.getByLabelText('Select Record 6')).toBeChecked(),+ );++ await userEvent.click(canvas.getByRole('button', {name: 'Unselect All'}));+ await expect(+ canvas.queryByRole('toolbar', {name: 'Bulk actions'}),+ ).not.toBeInTheDocument();+ },+};diff --git a/docs/specs/components/Table/TableSelectionToolbar.spec.md b/docs/specs/components/Table/TableSelectionToolbar.spec.mdindex d1d2902c34..5b7368646f 100644--- a/docs/specs/components/Table/TableSelectionToolbar.spec.md+++ b/docs/specs/components/Table/TableSelectionToolbar.spec.md@@ -13,6 +13,7 @@ review_triggers: [public-api, behavior, layout, theming, accessibility]verified_by:[packages/core/src/Table/TableSelectionToolbar.test.tsx,+ apps/storybook/stories/TableSelection.stories.tsx,scripts/check-knowledge.mjs,apps/storybook/rtl-audit/targets.json,]@@ -84,6 +85,8 @@ Consumer migration instructions belong in consumer docs and release notes.- Toolbar layout, size, and variant — owned by `component:Toolbar`.- The selection state — owned by useTableSelectionState.- Bulk actions in `startContent` — owned by the caller.+- A selection of every row matching a query across server pages — owned by+ the app, which passes its own count and label (DEC-1).## Public concepts@@ -154,7 +157,21 @@ so no anatomy-theming block is declared here.## Decision log-None recorded. The record describes shipped behavior.+### DEC-1 — A selection of every matching row stays with the app++**Reference:** `component:TableSelectionToolbar/DEC-1`+**Decider:** `cixzhang`, `2026-11-06`++When a person selects every row that matches a query across server pages,+the app keeps that selection ("every matching row minus exclusions") and+passes the toolbar its own `selectedCount` and `renderSelectionLabel`. In this+mode `selectedKeys` holds only the loaded rows, because the full set is not on+the client. A Core model for such a selection is decided together with+Table's server-pagination contract, since both need a total that is not+loaded.++Rejected: an all-matching mode in `useTableSelectionState` before the+server-pagination contract exists.## Open questionsdiff --git a/packages/core/src/Table/TableSelectionToolbar.doc.mjs b/packages/core/src/Table/TableSelectionToolbar.doc.mjsindex 99c85b9f13..872ff1e224 100644--- a/packages/core/src/Table/TableSelectionToolbar.doc.mjs+++ b/packages/core/src/Table/TableSelectionToolbar.doc.mjs@@ -6,13 +6,13 @@ export const docs = {subComponentOf: 'Table',displayName: 'Table Selection Toolbar',description:- 'Selection-aware bulk-action surface built on Toolbar. Pass selectionState from useTableSelectionState so count, visibility, and complete clearing stay synchronized with the Table selection plugin. The component owns no table or sticky layout: place it in flow or apply caller-owned positioning through xstyle.',+ 'Selection-aware bulk-action surface built on Toolbar. Pass selectionState from useTableSelectionState so count, visibility, and complete clearing stay synchronized with the Table selection plugin. When the app keeps its own selection, such as every row matching a query across server pages, it passes its own TableSelectionState instead (see the example). The component owns no table or sticky layout: place it in flow or apply caller-owned positioning through xstyle.',props: [{name: 'selection',type: 'TableSelectionState',description:- 'Shared selection state returned by useTableSelectionState: selectedKeys, selectedCount, hasSelection, and clearSelection.',+ 'Shared selection state: selectedKeys, selectedCount, hasSelection, and clearSelection. Usually useTableSelectionState returns it; an app that keeps its own selection builds it.',required: true,},{@@ -63,12 +63,12 @@ export const docs = {],usage: {description:- 'Pass both outputs of useTableSelectionState to their matching consumers: selectionConfig to useTableSelection and selectionState to TableSelectionToolbar. Render product actions through startContent. Keep fixed or floating placement in the surrounding layout.',+ 'Pass both outputs of useTableSelectionState to their matching consumers: selectionConfig to useTableSelection and selectionState to TableSelectionToolbar. An app that keeps its own selection, such as every row matching a query across server pages, passes its own config and state instead. Render product actions through startContent. Keep fixed or floating placement in the surrounding layout.',bestPractices: [{guidance: true,description:- 'Pass selectionState directly from useTableSelectionState so the count and clear action stay synchronized with row selection.',+ 'Pass selectionState directly from useTableSelectionState so the count and clear action stay synchronized with row selection, unless the app keeps its own selection across server pages.',},{guidance: true,@@ -82,16 +82,93 @@ export const docs = {},],},+ examples: [+ {+ label: 'Select every matching row across server pages',+ code: `+// The rows load one server page at a time. The app keeps the selection as+// "every matching row, minus the ones the person unticked", so rows on pages+// that never loaded are selected too. Table and the toolbar only show it.+const [isAllMatching, setIsAllMatching] = useState(false);+const [picked, setPicked] = useState(new Set()); // chosen one by one+const [excluded, setExcluded] = useState(new Set()); // unticked in all mode++const isSelected = row =>+ isAllMatching ? !excluded.has(row.id) : picked.has(row.id);+const isPageSelected = pageRows.every(isSelected);+const selectedCount = isAllMatching ? total - excluded.size : picked.size;++const selectionPlugin = useTableSelection({+ getIsItemSelected: isSelected,+ // setRows adds to or removes from excluded in all mode, picked otherwise.+ onSelectItem: ({item, isSelected}) => setRows([item], isSelected),+ onSelectAll: ({isAllSelected}) => setRows(pageRows, isAllSelected),+ getIsAllSelected: () => isPageSelected,+});++<TableSelectionToolbar+ selection={{+ // Only the loaded rows: the full set is not on the client.+ selectedKeys: new Set(pageRows.filter(isSelected).map(row => row.id)),+ selectedCount, // the app's own count+ hasSelection: selectedCount > 0,+ clearSelection: () => {+ setIsAllMatching(false);+ setPicked(new Set());+ setExcluded(new Set());+ },+ }}+ renderSelectionLabel={count =>+ !isAllMatching+ ? count + ' selected'+ : excluded.size === 0+ ? 'All ' + total + ' matching selected'+ : count + ' of ' + total + ' matching selected'+ }+ startContent={+ <>+ <Button label="Archive" variant="ghost" onClick={archive} />+ {/* Beside the action, not in its place. Once used, the offer stays as+ the command that undoes it, so focus stays on it and a second+ press can never run Archive. */}+ {isAllMatching || isPageSelected ? (+ <Button+ label={+ isAllMatching+ ? 'Select only this page'+ : 'Select all ' + total + ' matching'+ }+ variant="ghost"+ onClick={() => {+ if (isAllMatching) {+ // Every row on this page, so the label stays true and the+ // focused button stays mounted.+ setPicked(new Set(pageRows.map(row => row.id)));+ setExcluded(new Set());+ }+ setIsAllMatching(!isAllMatching);+ }}+ />+ ) : null}+ </>+ }+/>;+// In this mode the toolbar's selectedKeys holds only the loaded rows, and+// the count comes from the app. For a bulk action, send the server the+// query and the excluded ids, not a list of selected ids.+`,+ },+ ],};export const docsDense = {name: 'TableSelectionToolbar',displayName: 'Table Selection Toolbar',description:- 'Selection-aware Toolbar wrapper. Consumes selectionState from useTableSelectionState; owns count, clear, visibility, and Toolbar semantics. Caller owns actions and fixed/floating placement.',+ 'Selection-aware Toolbar wrapper. Consumes selectionState from useTableSelectionState, or an app-built state for a selection across server pages; owns count, clear, visibility, and Toolbar semantics. Caller owns actions and fixed/floating placement.',propDescriptions: {selection:- 'selectionState from useTableSelectionState: selectedKeys/count/presence + complete clear command',+ 'selectionState from useTableSelectionState, or app-built: selectedKeys/count/presence + complete clear command',startContent: 'product-owned bulk action controls',label: 'accessible toolbar name; defaults to Bulk actions',renderSelectionLabel: 'override visible count copy; receives selectedCount',