An open source design system that's fully customizable and agent ready
TypeScript
[Component Audit] Kbd: key badges grow with larger text (#10267)
Cindy Zhang6d0940f22596
diff --git a/.changeset/kbd-grows-with-text.md b/.changeset/kbd-grows-with-text.mdnew file mode 100644index 0000000000..70ad6a82ee--- /dev/null+++ b/.changeset/kbd-grows-with-text.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `Kbd`: a key badge grows with a larger text size instead of holding its fixed height, so a bigger glyph stays inside its badge. At the default text size nothing changes. The docs now list `ref`, say how a screen reader names the shortcut, and say that Kbd only shows keys and does not listen for them.++@cixzhangdiff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.jsonindex f14fd728b6..f3183df8ad 100644--- a/apps/storybook/rtl-audit/verified-not-applicable.json+++ b/apps/storybook/rtl-audit/verified-not-applicable.json@@ -443,5 +443,14 @@"packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx": "sha256:7d7ce618b802170660763de820c0551fc3c63530ba1c105cb4bf7146d30ad518","packages/core/src/DropdownMenu/index.ts": "sha256:59bf02be4a577cbecf3ad7e981e2577602375892f74548593aa9b998cae733fa"}+ },+ {+ "component": "core/Kbd",+ "reason": "Kbd renders one inline-flex group of key badges in the order the caller writes the keys, from inline start to inline end with a logical gap, so the sequence follows the region's direction (design:bidirectionality DR3). Its arrow badges name physical keys, so they stay unchanged (DR5): the left key shows ← in both directions, and the arrow glyphs are not Bidi_Mirrored. It draws no contextual separator, uses no physical inline property, and has no positioned affordance, scroll, drag, overlay, or keyboard behavior. Exact-head frames render the group in RTL and assert each badge's direction and inline order, and that every glyph keeps its text and has no transform.",+ "evidence": {+ "apps/storybook/stories/Kbd.stories.tsx": "sha256:b6770be1b6481064d541e9e9f9a75c3e5e0225aed6da242329c64e8102e03440",+ "packages/core/src/Kbd/Kbd.tsx": "sha256:e64111634e63600c9a145f18b6e3e2a947bf3b39185ffbdffb0db3578d5e4f24",+ "packages/core/src/Kbd/index.ts": "sha256:9e1e3942034e17a48c67b4a46161e8c44af9c16360a8d42e5fbb570135a975c2"+ }}]diff --git a/apps/storybook/stories/Kbd.stories.tsx b/apps/storybook/stories/Kbd.stories.tsxindex c6891f0c4b..bee2330b00 100644--- a/apps/storybook/stories/Kbd.stories.tsx+++ b/apps/storybook/stories/Kbd.stories.tsx@@ -270,3 +270,34 @@ export const MenuShortcuts: Story = {</div>),};++// =============================================================================+// Larger Text+// =============================================================================++type LargerTextRow = React.CSSProperties & {'--text-supporting-size'?: string};++export const LargerText: Story = {+ name: 'Larger text',+ render: () => (+ <div style={{display: 'flex', flexDirection: 'column', gap: '16px'}}>+ {['default', '1.25rem', '2.5rem'].map(size => {+ const row: LargerTextRow = {+ display: 'flex',+ flexWrap: 'wrap',+ gap: '16px',+ alignItems: 'center',+ ...(size === 'default' ? null : {'--text-supporting-size': size}),+ };+ return (+ <div key={size} data-testid={`kbd-row-${size}`} style={row}>+ <Kbd keys="mod+k" />+ <Kbd keys="shift+enter" />+ <Kbd keys="esc" />+ <Kbd keys="up" />+ </div>+ );+ })}+ </div>+ ),+};diff --git a/packages/core/src/Kbd/Kbd.doc.mjs b/packages/core/src/Kbd/Kbd.doc.mjsindex c8e142a1b3..d254603405 100644--- a/packages/core/src/Kbd/Kbd.doc.mjs+++ b/packages/core/src/Kbd/Kbd.doc.mjs@@ -15,6 +15,15 @@ const anatomy = [},];+/** @type {import('@astryxdesign/cli/authoring').ComponentBestPractice[]} */+const bestPractices = [+ { guidance: true, description: 'Place shortcuts near the action they trigger: in a tooltip, menu item, or inline instruction.' },+ { guidance: true, description: 'Use mod instead of ctrl or cmd; it automatically adapts to the user\'s platform.' },+ { guidance: true, description: 'Let Kbd name the shortcut: screen readers hear the keys as words, such as "Command + K". Kbd ignores an aria-label you pass; to name it from visible text, use aria-labelledby.' },+ { guidance: false, description: 'Use Kbd as the only way to discover an action; shortcuts should supplement visible controls, not replace them.' },+ { guidance: false, description: 'Expect Kbd to handle the key press. It only shows the keys; listen for the shortcut in your own code.' },+];+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */export const docs = {@@ -34,7 +43,7 @@ export const docs = {name: 'xstyle',type: 'StyleXStyles',description:- 'StyleX styles for layout customization (margins, positioning, sizing). Must be a stylex.create() value, not an inline style object like style={{}}.',+ 'StyleX styles for layout customization (margins, positioning, sizing). Must be a stylex.create() value: not an inline style object like style={{}}.',},{name: 'className',@@ -48,6 +57,11 @@ export const docs = {description:'Inline styles for the root element. Prefer xstyle for styling; inline styles bypass StyleX optimization.',},+ {+ name: 'ref',+ type: 'React.Ref<HTMLSpanElement>',+ description: 'Ref forwarded to the shortcut group element.',+ },],theming: {targets: [{className: 'astryx-kbd'}],@@ -55,11 +69,7 @@ export const docs = {usage: {anatomy,description: 'Renders a keyboard shortcut as styled key badges. Use Kbd in tooltips, menus, and help text to show key combinations.',- bestPractices: [- { guidance: true, description: 'Place shortcuts near the action they trigger: in a tooltip, menu item, or inline instruction.' },- { guidance: true, description: 'Use mod instead of ctrl or cmd; it automatically adapts to the user\'s platform.' },- { guidance: false, description: 'Use Kbd as the only way to discover an action; shortcuts should supplement visible controls, not replace them.' },- ],+ bestPractices,},};@@ -93,6 +103,11 @@ export const docsZh = {description:'根元素的内联样式。建议优先使用 xstyle 进行样式设置,内联样式会绕过 StyleX 优化。',},+ {+ name: 'ref',+ type: 'React.Ref<HTMLSpanElement>',+ description: '转发到快捷键组元素的 ref。',+ },],theming: {targets: [{className: 'astryx-kbd'}],@@ -100,11 +115,7 @@ export const docsZh = {usage: {anatomy,description: 'Renders a keyboard shortcut as styled key badges. Use Kbd in tooltips, menus, and help text to show key combinations.',- bestPractices: [- { guidance: true, description: 'Place shortcuts near the action they trigger: in a tooltip, menu item, or inline instruction.' },- { guidance: true, description: 'Use mod instead of ctrl or cmd; it automatically adapts to the user\'s platform.' },- { guidance: false, description: 'Use Kbd as the only way to discover an action; shortcuts should supplement visible controls, not replace them.' },- ],+ bestPractices,},};@@ -115,16 +126,13 @@ export const docsDense = {usage: {anatomy,description: 'Renders a keyboard shortcut as styled key badges. Use Kbd in tooltips, menus, and help text to show key combinations.',- bestPractices: [- { guidance: true, description: 'Place shortcuts near the action they trigger: in a tooltip, menu item, or inline instruction.' },- { guidance: true, description: 'Use mod instead of ctrl or cmd; it automatically adapts to the user\'s platform.' },- { guidance: false, description: 'Use Kbd as the only way to discover an action; shortcuts should supplement visible controls, not replace them.' },- ],+ bestPractices,},propDescriptions: {keys: 'Shortcut string. "+" separates keys. Special: mod (Cmd on Mac), ctrl, alt, shift, enter, backspace, escape, tab, up, down, left, right, plus. Aliases: esc for escape, return for enter.',xstyle: 'StyleX styles for layout customization. Must be stylex.create() value.',className: 'CSS class for root element. Prefer xstyle; className for non-StyleX integration.',style: 'Inline styles for root element. Prefer xstyle; inline styles bypass StyleX optimization.',+ ref: 'Ref forwarded to shortcut group element.',},};diff --git a/packages/core/src/Kbd/Kbd.test.tsx b/packages/core/src/Kbd/Kbd.test.tsxindex 0120b9ff0c..9d9a19df77 100644--- a/packages/core/src/Kbd/Kbd.test.tsx+++ b/packages/core/src/Kbd/Kbd.test.tsx@@ -9,7 +9,8 @@* so `mod` resolves to "Ctrl" rather than "\u2318" after the layout effect.*/-import {render, screen} from '@testing-library/react';+import {render, screen, within} from '@testing-library/react';+import {renderToString} from 'react-dom/server';import {describe, it, expect, afterEach, vi} from 'vitest';import {Kbd} from './Kbd';import {InternationalizationProvider} from '../i18n';@@ -69,6 +70,51 @@ describe('Kbd', () => {expect(screen.getByText('\u21B5')).toBeInTheDocument(); // \u21B5});+ it.each([+ {key: 'backspace', glyph: '\u232B', label: 'Backspace'},+ {key: 'tab', glyph: '\u21E5', label: 'Tab'},+ {key: 'up', glyph: '\u2191', label: 'Up arrow'},+ {key: 'down', glyph: '\u2193', label: 'Down arrow'},+ {key: 'left', glyph: '\u2190', label: 'Left arrow'},+ {key: 'right', glyph: '\u2192', label: 'Right arrow'},+ ])('shows the $key symbol and speaks its name', ({key, glyph, label}) => {+ render(<Kbd keys={key} />);+ expect(screen.getByText(glyph)).toBeInTheDocument();+ expect(screen.getByRole('img')).toHaveAccessibleName(label);+ });++ it('renders Ctrl and the Control name on the server, even on a Mac', () => {+ Object.defineProperty(navigator, 'platform', {+ value: 'MacIntel',+ configurable: true,+ });+ const container = document.createElement('div');+ container.innerHTML = renderToString(<Kbd keys="mod+k" />);+ document.body.appendChild(container);+ try {+ expect(within(container).getByText('Ctrl')).toBeInTheDocument();+ expect(within(container).queryByText('\u2318')).not.toBeInTheDocument();+ expect(within(container).getByRole('img')).toHaveAccessibleName(+ 'Control + K',+ );+ } finally {+ container.remove();+ }+ });++ it('puts the kbd theme target on the shortcut only, not on a key badge', () => {+ render(<Kbd keys="mod+shift+k" />);+ const shortcut = screen.getByRole('img');+ expect(shortcut).toHaveClass('astryx-kbd');+ const badges = Array.from(shortcut.querySelectorAll('kbd'));+ expect(badges).toHaveLength(3);+ badges.forEach(badge =>+ expect(+ Array.from(badge.classList).filter(name => name.startsWith('astryx-')),+ ).toEqual([]),+ );+ });+it('renders escape as text', () => {render(<Kbd keys="escape" />);expect(screen.getByText('Esc')).toBeInTheDocument();diff --git a/packages/core/src/Kbd/Kbd.tsx b/packages/core/src/Kbd/Kbd.tsxindex 5a7deaf80e..037d05bfbe 100644--- a/packages/core/src/Kbd/Kbd.tsx+++ b/packages/core/src/Kbd/Kbd.tsx@@ -49,6 +49,9 @@ const styles = stylex.create({justifyContent: 'center',minWidth: spacingVars['--spacing-5'],height: spacingVars['--spacing-5'],+ // The theme height holds while one line of text fits. A taller line+ // grows the badge.+ minHeight: '1lh',paddingInline: spacingVars['--spacing-1'],borderRadius: radiusVars['--radius-inner'],backgroundColor: colorVars['--color-neutral'],diff --git a/packages/core/src/Kbd/__tests__/KbdAudit.a11y.chromium.spec.ts b/packages/core/src/Kbd/__tests__/KbdAudit.a11y.chromium.spec.tsnew file mode 100644index 0000000000..3c1b110e8e--- /dev/null+++ b/packages/core/src/Kbd/__tests__/KbdAudit.a11y.chromium.spec.ts@@ -0,0 +1,610 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y audit Kbd++/**+ * @file KbdAudit.a11y.chromium.spec.ts+ * @input Exact-head Core/Kbd stories across themes, modes, text sizes, direction, and width+ * @output Screenshots and fail-closed sensor receipts for the Kbd whole-component audit+ * @position Component-owned Night Watch browser evidence; CI runs it only for a Kbd 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 {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++const OUTPUT = path.resolve('kbd-audit-evidence');+const WIDE = {width: 640, height: 400};+const TALL = {width: 640, height: 640};+const NARROW = {width: 320, height: 400};++type Mode = 'light' | 'dark';+type Theme = 'neutral' | 'butter';+type Direction = 'ltr' | 'rtl';+type Story =+ | 'modifier-combinations'+ | 'special-keys'+ | 'larger-text'+ | 'inline-with-text'+ | 'menu-shortcuts';++type AuditCase = {+ key: string;+ story: Story;+ mode: Mode;+ theme: Theme;+ direction: Direction;+ viewport: {width: number; height: number};+};++type AuditReceipt = {+ passed: boolean;+ expected: Record<string, unknown>;+ failures: string[];+};++// What each story shows, in document order: the visible text of every+// badge, then the spoken name of every shortcut. The CI browser is not an+// Apple platform, so `mod` shows "Ctrl" and is spoken "Control".+const GLYPHS: Record<Story, string[]> = {+ 'modifier-combinations': ['Ctrl', 'K', '⇧', '↵', '⌃', 'C', '⌥', '⇥'],+ 'special-keys': [+ 'Esc',+ 'Esc',+ '↵',+ '↵',+ '⌫',+ '⇥',+ 'SPACE',+ '↑',+ '↓',+ '←',+ '→',+ ],+ 'larger-text': [0, 1, 2].flatMap(() => ['Ctrl', 'K', '⇧', '↵', 'Esc', '↑']),+ 'inline-with-text': ['Ctrl', 'K', 'Ctrl', '⇧', 'P', 'Esc', '↑', '↓', '↵'],+ 'menu-shortcuts': [+ 'Ctrl',+ 'X',+ 'Ctrl',+ 'C',+ 'Ctrl',+ 'V',+ 'Ctrl',+ 'Z',+ 'Ctrl',+ '⇧',+ 'Z',+ ],+};+const NAMES: Record<Story, string[]> = {+ 'modifier-combinations': [+ 'Control + K',+ 'Shift + Enter',+ 'Control + C',+ 'Alt + Tab',+ ],+ 'special-keys': [+ 'Escape',+ 'Escape',+ 'Enter',+ 'Enter',+ 'Backspace',+ 'Tab',+ 'SPACE',+ 'Up arrow',+ 'Down arrow',+ 'Left arrow',+ 'Right arrow',+ ],+ 'larger-text': [0, 1, 2].flatMap(() => [+ 'Control + K',+ 'Shift + Enter',+ 'Escape',+ 'Up arrow',+ ]),+ 'inline-with-text': [+ 'Control + K',+ 'Control + Shift + P',+ 'Escape',+ 'Up arrow',+ 'Down arrow',+ 'Enter',+ ],+ 'menu-shortcuts': [+ 'Control + X',+ 'Control + C',+ 'Control + V',+ 'Control + Z',+ 'Control + Shift + Z',+ ],+};++const cases: AuditCase[] = [];+function add(+ story: Story,+ options: {+ theme?: Theme;+ direction?: Direction;+ modes?: Mode[];+ viewport?: {width: number; height: number};+ suffix?: string;+ } = {},+) {+ const theme = options.theme ?? 'neutral';+ const direction = options.direction ?? 'ltr';+ for (const mode of options.modes ?? ['light', 'dark']) {+ const parts: string[] = [story, options.suffix ?? '', theme];+ if (direction === 'rtl') {+ parts.push('rtl');+ }+ cases.push({+ key: `${parts.filter(Boolean).join('-')}-${mode}`,+ story,+ mode,+ theme,+ direction,+ viewport: options.viewport ?? WIDE,+ });+ }+}++add('modifier-combinations');+add('modifier-combinations', {theme: 'butter', modes: ['light']});+add('modifier-combinations', {direction: 'rtl', modes: ['light']});+add('special-keys', {viewport: TALL});+add('larger-text', {viewport: TALL});+add('larger-text', {theme: 'butter', modes: ['light'], viewport: TALL});+add('larger-text', {direction: 'rtl', modes: ['light'], viewport: TALL});+add('inline-with-text', {modes: ['light']});+add('inline-with-text', {suffix: 'narrow', viewport: NARROW, modes: ['light']});+add('menu-shortcuts', {modes: ['light']});++test.describe.configure({retries: 0});+let server: StaticServer;+let checkoutSha: string;+let storybookSha: string;++function storyUrl(item: AuditCase) {+ return `${server.origin}/iframe.html?id=core-kbd--${item.story}&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.evaluate(+ async () =>+ new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ ),+ );+ await page.waitForTimeout(40);+}++async function observe(page: Page) {+ return page.evaluate(() => {+ const round = (value: number) => Math.round(value * 10) / 10;+ const px = (value: string) => parseFloat(value) || 0;+ function box(rect: DOMRect) {+ return {+ left: round(rect.left),+ top: round(rect.top),+ right: round(rect.right),+ bottom: round(rect.bottom),+ width: round(rect.width),+ height: round(rect.height),+ };+ }+ // Resolve the badge tokens in the shortcut's own scope, so a row that+ // raises the text size resolves its own size.+ function resolveTokens(host: Element) {+ const probe = document.createElement('div');+ probe.style.cssText = [+ 'position:absolute',+ 'visibility:hidden',+ 'background-color:var(--color-neutral)',+ 'color:var(--color-text-primary)',+ 'border-bottom-style:solid',+ 'border-bottom-color:var(--color-border-emphasized)',+ 'border-radius:var(--radius-inner)',+ 'height:var(--spacing-5)',+ 'font-size:var(--text-supporting-size)',+ 'line-height:var(--text-supporting-leading)',+ ].join(';');+ host.appendChild(probe);+ const style = getComputedStyle(probe);+ const tokens = {+ background: style.backgroundColor,+ text: style.color,+ border: style.borderBottomColor,+ radius: px(style.borderTopLeftRadius),+ spacing5: px(style.height),+ fontSize: px(style.fontSize),+ lineHeight: px(style.lineHeight),+ };+ probe.remove();+ return tokens;+ }+ function channels(color: string) {+ const [r, g, b, a = 1] = (color.match(/[\d.]+/g) ?? []).map(Number);+ return {r, g, b, a: color.startsWith('rgba') ? a : 1};+ }+ // The badge fill is a translucent tint, so composite every background+ // from the element up to the first opaque one.+ function compositeBackground(element: Element) {+ const layers: ReturnType<typeof channels>[] = [];+ let node: Element | null = element;+ while (node) {+ const layer = channels(getComputedStyle(node).backgroundColor);+ if (layer.a > 0) {+ layers.push(layer);+ }+ if (layer.a >= 1) {+ break;+ }+ node = node.parentElement;+ }+ let result = {r: 255, g: 255, b: 255};+ for (const layer of layers.reverse()) {+ result = {+ r: layer.r * layer.a + result.r * (1 - layer.a),+ g: layer.g * layer.a + result.g * (1 - layer.a),+ b: layer.b * layer.a + result.b * (1 - layer.a),+ };+ }+ return `rgb(${result.r}, ${result.g}, ${result.b})`;+ }+ function luminance(color: string) {+ const [r, g, b] = (color.match(/[\d.]+/g) ?? []).map(Number);+ const channel = (value: number) => {+ const c = value / 255;+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);+ }+ function contrast(a: string, b: string) {+ const [high, low] = [luminance(a), luminance(b)].sort((x, y) => y - x);+ return round((high + 0.05) / (low + 0.05));+ }+ const shortcuts = Array.from(+ document.querySelectorAll<HTMLElement>('#storybook-root .astryx-kbd'),+ );+ return {+ theme: document+ .querySelector('[data-astryx-theme]')+ ?.getAttribute('data-astryx-theme'),+ mode: document.documentElement.getAttribute('data-theme'),+ viewport: {width: innerWidth, height: innerHeight},+ dpr: devicePixelRatio,+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,+ fonts: document.fonts.status,+ storybookError:+ document.querySelector('.sb-show-errordisplay') != null ||+ document.body.classList.contains('sb-show-errordisplay'),+ documentOverflow: round(+ document.documentElement.scrollWidth - innerWidth,+ ),+ shortcuts: shortcuts.map(shortcut => {+ const tokens = resolveTokens(shortcut.parentElement as HTMLElement);+ const badges = Array.from(shortcut.querySelectorAll('kbd'));+ return {+ role: shortcut.getAttribute('role'),+ name: shortcut.getAttribute('aria-label'),+ hidden: shortcut.getAttribute('aria-hidden'),+ tabIndex: shortcut.tabIndex,+ className: shortcut.className+ .split(/\s+/)+ .filter(name => name.startsWith('astryx-'))+ .join(' '),+ direction: getComputedStyle(shortcut).direction,+ box: box(shortcut.getBoundingClientRect()),+ tokens,+ badges: badges.map(badge => {+ const style = getComputedStyle(badge);+ const range = document.createRange();+ range.selectNodeContents(badge);+ return {+ text: badge.textContent ?? '',+ hidden: badge.getAttribute('aria-hidden'),+ targets: Array.from(badge.classList).filter(name =>+ name.startsWith('astryx-'),+ ),+ box: box(badge.getBoundingClientRect()),+ glyphBox: box(range.getBoundingClientRect()),+ paint: {+ background: style.backgroundColor,+ text: style.color,+ border: style.borderBottomColor,+ borderWidth: px(style.borderBottomWidth),+ borderStyle: style.borderBottomStyle,+ otherBorders: [+ px(style.borderTopWidth),+ px(style.borderLeftWidth),+ px(style.borderRightWidth),+ ],+ radius: px(style.borderTopLeftRadius),+ fontSize: px(style.fontSize),+ lineHeight: px(style.lineHeight),+ transform: style.transform,+ },+ surface: compositeBackground(badge),+ contrast: contrast(style.color, compositeBackground(badge)),+ };+ }),+ };+ }),+ };+ });+}++test.beforeAll(async () => {+ 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: 2,+ colorScheme: item.mode,+ reducedMotion: 'reduce',+ });+ 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 .astryx-kbd').first().waitFor();+ await settle(page);++ const first = await observe(page);+ await page.waitForTimeout(100);+ await settle(page);+ const observed = await observe(page);+ const geometryStable =+ JSON.stringify(first.shortcuts.map(shortcut => shortcut.box)) ===+ JSON.stringify(observed.shortcuts.map(shortcut => shortcut.box));++ const failures: string[] = [];+ const check = (condition: boolean, message: string) => {+ if (!condition) {+ failures.push(message);+ }+ };+ const near = (actual: number, expected: number, tolerance = 0.6) =>+ Math.abs(actual - expected) <= tolerance;++ check(storybookSha === checkoutSha, 'storybook build mismatch');+ check(pageErrors.length === 0, `page errors: ${pageErrors.join(' | ')}`);+ check(!observed.storybookError, 'storybook error display');+ check(observed.theme === item.theme, `theme ${observed.theme}`);+ check(observed.mode === item.mode, `mode ${observed.mode}`);+ check(+ observed.viewport.width === item.viewport.width &&+ observed.viewport.height === item.viewport.height,+ 'viewport mismatch',+ );+ check(observed.dpr === 2, `dpr ${observed.dpr}`);+ check(observed.reducedMotion, 'reduced motion not applied');+ check(observed.fonts === 'loaded', `fonts ${observed.fonts}`);+ check(geometryStable, 'geometry changed between samples');+ check(+ observed.documentOverflow <= 0,+ `document scrolls sideways by ${observed.documentOverflow}px`,+ );+ const glyphs = observed.shortcuts.flatMap(shortcut =>+ shortcut.badges.map(badge => badge.text),+ );+ check(+ JSON.stringify(glyphs) === JSON.stringify(GLYPHS[item.story]),+ `badges ${JSON.stringify(glyphs)}, expected ${JSON.stringify(GLYPHS[item.story])}`,+ );+ const names = observed.shortcuts.map(shortcut => shortcut.name);+ check(+ JSON.stringify(names) === JSON.stringify(NAMES[item.story]),+ `names ${JSON.stringify(names)}, expected ${JSON.stringify(NAMES[item.story])}`,+ );++ observed.shortcuts.forEach((shortcut, index) => {+ const where = `shortcut ${index} (${shortcut.name})`;+ const {tokens} = shortcut;+ // One named image, out of the tab order, with hidden badges.+ check(shortcut.role === 'img', `${where} role ${shortcut.role}`);+ check(shortcut.hidden == null, `${where} aria-hidden ${shortcut.hidden}`);+ check(shortcut.tabIndex === -1, `${where} tabIndex ${shortcut.tabIndex}`);+ check(+ shortcut.className === 'astryx-kbd',+ `${where} classes ${shortcut.className}`,+ );+ check(+ shortcut.direction === item.direction,+ `${where} direction ${shortcut.direction}`,+ );+ // The badges run from inline start to inline end.+ const boxes = shortcut.badges.map(badge => badge.box);+ for (let next = 1; next < boxes.length; next += 1) {+ const ordered =+ item.direction === 'rtl'+ ? boxes[next].right <= boxes[next - 1].left + 0.5+ : boxes[next].left >= boxes[next - 1].right - 0.5;+ check(ordered, `${where} badge ${next} is out of inline order`);+ }+ shortcut.badges.forEach((badge, badgeIndex) => {+ const at = `${where} badge ${badgeIndex} (${badge.text})`;+ const {paint} = badge;+ check(badge.hidden === 'true', `${at} aria-hidden ${badge.hidden}`);+ check(+ badge.targets.length === 0,+ `${at} carries ${badge.targets.join(' ')}`,+ );+ check(+ paint.background === tokens.background,+ `${at} background ${paint.background}, expected ${tokens.background}`,+ );+ check(+ paint.text === tokens.text,+ `${at} text ${paint.text}, expected ${tokens.text}`,+ );+ check(+ paint.border === tokens.border &&+ paint.borderStyle === 'solid' &&+ near(paint.borderWidth, 2, 0.01) &&+ paint.otherBorders.every(width => width === 0),+ `${at} border ${paint.borderStyle} ${paint.borderWidth} ${paint.border}, expected a 2px solid bottom border in ${tokens.border}`,+ );+ check(+ near(paint.radius, tokens.radius),+ `${at} radius ${paint.radius}, expected ${tokens.radius}`,+ );+ check(+ near(paint.fontSize, tokens.fontSize, 0.01),+ `${at} font size ${paint.fontSize}, expected ${tokens.fontSize}`,+ );+ check(paint.transform === 'none', `${at} transform ${paint.transform}`);+ // WCAG 1.4.3: the glyph is normal-size text on the badge surface.+ check(+ badge.contrast >= 4.5,+ `${at} text contrast ${badge.contrast} on ${badge.surface}`,+ );+ // A badge is never shorter than the theme's badge size or one line+ // of its glyph. At the default text size it keeps the theme's size.+ const expectedHeight = Math.max(tokens.spacing5, paint.lineHeight);+ check(+ near(badge.box.height, expectedHeight),+ `${at} height ${badge.box.height}, expected ${expectedHeight} (spacing-5 ${tokens.spacing5}, line ${paint.lineHeight})`,+ );+ check(+ badge.box.width >= tokens.spacing5 - 0.5,+ `${at} width ${badge.box.width} under ${tokens.spacing5}`,+ );+ // The glyph stays inside its painted badge.+ check(+ badge.glyphBox.top >= badge.box.top - 0.5 &&+ badge.glyphBox.bottom <= badge.box.bottom + 0.5 &&+ badge.glyphBox.left >= badge.box.left - 0.5 &&+ badge.glyphBox.right <= badge.box.right + 0.5,+ `${at} glyph ${JSON.stringify(badge.glyphBox)} leaves badge ${JSON.stringify(badge.box)}`,+ );+ });+ });++ const png = await page.screenshot({animations: 'disabled'});+ check(png.length > 1000, 'screenshot is empty');+ const image = `${item.key}.png`;+ const receipt = {+ schemaVersion: 1,+ expected: {+ build: checkoutSha,+ storyId: `core-kbd--${item.story}`,+ mode: item.mode,+ theme: item.theme,+ direction: item.direction,+ viewport: item.viewport,+ glyphs: GLYPHS[item.story],+ names: NAMES[item.story],+ anatomy:+ 'one astryx-kbd group per shortcut with role img, the spoken name, and no tab stop; one aria-hidden kbd badge per key with no theme target',+ paint:+ 'neutral background, primary text at the supporting text size, a 2px solid bottom border in the emphasized border color, the inner radius, all resolved from the theme tokens in the shortcut scope',+ layout:+ 'each badge is at least spacing-5 wide and exactly max(spacing-5, one line of its glyph) tall; the glyph stays inside the badge; badges run from inline start to inline end; no sideways document scroll',+ contrast:+ 'badge text reaches 4.5:1 against the composited badge surface (WCAG 1.4.3)',+ },+ observed: {+ build: storybookSha,+ ...observed,+ geometryStable,+ pageErrors,+ },+ image: {+ file: image,+ sha256: createHash('sha256').update(png).digest('hex'),+ width: png.readUInt32BE(16),+ height: png.readUInt32BE(20),+ },+ failures,+ passed: failures.length === 0,+ };+ 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();+ expect(failures).toEqual([]);+ });+}++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,+ );+ fs.writeFileSync(+ path.join(OUTPUT, 'manifest.json'),+ `${JSON.stringify(+ {+ schemaVersion: 1,+ component: 'core/Kbd',+ build: checkoutSha,+ frames: cases.map(item => ({+ key: item.key,+ image: `${item.key}.png`,+ receipt: `${item.key}.sensors.json`,+ })),+ },+ null,+ 2,+ )}\n`,+ );+ expect(receiptFiles).toHaveLength(cases.length);+ // A receipt left by an earlier build does not count.+ expect(+ receipts+ .filter(receipt => receipt.expected.build !== checkoutSha)+ .map(receipt => receipt.expected),+ ).toEqual([]);+ expect(+ receipts+ .filter(receipt => !receipt.passed)+ .map(receipt => ({frame: receipt.expected, failures: receipt.failures})),+ ).toEqual([]);+});