Skip to content

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

TypeScript

feat(MultiSelector): hasCreate — a Create "<query>" row for a search that matches nothing (#6829)

Christopher Chedeau03f7d70e3632
diff --git a/.changeset/multi-selector-create-row.md b/.changeset/multi-selector-create-row.md
new file mode 100644
index 0000000000..170533c489
--- /dev/null
+++ b/.changeset/multi-selector-create-row.md
@@ -0,0 +1,17 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `MultiSelector` can offer a `Create "<query>"` row for a search that matches nothing.
+
+With `hasSearch`, the new `hasCreate` switch puts a `Create "<query>"` row
+first in the list when the trimmed query equals no option label under the
+search's own case-insensitive matching and the options have loaded. Picking it, or Enter
+with nothing highlighted, calls `onChange` with the query appended to the value
+and a second argument `{type: 'create', query}` (exported as
+`MultiSelectorChange`), then clears the search; the caller adds an option for
+the new value in that same update. Every other change passes no descriptor, so
+existing one-argument handlers are unchanged. `hasCreate` without `hasSearch`
+warns in development and offers nothing. Off by default.
+
+@vjeux
diff --git a/apps/storybook/stories/MultiSelector.stories.tsx b/apps/storybook/stories/MultiSelector.stories.tsx
index 5d134a4fa3..1efad72dd8 100644
--- a/apps/storybook/stories/MultiSelector.stories.tsx
+++ b/apps/storybook/stories/MultiSelector.stories.tsx
@@ -751,3 +751,34 @@ export const EndIndicatorPosition: Story = {
);
},
};
+
+export const CreateFromQuery: Story = {
+ render: () => {
+ const [options, setOptions] = useState([
+ {value: 'bug', label: 'Bug'},
+ {value: 'feature', label: 'Feature'},
+ {value: 'docs', label: 'Docs'},
+ ]);
+ const [value, setValue] = useState<string[]>(['bug']);
+ return (
+ <MultiSelector
+ label="Labels"
+ options={options}
+ value={value}
+ onChange={(next, change) => {
+ if (change?.type === 'create') {
+ setOptions(current => [
+ ...current,
+ {value: change.query, label: change.query},
+ ]);
+ }
+ setValue(next);
+ }}
+ hasSearch
+ hasCreate
+ triggerDisplay="badges"
+ isDefaultOpen
+ />
+ );
+ },
+};
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index 47f6838e40..d1a856ad57 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -1355,6 +1355,14 @@
"defaultMessage": "{count, number} of {total, number} selected",
"description": "Polite screen-reader announcement of how many MultiSelector options are selected out of the total, spoken after each toggle. Live-region text, never shown on screen; example: `3 of 12 selected`."
},
+ "@astryx.multiSelector.createOption": {
+ "defaultMessage": "Create \"{query}\"",
+ "description": "Label of the first row in a MultiSelector's search panel when `hasCreate` is set and the typed text matches no option. Picking it reports a creation to the caller. `{query}` is the trimmed text the person typed, shown in quotes."
+ },
+ "@astryx.multiSelector.optionCreated": {
+ "defaultMessage": "{label} created",
+ "description": "Polite screen-reader announcement after the create row of a MultiSelector is picked. Live-region text, never shown on screen; `{label}` is the text the person typed."
+ },
"@astryx.multiSelector.emptySearchResults": {
"defaultMessage": "No results found",
"description": "Shown in a MultiSelector's dropdown panel when the search query matches no options, and announced in a polite live region at the same time. Short; neutral tone (not error-y)."
diff --git a/packages/core/src/MultiSelector/CreateRow.a11y.chromium.spec.ts b/packages/core/src/MultiSelector/CreateRow.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..2e27242fdb
--- /dev/null
+++ b/packages/core/src/MultiSelector/CreateRow.a11y.chromium.spec.ts
@@ -0,0 +1,91 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CreateRow.a11y.chromium.spec.ts
+ * @input The `Core/MultiSelector` CreateFromQuery story in a built Storybook.
+ * @output Real-engine proof of the create row's appear/disappear cycle: what
+ * the live region says as the row comes and goes, and where the highlight
+ * lands when the row vanishes mid-type.
+ * @position Run with `pnpm test:a11y-contract`; a DOM emulator cannot show
+ * the live region and the active descendant as a screen reader sees them
+ * across a sequence of keystrokes.
+ */
+
+import {expect, test, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+async function polite(page: Page): Promise<string> {
+ return page.evaluate(
+ () =>
+ document
+ .querySelector('[data-astryx-live-region="polite"]')
+ ?.textContent?.trim() ?? '',
+ );
+}
+
+async function activeDescendantText(page: Page): Promise<string | null> {
+ return page.evaluate(() => {
+ const id = document.activeElement?.getAttribute('aria-activedescendant');
+ return id ? (document.getElementById(id)?.textContent?.trim() ?? '') : null;
+ });
+}
+
+test('the create row is announced as it appears and the highlight survives it vanishing', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-multiselector--create-from-query&viewMode=story`,
+ );
+ const search = page.getByRole('combobox');
+ await expect(search).toBeFocused();
+
+ // "Bu": a partial match plus the create row above it.
+ await search.pressSequentially('Bu');
+ await expect(page.getByRole('option')).toHaveText(['Create "Bu"', 'Bug']);
+ await expect.poll(async () => polite(page)).toBe('1 result');
+
+ // Highlight the create row, then type the letter that makes it vanish: the
+ // highlight must not be left pointing at a row that no longer exists.
+ await search.press('ArrowDown');
+ await expect.poll(async () => activeDescendantText(page)).toBe('Create "Bu"');
+ await search.press('g');
+ await expect(page.getByRole('option')).toHaveText(['Bug']);
+ await expect
+ .poll(async () => activeDescendantText(page))
+ .not.toBe('Create "Bu"');
+ const after = await activeDescendantText(page);
+ expect(after === null || after === 'Bug').toBe(true);
+
+ // A query that matches nothing: the row is the whole result and the region
+ // says so rather than "No results found".
+ await search.fill('');
+ await search.pressSequentially('Urgent');
+ await expect(page.getByRole('option')).toHaveText(['Create "Urgent"']);
+ await expect.poll(async () => polite(page)).toBe('Create "Urgent"');
+
+ // Enter commits: the caller adds the option, the search clears, and the new
+ // label is a real row.
+ await search.press('Enter');
+ await expect.poll(async () => polite(page)).toBe('Urgent created');
+ await expect(search).toHaveValue('');
+ await expect(page.getByRole('option', {name: 'Urgent'})).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+});
diff --git a/packages/core/src/MultiSelector/MultiSelector.doc.mjs b/packages/core/src/MultiSelector/MultiSelector.doc.mjs
index 363954dad1..698239edc3 100644
--- a/packages/core/src/MultiSelector/MultiSelector.doc.mjs
+++ b/packages/core/src/MultiSelector/MultiSelector.doc.mjs
@@ -194,8 +194,9 @@ export const docs = {
},
{
name: 'onChange',
- type: '(value: string[]) => void',
- description: 'Callback fired when the selection changes.',
+ type: '(value: string[], change?: MultiSelectorChange) => void',
+ description:
+ 'Called when the selection changes. A creation (hasCreate) arrives with `{type: "create", query}` as the second argument and the query appended to value; the caller adds the matching option in that same update. Every other change passes no descriptor, so a one-argument handler keeps working.',
required: true,
},
{
@@ -278,6 +279,13 @@ export const docs = {
'Content shown in the dropdown panel when a search query matches no options, and announced in a polite live region at the same time. The announcement is the text this content renders, read from the DOM, so an element is announced as written and aria-hidden parts are left out of both.',
default: "'No results found'",
},
+ {
+ name: 'hasCreate',
+ type: 'boolean',
+ description:
+ 'With hasSearch, offers a `Create "<query>"` row first in the list when the typed text equals no option label under the search’s case-insensitive matching. Picking it, or Enter with nothing highlighted, calls onChange with the query appended to value and a `{type: "create", query}` descriptor, then clears the search; the caller must add an option for the new value in that update. Nothing is offered while isLoading. Without hasSearch it warns in development and offers nothing.',
+ default: 'false',
+ },
{
name: 'isDisabled',
type: 'boolean',
@@ -494,6 +502,8 @@ export const docsZh = {
searchPlaceholder: '搜索输入的占位文本。',
emptyText: '没有可显示的选项时,下拉面板中显示的内容。',
emptySearchText: '搜索查询未匹配到任何选项时,下拉面板中显示的内容。',
+ hasCreate:
+ '配合 hasSearch:当输入的文本与任何选项标签都不匹配时,在列表首行提供“创建 "<query>"”行;选中后通过 onChange 以 {type: "create", query} 描述符报告,调用方需在同一次更新中添加该选项。',
isDisabled: '禁用选择器。',
isReadOnly:
'将选择器设为只读:保留当前值、焦点顺序和表单提交,但移除选择面板、清除操作和展开指示器。与 isDisabled 不同,只读控件不会变暗;两者同时设置时 isDisabled 优先。',
@@ -641,6 +651,8 @@ export const docsDense = {
searchPlaceholder: 'search placeholder',
emptyText: 'panel content when there are no options',
emptySearchText: 'panel content when the query matches nothing',
+ hasCreate:
+ 'with hasSearch: first row is Create "<query>" when no option label matches; reported through onChange with a {type: "create", query} descriptor; caller adds the option',
isDisabled: 'disables selector',
isReadOnly:
'read-only: preserves values, focus + form submission; removes menu, clear + disclosure',
diff --git a/packages/core/src/MultiSelector/MultiSelector.spec.md b/packages/core/src/MultiSelector/MultiSelector.spec.md
index 3dfd71aaa0..53d6ca0734 100644
--- a/packages/core/src/MultiSelector/MultiSelector.spec.md
+++ b/packages/core/src/MultiSelector/MultiSelector.spec.md
@@ -58,6 +58,11 @@ behavior.
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.
+- `hasCreate` is additive and off by default. `onChange` gains an optional
+ second argument, a `MultiSelectorChange` descriptor, passed only for a
+ creation; a one-argument handler keeps working. When `hasCreate` is omitted,
+ DOM, styling, targets, keyboard behavior, announcements, and the callback's
+ calls are unchanged.
- Controlled/uncontrolled behavior: unchanged. Open state stays owned by the
component; `handleRef` drives it and `onOpenChange` reports it.
- Migration decision: none
@@ -98,23 +103,25 @@ 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 |
-| 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 |
+| 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 |
+| create row | `hasCreate` `false`, `true` | First row minting the typed query, reported through `onChange` as `{type: 'create', query}` | Search mode, query matching no option label, options loaded | `false` | Caller | additive | Without `hasSearch`: development warning, nothing offered |
## Behavioral and layout contract
-| ID | Candidate invariant | Basis | Draft review state |
-| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------------------------------------------------- |
-| FR1 | The current standalone presentation contains a Field and painted Trigger; the supported InputGroup path renders the same Trigger without a Field. Optional start content, clear action, status icon, or Indicator icon follows supplied props and state. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
-| FR2 | The shared panel content contains the optional Search row, zero or more Option rows, optional public Option dividers and Section headings, and an Empty state when the applicable result set is empty and the value is not loading. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
-| FR3 | Trigger, Indicator icon, Search row, Option row, Section heading, Empty state, and Pointer popup carry the seven current non-deprecated MultiSelector targets documented in `MultiSelector.doc.mjs`. | Current source, docs, and tests | Verified current behavior; no target change |
-| FR4 | When present, Field, shared clear actions, option checkbox indicators, public Option dividers, general icons, Touch sheet heading, and Touch sheet retain their Field, CheckboxInput, Divider, Icon, Text, and BottomSheet theming owners. | Current composition and owners | Verified current behavior; no target change |
-| FR5 | Pointer popup and Touch sheet are separate surface anatomy rows, but both host the same `panelContent` tree; the Touch sheet additionally renders its Heading. Changing presentation does not create a second search, option, divider, section, or empty-state content model. | Current source and tests | Verified current behavior; no normalization |
-| FR6 | `multi-selector-clear-icon` remains a deprecated compatibility alias for `input-clear-icon`; it is not a current target and does not claim a separate anatomy part. | Current public target metadata | Verified current compatibility state |
-| FR7 | While `isReadOnly` is true, selected values remain focusable and form-submittable, while the selection surface, clear action, disclosure indicator, and every value-change path are unavailable. | `spec:AST-011`, docs, and tests | Accepted read-only behavior |
-| FR8 | With `renderTrigger`, the caller-rendered control receives `ref`, `id`, `onClick`, `onKeyDown`, `onFocus`, `aria-haspopup`, `aria-expanded`, `aria-controls`, and `aria-busy`; the panel is anchored to it, focus returns to it on close, the listbox is named by `label`, and the listbox takes focus and owns the keyboard on open. No Field, status, clear action, spinner, or indicator renders. `handleRef` exposes `open`, `close`, `toggle`, `isOpen`; `onOpenChange` fires on every open and close. | DEC-1, docs, and tests | Proposed; awaiting owner approval |
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | -------------------------------------------------- |
+| FR1 | The current standalone presentation contains a Field and painted Trigger; the supported InputGroup path renders the same Trigger without a Field. Optional start content, clear action, status icon, or Indicator icon follows supplied props and state. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
+| FR2 | The shared panel content contains the optional Search row, zero or more Option rows, optional public Option dividers and Section headings, and an Empty state when the applicable result set is empty and the value is not loading. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
+| FR3 | Trigger, Indicator icon, Search row, Option row, Section heading, Empty state, and Pointer popup carry the seven current non-deprecated MultiSelector targets documented in `MultiSelector.doc.mjs`. | Current source, docs, and tests | Verified current behavior; no target change |
+| FR4 | When present, Field, shared clear actions, option checkbox indicators, public Option dividers, general icons, Touch sheet heading, and Touch sheet retain their Field, CheckboxInput, Divider, Icon, Text, and BottomSheet theming owners. | Current composition and owners | Verified current behavior; no target change |
+| FR5 | Pointer popup and Touch sheet are separate surface anatomy rows, but both host the same `panelContent` tree; the Touch sheet additionally renders its Heading. Changing presentation does not create a second search, option, divider, section, or empty-state content model. | Current source and tests | Verified current behavior; no normalization |
+| FR6 | `multi-selector-clear-icon` remains a deprecated compatibility alias for `input-clear-icon`; it is not a current target and does not claim a separate anatomy part. | Current public target metadata | Verified current compatibility state |
+| FR7 | While `isReadOnly` is true, selected values remain focusable and form-submittable, while the selection surface, clear action, disclosure indicator, and every value-change path are unavailable. | `spec:AST-011`, docs, and tests | Accepted read-only behavior |
+| FR8 | With `renderTrigger`, the caller-rendered control receives `ref`, `id`, `onClick`, `onKeyDown`, `onFocus`, `aria-haspopup`, `aria-expanded`, `aria-controls`, and `aria-busy`; the panel is anchored to it, focus returns to it on close, the listbox is named by `label`, and the listbox takes focus and owns the keyboard on open. No Field, status, clear action, spinner, or indicator renders. `handleRef` exposes `open`, `close`, `toggle`, `isOpen`; `onOpenChange` fires on every open and close. | DEC-1, docs, and tests | Proposed; awaiting owner approval |
+| FR9 | With `hasSearch` and `hasCreate`, once options have loaded, a `Create "<query>"` row leads the list when the trimmed query equals no option label under the search's own case-insensitive matching. Picking it, or Enter with nothing highlighted, calls `onChange` with the query appended to the value and a `{type: 'create', query}` descriptor, clears the search, and announces the creation; every other change passes no descriptor. The row has no checkbox, is never selected, is excluded from select-all and from `renderOption`, and is announced instead of the empty message when it is the only result. While `isLoading`, no row is offered and Enter commits nothing. `hasCreate` without `hasSearch` warns in development and offers nothing. | `spec:AST-056` FR5 / DEC-3, `component:Tokenizer` `hasCreate`, docs, and tests | Proposed; awaiting owner approval |
### Allowed variation
@@ -169,6 +176,11 @@ and `aria-controls` for the listbox, the listbox carries `aria-label` from
focused element that owns arrow, Enter, Escape, and typeahead keys while open,
so an anchor that cannot take focus still leaves a keyboard path.
+The create row is a `role="option"` with `aria-selected="false"` and no
+checkbox indicator. When it is the only result, the polite live region
+announces its label rather than the empty-search message, so what is announced
+matches what is on screen; picking it announces the creation.
+
## Design relationships
| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
@@ -275,15 +287,16 @@ empty-state content remains one shared tree.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |
-| FR1, FR2 | `MultiSelector.test.tsx` render, search, divider, grouping, status, select-all, and empty-state suites plus InputGroup source inspection | Standalone/InputGroup, search, divided, selected, empty, status | Removing a documented part or misreporting Field presence conflicts with existing structure, content assertions, or source. | `audit:MultiSelector/anatomy` |
-| FR3, FR6 | Component target suites, source inspection, and public target inventory | All seven current targets and deprecated alias | A current target is missed, invented, moved, or confused with the deprecated clear-icon alias. | `audit:MultiSelector/theming` |
-| FR4 | Composed owner source/tests for Field, CheckboxInput, Divider, Icon, Text, and BottomSheet | Field omission/presence, clear actions, checkbox, divider, icons, heading, sheet | A shared part gains the wrong local owner or its documented owner no longer renders it. | `audit:MultiSelector/theming` |
-| FR5 | `MultiSelector.test.tsx` presentation suites and `panelContent` source inspection | Explicit popover, explicit sheet, adaptive touch | A presentation stops using its owner or receives a divergent panel-content implementation. | `audit:MultiSelector/overlay` |
-| FR7 | read-only interaction, form, ARIA, and theme-state tests | search/non-search, clearable, open→read-only, disabled precedence | A value changes, popup or edit affordance remains, form value disappears, or read-only semantics are absent. | `audit:MultiSelector/accessibility` |
-| FR8 | `MultiSelector.test.tsx` "trigger render prop" suite | External trigger closed/open; handle open/close; disabled; listbox focus | Field chrome renders with a trigger, the control lacks disclosure state, the listbox is unnamed, or the handle opens a disabled selector. | `audit:MultiSelector/accessibility` |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current local targets | Missing, extra, prefixed, stale, or multiply assigned mappings fail repository validation. | `audit:MultiSelector/theming` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |
+| FR1, FR2 | `MultiSelector.test.tsx` render, search, divider, grouping, status, select-all, and empty-state suites plus InputGroup source inspection | Standalone/InputGroup, search, divided, selected, empty, status | Removing a documented part or misreporting Field presence conflicts with existing structure, content assertions, or source. | `audit:MultiSelector/anatomy` |
+| FR3, FR6 | Component target suites, source inspection, and public target inventory | All seven current targets and deprecated alias | A current target is missed, invented, moved, or confused with the deprecated clear-icon alias. | `audit:MultiSelector/theming` |
+| FR4 | Composed owner source/tests for Field, CheckboxInput, Divider, Icon, Text, and BottomSheet | Field omission/presence, clear actions, checkbox, divider, icons, heading, sheet | A shared part gains the wrong local owner or its documented owner no longer renders it. | `audit:MultiSelector/theming` |
+| FR5 | `MultiSelector.test.tsx` presentation suites and `panelContent` source inspection | Explicit popover, explicit sheet, adaptive touch | A presentation stops using its owner or receives a divergent panel-content implementation. | `audit:MultiSelector/overlay` |
+| FR7 | read-only interaction, form, ARIA, and theme-state tests | search/non-search, clearable, open→read-only, disabled precedence | A value changes, popup or edit affordance remains, form value disappears, or read-only semantics are absent. | `audit:MultiSelector/accessibility` |
+| FR8 | `MultiSelector.test.tsx` "trigger render prop" suite | External trigger closed/open; handle open/close; disabled; listbox focus | Field chrome renders with a trigger, the control lacks disclosure state, the listbox is unnamed, or the handle opens a disabled selector. | `audit:MultiSelector/accessibility` |
+| FR9 | `MultiSelector.test.tsx` "hasCreate" suite; `CreateRow.a11y.chromium.spec.ts` appear/disappear cycle | Create row offered, committed by click/Enter with descriptor, skipped on a case-insensitive exact match, offered for a label the filter cannot surface, absent while loading, beside select-all; toggle without descriptor; warning without search | The row appears while loading or for an existing label, reports without a descriptor, keeps the search text, is silently inert without search, or the live region says "no results" beside a create row. | `audit:MultiSelector/accessibility` |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current local targets | Missing, extra, prefixed, stale, or multiply assigned mappings fail repository validation. | `audit:MultiSelector/theming` |
Existing component tests directly assert the Trigger, Indicator icon, Search row,
Option row, Section heading, Empty state, and Pointer popup targets. Presentation
@@ -306,6 +319,23 @@ owner evidence rather than new MultiSelector targets.
**Decider:** `cixzhang`, 2026-10-03
+- **DEC-2 — The create row is one switch reporting through `onChange`.** The
+ row exists only while a query does, so it is enabled by `hasCreate` alone
+ and reported on the channel the caller already listens to, with a
+ descriptor naming the creation and the typed text already in the value, so
+ adding the option and accepting the value are one update (`spec:AST-056`
+ DEC-3; the shape `Tokenizer` ships). The duplicate rule is the search's own
+ matching rule at full equality: a label the filter shows as an exact match
+ is never offered for creation, and one the filter cannot surface for the
+ query is never a dead end. Nothing is offered while options are loading,
+ because a label a moment from arriving is not new. Rejected: a `hasCreate` +
+ `onCreate` pair (three silently inert half-configurations); offering the
+ row while loading (mints duplicates); a diacritic-folding duplicate rule
+ beside a case-only filter (hides `Café` from `CAFE` and refuses to create
+ it — the two rules widen together under `spec:AST-056` FR4 or not at all).
+
+ **Decider:** pending owner review
+
## Open questions
None.
diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsx
index 911285543d..7f60f91d2b 100644
--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx
@@ -20,7 +20,11 @@ import {
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import * as stylex from '@stylexjs/stylex';
-import {MultiSelector, type MultiSelectorHandle} from './MultiSelector';
+import {
+ MultiSelector,
+ type MultiSelectorHandle,
+ type MultiSelectorChange,
+} from './MultiSelector';
import {useRef} from 'react';
import {Icon} from '../Icon';
import {InternationalizationProvider} from '../i18n';
@@ -3499,3 +3503,279 @@ describe('MultiSelector renderTrigger — focus return', () => {
);
});
});
+
+describe('MultiSelector hasCreate', () => {
+ const OPTIONS = [
+ {value: 'bug', label: 'Bug'},
+ {value: 'feature', label: 'Feature'},
+ {value: 'cafe', label: 'Café'},
+ ];
+
+ it('offers Create "<query>" first and reports the creation through onChange', async () => {
+ const user = userEvent.setup();
+ const onChange =
+ vi.fn<(value: string[], change?: MultiSelectorChange) => void>();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={['bug']}
+ onChange={onChange}
+ hasSearch
+ hasCreate
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ const search = screen.getByRole('combobox', h);
+ await user.type(search, 'Urgent');
+
+ const options = screen.getAllByRole('option', h);
+ expect(options).toHaveLength(1);
+ expect(options[0]).toHaveTextContent('Create "Urgent"');
+ expect(options[0]).toHaveAttribute('aria-selected', 'false');
+ expect(options[0].querySelector('input[type="checkbox"]')).toBeNull();
+ expect(screen.queryByText('No results found')).toBeNull();
+
+ await user.click(options[0]);
+ // One update: the query joins the value and the change says it is a
+ // creation, so the caller adds the option and accepts the value together.
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith(['bug', 'Urgent'], {
+ type: 'create',
+ query: 'Urgent',
+ });
+ // The filter is cleared so the option the caller adds is visible.
+ expect(search).toHaveValue('');
+ });
+
+ it('a plain toggle passes no descriptor, so a one-argument handler is unchanged', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={onChange}
+ hasSearch
+ hasCreate
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ await user.click(screen.getByRole('option', {name: 'Bug', ...h}));
+ expect(onChange).toHaveBeenCalledWith(['bug']);
+ expect(onChange.mock.calls[0]).toHaveLength(1);
+ });
+
+ it('sits above partial matches and is skipped for a label the filter matches exactly', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ hasCreate
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ const search = screen.getByRole('combobox', h);
+
+ await user.type(search, 'Bu');
+ expect(screen.getAllByRole('option', h).map(o => o.textContent)).toEqual([
+ 'Create "Bu"',
+ 'Bug',
+ ]);
+
+ await user.type(search, 'g');
+ expect(screen.getAllByRole('option', h).map(o => o.textContent)).toEqual([
+ 'Bug',
+ ]);
+
+ await user.clear(search);
+ await user.type(search, 'bug');
+ // Case-insensitive, like the filter: "bug" is Bug, so nothing to create.
+ expect(screen.getAllByRole('option', h).map(o => o.textContent)).toEqual([
+ 'Bug',
+ ]);
+
+ await user.clear(search);
+ await user.type(search, 'CAFE');
+ // The duplicate rule is the filter's rule: the filter cannot surface
+ // Café for CAFE, so refusing to create would be a dead end.
+ expect(screen.getAllByRole('option', h).map(o => o.textContent)).toEqual([
+ 'Create "CAFE"',
+ ]);
+ });
+
+ it('leads the select-all row and is not handed to renderOption', async () => {
+ const user = userEvent.setup();
+ const renderOption = vi.fn((option: {label?: string}) => (
+ <span>{`row:${option.label}`}</span>
+ ));
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ hasSelectAll
+ hasCreate
+ renderOption={renderOption}
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ await user.type(screen.getByRole('combobox', h), 'Bu');
+ const options = screen.getAllByRole('option', h);
+ expect(options[0]).toHaveTextContent('Create "Bu"');
+ expect(options[1]).toHaveTextContent('Select all');
+ expect(options[2]).toHaveTextContent('row:Bug');
+ expect(
+ renderOption.mock.calls.some(([option]) =>
+ (option.label ?? '').startsWith('Create'),
+ ),
+ ).toBe(false);
+ });
+
+ it('Enter with nothing highlighted commits the create row; ArrowDown reaches it', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={onChange}
+ hasSearch
+ hasCreate
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ const search = screen.getByRole('combobox', h);
+ await user.type(search, 'Urgent');
+ await user.keyboard('{Enter}');
+ expect(onChange).toHaveBeenLastCalledWith(['Urgent'], {
+ type: 'create',
+ query: 'Urgent',
+ });
+
+ await user.type(search, 'Later');
+ fireEvent.keyDown(search, {key: 'ArrowDown'});
+ const createRow = screen.getByRole('option', {
+ name: 'Create "Later"',
+ ...h,
+ });
+ expect(search).toHaveAttribute('aria-activedescendant', createRow.id);
+ fireEvent.keyDown(search, {key: 'Enter'});
+ expect(onChange).toHaveBeenLastCalledWith(
+ expect.arrayContaining(['Later']),
+ {type: 'create', query: 'Later'},
+ );
+ });
+
+ it('offers nothing while isLoading, and Enter commits nothing', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const {rerender} = render(
+ <MultiSelector
+ label="Labels"
+ options={[]}
+ value={[]}
+ onChange={onChange}
+ hasSearch
+ hasCreate
+ isLoading
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ const search = screen.getByRole('combobox', h);
+ await user.type(search, 'Bug');
+ expect(screen.queryAllByRole('option', h)).toHaveLength(0);
+ expect(politeRegion()?.textContent ?? '').toBe('');
+ await user.keyboard('{Enter}');
+ expect(onChange).not.toHaveBeenCalled();
+
+ // The options land: Bug exists, so still no create row for "Bug" — the
+ // duplicate the gate was there to prevent.
+ rerender(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={onChange}
+ hasSearch
+ hasCreate
+ />,
+ );
+ expect(screen.getAllByRole('option', h).map(o => o.textContent)).toEqual([
+ 'Bug',
+ ]);
+ });
+
+ it('announces the create row, not "No results found", when it is the only result', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ hasCreate
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ await user.type(screen.getByRole('combobox', h), 'Urgent');
+ // The empty-state message is role="presentation", so the live region is
+ // what a screen reader gets — it must say what is on screen: a row.
+ await waitFor(() => {
+ expect(politeRegion()?.textContent).toBe('Create "Urgent"');
+ });
+ });
+
+ it('warns in development and offers nothing when hasCreate is set without hasSearch', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ hasCreate
+ />,
+ );
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringMatching(/MultiSelector[\s\S]*hasSearch/),
+ );
+ await user.click(screen.getByRole('combobox', {name: 'Labels'}));
+ // No search input, no query, no create row: the three real options only.
+ expect(
+ screen.queryByRole('combobox', {name: /search/i, ...h}),
+ ).toBeNull();
+ expect(screen.getAllByRole('option', h)).toHaveLength(3);
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it('is off by default', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Labels"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Labels'}));
+ await user.type(screen.getByRole('combobox', h), 'Urgent');
+ expect(screen.queryAllByRole('option', h)).toHaveLength(0);
+ expect(screen.getByText('No results found')).toBeInTheDocument();
+ });
+});
diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsx
index 419922439e..126f0f08ad 100644
--- a/packages/core/src/MultiSelector/MultiSelector.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.tsx
@@ -72,6 +72,7 @@ import {
} from '../Selector/utils';
import {useMultiCombobox} from './hooks';
import {getInputARIA, isImeKeyEvent, mergeProps} from '../utils';
+import {devWarn} from '../utils/devWarning';
import {useAnnounce} from '../hooks/useAnnounce';
import {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector';
import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';
@@ -95,6 +96,14 @@ import {selectorPresentationStyles} from '../Selector/selectorPresentation.style
// Sentinel value for the select-all item in keyboard navigation
const SELECT_ALL_VALUE = '__xds_select_all__';
+// Value of the synthetic "Create <query>" row `hasCreate` offers. Never a real
+// option value: picking it reports a `create` change, not a toggle.
+const CREATE_VALUE_PREFIX = '__astryx_multi_selector_create__';
+
+function isCreateValue(value: string): boolean {
+ return value.startsWith(CREATE_VALUE_PREFIX);
+}
+
const styles = stylex.create({
// Trigger container — the enhanced click target wrapping the combobox button and clear button as siblings
triggerContainer: {
@@ -493,6 +502,18 @@ export interface MultiSelectorHandle {
isOpen(): boolean;
}
+/**
+ * What kind of change an `onChange` call reports. Only a creation is reported
+ * today; a plain toggle, clear, or select-all passes no descriptor, so a
+ * one-argument `onChange` keeps working unchanged.
+ */
+export type MultiSelectorChange = {
+ /** The person picked the `Create "<query>"` row of a search. */
+ type: 'create';
+ /** The trimmed query, which is also the new entry appended to `value`. */
+ query: string;
+};
+
export interface MultiSelectorSelectedItem {
value: string;
label: string;
@@ -589,9 +610,12 @@ export interface MultiSelectorProps<
htmlName?: string;
/**
- * Callback when selection changes.
+ * Callback when selection changes. A creation (`hasCreate`) arrives with
+ * a descriptor as the second argument and the typed text appended to
+ * `value`; the caller adds the matching option and accepts the value in the
+ * same update. Every other change passes no descriptor.
*/
- onChange: (value: string[]) => void;
+ onChange: (value: string[], change?: MultiSelectorChange) => void;
/**
* Async action on change. Fires after onChange.
@@ -704,6 +728,19 @@ export interface MultiSelectorProps<
*/
emptySearchText?: ReactNode;
+ /**
+ * With `hasSearch`, offer a `Create "<query>"` row first in the list when the
+ * trimmed query equals no option's label under the search's own matching
+ * (case-insensitive). Picking it, or Enter with nothing highlighted, calls
+ * `onChange` with the query appended to `value` and a `{type: 'create',
+ * query}` descriptor, then clears the search. The caller MUST add an option
+ * for the new value in that same update; the component does not mint
+ * options. Nothing is offered while `isLoading`. Setting this without
+ * `hasSearch` warns in development and offers nothing.
+ * @default false
+ */
+ hasCreate?: boolean;
+
/**
* How to display selected items in the trigger.
* - 'count': "3 selected"
@@ -819,6 +856,10 @@ export interface MultiSelectorProps<
// Case-insensitive substring match for a single option. The one predicate used
// by both the flat filter (count + keyboard nav) and the grouped renderer, so
// what is shown while searching stays in lockstep with the announced count.
+function normalizeLabel(label: string): string {
+ return label.toLowerCase();
+}
+
function optionMatchesQuery(
option: MultiSelectorOptionData,
query: string,
@@ -826,9 +867,19 @@ function optionMatchesQuery(
if (!query) {
return true;
}
- return (option.label ?? option.value)
- .toLowerCase()
- .includes(query.toLowerCase());
+ return normalizeLabel(option.label ?? option.value).includes(
+ normalizeLabel(query),
+ );
+}
+
+// "Already exists" for the create row uses the filter's own normalization, so
+// a label the filter shows as an exact match is never offered for creation,
+// and a label the filter cannot surface for this query is never a dead end.
+function hasLabel(items: MultiSelectorOptionData[], query: string): boolean {
+ const wanted = normalizeLabel(query);
+ return items.some(
+ item => normalizeLabel(item.label ?? item.value) === wanted,
+ );
}
// Case-insensitive substring filter over the selectable options. Shared by the
@@ -888,6 +939,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
searchPlaceholder: searchPlaceholderFromProps,
emptyText: emptyTextFromProps,
emptySearchText: emptySearchTextFromProps,
+ hasCreate = false,
triggerDisplay = 'count',
formatValue,
maxBadges = 3,
@@ -994,6 +1046,18 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
[options],
);
+ // The one half-configuration a single switch cannot rule out: creation
+ // needs a query to create from. Say so rather than offer nothing in silence.
+ useEffect(() => {
+ if (hasCreate && !hasSearch && process.env.NODE_ENV !== 'production') {
+ devWarn(
+ 'MultiSelector',
+ '`hasCreate` needs `hasSearch`: the create row is minted from the ' +
+ 'typed query, so without a search input nothing is offered.',
+ );
+ }
+ }, [hasCreate, hasSearch]);
+
// Announce selection-count changes politely (comboboxes-7 announce path).
// Toggling options / select-all previously produced no audible feedback.
const announce = useAnnounce();
@@ -1030,6 +1094,29 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
// Selected-at-open items are placed first within each group/section, and the
// same walk applies while searching so group structure survives filtering
// (only matching items are kept; the query is empty in non-search mode).
+ // The query the create row would mint, or null when there is none to offer:
+ // no `hasCreate`, no search, options still loading (a label that is a moment
+ // from arriving must not be offered as new), nothing typed, or an option
+ // already carries that label — `Tokenizer.hasCreate`'s rule.
+ const canCreate = hasCreate && hasSearch && !isLoading;
+ const getCreateQuery = useCallback(
+ (query: string): string | null => {
+ if (!canCreate) {
+ return null;
+ }
+ const trimmed = query.trim();
+ if (trimmed === '') {
+ return null;
+ }
+ return hasLabel(selectableItems, trimmed) ? null : trimmed;
+ },
+ [canCreate, selectableItems],
+ );
+ const createQuery = useMemo(
+ () => getCreateQuery(searchQuery),
+ [getCreateQuery, searchQuery],
+ );
+
const sortedItems = useMemo(() => {
const selectedSet = selectedAtOpen ?? new Set<string>();
const result: MultiSelectorOptionData[] = [];
@@ -1068,10 +1155,25 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
flushFlat();
if (hasSelectAll) {
- return [{value: SELECT_ALL_VALUE, label: selectAllLabel}, ...result];
+ result.unshift({value: SELECT_ALL_VALUE, label: selectAllLabel});
+ }
+ if (createQuery != null) {
+ // First row, before select-all: the row the typed text asked for.
+ result.unshift({
+ value: `${CREATE_VALUE_PREFIX}${createQuery}`,
+ label: t('@astryx.multiSelector.createOption', {query: createQuery}),
+ });
}
return result;
- }, [searchQuery, options, selectedAtOpen, hasSelectAll, selectAllLabel]);
+ }, [
+ searchQuery,
+ options,
+ selectedAtOpen,
+ hasSelectAll,
+ selectAllLabel,
+ createQuery,
+ t,
+ ]);
// Layer for dropdown positioning
const hasExternalTrigger = renderTrigger != null;
@@ -1201,6 +1303,16 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
}
const count = filterOptionsByQuery(selectableItems, nextQuery).length;
if (count === 0) {
+ const nextCreateQuery = getCreateQuery(nextQuery);
+ if (nextCreateQuery != null) {
+ // The create row is the one result on screen, so the panel is not
+ // empty and the rendered-message route below stays silent; say the
+ // row.
+ announce(
+ t('@astryx.multiSelector.createOption', {query: nextCreateQuery}),
+ );
+ return;
+ }
// The empty panel is announced from the rendered message below, not
// from here. Two speakers for one transition would say it twice, and
// this one cannot cover an empty result that arrives after the
@@ -1209,7 +1321,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
}
announce(t('@astryx.multiSelector.resultCount', {count}));
},
- [announce, isLoading, selectableItems, t],
+ [announce, isLoading, selectableItems, getCreateQuery, t],
);
// The panel's empty message is role="presentation" — role="listbox" permits
@@ -1226,11 +1338,14 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
// region silent.
//
// `realItemCount` mirrors renderOptions exactly: the select-all sentinel
- // rides in `sortedItems` but is not an option anybody can match.
- const realItemCount = hasSelectAll
- ? sortedItems.length - 1
- : sortedItems.length;
- const isPanelEmpty = surface.isOpen && !isLoading && realItemCount === 0;
+ // and the create row ride in `sortedItems`, in that order from the top,
+ // but neither is an option anybody can match. A create row is a result of
+ // its own, so a panel showing one is not empty.
+ const hasCreateRow = createQuery != null;
+ const leadingCount = (hasCreateRow ? 1 : 0) + (hasSelectAll ? 1 : 0);
+ const realItemCount = sortedItems.length - leadingCount;
+ const isPanelEmpty =
+ surface.isOpen && !isLoading && realItemCount === 0 && !hasCreateRow;
useAnnounceRenderedText(emptyStateRef, isPanelEmpty, searchQuery);
// Handle toggle
@@ -1349,16 +1464,49 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
announceSelection,
]);
- // Route toggle: select-all sentinel → handleSelectAll, everything else → handleToggle
+ // Picking the create row: the typed text joins the value and the caller is
+ // told it is a creation on the channel it already listens to, so adding the
+ // option and accepting the value are one update. The search is cleared so
+ // the option the caller adds is visible.
+ const commitCreate = useCallback(
+ (query: string) => {
+ const newValue = optimisticValue.includes(query)
+ ? optimisticValue
+ : [...optimisticValue, query];
+ onChange(newValue, {type: 'create', query});
+ setSearchQuery('');
+ announce(t('@astryx.multiSelector.optionCreated', {label: query}));
+ if (changeAction) {
+ startTransition(async () => {
+ setOptimisticValue(newValue);
+ await changeAction(newValue);
+ });
+ }
+ },
+ [
+ optimisticValue,
+ onChange,
+ changeAction,
+ startTransition,
+ setOptimisticValue,
+ announce,
+ t,
+ ],
+ );
+
+ // Route toggle: select-all sentinel → handleSelectAll, the create row →
+ // commitCreate, everything else → handleToggle
const handleNavigableToggle = useCallback(
(itemValue: string) => {
if (itemValue === SELECT_ALL_VALUE) {
handleSelectAll();
+ } else if (isCreateValue(itemValue)) {
+ commitCreate(itemValue.slice(CREATE_VALUE_PREFIX.length));
} else {
handleToggle(itemValue);
}
},
- [handleSelectAll, handleToggle],
+ [handleSelectAll, handleToggle, commitCreate],
);
// Multi-select combobox behavior — index-based, matching useCombobox pattern.
@@ -1510,6 +1658,17 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
if (isImeKeyEvent(e.nativeEvent)) {
return;
}
+ if (
+ e.key === 'Enter' &&
+ highlightedIndex < 0 &&
+ createQuery != null
+ ) {
+ // Nothing highlighted and the typed text matches no option:
+ // Enter mints it, as it does in Tokenizer.
+ e.preventDefault();
+ commitCreate(createQuery);
+ return;
+ }
// Arrow keys navigate options; Enter toggles; Escape closes.
// Space and Home/End are left to the input (type a space / move
// the caret) per the APG editable combobox; PageUp/PageDown are
@@ -1547,6 +1706,8 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
surface.isOpen,
highlightedIndex,
getItemId,
+ createQuery,
+ commitCreate,
t,
]);
@@ -1555,9 +1716,12 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
(item: MultiSelectorOptionData, flatIndex: number) => {
const isHighlighted = flatIndex === highlightedIndex;
const isSelectAll = item.value === SELECT_ALL_VALUE;
+ // The create row is a plain labelled option: no checkbox, never
+ // selected, and the caller's `renderOption` does not see it.
+ const isCreate = isCreateValue(item.value);
const isSelected = isSelectAll
? allEnabledSelected
- : optimisticValue.includes(item.value);
+ : !isCreate && optimisticValue.includes(item.value);
const checkboxValue = isSelectAll ? selectAllState : isSelected;
// aria-selected="mixed" is invalid on role="option", and the tri-state
// checkbox is inert/decorative, so the indeterminate state must be
@@ -1565,7 +1729,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
const isPartiallySelected =
isSelectAll && selectAllState === 'indeterminate';
- const checkbox = (
+ const checkbox = isCreate ? null : (
<div
inert
{...stylex.props(
@@ -1623,7 +1787,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
),
)}>
{indicatorPosition === 'start' && checkbox}
- {renderOption && !isSelectAll ? (
+ {renderOption && !isSelectAll && !isCreate ? (
renderOption(item)
) : (
<span {...stylex.props(styles.itemLabel)}>
@@ -1657,15 +1821,21 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
const elements: ReactNode[] = [];
let cursor = 0;
+ // The create row is the first row: the row the typed text asked for.
+ if (hasCreateRow) {
+ elements.push(renderItem(sortedItems[cursor], cursor));
+ cursor++;
+ }
+
// Show select-all only when there are real items to select. It reads as
// the first row of the list, not a section of its own — no divider under
// it (the checkbox column already lines it up with the options below).
- if (hasSelectAll && realItemCount > 0) {
- elements.push(renderItem(sortedItems[0], 0));
- cursor = 1;
- } else if (hasSelectAll) {
+ if (hasSelectAll) {
+ if (realItemCount > 0) {
+ elements.push(renderItem(sortedItems[cursor], cursor));
+ }
// Skip the select-all sentinel when there are no real items
- cursor = 1;
+ cursor++;
}
// Empty state — no real items to show. role="presentation" keeps the
@@ -1675,7 +1845,8 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
// While isLoading the options have not arrived yet, so asserting either
// message would be a claim the component cannot make; the trigger's
// spinner covers it.
- if (realItemCount === 0 && !isLoading) {
+ // A create row is a result of its own, so the empty state stays out.
+ if (realItemCount === 0 && !isLoading && !hasCreateRow) {
elements.push(
<div
key="empty"
@@ -1785,6 +1956,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
isLoading,
emptyText,
emptySearchText,
+ hasCreateRow,
]);
// The detached message box renders its own leading status icon, so the
diff --git a/packages/core/src/MultiSelector/index.ts b/packages/core/src/MultiSelector/index.ts
index 6a6cf6548c..4a45993df5 100644
--- a/packages/core/src/MultiSelector/index.ts
+++ b/packages/core/src/MultiSelector/index.ts
@@ -17,6 +17,7 @@ export {
type MultiSelectorSelectedItem,
type MultiSelectorRenderTriggerProps,
type MultiSelectorHandle,
+ type MultiSelectorChange,
} from './MultiSelector';
export type {
MultiSelectorOptionType,