Skip to content

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

TypeScript

[Component Audit] HStack: alignment and right-to-left flow are now proven in a browser (#9540)

Cindy Zhangf20625c02f2f
diff --git a/.changeset/hstack-audit-docs.md b/.changeset/hstack-audit-docs.md
new file mode 100644
index 0000000000..eb915dc195
--- /dev/null
+++ b/.changeset/hstack-audit-docs.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[docs] HStack: say that items follow the writing direction (right to left in RTL), that an explicit `hAlign` or `vAlign` wins over its `justify` or `align` alias, and document the `className`, `style`, and `ref` props.
+
+@cixzhang
diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.json
index 95d6dd146d..c2d1b6d9ad 100644
--- a/apps/storybook/rtl-audit/targets.json
+++ b/apps/storybook/rtl-audit/targets.json
@@ -423,6 +423,15 @@
"next": ".astryx-stack > :nth-child(2)"
}
},
+ {
+ "component": "HStack",
+ "storyId": "core-hstack--alignment-matrix",
+ "dims": ["D2"],
+ "selectors": {
+ "prev": "[data-audit-case=\"default\"] > [data-audit-item=\"0\"]",
+ "next": "[data-audit-case=\"default\"] > [data-audit-item=\"1\"]"
+ }
+ },
{
"component": "InputGroup",
"storyId": "core-inputgroup--with-prefix",
diff --git a/apps/storybook/stories/HStack.stories.tsx b/apps/storybook/stories/HStack.stories.tsx
new file mode 100644
index 0000000000..1d406bede3
--- /dev/null
+++ b/apps/storybook/stories/HStack.stories.tsx
@@ -0,0 +1,171 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file HStack.stories.tsx
+ * @input Uses HStack with default, aligned, alias, precedence, and wrapping rows
+ * @output Component-owned rendered evidence for HStack
+ * @position Storybook evidence; lets HStack-scoped accessibility, RTL, and screenshot audits resolve an HStack story
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import type {ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {HStack} from '@astryxdesign/core/HStack';
+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-4'],
+ boxSizing: 'border-box',
+ paddingBlock: spacingVars['--spacing-4'],
+ paddingInline: spacingVars['--spacing-4'],
+ },
+ row: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-1'],
+ },
+ // An outline keeps each stack's box visible in every theme and mode.
+ box: {
+ boxSizing: 'border-box',
+ outline: `1px dashed ${colorVars['--color-border-emphasized']}`,
+ outlineOffset: -1,
+ borderRadius: radiusVars['--radius-element'],
+ },
+ item: {
+ boxSizing: 'border-box',
+ inlineSize: 24,
+ blockSize: 24,
+ flexShrink: 0,
+ backgroundColor: colorVars['--color-accent'],
+ borderRadius: radiusVars['--radius-inner'],
+ },
+});
+
+const BOX = {width: 240, height: 64};
+
+function Items({count = 3}: {count?: number}) {
+ return (
+ <>
+ {Array.from({length: count}, (_, index) => (
+ <div
+ key={index}
+ data-audit-item={index}
+ {...stylex.props(styles.item)}
+ />
+ ))}
+ </>
+ );
+}
+
+function Row({label, children}: {label: string; children: ReactNode}) {
+ return (
+ <div {...stylex.props(styles.row)}>
+ <Text type="supporting">{label}</Text>
+ {children}
+ </div>
+ );
+}
+
+const meta: Meta<typeof HStack> = {
+ title: 'Core/HStack',
+ component: HStack,
+};
+
+export default meta;
+type Story = StoryObj<typeof HStack>;
+
+/**
+ * Rows of HStack in fixed boxes: the default flow from the inline start, the
+ * main and cross axes set by `hAlign`/`vAlign` and by their `justify`/`align`
+ * aliases, an explicit alignment winning over its alias, and wrapping.
+ */
+export const AlignmentMatrix: Story = {
+ render: () => (
+ <div {...stylex.props(styles.matrix)}>
+ <Row label="Default">
+ <HStack data-audit-case="default" gap={2} {...BOX} xstyle={styles.box}>
+ <Items />
+ </HStack>
+ </Row>
+ <Row label="hAlign end">
+ <HStack
+ data-audit-case="h-end"
+ gap={2}
+ hAlign="end"
+ {...BOX}
+ xstyle={styles.box}>
+ <Items />
+ </HStack>
+ </Row>
+ <Row label="justify between">
+ <HStack
+ data-audit-case="justify-between"
+ justify="between"
+ {...BOX}
+ xstyle={styles.box}>
+ <Items />
+ </HStack>
+ </Row>
+ <Row label="hAlign center over justify end">
+ <HStack
+ data-audit-case="h-wins"
+ gap={2}
+ hAlign="center"
+ justify="end"
+ {...BOX}
+ xstyle={styles.box}>
+ <Items />
+ </HStack>
+ </Row>
+ <Row label="vAlign center">
+ <HStack
+ data-audit-case="v-center"
+ gap={2}
+ vAlign="center"
+ {...BOX}
+ xstyle={styles.box}>
+ <Items />
+ </HStack>
+ </Row>
+ <Row label="align end">
+ <HStack
+ data-audit-case="align-end"
+ gap={2}
+ align="end"
+ {...BOX}
+ xstyle={styles.box}>
+ <Items />
+ </HStack>
+ </Row>
+ <Row label="vAlign start over align end">
+ <HStack
+ data-audit-case="v-wins"
+ gap={2}
+ vAlign="start"
+ align="end"
+ {...BOX}
+ xstyle={styles.box}>
+ <Items />
+ </HStack>
+ </Row>
+ <Row label="wrap">
+ <HStack
+ data-audit-case="wrap"
+ gap={2}
+ wrap="wrap"
+ width={120}
+ xstyle={styles.box}>
+ <Items count={6} />
+ </HStack>
+ </Row>
+ </div>
+ ),
+};
diff --git a/packages/core/src/HStack/HStack.test.tsx b/packages/core/src/HStack/HStack.test.tsx
index 7306ab810c..9263f42a1a 100644
--- a/packages/core/src/HStack/HStack.test.tsx
+++ b/packages/core/src/HStack/HStack.test.tsx
@@ -2,17 +2,26 @@
/**
* @file HStack.test.tsx
- * @input Uses vitest, @testing-library/react, HStack component
+ * @input Uses vitest, @testing-library/react, React, HStack and Stack components
* @output Unit tests for HStack component behavior
* @position Testing; validates HStack.tsx implementation
*
* SYNC: When HStack.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi} from 'vitest';
+import {createRef, type ReactElement} from 'react';
+import {describe, it, expect} from 'vitest';
import {render, screen} from '@testing-library/react';
+import {Stack} from '../Stack/Stack';
import {HStack} from './HStack';
+function classNameOf(element: ReactElement): string {
+ const {container, unmount} = render(element);
+ const className = (container.firstElementChild as HTMLElement).className;
+ unmount();
+ return className;
+}
+
describe('HStack', () => {
it('renders children correctly', () => {
render(
@@ -41,89 +50,102 @@ describe('HStack', () => {
expect(element.tagName).toBe('NAV');
});
- it('renders with gap prop', () => {
+ it('renders a horizontal stack that carries the stack target', () => {
render(
- <HStack gap={4}>
- <div>Item 1</div>
- <div>Item 2</div>
+ <HStack gap={4} wrap="wrap" data-testid="hstack">
+ <div>Item</div>
</HStack>,
);
- expect(screen.getByText('Item 1')).toBeInTheDocument();
+ const element = screen.getByTestId('hstack');
+ expect(element).toHaveClass('astryx-stack');
+ expect(element).toHaveAttribute('data-direction', 'horizontal');
+ expect(element).toHaveAttribute('data-gap', '4');
+ expect(element).toHaveAttribute('data-wrap', 'wrap');
});
- it('renders with vAlign prop', () => {
- render(
- <HStack vAlign="center">
- <div>Item 1</div>
- </HStack>,
+ it('sets the main axis with hAlign and the cross axis with vAlign, as Stack does for a horizontal stack', () => {
+ expect(classNameOf(<HStack hAlign="center" />)).toBe(
+ classNameOf(<Stack direction="horizontal" justify="center" />),
+ );
+ expect(classNameOf(<HStack vAlign="center" />)).toBe(
+ classNameOf(<Stack direction="horizontal" align="center" />),
+ );
+ expect(classNameOf(<HStack hAlign="center" />)).not.toBe(
+ classNameOf(<HStack vAlign="center" />),
);
- expect(screen.getByText('Item 1')).toBeInTheDocument();
});
- it('renders with wrap prop', () => {
- render(
- <HStack wrap="wrap">
- <div>Item 1</div>
- <div>Item 2</div>
- </HStack>,
+ it('applies justify and align as aliases for hAlign and vAlign', () => {
+ expect(classNameOf(<HStack justify="between" />)).toBe(
+ classNameOf(<HStack hAlign="between" />),
+ );
+ expect(classNameOf(<HStack align="end" />)).toBe(
+ classNameOf(<HStack vAlign="end" />),
+ );
+ expect(classNameOf(<HStack justify="between" />)).not.toBe(
+ classNameOf(<HStack />),
+ );
+ expect(classNameOf(<HStack align="end" />)).not.toBe(
+ classNameOf(<HStack />),
);
- expect(screen.getByText('Item 1')).toBeInTheDocument();
});
- it('forwards ref correctly', () => {
- const ref = vi.fn();
- render(
- <HStack ref={ref}>
- <div>Test</div>
- </HStack>,
+ it('lets an explicit hAlign or vAlign win over its alias', () => {
+ expect(classNameOf(<HStack hAlign="center" justify="end" />)).toBe(
+ classNameOf(<HStack hAlign="center" />),
+ );
+ expect(classNameOf(<HStack vAlign="start" align="end" />)).toBe(
+ classNameOf(<HStack vAlign="start" />),
);
- expect(ref).toHaveBeenCalledWith(expect.any(HTMLElement));
});
- it('forwards ref with polymorphic as', () => {
- const ref = vi.fn();
+ it('forwards ref to the rendered element', () => {
+ const ref = createRef<HTMLElement>();
render(
- <HStack as="section" ref={ref}>
+ <HStack ref={ref} as="section" data-testid="hstack">
<div>Test</div>
</HStack>,
);
- expect(ref).toHaveBeenCalledWith(expect.any(HTMLElement));
+ expect(ref.current).toBe(screen.getByTestId('hstack'));
});
- it('passes through additional props', () => {
+ it('passes ARIA and data attributes to the rendered element', () => {
render(
- <HStack data-testid="hstack">
+ <HStack aria-label="Toolbar row" data-testid="hstack">
<div>Item</div>
</HStack>,
);
- expect(screen.getByTestId('hstack')).toBeInTheDocument();
- });
-
- it('accepts justify as alias for hAlign', () => {
- const {container} = render(
- <HStack justify="between">
- <div>A</div>
- <div>B</div>
- </HStack>,
+ expect(screen.getByTestId('hstack')).toHaveAttribute(
+ 'aria-label',
+ 'Toolbar row',
);
- expect(container.firstChild).toBeInTheDocument();
});
- it('accepts align as alias for vAlign', () => {
- const {container} = render(
- <HStack align="center">
- <div>A</div>
+ it('merges className and style, with sizing props after style', () => {
+ render(
+ <HStack
+ data-testid="hstack"
+ className="caller-row"
+ style={{color: 'red', width: 10}}
+ width={300}>
+ <div>Item</div>
</HStack>,
);
- expect(container.firstChild).toBeInTheDocument();
+ const element = screen.getByTestId('hstack');
+ expect(element).toHaveClass('astryx-stack');
+ expect(element).toHaveClass('caller-row');
+ expect(element.style.color).toBe('red');
+ expect(element.style.width).toBe('300px');
});
- it('prefers explicit hAlign over justify', () => {
- const {container} = render(
- <HStack hAlign="center" justify="end">
- <div>A</div>
+ it('adds no role and no tab stop of its own', () => {
+ render(
+ <HStack data-testid="hstack">
+ <div>Item</div>
</HStack>,
);
- expect(container.firstChild).toBeInTheDocument();
+ const element = screen.getByTestId('hstack');
+ expect(element).not.toHaveAttribute('role');
+ expect(element).not.toHaveAttribute('tabindex');
});
});
diff --git a/packages/core/src/HStack/HStack.tsx b/packages/core/src/HStack/HStack.tsx
index 4d51adcdf2..b62fc29a8e 100644
--- a/packages/core/src/HStack/HStack.tsx
+++ b/packages/core/src/HStack/HStack.tsx
@@ -55,7 +55,8 @@ export interface HStackProps extends Omit<
}
/**
- * Horizontal stack component for arranging items left-to-right.
+ * Horizontal stack component that arranges items along the inline axis:
+ * left to right in LTR, right to left in RTL.
* Convenience wrapper around `Stack` with `direction="horizontal"`.
*
* @example
diff --git a/packages/core/src/HStack/__tests__/HStackAudit.a11y.chromium.spec.ts b/packages/core/src/HStack/__tests__/HStackAudit.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..83f454a617
--- /dev/null
+++ b/packages/core/src/HStack/__tests__/HStackAudit.a11y.chromium.spec.ts
@@ -0,0 +1,415 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y audit HStack
+
+/**
+ * @file HStackAudit.a11y.chromium.spec.ts
+ * @input Exact-head HStack alignment matrix across themes, modes, direction, and viewport
+ * @output Screenshots and fail-closed sensor receipts for the HStack whole-component audit
+ * @position Component-owned Night Watch browser evidence; CI runs it only for an HStack 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('hstack-audit-evidence');
+const STORY_ID = 'core-hstack--alignment-matrix';
+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 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 = [
+ 'default',
+ 'h-end',
+ 'justify-between',
+ 'h-wins',
+ 'v-center',
+ 'align-end',
+ 'v-wins',
+ 'wrap',
+];
+
+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(() => {
+ const round = (value: number) => Math.round(value * 10) / 10;
+ function box(element: Element) {
+ 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),
+ };
+ }
+ const stacks = Array.from(
+ document.querySelectorAll<HTMLElement>('[data-audit-case]'),
+ ).map(stack => {
+ const style = getComputedStyle(stack);
+ return {
+ auditCase: stack.getAttribute('data-audit-case'),
+ tagName: stack.tagName,
+ hasTarget: stack.classList.contains('astryx-stack'),
+ dataDirection: stack.getAttribute('data-direction'),
+ role: stack.getAttribute('role'),
+ tabIndex: stack.getAttribute('tabindex'),
+ display: style.display,
+ flexDirection: style.flexDirection,
+ direction: style.direction,
+ box: box(stack),
+ items: Array.from(stack.children).map(child => box(child)),
+ };
+ });
+ 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,
+ 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'),
+ stacks,
+ };
+ });
+}
+
+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.stacks.map(stack => stack.items)) ===
+ JSON.stringify(observed.stacks.map(stack => stack.items));
+
+ 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;
+ const rtl = item.direction === 'rtl';
+
+ 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 === 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');
+ check(
+ JSON.stringify(observed.stacks.map(stack => stack.auditCase)) ===
+ JSON.stringify(EXPECTED_CASES),
+ 'audit cases missing or out of order',
+ );
+
+ for (const stack of observed.stacks) {
+ const id = stack.auditCase ?? 'unknown';
+ const {box, items} = stack;
+ check(stack.tagName === 'DIV', `${id}: renders ${stack.tagName}`);
+ check(stack.hasTarget, `${id}: no astryx-stack target`);
+ check(stack.dataDirection === 'horizontal', `${id}: data-direction`);
+ check(stack.display === 'flex', `${id}: display ${stack.display}`);
+ check(stack.flexDirection === 'row', `${id}: ${stack.flexDirection}`);
+ check(stack.direction === item.direction, `${id}: direction`);
+ check(
+ stack.role == null && stack.tabIndex == null,
+ `${id}: adds a role or tab stop`,
+ );
+ if (items.length === 0) {
+ check(false, `${id}: no items`);
+ continue;
+ }
+ const firstItem = items[0];
+ const lastItem = items[items.length - 1];
+ // Inline start and end, read in the writing direction.
+ const startOf = (rect: typeof box) => (rtl ? rect.right : rect.left);
+ const endOf = (rect: typeof box) => (rtl ? rect.left : rect.right);
+ const fromStart = (rect: typeof box) =>
+ rtl ? box.right - rect.right : rect.left - box.left;
+ const fromEnd = (rect: typeof box) =>
+ rtl ? rect.left - box.left : box.right - rect.right;
+
+ if (id !== 'wrap') {
+ // Items follow the writing direction in one line.
+ const inOrder = items.every(
+ (rect, index) =>
+ index === 0 ||
+ (rtl
+ ? rect.right <= items[index - 1].left + 0.5
+ : rect.left >= items[index - 1].right - 0.5),
+ );
+ check(inOrder, `${id}: items are not in inline order`);
+ check(
+ items.every(rect => near(rect.top, firstItem.top)),
+ `${id}: items are not on one line`,
+ );
+ }
+ if (id === 'default') {
+ check(near(startOf(firstItem), startOf(box)), `${id}: not at start`);
+ check(near(firstItem.top, box.top), `${id}: not at the block start`);
+ const gaps = items
+ .slice(1)
+ .map((rect, index) =>
+ rtl
+ ? items[index].left - rect.right
+ : rect.left - items[index].right,
+ );
+ check(
+ gaps.every(value => value > 0 && near(value, gaps[0])),
+ `${id}: gaps ${gaps.join(',')}`,
+ );
+ }
+ if (id === 'h-end') {
+ check(near(endOf(lastItem), endOf(box)), `${id}: not at the end`);
+ }
+ if (id === 'justify-between') {
+ check(near(startOf(firstItem), startOf(box)), `${id}: first item`);
+ check(near(endOf(lastItem), endOf(box)), `${id}: last item`);
+ }
+ if (id === 'h-wins') {
+ check(
+ near(fromStart(firstItem), fromEnd(lastItem)),
+ `${id}: group is not centered (hAlign did not win)`,
+ );
+ }
+ if (id === 'v-center') {
+ check(
+ near(firstItem.top - box.top, box.bottom - firstItem.bottom),
+ `${id}: items are not centered on the cross axis`,
+ );
+ }
+ if (id === 'align-end') {
+ check(near(firstItem.bottom, box.bottom), `${id}: not at block end`);
+ }
+ if (id === 'v-wins') {
+ check(
+ near(firstItem.top, box.top),
+ `${id}: not at block start (vAlign did not win)`,
+ );
+ }
+ if (id === 'wrap') {
+ const rows = new Set(items.map(rect => rect.top));
+ check(rows.size > 1, `${id}: items did not wrap`);
+ check(
+ items.every(
+ rect =>
+ rect.left >= box.left - 0.5 && rect.right <= box.right + 0.5,
+ ),
+ `${id}: an item leaves the stack`,
+ );
+ check(near(startOf(firstItem), startOf(box)), `${id}: not at start`);
+ }
+ }
+
+ 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,
+ layout:
+ 'every case is a horizontal flex row carrying astryx-stack and data-direction="horizontal" with no role or tab stop; items follow the writing direction',
+ alignment:
+ 'default starts at the inline start with equal gaps; hAlign end ends at the inline end; justify between spans start to end; hAlign center wins over justify end; vAlign center centers on the cross axis; align end sits at the block end; vAlign start wins over align end; wrap breaks into more than one line inside the stack',
+ },
+ 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();
+ });
+}
+
+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/HStack',
+ 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([]);
+});
diff --git a/packages/core/src/Stack/Stack.doc.mjs b/packages/core/src/Stack/Stack.doc.mjs
index 49c08a5bcc..79e8142436 100644
--- a/packages/core/src/Stack/Stack.doc.mjs
+++ b/packages/core/src/Stack/Stack.doc.mjs
@@ -184,7 +184,7 @@ export const docs = {
isHiddenFromOverview: true,
displayName: 'H Stack',
description:
- 'Horizontal stack for arranging items left-to-right. Supports polymorphic rendering.',
+ 'Horizontal stack that arranges items along the inline axis: left to right in LTR, right to left in RTL. Supports polymorphic rendering.',
playground: {
defaults: {
gap: 2,
@@ -285,12 +285,12 @@ export const docs = {
{
name: 'justify',
type: "'start' | 'center' | 'end' | 'between' | 'around' | 'evenly'",
- description: 'Main-axis alignment alias for hAlign. Mirrors CSS justify-content.',
+ description: 'Main-axis alignment alias for hAlign. Mirrors CSS justify-content. When hAlign is also set, hAlign wins.',
},
{
name: 'align',
type: "'start' | 'center' | 'end' | 'stretch'",
- description: 'Cross-axis alignment alias for vAlign. Mirrors CSS align-items.',
+ description: 'Cross-axis alignment alias for vAlign. Mirrors CSS align-items. When vAlign is also set, vAlign wins.',
},
{
name: 'wrap',
@@ -315,6 +315,21 @@ export const docs = {
description:
'StyleX styles for layout customization (margins, positioning, sizing). Must be a stylex.create() value, not an inline style object like style={{}}.',
},
+ {
+ name: 'className',
+ type: 'string',
+ description: 'Class name added to the stack element, after the component styles.',
+ },
+ {
+ name: 'style',
+ type: 'CSSProperties',
+ description: 'Inline styles for the stack element. width, height, maxWidth, and minHeight win over the same properties here.',
+ },
+ {
+ name: 'ref',
+ type: 'Ref<HTMLElement>',
+ description: 'Ref to the rendered stack element.',
+ },
], },
{
name: 'VStack',
@@ -525,7 +540,7 @@ export const docsZh = {
isHiddenFromOverview: true,
displayName: 'H Stack',
description:
- '水平堆叠组件,将元素从左到右排列。支持多态渲染。',
+ '水平堆叠组件,沿行内方向排列元素:LTR 中从左到右,RTL 中从右到左。支持多态渲染。',
props: [
{
name: 'gap',
@@ -557,12 +572,12 @@ export const docsZh = {
{
name: 'justify',
type: "'start' | 'center' | 'end' | 'between' | 'around' | 'evenly'",
- description: 'hAlign 的别名。对应 CSS justify-content。',
+ description: 'hAlign 的别名。对应 CSS justify-content。同时设置 hAlign 时,以 hAlign 为准。',
},
{
name: 'align',
type: "'start' | 'center' | 'end' | 'stretch'",
- description: 'vAlign 的别名。对应 CSS align-items。',
+ description: 'vAlign 的别名。对应 CSS align-items。同时设置 vAlign 时,以 vAlign 为准。',
},
{
name: 'wrap',
@@ -716,15 +731,15 @@ export const docsDense = {
name: 'HStack',
isHiddenFromOverview: true,
displayName: 'H Stack',
- description: 'Horizontal stack; left-to-right, polymorphic rendering.',
+ description: 'Horizontal stack; inline direction (left to right in LTR, right to left in RTL), polymorphic rendering.',
propDescriptions: {
gap: 'Number literal spacing step: 0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 8, 10. Use gap={4} not gap="4".',
width: "Width of container. Numbers=pixels, strings=as-is (e.g. '100%').",
height: "Height of container. Numbers=pixels, strings=as-is (e.g. '100%').",
hAlign: 'Horizontal (main-axis) alignment.',
vAlign: 'Vertical (cross-axis) alignment.',
- justify: 'Main-axis alignment alias for hAlign. Mirrors CSS justify-content.',
- align: 'Cross-axis alignment alias for vAlign. Mirrors CSS align-items.',
+ justify: 'Main-axis alignment alias for hAlign. Mirrors CSS justify-content. An explicit hAlign wins.',
+ align: 'Cross-axis alignment alias for vAlign. Mirrors CSS align-items. An explicit vAlign wins.',
wrap: 'Flex wrap behavior.',
as: 'HTML element to render as container.',
children: 'Stack content.',