An open source design system that's fully customizable and agent ready
TypeScript
[Component Audit] CommandPalette: protect nested layers and text entry (#6950)
Cindy Zhang2710a135aacc
diff --git a/.changeset/command-palette-shared-dismissal.md b/.changeset/command-palette-shared-dismissal.mdnew file mode 100644index 0000000000..79e5c9dc26--- /dev/null+++ b/.changeset/command-palette-shared-dismissal.md@@ -0,0 +1,11 @@+---+'@astryxdesign/core': patch+---++[fix] Keep CommandPalette dismissal, text entry, result focus, and empty-state accessibility aligned with shared contracts. These accessibility behaviors change (AST-017 FR53; WCAG 2.2 2.1.1 Keyboard and 4.1.2 Name, Role, Value):++- While no selectable result exists, the results container no longer exposes an empty `listbox`, and the query field reports `aria-expanded="false"` with no `aria-controls` or `aria-activedescendant`. It was an expanded combobox controlling an empty listbox.+- Home and End move the caret in the query field, as in any text field; they used to jump to the first and last result. Page Up and Page Down still jump to the first and last result.+- A search with no results announces the empty message the palette renders (`No results` by default, or the caller's `emptySearchText`), once the search settles. It used to announce `No results for <query>`, whatever the palette showed. An override of the `@astryx.commandPalette.noResultsFor` catalog entry no longer has any effect; use `emptySearchText` to customize the message.++@cixzhangdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 66cff2406a..b0554b558a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -2244,6 +2244,35 @@ jobs:retention-days: 30if-no-files-found: error+ # CommandPalette's interactive stories previously rendered only closed+ # triggers. Its owned matrix keeps grouped, empty, and pending anatomy+ # reachable for semantic, contrast, direction, and viewport receipts.+ - name: Run CommandPalette audit browser evidence+ if: github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] CommandPalette:')+ env:+ ASTRYX_HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ run: |+ node .github/scripts/accessibility-audit.js \+ --storybook-dir apps/storybook/dist \+ --output command-palette-a11y-report.json \+ --components CommandPalette \+ --baseline .github/a11y-baseline.json \+ --fail-on-new+ pnpm exec playwright test \+ packages/core/src/CommandPalette/__tests__/CommandPalette.a11y.chromium.spec.ts \+ --project chromium++ - name: Upload CommandPalette audit evidence+ if: always() && github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] CommandPalette:')+ uses: actions/upload-artifact@v7+ with:+ name: command-palette-audit-evidence-${{ needs.build-storybook.outputs.short_hash }}+ path: |+ command-palette-a11y-report.json+ test-results/command-palette-audit-evidence/+ retention-days: 30+ if-no-files-found: error+# Component-owned metadata fixtures retain exact-head browser receipts on# audit PRs, including failed pre-fix cases for before/after comparison.- name: Run ChatMessageMetadata audit browser evidencediff --git a/apps/storybook/stories/CommandPalette.stories.tsx b/apps/storybook/stories/CommandPalette.stories.tsxindex a699a068fc..16fa2d859b 100644--- a/apps/storybook/stories/CommandPalette.stories.tsx+++ b/apps/storybook/stories/CommandPalette.stories.tsx@@ -7,7 +7,7 @@* 1. No props beyond searchSource — default input, footer, rendering* 2. renderItem — custom item content, grouping still automatic*/-import {useState, useMemo} from 'react';+import {useEffect, useMemo, useRef, useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';import {CommandPalette,@@ -463,3 +463,143 @@ export const ThemedGroupHeading: Story = {</Theme>),};++// ─── Audit matrix ─────────────────────────────────────────────────────────────++/**+ * Stable, always-rendered states for visual, accessibility, RTL, and responsive+ * verification. Inline mode keeps each palette in normal document flow while+ * preserving the same owned input, result, empty, pending, and footer anatomy.+ */+export const AuditMatrix: Story = {+ tags: ['visual-theme-matrix'],+ render: function Render() {+ // React entangles async transitions that are in flight together, so a+ // never-settling bootstrap started beside the other palettes' would keep+ // them busy too. Mount the pending palette only after the grouped and+ // empty results have rendered without a spinner, so only it is busy.+ const matrixRef = useRef<HTMLDivElement>(null);+ const [isPendingMountable, setIsPendingMountable] = useState(false);+ useEffect(() => {+ const matrix = matrixRef.current;+ if (matrix == null) {+ return;+ }+ const hasSettled = () =>+ matrix.querySelector('[role="option"]') != null &&+ matrix.querySelector('.astryx-spinner') == null;+ if (hasSettled()) {+ setIsPendingMountable(true);+ return;+ }+ const observer = new MutationObserver(() => {+ if (hasSettled()) {+ observer.disconnect();+ setIsPendingMountable(true);+ }+ });+ observer.observe(matrix, {childList: true, subtree: true});+ return () => observer.disconnect();+ }, []);+ const groupedSource = useMemo(+ () =>+ createStaticSource([+ {id: 'home', label: 'Home', auxiliaryData: {group: 'Navigation'}},+ {+ id: 'settings',+ label: 'Settings',+ auxiliaryData: {group: 'Navigation'},+ },+ {id: 'save', label: 'Save', auxiliaryData: {group: 'Actions'}},+ {id: 'export', label: 'Export', auxiliaryData: {group: 'Actions'}},+ ]),+ [],+ );+ const emptySource = useMemo(() => createStaticSource([]), []);+ const pendingSource = useMemo<SearchSource>(+ () => ({+ bootstrap: () => new Promise<SearchableItem[]>(() => {}),+ search: () => new Promise<SearchableItem[]>(() => {}),+ }),+ [],+ );+ const panelStyle = {+ flex: '1 1 280px',+ minWidth: 0,+ } as const;+ const headingStyle = {+ marginBlock: '0 8px',+ font: 'inherit',+ fontWeight: 600,+ } as const;++ return (+ <div+ ref={matrixRef}+ data-command-palette-audit-matrix+ style={{+ display: 'flex',+ flexWrap: 'wrap',+ alignItems: 'flex-start',+ gap: 16,+ width: '100%',+ padding: 16,+ boxSizing: 'border-box',+ }}>+ <section style={panelStyle}>+ <h2 style={headingStyle}>Grouped results</h2>+ <CommandPalette+ isOpen+ isInline+ role="region"+ label="Grouped command palette"+ onOpenChange={() => {}}+ searchSource={groupedSource}+ value="settings"+ width="100%"+ maxHeight={420}+ />+ </section>+ <section style={panelStyle}>+ <h2 style={headingStyle}>Empty bootstrap</h2>+ <CommandPalette+ isOpen+ isInline+ role="region"+ label="Empty command palette"+ onOpenChange={() => {}}+ searchSource={emptySource}+ emptyBootstrapText={+ <span>+ No commands yet. <a href="#new-command">Create a command</a>+ </span>+ }+ emptySearchText={+ <span>+ No matching commands.{' '}+ <a href="#new-command">Create a command</a>+ </span>+ }+ width="100%"+ maxHeight={420}+ />+ </section>+ <section style={panelStyle}>+ <h2 style={headingStyle}>Pending bootstrap</h2>+ {isPendingMountable && (+ <CommandPalette+ isOpen+ isInline+ role="region"+ label="Pending command palette"+ onOpenChange={() => {}}+ searchSource={pendingSource}+ width="100%"+ maxHeight={420}+ />+ )}+ </section>+ </div>+ );+ },+};diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.mdindex 12c6edf151..05f21651e7 100644--- a/docs/architecture/layer-runtime.md+++ b/docs/architecture/layer-runtime.md@@ -38,6 +38,7 @@ verified_by:packages/core/src/ContextMenu/ContextMenu.test.tsx,packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx,packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx,+ packages/core/src/CommandPalette/CommandPalette.test.tsx,packages/core/src/hooks/useFocusTrap.test.tsx,packages/core/src/hooks/useMenuHover.test.tsx,packages/core/src/Toast/ToastViewport.test.tsx,@@ -328,8 +329,10 @@ handoff survive. Toast state lives inside the viewport. A viewport rendered with`isTopLayer={false}` stays in place.CommandPalette composes native Dialog. Its normal launcher presentation therefore-uses `showModal()`; its documentation/showcase `isInline` path does not. It-currently handles Escape on its own element as well as composing Dialog.+uses `showModal()`; its documentation/showcase `isInline` path does not. The+modal path delegates Escape to Dialog's shared dismissal registration. Only the+inline preview closes from CommandPalette's local key handler because it is not a+registered layer.Banner and FieldStatus are in-flow. `useAnnounce` is nonvisual. AlertDialog,imperative Dialog, Lightbox, and ordinary Popover-family surfaces are@@ -397,7 +400,6 @@ Current gaps are observable facts, not current target behavior:gesture claim or one association model.- Toast's root and fallback hosts remain behind the other native modals:Lightbox, MobileNav, and a scrim BottomSheet or BottomSheetSwitcher.-- CommandPalette's local Escape handler bypasses shared owner selection.- The reduced browser fallback is not documented as non-equivalent.- Existing tests simulate Popover `toggle` and DOM nesting; they do not provenative pointer light dismissal, top-layer/modal ordering, real anchor geometry,diff --git a/docs/families/overlay-dismissal.md b/docs/families/overlay-dismissal.mdindex ec45f70e65..d76df7cb33 100644--- a/docs/families/overlay-dismissal.md+++ b/docs/families/overlay-dismissal.md@@ -19,6 +19,7 @@ verified_by:packages/core/src/hooks/useFocusTrap.test.tsx,packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx,packages/core/src/ContextMenu/ContextMenu.test.tsx,+ packages/core/src/CommandPalette/CommandPalette.test.tsx,]members:[@@ -191,6 +192,7 @@ this record's current membership snapshot must be updated with it.| --------------------------------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------- || Dialog inside Dialog | Inner dialog handles the first request | Dialog supplies native modality and focus behavior || Popover inside Dialog | Popover handles the first Escape | Popover supplies anchoring, portal placement, and focus policy |+| Registered descendant inside CommandPalette | Descendant handles the first Escape | CommandPalette inherits Dialog's shared stack participation || Tooltip or HoverCard inside Dialog | Present hover surface handles the first Escape | Hover families decide when they are present and how controlled state responds || Lightbox or MobileNav above a required Dialog | Top member handles the request | Required Dialog uses `block` only when it is topmost || Required Dialog alone | Request is consumed without closing | Dialog purpose selects `block` behavior |@@ -202,12 +204,12 @@ this record's current membership snapshot must be updated with it.| Components or surface | Adoption | Current deviation or limitation || -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Dialog, AlertDialog, Popover, DropdownMenu root, ContextMenu, MoreMenu, Lightbox, MobileNav, Lab Drawer | shared owner | none |+| Dialog, AlertDialog, Popover, DropdownMenu root, ContextMenu, MoreMenu, Lightbox, MobileNav, Lab Drawer, CommandPalette | shared owner; CommandPalette composes Dialog | none || Tooltip, HoverCard | shared owner with DOM presence reporting | Neither provides nesting depth to descendant layers || Focus traps with `onEscape` | shared owner through `useFocusTrap` | They provide DOM containment, not descendant depth || BreadcrumbItem, ChatComposerInput, ComplexSelector, DateInput, DateRangeInput, DateTimeInput, Selector, MultiSelector, PowerSearch, BaseTypeahead, Typeahead, Tokenizer, SideNavHeading, SideNavItem, TabMenu, TopNavHeading, TopNavMenu, TopNavMegaMenu, Table, Lab TourStep, Lab ChatEmojiPicker | shared owner through `usePopover` or a composed Popover owner | Table filtering owns controlled Popover state and discards its draft on close; TourStep routes Popover close to the Tour; ChatEmojiPicker owns controlled Popover state || BottomSheet, BottomSheetSwitcher | shared owner | none |-| CommandPalette, DropdownMenuSubMenu, PowerSearchEditPopover | local only | Must migrate from component-specific listeners or registries to the shared owner |+| DropdownMenuSubMenu, PowerSearchEditPopover | local only | Must migrate from component-specific listeners or registries to the shared owner |The rows marked partial or local are current adoption gaps against FR1. They arenot approved exceptions. Migration must preserve each component's existing focus,@@ -215,12 +217,12 @@ modality, positioning, outside-dismissal, and open-state contracts.## Verification map-| Contract | Verification | Representative members and states | Mutation or failure expectation |-| ------------------ | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |-| FR1, FR2, FR4, FR5 | `useLayerDismissal.test.tsx`; `BottomSheetSwitcher.test.tsx`; `ContextMenu.test.tsx` | synthetic provider depth, same-DOM containment, non-modal switcher nesting, ContextMenu nested layers, unrelated, blocking, content-handled, present/absent | Removing depth, presence filtering, or event deferral sends Escape to the wrong surface |-| FR2, FR3, FR4, FR6 | `layerDismissalInvariants.test.tsx` | nested same-DOM Dialogs, Lightbox over Dialog, Dialog in BottomSheet, platform cancel, IME | One request closes two surfaces, closes a host before its child, or dismisses during composition |-| FR1, FR2, FR3, FR7 | `layerDismissalFamilies.test.tsx` | Dialog, Lightbox, MobileNav, BottomSheet, Tooltip, HoverCard; controlled and blocking states | A family bypasses the stack, a lower member handles a request, or controlled ownership is ignored |-| FR1 | `useFocusTrap.test.tsx` | active, nested, and deactivated traps with `onEscape` | A dismissible trap stays off the shared stack or nested traps respond together |+| Contract | Verification | Representative members and states | Mutation or failure expectation |+| ------------------ | --------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |+| FR1, FR2, FR4, FR5 | `useLayerDismissal.test.tsx`; `BottomSheetSwitcher.test.tsx`; `ContextMenu.test.tsx`; `CommandPalette.test.tsx` | synthetic provider depth, same-DOM containment, non-modal switcher nesting, ContextMenu nested layers, CommandPalette descendant nesting, unrelated, blocking, content-handled, present/absent | Removing depth, presence filtering, or event deferral sends Escape to the wrong surface |+| FR2, FR3, FR4, FR6 | `layerDismissalInvariants.test.tsx` | nested same-DOM Dialogs, Lightbox over Dialog, Dialog in BottomSheet, platform cancel, IME | One request closes two surfaces, closes a host before its child, or dismisses during composition |+| FR1, FR2, FR3, FR7 | `layerDismissalFamilies.test.tsx` | Dialog, Lightbox, MobileNav, BottomSheet, Tooltip, HoverCard; controlled and blocking states | A family bypasses the stack, a lower member handles a request, or controlled ownership is ignored |+| FR1 | `useFocusTrap.test.tsx` | active, nested, and deactivated traps with `onEscape` | A dismissible trap stays off the shared stack or nested traps respond together |## Decision linksdiff --git a/docs/specs/AST-009/spec.md b/docs/specs/AST-009/spec.mdindex 7371bfe922..ec2cdbf503 100644--- a/docs/specs/AST-009/spec.md+++ b/docs/specs/AST-009/spec.md@@ -184,6 +184,22 @@ All three rows block that stable release until they have passing durable receiptThe [Popover contract](../../../packages/core/src/Popover/Popover.spec.md), [layer runtime](../../architecture/layer-runtime.md), and [overlay dismissal](../../families/overlay-dismissal.md) continue to own focus, runtime, and dismissal behavior. AST-009 owns only the real-AT evidence and stable-release block for the claimed outcome.+### Pending release block — pull request #6950++| Field | Value |+| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Source change | Pull request [#6950](https://github.com/facebook/astryx/pull/6950) changes CommandPalette's empty-result live-region content and query-state announcement timing. Bind the final receipt to the landed commit after merge. |+| Affected release | The first stable release containing the landed pull request. |+| Trigger | FR4. The intended result depends on what the live region announces, when a populated result set narrows to nothing, and whether the update repeats or is skipped. |+| Scenario | Open the checked-in `CommandPalette / Audit Matrix` story. **Narrow to empty:** within the panel labeled `Grouped command palette`, focus its `Search commands` input, which lists four results. Type `s`, then `x`, one key at a time. After `s` the results narrow to Settings and Save and no empty-result message is announced. After `x` nothing matches: confirm `No results` is announced once, after the results are replaced by the message. Type `z`: the query still matches nothing and `No results` is announced once more, because each settled empty query announces once. Clear the query and confirm the four results return with no empty-result announcement. **Rendered message:** within the panel labeled `Empty command palette`, focus its `Search commands` input and paste `missing` as one edit. Confirm the rendered `No matching commands. Create a command` message is announced once, without substituting the built-in default. Clear the query and paste `missing` again; it is announced once more. |++| Required pairing | State |+| --------------------------- | --------- |+| NVDA + Chrome on Windows | `pending` |+| VoiceOver + Safari on macOS | `pending` |++Both rows block the first affected stable release until each has a passing durable receipt or a current owner-recorded exception. DOM, axe, accessibility-tree, and browser evidence continue to prove their assigned claims but do not clear this announcement gate.+This accepted spec creates no runtime or process implementation.**Current enforcement status: missing.** No automated fail-closed check currently reads this block before publication. Implementing that check is non-blocking stack work for this documentation slice. Until it lands, this record states the required hold but does not itself prevent publication.diff --git a/docs/specs/AST-056-search-prop-shape/spec.md b/docs/specs/AST-056-search-prop-shape/spec.mdindex 6f36a0e76f..5cb12dd932 100644--- a/docs/specs/AST-056-search-prop-shape/spec.md+++ b/docs/specs/AST-056-search-prop-shape/spec.md@@ -252,10 +252,9 @@ copying.person on screen is not reading.- **AR2 — The query input has an accessible name that is not its placeholder.**A placeholder is placeholder text and MUST NOT be the input's only- accessible name. The component supplies the name — `Selector` and- `MultiSelector` use a localized "Search options" today — and a component- that falls back to the placeholder, as `CommandPaletteInput` does and its own- comment flags, MUST gain a real name as part of adopting this record.+ accessible name. The component supplies the name: a localized "Search+ options" in `Selector` and `MultiSelector`, and a localized "Search commands"+ in `CommandPaletteInput`.### Platform support@@ -264,11 +263,11 @@ copying.- Unsupported behavior: none. A component that cannot satisfy FR3'srequired/optional rule does not partially adopt the prop; it keeps itscurrent API until the rule is settled for it.-- Browser evidence: this record contracts prop shape and announcement, not- layout or paint, so every requirement here is provable in jsdom. AR1's- announcement is a live-region assertion, not a pixel claim. Adopting- components keep whatever real-browser evidence their own records already- require.+- Browser evidence: DOM live-region assertions prove the rendered content source,+ but they do not prove what assistive technology announces or when. Any adopter+ that changes announcement content or timing follows `spec:AST-009`: name the+ applicable real-AT matrix and keep the first affected stable release blocked+ until the required durable receipts pass or a current exception applies.## Migration and compatibilitydiff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex 3f482c5d35..d8b0e9a254 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -409,7 +409,7 @@},"@astryx.commandPalette.noResultsFor": {"defaultMessage": "No results for {query}",- "description": "Screen-reader-only announcement when a CommandPalette query matches nothing. `{query}` is the user's verbatim search text; keep it last if your language allows so truncation-by-AT still conveys the outcome."+ "description": "Not read by any component: CommandPalette announces its rendered empty-search message (`emptySearchText`) instead. Formerly the screen-reader-only announcement when a query matched nothing; `{query}` was the user's verbatim search text."},"@astryx.commandPalette.loading": {"defaultMessage": "Loading",diff --git a/packages/core/src/CommandPalette/CommandPalette.doc.mjs b/packages/core/src/CommandPalette/CommandPalette.doc.mjsindex 927d771faf..65eabe8e63 100644--- a/packages/core/src/CommandPalette/CommandPalette.doc.mjs+++ b/packages/core/src/CommandPalette/CommandPalette.doc.mjs@@ -33,7 +33,7 @@ const anatomy = [name: 'List',required: true,description:- 'Scrollable listbox containing the current results or Empty state.',+ 'Scrollable results container: a listbox while selectable results exist, otherwise the Empty state as plain content.',},{name: 'Item',@@ -242,11 +242,21 @@ export const docs = {description:'Use auxiliaryData.group on items to automatically organize results into labeled sections.',},+ {+ guidance: true,+ description:+ 'Provide a specific label when more than one command palette can appear in the same product surface.',+ },{guidance: true,description:'Keep renderItem content non-interactive; each rendered row is one option, so buttons and links cannot be nested inside it.',},+ {+ guidance: false,+ description:+ 'Intercept query-field keyboard events without preserving active IME composition and native Home/End caret movement.',+ },{guidance: false,description:@@ -278,11 +288,21 @@ export const docsZh = {description:'Use auxiliaryData.group on items to automatically organize results into labeled sections.',},+ {+ guidance: true,+ description:+ 'Provide a specific label when more than one command palette can appear in the same product surface.',+ },{guidance: true,description:'Keep renderItem content non-interactive; each rendered row is one option, so buttons and links cannot be nested inside it.',},+ {+ guidance: false,+ description:+ 'Intercept query-field keyboard events without preserving active IME composition and native Home/End caret movement.',+ },{guidance: false,description:@@ -316,11 +336,21 @@ export const docsDense = {description:'Use auxiliaryData.group on items to automatically organize results into labeled sections.',},+ {+ guidance: true,+ description:+ 'Provide a specific label when more than one command palette can appear in the same product surface.',+ },{guidance: true,description:'Keep renderItem content non-interactive; each rendered row is one option, so buttons and links cannot be nested inside it.',},+ {+ guidance: false,+ description:+ 'Intercept query-field keyboard events without preserving active IME composition and native Home/End caret movement.',+ },{guidance: false,description:diff --git a/packages/core/src/CommandPalette/CommandPalette.spec.md b/packages/core/src/CommandPalette/CommandPalette.spec.mdindex 5769c0bb43..4dff2ab531 100644--- a/packages/core/src/CommandPalette/CommandPalette.spec.md+++ b/packages/core/src/CommandPalette/CommandPalette.spec.md@@ -1,6 +1,6 @@---schema_version: 3-template_version: 3+template_version: 7kind: componentid: component:CommandPaletteauthority: draft@@ -18,6 +18,7 @@ verified_by:packages/core/src/CommandPalette/CommandPaletteItem.test.tsx,packages/core/src/CommandPalette/CommandPaletteGroup.test.tsx,packages/core/src/CommandPalette/CommandPaletteFooter.test.tsx,+ packages/core/src/CommandPalette/__tests__/CommandPalette.a11y.chromium.spec.ts,packages/core/src/CommandPalette/__tests__/CommandPaletteFooter.a11y.chromium.spec.ts,packages/core/src/theme/themingTargets.test.ts,scripts/check-knowledge.mjs,@@ -32,24 +33,43 @@ architecture:architecture:public-component-api,]contributing: []-system_specs: []+system_specs: [spec:AST-056]---# CommandPalette component contract+## Contract at a glance++| Area | Contract |+| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | Prop and visual APIs are unchanged. The result surface exposes listbox semantics only with selectable results; the query input has a real default name; rich Empty content remains ordinary. |+| Behavior | Modal Escape delegates to Dialog; query-field Home/End and IME remain native; result changes reset stale highlight; Empty announcements mirror rendered content. |+| End-user impact | Nested dismissal and native text entry are preserved; assistive technology receives the visible empty message, an independent query-field name, and only existing active options. |+| Builder impact | None; no migration or new caller choice. |+| Compatibility/readiness | Visual output is preserved. Empty-result ARIA, query-field accessible naming, empty-state announcement, and highlight reset behavior are corrected and verified. |+| Review checks | Reject local modal Escape handling, IME routing, Home/End result navigation, empty listboxes, stale active descendants, placeholder-only names, mismatched Empty announcements, or gaps. |+| Governing rules | `family:overlay-dismissal/FR1`, `FR2`, `FR4`, `FR5`; `spec:AST-056/FR3`, `AR1`, `AR2`; existing public component and delegated-owner contracts. |++This table is a review projection; the body below is authoritative.+## Intent-CommandPalette presents searchable commands inside a Dialog. This draft records-its current aggregate consumer anatomy, target ownership, and delegated stable-parts without changing runtime behavior, styling, targets, or public API.+CommandPalette presents searchable commands inside a Dialog. It owns search and+selection orchestration plus the aggregate consumer anatomy while delegating its+surface and modal dismissal ordering to Dialog.## Compatibility and migration-- Released default preserved: `yes`-- Compatibility class: additive documentation only; runtime, DOM, styling,- targets, aliases, and public API remain unchanged+- Released default preserved: `yes` for props and visual output+- Compatibility class: behavioral and accessibility correction; empty states+ conditionally omit listbox, expanded, controls, and active-descendant ARIA+ attributes until selectable results exist; the default query accessible name+ is independent of its placeholder; empty-search announcements mirror the+ rendered content; public props, styling, targets, and visible defaults remain+ unchanged- Controlled/uncontrolled behavior: unchanged-- Migration decision: none+- Migration decision: adopts `family:overlay-dismissal/FR1`, `FR2`, `FR4`, and+ `FR5` through Dialog; no caller migrationConsumer migration instructions belong in consumer docs and release notes.@@ -83,12 +103,16 @@ documented in `CommandPalette.doc.mjs` and its subcomponent docs.## Behavioral and layout contract-| ID | Candidate invariant | Basis | Draft review state |-| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | ------------------------------------------------------------------------------------- |-| FR1 | The current default render places Input and Footer around a List inside a delegated Dialog; the List contains Items, optional Groups and Group headings, or Empty according to the current results. | Current source, docs, and tests | Verified current behavior; no new behavior decided |-| FR2 | Input, List, Item, Group, Group heading, Empty, and Footer carry the seven current `command-palette-*` targets documented below; no `command-palette` root target exists. | Current source and target docs | Verified current inventory; focused placement covers Group, Group heading, and Footer |-| FR3 | The default Input delegates its Search glyph to Icon and pending Loading spinner to Spinner; the default Footer delegates keyboard shortcuts to Kbd; the containing surface delegates to Dialog. | Current source and component docs | Footer-to-Kbd composition is focused-test verified; no ownership change |-| FR4 | Query field is a distinct native text field inside Input and currently has no separate public target. The `command-palette-input` target is on the surrounding search region, not the native field. | Current source and target docs | Verified current reachability; long-term theming intent remains unsettled |+| ID | Candidate invariant | Basis | Draft review state |+| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------- |+| FR1 | The current default render places Input and Footer around a result surface inside a delegated Dialog. That surface is a List listbox while Items exist and an ordinary Empty container otherwise. | Current source, docs, tests, and ARIA required-child rule | Verified current anatomy and valid rich Empty semantics |+| FR2 | Input, List, Item, Group, Group heading, Empty, and Footer carry the seven current `command-palette-*` targets documented below; no `command-palette` root target exists. | Current source and target docs | Verified current inventory and focused placement coverage |+| FR3 | The default Input delegates its Search glyph to Icon and pending Loading spinner to Spinner; the default Footer delegates keyboard shortcuts to Kbd; the containing surface delegates to Dialog. | Current source and component docs | Verified current composition; no ownership change |+| FR4 | Query field is a distinct native text field inside Input and currently has no separate public target. The `command-palette-input` target is on the surrounding search region, not the native field. | Current source and target docs | Verified current reachability; long-term theming intent remains unsettled |+| FR5 | A modal palette leaves Escape unclaimed for Dialog's shared dismissal stack so a nested member handles the first press; inline previews close locally because they do not register as layers. | `family:overlay-dismissal/FR1`, `FR2`, `FR4`, `FR5` | Verified by nested and inline integration tests |+| FR6 | The editable query field keeps Home and End for native caret movement, uses PageUp and PageDown for first/last result navigation, and does not route active IME composition keys to commands. | WAI-ARIA editable combobox convention; objective IME integrity | Verified by user-event navigation and composition-key tests |+| FR7 | A committed result set resets highlight before exposure; the query input emits active-descendant only for an index that exists in the current selectable set. | WAI-ARIA active-descendant integrity | Verified across populated, empty, and repopulated results |+| FR8 | Empty search announcements mirror rendered `emptySearchText`, including rich caller content; the query input's default accessible name is independent of its placeholder. | `spec:AST-056/FR3`, `AR1`, `AR2` | Verified by live-region and accessible-name tests |### Allowed variation@@ -101,14 +125,14 @@ documented in `CommandPalette.doc.mjs` and its subcomponent docs.### Representative states-| State | Required invariant | Allowed variation |-| ---------------------- | ------------------------------------------------------- | ----------------------------------------------- |-| Ungrouped results | List contains Item instances. | Item count and caller-rendered content. |-| Grouped results | List contains Group, Group heading, and Item instances. | Group names, count, ordering, and item content. |-| Empty bootstrap/search | List contains Empty instead of Items. | Caller-provided empty content. |-| Pending search | Default Input may contain Loading spinner. | Spinner is absent when no search is pending. |-| Default slots | Input and Footer render their documented defaults. | Footer shortcut text and translated labels. |-| Caller-replaced slots | The slot content replaces the corresponding default. | Replacement structure remains caller-owned. |+| State | Required invariant | Allowed variation |+| ---------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------- |+| Ungrouped results | List contains Item instances. | Item count and caller-rendered content. |+| Grouped results | List contains Group, Group heading, and Item instances. | Group names, count, ordering, and item content. |+| Empty bootstrap/search | Empty replaces listbox semantics; search-empty text is announced as rendered. | Caller-provided rich content, including ordinary controls. |+| Pending search | Default Input may contain Loading spinner. | Spinner is absent when no search is pending. |+| Default slots | Input and Footer render their documented defaults. | Footer shortcut text and translated labels. |+| Caller-replaced slots | The slot content replaces the corresponding default. | Replacement structure remains caller-owned. |### Transformation and precedence order@@ -120,8 +144,27 @@ documented in `CommandPalette.doc.mjs` and its subcomponent docs.## Accessibility contract-This draft does not change or extend CommandPalette's current Dialog, combobox,-listbox, option, announcement, or keyboard behavior.+- **AR1 — Named composite.** The containing Dialog, combobox, populated listbox,+ groups, options, busy status, empty state, and keyboard guidance preserve their+ owned accessible names and roles. When no selectable results exist, the result+ surface and combobox omit listbox, expanded, controls, and active-descendant+ semantics so rich Empty content stays ordinary non-nested content.+- **AR2 — Topmost Escape.** A modal palette delegates unclaimed Escape presses to+ Dialog's shared dismissal stack. A nested registered surface handles the first+ press; the host palette remains open until it becomes topmost.+- **AR3 — Inline preview.** Documentation-only inline rendering remains outside+ the shared layer stack and preserves its local Escape close behavior.+- **AR4 — Editable query keys.** Home and End preserve native caret movement;+ PageUp and PageDown navigate to the first and last results; active IME+ composition keys remain owned by the input method.+- **AR5 — Rendered empty message.** A search dead end announces the text rendered+ by `emptySearchText`, including text produced by caller components and links.+- **AR6 — Query-field name.** The default query field name is a localized+ "Search commands" label independent of its placeholder; caller `label` and+ native `aria-label` overrides remain supported.+- **AR7 — Existing active option.** Result changes reset highlight, and+ `aria-activedescendant` is present only when the indexed option exists in the+ current selectable set.## Design relationships@@ -187,27 +230,36 @@ current audit gap and does not authorize a new target.mapping, delegation, and factual `none` dispositions.- `architecture:public-component-api` owns the stable props and compositionsurface; this documentation adds no API.-- `architecture:interaction-modality` owns shared keyboard and pointer modality;- this draft does not redefine focus ownership or input behavior.-- `family:overlay-dismissal` identifies CommandPalette as a current member and- records its component-local Escape handling as an adoption gap.-- No layer-runtime record is linked because no current record with that scope is- present in this checkout.+- `architecture:interaction-modality/INV4` owns supported-modality path+ reachability; the exact query-key details follow objective editable-combobox+ and IME composition standards.+- `spec:AST-056/FR3`, `AR1`, and `AR2` own rendered empty-search announcement+ parity and an accessible query-field name independent of placeholder text.+- `family:overlay-dismissal` owns topmost Escape and close-request ordering;+ CommandPalette adopts it through Dialog while preserving local inline-preview+ closing because inline mode does not register as a layer.+- `architecture:layer-runtime` records that the modal path delegates Escape to+ Dialog's shared dismissal registration while the unregistered inline preview+ preserves local closing.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------ |-| FR1 | CommandPalette root and subcomponent render suites plus browser evidence | Default, grouped, empty, pending, and replaced slots | Removing the asserted Dialog, Query field, List, Item, Group, Group heading, Empty, or Footer content fails role, content, slot, or exact-head browser assertions; Search glyph and Loading spinner presence remain source-inspected only. | `audit:CommandPalette/anatomy` |-| FR2 | `themingTargets.test.ts`, focused subcomponent suites, and browser evidence | Seven local targets; Group, Group heading, and Footer placement | Removing a current target fails the global inventory; moving Group, Group heading, or Footer fails focused class assertions and the Footer browser receipt. | `audit:CommandPalette/theming` |-| FR3 | Focused Footer suite and browser evidence plus delegated component target metadata | Default surface, Input visuals, and Footer shortcuts | Removing Footer's four Kbd shortcuts or either stable target fails focused unit and browser assertions; Icon and Spinner composition remain source-inspected. | `audit:CommandPalette/theming` |-| FR4 | `CommandPaletteInput.test.tsx` and source inspection | Native query field with idle and pending Input | Removing the field fails combobox tests; adding a field target requires an explicit map update. | `audit:CommandPalette/anatomy` |-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and seven current local targets | Missing, extra, prefixed, stale, or alias-backed mappings fail repository validation. | `audit:CommandPalette/theming` |--Focused target-placement assertions cover Group, Group heading, and Footer.-Input, List, Item, and Empty placement rely on source inspection plus the global-target inventory. Focused Footer tests pin all four default Kbd instances; Icon-and Spinner composition remain source-inspected.+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |+| FR1, AR1 | CommandPalette root and subcomponent suites plus exact-head Chromium evidence | Default, grouped, empty, pending, rich Empty, and replaced slots | Exposing an empty listbox, leaving empty Input popup attributes, or nesting rich Empty controls under option semantics fails focused role and hosted axe assertions. | `audit:CommandPalette/anatomy` |+| FR2 | Focused subcomponent suites and `themingTargets.test.ts` | Seven local targets at their owned elements | Removing or moving a current target fails a focused placement assertion or the global inventory. | `audit:CommandPalette/theming` |+| FR3 | `CommandPaletteInput.test.tsx`, `CommandPaletteFooter.test.tsx`, and browser evidence | Default Search glyph, pending spinner, and Footer Kbd | Replacing or removing the delegated Icon, Spinner, or Kbd instance fails a composed-owner assertion and changes the exact-head evidence inventory. | `audit:CommandPalette/theming` |+| FR4 | `CommandPaletteInput.test.tsx` and source inspection | Native query field with idle and pending Input | Removing the field fails combobox tests; adding a field target requires an explicit map update. | `audit:CommandPalette/anatomy` |+| FR5, AR2, AR3 | `CommandPalette.test.tsx` | Modal host with nested layer; inline preview | Restoring local modal Escape handling closes the host instead of the nested surface; removing the inline branch loses preview closing. | `audit:CommandPalette/interaction` |+| FR6, AR4 | `CommandPalette.test.tsx` and `CommandPaletteInput.test.tsx` | Home, End, PageDown, Enter, and active IME composition | Routing Home/End to results or forwarding a composing command key fails user-event and native composition assertions. | `audit:CommandPalette/interaction` |+| FR7, AR7 | `CommandPalette.test.tsx` and `CommandPaletteInput.test.tsx` | Populated, empty, and repopulated result sets | Preserving an out-of-range highlight or emitting its nonexistent active descendant fails transition and direct bounds assertions. | `audit:CommandPalette/a11y` |+| FR8, AR5, AR6 | `CommandPalette.test.tsx`, `CommandPaletteInput.test.tsx`, and i18n checks | Rich caller Empty content; default and caller query names | Announcing catalog copy over rendered caller content or naming the query only through placeholder text fails live-region, name, and catalog assertions. | `audit:CommandPalette/a11y` |+| Theming anatomy map | `scripts/check-knowledge.mjs` and exact-head Chromium evidence | Canonical anatomy and seven current local targets | Missing, extra, prefixed, stale, alias-backed, or visually absent mappings fail repository validation or browser sensor counts. | `audit:CommandPalette/theming` |++Focused target-placement assertions cover all seven local targets. The composed+Input and Footer tests also pin the delegated Search Icon, pending Spinner, and+four default Kbd shortcuts; exact-head browser evidence verifies the same owned+anatomy across light, dark, LTR, RTL, and narrow rendering.## Decision log@@ -218,9 +270,6 @@ layer, API, or theming decision.- **OQ1 — Should Query field gain a stable public theming target?** (`human-api`)Its current lack of direct reachability is an audit gap, not settled intent.-- **OQ2 — Should focused tests pin the default Search glyph and pending Loading- spinner?** (`checkable`) Their presence is currently source-inspected rather- than asserted.## Content boundarydiff --git a/packages/core/src/CommandPalette/CommandPalette.test.tsx b/packages/core/src/CommandPalette/CommandPalette.test.tsxindex b317092b77..1019430d8f 100644--- a/packages/core/src/CommandPalette/CommandPalette.test.tsx+++ b/packages/core/src/CommandPalette/CommandPalette.test.tsx@@ -9,8 +9,11 @@import {describe, it, expect, vi, beforeEach} from 'vitest';import {render, screen, waitFor, fireEvent, act} from '@testing-library/react';+import userEvent from '@testing-library/user-event';import {useState} from 'react';import {CommandPalette} from './CommandPalette';+import {CommandPaletteInput} from './CommandPaletteInput';+import {useLayerDismissal} from '../Layer/useLayerDismissal';import {createStaticSource} from '@astryxdesign/core/Typeahead';import type {SearchSource, SearchableItem} from '@astryxdesign/core/Typeahead';import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';@@ -27,6 +30,11 @@ const groupedSource = createStaticSource([const emptySource = createStaticSource([]);+function NestedDismissible({onDismiss}: {onDismiss: () => void}) {+ useLayerDismissal({isActive: true, onDismiss});+ return null;+}+// Mock showModal and close since jsdom doesn't implement thembeforeEach(() => {HTMLDialogElement.prototype.showModal = vi.fn(function (@@ -198,6 +206,31 @@ describe('CommandPalette', () => {});});+ it('keeps actionable empty content outside listbox semantics', async () => {+ const {container} = render(+ <CommandPalette+ isOpen={true}+ onOpenChange={() => {}}+ searchSource={emptySource}+ emptyBootstrapText={<a href="/commands/new">Create a command</a>}+ />,+ );++ expect(+ await screen.findByRole('link', {name: 'Create a command'}),+ ).toHaveAttribute('href', '/commands/new');+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ expect(screen.queryByRole('option')).not.toBeInTheDocument();+ expect(+ container.querySelectorAll('.astryx-command-palette-empty'),+ ).toHaveLength(1);+ expect(screen.getByRole('combobox')).toHaveAttribute(+ 'aria-expanded',+ 'false',+ );+ expect(screen.getByRole('combobox')).not.toHaveAttribute('aria-controls');+ });+it('shows default emptyBootstrapText when not provided', async () => {render(<CommandPalette@@ -211,6 +244,40 @@ describe('CommandPalette', () => {});});+ it('clears a stale highlight across empty and repopulated results', async () => {+ render(+ <CommandPalette+ isOpen={true}+ onOpenChange={() => {}}+ searchSource={simpleSource}+ />,+ );+ await waitFor(() =>+ expect(screen.getByText('Settings')).toBeInTheDocument(),+ );++ const input = screen.getByRole('combobox');+ fireEvent.keyDown(input, {key: 'ArrowDown'});+ fireEvent.keyDown(input, {key: 'ArrowDown'});+ expect(input.getAttribute('aria-activedescendant')).toMatch(/-item-1$/);++ fireEvent.change(input, {target: {value: 'zzz'}});+ await waitFor(() => expect(screen.queryByRole('listbox')).toBeNull());+ expect(input).not.toHaveAttribute('aria-activedescendant');++ fireEvent.change(input, {target: {value: 'hom'}});+ await waitFor(() =>+ expect(screen.getByRole('option', {name: 'Home'})).toBeInTheDocument(),+ );+ expect(input).not.toHaveAttribute('aria-activedescendant');++ fireEvent.keyDown(input, {key: 'ArrowDown'});+ expect(input).toHaveAttribute(+ 'aria-activedescendant',+ screen.getByRole('option', {name: 'Home'}).id,+ );+ });+it('calls onOpenChange(false) when Escape is pressed', () => {const handleOpenChange = vi.fn();render(@@ -230,6 +297,46 @@ describe('CommandPalette', () => {expect(handleOpenChange).toHaveBeenCalledWith(false);});+ it('lets the topmost nested layer handle Escape before the palette', () => {+ const handleOpenChange = vi.fn();+ const handleNestedDismiss = vi.fn();+ render(+ <CommandPalette+ isOpen={true}+ onOpenChange={handleOpenChange}+ searchSource={simpleSource}+ input={+ <>+ <CommandPaletteInput />+ <NestedDismissible onDismiss={handleNestedDismiss} />+ </>+ }+ />,+ );++ fireEvent.keyDown(screen.getByRole('combobox'), {key: 'Escape'});++ expect(handleNestedDismiss).toHaveBeenCalledOnce();+ expect(handleOpenChange).not.toHaveBeenCalled();+ });++ it('preserves local Escape closing for inline previews', () => {+ const handleOpenChange = vi.fn();+ render(+ <CommandPalette+ isOpen={true}+ isInline+ onOpenChange={handleOpenChange}+ searchSource={simpleSource}+ />,+ );++ fireEvent.keyDown(screen.getByRole('combobox'), {key: 'Escape'});++ expect(handleOpenChange).toHaveBeenCalledOnce();+ expect(handleOpenChange).toHaveBeenCalledWith(false);+ });+it('keeps the empty state mounted while a no-result search is pending', async () => {// A source whose searches resolve only when we release them, so we can// observe the render output while a search transition is in flight.@@ -357,6 +464,52 @@ describe('CommandPalette', () => {expect(input).not.toHaveAttribute('aria-activedescendant');});+ it('keeps Home and End on the query field and uses Page keys for results', async () => {+ const user = userEvent.setup();+ const handleOpenChange = vi.fn();+ const handleValueChange = vi.fn();+ render(+ <CommandPalette+ isOpen={true}+ onOpenChange={handleOpenChange}+ onValueChange={handleValueChange}+ searchSource={simpleSource}+ />,+ );++ const input = screen.getByRole<HTMLInputElement>('combobox');+ await waitFor(() =>+ expect(screen.getByText('Settings')).toBeInTheDocument(),+ );+ await user.click(input);+ await user.type(input, 'e');+ await waitFor(() =>+ expect(screen.getByText('Settings')).toBeInTheDocument(),+ );+ const homeOption = screen.getByText('Home').closest('[role="option"]');+ const settingsOption = screen+ .getByText('Settings')+ .closest('[role="option"]');++ expect(input).toHaveValue('e');+ expect(input.selectionStart).toBe(1);+ await user.keyboard('{Home}');+ expect(input.selectionStart).toBe(0);+ await user.keyboard('{End}');+ expect(input.selectionStart).toBe(1);+ expect(input).not.toHaveAttribute('aria-activedescendant');++ await user.keyboard('{PageDown}');+ expect(input.getAttribute('aria-activedescendant')).toBe(+ settingsOption?.id,+ );+ await user.keyboard('{PageUp}');+ expect(input.getAttribute('aria-activedescendant')).toBe(homeOption?.id);+ await user.keyboard('{Enter}');+ expect(handleValueChange).toHaveBeenCalledWith('home');+ expect(handleOpenChange).toHaveBeenCalledWith(false);+ });+it('highlights on hover without scrolling and scrolls once per key (#6077)', async () => {// Hover must be handled by the root's delegated list handler (routed to// useCombobox's hover-aware path), and the shared useHighlightedOptionScroll effect@@ -453,19 +606,105 @@ describe('CommandPalette', () => {});});- it('announces the empty state with the query when nothing matches', async () => {+ it('announces the rendered default empty state when nothing matches', async () => {+ render(+ <CommandPalette+ isOpen={true}+ onOpenChange={() => {}}+ searchSource={simpleSource}+ />,+ );+ await waitFor(() => expect(screen.getByText('Home')).toBeInTheDocument());+ fireEvent.change(screen.getByRole('combobox'), {target: {value: 'zzz'}});+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent(/^No results$/);+ });+ });++ it('announces rich emptySearchText exactly as rendered', async () => {render(<CommandPaletteisOpen={true}onOpenChange={() => {}}searchSource={simpleSource}+ emptySearchText={+ <span>+ Nothing like that here. <a href="/commands/new">Add a command</a>+ </span>+ }/>,);await waitFor(() => expect(screen.getByText('Home')).toBeInTheDocument());fireEvent.change(screen.getByRole('combobox'), {target: {value: 'zzz'}});++ expect(+ await screen.findByRole('link', {name: 'Add a command'}),+ ).toHaveAttribute('href', '/commands/new');await waitFor(() => {- expect(politeRegion()).toHaveTextContent('No results for zzz');+ expect(politeRegion()).toHaveTextContent(+ /^Nothing like that here\. Add a command$/,+ );+ });+ });++ it('waits for a narrowed search to settle before announcing no results', async () => {+ const resolvers: ((items: SearchableItem[]) => void)[] = [];+ const source: SearchSource = {+ bootstrap: () => [+ {id: 'home', label: 'Home'},+ {id: 'settings', label: 'Settings'},+ ],+ async search(): Promise<SearchableItem[]> {+ return new Promise<SearchableItem[]>(resolve => {+ resolvers.push(resolve);+ });+ },+ };+ const spoken: string[] = [];+ const observer = new MutationObserver(() => {+ const text = politeRegion()?.textContent ?? '';+ if (text !== '' && spoken.at(-1) !== text) {+ spoken.push(text);+ }+ });+ observer.observe(document.body, {+ childList: true,+ subtree: true,+ characterData: true,});+ try {+ render(+ <CommandPalette+ isOpen={true}+ onOpenChange={() => {}}+ searchSource={source}+ />,+ );+ await waitFor(() =>+ expect(screen.getByText('Home')).toBeInTheDocument(),+ );+ const input = screen.getByRole('combobox');++ fireEvent.change(input, {target: {value: 'e'}});+ await act(async () =>+ resolvers.shift()?.(source.bootstrap() as SearchableItem[]),+ );+ await waitFor(() => expect(spoken.at(-1)).toBe('2 results'));++ // Optimistic narrowing empties the list while the source is still+ // answering; the source then finds one match.+ fireEvent.change(input, {target: {value: 'ez'}});+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 50));+ });+ await act(async () =>+ resolvers.shift()?.([{id: 'settings', label: 'Settings'}]),+ );+ await waitFor(() => expect(spoken.at(-1)).toBe('1 result'));+ expect(spoken).not.toContain('No results');+ } finally {+ observer.disconnect();+ }});it('announces loading politely while a search is in flight', async () => {diff --git a/packages/core/src/CommandPalette/CommandPalette.tsx b/packages/core/src/CommandPalette/CommandPalette.tsxindex 9053af0386..c586a76146 100644--- a/packages/core/src/CommandPalette/CommandPalette.tsx+++ b/packages/core/src/CommandPalette/CommandPalette.tsx@@ -3,7 +3,8 @@'use client';/*** @file CommandPalette.tsx- * @input Uses React, Dialog, Layout, CommandPaletteContext, SearchSource, useCombobox, useAnnounce+ * @input Uses React, Dialog, Layout, CommandPaletteContext, SearchSource,+ * useCombobox, useAnnounce, useAnnounceRenderedText* @output Exports CommandPalette root component and props* @position Core root component; dialog shell with searchSource-driven items*@@ -37,6 +38,7 @@ import {CommandPaletteFooter} from './CommandPaletteFooter';import {CommandPaletteEmpty} from './CommandPaletteEmpty';import type {BaseProps} from '../BaseProps';import {useAnnounce} from '../hooks/useAnnounce';+import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';import {useTranslator} from '../i18n';export interface CommandPaletteProps<@@ -255,9 +257,10 @@ function ItemRenderer<T extends SearchableItem>({* Uses `searchSource` for all search logic — same interface as Typeahead.* For static lists, use `createStaticSource` from `@astryxdesign/core/Typeahead`.*- * Keyboard navigation is handled by `useCombobox` from Selector,- * ensuring consistent arrow key, Home/End, Enter, and Escape behavior- * across all combobox-pattern components.+ * Keyboard navigation is handled by `useCombobox` from Selector for arrows,+ * PageUp/PageDown, and Enter. Home/End remain native caret keys. Modal Escape+ * dismissal delegates to Dialog's shared layer stack so nested surfaces handle+ * the first press.** Input and footer are rendered by default — only pass them to replace the defaults.*@@ -313,6 +316,7 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({useOptimistic(searchResults);const isBusy = isPending;const searchVersionRef = useRef(0);+ const emptyStateRef = useRef<HTMLDivElement>(null);// Announce search status to screen readers through the shared polite live// region (comboboxes-7 announce path, mirroring Selector / BaseTypeahead).@@ -395,6 +399,10 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({(query: string) => {searchSource.cancel?.();const version = ++searchVersionRef.current;+ // A highlight belongs to the query that created it. Clear it before any+ // optimistic narrowing so aria-activedescendant never shifts to a+ // different command at the same index while the next result set loads.+ combobox.setHighlightedIndex(-1);startTransition(async () => {const isBootstrap = query === '';@@ -431,16 +439,12 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({// Announce the outcome from the search commit (not a reactive// effect), matching Selector / BaseTypeahead: exactly one- // announcement per committed query, and the version check above- // already discards stale keystrokes. Bootstrap stays silent — the- // same role PowerSearch's mount guard plays — so opening the- // palette announces nothing; clearing the query only clears any- // lingering status text.+ // announcement per committed non-empty query. Empty results are+ // announced from their rendered content below so a caller-supplied+ // ReactNode reaches assistive technology as written.if (isBootstrap) {announce('');- } else if (items.length === 0) {- announce(t('@astryx.commandPalette.noResultsFor', {query}));- } else {+ } else if (items.length > 0) {announce(t('@astryx.commandPalette.resultCount', {count: items.length}),);@@ -496,14 +500,19 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({}}, [isOpen]);- // Wrap combobox's onKeyDown to intercept Escape (close palette) and- // Enter on highlight (select + close), since we're not using combobox's- // built-in open/close lifecycle.+ // Wrap combobox's onKeyDown to preserve inline-preview Escape handling and+ // select + close on Enter. Modal Escape stays unclaimed here so Dialog's+ // shared dismissal stack can route it to the topmost surface.const handleKeyDown = useCallback((e: React.KeyboardEvent) => {if (e.key === 'Escape') {- e.preventDefault();- handleClose();+ // Modal CommandPalette delegates Escape to Dialog's shared dismissal+ // stack so a nested layer handles the first press. Inline previews do+ // not join that stack, so preserve their local close behavior.+ if (isInline) {+ e.preventDefault();+ handleClose();+ }return;}if (e.key === 'Enter') {@@ -520,13 +529,18 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({}return;}+ // Home and End remain native caret-movement keys for this editable+ // combobox. PageUp/PageDown provide first/last result navigation.+ if (e.key === 'Home' || e.key === 'End') {+ return;+ }// Space should type in the input, not trigger selectionif (e.key === ' ') {return;}combobox.onKeyDown(e);},- [combobox, handleClose, selectableItems, selectItem],+ [combobox, handleClose, isInline, selectableItems, selectItem],);// Hover highlight is owned here by a single delegated handler on the list@@ -607,14 +621,24 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({// the empty state is never unmounted and re-added mid-search (which flashed).const showEmptyBootstrap = search === '' && optimisticResults.length === 0;const showEmptySearch = search !== '' && optimisticResults.length === 0;+ // Announce only once the search settles: while it is pending, optimistic+ // narrowing can empty the list before the source answers, which would+ // speak "No results" early or wrongly.+ useAnnounceRenderedText(emptyStateRef, showEmptySearch && !isPending, search);let listContent: ReactNode;if (showEmptyBootstrap) {listContent = (- <CommandPaletteEmpty>{emptyBootstrapText}</CommandPaletteEmpty>+ <CommandPaletteEmpty ref={emptyStateRef}>+ {emptyBootstrapText}+ </CommandPaletteEmpty>);} else if (showEmptySearch) {- listContent = <CommandPaletteEmpty>{emptySearchText}</CommandPaletteEmpty>;+ listContent = (+ <CommandPaletteEmpty ref={emptyStateRef}>+ {emptySearchText}+ </CommandPaletteEmpty>+ );} else {listContent = (<ItemRendererdiff --git a/packages/core/src/CommandPalette/CommandPaletteEmpty.tsx b/packages/core/src/CommandPalette/CommandPaletteEmpty.tsxindex 1904c0b880..b5022c2d9a 100644--- a/packages/core/src/CommandPalette/CommandPaletteEmpty.tsx+++ b/packages/core/src/CommandPalette/CommandPaletteEmpty.tsx@@ -52,13 +52,14 @@ export interface CommandPaletteEmptyProps extends BaseProps<HTMLDivElement> {* - `emptyBootstrapText`: no search term and bootstrap() returns nothing* - `emptySearchText`: a search query returned no results*- * Can also be composed manually inside a custom render function.+ * Can also be composed as a standalone empty result surface. Render actionable+ * empty content outside listbox and option semantics.** @example* ```* <CommandPalette- * emptyBootstrapText={<CommandPaletteEmpty>Start typing to search</CommandPaletteEmpty>}- * emptySearchText={<CommandPaletteEmpty>No results found</CommandPaletteEmpty>}+ * emptyBootstrapText="Start typing to search"+ * emptySearchText="No results found"* searchSource={source}* />* ```diff --git a/packages/core/src/CommandPalette/CommandPaletteInput.spec.md b/packages/core/src/CommandPalette/CommandPaletteInput.spec.mdindex 21c6bed169..341523bd29 100644--- a/packages/core/src/CommandPalette/CommandPaletteInput.spec.md+++ b/packages/core/src/CommandPalette/CommandPaletteInput.spec.md@@ -99,7 +99,7 @@ Consumer migration instructions belong in consumer docs and release notes.| 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 |+| FR2 | Consumer `onKeyDown` runs before contextual navigation; preventing the event, or an active IME composition, 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 |@@ -118,6 +118,7 @@ Consumer migration instructions belong in consumer docs and release notes.| 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, no results | Named combobox reports collapsed state and references no list. | Empty or pending message. || 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. |@@ -127,8 +128,8 @@ Consumer migration instructions belong in consumer docs and release notes.- **ORD1 — Search state.** Explicit props → CommandPalette context → nativeuncontrolled state.-- **ORD2 — Keyboard handling.** Consumer handler → default-prevented check →- CommandPalette context handler.+- **ORD2 — Keyboard handling.** Consumer handler → default-prevented or+ IME-composition check → CommandPalette context handler.- **ORD3 — Accessible name.** Native `aria-label` → `label` → the translateddefault "Search commands" (DEC-1). Placeholder text is never the name.@@ -147,7 +148,9 @@ Consumer migration instructions belong in consumer docs and release notes.own popup relationships retain those semantics. CommandPalette context exposesa `combobox` with context-owned expanded state, list relationship, autocompletemode, and active descendant, following `spec:AST-020/FR1,FR2` and the WAI-ARIA- combobox pattern.+ combobox pattern. While the palette holds no selectable result, the field+ reports collapsed state and has no list relationship or active descendant, and+ an active descendant always names an existing option.- **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;diff --git a/packages/core/src/CommandPalette/CommandPaletteInput.test.tsx b/packages/core/src/CommandPalette/CommandPaletteInput.test.tsxindex a0bad3fbd9..2cdd74d4a4 100644--- a/packages/core/src/CommandPalette/CommandPaletteInput.test.tsx+++ b/packages/core/src/CommandPalette/CommandPaletteInput.test.tsx@@ -27,7 +27,7 @@ function makeContext(highlightedIndex: -1,setHighlightedIndex: vi.fn(),getItemId: (i: number) => `item-${i}`,- selectableItems: [],+ selectableItems: [{value: 'open', label: 'Open'}],searchResults: [],selectItem: vi.fn(),onKeyDown: vi.fn(),@@ -44,6 +44,18 @@ describe('CommandPaletteInput', () => {expect(screen.getByPlaceholderText('Search…')).toBeInTheDocument();});+ it('renders the local input target and delegated search icon', () => {+ const {container} = render(<CommandPaletteInput />);++ expect(container.firstElementChild).toHaveClass(+ 'astryx-command-palette-input',+ );+ expect(container.querySelector('.astryx-icon')).toHaveAttribute(+ 'aria-hidden',+ 'true',+ );+ });+it('renders with custom placeholder', () => {render(<CommandPaletteInput placeholder="Type a command..." />);expect(@@ -340,7 +352,11 @@ describe('CommandPaletteInput popup context', () => {it('exposes the highlighted option as the active descendant', () => {render(- <CommandPaletteContext value={makeContext({highlightedIndex: 2})}>+ <CommandPaletteContext+ value={makeContext({+ highlightedIndex: 2,+ selectableItems: [{value: 'a'}, {value: 'b'}, {value: 'c'}],+ })}><CommandPaletteInput /></CommandPaletteContext>,);@@ -394,6 +410,51 @@ describe('CommandPaletteInput popup context', () => {expect(onKeyDown).not.toHaveBeenCalled();});+ it('omits popup ARIA while the result surface has no listbox', () => {+ render(+ <CommandPaletteContext value={makeContext({selectableItems: []})}>+ <CommandPaletteInput />+ </CommandPaletteContext>,+ );++ const input = screen.getByRole('combobox');+ expect(input).toHaveAttribute('aria-expanded', 'false');+ expect(input).not.toHaveAttribute('aria-controls');+ expect(input).not.toHaveAttribute('aria-activedescendant');+ });++ it('omits an active descendant whose highlighted index has no option', () => {+ render(+ <CommandPaletteContext+ value={makeContext({+ highlightedIndex: 1,+ selectableItems: [{value: 'home'}],+ })}>+ <CommandPaletteInput />+ </CommandPaletteContext>,+ );++ expect(screen.getByRole('combobox')).not.toHaveAttribute(+ 'aria-activedescendant',+ );+ });++ it('does not route IME composition keys to palette commands', () => {+ const onKeyDown = vi.fn();+ render(+ <CommandPaletteContext value={makeContext({onKeyDown})}>+ <CommandPaletteInput />+ </CommandPaletteContext>,+ );++ fireEvent.keyDown(screen.getByRole('combobox'), {+ key: 'Enter',+ isComposing: true,+ });++ expect(onKeyDown).not.toHaveBeenCalled();+ });+it('does not auto-focus inside an inline dialog', async () => {const focusSpy = vi.spyOn(HTMLElement.prototype, 'focus');render(diff --git a/packages/core/src/CommandPalette/CommandPaletteInput.tsx b/packages/core/src/CommandPalette/CommandPaletteInput.tsxindex 30ae779737..6ab4a5beb6 100644--- a/packages/core/src/CommandPalette/CommandPaletteInput.tsx+++ b/packages/core/src/CommandPalette/CommandPaletteInput.tsx@@ -17,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 {isRenderable, mergeProps} from '../utils';+import {isImeKeyEvent, isRenderable, mergeProps} from '../utils';import {colorVars,typeScaleVars,@@ -179,6 +179,9 @@ export function CommandPaletteInput({const placeholder =placeholderFromProps ?? t('@astryx.commandPalette.input.placeholder');const ctx = useCommandPaletteContext();+ // Inside CommandPalette the results surface is a listbox only while it holds+ // selectable results; empty and pending states expose no popup.+ const hasListbox = ctx ? ctx.selectableItems.length > 0 : true;const dialogContext = useDialogContext();const inputRef = useRef<HTMLInputElement>(null);@@ -230,7 +233,10 @@ export function CommandPaletteInput({const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {onKeyDown?.(e);- if (e.defaultPrevented) {+ if (e.defaultPrevented || isImeKeyEvent(e.nativeEvent)) {+ // An in-progress IME composition owns Enter, Escape, and arrows. Let+ // the input method finish or cancel composition without selecting or+ // dismissing palette content.return;}// Delegate to useCombobox's keyboard handler from context@@ -258,7 +264,7 @@ export function CommandPaletteInput({role={ctx ? 'combobox' : standaloneRole}aria-expanded={ctx- ? ctx.isOpen+ ? ctx.isOpen && hasListbox: callerSets('aria-expanded')? props['aria-expanded']: callerOwnsPopup || undefined@@ -272,10 +278,14 @@ export function CommandPaletteInput({? 'list': undefined}- aria-controls={ctx ? ctx.listId : props['aria-controls']}+ aria-controls={+ ctx ? (hasListbox ? ctx.listId : undefined) : props['aria-controls']+ }aria-activedescendant={ctx- ? ctx.highlightedIndex >= 0+ ? hasListbox &&+ ctx.highlightedIndex >= 0 &&+ ctx.highlightedIndex < ctx.selectableItems.length? ctx.getItemId(ctx.highlightedIndex): undefined: props['aria-activedescendant']diff --git a/packages/core/src/CommandPalette/CommandPaletteItem.test.tsx b/packages/core/src/CommandPalette/CommandPaletteItem.test.tsxindex dfc60dcd80..cba4cf64b7 100644--- a/packages/core/src/CommandPalette/CommandPaletteItem.test.tsx+++ b/packages/core/src/CommandPalette/CommandPaletteItem.test.tsx@@ -88,6 +88,13 @@ describe('CommandPaletteItem', () => {expect(screen.getByRole('option')).toBeInTheDocument();});+ it('carries the stable item theme target', () => {+ render(<CommandPaletteItem value="test">Item</CommandPaletteItem>);+ expect(screen.getByRole('option')).toHaveClass(+ 'astryx-command-palette-item',+ );+ });+it('calls onSelect when clicked', () => {const handleSelect = vi.fn();render(diff --git a/packages/core/src/CommandPalette/CommandPaletteList.doc.mjs b/packages/core/src/CommandPalette/CommandPaletteList.doc.mjsindex 13984247b5..5b881582b2 100644--- a/packages/core/src/CommandPalette/CommandPaletteList.doc.mjs+++ b/packages/core/src/CommandPalette/CommandPaletteList.doc.mjs@@ -7,7 +7,7 @@ export const docs = {subComponentOf: 'CommandPalette',displayName: 'Command Palette List',isHiddenFromOverview: true,- description: 'Scrollable results container. Renders as a listbox for ARIA. Contains CommandPaletteItem and CommandPaletteGroup children.',+ description: 'Scrollable results container. Renders as a listbox standalone, and inside CommandPalette while selectable results exist. Contains CommandPaletteItem and CommandPaletteGroup children.',props: [{name: 'children',@@ -42,7 +42,7 @@ export const docsZh = {name: 'CommandPaletteList',isHiddenFromOverview: true,displayName: 'Command Palette List',- description: '可滚动的结果容器。作为 listbox 渲染以符合 ARIA 规范。',+ description: '可滚动的结果容器。独立使用时,以及在 CommandPalette 中存在可选结果时,作为 listbox 渲染。',propDescriptions: {children: '条目、分组和空状态。',label: 'listbox 的无障碍标签。',@@ -54,7 +54,7 @@ export const docsDense = {name: 'CommandPaletteList',isHiddenFromOverview: true,displayName: 'Command Palette List',- description: 'scrollable results container; role=listbox',+ description: 'scrollable results container; role=listbox standalone, and in CommandPalette only while results exist',propDescriptions: {children: 'items, groups, empty states',label: 'a11y label for listbox',diff --git a/packages/core/src/CommandPalette/CommandPaletteList.spec.md b/packages/core/src/CommandPalette/CommandPaletteList.spec.mdindex 5a04244d3a..1e6920770a 100644--- a/packages/core/src/CommandPalette/CommandPaletteList.spec.md+++ b/packages/core/src/CommandPalette/CommandPaletteList.spec.md@@ -36,15 +36,15 @@ system_specs: []## Contract at a glance-| Area | Contract |-| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Public contract | None changes. One named listbox container for result options, rendered by CommandPalette or directly for a standalone results list. |-| Behavior | The root is a `listbox` named by `label` or the translated default; inside CommandPalette it carries the context list id that the query field controls. |-| End-user impact | Screen-reader users reach a named results list from the query field; overflowing results scroll inside the list instead of growing the palette. |-| Builder impact | None. CommandPalette renders its own list; standalone compositions render items and groups directly inside this one. |-| Compatibility/readiness | Observational draft with no runtime change. A standalone caller `id` is overwritten (FR1), an empty list keeps the listbox role (AR4), and the standalone keyboard model remains OQ1. |-| Review checks | Reject a second list-id owner, a role or name that consumer props can replace, dropped native or styling inputs, or a list target moved off the scrolling root. |-| Governing rules | `architecture:public-component-api/INV5,INV6,INV8`; `architecture:component-theming-surface`; WAI-ARIA 1.2 `listbox`. |+| Area | Contract |+| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | None changes. One named listbox container for result options, rendered by CommandPalette or directly for a standalone results list. |+| Behavior | The root is a `listbox` named by `label` or the translated default; inside CommandPalette it is one only while selectable results exist, and carries the context list id the query field controls. |+| End-user impact | Screen-reader users reach a named results list from the query field; overflowing results scroll inside the list instead of growing the palette. |+| Builder impact | None. CommandPalette renders its own list; standalone compositions render items and groups directly inside this one. |+| Compatibility/readiness | Draft. Inside CommandPalette an empty or pending result surface drops the listbox role and name (AR4, an accessibility fix); a standalone caller `id` is kept (FR1); the standalone keyboard model remains OQ1. |+| Review checks | Reject a second list-id owner, a role or name that consumer props can replace, dropped native or styling inputs, or a list target moved off the scrolling root. |+| Governing rules | `architecture:public-component-api/INV5,INV6,INV8`; `architecture:component-theming-surface`; WAI-ARIA 1.2 `listbox`. |This table is a review projection; the body below is authoritative.@@ -56,9 +56,10 @@ presents a named results listbox around caller-provided option content.## Compatibility and migration-- Released default preserved: `yes`-- Compatibility class: observational record only; runtime, DOM, styling, target,- and public API are unchanged+- Released default preserved: `yes`, except inside CommandPalette while no+ selectable result exists, where the root no longer exposes an empty listbox+- Compatibility class: accessibility behavior fix (`spec:AST-017/FR53`); styling,+ target, and public API are unchanged- Controlled/uncontrolled behavior: not applicable; the list holds no state- Migration decision: none@@ -69,7 +70,8 @@ Consumer migration instructions belong in consumer docs and release notes.**Owns**- The listbox root and its accessible name from `label`, falling back to the- translated default.+ translated default, and dropping both inside CommandPalette while no selectable+ result exists.- Applying the CommandPalette context list id to the root.- Native passthrough, `ref`, and styling-input composition on the root.- Block-axis scrolling of overflowing children, with spacing-scale padding and@@ -91,31 +93,32 @@ Consumer migration instructions belong in consumer docs and release notes.| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior || --------------- | ---------------------------------- | ------------------------------------------------- | ----------------------------------------- | ----------------------------------------------------------- | ------------------------------ | --------- | ------------------------------------------------------------------------ || Accessible name | caller `label`; translated default | Name announced for the results listbox. | All uses | `@astryx.commandPalette.list.label` ("Commands" in English) | `component:CommandPaletteList` | Stable | An empty `label` leaves the listbox unnamed; callers supply a real name. |-| List identity | context list id; absent | DOM id the CommandPalette query field references. | Inside CommandPalette; standalone | Context id inside CommandPalette; absent standalone | `component:CommandPalette` | Stable | A standalone caller `id` is overwritten (FR1 gap). |+| List identity | context list id; caller `id` | DOM id the CommandPalette query field references. | Inside CommandPalette; standalone | Context id inside CommandPalette; caller `id` standalone | `component:CommandPalette` | Stable | Inside CommandPalette a caller `id` is replaced by the context id. |## Behavioral and layout contract-| ID | Candidate invariant | Basis | Draft review state |-| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |-| FR1 | Native props and `ref` reach the listbox root, and consumer `className` and `style` combine with the list target and base styles. Inside CommandPalette the root id is the context list id; standalone, an absent id replaces a caller `id`. | Released source; `architecture:public-component-api/INV5,INV6,INV8` | Ref and styling verified by focused tests; the standalone `id` conflicts with INV5 |-| FR2 | The root exposes `role=listbox` with an accessible name from `label`, falling back to the translated default; consumer `role` and `aria-label` props do not replace them. | Released source and docs; WAI-ARIA 1.2 `listbox` | Role and name verified by focused tests; consumer-prop precedence is source-verified; the role also applies with no option (AR4) |-| FR3 | Inside CommandPalette, the query field's `aria-controls` names the listbox id. | Released source and component docs | Verified by a focused composition test |-| FR4 | The root lays out children in one column with spacing-scale padding and gaps, grows within a flex parent, caps its height at the parent's height, and scrolls overflowing children inside itself. | Released source and component docs | Source-verified; the scrolling fixture renders it in a browser, but scroll geometry is not yet measured |+| ID | Candidate invariant | Basis | Draft review state |+| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |+| FR1 | Native props and `ref` reach the listbox root, and consumer `className` and `style` combine with the list target and base styles. Inside CommandPalette the root id is the context list id; standalone, a caller `id` is kept. | Released source; `architecture:public-component-api/INV5,INV6,INV8` | Ref, styling, and the standalone `id` verified by focused tests |+| FR2 | Standalone, and inside CommandPalette while at least one selectable result exists, the root exposes `role=listbox` with an accessible name from `label`, falling back to the translated default; consumer `role` and `aria-label` props do not replace them. Otherwise AR4 applies. | Released source and docs; WAI-ARIA 1.2 `listbox` | Role and name verified by focused tests, with and without palette results; consumer-prop precedence is source-verified |+| FR3 | Inside CommandPalette, the query field's `aria-controls` names the listbox id. | Released source and component docs | Verified by a focused composition test |+| FR4 | The root lays out children in one column with spacing-scale padding and gaps, grows within a flex parent, caps its height at the parent's height, and scrolls overflowing children inside itself. | Released source and component docs | Source-verified; the scrolling fixture renders it in a browser, but scroll geometry is not yet measured |### Allowed variation- **AV1 — Children.** Items, groups, and empty states may vary in count, order,- and content without changing the listbox root.+ and content without changing the root, except as AR4 states.- **AV2 — Layout.** Consumer `xstyle`, class, and style may adjust the rootwithout replacing its role, name, id, or target.### Representative states-| State | Required invariant | Allowed variation |-| --------------------- | --------------------------------------------------------------------- | -------------------------- |-| Standalone results | The listbox is named by `label` or the translated default. | Item count and grouping. |-| Inside CommandPalette | The root id equals the query field's `aria-controls` value. | Results count and groups. |-| Overflowing results | Results scroll inside the list instead of growing past the container. | Container and item height. |+| State | Required invariant | Allowed variation |+| --------------------- | ------------------------------------------------------------------------------ | -------------------------- |+| Standalone results | The listbox is named by `label` or the translated default. | Item count and grouping. |+| Inside CommandPalette | The root id equals the query field's `aria-controls` value. | Results count and groups. |+| Overflowing results | Results scroll inside the list instead of growing past the container. | Container and item height. |+| Empty palette results | Inside CommandPalette with no selectable result, the root has no role or name. | Empty or pending message. |### Transformation and precedence order@@ -139,9 +142,11 @@ Consumer migration instructions belong in consumer docs and release notes.- **AR3 — Standalone gap.** A standalone list exposes a listbox of options withno owning keyboard model. OQ1 must settle that contract before runtimesemantics change.-- **AR4 — Empty content.** The root keeps `role=listbox` when its children contain- no option, as in CommandPalette's empty states. WAI-ARIA 1.2 requires a listbox- to own options, so this is an open conflict, not a contract.+- **AR4 — Empty content.** Inside CommandPalette, while no selectable result+ exists, the root has no role and no accessible name, so screen readers meet the+ empty or pending message as plain content and no empty popup; WAI-ARIA 1.2+ requires a listbox to own options. A standalone list stays a listbox, and its+ caller supplies the options.## Design relationships@@ -163,17 +168,17 @@ Consumer migration instructions belong in consumer docs and release notes.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| -------- | --------------------------------------------------------------------------------------- | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------- | ---------------------------------- |-| FR1 | `CommandPaletteList.test.tsx` | standalone root with ref, class, and style | Disconnecting `ref`, or dropping the consumer class or the list target, fails focused DOM assertions. | `audit:CommandPaletteList/api` |-| FR2, AR1 | `CommandPaletteList.test.tsx` | default and caller label | Removing the role or name fails the role and name assertions. | `audit:CommandPaletteList/a11y` |-| FR3, AR2 | `CommandPaletteList.test.tsx`, `CommandPalette.test.tsx` | inline CommandPalette | Dropping the context id breaks the query-field relationship assertion. | `audit:CommandPaletteList/a11y` |-| FR4 | Storybook fixtures, `themingTargets.test.ts`, exact-head accessibility and RTL evidence | standalone list; scrolling palette | Losing the target fails the target inventory; any new directional behavior requires a non-empty RTL dimension. | `audit:CommandPaletteList/theming` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------- | --------------------------------------------------------------------------------------- | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ---------------------------------- |+| FR1 | `CommandPaletteList.test.tsx` | standalone root with ref, class, and style | Disconnecting `ref`, or dropping the consumer class or the list target, fails focused DOM assertions. | `audit:CommandPaletteList/api` |+| FR2, AR1, AR4 | `CommandPaletteList.test.tsx` | default and caller label; palette with and without results | Removing the role or name, or keeping them on an empty palette surface, fails the role and name assertions. | `audit:CommandPaletteList/a11y` |+| FR3, AR2 | `CommandPaletteList.test.tsx`, `CommandPalette.test.tsx` | inline CommandPalette | Dropping the context id breaks the query-field relationship assertion. | `audit:CommandPaletteList/a11y` |+| FR4 | Storybook fixtures, `themingTargets.test.ts`, exact-head accessibility and RTL evidence | standalone list; scrolling palette | Losing the target fails the target inventory; any new directional behavior requires a non-empty RTL dimension. | `audit:CommandPaletteList/theming` |## Decision logNone. This draft records current facts and settles no component-local API,-keyboard, or visual decision.+keyboard, or visual decision; AR4 applies the WAI-ARIA 1.2 listbox rule.## Open questionsdiff --git a/packages/core/src/CommandPalette/CommandPaletteList.test.tsx b/packages/core/src/CommandPalette/CommandPaletteList.test.tsxindex cf0ffc161b..cfc96ef712 100644--- a/packages/core/src/CommandPalette/CommandPaletteList.test.tsx+++ b/packages/core/src/CommandPalette/CommandPaletteList.test.tsx@@ -11,8 +11,35 @@ import {createRef} from 'react';import {render, screen} from '@testing-library/react';import {createStaticSource} from '@astryxdesign/core/Typeahead';import {CommandPalette} from './CommandPalette';+import {+ CommandPaletteContext,+ type CommandPaletteContextValue,+} from './CommandPaletteContext';import {CommandPaletteList} from './CommandPaletteList';+function makeContext(+ overrides: Partial<CommandPaletteContextValue> = {},+): CommandPaletteContextValue {+ return {+ search: '',+ setSearch: () => {},+ value: '',+ setValue: () => {},+ listId: 'command-list',+ highlightedIndex: -1,+ setHighlightedIndex: () => {},+ getItemId: index => `command-item-${index}`,+ selectableItems: [],+ searchResults: [],+ selectItem: () => {},+ onKeyDown: () => {},+ onClose: () => {},+ isOpen: true,+ isBusy: false,+ ...overrides,+ };+}+describe('CommandPaletteList', () => {it('renders children', () => {render(@@ -34,6 +61,17 @@ describe('CommandPaletteList', () => {expect(screen.getByRole('listbox')).toBeInTheDocument();});+ it('carries the stable list theme target', () => {+ render(+ <CommandPaletteList>+ <div>Item</div>+ </CommandPaletteList>,+ );+ expect(screen.getByRole('listbox')).toHaveClass(+ 'astryx-command-palette-list',+ );+ });+it('preserves the consumer id when used standalone', () => {render(<CommandPaletteList id="custom-commands">@@ -47,6 +85,35 @@ describe('CommandPaletteList', () => {);});+ it('inside a palette, is a listbox only while it holds selectable results', () => {+ const {rerender} = render(+ <CommandPaletteContext value={makeContext()}>+ <CommandPaletteList>+ <div>No results</div>+ </CommandPaletteList>+ </CommandPaletteContext>,+ );+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();+ expect(screen.getByText('No results').parentElement).not.toHaveAttribute(+ 'aria-label',+ );++ rerender(+ <CommandPaletteContext+ value={makeContext({+ selectableItems: [{value: 'open', label: 'Open'}],+ })}>+ <CommandPaletteList>+ <div>Open</div>+ </CommandPaletteList>+ </CommandPaletteContext>,+ );+ expect(screen.getByRole('listbox', {name: 'Commands'})).toHaveAttribute(+ 'id',+ 'command-list',+ );+ });+it('has default aria-label', () => {render(<CommandPaletteList>diff --git a/packages/core/src/CommandPalette/CommandPaletteList.tsx b/packages/core/src/CommandPalette/CommandPaletteList.tsxindex 1e2061daf9..be3ba74c75 100644--- a/packages/core/src/CommandPalette/CommandPaletteList.tsx+++ b/packages/core/src/CommandPalette/CommandPaletteList.tsx@@ -53,8 +53,10 @@ export interface CommandPaletteListProps extends BaseProps<HTMLDivElement> {}/**- * Scrollable results container for the command palette.- * Renders as a listbox for ARIA compliance.+ * Scrollable results container for the command palette. Standalone composition+ * renders as a listbox. Inside CommandPalette, listbox semantics are present+ * only while selectable results exist; empty and pending states retain the same+ * styled container without exposing an empty interactive popup.** When used inside CommandPalette, automatically gets the correct* ID for aria-controls linking with the input.@@ -84,14 +86,17 @@ export function CommandPaletteList({const t = useTranslator();const label = labelFromProps ?? t('@astryx.commandPalette.list.label');const ctx = useCommandPaletteContext();+ // Inside CommandPalette the list is a listbox only while it holds selectable+ // results; standalone composition is always a listbox.+ const hasListbox = ctx ? ctx.selectableItems.length > 0 : true;return (<divref={ref}{...props}id={ctx?.listId ?? props.id}- role="listbox"- aria-label={label}+ role={hasListbox ? 'listbox' : undefined}+ aria-label={hasListbox ? label : undefined}{...mergeProps(themeProps('command-palette-list'),stylex.props(styles.list, xstyle),diff --git a/packages/core/src/CommandPalette/__tests__/CommandPalette.a11y.chromium.spec.ts b/packages/core/src/CommandPalette/__tests__/CommandPalette.a11y.chromium.spec.tsnew file mode 100644index 0000000000..6dfddd6bd5--- /dev/null+++ b/packages/core/src/CommandPalette/__tests__/CommandPalette.a11y.chromium.spec.ts@@ -0,0 +1,599 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CommandPalette.a11y.chromium.spec.ts+ * @input Uses the component-owned Storybook fixture and exact-head build stamp+ * @output Chromium screenshots and fail-closed semantic sensor receipts+ * @position Browser evidence for the CommandPalette audit+ */++import {createHash} from 'node:crypto';+import {execFileSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {expect, test, type Page} from '@playwright/test';+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++const OUTPUT = path.resolve('test-results/command-palette-audit-evidence');+const STORY_ID = 'core-commandpalette--audit-matrix';+const WIDE = {width: 1024, height: 900};+const NARROW = {width: 320, height: 900};++interface Case {+ state: string;+ mode: 'light' | 'dark';+ direction: 'ltr' | 'rtl';+ viewport: {width: number; height: number};+}++const CASES: Case[] = [+ {state: 'wide-light-ltr', mode: 'light', direction: 'ltr', viewport: WIDE},+ {state: 'wide-dark-ltr', mode: 'dark', direction: 'ltr', viewport: WIDE},+ {state: 'wide-light-rtl', mode: 'light', direction: 'rtl', viewport: WIDE},+ {state: 'wide-dark-rtl', mode: 'dark', direction: 'rtl', viewport: WIDE},+ {+ state: 'narrow-light',+ mode: 'light',+ direction: 'ltr',+ viewport: NARROW,+ },+ {+ state: 'narrow-dark',+ mode: 'dark',+ direction: 'ltr',+ viewport: NARROW,+ },+];++const frames: Record<string, unknown>[] = [];+const stateVisualMatrix: Record<string, unknown>[] = [];+const contrastPairMatrix: Record<string, unknown>[] = [];+let storybook: StaticServer;+let checkoutSha: string;+let storybookSha: string;+let browserVersion = 'unknown';++test.beforeAll(async () => {+ checkoutSha = execFileSync('git', ['rev-parse', 'HEAD'], {+ encoding: 'utf8',+ }).trim();+ const expectedHead = process.env.ASTRYX_HEAD_SHA;+ if (expectedHead && expectedHead !== checkoutSha) {+ throw new Error('The audited checkout does not match the PR head');+ }+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+ const stamp = await fetch(`${storybook.origin}/astryx-build-sha.txt`);+ if (!stamp.ok) {+ throw new Error(+ `The Storybook build has no source stamp (${stamp.status})`,+ );+ }+ storybookSha = (await stamp.text()).trim();+ if (storybookSha !== checkoutSha) {+ throw new Error(+ 'The served Storybook build does not match the audited checkout',+ );+ }+ fs.mkdirSync(OUTPUT, {recursive: true});+});++test.afterAll(async () => {+ if (checkoutSha && storybookSha) {+ fs.writeFileSync(+ path.join(OUTPUT, 'manifest.json'),+ `${JSON.stringify(+ {+ version: 1,+ component: 'core/CommandPalette',+ headSha: checkoutSha,+ storybookSha,+ browser: browserVersion,+ frames,+ stateVisualMatrix,+ contrastPairMatrix,+ },+ null,+ 2,+ )}\n`,+ );+ }+ await storybook?.close();+});++async function capture(page: Page, scenario: Case) {+ const errors: string[] = [];+ const onPageError = (error: Error) =>+ errors.push(`pageerror: ${String(error)}`);+ const onConsole = (message: {type(): string; text(): string}) => {+ if (message.type() === 'error') {+ errors.push(`console: ${message.text()}`);+ }+ };+ page.on('pageerror', onPageError);+ page.on('console', onConsole);++ try {+ await page.setViewportSize(scenario.viewport);+ await page.emulateMedia({reducedMotion: 'reduce'});+ browserVersion = page.context().browser()?.version() ?? 'unknown';+ await page.goto(+ `${storybook.origin}/iframe.html?id=${STORY_ID}&viewMode=story&globals=colorMode:${scenario.mode};astryxTheme:neutral;direction:${scenario.direction}`,+ );++ const canvas = page.locator('#storybook-root');+ const subject = canvas.locator('[data-command-palette-audit-matrix]');+ await subject.waitFor();+ await expect(subject.locator('[role="region"]')).toHaveCount(3);+ await expect(+ subject+ .getByRole('region', {name: 'Pending command palette'})+ .locator('.astryx-spinner[role="status"]'),+ ).toHaveCount(1);+ await page.waitForTimeout(200);+ await holdMotionStill(page);+ await page.evaluate(async () => document.fonts.ready);+ await page.waitForFunction(+ expected =>+ document.documentElement.getAttribute('data-theme') === expected,+ scenario.mode,+ );+ await page.waitForFunction(+ expected =>+ document.querySelector('#storybook-root [dir]')?.getAttribute('dir') ===+ expected,+ scenario.direction,+ );+ await subject.scrollIntoViewIfNeeded();+ await page.evaluate(async () => {+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ );+ });++ const initialBox = await subject.boundingBox();+ if (initialBox == null) {+ throw new Error(`${scenario.state}: the audit matrix has no layout box`);+ }+ await page.evaluate(async () => {+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ );+ });+ const settledBox = await subject.boundingBox();+ if (settledBox == null) {+ throw new Error(+ `${scenario.state}: the audit matrix lost its layout box before capture`,+ );+ }+ const geometryDelta = Math.max(+ Math.abs(settledBox.x - initialBox.x),+ Math.abs(settledBox.y - initialBox.y),+ Math.abs(settledBox.width - initialBox.width),+ Math.abs(settledBox.height - initialBox.height),+ );++ const observed = await subject.evaluate((node, expectedDirection) => {+ type Color = {r: number; g: number; b: number; a: number};+ const elements = <T extends Element>(selector: string) => [+ ...node.querySelectorAll<T>(selector),+ ];+ const geometry = (element: Element) => {+ const rect = element.getBoundingClientRect();+ return {+ x: rect.x,+ y: rect.y,+ width: rect.width,+ height: rect.height,+ right: rect.right,+ bottom: rect.bottom,+ };+ };+ const parseColor = (value: string): Color => {+ const channels = value.match(/[\d.]+/g)?.map(Number);+ if (!channels || channels.length < 3) {+ throw new Error(`Cannot parse computed color: ${value}`);+ }+ return {+ r: channels[0] ?? 0,+ g: channels[1] ?? 0,+ b: channels[2] ?? 0,+ a: channels[3] ?? 1,+ };+ };+ const composite = (foreground: Color, background: Color): Color => {+ const a = foreground.a + background.a * (1 - foreground.a);+ if (a === 0) {+ return {r: 0, g: 0, b: 0, a: 0};+ }+ return {+ r:+ (foreground.r * foreground.a ++ background.r * background.a * (1 - foreground.a)) /+ a,+ g:+ (foreground.g * foreground.a ++ background.g * background.a * (1 - foreground.a)) /+ a,+ b:+ (foreground.b * foreground.a ++ background.b * background.a * (1 - foreground.a)) /+ a,+ a,+ };+ };+ const renderedBackground = (element: Element): Color => {+ const layers: Color[] = [];+ let current: Element | null = element;+ while (current) {+ const layer = parseColor(getComputedStyle(current).backgroundColor);+ if (layer.a > 0) {+ layers.push(layer);+ }+ if (layer.a >= 0.999) {+ break;+ }+ current = current.parentElement;+ }+ return layers+ .reverse()+ .reduce(+ (background, foreground) => composite(foreground, background),+ {r: 255, g: 255, b: 255, a: 1},+ );+ };+ const formatColor = ({r, g, b, a}: Color) =>+ `rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${a.toFixed(3)})`;+ const luminance = ({r, g, b}: Color) => {+ const channel = (value: number) => {+ const normalized = value / 255;+ return normalized <= 0.04045+ ? normalized / 12.92+ : ((normalized + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);+ };+ const contrast = (left: Color, right: Color) => {+ const leftLuminance = luminance(left);+ const rightLuminance = luminance(right);+ return (+ (Math.max(leftLuminance, rightLuminance) + 0.05) /+ (Math.min(leftLuminance, rightLuminance) + 0.05)+ );+ };+ const isVisible = (element: Element) => {+ const rect = element.getBoundingClientRect();+ const style = getComputedStyle(element);+ return (+ rect.width > 0 &&+ rect.height > 0 &&+ style.display !== 'none' &&+ style.visibility !== 'hidden' &&+ style.opacity !== '0'+ );+ };+ const measure = (+ element: Element,+ part: string,+ type: 'text' | 'non-text',+ colorValue?: string,+ styleOverride?: CSSStyleDeclaration,+ ) => {+ const style = styleOverride ?? getComputedStyle(element);+ const background = renderedBackground(element);+ const foreground = parseColor(colorValue ?? style.color);+ const renderedForeground = composite(foreground, background);+ const ratio = contrast(renderedForeground, background);+ const fontSize = Number.parseFloat(style.fontSize);+ const fontWeight =+ style.fontWeight === 'bold'+ ? 700+ : Number.parseFloat(style.fontWeight) || 400;+ const threshold =+ type === 'non-text' ||+ fontSize >= 24 ||+ (fontSize >= 18.66 && fontWeight >= 700)+ ? 3+ : 4.5;+ return {+ part,+ type,+ state: 'rest',+ meaningful: true,+ foreground: colorValue ?? style.color,+ renderedForeground: formatColor(renderedForeground),+ renderedBackdrop: formatColor(background),+ fontSize,+ fontWeight,+ ratio: Number(ratio.toFixed(2)),+ threshold,+ exception: null,+ passed: ratio + 1e-6 >= threshold,+ };+ };++ const regions = elements<HTMLElement>('[role="region"]');+ const inputs = elements<HTMLInputElement>('[role="combobox"]');+ const lists = elements<HTMLElement>('[role="listbox"]');+ const options = elements<HTMLElement>('[role="option"]');+ const groups = elements<HTMLElement>('[role="group"]');+ const empties = elements<HTMLElement>('.astryx-command-palette-empty');+ const footers = elements<HTMLElement>('.astryx-command-palette-footer');+ const icons = elements<HTMLElement>(+ '.astryx-command-palette-input .astryx-icon',+ );+ const spinners = elements<HTMLElement>(+ '.astryx-command-palette-input .astryx-spinner',+ );+ const spinnerArcs = elements<SVGCircleElement>(+ '.astryx-command-palette-input .astryx-spinner circle:last-of-type',+ );+ const shortcuts = elements<HTMLElement>(+ '.astryx-command-palette-footer .astryx-kbd',+ );+ const headings = elements<HTMLElement>('h2');+ const groupHeadings = elements<HTMLElement>(+ '.astryx-command-palette-group-heading',+ );+ const targetSelectors = [+ '.astryx-command-palette-input',+ '.astryx-command-palette-list',+ '.astryx-command-palette-item',+ '.astryx-command-palette-group',+ '.astryx-command-palette-group-heading',+ '.astryx-command-palette-empty',+ '.astryx-command-palette-footer',+ ];+ const targets = targetSelectors.flatMap(selector => elements(selector));+ const footerText = footers.flatMap(footer => [+ ...footer.querySelectorAll<HTMLElement>(':scope > span'),+ ]);++ const contrastPairs = [+ ...headings+ .filter(isVisible)+ .map((element, index) =>+ measure(element, `section-heading-${index + 1}`, 'text'),+ ),+ ...groupHeadings+ .filter(isVisible)+ .map((element, index) =>+ measure(element, `group-heading-${index + 1}`, 'text'),+ ),+ ...inputs.filter(isVisible).map((element, index) => {+ const placeholder = getComputedStyle(element, '::placeholder');+ return measure(+ element,+ `input-placeholder-${index + 1}`,+ 'text',+ placeholder.color,+ placeholder,+ );+ }),+ ...options+ .filter(isVisible)+ .map((element, index) =>+ measure(element, `option-${index + 1}`, 'text'),+ ),+ ...empties+ .filter(isVisible)+ .map((element, index) =>+ measure(element, `empty-${index + 1}`, 'text'),+ ),+ ...footerText+ .filter(isVisible)+ .map((element, index) =>+ measure(element, `footer-hint-${index + 1}`, 'text'),+ ),+ ...shortcuts.flatMap((shortcut, shortcutIndex) =>+ [...shortcut.querySelectorAll<HTMLElement>('kbd')]+ .filter(isVisible)+ .map((element, keyIndex) =>+ measure(+ element,+ `shortcut-${shortcutIndex + 1}-key-${keyIndex + 1}`,+ 'text',+ ),+ ),+ ),+ ...icons+ .filter(isVisible)+ .map((element, index) =>+ measure(element, `search-icon-${index + 1}`, 'non-text'),+ ),+ ...spinnerArcs+ .filter(isVisible)+ .map((element, index) =>+ measure(+ element,+ `loading-spinner-${index + 1}`,+ 'non-text',+ getComputedStyle(element).stroke,+ ),+ ),+ ];++ return {+ declaredDirection: expectedDirection,+ computedDirections: regions.map(+ region => getComputedStyle(region).direction,+ ),+ text: (node as HTMLElement).innerText,+ counts: {+ regions: regions.length,+ inputs: inputs.length,+ lists: lists.length,+ options: options.length,+ groups: groups.length,+ groupHeadings: groupHeadings.length,+ empties: empties.length,+ footers: footers.length,+ icons: icons.length,+ spinners: spinners.length,+ shortcuts: shortcuts.length,+ targets: targets.length,+ },+ inputLinks: inputs.map(input => ({+ name: input.getAttribute('aria-label'),+ controls: input.getAttribute('aria-controls'),+ controlsExistingList:+ input.getAttribute('aria-controls') != null &&+ lists.some(list => list.id === input.getAttribute('aria-controls')),+ expanded: input.getAttribute('aria-expanded'),+ })),+ selectedValues: options+ .filter(option => option.getAttribute('aria-selected') === 'true')+ .map(option => option.getAttribute('data-value')),+ regions: regions.map(region => ({+ name: region.getAttribute('aria-label'),+ geometry: geometry(region),+ })),+ targetGeometry: targets.map(geometry),+ noHorizontalOverflow:+ document.documentElement.scrollWidth <= window.innerWidth + 1 &&+ targets.every(element => {+ const rect = element.getBoundingClientRect();+ return rect.left >= -1 && rect.right <= window.innerWidth + 1;+ }),+ contrastPairs,+ };+ }, scenario.direction);++ expect(observed.computedDirections).toEqual([+ scenario.direction,+ scenario.direction,+ scenario.direction,+ ]);+ expect(observed.counts).toEqual({+ regions: 3,+ inputs: 3,+ lists: 1,+ options: 4,+ groups: 2,+ groupHeadings: 2,+ empties: 2,+ footers: 3,+ icons: 3,+ spinners: 1,+ shortcuts: 12,+ targets: 19,+ });+ expect(observed.inputLinks).toEqual([+ expect.objectContaining({+ name: 'Search commands',+ controlsExistingList: true,+ expanded: 'true',+ }),+ expect.objectContaining({+ name: 'Search commands',+ controls: null,+ controlsExistingList: false,+ expanded: 'false',+ }),+ expect.objectContaining({+ name: 'Search commands',+ controls: null,+ controlsExistingList: false,+ expanded: 'false',+ }),+ ]);+ expect(observed.selectedValues).toEqual(['settings']);+ expect(observed.text).toContain('Grouped results');+ expect(observed.text).toContain('Empty bootstrap');+ expect(observed.text).toContain('Pending bootstrap');+ expect(observed.text).toContain('Type to search');+ expect(observed.text).toContain('Create a command');+ expect(observed.text).toContain('Navigate');+ expect(observed.text).toContain('Select');+ expect(observed.text).toContain('Close');+ expect(observed.noHorizontalOverflow).toBe(true);+ expect(geometryDelta).toBeLessThanOrEqual(0.5);+ expect(observed.contrastPairs.length).toBeGreaterThanOrEqual(30);+ expect(observed.contrastPairs.every(pair => pair.passed)).toBe(true);+ expect(errors).toEqual([]);++ const file = `CommandPalette__${scenario.state}.png`;+ const png = await subject.screenshot({animations: 'disabled'});+ const stateRows = [+ {+ scenario: scenario.state,+ state: 'grouped-results-selected',+ visible: true,+ optionCount: 4,+ groupCount: 2,+ selectedValue: 'settings',+ },+ {+ scenario: scenario.state,+ state: 'empty-bootstrap',+ visible: true,+ emptyCount: 1,+ listboxPresent: false,+ comboboxExpanded: false,+ },+ {+ scenario: scenario.state,+ state: 'pending-bootstrap',+ visible: true,+ spinnerCount: 1,+ emptyStateRemainsMounted: true,+ listboxPresent: false,+ comboboxExpanded: false,+ },+ ];+ const contrastRows = observed.contrastPairs.map(pair => ({+ scenario: scenario.state,+ ...pair,+ }));+ const receipt = {+ state: scenario.state,+ mode: scenario.mode,+ direction: scenario.direction,+ viewport: scenario.viewport,+ headSha: checkoutSha,+ storybookSha,+ image: file,+ imageSha256: createHash('sha256').update(png).digest('hex'),+ imageSize: {+ width: png.readUInt32BE(16),+ height: png.readUInt32BE(20),+ },+ geometryDelta,+ observed,+ stateVisualMatrix: stateRows,+ contrastPairMatrix: contrastRows,+ browser: browserVersion,+ passed: true,+ };+ fs.writeFileSync(path.join(OUTPUT, file), png);+ fs.writeFileSync(+ path.join(OUTPUT, `${file}.sensors.json`),+ `${JSON.stringify(receipt, null, 2)}\n`,+ );+ frames.push({+ state: scenario.state,+ mode: scenario.mode,+ direction: scenario.direction,+ viewport: scenario.viewport,+ passed: true,+ image: receipt.image,+ });+ stateVisualMatrix.push(...stateRows);+ contrastPairMatrix.push(...contrastRows);+ } finally {+ page.off('pageerror', onPageError);+ page.off('console', onConsole);+ }+}++for (const scenario of CASES) {+ test(`captures ${scenario.state}`, async ({page}) => {+ await capture(page, scenario);+ });+}diff --git a/packages/core/src/Layer/useLayerDismissal.ts b/packages/core/src/Layer/useLayerDismissal.tsindex 2e265580a2..0fdaaa7088 100644--- a/packages/core/src/Layer/useLayerDismissal.ts+++ b/packages/core/src/Layer/useLayerDismissal.ts@@ -96,16 +96,16 @@ export interface UseLayerDismissalReturn {** The layer does NOT attach a key listener — the stack owns one listener and* routes each Escape press to the top-most REGISTERED layer, so one press- * dismisses exactly one of them. Dialog (and what is built on it), Popover and- * the menus built on it, ContextMenu, Tooltip, HoverCard, Lightbox, MobileNav,- * BottomSheet, BottomSheetSwitcher and lab's `Drawer` register today.+ * dismisses exactly one of them. Dialog (and what is built on it, including+ * CommandPalette), Popover and the menus built on it, ContextMenu, Tooltip,+ * HoverCard, Lightbox, MobileNav, BottomSheet, BottomSheetSwitcher and lab's+ * `Drawer` register today.*- * `CommandPalette`, `DropdownMenuSubMenu`, and- * `PowerSearchEditPopover` still run their own Escape listeners. They stay safe- * next to the stack only because each claims the press at element level, and the- * stack stands down on an already-`defaultPrevented` press — but a registered- * layer opened inside one of them does not get the press. Migrating them is the- * fix.+ * `DropdownMenuSubMenu` and `PowerSearchEditPopover` still run their own Escape+ * listeners. They stay safe next to the stack only because each claims the press+ * at element level, and the stack stands down on an already-`defaultPrevented`+ * press — but a registered layer opened inside one of them does not get the+ * press. Migrating them is the fix.** Wrap the layer's own content in `LayerDepthProvider` so anything opened from* inside it registers as nested.