Skip to content

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

TypeScript

[Component Audit] CommandPaletteEmpty: keep long empty messages readable inside the palette (#8516)

Cindy Zhang9600039ee0d4
diff --git a/.changeset/command-palette-empty-long-text.md b/.changeset/command-palette-empty-long-text.md
new file mode 100644
index 0000000000..52328c9286
--- /dev/null
+++ b/.changeset/command-palette-empty-long-text.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] CommandPaletteEmpty wraps a long unbroken word, such as a file path or URL in an empty-search message, inside the palette instead of spilling it past both edges where its start and end could not be read.
+
+@cixzhang
diff --git a/.github/a11y-audit-axe.json b/.github/a11y-audit-axe.json
index c57ee00464..04a5bee85c 100644
--- a/.github/a11y-audit-axe.json
+++ b/.github/a11y-audit-axe.json
@@ -11,7 +11,16 @@
"ChatMessageList": {"evidence": null},
"ChatMessageMetadata": {"evidence": null},
"ChatTokenizedText": {
- "env": {"ASTRYX_AUDIT_BASELINE_HEAD": "a7c6c7ecdf6b422df331124e8f6fc6d33cf1bd63"}
+ "env": {
+ "ASTRYX_AUDIT_BASELINE_HEAD": "a7c6c7ecdf6b422df331124e8f6fc6d33cf1bd63"
+ }
+ },
+ "CommandPaletteEmpty": {
+ "components": ["CommandPaletteEmpty", "CommandPalette"],
+ "stories": [
+ "core-commandpaletteempty--content-matrix",
+ "core-commandpalette--audit-matrix"
+ ]
},
"ContextMenuItem": {"readySelector": "[role=\"menu\"]", "evidence": null},
"DateInput": {
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index 0644d3f102..f363844644 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -350,6 +350,15 @@
"packages/core/src/CommandPalette/index.ts": "sha256:ba38845bbde6d73172df2c0791ca513c9f2b7baab17440e066e783ff6cfc7558"
}
},
+ {
+ "component": "core/CommandPaletteEmpty",
+ "reason": "CommandPaletteEmpty owns one message container that centers caller content on both axes with symmetric logical inline padding, block padding, and centered text, and wraps an unbroken token inside the host. It renders no directional glyph, physical inline positioning, reordered controls, horizontal scrolling or dragging, side-placed overlay, or horizontal keyboard behavior; caller text follows the document direction. The content fixture and the CommandPalette audit matrix exercise translated, long, standalone, and in-palette content in RTL without adding a component-owned RTL dimension.",
+ "evidence": {
+ "apps/storybook/stories/CommandPaletteEmpty.stories.tsx": "sha256:35e5e5da27d4440fec7f45d62c9db503210f37c042afd01fd17365ca59c6b2e7",
+ "packages/core/src/CommandPalette/CommandPaletteEmpty.tsx": "sha256:721c495b144ca2e0ccc1f869a44d8be1350d880d17f9a08eb025e7941421bc0e",
+ "packages/core/src/CommandPalette/index.ts": "sha256:ba38845bbde6d73172df2c0791ca513c9f2b7baab17440e066e783ff6cfc7558"
+ }
+ },
{
"component": "core/CommandPaletteList",
"reason": "CommandPaletteList owns one vertically stacked results container that scrolls on the block axis, with symmetric padding and block-axis gaps. It renders no directional glyph, physical inline positioning, reordered controls, horizontal scrolling or dragging, side-placed overlay, or horizontal keyboard behavior; item and group content follow normal document direction, and CommandPalette owns arrow-key navigation. The dedicated fixtures exercise the standalone listbox and the scrolling palette composition without adding a component-owned RTL dimension.",
diff --git a/apps/storybook/stories/CommandPaletteEmpty.stories.tsx b/apps/storybook/stories/CommandPaletteEmpty.stories.tsx
new file mode 100644
index 0000000000..47cf22ed52
--- /dev/null
+++ b/apps/storybook/stories/CommandPaletteEmpty.stories.tsx
@@ -0,0 +1,107 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandPaletteEmpty.stories.tsx
+ * @input Uses CommandPalette, CommandPaletteEmpty, Link, InternationalizationProvider
+ * @output Storybook fixture for empty-state content the CommandPalette stories do not reach
+ * @position Component-owned fixture; the CommandPalette audit matrix covers the
+ * default built-in empty branch, this covers expanded, long, and standalone content
+ */
+
+import {useMemo} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {
+ CommandPalette,
+ CommandPaletteEmpty,
+} from '@astryxdesign/core/CommandPalette';
+import {Link} from '@astryxdesign/core/Link';
+import {InternationalizationProvider} from '@astryxdesign/core/i18n';
+import {createStaticSource} from '@astryxdesign/core/Typeahead';
+
+const meta: Meta<typeof CommandPaletteEmpty> = {
+ title: 'Core/CommandPaletteEmpty',
+ component: CommandPaletteEmpty,
+ tags: ['autodocs'],
+};
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+const panelStyle = {flex: '1 1 280px', minWidth: 0} as const;
+const headingStyle = {
+ marginBlock: '0 8px',
+ font: 'inherit',
+ fontWeight: 600,
+} as const;
+
+/**
+ * Empty content the built-in branch must hold without breaking layout: catalog
+ * text expanded by translation, a long unbroken path echoed into the message,
+ * and the standalone composition with caller-provided rich content.
+ */
+export const ContentMatrix: Story = {
+ render: function Render() {
+ const emptySource = useMemo(() => createStaticSource([]), []);
+ return (
+ <div
+ style={{
+ display: 'flex',
+ flexWrap: 'wrap',
+ alignItems: 'flex-start',
+ gap: 16,
+ width: '100%',
+ padding: 16,
+ boxSizing: 'border-box',
+ }}>
+ <section style={panelStyle}>
+ <h2 style={headingStyle}>Translated built-in text</h2>
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{
+ fr: {
+ '@astryx.commandPalette.emptyBootstrap':
+ 'Commencez à saisir pour rechercher parmi les commandes disponibles',
+ '@astryx.commandPalette.emptySearch':
+ 'Aucune commande ne correspond à votre recherche',
+ },
+ }}>
+ <CommandPalette
+ isOpen
+ isInline
+ role="region"
+ label="Translated empty command palette"
+ onOpenChange={() => {}}
+ searchSource={emptySource}
+ width="100%"
+ maxHeight={320}
+ />
+ </InternationalizationProvider>
+ </section>
+ <section style={panelStyle}>
+ <h2 style={headingStyle}>Long unbroken text</h2>
+ <CommandPalette
+ isOpen
+ isInline
+ role="region"
+ label="Long empty command palette"
+ onOpenChange={() => {}}
+ searchSource={emptySource}
+ emptyBootstrapText="No files in /workspace/design-system/packages/core/src/CommandPalette/__fixtures__/empty-results/"
+ emptySearchText="No files match /workspace/design-system/packages/core/src/CommandPalette/__fixtures__/empty-results/"
+ width="100%"
+ maxHeight={320}
+ />
+ </section>
+ <section style={panelStyle}>
+ <h2 style={headingStyle}>Standalone rich content</h2>
+ <CommandPaletteEmpty>
+ <span>
+ No saved searches yet.{' '}
+ <Link href="#create-saved-search">Create a saved search</Link>
+ </span>
+ </CommandPaletteEmpty>
+ </section>
+ </div>
+ );
+ },
+};
diff --git a/packages/cli/test/__golden__/no-icon-set/search-search.json b/packages/cli/test/__golden__/no-icon-set/search-search.json
index 6bc0a9281b..2573fa1bb2 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-search.json
+++ b/packages/cli/test/__golden__/no-icon-set/search-search.json
@@ -3,7 +3,7 @@
"type": "search",
"data": {
"query": "search",
- "matchCount": 112,
+ "matchCount": 113,
"results": [
{
"domain": "doc",
diff --git a/packages/cli/test/__golden__/no-icon-set/search-search.txt b/packages/cli/test/__golden__/no-icon-set/search-search.txt
index 2112617cef..abe619e828 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-search.txt
+++ b/packages/cli/test/__golden__/no-icon-set/search-search.txt
@@ -1,4 +1,4 @@
-Results for "search" (20 of 112)
+Results for "search" (20 of 113)
name: cli/api/functions/search
domain: doc
package: @astryxdesign/cli
diff --git a/packages/core/src/CommandPalette/CommandPaletteEmpty.doc.mjs b/packages/core/src/CommandPalette/CommandPaletteEmpty.doc.mjs
index 631dac9425..e84f9a15cc 100644
--- a/packages/core/src/CommandPalette/CommandPaletteEmpty.doc.mjs
+++ b/packages/core/src/CommandPalette/CommandPaletteEmpty.doc.mjs
@@ -7,7 +7,8 @@ export const docs = {
subComponentOf: 'CommandPalette',
displayName: 'Command Palette Empty',
isHiddenFromOverview: true,
- description: 'Empty state display for the results area. Rendered automatically by CommandPalette for no-results and no-query states.',
+ description:
+ 'Empty state display for the results area. CommandPalette renders it automatically when a search returns no results, or when there is no query and bootstrap() returns nothing.',
props: [
{
name: 'children',
@@ -27,7 +28,8 @@ export const docsZh = {
name: 'CommandPaletteEmpty',
isHiddenFromOverview: true,
displayName: 'Command Palette Empty',
- description: '结果区域的空状态展示。由 CommandPalette 在无结果和无查询状态下自动渲染。',
+ description:
+ '结果区域的空状态展示。当搜索没有结果,或没有查询且 bootstrap() 未返回任何内容时,由 CommandPalette 自动渲染。',
propDescriptions: {
children: '要显示的消息或内容。',
},
@@ -37,7 +39,8 @@ export const docsDense = {
name: 'CommandPaletteEmpty',
isHiddenFromOverview: true,
displayName: 'Command Palette Empty',
- description: 'empty state; auto-rendered by palette for no-results+no-query states',
+ description:
+ 'empty state; auto-rendered by palette when a search has no results, or no query and bootstrap() returns nothing',
propDescriptions: {
children: 'message or content to display',
},
diff --git a/packages/core/src/CommandPalette/CommandPaletteEmpty.spec.md b/packages/core/src/CommandPalette/CommandPaletteEmpty.spec.md
new file mode 100644
index 0000000000..cd324b8612
--- /dev/null
+++ b/packages/core/src/CommandPalette/CommandPaletteEmpty.spec.md
@@ -0,0 +1,190 @@
+---
+schema_version: 3
+template_version: 7
+kind: component
+id: component:CommandPaletteEmpty
+authority: draft
+archive_reason: null
+superseded_by: null
+approved_by: null
+approved_at: null
+owners: [cixzhang]
+review_triggers: [public-api, behavior, theming, accessibility, testing]
+verified_by:
+ [
+ packages/core/src/CommandPalette/CommandPaletteEmpty.test.tsx,
+ packages/core/src/CommandPalette/CommandPalette.test.tsx,
+ packages/core/src/CommandPalette/CommandPaletteList.test.tsx,
+ packages/core/src/CommandPalette/__tests__/CommandPaletteEmptyAudit.a11y.chromium.spec.ts,
+ packages/core/src/theme/themingTargets.test.ts,
+ apps/storybook/stories/CommandPaletteEmpty.stories.tsx,
+ scripts/check-knowledge.mjs,
+ ]
+modules: []
+families: []
+design_specs: []
+architecture:
+ [
+ architecture:public-component-api,
+ architecture:component-theming-surface,
+ architecture:component-test-sufficiency,
+ ]
+contributing: []
+system_specs: [spec:AST-029, spec:AST-056]
+---
+
+# CommandPaletteEmpty component contract
+
+## Contract at a glance
+
+| Area | Contract |
+| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | `CommandPaletteEmpty` / `CommandPaletteEmptyProps`: required `children`, `BaseProps<HTMLDivElement>`, and a root `ref`. |
+| Behavior | One ordinary container centers caller content as supporting text. CommandPalette renders it for the no-query and no-results branches; it owns no role, state, announcement, or interaction. |
+| End-user impact | People who reach a palette dead end read the message, and any caller link stays ordinary reachable content rather than an option. |
+| Builder impact | None. Caller content, host attributes, and styling inputs compose on the root. |
+| Compatibility/readiness | Observational patch contract. Runtime behavior, exports, and the target name are unchanged; authority stays `draft` until exact-head owner approval. |
+| Review checks | Reject a component-owned role or live region, option semantics around caller content, dropped root inputs, a target moved off the painted root, or content that overflows its host inline axis. |
+| Governing rules | `architecture:public-component-api/INV1,INV5–INV8`; `architecture:component-theming-surface/INV2–INV6`; `spec:AST-056/FR3`, `AR1` for the parent's announcement; WCAG 2.2 SC 1.4.3 and 1.4.10. |
+
+This table is a review projection; the body below is authoritative.
+
+## Intent
+
+CommandPaletteEmpty presents the message shown in a CommandPalette result area
+when there is nothing to choose. It owns the empty-message surface: its layout,
+supporting typography, secondary text color, root input composition, and the
+`command-palette-empty` theme target. CommandPalette decides when the message
+appears, what it says by default, and whether it is announced.
+
+Consumer syntax and examples belong in `CommandPaletteEmpty.doc.mjs`.
+
+## Compatibility and migration
+
+- Released default preserved: yes — one centered, ordinary message container.
+- Compatibility class: observational patch; no public surface changes.
+- Controlled/uncontrolled behavior: not applicable.
+- Migration decision: none.
+
+Consumer migration instructions belong in consumer docs and release notes.
+
+## Ownership boundary
+
+**Owns**
+
+- One root container and its public ref, DOM/data/ARIA, class, style, event, and
+ `xstyle` composition.
+- Centered layout, block and inline padding, supporting type size and leading,
+ body font family, and secondary text color for caller content.
+- Wrapping caller text inside the host's inline size.
+- The `command-palette-empty` target on the same painted root.
+
+**Does not own / non-goals**
+
+- When the empty branch appears, the built-in catalog messages, and the
+ empty-search announcement — owned by `component:CommandPalette`.
+- Result-surface semantics while empty, including dropping listbox semantics —
+ owned by `component:CommandPalette` and `component:CommandPaletteList`.
+- The meaning, links, or controls inside caller content — owned by the product
+ callsite.
+
+## Public concepts
+
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ------------- | --------------------------------------------- | ------------------------------------------------------------------- | ---------------------------------------------------------------- | -------- | -------------------- | --------- | ------------------------------------------------------- |
+| Empty message | caller `ReactNode`: text or elements | The supporting message people read when there is nothing to choose. | No-query and no-results palette branches; standalone composition | required | component | stable | Rendered as given; React decides non-renderable values. |
+| Root surface | ref; DOM/data/ARIA; class/style/xstyle/events | Extends the message root. | Every render | omitted | public component API | stable | Accepted inputs compose; the component adds no role. |
+
+## Behavioral and layout contract
+
+Draft requirements identify their basis so observed code is not mistaken for an
+intentional decision.
+
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | ------------------ |
+| FR1 | The component MUST render its children inside one container element that centers them on both axes with centered text, supporting type, body font family, and secondary text color. | Current source, consumer docs, and focused tests | verify |
+| FR2 | CommandPalette MUST render this component with `emptyBootstrapText` when there is no query and no result, and with `emptySearchText` when a query has no result. | Current CommandPalette source and tests | verify |
+| FR3 | The root MUST carry no component-owned role, live region, or focus stop, so caller links and controls remain ordinary content. | WAI-ARIA 1.2 listbox owned-children rule; current source and Chromium evidence | verify |
+| FR4 | Caller text MUST wrap inside the host's inline size, including a single unbroken token, so no message forces inline scrolling or clipping at 320 CSS px. | WCAG 2.2 SC 1.4.10; Chromium evidence | verify |
+| FR5 | The painted root MUST carry the `command-palette-empty` target; component styles apply before caller `xstyle`. | `architecture:component-theming-surface/INV2–INV6`; source and focused tests | verify |
+| FR6 | Accepted ref, DOM/data/ARIA, class, style, events, and `xstyle` MUST reach or compose on the root. | `architecture:public-component-api/INV5–INV8`; focused tests | verify |
+
+### Allowed variation
+
+- **AV1 — Theme paint.** The target may restyle the message surface and text
+ without changing semantics or layout ownership.
+- **AV2 — Caller content.** Text length, translation, inline elements, and links
+ may vary while the root stays one ordinary container.
+
+### Representative states
+
+| State | Required invariant | Allowed variation |
+| ---------------------- | ----------------------------------------------------------------------------- | --------------------------------------------- |
+| Palette no-query empty | The bootstrap message renders in the result area; no listbox is exposed. | Built-in catalog text or caller content. |
+| Palette no-result | The search message renders; CommandPalette announces the rendered text. | Built-in catalog text or caller rich content. |
+| Standalone | The same root renders outside a palette with caller content. | Host layout and caller roles. |
+| Long or translated | Text wraps inside the host; no inline overflow. | Line count grows. |
+| RTL | Centered layout and text remain direction-neutral; inline text order mirrors. | Caller content direction. |
+| Narrow viewport | The message wraps within a 320 CSS px host. | Line count grows. |
+
+### Transformation and precedence order
+
+- **ORD1 — Root composition.** Apply the target class, component styles, then
+ caller `xstyle`; append caller `className`; apply caller `style`; spread
+ remaining host props onto the root.
+
+### Performance and resources
+
+- **PR1 — No lifecycle.** CommandPaletteEmpty uses no hook, listener, observer,
+ timer, request, state, or Effect.
+
+## Accessibility contract
+
+- **AR1 — Ordinary content.** The root exposes caller content in reading order
+ with no added role; a caller link keeps its own role and focus behavior.
+- **AR2 — Readable message.** Message text meets the WCAG 2.2 SC 1.4.3 contrast
+ minimum against its rendered surface in every supported theme and mode.
+
+## Design relationships
+
+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
+| ---------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------- | -------------- | ------------------ |
+| Empty message | Presents the dead-end message as supporting text centered in the results. | Current source tokens; no component-local visual decision settled | supporting | FR1, FR4, FR5 |
+
+No component-local visual decision is settled by this draft.
+
+## Family and system relationships
+
+- `architecture:public-component-api` owns exports and root input composition.
+- `architecture:component-theming-surface` owns target placement.
+- `architecture:component-test-sufficiency` owns proportionate, observable
+ evidence.
+- `spec:AST-056/FR3` and `AR1` require CommandPalette to announce the
+ empty-search message it rendered; this component supplies the rendered node.
+- CommandPalette and CommandPaletteList draft records describe the parent
+ branches and empty result surface; they are observational context, not
+ authority for this contract.
+- `spec:AST-029` keeps this observational draft separate from the audit receipt.
+
+## Verification map
+
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ------------------------------------ |
+| FR1, FR5–FR6 | `CommandPaletteEmpty.test.tsx`; `themingTargets.test.ts` | text and element children; root inputs | A dropped input, a moved target, or lost children fails the focused assertions. | `audit:CommandPaletteEmpty/§2,§3,§4` |
+| FR2, FR3, AR1 | `CommandPalette.test.tsx`; `CommandPaletteList.test.tsx`; exact-head Chromium receipts | bootstrap, search, rich content, modal and inline | Exposing a listbox, adding a role, or announcing other text than the rendered message fails assertions. | `audit:CommandPaletteEmpty/§1,§4` |
+| FR4, AR2 | Exact-head Chromium receipts and contrast pairs | long and translated text; 320 px; themes and modes | Inline overflow or clipping fails the reflow sensor; ratios are recorded per frame. | `audit:CommandPaletteEmpty/§5,§10` |
+| PR1 | Source review and the presentational lint rule | every state | A hook or lifecycle mechanism fails the lint rule. | `audit:CommandPaletteEmpty/§7` |
+
+## Decision log
+
+None. This draft records current facts and introduces no product decision.
+
+## Open questions
+
+None.
+
+## Content boundary
+
+This file does not duplicate consumer prop tables/examples, current audit scores,
+screenshot matrices, implementation steps, or system rules. The audit pull request
+owns the closed run evidence required by `spec:AST-029/FR5`.
diff --git a/packages/core/src/CommandPalette/CommandPaletteEmpty.tsx b/packages/core/src/CommandPalette/CommandPaletteEmpty.tsx
index b5022c2d9a..ed49e41c90 100644
--- a/packages/core/src/CommandPalette/CommandPaletteEmpty.tsx
+++ b/packages/core/src/CommandPalette/CommandPaletteEmpty.tsx
@@ -36,6 +36,10 @@ const styles = stylex.create({
lineHeight: typeScaleVars['--text-supporting-leading'],
color: colorVars['--color-text-secondary'],
textAlign: 'center' as const,
+ // Lets an unbroken token (a path or URL echoed into the message) wrap
+ // instead of setting the centered line's minimum width, which pushes text
+ // past both inline edges where neither side can scroll to it.
+ overflowWrap: 'anywhere',
},
});
diff --git a/packages/core/src/CommandPalette/__tests__/CommandPaletteEmptyAudit.a11y.chromium.spec.ts b/packages/core/src/CommandPalette/__tests__/CommandPaletteEmptyAudit.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..ee6dfe5d79
--- /dev/null
+++ b/packages/core/src/CommandPalette/__tests__/CommandPaletteEmptyAudit.a11y.chromium.spec.ts
@@ -0,0 +1,715 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y audit CommandPaletteEmpty
+
+/**
+ * @file CommandPaletteEmptyAudit.a11y.chromium.spec.ts
+ * @input Exact-head CommandPalette and CommandPaletteEmpty stories: the inline
+ * audit matrix, the modal built-in strings palette, and the empty content
+ * matrix, across states, themes, direction, pointers, and viewport sizes
+ * @output Screenshots and fail-closed sensor receipts for the CommandPaletteEmpty whole-component audit
+ * @position Component-owned Night Watch browser evidence; CI runs it only for a CommandPaletteEmpty audit pull request
+ */
+
+import {createHash} from 'node:crypto';
+import {execFileSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {inflateSync} from 'node:zlib';
+import {expect, test, type Locator, 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('command-palette-empty-audit-evidence');
+const WIDE = {width: 1024, height: 768};
+const NARROW = {width: 320, height: 720};
+const QUERY = 'zzz';
+
+type Mode = 'light' | 'dark';
+type Direction = 'ltr' | 'rtl';
+type Theme = 'neutral' | 'butter' | 'probe';
+type Pointer = 'fine' | 'coarse';
+type Story = 'matrix' | 'builtin' | 'content';
+type State = 'rest' | 'search' | 'link-focus';
+
+type AuditCase = {
+ key: string;
+ story: Story;
+ mode: Mode;
+ direction: Direction;
+ theme: Theme;
+ state: State;
+ pointer: Pointer;
+ forcedColors: boolean;
+ viewport: {width: number; height: number};
+};
+
+type AuditReceipt = {
+ passed: boolean;
+ expected: Record<string, unknown>;
+};
+
+const cases: AuditCase[] = [];
+function addPair(
+ key: string,
+ options: Partial<Omit<AuditCase, 'key' | 'mode'>> = {},
+) {
+ for (const mode of ['light', 'dark'] as const) {
+ cases.push({
+ key: `${key}-${mode}`,
+ story: options.story ?? 'matrix',
+ mode,
+ direction: options.direction ?? 'ltr',
+ theme: options.theme ?? 'neutral',
+ state: options.state ?? 'rest',
+ pointer: options.pointer ?? 'fine',
+ forcedColors: options.forcedColors ?? false,
+ viewport: options.viewport ?? WIDE,
+ });
+ }
+}
+
+addPair('matrix-bootstrap');
+addPair('matrix-bootstrap-butter', {theme: 'butter'});
+addPair('matrix-bootstrap-probe', {theme: 'probe'});
+addPair('matrix-bootstrap-rtl', {direction: 'rtl'});
+addPair('matrix-bootstrap-narrow', {viewport: NARROW});
+addPair('matrix-bootstrap-coarse', {viewport: NARROW, pointer: 'coarse'});
+addPair('matrix-bootstrap-forced-colors', {forcedColors: true});
+addPair('matrix-search', {state: 'search'});
+addPair('matrix-search-butter', {state: 'search', theme: 'butter'});
+addPair('matrix-search-probe', {state: 'search', theme: 'probe'});
+addPair('matrix-search-rtl', {state: 'search', direction: 'rtl'});
+addPair('matrix-search-narrow', {state: 'search', viewport: NARROW});
+addPair('matrix-link-focus', {state: 'link-focus'});
+addPair('matrix-link-focus-butter', {state: 'link-focus', theme: 'butter'});
+addPair('builtin-bootstrap', {story: 'builtin'});
+addPair('builtin-search', {story: 'builtin', state: 'search'});
+addPair('builtin-search-narrow', {
+ story: 'builtin',
+ state: 'search',
+ viewport: NARROW,
+});
+addPair('content-rest', {story: 'content'});
+addPair('content-rest-butter', {story: 'content', theme: 'butter'});
+addPair('content-rest-rtl', {story: 'content', direction: 'rtl'});
+addPair('content-rest-narrow', {story: 'content', viewport: NARROW});
+addPair('content-search', {story: 'content', state: 'search'});
+addPair('content-search-narrow', {
+ story: 'content',
+ state: 'search',
+ viewport: NARROW,
+});
+
+const LONG_PATH =
+ '/workspace/design-system/packages/core/src/CommandPalette/__fixtures__/empty-results/';
+const STANDALONE = 'No saved searches yet. Create a saved search';
+
+/** Rendered empty messages each story and state must show, in DOM order. */
+function expectedTexts(item: AuditCase): string[] {
+ const isSearch = item.state === 'search';
+ if (item.story === 'builtin') {
+ return [isSearch ? 'No results' : 'Type to search'];
+ }
+ if (item.story === 'content') {
+ return isSearch
+ ? [
+ 'Aucune commande ne correspond à votre recherche',
+ `No files match ${LONG_PATH}`,
+ STANDALONE,
+ ]
+ : [
+ 'Commencez à saisir pour rechercher parmi les commandes disponibles',
+ `No files in ${LONG_PATH}`,
+ STANDALONE,
+ ];
+ }
+ return [
+ isSearch
+ ? 'No matching commands. Create a command'
+ : 'No commands yet. Create a command',
+ ];
+}
+
+/**
+ * The search message the live region must carry; null where not asserted.
+ * Only the modal palette settles: the audit matrix keeps a never-settling
+ * pending palette beside the empty one, and React entangles their transitions,
+ * so its search stays pending and is announced only once it settles. The
+ * content matrix types into two palettes, so the region holds whichever
+ * message was announced last.
+ */
+function expectedAnnouncement(item: AuditCase): string | null {
+ if (item.state !== 'search' || item.story !== 'builtin') {
+ return null;
+ }
+ return expectedTexts(item)[0];
+}
+
+/**
+ * The root color scheme: `html[data-theme]` maps the mode to `color-scheme`,
+ * and forced colors mode forces `color-scheme: light dark` (CSS Color
+ * Adjustment Module Level 1).
+ */
+function expectedColorScheme(item: AuditCase) {
+ return item.forcedColors ? 'light dark' : item.mode;
+}
+
+test.describe.configure({mode: 'serial', retries: 0});
+let server: StaticServer;
+let checkoutSha: string;
+let storybookSha: string;
+
+function storyId(item: AuditCase) {
+ if (item.story === 'builtin') {
+ return 'core-commandpalette--built-in-strings';
+ }
+ if (item.story === 'content') {
+ return 'core-commandpaletteempty--content-matrix';
+ }
+ return 'core-commandpalette--audit-matrix';
+}
+
+function storyUrl(item: AuditCase) {
+ return `${server.origin}/iframe.html?id=${storyId(item)}&viewMode=story&globals=colorMode:${item.mode};astryxTheme:${item.theme};direction:${item.direction}`;
+}
+
+async function settle(page: Page) {
+ await holdMotionStill(page);
+ await page.evaluate(async () => document.fonts.ready);
+ await page.waitForTimeout(40);
+}
+
+async function politeText(page: Page) {
+ return page.evaluate(
+ () =>
+ document
+ .querySelector('[data-astryx-live-region="polite"]')
+ ?.textContent?.replace(/\s+/g, ' ')
+ .trim() ?? '',
+ );
+}
+
+async function emptyTexts(subject: Locator) {
+ return subject
+ .locator('.astryx-command-palette-empty')
+ .evaluateAll(nodes =>
+ nodes.map(node => node.textContent?.replace(/\s+/g, ' ').trim() ?? ''),
+ );
+}
+
+/** Waits up to `timeout` for `read` to return `want`; returns the last value. */
+async function waitFor<T>(
+ read: () => Promise<T>,
+ want: (value: T) => boolean,
+ timeout = 4000,
+): Promise<T> {
+ const start = Date.now();
+ let value = await read();
+ while (!want(value) && Date.now() - start < timeout) {
+ await new Promise(resolve => setTimeout(resolve, 50));
+ value = await read();
+ }
+ return value;
+}
+
+/**
+ * Whether a PNG paints more than one color, read from its decoded pixels so a
+ * blank or single-color frame cannot pass as evidence.
+ */
+function isNonBlank(png: Buffer): boolean {
+ let offset = 8;
+ let width = 0;
+ let height = 0;
+ let channels = 0;
+ const chunks: Buffer[] = [];
+ while (offset < png.length) {
+ const length = png.readUInt32BE(offset);
+ const type = png.toString('ascii', offset + 4, offset + 8);
+ const data = png.subarray(offset + 8, offset + 8 + length);
+ if (type === 'IHDR') {
+ width = data.readUInt32BE(0);
+ height = data.readUInt32BE(4);
+ channels = data[9] === 6 ? 4 : data[9] === 2 ? 3 : 0;
+ } else if (type === 'IDAT') {
+ chunks.push(data);
+ }
+ offset += 12 + length;
+ }
+ if (channels === 0 || width === 0 || height === 0) {
+ return false;
+ }
+ const raw = inflateSync(Buffer.concat(chunks));
+ const stride = width * channels;
+ let previous = Buffer.alloc(stride);
+ let first: string | null = null;
+ for (let y = 0; y < height; y++) {
+ const filter = raw[y * (stride + 1)];
+ const line = Buffer.from(
+ raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1)),
+ );
+ for (let x = 0; x < stride; x++) {
+ const left = x >= channels ? line[x - channels] : 0;
+ const up = previous[x];
+ const upLeft = x >= channels ? previous[x - channels] : 0;
+ let predictor = 0;
+ if (filter === 1) {
+ predictor = left;
+ } else if (filter === 2) {
+ predictor = up;
+ } else if (filter === 3) {
+ predictor = Math.floor((left + up) / 2);
+ } else if (filter === 4) {
+ const estimate = left + up - upLeft;
+ const toLeft = Math.abs(estimate - left);
+ const toUp = Math.abs(estimate - up);
+ const toUpLeft = Math.abs(estimate - upLeft);
+ predictor =
+ toLeft <= toUp && toLeft <= toUpLeft
+ ? left
+ : toUp <= toUpLeft
+ ? up
+ : upLeft;
+ }
+ line[x] = (line[x] + predictor) & 255;
+ }
+ for (let x = 0; x < stride; x += channels) {
+ const pixel = line.subarray(x, x + channels).toString('hex');
+ if (first == null) {
+ first = pixel;
+ } else if (pixel !== first) {
+ return true;
+ }
+ }
+ previous = line;
+ }
+ return false;
+}
+
+/**
+ * Settled-render readback taken just before capture: running animations under
+ * the subject, and the subject plus every empty root measured twice, two
+ * animation frames and 100 ms apart.
+ */
+async function readSettledRender(page: Page, subject: Locator) {
+ const sample = async () =>
+ subject.evaluate(root =>
+ [root, ...root.querySelectorAll('.astryx-command-palette-empty')].map(
+ node => {
+ const box = node.getBoundingClientRect();
+ return [box.x, box.y, box.width, box.height].map(
+ value => Math.round(value * 100) / 100,
+ );
+ },
+ ),
+ );
+ const first = await sample();
+ await page.evaluate(
+ async () =>
+ new Promise<void>(resolve => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
+ }),
+ );
+ await page.waitForTimeout(100);
+ const second = await sample();
+ const animations = await subject.evaluate(root => {
+ const running = document
+ .getAnimations()
+ .filter(animation => animation.playState === 'running');
+ return {
+ document: running.length,
+ subject: running.filter(animation => {
+ const target = (animation.effect as KeyframeEffect | null)?.target;
+ return target != null && root.contains(target);
+ }).length,
+ };
+ });
+ return {
+ runningAnimations: animations,
+ geometry: {first, second},
+ geometryStable: JSON.stringify(first) === JSON.stringify(second),
+ };
+}
+
+test.beforeAll(async () => {
+ fs.rmSync(OUTPUT, {recursive: true, force: true});
+ fs.mkdirSync(OUTPUT, {recursive: true});
+ checkoutSha = execFileSync('git', ['rev-parse', 'HEAD'], {
+ encoding: 'utf8',
+ }).trim();
+ const expected = process.env.ASTRYX_HEAD_SHA;
+ if (expected && expected !== checkoutSha) {
+ throw new Error(
+ `checkout ${checkoutSha} does not match expected head ${expected}`,
+ );
+ }
+ server = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+ const response = await fetch(`${server.origin}/astryx-build-sha.txt`);
+ if (!response.ok) {
+ throw new Error(`Storybook build has no SHA stamp (${response.status})`);
+ }
+ storybookSha = (await response.text()).trim();
+ if (storybookSha !== checkoutSha) {
+ throw new Error(
+ `Storybook ${storybookSha} does not match checkout ${checkoutSha}`,
+ );
+ }
+});
+
+test.afterAll(async () => {
+ await server?.close();
+});
+
+for (const item of cases) {
+ test(item.key, async ({browser}) => {
+ const context = await browser.newContext({
+ viewport: item.viewport,
+ deviceScaleFactor: 1,
+ colorScheme: item.mode,
+ reducedMotion: 'reduce',
+ hasTouch: item.pointer === 'coarse',
+ forcedColors: item.forcedColors ? 'active' : 'none',
+ });
+ const page = await context.newPage();
+ const pageErrors: string[] = [];
+ page.on('pageerror', error => pageErrors.push(String(error)));
+ await page.goto(storyUrl(item), {waitUntil: 'load'});
+ await page.locator('#storybook-root').waitFor();
+
+ let subject: Locator;
+ if (item.story === 'builtin') {
+ await page.getByRole('button', {name: 'Open'}).click();
+ subject = page.getByRole('dialog');
+ await subject.waitFor();
+ } else if (item.story === 'content') {
+ subject = page.locator('#storybook-root');
+ } else {
+ subject = page.getByRole('region', {name: 'Empty command palette'});
+ }
+ await subject.locator('.astryx-command-palette-empty').first().waitFor();
+ await settle(page);
+
+ const wantTexts = expectedTexts(item);
+ const wantAnnouncement = expectedAnnouncement(item);
+ let announcement: string | null = null;
+ if (item.state === 'search') {
+ const comboboxes = subject.getByRole('combobox');
+ const count = await comboboxes.count();
+ for (let index = 0; index < count; index++) {
+ await comboboxes.nth(index).focus();
+ await comboboxes.nth(index).pressSequentially(QUERY);
+ }
+ announcement = await waitFor(
+ async () => politeText(page),
+ value =>
+ wantAnnouncement == null ? value !== '' : value === wantAnnouncement,
+ );
+ await waitFor(
+ async () => emptyTexts(subject),
+ value => JSON.stringify(value) === JSON.stringify(wantTexts),
+ );
+ } else if (item.state === 'link-focus') {
+ await subject.getByRole('combobox').focus();
+ await page.keyboard.press('Tab');
+ }
+ await page.evaluate(async () => document.fonts.ready);
+ await page.waitForTimeout(40);
+
+ const observed = await page.evaluate(() => ({
+ theme: document
+ .querySelector('[data-astryx-theme]')
+ ?.getAttribute('data-astryx-theme'),
+ mode: document.documentElement.getAttribute('data-theme'),
+ colorScheme: getComputedStyle(document.documentElement).colorScheme,
+ viewport: {width: innerWidth, height: innerHeight},
+ dpr: devicePixelRatio,
+ hover: matchMedia('(hover: hover)').matches,
+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,
+ coarsePointer: matchMedia('(pointer: coarse)').matches,
+ forcedColors: matchMedia('(forced-colors: active)').matches,
+ horizontalOverflow: document.documentElement.scrollWidth > innerWidth + 1,
+ fonts: document.fonts.status,
+ storybookError: document.body.classList.contains('sb-show-errordisplay'),
+ }));
+
+ const empties = await subject
+ .locator('.astryx-command-palette-empty')
+ .evaluateAll(nodes => {
+ const canvas = document.createElement('canvas');
+ canvas.width = 1;
+ canvas.height = 1;
+ const ctx = canvas.getContext('2d', {willReadFrequently: true});
+ /** Any computed CSS color as sRGB 0–255 plus alpha 0–1. */
+ function rgba(color: string): [number, number, number, number] {
+ if (ctx == null) {
+ return [0, 0, 0, 0];
+ }
+ ctx.clearRect(0, 0, 1, 1);
+ ctx.fillStyle = '#000';
+ ctx.fillStyle = color;
+ ctx.fillRect(0, 0, 1, 1);
+ const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data;
+ return [r, g, b, a / 255];
+ }
+ function backdropOf(start: Element): string {
+ let node: Element | null = start;
+ while (node) {
+ const color = getComputedStyle(node).backgroundColor;
+ if (rgba(color)[3] > 0) {
+ return color;
+ }
+ node = node.parentElement;
+ }
+ return getComputedStyle(document.body).backgroundColor;
+ }
+ function luminance([r, g, b]: number[]) {
+ const [lr, lg, lb] = [r, g, b].map(channel => {
+ const c = channel / 255;
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
+ });
+ return 0.2126 * lr + 0.7152 * lg + 0.0722 * lb;
+ }
+ function ratio(foreground: string, backdrop: string) {
+ const bg = rgba(backdrop);
+ const fg = rgba(foreground);
+ const mixed = [0, 1, 2].map(
+ index => fg[index] * fg[3] + bg[index] * (1 - fg[3]),
+ );
+ const [high, low] = [luminance(mixed), luminance(bg)].sort(
+ (a, b) => b - a,
+ );
+ return Math.round(((high + 0.05) / (low + 0.05)) * 100) / 100;
+ }
+ return nodes.map(node => {
+ const element = node as HTMLElement;
+ const style = getComputedStyle(element);
+ const box = element.getBoundingClientRect();
+ const list = element.closest('.astryx-command-palette-list');
+ const host = element.closest('[role="dialog"], section, dialog');
+ const hostBox = host?.getBoundingClientRect() ?? null;
+ const backdrop = backdropOf(element);
+ const link = element.querySelector('a');
+ const linkStyle = link == null ? null : getComputedStyle(link);
+ return {
+ text: element.textContent?.replace(/\s+/g, ' ').trim() ?? '',
+ role: element.getAttribute('role'),
+ inPalette: list != null,
+ listRole: list?.getAttribute('role') ?? null,
+ listOverflow:
+ list == null
+ ? false
+ : list.scrollWidth > (list as HTMLElement).clientWidth + 1,
+ selfOverflow: element.scrollWidth > element.clientWidth + 1,
+ outsideHost:
+ hostBox == null
+ ? false
+ : box.left < hostBox.left - 1 || box.right > hostBox.right + 1,
+ direction: style.direction,
+ textAlign: style.textAlign,
+ color: style.color,
+ backdrop,
+ textContrast: ratio(style.color, backdrop),
+ fontSize: style.fontSize,
+ lineHeight: style.lineHeight,
+ fontFamily: style.fontFamily,
+ padding: {
+ blockStart: style.paddingBlockStart,
+ blockEnd: style.paddingBlockEnd,
+ inlineStart: style.paddingInlineStart,
+ inlineEnd: style.paddingInlineEnd,
+ },
+ link:
+ link == null || linkStyle == null
+ ? null
+ : {
+ text: link.textContent?.trim() ?? '',
+ color: linkStyle.color,
+ contrast: ratio(linkStyle.color, backdrop),
+ focused: link === document.activeElement,
+ focusVisible: link.matches(':focus-visible'),
+ outlineStyle: linkStyle.outlineStyle,
+ outlineWidth: linkStyle.outlineWidth,
+ outlineColor: linkStyle.outlineColor,
+ outlineContrast:
+ linkStyle.outlineStyle === 'none'
+ ? null
+ : ratio(linkStyle.outlineColor, backdrop),
+ },
+ geometry: {
+ x: box.x,
+ y: box.y,
+ width: box.width,
+ height: box.height,
+ },
+ };
+ });
+ });
+ const listboxesInSubject = await subject.getByRole('listbox').count();
+ const pendingIndicators = await subject.locator('.astryx-spinner').count();
+ const comboboxStates = await subject
+ .getByRole('combobox')
+ .evaluateAll(nodes =>
+ nodes.map(node => ({
+ value: (node as HTMLInputElement).value,
+ expanded: node.getAttribute('aria-expanded'),
+ controls: node.getAttribute('aria-controls'),
+ activeDescendant: node.getAttribute('aria-activedescendant'),
+ })),
+ );
+
+ const paletteEmpties = empties.filter(empty => empty.inPalette);
+ const semanticsPass =
+ JSON.stringify(empties.map(empty => empty.text)) ===
+ JSON.stringify(wantTexts) &&
+ empties.every(empty => empty.role === null) &&
+ paletteEmpties.every(empty => empty.listRole === null) &&
+ listboxesInSubject === 0 &&
+ empties.every(
+ empty => empty.geometry.width > 0 && empty.geometry.height > 0,
+ );
+ const reflowPass = empties.every(
+ empty => !empty.listOverflow && !empty.selfOverflow && !empty.outsideHost,
+ );
+ let statePass: boolean;
+ if (item.state === 'search') {
+ statePass =
+ comboboxStates.length > 0 &&
+ comboboxStates.every(
+ combobox =>
+ combobox.value === QUERY && combobox.activeDescendant === null,
+ ) &&
+ (wantAnnouncement == null || announcement === wantAnnouncement);
+ } else if (item.state === 'link-focus') {
+ const link = empties[0]?.link;
+ statePass = link?.focused === true && link.focusVisible === true;
+ } else {
+ statePass = comboboxStates.every(
+ combobox => combobox.value === '' && combobox.activeDescendant === null,
+ );
+ }
+
+ const settled = await readSettledRender(page, subject);
+ const png =
+ item.story === 'content'
+ ? await page.screenshot({animations: 'disabled', fullPage: true})
+ : await subject.screenshot({animations: 'disabled'});
+
+ const image = `${item.key}.png`;
+ const receipt = {
+ schemaVersion: 3,
+ expected: {
+ build: checkoutSha,
+ storyId: storyId(item),
+ mode: item.mode,
+ direction: item.direction,
+ theme: item.theme,
+ state: item.state,
+ pointer: item.pointer,
+ forcedColors: item.forcedColors,
+ viewport: item.viewport,
+ dpr: 1,
+ colorScheme: expectedColorScheme(item),
+ runningAnimationsInSubject: 0,
+ geometryStable: true,
+ texts: wantTexts,
+ announcement: wantAnnouncement,
+ listboxes: 0,
+ textContrastThreshold: 4.5,
+ },
+ observed: {
+ build: storybookSha,
+ ...observed,
+ empties,
+ listboxesInSubject,
+ pendingIndicators,
+ comboboxStates,
+ announcement,
+ settled,
+ pageErrors,
+ },
+ image: {
+ file: image,
+ sha256: createHash('sha256').update(png).digest('hex'),
+ width: png.readUInt32BE(16),
+ height: png.readUInt32BE(20),
+ nonBlank: isNonBlank(png),
+ },
+ checks: {
+ semanticsPass,
+ reflowPass,
+ statePass,
+ // Recorded, not gating: a token-layer pair is reported against the
+ // token layer rather than this component.
+ textContrastPass: item.forcedColors
+ ? null
+ : empties.every(empty => empty.textContrast >= 4.5),
+ },
+ passed:
+ storybookSha === checkoutSha &&
+ pageErrors.length === 0 &&
+ !observed.storybookError &&
+ observed.theme === item.theme &&
+ observed.mode === item.mode &&
+ observed.colorScheme === expectedColorScheme(item) &&
+ observed.dpr === 1 &&
+ settled.runningAnimations.subject === 0 &&
+ settled.geometryStable &&
+ isNonBlank(png) &&
+ empties.every(empty => empty.direction === item.direction) &&
+ observed.viewport.width === item.viewport.width &&
+ observed.viewport.height === item.viewport.height &&
+ observed.reducedMotion &&
+ observed.coarsePointer === (item.pointer === 'coarse') &&
+ observed.forcedColors === item.forcedColors &&
+ !observed.horizontalOverflow &&
+ observed.fonts === 'loaded' &&
+ semanticsPass &&
+ reflowPass &&
+ statePass,
+ };
+ fs.writeFileSync(path.join(OUTPUT, image), png);
+ fs.writeFileSync(
+ path.join(OUTPUT, `${item.key}.sensors.json`),
+ `${JSON.stringify(receipt, null, 2)}\n`,
+ );
+
+ await context.close();
+ });
+}
+
+test('manifest is complete', async () => {
+ const receiptFiles = fs
+ .readdirSync(OUTPUT)
+ .filter(file => file.endsWith('.sensors.json'));
+ const receipts = receiptFiles.map(
+ (file): AuditReceipt =>
+ JSON.parse(
+ fs.readFileSync(path.join(OUTPUT, file), 'utf8'),
+ ) as AuditReceipt,
+ );
+ const manifest = {
+ schemaVersion: 3,
+ component: 'core/CommandPaletteEmpty',
+ build: checkoutSha,
+ frames: cases.map(item => ({
+ key: item.key,
+ image: `${item.key}.png`,
+ receipt: `${item.key}.sensors.json`,
+ })),
+ };
+ fs.writeFileSync(
+ path.join(OUTPUT, 'manifest.json'),
+ `${JSON.stringify(manifest, null, 2)}\n`,
+ );
+ expect(receiptFiles).toHaveLength(cases.length);
+ expect(
+ receipts
+ .filter(receipt => !receipt.passed)
+ .map(receipt => receipt.expected),
+ ).toEqual([]);
+});