Skip to content

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

TypeScript

[Component Audit] GridSpan: accessibility and RTL audits now reach spanned grid items (#9312)

Cindy Zhang8c15f9975adc
diff --git a/.changeset/grid-span-audit-docs.md b/.changeset/grid-span-audit-docs.md
new file mode 100644
index 0000000000..c2f919815e
--- /dev/null
+++ b/.changeset/grid-span-audit-docs.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[docs] GridSpan: document the `xstyle`, `className`, `style`, and `ref` props, including that a set `columns` or `rows` replaces the same grid placement in `style`.
+
+@cixzhang
diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.json
index 719d3bea8d..dfaa53799d 100644
--- a/apps/storybook/rtl-audit/targets.json
+++ b/apps/storybook/rtl-audit/targets.json
@@ -86,6 +86,15 @@
"next": "[data-testid=\"checkbox-end-content\"]"
}
},
+ {
+ "component": "GridSpan",
+ "storyId": "core-gridspan--span-matrix",
+ "dims": ["D2"],
+ "selectors": {
+ "prev": "[data-audit-case=\"rows\"]",
+ "next": "[data-audit-grid=\"rows\"] > :nth-child(4)"
+ }
+ },
{
"component": "PowerSearch",
"storyId": "core-powersearch--with-date-filters",
diff --git a/apps/storybook/stories/GridSpan.stories.tsx b/apps/storybook/stories/GridSpan.stories.tsx
new file mode 100644
index 0000000000..bd80615c19
--- /dev/null
+++ b/apps/storybook/stories/GridSpan.stories.tsx
@@ -0,0 +1,148 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file GridSpan.stories.tsx
+ * @input Uses Grid and GridSpan with numeric, full, row, long-content, and aligned-row spans
+ * @output Component-owned rendered evidence for GridSpan
+ * @position Storybook evidence; lets GridSpan-scoped accessibility, RTL, and screenshot audits resolve a story
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import type {ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {Grid, GridSpan} from '@astryxdesign/core/Grid';
+import {Text} from '@astryxdesign/core/Text';
+import {
+ colorVars,
+ radiusVars,
+ spacingVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+
+const styles = stylex.create({
+ matrix: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-6'],
+ boxSizing: 'border-box',
+ inlineSize: '100%',
+ maxInlineSize: 720,
+ minInlineSize: 0,
+ },
+ item: {
+ boxSizing: 'border-box',
+ padding: spacingVars['--spacing-3'],
+ backgroundColor: colorVars['--color-background-muted'],
+ borderRadius: radiusVars['--radius-element'],
+ },
+ // A dashed outline keeps each span's extent visible in every theme and
+ // mode, including where the muted fill matches the page surface.
+ spanned: {
+ boxSizing: 'border-box',
+ padding: spacingVars['--spacing-3'],
+ backgroundColor: colorVars['--color-background-muted'],
+ borderRadius: radiusVars['--radius-element'],
+ outline: `1px dashed ${colorVars['--color-border-emphasized']}`,
+ outlineOffset: -1,
+ },
+ tall: {
+ minBlockSize: 96,
+ },
+ narrowHost: {
+ maxInlineSize: 240,
+ minInlineSize: 0,
+ },
+});
+
+function Item({
+ children,
+ isTall,
+ auditItem,
+}: {
+ children: ReactNode;
+ isTall?: boolean;
+ auditItem?: string;
+}) {
+ return (
+ <div
+ data-audit-item={auditItem}
+ {...stylex.props(styles.item, isTall && styles.tall)}>
+ {children}
+ </div>
+ );
+}
+
+function Spanned({children}: {children: ReactNode}) {
+ return <div {...stylex.props(styles.spanned)}>{children}</div>;
+}
+
+const meta: Meta<typeof GridSpan> = {
+ title: 'Core/GridSpan',
+ component: GridSpan,
+ tags: ['autodocs'],
+ parameters: {
+ layout: 'padded',
+ docs: {
+ description: {
+ component:
+ 'An optional wrapper that makes one Grid item span several columns or rows. `columns="full"` covers every explicit column.',
+ },
+ },
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof GridSpan>;
+
+/** Bounded browser fixture for the GridSpan layout contract. */
+export const SpanMatrix: Story = {
+ render: () => (
+ <div {...stylex.props(styles.matrix)}>
+ <Grid data-audit-grid="numeric" columns={3} gap={2}>
+ <GridSpan data-audit-case="numeric" columns={2}>
+ <Spanned>Spans 2 columns</Spanned>
+ </GridSpan>
+ <Item>One</Item>
+ </Grid>
+
+ <Grid data-audit-grid="full" columns={3} gap={2}>
+ <GridSpan data-audit-case="full" columns="full">
+ <Spanned>Spans every explicit column</Spanned>
+ </GridSpan>
+ <Item>One</Item>
+ <Item>Two</Item>
+ <Item>Three</Item>
+ </Grid>
+
+ <Grid data-audit-grid="rows" columns={3} gap={2} rowHeight={48}>
+ <GridSpan data-audit-case="rows" rows={2}>
+ <Spanned>Spans 2 rows</Spanned>
+ </GridSpan>
+ <Item>One</Item>
+ <Item>Two</Item>
+ <Item>Three</Item>
+ <Item>Four</Item>
+ </Grid>
+
+ <div data-audit-host="long-content" {...stylex.props(styles.narrowHost)}>
+ <Grid data-audit-grid="long-content" columns={2} gap={2}>
+ <GridSpan data-audit-case="long-content" columns="full">
+ <Spanned>
+ <Text data-audit-text="long-content" type="body" maxLines={1}>
+ A long single-line label that is much wider than its 240px grid
+ and truncates inside the span
+ </Text>
+ </Spanned>
+ </GridSpan>
+ </Grid>
+ </div>
+
+ <Grid data-audit-grid="aligned" columns={3} gap={2} align="center">
+ <Item isTall>Tall item</Item>
+ <Item auditItem="aligned-plain">Short plain item</Item>
+ <GridSpan data-audit-case="aligned">
+ <Spanned>Short spanned item</Spanned>
+ </GridSpan>
+ </Grid>
+ </div>
+ ),
+};
diff --git a/packages/cli/test/core-doc-types.known-drift.json b/packages/cli/test/core-doc-types.known-drift.json
index 25023e62b7..44a22d9a4b 100644
--- a/packages/cli/test/core-doc-types.known-drift.json
+++ b/packages/cli/test/core-doc-types.known-drift.json
@@ -47,7 +47,6 @@
"packages/core/src/DropdownMenu/DropdownMenuRadioItem.doc.mjs docsZh isHiddenFromOverview unknown_field",
"packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs docsDense isHiddenFromOverview unknown_field",
"packages/core/src/Field/FieldLabel.doc.mjs docsDense isHiddenFromOverview unknown_field",
- "packages/core/src/Grid/GridSpan.doc.mjs docsDense isHiddenFromOverview unknown_field",
"packages/core/src/InputGroup/InputGroupText.doc.mjs docsDense isHiddenFromOverview unknown_field",
"packages/core/src/Layout/LayoutContent.doc.mjs docsDense isHiddenFromOverview unknown_field",
"packages/core/src/Layout/LayoutFooter.doc.mjs docsDense isHiddenFromOverview unknown_field",
diff --git a/packages/core/src/Grid/Grid.test.tsx b/packages/core/src/Grid/Grid.test.tsx
index 72a8204e22..6cb2f3a16f 100644
--- a/packages/core/src/Grid/Grid.test.tsx
+++ b/packages/core/src/Grid/Grid.test.tsx
@@ -9,11 +9,19 @@
* SYNC: When Grid.tsx or GridSpan.tsx changes, update tests to match new behavior
*/
+import {createRef} from 'react';
+import * as stylex from '@stylexjs/stylex';
import {describe, it, expect, vi} from 'vitest';
import {render, screen} from '@testing-library/react';
import {Grid} from './Grid';
import {GridSpan} from './GridSpan';
+const spanStyles = stylex.create({
+ // Overrides a property GridSpan's own styles set, so the consumer value
+ // survives only when xstyle merges after them.
+ consumer: {minWidth: 10},
+});
+
/**
* The track template is applied via a StyleX dynamic style: the element
* carries an inline CSS variable while the `grid-template-columns`
@@ -506,4 +514,93 @@ describe('GridSpan', () => {
);
expect(screen.getByTestId('child')).toBeInTheDocument();
});
+
+ it('carries the grid-span theme target on the element it renders', () => {
+ render(
+ <Grid columns={2}>
+ <GridSpan data-testid="span">Item</GridSpan>
+ </Grid>,
+ );
+ expect(screen.getByTestId('span')).toHaveClass('astryx-grid-span');
+ });
+
+ it('resolves ref to the rendered span element', () => {
+ const ref = createRef<HTMLDivElement>();
+ render(
+ <Grid columns={2}>
+ <GridSpan ref={ref} data-testid="span">
+ Item
+ </GridSpan>
+ </Grid>,
+ );
+ expect(ref.current).toBeInstanceOf(HTMLDivElement);
+ expect(ref.current).toBe(screen.getByTestId('span'));
+ });
+
+ it('applies its spans after the caller style and keeps the rest of it', () => {
+ render(
+ <Grid columns={4}>
+ <GridSpan
+ columns={2}
+ rows={3}
+ data-testid="span"
+ style={{gridColumn: '1 / 2', gridRow: '1', opacity: 0.5}}>
+ Item
+ </GridSpan>
+ </Grid>,
+ );
+ const span = screen.getByTestId('span');
+ expect(span.style.gridColumn).toBe('span 2');
+ expect(span.style.gridRow).toBe('span 3');
+ expect(span.style.opacity).toBe('0.5');
+ });
+
+ it('leaves caller grid placement alone when no span is set', () => {
+ render(
+ <Grid columns={4}>
+ <GridSpan data-testid="span" style={{gridColumn: '2 / 4'}}>
+ Item
+ </GridSpan>
+ </Grid>,
+ );
+ expect(screen.getByTestId('span').style.gridColumn).toBe('2 / 4');
+ });
+
+ it('merges className and xstyle with its own target class', () => {
+ render(
+ <Grid columns={2}>
+ <GridSpan
+ data-testid="span"
+ className="consumer-span"
+ xstyle={spanStyles.consumer}>
+ Item
+ </GridSpan>
+ </Grid>,
+ );
+ const span = screen.getByTestId('span');
+ const consumerClasses = (stylex.props(spanStyles.consumer).className ?? '')
+ .split(' ')
+ .filter(Boolean);
+ expect(consumerClasses.length).toBeGreaterThan(0);
+ expect(span).toHaveClass(
+ 'astryx-grid-span',
+ 'consumer-span',
+ ...consumerClasses,
+ );
+ });
+
+ it('adds no role, accessible name, or tab stop of its own', () => {
+ render(
+ <Grid columns={2}>
+ <GridSpan columns="full" data-testid="span">
+ <button type="button">Action</button>
+ </GridSpan>
+ </Grid>,
+ );
+ const span = screen.getByTestId('span');
+ expect(span).not.toHaveAttribute('role');
+ expect(span).not.toHaveAttribute('tabindex');
+ expect(span).not.toHaveAttribute('aria-label');
+ expect(screen.getByRole('button', {name: 'Action'})).toBeInTheDocument();
+ });
});
diff --git a/packages/core/src/Grid/GridSpan.doc.mjs b/packages/core/src/Grid/GridSpan.doc.mjs
index 489e3b67d6..1d653f6be4 100644
--- a/packages/core/src/Grid/GridSpan.doc.mjs
+++ b/packages/core/src/Grid/GridSpan.doc.mjs
@@ -19,7 +19,8 @@ export const docs = {
{
name: 'columns',
type: "number | 'full'",
- description: "Columns to span; use `'full'` to span all explicit columns.",
+ description:
+ "Columns to span; use `'full'` to span all explicit columns.",
},
{
name: 'rows',
@@ -31,6 +32,28 @@ export const docs = {
type: 'ReactNode',
description: 'Content.',
},
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description:
+ 'StyleX styles applied to the span wrapper. Must be a stylex.create() value: not an inline style object like style={{}}.',
+ },
+ {
+ name: 'className',
+ type: 'string',
+ description: 'CSS class name applied to the span wrapper.',
+ },
+ {
+ name: 'style',
+ type: 'React.CSSProperties',
+ description:
+ 'Inline styles applied to the span wrapper. When `columns` or `rows` is set, its `grid-column` or `grid-row` replaces the same property in `style`.',
+ },
+ {
+ name: 'ref',
+ type: 'React.Ref<HTMLDivElement>',
+ description: 'Ref forwarded to the span wrapper.',
+ },
],
};
@@ -55,17 +78,43 @@ export const docsZh = {
type: 'ReactNode',
description: '内容。',
},
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description:
+ '应用于跨度包装元素的 StyleX 样式。必须是 stylex.create() 的值,而不是 style={{}} 这样的内联样式对象。',
+ },
+ {
+ name: 'className',
+ type: 'string',
+ description: '应用于跨度包装元素的 CSS 类名。',
+ },
+ {
+ name: 'style',
+ type: 'React.CSSProperties',
+ description:
+ '应用于跨度包装元素的内联样式。设置 `columns` 或 `rows` 时,其 `grid-column` 或 `grid-row` 会替换 `style` 中的同名属性。',
+ },
+ {
+ name: 'ref',
+ type: 'React.Ref<HTMLDivElement>',
+ description: '转发到跨度包装元素的 Ref。',
+ },
],
};
export const docsDense = {
name: 'GridSpan',
- isHiddenFromOverview: true,
displayName: 'Grid Span',
description: 'Grid item spanning multiple columns/rows.',
propDescriptions: {
columns: "Columns to span; 'full' spans all explicit columns.",
rows: 'Rows to span.',
children: 'Content.',
+ xstyle: 'StyleX styles on the span wrapper; stylex.create() value only.',
+ className: 'CSS class on the span wrapper.',
+ style:
+ 'inline styles on the span wrapper; a set columns/rows replaces its grid-column/grid-row.',
+ ref: 'ref to the span wrapper div.',
},
};
diff --git a/packages/core/src/Grid/GridSpan.tsx b/packages/core/src/Grid/GridSpan.tsx
index 7f6f4cde35..7c109c5292 100644
--- a/packages/core/src/Grid/GridSpan.tsx
+++ b/packages/core/src/Grid/GridSpan.tsx
@@ -7,8 +7,10 @@
* @position Grid span component; controls grid item span
*
* SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Grid/GridSpan.doc.mjs
* - /packages/core/src/Grid/Grid.doc.mjs
* - /packages/core/src/Grid/Grid.test.tsx
+ * - /apps/storybook/stories/GridSpan.stories.tsx
* - /apps/storybook/stories/Grid.stories.tsx
* - /packages/cli/assets/templates/blocks/components/Grid/ (showcase blocks)
*/
diff --git a/packages/core/src/Grid/__tests__/GridSpanAudit.a11y.chromium.spec.ts b/packages/core/src/Grid/__tests__/GridSpanAudit.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..663f5eff0b
--- /dev/null
+++ b/packages/core/src/Grid/__tests__/GridSpanAudit.a11y.chromium.spec.ts
@@ -0,0 +1,467 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y audit GridSpan
+
+/**
+ * @file GridSpanAudit.a11y.chromium.spec.ts
+ * @input Exact-head GridSpan span matrix across themes, modes, direction, and viewport
+ * @output Screenshots and fail-closed sensor receipts for the GridSpan whole-component audit
+ * @position Component-owned Night Watch browser evidence; CI runs it only for a GridSpan 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('grid-span-audit-evidence');
+const STORY_ID = 'core-gridspan--span-matrix';
+const WIDE = {width: 1024, height: 900};
+const NARROW = {width: 320, height: 1100};
+const ROW_HEIGHT = 48;
+
+type Mode = 'light' | 'dark';
+type Direction = 'ltr' | 'rtl';
+type Theme = 'neutral' | 'butter';
+
+type AuditCase = {
+ key: string;
+ mode: Mode;
+ direction: Direction;
+ theme: Theme;
+ viewport: {width: number; height: number};
+};
+
+type AuditReceipt = {
+ passed: boolean;
+ expected: Record<string, unknown>;
+ failures: string[];
+};
+
+const EXPECTED_CASES = ['numeric', 'full', 'rows', 'long-content', 'aligned'];
+
+const cases: AuditCase[] = [];
+function addPair(
+ key: string,
+ options: Partial<Omit<AuditCase, 'key' | 'mode'>> = {},
+) {
+ for (const mode of ['light', 'dark'] as const) {
+ cases.push({
+ key: `${key}-${mode}`,
+ mode,
+ direction: options.direction ?? 'ltr',
+ theme: options.theme ?? 'neutral',
+ viewport: options.viewport ?? WIDE,
+ });
+ }
+}
+
+addPair('default');
+addPair('custom-theme', {theme: 'butter'});
+addPair('rtl', {direction: 'rtl'});
+addPair('narrow', {viewport: NARROW});
+
+test.describe.configure({mode: 'serial', retries: 0});
+let server: StaticServer;
+let checkoutSha: string;
+let storybookSha: string;
+
+function storyUrl(item: AuditCase) {
+ return `${server.origin}/iframe.html?id=${STORY_ID}&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((expectedCases: string[]) => {
+ const round = (value: number) => Math.round(value * 10) / 10;
+ function box(element: Element | null) {
+ if (element == null) {
+ return null;
+ }
+ const rect = element.getBoundingClientRect();
+ return {
+ left: round(rect.left),
+ right: round(rect.right),
+ top: round(rect.top),
+ bottom: round(rect.bottom),
+ width: round(rect.width),
+ height: round(rect.height),
+ };
+ }
+ function tracks(value: string): number[] {
+ return value
+ .split(' ')
+ .map(part => Number.parseFloat(part))
+ .filter(part => Number.isFinite(part));
+ }
+
+ const spans = Array.from(
+ document.querySelectorAll<HTMLElement>('[data-audit-case]'),
+ ).map(span => {
+ const grid = span.parentElement as HTMLElement;
+ const gridStyle = getComputedStyle(grid);
+ const style = getComputedStyle(span);
+ const child = span.firstElementChild;
+ return {
+ auditCase: span.getAttribute('data-audit-case'),
+ className: span.className,
+ hasTarget: span.classList.contains('astryx-grid-span'),
+ tagName: span.tagName,
+ role: span.getAttribute('role'),
+ tabIndex: span.getAttribute('tabindex'),
+ ariaLabel: span.getAttribute('aria-label'),
+ inlineGridColumn: span.style.gridColumn,
+ inlineGridRow: span.style.gridRow,
+ display: style.display,
+ innerTracks: tracks(style.gridTemplateColumns),
+ minWidth: style.minWidth,
+ direction: style.direction,
+ gridColumnTracks: tracks(gridStyle.gridTemplateColumns),
+ gridRowTracks: tracks(gridStyle.gridTemplateRows),
+ columnGap: Number.parseFloat(gridStyle.columnGap) || 0,
+ rowGap: Number.parseFloat(gridStyle.rowGap) || 0,
+ gridPaddingInline:
+ (Number.parseFloat(gridStyle.paddingLeft) || 0) +
+ (Number.parseFloat(gridStyle.paddingRight) || 0),
+ span: box(span),
+ grid: box(grid),
+ child: box(child),
+ childOverflowsSpan:
+ child != null &&
+ (child.getBoundingClientRect().left <
+ span.getBoundingClientRect().left - 0.5 ||
+ child.getBoundingClientRect().right >
+ span.getBoundingClientRect().right + 0.5),
+ };
+ });
+ const host = document.querySelector('[data-audit-host="long-content"]');
+ const truncating = host?.querySelector('[data-audit-text="long-content"]');
+ const plain = document.querySelector('[data-audit-item="aligned-plain"]');
+ const tall = plain?.previousElementSibling ?? null;
+ const root = document.querySelector<HTMLElement>('.astryx-grid-span');
+ return {
+ theme: document
+ .querySelector('[data-astryx-theme]')
+ ?.getAttribute('data-astryx-theme'),
+ mode: document.documentElement.getAttribute('data-theme'),
+ direction: root ? getComputedStyle(root).direction : null,
+ 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'),
+ cases: spans.map(span => span.auditCase),
+ expectedCases,
+ spans,
+ longContent: {
+ host: box(host ?? null),
+ text: box(truncating ?? null),
+ textClipped:
+ truncating != null &&
+ (truncating as HTMLElement).scrollWidth >
+ (truncating as HTMLElement).clientWidth,
+ },
+ aligned: {
+ tall: box(tall),
+ plain: box(plain),
+ },
+ };
+ }, EXPECTED_CASES);
+}
+
+test.beforeAll(async () => {
+ fs.rmSync(OUTPUT, {recursive: true, force: true});
+ fs.mkdirSync(OUTPUT, {recursive: true});
+ checkoutSha = execFileSync('git', ['rev-parse', 'HEAD'], {
+ encoding: 'utf8',
+ }).trim();
+ const expected = process.env.ASTRYX_HEAD_SHA;
+ if (expected && expected !== checkoutSha) {
+ throw new Error(
+ `checkout ${checkoutSha} does not match expected head ${expected}`,
+ );
+ }
+ server = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+ const response = await fetch(`${server.origin}/astryx-build-sha.txt`);
+ if (!response.ok) {
+ throw new Error(`Storybook build has no SHA stamp (${response.status})`);
+ }
+ storybookSha = (await response.text()).trim();
+ if (storybookSha !== checkoutSha) {
+ throw new Error(
+ `Storybook ${storybookSha} does not match checkout ${checkoutSha}`,
+ );
+ }
+});
+
+test.afterAll(async () => {
+ await server?.close();
+});
+
+for (const item of cases) {
+ test(item.key, async ({browser}) => {
+ const context = await browser.newContext({
+ viewport: item.viewport,
+ deviceScaleFactor: 1,
+ colorScheme: item.mode,
+ reducedMotion: 'reduce',
+ });
+ const page = await context.newPage();
+ const pageErrors: string[] = [];
+ page.on('pageerror', error => pageErrors.push(String(error)));
+ await page.goto(storyUrl(item), {waitUntil: 'load'});
+ await page.locator('#storybook-root').waitFor();
+ await expect(page.locator('[data-audit-case]')).toHaveCount(
+ EXPECTED_CASES.length,
+ );
+
+ 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.spans.map(span => span.span)) ===
+ JSON.stringify(observed.spans.map(span => span.span));
+
+ 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(
+ JSON.stringify(observed.cases) === JSON.stringify(EXPECTED_CASES),
+ `cases ${observed.cases.join(',')}`,
+ );
+ check(!observed.documentOverflow, 'document scrolls horizontally');
+
+ const spanAlignedObservation: Record<string, unknown> = {};
+ for (const span of observed.spans) {
+ const id = span.auditCase ?? 'unknown';
+ const spanBox = span.span;
+ const gridBox = span.grid;
+ if (spanBox == null || gridBox == null) {
+ check(false, `${id}: span or grid not measured`);
+ continue;
+ }
+ // FR1: one div carrying the grid-span target, a one-track grid with a
+ // zero minimum width. AR1: no role, name, or tab stop of its own.
+ check(span.tagName === 'DIV', `${id}: renders ${span.tagName}`);
+ check(span.hasTarget, `${id}: no astryx-grid-span target`);
+ check(span.display === 'grid', `${id}: display ${span.display}`);
+ check(
+ span.innerTracks.length === 1,
+ `${id}: inner tracks ${span.innerTracks.join(' ')}`,
+ );
+ check(span.minWidth === '0px', `${id}: min-width ${span.minWidth}`);
+ check(
+ span.role == null && span.tabIndex == null && span.ariaLabel == null,
+ `${id}: span adds role, tab stop, or name`,
+ );
+ check(span.direction === item.direction, `${id}: direction`);
+ check(!span.childOverflowsSpan, `${id}: content escapes the span`);
+
+ const [firstTrack = 0, secondTrack = 0] = span.gridColumnTracks;
+ // Auto placement puts every audited span at the inline start.
+ const startEdgeMatches =
+ item.direction === 'rtl'
+ ? near(spanBox.right, gridBox.right)
+ : near(spanBox.left, gridBox.left);
+
+ if (id === 'numeric') {
+ // FR2: columns={2} spans two explicit tracks and one gap.
+ check(span.inlineGridColumn === 'span 2', `${id}: inline column`);
+ check(
+ near(spanBox.width, firstTrack + secondTrack + span.columnGap),
+ `${id}: width ${spanBox.width} is not two tracks plus a gap`,
+ );
+ check(startEdgeMatches, `${id}: does not start at the inline start`);
+ }
+ if (id === 'full' || id === 'long-content') {
+ // FR2: 'full' covers every explicit column, line 1 to -1.
+ check(span.inlineGridColumn === '1 / -1', `${id}: inline column`);
+ check(
+ near(spanBox.width, gridBox.width - span.gridPaddingInline),
+ `${id}: width ${spanBox.width} is not the grid's content width`,
+ );
+ check(startEdgeMatches, `${id}: does not start at the inline start`);
+ }
+ if (id === 'rows') {
+ // FR2: rows={2} spans two rowHeight tracks and one row gap.
+ check(span.inlineGridRow === 'span 2', `${id}: inline row`);
+ check(
+ near(spanBox.height, ROW_HEIGHT * 2 + span.rowGap),
+ `${id}: height ${spanBox.height} is not two rows plus a gap`,
+ );
+ check(
+ near(spanBox.width, firstTrack),
+ `${id}: width ${spanBox.width} is not one track`,
+ );
+ check(startEdgeMatches, `${id}: does not start at the inline start`);
+ }
+ if (id === 'long-content') {
+ // AR2: the zero minimum width keeps shrinkable content in its track.
+ const host = observed.longContent.host;
+ const text = observed.longContent.text;
+ check(host != null && text != null, `${id}: host or text missing`);
+ if (host != null && text != null) {
+ check(
+ spanBox.left >= host.left - 0.5 &&
+ spanBox.right <= host.right + 0.5,
+ `${id}: span escapes its 240px host`,
+ );
+ check(
+ text.left >= host.left - 0.5 && text.right <= host.right + 0.5,
+ `${id}: text escapes its 240px host`,
+ );
+ }
+ check(observed.longContent.textClipped, `${id}: text did not truncate`);
+ }
+ if (id === 'aligned') {
+ // Observation for the owner: Grid align="center" positions plain
+ // items, while GridSpan's full height stretches its content.
+ const tall = observed.aligned.tall;
+ const plain = observed.aligned.plain;
+ spanAlignedObservation.tall = tall;
+ spanAlignedObservation.plain = plain;
+ spanAlignedObservation.span = spanBox;
+ spanAlignedObservation.spannedContent = span.child;
+ if (tall != null && plain != null && span.child != null) {
+ spanAlignedObservation.plainCentered =
+ plain.height < tall.height - 1 &&
+ near(plain.top - tall.top, tall.bottom - plain.bottom);
+ spanAlignedObservation.spannedContentFillsRow = near(
+ span.child.height,
+ tall.height,
+ );
+ }
+ }
+ }
+
+ 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: STORY_ID,
+ mode: item.mode,
+ direction: item.direction,
+ theme: item.theme,
+ viewport: item.viewport,
+ cases: EXPECTED_CASES,
+ geometry:
+ 'numeric spans two tracks and a gap; full and long-content span the grid content width; rows spans two 48px rows and a gap; every span starts at the inline start',
+ reflow:
+ 'no span content escapes its span, the long-content span and text stay inside the 240px host, and the document never scrolls horizontally',
+ },
+ observed: {
+ build: storybookSha,
+ ...observed,
+ geometryStable,
+ pageErrors,
+ },
+ observations: {
+ alignCenter: spanAlignedObservation,
+ },
+ 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();
+ });
+}
+
+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/GridSpan',
+ 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);
+ expect(
+ receipts
+ .filter(receipt => !receipt.passed)
+ .map(receipt => ({frame: receipt.expected, failures: receipt.failures})),
+ ).toEqual([]);
+});