Skip to content

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

TypeScript

feat(core): add read-only selectors (#5805)

Cindy Zhangc5197506492b
diff --git a/.changeset/selector-read-only.md b/.changeset/selector-read-only.md
new file mode 100644
index 0000000000..16241c98c0
--- /dev/null
+++ b/.changeset/selector-read-only.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[component] Add `isReadOnly` to Selector and MultiSelector so selected values remain focusable and form-submittable without exposing selection menus or editing affordances.
+
+@cixzhang
diff --git a/apps/storybook/stories/MultiSelector.stories.tsx b/apps/storybook/stories/MultiSelector.stories.tsx
index 3209214bc5..6a712ffafc 100644
--- a/apps/storybook/stories/MultiSelector.stories.tsx
+++ b/apps/storybook/stories/MultiSelector.stories.tsx
@@ -36,6 +36,7 @@ const meta: Meta<typeof MultiSelector> = {
options: ['count', 'labels', 'badges'],
},
isDisabled: {control: 'boolean'},
+ isReadOnly: {control: 'boolean'},
disabledMessage: {control: 'text'},
isOptional: {control: 'boolean'},
isRequired: {control: 'boolean'},
@@ -66,6 +67,20 @@ export const Default: Story = {
},
};
+export const ReadOnly: Story = {
+ args: {
+ label: 'Assigned teams',
+ options: ['Design', 'Engineering', 'Marketing'],
+ value: ['Design', 'Engineering'],
+ onChange: () => {},
+ hasClear: true,
+ hasSearch: true,
+ htmlName: 'teams',
+ triggerDisplay: 'labels',
+ isReadOnly: true,
+ },
+};
+
export const BottomSheetPresentation: Story = {
render: () => {
const [value, setValue] = useState<string[]>([]);
diff --git a/apps/storybook/stories/Selector.stories.tsx b/apps/storybook/stories/Selector.stories.tsx
index b2c9c8e6ab..10002628a9 100644
--- a/apps/storybook/stories/Selector.stories.tsx
+++ b/apps/storybook/stories/Selector.stories.tsx
@@ -80,6 +80,11 @@ const meta: Meta<typeof Selector> = {
control: 'boolean',
description: 'Whether the selector is disabled',
},
+ isReadOnly: {
+ control: 'boolean',
+ description:
+ 'Whether the selected value is visible and submittable without selection controls',
+ },
disabledMessage: {
control: 'text',
description:
@@ -137,6 +142,19 @@ export const Default: Story = {
},
};
+export const ReadOnly: Story = {
+ args: {
+ label: 'Assigned owner',
+ options: ['Alice', 'Bob', 'Charlie'],
+ value: 'Alice',
+ onChange: () => {},
+ hasClear: true,
+ hasSearch: true,
+ htmlName: 'owner',
+ isReadOnly: true,
+ },
+};
+
export const BottomSheetPresentation: Story = {
render: () => {
const [value, setValue] = useState<string | undefined>();
diff --git a/docs/specs/AST-011/spec.md b/docs/specs/AST-011/spec.md
new file mode 100644
index 0000000000..998c232a45
--- /dev/null
+++ b/docs/specs/AST-011/spec.md
@@ -0,0 +1,141 @@
+---
+schema_version: 1
+template_version: 1
+kind: system-spec
+id: spec:AST-011
+authority: current
+archive_reason: null
+superseded_by: null
+approved_by: cixzhang
+approved_at: 2026-08-31
+phase: accepted
+owners: [cixzhang]
+affects_architecture: [architecture:public-component-api]
+affects_families: [family:input-fields]
+affects_contributing: []
+affects_consumer_docs: [Selector, MultiSelector]
+---
+
+# Read-only selection inputs
+
+## Intent
+
+People should be able to review and submit a selected value that policy or
+permissions prevent them from changing. Selector and MultiSelector should expose
+that state as read-only rather than disabled, without offering a menu that cannot
+change the value.
+
+## Non-goals
+
+- Adding read-only behavior to every input-family member in this change.
+- Changing disabled, disabled-reason, loading, validation, or option-source state.
+- Adding read-only explanation text or a tooltip API.
+- Changing selected-value rendering, option rendering, or form serialization.
+
+## Requirements
+
+- **FR1 — Read-only preserves the value.** With `isReadOnly`, the current value
+ MUST remain visible at full opacity, focusable in the ordinary tab order, and
+ included in form submission. It MUST NOT invoke `onChange` or `changeAction`.
+- **FR2 — Read-only exposes no selection surface.** Pointer, keyboard, typeahead,
+ search, and `isDefaultOpen` MUST NOT open or render the Popover or BottomSheet
+ selection surface while read-only.
+- **FR3 — Editing affordances are absent.** Clear actions and the disclosure
+ indicator MUST NOT render while read-only. Status and busy presentation remain
+ independent because they describe the preserved value rather than an available
+ edit.
+- **FR4 — Accessibility matches behavior.** The focusable read-only value MUST
+ retain `combobox` semantics, expose `aria-readonly="true"` and
+ `aria-expanded="false"`, and preserve its accessible name and rendered value.
+ It MUST NOT expose `aria-controls` or `aria-activedescendant` when no selection
+ surface exists. The combobox role's implicit listbox popup describes the
+ control's selection capability; `aria-readonly` communicates that the value
+ cannot currently be changed. When a supported accessibility tree does not map
+ that ARIA property for the trigger's host element, a localized accessible
+ description MUST additionally announce the read-only state. Search-enabled and
+ non-search selectors use the same read-only combobox semantics because neither
+ exposes a search or selection surface in this state.
+- **FR5 — Disabled takes precedence.** When `isDisabled` and `isReadOnly` are both
+ true, disabled focus, interaction, appearance, accessibility, and form-submission
+ behavior win.
+- **IR1 — The public API follows the input convention.** Selector and
+ MultiSelector MUST use the established optional `isReadOnly` boolean and expose
+ the existing `readonly` theme state on their root targets.
+- **IR2 — Read-only is not disabled paint.** Implementations MUST NOT reuse
+ disabled opacity or disabled form behavior for read-only state. They MAY remove
+ hover, pressed, and pointer affordances that would falsely imply editability.
+
+### Platform support
+
+- Supported feature/engine floor: every browser and assistive-technology
+ combination supported by Astryx Core.
+- WCAG baseline: [WCAG 2.2 SC 4.1.2](https://www.w3.org/TR/WCAG22/#name-role-value)
+ requires the control's name, role, value, and state to be programmatically
+ determinable. The retained `combobox` role, rendered value, and
+ `aria-readonly="true"` state satisfy that contract without changing the
+ control's programmatic identity.
+- ARIA contract: [WAI-ARIA 1.2](https://www.w3.org/TR/wai-aria-1.2/#aria-readonly)
+ supports `aria-readonly` on `combobox` and defines read-only as a value the user
+ can read but cannot set. A combobox has an implicit
+ `aria-haspopup="listbox"`; that capability metadata remains valid even though
+ read-only interaction never opens the surface.
+- Browser evidence: DOM inspection MUST expose `aria-readonly="true"` and no
+ nonexistent controlled surface. Chromium accessibility inspection MUST expose a
+ focusable, collapsed combobox with the correct name and rendered value; its
+ implicit popup remains `listbox`, and its accessible description MUST announce
+ the localized read-only state because Chromium does not map `aria-readonly` on
+ the button host. Pointer and keyboard probes MUST confirm that no selection
+ surface opens and no value changes.
+
+## Current-state impact
+
+- TextInput, TextArea, NumberInput, CheckboxInput, and CheckboxList already
+ establish `isReadOnly` as the input-family name for visible, focusable,
+ non-editable values.
+- Selector and MultiSelector currently expose only disabled state. Their triggers
+ can open a selection surface, their clear actions can change the value, and
+ their form carriers are removed only when disabled.
+- The caller owns whether a selected value is policy- or permission-locked; the
+ components cannot derive that distinction from the value, options, loading
+ state, or layout. The prop therefore satisfies `spec:AST-002` public-prop
+ admission.
+- Implementation updates both component contracts, consumer docs, focused tests,
+ and theme-state metadata in the same pull request.
+
+## Verification
+
+| Contract | Verification | Representative states | Mutation or failure expectation |
+| -------- | --------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- |
+| FR1, FR5 | Focus, callback, and form-participation tests | read-only; disabled; both; single and multiple values | A read-only value changes, leaves the tab order, fails to submit, dims, or overrides disabled behavior |
+| FR2, FR3 | Pointer/keyboard/typeahead and DOM affordance tests | popover, bottom sheet, adaptive, search, clear, default-open | A read-only trigger opens or renders a surface, clears a value, or displays a disclosure indicator |
+| FR4 | DOM and real-browser accessibility inspection | search and non-search triggers; standalone and InputGroup | The value changes role, loses its name/value/read-only state, appears expanded, or points at a nonexistent controlled surface |
+| IR1, IR2 | Theme-state and rendered-style tests | input and ghost variants | The root omits `data-readonly`, gains disabled opacity, or keeps interactive hover/pressed cues |
+
+## Decision log
+
+### DEC-1 — Selection inputs use the established read-only contract
+
+**Reference:** `spec:AST-011/DEC-1`
+**Decider:** `cixzhang`, `2026-08-31`
+
+Selector and MultiSelector accept `isReadOnly` when the caller owns a value that
+must remain visible and submitted but cannot be changed. Read-only controls stay
+focusable, retain their combobox identity, expose their rendered content as the
+value, and publish `aria-readonly="true"`, while selection and editing affordances
+are absent.
+
+The retained role follows WCAG 2.2 SC 4.1.2's stable programmatic name, role,
+value, and state contract and WAI-ARIA 1.2's explicit support for
+`aria-readonly` on `combobox`. [MUI Select](https://github.com/mui/material-ui/blob/bddf22f5c6d4c4383aae88dbd77b6c7a53c5fd17/packages/mui-material/src/Select/SelectInput.js#L841-L853)
+and [React Aria ComboBox](https://github.com/adobe/react-spectrum/blob/7c6100839de0f53bfa3c4e2f99529bdaa96bf205/packages/react-aria/src/combobox/useComboBox.ts#L143-L151)
+use the same shape: a read-only combobox remains identifiable as a combobox while
+pointer and keyboard opening are blocked. The implicit listbox popup describes
+the widget's selection capability; it does not promise that every state can open
+it.
+
+Rejected: mapping this state to `isDisabled`, because disabled values are dimmed,
+removed from the tab order by default, and excluded from form submission.
+
+## Open questions
+
+None.
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index 8dcd5b541f..444dd8a911 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -1087,6 +1087,10 @@
"defaultMessage": "Clear all {label}",
"description": "Screen-reader-only label on the X that clears every selected value from a MultiSelector. Example: `Clear all Countries`. `{label}` is typically already plural in English."
},
+ "@astryx.input.readOnly": {
+ "defaultMessage": "Read only",
+ "description": "Screen-reader-only description appended to a read-only form control when the platform does not expose aria-readonly for that control's host element. Short state label, not an instruction."
+ },
"@astryx.input.statusButton.error": {
"defaultMessage": "Error details",
"description": "Accessible name for the focusable status icon button inside an input when statusVariant is 'tooltip' and the status type is error. Activating or focusing the button reveals the error message in a tooltip. Keep it short — it labels an icon-only button."
diff --git a/packages/core/src/MultiSelector/MultiSelector.doc.mjs b/packages/core/src/MultiSelector/MultiSelector.doc.mjs
index 5673b91a92..9ffd5282ad 100644
--- a/packages/core/src/MultiSelector/MultiSelector.doc.mjs
+++ b/packages/core/src/MultiSelector/MultiSelector.doc.mjs
@@ -12,7 +12,7 @@ const anatomy = [
name: 'Trigger',
required: true,
description:
- 'Painted control that displays the current selection or placeholder and opens the selection surface.',
+ 'Painted control that displays the current selection or placeholder and opens the selection surface when editable.',
},
{
name: 'Icon-rendered start icon',
@@ -134,7 +134,7 @@ export const docs = {
{
className: 'astryx-multi-selector',
visualProps: ['variant', 'size', 'status'],
- states: ['disabled'],
+ states: ['disabled', 'readonly'],
},
{
className: 'astryx-multi-selector-clear-icon',
@@ -272,6 +272,13 @@ export const docs = {
type: 'boolean',
description: 'Disables the selector.',
},
+ {
+ name: 'isReadOnly',
+ type: 'boolean',
+ description:
+ 'Makes the selector read-only: the selected values stay visible, focusable, and included in form submission, and retain their combobox identity with aria-readonly. The selection surface, clear action, and disclosure indicator are removed. Unlike isDisabled, the control is not dimmed. isDisabled takes precedence when both are set.',
+ default: 'false',
+ },
{
name: 'htmlName',
type: 'string',
@@ -459,6 +466,8 @@ export const docsZh = {
emptyText: '没有可显示的选项时,下拉面板中显示的内容。',
emptySearchText: '搜索查询未匹配到任何选项时,下拉面板中显示的内容。',
isDisabled: '禁用选择器。',
+ isReadOnly:
+ '将选择器设为只读:保留当前值、焦点顺序和表单提交,但移除选择面板、清除操作和展开指示器。与 isDisabled 不同,只读控件不会变暗;两者同时设置时 isDisabled 优先。',
htmlName:
'用于表单提交的 HTML name 属性。为每个已选值渲染一个隐藏输入,类似原生多选。',
disabledMessage:
@@ -600,6 +609,8 @@ export const docsDense = {
emptyText: 'panel content when there are no options',
emptySearchText: 'panel content when the query matches nothing',
isDisabled: 'disables selector',
+ isReadOnly:
+ 'read-only: preserves values, focus + form submission; removes menu, clear + disclosure',
htmlName: 'HTML name attr; one hidden input per selected value.',
disabledMessage:
'why disabled; w/ isDisabled shows tooltip on hover/focus, trigger stays focusable via aria-disabled; use instead of Tooltip wrapper',
diff --git a/packages/core/src/MultiSelector/MultiSelector.spec.md b/packages/core/src/MultiSelector/MultiSelector.spec.md
index f754c05533..47bba00e9c 100644
--- a/packages/core/src/MultiSelector/MultiSelector.spec.md
+++ b/packages/core/src/MultiSelector/MultiSelector.spec.md
@@ -9,7 +9,7 @@ superseded_by: null
approved_by: null
approved_at: null
owners: [cixzhang]
-review_triggers: [theming]
+review_triggers: [public-api, behavior, theming, accessibility]
verified_by:
[
packages/core/src/MultiSelector/MultiSelector.test.tsx,
@@ -24,9 +24,13 @@ verified_by:
families: [family:overlay-dismissal]
design_specs: []
architecture:
- [architecture:component-theming-surface, architecture:layer-runtime]
+ [
+ architecture:component-theming-surface,
+ architecture:layer-runtime,
+ architecture:public-component-api,
+ ]
contributing: []
-system_specs: []
+system_specs: [spec:AST-011/DEC-1]
---
# MultiSelector component contract
@@ -35,15 +39,19 @@ system_specs: []
MultiSelector renders a multi-selection control with an optional standalone Field
shell and one shared panel content tree in either an anchored pointer popup or a
-touch-oriented BottomSheet.
-This draft records current consumer anatomy and theming ownership without changing
-runtime behavior, styling, targets, or public API.
+touch-oriented BottomSheet. It also supports a read-only state that preserves and
+submits the selected values without exposing that panel or an editing affordance.
+This draft records current consumer anatomy, theming ownership, and read-only
+behavior.
## Compatibility and migration
- Released default preserved: `yes`
-- Compatibility class: additive documentation only; runtime, DOM, styling,
- targets, and public API remain unchanged
+- `isReadOnly` is additive and defaults to `false`. It preserves selected values,
+ focus, and form participation while removing selection-surface and editing
+ 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
- Migration decision: none
@@ -80,8 +88,12 @@ Consumer migration instructions belong in consumer docs and release notes.
## Public concepts
-No new public concept is introduced. Consumer props and usage remain documented
-in `MultiSelector.doc.mjs`.
+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 |
## Behavioral and layout contract
@@ -93,6 +105,7 @@ in `MultiSelector.doc.mjs`.
| 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 |
### Allowed variation
@@ -117,6 +130,7 @@ in `MultiSelector.doc.mjs`.
| Search enabled with a query | Search row owns `multi-selector-search`; its icons/actions keep their shared owners. | Results may be flat, grouped, or empty. |
| Option, select all, selected, disabled | Option row owns `multi-selector-option` and reflects its current size/state metadata. | Checkbox state and custom row content vary independently. |
| Attached or tooltip status | Status icon replaces the Indicator icon. | Tooltip status wraps the icon in a button without changing Icon owner. |
+| Read-only | Values stay focusable and submittable; panel, clear, and disclosure affordances are absent. | Trigger display, status, and busy presentation remain available. |
### Transformation and precedence order
@@ -128,8 +142,17 @@ in `MultiSelector.doc.mjs`.
## Accessibility contract
-This draft does not change or extend MultiSelector's existing field, combobox,
-listbox, checkbox, live-region, focus, or dismissal behavior.
+Existing field, combobox, listbox, checkbox, live-region, focus, and dismissal
+behavior remains unchanged when editable. A read-only value stays focusable,
+retains `role="combobox"`, and exposes `aria-readonly="true"` plus
+`aria-expanded="false"`. Its rendered content remains the combobox value. It does
+not expose `aria-controls`, `aria-activedescendant`, or an active selection
+surface. The implicit listbox popup describes the widget's selection capability;
+read-only state communicates that its values cannot currently change. Chromium's
+button-hosted combobox mapping omits the ARIA read-only property, so a localized
+accessible description also announces that state. Search and non-search modes use
+the same read-only combobox semantics because neither exposes a search control in
+this state.
## Design relationships
@@ -223,6 +246,8 @@ empty-state content remains one shared tree.
## Family and system relationships
+- `architecture:public-component-api` and `spec:AST-011/DEC-1` own the additive
+ read-only API and its cross-input meaning.
- `architecture:component-theming-surface` owns anatomy qualification, local
target mapping, delegation, and exclusion of deprecated aliases.
- `architecture:layer-runtime` owns the current Popover host and the distinction
@@ -235,13 +260,14 @@ 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` |
-| 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` |
+| 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
diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsx
index 7baa04d63b..9f8281fa63 100644
--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx
@@ -1140,7 +1140,9 @@ describe('MultiSelector', () => {
/>,
);
- await user.click(screen.getByRole('combobox', {name: 'Fruit'}));
+ const trigger = screen.getByRole('combobox', {name: 'Fruit'});
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
// useAnnounce writes on the next animation frame, so an immediate read
// would pass whether or not anything was announced.
@@ -1395,7 +1397,7 @@ describe('MultiSelector', () => {
expect(group).toHaveAttribute('aria-label', 'Citrus');
});
- it('shows loading state with aria-busy', () => {
+ it('shows loading state with a spinner and aria-busy', () => {
render(
<MultiSelector
label="Fruit"
@@ -1406,6 +1408,7 @@ describe('MultiSelector', () => {
/>,
);
expect(screen.getByRole('combobox')).toHaveAttribute('aria-busy', 'true');
+ expect(screen.getByRole('status', {name: 'Loading'})).toBeInTheDocument();
});
it('renders with custom selectAllLabel', async () => {
@@ -1885,6 +1888,306 @@ describe('MultiSelector', () => {
expect(trigger).toHaveAttribute('tabIndex', '-1');
});
});
+ describe('isReadOnly', () => {
+ const readOnlyCases = [
+ {presentation: 'popover', hasSearch: false},
+ {presentation: 'popover', hasSearch: true},
+ {presentation: 'bottom-sheet', hasSearch: false},
+ {presentation: 'bottom-sheet', hasSearch: true},
+ {presentation: 'adaptive', hasSearch: false},
+ {presentation: 'adaptive', hasSearch: true},
+ ] as const;
+
+ const sheetTransitionCases = [
+ {presentation: 'bottom-sheet', hasSearch: false},
+ {presentation: 'bottom-sheet', hasSearch: true},
+ {presentation: 'adaptive', hasSearch: false},
+ {presentation: 'adaptive', hasSearch: true},
+ ] as const;
+
+ const disabledPrecedenceCases = (
+ ['popover', 'bottom-sheet', 'adaptive'] as const
+ ).flatMap(presentation =>
+ [false, true].flatMap(hasSearch =>
+ [false, true].map(hasDisabledMessage => ({
+ presentation,
+ hasSearch,
+ hasDisabledMessage,
+ })),
+ ),
+ );
+
+ function stubCompactTouch(presentation: 'bottom-sheet' | 'adaptive') {
+ if (presentation !== 'adaptive') {
+ return;
+ }
+ vi.mocked(matchMedia).mockImplementation(
+ (query: string) =>
+ ({
+ matches: query === '(max-width: 768px) and (pointer: coarse)',
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ }) as MediaQueryList,
+ );
+ }
+
+ it.each(readOnlyCases)(
+ 'uses a read-only combobox with no rendered popup ($presentation, search=$hasSearch)',
+ async ({presentation, hasSearch}) => {
+ const user = userEvent.setup();
+ const {container} = render(
+ <form>
+ <MultiSelector
+ label="Fruit"
+ htmlName="fruit"
+ options={defaultOptions}
+ value={['Apple', 'Banana']}
+ onChange={() => {}}
+ hasClear
+ hasSearch={hasSearch}
+ presentation={presentation}
+ isDefaultOpen
+ triggerDisplay="labels"
+ isReadOnly
+ />
+ </form>,
+ );
+
+ const trigger = screen.getByRole('combobox', {name: 'Fruit'});
+ expect(trigger.tagName).toBe('BUTTON');
+ expect(trigger).toHaveTextContent('Apple, Banana');
+ expect(trigger).toHaveAttribute('aria-readonly', 'true');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ const readOnlyDescription = screen.getByText('Read only');
+ expect(trigger.getAttribute('aria-describedby')).toContain(
+ readOnlyDescription.id,
+ );
+ expect(trigger).not.toHaveAttribute('aria-controls');
+ expect(trigger).not.toHaveAttribute('aria-haspopup');
+ expect(screen.getAllByRole('combobox', h)).toHaveLength(1);
+ expect(screen.queryByRole('listbox', h)).not.toBeInTheDocument();
+ expect(screen.queryByRole('dialog', h)).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: 'Clear all Fruit'}),
+ ).not.toBeInTheDocument();
+ expect(
+ container.querySelector('.astryx-multi-selector-indicator-icon'),
+ ).toBeNull();
+ expect(
+ container.querySelector('.astryx-multi-selector'),
+ ).toHaveAttribute('data-readonly', 'readonly');
+ expect(
+ new FormData(container.querySelector('form')!).getAll('fruit'),
+ ).toEqual(['Apple', 'Banana']);
+
+ await user.tab();
+ expect(trigger).toHaveFocus();
+ },
+ );
+
+ it('keeps loading feedback while blocking the selection surface', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Fruit"
+ options={defaultOptions}
+ value={['Apple']}
+ onChange={() => {}}
+ isLoading
+ isReadOnly
+ />,
+ );
+
+ const trigger = screen.getByRole('combobox', {name: 'Fruit'});
+ expect(trigger).toHaveAttribute('aria-busy', 'true');
+ expect(screen.getByRole('status', {name: 'Loading'})).toBeInTheDocument();
+
+ await user.click(trigger);
+ expect(screen.queryByRole('listbox', h)).not.toBeInTheDocument();
+ });
+
+ it('blocks pointer, keyboard, and typeahead changes', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const changeAction = vi.fn();
+ render(
+ <MultiSelector
+ label="Fruit"
+ options={defaultOptions}
+ value={['Apple']}
+ onChange={onChange}
+ changeAction={changeAction}
+ isReadOnly
+ />,
+ );
+
+ const trigger = screen.getByRole('combobox');
+ await user.click(trigger);
+ trigger.focus();
+ await user.keyboard('{Enter}{ArrowDown}b{Backspace}');
+
+ expect(screen.queryByRole('listbox', h)).not.toBeInTheDocument();
+ expect(onChange).not.toHaveBeenCalled();
+ expect(changeAction).not.toHaveBeenCalled();
+ });
+
+ it.each([false, true])(
+ 'restores popover focus when an open selector becomes read-only (search=%s)',
+ async hasSearch => {
+ const user = userEvent.setup();
+ const selector = (isReadOnly: boolean) => (
+ <MultiSelector
+ label="Fruit"
+ options={defaultOptions}
+ value={['Apple']}
+ onChange={() => {}}
+ hasSearch={hasSearch}
+ isReadOnly={isReadOnly}
+ />
+ );
+ const {rerender} = render(selector(false));
+ const editableTrigger = screen.getByRole(
+ hasSearch ? 'button' : 'combobox',
+ {name: 'Fruit'},
+ );
+ await user.click(editableTrigger);
+ if (hasSearch) {
+ await waitFor(() =>
+ expect(screen.getByRole('combobox', h)).toHaveFocus(),
+ );
+ }
+
+ rerender(selector(true));
+
+ const readOnlyTrigger = screen.getByRole('combobox', {name: 'Fruit'});
+ await waitFor(() => expect(readOnlyTrigger).toHaveFocus());
+ expect(screen.queryByRole('listbox', h)).not.toBeInTheDocument();
+ },
+ );
+
+ it.each(sheetTransitionCases)(
+ 'finishes $presentation close and restores focus when read-only changes (search=$hasSearch)',
+ async ({presentation, hasSearch}) => {
+ stubCompactTouch(presentation);
+ const user = userEvent.setup();
+ const selector = (isReadOnly: boolean) => (
+ <MultiSelector
+ label="Fruit"
+ options={defaultOptions}
+ value={['Apple']}
+ onChange={() => {}}
+ hasSearch={hasSearch}
+ presentation={presentation}
+ isReadOnly={isReadOnly}
+ />
+ );
+ const {rerender} = render(selector(false));
+ const editableTrigger = screen.getByRole(
+ hasSearch ? 'button' : 'combobox',
+ {name: 'Fruit'},
+ );
+ await user.click(editableTrigger);
+ const dialog = await screen.findByRole('dialog', {name: 'Fruit'});
+ const panel = dialog.querySelector<HTMLElement>('.astryx-bottom-sheet');
+ expect(panel).not.toBeNull();
+ await waitFor(() =>
+ expect(
+ hasSearch
+ ? screen.getByRole('combobox', h)
+ : screen.getByRole('listbox'),
+ ).toHaveFocus(),
+ );
+
+ rerender(selector(true));
+
+ await waitFor(() => expect(dialog).toHaveAttribute('inert'));
+ fireEvent.transitionEnd(panel!, {propertyName: 'transform'});
+ const readOnlyTrigger = screen.getByRole('combobox', {name: 'Fruit'});
+ await waitFor(() => expect(readOnlyTrigger).toHaveFocus());
+ expect(screen.queryByRole('dialog', h)).not.toBeInTheDocument();
+ expect(screen.queryByRole('listbox', h)).not.toBeInTheDocument();
+ },
+ );
+
+ it.each(disabledPrecedenceCases)(
+ 'matches disabled-only semantics for $presentation (search=$hasSearch, reason=$hasDisabledMessage)',
+ async ({presentation, hasSearch, hasDisabledMessage}) => {
+ if (presentation === 'adaptive') {
+ stubCompactTouch(presentation);
+ }
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const selector = (isReadOnly: boolean) => (
+ <form>
+ <MultiSelector
+ label="Fruit"
+ htmlName="fruit"
+ options={defaultOptions}
+ value={['Apple', 'Banana']}
+ onChange={onChange}
+ hasClear
+ hasSearch={hasSearch}
+ presentation={presentation}
+ isDisabled
+ isReadOnly={isReadOnly}
+ disabledMessage={
+ hasDisabledMessage ? 'Locked by policy' : undefined
+ }
+ />
+ </form>
+ );
+ const {container, rerender} = render(selector(false));
+ const getTrigger = () =>
+ screen.getByRole(hasSearch ? 'button' : 'combobox', {name: 'Fruit'});
+ const snapshot = () => {
+ const trigger = getTrigger();
+ const root = container.querySelector('.astryx-multi-selector');
+ return {
+ tagName: trigger.tagName,
+ role: trigger.getAttribute('role'),
+ hasPopup: trigger.getAttribute('aria-haspopup'),
+ expanded: trigger.getAttribute('aria-expanded'),
+ controls: trigger.getAttribute('aria-controls'),
+ readOnly: trigger.getAttribute('aria-readonly'),
+ disabled: trigger.matches(':disabled'),
+ ariaDisabled: trigger.getAttribute('aria-disabled'),
+ tabIndex: trigger.tabIndex,
+ rootClassName: root?.className,
+ rootDisabled: root?.getAttribute('data-disabled'),
+ rootReadOnly: root?.getAttribute('data-readonly'),
+ hasIndicator:
+ root?.querySelector('.astryx-multi-selector-indicator-icon') !=
+ null,
+ listboxes: screen.queryAllByRole('listbox', h).length,
+ dialogs: screen.queryAllByRole('dialog', h).length,
+ formEntries: [
+ ...new FormData(container.querySelector('form')!).entries(),
+ ],
+ };
+ };
+ const disabledOnly = snapshot();
+
+ rerender(selector(true));
+
+ expect(snapshot()).toEqual(disabledOnly);
+ expect(disabledOnly.rootDisabled).toBe('disabled');
+ expect(disabledOnly.rootReadOnly).toBeNull();
+ expect(disabledOnly.readOnly).toBeNull();
+ expect(disabledOnly.formEntries).toEqual([]);
+ const trigger = getTrigger();
+ await user.click(trigger);
+ trigger.focus();
+ await user.keyboard('{Enter}{ArrowDown}b{Backspace}');
+ expect(onChange).not.toHaveBeenCalled();
+ },
+ );
+ });
+
describe('form participation', () => {
it('submits one entry per selected value under htmlName', () => {
const {container} = render(
diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsx
index 08a5c76b4e..3bde456130 100644
--- a/packages/core/src/MultiSelector/MultiSelector.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.tsx
@@ -221,6 +221,16 @@ const styles = stylex.create({
':active': 'none',
},
},
+ triggerReadOnly: {
+ cursor: 'default',
+ },
+ triggerGhostReadOnly: {
+ backgroundImage: 'none',
+ transform: {
+ default: 'none',
+ ':active': 'none',
+ },
+ },
// Clear button
statusButton: {
@@ -468,6 +478,17 @@ export interface MultiSelectorProps<
*/
isDisabled?: boolean;
+ /**
+ * Whether the selector is read-only.
+ * The selected values stay visible, focusable, and included in form
+ * submission, and retain their combobox identity with `aria-readonly`. The
+ * selection surface and editing affordances are removed.
+ * Unlike `isDisabled`, a read-only selector is not dimmed and stays in the
+ * tab order. `isDisabled` takes precedence when both are set.
+ * @default false
+ */
+ isReadOnly?: boolean;
+
/**
* Explains why the selector is disabled. When set together with
* `isDisabled`, the selector shows a tooltip with this text on hover and
@@ -738,6 +759,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
isOptional = false,
isRequired = false,
isDisabled = false,
+ isReadOnly = false,
disabledMessage,
options,
value,
@@ -789,14 +811,16 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
variant === 'ghost' && statusVariant === 'attached'
? 'detached'
: statusVariant;
+ const isEffectivelyReadOnly = isReadOnly && !isDisabled;
const triggerId = useId();
const listboxId = useId();
const descriptionId = useId();
const statusMessageId = useId();
const inputLabelId = useId();
+ const readOnlyDescriptionId = useId();
const searchId = useId();
- const triggerRef = useRef<HTMLButtonElement>(null);
+ const triggerRef = useRef<HTMLElement>(null);
const searchRef = useRef<HTMLInputElement>(null);
const listboxRef = useRef<HTMLDivElement>(null);
const inputGroup = useInputGroup();
@@ -846,6 +870,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
? statusTooltip.describedBy
: null,
showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
+ isEffectivelyReadOnly ? readOnlyDescriptionId : null,
],
inputGroup,
);
@@ -973,16 +998,27 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
},
});
const {popover} = surface;
+ const hideSurface = surface.hide;
+ const isSurfaceOpen = surface.isOpen;
const keepOpenProps = useKeepLayerOpenProps(popover.id, popover.isOpen);
- // Open dropdown on mount when isDefaultOpen is true
+ // Open dropdown on mount when isDefaultOpen is true and interaction is allowed.
useEffect(() => {
- if (isDefaultOpen) {
+ if (isDefaultOpen && !isEffectivelyReadOnly) {
surface.show();
}
// eslint-disable-next-line @eslint-react/exhaustive-deps -- mount-only: isDefaultOpen is not reactive
}, []);
+ // Read-only is controlled by caller policy, so an already-open surface must
+ // close when that policy changes. The presentation controller keeps a sheet
+ // mounted through its exit and lets BottomSheet return final focus.
+ useEffect(() => {
+ if (isEffectivelyReadOnly && isSurfaceOpen) {
+ hideSurface();
+ }
+ }, [isEffectivelyReadOnly, isSurfaceOpen, hideSurface]);
+
// 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
@@ -1183,7 +1219,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
} = useMultiCombobox({
wasJustDismissed: surface.wasJustDismissed,
selectableItems: sortedItems,
- isDisabled,
+ isDisabled: isDisabled || isEffectivelyReadOnly,
isOpen: surface.isOpen,
hasSearch,
onOpen: useCallback(() => {
@@ -1670,24 +1706,47 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
</div>
);
- const selectionSurface =
- surface.activePresentation === 'bottom-sheet' ? (
- <SelectorBottomSheet
- isOpen={surface.isSheetOpen}
- onOpenChange={surface.onSheetOpenChange}
- finalFocusRef={triggerRef}
- initialFocusRef={hasSearch ? searchRef : listboxRef}
- label={label}>
- {panelContent}
- </SelectorBottomSheet>
- ) : (
- popover.render(panelContent, {
- placement: 'below',
- alignment: 'start',
- offset: spacingVars['--spacing-1'],
- xstyle: styles.popover,
- })
- );
+ let selectionSurface: ReactNode = null;
+ if (surface.activePresentation === 'bottom-sheet') {
+ if (!isEffectivelyReadOnly || surface.isSheetPresented) {
+ selectionSurface = (
+ <SelectorBottomSheet
+ isOpen={surface.isSheetOpen}
+ onOpenChange={surface.onSheetOpenChange}
+ finalFocusRef={triggerRef}
+ initialFocusRef={hasSearch ? searchRef : listboxRef}
+ label={label}>
+ {panelContent}
+ </SelectorBottomSheet>
+ );
+ }
+ } else if (!isEffectivelyReadOnly) {
+ selectionSurface = popover.render(panelContent, {
+ placement: 'below',
+ alignment: 'start',
+ offset: spacingVars['--spacing-1'],
+ xstyle: styles.popover,
+ });
+ }
+
+ const triggerSharedProps: React.HTMLAttributes<HTMLElement> = {
+ id: triggerId,
+ 'aria-describedby': ariaDescribedBy,
+ 'aria-labelledby': ariaLabelledBy,
+ 'aria-required': isEffectivelyRequired ? 'true' : undefined,
+ 'aria-invalid': status?.type === 'error' ? 'true' : undefined,
+ 'aria-busy': isBusy || undefined,
+ onKeyDown,
+ onFocus: event => {
+ onFocus?.(event);
+ surface.onTriggerFocus(event);
+ },
+ tabIndex: isDisabled && !showsDisabledMessage ? -1 : 0,
+ ...stylex.props(
+ styles.trigger,
+ isEffectivelyReadOnly && styles.triggerReadOnly,
+ ),
+ };
const multiSelectorContent = (
<>
@@ -1707,6 +1766,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
size,
status: status?.type ?? null,
disabled: isDisabled ? 'disabled' : null,
+ readonly: isEffectivelyReadOnly ? 'readonly' : null,
}),
stylex.props(
inputWrapperStyles.base,
@@ -1718,7 +1778,11 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
surface.isTriggerFocusRingSuppressed &&
selectorPresentationStyles.pointerRestoredFocus,
isDisabled && inputWrapperStyles.disabled,
+ isEffectivelyReadOnly && styles.triggerReadOnly,
variant === 'ghost' && isDisabled && styles.triggerGhostDisabled,
+ variant === 'ghost' &&
+ isEffectivelyReadOnly &&
+ styles.triggerGhostReadOnly,
optimisticValue.length === 0 && styles.triggerPlaceholder,
variant !== 'ghost' &&
status &&
@@ -1738,41 +1802,43 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
{inputGroup && (
<VisuallyHidden id={inputLabelId}>{label}</VisuallyHidden>
)}
+ {isEffectivelyReadOnly && (
+ <VisuallyHidden id={readOnlyDescriptionId}>
+ {t('@astryx.input.readOnly')}
+ </VisuallyHidden>
+ )}
<button
- ref={triggerRef}
- id={triggerId}
+ {...triggerSharedProps}
+ ref={triggerRef as React.Ref<HTMLButtonElement>}
type="button"
- // In hasSearch mode the popup's search input is the combobox (it owns
- // focus + aria-activedescendant, comboboxes-4), so the trigger is a
- // plain button that opens the listbox — not a second combobox.
- role={hasSearch ? undefined : 'combobox'}
+ // The read-only trigger stays a combobox even when hasSearch is set:
+ // no search input is rendered in that state, and preserving the role
+ // keeps the control's programmatic identity stable. Editable search
+ // mode still moves combobox semantics to the popup input.
+ role={isEffectivelyReadOnly || !hasSearch ? 'combobox' : undefined}
aria-haspopup={
- surface.activePresentation === 'bottom-sheet' ? 'dialog' : 'listbox'
+ isEffectivelyReadOnly
+ ? undefined
+ : surface.activePresentation === 'bottom-sheet'
+ ? 'dialog'
+ : 'listbox'
}
- aria-expanded={surface.isOpen}
- aria-controls={listboxId}
+ aria-expanded={isEffectivelyReadOnly ? false : surface.isOpen}
+ aria-controls={isEffectivelyReadOnly ? undefined : listboxId}
+ aria-readonly={isEffectivelyReadOnly || undefined}
aria-activedescendant={
- !hasSearch && surface.isOpen && highlightedIndex >= 0
+ !isEffectivelyReadOnly &&
+ !hasSearch &&
+ surface.isOpen &&
+ highlightedIndex >= 0
? getItemId(highlightedIndex)
: undefined
}
- aria-describedby={ariaDescribedBy}
- aria-labelledby={ariaLabelledBy}
- aria-required={isEffectivelyRequired ? 'true' : undefined}
- aria-invalid={status?.type === 'error' ? 'true' : undefined}
- aria-busy={isBusy || undefined}
// With a disabledMessage the trigger keeps focusability via
// aria-disabled so the reason is focus-discoverable; activation is
// still blocked by the isDisabled guards in useMultiCombobox.
disabled={isDisabled && !showsDisabledMessage}
- aria-disabled={showsDisabledMessage ? 'true' : undefined}
- onKeyDown={onKeyDown}
- onFocus={event => {
- onFocus?.(event);
- surface.onTriggerFocus(event);
- }}
- tabIndex={isDisabled && !showsDisabledMessage ? -1 : 0}
- {...stylex.props(styles.trigger)}>
+ aria-disabled={showsDisabledMessage ? 'true' : undefined}>
<span {...stylex.props(styles.triggerContent)}>
{renderTriggerContent()}
</span>
@@ -1790,14 +1856,17 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
/>
))}
{isBusy && <Spinner size="sm" />}
- {hasClear && value.length > 0 && !isDisabled && (
- <InternalInputClearButton
- {...keepOpenProps}
- label={t('@astryx.multiSelector.clearAll', {label})}
- onClick={handleClear}
- iconClassName={stableClassName('multi-selector-clear-icon')}
- />
- )}
+ {hasClear &&
+ value.length > 0 &&
+ !isDisabled &&
+ !isEffectivelyReadOnly && (
+ <InternalInputClearButton
+ {...keepOpenProps}
+ label={t('@astryx.multiSelector.clearAll', {label})}
+ onClick={handleClear}
+ iconClassName={stableClassName('multi-selector-clear-icon')}
+ />
+ )}
{/*
No wrapper span: Icon's own span already provides the 16px box (`sm`)
and the icon color, so the status glyph and the chevron are each
@@ -1832,7 +1901,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
xstyle={styles.triggerIcon}
/>
)
- ) : (
+ ) : !isEffectivelyReadOnly ? (
<Icon
icon="chevronDown"
size="sm"
@@ -1854,7 +1923,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
state: surface.isOpen ? 'expanded' : 'collapsed',
})}
/>
- )}
+ ) : null}
</div>
{selectionSurface}
diff --git a/packages/core/src/Selector/Selector.doc.mjs b/packages/core/src/Selector/Selector.doc.mjs
index e73456886e..1371407713 100644
--- a/packages/core/src/Selector/Selector.doc.mjs
+++ b/packages/core/src/Selector/Selector.doc.mjs
@@ -12,7 +12,7 @@ const anatomy = [
name: 'Trigger',
required: true,
description:
- 'Painted control that displays the current selection or placeholder and opens the selection surface.',
+ 'Painted control that displays the current selection or placeholder and opens the selection surface when editable.',
},
{
name: 'Icon-rendered start icon',
@@ -146,7 +146,7 @@ export const docs = {
{
className: 'astryx-selector',
visualProps: ['variant', 'size', 'status'],
- states: ['disabled'],
+ states: ['disabled', 'readonly'],
},
{className: 'astryx-selector-option'},
{
@@ -250,6 +250,13 @@ export const docs = {
description: 'Disables the selector.',
default: 'false',
},
+ {
+ name: 'isReadOnly',
+ type: 'boolean',
+ description:
+ 'Makes the selector read-only: the selected value stays visible, focusable, and included in form submission, and retains its combobox identity with aria-readonly. The selection surface, clear action, and disclosure indicator are removed. Unlike isDisabled, the control is not dimmed. isDisabled takes precedence when both are set.',
+ default: 'false',
+ },
{
name: 'htmlName',
type: 'string',
diff --git a/packages/core/src/Selector/Selector.spec.md b/packages/core/src/Selector/Selector.spec.md
index e736be185f..054f4e0ab5 100644
--- a/packages/core/src/Selector/Selector.spec.md
+++ b/packages/core/src/Selector/Selector.spec.md
@@ -26,7 +26,7 @@ architecture:
architecture:public-component-api,
]
contributing: []
-system_specs: [spec:AST-004/DEC-1]
+system_specs: [spec:AST-004/DEC-1, spec:AST-011/DEC-1]
---
# Selector component contract
@@ -47,6 +47,9 @@ connection between the closed trigger and its selection surface.
presentation, and `adaptive` selects it on compact coarse-pointer screens.
- `hasClear` changes the value contract to include `null`; that distinction is
already part of the public type.
+- `isReadOnly` is additive and defaults to `false`. It preserves the selected
+ value, focus, and form participation while removing selection-surface and
+ editing affordances. `isDisabled` takes precedence when both are set.
- `spec:AST-004/DEC-1` accepts a future change that collapses an empty indicator
column. It is not shipped behavior and does not replace FR3 until implementation,
visual verification, and an update to this current contract land together.
@@ -75,14 +78,15 @@ connection between the closed trigger and its selection surface.
This table names semantic concepts reviewers need. Prop syntax, complete defaults,
and examples remain in `Selector.doc.mjs`.
-| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
-| ---------------------- | -------------------------------------- | ------------------------------------------------------- | ----------------------------------------- | --------- | -------- | --------- | ------------------------------- |
-| trigger variant | `input`, `ghost` | Form-field or toolbar presentation | All trigger states | `input` | Selector | released | TypeScript rejects other values |
-| size | `sm`, `md`, `lg` | Trigger and option-row density | All presentations | `md` | Selector | released | TypeScript rejects other values |
-| selected-mark position | `start`, `end` | Logical edge containing the reserved selection column | Every option row | `end` | Selector | released | TypeScript rejects other values |
-| presentation | `popover`, `bottom-sheet`, `adaptive` | Anchored pointer surface or modal compact-touch surface | All trigger variants | `popover` | Selector | released | TypeScript rejects other values |
-| popup semantics | `listbox`; modal dialog containing one | Semantics follow the active presentation | Popover; bottom sheet | `listbox` | Selector | released | No separate role prop is public |
-| option-row state | `selected`, `disabled` | Stable theming state on each option row | Every rendered option | neither | Selector | released | Unknown states are not emitted |
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ---------------------- | -------------------------------------- | -------------------------------------------------------- | ----------------------------------------- | --------- | -------- | --------- | ------------------------------- |
+| trigger variant | `input`, `ghost` | Form-field or toolbar presentation | All trigger states | `input` | Selector | released | TypeScript rejects other values |
+| size | `sm`, `md`, `lg` | Trigger and option-row density | All presentations | `md` | Selector | released | TypeScript rejects other values |
+| selected-mark position | `start`, `end` | Logical edge containing the reserved selection column | Every option row | `end` | Selector | released | TypeScript rejects other values |
+| presentation | `popover`, `bottom-sheet`, `adaptive` | Anchored pointer surface or modal compact-touch surface | All trigger variants | `popover` | Selector | released | TypeScript rejects other values |
+| popup semantics | `listbox`; modal dialog containing one | Semantics follow the active presentation | Popover; bottom sheet | `listbox` | Selector | released | No separate role prop is public |
+| option-row state | `selected`, `disabled` | Stable theming state on each option row | Every rendered option | neither | Selector | released | Unknown states are not emitted |
+| read-only state | `false`, `true` | Preserves and submits value without selection affordance | Closed trigger | `false` | Caller | additive | Boolean normalization |
## Behavioral and layout contract
@@ -95,6 +99,7 @@ These requirements describe shipped behavior on current `main`.
| FR3 | Every option row reserves one selection-mark column at `indicatorPosition`, even when the default unchecked indicator draws nothing. The column has a minimum width and can grow for a larger themed replacement. | `itemMarkColumn`, indicator-position tests, and theme tests |
| FR4 | `popover` uses an anchored Popover. `bottom-sheet` uses a modal BottomSheet. `adaptive` resolves to the modal bottom sheet on compact coarse-pointer screens and Popover otherwise. | Presentation controller and adaptive-presentation tests |
| FR5 | While `isLoading` is true, the trigger exposes busy state and the listbox suppresses empty and no-results output. | Loading, empty-state, and announcement tests |
+| FR6 | While `isReadOnly` is true, the selected value remains focusable and form-submittable, while the selection surface, clear action, disclosure indicator, and every value-change path are unavailable. | Read-only interaction, form, and accessibility tests |
### Allowed variation
@@ -105,20 +110,21 @@ These requirements describe shipped behavior on current `main`.
while Selector keeps row role, selection, disabled state, navigation, and
theming state.
- **AV3 — Selected value content.** `renderValue` may replace the closed value
- display without changing the placeholder or trigger's selection role.
+ display without changing its combobox identity, whether editable or read-only.
### Representative states
-| State | Required invariant | Allowed variation |
-| ------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------ |
-| closed with no value | Label and placeholder identify the field | Consumer placeholder text |
-| closed with a value | Selected option is represented in the trigger | Custom `renderValue` content |
-| pointer / popover | Anchored surface exposes the listbox without modal-dialog semantics | Default or explicit placement |
-| compact coarse pointer | BottomSheet exposes a modal dialog containing the listbox | Explicit `bottom-sheet` or resolved `adaptive` |
-| searching | Visible options, keyboard navigation, and announced result count use one filter | Consumer search and empty text |
-| loading | Trigger is busy; empty and no-results output is suppressed | Consumer loading duration |
-| disabled with reason | Trigger remains focusable enough to expose the reason while activation stays blocked | Consumer reason text |
-| selected/unselected rows | Row semantics and theming state are correct; both reserve the indicator column | Start/end position and themed indicator representation |
+| State | Required invariant | Allowed variation |
+| ------------------------ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------ |
+| closed with no value | Label and placeholder identify the field | Consumer placeholder text |
+| closed with a value | Selected option is represented in the trigger | Custom `renderValue` content |
+| pointer / popover | Anchored surface exposes the listbox without modal-dialog semantics | Default or explicit placement |
+| compact coarse pointer | BottomSheet exposes a modal dialog containing the listbox | Explicit `bottom-sheet` or resolved `adaptive` |
+| searching | Visible options, keyboard navigation, and announced result count use one filter | Consumer search and empty text |
+| loading | Trigger is busy; empty and no-results output is suppressed | Consumer loading duration |
+| disabled with reason | Trigger remains focusable enough to expose the reason while activation stays blocked | Consumer reason text |
+| read-only | Value stays focusable and submittable; menu, clear, and disclosure affordances are absent | Value rendering, status, and busy presentation |
+| selected/unselected rows | Row semantics and theming state are correct; both reserve the indicator column | Start/end position and themed indicator representation |
### Transformation and precedence order
@@ -151,6 +157,16 @@ These requirements describe shipped behavior on current `main`.
- **AR3 — Keyboard selection matches the visible set.** Arrow, Home/End,
typeahead, search, Enter, Escape, and Tab behavior operate on the options a
person can currently perceive.
+- **AR4 — Read-only semantics match availability.** A read-only value stays
+ focusable, retains `role="combobox"`, and exposes `aria-readonly="true"` plus
+ `aria-expanded="false"`. Its rendered content remains the combobox value. It
+ does not expose `aria-controls`, `aria-activedescendant`, or an active selection
+ surface. The implicit listbox popup describes the widget's selection capability;
+ read-only state communicates that its value cannot currently change. Chromium's
+ button-hosted combobox mapping omits the ARIA read-only property, so a localized
+ accessible description also announces that state. Search and non-search modes
+ use the same read-only combobox semantics because neither exposes a search
+ control in this state.
## Design relationships
@@ -247,20 +263,23 @@ in `spec:AST-004` as current runtime behavior.
- `spec:AST-004/DEC-1` owns the accepted future indicator-space change. Its
`accepted` phase is direction for implementation, not evidence that the runtime
has changed.
+- `spec:AST-011/DEC-1` owns the additive read-only state: caller-owned policy can
+ preserve a focusable, submittable value without exposing selection controls.
- `family:input-fields` remains a draft. It may inform future reconciliation, but
this current component contract neither backlinks to it in frontmatter nor
depends on it for present policy.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| --------------------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------- |
-| FR1, AR2, AR3 | `Selector.test.tsx` selection, focus, and keyboard suites | closed/open, search/non-search, disabled option | Removing selection wiring, focus movement, or keyboard behavior fails the named interaction tests | `audit:Selector/behavior` |
-| FR2 | placement and selected-item geometry tests | default, explicit, RTL, transformed entry | Using the wrong positioning model fails the expected position-area or margin | `audit:Selector/behavior` |
-| FR3, AV1 | `itemMarkColumn` source inspection plus indicator-position and replacement-indicator tests | start/end, selected/unselected, check/radio | Removing the wrapper fails row-structure tests; changing its reserved width requires source/layout review | `audit:Selector/design-rendered` |
-| FR4, AR1, AR2 | presentation tests plus `aria-haspopup` source review | pointer, compact coarse pointer, search/non-search | Wrong Popover/dialog roles or focus destinations fail tests; `aria-haspopup` values require source/a11y review | `audit:Selector/accessibility` |
-| FR5 | loading, empty-state, and live-region tests | empty options, unmatched search, loading | Empty/no-results output appears or is announced while loading | `audit:Selector/behavior` |
-| source-build contract | `Selector.source-build.test.mjs` | package source compiled by consumer Babel | Moving evaluated StyleX values outside the supported source form fails compilation | `audit:Selector/code-health` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| --------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------- |
+| FR1, AR2, AR3 | `Selector.test.tsx` selection, focus, and keyboard suites | closed/open, search/non-search, disabled option | Removing selection wiring, focus movement, or keyboard behavior fails the named interaction tests | `audit:Selector/behavior` |
+| FR2 | placement and selected-item geometry tests | default, explicit, RTL, transformed entry | Using the wrong positioning model fails the expected position-area or margin | `audit:Selector/behavior` |
+| FR3, AV1 | `itemMarkColumn` source inspection plus indicator-position and replacement-indicator tests | start/end, selected/unselected, check/radio | Removing the wrapper fails row-structure tests; changing its reserved width requires source/layout review | `audit:Selector/design-rendered` |
+| FR4, AR1, AR2 | presentation tests plus `aria-haspopup` source review | pointer, compact coarse pointer, search/non-search | Wrong Popover/dialog roles or focus destinations fail tests; `aria-haspopup` values require source/a11y review | `audit:Selector/accessibility` |
+| FR5 | loading, empty-state, and live-region tests | empty options, unmatched search, loading | Empty/no-results output appears or is announced while loading | `audit:Selector/behavior` |
+| FR6, AR4 | 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:Selector/accessibility` |
+| source-build contract | `Selector.source-build.test.mjs` | package source compiled by consumer Babel | Moving evaluated StyleX values outside the supported source form fails compilation | `audit:Selector/code-health` |
## Decision log
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index 874690d793..85cf686438 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -1167,7 +1167,12 @@ describe('Selector', () => {
render(
<Selector label="Fruit" options={[]} onChange={() => {}} isLoading />,
);
- await user.click(screen.getByRole('combobox', {name: 'Fruit'}));
+ const trigger = screen.getByRole('combobox', {name: 'Fruit'});
+ expect(trigger).toHaveAttribute('aria-busy', 'true');
+ expect(screen.getByRole('status', {name: 'Loading'})).toBeInTheDocument();
+
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
// useAnnounce writes on the next animation frame, so an immediate read
// would pass whether or not anything was announced.
@@ -2434,6 +2439,318 @@ describe('Selector', () => {
expect(trigger).toHaveAttribute('tabIndex', '-1');
});
});
+ describe('isReadOnly', () => {
+ const readOnlyCases = [
+ {presentation: 'popover', hasSearch: false},
+ {presentation: 'popover', hasSearch: true},
+ {presentation: 'bottom-sheet', hasSearch: false},
+ {presentation: 'bottom-sheet', hasSearch: true},
+ {presentation: 'adaptive', hasSearch: false},
+ {presentation: 'adaptive', hasSearch: true},
+ ] as const;
+
+ const sheetTransitionCases = [
+ {presentation: 'bottom-sheet', hasSearch: false},
+ {presentation: 'bottom-sheet', hasSearch: true},
+ {presentation: 'adaptive', hasSearch: false},
+ {presentation: 'adaptive', hasSearch: true},
+ ] as const;
+
+ const disabledPrecedenceCases = (
+ ['popover', 'bottom-sheet', 'adaptive'] as const
+ ).flatMap(presentation =>
+ [false, true].flatMap(hasSearch =>
+ [false, true].map(hasDisabledMessage => ({
+ presentation,
+ hasSearch,
+ hasDisabledMessage,
+ })),
+ ),
+ );
+
+ function stubCompactTouch(presentation: 'bottom-sheet' | 'adaptive') {
+ if (presentation !== 'adaptive') {
+ return;
+ }
+ vi.mocked(matchMedia).mockImplementation(
+ (query: string) =>
+ ({
+ matches: query === '(max-width: 768px) and (pointer: coarse)',
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ }) as MediaQueryList,
+ );
+ }
+
+ it.each(readOnlyCases)(
+ 'uses a read-only combobox with no rendered popup ($presentation, search=$hasSearch)',
+ async ({presentation, hasSearch}) => {
+ const user = userEvent.setup();
+ const {container} = render(
+ <form>
+ <Selector
+ label="Fruit"
+ htmlName="fruit"
+ options={OPTIONS}
+ value="Banana"
+ onChange={() => {}}
+ hasClear
+ hasSearch={hasSearch}
+ presentation={presentation}
+ isDefaultOpen
+ isReadOnly
+ />
+ </form>,
+ );
+
+ const trigger = screen.getByRole('combobox', {name: 'Fruit'});
+ expect(trigger.tagName).toBe('BUTTON');
+ expect(trigger).toHaveTextContent('Banana');
+ expect(trigger).toHaveAttribute('aria-readonly', 'true');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ const readOnlyDescription = screen.getByText('Read only');
+ expect(trigger.getAttribute('aria-describedby')).toContain(
+ readOnlyDescription.id,
+ );
+ expect(trigger).not.toHaveAttribute('aria-controls');
+ expect(trigger).not.toHaveAttribute('aria-haspopup');
+ expect(screen.getAllByRole('combobox', h)).toHaveLength(1);
+ expect(screen.queryByRole('listbox', h)).not.toBeInTheDocument();
+ expect(screen.queryByRole('dialog', h)).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: 'Clear Fruit'}),
+ ).not.toBeInTheDocument();
+ expect(
+ container.querySelector('.astryx-selector-indicator-icon'),
+ ).toBeNull();
+ expect(container.querySelector('.astryx-selector')).toHaveAttribute(
+ 'data-readonly',
+ 'readonly',
+ );
+ expect(
+ new FormData(container.querySelector('form')!).get('fruit'),
+ ).toBe('Banana');
+
+ await user.tab();
+ expect(trigger).toHaveFocus();
+ },
+ );
+
+ it('localizes the accessible read-only description', () => {
+ render(
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{fr: {'@astryx.input.readOnly': 'Lecture seule'}}}>
+ <Selector label="Fruit" options={OPTIONS} value="Banana" isReadOnly />
+ </InternationalizationProvider>,
+ );
+
+ const trigger = screen.getByRole('combobox', {name: 'Fruit'});
+ const description = screen.getByText('Lecture seule');
+ expect(trigger.getAttribute('aria-describedby')).toContain(
+ description.id,
+ );
+ });
+
+ it('keeps loading feedback while blocking the selection surface', async () => {
+ const user = userEvent.setup();
+ render(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ isLoading
+ isReadOnly
+ />,
+ );
+
+ const trigger = screen.getByRole('combobox', {name: 'Fruit'});
+ expect(trigger).toHaveAttribute('aria-busy', 'true');
+ expect(screen.getByRole('status', {name: 'Loading'})).toBeInTheDocument();
+
+ await user.click(trigger);
+ expect(screen.queryByRole('listbox', h)).not.toBeInTheDocument();
+ });
+
+ it('blocks pointer, keyboard, and typeahead changes', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const changeAction = vi.fn();
+ render(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ onChange={onChange}
+ changeAction={changeAction}
+ isReadOnly
+ />,
+ );
+
+ const trigger = screen.getByRole('combobox');
+ await user.click(trigger);
+ trigger.focus();
+ await user.keyboard('{Enter}{ArrowDown}c{Backspace}');
+
+ expect(screen.queryByRole('listbox', h)).not.toBeInTheDocument();
+ expect(onChange).not.toHaveBeenCalled();
+ expect(changeAction).not.toHaveBeenCalled();
+ });
+
+ it.each([false, true])(
+ 'restores popover focus when an open selector becomes read-only (search=%s)',
+ async hasSearch => {
+ const user = userEvent.setup();
+ const selector = (isReadOnly: boolean) => (
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ hasSearch={hasSearch}
+ isReadOnly={isReadOnly}
+ />
+ );
+ const {rerender} = render(selector(false));
+ const editableTrigger = screen.getByRole(
+ hasSearch ? 'button' : 'combobox',
+ {name: 'Fruit'},
+ );
+ await user.click(editableTrigger);
+ if (hasSearch) {
+ await waitFor(() =>
+ expect(screen.getByRole('combobox', h)).toHaveFocus(),
+ );
+ }
+
+ rerender(selector(true));
+
+ const readOnlyTrigger = screen.getByRole('combobox', {name: 'Fruit'});
+ await waitFor(() => expect(readOnlyTrigger).toHaveFocus());
+ expect(screen.queryByRole('listbox', h)).not.toBeInTheDocument();
+ },
+ );
+
+ it.each(sheetTransitionCases)(
+ 'finishes $presentation close and restores focus when read-only changes (search=$hasSearch)',
+ async ({presentation, hasSearch}) => {
+ stubCompactTouch(presentation);
+ const user = userEvent.setup();
+ const selector = (isReadOnly: boolean) => (
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ hasSearch={hasSearch}
+ presentation={presentation}
+ isReadOnly={isReadOnly}
+ />
+ );
+ const {rerender} = render(selector(false));
+ const editableTrigger = screen.getByRole(
+ hasSearch ? 'button' : 'combobox',
+ {name: 'Fruit'},
+ );
+ await user.click(editableTrigger);
+ const dialog = await screen.findByRole('dialog', {name: 'Fruit'});
+ const panel = dialog.querySelector<HTMLElement>('.astryx-bottom-sheet');
+ expect(panel).not.toBeNull();
+ await waitFor(() =>
+ expect(
+ hasSearch
+ ? screen.getByRole('combobox', h)
+ : screen.getByRole('listbox'),
+ ).toHaveFocus(),
+ );
+
+ rerender(selector(true));
+
+ await waitFor(() => expect(dialog).toHaveAttribute('inert'));
+ fireEvent.transitionEnd(panel!, {propertyName: 'transform'});
+ const readOnlyTrigger = screen.getByRole('combobox', {name: 'Fruit'});
+ await waitFor(() => expect(readOnlyTrigger).toHaveFocus());
+ expect(screen.queryByRole('dialog', h)).not.toBeInTheDocument();
+ expect(screen.queryByRole('listbox', h)).not.toBeInTheDocument();
+ },
+ );
+
+ it.each(disabledPrecedenceCases)(
+ 'matches disabled-only semantics for $presentation (search=$hasSearch, reason=$hasDisabledMessage)',
+ async ({presentation, hasSearch, hasDisabledMessage}) => {
+ if (presentation === 'adaptive') {
+ stubCompactTouch(presentation);
+ }
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const selector = (isReadOnly: boolean) => (
+ <form>
+ <Selector
+ label="Fruit"
+ htmlName="fruit"
+ options={OPTIONS}
+ value="Banana"
+ onChange={onChange}
+ hasClear
+ hasSearch={hasSearch}
+ presentation={presentation}
+ isDisabled
+ isReadOnly={isReadOnly}
+ disabledMessage={
+ hasDisabledMessage ? 'Locked by policy' : undefined
+ }
+ />
+ </form>
+ );
+ const {container, rerender} = render(selector(false));
+ const getTrigger = () =>
+ screen.getByRole(hasSearch ? 'button' : 'combobox', {name: 'Fruit'});
+ const snapshot = () => {
+ const trigger = getTrigger();
+ const root = container.querySelector('.astryx-selector');
+ return {
+ tagName: trigger.tagName,
+ role: trigger.getAttribute('role'),
+ hasPopup: trigger.getAttribute('aria-haspopup'),
+ expanded: trigger.getAttribute('aria-expanded'),
+ controls: trigger.getAttribute('aria-controls'),
+ readOnly: trigger.getAttribute('aria-readonly'),
+ disabled: trigger.matches(':disabled'),
+ ariaDisabled: trigger.getAttribute('aria-disabled'),
+ tabIndex: trigger.tabIndex,
+ rootClassName: root?.className,
+ rootDisabled: root?.getAttribute('data-disabled'),
+ rootReadOnly: root?.getAttribute('data-readonly'),
+ hasIndicator:
+ root?.querySelector('.astryx-selector-indicator-icon') != null,
+ listboxes: screen.queryAllByRole('listbox', h).length,
+ dialogs: screen.queryAllByRole('dialog', h).length,
+ formEntries: [
+ ...new FormData(container.querySelector('form')!).entries(),
+ ],
+ };
+ };
+ const disabledOnly = snapshot();
+
+ rerender(selector(true));
+
+ expect(snapshot()).toEqual(disabledOnly);
+ expect(disabledOnly.rootDisabled).toBe('disabled');
+ expect(disabledOnly.rootReadOnly).toBeNull();
+ expect(disabledOnly.readOnly).toBeNull();
+ expect(disabledOnly.formEntries).toEqual([]);
+ const trigger = getTrigger();
+ await user.click(trigger);
+ trigger.focus();
+ await user.keyboard('{Enter}{ArrowDown}c{Backspace}');
+ expect(onChange).not.toHaveBeenCalled();
+ },
+ );
+ });
+
describe('form participation', () => {
it('submits the selected value under htmlName', () => {
const {container} = render(
diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx
index 50b9c6434f..4d7ad3de4c 100644
--- a/packages/core/src/Selector/Selector.tsx
+++ b/packages/core/src/Selector/Selector.tsx
@@ -244,6 +244,16 @@ const styles = stylex.create({
':active': 'none',
},
},
+ triggerReadOnly: {
+ cursor: 'default',
+ },
+ triggerGhostReadOnly: {
+ backgroundImage: 'none',
+ transform: {
+ default: 'none',
+ ':active': 'none',
+ },
+ },
// Clear button
statusButton: {
@@ -506,6 +516,17 @@ interface SelectorPropsBase<
*/
isDisabled?: boolean;
+ /**
+ * Whether the selector is read-only.
+ * The selected value stays visible, focusable, and included in form
+ * submission, and retains its combobox identity with `aria-readonly`. The
+ * selection surface and editing affordances are removed.
+ * Unlike `isDisabled`, a read-only selector is not dimmed and stays in the
+ * tab order. `isDisabled` takes precedence when both are set.
+ * @default false
+ */
+ isReadOnly?: boolean;
+
/**
* Explains why the selector is disabled. When set together with
* `isDisabled`, the selector shows a tooltip with this text on hover and
@@ -804,6 +825,7 @@ export function Selector<T extends SelectorOptionType>(
isOptional = false,
isRequired = false,
isDisabled = false,
+ isReadOnly = false,
disabledMessage,
options,
value,
@@ -851,6 +873,7 @@ export function Selector<T extends SelectorOptionType>(
variant === 'ghost' && statusVariant === 'attached'
? 'detached'
: statusVariant;
+ const isEffectivelyReadOnly = isReadOnly && !isDisabled;
// Normalize null to undefined for internal use (null is the clear sentinel)
const normalizedValue = value === null ? undefined : value;
@@ -862,11 +885,12 @@ export function Selector<T extends SelectorOptionType>(
const descriptionId = useId();
const statusMessageId = useId();
const inputLabelId = useId();
+ const readOnlyDescriptionId = useId();
const searchId = useId();
// Measure from the same outer control that usePopover anchors to; using the
// shorter inner button makes every size's selected row land too low.
const anchorRef = useRef<HTMLDivElement>(null);
- const triggerRef = useRef<HTMLButtonElement>(null);
+ const triggerRef = useRef<HTMLElement>(null);
const searchRef = useRef<HTMLInputElement>(null);
const inputGroup = useInputGroup();
@@ -923,6 +947,7 @@ export function Selector<T extends SelectorOptionType>(
? statusTooltip.describedBy
: null,
showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
+ isEffectivelyReadOnly ? readOnlyDescriptionId : null,
],
inputGroup,
);
@@ -985,16 +1010,27 @@ export function Selector<T extends SelectorOptionType>(
},
});
const {popover} = surface;
+ const hideSurface = surface.hide;
+ const isSurfaceOpen = surface.isOpen;
const keepOpenProps = useKeepLayerOpenProps(popover.id, popover.isOpen);
- // Open dropdown on mount when isDefaultOpen is true
+ // Open dropdown on mount when isDefaultOpen is true and interaction is allowed.
useEffect(() => {
- if (isDefaultOpen) {
+ if (isDefaultOpen && !isEffectivelyReadOnly) {
surface.show();
}
// eslint-disable-next-line @eslint-react/exhaustive-deps -- mount-only: isDefaultOpen is not reactive
}, []);
+ // Read-only is controlled by caller policy, so an already-open surface must
+ // close when that policy changes. The presentation controller keeps a sheet
+ // mounted through its exit and lets BottomSheet return final focus.
+ useEffect(() => {
+ if (isEffectivelyReadOnly && isSurfaceOpen) {
+ hideSurface();
+ }
+ }, [isEffectivelyReadOnly, isSurfaceOpen, hideSurface]);
+
// Announce the filtered result count from the query-change handlers (matching
// BaseTypeahead) rather than a reactive effect: computing the count for the
// next query here fires the announcement exactly once per keystroke and does
@@ -1145,7 +1181,7 @@ export function Selector<T extends SelectorOptionType>(
// highlight on it and Delete/Backspace could clear a value the action has
// already replaced.
value: optimisticValue,
- isDisabled,
+ isDisabled: isDisabled || isEffectivelyReadOnly,
isOpen: surface.isOpen,
hasSearch,
onOpen: useCallback(() => {
@@ -1197,14 +1233,17 @@ export function Selector<T extends SelectorOptionType>(
const handleTriggerKeyDown = useCallback(
(e: React.KeyboardEvent) => {
+ if (isDisabled || isEffectivelyReadOnly) {
+ return;
+ }
// With hasSearch the query input owns typing, so type-to-select is off.
- if (!isDisabled && !hasSearch && typeahead.onKeyDown(e)) {
+ if (!hasSearch && typeahead.onKeyDown(e)) {
e.preventDefault();
return;
}
onKeyDown(e);
},
- [isDisabled, hasSearch, typeahead, onKeyDown],
+ [isDisabled, isEffectivelyReadOnly, hasSearch, typeahead, onKeyDown],
);
// Keep the highlighted option visible during keyboard navigation. The
@@ -1628,30 +1667,55 @@ export function Selector<T extends SelectorOptionType>(
</div>
);
- const selectionSurface =
- surface.activePresentation === 'bottom-sheet' ? (
- <SelectorBottomSheet
- isOpen={surface.isSheetOpen}
- onOpenChange={surface.onSheetOpenChange}
- finalFocusRef={triggerRef}
- initialFocusRef={hasSearch ? searchRef : listboxRef}
- label={label}>
- {panelContent}
- </SelectorBottomSheet>
- ) : (
- popover.render(panelContent, {
- placement: popoverPlacement,
- alignment: 'start',
- // The system's standard menu clearance, except in overlay mode:
- // there the measured negative margin owns the block geometry and
- // the menu is meant to sit on the trigger, not clear it.
- offset: shouldOverlaySelectedItem
- ? undefined
- : spacingVars['--spacing-1'],
- xstyle: [styles.popover, layerAnimations[popoverPlacement]],
- style: popoverOffsetStyle,
- })
- );
+ let selectionSurface: ReactNode = null;
+ if (surface.activePresentation === 'bottom-sheet') {
+ if (!isEffectivelyReadOnly || surface.isSheetPresented) {
+ selectionSurface = (
+ <SelectorBottomSheet
+ isOpen={surface.isSheetOpen}
+ onOpenChange={surface.onSheetOpenChange}
+ finalFocusRef={triggerRef}
+ initialFocusRef={hasSearch ? searchRef : listboxRef}
+ label={label}>
+ {panelContent}
+ </SelectorBottomSheet>
+ );
+ }
+ } else if (!isEffectivelyReadOnly) {
+ selectionSurface = popover.render(panelContent, {
+ placement: popoverPlacement,
+ alignment: 'start',
+ // The system's standard menu clearance, except in overlay mode:
+ // there the measured negative margin owns the block geometry and
+ // the menu is meant to sit on the trigger, not clear it.
+ offset: shouldOverlaySelectedItem
+ ? undefined
+ : spacingVars['--spacing-1'],
+ xstyle: [styles.popover, layerAnimations[popoverPlacement]],
+ style: popoverOffsetStyle,
+ });
+ }
+
+ const triggerSharedProps: React.HTMLAttributes<HTMLElement> = {
+ ...rest,
+ id: triggerId,
+ 'aria-describedby': ariaDescribedBy,
+ 'aria-labelledby': ariaLabelledBy,
+ 'aria-required': isEffectivelyRequired ? 'true' : undefined,
+ 'aria-invalid': status?.type === 'error' ? 'true' : undefined,
+ 'aria-busy': isBusy || undefined,
+ onKeyDown: handleTriggerKeyDown,
+ onFocus: event => {
+ onFocus?.(event);
+ surface.onTriggerFocus(event);
+ },
+ tabIndex: isDisabled && !showsDisabledMessage ? -1 : 0,
+ ...stylex.props(
+ styles.trigger,
+ isEffectivelyReadOnly && styles.triggerReadOnly,
+ inputGroup && styles.triggerButtonInGroup,
+ ),
+ };
const selectorContent = (
<>
@@ -1672,6 +1736,7 @@ export function Selector<T extends SelectorOptionType>(
size,
status: status?.type ?? null,
disabled: isDisabled ? 'disabled' : null,
+ readonly: isEffectivelyReadOnly ? 'readonly' : null,
}),
stylex.props(
inputWrapperStyles.base,
@@ -1683,7 +1748,11 @@ export function Selector<T extends SelectorOptionType>(
surface.isTriggerFocusRingSuppressed &&
selectorPresentationStyles.pointerRestoredFocus,
isDisabled && inputWrapperStyles.disabled,
+ isEffectivelyReadOnly && styles.triggerReadOnly,
variant === 'ghost' && isDisabled && styles.triggerGhostDisabled,
+ variant === 'ghost' &&
+ isEffectivelyReadOnly &&
+ styles.triggerGhostReadOnly,
!selectedItem && styles.triggerPlaceholder,
variant !== 'ghost' &&
status &&
@@ -1704,45 +1773,43 @@ export function Selector<T extends SelectorOptionType>(
{inputGroup && (
<VisuallyHidden id={inputLabelId}>{label}</VisuallyHidden>
)}
+ {isEffectivelyReadOnly && (
+ <VisuallyHidden id={readOnlyDescriptionId}>
+ {t('@astryx.input.readOnly')}
+ </VisuallyHidden>
+ )}
<button
- ref={triggerRef}
- id={triggerId}
+ {...triggerSharedProps}
+ ref={triggerRef as React.Ref<HTMLButtonElement>}
type="button"
- // In hasSearch mode the popup's search input is the combobox (it owns
- // focus + aria-activedescendant, comboboxes-4), so the trigger is a
- // plain button that opens the listbox — not a second combobox.
- role={hasSearch ? undefined : 'combobox'}
- {...rest}
+ // The read-only trigger stays a combobox even when hasSearch is set:
+ // no search input is rendered in that state, and preserving the role
+ // keeps the control's programmatic identity stable. Editable search
+ // mode still moves combobox semantics to the popup input.
+ role={isEffectivelyReadOnly || !hasSearch ? 'combobox' : undefined}
aria-haspopup={
- surface.activePresentation === 'bottom-sheet' ? 'dialog' : 'listbox'
+ isEffectivelyReadOnly
+ ? undefined
+ : surface.activePresentation === 'bottom-sheet'
+ ? 'dialog'
+ : 'listbox'
}
- aria-expanded={surface.isOpen}
- aria-controls={listboxId}
+ aria-expanded={isEffectivelyReadOnly ? false : surface.isOpen}
+ aria-controls={isEffectivelyReadOnly ? undefined : listboxId}
+ aria-readonly={isEffectivelyReadOnly || undefined}
aria-activedescendant={
- !hasSearch && surface.isOpen && highlightedIndex >= 0
+ !isEffectivelyReadOnly &&
+ !hasSearch &&
+ surface.isOpen &&
+ highlightedIndex >= 0
? getItemId(highlightedIndex)
: undefined
}
- aria-describedby={ariaDescribedBy}
- aria-labelledby={ariaLabelledBy}
- aria-required={isEffectivelyRequired ? 'true' : undefined}
- aria-invalid={status?.type === 'error' ? 'true' : undefined}
- aria-busy={isBusy || undefined}
// With a disabledMessage the trigger keeps focusability via
// aria-disabled so the reason is focus-discoverable; activation is
// still blocked by the isDisabled guards in useCombobox.
disabled={isDisabled && !showsDisabledMessage}
- aria-disabled={showsDisabledMessage ? 'true' : undefined}
- onKeyDown={handleTriggerKeyDown}
- onFocus={event => {
- onFocus?.(event);
- surface.onTriggerFocus(event);
- }}
- tabIndex={isDisabled && !showsDisabledMessage ? -1 : 0}
- {...stylex.props(
- styles.trigger,
- inputGroup && styles.triggerButtonInGroup,
- )}>
+ aria-disabled={showsDisabledMessage ? 'true' : undefined}>
{valueContent}
</button>
{htmlName != null && (
@@ -1756,7 +1823,7 @@ export function Selector<T extends SelectorOptionType>(
/>
)}
{isBusy && <Spinner size="sm" />}
- {hasClear && value != null && !isDisabled && (
+ {hasClear && value != null && !isDisabled && !isEffectivelyReadOnly && (
<InternalInputClearButton
{...keepOpenProps}
label={t('@astryx.selector.clearLabel', {label})}
@@ -1798,7 +1865,7 @@ export function Selector<T extends SelectorOptionType>(
xstyle={styles.triggerIcon}
/>
)
- ) : (
+ ) : !isEffectivelyReadOnly ? (
<Icon
icon="chevronDown"
size="sm"
@@ -1820,7 +1887,7 @@ export function Selector<T extends SelectorOptionType>(
state: surface.isOpen ? 'expanded' : 'collapsed',
})}
/>
- )}
+ ) : null}
</div>
{selectionSurface}
diff --git a/packages/core/src/Selector/useSelectorPresentation.ts b/packages/core/src/Selector/useSelectorPresentation.ts
index 2bbd0c9ee4..d153fb0e0a 100644
--- a/packages/core/src/Selector/useSelectorPresentation.ts
+++ b/packages/core/src/Selector/useSelectorPresentation.ts
@@ -40,6 +40,7 @@ interface SelectorPresentationController {
hide: () => void;
isOpen: boolean;
isSheetOpen: boolean;
+ isSheetPresented: boolean;
isTriggerFocusRingSuppressed: boolean;
onSheetOpenChange: (isOpen: boolean) => void;
onTriggerFocus: (event: FocusEvent<HTMLElement>) => void;
@@ -59,6 +60,10 @@ export function useSelectorPresentation({
useRef<ResolvedAdaptivePresentation>(resolvedPresentation);
const [isSheetOpen, setIsSheetOpen] = useState(false);
const isSheetOpenRef = useRef(false);
+ // BottomSheet owns its exit animation and final-focus handoff. Keep it mounted
+ // after the controlled open state turns false until that handoff reaches the
+ // trigger, then consumers may remove the hidden surface tree.
+ const [isSheetPresented, setIsSheetPresented] = useState(false);
const onHideRef = useRef(onHide);
const {
isFocusRingSuppressed,
@@ -88,8 +93,10 @@ export function useSelectorPresentation({
activePresentationRef.current = resolvedPresentation;
if (resolvedPresentation === 'bottom-sheet') {
isSheetOpenRef.current = true;
+ setIsSheetPresented(true);
setIsSheetOpen(true);
} else {
+ setIsSheetPresented(false);
showPopover();
}
}, [resetFocusReturn, resolvedPresentation, showPopover]);
@@ -106,7 +113,18 @@ export function useSelectorPresentation({
}, [hidePopover, prepareFocusReturn]);
const handleTriggerFocus = useCallback(
- (_event: FocusEvent<HTMLElement>) => onFocusReturnTargetFocus(),
+ (_event: FocusEvent<HTMLElement>) => {
+ onFocusReturnTargetFocus();
+ if (
+ !isSheetOpenRef.current &&
+ activePresentationRef.current === 'bottom-sheet'
+ ) {
+ // BottomSheet focuses finalFocusRef only after its exit completes. That
+ // focus event is the lifecycle signal that the retained sheet can now
+ // leave the tree without dropping focus to the document body.
+ setIsSheetPresented(false);
+ }
+ },
[onFocusReturnTargetFocus],
);
@@ -122,9 +140,10 @@ export function useSelectorPresentation({
);
const isOpen = popover.isOpen || isSheetOpen;
- const activePresentation = isOpen
- ? activePresentationRef.current
- : resolvedPresentation;
+ const activePresentation =
+ isOpen || isSheetPresented
+ ? activePresentationRef.current
+ : resolvedPresentation;
const wasJustDismissed = useCallback(
() =>
@@ -137,6 +156,7 @@ export function useSelectorPresentation({
hide,
isOpen,
isSheetOpen,
+ isSheetPresented,
isTriggerFocusRingSuppressed: isFocusRingSuppressed,
onSheetOpenChange: handleSheetOpenChange,
onTriggerFocus: handleTriggerFocus,