Skip to content

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

TypeScript

[Component Audit] LayoutFooter: spacing above the footer always follows its divider (#10674)

Cindy Zhang9d753c5c2c4d
diff --git a/.changeset/layout-footer-keeps-divider-state.md b/.changeset/layout-footer-keeps-divider-state.md
new file mode 100644
index 0000000000..1de30fa3e2
--- /dev/null
+++ b/.changeset/layout-footer-keeps-divider-state.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `LayoutFooter`: a `data-divider` attribute passed by the caller no longer replaces the divider state the footer reflects, so the content above a footer without a divider keeps its collapsed spacing, and a footer with a divider keeps its spacing above the line. The docs now list `padding` and `ref`, and say that an unset `hasDivider` follows the Layout's `defaultHasDividers`.
+
+@cixzhang
diff --git a/.github/a11y-audit-axe.json b/.github/a11y-audit-axe.json
index 52e1422079..b4258aa174 100644
--- a/.github/a11y-audit-axe.json
+++ b/.github/a11y-audit-axe.json
@@ -35,5 +35,15 @@
"stories": ["core-hovercard--open-states"],
"readySelector": "[role=\"dialog\"]"
},
- "InputGroupText": {"components": ["InputGroupText", "InputGroup"]}
+ "InputGroupText": {"components": ["InputGroupText", "InputGroup"]},
+ "LayoutFooter": {
+ "components": ["Layout"],
+ "stories": [
+ "core-layout--footer-states",
+ "core-layout--basic-card",
+ "core-layout--with-sidebar",
+ "core-layout--no-dividers",
+ "core-layout--full-bleed-content"
+ ]
+ }
}
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index f3183df8ad..563fdd84db 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -165,6 +165,14 @@
"component": "core/FormLayout",
"reason": "FormLayout arranges caller-owned fields with grid/block flow, logical gaps, and responsive columns. It owns no directional glyph, physical inline placement, transform, scrolling action, dragging, overlay, or keyboard behavior."
},
+ {
+ "component": "core/LayoutFooter",
+ "reason": "LayoutFooter is a block-axis band below the Layout's middle row. Its inner wrapper uses logical padding with the same value on both inline edges, its width is capped at the content width, and it centers inside the footer with marginInline auto. Its only line is on the block-start edge. It owns no directional glyph, physical inline offset or transform, inline ordering, scrolling, dragging, overlay, or keyboard behavior. Caller content follows the document direction."
+ },
+ {
+ "component": "core/LayoutHeader",
+ "reason": "LayoutHeader is a block-axis band above the Layout's middle row. Its inner wrapper uses logical padding with the same value on both inline edges; its width is capped at the content width, and it centers inside the header with marginInline auto. The only per-edge override, paddingBlockEnd, is on the block axis, and its only line is on the block-end edge. It owns no directional glyph, physical inline offset or transform, inline ordering, scrolling, dragging, overlay, or keyboard behavior. Caller content follows the document direction."
+ },
{
"component": "core/Item",
"reason": "Item places start content, text, and end content in normal flex flow using logical padding, text-align:start, and margin-inline-start:auto. Those slots mirror through CSS direction without component branching; Item owns no directional glyph or directional keyboard behavior."
diff --git a/apps/storybook/stories/Layout.stories.tsx b/apps/storybook/stories/Layout.stories.tsx
index 9fc4e7d573..265f915274 100644
--- a/apps/storybook/stories/Layout.stories.tsx
+++ b/apps/storybook/stories/Layout.stories.tsx
@@ -1865,3 +1865,213 @@ export const ContentInsets: Story = {
);
},
};
+
+/**
+ * LayoutFooter in each configuration, in plain frames with no padding
+ * container: the inner inset is spacing step 4, and `padding={6}` sets the
+ * Layout-edge inset. Each case names its footer with `data-footer-case`. The
+ * nested case puts a Layout with a divided footer above an outer footer
+ * without a divider. The caller-attribute case passes its own `data-divider`,
+ * which must not replace the value the footer reflects.
+ */
+export const FooterStates: Story = {
+ name: 'Footer States',
+ render: () => {
+ const body = <p {...stylex.props(styles.bodyText)}>Content area.</p>;
+ const tallBody = (
+ <VStack gap={2}>
+ {Array.from({length: 12}, (_, index) => (
+ <p key={index} {...stylex.props(styles.bodyText)}>
+ Row {index + 1}
+ </p>
+ ))}
+ {/* A focusable control keeps the scrolling content keyboard-reachable. */}
+ <Button label="Load more" variant="secondary">
+ Load more
+ </Button>
+ </VStack>
+ );
+ const footerText = <p {...stylex.props(styles.bodyText)}>Footer</p>;
+ const cases = [
+ {
+ id: 'automatic',
+ label: 'No divider, padding=6',
+ layout: (
+ <Layout
+ padding={6}
+ content={<LayoutContent>{body}</LayoutContent>}
+ footer={
+ <LayoutFooter data-footer-case="automatic">
+ {footerText}
+ </LayoutFooter>
+ }
+ />
+ ),
+ },
+ {
+ id: 'divider',
+ label: 'hasDivider, padding=6',
+ layout: (
+ <Layout
+ padding={6}
+ content={<LayoutContent>{body}</LayoutContent>}
+ footer={
+ <LayoutFooter hasDivider data-footer-case="divider">
+ {footerText}
+ </LayoutFooter>
+ }
+ />
+ ),
+ },
+ {
+ id: 'layout-default',
+ label: 'Layout defaultHasDividers',
+ layout: (
+ <Layout
+ padding={6}
+ defaultHasDividers
+ content={<LayoutContent>{body}</LayoutContent>}
+ footer={
+ <LayoutFooter data-footer-case="layout-default">
+ {footerText}
+ </LayoutFooter>
+ }
+ />
+ ),
+ },
+ {
+ id: 'explicit-off',
+ label: 'Layout defaultHasDividers, hasDivider={false}',
+ layout: (
+ <Layout
+ padding={6}
+ defaultHasDividers
+ content={<LayoutContent>{body}</LayoutContent>}
+ footer={
+ <LayoutFooter hasDivider={false} data-footer-case="explicit-off">
+ {footerText}
+ </LayoutFooter>
+ }
+ />
+ ),
+ },
+ {
+ id: 'padding-2',
+ label: 'hasDivider, footer padding=2',
+ layout: (
+ <Layout
+ padding={6}
+ content={<LayoutContent>{body}</LayoutContent>}
+ footer={
+ <LayoutFooter hasDivider padding={2} data-footer-case="padding-2">
+ {footerText}
+ </LayoutFooter>
+ }
+ />
+ ),
+ },
+ {
+ id: 'full-bleed',
+ label: 'hasDivider, footer padding=0',
+ layout: (
+ <Layout
+ padding={6}
+ content={<LayoutContent>{body}</LayoutContent>}
+ footer={
+ <LayoutFooter
+ hasDivider
+ padding={0}
+ data-footer-case="full-bleed">
+ {footerText}
+ </LayoutFooter>
+ }
+ />
+ ),
+ },
+ {
+ id: 'height',
+ label: 'hasDivider, height=72 below overflowing content',
+ layout: (
+ <Layout
+ padding={6}
+ content={<LayoutContent>{tallBody}</LayoutContent>}
+ footer={
+ <LayoutFooter hasDivider height={72} data-footer-case="height">
+ {footerText}
+ </LayoutFooter>
+ }
+ />
+ ),
+ },
+ {
+ id: 'content-width',
+ label: 'hasDivider, Layout contentWidth=240',
+ layout: (
+ <Layout
+ padding={6}
+ contentWidth={240}
+ content={<LayoutContent>{body}</LayoutContent>}
+ footer={
+ <LayoutFooter hasDivider data-footer-case="content-width">
+ {footerText}
+ </LayoutFooter>
+ }
+ />
+ ),
+ },
+ {
+ id: 'nested',
+ label: 'Nested Layout above an outer footer without divider',
+ layout: (
+ <Layout
+ padding={6}
+ content={
+ <LayoutContent padding={0}>
+ <Layout
+ content={<LayoutContent>{body}</LayoutContent>}
+ footer={
+ <LayoutFooter hasDivider data-footer-case="nested">
+ {footerText}
+ </LayoutFooter>
+ }
+ />
+ </LayoutContent>
+ }
+ footer={<LayoutFooter>{footerText}</LayoutFooter>}
+ />
+ ),
+ },
+ {
+ id: 'caller-attribute',
+ label: 'No divider, caller data-divider="false"',
+ layout: (
+ <Layout
+ padding={6}
+ content={<LayoutContent>{body}</LayoutContent>}
+ footer={
+ <LayoutFooter
+ data-divider="false"
+ data-footer-case="caller-attribute">
+ {footerText}
+ </LayoutFooter>
+ }
+ />
+ ),
+ },
+ ];
+ return (
+ <VStack gap={4} xstyle={styles.storySection}>
+ <HStack gap={4} wrap="wrap">
+ {cases.map(({id, label, layout}) => (
+ <VStack key={id} gap={2}>
+ <p {...stylex.props(styles.subheading)}>{label}</p>
+ <div {...stylex.props(styles.cwContainer, styles.insetFrame)}>
+ {layout}
+ </div>
+ </VStack>
+ ))}
+ </HStack>
+ </VStack>
+ );
+ },
+};
diff --git a/packages/cli/test/core-prop-docs.known-drift.json b/packages/cli/test/core-prop-docs.known-drift.json
index 97c64caaed..47462d8e5c 100644
--- a/packages/cli/test/core-prop-docs.known-drift.json
+++ b/packages/cli/test/core-prop-docs.known-drift.json
@@ -21,7 +21,6 @@
"src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs DropdownMenuCheckboxItem.value required_mismatch",
"src/FieldStatus/FieldStatus.doc.mjs FieldStatus.variant type_mismatch",
"src/HoverCard/HoverCard.doc.mjs HoverCard.children required_mismatch",
- "src/Layout/LayoutFooter.doc.mjs LayoutFooter.padding not_in_doc",
"src/Layout/LayoutHeader.doc.mjs LayoutHeader.padding not_in_doc",
"src/Link/Link.doc.mjs Link.type not_in_doc",
"src/List/List.doc.mjs List.children required_mismatch",
diff --git a/packages/core/src/Layout/Layout.test.tsx b/packages/core/src/Layout/Layout.test.tsx
index 1848aecabe..9b45744c06 100644
--- a/packages/core/src/Layout/Layout.test.tsx
+++ b/packages/core/src/Layout/Layout.test.tsx
@@ -280,6 +280,42 @@ describe('Layout', () => {
).not.toHaveAttribute('data-divider');
});
+ it('an explicit hasDivider={false} on a footer overrides the context default', () => {
+ const {container} = render(
+ <Layout
+ defaultHasDividers
+ footer={<LayoutFooter hasDivider={false}>F</LayoutFooter>}
+ content={<div>c</div>}
+ />,
+ );
+ expect(
+ container.querySelector('.astryx-layout-footer'),
+ ).not.toHaveAttribute('data-divider');
+ });
+
+ it('stops the footer default at a layer boundary', () => {
+ render(
+ <Layout
+ defaultHasDividers
+ content={
+ <Dialog
+ isOpen
+ isInline
+ aria-label="Settings"
+ onOpenChange={() => {}}>
+ <Layout
+ content={<div>c</div>}
+ footer={<LayoutFooter>In dialog</LayoutFooter>}
+ />
+ </Dialog>
+ }
+ />,
+ );
+ expect(
+ screen.getByText('In dialog').closest('.astryx-layout-footer'),
+ ).not.toHaveAttribute('data-divider');
+ });
+
it('an explicit hasDivider={false} on a header overrides the context default', () => {
const {container} = render(
<Layout
diff --git a/packages/core/src/Layout/LayoutFooter.doc.mjs b/packages/core/src/Layout/LayoutFooter.doc.mjs
index 408ae4257a..0e51067dc6 100644
--- a/packages/core/src/Layout/LayoutFooter.doc.mjs
+++ b/packages/core/src/Layout/LayoutFooter.doc.mjs
@@ -34,24 +34,37 @@ export const docs = {
{
name: 'hasDivider',
type: 'boolean',
- description: 'Border at top edge.',
+ description:
+ "Border at top edge. When unset, the parent Layout's defaultHasDividers decides.",
default: 'false',
},
{
name: 'height',
type: 'SizeValue',
- description: 'Footer height. Numbers are treated as pixels, strings are used as-is.',
+ description:
+ 'Footer height. Numbers are treated as pixels, strings are used as-is.',
},
{
name: 'label',
type: 'string',
description: 'Accessible label for the landmark element.',
},
+ {
+ name: 'padding',
+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',
+ description:
+ 'Internal padding on every edge, using the spacing scale. Replaces the inset from the layout; 0 is full bleed.',
+ },
{
name: 'role',
type: 'AriaRole',
description: 'ARIA landmark role.',
},
+ {
+ name: 'ref',
+ type: 'React.Ref<HTMLDivElement>',
+ description: 'Ref forwarded to the footer element.',
+ },
],
};
@@ -69,7 +82,8 @@ export const docsZh = {
{
name: 'hasDivider',
type: 'boolean',
- description: '顶部边缘的边框。',
+ description:
+ '顶部边缘的边框。未设置时,由父级 Layout 的 defaultHasDividers 决定。',
default: 'false',
},
{
@@ -82,11 +96,22 @@ export const docsZh = {
type: 'string',
description: '地标元素的无障碍标签。',
},
+ {
+ name: 'padding',
+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',
+ description:
+ '所有边的内边距,使用间距刻度。替换布局提供的内边距;0 表示全出血。',
+ },
{
name: 'role',
type: 'AriaRole',
description: 'ARIA 地标角色。',
},
+ {
+ name: 'ref',
+ type: 'React.Ref<HTMLDivElement>',
+ description: '转发到页脚元素的 ref。',
+ },
],
};
@@ -97,9 +122,12 @@ export const docsDense = {
description: 'Bottom bar for action bars, pagination, status bars.',
propDescriptions: {
children: 'Footer content.',
- hasDivider: 'Border at top edge.',
+ hasDivider: 'Border at top edge; unset uses the Layout default.',
height: 'Footer height.',
label: 'Accessible label for landmark element.',
+ padding:
+ 'Padding on every edge; replaces the layout inset. 0 is full bleed.',
role: 'ARIA landmark role.',
+ ref: 'Ref forwarded to the footer element.',
},
};
diff --git a/packages/core/src/Layout/LayoutFooter.tsx b/packages/core/src/Layout/LayoutFooter.tsx
index c7ff873370..e995083a79 100644
--- a/packages/core/src/Layout/LayoutFooter.tsx
+++ b/packages/core/src/Layout/LayoutFooter.tsx
@@ -127,12 +127,12 @@ export interface LayoutFooterProps extends BaseProps<HTMLDivElement> {
*
* @example
* ```
- * <LayoutContainer variant="card">
+ * <Card>
* <Layout
* content={<LayoutContent>...</LayoutContent>}
* footer={<LayoutFooter hasDivider>Actions</LayoutFooter>}
* />
- * </LayoutContainer>
+ * </Card>
* ```
*/
export function LayoutFooter({
@@ -158,7 +158,6 @@ export function LayoutFooter({
ref={ref}
role={role}
aria-label={label}
- data-divider={resolvedHasDivider || undefined}
{...mergeProps(
themeProps('layout-footer'),
stylex.props(
@@ -172,7 +171,8 @@ export function LayoutFooter({
className,
style,
)}
- {...props}>
+ {...props}
+ data-divider={resolvedHasDivider || undefined}>
<div
{...stylex.props(
styles.inner,
diff --git a/packages/core/src/Layout/LayoutSlots.test.tsx b/packages/core/src/Layout/LayoutSlots.test.tsx
index 4d213bc30d..a413b10131 100644
--- a/packages/core/src/Layout/LayoutSlots.test.tsx
+++ b/packages/core/src/Layout/LayoutSlots.test.tsx
@@ -189,6 +189,58 @@ describe('LayoutFooter', () => {
expect(ref.current).toBeInstanceOf(HTMLDivElement);
expect(ref.current?.className).toContain('astryx-layout-footer');
});
+
+ it('applies a numeric height as pixels on the root', () => {
+ const {container} = render(<LayoutFooter height={72}>F</LayoutFooter>);
+ const el = container.querySelector('.astryx-layout-footer') as HTMLElement;
+ expect(el.getAttribute('style') ?? '').toContain('72px');
+ });
+
+ it('exposes no role or name without a caller role', () => {
+ const {container} = render(<LayoutFooter>F</LayoutFooter>);
+ const footer = container.querySelector('.astryx-layout-footer');
+ expect(footer).not.toHaveAttribute('role');
+ expect(footer).not.toHaveAttribute('aria-label');
+ });
+
+ it('passes className, style, DOM, data, and event props to the root', () => {
+ const onClick = vi.fn();
+ render(
+ <LayoutFooter
+ className="caller"
+ style={{color: 'red'}}
+ id="page-footer"
+ data-testid="footer"
+ aria-describedby="hint"
+ onClick={onClick}>
+ F
+ </LayoutFooter>,
+ );
+ const footer = screen.getByTestId('footer');
+ expect(footer).toHaveClass('astryx-layout-footer', 'caller');
+ expect(footer.style.color).toBe('red');
+ expect(footer).toHaveAttribute('id', 'page-footer');
+ expect(footer).toHaveAttribute('aria-describedby', 'hint');
+ fireEvent.click(screen.getByText('F'));
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps data-divider when a caller passes its own value', () => {
+ const {container, rerender} = render(
+ <LayoutFooter data-divider="false">F</LayoutFooter>,
+ );
+ const sel = '.astryx-layout-footer';
+ expect(container.querySelector(sel)).not.toHaveAttribute('data-divider');
+ rerender(
+ <LayoutFooter hasDivider {...{'data-divider': undefined}}>
+ F
+ </LayoutFooter>,
+ );
+ expect(container.querySelector(sel)).toHaveAttribute(
+ 'data-divider',
+ 'true',
+ );
+ });
});
// =============================================================================
diff --git a/packages/core/src/Layout/__tests__/LayoutFooterAudit.a11y.chromium.spec.ts b/packages/core/src/Layout/__tests__/LayoutFooterAudit.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..f00f3b2dce
--- /dev/null
+++ b/packages/core/src/Layout/__tests__/LayoutFooterAudit.a11y.chromium.spec.ts
@@ -0,0 +1,628 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y audit LayoutFooter
+
+/**
+ * @file LayoutFooterAudit.a11y.chromium.spec.ts
+ * @input Exact-head Core/Layout stories across themes, modes, direction, and width
+ * @output Screenshots and fail-closed sensor receipts for the LayoutFooter whole-component audit
+ * @position Component-owned Night Watch browser evidence; CI runs it only for a LayoutFooter 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('layout-footer-audit-evidence');
+const WIDE = {width: 1280, height: 1000};
+const NARROW = {width: 320, height: 900};
+
+type Mode = 'light' | 'dark';
+type Theme = 'neutral' | 'butter';
+type Direction = 'ltr' | 'rtl';
+type Story =
+ | 'footer-states'
+ | 'basic-card'
+ | 'with-sidebar'
+ | 'no-dividers'
+ | 'full-bleed-content';
+
+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[];
+};
+
+type Edge = 'inlineStart' | 'inlineEnd' | 'blockStart' | 'blockEnd';
+const EDGES: Edge[] = ['inlineStart', 'inlineEnd', 'blockStart', 'blockEnd'];
+type Step = 0 | 2 | 4 | 6;
+
+// The number of LayoutFooter regions each story renders, so a story that
+// stops rendering one fails instead of passing with nothing to check.
+const FOOTERS: Record<Story, number> = {
+ // Footer States has ten cases plus the outer footer of the nested case.
+ 'footer-states': 11,
+ 'basic-card': 1,
+ 'with-sidebar': 1,
+ 'no-dividers': 1,
+ 'full-bleed-content': 1,
+};
+
+type FooterExpectation = {
+ // The padding the inner wrapper applies on each edge, as a spacing step:
+ // 6 is the Layout's `padding={6}`, 4 the inner inset. Not asserted when
+ // absent.
+ insets?: Record<Edge, Step>;
+ hasDivider: boolean;
+ // The block-end padding of the content above, as a spacing step: 0 when it
+ // collapses against a footer without a divider.
+ contentBlockEnd: Step;
+ height?: number;
+ contentWidth?: number;
+};
+
+const AUTOMATIC: Record<Edge, Step> = {
+ inlineStart: 6,
+ inlineEnd: 6,
+ blockStart: 4,
+ blockEnd: 6,
+};
+
+const CASES: Record<string, FooterExpectation> = {
+ automatic: {insets: AUTOMATIC, hasDivider: false, contentBlockEnd: 0},
+ divider: {insets: AUTOMATIC, hasDivider: true, contentBlockEnd: 4},
+ 'layout-default': {insets: AUTOMATIC, hasDivider: true, contentBlockEnd: 4},
+ 'explicit-off': {insets: AUTOMATIC, hasDivider: false, contentBlockEnd: 0},
+ 'padding-2': {
+ insets: {inlineStart: 2, inlineEnd: 2, blockStart: 2, blockEnd: 2},
+ hasDivider: true,
+ contentBlockEnd: 4,
+ },
+ 'full-bleed': {
+ insets: {inlineStart: 0, inlineEnd: 0, blockStart: 0, blockEnd: 0},
+ hasDivider: true,
+ contentBlockEnd: 4,
+ },
+ height: {insets: AUTOMATIC, hasDivider: true, contentBlockEnd: 4, height: 72},
+ 'content-width': {
+ insets: AUTOMATIC,
+ hasDivider: true,
+ contentBlockEnd: 4,
+ contentWidth: 240,
+ },
+ // The outer footer has no divider, but the collapse stops at the nested
+ // Layout: the nested content keeps its spacing above its divided footer.
+ nested: {hasDivider: true, contentBlockEnd: 4},
+ // The caller's `data-divider="false"` must not replace the reflected value:
+ // no line, no attribute, and the content above still collapses.
+ 'caller-attribute': {
+ insets: AUTOMATIC,
+ hasDivider: false,
+ contentBlockEnd: 0,
+ },
+};
+
+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('footer-states');
+add('footer-states', {theme: 'butter', modes: ['light']});
+add('footer-states', {direction: 'rtl', modes: ['light']});
+add('footer-states', {suffix: 'narrow', modes: ['light'], viewport: NARROW});
+add('basic-card');
+add('with-sidebar', {direction: 'rtl', modes: ['light']});
+add('no-dividers', {modes: ['light']});
+add('full-bleed-content', {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-layout--${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(element: Element) {
+ const rect = element.getBoundingClientRect();
+ 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 a length expression to pixels in the element's own scope.
+ function resolve(element: Element, expression: string) {
+ const probe = document.createElement('div');
+ probe.style.cssText = `position:absolute;visibility:hidden;width:${expression}`;
+ element.appendChild(probe);
+ const width = px(getComputedStyle(probe).width);
+ probe.remove();
+ return round(width);
+ }
+ // Resolve a color expression to its computed rgb() in the element's scope.
+ function color(element: Element, expression: string) {
+ const probe = document.createElement('div');
+ probe.style.cssText = `position:absolute;visibility:hidden;color:${expression}`;
+ element.appendChild(probe);
+ const value = getComputedStyle(probe).color;
+ probe.remove();
+ return value;
+ }
+ function edges(style: CSSStyleDeclaration) {
+ return {
+ inlineStart: px(style.paddingInlineStart),
+ inlineEnd: px(style.paddingInlineEnd),
+ blockStart: px(style.paddingBlockStart),
+ blockEnd: px(style.paddingBlockEnd),
+ };
+ }
+ const root = document.querySelector('#storybook-root') as Element;
+ const steps = {
+ 2: resolve(root, 'var(--spacing-2)'),
+ 4: resolve(root, 'var(--spacing-4)'),
+ 6: resolve(root, 'var(--spacing-6)'),
+ };
+ const footers = Array.from(
+ document.querySelectorAll('#storybook-root .astryx-layout-footer'),
+ ).map(footer => {
+ const style = getComputedStyle(footer);
+ const inner = footer.firstElementChild as Element;
+ const innerStyle = getComputedStyle(inner);
+ const layout = footer.closest('.astryx-layout');
+ const content = Array.from(
+ layout?.querySelectorAll('.astryx-layout-content') ?? [],
+ ).find(candidate => candidate.closest('.astryx-layout') === layout);
+ return {
+ footerCase: footer.getAttribute('data-footer-case'),
+ targets: Array.from(footer.classList).filter(name =>
+ name.startsWith('astryx-'),
+ ),
+ innerTargets: Array.from(inner.classList).filter(name =>
+ name.startsWith('astryx-'),
+ ),
+ dataDivider: footer.getAttribute('data-divider'),
+ role: footer.getAttribute('role'),
+ name: footer.getAttribute('aria-label'),
+ flexShrink: style.flexShrink,
+ direction: style.direction,
+ border: {
+ width: px(style.borderBlockStartWidth),
+ style: style.borderBlockStartStyle,
+ color: style.borderBlockStartColor,
+ expectedColor: color(footer, 'var(--color-border)'),
+ },
+ box: box(footer),
+ innerBox: box(inner),
+ innerMaxWidth: innerStyle.maxWidth,
+ layoutBox: layout == null ? null : box(layout),
+ applied: edges(innerStyle),
+ published: {
+ inlineStart: resolve(
+ inner,
+ 'var(--container-padding-inline-start, 0px)',
+ ),
+ inlineEnd: resolve(inner, 'var(--container-padding-inline-end, 0px)'),
+ blockStart: resolve(
+ inner,
+ 'var(--container-padding-block-start, 0px)',
+ ),
+ blockEnd: resolve(inner, 'var(--container-padding-block-end, 0px)'),
+ },
+ contentBlockEnd:
+ content == null
+ ? null
+ : px(getComputedStyle(content).paddingBlockEnd),
+ contentScrolls:
+ content == null
+ ? null
+ : content.scrollHeight > content.clientHeight + 1,
+ };
+ });
+ 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,
+ ),
+ steps,
+ footers,
+ };
+ });
+}
+
+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-layout-footer')
+ .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.footers.map(footer => footer.box)) ===
+ JSON.stringify(observed.footers.map(footer => footer.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;
+ const stepPx = (step: Step) => (step === 0 ? 0 : observed.steps[step]);
+
+ 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.steps[2] > 0 &&
+ observed.steps[4] > observed.steps[2] &&
+ observed.steps[6] > observed.steps[4],
+ `spacing steps ${JSON.stringify(observed.steps)}`,
+ );
+ check(
+ observed.footers.length === FOOTERS[item.story],
+ `${observed.footers.length} footers, expected ${FOOTERS[item.story]}`,
+ );
+ if (item.viewport !== NARROW) {
+ check(
+ observed.documentOverflow <= 0,
+ `document scrolls sideways by ${observed.documentOverflow}px`,
+ );
+ }
+
+ const footerCases = new Set<string>();
+ observed.footers.forEach((footer, index) => {
+ const where = `footer ${index}${footer.footerCase ? ` (${footer.footerCase})` : ''}`;
+ // One `layout-footer` target on the root; the inner wrapper has none.
+ check(
+ JSON.stringify(footer.targets) === '["astryx-layout-footer"]',
+ `${where} targets ${footer.targets.join(' ')}`,
+ );
+ check(
+ footer.innerTargets.length === 0,
+ `${where} inner targets ${footer.innerTargets.join(' ')}`,
+ );
+ check(
+ footer.flexShrink === '0',
+ `${where} flex-shrink ${footer.flexShrink}`,
+ );
+ check(
+ footer.direction === item.direction,
+ `${where} direction ${footer.direction}`,
+ );
+ // No role or name of its own.
+ check(
+ footer.role == null && footer.name == null,
+ `${where} has role ${footer.role} name ${footer.name}`,
+ );
+ // A divider is a 1px solid --color-border line on the block-start
+ // edge, reflected as data-divider="true"; no divider, no line and no
+ // attribute.
+ const drawsLine = footer.border.width > 0;
+ check(
+ drawsLine === (footer.dataDivider === 'true'),
+ `${where} line ${footer.border.width}px but data-divider ${footer.dataDivider}`,
+ );
+ check(
+ footer.dataDivider == null || footer.dataDivider === 'true',
+ `${where} data-divider ${footer.dataDivider}`,
+ );
+ if (drawsLine) {
+ check(
+ near(footer.border.width, 1, 0.01) &&
+ footer.border.style === 'solid' &&
+ footer.border.color === footer.border.expectedColor,
+ `${where} line ${JSON.stringify(footer.border)}`,
+ );
+ }
+ // The inner wrapper publishes the padding it applies, stays inside the
+ // footer, and is centered in it.
+ for (const edge of EDGES) {
+ check(
+ near(footer.applied[edge], footer.published[edge]),
+ `${where} ${edge} applies ${footer.applied[edge]} but publishes ${footer.published[edge]}`,
+ );
+ }
+ check(
+ footer.innerBox.left >= footer.box.left - 0.6 &&
+ footer.innerBox.right <= footer.box.right + 0.6,
+ `${where} inner ${JSON.stringify(footer.innerBox)} leaves ${JSON.stringify(footer.box)}`,
+ );
+ check(
+ near(
+ footer.innerBox.left - footer.box.left,
+ footer.box.right - footer.innerBox.right,
+ ),
+ `${where} inner is not centered`,
+ );
+ if (footer.layoutBox != null) {
+ check(
+ footer.box.left >= footer.layoutBox.left - 0.6 &&
+ footer.box.right <= footer.layoutBox.right + 0.6 &&
+ footer.box.bottom <= footer.layoutBox.bottom + 0.6,
+ `${where} ${JSON.stringify(footer.box)} leaves its layout ${JSON.stringify(footer.layoutBox)}`,
+ );
+ }
+
+ if (footer.footerCase != null) {
+ footerCases.add(footer.footerCase);
+ const expected = CASES[footer.footerCase];
+ check(expected != null, `${where} is not an expected case`);
+ if (expected == null) {
+ return;
+ }
+ const insets = expected.insets;
+ if (insets != null) {
+ for (const edge of EDGES) {
+ check(
+ near(footer.applied[edge], stepPx(insets[edge])),
+ `${where} ${edge} applies ${footer.applied[edge]}, expected ${stepPx(insets[edge])} (step ${insets[edge]})`,
+ );
+ }
+ }
+ check(
+ (footer.dataDivider === 'true') === expected.hasDivider,
+ `${where} data-divider ${footer.dataDivider}, expected divider ${expected.hasDivider}`,
+ );
+ check(
+ footer.contentBlockEnd != null &&
+ near(footer.contentBlockEnd, stepPx(expected.contentBlockEnd)),
+ `${where} content above ends with ${footer.contentBlockEnd}, expected ${stepPx(expected.contentBlockEnd)} (step ${expected.contentBlockEnd})`,
+ );
+ if (expected.height != null) {
+ check(
+ near(footer.box.height, expected.height),
+ `${where} height ${footer.box.height}, expected ${expected.height}`,
+ );
+ check(
+ footer.contentScrolls === true,
+ `${where} content above does not overflow, so shrinking is not exercised`,
+ );
+ }
+ if (expected.contentWidth != null) {
+ check(
+ footer.innerMaxWidth === `${expected.contentWidth}px` &&
+ near(footer.innerBox.width, expected.contentWidth),
+ `${where} inner max ${footer.innerMaxWidth} width ${footer.innerBox.width}, expected ${expected.contentWidth}`,
+ );
+ } else if (item.viewport !== NARROW) {
+ // Without a content width the inner wrapper spans the footer. In
+ // the 320px viewport the story frames are wider than the viewport,
+ // so the Layout's default content width caps the wrapper there.
+ check(
+ near(footer.innerBox.width, footer.box.width),
+ `${where} inner width ${footer.innerBox.width}, footer ${footer.box.width}`,
+ );
+ }
+ }
+ });
+ if (item.story === 'footer-states') {
+ check(
+ JSON.stringify([...footerCases].sort()) ===
+ JSON.stringify(Object.keys(CASES).sort()),
+ `footer cases ${[...footerCases].join(',')}`,
+ );
+ }
+
+ 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-layout--${item.story}`,
+ mode: item.mode,
+ theme: item.theme,
+ direction: item.direction,
+ viewport: item.viewport,
+ footers: FOOTERS[item.story],
+ anatomy:
+ 'each footer root carries only the astryx-layout-footer target, does not shrink, follows the page direction, and stays inside its layout; its inner wrapper has no target and is centered',
+ semantics: 'no role or name without a caller role',
+ divider:
+ 'a line exists exactly when data-divider is "true", and it is 1px solid --color-border on the block-start edge',
+ publication:
+ 'the inner wrapper applies exactly the padding it publishes',
+ cases: item.story === 'footer-states' ? CASES : 'not applicable',
+ overflow:
+ item.viewport === NARROW
+ ? 'not asserted at the document: the story frames are wider than 320px'
+ : 'no sideways document scroll',
+ },
+ 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 () => {
+ // Read only this run's frames, so files left by another run do not count.
+ const receipts = cases.map(item => {
+ const file = path.join(OUTPUT, `${item.key}.sensors.json`);
+ return {
+ key: item.key,
+ receipt: fs.existsSync(file)
+ ? (JSON.parse(fs.readFileSync(file, 'utf8')) as AuditReceipt)
+ : null,
+ };
+ });
+ fs.writeFileSync(
+ path.join(OUTPUT, 'manifest.json'),
+ `${JSON.stringify(
+ {
+ schemaVersion: 1,
+ component: 'core/LayoutFooter',
+ build: checkoutSha,
+ frames: cases.map(item => ({
+ key: item.key,
+ image: `${item.key}.png`,
+ receipt: `${item.key}.sensors.json`,
+ })),
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ expect(
+ receipts.filter(({receipt}) => receipt == null).map(({key}) => key),
+ ).toEqual([]);
+ // A receipt left by an earlier build does not count.
+ expect(
+ receipts
+ .filter(({receipt}) => receipt?.expected.build !== checkoutSha)
+ .map(({key}) => key),
+ ).toEqual([]);
+ expect(
+ receipts
+ .filter(({receipt}) => receipt?.passed !== true)
+ .map(({key, receipt}) => ({frame: key, failures: receipt?.failures})),
+ ).toEqual([]);
+});