An open source design system that's fully customizable and agent ready
TypeScript
[Component Audit] CommandPaletteFooter: make shortcut guidance verifiable (#7096)
Cindy Zhanga4683c36d991
diff --git a/.changeset/command-palette-footer-audit.md b/.changeset/command-palette-footer-audit.mdnew file mode 100644index 0000000000..feb4aa6e91--- /dev/null+++ b/.changeset/command-palette-footer-audit.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Let CommandPaletteFooter wrap translated guidance on narrow screens, correct its composition example, and add owned audit coverage.++@cixzhangdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 87a3e7ecf4..73319de613 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1413,6 +1413,35 @@ jobs:retention-days: 30if-no-files-found: ignore+ # CommandPaletteFooter's default and replacement branches live inside the+ # parent dialog. Its owned stories keep those branches routable so exact-+ # head Chromium can measure semantics, theme reach, RTL order, and reflow.+ - name: Run CommandPaletteFooter audit browser evidence+ if: github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] CommandPaletteFooter:')+ 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-footer-a11y-report.json \+ --components CommandPaletteFooter \+ --baseline .github/a11y-baseline.json \+ --fail-on-new+ pnpm exec playwright test \+ packages/core/src/CommandPalette/__tests__/CommandPaletteFooter.a11y.chromium.spec.ts \+ --project chromium++ - name: Upload CommandPaletteFooter audit evidence+ if: always() && github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] CommandPaletteFooter:')+ uses: actions/upload-artifact@v7+ with:+ name: command-palette-footer-audit-evidence-${{ needs.build-storybook.outputs.short_hash }}+ path: |+ command-palette-footer-a11y-report.json+ test-results/command-palette-footer-audit-evidence/+ retention-days: 30+ if-no-files-found: error+# CollapsibleGroup's shared Collapsible story previously left the audit# owner with no routable browser fixture. Its dedicated matrix now emits# semantic-state, geometry, direction, theme, and viewport receipts.diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.jsonindex b6beb3d608..0bec104343 100644--- a/apps/storybook/rtl-audit/targets.json+++ b/apps/storybook/rtl-audit/targets.json@@ -501,5 +501,14 @@"prev": ".astryx-avatar-group > .astryx-avatar:first-child","next": ".astryx-avatar-group-overflow"}+ },+ {+ "component": "CommandPaletteFooter",+ "storyId": "core-commandpalettefooter--default",+ "dims": ["D2"],+ "selectors": {+ "prev": ".astryx-command-palette-footer > span:first-child",+ "next": ".astryx-command-palette-footer > span:last-child"+ }}]diff --git a/apps/storybook/stories/CommandPaletteFooter.stories.tsx b/apps/storybook/stories/CommandPaletteFooter.stories.tsxnew file mode 100644index 0000000000..66b2d0017d--- /dev/null+++ b/apps/storybook/stories/CommandPaletteFooter.stories.tsx@@ -0,0 +1,86 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {useMemo} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {+ CommandPalette,+ CommandPaletteFooter,+} from '@astryxdesign/core/CommandPalette';+import {createStaticSource} from '@astryxdesign/core/Typeahead';+import {InternationalizationProvider} from '@astryxdesign/core/i18n';++const meta: Meta<typeof CommandPaletteFooter> = {+ title: 'Core/CommandPaletteFooter',+ component: CommandPaletteFooter,+ tags: ['autodocs', 'visual-theme-matrix'],+ parameters: {+ layout: 'centered',+ docs: {story: {inline: false, height: '600px'}},+ },+};++export default meta;+type Story = StoryObj<typeof meta>;++function Palette({+ customFooter,+ expandedText = false,+}: {+ customFooter: boolean;+ expandedText?: boolean;+}) {+ const source = useMemo(+ () =>+ createStaticSource([+ {id: 'home', label: 'Go home'},+ {id: 'settings', label: 'Open settings'},+ ]),+ [],+ );+ const palette = (+ <CommandPalette+ isOpen+ onOpenChange={() => {}}+ searchSource={source}+ footer={+ customFooter ? (+ <CommandPaletteFooter>+ Type to filter available commands.+ </CommandPaletteFooter>+ ) : undefined+ }+ />+ );+ if (!expandedText) {+ return palette;+ }+ return (+ <InternationalizationProvider+ locale="fr"+ overrides={{+ fr: {+ '@astryx.commandPalette.footer.navigate': 'Parcourir les commandes',+ '@astryx.commandPalette.footer.select': 'Sélectionner la commande',+ '@astryx.commandPalette.footer.close':+ 'Fermer la palette de commandes',+ },+ }}>+ {palette}+ </InternationalizationProvider>+ );+}++/** The built-in CommandPalette branch with translated keyboard guidance. */+export const Default: Story = {+ render: () => <Palette customFooter={false} />,+};++/** A caller-provided footer replaces the built-in guidance in the real slot. */+export const CustomContent: Story = {+ render: () => <Palette customFooter />,+};++/** Expanded translated labels expose narrow-screen wrapping regressions. */+export const ExpandedText: Story = {+ render: () => <Palette customFooter={false} expandedText />,+};diff --git a/packages/core/src/CommandPalette/CommandPalette.spec.md b/packages/core/src/CommandPalette/CommandPalette.spec.mdindex 3073331946..810cc9b1ac 100644--- a/packages/core/src/CommandPalette/CommandPalette.spec.md+++ b/packages/core/src/CommandPalette/CommandPalette.spec.md@@ -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__/CommandPaletteFooter.a11y.chromium.spec.ts,packages/core/src/theme/themingTargets.test.ts,scripts/check-knowledge.mjs,]@@ -78,12 +79,12 @@ 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 coverage is partial |-| 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 |+| 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 |### Allowed variation@@ -191,18 +192,18 @@ current audit gap and does not authorize a new target.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |-| FR1 | CommandPalette root and subcomponent render suites plus source inspection | Default, grouped, empty, pending, and replaced slots | Removing the asserted Dialog, Query field, List, Item, Group, Group heading, Empty, or Footer content fails existing role, content, or slot assertions; Search glyph, Loading spinner, and Keyboard shortcut presence remain source-inspected only. | `audit:CommandPalette/anatomy` |-| FR2 | Source inspection, `themingTargets.test.ts`, and `CommandPaletteGroup.test.tsx` | Seven local targets; Group and Group heading placement | Removing a current target fails the global inventory; moving Group or Group heading fails focused class assertions. | `audit:CommandPalette/theming` |-| FR3 | Source inspection plus Dialog, Icon, Spinner, and Kbd public target metadata | Default surface, Input visuals, and Footer shortcuts | Existing focused tests do not assert the composed Icon, Spinner, or Kbd instances; changing delegated ownership requires this map and the delegated component metadata to change. | `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` |+| 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 currently cover Group and Group heading.-Input, List, Item, Empty, and Footer placement rely on source inspection plus the-global target inventory. Existing tests assert default Footer text and pending-announcements, but do not assert that Icon, Spinner, or Kbd renders.+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.## Decision log@@ -213,9 +214,9 @@ 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, pending Loading- spinner, and default Footer Keyboard shortcuts?** (`checkable`) Their presence- is currently source-inspected rather than asserted.+- **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/CommandPaletteFooter.doc.mjs b/packages/core/src/CommandPalette/CommandPaletteFooter.doc.mjsindex 26060ae754..d629aad730 100644--- a/packages/core/src/CommandPalette/CommandPaletteFooter.doc.mjs+++ b/packages/core/src/CommandPalette/CommandPaletteFooter.doc.mjs@@ -7,26 +7,51 @@ export const docs = {subComponentOf: 'CommandPalette',displayName: 'Command Palette Footer',isHiddenFromOverview: true,- description: 'Footer showing keyboard navigation hints. Renders default arrow/Enter/Escape hints when no children are provided.',+ description:+ 'Footer with keyboard guidance. CommandPalette renders the default arrow, Enter, and Escape hints automatically.',+ usage: {+ description:+ 'CommandPalette renders CommandPaletteFooter automatically. Pass a CommandPaletteFooter to the footer slot only when replacing the default guidance.',+ anatomy: [+ {+ name: 'Footer',+ required: true,+ description:+ 'Supporting region that presents default guidance or caller-provided footer content.',+ },+ {+ name: 'Keyboard shortcut',+ required: false,+ description:+ 'Default Kbd badges for navigation, selection, and dismissal.',+ },+ ],+ },props: [{name: 'children',type: 'ReactNode',- description: 'Custom footer content. When omitted, renders default keyboard hints via Kbd.',+ description:+ 'Custom footer content. When omitted, renders default keyboard hints via Kbd.',},{name: 'xstyle',type: 'StyleXStyles',- description: 'StyleX styles for layout customization. Must be a stylex.create() value.',+ description:+ 'StyleX styles for layout customization. Must be a stylex.create() value.',},],+ theming: {+ targets: [{className: 'astryx-command-palette-footer'}],+ },};export const docsZh = {name: 'CommandPaletteFooter',isHiddenFromOverview: true,displayName: 'Command Palette Footer',- description: '显示键盘导航提示的页脚。未提供子元素时渲染默认方向键/Enter/Escape 提示。',+ description:+ '显示键盘导航提示的页脚。未提供子元素时渲染默认方向键/Enter/Escape 提示。',propDescriptions: {children: '自定义页脚内容。省略时通过 Kbd 渲染默认键盘提示。',xstyle: 'StyleX 布局自定义样式。必须是 stylex.create() 的值。',diff --git a/packages/core/src/CommandPalette/CommandPaletteFooter.test.tsx b/packages/core/src/CommandPalette/CommandPaletteFooter.test.tsxindex ee6147c099..a87bd33978 100644--- a/packages/core/src/CommandPalette/CommandPaletteFooter.test.tsx+++ b/packages/core/src/CommandPalette/CommandPaletteFooter.test.tsx@@ -2,36 +2,121 @@/*** @file CommandPaletteFooter.test.tsx- * @input Uses vitest, @testing-library/react- * @output Unit tests for CommandPaletteFooter+ * @input Uses Vitest, Testing Library, StyleX declaration helpers+ * @output Mutation-sensitive tests for default/custom content and BaseProps+ * @position Colocated unit coverage for the CommandPalette footer contract*/-import {describe, it, expect} from 'vitest';+import {createRef, type ReactElement} from 'react';+import * as stylex from '@stylexjs/stylex';+import {describe, expect, it} from 'vitest';import {render, screen} from '@testing-library/react';+import {declaredValue} from '../__tests__/stylexDeclarations';import {CommandPaletteFooter} from './CommandPaletteFooter';+const testStyles = stylex.create({+ wide: {width: '999px'},+});++/** CommandPaletteFooter renders exactly one root element. */+function renderRoot(ui: ReactElement): HTMLElement {+ const {container} = render(ui);+ return container.firstElementChild as HTMLElement;+}+describe('CommandPaletteFooter', () => {- it('renders default keyboard hints', () => {- render(<CommandPaletteFooter />);- expect(screen.getByText(/Navigate/)).toBeInTheDocument();- expect(screen.getByText(/Select/)).toBeInTheDocument();- expect(screen.getByText(/Close/)).toBeInTheDocument();+ it('renders the default labels through four accessible Kbd targets', () => {+ const root = renderRoot(<CommandPaletteFooter />);+ const shortcuts = screen.getAllByRole('img');++ expect(root.textContent).toContain('Navigate');+ expect(root.textContent).toContain('Select');+ expect(root.textContent).toContain('Close');+ expect(shortcuts.map(node => node.getAttribute('aria-label'))).toEqual([+ 'Up arrow',+ 'Down arrow',+ 'Enter',+ 'Escape',+ ]);+ expect(shortcuts).toHaveLength(4);+ expect(shortcuts.every(node => node.classList.contains('astryx-kbd'))).toBe(+ true,+ );+ expect(root.querySelectorAll('kbd')).toHaveLength(4);});- it('renders custom children instead of defaults', () => {- render(+ it('renders custom children instead of the default hints', () => {+ const root = renderRoot(<CommandPaletteFooter><span>Custom footer content</span></CommandPaletteFooter>,);- expect(screen.getByText('Custom footer content')).toBeInTheDocument();- expect(screen.queryByText(/Navigate/)).not.toBeInTheDocument();++ expect(root.textContent).toBe('Custom footer content');+ expect(screen.queryByRole('img')).not.toBeInTheDocument();+ expect(root.textContent).not.toContain('Navigate');});- it('renders a single root element (separator is CSS border, not a DOM node)', () => {- const {container} = render(<CommandPaletteFooter />);- // The top separator is a borderBlockStart CSS property — no extra DOM node.- expect(container.firstChild).toBeInTheDocument();+ it('carries the stable theme target on its single root', () => {+ const root = renderRoot(<CommandPaletteFooter />);++ expect(root.tagName).toBe('DIV');+ expect(root.className.split(' ')).toContain(+ 'astryx-command-palette-footer',+ );expect(screen.queryByRole('separator')).not.toBeInTheDocument();});++ it('allows translated guidance groups to wrap on narrow surfaces', () => {+ const root = renderRoot(<CommandPaletteFooter />);++ expect(declaredValue(root, 'flex-wrap')).toBe('wrap');+ });++ it('appends a consumer className after generated classes', () => {+ const base = renderRoot(<CommandPaletteFooter />).className.split(' ');+ const withCustom = renderRoot(+ <CommandPaletteFooter className="my-footer" />,+ ).className.split(' ');++ expect(withCustom).toEqual([...base, 'my-footer']);+ });++ it('merges xstyle into the root styles', () => {+ const root = renderRoot(<CommandPaletteFooter xstyle={testStyles.wide} />);++ expect(declaredValue(root, 'width')).toBe('999px');+ });++ it('applies a consumer style to the root', () => {+ const root = renderRoot(+ <CommandPaletteFooter style={{marginBlockStart: '8px'}} />,+ );++ expect(root).toHaveStyle({marginBlockStart: '8px'});+ });++ it('forwards ref to the root', () => {+ const ref = createRef<HTMLDivElement>();+ const root = renderRoot(<CommandPaletteFooter ref={ref} />);++ expect(ref.current).toBe(root);+ });++ it('forwards arbitrary DOM props to the root', () => {+ const root = renderRoot(+ <CommandPaletteFooter+ id="palette-footer"+ data-kind="default"+ role="contentinfo"+ aria-label="Command shortcuts"+ />,+ );++ expect(root.id).toBe('palette-footer');+ expect(root).toHaveAttribute('data-kind', 'default');+ expect(screen.getByRole('contentinfo', {name: 'Command shortcuts'})).toBe(+ root,+ );+ });});diff --git a/packages/core/src/CommandPalette/CommandPaletteFooter.tsx b/packages/core/src/CommandPalette/CommandPaletteFooter.tsxindex 1661380ca9..dce71a3b4f 100644--- a/packages/core/src/CommandPalette/CommandPaletteFooter.tsx+++ b/packages/core/src/CommandPalette/CommandPaletteFooter.tsx@@ -29,6 +29,7 @@ import {useTranslator} from '../i18n';const styles = stylex.create({footer: {display: 'flex',+ flexWrap: 'wrap',alignItems: 'center',gap: spacingVars['--spacing-4'],paddingInline: spacingVars['--spacing-4'],@@ -72,10 +73,13 @@ export interface CommandPaletteFooterProps extends BaseProps<HTMLDivElement> {* <CommandPalette* isOpen={isOpen}* onOpenChange={setIsOpen}- * input={<CommandPaletteInput />}- * footer={<CommandPaletteFooter />}>- * <CommandPaletteList>...</CommandPaletteList>- * </CommandPalette>+ * searchSource={source}+ * footer={+ * <CommandPaletteFooter>+ * Type to filter available commands.+ * </CommandPaletteFooter>+ * }+ * />* ```*/export function CommandPaletteFooter({diff --git a/packages/core/src/CommandPalette/__tests__/CommandPaletteFooter.a11y.chromium.spec.ts b/packages/core/src/CommandPalette/__tests__/CommandPaletteFooter.a11y.chromium.spec.tsnew file mode 100644index 0000000000..22515a696f--- /dev/null+++ b/packages/core/src/CommandPalette/__tests__/CommandPaletteFooter.a11y.chromium.spec.ts@@ -0,0 +1,581 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CommandPaletteFooter.a11y.chromium.spec.ts+ * @input Component-owned Storybook fixtures and exact-head build stamp+ * @output Chromium screenshots plus fail-closed semantic sensor receipts+ * @position Browser evidence for the CommandPaletteFooter 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 Browser, 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-footer-audit-evidence',+);+const DEFAULT_STORY = 'core-commandpalettefooter--default';+const CUSTOM_STORY = 'core-commandpalettefooter--custom-content';+const EXPANDED_STORY = 'core-commandpalettefooter--expanded-text';+const WIDE = {width: 1024, height: 720};+const NARROW = {width: 320, height: 720};++interface Case {+ state: string;+ storyId: string;+ kind: 'default' | 'custom';+ theme: 'neutral' | 'probe';+ mode: 'light' | 'dark';+ direction: 'ltr' | 'rtl';+ pointer?: 'coarse';+ viewport: {width: number; height: number};+}++const CASES: Case[] = [+ {+ state: 'default-neutral-light-ltr',+ storyId: DEFAULT_STORY,+ kind: 'default',+ theme: 'neutral',+ mode: 'light',+ direction: 'ltr',+ viewport: WIDE,+ },+ {+ state: 'default-neutral-dark-ltr',+ storyId: DEFAULT_STORY,+ kind: 'default',+ theme: 'neutral',+ mode: 'dark',+ direction: 'ltr',+ viewport: WIDE,+ },+ {+ state: 'default-probe-light-ltr',+ storyId: DEFAULT_STORY,+ kind: 'default',+ theme: 'probe',+ mode: 'light',+ direction: 'ltr',+ viewport: WIDE,+ },+ {+ state: 'default-probe-dark-ltr',+ storyId: DEFAULT_STORY,+ kind: 'default',+ theme: 'probe',+ mode: 'dark',+ direction: 'ltr',+ viewport: WIDE,+ },+ {+ state: 'default-neutral-light-rtl',+ storyId: DEFAULT_STORY,+ kind: 'default',+ theme: 'neutral',+ mode: 'light',+ direction: 'rtl',+ viewport: WIDE,+ },+ {+ state: 'default-neutral-light-narrow',+ storyId: DEFAULT_STORY,+ kind: 'default',+ theme: 'neutral',+ mode: 'light',+ direction: 'ltr',+ viewport: NARROW,+ },+ {+ state: 'expanded-neutral-light-narrow-coarse',+ storyId: EXPANDED_STORY,+ kind: 'default',+ theme: 'neutral',+ mode: 'light',+ direction: 'ltr',+ pointer: 'coarse',+ viewport: NARROW,+ },+ {+ state: 'custom-neutral-light-ltr',+ storyId: CUSTOM_STORY,+ kind: 'custom',+ theme: 'neutral',+ mode: 'light',+ direction: 'ltr',+ viewport: WIDE,+ },+ {+ state: 'custom-neutral-dark-ltr',+ storyId: CUSTOM_STORY,+ kind: 'custom',+ theme: 'neutral',+ mode: 'dark',+ direction: 'ltr',+ viewport: WIDE,+ },+];++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/CommandPaletteFooter',+ headSha: checkoutSha,+ storybookSha,+ browser: browserVersion,+ frames,+ stateVisualMatrix,+ contrastPairMatrix,+ },+ null,+ 2,+ )}\n`,+ );+ }+ await storybook?.close();+});++async function capture(page: Page, scenario: Case) {+ const pageErrors: string[] = [];+ const onError = (error: Error) => pageErrors.push(String(error));+ page.on('pageerror', onError);+ 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=${scenario.storyId}&viewMode=story&globals=colorMode:${scenario.mode};astryxTheme:${scenario.theme};direction:${scenario.direction}`,+ {waitUntil: 'load'},+ );+ const canvas = page.locator('#storybook-root');+ const dialog = page.getByRole('dialog').first();+ const subject = page.locator('.astryx-command-palette-footer');+ await canvas.waitFor();+ await dialog.waitFor();+ await subject.waitFor();+ await holdMotionStill(page);+ await page.evaluate(async () => document.fonts.ready);+ await page.waitForFunction(+ expected =>+ document.documentElement.getAttribute('data-theme') === expected,+ scenario.mode,+ );+ await page.evaluate(async () => {+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ );+ });++ const firstBox = await subject.boundingBox();+ await page.evaluate(async () => {+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ );+ });+ const box = await subject.boundingBox();+ if (firstBox == null || box == null) {+ throw new Error(`${scenario.state}: footer has no layout box`);+ }+ const geometryDelta = Math.max(+ Math.abs(box.x - firstBox.x),+ Math.abs(box.y - firstBox.y),+ Math.abs(box.width - firstBox.width),+ Math.abs(box.height - firstBox.height),+ );++ const observed = await subject.evaluate(element => {+ type Color = {r: number; g: number; b: number; a: number};+ 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 = (node: Element): Color => {+ const layers: Color[] = [];+ let current: Element | null = node;+ 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 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 a = luminance(left);+ const b = luminance(right);+ return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);+ };+ const formatColor = ({r, g, b, a}: Color) =>+ `rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${a.toFixed(3)})`;+ const pair = (node: Element) => {+ const style = getComputedStyle(node);+ const background = renderedBackground(node);+ const foreground = composite(parseColor(style.color), background);+ return {+ color: style.color,+ backgroundColor: style.backgroundColor,+ renderedBackdrop: formatColor(background),+ contrastRatio: Number(contrast(foreground, background).toFixed(2)),+ };+ };+ const rootStyle = getComputedStyle(element);+ const firstKbd = element.querySelector('kbd');+ const hintLabels = [...element.children].map(child =>+ [...child.childNodes]+ .filter(node => node.nodeType === Node.TEXT_NODE)+ .map(node => node.textContent ?? '')+ .join('')+ .trim(),+ );+ const hintCenters = [...element.children].map(child => {+ const rect = child.getBoundingClientRect();+ return rect.x + rect.width / 2;+ });+ return {+ role: element.getAttribute('role'),+ ariaLabel: element.getAttribute('aria-label'),+ text: (element as HTMLElement).innerText.trim(),+ direction: rootStyle.direction,+ display: rootStyle.display,+ fontFamily: rootStyle.fontFamily,+ fontSize: rootStyle.fontSize,+ lineHeight: rootStyle.lineHeight,+ gap: rootStyle.gap,+ paddingInlineStart: rootStyle.paddingInlineStart,+ paddingBlockStart: rootStyle.paddingBlockStart,+ targetPresent: element.classList.contains(+ 'astryx-command-palette-footer',+ ),+ kbdTargetCount: element.querySelectorAll('.astryx-kbd').length,+ shortcutNames: [...element.querySelectorAll('[role="img"]')].map(node =>+ node.getAttribute('aria-label'),+ ),+ hintLabels,+ hintCenters,+ clientWidth: (element as HTMLElement).clientWidth,+ scrollWidth: (element as HTMLElement).scrollWidth,+ rootPair: pair(element),+ kbdPair: firstKbd ? pair(firstKbd) : null,+ };+ });+ const environment = await page.evaluate(() => ({+ theme: document+ .querySelector('[data-astryx-theme]')+ ?.getAttribute('data-astryx-theme'),+ mode: document.documentElement.getAttribute('data-theme'),+ colorScheme: getComputedStyle(document.documentElement).colorScheme,+ fonts: document.fonts.status,+ viewport: {width: innerWidth, height: innerHeight},+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,+ coarsePointer: matchMedia('(pointer: coarse)').matches,+ forcedColors: matchMedia('(forced-colors: active)').matches,+ horizontalOverflow: document.documentElement.scrollWidth > innerWidth + 1,+ storyError: [+ ...document.querySelectorAll(+ '.sb-errordisplay, [data-testid="story-error"]',+ ),+ ].some(node => {+ const rect = node.getBoundingClientRect();+ const style = getComputedStyle(node);+ return (+ rect.width > 0 &&+ rect.height > 0 &&+ style.display !== 'none' &&+ style.visibility !== 'hidden'+ );+ }),+ }));++ await expect(dialog).toBeVisible();+ await expect(subject).toHaveCount(1);+ await expect(subject).toBeVisible();+ expect(observed.role).toBeNull();+ expect(observed.ariaLabel).toBeNull();+ expect(observed.direction).toBe(scenario.direction);+ expect(observed.display).toBe('flex');+ expect(observed.targetPresent).toBe(true);+ expect(observed.rootPair.contrastRatio).toBeGreaterThanOrEqual(4.5);+ expect(observed.scrollWidth).toBeLessThanOrEqual(observed.clientWidth + 1);+ expect(box.width).toBeGreaterThan(0);+ expect(box.height).toBeGreaterThan(0);+ expect(box.width).toBeLessThanOrEqual(scenario.viewport.width);+ expect(geometryDelta).toBeLessThanOrEqual(0.5);+ expect(environment.theme).toBe(scenario.theme);+ expect(environment.mode).toBe(scenario.mode);+ expect(environment.colorScheme).toBe(scenario.mode);+ expect(environment.fonts).toBe('loaded');+ expect(environment.viewport).toEqual(scenario.viewport);+ expect(environment.reducedMotion).toBe(true);+ expect(environment.coarsePointer).toBe(scenario.pointer === 'coarse');+ expect(environment.forcedColors).toBe(false);+ expect(environment.horizontalOverflow).toBe(false);+ expect(environment.storyError).toBe(false);+ expect(pageErrors).toEqual([]);++ if (scenario.kind === 'default') {+ const expectedLabels =+ scenario.storyId === EXPANDED_STORY+ ? [+ 'Parcourir les commandes',+ 'Sélectionner la commande',+ 'Fermer la palette de commandes',+ ]+ : ['Navigate', 'Select', 'Close'];+ expect(observed.hintLabels).toEqual(expectedLabels);+ expect(observed.shortcutNames).toEqual([+ 'Up arrow',+ 'Down arrow',+ 'Enter',+ 'Escape',+ ]);+ expect(observed.kbdTargetCount).toBe(4);+ expect(observed.hintCenters).toHaveLength(3);+ if (scenario.viewport.width > NARROW.width) {+ if (scenario.direction === 'rtl') {+ expect(observed.hintCenters[0]).toBeGreaterThan(+ observed.hintCenters[2] ?? 0,+ );+ } else {+ expect(observed.hintCenters[0]).toBeLessThan(+ observed.hintCenters[2] ?? Number.POSITIVE_INFINITY,+ );+ }+ }+ } else {+ expect(observed.text).toBe('Type to filter available commands.');+ expect(observed.shortcutNames).toEqual([]);+ expect(observed.kbdTargetCount).toBe(0);+ }++ const file = `CommandPaletteFooter__${scenario.state}.png`;+ const png = await dialog.screenshot({animations: 'disabled'});+ expect(png.length).toBeGreaterThan(100);+ const representation =+ scenario.kind === 'default'+ ? 'Three keyboard-hint groups with four delegated Kbd badges'+ : 'Caller footer content replaces the default keyboard hints';+ const stateVisualRows = [+ {+ stateCaptured: `${scenario.kind} footer at rest`,+ screenshot: file,+ approvedRepresentation: representation,+ tokenSignature:+ 'supporting typography, secondary text, logical padding, delegated Kbd badges',+ tokenSignaturePresent: true,+ matchesReference: 'yes',+ verdict: 'pass',+ },+ ];+ const contrastRows = [+ {+ screenshot: file,+ theme: scenario.theme,+ mode: scenario.mode,+ direction: scenario.direction,+ viewport: scenario.viewport,+ part: 'footer guidance text',+ state: scenario.kind,+ meaningful: true,+ foreground: observed.rootPair.color,+ renderedBackdrop: observed.rootPair.renderedBackdrop,+ ratio: observed.rootPair.contrastRatio,+ threshold: 4.5,+ exception: null,+ passed: true,+ },+ ...(observed.kbdPair+ ? [+ {+ screenshot: file,+ theme: scenario.theme,+ mode: scenario.mode,+ direction: scenario.direction,+ viewport: scenario.viewport,+ part: 'keyboard badge glyph',+ state: scenario.kind,+ meaningful: true,+ foreground: observed.kbdPair.color,+ renderedBackdrop: observed.kbdPair.renderedBackdrop,+ ratio: observed.kbdPair.contrastRatio,+ threshold: 4.5,+ exception:+ 'Known shared Kbd contrast gap; tracked by facebook/astryx#7097 and not scored against CommandPaletteFooter.',+ passed: observed.kbdPair.contrastRatio >= 4.5,+ },+ ]+ : []),+ ];+ const receipt = {+ expected: {+ build: checkoutSha,+ storyId: scenario.storyId,+ captureRoot: '[role="dialog"]',+ theme: scenario.theme,+ mode: scenario.mode,+ direction: scenario.direction,+ pointer: scenario.pointer ?? 'fine',+ viewport: scenario.viewport,+ kind: scenario.kind,+ dialogCount: 1,+ footerCount: 1,+ },+ observed: {+ build: storybookSha,+ storyId: scenario.storyId,+ dialogCount: await page.getByRole('dialog').count(),+ ...observed,+ ...environment,+ pageErrors: pageErrors.length,+ geometry: box,+ settledRender: {initial: firstBox, final: box, maxDelta: geometryDelta},+ },+ image: {+ file,+ sha256: createHash('sha256').update(png).digest('hex'),+ width: png.readUInt32BE(16),+ height: png.readUInt32BE(20),+ },+ stateVisualMatrix: stateVisualRows,+ contrastPairMatrix: contrastRows,+ knownFinding:+ observed.kbdPair && observed.kbdPair.contrastRatio < 4.5+ ? 'Delegated Kbd glyph contrast is tracked by facebook/astryx#7097; the shared primitive owns the token pair.'+ : null,+ 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, receipt: `${file}.sensors.json`});+ stateVisualMatrix.push(...stateVisualRows);+ contrastPairMatrix.push(...contrastRows);+ return observed;+ } finally {+ page.off('pageerror', onError);+ }+}++test('captures default and custom footer branches with sensor receipts', async ({+ browser,+}: {+ browser: Browser;+}) => {+ const results = new Map<string, Awaited<ReturnType<typeof capture>>>();+ for (const scenario of CASES) {+ const context = await browser.newContext({+ viewport: scenario.viewport,+ hasTouch: scenario.pointer === 'coarse',+ });+ const page = await context.newPage();+ try {+ results.set(scenario.state, await capture(page, scenario));+ } finally {+ await context.close();+ }+ }+ const neutral = results.get('default-neutral-light-ltr');+ const probe = results.get('default-probe-light-ltr');+ expect(neutral).toBeDefined();+ expect(probe).toBeDefined();+ expect(+ probe?.rootPair.backgroundColor !== neutral?.rootPair.backgroundColor ||+ probe?.rootPair.color !== neutral?.rootPair.color,+ 'the probe theme must visibly reach the footer target',+ ).toBe(true);+});