Skip to content

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

TypeScript

feat(MultiSelector): option actions — `action?: ReactNode` on the option; a latched grid of two-cell rows (#6828)

Christopher Chedeau32f160e8cba4
diff --git a/.changeset/multi-selector-option-action.md b/.changeset/multi-selector-option-action.md
new file mode 100644
index 0000000000..bec8c504bb
--- /dev/null
+++ b/.changeset/multi-selector-option-action.md
@@ -0,0 +1,17 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] An option can carry a secondary action; `MultiSelector` renders it in a grid.
+
+`SelectorOptionData` and `SearchableItem` gain `action?: ReactNode`: one node
+the caller renders and names — an `IconButton`, a `Button`, a menu trigger.
+In `MultiSelector`, once any option carries one the popup is a `role="grid"`
+whose rows pair the option with its action: Up/Down move rows, the inline-end
+arrow reaches the action (following RTL), Enter fires it, pointer and touch
+press it directly, and pressing it never changes the selection. The trigger
+advertises `aria-haspopup="grid"`. Nothing changes for options without an
+action. `Selector` and the typeahead panel do not render the key yet and warn
+in development when an item carries one.
+
+@vjeux
diff --git a/apps/storybook/stories/MultiSelector.stories.tsx b/apps/storybook/stories/MultiSelector.stories.tsx
index 1efad72dd8..279af2df30 100644
--- a/apps/storybook/stories/MultiSelector.stories.tsx
+++ b/apps/storybook/stories/MultiSelector.stories.tsx
@@ -4,6 +4,7 @@ import type {Meta, StoryObj} from '@storybook/react';
import {expect} from 'storybook/test';
import {useState} from 'react';
import {Button} from '@astryxdesign/core/Button';
+import {IconButton} from '@astryxdesign/core/IconButton';
import {MultiSelector} from '@astryxdesign/core/MultiSelector';
import {Theme, defineTheme} from '@astryxdesign/core/theme';
@@ -782,3 +783,90 @@ export const CreateFromQuery: Story = {
);
},
};
+
+export const RowActions: Story = {
+ render: () => {
+ const [value, setValue] = useState<string[]>(['feature']);
+ const [lastEdited, setLastEdited] = useState<string | null>(null);
+ const action = (label: string) => (
+ <IconButton
+ label={`Edit ${label}`}
+ icon="moreHorizontal"
+ variant="ghost"
+ size="sm"
+ tooltip={`Edit ${label}`}
+ onClick={() => setLastEdited(label)}
+ />
+ );
+ return (
+ <>
+ <MultiSelector
+ label="Labels"
+ options={[
+ {
+ type: 'section',
+ title: 'Type',
+ options: [
+ {value: 'feature', label: 'Feature'},
+ {value: 'bug', label: 'Bug', action: action('Bug')},
+ {value: 'docs', label: 'Docs'},
+ {
+ value: 'review',
+ label: 'Design review',
+ action: action('Design review'),
+ },
+ ],
+ },
+ {
+ type: 'section',
+ title: 'Priority',
+ options: [
+ {value: 'p0', label: 'P0', action: action('P0')},
+ {value: 'p1', label: 'P1', action: action('P1')},
+ ],
+ },
+ ]}
+ value={value}
+ onChange={setValue}
+ hasSearch
+ hasSelectAll
+ hasClear
+ triggerDisplay="badges"
+ isDefaultOpen
+ />
+ <output data-testid="last-edited">{lastEdited ?? ''}</output>
+ </>
+ );
+ },
+};
+
+export const RowActionsRtl: Story = {
+ render: () => {
+ const [value, setValue] = useState<string[]>([]);
+ return (
+ <div dir="rtl">
+ <MultiSelector
+ label="Labels"
+ options={[
+ {
+ value: 'bug',
+ label: 'Bug',
+ action: (
+ <IconButton
+ label="Edit Bug"
+ icon="moreHorizontal"
+ variant="ghost"
+ size="sm"
+ />
+ ),
+ },
+ {value: 'feature', label: 'Feature'},
+ ]}
+ value={value}
+ onChange={setValue}
+ isDefaultOpen
+ />
+ </div>
+ );
+ },
+};
diff --git a/docs/specs/AST-042-cli-command-admission/spec.md b/docs/specs/AST-042-cli-command-admission/spec.md
index 244bf157a8..8451593de3 100644
--- a/docs/specs/AST-042-cli-command-admission/spec.md
+++ b/docs/specs/AST-042-cli-command-admission/spec.md
@@ -240,31 +240,31 @@ bar.
### DEP-0006 — Deprecate the `astryx layout` command group
-| Field | Value |
-|---|---|
-| id | `DEP-0006` |
-| cleanup | `CLN-0006` |
-| package | `@astryxdesign/cli` |
-| surface | CLI command group: `astryx layout` (`expand`, `check`, `grammar`), its three JSON response types (`layout.expand`, `layout.check`, `layout.grammar`), and the programmatic API exports `layoutExpand`, `layoutCheck`, `layoutGrammar` from `@astryxdesign/cli` |
-| old contract | Compressed XLE/XLO expressions parsed, validated, and expanded into XDS TSX; expression validation with canonical-surface echo; grammar cheatsheet with alias table |
-| replacement | `astryx build` chooses the closest template to start from. `astryx template <name> <path>` scaffolds it. `astryx docs layout` teaches the layout principles (scaffold, structure, spacing, breakpoints). |
-| warning | Human mode: one stderr line per invocation naming DEP-0006 and the replacement commands. JSON mode: `meta.deprecations` array in the response envelope, each entry `{id, replacements}`, matching the documented envelope schema. |
-| migration | Non-mechanical. The XLE/XLO expression language has no source-level equivalent in the replacement commands. Use `astryx build` to find the right template, `astryx template <name>` to scaffold it, and edit the scaffolded code directly. |
-| codemod | None — vacuous: expressions are ad-hoc input, not persisted source that a codemod can rewrite. |
-| downstream | Maintained agent-docs teach `build` as the front door. The layout guide (`astryx docs layout`) is unaffected. |
-| direct authority | `spec:AST-042` (CLI command admission and programmatic parity) |
-| state | `deprecated` |
-| target plan | `CLN-0006` removal in the next scheduled minor |
+| Field | Value |
+| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| id | `DEP-0006` |
+| cleanup | `CLN-0006` |
+| package | `@astryxdesign/cli` |
+| surface | CLI command group: `astryx layout` (`expand`, `check`, `grammar`), its three JSON response types (`layout.expand`, `layout.check`, `layout.grammar`), and the programmatic API exports `layoutExpand`, `layoutCheck`, `layoutGrammar` from `@astryxdesign/cli` |
+| old contract | Compressed XLE/XLO expressions parsed, validated, and expanded into XDS TSX; expression validation with canonical-surface echo; grammar cheatsheet with alias table |
+| replacement | `astryx build` chooses the closest template to start from. `astryx template <name> <path>` scaffolds it. `astryx docs layout` teaches the layout principles (scaffold, structure, spacing, breakpoints). |
+| warning | Human mode: one stderr line per invocation naming DEP-0006 and the replacement commands. JSON mode: `meta.deprecations` array in the response envelope, each entry `{id, replacements}`, matching the documented envelope schema. |
+| migration | Non-mechanical. The XLE/XLO expression language has no source-level equivalent in the replacement commands. Use `astryx build` to find the right template, `astryx template <name>` to scaffold it, and edit the scaffolded code directly. |
+| codemod | None — vacuous: expressions are ad-hoc input, not persisted source that a codemod can rewrite. |
+| downstream | Maintained agent-docs teach `build` as the front door. The layout guide (`astryx docs layout`) is unaffected. |
+| direct authority | `spec:AST-042` (CLI command admission and programmatic parity) |
+| state | `deprecated` |
+| target plan | `CLN-0006` removal in the next scheduled minor |
### CLN-0006 — Remove the `astryx layout` command group
-| Field | Value |
-|---|---|
-| id | `CLN-0006` |
-| lifecycle | `DEP-0006` |
-| delta | Remove command registration, API exports (`layoutExpand`, `layoutCheck`, `layoutGrammar`), CLI bindings, command docs, tests, and the `layout.*` response types. |
-| rollback | Re-register the command group with the same API, response types, and tests from the final-patch baseline. |
-| state | `pending` — lands only when a minor is scheduled and `CLN-0006` appears in its frozen manifest |
+| Field | Value |
+| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| id | `CLN-0006` |
+| lifecycle | `DEP-0006` |
+| delta | Remove command registration, API exports (`layoutExpand`, `layoutCheck`, `layoutGrammar`), CLI bindings, command docs, tests, and the `layout.*` response types. |
+| rollback | Re-register the command group with the same API, response types, and tests from the final-patch baseline. |
+| state | `pending` — lands only when a minor is scheduled and `CLN-0006` appears in its frozen manifest |
## Open questions
diff --git a/packages/core/src/MultiSelector/MultiSelector.doc.mjs b/packages/core/src/MultiSelector/MultiSelector.doc.mjs
index 698239edc3..b7334d1f82 100644
--- a/packages/core/src/MultiSelector/MultiSelector.doc.mjs
+++ b/packages/core/src/MultiSelector/MultiSelector.doc.mjs
@@ -183,7 +183,7 @@ export const docs = {
name: 'options',
type: 'MultiSelectorOptionType[]',
description:
- 'Array of items: strings, objects with value/label/icon/disabled, dividers, or sections.',
+ 'Array of items: strings, objects with value/label/icon/disabled, dividers, or sections. An option may carry `action`: one node — an IconButton, a Button, a menu trigger — the caller renders and names. Once any option does, the popup is a grid whose rows pair the option with its action: Up/Down move rows, the inline-end arrow reaches the action, Enter fires it, pointer and touch press it directly, and pressing it never changes the selection.',
required: true,
},
{
diff --git a/packages/core/src/MultiSelector/MultiSelector.spec.md b/packages/core/src/MultiSelector/MultiSelector.spec.md
index 53d6ca0734..8a0a466f26 100644
--- a/packages/core/src/MultiSelector/MultiSelector.spec.md
+++ b/packages/core/src/MultiSelector/MultiSelector.spec.md
@@ -111,17 +111,19 @@ syntax and examples remain in `MultiSelector.doc.mjs`.
## Behavioral and layout contract
-| ID | Candidate invariant | Basis | Draft review state |
-| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | -------------------------------------------------- |
-| FR1 | The current standalone presentation contains a Field and painted Trigger; the supported InputGroup path renders the same Trigger without a Field. Optional start content, clear action, status icon, or Indicator icon follows supplied props and state. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
-| FR2 | The shared panel content contains the optional Search row, zero or more Option rows, optional public Option dividers and Section headings, and an Empty state when the applicable result set is empty and the value is not loading. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
-| FR3 | Trigger, Indicator icon, Search row, Option row, Section heading, Empty state, and Pointer popup carry the seven current non-deprecated MultiSelector targets documented in `MultiSelector.doc.mjs`. | Current source, docs, and tests | Verified current behavior; no target change |
-| FR4 | When present, Field, shared clear actions, option checkbox indicators, public Option dividers, general icons, Touch sheet heading, and Touch sheet retain their Field, CheckboxInput, Divider, Icon, Text, and BottomSheet theming owners. | Current composition and owners | Verified current behavior; no target change |
-| FR5 | Pointer popup and Touch sheet are separate surface anatomy rows, but both host the same `panelContent` tree; the Touch sheet additionally renders its Heading. Changing presentation does not create a second search, option, divider, section, or empty-state content model. | Current source and tests | Verified current behavior; no normalization |
-| FR6 | `multi-selector-clear-icon` remains a deprecated compatibility alias for `input-clear-icon`; it is not a current target and does not claim a separate anatomy part. | Current public target metadata | Verified current compatibility state |
-| FR7 | While `isReadOnly` is true, selected values remain focusable and form-submittable, while the selection surface, clear action, disclosure indicator, and every value-change path are unavailable. | `spec:AST-011`, docs, and tests | Accepted read-only behavior |
-| FR8 | With `renderTrigger`, the caller-rendered control receives `ref`, `id`, `onClick`, `onKeyDown`, `onFocus`, `aria-haspopup`, `aria-expanded`, `aria-controls`, and `aria-busy`; the panel is anchored to it, focus returns to it on close, the listbox is named by `label`, and the listbox takes focus and owns the keyboard on open. No Field, status, clear action, spinner, or indicator renders. `handleRef` exposes `open`, `close`, `toggle`, `isOpen`; `onOpenChange` fires on every open and close. | DEC-1, docs, and tests | Proposed; awaiting owner approval |
-| FR9 | With `hasSearch` and `hasCreate`, once options have loaded, a `Create "<query>"` row leads the list when the trimmed query equals no option label under the search's own case-insensitive matching. Picking it, or Enter with nothing highlighted, calls `onChange` with the query appended to the value and a `{type: 'create', query}` descriptor, clears the search, and announces the creation; every other change passes no descriptor. The row has no checkbox, is never selected, is excluded from select-all and from `renderOption`, and is announced instead of the empty message when it is the only result. While `isLoading`, no row is offered and Enter commits nothing. `hasCreate` without `hasSearch` warns in development and offers nothing. | `spec:AST-056` FR5 / DEC-3, `component:Tokenizer` `hasCreate`, docs, and tests | Proposed; awaiting owner approval |
+| ID | Candidate invariant | Basis | Draft review state |
+| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
+| FR1 | The current standalone presentation contains a Field and painted Trigger; the supported InputGroup path renders the same Trigger without a Field. Optional start content, clear action, status icon, or Indicator icon follows supplied props and state. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
+| FR2 | The shared panel content contains the optional Search row, zero or more Option rows, optional public Option dividers and Section headings, and an Empty state when the applicable result set is empty and the value is not loading. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
+| FR3 | Trigger, Indicator icon, Search row, Option row, Section heading, Empty state, and Pointer popup carry the seven current non-deprecated MultiSelector targets documented in `MultiSelector.doc.mjs`. | Current source, docs, and tests | Verified current behavior; no target change |
+| FR4 | When present, Field, shared clear actions, option checkbox indicators, public Option dividers, general icons, Touch sheet heading, and Touch sheet retain their Field, CheckboxInput, Divider, Icon, Text, and BottomSheet theming owners. | Current composition and owners | Verified current behavior; no target change |
+| FR5 | Pointer popup and Touch sheet are separate surface anatomy rows, but both host the same `panelContent` tree; the Touch sheet additionally renders its Heading. Changing presentation does not create a second search, option, divider, section, or empty-state content model. | Current source and tests | Verified current behavior; no normalization |
+| FR6 | `multi-selector-clear-icon` remains a deprecated compatibility alias for `input-clear-icon`; it is not a current target and does not claim a separate anatomy part. | Current public target metadata | Verified current compatibility state |
+| FR7 | While `isReadOnly` is true, selected values remain focusable and form-submittable, while the selection surface, clear action, disclosure indicator, and every value-change path are unavailable. | `spec:AST-011`, docs, and tests | Accepted read-only behavior |
+| FR8 | With `renderTrigger`, the caller-rendered control receives `ref`, `id`, `onClick`, `onKeyDown`, `onFocus`, `aria-haspopup`, `aria-expanded`, `aria-controls`, and `aria-busy`; the panel is anchored to it, focus returns to it on close, the listbox is named by `label`, and the listbox takes focus and owns the keyboard on open. No Field, status, clear action, spinner, or indicator renders. `handleRef` exposes `open`, `close`, `toggle`, `isOpen`; `onOpenChange` fires on every open and close. | DEC-1, docs, and tests | Proposed; awaiting owner approval |
+| FR9 | With `hasSearch` and `hasCreate`, once options have loaded, a `Create "<query>"` row leads the list when the trimmed query equals no option label under the search's own case-insensitive matching. Picking it, or Enter with nothing highlighted, calls `onChange` with the query appended to the value and a `{type: 'create', query}` descriptor, clears the search, and announces the creation; every other change passes no descriptor. The row has no checkbox, is never selected, is excluded from select-all and from `renderOption`, and is announced instead of the empty message when it is the only result. While `isLoading`, no row is offered and Enter commits nothing. `hasCreate` without `hasSearch` warns in development and offers nothing. | `spec:AST-056` FR5 / DEC-3, `component:Tokenizer` `hasCreate`, docs, and tests | Proposed; awaiting owner approval |
+| option action | `action` absent, present | The option's secondary control as one node; the popup is a grid of rows pairing option and action | Pointer popup and Touch sheet | absent | Caller | additive | `null` is none; a control without a name warns in development |
+| FR10 | Once any declared option — at any depth of sections, before any query filters it — carries an `action`, the popup is a `role="grid"` and stays one while mounted; the trigger advertises `aria-haspopup="grid"` (the bottom sheet keeps `dialog`). Each option, the select-all row included, is a `role="row"` carrying the option's id, `aria-selected` and `aria-disabled`, with exactly two `gridcell` children: the option's content, then its action or an empty cell. A section is a `rowgroup` named by its title. Pressing the option cell toggles; pressing the action fires the caller's control and nothing else. Up/Down move rows onto the option cell; the inline-end arrow moves to the action cell and the inline-start arrow back, following visual direction under RTL; Enter on the action cell activates the control. `aria-activedescendant` names the row or the action cell. No control inside the popup is a tab stop. | `spec:AST-058` FR1–FR8, AR1–AR4 | Proposed; awaiting owner approval |
### Allowed variation
@@ -287,16 +289,17 @@ empty-state content remains one shared tree.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |
-| FR1, FR2 | `MultiSelector.test.tsx` render, search, divider, grouping, status, select-all, and empty-state suites plus InputGroup source inspection | Standalone/InputGroup, search, divided, selected, empty, status | Removing a documented part or misreporting Field presence conflicts with existing structure, content assertions, or source. | `audit:MultiSelector/anatomy` |
-| FR3, FR6 | Component target suites, source inspection, and public target inventory | All seven current targets and deprecated alias | A current target is missed, invented, moved, or confused with the deprecated clear-icon alias. | `audit:MultiSelector/theming` |
-| FR4 | Composed owner source/tests for Field, CheckboxInput, Divider, Icon, Text, and BottomSheet | Field omission/presence, clear actions, checkbox, divider, icons, heading, sheet | A shared part gains the wrong local owner or its documented owner no longer renders it. | `audit:MultiSelector/theming` |
-| FR5 | `MultiSelector.test.tsx` presentation suites and `panelContent` source inspection | Explicit popover, explicit sheet, adaptive touch | A presentation stops using its owner or receives a divergent panel-content implementation. | `audit:MultiSelector/overlay` |
-| FR7 | read-only interaction, form, ARIA, and theme-state tests | search/non-search, clearable, open→read-only, disabled precedence | A value changes, popup or edit affordance remains, form value disappears, or read-only semantics are absent. | `audit:MultiSelector/accessibility` |
-| FR8 | `MultiSelector.test.tsx` "trigger render prop" suite | External trigger closed/open; handle open/close; disabled; listbox focus | Field chrome renders with a trigger, the control lacks disclosure state, the listbox is unnamed, or the handle opens a disabled selector. | `audit:MultiSelector/accessibility` |
-| FR9 | `MultiSelector.test.tsx` "hasCreate" suite; `CreateRow.a11y.chromium.spec.ts` appear/disappear cycle | Create row offered, committed by click/Enter with descriptor, skipped on a case-insensitive exact match, offered for a label the filter cannot surface, absent while loading, beside select-all; toggle without descriptor; warning without search | The row appears while loading or for an existing label, reports without a descriptor, keeps the search text, is silently inert without search, or the live region says "no results" beside a create row. | `audit:MultiSelector/accessibility` |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current local targets | Missing, extra, prefixed, stale, or multiply assigned mappings fail repository validation. | `audit:MultiSelector/theming` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------- |
+| FR1, FR2 | `MultiSelector.test.tsx` render, search, divider, grouping, status, select-all, and empty-state suites plus InputGroup source inspection | Standalone/InputGroup, search, divided, selected, empty, status | Removing a documented part or misreporting Field presence conflicts with existing structure, content assertions, or source. | `audit:MultiSelector/anatomy` |
+| FR3, FR6 | Component target suites, source inspection, and public target inventory | All seven current targets and deprecated alias | A current target is missed, invented, moved, or confused with the deprecated clear-icon alias. | `audit:MultiSelector/theming` |
+| FR4 | Composed owner source/tests for Field, CheckboxInput, Divider, Icon, Text, and BottomSheet | Field omission/presence, clear actions, checkbox, divider, icons, heading, sheet | A shared part gains the wrong local owner or its documented owner no longer renders it. | `audit:MultiSelector/theming` |
+| FR5 | `MultiSelector.test.tsx` presentation suites and `panelContent` source inspection | Explicit popover, explicit sheet, adaptive touch | A presentation stops using its owner or receives a divergent panel-content implementation. | `audit:MultiSelector/overlay` |
+| FR7 | read-only interaction, form, ARIA, and theme-state tests | search/non-search, clearable, open→read-only, disabled precedence | A value changes, popup or edit affordance remains, form value disappears, or read-only semantics are absent. | `audit:MultiSelector/accessibility` |
+| FR8 | `MultiSelector.test.tsx` "trigger render prop" suite | External trigger closed/open; handle open/close; disabled; listbox focus | Field chrome renders with a trigger, the control lacks disclosure state, the listbox is unnamed, or the handle opens a disabled selector. | `audit:MultiSelector/accessibility` |
+| FR9 | `MultiSelector.test.tsx` "hasCreate" suite; `CreateRow.a11y.chromium.spec.ts` appear/disappear cycle | Create row offered, committed by click/Enter with descriptor, skipped on a case-insensitive exact match, offered for a label the filter cannot surface, absent while loading, beside select-all; toggle without descriptor; warning without search | The row appears while loading or for an existing label, reports without a descriptor, keeps the search text, is silently inert without search, or the live region says "no results" beside a create row. | `audit:MultiSelector/accessibility` |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current local targets | Missing, extra, prefixed, stale, or multiply assigned mappings fail repository validation. | `audit:MultiSelector/theming` |
+| FR10 | `MultiSelector.test.tsx` "option actions (grid)" suite; `OptionActions.a11y.chromium.spec.ts`; `Selector.test.tsx` non-adoption case | No action; `action: null`; action inside a section; filtered out; removed later; options after loading; click cell vs action; disabled option with action; arrows LTR/RTL; search Left/Right; hover; Tab; unnamed control | A grid with no declared action, a listbox with one, a role that follows the filtered view, a row with other than two cells, a `group` in a grid, a toggle on an action press, an action unreachable by arrow, a tab stop inside the popup, or an action absent at rest, fails. | `audit:MultiSelector/accessibility` |
Existing component tests directly assert the Trigger, Indicator icon, Search row,
Option row, Section heading, Empty state, and Pointer popup targets. Presentation
diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsx
index 7f60f91d2b..ffca832eac 100644
--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx
@@ -3779,3 +3779,432 @@ describe('MultiSelector hasCreate', () => {
expect(screen.getByText('No results found')).toBeInTheDocument();
});
});
+
+describe('MultiSelector option actions (grid)', () => {
+ const edit = vi.fn();
+ const OPTIONS = [
+ {
+ value: 'bug',
+ label: 'Bug',
+ action: (
+ <button
+ type="button"
+ onClick={() => {
+ edit('bug');
+ }}>
+ Edit Bug
+ </button>
+ ),
+ },
+ {value: 'feature', label: 'Feature'},
+ {
+ value: 'docs',
+ label: 'Docs',
+ disabled: true,
+ action: (
+ <button
+ type="button"
+ onClick={() => {
+ edit('docs');
+ }}>
+ Edit Docs
+ </button>
+ ),
+ },
+ ];
+ beforeEach(() => {
+ edit.mockClear();
+ });
+
+ it('stays a listbox when no option carries an action, and action: null is none', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={[
+ {value: 'bug', label: 'Bug', action: null},
+ {value: 'feature', label: 'Feature'},
+ ]}
+ value={[]}
+ onChange={() => {}}
+ />,
+ );
+ const trigger = screen.getByRole('combobox', {name: 'Labels'});
+ expect(trigger).toHaveAttribute('aria-haspopup', 'listbox');
+ await user.click(trigger);
+ expect(screen.getByRole('listbox', h)).toBeInTheDocument();
+ expect(screen.queryByRole('grid', h)).toBeNull();
+ expect(screen.getAllByRole('option', h)).toHaveLength(2);
+ });
+
+ it('is a grid of rows with exactly two gridcells once an option carries an action', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={['bug']}
+ onChange={() => {}}
+ hasSelectAll
+ />,
+ );
+ const trigger = screen.getByRole('combobox', {name: 'Labels'});
+ expect(trigger).toHaveAttribute('aria-haspopup', 'grid');
+ await user.click(trigger);
+
+ const grid = screen.getByRole('grid', h);
+ expect(screen.queryByRole('listbox', h)).toBeNull();
+ expect(screen.queryByRole('option', h)).toBeNull();
+ expect(grid).toHaveAttribute('aria-multiselectable', 'true');
+ expect(trigger.getAttribute('aria-controls')).toBe(grid.id);
+
+ const rows = screen.getAllByRole('row', h);
+ // select-all + 3 options
+ expect(rows).toHaveLength(4);
+ for (const row of rows) {
+ const cells = Array.from(row.children);
+ expect(cells).toHaveLength(2);
+ expect(cells[0]).toHaveAttribute('role', 'gridcell');
+ expect(cells[1]).toHaveAttribute('role', 'gridcell');
+ }
+ // Every exposed child of the grid is a row.
+ expect(
+ Array.from(grid.children).every(c => c.getAttribute('role') === 'row'),
+ ).toBe(true);
+
+ const bug = screen.getByRole('row', {name: 'Bug', ...h});
+ expect(bug).toHaveAttribute('aria-selected', 'true');
+ expect(bug.children[1]).toContainElement(
+ screen.getByRole('button', {name: 'Edit Bug', ...h}),
+ );
+ // Rows without an action, and the select-all row, have an empty cell.
+ expect(
+ screen.getByRole('row', {name: 'Feature', ...h}).children[1],
+ ).toBeEmptyDOMElement();
+ expect(rows[0].children[1]).toBeEmptyDOMElement();
+ // The row's name is the option; the control keeps its own.
+ expect(bug).toHaveAccessibleName('Bug');
+ });
+
+ it('latches: a query that filters the actioned option out keeps the grid', async () => {
+ const user = userEvent.setup();
+ const {rerender} = render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ expect(screen.getByRole('grid', h)).toBeInTheDocument();
+ await user.type(screen.getByRole('combobox', h), 'Feat');
+ expect(screen.getAllByRole('row', h).map(r => r.textContent)).toEqual([
+ 'Feature',
+ ]);
+ expect(screen.getByRole('grid', h)).toBeInTheDocument();
+ // The action removed on a later render: still a grid.
+ rerender(
+ <MultiSelector
+ label="Labels"
+ options={[{value: 'feature', label: 'Feature'}]}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ />,
+ );
+ expect(screen.getByRole('grid', h)).toBeInTheDocument();
+ });
+
+ it('becomes a grid when options arrive after loading, inside a section too', async () => {
+ const user = userEvent.setup();
+ const {rerender} = render(
+ <MultiSelector
+ label="Labels"
+ options={[]}
+ value={[]}
+ onChange={() => {}}
+ isLoading
+ />,
+ );
+ expect(screen.getByRole('combobox', {name: 'Labels'})).toHaveAttribute(
+ 'aria-haspopup',
+ 'listbox',
+ );
+ rerender(
+ <MultiSelector
+ label="Labels"
+ options={[
+ {
+ type: 'section',
+ title: 'Type',
+ options: OPTIONS,
+ },
+ ]}
+ value={[]}
+ onChange={() => {}}
+ />,
+ );
+ const trigger = screen.getByRole('combobox', {name: 'Labels'});
+ expect(trigger).toHaveAttribute('aria-haspopup', 'grid');
+ await user.click(trigger);
+ const group = screen.getByRole('rowgroup', {name: 'Type', ...h});
+ expect(screen.queryByRole('group', h)).toBeNull();
+ expect(group.querySelectorAll('[role="row"]')).toHaveLength(3);
+ });
+
+ it('pressing the option cell toggles; pressing the action fires only the action', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={onChange}
+ />,
+ );
+ await user.click(screen.getByRole('combobox', {name: 'Labels'}));
+ const bug = screen.getByRole('row', {name: 'Bug', ...h});
+ await user.click(bug.children[0]);
+ expect(onChange).toHaveBeenCalledWith(['bug']);
+
+ onChange.mockClear();
+ await user.click(screen.getByRole('button', {name: 'Edit Bug', ...h}));
+ expect(edit).toHaveBeenCalledWith('bug');
+ expect(onChange).not.toHaveBeenCalled();
+ // The panel stays open.
+ expect(screen.getByRole('grid', h)).toBeInTheDocument();
+
+ // A disabled option's action is the caller's control, still live.
+ await user.click(screen.getByRole('button', {name: 'Edit Docs', ...h}));
+ expect(edit).toHaveBeenCalledWith('docs');
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('the inline-end arrow reaches the action cell, Enter fires it, inline-start returns', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={onChange}
+ />,
+ );
+ const trigger = screen.getByRole('combobox', {name: 'Labels'});
+ await user.click(trigger);
+ const bug = screen.getByRole('row', {name: 'Bug', ...h});
+ // Click-open highlights the first row, on its option cell.
+ expect(trigger).toHaveAttribute('aria-activedescendant', bug.id);
+
+ fireEvent.keyDown(trigger, {key: 'ArrowRight'});
+ expect(trigger).toHaveAttribute(
+ 'aria-activedescendant',
+ bug.children[1].id,
+ );
+ fireEvent.keyDown(trigger, {key: 'Enter'});
+ expect(edit).toHaveBeenCalledWith('bug');
+ expect(onChange).not.toHaveBeenCalled();
+ // The highlight stays where it was.
+ expect(trigger).toHaveAttribute(
+ 'aria-activedescendant',
+ bug.children[1].id,
+ );
+
+ fireEvent.keyDown(trigger, {key: 'ArrowLeft'});
+ expect(trigger).toHaveAttribute('aria-activedescendant', bug.id);
+ fireEvent.keyDown(trigger, {key: 'Enter'});
+ expect(onChange).toHaveBeenCalledWith(['bug']);
+
+ // A row without an action: the inline-end arrow is a no-op there, and
+ // Down from the action cell lands on the next row's option cell.
+ fireEvent.keyDown(trigger, {key: 'ArrowRight'});
+ fireEvent.keyDown(trigger, {key: 'ArrowDown'});
+ const feature = screen.getByRole('row', {name: 'Feature', ...h});
+ expect(trigger).toHaveAttribute('aria-activedescendant', feature.id);
+ fireEvent.keyDown(trigger, {key: 'ArrowRight'});
+ expect(trigger).toHaveAttribute('aria-activedescendant', feature.id);
+ });
+
+ it('follows visual direction under RTL', async () => {
+ const user = userEvent.setup();
+ const original = window.getComputedStyle;
+ const spy = vi
+ .spyOn(window, 'getComputedStyle')
+ .mockImplementation((el: Element, pseudo?: string | null) => {
+ const style = original.call(window, el, pseudo);
+ Object.defineProperty(style, 'direction', {value: 'rtl'});
+ return style;
+ });
+ try {
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ />,
+ );
+ const trigger = screen.getByRole('combobox', {name: 'Labels'});
+ await user.click(trigger);
+ const bug = screen.getByRole('row', {name: 'Bug', ...h});
+ fireEvent.keyDown(trigger, {key: 'ArrowRight'});
+ expect(trigger).toHaveAttribute('aria-activedescendant', bug.id);
+ fireEvent.keyDown(trigger, {key: 'ArrowLeft'});
+ expect(trigger).toHaveAttribute(
+ 'aria-activedescendant',
+ bug.children[1].id,
+ );
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('with search, Left/Right move the caret until a row is highlighted', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ const search = screen.getByRole('combobox', h);
+ await user.type(search, 'Bu');
+ // No row highlighted: the arrow is the input's.
+ const right = fireEvent.keyDown(search, {key: 'ArrowRight'});
+ expect(right).toBe(true);
+ expect(search).not.toHaveAttribute('aria-activedescendant');
+
+ fireEvent.keyDown(search, {key: 'ArrowDown'});
+ const bug = screen.getByRole('row', {name: 'Bug', ...h});
+ expect(search).toHaveAttribute('aria-activedescendant', bug.id);
+ const moved = fireEvent.keyDown(search, {key: 'ArrowRight'});
+ expect(moved).toBe(false);
+ expect(search).toHaveAttribute('aria-activedescendant', bug.children[1].id);
+ fireEvent.keyDown(search, {key: 'Enter'});
+ expect(edit).toHaveBeenCalledWith('bug');
+ expect(search).toHaveValue('Bu');
+ });
+
+ it('hovering the action cell highlights that row on its action cell', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ />,
+ );
+ const trigger = screen.getByRole('combobox', {name: 'Labels'});
+ await user.click(trigger);
+ const bug = screen.getByRole('row', {name: 'Bug', ...h});
+ const feature = screen.getByRole('row', {name: 'Feature', ...h});
+ fireEvent.mouseEnter(feature.children[0]);
+ expect(trigger).toHaveAttribute('aria-activedescendant', feature.id);
+ fireEvent.mouseEnter(bug.children[1]);
+ expect(trigger).toHaveAttribute(
+ 'aria-activedescendant',
+ bug.children[1].id,
+ );
+ fireEvent.mouseEnter(bug.children[0]);
+ expect(trigger).toHaveAttribute('aria-activedescendant', bug.id);
+ });
+
+ it('Tab closes the panel as before: no action control is a stop inside it', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ />,
+ );
+ const trigger = screen.getByRole('combobox', {name: 'Labels'});
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ fireEvent.keyDown(trigger, {key: 'Tab'});
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+ });
+
+ it('warns in development about an action control with no accessible name', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={[
+ {value: 'bug', label: 'Bug', action: <button type="button" />},
+ ]}
+ value={[]}
+ onChange={() => {}}
+ />,
+ );
+ await user.click(screen.getByRole('combobox', {name: 'Labels'}));
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringMatching(/MultiSelector[\s\S]*accessible name/),
+ );
+ } finally {
+ warn.mockRestore();
+ }
+ });
+});
+
+describe('MultiSelector create row inside a grid', () => {
+ it('is a row with exactly two gridcells, the action cell empty, and the arrow stays on the option', async () => {
+ // spec:AST-058 FR3: in a grid every row has exactly two cells, and a
+ // system-minted row is no exception. The create row has no control of
+ // its own, so its action cell is present and empty, and the inline-end
+ // arrow has nowhere to go.
+ const user = userEvent.setup();
+ const onChange =
+ vi.fn<(value: string[], change?: MultiSelectorChange) => void>();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={[
+ {
+ value: 'bug',
+ label: 'Bug',
+ action: <button type="button">Edit Bug</button>,
+ },
+ {value: 'feature', label: 'Feature'},
+ ]}
+ value={[]}
+ onChange={onChange}
+ hasSearch
+ hasCreate
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ const search = screen.getByRole('combobox', {hidden: true});
+ await user.type(search, 'Urgent');
+
+ const rows = screen.getAllByRole('row', {hidden: true});
+ expect(rows).toHaveLength(1);
+ const create = rows[0];
+ expect(create).toHaveTextContent('Create "Urgent"');
+ const cells = Array.from(create.children).filter(
+ c => c.getAttribute('role') === 'gridcell',
+ );
+ expect(cells).toHaveLength(2);
+ expect(cells[1]).toBeEmptyDOMElement();
+
+ await user.keyboard('{ArrowDown}{ArrowRight}{Enter}');
+ expect(onChange).toHaveBeenCalledWith(['Urgent'], {
+ type: 'create',
+ query: 'Urgent',
+ });
+ });
+});
diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsx
index 4469f2f1e7..7cade1685c 100644
--- a/packages/core/src/MultiSelector/MultiSelector.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.tsx
@@ -72,7 +72,8 @@ import {
} from '../Selector/utils';
import {useMultiCombobox} from './hooks';
import {getInputARIA, isImeKeyEvent, mergeProps} from '../utils';
-import {devWarn} from '../utils/devWarning';
+import {devWarn, warnOnce} from '../utils/devWarning';
+import {FOCUS_OUTLINE_PARTS} from '../utils/focusOutline.stylex';
import {useAnnounce} from '../hooks/useAnnounce';
import {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector';
import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';
@@ -377,6 +378,38 @@ const styles = stylex.create({
whiteSpace: 'nowrap',
},
+ // Grid rows (spec:AST-058): the row carries today's option chrome (padding,
+ // radius, highlight); its two cells split it into the option's click
+ // target and the action's slot. The action cell is a real cell for the
+ // active-descendant ring, drawn with the shared focus-outline parts because
+ // no element inside the popup has DOM focus.
+ gridRow: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ },
+ optionCell: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ flexGrow: 1,
+ flexShrink: 1,
+ minWidth: 0,
+ alignSelf: 'stretch',
+ },
+ actionCell: {
+ display: 'flex',
+ alignItems: 'center',
+ flexShrink: 0,
+ borderRadius: radiusVars['--radius-element'],
+ },
+ actionCellActive: {
+ outlineWidth: FOCUS_OUTLINE_PARTS.outlineWidth,
+ outlineStyle: FOCUS_OUTLINE_PARTS.outlineStyle,
+ outlineColor: FOCUS_OUTLINE_PARTS.outlineColor,
+ outlineOffset: FOCUS_OUTLINE_PARTS.outlineOffset,
+ },
+
// Empty state
emptyState: {
padding: spacingVars['--spacing-3'],
@@ -482,7 +515,7 @@ export interface MultiSelectorRenderTriggerProps {
* `aria-haspopup` and `aria-controls` are absent and `aria-expanded` is
* `false` (`spec:AST-011` FR4).
*/
- 'aria-haspopup'?: 'listbox' | 'dialog';
+ 'aria-haspopup'?: 'listbox' | 'grid' | 'dialog';
'aria-expanded': boolean;
'aria-controls'?: string;
'aria-busy': boolean | undefined;
@@ -862,6 +895,30 @@ export interface MultiSelectorProps<
'data-testid'?: string;
}
+// Whether any declared option — at any depth of sections, before any query
+// filters it — carries an action. Presence only: the node is never read
+// (spec:AST-058 FR2, DEC-5).
+function hasDeclaredAction(options: MultiSelectorOptionType[]): boolean {
+ for (const option of options) {
+ if (isSection(option)) {
+ if (
+ option.options.some(
+ opt => typeof opt !== 'string' && opt.action != null,
+ )
+ ) {
+ return true;
+ }
+ } else if (
+ typeof option !== 'string' &&
+ isOptionData(option) &&
+ option.action != null
+ ) {
+ return true;
+ }
+ }
+ return false;
+}
+
// Case-insensitive substring match for a single option. The one predicate used
// by both the flat filter (count + keyboard nav) and the grouped renderer, so
// what is shown while searching stays in lockstep with the announced count.
@@ -1056,6 +1113,16 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
[options],
);
+ // Grid mode (spec:AST-058 FR2, DEC-5): decided from the declared options,
+ // and latched — once a grid, a grid for the life of the instance, so a
+ // query that filters the actioned option out, or options that arrive after
+ // a loading state, never flip the role under a screen reader.
+ const hasActions = useMemo(() => hasDeclaredAction(options), [options]);
+ const [isGrid, setIsGrid] = useState(hasActions);
+ if (hasActions && !isGrid) {
+ setIsGrid(true);
+ }
+
// The one half-configuration a single switch cannot rule out: creation
// needs a query to create from. Say so rather than offer nothing in silence.
useEffect(() => {
@@ -1250,6 +1317,43 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
const {popover} = surface;
const hideSurface = surface.hide;
const isSurfaceOpen = surface.isOpen;
+
+ // AR2: the caller's control must carry its own name. Checked against the
+ // rendered DOM in development, never by reading the node.
+ useEffect(() => {
+ if (!isGrid || !isSurfaceOpen) {
+ return;
+ }
+ const panel = listboxRef.current;
+ if (panel == null) {
+ return;
+ }
+ for (const cell of Array.from(
+ panel.querySelectorAll<HTMLElement>('[data-multi-selector-action-cell]'),
+ )) {
+ const control = cell.querySelector<HTMLElement>(
+ 'button, a, input, [role="button"], [tabindex]',
+ );
+ if (control == null) {
+ continue;
+ }
+ const named =
+ (control.getAttribute('aria-label') ?? '').trim() !== '' ||
+ control.hasAttribute('aria-labelledby') ||
+ (control.textContent ?? '').trim() !== '' ||
+ (control.getAttribute('title') ?? '').trim() !== '';
+ if (!named) {
+ warnOnce(
+ 'multi-selector:unnamed-action',
+ 'MultiSelector',
+ 'An option `action` renders a control with no accessible name. Give ' +
+ 'it a label: a screen reader reaches it through the action cell ' +
+ 'and has nothing to read.',
+ );
+ break;
+ }
+ }
+ });
const keepOpenProps = useKeepLayerOpenProps(popover.id, popover.isOpen);
// Open dropdown on mount when isDefaultOpen is true and interaction is allowed.
@@ -1521,9 +1625,16 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
// Multi-select combobox behavior — index-based, matching useCombobox pattern.
// sortedItems is the single source of truth for item order.
+ const getActionCellIdForActivate = useCallback(
+ (index: number) => `${listboxId}-item-${index}-action`,
+ [listboxId],
+ );
const {
highlightedIndex,
+ highlightedCell,
getItemId,
+ getActionCellId,
+ activeDescendantId,
onTriggerClick,
onKeyDown,
onItemMouseEnter,
@@ -1538,6 +1649,23 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
onClear: hasClear ? clearValues : undefined,
hasValue,
listboxId,
+ isGrid,
+ rowHasAction: useCallback(
+ (index: number) => sortedItems[index]?.action != null,
+ [sortedItems],
+ ),
+ onActivateAction: useCallback(
+ (index: number) => {
+ // Fire the caller's control as a press would: the first focusable
+ // thing in the action cell. Reading the rendered DOM, not the node.
+ const cell = document.getElementById(getActionCellIdForActivate(index));
+ const control = cell?.querySelector<HTMLElement>(
+ 'button, a, input, [role="button"], [tabindex]',
+ );
+ control?.click();
+ },
+ [getActionCellIdForActivate],
+ ),
});
// Highlight scrolling (and its hover/keyboard split) lives in useMultiCombobox.
@@ -1638,11 +1766,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
aria-expanded={surface.isOpen}
aria-controls={listboxId}
aria-autocomplete="list"
- aria-activedescendant={
- surface.isOpen && highlightedIndex >= 0
- ? getItemId(highlightedIndex)
- : undefined
- }
+ aria-activedescendant={activeDescendantId}
value={searchQuery}
onValueChange={handleSearchChange}
onContainerKeyDown={e => {
@@ -1694,6 +1818,17 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
onKeyDown(e);
return;
}
+ // In a grid with a row highlighted, Left/Right move between the
+ // row's cells (APG combobox with grid popup); with no row
+ // highlighted they keep moving the caret.
+ if (
+ isGrid &&
+ highlightedIndex >= 0 &&
+ (e.key === 'ArrowLeft' || e.key === 'ArrowRight')
+ ) {
+ onKeyDown(e);
+ return;
+ }
// Tab: when a query is showing the clear (✕) button, forward-tab
// moves focus to it (keeping the popup open) so the affordance is
// keyboard-reachable. Every other Tab dismisses the popup as usual.
@@ -1715,7 +1850,8 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
onKeyDown,
surface.isOpen,
highlightedIndex,
- getItemId,
+ activeDescendantId,
+ isGrid,
createQuery,
commitCreate,
t,
@@ -1757,11 +1893,30 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
</div>
);
+ const content = (
+ <>
+ {indicatorPosition === 'start' && checkbox}
+ {renderOption && !isSelectAll && !isCreate ? (
+ renderOption(item)
+ ) : (
+ <span {...stylex.props(styles.itemLabel)}>
+ {item.label ?? item.value}
+ </span>
+ )}
+ {indicatorPosition === 'end' && checkbox}
+ </>
+ );
+ const toggle = () => {
+ if (!item.disabled) {
+ handleNavigableToggle(item.value);
+ }
+ };
+
return (
<div
key={item.value}
id={getItemId(flatIndex)}
- role="option"
+ role={isGrid ? 'row' : 'option'}
aria-selected={isSelected}
aria-label={
isPartiallySelected
@@ -1770,13 +1925,21 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
})
: undefined
}
+ // In a grid the row is named by its option cell alone, so the
+ // caller's control is never folded into the row's name
+ // (spec:AST-058 AR2).
+ aria-labelledby={
+ isGrid && !isPartiallySelected
+ ? `${getItemId(flatIndex)}-option`
+ : undefined
+ }
aria-disabled={item.disabled}
- onClick={() => {
- if (!item.disabled) {
- handleNavigableToggle(item.value);
- }
- }}
- onMouseEnter={() => onItemMouseEnter(item, flatIndex)}
+ // In a grid the option cell is the click target, so a press on the
+ // action cell never toggles (spec:AST-058 FR4).
+ onClick={isGrid ? undefined : toggle}
+ onMouseEnter={
+ isGrid ? undefined : () => onItemMouseEnter(item, flatIndex)
+ }
{...mergeProps(
// One target for every dropdown row, carrying the row's size and
// runtime state so a theme can express "selected option at large"
@@ -1794,21 +1957,47 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
isSelectAll && styles.selectAllWrapper,
isHighlighted && styles.itemHighlighted,
item.disabled && styles.itemDisabled,
+ isGrid && styles.gridRow,
),
)}>
- {indicatorPosition === 'start' && checkbox}
- {renderOption && !isSelectAll && !isCreate ? (
- renderOption(item)
+ {isGrid ? (
+ <>
+ <div
+ role="gridcell"
+ id={`${getItemId(flatIndex)}-option`}
+ onClick={toggle}
+ onMouseEnter={() => onItemMouseEnter(item, flatIndex, 'option')}
+ {...stylex.props(styles.optionCell)}>
+ {content}
+ </div>
+ <div
+ role="gridcell"
+ id={getActionCellId(flatIndex)}
+ data-multi-selector-action-cell=""
+ onMouseEnter={
+ item.action != null
+ ? () => onItemMouseEnter(item, flatIndex, 'action')
+ : undefined
+ }
+ {...stylex.props(
+ styles.actionCell,
+ isHighlighted &&
+ highlightedCell === 'action' &&
+ styles.actionCellActive,
+ )}>
+ {isSelectAll || isCreate ? null : item.action}
+ </div>
+ </>
) : (
- <span {...stylex.props(styles.itemLabel)}>
- {item.label ?? item.value}
- </span>
+ content
)}
- {indicatorPosition === 'end' && checkbox}
</div>
);
},
[
+ isGrid,
+ highlightedCell,
+ getActionCellId,
renderOption,
indicatorPosition,
highlightedIndex,
@@ -1930,7 +2119,10 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
// children to option/group only — the old labeled Divider sat in the
// listbox as a stray role="separator".
elements.push(
- <div key={`section-${i}`} role="group" aria-label={option.title}>
+ <div
+ key={`section-${i}`}
+ role={isGrid ? 'rowgroup' : 'group'}
+ aria-label={option.title}>
{option.title && (
<div
aria-hidden="true"
@@ -1966,6 +2158,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
isLoading,
emptyText,
emptySearchText,
+ isGrid,
hasCreateRow,
]);
@@ -1994,7 +2187,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
<div
ref={listboxRef}
id={listboxId}
- role="listbox"
+ role={isGrid ? 'grid' : 'listbox'}
aria-multiselectable="true"
{...listboxLabelProps}
{...stylex.props(styles.listbox)}>
@@ -2007,7 +2200,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
<div
ref={listboxRef}
id={listboxId}
- role="listbox"
+ role={isGrid ? 'grid' : 'listbox'}
aria-multiselectable="true"
// The bottom sheet is rendered in a modal layer, so Chromium cannot
// reliably compute this listbox's name from the trigger outside that
@@ -2017,11 +2210,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
{...(surface.activePresentation === 'bottom-sheet'
? {'aria-label': label}
: listboxLabelProps)}
- aria-activedescendant={
- surface.isOpen && highlightedIndex >= 0
- ? getItemId(highlightedIndex)
- : undefined
- }
+ aria-activedescendant={activeDescendantId}
tabIndex={listboxOwnsKeyboard ? 0 : undefined}
onKeyDown={listboxOwnsKeyboard ? onKeyDown : undefined}
{...stylex.props(styles.listbox)}>
@@ -2108,7 +2297,9 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
? undefined
: surface.activePresentation === 'bottom-sheet'
? 'dialog'
- : 'listbox',
+ : isGrid
+ ? 'grid'
+ : 'listbox',
'aria-expanded': isEffectivelyReadOnly ? false : surface.isOpen,
'aria-controls': isEffectivelyReadOnly ? undefined : listboxId,
'aria-busy': isBusy || undefined,
@@ -2210,17 +2401,16 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
? undefined
: surface.activePresentation === 'bottom-sheet'
? 'dialog'
- : 'listbox'
+ : isGrid
+ ? 'grid'
+ : 'listbox'
}
aria-expanded={isEffectivelyReadOnly ? false : surface.isOpen}
aria-controls={isEffectivelyReadOnly ? undefined : listboxId}
aria-readonly={isEffectivelyReadOnly || undefined}
aria-activedescendant={
- !isEffectivelyReadOnly &&
- !hasSearch &&
- surface.isOpen &&
- highlightedIndex >= 0
- ? getItemId(highlightedIndex)
+ !isEffectivelyReadOnly && !hasSearch
+ ? activeDescendantId
: undefined
}
// With a disabledMessage the trigger keeps focusability via
diff --git a/packages/core/src/MultiSelector/OptionActions.a11y.chromium.spec.ts b/packages/core/src/MultiSelector/OptionActions.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..24cc610d75
--- /dev/null
+++ b/packages/core/src/MultiSelector/OptionActions.a11y.chromium.spec.ts
@@ -0,0 +1,199 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file OptionActions.a11y.chromium.spec.ts
+ * @input The `Core/MultiSelector` RowActions and RowActionsRtl stories in a
+ * built Storybook.
+ * @output Real-engine proof for option actions: the action is visible at rest
+ * beside its row (`spec:AST-058` FR8), the keyboard reaches it through the
+ * inline-end arrow in both directions and fires it with Enter, and the
+ * highlight follows a real mouse across rows and actions.
+ * @position Run with `pnpm test:a11y-contract`; paint, pointer paths and the
+ * active descendant as an engine exposes them are not jsdom claims.
+ */
+
+import {expect, test, type Locator, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+async function box(locator: Locator) {
+ const rect = await locator.boundingBox();
+ if (rect == null) {
+ throw new Error(`no box for ${String(locator)}`);
+ }
+ return rect;
+}
+
+async function litRows(page: Page): Promise<string[]> {
+ return page.evaluate(() => {
+ const rows = Array.from(
+ document.querySelectorAll<HTMLElement>('[role="row"]'),
+ );
+ const base = rows.find(r => r.textContent?.includes('P1'));
+ const baseBg = base
+ ? getComputedStyle(base).backgroundColor
+ : 'rgba(0, 0, 0, 0)';
+ return rows
+ .filter(r => getComputedStyle(r).backgroundColor !== baseBg)
+ .map(
+ r => r.querySelector('[role="gridcell"]')?.textContent?.trim() ?? '',
+ );
+ });
+}
+
+async function activeDescendant(page: Page): Promise<string | null> {
+ return page.evaluate(() => {
+ const id = document.activeElement?.getAttribute('aria-activedescendant');
+ if (!id) {
+ return null;
+ }
+ const el = document.getElementById(id);
+ if (!el) {
+ return 'missing';
+ }
+ // The row is named by its option cell; the action cell by the control in
+ // it. Report role + that name, not raw text (an icon's title would leak).
+ const role = el.getAttribute('role');
+ const name =
+ role === 'row'
+ ? (document.getElementById(el.getAttribute('aria-labelledby') ?? '')
+ ?.textContent ?? '')
+ : (el.querySelector('button')?.getAttribute('aria-label') ?? '');
+ return `${role}:${name.trim()}`;
+ });
+}
+
+test('actions are visible at rest, in their rows, inside the grid', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-multiselector--row-actions&viewMode=story`,
+ );
+ const grid = page.getByRole('grid');
+ await expect(grid).toBeVisible();
+ expect(await page.getByRole('listbox').count()).toBe(0);
+
+ for (const label of ['Bug', 'Design review', 'P0', 'P1']) {
+ const row = page.getByRole('row', {name: label});
+ const action = page.getByRole('button', {name: `Edit ${label}`});
+ await expect(action).toBeVisible();
+ // Inside its own row, not merely aligned with it.
+ expect(await row.locator('button').count()).toBe(1);
+ const r = await box(row);
+ const a = await box(action);
+ expect(Math.abs(r.y + r.height / 2 - (a.y + a.height / 2))).toBeLessThan(2);
+ expect(a.x + a.width).toBeLessThanOrEqual(r.x + r.width + 1);
+ }
+ expect(await page.getByRole('button', {name: 'Edit Docs'}).count()).toBe(0);
+ // Two cells per row, every row.
+ const shapes = await page.evaluate(() =>
+ Array.from(document.querySelectorAll('[role="row"]')).map(
+ r =>
+ Array.from(r.children).filter(
+ c => c.getAttribute('role') === 'gridcell',
+ ).length,
+ ),
+ );
+ expect(shapes.every(n => n === 2)).toBe(true);
+});
+
+test('the keyboard reaches an action through the inline-end arrow and fires it with Enter', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-multiselector--row-actions&viewMode=story`,
+ );
+ const search = page.getByRole('combobox');
+ await expect(search).toBeFocused();
+ await search.press('ArrowDown'); // select-all
+ await search.press('ArrowDown'); // Feature (no action)
+ await search.press('ArrowDown'); // Bug
+ await expect.poll(async () => activeDescendant(page)).toBe('row:Bug');
+ await search.press('ArrowRight');
+ await expect
+ .poll(async () => activeDescendant(page))
+ .toBe('gridcell:Edit Bug');
+ await search.press('Enter');
+ await expect(page.getByTestId('last-edited')).toHaveText('Bug');
+ // Selection untouched, panel open, highlight where it was.
+ await expect(page.getByRole('row', {name: 'Bug'})).toHaveAttribute(
+ 'aria-selected',
+ 'false',
+ );
+ await expect(page.getByRole('grid')).toBeVisible();
+ await expect
+ .poll(async () => activeDescendant(page))
+ .toBe('gridcell:Edit Bug');
+ await search.press('ArrowLeft');
+ await expect.poll(async () => activeDescendant(page)).toBe('row:Bug');
+});
+
+test('under RTL the inline-end arrow is ArrowLeft', async ({page}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-multiselector--row-actions-rtl&viewMode=story`,
+ );
+ const trigger = page.getByRole('combobox');
+ await expect(page.getByRole('grid')).toBeVisible();
+ await trigger.focus();
+ await trigger.press('ArrowDown');
+ await expect.poll(async () => activeDescendant(page)).toBe('row:Bug');
+ await trigger.press('ArrowRight');
+ await expect.poll(async () => activeDescendant(page)).toBe('row:Bug');
+ await trigger.press('ArrowLeft');
+ await expect
+ .poll(async () => activeDescendant(page))
+ .toBe('gridcell:Edit Bug');
+ // And the action is painted at the inline end: to the LEFT of the label.
+ const label = await box(page.getByText('Bug', {exact: true}));
+ const action = await box(page.getByRole('button', {name: 'Edit Bug'}));
+ expect(action.x + action.width).toBeLessThanOrEqual(label.x + 1);
+});
+
+test('the highlight follows a real mouse across rows and actions', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-multiselector--row-actions&viewMode=story`,
+ );
+ await expect(page.getByRole('grid')).toBeVisible();
+ const center = async (l: Locator) => {
+ const b = await box(l);
+ return {x: b.x + b.width / 2, y: b.y + b.height / 2};
+ };
+ const docs = await center(page.getByRole('row', {name: 'Docs'}));
+ const p0Action = await center(page.getByRole('button', {name: 'Edit P0'}));
+ const reviewAction = await center(
+ page.getByRole('button', {name: 'Edit Design review'}),
+ );
+
+ await page.mouse.move(docs.x, docs.y, {steps: 4});
+ await expect.poll(async () => litRows(page)).toEqual(['Docs']);
+ // Straight onto an action several rows lower: that row, not Docs.
+ await page.mouse.move(p0Action.x, p0Action.y, {steps: 12});
+ await expect.poll(async () => litRows(page)).toEqual(['P0']);
+ await expect
+ .poll(async () => activeDescendant(page))
+ .toBe('gridcell:Edit P0');
+ // Up the action column.
+ await page.mouse.move(reviewAction.x, reviewAction.y, {steps: 8});
+ await expect.poll(async () => litRows(page)).toEqual(['Design review']);
+ // Rest until the tooltip shows, then leave: nothing stale.
+ await expect(page.getByRole('tooltip')).toBeVisible({timeout: 3000});
+ await page.mouse.move(docs.x, docs.y, {steps: 10});
+ await expect.poll(async () => litRows(page)).toEqual(['Docs']);
+});
diff --git a/packages/core/src/MultiSelector/hooks.ts b/packages/core/src/MultiSelector/hooks.ts
index ea24b938da..cc49709962 100644
--- a/packages/core/src/MultiSelector/hooks.ts
+++ b/packages/core/src/MultiSelector/hooks.ts
@@ -13,6 +13,7 @@
*/
import {useCallback, useRef, useState} from 'react';
+import {isRtlElement} from '../hooks/isRtlElement';
import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';
import type {MultiSelectorOptionData} from './types';
@@ -36,15 +37,39 @@ interface UseMultiComboboxOptions {
*/
hasValue?: boolean;
listboxId: string;
+ /**
+ * Whether the popup is a grid (`spec:AST-058`): rows pair an option cell
+ * with an action cell, the inline-end arrow moves the highlight from the
+ * option to the action and the inline-start arrow back, and Enter on the
+ * action cell activates the caller's control instead of toggling.
+ */
+ isGrid?: boolean;
+ /** Whether the row at `index` carries an action to move to. */
+ rowHasAction?: (index: number) => boolean;
+ /** Activate the control in the highlighted row's action cell. */
+ onActivateAction?: (index: number) => void;
}
+/** Which cell of the highlighted row the highlight is on. */
+export type MultiComboboxCell = 'option' | 'action';
+
interface UseMultiComboboxResult {
highlightedIndex: number;
setHighlightedIndex: (index: number) => void;
+ /** `'action'` only in a grid, while the highlight is on the action cell. */
+ highlightedCell: MultiComboboxCell;
getItemId: (index: number) => string;
+ /** Id of the action cell of the row at `index` (the active descendant there). */
+ getActionCellId: (index: number) => string;
+ /** The element `aria-activedescendant` names, or undefined. */
+ activeDescendantId: string | undefined;
onTriggerClick: () => void;
onKeyDown: (e: React.KeyboardEvent) => void;
- onItemMouseEnter: (item: MultiSelectorOptionData, index: number) => void;
+ onItemMouseEnter: (
+ item: MultiSelectorOptionData,
+ index: number,
+ cell?: MultiComboboxCell,
+ ) => void;
}
/**
@@ -64,8 +89,18 @@ export function useMultiCombobox({
onClear,
hasValue = false,
listboxId,
+ isGrid = false,
+ rowHasAction,
+ onActivateAction,
}: UseMultiComboboxOptions): UseMultiComboboxResult {
- const [highlightedIndex, setHighlightedIndex] = useState<number>(-1);
+ const [highlightedIndex, setHighlightedIndexState] = useState<number>(-1);
+ const [highlightedCell, setHighlightedCell] =
+ useState<MultiComboboxCell>('option');
+ // Every move between rows lands on the option cell (spec:AST-058 FR5).
+ const setHighlightedIndex = useCallback((index: number) => {
+ setHighlightedIndexState(index);
+ setHighlightedCell('option');
+ }, []);
const [typeahead, setTypeahead] = useState('');
const typeaheadTimeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(
undefined,
@@ -75,6 +110,16 @@ export function useMultiCombobox({
(index: number) => `${listboxId}-item-${index}`,
[listboxId],
);
+ const getActionCellId = useCallback(
+ (index: number) => `${listboxId}-item-${index}-action`,
+ [listboxId],
+ );
+ const activeDescendantId =
+ isOpen && highlightedIndex >= 0
+ ? isGrid && highlightedCell === 'action'
+ ? getActionCellId(highlightedIndex)
+ : getItemId(highlightedIndex)
+ : undefined;
const getEnabledIndices = useCallback(() => {
return selectableItems
@@ -85,7 +130,7 @@ export function useMultiCombobox({
const closeAndReset = useCallback(() => {
setHighlightedIndex(-1);
onClose();
- }, [onClose]);
+ }, [onClose, setHighlightedIndex]);
const onTriggerClick = useCallback(() => {
if (isDisabled) {
@@ -99,7 +144,14 @@ export function useMultiCombobox({
setHighlightedIndex(0);
}
}
- }, [isDisabled, isOpen, onOpen, closeAndReset, hasSearch]);
+ }, [
+ isDisabled,
+ isOpen,
+ onOpen,
+ closeAndReset,
+ hasSearch,
+ setHighlightedIndex,
+ ]);
// The scroll effect lives here, the highlight owner, so the hover/keyboard
// split is shared instead of re-implemented in MultiSelector.tsx (#6077).
@@ -111,9 +163,21 @@ export function useMultiCombobox({
});
const onItemMouseEnter = useCallback(
- (item: MultiSelectorOptionData, index: number) => {
+ (
+ item: MultiSelectorOptionData,
+ index: number,
+ cell: MultiComboboxCell = 'option',
+ ) => {
+ // The action cell is the caller's control, usable whether or not the
+ // option itself is disabled (spec:AST-058 FR4).
+ if (cell === 'action') {
+ highlightOnHover(index);
+ setHighlightedCell('action');
+ return;
+ }
if (!item.disabled) {
highlightOnHover(index);
+ setHighlightedCell('option');
}
},
[highlightOnHover],
@@ -127,6 +191,33 @@ export function useMultiCombobox({
const enabledIndices = getEnabledIndices();
+ // In a grid the horizontal arrows move between the row's two cells,
+ // following visual direction under RTL (spec:AST-058 FR5). Outside a
+ // grid, or with no row highlighted, they keep their default meaning
+ // (the caret, in a search input).
+ if (isGrid && isOpen && highlightedIndex >= 0) {
+ const isRtl = isRtlElement(e.currentTarget as HTMLElement);
+ const inlineEnd = isRtl ? 'ArrowLeft' : 'ArrowRight';
+ const inlineStart = isRtl ? 'ArrowRight' : 'ArrowLeft';
+ if (e.key === inlineEnd) {
+ if (
+ highlightedCell === 'option' &&
+ rowHasAction?.(highlightedIndex) === true
+ ) {
+ e.preventDefault();
+ setHighlightedCell('action');
+ }
+ return;
+ }
+ if (e.key === inlineStart) {
+ if (highlightedCell === 'action') {
+ e.preventDefault();
+ setHighlightedCell('option');
+ }
+ return;
+ }
+ }
+
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
@@ -165,6 +256,12 @@ export function useMultiCombobox({
}
e.preventDefault();
if (isOpen && highlightedIndex >= 0) {
+ if (isGrid && highlightedCell === 'action') {
+ // The highlight is on the caller's control: fire it, and only
+ // it — the selection does not change (spec:AST-058 FR4).
+ onActivateAction?.(highlightedIndex);
+ break;
+ }
const item = selectableItems[highlightedIndex];
if (item && !item.disabled) {
onToggle(item.value);
@@ -266,6 +363,11 @@ export function useMultiCombobox({
closeAndReset,
selectableItems,
highlightedIndex,
+ highlightedCell,
+ isGrid,
+ rowHasAction,
+ onActivateAction,
+ setHighlightedIndex,
onToggle,
getEnabledIndices,
typeahead,
@@ -278,7 +380,10 @@ export function useMultiCombobox({
return {
highlightedIndex,
setHighlightedIndex,
+ highlightedCell,
getItemId,
+ getActionCellId,
+ activeDescendantId,
onTriggerClick,
onKeyDown,
onItemMouseEnter,
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index 24f5f2ede6..ea7faf5d88 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -4644,3 +4644,38 @@ describe('Selector in a narrow row', () => {
expect(getComputedStyle(root).minWidth).toBe('0');
});
});
+
+describe('Selector and option actions (not adopted)', () => {
+ it('renders the option without the control and warns in development', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const user = userEvent.setup();
+ render(
+ <Selector
+ label="Fruit"
+ options={[
+ {
+ value: 'apple',
+ label: 'Apple',
+ action: <button type="button">Edit Apple</button>,
+ },
+ ]}
+ value={undefined}
+ onChange={() => {}}
+ />,
+ );
+ await user.click(screen.getByRole('combobox', {name: 'Fruit'}));
+ expect(
+ screen.queryByRole('button', {name: 'Edit Apple', hidden: true}),
+ ).toBeNull();
+ expect(
+ screen.getByRole('option', {name: 'Apple', hidden: true}),
+ ).toBeInTheDocument();
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringMatching(/Selector[\s\S]*action/),
+ );
+ } finally {
+ warn.mockRestore();
+ }
+ });
+});
diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx
index 73bc817452..147fda18f4 100644
--- a/packages/core/src/Selector/Selector.tsx
+++ b/packages/core/src/Selector/Selector.tsx
@@ -79,6 +79,7 @@ import {useResolvedRequired} from '../hooks/useResolvedRequired';
import {SelectorOption} from './SelectorOption';
import {SelectorRowLayoutContext} from './SelectorRowLayoutContext';
import {getInputARIA, isImeKeyEvent, mergeProps} from '../utils';
+import {warnOnce} from '../utils/devWarning';
import {useSize} from '../SizeContext/SizeContext';
import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
@@ -995,6 +996,21 @@ export function Selector<T extends SelectorOptionType>(
[options],
);
+ // `action` is declared on the shared option type for `MultiSelector`;
+ // this listbox has not adopted it, so it renders the option without the
+ // control and says so (spec:AST-058 FR9) rather than nesting a control in
+ // an option.
+ useEffect(() => {
+ if (selectableItems.some(item => item.action != null)) {
+ warnOnce(
+ 'selector:option-action',
+ 'Selector',
+ 'An option carries `action`, which Selector does not render yet; the ' +
+ 'option is shown without it. MultiSelector renders option actions.',
+ );
+ }
+ }, [selectableItems]);
+
// Filter items by search query
const filteredItems = useMemo(
() => filterOptionsByQuery(selectableItems, searchQuery),
diff --git a/packages/core/src/Selector/types.ts b/packages/core/src/Selector/types.ts
index df15278705..dfb1252186 100644
--- a/packages/core/src/Selector/types.ts
+++ b/packages/core/src/Selector/types.ts
@@ -20,6 +20,16 @@ export type SelectorOptionData = {
description?: ReactNode;
disabled?: boolean;
icon?: ReactNode | IconType;
+ /**
+ * The option's secondary control — an Edit button beside a saved label —
+ * as one node the caller renders and names; the host only places it. In
+ * `MultiSelector`, any option carrying one turns the popup into a grid whose
+ * rows pair the option with its action, reachable by pointer, touch, the
+ * inline-end arrow, and a screen reader (`spec:AST-058`). `Selector` does
+ * not render it yet and warns in development when an option carries one.
+ * Absent and `null` mean the same: none.
+ */
+ action?: ReactNode;
};
/**
diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx
index 2cb97f75a6..e8d241c0b0 100644
--- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx
+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx
@@ -484,7 +484,9 @@ describe('useTableRowExpansion (detail panel)', () => {
key: 'name',
header: 'Name',
renderCell: item => (
- <div contentEditable="false" data-testid={`readonly-${item.id}`}>
+ <div
+ contentEditable="false"
+ data-testid={`readonly-${item.id}`}>
{item.name}
</div>
),
diff --git a/packages/core/src/Table/plugins/tree/useTableTreeData.test.tsx b/packages/core/src/Table/plugins/tree/useTableTreeData.test.tsx
index 167da95ab0..7dc064d9c1 100644
--- a/packages/core/src/Table/plugins/tree/useTableTreeData.test.tsx
+++ b/packages/core/src/Table/plugins/tree/useTableTreeData.test.tsx
@@ -304,7 +304,10 @@ describe('useTableTreeData — row-click expansion', () => {
data: fileTree,
idKey: 'id',
});
- const tree = useTableTreeData({...treeConfig, hasRowClickExpansion: true});
+ const tree = useTableTreeData({
+ ...treeConfig,
+ hasRowClickExpansion: true,
+ });
return (
<Table
data={visibleData}
@@ -336,7 +339,10 @@ describe('useTableTreeData — row-click expansion', () => {
data: fileTree,
idKey: 'id',
});
- const tree = useTableTreeData({...treeConfig, hasRowClickExpansion: true});
+ const tree = useTableTreeData({
+ ...treeConfig,
+ hasRowClickExpansion: true,
+ });
return (
<Table
data={visibleData}
@@ -368,7 +374,10 @@ describe('useTableTreeData — row-click expansion', () => {
data: fileTree,
idKey: 'id',
});
- const tree = useTableTreeData({...treeConfig, hasRowClickExpansion: true});
+ const tree = useTableTreeData({
+ ...treeConfig,
+ hasRowClickExpansion: true,
+ });
return (
<Table
data={visibleData}
@@ -377,7 +386,9 @@ describe('useTableTreeData — row-click expansion', () => {
key: 'name',
header: 'Name',
renderCell: item => (
- <div contentEditable="false" data-testid={`readonly-${item.id}`}>
+ <div
+ contentEditable="false"
+ data-testid={`readonly-${item.id}`}>
{item.name}
</div>
),
diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsx
index 3515872ee2..5153617c20 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.tsx
+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx
@@ -55,6 +55,7 @@ import {
groupItems,
mergeProps,
} from '../utils';
+import {warnOnce} from '../utils/devWarning';
import type {BaseProps} from '../BaseProps';
import type {SearchableItem, SearchSource} from './types';
import {themeProps} from '../utils/themeProps';
@@ -531,6 +532,20 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
const [query, setQuery] = useState('');
const [results, setResults] = useState<T[]>([]);
+
+ // `action` is declared on `SearchableItem` for the grid-adopting hosts;
+ // this panel has not adopted it, so it renders the item without the
+ // control and says so (spec:AST-058 FR9).
+ useEffect(() => {
+ if (results.some(item => item.action != null)) {
+ warnOnce(
+ 'base-typeahead:item-action',
+ 'BaseTypeahead',
+ 'A result carries `action`, which the typeahead panel does not render ' +
+ 'yet; the item is shown without it.',
+ );
+ }
+ }, [results]);
const [highlightedIndex, setHighlightedIndex] = useState(-1);
const [isLoading, setIsLoading] = useState(false);
const [hasSearched, setHasSearched] = useState(false);
diff --git a/packages/core/src/Typeahead/types.ts b/packages/core/src/Typeahead/types.ts
index 5fd29464cb..e629062db3 100644
--- a/packages/core/src/Typeahead/types.ts
+++ b/packages/core/src/Typeahead/types.ts
@@ -38,6 +38,15 @@ export interface SearchableItem<TAuxData = unknown> {
*/
label: string;
+ /**
+ * The item's secondary control as one node the caller renders and names;
+ * the same key with the same type as `SelectorOptionData.action`
+ * (`spec:AST-058`). The typeahead panel does not render it yet and warns in
+ * development when an item carries one. Absent and `null` mean the same:
+ * none.
+ */
+ action?: ReactNode;
+
/**
* Pre-rendered element for SSR compatibility.
* When provided, takes priority over `renderItem` and default label rendering.
@@ -82,9 +91,7 @@ export interface SearchableItem<TAuxData = unknown> {
* };
* ```
*/
-export interface SearchSource<
- T extends SearchableItem = SearchableItem,
-> {
+export interface SearchSource<T extends SearchableItem = SearchableItem> {
/**
* Called on query change. Returns matching items.
* Can be synchronous or asynchronous.