Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(table): add selection-aware bulk actions (#5486) (#5489)

Humberto Virtudesd774400a9dec
diff --git a/.changeset/table-selection-toolbar.md b/.changeset/table-selection-toolbar.md
new file mode 100644
index 0000000000..d1f759b709
--- /dev/null
+++ b/.changeset/table-selection-toolbar.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Table: add a selection-aware bulk-actions wrapper that consumes `useTableSelectionState` output while keeping the selection plugin behavior-only. (#6474)
+
+@humbertovirtudes
diff --git a/apps/docsite/scripts/generate-shadcn-registry.mjs b/apps/docsite/scripts/generate-shadcn-registry.mjs
index 5d27705f88..4b670671d8 100644
--- a/apps/docsite/scripts/generate-shadcn-registry.mjs
+++ b/apps/docsite/scripts/generate-shadcn-registry.mjs
@@ -549,6 +549,7 @@ export function buildShadcnRegistry({
cliRoot = process.cwd(),
dependencyTag = null,
externalDependencySpecs = {},
+ skipBlocksWithUnavailableComponents = false,
}) {
const cliPackage = packages.find(pkg => pkg.name === '@astryxdesign/cli');
const sourceVersion = dependencyTag ?? cliPackage?.version;
@@ -587,10 +588,27 @@ export function buildShadcnRegistry({
),
)
.sort((a, b) => a.name.localeCompare(b.name));
+ const availableComponentNames = new Set(
+ componentEntries
+ .filter(([packageName]) => packageDependencies.has(packageName))
+ .flatMap(([, components]) => components.map(component => component.name)),
+ );
const packageCatalog = new Map(packages.map(pkg => [pkg.name, pkg]));
const blockItems = [];
let skippedUnpublishedBlocks = 0;
for (const block of blocks) {
+ // A released subpath can still lack a named component added after the last
+ // package release. Production blocks must satisfy both contracts: the
+ // imported subpath below and the published component snapshot here.
+ if (
+ skipBlocksWithUnavailableComponents &&
+ block.componentsUsed?.some(
+ componentName => !availableComponentNames.has(componentName),
+ )
+ ) {
+ skippedUnpublishedBlocks++;
+ continue;
+ }
const unpublishedComponentImport = readImportSpecifiers(
block.source,
`${block.dirName}.tsx`,
@@ -698,7 +716,11 @@ export function generateShadcnRegistryForTarget({target, outDir, ...options}) {
fs.rmSync(outDir, {recursive: true, force: true});
throw new Error(`Unsupported ShadCN registry target: ${String(target)}`);
}
- return generateShadcnRegistry({outDir, ...options});
+ return generateShadcnRegistry({
+ outDir,
+ ...options,
+ skipBlocksWithUnavailableComponents: target === 'latest',
+ });
}
export function generateShadcnRegistry({
@@ -710,6 +732,7 @@ export function generateShadcnRegistry({
cliRoot,
dependencyTag,
externalDependencySpecs,
+ skipBlocksWithUnavailableComponents,
}) {
const result = buildShadcnRegistry({
packages,
@@ -719,6 +742,7 @@ export function generateShadcnRegistry({
cliRoot,
dependencyTag,
externalDependencySpecs,
+ skipBlocksWithUnavailableComponents,
});
fs.rmSync(outDir, {recursive: true, force: true});
fs.mkdirSync(outDir, {recursive: true});
diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json
index f9bd90f148..6476b0dcb2 100644
--- a/apps/sandbox/scripts/next-export-routes.json
+++ b/apps/sandbox/scripts/next-export-routes.json
@@ -571,8 +571,10 @@
"/templates/TabMenuShowcase/",
"/templates/TabShowcase/",
"/templates/TabWithSelectedIcon/",
+ "/templates/TableBulkActionsTable/",
"/templates/TableColumnSettingsTable/",
"/templates/TableFilterableTable/",
+ "/templates/TableFloatingBulkActionsTable/",
"/templates/TableGridDividersTable/",
"/templates/TableGroupedRowsTable/",
"/templates/TableInCard/",
diff --git a/apps/storybook/stories/TableSelection.stories.tsx b/apps/storybook/stories/TableSelection.stories.tsx
index b32be96e74..12f0788266 100644
--- a/apps/storybook/stories/TableSelection.stories.tsx
+++ b/apps/storybook/stories/TableSelection.stories.tsx
@@ -2,12 +2,24 @@
import {useState} from 'react';
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 {ScrollableArea} from '@astryxdesign/core/ScrollableArea';
import {
Table,
+ TableSelectionToolbar,
useTableSelection,
useTableSelectionState,
} from '@astryxdesign/core/Table';
-import type {TableColumn} from '@astryxdesign/core/Table';
+import type {TableColumn, TableSelectionState} from '@astryxdesign/core/Table';
+import {
+ colorVars,
+ radiusVars,
+ shadowVars,
+ sizeVars,
+ spacingVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
// =============================================================================
// Sample Data
@@ -292,3 +304,247 @@ export const WithStripedRows: Story = {
);
},
};
+
+const longUsers: User[] = Array.from({length: 40}, (_, index) => {
+ const user = users[index % users.length];
+ return {
+ ...user,
+ id: `long-${index + 1}`,
+ name: `${user.name} ${index + 1}`,
+ };
+});
+
+const bulkActionsStyles = stylex.create({
+ page: {
+ maxWidth: 600,
+ marginInline: 'auto',
+ },
+ scrollContainer: {
+ maxBlockSize: 640,
+ isolation: 'isolate',
+ scrollbarGutter: 'stable',
+ },
+ metrics: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
+ gap: spacingVars['--spacing-3'],
+ marginBlockEnd: spacingVars['--spacing-6'],
+ },
+ metricCard: {
+ padding: spacingVars['--spacing-4'],
+ borderRadius: radiusVars['--radius-container'],
+ backgroundColor: colorVars['--color-background-muted'],
+ },
+ metricLabel: {
+ display: 'block',
+ color: colorVars['--color-text-secondary'],
+ },
+ metricValue: {
+ display: 'block',
+ marginBlockStart: spacingVars['--spacing-1'],
+ color: colorVars['--color-text-primary'],
+ },
+ tableRegion: {
+ position: 'relative',
+ },
+ floatingRegion: {
+ // Reserve the 28px sm control plus 8px block padding on each side, then a
+ // 16px gap. The toolbar reads the same value for every placement offset,
+ // so selection never moves the table.
+ '--table-bulk-actions-space': `calc(${sizeVars['--size-element-sm']} + ${spacingVars['--spacing-2']} + ${spacingVars['--spacing-2']} + ${spacingVars['--spacing-4']})`,
+ paddingBlockStart: 'var(--table-bulk-actions-space)',
+ },
+ floatingToolbar: {
+ // The transformed normal position is 16px above the table. The sticky
+ // inset includes one additional 16px gap, leaving the visible surface 16px
+ // from the self-contained scrollport edge.
+ position: 'sticky',
+ insetBlockStart: `calc(var(--table-bulk-actions-space) + ${spacingVars['--spacing-4']})`,
+ transform: 'translateY(calc(0px - var(--table-bulk-actions-space)))',
+ marginBlockEnd: `calc(${spacingVars['--spacing-4']} - var(--table-bulk-actions-space))`,
+ zIndex: 1,
+ borderRadius: radiusVars['--radius-element'],
+ boxShadow: shadowVars['--shadow-med'],
+ },
+});
+
+type BulkActionsLayout = 'fixed' | 'floating';
+
+function BulkActionsBar({
+ layout,
+ selection,
+}: {
+ layout: BulkActionsLayout;
+ selection: TableSelectionState;
+}) {
+ return (
+ <TableSelectionToolbar
+ selection={selection}
+ data-layout={layout}
+ xstyle={
+ layout === 'floating' ? bulkActionsStyles.floatingToolbar : undefined
+ }
+ startContent={
+ layout === 'floating' ? (
+ <Button label="Approve" variant="ghost" onClick={() => {}} />
+ ) : (
+ <>
+ <Button label="Export" variant="ghost" onClick={() => {}} />
+ <Button
+ label="Delete"
+ variant="ghost"
+ onClick={selection.clearSelection}
+ />
+ </>
+ )
+ }
+ />
+ );
+}
+
+function BulkActionsExample({layout}: {layout: BulkActionsLayout}) {
+ const data = layout === 'floating' ? longUsers : users;
+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
+
+ const {selectionConfig, selectionState} = useTableSelectionState<User>({
+ data,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
+ });
+ const selectionPlugin = useTableSelection<User>(selectionConfig);
+
+ const content = (
+ <>
+ {layout === 'floating' ? (
+ <div {...stylex.props(bulkActionsStyles.metrics)}>
+ {[
+ ['Active users', '12,840'],
+ ['Selection rate', '18.4%'],
+ ['Pending reviews', '247'],
+ ].map(([label, value]) => (
+ <div key={label} {...stylex.props(bulkActionsStyles.metricCard)}>
+ <span {...stylex.props(bulkActionsStyles.metricLabel)}>
+ {label}
+ </span>
+ <strong {...stylex.props(bulkActionsStyles.metricValue)}>
+ {value}
+ </strong>
+ </div>
+ ))}
+ </div>
+ ) : null}
+ <div
+ data-table-region={layout}
+ {...stylex.props(
+ bulkActionsStyles.tableRegion,
+ layout === 'floating' && bulkActionsStyles.floatingRegion,
+ )}>
+ <BulkActionsBar layout={layout} selection={selectionState} />
+ <Table
+ data={data}
+ columns={columns}
+ idKey="id"
+ hasHover
+ plugins={{selection: selectionPlugin}}
+ />
+ </div>
+ </>
+ );
+
+ return layout === 'floating' ? (
+ <div {...stylex.props(bulkActionsStyles.page)}>
+ <ScrollableArea
+ axis="block"
+ label="Bulk actions example"
+ overscroll="contain"
+ xstyle={bulkActionsStyles.scrollContainer}>
+ {content}
+ </ScrollableArea>
+ </div>
+ ) : (
+ <div {...stylex.props(bulkActionsStyles.page)}>{content}</div>
+ );
+}
+
+/**
+ * Product-composed in-flow bar. Actions lead; selection status and clear trail.
+ */
+export const BulkActions: Story = {
+ render: () => <BulkActionsExample layout="fixed" />,
+ play: async ({canvasElement}) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(canvas.getAllByLabelText('Select row')[0]);
+
+ const toolbar = canvas.getByRole('toolbar', {name: 'Bulk actions'});
+ const toolbarSurface = toolbar.closest('.astryx-section');
+ await expect(toolbar).toHaveAttribute('data-layout', 'fixed');
+ await expect(toolbar).toHaveAttribute('data-size', 'sm');
+ await expect(toolbarSurface).toHaveAttribute('data-variant', 'muted');
+ await expect(toolbar.closest('[role="group"]')).toBeNull();
+ await expect(canvas.getByText('1 selected')).toBeInTheDocument();
+
+ await userEvent.click(canvas.getByRole('button', {name: 'Unselect All'}));
+ await expect(
+ canvas.queryByRole('toolbar', {name: 'Bulk actions'}),
+ ).not.toBeInTheDocument();
+
+ // Leave the story ready for manual review.
+ await userEvent.click(canvas.getAllByLabelText('Select row')[0]);
+ },
+};
+
+/**
+ * Product-composed floating bar for a long, non-sticky table below metrics.
+ * The example owns a capped scrollport; the toolbar stays 16px from that
+ * scrollport and releases at the table region's block-end boundary.
+ */
+export const BulkActionsFloating: Story = {
+ render: () => <BulkActionsExample layout="floating" />,
+ play: async ({canvasElement}) => {
+ const canvas = within(canvasElement);
+ const scrollRegion = await canvas.findByRole('group', {
+ name: 'Bulk actions example',
+ });
+ const table = canvas.getByRole('table');
+ const tableTopBeforeSelection = table.getBoundingClientRect().top;
+
+ await expect(scrollRegion.scrollHeight).toBeGreaterThan(
+ scrollRegion.clientHeight,
+ );
+ await expect(scrollRegion).toHaveAttribute('tabindex', '0');
+ await expect(canvas.queryByRole('region', {name: 'Metrics'})).toBeNull();
+ const scrollStyles = getComputedStyle(scrollRegion);
+ await expect(scrollStyles.overscrollBehaviorY).toBe('contain');
+ await expect(scrollStyles.overscrollBehaviorX).toBe('auto');
+ await expect(scrollStyles.isolation).toBe('isolate');
+ await userEvent.click(canvas.getAllByLabelText('Select row')[0]);
+
+ const toolbar = canvas.getByRole('toolbar', {name: 'Bulk actions'});
+ const toolbarSurface = toolbar.closest<HTMLElement>('.astryx-section');
+ if (toolbarSurface == null) {
+ throw new Error('Expected the Toolbar surface');
+ }
+
+ await expect(toolbar).toHaveAttribute('data-layout', 'floating');
+ await expect(toolbar).toHaveAttribute('data-size', 'sm');
+ await expect(toolbarSurface).toHaveAttribute('data-variant', 'muted');
+ await expect(toolbar.closest('[role="group"]')).toBe(scrollRegion);
+ await expect(
+ Math.abs(table.getBoundingClientRect().top - tableTopBeforeSelection),
+ ).toBeLessThanOrEqual(1);
+
+ scrollRegion.scrollTop = 300;
+ scrollRegion.dispatchEvent(new Event('scroll'));
+ await waitFor(() => {
+ expect(
+ Math.round(
+ toolbarSurface.getBoundingClientRect().top -
+ scrollRegion.getBoundingClientRect().top,
+ ),
+ ).toBe(16);
+ });
+
+ scrollRegion.scrollTop = 0;
+ },
+};
diff --git a/internal/shadcn-registry/generate-shadcn-registry.test.mjs b/internal/shadcn-registry/generate-shadcn-registry.test.mjs
index 21a4d1f9d3..ba24a59de1 100644
--- a/internal/shadcn-registry/generate-shadcn-registry.test.mjs
+++ b/internal/shadcn-registry/generate-shadcn-registry.test.mjs
@@ -314,6 +314,40 @@ describe('buildShadcnRegistry', () => {
expect(counts.skippedUnpublishedBlocks).toBe(1);
});
+ it('omits production blocks that import an unpublished named component', () => {
+ const root = mkdtempSync(
+ path.join(tmpdir(), 'astryx-shadcn-unpublished-component-'),
+ );
+ const outDir = path.join(root, 'shadcn');
+ try {
+ const input = fixture();
+ input.blocks.push({
+ ...input.blocks[0],
+ dirName: 'ButtonFuture',
+ name: 'Button — Future',
+ displayName: 'Button — Future',
+ componentsUsed: ['Button', 'FutureButton'],
+ source:
+ "import {Button, FutureButton} from '@astryxdesign/core/Button';\n" +
+ 'export default function ButtonFuture() { return <><Button label="Save" /><FutureButton /></>; }\n',
+ });
+
+ const result = generateShadcnRegistryForTarget({
+ target: 'latest',
+ outDir,
+ ...input,
+ });
+
+ expect(result.total).toBe(3);
+ expect(result.skippedUnpublishedBlocks).toBe(1);
+ expect(
+ existsSync(path.join(outDir, 'showcases', 'button', 'future.json')),
+ ).toBe(false);
+ } finally {
+ rmSync(root, {recursive: true, force: true});
+ }
+ });
+
it('writes canonical nested paths and compatibility aliases', () => {
const outDir = mkdtempSync(path.join(tmpdir(), 'astryx-shadcn-routes-'));
try {
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index 735f0d7be2..a3226ed937 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -976,6 +976,11 @@
"path": "components/table-row",
"aliases": []
},
+ {
+ "name": "component-table-selection-toolbar",
+ "path": "components/table-selection-toolbar",
+ "aliases": []
+ },
{
"name": "component-text",
"path": "components/text",
@@ -3570,6 +3575,16 @@
"path": "examples/use-table-row-status/semantic-and-custom-markers",
"aliases": []
},
+ {
+ "name": "example-use-table-selection-table-bulk-actions",
+ "path": "examples/use-table-selection/table-bulk-actions",
+ "aliases": []
+ },
+ {
+ "name": "example-use-table-selection-table-floating-bulk-actions",
+ "path": "examples/use-table-selection/table-floating-bulk-actions",
+ "aliases": []
+ },
{
"name": "example-use-table-sticky-columns-pinned-columns",
"path": "examples/use-table-sticky-columns/pinned-columns",
diff --git a/packages/cli/api/template/table-floating-bulk-actions.test.mjs b/packages/cli/api/template/table-floating-bulk-actions.test.mjs
new file mode 100644
index 0000000000..af69e1cc07
--- /dev/null
+++ b/packages/cli/api/template/table-floating-bulk-actions.test.mjs
@@ -0,0 +1,66 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Regression coverage for the floating bulk-actions Table block.
+ * @input The shipped TableFloatingBulkActionsTable source.
+ * @output Assertions for width, logical scrolling, local stacking, and shared toolbar geometry.
+ * @position Template contract test for the website example layout.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {describe, expect, it} from 'vitest';
+
+const sourcePath = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../../assets/templates/blocks/components/Table/TableFloatingBulkActionsTable.tsx',
+);
+const source = fs.readFileSync(sourcePath, 'utf8');
+const pageStyles = source.match(/page:\s*\{([\s\S]*?)\n\s{2}\},/)?.[1];
+const tableRegionStyles = source.match(
+ /tableRegion:\s*\{([\s\S]*?)\n\s{2}\},/,
+)?.[1];
+const toolbarStyles = source.match(/toolbar:\s*\{([\s\S]*?)\n\s{2}\},/)?.[1];
+const columns = source.match(
+ /const columns:[\s\S]*?=\s*\[([\s\S]*?)\n\];/,
+)?.[1];
+
+describe('Table floating bulk-actions template', () => {
+ it('caps the demo height without capping its width', () => {
+ expect(pageStyles).toContain('maxBlockSize: 640');
+ expect(pageStyles).not.toContain('maxWidth');
+ expect(pageStyles).not.toContain('marginInline');
+ });
+
+ it('uses the shared logical-axis scroll behavior', () => {
+ expect(source).toContain(
+ "import {ScrollableArea} from '@astryxdesign/core/ScrollableArea'",
+ );
+ expect(source).toMatch(
+ /<ScrollableArea[\s\S]*?axis="block"[\s\S]*?label="Bulk actions example"[\s\S]*?overscroll="contain"/,
+ );
+ expect(source).not.toContain('role="region"');
+ expect(source).not.toContain('tabIndex={0}');
+ expect(source).not.toContain('aria-label="Metrics"');
+ expect(pageStyles).not.toContain('overflowY');
+ expect(pageStyles).not.toContain('overscrollBehavior');
+ });
+
+ it('keeps the floating toolbar inside an isolated local stacking context', () => {
+ expect(pageStyles).toContain("isolation: 'isolate'");
+ expect(toolbarStyles).toContain('zIndex: 1');
+ expect(toolbarStyles).not.toContain('zIndex: 20');
+ });
+
+ it('shares one reserved-space variable across the placement geometry', () => {
+ expect(tableRegionStyles).toContain("'--table-bulk-actions-space'");
+ expect(source.match(/var\(--table-bulk-actions-space\)/g)).toHaveLength(4);
+ });
+
+ it('keeps the email column compact enough to avoid horizontal overflow', () => {
+ expect(columns).toContain(
+ "{key: 'email', header: 'Email', width: proportional(1)}",
+ );
+ });
+});
diff --git a/packages/cli/assets/templates/blocks/components/Table/TableBulkActionsTable.doc.mjs b/packages/cli/assets/templates/blocks/components/Table/TableBulkActionsTable.doc.mjs
new file mode 100644
index 0000000000..9622e9e9a9
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Table/TableBulkActionsTable.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'useTableSelection',
+ name: 'Table: Bulk Actions',
+ displayName: 'Table: Bulk Actions',
+ description:
+ 'Controlled row selection with the reusable TableSelectionToolbar rendered in flow above the table. Product actions occupy the logical start; synchronized selection count and complete clear action occupy the logical end.',
+ isReady: true,
+ aspectRatio: 16 / 9,
+ componentsUsed: ['Table', 'TableSelectionToolbar', 'Button'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Table/TableBulkActionsTable.tsx b/packages/cli/assets/templates/blocks/components/Table/TableBulkActionsTable.tsx
new file mode 100644
index 0000000000..4856182bc6
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Table/TableBulkActionsTable.tsx
@@ -0,0 +1,71 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import {Button} from '@astryxdesign/core/Button';
+import {
+ Table,
+ TableSelectionToolbar,
+ useTableSelection,
+ useTableSelectionState,
+ proportional,
+} from '@astryxdesign/core/Table';
+import type {TableColumn} from '@astryxdesign/core/Table';
+
+interface User extends Record<string, unknown> {
+ id: string;
+ name: string;
+ email: string;
+ role: string;
+}
+
+const users: User[] = [
+ {id: '1', name: 'Alice', email: '[email protected]', role: 'Engineer'},
+ {id: '2', name: 'Bob', email: '[email protected]', role: 'Designer'},
+ {id: '3', name: 'Charlie', email: '[email protected]', role: 'Manager'},
+ {id: '4', name: 'Diana', email: '[email protected]', role: 'Engineer'},
+ {id: '5', name: 'Eve', email: '[email protected]', role: 'Admin'},
+];
+
+const columns: TableColumn<User>[] = [
+ {key: 'name', header: 'Name', width: proportional(1)},
+ {key: 'email', header: 'Email', width: proportional(2)},
+ {key: 'role', header: 'Role', width: proportional(1)},
+];
+
+export default function TableBulkActionsTable() {
+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
+
+ const {selectionConfig, selectionState} = useTableSelectionState<User>({
+ data: users,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
+ });
+ const selectionPlugin = useTableSelection<User>(selectionConfig);
+
+ return (
+ <div>
+ <TableSelectionToolbar
+ selection={selectionState}
+ startContent={
+ <>
+ <Button label="Export" variant="ghost" onClick={() => {}} />
+ <Button
+ label="Delete"
+ variant="ghost"
+ onClick={selectionState.clearSelection}
+ />
+ </>
+ }
+ />
+ <Table
+ data={users}
+ columns={columns}
+ idKey="id"
+ plugins={{selection: selectionPlugin}}
+ />
+ </div>
+ );
+}
diff --git a/packages/cli/assets/templates/blocks/components/Table/TableFloatingBulkActionsTable.doc.mjs b/packages/cli/assets/templates/blocks/components/Table/TableFloatingBulkActionsTable.doc.mjs
new file mode 100644
index 0000000000..30ba04fc19
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Table/TableFloatingBulkActionsTable.doc.mjs
@@ -0,0 +1,19 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'useTableSelection',
+ name: 'Table: Floating Bulk Actions',
+ displayName: 'Table: Floating Bulk Actions',
+ description:
+ 'The reusable TableSelectionToolbar inside a capped, self-contained scroll region for a long non-sticky table below metric cards. The caller-owned sticky placement keeps actions 16px from the example scrollport without moving the table when selection changes.',
+ isReady: true,
+ aspectRatio: 16 / 9,
+ componentsUsed: [
+ 'Table',
+ 'TableSelectionToolbar',
+ 'Button',
+ 'ScrollableArea',
+ ],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Table/TableFloatingBulkActionsTable.tsx b/packages/cli/assets/templates/blocks/components/Table/TableFloatingBulkActionsTable.tsx
new file mode 100644
index 0000000000..5b3ee9cbdb
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Table/TableFloatingBulkActionsTable.tsx
@@ -0,0 +1,139 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {Button} from '@astryxdesign/core/Button';
+import {ScrollableArea} from '@astryxdesign/core/ScrollableArea';
+import {
+ Table,
+ TableSelectionToolbar,
+ useTableSelection,
+ useTableSelectionState,
+ proportional,
+} from '@astryxdesign/core/Table';
+import type {TableColumn} from '@astryxdesign/core/Table';
+import {
+ colorVars,
+ radiusVars,
+ shadowVars,
+ sizeVars,
+ spacingVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+
+interface User extends Record<string, unknown> {
+ id: string;
+ name: string;
+ email: string;
+ role: string;
+}
+
+const baseUsers: Array<Pick<User, 'name' | 'email' | 'role'>> = [
+ {name: 'Alice', email: '[email protected]', role: 'Engineer'},
+ {name: 'Bob', email: '[email protected]', role: 'Designer'},
+ {name: 'Charlie', email: '[email protected]', role: 'Manager'},
+ {name: 'Diana', email: '[email protected]', role: 'Engineer'},
+ {name: 'Eve', email: '[email protected]', role: 'Admin'},
+];
+
+const users: User[] = Array.from({length: 40}, (_, index) => {
+ const user = baseUsers[index % baseUsers.length];
+ return {...user, id: String(index + 1), name: `${user.name} ${index + 1}`};
+});
+
+const columns: TableColumn<User>[] = [
+ {key: 'name', header: 'Name', width: proportional(1)},
+ {key: 'email', header: 'Email', width: proportional(1)},
+ {key: 'role', header: 'Role', width: proportional(1)},
+];
+
+const styles = stylex.create({
+ page: {
+ maxBlockSize: 640,
+ isolation: 'isolate',
+ scrollbarGutter: 'stable',
+ },
+ metrics: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
+ gap: spacingVars['--spacing-3'],
+ marginBlockEnd: spacingVars['--spacing-6'],
+ },
+ metricCard: {
+ padding: spacingVars['--spacing-4'],
+ borderRadius: radiusVars['--radius-container'],
+ backgroundColor: colorVars['--color-background-muted'],
+ },
+ metricLabel: {
+ display: 'block',
+ color: colorVars['--color-text-secondary'],
+ },
+ metricValue: {
+ display: 'block',
+ marginBlockStart: spacingVars['--spacing-1'],
+ color: colorVars['--color-text-primary'],
+ },
+ tableRegion: {
+ '--table-bulk-actions-space': `calc(${sizeVars['--size-element-sm']} + ${spacingVars['--spacing-2']} + ${spacingVars['--spacing-2']} + ${spacingVars['--spacing-4']})`,
+ position: 'relative',
+ paddingBlockStart: 'var(--table-bulk-actions-space)',
+ },
+ toolbar: {
+ position: 'sticky',
+ insetBlockStart: `calc(var(--table-bulk-actions-space) + ${spacingVars['--spacing-4']})`,
+ transform: 'translateY(calc(0px - var(--table-bulk-actions-space)))',
+ marginBlockEnd: `calc(${spacingVars['--spacing-4']} - var(--table-bulk-actions-space))`,
+ zIndex: 1,
+ borderRadius: radiusVars['--radius-element'],
+ boxShadow: shadowVars['--shadow-med'],
+ },
+});
+
+export default function TableFloatingBulkActionsTable() {
+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
+
+ const {selectionConfig, selectionState} = useTableSelectionState<User>({
+ data: users,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
+ });
+ const selectionPlugin = useTableSelection<User>(selectionConfig);
+
+ return (
+ <ScrollableArea
+ axis="block"
+ label="Bulk actions example"
+ overscroll="contain"
+ xstyle={styles.page}>
+ <div {...stylex.props(styles.metrics)}>
+ {[
+ ['Active users', '12,840'],
+ ['Selection rate', '18.4%'],
+ ['Pending reviews', '247'],
+ ].map(([label, value]) => (
+ <div key={label} {...stylex.props(styles.metricCard)}>
+ <span {...stylex.props(styles.metricLabel)}>{label}</span>
+ <strong {...stylex.props(styles.metricValue)}>{value}</strong>
+ </div>
+ ))}
+ </div>
+ <div {...stylex.props(styles.tableRegion)}>
+ <TableSelectionToolbar
+ selection={selectionState}
+ xstyle={styles.toolbar}
+ startContent={
+ <Button label="Approve" variant="ghost" onClick={() => {}} />
+ }
+ />
+ <Table
+ data={users}
+ columns={columns}
+ idKey="id"
+ plugins={{selection: selectionPlugin}}
+ />
+ </div>
+ </ScrollableArea>
+ );
+}
diff --git a/packages/cli/test/doc-routes.ids.json b/packages/cli/test/doc-routes.ids.json
index 001922783f..ad95b5a205 100644
--- a/packages/cli/test/doc-routes.ids.json
+++ b/packages/cli/test/doc-routes.ids.json
@@ -147,6 +147,7 @@
"TableHeader",
"TableHeaderCell",
"TableRow",
+ "TableSelectionToolbar",
"TabList",
"TabMenu",
"Text",
@@ -806,8 +807,10 @@
"SyntaxThemeDarkPreset",
"SyntaxThemeLightPreset",
"SyntaxThemeShowcase",
+ "TableBulkActionsTable",
"TableColumnSettingsTable",
"TableFilterableTable",
+ "TableFloatingBulkActionsTable",
"TableGridDividersTable",
"TableGroupedRowsTable",
"TableInCard",
diff --git a/packages/cli/test/doc-routes.json b/packages/cli/test/doc-routes.json
index 3a6ebc1eef..c6d238b6dc 100644
--- a/packages/cli/test/doc-routes.json
+++ b/packages/cli/test/doc-routes.json
@@ -2272,7 +2272,7 @@
"kind": "component",
"id": "@astryxdesign/core/component",
"provider": "@astryxdesign/core",
- "count": 175,
+ "count": 176,
"oldCliRoute": "astryx component <id>",
"oldDocsiteUrl": "/components/<id>",
"docsiteExceptions": {
@@ -2339,7 +2339,7 @@
"kind": "block",
"id": "@astryxdesign/core/block",
"provider": "@astryxdesign/core",
- "count": 657,
+ "count": 659,
"oldCliRoute": "astryx template <id> --type block",
"oldDocsiteUrl": null,
"placement": "generated:@astryxdesign/core/block",
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index 665ef0deaa..bc31c4a19a 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -611,6 +611,18 @@
"defaultMessage": "Row status",
"description": "Screen-reader-only column header for the narrow status-indicator gutter a Table gains from useTableRowStatus. Sighted users see a blank gutter; assistive tech announces this as the column name."
},
+ "@astryx.table.selection.bulkActionsLabel": {
+ "defaultMessage": "Bulk actions",
+ "description": "Accessible name for the contextual Toolbar shown while Table rows are selected."
+ },
+ "@astryx.table.selection.clearAll": {
+ "defaultMessage": "Unselect All",
+ "description": "Visible button label that clears the complete controlled Table row selection, including keys outside the current view."
+ },
+ "@astryx.table.selection.selectedCount": {
+ "defaultMessage": "{count, number} selected",
+ "description": "Visible status in TableSelectionToolbar showing the number of selected rows."
+ },
"@astryx.table.selection.selectAllRows": {
"defaultMessage": "Select all rows",
"description": "Aria label for the \"select all rows\" checkbox in a Table header."
diff --git a/packages/core/src/Table/Table.doc.mjs b/packages/core/src/Table/Table.doc.mjs
index 2426fe7f3d..5f0de0dd6b 100644
--- a/packages/core/src/Table/Table.doc.mjs
+++ b/packages/core/src/Table/Table.doc.mjs
@@ -225,6 +225,7 @@ export const docs = {
{name: 'TableHeaderCell'},
{name: 'useTableSelection'},
{name: 'useTableSelectionState'},
+ {name: 'TableSelectionToolbar'},
{name: 'useTableSortable'},
{name: 'useTableTreeData'},
{name: 'useTableTreeState'},
diff --git a/packages/core/src/Table/TableSelectionToolbar.doc.mjs b/packages/core/src/Table/TableSelectionToolbar.doc.mjs
new file mode 100644
index 0000000000..99c85b9f13
--- /dev/null
+++ b/packages/core/src/Table/TableSelectionToolbar.doc.mjs
@@ -0,0 +1,103 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+export const docs = {
+ name: 'TableSelectionToolbar',
+ 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.',
+ props: [
+ {
+ name: 'selection',
+ type: 'TableSelectionState',
+ description:
+ 'Shared selection state returned by useTableSelectionState: selectedKeys, selectedCount, hasSelection, and clearSelection.',
+ required: true,
+ },
+ {
+ name: 'startContent',
+ type: 'ReactNode',
+ description:
+ 'Product-owned action controls aligned to the logical start. Child controls inherit the toolbar size.',
+ },
+ {
+ name: 'label',
+ type: 'string',
+ description: 'Accessible name for the action surface.',
+ default: 'Bulk actions',
+ },
+ {
+ name: 'renderSelectionLabel',
+ type: '(selectedCount: number) => ReactNode',
+ description:
+ 'Overrides the visible count text for localisation or domain-specific copy.',
+ default: 'count => `${count} selected`',
+ },
+ {
+ name: 'clearLabel',
+ type: 'string',
+ description:
+ 'Visible label for the command that clears the complete controlled selection.',
+ default: 'Unselect All',
+ },
+ {
+ name: 'size',
+ type: "'sm' | 'md' | 'lg'",
+ description:
+ 'Toolbar size. Cascades to product action controls and the clear action.',
+ default: 'sm',
+ },
+ {
+ name: 'variant',
+ type: 'SectionVariant',
+ description: 'Toolbar surface variant.',
+ default: 'muted',
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description:
+ 'Caller-owned layout styles, including sticky positioning for floating compositions.',
+ },
+ ],
+ 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.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Pass selectionState directly from useTableSelectionState so the count and clear action stay synchronized with row selection.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Provide product actions as startContent instead of encoding them as configuration objects.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Inject the toolbar through the Table plugin or its horizontal scroll wrapper.',
+ },
+ ],
+ },
+};
+
+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.',
+ propDescriptions: {
+ selection:
+ 'selectionState from useTableSelectionState: 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',
+ clearLabel: 'complete-clear button label; defaults to Unselect All',
+ size: 'Toolbar size; defaults to sm and cascades to child controls',
+ variant: 'Toolbar surface; defaults to muted',
+ xstyle: 'caller-owned layout/positioning styles',
+ },
+};
diff --git a/packages/core/src/Table/TableSelectionToolbar.test.tsx b/packages/core/src/Table/TableSelectionToolbar.test.tsx
new file mode 100644
index 0000000000..6ad18622bc
--- /dev/null
+++ b/packages/core/src/Table/TableSelectionToolbar.test.tsx
@@ -0,0 +1,109 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TableSelectionToolbar.test.tsx
+ * @input Uses TableSelectionToolbar, Button, React Testing Library, Vitest
+ * @output Behavior tests for the product-composed selection toolbar
+ * @position Test file; validates state integration and Toolbar delegation
+ */
+
+import {describe, expect, it, vi} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {Button} from '../Button';
+import {TableSelectionToolbar} from './TableSelectionToolbar';
+import type {TableSelectionState} from './plugins/selection/useTableSelectionState';
+
+function createSelectionState(
+ selectedKeys: ReadonlySet<string>,
+ clearSelection = vi.fn(),
+): TableSelectionState {
+ return {
+ selectedKeys,
+ selectedCount: selectedKeys.size,
+ hasSelection: selectedKeys.size > 0,
+ clearSelection,
+ };
+}
+
+describe('TableSelectionToolbar', () => {
+ it('renders nothing without a selection', () => {
+ render(
+ <TableSelectionToolbar
+ selection={createSelectionState(new Set())}
+ startContent={<Button label="Export" />}
+ />,
+ );
+
+ expect(
+ screen.queryByRole('toolbar', {name: 'Bulk actions'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('renders product actions with synchronized selection status', () => {
+ render(
+ <TableSelectionToolbar
+ selection={createSelectionState(new Set(['1', '2']))}
+ startContent={<Button label="Export" variant="ghost" />}
+ />,
+ );
+
+ const toolbar = screen.getByRole('toolbar', {name: 'Bulk actions'});
+ expect(toolbar).toHaveAttribute('data-size', 'sm');
+ expect(toolbar.closest('.astryx-section')).toHaveAttribute(
+ 'data-variant',
+ 'muted',
+ );
+ expect(screen.getByRole('button', {name: 'Export'})).toBeInTheDocument();
+ expect(screen.getByText('2 selected')).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {name: 'Unselect All'}),
+ ).toBeInTheDocument();
+ });
+
+ it('allows a custom selection label to render nothing', () => {
+ render(
+ <TableSelectionToolbar
+ selection={createSelectionState(new Set(['1']))}
+ renderSelectionLabel={() => null}
+ />,
+ );
+
+ expect(screen.queryByText('1 selected')).not.toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {name: 'Unselect All'}),
+ ).toBeInTheDocument();
+ });
+
+ it('clears the complete selection through the shared state output', async () => {
+ const user = userEvent.setup();
+ const clearSelection = vi.fn();
+ render(
+ <TableSelectionToolbar
+ selection={createSelectionState(new Set(['1']), clearSelection)}
+ />,
+ );
+
+ await user.click(screen.getByRole('button', {name: 'Unselect All'}));
+ expect(clearSelection).toHaveBeenCalledOnce();
+ });
+
+ it('supports product-specific toolbar, count, and clear labels', () => {
+ render(
+ <TableSelectionToolbar
+ selection={createSelectionState(new Set(['1', '2', '3']))}
+ label="Invoice actions"
+ renderSelectionLabel={count => `${count} invoices selected`}
+ clearLabel="Clear invoices"
+ />,
+ );
+
+ expect(
+ screen.getByRole('toolbar', {name: 'Invoice actions'}),
+ ).toBeInTheDocument();
+ expect(screen.getByText('3 invoices selected')).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {name: 'Clear invoices'}),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/packages/core/src/Table/TableSelectionToolbar.tsx b/packages/core/src/Table/TableSelectionToolbar.tsx
new file mode 100644
index 0000000000..f884beb859
--- /dev/null
+++ b/packages/core/src/Table/TableSelectionToolbar.tsx
@@ -0,0 +1,84 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file TableSelectionToolbar.tsx
+ * @input Uses Toolbar, Button, and selection state from useTableSelectionState
+ * @output Exports TableSelectionToolbar and its props
+ * @position Product-composed selection UI; never injected by the Table plugin
+ */
+
+import type {ReactNode} from 'react';
+import {Button} from '../Button';
+import {Toolbar} from '../Toolbar';
+import type {ToolbarProps} from '../Toolbar';
+import {useTranslator} from '../i18n';
+import type {TableSelectionState} from './plugins/selection/useTableSelectionState';
+
+export interface TableSelectionToolbarProps extends Omit<
+ ToolbarProps,
+ 'endContent' | 'label'
+> {
+ /** Shared state returned by useTableSelectionState. */
+ selection: TableSelectionState;
+ /** Accessible name for the toolbar. @default 'Bulk actions' */
+ label?: string;
+ /** Override the visible selected-count content. */
+ renderSelectionLabel?: (selectedCount: number) => ReactNode;
+ /** Visible label for the command that clears the complete selection. @default 'Unselect All' */
+ clearLabel?: string;
+}
+
+/**
+ * Selection-aware action surface that remains outside the Table plugin.
+ *
+ * The caller owns action content and placement. This component owns only the
+ * shared Toolbar presentation, selected count, and complete clear command.
+ */
+export function TableSelectionToolbar({
+ selection,
+ label: labelFromProps,
+ renderSelectionLabel,
+ clearLabel: clearLabelFromProps,
+ size = 'sm',
+ variant = 'muted',
+ ...toolbarProps
+}: TableSelectionToolbarProps): ReactNode {
+ const t = useTranslator();
+ const label = labelFromProps ?? t('@astryx.table.selection.bulkActionsLabel');
+ const clearLabel =
+ clearLabelFromProps ?? t('@astryx.table.selection.clearAll');
+
+ if (!selection.hasSelection) {
+ return null;
+ }
+
+ const selectionLabel =
+ renderSelectionLabel == null
+ ? t('@astryx.table.selection.selectedCount', {
+ count: selection.selectedCount,
+ })
+ : renderSelectionLabel(selection.selectedCount);
+
+ return (
+ <Toolbar
+ {...toolbarProps}
+ label={label}
+ size={size}
+ variant={variant}
+ endContent={
+ <>
+ <span>{selectionLabel}</span>
+ <Button
+ label={clearLabel}
+ variant="ghost"
+ onClick={selection.clearSelection}
+ />
+ </>
+ }
+ />
+ );
+}
+
+TableSelectionToolbar.displayName = 'TableSelectionToolbar';
diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.ts
index c2f03d7ca8..82d7328064 100644
--- a/packages/core/src/Table/index.ts
+++ b/packages/core/src/Table/index.ts
@@ -35,6 +35,7 @@ export {TableHeader} from './TableHeader';
export {TableBody} from './TableBody';
export {TableFooter} from './TableFooter';
export {TableContext} from './TableContext';
+export {TableSelectionToolbar} from './TableSelectionToolbar';
export {useTableSelection} from './plugins/selection';
export {useTableSelectionState} from './plugins/selection';
export {useTableSortable} from './plugins/sortable';
@@ -94,8 +95,10 @@ export type {TableHeaderProps} from './TableHeader';
export type {TableBodyProps} from './TableBody';
export type {TableFooterProps} from './TableFooter';
export type {TableContextValue} from './TableContext';
+export type {TableSelectionToolbarProps} from './TableSelectionToolbar';
export type {UseTableSelectionConfig} from './plugins/selection';
export type {
+ TableSelectionState,
UseTableSelectionStateConfig,
UseTableSelectionStateResult,
} from './plugins/selection';
diff --git a/packages/core/src/Table/plugins/selection/index.ts b/packages/core/src/Table/plugins/selection/index.ts
index 770e9aaaf0..8dc45a23f1 100644
--- a/packages/core/src/Table/plugins/selection/index.ts
+++ b/packages/core/src/Table/plugins/selection/index.ts
@@ -4,6 +4,7 @@ export {useTableSelection} from './useTableSelection';
export type {UseTableSelectionConfig} from './useTableSelection';
export {useTableSelectionState} from './useTableSelectionState';
export type {
+ TableSelectionState,
UseTableSelectionStateConfig,
UseTableSelectionStateResult,
} from './useTableSelectionState';
diff --git a/packages/core/src/Table/plugins/selection/useTableSelection.test.tsx b/packages/core/src/Table/plugins/selection/useTableSelection.test.tsx
index 63a4cc0174..a34fa3c4d2 100644
--- a/packages/core/src/Table/plugins/selection/useTableSelection.test.tsx
+++ b/packages/core/src/Table/plugins/selection/useTableSelection.test.tsx
@@ -349,6 +349,19 @@ describe('useTableSelection', () => {
});
});
+ it('leaves product chrome outside the selection plugin', () => {
+ const {result} = renderHook(() =>
+ useTableSelection<SelectableUser>({
+ getIsItemSelected: () => false,
+ onSelectItem: vi.fn(),
+ onSelectAll: vi.fn(),
+ getIsAllSelected: () => false,
+ }),
+ );
+
+ expect(result.current.transformScrollWrapper).toBeUndefined();
+ });
+
it('unsubscribes detached row refs instead of accumulating listeners', () => {
const getIsItemSelected = vi.fn(() => false);
const {result, rerender} = renderHook(() =>
diff --git a/packages/core/src/Table/plugins/selection/useTableSelectionState.test.tsx b/packages/core/src/Table/plugins/selection/useTableSelectionState.test.tsx
index 729545a2f1..eb3c754056 100644
--- a/packages/core/src/Table/plugins/selection/useTableSelectionState.test.tsx
+++ b/packages/core/src/Table/plugins/selection/useTableSelectionState.test.tsx
@@ -7,9 +7,9 @@
* @position Test file; validates disabled/selectable filtering in select-all
*/
-import {describe, it, expect} from 'vitest';
+import {describe, it, expect, vi} from 'vitest';
import {useState} from 'react';
-import {render, screen} from '@testing-library/react';
+import {act, render, renderHook, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {Table} from '../../Table';
import {useTableSelection} from './useTableSelection';
@@ -81,6 +81,32 @@ function StateHelperTable({
// Tests
// =============================================================================
+describe('useTableSelectionState selection state output', () => {
+ it('exposes selected keys, count, presence, and a complete clear command', () => {
+ const selectedKeys = new Set(['2', '4']);
+ const setSelectedKeys = vi.fn();
+ const {result} = renderHook(() =>
+ useTableSelectionState<TestItem>({
+ data: testData,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
+ }),
+ );
+
+ const selectionState = result.current.selectionState;
+
+ expect(selectionState).toMatchObject({
+ selectedKeys,
+ selectedCount: 2,
+ hasSelection: true,
+ });
+
+ act(() => selectionState.clearSelection());
+ expect(setSelectedKeys).toHaveBeenCalledWith(new Set());
+ });
+});
+
describe('useTableSelectionState', () => {
it('select-all selects only enabled items', async () => {
const user = userEvent.setup();
diff --git a/packages/core/src/Table/plugins/selection/useTableSelectionState.tsx b/packages/core/src/Table/plugins/selection/useTableSelectionState.tsx
index 1696463c02..128dfe8fe7 100644
--- a/packages/core/src/Table/plugins/selection/useTableSelectionState.tsx
+++ b/packages/core/src/Table/plugins/selection/useTableSelectionState.tsx
@@ -5,7 +5,7 @@
/**
* @file useTableSelectionState.tsx
* @input React, UseTableSelectionConfig type
- * @output Exports useTableSelectionState hook and config types
+ * @output Exports useTableSelectionState hook and public selection state types
* @position Selection state helper; manages selection set with correct
* disabled/selectable filtering. Pairs with useTableSelection.
*
@@ -63,11 +63,24 @@ export interface UseTableSelectionStateConfig<
setSelectedKeys: React.Dispatch<React.SetStateAction<Set<string>>>;
}
+export interface TableSelectionState {
+ /** Complete controlled selection, including keys outside the current view. */
+ readonly selectedKeys: ReadonlySet<string>;
+ /** Number of keys in the complete controlled selection. */
+ readonly selectedCount: number;
+ /** Whether the complete controlled selection contains any keys. */
+ readonly hasSelection: boolean;
+ /** Clear every selected key, including keys outside the current view. */
+ clearSelection: () => void;
+}
+
export interface UseTableSelectionStateResult<
T extends Record<string, unknown>,
> {
/** Ready-to-use config for useTableSelection. */
selectionConfig: UseTableSelectionConfig<T>;
+ /** Shared state for selection-aware UI outside the behavior plugin. */
+ selectionState: TableSelectionState;
}
// =============================================================================
@@ -206,5 +219,19 @@ export function useTableSelectionState<T extends Record<string, unknown>>(
],
);
- return {selectionConfig};
+ const clearSelection = useCallback(() => {
+ setSelectedKeys(new Set<string>());
+ }, [setSelectedKeys]);
+
+ const selectionState = useMemo(
+ (): TableSelectionState => ({
+ selectedKeys,
+ selectedCount: selectedKeys.size,
+ hasSelection: selectedKeys.size > 0,
+ clearSelection,
+ }),
+ [selectedKeys, clearSelection],
+ );
+
+ return {selectionConfig, selectionState};
}
diff --git a/packages/core/src/Table/useTableSelectionState.doc.mjs b/packages/core/src/Table/useTableSelectionState.doc.mjs
index 2e249628c9..8327b1a1c5 100644
--- a/packages/core/src/Table/useTableSelectionState.doc.mjs
+++ b/packages/core/src/Table/useTableSelectionState.doc.mjs
@@ -6,7 +6,8 @@ export const docs = {
name: 'useTableSelectionState',
subComponentOf: 'Table',
displayName: 'useTableSelectionState',
- description: 'State management companion for useTableSelection. Handles disabled/selectable row filtering for select-all automatically: disabled rows are frozen (preserved across select-all/deselect-all), non-selectable rows are excluded.',
+ description:
+ 'State management companion for useTableSelection. Returns selectionConfig for the behaviour plugin plus selectionState for selection-aware UI such as TableSelectionToolbar. Handles disabled/selectable row filtering for select-all automatically: disabled rows are frozen (preserved across select-all/deselect-all), non-selectable rows are excluded.',
props: [
{
name: 'data',
@@ -17,7 +18,8 @@ export const docs = {
{
name: 'idKey',
type: '(keyof T & string) | ((item: T) => string)',
- description: 'Key extractor: property name or function returning a unique string ID.',
+ description:
+ 'Key extractor: property name or function returning a unique string ID.',
required: true,
},
{
@@ -35,13 +37,15 @@ export const docs = {
{
name: 'getIsItemSelectable',
type: '(item: T) => boolean',
- description: 'Should this row show a checkbox? Non-selectable rows are excluded from select-all.',
+ description:
+ 'Should this row show a checkbox? Non-selectable rows are excluded from select-all.',
default: '() => true',
},
{
name: 'getIsItemEnabled',
type: '(item: T) => boolean',
- description: 'Is this row checkbox interactive? Disabled rows are frozen: select-all preserves their state.',
+ description:
+ 'Is this row checkbox interactive? Disabled rows are frozen: select-all preserves their state.',
default: '() => true',
},
],
@@ -50,13 +54,16 @@ export const docs = {
export const docsDense = {
name: 'useTableSelectionState',
displayName: 'useTableSelectionState',
- description: 'State companion for useTableSelection. Handles disabled/selectable row filtering for select-all automatically: disabled rows frozen (state preserved across select-all/deselect-all), non-selectable rows excluded.',
+ description:
+ 'State companion for useTableSelection. Returns selectionConfig for the behavior plugin + selectionState for selection-aware UI. Handles disabled/selectable row filtering for select-all automatically: disabled rows frozen (state preserved across select-all/deselect-all), non-selectable rows excluded.',
propDescriptions: {
data: 'full data array rendered in table',
idKey: 'key extractor: property name or fn returning unique string ID',
selectedKeys: 'controlled set of selected item IDs',
setSelectedKeys: 'setter for controlled selected keys',
- getIsItemSelectable: 'Returns whether row shows checkbox; non-selectable rows excluded from select-all. Defaults to () => true.',
- getIsItemEnabled: 'Returns whether row checkbox is interactive; disabled rows frozen: select-all preserves their state. Defaults to () => true.',
+ getIsItemSelectable:
+ 'Returns whether row shows checkbox; non-selectable rows excluded from select-all. Defaults to () => true.',
+ getIsItemEnabled:
+ 'Returns whether row checkbox is interactive; disabled rows frozen: select-all preserves their state. Defaults to () => true.',
},
};