An open source design system that's fully customizable and agent ready
TypeScript
[Component Audit] LayoutPanel: full-bleed children reach the panel's outer edge (#10774)
Cindy Zhangfe174dd12131
diff --git a/.changeset/layout-panel-publishes-applied-inset.md b/.changeset/layout-panel-publishes-applied-inset.mdnew file mode 100644index 0000000000..8f306ce634--- /dev/null+++ b/.changeset/layout-panel-publishes-applied-inset.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `LayoutPanel`: on an edge that takes the Layout's own inset, the panel now tells its children the padding it applies there. Children that read their container's padding, such as a full-bleed `Divider`, `Table`, or `TabList`, or a nested `Layout`, now follow the panel's outer edge whenever the Layout's `padding` differs from the inner inset. Before, they used the inner inset: with `padding={6}` a full-bleed `Divider` stopped 8px short of the edge, and with `padding={0}` it ran 16px past it. The docs now say which edge `hasDivider` draws on, that the Layout's `defaultHasDividers` does not apply, and that `padding={0}` is full bleed, and they list `ref`.++@cixzhangdiff --git a/.github/a11y-audit-axe.json b/.github/a11y-audit-axe.jsonindex 2898c325c2..155c073071 100644--- a/.github/a11y-audit-axe.json+++ b/.github/a11y-audit-axe.json@@ -55,5 +55,14 @@"core-layout--no-dividers","core-layout--full-bleed-content"]+ },+ "LayoutPanel": {+ "components": ["Layout"],+ "stories": [+ "core-layout--panel-states",+ "core-layout--with-sidebar",+ "core-layout--dual-panels",+ "core-layout--content-width-with-start-panel"+ ]}}diff --git a/apps/storybook/stories/Layout.stories.tsx b/apps/storybook/stories/Layout.stories.tsxindex 343cc3baec..6f4413fab7 100644--- a/apps/storybook/stories/Layout.stories.tsx+++ b/apps/storybook/stories/Layout.stories.tsx@@ -15,6 +15,7 @@ import {VStack,} from '@astryxdesign/core/Layout';import {Button} from '@astryxdesign/core/Button';+import {Divider} from '@astryxdesign/core/Divider';import {colorVars,spacingVars,@@ -2339,3 +2340,256 @@ export const HeaderStates: Story = {);},};++export const PanelStates: Story = {+ name: 'Panel States',+ render: () => {+ const body = <p {...stylex.props(styles.bodyText)}>Content area.</p>;+ const panelText = <p {...stylex.props(styles.bodyText)}>Panel</p>;+ const rows = Array.from({length: 12}, (_, index) => (+ <p key={index} {...stylex.props(styles.bodyText)}>+ Item {index + 1}+ </p>+ ));+ const cases = [+ {+ id: 'start-automatic',+ label: 'Start, no divider, padding=6',+ layout: (+ <Layout+ padding={6}+ start={+ <LayoutPanel width={120} data-panel-case="start-automatic">+ {panelText}+ </LayoutPanel>+ }+ content={<LayoutContent>{body}</LayoutContent>}+ />+ ),+ },+ {+ id: 'start-divider',+ label: 'Start, hasDivider, padding=6',+ layout: (+ <Layout+ padding={6}+ start={+ <LayoutPanel+ width={120}+ hasDivider+ data-panel-case="start-divider">+ {panelText}+ </LayoutPanel>+ }+ content={<LayoutContent>{body}</LayoutContent>}+ />+ ),+ },+ {+ id: 'end-automatic',+ label: 'End, no divider, padding=6',+ layout: (+ <Layout+ padding={6}+ end={+ <LayoutPanel width={120} data-panel-case="end-automatic">+ {panelText}+ </LayoutPanel>+ }+ content={<LayoutContent>{body}</LayoutContent>}+ />+ ),+ },+ {+ id: 'end-divider',+ label: 'End, hasDivider, padding=6',+ layout: (+ <Layout+ padding={6}+ end={+ <LayoutPanel width={120} hasDivider data-panel-case="end-divider">+ {panelText}+ </LayoutPanel>+ }+ content={<LayoutContent>{body}</LayoutContent>}+ />+ ),+ },+ {+ id: 'header-footer',+ label: 'Start, hasDivider, with header and footer',+ layout: (+ <Layout+ padding={6}+ header={+ <LayoutHeader hasDivider>+ <p {...stylex.props(styles.bodyText)}>Header</p>+ </LayoutHeader>+ }+ start={+ <LayoutPanel+ width={120}+ hasDivider+ data-panel-case="header-footer">+ {panelText}+ </LayoutPanel>+ }+ content={<LayoutContent>{body}</LayoutContent>}+ footer={+ <LayoutFooter hasDivider>+ <p {...stylex.props(styles.bodyText)}>Footer</p>+ </LayoutFooter>+ }+ />+ ),+ },+ {+ id: 'bleed-child',+ label: 'Start, hasDivider, full-bleed Divider inside',+ layout: (+ <Layout+ padding={6}+ start={+ <LayoutPanel width={160} hasDivider data-panel-case="bleed-child">+ {panelText}+ <Divider isFullBleed />+ {panelText}+ </LayoutPanel>+ }+ content={<LayoutContent>{body}</LayoutContent>}+ />+ ),+ },+ {+ id: 'padding-2',+ label: 'Start, hasDivider, panel padding=2',+ layout: (+ <Layout+ padding={6}+ start={+ <LayoutPanel+ width={120}+ hasDivider+ padding={2}+ data-panel-case="padding-2">+ {panelText}+ </LayoutPanel>+ }+ content={<LayoutContent>{body}</LayoutContent>}+ />+ ),+ },+ {+ id: 'full-bleed',+ label: 'Start, hasDivider, panel padding=0',+ layout: (+ <Layout+ padding={6}+ start={+ <LayoutPanel+ width={120}+ hasDivider+ padding={0}+ data-panel-case="full-bleed">+ {panelText}+ </LayoutPanel>+ }+ content={<LayoutContent>{body}</LayoutContent>}+ />+ ),+ },+ {+ id: 'width-string',+ label: 'Start, hasDivider, width="10rem"',+ layout: (+ <Layout+ padding={6}+ start={+ <LayoutPanel+ width="10rem"+ hasDivider+ data-panel-case="width-string">+ {panelText}+ </LayoutPanel>+ }+ content={<LayoutContent>{body}</LayoutContent>}+ />+ ),+ },+ {+ id: 'landmark',+ label: 'Start, role="navigation", label="Sections"',+ layout: (+ <Layout+ padding={6}+ start={+ <LayoutPanel+ width={120}+ hasDivider+ role="navigation"+ label="Sections"+ data-panel-case="landmark">+ {panelText}+ </LayoutPanel>+ }+ content={<LayoutContent>{body}</LayoutContent>}+ />+ ),+ },+ {+ id: 'scrolling',+ label: 'Start, overflowing content',+ layout: (+ <Layout+ padding={6}+ start={+ <LayoutPanel width={120} hasDivider data-panel-case="scrolling">+ <VStack gap={2}>+ {rows}+ {/* A focusable control keeps the scrolling content keyboard-reachable. */}+ <Button label="More" variant="secondary">+ More+ </Button>+ </VStack>+ </LayoutPanel>+ }+ content={<LayoutContent>{body}</LayoutContent>}+ />+ ),+ },+ {+ id: 'not-scrollable',+ label: 'Start, overflowing content, isScrollable={false}',+ layout: (+ <Layout+ padding={6}+ start={+ <LayoutPanel+ width={120}+ hasDivider+ isScrollable={false}+ data-panel-case="not-scrollable">+ <VStack gap={2}>{rows}</VStack>+ </LayoutPanel>+ }+ content={<LayoutContent>{body}</LayoutContent>}+ />+ ),+ },+ ];+ 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/core/src/Layout/LayoutPanel.doc.mjs b/packages/core/src/Layout/LayoutPanel.doc.mjsindex 2ef82b18d7..b6b808c43f 100644--- a/packages/core/src/Layout/LayoutPanel.doc.mjs+++ b/packages/core/src/Layout/LayoutPanel.doc.mjs@@ -35,14 +35,15 @@ export const docs = {{name: 'hasDivider',type: 'boolean',- description: 'Border on the appropriate edge.',+ description:+ "Line on the edge that faces the content: the inline end in the start slot, the inline start in the end slot. Without it and without padding, the panel and the content share one gap. The Layout's defaultHasDividers does not apply. Beside a ResizeHandle that draws its own line, leave it false.",default: 'false',},{name: 'padding',type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description:- 'Internal padding using the spacing scale. Overrides the default padding from the layout container.',+ 'Internal padding on every edge, using the spacing scale. Replaces the automatic inset and the gap shared with the content. 0 is full bleed.',},{name: 'isScrollable',@@ -73,6 +74,11 @@ export const docs = {description:"The output of useResizable(), or its props. When provided, the hook drives the panel width and a ResizeHandle should be placed adjacent to the panel. Carries the region's axis ('horizontal' | 'vertical'), which must match the adjacent ResizeHandle's direction. With the hook's own value, the panel slides closed and open from the edge facing its ResizeHandle; a hand-built object does not slide. Either way, focus inside the panel moves to its ResizeHandle as it collapses, and the panel is inert while collapsed.",},+ {+ name: 'ref',+ type: 'React.Ref<HTMLDivElement>',+ description: 'Ref forwarded to the panel element.',+ },],};@@ -90,13 +96,15 @@ export const docsZh = {{name: 'hasDivider',type: 'boolean',- description: '相应边缘的边框。',+ description:+ '朝向内容一侧边缘的分隔线:在 start 插槽中位于行内结束边,在 end 插槽中位于行内起始边。不设置此项且未设置 padding 时,面板与内容共用一个间距。Layout 的 defaultHasDividers 不适用。旁边的 ResizeHandle 自带分隔线时,请保持为 false。',default: 'false',},{name: 'padding',type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',- description: '使用间距比例的内边距。覆盖布局容器的默认内边距。',+ description:+ '使用间距比例设置四边的内边距,替换自动内边距以及与内容共用的间距。0 表示全出血。',},{name: 'isScrollable',@@ -127,6 +135,11 @@ export const docsZh = {description:"useResizable() 的返回值或其 props。提供时面板宽度由 hook 驱动,应在面板旁放置 ResizeHandle。其中携带区域的轴向('horizontal' | 'vertical'),必须与相邻 ResizeHandle 的 direction 一致。使用 hook 自身返回的值时,面板从朝向其 ResizeHandle 的边缘滑动关闭和打开;手动构造的对象不会滑动。两种情况下,折叠时面板内的焦点都会移到其 ResizeHandle 上,折叠期间面板为 inert。",},+ {+ name: 'ref',+ type: 'React.Ref<HTMLDivElement>',+ description: '转发到面板元素的 ref。',+ },],};@@ -137,9 +150,10 @@ export const docsDense = {description: 'Sidebar for navigation, settings, inspector panels.',propDescriptions: {children: 'Panel content.',- hasDivider: 'Border on appropriate edge.',+ hasDivider:+ 'Line on the content-facing edge (start slot: inline end; end slot: inline start); without it or padding, panel and content share one gap. Layout defaultHasDividers does not apply. False beside a ResizeHandle with its own line.',padding:- 'Internal padding on spacing scale. Overrides layout container default.',+ 'Padding on every edge; replaces the automatic inset and the shared gap. 0 is full bleed.',isScrollable: 'Enable scrollable overflow.',label:'Accessible label for landmark element; also names the region while it scrolls (default "Content").',@@ -148,5 +162,6 @@ export const docsDense = {'Panel width. Numbers = pixels, strings as-is. Ignored when resizable provided; hook controls width. width={region.size} beside a ResizeHandle given the region props: inert while collapsed; focus inside moves to the handle on collapse.',resizable:'useResizable() output or its props. Hook drives panel width; place ResizeHandle adjacent. Hook values slide; hand-built ones do not. Focus inside moves to the handle on collapse; inert while collapsed.',+ ref: 'Ref forwarded to the panel element.',},};diff --git a/packages/core/src/Layout/LayoutPanel.tsx b/packages/core/src/Layout/LayoutPanel.tsxindex 3e1b733209..3144cbb98b 100644--- a/packages/core/src/Layout/LayoutPanel.tsx+++ b/packages/core/src/Layout/LayoutPanel.tsx@@ -54,7 +54,6 @@ const styles = stylex.create({boxSizing: 'border-box',flexShrink: 0,overflow: 'clip',- // Default: inner padding on all sides (will be overridden by position-specific styles)paddingInlineStart: `var(--layout-padding-inner-x, ${spacingVars['--spacing-4']})`,paddingInlineEnd: `var(--layout-padding-inner-x, ${spacingVars['--spacing-4']})`,paddingBlockStart: `var(--layout-padding-inner-y, ${spacingVars['--spacing-4']})`,@@ -64,21 +63,23 @@ const styles = stylex.create({'--container-padding-block-start': `var(--layout-padding-inner-y, ${spacingVars['--spacing-4']})`,'--container-padding-block-end': `var(--layout-padding-inner-y, ${spacingVars['--spacing-4']})`,},- // Start panel: outer-x on left edge+ // An edge on the Layout's boundary takes the Layout-edge inset. Each edge+ // publishes the padding it applies, so full-bleed children line up with it.startPanel: {paddingInlineStart: `var(--layout-padding-own-outer-x, var(--layout-padding-outer-x, ${spacingVars['--spacing-4']}))`,+ '--container-padding-inline-start': `var(--layout-padding-own-outer-x, var(--layout-padding-outer-x, ${spacingVars['--spacing-4']}))`,},- // End panel: outer-x on right edgeendPanel: {paddingInlineEnd: `var(--layout-padding-own-outer-x, var(--layout-padding-outer-x, ${spacingVars['--spacing-4']}))`,+ '--container-padding-inline-end': `var(--layout-padding-own-outer-x, var(--layout-padding-outer-x, ${spacingVars['--spacing-4']}))`,},- // When no header: outer-y on topnoHeader: {paddingBlockStart: `var(--layout-padding-own-outer-y, var(--layout-padding-outer-y, ${spacingVars['--spacing-4']}))`,+ '--container-padding-block-start': `var(--layout-padding-own-outer-y, var(--layout-padding-outer-y, ${spacingVars['--spacing-4']}))`,},- // When no footer: outer-y on bottomnoFooter: {paddingBlockEnd: `var(--layout-padding-own-outer-y, var(--layout-padding-outer-y, ${spacingVars['--spacing-4']}))`,+ '--container-padding-block-end': `var(--layout-padding-own-outer-y, var(--layout-padding-outer-y, ${spacingVars['--spacing-4']}))`,},fullBleed: {paddingInlineStart: 0,@@ -142,7 +143,7 @@ export interface LayoutPanelProps extends BaseProps<HTMLDivElement> {* Adds a themed border on the appropriate edge.* - Start panel: border on end edge (right in LTR)* - End panel: border on start edge (left in LTR)- * When false, spacing collapse is applied automatically for seamless visual flow.+ * When false and `padding` is unset, the panel and the content share one gap.** Note: When using `resizable` with an adjacent `ResizeHandle hasDivider`,* set this to `false` to avoid a double-line artifact.@@ -151,9 +152,10 @@ export interface LayoutPanelProps extends BaseProps<HTMLDivElement> {hasDivider?: boolean;/**- * Internal padding of the panel using the spacing scale.+ * Internal padding of the panel on every edge, using the spacing scale.* Accepts numeric spacing steps: 0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 8, 10.- * Overrides the default padding from the layout container.+ * Replaces the automatic inset and the gap shared with the content.+ * `0` is full bleed.*/padding?: SpacingStep;diff --git a/packages/core/src/Layout/LayoutSlots.test.tsx b/packages/core/src/Layout/LayoutSlots.test.tsxindex 6c3a5036f5..46fbf9dc8d 100644--- a/packages/core/src/Layout/LayoutSlots.test.tsx+++ b/packages/core/src/Layout/LayoutSlots.test.tsx@@ -484,6 +484,34 @@ describe('LayoutPanel', () => {).toHaveTextContent('Details');});+ it('exposes no role or name without a caller role while it does not overflow', () => {+ const {container} = render(<LayoutPanel>P</LayoutPanel>);+ const panel = container.querySelector('.astryx-layout-panel');+ expect(panel).not.toHaveAttribute('role');+ expect(panel).not.toHaveAttribute('aria-label');+ });++ it('passes style, DOM, data, ARIA, and event props to the root', () => {+ const onClick = vi.fn();+ render(+ <LayoutPanel+ style={{color: 'red'}}+ id="side-panel"+ data-testid="panel"+ aria-describedby="hint"+ onClick={onClick}>+ P+ </LayoutPanel>,+ );+ const panel = screen.getByTestId('panel');+ expect(panel).toHaveClass('astryx-layout-panel');+ expect(panel.style.color).toBe('red');+ expect(panel).toHaveAttribute('id', 'side-panel');+ expect(panel).toHaveAttribute('aria-describedby', 'hint');+ fireEvent.click(screen.getByText('P'));+ expect(onClick).toHaveBeenCalledTimes(1);+ });+it('merges a caller className', () => {const {container} = render(<LayoutPanel className="panel-custom">P</LayoutPanel>,diff --git a/packages/core/src/Layout/__tests__/LayoutPanelAudit.a11y.chromium.spec.ts b/packages/core/src/Layout/__tests__/LayoutPanelAudit.a11y.chromium.spec.tsnew file mode 100644index 0000000000..9ff0ed0324--- /dev/null+++ b/packages/core/src/Layout/__tests__/LayoutPanelAudit.a11y.chromium.spec.ts@@ -0,0 +1,731 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y audit LayoutPanel++/**+ * @file LayoutPanelAudit.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 LayoutPanel whole-component audit+ * @position Component-owned Night Watch browser evidence; CI runs it only for a LayoutPanel 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-panel-audit-evidence');+const WIDE = {width: 1280, height: 1400};+const NARROW = {width: 320, height: 900};++type Mode = 'light' | 'dark';+type Theme = 'neutral' | 'butter';+type Direction = 'ltr' | 'rtl';+type Story =+ | 'panel-states'+ | 'with-sidebar'+ | 'dual-panels'+ | 'content-width-with-start-panel';++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;+type Slot = 'start' | 'end';++// The number of LayoutPanel regions each story renders, so a story that+// stops rendering one fails instead of passing with nothing to check.+const PANELS: Record<Story, number> = {+ 'panel-states': 12,+ 'with-sidebar': 1,+ 'dual-panels': 2,+ 'content-width-with-start-panel': 1,+};++type PanelExpectation = {+ slot: Slot;+ // The padding the panel applies on each edge, as a spacing step: 6 is the+ // Layout's `padding={6}`, 4 the inner inset.+ insets: Record<Edge, Step>;+ hasDivider: boolean;+ // The negative margin on the content-facing edge, as a spacing step: the+ // inner inset when the panel shares its gap with the content.+ overlap: Step;+ width?: number;+ role: string | null;+ name: string | null;+ overflow: 'auto' | 'clip';+ overflows?: boolean;+ // A full-bleed Divider inside reaches both inline edges of the panel's+ // padding box.+ hasBleedChild?: boolean;+};++const START_AUTOMATIC: Record<Edge, Step> = {+ inlineStart: 6,+ inlineEnd: 4,+ blockStart: 6,+ blockEnd: 6,+};+const END_AUTOMATIC: Record<Edge, Step> = {+ inlineStart: 4,+ inlineEnd: 6,+ blockStart: 6,+ blockEnd: 6,+};++const CASES: Record<string, PanelExpectation> = {+ 'start-automatic': {+ slot: 'start',+ insets: START_AUTOMATIC,+ hasDivider: false,+ overlap: 4,+ width: 120,+ role: null,+ name: null,+ overflow: 'auto',+ },+ 'start-divider': {+ slot: 'start',+ insets: START_AUTOMATIC,+ hasDivider: true,+ overlap: 0,+ width: 120,+ role: null,+ name: null,+ overflow: 'auto',+ },+ 'end-automatic': {+ slot: 'end',+ insets: END_AUTOMATIC,+ hasDivider: false,+ overlap: 4,+ width: 120,+ role: null,+ name: null,+ overflow: 'auto',+ },+ 'end-divider': {+ slot: 'end',+ insets: END_AUTOMATIC,+ hasDivider: true,+ overlap: 0,+ width: 120,+ role: null,+ name: null,+ overflow: 'auto',+ },+ // A header and a footer take the Layout-edge inset on the block edges, so+ // the panel keeps the inner inset there.+ 'header-footer': {+ slot: 'start',+ insets: {inlineStart: 6, inlineEnd: 4, blockStart: 4, blockEnd: 4},+ hasDivider: true,+ overlap: 0,+ width: 120,+ role: null,+ name: null,+ overflow: 'auto',+ },+ 'bleed-child': {+ slot: 'start',+ insets: START_AUTOMATIC,+ hasDivider: true,+ overlap: 0,+ width: 160,+ role: null,+ name: null,+ overflow: 'auto',+ hasBleedChild: true,+ },+ 'padding-2': {+ slot: 'start',+ insets: {inlineStart: 2, inlineEnd: 2, blockStart: 2, blockEnd: 2},+ hasDivider: true,+ overlap: 0,+ width: 120,+ role: null,+ name: null,+ overflow: 'auto',+ },+ 'full-bleed': {+ slot: 'start',+ insets: {inlineStart: 0, inlineEnd: 0, blockStart: 0, blockEnd: 0},+ hasDivider: true,+ overlap: 0,+ width: 120,+ role: null,+ name: null,+ overflow: 'auto',+ },+ 'width-string': {+ slot: 'start',+ insets: START_AUTOMATIC,+ hasDivider: true,+ overlap: 0,+ width: 160,+ role: null,+ name: null,+ overflow: 'auto',+ },+ landmark: {+ slot: 'start',+ insets: START_AUTOMATIC,+ hasDivider: true,+ overlap: 0,+ width: 120,+ role: 'navigation',+ name: 'Sections',+ overflow: 'auto',+ },+ // While it overflows, a scrolling panel is a group named "Content".+ scrolling: {+ slot: 'start',+ insets: START_AUTOMATIC,+ hasDivider: true,+ overlap: 0,+ width: 120,+ role: 'group',+ name: 'Content',+ overflow: 'auto',+ overflows: true,+ },+ 'not-scrollable': {+ slot: 'start',+ insets: START_AUTOMATIC,+ hasDivider: true,+ overlap: 0,+ width: 120,+ role: null,+ name: null,+ overflow: 'clip',+ overflows: true,+ },+};++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('panel-states');+add('panel-states', {theme: 'butter', modes: ['light']});+add('panel-states', {direction: 'rtl', modes: ['light']});+add('panel-states', {suffix: 'narrow', modes: ['light'], viewport: NARROW});+add('with-sidebar');+add('with-sidebar', {direction: 'rtl', modes: ['light']});+add('dual-panels', {modes: ['light']});+add('content-width-with-start-panel', {modes: ['light']});+add('content-width-with-start-panel', {direction: 'rtl', 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 border(style: CSSStyleDeclaration, side: 'Start' | 'End') {+ return {+ width: px(+ style.getPropertyValue(`border-inline-${side.toLowerCase()}-width`),+ ),+ style: style.getPropertyValue(+ `border-inline-${side.toLowerCase()}-style`,+ ),+ color: style.getPropertyValue(+ `border-inline-${side.toLowerCase()}-color`,+ ),+ };+ }+ 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 panels = Array.from(+ document.querySelectorAll('#storybook-root .astryx-layout-panel'),+ ).map(panel => {+ const style = getComputedStyle(panel);+ const layout = panel.closest('.astryx-layout');+ const content = Array.from(+ layout?.querySelectorAll('.astryx-layout-content') ?? [],+ ).find(candidate => candidate.closest('.astryx-layout') === layout);+ return {+ panelCase: panel.getAttribute('data-panel-case'),+ targets: Array.from(panel.classList).filter(name =>+ name.startsWith('astryx-'),+ ),+ role: panel.getAttribute('role'),+ name: panel.getAttribute('aria-label'),+ inert: panel.hasAttribute('inert'),+ flexShrink: style.flexShrink,+ direction: style.direction,+ overflowX: style.overflowX,+ overflowY: style.overflowY,+ overflows: panel.scrollHeight > panel.clientHeight + 1,+ borderStart: border(style, 'Start'),+ borderEnd: border(style, 'End'),+ borderColor: color(panel, 'var(--color-border)'),+ marginInlineStart: px(style.marginInlineStart),+ marginInlineEnd: px(style.marginInlineEnd),+ box: box(panel),+ bleedBox: (() => {+ const divider = panel.querySelector(':scope > .astryx-divider');+ return divider == null ? null : box(divider);+ })(),+ contentBox: content == null ? null : box(content),+ layoutBox: layout == null ? null : box(layout),+ applied: {+ inlineStart: px(style.paddingInlineStart),+ inlineEnd: px(style.paddingInlineEnd),+ blockStart: px(style.paddingBlockStart),+ blockEnd: px(style.paddingBlockEnd),+ },+ published: {+ inlineStart: resolve(+ panel,+ 'var(--container-padding-inline-start, 0px)',+ ),+ inlineEnd: resolve(panel, 'var(--container-padding-inline-end, 0px)'),+ blockStart: resolve(+ panel,+ 'var(--container-padding-block-start, 0px)',+ ),+ blockEnd: resolve(panel, 'var(--container-padding-block-end, 0px)'),+ },+ };+ });+ 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,+ panels,+ };+ });+}++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-panel')+ .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.panels.map(panel => panel.box)) ===+ JSON.stringify(observed.panels.map(panel => panel.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.panels.length === PANELS[item.story],+ `${observed.panels.length} panels, expected ${PANELS[item.story]}`,+ );+ if (item.viewport !== NARROW) {+ check(+ observed.documentOverflow <= 0,+ `document scrolls sideways by ${observed.documentOverflow}px`,+ );+ }++ const panelCases = new Set<string>();+ observed.panels.forEach((panel, index) => {+ const where = `panel ${index}${panel.panelCase ? ` (${panel.panelCase})` : ''}`;+ check(+ JSON.stringify(panel.targets) === '["astryx-layout-panel"]',+ `${where} targets ${panel.targets.join(' ')}`,+ );+ check(+ panel.flexShrink === '0',+ `${where} flex-shrink ${panel.flexShrink}`,+ );+ check(+ panel.direction === item.direction,+ `${where} direction ${panel.direction}`,+ );+ check(!panel.inert, `${where} is inert`);+ // The panel publishes the padding it applies on every edge.+ for (const edge of EDGES) {+ check(+ near(panel.applied[edge], panel.published[edge]),+ `${where} ${edge} applies ${panel.applied[edge]} but publishes ${panel.published[edge]}`,+ );+ }+ // Its slot, read from its place beside the content: a start panel sits+ // at the content's inline start, which is the left in LTR.+ const contentBox = panel.contentBox;+ const slot: Slot | null =+ contentBox == null+ ? null+ : panel.box.left < contentBox.left === (item.direction === 'ltr')+ ? 'start'+ : 'end';+ // A divider is a 1px solid --color-border line on the content-facing+ // edge only: inline end for a start panel, inline start for an end panel.+ const facing = slot === 'end' ? panel.borderStart : panel.borderEnd;+ const outer = slot === 'end' ? panel.borderEnd : panel.borderStart;+ check(outer.width === 0, `${where} line on its outer edge`);+ if (facing.width > 0) {+ check(+ near(facing.width, 1, 0.01) &&+ facing.style === 'solid' &&+ facing.color === panel.borderColor,+ `${where} line ${JSON.stringify(facing)}`,+ );+ }+ if (panel.layoutBox != null) {+ check(+ panel.box.left >= panel.layoutBox.left - 0.6 &&+ panel.box.right <= panel.layoutBox.right + 0.6,+ `${where} ${JSON.stringify(panel.box)} leaves its layout ${JSON.stringify(panel.layoutBox)}`,+ );+ }++ if (panel.panelCase != null) {+ panelCases.add(panel.panelCase);+ const expected = CASES[panel.panelCase];+ check(expected != null, `${where} is not an expected case`);+ if (expected == null) {+ return;+ }+ check(+ slot === expected.slot,+ `${where} slot ${slot}, expected ${expected.slot}`,+ );+ for (const edge of EDGES) {+ check(+ near(panel.applied[edge], stepPx(expected.insets[edge])),+ `${where} ${edge} applies ${panel.applied[edge]}, expected ${stepPx(expected.insets[edge])} (step ${expected.insets[edge]})`,+ );+ }+ check(+ facing.width > 0 === expected.hasDivider,+ `${where} line ${facing.width}px, expected divider ${expected.hasDivider}`,+ );+ const overlap =+ expected.slot === 'end'+ ? panel.marginInlineStart+ : panel.marginInlineEnd;+ const otherMargin =+ expected.slot === 'end'+ ? panel.marginInlineEnd+ : panel.marginInlineStart;+ check(+ near(overlap, -stepPx(expected.overlap)) && otherMargin === 0,+ `${where} margins ${panel.marginInlineStart}/${panel.marginInlineEnd}, expected an overlap of ${stepPx(expected.overlap)} on the content-facing edge`,+ );+ if (expected.width != null) {+ check(+ near(panel.box.width, expected.width),+ `${where} width ${panel.box.width}, expected ${expected.width}`,+ );+ }+ check(+ panel.role === expected.role && panel.name === expected.name,+ `${where} role ${panel.role} name ${panel.name}, expected ${expected.role} ${expected.name}`,+ );+ check(+ panel.overflowY === expected.overflow,+ `${where} overflow ${panel.overflowX}/${panel.overflowY}, expected ${expected.overflow}`,+ );+ if (expected.hasBleedChild) {+ // The padding box spans the border box less the divider line on+ // the content-facing edge.+ const line = facing.width;+ const paddingLeft =+ panel.box.left + (item.direction === 'rtl' ? line : 0);+ const paddingRight =+ panel.box.right - (item.direction === 'rtl' ? 0 : line);+ check(+ panel.bleedBox != null &&+ near(panel.bleedBox.left, paddingLeft) &&+ near(panel.bleedBox.right, paddingRight),+ `${where} full-bleed child ${JSON.stringify(panel.bleedBox)}, expected ${paddingLeft} to ${paddingRight}`,+ );+ }+ if (expected.overflows != null) {+ check(+ panel.overflows === expected.overflows,+ `${where} overflows ${panel.overflows}, expected ${expected.overflows}`,+ );+ }+ }+ });+ if (item.story === 'panel-states') {+ check(+ JSON.stringify([...panelCases].sort()) ===+ JSON.stringify(Object.keys(CASES).sort()),+ `panel cases ${[...panelCases].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,+ panels: PANELS[item.story],+ anatomy:+ 'each panel root carries only the astryx-layout-panel target, does not shrink, follows the page direction, is not inert, and stays inside its layout',+ divider:+ 'no line on the outer edge; a line on the content-facing edge is 1px solid --color-border',+ publication: 'the panel applies exactly the padding it publishes',+ cases: item.story === 'panel-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/LayoutPanel',+ 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([]);+});diff --git a/packages/core/src/Layout/__tests__/nestedPadding.test.tsx b/packages/core/src/Layout/__tests__/nestedPadding.test.tsxindex 049331dec4..bf6118ed5b 100644--- a/packages/core/src/Layout/__tests__/nestedPadding.test.tsx+++ b/packages/core/src/Layout/__tests__/nestedPadding.test.tsx@@ -4,22 +4,22 @@* @file nestedPadding.test.tsx* @input Uses vitest, @testing-library/react, Layout, AppShell, Card, Section* @output Tests which outer inset a Layout's regions resolve to when Layouts- * are nested or composed inside padding containers+ * are nested or composed inside padding containers, and that LayoutPanel+ * publishes the inset it applies on each edge* @position Layout tests; validates the scope of Layout's `padding` prop** A Layout's `padding` belongs to its own regions. A nested Layout without* `padding` takes the nearest padding container's inset (Card, Section,- * Dialog) or the default, and never an ancestor Layout's value. AppShell's- * internal Layout uses `padding={0}`, so before this was scoped every page- * Layout inside AppShell lost its default inset.+ * Dialog) or the default, and never an ancestor Layout's value, so a page+ * Layout inside AppShell, whose internal Layout uses `padding={0}`, keeps its+ * default inset.** jsdom neither inherits custom properties nor keeps logical padding* declarations, so `resolvedInset` reproduces the cascade from the injected* StyleX rules: it reads the region's republished* `--container-padding-inline-start` (the same expression as its applied* inline-start padding) and substitutes each `var()` from the nearest- * declaring ancestor. The pixel results are verified in a browser; see the- * pull request description.+ * declaring ancestor. Browser tests verify the pixel results.*/import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';@@ -27,6 +27,8 @@ import {render, screen} from '@testing-library/react';import {Layout} from '../Layout';import {LayoutHeader} from '../LayoutHeader';import {LayoutContent} from '../LayoutContent';+import {LayoutFooter} from '../LayoutFooter';+import {LayoutPanel} from '../LayoutPanel';import {AppShell} from '../../AppShell';import {Card} from '../../Card';import {Section} from '../../Section';@@ -262,3 +264,106 @@ describe('Layout padding scope', () => {expect(resolvedInset('page-header')).toBe('var(--spacing-2)');});});++type PanelEdge = 'inline-start' | 'inline-end' | 'block-start' | 'block-end';++/** The inset a panel publishes on one edge, as a spacing token reference. */+function publishedPanelInset(testId: string, edge: PanelEdge) {+ return lookup(+ screen.getByTestId(testId),+ `--container-padding-${edge}`,+ declarationsByClass(),+ );+}++describe('LayoutPanel inset publication', () => {+ // The Layout's `padding` sets the Layout-edge inset; the inner inset stays+ // at the step-4 default, so the two differ on every edge.+ function PanelLayout({hasHeaderAndFooter = false}) {+ return (+ <Layout+ padding={2}+ header={hasHeaderAndFooter ? <LayoutHeader>Title</LayoutHeader> : null}+ start={<LayoutPanel data-testid="start-panel">Start</LayoutPanel>}+ content={<LayoutContent>Body</LayoutContent>}+ end={<LayoutPanel data-testid="end-panel">End</LayoutPanel>}+ footer={+ hasHeaderAndFooter ? <LayoutFooter>Actions</LayoutFooter> : null+ }+ />+ );+ }++ it('publishes the Layout-edge inset on the edges where a panel applies it', () => {+ render(<PanelLayout />);+ expect(publishedPanelInset('start-panel', 'inline-start')).toBe(+ 'var(--spacing-2)',+ );+ expect(publishedPanelInset('start-panel', 'inline-end')).toBe(+ 'var(--spacing-4)',+ );+ expect(publishedPanelInset('end-panel', 'inline-start')).toBe(+ 'var(--spacing-4)',+ );+ expect(publishedPanelInset('end-panel', 'inline-end')).toBe(+ 'var(--spacing-2)',+ );+ for (const panel of ['start-panel', 'end-panel']) {+ expect(publishedPanelInset(panel, 'block-start')).toBe(+ 'var(--spacing-2)',+ );+ expect(publishedPanelInset(panel, 'block-end')).toBe('var(--spacing-2)');+ }+ });++ it('publishes the inner inset on block edges beside a header and footer', () => {+ render(<PanelLayout hasHeaderAndFooter />);+ for (const panel of ['start-panel', 'end-panel']) {+ expect(publishedPanelInset(panel, 'block-start')).toBe(+ 'var(--spacing-4)',+ );+ expect(publishedPanelInset(panel, 'block-end')).toBe('var(--spacing-4)');+ }+ });++ it('publishes a zero Layout padding on its outer edges', () => {+ render(+ <Layout+ padding={0}+ start={<LayoutPanel data-testid="start-panel">Start</LayoutPanel>}+ content={<LayoutContent>Body</LayoutContent>}+ />,+ );+ expect(publishedPanelInset('start-panel', 'inline-start')).toBe(+ 'var(--spacing-0)',+ );+ expect(publishedPanelInset('start-panel', 'inline-end')).toBe(+ 'var(--spacing-4)',+ );+ expect(publishedPanelInset('start-panel', 'block-start')).toBe(+ 'var(--spacing-0)',+ );+ });++ it('publishes an explicit padding on every edge', () => {+ render(+ <Layout+ padding={2}+ start={+ <LayoutPanel padding={6} data-testid="start-panel">+ Start+ </LayoutPanel>+ }+ content={<LayoutContent>Body</LayoutContent>}+ />,+ );+ for (const edge of [+ 'inline-start',+ 'inline-end',+ 'block-start',+ 'block-end',+ ] as const) {+ expect(publishedPanelInset('start-panel', edge)).toBe('var(--spacing-6)');+ }+ });+});