An open source design system that's fully customizable and agent ready
TypeScript
[Component Audit] Icon: labelled icons from icon libraries reach screen readers (#9738)
Cindy Zhang9ee4282db4ee
diff --git a/.changeset/icon-audit-docs.md b/.changeset/icon-audit-docs.mdnew file mode 100644index 0000000000..ebce43d45e--- /dev/null+++ b/.changeset/icon-audit-docs.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[docs] Icon: list the ten palette `color` values and namespaced `icon` keys, and document `className`, `style`, and `ref` in every doc language, including that `ref` reaches the SVG only when `icon` is an icon component.++@cixzhangdiff --git a/.changeset/icon-label-heroicons.md b/.changeset/icon-label-heroicons.mdnew file mode 100644index 0000000000..249765bd8a--- /dev/null+++ b/.changeset/icon-label-heroicons.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Icon: a labelled icon component that hides itself unless a prop replaces it, such as a Heroicons icon, is now exposed to assistive technology as an image with its `label`. Before, the component's own `aria-hidden="true"` stayed on the SVG and hid the label. If a parent control already names the icon, remove `label` so the name is not announced twice.++@cixzhangdiff --git a/.github/a11y-baseline.json b/.github/a11y-baseline.jsonindex 0a3de8f24b..4313c838d1 100644--- a/.github/a11y-baseline.json+++ b/.github/a11y-baseline.json@@ -318,11 +318,6 @@"impact": "serious","helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"},- {- "key": "Icon::Inherit Color::color-contrast",- "impact": "serious",- "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"- },{"key": "InputGroup::All Variations::color-contrast","impact": "serious",diff --git a/apps/storybook/stories/Icon.stories.tsx b/apps/storybook/stories/Icon.stories.tsxindex 33f10b824e..56523ccd68 100644--- a/apps/storybook/stories/Icon.stories.tsx+++ b/apps/storybook/stories/Icon.stories.tsx@@ -1,7 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import type {Meta, StoryObj} from '@storybook/react';-import {Icon} from '@astryxdesign/core/Icon';+import {Icon, getIconRegistry, type IconName} from '@astryxdesign/core/Icon';import {HStack, VStack} from '@astryxdesign/core/Layout';import {Text} from '@astryxdesign/core/Text';import {@@ -14,6 +14,7 @@ import {CheckCircleIcon,ExclamationTriangleIcon,XCircleIcon,+ InformationCircleIcon,} from '@heroicons/react/24/outline';import {HeartIcon as HeartIconSolid,@@ -37,10 +38,21 @@ const meta: Meta<typeof Icon> = {'tertiary','disabled','accent',+ 'info','success','error','warning','inherit',+ 'blue',+ 'red',+ 'green',+ 'gray',+ 'cyan',+ 'teal',+ 'yellow',+ 'orange',+ 'pink',+ 'purple',],description: 'Color variant',},@@ -175,6 +187,7 @@ export const AllColors: Story = {<Icon icon={CogIcon} color="tertiary" /><Icon icon={BellIcon} color="disabled" /><Icon icon={HeartIcon} color="accent" />+ <Icon icon={InformationCircleIcon} color="info" /><Icon icon={CheckCircleIcon} color="success" /><Icon icon={XCircleIcon} color="error" /><Icon icon={ExclamationTriangleIcon} color="warning" />@@ -253,7 +266,7 @@ export const InheritColor: Story = {<div style={{display: 'flex', gap: '16px', alignItems: 'center'}}><spanstyle={{- color: 'blue',+ color: 'var(--color-text-blue)',display: 'flex',alignItems: 'center',gap: '4px',@@ -263,7 +276,7 @@ export const InheritColor: Story = {</span><spanstyle={{- color: 'green',+ color: 'var(--color-text-green)',display: 'flex',alignItems: 'center',gap: '4px',@@ -310,3 +323,31 @@ export const NonSemanticColors: Story = {</HStack>),};++const builtInIconNames = Object.keys(getIconRegistry()) as IconName[];++/**+ * Semantic names resolve from the active theme's icon registry, or from the+ * built-in artwork, and render inside Icon's sized wrapper. The first row shows+ * one registry glyph at every size; the grid shows every built-in name.+ */+export const SemanticNames: Story = {+ render: () => (+ <VStack gap={6}>+ <HStack gap={4} vAlign="center">+ <Icon icon="check" size="xsm" />+ <Icon icon="check" size="sm" />+ <Icon icon="check" size="md" />+ <Icon icon="check" size="lg" />+ </HStack>+ <HStack gap={4} wrap="wrap">+ {builtInIconNames.map(name => (+ <VStack key={name} gap={1} hAlign="center">+ <Icon icon={name} color="secondary" />+ <Text type="supporting">{name}</Text>+ </VStack>+ ))}+ </HStack>+ </VStack>+ ),+};diff --git a/packages/core/src/Icon/Icon.doc.mjs b/packages/core/src/Icon/Icon.doc.mjsindex d6bc5a311b..0c25da673a 100644--- a/packages/core/src/Icon/Icon.doc.mjs+++ b/packages/core/src/Icon/Icon.doc.mjs@@ -71,15 +71,16 @@ export const docs = {props: [{name: 'icon',- type: 'IconName | ComponentType<SVGProps>',+ type: 'IconName | NamespacedIconName | ComponentType<SVGProps>',description:- 'Semantic icon name or SVG component. Valid semantic names: close, chevronDown, chevronLeft, chevronRight, chevronsLeft, chevronsRight, check, success, error, warning, info, calendar, clock, externalLink, menu, moreHorizontal, search, upload, arrowUp, arrowDown, arrowsUpDown, funnel, eyeSlash, viewColumns, copy, checkDouble, wrench, stop, microphone. For any icon not in this list, pass an SVG component directly (e.g. import from lucide-react or @heroicons/react). Note: this prop is called `icon`, not `name`.',+ 'Semantic icon name or SVG component. Valid semantic names: close, chevronDown, chevronLeft, chevronRight, chevronsLeft, chevronsRight, check, success, error, warning, info, calendar, clock, externalLink, menu, moreHorizontal, search, upload, arrowUp, arrowDown, arrowsUpDown, funnel, eyeSlash, viewColumns, copy, checkDouble, wrench, stop, microphone. A namespaced key such as `richtext:bold` names a glyph that one component or library registers, and a theme can replace it by key; a namespaced key that nothing registers renders nothing. For any icon not in this list, pass an SVG component directly (e.g. import from lucide-react or @heroicons/react). Note: this prop is called `icon`, not `name`.',required: true,},{name: 'color',type: "'primary' | 'secondary' | 'tertiary' | 'disabled' | 'accent' | 'info' | 'success' | 'error' | 'warning' | 'inherit'",- description: 'Color variant mapped to Astryx icon color tokens.',+ description:+ 'Color variant mapped to Astryx icon color tokens. Semantic values (primary through warning) follow the role, and inherit uses the surrounding text color. On the web, Icon also accepts the palette values blue, red, green, gray, cyan, teal, yellow, orange, pink, and purple, which pick a non-semantic hue.',default: "'inherit'",},{@@ -107,6 +108,24 @@ export const docs = {description:"StyleX styles for customization (color, size, opacity). Folded into the icon's own stylex.props() call so it composes with the base color/size styles. Must be a stylex.create() value, not an inline style object like style={{}}.",},+ {+ name: 'className',+ type: 'string',+ description:+ 'Class name added to the rendered glyph, beside the astryx-icon target class.',+ },+ {+ name: 'style',+ type: 'CSSProperties',+ description:+ "Inline styles merged onto the rendered glyph after Icon's own size and color styles.",+ },+ {+ name: 'ref',+ type: 'Ref<SVGSVGElement>',+ description:+ 'Ref to the rendered SVG element when icon is an icon component. A semantic or namespaced name renders inside an internal wrapper, and the ref is not attached.',+ },],theming: {targets: [{className: 'astryx-icon', visualProps: ['color', 'size']}],@@ -207,15 +226,16 @@ export const docsZh = {props: [{name: 'icon',- type: 'IconName | ComponentType<SVGProps>',+ type: 'IconName | NamespacedIconName | ComponentType<SVGProps>',description:- '语义图标名称或 SVG 组件。有效语义名称:close, chevronDown, chevronLeft, chevronRight, chevronsLeft, chevronsRight, check, success, error, warning, info, calendar, clock, externalLink, menu, moreHorizontal, search, upload, arrowUp, arrowDown, arrowsUpDown, funnel, eyeSlash, viewColumns, copy, checkDouble, wrench, stop, microphone。列表之外的图标请直接传入 SVG 组件。',+ '语义图标名称或 SVG 组件。有效语义名称:close, chevronDown, chevronLeft, chevronRight, chevronsLeft, chevronsRight, check, success, error, warning, info, calendar, clock, externalLink, menu, moreHorizontal, search, upload, arrowUp, arrowDown, arrowsUpDown, funnel, eyeSlash, viewColumns, copy, checkDouble, wrench, stop, microphone。命名空间键(如 `richtext:bold`)指向某个组件或库注册的图标,主题可以按键替换它;没有注册的命名空间键不渲染任何内容。列表之外的图标请直接传入 SVG 组件。',required: true,},{name: 'color',type: "'primary' | 'secondary' | 'tertiary' | 'disabled' | 'accent' | 'info' | 'success' | 'error' | 'warning' | 'inherit'",- description: '映射到 Astryx 图标颜色令牌的颜色变体。',+ description:+ '映射到 Astryx 图标颜色令牌的颜色变体。语义值(primary 到 warning)跟随角色,inherit 使用周围文字的颜色。在 Web 上,Icon 还接受调色板值 blue、red、green、gray、cyan、teal、yellow、orange、pink 和 purple,它们选择非语义色相。',default: "'inherit'",},{@@ -243,6 +263,23 @@ export const docsZh = {description:'用于自定义的 StyleX 样式(颜色、尺寸、不透明度)。会并入图标自身的 stylex.props() 调用,从而与基础的颜色/尺寸样式组合。必须是 stylex.create() 的值,而不是像 style={{}} 这样的内联样式对象。',},+ {+ name: 'className',+ type: 'string',+ description: '添加到渲染图标上的类名,与 astryx-icon 目标类名并列。',+ },+ {+ name: 'style',+ type: 'CSSProperties',+ description:+ '合并到渲染图标上的内联样式,位于 Icon 自身的尺寸和颜色样式之后。',+ },+ {+ name: 'ref',+ type: 'Ref<SVGSVGElement>',+ description:+ 'icon 为图标组件时,指向渲染的 SVG 元素的 ref。语义名称或命名空间名称在内部包装元素中渲染,不会附加 ref。',+ },],theming: {targets: [{className: 'astryx-icon', visualProps: ['color', 'size']}],@@ -390,8 +427,9 @@ export const docsDense = {],},propDescriptions: {- icon: 'Semantic icon name or SVG component. Valid names: close, chevronDown, chevronLeft, chevronRight, chevronsLeft, chevronsRight, check, success, error, warning, info, calendar, clock, externalLink, menu, moreHorizontal, search, upload, arrowUp, arrowDown, arrowsUpDown, funnel, eyeSlash, viewColumns, copy, checkDouble, wrench, stop, microphone. For others, pass an SVG component.',- color: 'Color variant mapped to Astryx icon color tokens.',+ icon: 'Semantic icon name or SVG component. Valid names: close, chevronDown, chevronLeft, chevronRight, chevronsLeft, chevronsRight, check, success, error, warning, info, calendar, clock, externalLink, menu, moreHorizontal, search, upload, arrowUp, arrowDown, arrowsUpDown, funnel, eyeSlash, viewColumns, copy, checkDouble, wrench, stop, microphone. A namespaced key (`richtext:bold`) names a glyph a component or library registers; an unregistered one renders nothing. For others, pass an SVG component.',+ color:+ 'Color variant mapped to Astryx icon color tokens; inherit = surrounding text color. Web also accepts the non-semantic palette: blue, red, green, gray, cyan, teal, yellow, orange, pink, purple.',size: "xsm/sm/md/lg = 12/16/20/24px at a 16px root, scale w/ root font size; theme sets a size's glyph dimension via width + height (px or rem) on components.icon['size:sm'] etc. Explicit Icon size; otherwise nearest owning-component default, then 'md' when no contextual default exists",variant:"Requests the active theme's alternate artwork (e.g. 'filled'); names from augmentable IconVariantMap. Reaches the entry only if the active theme's iconVariants lists it (and an inherited entry's defining theme does too); else normal artwork. Ignored by a directly passed component; never in the DOM; no theming selector.",@@ -399,5 +437,8 @@ export const docsDense = {'Accessible name for a meaningful, standalone icon. Sets role="img" + aria-label and drops the default aria-hidden. Omit (default) for decorative icons (stays aria-hidden). Empty string = decorative. The accessible-name/alt-text prop for icons.',xstyle:'StyleX styles (color, size, opacity) via stylex.create(); composes with the base color/size styles.',+ className: 'Class added to the rendered glyph beside astryx-icon.',+ style: "Inline styles merged after Icon's size and color styles.",+ ref: 'Reaches the SVG only when icon is a component; a semantic or namespaced name renders in a wrapper and gets no ref.',},};diff --git a/packages/core/src/Icon/Icon.test.tsx b/packages/core/src/Icon/Icon.test.tsxindex 0bbf37bd0c..b19a4b0a4b 100644--- a/packages/core/src/Icon/Icon.test.tsx+++ b/packages/core/src/Icon/Icon.test.tsx@@ -13,6 +13,7 @@import {describe, it, expect, vi} from 'vitest';import {render, screen} from '@testing-library/react';import * as stylex from '@stylexjs/stylex';+import {CheckCircleIcon} from '@heroicons/react/24/outline';import {TestIcon} from '../__tests__/TestIcon';import {unthemedLength} from '../__tests__/unthemedLength';import {Theme} from '../theme/Theme';@@ -57,36 +58,18 @@ describe('Icon', () => {expect(screen.getByTestId('icon')).toHaveAttribute('aria-hidden', 'true');});- it('renders with different color variants', () => {- const {rerender} = render(- <Icon icon={TestIcon} color="primary" data-testid="icon" />,- );- expect(screen.getByTestId('icon')).toBeInTheDocument();-- rerender(<Icon icon={TestIcon} color="secondary" data-testid="icon" />);- expect(screen.getByTestId('icon')).toBeInTheDocument();-- rerender(<Icon icon={TestIcon} color="accent" data-testid="icon" />);- expect(screen.getByTestId('icon')).toBeInTheDocument();-- rerender(<Icon icon={TestIcon} color="info" data-testid="icon" />);- expect(screen.getByTestId('icon')).toBeInTheDocument();-- rerender(<Icon icon={TestIcon} color="success" data-testid="icon" />);- expect(screen.getByTestId('icon')).toBeInTheDocument();-- rerender(<Icon icon={TestIcon} color="error" data-testid="icon" />);- expect(screen.getByTestId('icon')).toBeInTheDocument();-- rerender(<Icon icon={TestIcon} color="warning" data-testid="icon" />);- expect(screen.getByTestId('icon')).toBeInTheDocument();-- rerender(<Icon icon={TestIcon} color="inherit" data-testid="icon" />);- expect(screen.getByTestId('icon')).toBeInTheDocument();- });-- it('renders with non-semantic color variants', () => {- const nonSemanticColors = [+ describe('theming target reflection', () => {+ const colors = [+ 'primary',+ 'secondary',+ 'tertiary',+ 'disabled',+ 'accent',+ 'info',+ 'success',+ 'error',+ 'warning',+ 'inherit','blue','red','green',@@ -98,31 +81,68 @@ describe('Icon', () => {'pink','purple',] as const;- const {rerender} = render(- <Icon icon={TestIcon} color={nonSemanticColors[0]} data-testid="icon" />,- );- expect(screen.getByTestId('icon')).toBeInTheDocument();+ const sizes = ['xsm', 'sm', 'md', 'lg'] as const;- for (const c of nonSemanticColors.slice(1)) {- rerender(<Icon icon={TestIcon} color={c} data-testid="icon" />);- expect(screen.getByTestId('icon')).toBeInTheDocument();- }- });-- it('renders with different size variants', () => {- const {rerender} = render(- <Icon icon={TestIcon} size="xsm" data-testid="icon" />,- );- expect(screen.getByTestId('icon')).toBeInTheDocument();+ it('reflects each color on the icon target in component mode', () => {+ for (const color of colors) {+ const {unmount} = render(+ <Icon icon={TestIcon} color={color} data-testid="icon" />,+ );+ const icon = screen.getByTestId('icon');+ expect(icon).toHaveClass('astryx-icon');+ expect(icon).toHaveAttribute('data-color', color);+ unmount();+ }+ });- rerender(<Icon icon={TestIcon} size="sm" data-testid="icon" />);- expect(screen.getByTestId('icon')).toBeInTheDocument();+ it('reflects each color on the icon target in registry mode', () => {+ for (const color of colors) {+ const {unmount} = render(+ <Icon icon="check" color={color} data-testid="icon" />,+ );+ const icon = screen.getByTestId('icon');+ expect(icon).toHaveClass('astryx-icon');+ expect(icon).toHaveAttribute('data-color', color);+ unmount();+ }+ });- rerender(<Icon icon={TestIcon} size="md" data-testid="icon" />);- expect(screen.getByTestId('icon')).toBeInTheDocument();+ it('reflects the default inherit color when color is omitted', () => {+ render(+ <>+ <Icon icon={TestIcon} data-testid="component" />+ <Icon icon="check" data-testid="registry" />+ </>,+ );+ expect(screen.getByTestId('component')).toHaveAttribute(+ 'data-color',+ 'inherit',+ );+ expect(screen.getByTestId('registry')).toHaveAttribute(+ 'data-color',+ 'inherit',+ );+ });- rerender(<Icon icon={TestIcon} size="lg" data-testid="icon" />);- expect(screen.getByTestId('icon')).toBeInTheDocument();+ it('reflects each size on the icon target in both modes', () => {+ for (const size of sizes) {+ const {unmount} = render(+ <>+ <Icon icon={TestIcon} size={size} data-testid="component" />+ <Icon icon="check" size={size} data-testid="registry" />+ </>,+ );+ expect(screen.getByTestId('component')).toHaveAttribute(+ 'data-size',+ size,+ );+ expect(screen.getByTestId('registry')).toHaveAttribute(+ 'data-size',+ size,+ );+ unmount();+ }+ });});it('sizes component-mode icons in rem so they scale with root font-size', () => {@@ -821,6 +841,19 @@ describe('Icon', () => {expect(icon).not.toHaveAttribute('aria-hidden');});+ it('exposes a labelled icon component that hides itself by default', () => {+ // Heroicons render aria-hidden="true" unless the caller overrides it.+ render(<Icon icon={CheckCircleIcon} label="Completed" />);+ const icon = screen.getByRole('img', {name: 'Completed'});+ expect(icon).not.toHaveAttribute('aria-hidden');+ });++ it('keeps an icon component that hides itself decorative without a label', () => {+ render(<Icon icon={CheckCircleIcon} data-testid="icon" />);+ expect(screen.getByTestId('icon')).toHaveAttribute('aria-hidden', 'true');+ expect(screen.queryByRole('img')).not.toBeInTheDocument();+ });+it('keeps the decorative default when label is omitted (component mode)', () => {render(<Icon icon={TestIcon} data-testid="icon" />);const icon = screen.getByTestId('icon');diff --git a/packages/core/src/Icon/Icon.tsx b/packages/core/src/Icon/Icon.tsxindex a85d7990ed..a0577e72ab 100644--- a/packages/core/src/Icon/Icon.tsx+++ b/packages/core/src/Icon/Icon.tsx@@ -176,7 +176,11 @@ export interface IconProps extends Omit<SVGProps<SVGSVGElement>,'ref' | 'color'> {- /** Ref forwarded to the root element */+ /**+ * Ref to the rendered SVG element when `icon` is an icon component. A+ * semantic or namespaced name renders inside an internal wrapper, and the+ * ref is not attached.+ */ref?: React.Ref<SVGSVGElement>;/*** Icon to render. Can be:@@ -267,22 +271,26 @@ export interface IconProps extends Omit<xstyle?: StyleXStyles;}+type IconA11yProps =+ | {role: 'img'; 'aria-label': string; 'aria-hidden': undefined}+ | {'aria-hidden': 'true'};+/*** Derives the ARIA attributes for an icon from its `label` prop.** - Non-empty `label` → meaningful image: `role="img"` + `aria-label`, and no* `aria-hidden` (an `aria-hidden` element is removed from the accessibility- * tree, so its accessible name would be ignored).+ * tree, so its accessible name would be ignored). Icon passes+ * `aria-hidden: undefined`. Many icon components, such as Heroicons, write+ * `aria-hidden="true"` unless a prop replaces it.* - Omitted or empty `label` → decorative default: `aria-hidden="true"`.** The result is spread BEFORE `{...props}` in both render modes so an explicit* `aria-hidden` / `role` / `aria-label` from the consumer always wins.*/-function getIconA11yProps(- label: string | undefined,-): {role: 'img'; 'aria-label': string} | {'aria-hidden': 'true'} {+function getIconA11yProps(label: string | undefined): IconA11yProps {return label != null && label !== ''- ? {role: 'img', 'aria-label': label}+ ? {role: 'img', 'aria-label': label, 'aria-hidden': undefined}: {'aria-hidden': 'true'};}@@ -392,7 +400,7 @@ function IconFromRegistry({color: IconColor;size: IconSize;variant: IconVariant | undefined;- a11yProps: {role: 'img'; 'aria-label': string} | {'aria-hidden': 'true'};+ a11yProps: IconA11yProps;className?: string;style?: React.CSSProperties;xstyle?: StyleXStyles;diff --git a/packages/core/src/Icon/__tests__/IconAudit.a11y.chromium.spec.ts b/packages/core/src/Icon/__tests__/IconAudit.a11y.chromium.spec.tsnew file mode 100644index 0000000000..0780d5da17--- /dev/null+++ b/packages/core/src/Icon/__tests__/IconAudit.a11y.chromium.spec.ts@@ -0,0 +1,572 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y audit Icon++/**+ * @file IconAudit.a11y.chromium.spec.ts+ * @input Exact-head Core/Icon stories across themes, modes, direction, and viewport+ * @output Screenshots and fail-closed sensor receipts for the Icon whole-component audit+ * @position Component-owned Night Watch browser evidence; CI runs it only for an Icon 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 '@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('icon-audit-evidence');+const WIDE = {width: 1024, height: 900};+const NARROW = {width: 320, height: 900};++type Mode = 'light' | 'dark';+type Direction = 'ltr' | 'rtl';+type Theme = 'neutral' | 'butter';+type Story =+ | 'semantic-names'+ | 'all-colors'+ | 'non-semantic-colors'+ | 'all-sizes'+ | 'accessible-name'+ | 'inherit-color';++type AuditCase = {+ key: string;+ story: Story;+ mode: Mode;+ direction: Direction;+ theme: Theme;+ viewport: {width: number; height: number};+};++type AuditReceipt = {+ passed: boolean;+ expected: Record<string, unknown>;+ failures: string[];+};++const SIZES = ['xsm', 'sm', 'md', 'lg'];+const NEUTRAL_SIZE_PX = [12, 16, 20, 24];+const SEMANTIC_COLORS = [+ 'primary',+ 'secondary',+ 'tertiary',+ 'disabled',+ 'accent',+ 'info',+ 'success',+ 'error',+ 'warning',+];+const PALETTE_COLORS = [+ 'blue',+ 'red',+ 'green',+ 'gray',+ 'cyan',+ 'teal',+ 'yellow',+ 'orange',+ 'pink',+ 'purple',+];+// The token each color reads, as shipped. Used to read the expected+// computed color from a probe element in the same frame.+const COLOR_TOKEN: Record<string, string> = {+ primary: '--color-icon-primary',+ secondary: '--color-icon-secondary',+ tertiary: '--color-icon-secondary',+ disabled: '--color-icon-disabled',+ accent: '--color-accent',+ info: '--color-icon-info',+ success: '--color-icon-success',+ error: '--color-icon-error',+ warning: '--color-icon-warning',+ ...Object.fromEntries(PALETTE_COLORS.map(c => [c, `--color-icon-${c}`])),+};++const cases: AuditCase[] = [];+function add(+ story: Story,+ variant: string,+ options: Partial<Omit<AuditCase, 'key' | 'story' | 'mode'>> = {},+ modes: Mode[] = ['light', 'dark'],+) {+ for (const mode of modes) {+ cases.push({+ key: `${story}-${variant}-${mode}`,+ story,+ mode,+ direction: options.direction ?? 'ltr',+ theme: options.theme ?? 'neutral',+ viewport: options.viewport ?? WIDE,+ });+ }+}++add('semantic-names', 'neutral');+add('semantic-names', 'butter', {theme: 'butter'});+add('semantic-names', 'rtl', {direction: 'rtl'}, ['light']);+add('semantic-names', 'narrow', {viewport: NARROW}, ['light']);+add('all-colors', 'neutral');+add('all-colors', 'butter', {theme: 'butter'});+add('non-semantic-colors', 'neutral');+add('non-semantic-colors', 'narrow', {viewport: NARROW}, ['light']);+add('all-sizes', 'neutral');+add('accessible-name', 'neutral');+add('inherit-color', 'neutral');++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-icon--${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, colorToken: Record<string, string>) {+ return page.evaluate(tokens => {+ const round = (value: number) => Math.round(value * 10) / 10;+ function box(element: Element) {+ const rect = element.getBoundingClientRect();+ return {+ left: round(rect.left),+ top: round(rect.top),+ width: round(rect.width),+ height: round(rect.height),+ };+ }+ function parseRgb(value: string) {+ const match = value.match(/rgba?\(([^)]+)\)/);+ if (!match) {+ return null;+ }+ const [r, g, b, a = '1'] = match[1].split(/[\s,/]+/).filter(Boolean);+ return [Number(r), Number(g), Number(b), Number(a)];+ }+ function luminance(rgb: number[]) {+ const [r, g, b] = rgb+ .slice(0, 3)+ .map(v => v / 255)+ .map(v => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4));+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;+ }+ function backdrop(element: Element): string {+ let node: Element | null = element.parentElement;+ while (node) {+ const color = getComputedStyle(node).backgroundColor;+ const rgb = parseRgb(color);+ if (rgb && rgb[3] > 0) {+ return color;+ }+ node = node.parentElement;+ }+ return getComputedStyle(document.body).backgroundColor;+ }+ const root = document.querySelector('#storybook-root') ?? document.body;+ // Read tokens beside the first glyph so the probe sits inside the same+ // theme scope.+ const scope = root.querySelector('.astryx-icon')?.parentElement ?? root;+ const probe = document.createElement('span');+ scope.appendChild(probe);+ const tokenColor = (token: string) => {+ probe.style.color = `var(${token})`;+ return getComputedStyle(probe).color;+ };+ const resolvedTokens = Object.fromEntries(+ Object.entries(tokens).map(([name, token]) => [name, tokenColor(token)]),+ );+ probe.remove();+ const icons = Array.from(root.querySelectorAll('.astryx-icon')).map(+ icon => {+ const style = getComputedStyle(icon);+ const svg =+ icon.tagName.toLowerCase() === 'svg'+ ? icon+ : icon.querySelector('svg');+ const fg = parseRgb(style.color);+ const bgColor = backdrop(icon);+ const bg = parseRgb(bgColor);+ let contrast: number | null = null;+ if (fg && bg) {+ const [hi, lo] = [luminance(fg), luminance(bg)].sort((a, b) => b - a);+ contrast = Math.round(((hi + 0.05) / (lo + 0.05)) * 100) / 100;+ }+ return {+ tagName: icon.tagName.toLowerCase(),+ dataSize: icon.getAttribute('data-size'),+ dataColor: icon.getAttribute('data-color'),+ dataVariant: icon.getAttribute('data-variant'),+ ariaHidden: icon.getAttribute('aria-hidden'),+ role: icon.getAttribute('role'),+ ariaLabel: icon.getAttribute('aria-label'),+ tabIndex: icon.getAttribute('tabindex'),+ color: style.color,+ parentColor: icon.parentElement+ ? getComputedStyle(icon.parentElement).color+ : null,+ backdrop: bgColor,+ contrast,+ transform: style.transform,+ fontSize: style.fontSize,+ box: box(icon),+ glyphBox: svg ? box(svg) : null,+ glyphPaths: svg+ ? svg.querySelectorAll(+ 'path, circle, rect, line, polyline, polygon, ellipse',+ ).length+ : 0,+ };+ },+ );+ return {+ theme: document+ .querySelector('[data-astryx-theme]')+ ?.getAttribute('data-astryx-theme'),+ mode: document.documentElement.getAttribute('data-theme'),+ direction: getComputedStyle(root.querySelector('.astryx-icon') ?? root)+ .direction,+ rootFontSize: getComputedStyle(document.documentElement).fontSize,+ viewport: {width: innerWidth, height: innerHeight},+ dpr: devicePixelRatio,+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,+ documentOverflow: document.documentElement.scrollWidth > innerWidth + 1,+ fonts: document.fonts.status,+ runningAnimations: document+ .getAnimations()+ .filter(animation => animation.playState === 'running').length,+ storybookError:+ document.querySelector('.sb-show-errordisplay') != null ||+ document.body.classList.contains('sb-show-errordisplay'),+ resolvedTokens,+ icons,+ };+ }, colorToken);+}++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: 1,+ 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-icon').first().waitFor();++ await settle(page);+ const first = await observe(page, COLOR_TOKEN);+ await page.waitForTimeout(100);+ await settle(page);+ const observed = await observe(page, COLOR_TOKEN);+ const geometryStable =+ JSON.stringify(first.icons.map(icon => icon.box)) ===+ JSON.stringify(observed.icons.map(icon => icon.box));++ const failures: string[] = [];+ const check = (condition: boolean, message: string) => {+ if (!condition) {+ failures.push(message);+ }+ };+ const near = (actual: number, expected: number) =>+ Math.abs(actual - expected) <= 1;++ 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.direction === item.direction,+ `direction ${observed.direction}`,+ );+ check(+ observed.viewport.width === item.viewport.width &&+ observed.viewport.height === item.viewport.height,+ 'viewport mismatch',+ );+ check(observed.dpr === 1, `dpr ${observed.dpr}`);+ check(observed.reducedMotion, 'reduced motion not applied');+ check(observed.fonts === 'loaded', `fonts ${observed.fonts}`);+ check(observed.runningAnimations === 0, 'animations still running');+ check(geometryStable, 'geometry changed between samples');+ check(!observed.documentOverflow, 'document scrolls horizontally');++ const {icons} = observed;+ // Every glyph: one icon target, square box, painted artwork, no tab stop,+ // no mirroring, no variant reflection.+ icons.forEach((icon, index) => {+ const id = `icon ${index}`;+ check(icon.glyphBox != null && icon.glyphPaths > 0, `${id}: no artwork`);+ check(icon.box.width > 0 && icon.box.height > 0, `${id}: empty box`);+ check(near(icon.box.width, icon.box.height), `${id}: not square`);+ check(icon.tabIndex == null, `${id}: adds a tab stop`);+ check(icon.transform === 'none', `${id}: transformed ${icon.transform}`);+ check(icon.dataVariant == null, `${id}: reflects a variant`);+ check(+ SIZES.includes(icon.dataSize ?? ''),+ `${id}: data-size ${icon.dataSize}`,+ );+ check(icon.dataColor != null, `${id}: no data-color`);+ if (icon.tagName === 'span' && icon.glyphBox) {+ check(+ near(icon.glyphBox.width, icon.box.width) &&+ near(icon.glyphBox.height, icon.box.height),+ `${id}: registry artwork does not fill its box`,+ );+ }+ if (icon.dataColor && icon.dataColor !== 'inherit') {+ check(+ icon.color === observed.resolvedTokens[icon.dataColor],+ `${id}: ${icon.dataColor} paints ${icon.color}, token ${observed.resolvedTokens[icon.dataColor]}`,+ );+ }+ });+ const decorative = (from: number, to: number) => {+ icons.slice(from, to).forEach((icon, offset) => {+ check(+ icon.ariaHidden === 'true' &&+ icon.role == null &&+ icon.ariaLabel == null,+ `icon ${from + offset}: not decorative`,+ );+ });+ };+ const sizes = (from: number, tagName: string) => {+ const row = icons.slice(from, from + 4);+ check(+ JSON.stringify(row.map(icon => icon.dataSize)) ===+ JSON.stringify(SIZES),+ `size row ${row.map(icon => icon.dataSize).join(',')}`,+ );+ row.forEach((icon, offset) => {+ check(+ icon.tagName === tagName,+ `size ${SIZES[offset]}: ${icon.tagName}`,+ );+ if (offset > 0) {+ check(+ icon.box.width > row[offset - 1].box.width,+ `size ${SIZES[offset]} is not larger than ${SIZES[offset - 1]}`,+ );+ }+ if (item.theme === 'neutral') {+ check(+ near(icon.box.width, NEUTRAL_SIZE_PX[offset]),+ `size ${SIZES[offset]}: ${icon.box.width}px`,+ );+ }+ });+ };++ if (item.story === 'semantic-names') {+ sizes(0, 'span');+ const grid = icons.slice(4);+ check(grid.length >= 29, `only ${grid.length} built-in names`);+ grid.forEach((icon, index) => {+ check(icon.tagName === 'span', `name ${index}: ${icon.tagName}`);+ check(icon.dataSize === 'md', `name ${index}: size ${icon.dataSize}`);+ check(+ icon.dataColor === 'secondary',+ `name ${index}: ${icon.dataColor}`,+ );+ });+ decorative(0, icons.length);+ }+ if (item.story === 'all-colors') {+ check(+ JSON.stringify(icons.map(icon => icon.dataColor)) ===+ JSON.stringify(SEMANTIC_COLORS),+ `colors ${icons.map(icon => icon.dataColor).join(',')}`,+ );+ check(+ icons.every(icon => icon.tagName === 'svg'),+ 'not component mode',+ );+ check(+ icons.every(icon => icon.dataSize === 'md'),+ 'not the md fallback',+ );+ decorative(0, icons.length);+ }+ if (item.story === 'non-semantic-colors') {+ check(+ JSON.stringify(icons.map(icon => icon.dataColor)) ===+ JSON.stringify(PALETTE_COLORS),+ `colors ${icons.map(icon => icon.dataColor).join(',')}`,+ );+ decorative(0, icons.length);+ }+ if (item.story === 'all-sizes') {+ check(icons.length === 4, `${icons.length} icons`);+ sizes(0, 'svg');+ decorative(0, icons.length);+ }+ if (item.story === 'accessible-name') {+ check(icons.length === 2, `${icons.length} icons`);+ const [meaningful, plain] = icons;+ check(+ meaningful?.role === 'img' &&+ meaningful.ariaLabel === 'Completed' &&+ meaningful.ariaHidden == null,+ 'labelled icon is not a named image',+ );+ check(+ plain?.ariaHidden === 'true' && plain.role == null,+ 'unlabelled icon is not decorative',+ );+ }+ if (item.story === 'inherit-color') {+ check(icons.length === 3, `${icons.length} icons`);+ icons.forEach((icon, index) => {+ check(+ icon.dataColor === 'inherit',+ `inherit ${index}: ${icon.dataColor}`,+ );+ check(+ icon.color === icon.parentColor,+ `inherit ${index}: ${icon.color} vs parent ${icon.parentColor}`,+ );+ });+ }++ const png = await page.screenshot({animations: 'disabled', fullPage: true});+ check(png.length > 1000, 'screenshot is empty');+ const image = `${item.key}.png`;+ const receipt = {+ schemaVersion: 1,+ expected: {+ build: checkoutSha,+ storyId: `core-icon--${item.story}`,+ mode: item.mode,+ direction: item.direction,+ theme: item.theme,+ viewport: item.viewport,+ glyph:+ 'every glyph carries one astryx-icon target with data-size and data-color, is square, paints artwork, has no tab stop, no transform, and no variant reflection; registry artwork fills its wrapper',+ color:+ 'each non-inherit color paints the computed value of its token in this frame; inherit paints the parent text color',+ size: 'sizes grow xsm < sm < md < lg; at the neutral theme they are 12, 16, 20, and 24px',+ accessibility:+ 'icons without label are aria-hidden with no role; a label gives role="img" and that accessible name',+ contrast:+ 'recorded per icon against the nearest painted backdrop for review; not a pass condition',+ },+ 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/Icon',+ 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([]);+});diff --git a/packages/native/src/contract/contracts.test.ts b/packages/native/src/contract/contracts.test.tsindex c5d36a14e2..c6cc054ac0 100644--- a/packages/native/src/contract/contracts.test.ts+++ b/packages/native/src/contract/contracts.test.ts@@ -125,6 +125,12 @@ describe('native contracts', () => {reason: 'type "IconVariant" has no portable definition yet',},{name: 'xstyle', reason: 'web styling input'},+ {+ name: 'className',+ reason: '"className" already means something else in web',+ },+ {name: 'style', reason: 'web styling input'},+ {name: 'ref', reason: 'web element reference'},]);const swift = generateSwift(contracts);