Skip to content

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

TypeScript

[Component Audit] CommandPaletteInput: expose accurate search semantics (#7321)

Cindy Zhang26118f805010
diff --git a/.changeset/command-palette-input-semantics.md b/.changeset/command-palette-input-semantics.md
new file mode 100644
index 0000000000..2ceea8a671
--- /dev/null
+++ b/.changeset/command-palette-input-semantics.md
@@ -0,0 +1,13 @@
+---
+'@astryxdesign/cli': patch
+'@astryxdesign/core': patch
+---
+
+[fix] `CommandPaletteInput` gets accurate search semantics and a real name (AST-017 FR53; WCAG 2.2 4.1.2 Name, Role, Value):
+
+- A standalone field with no popup attributes was `role="combobox"` with `aria-expanded="true"` and `aria-autocomplete="list"`; it is now `role="searchbox"` with no popup state. Pass `role="combobox"`, or your popup's own ARIA attributes, to keep the old semantics. A field that already passes popup attributes (`aria-expanded`, `aria-controls`, `aria-owns`, `aria-haspopup`, and the like) stays a `combobox` and keeps them, and a field inside `CommandPalette` is unchanged.
+- The field's default accessible name was its placeholder (`Search…`, or the caller's `placeholder`); it is now `Search commands`, translated. Pass `label` to keep a specific name, for example `label="Search…"` for the old default. A caller whose custom `placeholder` served as the name keeps working code and hears the generic name until it passes `label`.
+- The CLI's async-search CommandPalette block names its field `Search files`.
+- `endContent={true}` no longer renders an empty trailing slot, and `endContent={0}` renders inside the trailing slot instead of after it.
+
+@cixzhang
diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.json
index fa9baf2631..444a70eae8 100644
--- a/apps/storybook/rtl-audit/targets.json
+++ b/apps/storybook/rtl-audit/targets.json
@@ -38,6 +38,15 @@
"next": ".astryx-command-palette-input > input[role=\"combobox\"]"
}
},
+ {
+ "component": "CommandPaletteInput",
+ "storyId": "core-commandpaletteinput--standalone",
+ "dims": ["D2"],
+ "selectors": {
+ "prev": ".astryx-command-palette-input > span:first-child",
+ "next": "[data-testid=\"input-end-content\"]"
+ }
+ },
{
"component": "Center",
"storyId": "core-center--padding-per-edge",
diff --git a/apps/storybook/stories/CommandPalette.stories.tsx b/apps/storybook/stories/CommandPalette.stories.tsx
index 63204f3a09..a699a068fc 100644
--- a/apps/storybook/stories/CommandPalette.stories.tsx
+++ b/apps/storybook/stories/CommandPalette.stories.tsx
@@ -266,7 +266,12 @@ export const AsyncSearch: Story = {
isOpen={isOpen}
onOpenChange={setIsOpen}
searchSource={source}
- input={<CommandPaletteInput placeholder="Search files..." />}
+ input={
+ <CommandPaletteInput
+ label="Search files"
+ placeholder="Search files..."
+ />
+ }
emptyBootstrapText="Type a filename to search"
emptySearchText="No files found"
/>
diff --git a/apps/storybook/stories/CommandPaletteInput.stories.tsx b/apps/storybook/stories/CommandPaletteInput.stories.tsx
new file mode 100644
index 0000000000..4ab46795bc
--- /dev/null
+++ b/apps/storybook/stories/CommandPaletteInput.stories.tsx
@@ -0,0 +1,79 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useMemo, useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {
+ CommandPalette,
+ CommandPaletteInput,
+} from '@astryxdesign/core/CommandPalette';
+import {createStaticSource} from '@astryxdesign/core/Typeahead';
+import {Kbd} from '@astryxdesign/core/Kbd';
+
+const meta: Meta<typeof CommandPaletteInput> = {
+ title: 'Core/CommandPaletteInput',
+ component: CommandPaletteInput,
+ tags: ['autodocs', 'visual-theme-matrix'],
+ parameters: {
+ layout: 'centered',
+ docs: {story: {inline: false, height: '600px'}},
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+/** Independent search field with a visible trailing shortcut hint. */
+export const Standalone: Story = {
+ render: function Render() {
+ const [value, setValue] = useState('');
+ return (
+ <div
+ style={{
+ width: 'min(22rem, calc(100vw - 2rem))',
+ border: '1px solid currentColor',
+ borderRadius: 8,
+ }}>
+ <CommandPaletteInput
+ value={value}
+ onValueChange={setValue}
+ hasAutoFocus={false}
+ label="Search documentation"
+ endContent={
+ <span data-testid="input-end-content">
+ <Kbd keys="mod+k" />
+ </span>
+ }
+ />
+ </div>
+ );
+ },
+};
+
+/** Popup-backed query field with the real CommandPalette context and list. */
+export const PopupContext: Story = {
+ render: function Render() {
+ const source = useMemo(
+ () =>
+ createStaticSource([
+ {id: 'home', label: 'Go home'},
+ {id: 'settings', label: 'Open settings'},
+ {id: 'help', label: 'Open help'},
+ ]),
+ [],
+ );
+ return (
+ <CommandPalette
+ isOpen
+ onOpenChange={() => {}}
+ searchSource={source}
+ input={
+ <CommandPaletteInput
+ hasAutoFocus={false}
+ label="Search commands"
+ endContent={<Kbd keys="mod+k" />}
+ />
+ }
+ />
+ );
+ },
+};
diff --git a/packages/cli/assets/templates/blocks/components/CommandPalette/CommandPaletteAsyncSearch.tsx b/packages/cli/assets/templates/blocks/components/CommandPalette/CommandPaletteAsyncSearch.tsx
index 0f084a76f5..eac3bbe6a7 100644
--- a/packages/cli/assets/templates/blocks/components/CommandPalette/CommandPaletteAsyncSearch.tsx
+++ b/packages/cli/assets/templates/blocks/components/CommandPalette/CommandPaletteAsyncSearch.tsx
@@ -39,7 +39,12 @@ export default function CommandPaletteAsyncSearch() {
isInline
onOpenChange={() => {}}
searchSource={source}
- input={<CommandPaletteInput placeholder="Search files..." />}
+ input={
+ <CommandPaletteInput
+ label="Search files"
+ placeholder="Search files..."
+ />
+ }
emptyBootstrapText="Type a filename to search"
emptySearchText="No files found"
/>
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index 0c2dc57de1..3f482c5d35 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -863,6 +863,10 @@
"defaultMessage": "Search…",
"description": "Grey placeholder inside the CommandPalette's search input. Imperative verb; trailing `…` is one character."
},
+ "@astryx.commandPalette.input.label": {
+ "defaultMessage": "Search commands",
+ "description": "Screen-reader-only accessible name for the CommandPalette query input. Distinguish it from the visible placeholder; verb followed by the app actions being searched."
+ },
"@astryx.commandPalette.list.label": {
"defaultMessage": "Commands",
"description": "\"Command\" = an app action a user can invoke (metaphor from CLI), not a Unix command. Screen-reader-only name for the matching-commands list."
diff --git a/packages/core/src/CommandPalette/CommandPalette.spec.md b/packages/core/src/CommandPalette/CommandPalette.spec.md
index 89aed414f3..5769c0bb43 100644
--- a/packages/core/src/CommandPalette/CommandPalette.spec.md
+++ b/packages/core/src/CommandPalette/CommandPalette.spec.md
@@ -59,7 +59,7 @@ Consumer migration instructions belong in consumer docs and release notes.
- Search orchestration and composition of the current Input, List, Item, Group,
Group heading, Empty, and Footer parts and targets.
-- The native Query field rendered inside the default Input.
+- Composition of the native Query field rendered inside the default Input; the field's semantics and native passthrough are owned by `component:CommandPaletteInput`.
**Does not own / non-goals**
diff --git a/packages/core/src/CommandPalette/CommandPaletteInput.doc.mjs b/packages/core/src/CommandPalette/CommandPaletteInput.doc.mjs
index 791582bd78..f829c438c3 100644
--- a/packages/core/src/CommandPalette/CommandPaletteInput.doc.mjs
+++ b/packages/core/src/CommandPalette/CommandPaletteInput.doc.mjs
@@ -9,18 +9,73 @@ export const docs = {
isHiddenFromOverview: true,
description:
'Search input slot. Auto-focuses on mount. Wires to command palette context when used inside CommandPalette.',
+ usage: {
+ description:
+ 'Use CommandPaletteInput inside CommandPalette for a popup-backed command query, or as an independent search field when no result popup is present.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Pass a concise label that identifies what can be searched when "Search commands" does not describe it; the placeholder is never the field\'s name.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use endContent for short supporting controls or shortcut hints at the trailing edge.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Override combobox role or popup state. CommandPaletteInput owns those semantics when connected to CommandPalette.',
+ },
+ ],
+ anatomy: [
+ {
+ name: 'Input',
+ required: true,
+ description:
+ 'The surrounding inline layout for the search glyph, query field, and trailing content.',
+ },
+ {
+ name: 'Search glyph',
+ required: true,
+ description: 'A decorative search icon before the query field.',
+ },
+ {
+ name: 'Query field',
+ required: true,
+ description:
+ 'The native text field. It is a searchbox when standalone without popup attributes and a combobox when popup relationships are supplied or CommandPalette context is present.',
+ },
+ {
+ name: 'Loading spinner',
+ required: false,
+ description:
+ 'A delayed pending indicator shown before trailing content while search is busy.',
+ },
+ {
+ name: 'Trailing content',
+ required: false,
+ description:
+ 'Caller-provided supporting content such as a clear control or shortcut hint.',
+ },
+ ],
+ },
+ theming: {
+ targets: [{className: 'astryx-command-palette-input'}],
+ },
props: [
{
name: 'placeholder',
type: 'string',
description: 'Placeholder text for the input.',
- default: "'Search...'",
+ default: "'Search…'",
},
{
name: 'label',
type: 'string',
description:
- 'Accessible label for the combobox input, announced by screen readers. Falls back to the placeholder text when omitted.',
+ 'Accessible label for the query field, announced by screen readers. Defaults to the translated "Search commands"; the placeholder is never used as the name.',
},
{
name: 'hasAutoFocus',
@@ -85,7 +140,8 @@ export const docsZh = {
'搜索输入插槽。挂载时自动聚焦。在 CommandPalette 内使用时连接到上下文。',
propDescriptions: {
placeholder: '输入框的占位文本。',
- label: '组合框输入的无障碍标签,供屏幕阅读器朗读。省略时回退到占位文本。',
+ label:
+ '查询字段的无障碍标签,供屏幕阅读器朗读。默认为翻译后的 "Search commands";占位文本不会用作名称。',
hasAutoFocus: '挂载时自动聚焦输入框。内联命令面板中自动禁用。',
endContent: '渲染在输入框末尾的内容,位于加载指示器之后。',
value: '搜索值。在 CommandPalette 内省略时从上下文读取。',
@@ -102,7 +158,8 @@ export const docsDense = {
'search input; auto-focus on mount; wires to context inside CommandPalette',
propDescriptions: {
placeholder: 'input placeholder text',
- label: 'accessible label for the combobox; falls back to placeholder',
+ label:
+ 'accessible label for the query field; default "Search commands", never the placeholder',
hasAutoFocus: 'auto-focus on mount; auto-disabled in inline mode',
endContent: 'trailing content after spinner',
value: 'search value; reads context when omitted inside palette',
diff --git a/packages/core/src/CommandPalette/CommandPaletteInput.spec.md b/packages/core/src/CommandPalette/CommandPaletteInput.spec.md
new file mode 100644
index 0000000000..21c6bed169
--- /dev/null
+++ b/packages/core/src/CommandPalette/CommandPaletteInput.spec.md
@@ -0,0 +1,212 @@
+---
+schema_version: 3
+template_version: 7
+kind: component
+id: component:CommandPaletteInput
+authority: current
+archive_reason: null
+superseded_by: null
+approved_by: cixzhang
+approved_at: 2026-10-14
+owners: [cixzhang]
+review_triggers: [public-api, behavior, layout, theming, accessibility]
+verified_by:
+ [
+ packages/core/src/CommandPalette/CommandPaletteInput.test.tsx,
+ apps/storybook/stories/CommandPaletteInput.stories.tsx,
+ apps/storybook/rtl-audit/targets.json,
+ packages/core/src/theme/themingTargets.test.ts,
+ scripts/check-knowledge.mjs,
+ ]
+modules: []
+families: []
+design_specs: []
+architecture:
+ [
+ architecture:component-test-sufficiency,
+ architecture:component-theming-surface,
+ architecture:interaction-modality,
+ architecture:public-component-api,
+ ]
+contributing: []
+system_specs: [spec:AST-017, spec:AST-020, spec:AST-056]
+---
+
+# CommandPaletteInput component contract
+
+## Contract at a glance
+
+| Area | Contract |
+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| Public contract | A query field with context-backed search state, optional trailing content, and a split wrapper/field attribute boundary. |
+| Behavior | Standalone use without popup attributes is a searchbox; caller popup attributes or CommandPalette context supply combobox state and relationships. |
+| End-user impact | Screen-reader users receive role and popup state that match whether a controlled result popup exists. |
+| Builder impact | Context-owned popup semantics cannot be replaced through native passthrough props; standalone caller-owned popup semantics remain supported. |
+| Compatibility/readiness | A `[fix]` restores no-popup semantics while preserving released caller-owned popup associations, and names the field "Search commands" by default instead of its placeholder; primary callback naming remains OQ1. |
+| Review checks | Reject unassociated standalone combobox state, clobberable owned popup semantics, empty trailing chrome, or changed input ref routing. |
+| Governing rules | `architecture:public-component-api/INV2,INV5`; `spec:AST-017/FR1,FR3,FR5,FR53`; `spec:AST-020/FR1,FR2`; `spec:AST-056/AR2`; WCAG 2.2 4.1.2. |
+
+This table is a review projection; the body below is authoritative.
+
+## Intent
+
+CommandPaletteInput presents the text query for a command palette. It can bind
+to CommandPalette search and navigation context or act as an independent search
+field when no result-popup context is present.
+
+## Compatibility and migration
+
+- Released default preserved: `no` for no-popup standalone semantic output and
+ for the default accessible name; caller-owned popup associations and all other
+ CommandPalette output remain equivalent
+- Compatibility class: contract restoration under `spec:AST-017/FR1,FR3,FR5` for
+ standalone semantics, since no-popup standalone use has no released popup
+ association to preserve; accessibility behavior fix under `spec:AST-017/FR53`
+ for the default name
+- Controlled/uncontrolled behavior: unchanged
+- Migration decision: `role="combobox"` keeps the earlier standalone semantics,
+ and `label` or `aria-label` keeps a specific name; the primary callback naming
+ question remains OQ1
+
+Consumer migration instructions belong in consumer docs and release notes.
+
+## Ownership boundary
+
+**Owns**
+
+- The arrangement inside Input: Search glyph, native Query field, Loading spinner
+ placement, and Trailing content.
+- The query field's role and popup state when CommandPalette context is present.
+- Context fallback for the search value, value updates, and keyboard navigation.
+
+**Does not own / non-goals**
+
+- The result popup, option collection, selection, or search orchestration — owned
+ by `component:CommandPalette` and its list/item parts.
+- Spinner and search-glyph rendering — delegated to Spinner and Icon.
+- Caller-provided trailing content behavior — owned by the product callsite.
+
+## Public concepts
+
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ---------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------ | ----------------------------------------- | -------------------- | ------------------------------- | --------- | ------------------------------------------------------------ |
+| Query binding | explicit; CommandPalette context; native | Source and destination of query text changes. | All uses | context, then native | `component:CommandPaletteInput` | Released | Missing handlers leave native state |
+| Popup semantics | standalone searchbox; standalone caller-owned popup; contextual CommandPalette popup | Whether the query field controls a result popup. | Context-dependent | standalone searchbox | `component:CommandPaletteInput` | Stable | Standalone overrides persist; CommandPalette context wins |
+| Trailing content | busy indicator; `endContent`; both; absent | Supporting status or caller content after query. | All uses | absent | `component:CommandPaletteInput` | Released | Boolean, empty-string, null, and undefined values are absent |
+
+## Behavioral and layout contract
+
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | ---------------------------------------------------------- |
+| FR1 | Explicit `value` and `onValueChange` take precedence; otherwise CommandPalette context supplies search state; native uncontrolled state remains when neither exists. | Released source, docs, and tests | Verified current behavior |
+| FR2 | Consumer `onKeyDown` runs before contextual navigation; preventing the event prevents contextual delegation. | Released source and tests | Verified current behavior |
+| FR3 | `ref` and native passthrough attributes reach the native query field; standalone caller-owned popup semantics persist, while CommandPalette context owns its popup role and relationships; `xstyle`, `className`, and `style` customize the surrounding Input. | Released source and docs; `architecture:public-component-api/INV5` | Verified current routing |
+| FR4 | Pending state and renderable `endContent` share one trailing-content group; booleans, empty strings, null, and undefined do not create empty trailing chrome. | React rendering semantics and current utility contract | Verified current behavior |
+| FR5 | Auto-focus is enabled by default and suppressed inside an inline Dialog; `hasAutoFocus={false}` suppresses both focus work and the autofocus marker. | Released source, docs, and tests | Verified current behavior; browser timing evidence remains |
+
+### Allowed variation
+
+- **AV1 — Query content.** Value, placeholder, label, and caller-provided trailing
+ content may vary without changing semantic ownership.
+- **AV2 — Delegated visuals.** Icon and Spinner may change internal markup while
+ preserving their public contracts.
+
+### Representative states
+
+| State | Required invariant | Allowed variation |
+| ------------------------ | ----------------------------------------------------------------- | ------------------------------------ |
+| Standalone, no popup | Named searchbox with no popup-only ARIA state. | Explicit value and change handler. |
+| Standalone, caller popup | Caller role, state, relationships, and active descendant persist. | Caller-owned popup model. |
+| Contextual, closed | Named combobox references the list and reports collapsed state. | Query value and trailing content. |
+| Contextual, open | Named combobox references the list and reports expanded state. | Highlighted option and result count. |
+| Contextual, highlighted | Active descendant names the context-owned highlighted option. | Highlighted index. |
+| Pending or trailing | Supporting content remains at the logical trailing edge. | Spinner, caller content, or both. |
+| Inline Dialog | Mount does not steal focus from the surrounding page. | Query and result content. |
+
+### Transformation and precedence order
+
+- **ORD1 — Search state.** Explicit props → CommandPalette context → native
+ uncontrolled state.
+- **ORD2 — Keyboard handling.** Consumer handler → default-prevented check →
+ CommandPalette context handler.
+- **ORD3 — Accessible name.** Native `aria-label` → `label` → the translated
+ default "Search commands" (DEC-1). Placeholder text is never the name.
+
+### Performance and resources
+
+- **PR1 — Focus scheduling.** At most one animation-frame focus request is
+ scheduled by a mounted eligible field; no listener or observer is retained.
+
+## Accessibility contract
+
+- **AR1 — Name.** The native query field always has an explicit accessible name
+ from ORD3 and never takes its name from placeholder text, satisfying
+ `spec:AST-056/AR2` and WCAG 2.2 4.1.2.
+- **AR2 — Role and popup state.** Standalone use without popup attributes exposes
+ a `searchbox` without popup-only state. Standalone callers that provide their
+ own popup relationships retain those semantics. CommandPalette context exposes
+ a `combobox` with context-owned expanded state, list relationship, autocomplete
+ mode, and active descendant, following `spec:AST-020/FR1,FR2` and the WAI-ARIA
+ combobox pattern.
+- **AR3 — Semantic ownership.** With CommandPalette context, the field owns
+ `role`, `aria-expanded`, `aria-autocomplete`, `aria-controls`, and
+ `aria-activedescendant`, and these replace the same native passthrough props;
+ other ARIA props, including `aria-haspopup` and `aria-owns`, pass through.
+ Standalone caller-owned roles and relationships remain intact.
+
+## Design relationships
+
+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
+| ---------------- | --------------------------------------------------------------------------------- | ----------------------------------------- | -------------- | ------------------ |
+| Input | Arranges Search glyph, Query field, Loading spinner, and Trailing content inline. | Current source and public docs | Prominent | FR3, FR4 |
+| Search glyph | Identifies the query affordance without adding a name. | Icon component | Supporting | AR1 |
+| Query field | Receives text, focus, name, and popup semantics. | Current source and accessibility standard | Prominent | FR1–FR3, AR1–AR3 |
+| Loading spinner | Indicates a pending contextual search before Trailing content. | Spinner component | Supporting | FR4 |
+| Trailing content | Keeps caller content at logical inline-end. | Current source and public docs | Supporting | FR4 |
+
+## Family and system relationships
+
+- `component:CommandPalette` owns the result-popup context, aggregate composition,
+ and the open theming-reachability question; this component owns the default
+ Input's query-field semantics and binds them to that context.
+- `spec:AST-017` owns compatibility classification for the released standalone
+ caller-popup and no-popup cases.
+- `spec:AST-020` supplies the WCAG 2.2 and adopted-pattern evidence boundaries.
+- `spec:AST-056/AR2` requires a query-field name distinct from placeholder text;
+ ORD3 and AR1 satisfy it.
+
+## Verification map
+
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ----------- | --------------------------------------------------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ |
+| FR1–FR3 | `CommandPaletteInput.test.tsx` | explicit, context, prevented key, native, caller popup | Reversing state precedence, rerouting the ref, dropping standalone popup relationships, or allowing context semantics to be clobbered fails focused DOM tests. | `audit:CommandPaletteInput/testing` |
+| FR4 | `CommandPaletteInput.test.tsx` | numeric, empty, busy, caller content | Truthiness routing creates empty chrome or moves numeric content away from the trailing edge. | `audit:CommandPaletteInput/behavior` |
+| FR5 | focused unit tests plus exact-head browser evidence | enabled, disabled, inline | Eligible focus is lost, disabled focus is scheduled, or inline mode steals focus. | `audit:CommandPaletteInput/behavior` |
+| AR1–AR3 | unit tests, exact-head axe/browser run, and source review | standalone, open, closed, highlighted | Wrong role/state, consumer clobbering of an owned attribute, or a placeholder-derived name fails semantics and name assertions. | `audit:CommandPaletteInput/a11y` |
+| Theming/RTL | target inventory, Storybook fixture, and RTL D2 audit | standalone trailing content, contextual | Target loss or physical ordering fails the owned fixture. | `audit:CommandPaletteInput/theming` |
+
+## Decision log
+
+### DEC-1 — The query field's default name is "Search commands"
+
+**Reference:** `component:CommandPaletteInput/DEC-1`
+**Decider:** `cixzhang`, 2026-10-14
+
+A screen-reader user reaching the field hears what it does, whatever the
+placeholder says or whether one is set. The default is a fixed, localizable
+"Search commands"; `label` and `aria-label` replace it, and placeholder text is
+never the name.
+
+Rejected: falling back to the placeholder, which a caller writes as a visual
+hint and AST-056 AR2 does not accept as a name.
+
+## Open questions
+
+- **OQ1 — How should the released `onValueChange(value)` primary callback and
+ native-event `onChange(event)` exception migrate to the shared `onChange`
+ callback grammar without breaking existing consumers?** (`human-api`)
+
+## Content boundary
+
+This file does not duplicate consumer prop tables/examples, current audit
+results, implementation steps, or family/system rules. It links to their owners.
diff --git a/packages/core/src/CommandPalette/CommandPaletteInput.test.tsx b/packages/core/src/CommandPalette/CommandPaletteInput.test.tsx
index e61b932c24..a0bad3fbd9 100644
--- a/packages/core/src/CommandPalette/CommandPaletteInput.test.tsx
+++ b/packages/core/src/CommandPalette/CommandPaletteInput.test.tsx
@@ -7,6 +7,7 @@
* @position Testing; validates CommandPaletteInput.tsx implementation
*/
+import {createRef} from 'react';
import {describe, it, expect, vi} from 'vitest';
import {render, screen, fireEvent} from '@testing-library/react';
import {CommandPaletteInput} from './CommandPaletteInput';
@@ -14,6 +15,29 @@ import {CommandPaletteContext} from './CommandPaletteContext';
import {Dialog} from '../Dialog';
import type {CommandPaletteContextValue} from './CommandPaletteContext';
+function makeContext(
+ overrides: Partial<CommandPaletteContextValue> = {},
+): CommandPaletteContextValue {
+ return {
+ search: '',
+ setSearch: vi.fn(),
+ value: '',
+ setValue: vi.fn(),
+ listId: 'list-1',
+ highlightedIndex: -1,
+ setHighlightedIndex: vi.fn(),
+ getItemId: (i: number) => `item-${i}`,
+ selectableItems: [],
+ searchResults: [],
+ selectItem: vi.fn(),
+ onKeyDown: vi.fn(),
+ onClose: vi.fn(),
+ isOpen: true,
+ isBusy: false,
+ ...overrides,
+ };
+}
+
describe('CommandPaletteInput', () => {
it('renders with default placeholder', () => {
render(<CommandPaletteInput />);
@@ -27,40 +51,166 @@ describe('CommandPaletteInput', () => {
).toBeInTheDocument();
});
- it('has combobox role', () => {
+ it('uses searchbox semantics when no popup context exists', () => {
render(<CommandPaletteInput />);
- expect(screen.getByRole('combobox')).toBeInTheDocument();
+ const input = screen.getByRole('searchbox');
+ expect(input).not.toHaveAttribute('aria-expanded');
+ expect(input).not.toHaveAttribute('aria-controls');
+ expect(input).not.toHaveAttribute('aria-autocomplete');
});
- it('has an accessible name by default', () => {
- render(<CommandPaletteInput />);
- expect(screen.getByRole('combobox')).toHaveAttribute(
- 'aria-label',
- 'Search…',
+ it('preserves standalone caller-owned popup semantics', () => {
+ render(
+ <CommandPaletteInput
+ aria-expanded="false"
+ aria-autocomplete="both"
+ aria-controls="caller-list"
+ aria-activedescendant="caller-item"
+ />,
);
+
+ const input = screen.getByRole('combobox');
+ expect(input).toHaveAttribute('aria-expanded', 'false');
+ expect(input).toHaveAttribute('aria-autocomplete', 'both');
+ expect(input).toHaveAttribute('aria-controls', 'caller-list');
+ expect(input).toHaveAttribute('aria-activedescendant', 'caller-item');
});
- it('uses the label prop as the accessible name', () => {
- render(<CommandPaletteInput label="Search commands" />);
+ it('infers caller-owned popup defaults from aria-controls alone', () => {
+ render(<CommandPaletteInput aria-controls="caller-list" />);
+
const input = screen.getByRole('combobox');
- expect(input).toHaveAttribute('aria-label', 'Search commands');
- // The label prop does not affect the visible placeholder
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ expect(input).toHaveAttribute('aria-autocomplete', 'list');
+ expect(input).toHaveAttribute('aria-controls', 'caller-list');
+ });
+
+ it('preserves a caller-owned combobox role and supplies popup defaults', () => {
+ render(<CommandPaletteInput role="combobox" />);
+
+ const input = screen.getByRole('combobox');
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ expect(input).toHaveAttribute('aria-autocomplete', 'list');
+ });
+
+ it('keeps a toggling caller popup a combobox with its own values', () => {
+ function CallerPopup({open}: {open: boolean}) {
+ return (
+ <CommandPaletteInput
+ aria-expanded={open || undefined}
+ aria-controls={open ? 'caller-list' : undefined}
+ />
+ );
+ }
+ const {rerender} = render(<CallerPopup open={false} />);
+
+ const closed = screen.getByRole('combobox');
+ expect(closed).not.toHaveAttribute('aria-expanded');
+ expect(closed).not.toHaveAttribute('aria-controls');
+
+ rerender(<CallerPopup open />);
+ const open = screen.getByRole('combobox');
+ expect(open).toHaveAttribute('aria-expanded', 'true');
+ expect(open).toHaveAttribute('aria-controls', 'caller-list');
+
+ rerender(<CallerPopup open={false} />);
+ expect(screen.getByRole('combobox')).not.toHaveAttribute('aria-expanded');
+ });
+
+ it('omits an explicitly undefined aria-expanded beside a caller list', () => {
+ render(
+ <CommandPaletteInput
+ aria-expanded={undefined}
+ aria-controls="caller-list"
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ expect(input).not.toHaveAttribute('aria-expanded');
+ expect(input).toHaveAttribute('aria-controls', 'caller-list');
+ });
+
+ it.each([
+ ['aria-owns', {'aria-owns': 'caller-list'}],
+ ['aria-haspopup="listbox"', {'aria-haspopup': 'listbox' as const}],
+ ['aria-haspopup={true}', {'aria-haspopup': true}],
+ ])(
+ 'keeps a field wired to its popup only through %s a combobox',
+ (_label, popupProps) => {
+ render(<CommandPaletteInput {...popupProps} />);
+
+ const input = screen.getByRole('combobox');
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ expect(input).toHaveAttribute('aria-autocomplete', 'list');
+ },
+ );
+
+ it.each([
+ ['false', false],
+ ['"false"', 'false' as const],
+ ])('stays a searchbox when aria-haspopup is %s', (_label, value) => {
+ render(<CommandPaletteInput aria-haspopup={value} />);
+
+ const input = screen.getByRole('searchbox');
+ expect(input).not.toHaveAttribute('aria-expanded');
+ expect(input).not.toHaveAttribute('aria-autocomplete');
+ });
+
+ it('is named "Search commands" by default, not by its placeholder', () => {
+ render(<CommandPaletteInput />);
+ const input = screen.getByRole('searchbox', {name: 'Search commands'});
+ expect(input).toHaveAttribute('placeholder', 'Search…');
+ });
+
+ it('uses the label prop as the accessible name', () => {
+ render(<CommandPaletteInput label="Find files" />);
+ const input = screen.getByRole('searchbox', {name: 'Find files'});
expect(input).toHaveAttribute('placeholder', 'Search…');
});
- it('falls back to a custom placeholder for the accessible name', () => {
+ it('never takes its name from a custom placeholder', () => {
render(<CommandPaletteInput placeholder="Type a command..." />);
- expect(screen.getByRole('combobox')).toHaveAttribute(
- 'aria-label',
- 'Type a command...',
+ expect(
+ screen.getByRole('searchbox', {name: 'Search commands'}),
+ ).toHaveAttribute('placeholder', 'Type a command...');
+ });
+
+ it('owns role and popup state inside CommandPalette context, passing other ARIA through', () => {
+ render(
+ <CommandPaletteContext value={makeContext()}>
+ <CommandPaletteInput
+ role="searchbox"
+ aria-expanded={false}
+ aria-controls="caller-list"
+ aria-haspopup="dialog"
+ aria-owns="caller-owned"
+ />
+ </CommandPaletteContext>,
);
+ const input = screen.getByRole('combobox');
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ expect(input).toHaveAttribute('aria-controls', 'list-1');
+ expect(input).toHaveAttribute('aria-autocomplete', 'list');
+ expect(input).toHaveAttribute('aria-haspopup', 'dialog');
+ expect(input).toHaveAttribute('aria-owns', 'caller-owned');
+ });
+
+ it('keeps the default name inside CommandPalette context', () => {
+ render(
+ <CommandPaletteContext value={makeContext()}>
+ <CommandPaletteInput placeholder="Jump to…" />
+ </CommandPaletteContext>,
+ );
+ expect(
+ screen.getByRole('combobox', {name: 'Search commands'}),
+ ).toBeInTheDocument();
});
it('lets a consumer-passed aria-label override the default', () => {
render(
<CommandPaletteInput label="Search commands" aria-label="Custom name" />,
);
- expect(screen.getByRole('combobox')).toHaveAttribute(
+ expect(screen.getByRole('searchbox')).toHaveAttribute(
'aria-label',
'Custom name',
);
@@ -70,15 +220,16 @@ describe('CommandPaletteInput', () => {
const handleChange = vi.fn();
render(<CommandPaletteInput onValueChange={handleChange} />);
- const input = screen.getByRole('combobox');
- fireEvent.change(input, {target: {value: 'test'}});
+ fireEvent.change(screen.getByRole('searchbox'), {
+ target: {value: 'test'},
+ });
expect(handleChange).toHaveBeenCalledWith('test');
});
it('displays controlled value', () => {
render(<CommandPaletteInput value="hello" onValueChange={() => {}} />);
- expect(screen.getByRole('combobox')).toHaveValue('hello');
+ expect(screen.getByRole('searchbox')).toHaveValue('hello');
});
it('forwards native onChange alongside onValueChange', () => {
@@ -92,46 +243,158 @@ describe('CommandPaletteInput', () => {
/>,
);
- const input = screen.getByRole('combobox');
- fireEvent.change(input, {target: {value: 'x'}});
+ fireEvent.change(screen.getByRole('searchbox'), {target: {value: 'x'}});
expect(handleChange).toHaveBeenCalledWith('x');
expect(handleNativeChange).toHaveBeenCalled();
});
- it('has aria-expanded and aria-autocomplete', () => {
- render(<CommandPaletteInput />);
+ it('keeps visible numeric end content in the trailing group', () => {
+ render(<CommandPaletteInput endContent={0} />);
+ const input = screen.getByRole('searchbox');
+ const trailingGroup = screen.getByText('0');
+ expect(trailingGroup.tagName).toBe('SPAN');
+ expect(input.parentElement?.lastElementChild).toBe(trailingGroup);
+ });
+
+ it.each([false, true, '', null, undefined])(
+ 'omits trailing chrome for empty end content %#',
+ endContent => {
+ render(<CommandPaletteInput endContent={endContent} />);
+ expect(
+ screen.getByRole('searchbox').parentElement?.children,
+ ).toHaveLength(2);
+ },
+ );
+
+ it('does not schedule focus when hasAutoFocus is false', async () => {
+ const focusSpy = vi.spyOn(HTMLElement.prototype, 'focus');
+ render(<CommandPaletteInput hasAutoFocus={false} />);
+
+ const input = screen.getByRole('searchbox');
+ await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
+ const inputFocusCalls = focusSpy.mock.calls.filter((_, i) => {
+ return focusSpy.mock.contexts[i] === input;
+ });
+ expect(input).not.toHaveAttribute('data-autofocus');
+ expect(inputFocusCalls).toHaveLength(0);
+ focusSpy.mockRestore();
+ });
+
+ it('forwards the ref and native data attributes to the query field', () => {
+ const ref = createRef<HTMLInputElement>();
+ render(<CommandPaletteInput ref={ref} data-testid="query-field" />);
+
+ expect(ref.current).toBe(screen.getByTestId('query-field'));
+ });
+});
+
+describe('CommandPaletteInput popup context', () => {
+ it('preserves component-owned combobox semantics against rest props', () => {
+ render(
+ <CommandPaletteContext value={makeContext({isOpen: false})}>
+ <CommandPaletteInput
+ role="button"
+ aria-expanded="true"
+ aria-autocomplete="none"
+ aria-controls="wrong-list"
+ aria-activedescendant="wrong-item"
+ />
+ </CommandPaletteContext>,
+ );
+
const input = screen.getByRole('combobox');
- expect(input).toHaveAttribute('aria-expanded', 'true');
+ expect(input).toHaveAttribute('aria-expanded', 'false');
expect(input).toHaveAttribute('aria-autocomplete', 'list');
+ expect(input).toHaveAttribute('aria-controls', 'list-1');
+ expect(input).not.toHaveAttribute('aria-activedescendant');
+ });
+
+ it('renders the busy spinner before trailing content', () => {
+ render(
+ <CommandPaletteContext value={makeContext({isBusy: true})}>
+ <CommandPaletteInput
+ endContent={<span data-testid="trailing-content">⌘K</span>}
+ />
+ </CommandPaletteContext>,
+ );
+
+ const spinner = screen.getByRole('status');
+ const trailingContent = screen.getByTestId('trailing-content');
+ expect(trailingContent.parentElement?.firstElementChild).toContainElement(
+ spinner,
+ );
+ });
+
+ it('reports the contextual open state and controlled list', () => {
+ render(
+ <CommandPaletteContext value={makeContext()}>
+ <CommandPaletteInput />
+ </CommandPaletteContext>,
+ );
+
+ const input = screen.getByRole('combobox');
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ expect(input).toHaveAttribute('aria-controls', 'list-1');
+ });
+
+ it('exposes the highlighted option as the active descendant', () => {
+ render(
+ <CommandPaletteContext value={makeContext({highlightedIndex: 2})}>
+ <CommandPaletteInput />
+ </CommandPaletteContext>,
+ );
+
+ expect(screen.getByRole('combobox')).toHaveAttribute(
+ 'aria-activedescendant',
+ 'item-2',
+ );
+ });
+
+ it('reads and writes search state through context', () => {
+ const setSearch = vi.fn();
+ render(
+ <CommandPaletteContext value={makeContext({search: 'hel', setSearch})}>
+ <CommandPaletteInput />
+ </CommandPaletteContext>,
+ );
+
+ const input = screen.getByRole('combobox');
+ expect(input).toHaveValue('hel');
+ fireEvent.change(input, {target: {value: 'help'}});
+ expect(setSearch).toHaveBeenCalledWith('help');
+ });
+
+ it('gives explicit search state precedence over context', () => {
+ const setSearch = vi.fn();
+ const onValueChange = vi.fn();
+ render(
+ <CommandPaletteContext
+ value={makeContext({search: 'context', setSearch})}>
+ <CommandPaletteInput value="explicit" onValueChange={onValueChange} />
+ </CommandPaletteContext>,
+ );
+
+ const input = screen.getByRole('combobox');
+ expect(input).toHaveValue('explicit');
+ fireEvent.change(input, {target: {value: 'next'}});
+ expect(onValueChange).toHaveBeenCalledWith('next');
+ expect(setSearch).not.toHaveBeenCalled();
+ });
+
+ it('does not delegate a consumer-prevented keyboard event', () => {
+ const onKeyDown = vi.fn();
+ render(
+ <CommandPaletteContext value={makeContext({onKeyDown})}>
+ <CommandPaletteInput onKeyDown={event => event.preventDefault()} />
+ </CommandPaletteContext>,
+ );
+
+ fireEvent.keyDown(screen.getByRole('combobox'), {key: 'ArrowDown'});
+ expect(onKeyDown).not.toHaveBeenCalled();
});
-});
-describe('CommandPaletteInput dialog context', () => {
- function makeContext(
- overrides: Partial<CommandPaletteContextValue> = {},
- ): CommandPaletteContextValue {
- return {
- search: '',
- setSearch: vi.fn(),
- value: '',
- setValue: vi.fn(),
- listId: 'list-1',
- highlightedIndex: -1,
- setHighlightedIndex: vi.fn(),
- getItemId: (i: number) => `item-${i}`,
- selectableItems: [],
- searchResults: [],
- selectItem: vi.fn(),
- onKeyDown: vi.fn(),
- onClose: vi.fn(),
- isOpen: true,
- isBusy: false,
- ...overrides,
- };
- }
-
- it('does not auto-focus inside an inline dialog', () => {
+ it('does not auto-focus inside an inline dialog', async () => {
const focusSpy = vi.spyOn(HTMLElement.prototype, 'focus');
render(
<Dialog isOpen isInline onOpenChange={() => {}}>
@@ -142,6 +405,7 @@ describe('CommandPaletteInput dialog context', () => {
);
const input = screen.getByRole('combobox');
+ await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
const inputFocusCalls = focusSpy.mock.calls.filter((_, i) => {
return focusSpy.mock.contexts[i] === input;
});
@@ -156,7 +420,6 @@ describe('CommandPaletteInput dialog context', () => {
</CommandPaletteContext>,
);
- // Auto-focus uses requestAnimationFrame — flush it
await vi.waitFor(() => {
expect(screen.getByRole('combobox')).toHaveFocus();
});
diff --git a/packages/core/src/CommandPalette/CommandPaletteInput.tsx b/packages/core/src/CommandPalette/CommandPaletteInput.tsx
index 00385b33a5..30ae779737 100644
--- a/packages/core/src/CommandPalette/CommandPaletteInput.tsx
+++ b/packages/core/src/CommandPalette/CommandPaletteInput.tsx
@@ -9,6 +9,7 @@
*
* SYNC: When modified, update these files to stay in sync:
* - /apps/storybook/stories/CommandPalette.stories.tsx
+ * - /apps/storybook/stories/CommandPaletteInput.stories.tsx
* - /packages/cli/assets/templates/blocks/components/CommandPalette/ (showcase blocks)
*/
@@ -16,7 +17,7 @@ import {useCallback, useEffect, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {Icon} from '../Icon';
import {Spinner} from '../Spinner';
-import {mergeProps} from '../utils';
+import {isRenderable, mergeProps} from '../utils';
import {
colorVars,
typeScaleVars,
@@ -112,14 +113,14 @@ export interface CommandPaletteInputProps extends Omit<
/**
* Placeholder text for the input.
- * @default 'Search...'
+ * @default 'Search…'
*/
placeholder?: string;
/**
- * Accessible label for the combobox input, announced by screen readers.
- * Falls back to the placeholder text (`'Search…'` by default), since a
- * placeholder alone is not a reliable accessible name.
+ * Accessible label for the query field, announced by screen readers. The
+ * placeholder is never the field's name.
+ * @default 'Search commands'
*/
label?: string;
@@ -184,6 +185,33 @@ export function CommandPaletteInput({
// Use context values as fallback
const value = controlledValue ?? ctx?.search;
const handleValueChange = onValueChange ?? ctx?.setSearch;
+ const accessibleLabel =
+ props['aria-label'] ?? label ?? t('@astryx.commandPalette.input.label');
+ const hasEndContent = isRenderable(endContent);
+ // A popup attribute the caller passes is caller-owned even while its value
+ // is undefined (`aria-expanded={open || undefined}`), so the role stays
+ // stable as the caller's popup opens and closes, and a present value is
+ // passed through unchanged.
+ // `aria-haspopup` counts unless it says there is no popup.
+ const callerSets = (key: keyof typeof props) => Object.hasOwn(props, key);
+ const callerDeclaresPopup =
+ callerSets('aria-haspopup') &&
+ props['aria-haspopup'] !== false &&
+ props['aria-haspopup'] !== 'false';
+ const callerOwnsPopup =
+ !ctx &&
+ (props.role === 'combobox' ||
+ callerSets('aria-expanded') ||
+ callerSets('aria-autocomplete') ||
+ callerSets('aria-controls') ||
+ callerSets('aria-owns') ||
+ callerSets('aria-activedescendant') ||
+ callerDeclaresPopup);
+ const standaloneRole = callerSets('role')
+ ? props.role
+ : callerOwnsPopup
+ ? 'combobox'
+ : 'searchbox';
// When rendered inside an inline dialog, disable auto-focus by default
// to avoid stealing focus from the surrounding page.
@@ -223,20 +251,37 @@ export function CommandPaletteInput({
<Icon icon="search" size="sm" color="inherit" />
</span>
<input
+ {...props}
ref={useMergedRefs(ref, inputRef)}
+ {...stylex.props(styles.input)}
type="text"
- role="combobox"
- aria-expanded={ctx?.isOpen ?? true}
- aria-autocomplete="list"
- aria-controls={ctx?.listId}
+ role={ctx ? 'combobox' : standaloneRole}
+ aria-expanded={
+ ctx
+ ? ctx.isOpen
+ : callerSets('aria-expanded')
+ ? props['aria-expanded']
+ : callerOwnsPopup || undefined
+ }
+ aria-autocomplete={
+ ctx
+ ? 'list'
+ : callerSets('aria-autocomplete')
+ ? props['aria-autocomplete']
+ : callerOwnsPopup
+ ? 'list'
+ : undefined
+ }
+ aria-controls={ctx ? ctx.listId : props['aria-controls']}
aria-activedescendant={
- ctx && ctx.highlightedIndex >= 0
- ? ctx.getItemId(ctx.highlightedIndex)
- : undefined
+ ctx
+ ? ctx.highlightedIndex >= 0
+ ? ctx.getItemId(ctx.highlightedIndex)
+ : undefined
+ : props['aria-activedescendant']
}
- // A placeholder alone is not a reliable accessible name; give the
- // combobox an explicit one (consumer aria-label via rest props wins).
- aria-label={label ?? placeholder}
+ // Placeholder text is never the field's name (AST-056 AR2).
+ aria-label={accessibleLabel}
placeholder={placeholder}
value={value}
data-autofocus={effectiveAutoFocus || undefined}
@@ -245,19 +290,17 @@ export function CommandPaletteInput({
onChange?.(e);
}}
onKeyDown={handleKeyDown}
- {...stylex.props(styles.input)}
- {...props}
/>
- {(ctx?.isBusy || endContent) && (
+ {(ctx?.isBusy || hasEndContent) && (
<span {...stylex.props(styles.end)}>
{ctx?.isBusy && (
<span {...stylex.props(styles.icon, styles.spinner)}>
<Spinner size="sm" />
</span>
)}
- {endContent}
+ {hasEndContent && endContent}
</span>
- )}{' '}
+ )}
</div>
);
}