Skip to content

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

TypeScript

feat(MultiSelector): trigger render prop, handleRef and onOpenChange — hang the panel off a control the caller renders (#6689)

Christopher Chedeaue8fcf3c36986
diff --git a/.changeset/multi-selector-trigger.md b/.changeset/multi-selector-trigger.md
new file mode 100644
index 0000000000..3d400c012f
--- /dev/null
+++ b/.changeset/multi-selector-trigger.md
@@ -0,0 +1,16 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `MultiSelector` can hang off a control the caller renders.
+
+A new `renderTrigger` render prop renders the control the panel hangs off — a glyph
+in a list row, a chip, an icon button — in place of the selector's own field
+and button. Spread the given props onto it; the listbox is anchored to it,
+named by `label`, takes focus on open, and focus returns to the control on
+close. `handleRef` (`open`/`close`/`toggle`/`isOpen`, the `ComplexSelectorHandle`
+shape) and `onOpenChange` let the caller open the panel from a keystroke
+elsewhere and observe every open and close. All three are off by default;
+existing selectors are unchanged.
+
+@vjeux @cixzhang
diff --git a/packages/core/src/MultiSelector/MultiSelector.doc.mjs b/packages/core/src/MultiSelector/MultiSelector.doc.mjs
index ce54fde87c..363954dad1 100644
--- a/packages/core/src/MultiSelector/MultiSelector.doc.mjs
+++ b/packages/core/src/MultiSelector/MultiSelector.doc.mjs
@@ -383,6 +383,24 @@ export const docs = {
description: 'Whether the dropdown starts open on mount.',
default: 'false',
},
+ {
+ name: 'renderTrigger',
+ type: '(props: MultiSelectorRenderTriggerProps) => ReactNode',
+ description:
+ "Render the control the panel hangs off — a glyph in a list row, a chip, an icon button — instead of the selector's own field and button. Spread the given props ({ref, id, onClick, onKeyDown, onFocus, aria-haspopup, aria-expanded, aria-controls, aria-busy}) onto it; the listbox is anchored to that control and named by `label`. The field chrome (Field, status, clear, spinner) is not rendered. Pair with handleRef to open from a keystroke elsewhere.",
+ },
+ {
+ name: 'handleRef',
+ type: 'React.Ref<MultiSelectorHandle>',
+ description:
+ 'Imperative handle with open(), close(), toggle() and isOpen(). Prefer it over mirroring open state in the parent; the selector owns its visibility.',
+ },
+ {
+ name: 'onOpenChange',
+ type: '(isOpen: boolean) => void',
+ description:
+ 'Called whenever the panel opens or closes, however it happened: the trigger, the keyboard, a light dismiss, Escape, or the handle.',
+ },
{
name: 'xstyle',
type: 'StyleXStyles',
@@ -493,6 +511,10 @@ export const docsZh = {
'状态消息的放置方式:attached 直接叠加在输入框下方;detached 作为独立元素浮于下方并留有间距。',
renderOption:
'每个可选选项的自定义渲染函数。不会用于分隔线、分组或全选行。',
+ renderTrigger:
+ '由调用方渲染面板的触发控件(替代选择器自带的字段和按钮);将传入的属性展开到该控件上,列表框将锚定于它并由 label 命名。',
+ handleRef: '命令式句柄:open()、close()、toggle()、isOpen()。',
+ onOpenChange: '面板每次打开或关闭时触发,无论由何种方式引起。',
presentation:
'选项列表的呈现方式:锚定弹出框、底部抽屉,或根据紧凑触控屏自适应。',
xstyle: '布局自定义的 StyleX 样式,必须是 stylex.create() 值。',
@@ -635,6 +657,10 @@ export const docsDense = {
'status message placement; ghost detaches attached by default; use tooltip for compact toolbars.',
renderOption:
'custom render fn per selectable option; not dividers/sections/select-all',
+ renderTrigger:
+ 'caller-rendered opener replacing the field+button; spread the given props; listbox anchored to it, named by label',
+ handleRef: 'imperative open()/close()/toggle()/isOpen()',
+ onOpenChange: 'fires on every open/close, whatever caused it',
presentation:
'popover, bottom-sheet, or compact-touch adaptive presentation',
xstyle: 'StyleX layout styles; stylex.create() only',
diff --git a/packages/core/src/MultiSelector/MultiSelector.spec.md b/packages/core/src/MultiSelector/MultiSelector.spec.md
index d9b238da03..3dfd71aaa0 100644
--- a/packages/core/src/MultiSelector/MultiSelector.spec.md
+++ b/packages/core/src/MultiSelector/MultiSelector.spec.md
@@ -53,7 +53,13 @@ behavior.
affordances. `isDisabled` takes precedence when both are set.
- Existing DOM, styling, targets, and public API remain unchanged when the prop is
omitted.
-- Controlled/uncontrolled behavior: unchanged
+- `renderTrigger`, `handleRef`, and `onOpenChange` are additive and absent by
+ default. When omitted, DOM, styling, targets, keyboard behavior, and public
+ API remain unchanged. With `renderTrigger`, the caller-rendered control replaces
+ the Field shell and Trigger by the caller's choice, not as a change to the
+ released default.
+- Controlled/uncontrolled behavior: unchanged. Open state stays owned by the
+ component; `handleRef` drives it and `onOpenChange` reports it.
- Migration decision: none
Consumer migration instructions belong in consumer docs and release notes.
@@ -92,21 +98,23 @@ Consumer migration instructions belong in consumer docs and release notes.
This table names the additive concept introduced by `spec:AST-011`. Complete prop
syntax and examples remain in `MultiSelector.doc.mjs`.
-| Concept | Closed values or states | Meaning | Availability | Default | Owner | Stability | Invalid-value behavior |
-| --------------- | ----------------------- | --------------------------------------------------------- | -------------- | ------- | ------ | --------- | ---------------------- |
-| read-only state | `false`, `true` | Preserves and submits values without selection affordance | Closed trigger | `false` | Caller | additive | Boolean normalization |
+| Concept | Closed values or states | Meaning | Availability | Default | Owner | Stability | Invalid-value behavior |
+| --------------- | ------------------------------- | --------------------------------------------------------------------------------------------------- | ----------------------------- | ------- | ------ | --------- | ------------------------------------------------------------ |
+| read-only state | `false`, `true` | Preserves and submits values without selection affordance | Closed trigger | `false` | Caller | additive | Boolean normalization |
+| anchored mode | `renderTrigger` absent, present | Caller-rendered control replaces Field shell and Trigger; panel anchored to it and named by `label` | Pointer popup and Touch sheet | absent | Caller | additive | Render prop must return the control carrying the given props |
## 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 |
+| 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 |
### Allowed variation
@@ -155,6 +163,12 @@ accessible description also announces that state. Search and non-search modes us
the same read-only combobox semantics because neither exposes a search control in
this state.
+With `renderTrigger`, the caller's control carries `aria-haspopup`, `aria-expanded`,
+and `aria-controls` for the listbox, the listbox carries `aria-label` from
+`label` instead of `aria-labelledby` the trigger, and the listbox is the
+focused element that owns arrow, Enter, Escape, and typeahead keys while open,
+so an anchor that cannot take focus still leaves a keyboard path.
+
## Design relationships
| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
@@ -261,14 +275,15 @@ 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` |
-| 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` |
+| 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` |
Existing component tests directly assert the Trigger, Indicator icon, Search row,
Option row, Section heading, Empty state, and Pointer popup targets. Presentation
@@ -279,8 +294,17 @@ owner evidence rather than new MultiSelector targets.
## Decision log
-None. This draft records current facts and introduces no component-local design,
-API, theming, or layer-system decision.
+- **DEC-1 — Anchored mode through `renderTrigger` + `handleRef`, not a controlled
+ `isOpen`.** A picker anchored in a row the caller owns (a link row whose
+ opener is a presentational glyph) cannot host the Field shell or a nested
+ button. The caller renders the control and spreads the given props; the
+ component keeps owning open state, and `handleRef`/`onOpenChange` open it
+ from a keystroke elsewhere and report every change — the rule already written
+ on `ComplexSelectorHandle`. Rejected: an `anchorRef` plus controlled
+ `isOpen`, which mirrors open state in the parent and reintroduces the focus
+ pitfalls that rule names.
+
+ **Decider:** `cixzhang`, 2026-10-03
## Open questions
diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsx
index 955be97e7a..911285543d 100644
--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx
@@ -20,7 +20,8 @@ import {
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import * as stylex from '@stylexjs/stylex';
-import {MultiSelector} from './MultiSelector';
+import {MultiSelector, type MultiSelectorHandle} from './MultiSelector';
+import {useRef} from 'react';
import {Icon} from '../Icon';
import {InternationalizationProvider} from '../i18n';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
@@ -3228,3 +3229,273 @@ describe('MultiSelector popup theme target', () => {
);
});
});
+
+describe('MultiSelector trigger render prop', () => {
+ const OPTIONS = [
+ {value: 'bug', label: 'Bug'},
+ {value: 'feature', label: 'Feature'},
+ {value: 'docs', label: 'Docs'},
+ ];
+
+ it('renders the caller control instead of the field and button', () => {
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ renderTrigger={props => (
+ <button type="button" {...props}>
+ Pick labels
+ </button>
+ )}
+ />,
+ );
+ const opener = screen.getByRole('button', {name: 'Pick labels'});
+ expect(opener).toHaveAttribute('aria-haspopup', 'listbox');
+ expect(opener).toHaveAttribute('aria-expanded', 'false');
+ expect(opener).toHaveAttribute('aria-controls');
+ // No field chrome: exactly one button, and no Field label element.
+ expect(screen.getAllByRole('button')).toHaveLength(1);
+ expect(screen.queryByText('Labels')).toBeNull();
+ });
+
+ it('opens against the caller control and names the listbox by label', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={['bug']}
+ onChange={() => {}}
+ renderTrigger={props => (
+ <button type="button" {...props}>
+ Pick labels
+ </button>
+ )}
+ />,
+ );
+ const opener = screen.getByRole('button', {name: 'Pick labels'});
+ await user.click(opener);
+
+ expect(opener).toHaveAttribute('aria-expanded', 'true');
+ const listbox = screen.getByRole('listbox', {name: 'Labels', ...h});
+ expect(opener.getAttribute('aria-controls')).toBe(listbox.id);
+ expect(screen.getAllByRole('option', h)).toHaveLength(3);
+ expect(screen.getByRole('option', {name: 'Bug', ...h})).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ });
+
+ it('the listbox owns the keyboard once open and toggles on Enter', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={onChange}
+ renderTrigger={props => (
+ <button type="button" {...props}>
+ Pick labels
+ </button>
+ )}
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Pick labels'}));
+ const listbox = screen.getByRole('listbox', h);
+ expect(listbox).toHaveAttribute('tabindex', '0');
+ await waitFor(() => expect(listbox).toHaveFocus());
+
+ // Opening by click highlights the first option; Enter toggles it.
+ fireEvent.keyDown(listbox, {key: 'ArrowDown'});
+ fireEvent.keyDown(listbox, {key: 'Enter'});
+ expect(onChange).toHaveBeenCalledWith(['feature']);
+ });
+
+ it('handleRef opens and closes the panel and onOpenChange reports it', async () => {
+ const onOpenChange = vi.fn();
+ function Harness() {
+ const handleRef = useRef<MultiSelectorHandle>(null);
+ return (
+ <>
+ <button type="button" onClick={() => handleRef.current?.open()}>
+ open from outside
+ </button>
+ <button type="button" onClick={() => handleRef.current?.close()}>
+ close from outside
+ </button>
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ handleRef={handleRef}
+ onOpenChange={onOpenChange}
+ renderTrigger={props => (
+ <button type="button" {...props}>
+ anchor
+ </button>
+ )}
+ />
+ </>
+ );
+ }
+ const user = userEvent.setup();
+ render(<Harness />);
+ const anchor = screen.getByRole('button', {name: 'anchor'});
+ expect(anchor).toHaveAttribute('aria-expanded', 'false');
+ expect(onOpenChange).not.toHaveBeenCalled();
+
+ await user.click(screen.getByRole('button', {name: 'open from outside'}));
+ expect(anchor).toHaveAttribute('aria-expanded', 'true');
+ expect(onOpenChange).toHaveBeenLastCalledWith(true);
+
+ await user.click(screen.getByRole('button', {name: 'close from outside'}));
+ await waitFor(() => {
+ expect(anchor).toHaveAttribute('aria-expanded', 'false');
+ });
+ expect(onOpenChange).toHaveBeenLastCalledWith(false);
+ expect(onOpenChange).toHaveBeenCalledTimes(2);
+ });
+
+ it('the handle does not open a disabled selector', () => {
+ const handleRef = {current: null as MultiSelectorHandle | null};
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ isDisabled
+ handleRef={handleRef}
+ renderTrigger={props => (
+ <button type="button" {...props}>
+ anchor
+ </button>
+ )}
+ />,
+ );
+ act(() => {
+ handleRef.current?.open();
+ });
+ expect(handleRef.current?.isOpen()).toBe(false);
+ expect(screen.getByRole('button', {name: 'anchor'})).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ });
+});
+
+describe('MultiSelector renderTrigger — read-only', () => {
+ it("a read-only selector advertises no panel on the caller's control", () => {
+ // spec:AST-011 FR4. A read-only selector has no surface to open, so a
+ // control that says "collapsed, has popup" sends a screen-reader user
+ // to press Enter on something that cannot respond — with nothing to
+ // tell them the value is read-only rather than the control broken.
+ const onOpen = vi.fn();
+ render(
+ <MultiSelector
+ label="Labels"
+ value={['a']}
+ onChange={() => {}}
+ isReadOnly
+ options={[
+ {value: 'a', label: 'Alpha'},
+ {value: 'b', label: 'Beta'},
+ ]}
+ renderTrigger={props => (
+ <button type="button" {...props} onClick={onOpen}>
+ Labels
+ </button>
+ )}
+ />,
+ );
+
+ const trigger = screen.getByRole('button', {name: 'Labels'});
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(trigger).not.toHaveAttribute('aria-haspopup');
+ expect(trigger).not.toHaveAttribute('aria-controls');
+ // Withholding the disclosure attributes stops the control lying about a
+ // panel; this says why it does not open, which the field path conveys
+ // through chrome the caller's control does not have.
+ expect(trigger).toHaveAttribute('aria-readonly', 'true');
+ });
+
+ it('still advertises the panel when the selector is not read-only', () => {
+ render(
+ <MultiSelector
+ label="Labels"
+ value={[]}
+ onChange={() => {}}
+ options={[{value: 'a', label: 'Alpha'}]}
+ renderTrigger={props => (
+ <button type="button" {...props}>
+ Labels
+ </button>
+ )}
+ />,
+ );
+
+ const trigger = screen.getByRole('button', {name: 'Labels'});
+ expect(trigger).toHaveAttribute('aria-haspopup', 'listbox');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(trigger).toHaveAttribute('aria-controls');
+ });
+});
+
+describe('MultiSelector renderTrigger — focus return', () => {
+ it('returns focus to a control that takes no focus of its own', async () => {
+ // A glyph is not keyboard-openable, but when it IS opened by pointer the
+ // panel still has to give focus back somewhere the person recognises.
+ // Without the fallback focus lands on the body and they lose their place.
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Labels"
+ value={[]}
+ onChange={() => {}}
+ options={[
+ {value: 'a', label: 'Alpha'},
+ {value: 'b', label: 'Beta'},
+ ]}
+ renderTrigger={props => (
+ <span {...props} data-testid="glyph">
+ #
+ </span>
+ )}
+ />,
+ );
+
+ const glyph = screen.getByTestId('glyph');
+ expect(glyph).toHaveAttribute('tabindex', '-1');
+
+ await user.click(glyph);
+ await waitFor(() => expect(glyph).toHaveAttribute('aria-expanded', 'true'));
+ await user.keyboard('{Escape}');
+ await waitFor(() => expect(glyph).toHaveFocus());
+ expect(document.body).not.toHaveFocus();
+ });
+
+ it('leaves a real control\u2019s own focusability alone', () => {
+ render(
+ <MultiSelector
+ label="Labels"
+ value={[]}
+ onChange={() => {}}
+ options={[{value: 'a', label: 'Alpha'}]}
+ renderTrigger={props => (
+ <button type="button" {...props}>
+ Labels
+ </button>
+ )}
+ />,
+ );
+
+ expect(screen.getByRole('button', {name: 'Labels'})).not.toHaveAttribute(
+ 'tabindex',
+ );
+ });
+});
diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsx
index e8862477c2..419922439e 100644
--- a/packages/core/src/MultiSelector/MultiSelector.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.tsx
@@ -20,6 +20,7 @@ import React, {
useCallback,
useEffect,
useId,
+ useImperativeHandle,
useMemo,
useOptimistic,
useRef,
@@ -72,6 +73,7 @@ import {
import {useMultiCombobox} from './hooks';
import {getInputARIA, isImeKeyEvent, mergeProps} from '../utils';
import {useAnnounce} from '../hooks/useAnnounce';
+import {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector';
import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';
import {useResolvedRequired} from '../hooks/useResolvedRequired';
import type {BaseProps} from '../BaseProps';
@@ -438,6 +440,59 @@ export type MultiSelectorStatusType = 'warning' | 'error' | 'success';
export type {MultiSelectorStatus};
+/**
+ * Props the `renderTrigger` render prop hands to the control the caller
+ * renders.
+ * Spread them onto that control: it becomes the panel's anchor, the element
+ * focus returns to, and the control that announces the panel's state.
+ */
+export interface MultiSelectorRenderTriggerProps {
+ /** Attaches the control as the panel's anchor and focus-return target. */
+ ref: (element: HTMLElement | null) => void;
+ /** The id the field would have given its own button. */
+ id: string;
+ /**
+ * Opening handlers, present only when there is a panel to open. A
+ * read-only selector withholds them, so spreading these props onto a
+ * control gives it no opener rather than a dead one.
+ */
+ onClick?: (event: React.MouseEvent<HTMLElement>) => void;
+ onKeyDown?: (event: React.KeyboardEvent<HTMLElement>) => void;
+ onFocus: (event: React.FocusEvent<HTMLElement>) => void;
+ /**
+ * Disclosure state. A read-only selector has no surface to disclose, so
+ * `aria-haspopup` and `aria-controls` are absent and `aria-expanded` is
+ * `false` (`spec:AST-011` FR4).
+ */
+ 'aria-haspopup'?: 'listbox' | 'dialog';
+ 'aria-expanded': boolean;
+ 'aria-controls'?: string;
+ 'aria-busy': boolean | undefined;
+ /**
+ * `true` when the selector is read-only, so the caller's control can show
+ * that state the way its own design calls for.
+ */
+ 'aria-readonly'?: boolean;
+}
+
+/**
+ * Imperative control surface for MultiSelector, accessed via the `handleRef`
+ * prop. Methods drive the same popover machinery as the built-in trigger, so
+ * they respect focus restoration, light dismiss, and Escape. Pair with
+ * `onOpenChange` to observe every open and close, including the ones the
+ * selector performs itself. Same shape as `ComplexSelectorHandle`.
+ */
+export interface MultiSelectorHandle {
+ /** Open the panel. No-op when disabled, read-only, or already open. */
+ open(): void;
+ /** Close the panel. Restores focus to the trigger. */
+ close(): void;
+ /** Toggle the panel open or closed. */
+ toggle(): void;
+ /** Whether the panel is currently open. Reads live state. */
+ isOpen(): boolean;
+}
+
export interface MultiSelectorSelectedItem {
value: string;
label: string;
@@ -705,6 +760,56 @@ export interface MultiSelectorProps<
*/
isDefaultOpen?: boolean;
+ /**
+ * Render the control the panel hangs off — a glyph in a list row, a chip,
+ * an icon button — instead of the selector's own field and button. Spread
+ * the given props onto it; the listbox is then anchored to and labelled by
+ * that control, and `label` names the listbox for assistive technology.
+ * The field chrome (`Field`, status, clear button, spinner) is not
+ * rendered; the caller owns the opener. Pair with `handleRef` to open the
+ * panel from a keystroke elsewhere.
+ *
+ * Hover and pressed paint stay yours. The open state reaches your control
+ * as `aria-expanded` on the given props, so style it from the rendered
+ * attribute. A pressed look keyed to `:active` is not a substitute:
+ * `:active` does not behave the same under a coarse pointer, which is why
+ * menu rows drop coarse-pointer `:active` paint entirely.
+ *
+ * A read-only selector has no panel to open, so the disclosure attributes
+ * and the opening handlers are withheld: your control reports
+ * `aria-expanded="false"` and points at nothing.
+ *
+ * @example
+ * ```
+ * <MultiSelector
+ * label="Labels"
+ * renderTrigger={props => <IconButton icon="tag" label="Labels" {...props} />}
+ * …
+ * />
+ * ```
+ *
+ * @example
+ * ```
+ * // Styling the open state from the rendered attribute:
+ * // .my-trigger[aria-expanded='true'] { background: var(--color-overlay-pressed); }
+ * ```
+ */
+ renderTrigger?: (props: MultiSelectorRenderTriggerProps) => ReactNode;
+
+ /**
+ * Imperative handle for opening and closing the panel. Prefer `handleRef`
+ * over mirroring open state in the parent — the selector owns its
+ * visibility, and imperative calls avoid the focus-management pitfalls of
+ * syncing an external `isOpen` prop.
+ */
+ handleRef?: React.Ref<MultiSelectorHandle>;
+
+ /**
+ * Called whenever the panel opens or closes, however it happened — the
+ * trigger, the keyboard, a light dismiss, Escape, or the imperative handle.
+ */
+ onOpenChange?: (isOpen: boolean) => void;
+
/**
* Test ID for testing frameworks.
*/
@@ -790,6 +895,9 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
indicatorPosition = 'start',
presentation = 'popover',
isDefaultOpen = false,
+ renderTrigger,
+ handleRef,
+ onOpenChange,
'data-testid': testId,
htmlName,
width,
@@ -966,24 +1074,49 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
}, [searchQuery, options, selectedAtOpen, hasSelectAll, selectAllLabel]);
// Layer for dropdown positioning
+ const hasExternalTrigger = renderTrigger != null;
+
+ // The open handlers defer their focus move by a frame, so a panel closed
+ // inside that frame would otherwise be focused after it has gone — the
+ // person loses focus to a surface that is no longer there. The pending
+ // frame is cancelled on hide.
+ const openFocusFrameRef = useRef<number | null>(null);
+ const cancelOpenFocus = useCallback(() => {
+ if (openFocusFrameRef.current != null) {
+ cancelAnimationFrame(openFocusFrameRef.current);
+ openFocusFrameRef.current = null;
+ }
+ }, []);
+
const handleLayerHide = useCallback(() => {
+ cancelOpenFocus();
setSearchQuery('');
setSelectedAtOpen(null);
// Clear any lingering result count when the popover closes so stale status
// text does not linger in the a11y tree.
announce('');
- }, [announce]);
+ onOpenChange?.(false);
+ }, [announce, onOpenChange, cancelOpenFocus]);
const handleLayerShow = useCallback(() => {
// Snapshot selection only after the surface actually opens; a same-gesture
// rejection must not prepare state for an opening that never happened.
setSelectedAtOpen(new Set(optimisticValue));
if (hasSearch) {
- requestAnimationFrame(() => {
+ openFocusFrameRef.current = requestAnimationFrame(() => {
+ openFocusFrameRef.current = null;
searchRef.current?.focus();
});
+ } else if (hasExternalTrigger) {
+ // The caller's anchor may not take focus (a glyph in a link row), so
+ // the listbox owns the keyboard while the panel is open.
+ openFocusFrameRef.current = requestAnimationFrame(() => {
+ openFocusFrameRef.current = null;
+ listboxRef.current?.focus();
+ });
}
- }, [hasSearch, optimisticValue]);
+ onOpenChange?.(true);
+ }, [hasSearch, hasExternalTrigger, optimisticValue, onOpenChange]);
const surface = useSelectorPresentation({
presentation,
@@ -1024,6 +1157,28 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
}
}, [isEffectivelyReadOnly, isSurfaceOpen, hideSurface]);
+ const canOpen = !isDisabled && !isEffectivelyReadOnly;
+ useImperativeHandle(
+ handleRef,
+ () => ({
+ open: () => {
+ if (canOpen && !surface.isOpen) {
+ surface.show();
+ }
+ },
+ close: () => surface.hide(),
+ toggle: () => {
+ if (surface.isOpen) {
+ surface.hide();
+ } else if (canOpen) {
+ surface.show();
+ }
+ },
+ isOpen: () => surface.isOpen,
+ }),
+ [canOpen, surface],
+ );
+
// Announce the filtered result count from the query-change handler (matching
// BaseTypeahead) rather than a reactive effect: computing the count for the
// next query here fires the announcement exactly once per keystroke and does
@@ -1639,6 +1794,16 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
const showStatusTooltip =
status != null && effectiveStatusVariant === 'tooltip' && !!status.message;
+ // With the caller's own trigger, `label` names the listbox directly: the
+ // anchor may carry no text of its own (a glyph in a link row).
+ const listboxLabelProps = hasExternalTrigger
+ ? {'aria-label': label}
+ : {'aria-labelledby': triggerId};
+ // In a bottom sheet, or hung off a caller's anchor that may not take focus,
+ // the listbox itself owns the keyboard.
+ const listboxOwnsKeyboard =
+ surface.activePresentation === 'bottom-sheet' || hasExternalTrigger;
+
const panelContent = hasSearch ? (
<div>
{renderSearch()}
@@ -1649,7 +1814,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
id={listboxId}
role="listbox"
aria-multiselectable="true"
- aria-labelledby={triggerId}
+ {...listboxLabelProps}
{...stylex.props(styles.listbox)}>
{renderOptions()}
</div>
@@ -1662,16 +1827,14 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
id={listboxId}
role="listbox"
aria-multiselectable="true"
- aria-labelledby={triggerId}
+ {...listboxLabelProps}
aria-activedescendant={
surface.isOpen && highlightedIndex >= 0
? getItemId(highlightedIndex)
: undefined
}
- tabIndex={surface.activePresentation === 'bottom-sheet' ? 0 : undefined}
- onKeyDown={
- surface.activePresentation === 'bottom-sheet' ? onKeyDown : undefined
- }
+ tabIndex={listboxOwnsKeyboard ? 0 : undefined}
+ onKeyDown={listboxOwnsKeyboard ? onKeyDown : undefined}
{...stylex.props(styles.listbox)}>
{renderOptions()}
</div>
@@ -1720,6 +1883,70 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
),
};
+ if (renderTrigger != null) {
+ // Anchor-only mode: the caller renders the opener and spreads these props
+ // on it. No Field, no status, no clear button — the caller owns the
+ // control; the selector owns the panel, its anchor, and focus return.
+ const triggerProps: MultiSelectorRenderTriggerProps = {
+ ref: el => {
+ popover.triggerRef(el);
+ triggerRef.current = el;
+ // A control that takes no focus has nowhere for focus to return to
+ // when the panel closes, and focus would land on the body — the
+ // person loses their place in the page. Making it programmatically
+ // focusable repairs the return without putting it in the tab order,
+ // which is the caller's decision to make. It does not make the
+ // control openable from the keyboard: only a real control does
+ // that, which is what the warning below is for.
+ if (el != null && !el.matches(FOCUSABLE_SELECTOR)) {
+ el.tabIndex = -1;
+ }
+ },
+ id: triggerId,
+ onClick: isEffectivelyReadOnly ? undefined : onTriggerClick,
+ onKeyDown: isEffectivelyReadOnly ? undefined : onKeyDown,
+ onFocus: event => {
+ onFocus?.(event);
+ surface.onTriggerFocus(event);
+ },
+ // A read-only selector has no selection surface to open, so it must
+ // not advertise one: `spec:AST-011` FR4. Telling a screen-reader user
+ // "collapsed, has popup" on a control that cannot open leaves them
+ // pressing Enter with nothing happening and no way to tell the value
+ // is read-only rather than the control broken. The field path below
+ // already respects this; the anchor-only path must not regress it.
+ 'aria-haspopup': isEffectivelyReadOnly
+ ? undefined
+ : surface.activePresentation === 'bottom-sheet'
+ ? 'dialog'
+ : 'listbox',
+ 'aria-expanded': isEffectivelyReadOnly ? false : surface.isOpen,
+ 'aria-controls': isEffectivelyReadOnly ? undefined : listboxId,
+ 'aria-busy': isBusy || undefined,
+ // Withholding the disclosure attributes stops the control lying about
+ // a panel, but leaves it silent about WHY it does not open. The field
+ // path says so through its own chrome; the caller's control has none,
+ // so the state is handed over for it to present.
+ 'aria-readonly': isEffectivelyReadOnly || undefined,
+ };
+ return (
+ <>
+ {renderTrigger(triggerProps)}
+ {htmlName != null &&
+ value.map(v => (
+ <input
+ key={v}
+ type="hidden"
+ name={htmlName}
+ value={v}
+ disabled={isDisabled}
+ />
+ ))}
+ {selectionSurface}
+ </>
+ );
+ }
+
const multiSelectorContent = (
<>
<div
diff --git a/packages/core/src/MultiSelector/index.ts b/packages/core/src/MultiSelector/index.ts
index 9859cb5c46..6a6cf6548c 100644
--- a/packages/core/src/MultiSelector/index.ts
+++ b/packages/core/src/MultiSelector/index.ts
@@ -15,6 +15,8 @@ export {
type MultiSelectorSize,
type MultiSelectorStatusType,
type MultiSelectorSelectedItem,
+ type MultiSelectorRenderTriggerProps,
+ type MultiSelectorHandle,
} from './MultiSelector';
export type {
MultiSelectorOptionType,