An open source design system that's fully customizable and agent ready
TypeScript
fix(CommandPalette): no 'Type to search' over a query you've typed while the first search loads (#9420)
Cindy Zhang3dec8e7d902f
diff --git a/.changeset/command-palette-pending-empty.md b/.changeset/command-palette-pending-empty.mdnew file mode 100644index 0000000000..0021425693--- /dev/null+++ b/.changeset/command-palette-pending-empty.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] CommandPalette no longer shows its "Type to search" text after you have typed. While the first search is still loading, the list stays empty and the field's loading spinner shows; the no-results text appears once that search finishes with nothing. Clearing the field brings "Type to search" back.++@cixzhangdiff --git a/docs/specs/components/CommandPalette/CommandPalette.spec.md b/docs/specs/components/CommandPalette/CommandPalette.spec.mdindex cf2b3ee252..cc32117ca5 100644--- a/docs/specs/components/CommandPalette/CommandPalette.spec.md+++ b/docs/specs/components/CommandPalette/CommandPalette.spec.md@@ -105,16 +105,16 @@ documented in `CommandPalette.doc.mjs` and its subcomponent docs.## Behavioral and layout contract-| ID | Invariant | Basis |-| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------- |-| FR1 | The 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 |-| 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 |-| 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 |-| FR4 | Query field is a distinct native text field inside Input and 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 |-| 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` |-| 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 |-| 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 |-| 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` |+| ID | Invariant | Basis |+| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |+| FR1 | The 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. Before the first query's result is committed, while that query is pending, the result surface keeps the Empty container's size and shows no message; once an answer is committed, a later pending query keeps the current results or the search-empty message until its own result commits (the "Pending search" state row; `component:CommandPaletteEmpty` FR2). | Current source, docs, tests, and ARIA required-child rule |+| 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 |+| 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 |+| FR4 | Query field is a distinct native text field inside Input and 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 |+| 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` |+| 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 |+| 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 |+| 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` |### Allowed variation@@ -249,17 +249,17 @@ unsettled (OQ1) and does not authorize a new target.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | -------------------------------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |-| FR1, AR1 | CommandPalette root and subcomponent suites | 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 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` and `CommandPaletteFooter.test.tsx` | Default Search glyph, pending spinner, and Footer Kbd | Replacing or removing the delegated Icon, Spinner, or Kbd instance fails a composed-owner assertion. | `audit:CommandPalette/theming` |-| FR4 | `CommandPaletteInput.test.tsx` | 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` | Canonical anatomy and seven current local targets | Missing, extra, prefixed, stale, or alias-backed mappings fail repository validation. Gap: no check fails if a mapped part stops painting. | `audit:CommandPalette/theming` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |+| FR1, AR1 | CommandPalette root and subcomponent suites; `CommandPalette.test.tsx` pending-state cases; `CommandPalettePending.a11y.chromium.spec.ts` (pending keeps the empty surface's height) | 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 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` and `CommandPaletteFooter.test.tsx` | Default Search glyph, pending spinner, and Footer Kbd | Replacing or removing the delegated Icon, Spinner, or Kbd instance fails a composed-owner assertion. | `audit:CommandPalette/theming` |+| FR4 | `CommandPaletteInput.test.tsx` | 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` | Canonical anatomy and seven current local targets | Missing, extra, prefixed, stale, or alias-backed mappings fail repository validation. Gap: no check fails if a mapped part stops painting. | `audit:CommandPalette/theming` |Focused target-placement assertions cover all seven local targets. The composedInput and Footer tests also pin the delegated Search Icon, pending Spinner, anddiff --git a/packages/core/src/CommandPalette/CommandPalette.test.tsx b/packages/core/src/CommandPalette/CommandPalette.test.tsxindex a706a2dc2b..b9d4fe45e5 100644--- a/packages/core/src/CommandPalette/CommandPalette.test.tsx+++ b/packages/core/src/CommandPalette/CommandPalette.test.tsx@@ -382,6 +382,120 @@ describe('CommandPalette', () => {);});+ // component:CommandPaletteEmpty FR2: "no query" is the field's current value.+ it('shows no empty text while the first query is pending, then its outcome', async () => {+ const resolvers: ((items: SearchableItem[]) => void)[] = [];+ const source: SearchSource = {+ bootstrap: () => [],+ async search(): Promise<SearchableItem[]> {+ return new Promise<SearchableItem[]>(resolve => {+ resolvers.push(resolve);+ });+ },+ };++ render(+ <CommandPalette+ isOpen={true}+ onOpenChange={() => {}}+ searchSource={source}+ emptyBootstrapText="Type to search"+ emptySearchText="No results"+ />,+ );+ await waitFor(() =>+ expect(screen.getByText('Type to search')).toBeInTheDocument(),+ );++ const input = screen.getByRole('combobox');+ fireEvent.change(input, {target: {value: 'ap'}});+ await waitFor(() => expect(resolvers).toHaveLength(1));+ // Pending: no bootstrap text, no search-empty text; the spinner shows.+ expect(screen.queryByText('Type to search')).toBeNull();+ expect(screen.queryByText('No results')).toBeNull();+ // The Input's spinner is decorative (spec:AST-086 FR8): find it by class.+ expect(document.querySelector('.astryx-spinner')).not.toBeNull();+ // The result surface keeps the Empty container (so the dialog keeps its+ // height), hidden from assistive technology and with no message.+ const placeholder = document.querySelector('.astryx-command-palette-empty');+ expect(placeholder).not.toBeNull();+ expect(placeholder).toHaveAttribute('aria-hidden', 'true');+ expect(placeholder?.textContent?.trim()).toBe('');++ resolvers[0]([]);+ await waitFor(() =>+ expect(screen.getByText('No results')).toBeInTheDocument(),+ );+ expect(screen.queryByText('Type to search')).toBeNull();+ });++ it('shows the first query results once they arrive, with no empty text before', async () => {+ const resolvers: ((items: SearchableItem[]) => void)[] = [];+ const source: SearchSource = {+ bootstrap: () => [],+ async search(): Promise<SearchableItem[]> {+ return new Promise<SearchableItem[]>(resolve => {+ resolvers.push(resolve);+ });+ },+ };++ render(+ <CommandPalette+ isOpen={true}+ onOpenChange={() => {}}+ searchSource={source}+ emptyBootstrapText="Type to search"+ emptySearchText="No results"+ />,+ );+ const input = screen.getByRole('combobox');+ fireEvent.change(input, {target: {value: 'ap'}});+ await waitFor(() => expect(resolvers).toHaveLength(1));+ expect(screen.queryByText('Type to search')).toBeNull();++ resolvers[0]([{id: 'apple', label: 'Apple'}]);+ await waitFor(() =>+ expect(screen.getByRole('option', {name: /Apple/})).toBeInTheDocument(),+ );+ expect(screen.queryByText('No results')).toBeNull();+ });++ it('brings the bootstrap text back when the field is cleared', async () => {+ const resolvers: ((items: SearchableItem[]) => void)[] = [];+ const source: SearchSource = {+ bootstrap: () => [],+ async search(): Promise<SearchableItem[]> {+ return new Promise<SearchableItem[]>(resolve => {+ resolvers.push(resolve);+ });+ },+ };++ render(+ <CommandPalette+ isOpen={true}+ onOpenChange={() => {}}+ searchSource={source}+ emptyBootstrapText="Type to search"+ emptySearchText="No results"+ />,+ );+ const input = screen.getByRole('combobox');+ fireEvent.change(input, {target: {value: 'zq'}});+ await waitFor(() => expect(resolvers).toHaveLength(1));+ resolvers[0]([]);+ await waitFor(() =>+ expect(screen.getByText('No results')).toBeInTheDocument(),+ );++ fireEvent.change(input, {target: {value: ''}});+ await waitFor(() =>+ expect(screen.getByText('Type to search')).toBeInTheDocument(),+ );+ expect(screen.queryByText('No results')).toBeNull();+ });+it('discards a search response that resolves after the palette closed', async () => {// A source whose search resolves only when released, and no cancel()// implementation — closing the palette must invalidate the request itself.diff --git a/packages/core/src/CommandPalette/CommandPalette.tsx b/packages/core/src/CommandPalette/CommandPalette.tsxindex 02976a8262..a1bdb5d400 100644--- a/packages/core/src/CommandPalette/CommandPalette.tsx+++ b/packages/core/src/CommandPalette/CommandPalette.tsx@@ -624,12 +624,20 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({],);- // `search` is the committed query the on-screen results correspond to (it- // still holds the previous query while a transition is pending). Keeping both- // flags ungated by `isPending` makes them exhaustive over the empty case, so- // 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;+ // "No query" is the field's current value (`optimisticSearch`), so the+ // bootstrap text never shows over a query the person has typed+ // (component:CommandPaletteEmpty FR2). The search-empty text belongs to a+ // committed query (`search`, which still holds the previous query while a+ // transition is pending): it stays mounted across keystrokes after a query+ // settled empty, so it never flashes. While the first query is pending and+ // nothing is committed, neither text shows: the result surface keeps the+ // Empty container's size with no message, so the dialog does not jump, and+ // the Input's Loading spinner is the indicator (component:CommandPalette+ // FR1 and its Pending search state row).+ const hasQuery = optimisticSearch !== '';+ const showEmptyBootstrap = !hasQuery && optimisticResults.length === 0;+ const showEmptySearch =+ hasQuery && 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.@@ -648,6 +656,12 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({{emptySearchText}</CommandPaletteEmpty>);+ } else if (optimisticResults.length === 0) {+ // A no-break space gives the empty container one line of height; it is+ // hidden from assistive technology, which hears the busy start instead.+ listContent = (+ <CommandPaletteEmpty aria-hidden="true">{'\u00a0'}</CommandPaletteEmpty>+ );} else {listContent = (<ItemRendererdiff --git a/packages/core/src/CommandPalette/__tests__/CommandPalettePending.a11y.chromium.spec.ts b/packages/core/src/CommandPalette/__tests__/CommandPalettePending.a11y.chromium.spec.tsnew file mode 100644index 0000000000..abe25b09f0--- /dev/null+++ b/packages/core/src/CommandPalette/__tests__/CommandPalettePending.a11y.chromium.spec.ts@@ -0,0 +1,60 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope ^(packages/core/src/CommandPalette/|apps/storybook/stories/CommandPalette)++/**+ * @file CommandPalettePending.a11y.chromium.spec.ts+ * @input The `Core/CommandPalette` Built-in strings story in a built Storybook,+ * in Chromium: bootstrap returns nothing, and search answers after 600 ms.+ * @output Real-browser proof of component:CommandPalette FR1's pending case:+ * while the first query is pending, the result surface shows no message+ * ("Type to search" never sits under a typed query) and keeps the Empty+ * container's height, so the result surface does not jump.+ * @position Runs in pr-a11y when CommandPalette, its stories or this spec+ * changes.+ */++import {expect, test} from '@playwright/test';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++const STORY = 'core-commandpalette--built-in-strings';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(DEFAULT_STORYBOOK_DIR);+});++test.afterAll(async () => {+ await storybook?.close();+});++test('the first pending query shows no message and keeps the height', async ({+ page,+}) => {+ await page.goto(`${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`);+ await page.locator('#storybook-root button').first().click();+ const dialog = page.locator('dialog[open]');+ await expect(dialog.getByText('Type to search')).toBeVisible();+ // The result surface's layout height (offsetHeight ignores the dialog's+ // entry transform, which a bounding box would include mid-animation).+ const empty = dialog.locator('.astryx-command-palette-empty');+ const before = await empty.evaluate(+ (element: HTMLElement) => element.offsetHeight,+ );++ await dialog.getByRole('combobox').pressSequentially('butt');+ // The search answers after 600 ms; check while the spinner shows.+ await expect(dialog.locator('.astryx-spinner')).toBeVisible();+ await expect(dialog.getByText('Type to search')).toHaveCount(0);+ await expect(dialog.getByText('No results')).toHaveCount(0);+ const pending = await empty.evaluate(+ (element: HTMLElement) => element.offsetHeight,+ );+ expect(pending).toBe(before);++ await expect(dialog.getByText('No results')).toBeVisible();+});