An open source design system that's fully customizable and agent ready
TypeScript
[Component Audit] ChatLayout: keyboard users no longer land on an invisible scroll button (#6466)
Cindy Zhange9b8aa112b10
diff --git a/.changeset/chatlayout-audit-hidden-scroll-button.md b/.changeset/chatlayout-audit-hidden-scroll-button.mdnew file mode 100644index 0000000000..e26ea323cc--- /dev/null+++ b/.changeset/chatlayout-audit-hidden-scroll-button.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Stop ChatLayout's scroll-to-bottom button from being a tab stop while it is invisible. At rest the layout's default `scrollButton` renders hidden, but `opacity: 0` and `pointer-events: none` leave it in sequential focus navigation — so a keyboard user's first Tab into any chat landed on a control with no visible focus indicator (WCAG 2.2 SC 2.4.7), and Enter scrolled the transcript. The hidden state now also sets `visibility: hidden`, which the fade transition carries so the animation is unchanged; the visible button keeps its keyboard access. The pill's height and collapsed width now track `--size-element-md` instead of a hardcoded `32px`, so a theme that retunes the element scale can no longer make the pill clip its own Button. ChatLayout's consumer docs also gain the `density` prop, which was undocumented, and drop the claim that density adapts automatically to container width — it never did. A Chromium evidence spec pins the hidden/visible/re-hidden keyboard contract and the pill's containment of its Button under a size-retuning theme, and the RTL applicability ledger records why ChatLayout and its scroll button have no applicable RTL dimension. (#6466)++@cixzhangdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 80ee4bce5c..4c4cac878a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -821,6 +821,19 @@ jobs:retention-days: 30if-no-files-found: error+ # Component-audit browser evidence. A whole-component audit has to show+ # the states it graded, and the audit node cannot always run a browser —+ # so the frames and their sensor receipts are produced here, bound to the+ # same exact head as every other check in this job.+ - name: Upload component-audit browser evidence+ if: always()+ uses: actions/upload-artifact@v7+ with:+ name: component-audit-evidence-${{ needs.build-storybook.outputs.short_hash }}+ path: test-results/chat-layout-audit-evidence/+ retention-days: 30+ if-no-files-found: error+# Build package test owner. The plugin's production CSS partition is a Build# integration contract: source inspection cannot prove which declaration# paints after Vite emits the final bundle. The `test-build` name makes thatdiff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.jsonindex 570b5aecf9..a293110793 100644--- a/apps/storybook/rtl-audit/verified-not-applicable.json+++ b/apps/storybook/rtl-audit/verified-not-applicable.json@@ -1,7 +1,7 @@[{"component": "core/Banner",- "reason": "Banner renders a single wrap-capable flex header row \u2014 status icon, title/description column, and an end area pushed over with `marginInlineStart: 'auto'` \u2014 above an optional content panel. Its status, close and expand glyphs (`info`, `warning`, `error`, `success`, `close`, `chevronDown`) are all radially symmetric or vertical, and the expanded state rotates the chevron 180\u00b0 about the block axis. Every inset, corner radius and border it draws is a logical property, so the whole banner mirrors under RTL with nothing positioned, ordered or animated along the inline axis for the audit to assert.",+ "reason": "Banner renders a single wrap-capable flex header row — status icon, title/description column, and an end area pushed over with `marginInlineStart: 'auto'` — above an optional content panel. Its status, close and expand glyphs (`info`, `warning`, `error`, `success`, `close`, `chevronDown`) are all radially symmetric or vertical, and the expanded state rotates the chevron 180° about the block axis. Every inset, corner radius and border it draws is a logical property, so the whole banner mirrors under RTL with nothing positioned, ordered or animated along the inline axis for the audit to assert.","evidence": {"apps/storybook/stories/Banner.stories.tsx": "sha256:15792a91bf7a7df1d6e15085cc42b9fc7f4df05135d09b6360b2a24ca2a6db5d","packages/core/src/Banner/Banner.tsx": "sha256:d69e58bc792b8c8802311aacd7b629c890915424f5b575d3bb3f71645db9c77f",@@ -10,7 +10,7 @@},{"component": "core/ToggleButton",- "reason": "ToggleButton stories lay out label and optional icon in an inline flex row with logical gap only \u2014 no directional glyphs (the toolbar icons are non-directional), no side-specific placement, order, inset, or offset, no scrolling, dragging, or overlays. Elevation is a symmetric box-shadow, direction-independent by construction, so the LTR and RTL renders are mirror-identical."+ "reason": "ToggleButton stories lay out label and optional icon in an inline flex row with logical gap only — no directional glyphs (the toolbar icons are non-directional), no side-specific placement, order, inset, or offset, no scrolling, dragging, or overlays. Elevation is a symmetric box-shadow, direction-independent by construction, so the LTR and RTL renders are mirror-identical."},{"component": "core/Field",@@ -26,7 +26,7 @@},{"component": "core/Spinner",- "reason": "No direction-sensitive visual, layout, or behavior. The ring is a concentric SVG \u2014 two <circle> elements sharing one center, sized by diameter and stroke, with no physical inset, offset, or asymmetry to mirror. Its only layout is the optional label wrapper, which is flexDirection: column + alignItems: center, so the label stacks below the ring on both axes' terms rather than beside it. The rotation keyframe (0deg to 360deg) is deliberately absolute: a loading spinner turns the same way in every locale, and mirroring it would be a bug, not RTL support."+ "reason": "No direction-sensitive visual, layout, or behavior. The ring is a concentric SVG — two <circle> elements sharing one center, sized by diameter and stroke, with no physical inset, offset, or asymmetry to mirror. Its only layout is the optional label wrapper, which is flexDirection: column + alignItems: center, so the label stacks below the ring on both axes' terms rather than beside it. The rotation keyframe (0deg to 360deg) is deliberately absolute: a loading spinner turns the same way in every locale, and mirroring it would be a bug, not RTL support."},{"component": "core/Table",@@ -34,7 +34,7 @@},{"component": "core/Text",- "reason": "Text sets typography \u2014 size, weight, colour, line-height, wrapping, truncation \u2014 and nothing else. Its one alignment prop is `justify`, which compiles to the logical `text-align: start | center | end` and defaults to `start`, so text hangs off the correct edge in either direction without a component-side branch. Truncation is `text-overflow: ellipsis` and `-webkit-line-clamp`, both of which put the ellipsis at the reading end on their own, and the tooltip that accompanies a clamped string is placed with the logical `above`/`below`/`start`/`end` vocabulary. Nothing is positioned, nothing is transformed, and the component renders no glyph, separator, or control."+ "reason": "Text sets typography — size, weight, colour, line-height, wrapping, truncation — and nothing else. Its one alignment prop is `justify`, which compiles to the logical `text-align: start | center | end` and defaults to `start`, so text hangs off the correct edge in either direction without a component-side branch. Truncation is `text-overflow: ellipsis` and `-webkit-line-clamp`, both of which put the ellipsis at the reading end on their own, and the tooltip that accompanies a clamped string is placed with the logical `above`/`below`/`start`/`end` vocabulary. Nothing is positioned, nothing is transformed, and the component renders no glyph, separator, or control."},{"component": "core/Timestamp",@@ -235,5 +235,23 @@"packages/core/src/Chat/ChatDictationButton.tsx": "sha256:bad96c58a64ed9463c428ab7ef53a8c41794bb685eb34b4b333c6cad5c8993c2","packages/core/src/Chat/index.ts": "sha256:0f4a9d3ee08b4fcd43698ad017460aad109c500d2411913f509506d2a27387bb"}+ },+ {+ "component": "core/ChatLayout",+ "reason": "ChatLayout is a block-flow shell: a flex column whose message area centers with marginInline auto and whose dock spans the full inline width using insetInlineStart/insetInlineEnd and logical padding. It scrolls on the block axis only (overflowY auto with overflowX hidden), owns no directional glyph, no physical inline offset or transform, no inline reordering, no horizontal scrolling or dragging, no side-placed overlay, and no horizontal keyboard behavior. Density selects block-axis blur height and symmetric inline padding. Message, composer, and scroll-affordance direction remain with their own owners.",+ "evidence": {+ "apps/storybook/stories/ChatLayout.stories.tsx": "sha256:e269ccea468b27e9dc20abd5e7998233c6726d2f84d88b9c6d64fefac74fc9b8",+ "packages/core/src/Chat/ChatLayout.tsx": "sha256:bc5fbef0379c622adaf46dc7119d327100eb40c2440664b3bc288bab758b116b",+ "packages/core/src/Chat/index.ts": "sha256:0f4a9d3ee08b4fcd43698ad017460aad109c500d2411913f509506d2a27387bb"+ }+ },+ {+ "component": "core/ChatLayoutScrollButton",+ "reason": "ChatLayoutScrollButton is a centered pill on the block axis. Its only glyph is the block-axis chevronDown, which points along the axis RTL does not mirror, so mirroring it would be wrong rather than missing. The wrapper centers with justifyContent center, the pill sizes from logical maxWidth and the element-size token, and the labelled form uses logical paddingInline/paddingInlineEnd so the icon leads and the text trails in both directions. It owns no left/right glyph, physical inline positioning, inline ordering, horizontal scrolling or dragging, overlay placement, or horizontal keyboard behavior.",+ "evidence": {+ "apps/storybook/stories/ChatLayout.stories.tsx": "sha256:e269ccea468b27e9dc20abd5e7998233c6726d2f84d88b9c6d64fefac74fc9b8",+ "packages/core/src/Chat/ChatLayoutScrollButton.tsx": "sha256:33e69782520576df24846e01712628788eb5b1ccade74db6a836fd47a1eba92d",+ "packages/core/src/Chat/index.ts": "sha256:0f4a9d3ee08b4fcd43698ad017460aad109c500d2411913f509506d2a27387bb"+ }}]diff --git a/apps/storybook/stories/ChatLayout.stories.tsx b/apps/storybook/stories/ChatLayout.stories.tsxindex 9b75c9b10d..ba1a149539 100644--- a/apps/storybook/stories/ChatLayout.stories.tsx+++ b/apps/storybook/stories/ChatLayout.stories.tsx@@ -472,9 +472,7 @@ export const FullAIChat: StoryObj = {placeholder="Ask about the codebase..."/>}- footerActions={- <Button label="Claude Opus" variant="ghost" size="md" />- }+ footerActions={<Button label="Claude Opus" variant="ghost" size="md" />}sendActions={<Buttonlabel="Microphone"@@ -847,3 +845,113 @@ export const WithEmptyState: StoryObj = {</div>),};++const DENSITIES = ['compact', 'balanced', 'spacious'] as const;+/**+ * The three densities side by side. Density is a prop, not an automatic+ * container-width adaptation: it selects the dock's inline and block-end+ * padding, the message area's max-width and inline padding, and the height and+ * mask of the frosted glass blur layer.+ */+export const Densities: StoryObj = {+ name: 'Densities',+ render: () => (+ <div+ style={{+ display: 'flex',+ gap: 16,+ height: '100vh',+ padding: 16,+ boxSizing: 'border-box',+ }}>+ {DENSITIES.map(density => (+ <div+ key={density}+ style={{+ flex: 1,+ minWidth: 0,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ }}>+ <strong style={{paddingBlockEnd: 8}}>{density}</strong>+ <ChatLayout+ density={density}+ composer={+ <ChatComposer onSubmit={() => {}} placeholder="Reply…" />+ }>+ <ChatMessageList density={density}>+ <ChatSystemMessage variant="divider">Today</ChatSystemMessage>+ <ChatMessage sender="user">+ <ChatMessageBubble>+ How does density change the layout?+ </ChatMessageBubble>+ </ChatMessage>+ <ChatMessage sender="assistant">+ <ChatMessageBubble>+ It sets the dock padding, the message column width, and the+ height of the blur behind the composer.+ </ChatMessageBubble>+ </ChatMessage>+ </ChatMessageList>+ </ChatLayout>+ </div>+ ))}+ </div>+ ),+};++const AFFORDANCE_TURNS = [+ 'What does the scroll-to-bottom button do?',+ 'It appears once you scroll away from the newest message.',+ 'And when I am already at the bottom?',+ 'Then it is hidden, and it must not take keyboard focus.',+ 'Why does that matter?',+ 'Focus landing on something invisible has no visible focus indicator.',+ 'So the hidden state has to leave the tab order.',+ 'Exactly — opacity alone does not do that.',+ 'What removes it?',+ 'visibility: hidden, carried on the same transition so the fade still plays.',+ 'Does the visible button stay reachable?',+ 'Yes. Hiding it from the keyboard only applies while it paints nothing.',+];++/**+ * Deterministic fixture for the scroll-to-bottom affordance: a bounded,+ * self-scrolling ChatLayout with static content and a sentinel control in+ * front of it. Scrolling away from the bottom reveals the affordance and+ * scrolling back hides it, so one story reaches the hidden, visible, and+ * re-hidden states without timers, streaming, or `new Date()`.+ *+ * Drives the exact-head keyboard and theme-size evidence in+ * `ChatLayoutScrollButton.a11y.chromium.spec.ts`.+ */+export const ScrollAffordanceStates: StoryObj = {+ name: 'Scroll Affordance States',+ render: () => (+ <div style={{padding: 16}}>+ <button type="button">Before chat</button>+ <div+ style={{+ height: 420,+ marginBlockStart: 12,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ }}>+ <ChatLayout+ composer={<ChatComposer onSubmit={() => {}} placeholder="Reply…" />}>+ <ChatMessageList>+ {AFFORDANCE_TURNS.map((text, index) => (+ <ChatMessage+ key={text}+ sender={index % 2 === 0 ? 'user' : 'assistant'}>+ <ChatMessageBubble>{text}</ChatMessageBubble>+ </ChatMessage>+ ))}+ </ChatMessageList>+ </ChatLayout>+ </div>+ </div>+ ),+};diff --git a/packages/core/src/Chat/ChatLayout.doc.mjs b/packages/core/src/Chat/ChatLayout.doc.mjsindex 734fd2b891..9a56754938 100644--- a/packages/core/src/Chat/ChatLayout.doc.mjs+++ b/packages/core/src/Chat/ChatLayout.doc.mjs@@ -6,7 +6,7 @@ export const docs = {name: 'ChatLayout',subComponentOf: 'Chat',displayName: 'Chat Layout',- description: 'Layout shell for full chat interfaces. Messages flow in normal page flow, composer is fixed to the bottom with a frosted glass dock. Adapts density (compact/balanced/spacious) automatically via container width observation. Includes built-in auto-scroll, a "New messages" scroll-to-bottom button, and a frosted glass blur layer behind the composer. By default the layout root is the scroll container; pass scrollRef to delegate scrolling to a parent element or the document body.',+ description: 'Layout shell for full chat interfaces. Messages flow in normal page flow, composer is fixed to the bottom with a frosted glass dock. Set density (compact/balanced/spacious) to control spacing, message max-width, and blur layer sizing. Includes built-in auto-scroll, a "New messages" scroll-to-bottom button, and a frosted glass blur layer behind the composer. By default the layout root is the scroll container; pass scrollRef to delegate scrolling to a parent element or the document body.',props: [{name: 'children',@@ -53,9 +53,15 @@ export const docs = {type: 'React.RefObject<HTMLElement | null>',description: 'External scroll container ref. When provided, auto-scroll and scroll-to-bottom target this element instead of the layout root. Use when the chat is embedded in a page where a parent element or the document body scrolls.',},+ {+ name: 'density',+ type: "'compact' | 'balanced' | 'spacious'",+ description: 'Visual density: controls dock padding, message-area max-width and inline padding, and the height of the frosted glass blur layer.',+ default: "'balanced'",+ },],usage: {- description: 'ChatLayout is the layout shell for full-page chat interfaces. It renders messages in normal page flow and docks the composer to the bottom with a frosted glass blur layer. Density adapts automatically via container width observation. Use it to wrap ChatMessageList and ChatComposer for a complete chat experience with built-in auto-scroll and a scroll-to-bottom button.',+ description: 'ChatLayout is the layout shell for full-page chat interfaces. It renders messages in normal page flow and docks the composer to the bottom with a frosted glass blur layer. Set the density prop to control spacing; it defaults to balanced. Use it to wrap ChatMessageList and ChatComposer for a complete chat experience with built-in auto-scroll and a scroll-to-bottom button.',bestPractices: [{guidance: true,@@ -111,20 +117,21 @@ export const docs = {export const docsZh = {name: 'ChatLayout',displayName: 'Chat Layout',- description: '完整聊天界面的布局外壳。消息在页面中自然流动,编写器固定在底部,带有毛玻璃效果。通过容器宽度自动适配密度。',+ description: '完整聊天界面的布局外壳。消息在页面中自然流动,编写器固定在底部,带有毛玻璃效果。通过 density 属性控制密度。',propDescriptions: {children: '消息内容,通常是 ChatMessageList。在页面中自然流动。',composer: '编写器元素,通常是 ChatComposer。固定在底部,带有毛玻璃底座。',emptyState: '子元素为空时显示的内容。',scrollButton: '编写器上方的滚动到底部按钮。默认使用 ChatLayoutScrollButton。传入 null 隐藏。',scrollRef: '外部滚动容器引用。提供时,自动滚动和滚动到底部将目标指向此元素。',+ density: '视觉密度:控制底座内边距、消息区最大宽度和毛玻璃层高度。',},};export const docsDense = {name: 'ChatLayout',displayName: 'Chat Layout',- description: 'layout shell for full chat; msgs in page flow, composer fixed bottom w/ frosted glass dock; auto density via container width; scrollRef delegates to parent/body',+ description: 'layout shell for full chat; msgs in page flow, composer fixed bottom w/ frosted glass dock; density prop (default balanced); scrollRef delegates to parent/body',usage: {bestPractices: [{guidance: true, description: 'Pass ChatMessageList as children and ChatComposer as composer prop for complete chat.'},@@ -140,5 +147,6 @@ export const docsDense = {emptyState: 'content when children empty',scrollButton: 'scroll-to-bottom btn; defaults to ChatLayoutScrollButton; pass null to hide',scrollRef: 'external scroll container ref; targets parent/body instead of layout root',+ density: 'visual density; dock padding, message max-width, blur height',},};diff --git a/packages/core/src/Chat/ChatLayout.spec.md b/packages/core/src/Chat/ChatLayout.spec.mdnew file mode 100644index 0000000000..67b74405d6--- /dev/null+++ b/packages/core/src/Chat/ChatLayout.spec.md@@ -0,0 +1,271 @@+---+schema_version: 3+template_version: 5+kind: component+id: component:ChatLayout+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+owners: [cixzhang]+review_triggers:+ [public-api, behavior, layout, scrolling, accessibility, theming, testing]+verified_by:+ [+ packages/core/src/Chat/ChatLayout.test.tsx,+ packages/core/src/Chat/ChatLayoutScrollButton.test.tsx,+ packages/core/src/Chat/useChatStreamScroll.test.tsx,+ packages/core/src/Chat/useChatNewMessages.test.tsx,+ apps/storybook/stories/ChatLayout.stories.tsx,+ ]+modules: []+families: []+design_specs: []+architecture:+ [+ architecture:public-component-api,+ architecture:component-style-authoring,+ architecture:component-theming-surface,+ architecture:theme-tokens,+ architecture:react-component-runtime,+ architecture:component-test-sufficiency,+ architecture:knowledge-contracts,+ ]+contributing: []+system_specs: [spec:AST-025, spec:AST-029]+---++# ChatLayout component contract++This record is an **observational backfill** written during the 2026-09-23+component audit under `spec:AST-029/FR3–FR4`. Every row below describes behavior+already shipped on `main` and verified against source, focused tests, and+consumer docs. It adds, improves, removes and reinterprets nothing. Rows whose+basis is only current behavior are marked `verify`; unresolved questions stay in+Open questions rather than being settled here.++## Contract at a glance++| Area | Contract |+| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | `children`, `composer`, `emptyState`, `scrollButton`, `scrollRef`, `density`, plus `BaseProps<HTMLDivElement>` and `ref` on the layout root. |+| Behavior | The root is a flex column; the message area grows and never shrinks; the dock is sticky when the root scrolls and fixed when `scrollRef` names an outer scroller. |+| End-user impact | A chat transcript scrolls under a composer that stays reachable, auto-follows streaming output, and offers a scroll-to-bottom affordance when the reader has moved away from the bottom. |+| Builder impact | None from this record. It documents the shipped surface; `density` becomes discoverable in consumer docs, which previously described an adaptation the component never performed. |+| Compatibility/readiness | Observational draft. No public API, default, or compatibility promise changes. Authority is `draft` until exact-head owner approval. |+| Review checks | Reject any row that states unshipped behavior, promises a default this component does not apply, or resolves OQ1 or OQ2 without an owner decision. |+| Governing rules | `architecture:public-component-api/INV1, INV5–INV6, INV8`; `architecture:component-style-authoring/INV1–INV3, INV5`; `architecture:theme-tokens/INV3`; `spec:AST-025/FR12` (not adopted). |++This table is a review projection; the body below is authoritative.++## Intent++ChatLayout is the structural shell for a chat surface. It owns one job: place a+scrolling transcript above a docked composer so that short conversations do not+overflow, long ones scroll, and the composer stays at the bottom edge of+whichever element actually scrolls. Scroll mechanics live in+`useChatStreamScroll` and `useChatNewMessages`; this component wires them to the+DOM it owns and publishes the resulting refs through `ChatLayoutContext`.++Consumer usage, prop syntax, and examples belong in `ChatLayout.doc.mjs`.++## Compatibility and migration++- Released default preserved: yes — `@astryxdesign/[email protected]` ships `./Chat`+ with `ChatLayout`, `ChatLayoutProps`, and `ChatLayoutScrollButton`.+- Compatibility class: no change. This record is descriptive.+- Controlled/uncontrolled behavior: not applicable; the component holds no+ controllable value.+- Migration decision: none.++## Ownership boundary++**Owns**++- The layout root: flex column, relative positioning, `container-type:+inline-size`, and the `chat-layout` theming target with its `density` axis.+- Which element scrolls: the root itself, or the element named by `scrollRef`.+- Dock positioning — `sticky` in self-scroll mode, `fixed` in external-scroll+ mode — and the frosted glass layer painted behind it.+- Density geometry: dock padding, message-column max-width and inline padding,+ and the blur layer's height and mask.+- Empty-state substitution and its centering box.+- The default scroll-to-bottom affordance and the visibility signal it receives.+- Publication of `scrollContainerRef` and `contentRef` through `ChatLayoutContext`.++**Does not own / non-goals**++- Scroll measurement, spring animation, lock behavior, or new-message detection —+ owned by `useChatStreamScroll` and `useChatNewMessages`.+- Message presentation, grouping, or sender semantics — owned by+ `component:ChatMessageList` and `component:ChatMessage`.+- Composer behavior, sizing, or status — owned by `component:ChatComposer`.+- The scroll-to-bottom control's own presentation — owned by+ `component:ChatLayoutScrollButton`.+- Page shell, navigation, and landmark assignment — the caller's.+- The shared effective-axis scroll capability defined by `spec:AST-025`. This+ component predates it and has not adopted it; see OQ1.++## Public concepts++| Concept | Closed values or states | Meaning | Default | Owner | Stability | Invalid-value behavior |+| -------------- | -------------------------------------------------------- | ---------------------------------------------------------------------------------- | ----------- | -------------------- | --------- | ------------------------------------------ |+| `children` | any `ReactNode` | Transcript content placed in the message area. | required | caller | stable | n/a — required |+| `composer` | any `ReactNode` | Content placed inside the dock. | required | caller | stable | n/a — required |+| `emptyState` | `ReactNode`; omitted | Rendered centred in place of `children` when `children` is empty. | omitted | caller | stable | omitted renders `children` unchanged |+| `scrollButton` | `undefined`; `null`; any `ReactNode` | `undefined` selects the wired default, `null` renders nothing, a node replaces it. | `undefined` | component/caller | stable | any node renders as given |+| `scrollRef` | `RefObject<HTMLElement \| null>`; omitted | Names the scrolling element; omitted makes the root scroll. | omitted | caller | stable | a null `current` leaves scrolling inactive |+| `density` | `compact`; `balanced`; `spacious` | Selects dock padding, message-column width, and blur-layer size. | `balanced` | component | stable | closed union; rejected by types |+| root surface | `ref`; DOM/data/ARIA props; `className`/`style`/`xstyle` | Extends the layout root. | omitted | public component API | stable | n/a |++`density` is a closed union. It is a documented `visualProps` axis of the+`chat-layout` target, and it is not theme-extensible: no unavailable custom value+has a safe theme-independent baseline, so it stays closed under+`architecture:component-theming-surface/INV14`.++## Behavioral and layout contract++| ID | Candidate invariant | Basis | Draft review state |+| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | ------------------ |+| FR1 | The root MUST be a flex column, so an in-flow sticky dock's height is part of the root's height rather than added on top of it. | regression fix for the phantom-scrollbar defect; pinned tests | settled |+| FR2 | The message area MUST grow into leftover space and MUST NOT shrink below its content height, so short transcripts fill the root exactly and long ones overflow it. | same regression fix; pinned tests | settled |+| FR3 | With no `scrollRef`, the root MUST be the scroll container and the dock MUST be `position: sticky`. | shipped implementation; pinned test | verify |+| FR4 | With a `scrollRef`, the root MUST NOT become a scroll container and the dock MUST be `position: fixed`. | shipped implementation; pinned test | verify |+| FR5 | `emptyState` MUST replace `children` exactly when `children` is `null`, `undefined`, `false`, or an empty array, and MUST NOT replace any other children. | shipped `hasVisibleContent`; pinned tests | verify |+| FR6 | `scrollButton` MUST distinguish three cases: omitted selects the wired default, `null` renders nothing, and a supplied node replaces the default. | shipped implementation; pinned tests | verify |+| FR7 | `density` MUST reflect on the root as the `chat-layout` target's `data-density`, and MUST select the dock, message-area, dock-inner, and blur-layer geometry together. | shipped implementation; pinned tests; family doc `visualProps` | verify |+| FR8 | The layout MUST publish its scroll container and message content refs through `ChatLayoutContext` so the message list can register the observed content box. | shipped implementation | verify |+| FR9 | Accepted `ref`, DOM/data/ARIA props, `className`, `style`, and `xstyle` MUST reach and compose on the layout root. | `architecture:public-component-api/INV5–INV6, INV8` | settled |++### Allowed variation++- **AV1 — Scroll ownership.** The caller chooses between root-owned and+ externally-owned scrolling; the dock's positioning strategy follows that choice.+- **AV2 — Scroll affordance.** The caller may keep the wired default, remove it,+ or substitute any node.+- **AV3 — Transcript content.** Any content is allowed in the message area;+ ChatMessageList is a convention, not a requirement.+- **AV4 — Density geometry.** Resolved spacing and widths follow the active+ theme's spacing scale; only the relationships between the three steps are fixed.++### Representative states++| State | Required invariant | Allowed variation |+| ----------------------------------- | --------------------------------------------------------------- | --------------------------------------------- |+| Self-scroll, short transcript | Root fills without overflowing; dock sticky at the block end | Empty state may occupy the message area |+| Self-scroll, overflowing transcript | Root scrolls; message area keeps content height | Scroll affordance becomes visible |+| External `scrollRef` | Root does not scroll; dock is fixed to the viewport's block end | The named element may be the document element |+| Empty children with `emptyState` | Centred empty state replaces the transcript | Any node may be the empty state |+| `scrollButton={null}` | No scroll affordance renders | Auto-scroll behavior is unchanged |++### Performance and resources++- **PR1 — No layout measurement in the component.** Density is a prop. ChatLayout+ MUST NOT add a `ResizeObserver`, media query, or animation frame of its own for+ presentation the CSS container/flex model already resolves+ (`architecture:component-style-authoring/INV2`).+- **PR2 — Shared observation only.** Content-size observation reaches the browser+ through the pooled `observeResize` utility used by `useChatNewMessages`, never a+ per-instance observer.++## Accessibility contract++- **AR1 — The wired default scroll affordance MUST NOT be focusable while it is+ visually hidden.** The hidden pill paints nothing, so focus landing on it would+ have no visible indicator (WCAG 2.2 SC 2.4.7, Level AA). `opacity` and+ `pointer-events` do not remove an element from sequential focus navigation.+- **AR2 — The scroll affordance MUST remain keyboard reachable and operable while+ visible**, with its accessible name supplied by the catalog and replaced by the+ new-messages label when new messages have arrived.+- **AR3 — All user-visible and AT-facing strings MUST come from the catalog**:+ `@astryx.chatLayout.newMessages` and+ `@astryx.chatLayoutScrollButton.scrollToBottom`.+- **AR4 — The layout MUST NOT assign a landmark role or accessible name to the+ caller's regions.** Region semantics stay caller-owned.+- The self-scroll root carries no `tabIndex`, role, or accessible name of its+ own; the keyboard path into scrolled content comes from whatever `children`+ supplies. Which layer should own that guarantee is unresolved; see OQ1.++## Design relationships++- The dock paints a `backdrop-filter` blur with a block-start mask so the+ transcript fades out behind the composer rather than ending at a hard edge.+ Blur height and mask distance step with `density`.+- The scroll affordance is a pill whose height tracks `--size-element-md`, the+ same token that sizes the `md` Button it wraps, so the pill's `overflow: hidden`+ cannot clip that Button under a theme that retunes the element scale+ (`architecture:theme-tokens/INV3`).+- Spacing, radius, shadow, duration, and easing all resolve from portable+ semantic tokens. Component-local geometry that has no semantic role — the+ message-column and dock-inner caps, the blur heights, and the empty-state+ minimum height — remains a named component design decision.+- The component declares no portable token and no public custom property.++### Theming reachability (observed)++Observed dispositions for ChatLayout's five anatomy parts. This record carries no+`anatomy-theming:v1` block; the block is optional during migration, and see OQ2.++| Anatomy part | Disposition |+| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Message area | `none` — reachability-gap: an internal element with no `themeProps` call. `chat-layout` sits on the scrolling root, so a theme cannot reach the transcript column's own padding or width cap. |+| Frosted glass dock | `none` — reachability-gap: the dock, its inner column, and the backdrop-filter blur layer paint the component's most distinctive surface and carry no target. |+| Scroll-to-bottom button | `delegatesTo` the `chat-layout-scroll-button` target, whose canonical owner in the current inventory is `component:Chat`. |+| Composer | `delegatesTo` the `chat-composer` target, whose canonical owner in the current inventory is `component:Chat`. |+| Empty state | `none` — reachability-gap: the empty-state box only centres caller content and carries no target. |++The `chat-layout` target itself is declared on the Chat family document+(`Chat.doc.mjs`) rather than on `ChatLayout.doc.mjs`.++## Family and system relationships++- There is no `family:chat` record. The Chat components share the `Chat.doc.mjs`+ family document and its theming target inventory, which is not a knowledge-record+ family contract.+- `component:ChatLayoutScrollButton` owns the scroll affordance's presentation,+ label, and focus behavior. ChatLayout owns only when it is visible.+- `component:ChatMessageList` consumes `ChatLayoutContext.contentRef`.+- `spec:AST-025` owns the shared effective-axis scroll capability. ChatLayout+ does not adopt it today: it declares `overflow-y: auto` unconditionally in+ self-scroll mode rather than resolving an effective axis, and it assigns no+ keyboard access to the viewport itself. FR12 accepts an existing focusable+ descendant as the keyboard path; see OQ1 for the open ownership question.++## Verification map++| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| -------- | -------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------- | --------------------- |+| FR1, FR2 | `ChatLayout.test.tsx` self-scroll layout contract | self-scroll, short and long transcript | Restoring `min-height: 100%` on the message area re-adds the dock's height and the root overflows | `audit:ChatLayout/§4` |+| FR3, FR4 | `ChatLayout.test.tsx` dock positioning | no `scrollRef`; external `scrollRef` | Swapping sticky and fixed detaches the dock from the element that actually scrolls | `audit:ChatLayout/§4` |+| FR5 | `ChatLayout.test.tsx` empty-state cases | empty array; populated children | Treating populated children as empty hides the transcript | `audit:ChatLayout/§4` |+| FR6 | `ChatLayout.test.tsx` scroll-button cases | default; custom node; `null` | Collapsing `null` into the default renders an affordance the caller removed | `audit:ChatLayout/§4` |+| FR7 | `ChatLayout.test.tsx` density cases; `themingTargets.test.ts` | compact; balanced; spacious | Dropping the reflected attribute makes the theming axis unselectable | `audit:ChatLayout/§2` |+| FR8 | `useChatNewMessages.test.tsx`, `useChatStreamScroll.test.tsx` | first fill; streaming growth | Losing the published refs stops auto-scroll from observing content growth | `audit:ChatLayout/§7` |+| AR1, AR2 | `ChatLayoutScrollButton.test.tsx` and `ChatLayout.test.tsx` tab-order cases; `ChatLayoutScrollButton.a11y.chromium.spec.ts` in real Chromium | hidden at rest; visible; re-hidden after activation | Reverting to `opacity`-only hiding puts an invisible control back in the tab order | `audit:ChatLayout/§1` |+| PR2 | Source review of `useChatNewMessages` | mounted list | A per-instance `ResizeObserver` replaces the pooled one | `audit:ChatLayout/§7` |++## Decision log++None. This record settles no decision; it describes shipped behavior.++## Open questions++- **OQ1 — Which layer owns the keyboard path to scrolled content, and should+ ChatLayout guarantee it?** (`human-api`) In self-scroll mode the root is the+ scroll container and carries no `tabIndex`, role, or accessible name of its+ own. `component:ChatMessageList`, the documented child, carries `role="log"`+ and `tabIndex={0}`, and `spec:AST-025/FR12` accepts such an existing+ focusable descendant instead of a named viewport. `children` is typed+ `ReactNode`, so whether a composition supplying no focusable descendant is+ also covered is unresolved, as is which layer should own the guarantee. This+ record states the arrangement and asserts no defect.+- **OQ2 — Should the frosted dock be themeable?** (`human-api`) The dock, its+ inner column, and the blur layer paint the component's signature surface, and+ no current target reaches them.++## Content boundary++This file does not duplicate `ChatLayout.doc.mjs` prop tables or examples, the+audit's scores and evidence, or the scroll, message, and composer contracts owned+by their own components and hooks.diff --git a/packages/core/src/Chat/ChatLayout.test.tsx b/packages/core/src/Chat/ChatLayout.test.tsxindex 6202bf7a3e..baa7325352 100644--- a/packages/core/src/Chat/ChatLayout.test.tsx+++ b/packages/core/src/Chat/ChatLayout.test.tsx@@ -2,6 +2,7 @@import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';import {act, render, screen} from '@testing-library/react';+import userEvent from '@testing-library/user-event';import {ChatLayout} from './ChatLayout';import {ChatMessageList} from './ChatMessageList';import {ChatMessage} from './ChatMessage';@@ -103,6 +104,33 @@ describe('ChatLayout', () => {});});+// ---------------------------------------------------------------------------+// Keyboard reachability of the default scroll-to-bottom button+//+// At rest the layout is neither scrolled up nor holding new messages, so the+// default ChatLayoutScrollButton renders in its hidden state. It is still in+// the DOM, and it is the first control in the dock — ahead of the composer.+// A control nobody can see must not be a tab stop: WCAG 2.2 SC 2.4.7 requires+// a visible focus indicator wherever focus can land, and the hidden pill paints+// nothing. `opacity: 0` and `pointer-events: none` do not remove an element+// from sequential focus navigation; only visibility/display/inert do.+// ---------------------------------------------------------------------------++describe('ChatLayout — default scroll button keyboard reachability', () => {+ it('does not make the resting scroll-to-bottom button the first tab stop', async () => {+ const user = userEvent.setup();+ render(+ <ChatLayout composer={<button type="button">Send</button>}>+ <div>msg</div>+ </ChatLayout>,+ );++ await user.tab();++ expect(screen.getByRole('button', {name: 'Send'})).toHaveFocus();+ });+});+// ---------------------------------------------------------------------------// Self-scroll layout contract (#2573)//diff --git a/packages/core/src/Chat/ChatLayout.tsx b/packages/core/src/Chat/ChatLayout.tsxindex d45a912992..295825a914 100644--- a/packages/core/src/Chat/ChatLayout.tsx+++ b/packages/core/src/Chat/ChatLayout.tsx@@ -268,6 +268,25 @@ function hasVisibleContent(children: ReactNode): boolean {// Component// =============================================================================+/**+ * Layout shell for a full chat interface: messages in page flow, composer+ * docked to the bottom behind a frosted glass layer, with auto-scroll and a+ * scroll-to-bottom button wired in.+ *+ * @example+ * ```+ * <ChatLayout+ * density="spacious"+ * composer={<ChatComposer onSubmit={send} />}+ * emptyState={<EmptyState title="No messages yet" />}>+ * <ChatMessageList>+ * <ChatMessage sender="assistant">+ * <ChatMessageBubble>How can I help?</ChatMessageBubble>+ * </ChatMessage>+ * </ChatMessageList>+ * </ChatLayout>+ * ```+ */export function ChatLayout({children,composer,diff --git a/packages/core/src/Chat/ChatLayoutScrollButton.test.tsx b/packages/core/src/Chat/ChatLayoutScrollButton.test.tsxindex e7031996da..edb9d77b57 100644--- a/packages/core/src/Chat/ChatLayoutScrollButton.test.tsx+++ b/packages/core/src/Chat/ChatLayoutScrollButton.test.tsx@@ -2,6 +2,7 @@import {describe, it, expect} from 'vitest';import {render, screen} from '@testing-library/react';+import userEvent from '@testing-library/user-event';import {ChatLayoutScrollButton} from './ChatLayoutScrollButton';describe('ChatLayoutScrollButton', () => {@@ -52,4 +53,34 @@ describe('ChatLayoutScrollButton', () => {expect(root).toHaveAttribute('data-custom', 'x');expect(root).toHaveAttribute('id', 'scroll-1');});++ // The hidden state paints nothing, so focus landing on it would have no+ // visible indicator (WCAG 2.2 SC 2.4.7). `opacity: 0` and+ // `pointer-events: none` suppress paint and the pointer but leave the button+ // in sequential focus navigation, so the hidden state must also stop being+ // focusable — without costing the visible state its keyboard access.+ it('is keyboard reachable while visible', async () => {+ const user = userEvent.setup();+ render(<ChatLayoutScrollButton isVisible onClick={() => {}} />);++ await user.tab();++ expect(+ screen.getByRole('button', {name: 'Scroll to bottom'}),+ ).toHaveFocus();+ });++ it('is not keyboard reachable while hidden', async () => {+ const user = userEvent.setup();+ render(+ <>+ <ChatLayoutScrollButton isVisible={false} onClick={() => {}} />+ <button type="button">After</button>+ </>,+ );++ await user.tab();++ expect(screen.getByRole('button', {name: 'After'})).toHaveFocus();+ });});diff --git a/packages/core/src/Chat/ChatLayoutScrollButton.tsx b/packages/core/src/Chat/ChatLayoutScrollButton.tsxindex c0112a6a37..72f2e2c4b0 100644--- a/packages/core/src/Chat/ChatLayoutScrollButton.tsx+++ b/packages/core/src/Chat/ChatLayoutScrollButton.tsx@@ -23,6 +23,7 @@ import {spacingVars,radiusVars,shadowVars,+ sizeVars,durationVars,easeVars,} from '../theme/tokens.stylex';@@ -67,8 +68,14 @@ const styles = stylex.create({borderRadius: radiusVars['--radius-full'],backgroundColor: colorVars['--color-background-popover'],boxShadow: shadowVars['--shadow-med'],- height: '32px',- transitionProperty: 'opacity, transform, max-width',+ // The pill clips its own content, so it must track the height of the+ // md Button it wraps. A literal would clip that Button under any theme+ // that retunes the element scale.+ height: sizeVars['--size-element-md'],+ // `visibility` rides the same transition so the fade-out still plays:+ // it flips to `visible` immediately on the way in and only at the end+ // of the duration on the way out.+ transitionProperty: 'opacity, transform, max-width, visibility',transitionTimingFunction: easeVars['--ease-standard'],transitionDuration: {default: durationVars['--duration-fast-max'],@@ -78,14 +85,19 @@ const styles = stylex.create({hidden: {opacity: 0,pointerEvents: 'none',- maxWidth: '32px',+ // The hidden pill paints nothing, so focus landing on it would have no+ // visible indicator (WCAG 2.2 SC 2.4.7). `opacity` and `pointer-events`+ // leave the button in sequential focus navigation; `visibility` removes it.+ visibility: 'hidden',+ maxWidth: sizeVars['--size-element-md'],},visible: {opacity: 1,pointerEvents: 'auto',+ visibility: 'visible',},collapsed: {- maxWidth: '32px',+ maxWidth: sizeVars['--size-element-md'],},expanded: {maxWidth: '200px',diff --git a/packages/core/src/Chat/__tests__/ChatLayoutScrollButton.a11y.chromium.spec.ts b/packages/core/src/Chat/__tests__/ChatLayoutScrollButton.a11y.chromium.spec.tsnew file mode 100644index 0000000000..d161d81e5d--- /dev/null+++ b/packages/core/src/Chat/__tests__/ChatLayoutScrollButton.a11y.chromium.spec.ts@@ -0,0 +1,510 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ChatLayoutScrollButton.a11y.chromium.spec.ts+ * @input Uses the ChatLayout scroll-affordance story and a built Storybook+ * @output Keyboard and pixel evidence for the hidden/visible/re-hidden scroll+ * affordance, and for the pill tracking the theme's element-size token+ * @position Real-Chromium evidence for the 2026-09-23 ChatLayout audit. jsdom+ * has no cascade and no sequential focus model, so neither the hidden state's+ * removal from the tab order nor the pill's containment of its own Button is+ * observable in the unit lane.+ *+ * Two claims are proven here, both against the shipped public API:+ *+ * 1. The default affordance is hidden at rest, becomes visible when the reader+ * scrolls away from the newest message, and hides again on activation. It is+ * keyboard reachable exactly while it is visible, because focus landing on+ * something that paints nothing has no visible indicator (WCAG 2.2 SC 2.4.7).+ * 2. The pill's height follows `--size-element-md`, so a theme that retunes the+ * element scale cannot make it clip the Button it wraps. Butter resolves that+ * token to 40px where Neutral resolves it to 32px, so the two shipped themes+ * are the natural before/after — no hand-built arm is needed for the token+ * claim. The regression arm below restores the old literal to show what the+ * fix prevents, and declares its exact delta.+ */++import {createHash} from 'node:crypto';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {expect, test, type Locator, 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('test-results/chat-layout-audit-evidence');+const STORY_ID = 'core-chatlayout--scroll-affordance-states';++/** The pill wrapper: the element whose visibility and height are the claims. */+const PILL = '.astryx-chat-layout-scroll-button > div';++/** One observed tab stop, identified structurally rather than by its text. */+type FocusStop = {+ tag: string;+ astryxClass: string | null;+ role: string | null;+ tabIndex: string | null;+ accessibleName: string | null;+ isLayoutRoot: boolean;+};++type Shot = {+ file: string;+ sha256: string;+ width: number;+ height: number;+};++type Receipt = {+ /** What this frame is evidence of. */+ state: string;+ storyId: string;+ theme: string;+ colorMode: string;+ direction: string;+ viewport: {width: number; height: number};+ devicePixelRatio: number;+ /** Semantic state that uniquely identifies the intended render. */+ rendered: Record<string, unknown>;+ /** Visible subject geometry, so a zero-box decoy cannot pass as the subject. */+ geometry: {selectorCount: number; width: number; height: number};+ settled: {fontsReady: boolean; pageErrors: number};+ image: Shot;+};++const receipts: Receipt[] = [];+const pageErrors: string[] = [];+let storybook: StaticServer;+let browserVersion = 'unknown';++test.beforeAll(async () => {+ // Do NOT wipe: Playwright restarts the worker after a failing test, which+ // re-runs this hook. Wiping here would delete the frames the earlier tests+ // already banked, which is exactly when the evidence matters most.+ fs.mkdirSync(OUTPUT, {recursive: true});+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => {+ const manifestPath = path.join(OUTPUT, 'manifest.json');+ const previous = fs.existsSync(manifestPath)+ ? (JSON.parse(fs.readFileSync(manifestPath, 'utf8')).frames ?? [])+ : [];+ const merged = [...previous, ...receipts].filter(+ (frame, index, all) =>+ all.findIndex(other => other.state === frame.state) === index,+ );+ fs.writeFileSync(+ manifestPath,+ `${JSON.stringify(+ {+ version: 1,+ component: 'core/ChatLayout',+ headSha:+ process.env.ASTRYX_HEAD_SHA ??+ process.env.GITHUB_SHA ??+ 'local-working-copy',+ checkoutSha: process.env.GITHUB_SHA ?? 'local-working-copy',+ browser: browserVersion,+ frames: merged,+ },+ null,+ 2,+ )}\n`,+ );+ await storybook?.close();+});++async function openStory(+ page: Page,+ {theme = 'neutral', colorMode = 'light'} = {},+): Promise<Locator> {+ page.on('pageerror', error => pageErrors.push(String(error)));+ browserVersion = page.context().browser()?.version() ?? 'unknown';+ await page.goto(+ `${storybook.origin}/iframe.html?id=${STORY_ID}&viewMode=story` ++ `&globals=colorMode:${colorMode};astryxTheme:${theme}`,+ );+ const root = page.locator('.astryx-chat-layout');+ await root.waitFor({state: 'visible'});+ await holdMotionStill(page);+ await page.evaluate(async () => document.fonts.ready);+ return root;+}++/** The scroll container settles at the bottom on first fill. */+async function distanceFromBottom(root: Locator): Promise<number> {+ return root.evaluate(+ element => element.scrollHeight - element.clientHeight - element.scrollTop,+ );+}++/** How far this fixture can scroll at all. The states below need real range. */+async function scrollRange(root: Locator): Promise<number> {+ return root.evaluate(element => element.scrollHeight - element.clientHeight);+}++/** Scroll to the top, which is the furthest the reader can get from newest. */+async function scrollToTop(root: Locator): Promise<void> {+ await root.evaluate(element => {+ element.scrollTop = 0;+ element.dispatchEvent(new Event('scroll'));+ });+}++/** Computed visibility of the pill — the state every claim below turns on. */+async function pillVisibility(page: Page): Promise<string> {+ return page+ .locator(PILL)+ .evaluate(element => getComputedStyle(element).visibility);+}++/**+ * Can the affordance take focus at all? This is the mechanism under test:+ * `visibility: hidden` removes an element from sequential focus navigation AND+ * refuses programmatic focus, which `opacity: 0` does neither of. A CSS locator+ * is used rather than a role query because a hidden button is not in the+ * accessibility tree and a role query would not resolve it.+ */+async function affordanceAcceptsFocus(page: Page): Promise<boolean> {+ return page+ .locator('.astryx-chat-layout-scroll-button button')+ .evaluate(element => {+ // preventScroll: focusing must not move the scroll position, or the+ // probe would change the very state the next assertion reads.+ (element as HTMLElement).focus({preventScroll: true});+ return document.activeElement === element;+ });+}++/**+ * Tab forward from `from` and report where focus actually lands, by identity.+ *+ * Each stop records the element's tag, its `astryx-*` class, explicit role,+ * explicit tabindex, accessible name, and whether it IS the layout root — not+ * a text-content guess. Several nested elements share the transcript's text,+ * so a label built from `textContent` cannot tell the scrolling layout root+ * from the `role="log"` message list inside it.+ *+ * The sweep MUST stop at the layout boundary. Sequential focus navigation+ * scrolls each stop into view, and this affordance's visibility is a function+ * of scroll position, so a sweep that runs past the last stop wraps around the+ * document, re-enters the layout, and can flip the state it is measuring.+ */+/** Render a sweep as a readable trail for a failure message. */+function describeStops(stops: FocusStop[]): string {+ return stops+ .map(stop => {+ const parts = [stop.tag];+ if (stop.astryxClass != null) {+ parts.push(`.${stop.astryxClass}`);+ }+ if (stop.role != null) {+ parts.push(`[role=${stop.role}]`);+ }+ if (stop.isLayoutRoot) {+ parts.push('(layout root)');+ }+ return parts.join('');+ })+ .join(' -> ');+}++async function tabWithinLayout(+ page: Page,+ from: Locator,+ maxPresses: number,+): Promise<{reached: boolean; sequence: FocusStop[]}> {+ await from.focus();+ const sequence: FocusStop[] = [];+ for (let index = 0; index < maxPresses; index += 1) {+ await page.keyboard.press('Tab');+ const stop = await page.evaluate(() => {+ const active = document.activeElement as HTMLElement | null;+ const layout = document.querySelector('.astryx-chat-layout');+ if (active == null || active === document.body) {+ return {+ tag: 'body',+ astryxClass: null,+ role: null,+ tabIndex: null,+ accessibleName: null,+ isLayoutRoot: false,+ inside: false,+ onAffordance: false,+ };+ }+ return {+ tag: active.tagName.toLowerCase(),+ astryxClass:+ [...active.classList].find(name => name.startsWith('astryx-')) ??+ null,+ role: active.getAttribute('role'),+ tabIndex: active.getAttribute('tabindex'),+ accessibleName:+ active.getAttribute('aria-label') ??+ active.getAttribute('aria-labelledby') ??+ null,+ isLayoutRoot: active === layout,+ inside: layout != null && layout.contains(active),+ onAffordance:+ active.closest('.astryx-chat-layout-scroll-button') != null,+ };+ });+ const {inside, onAffordance, ...identity} = stop;+ sequence.push(identity);+ if (onAffordance) {+ return {reached: true, sequence};+ }+ if (!inside) {+ break;+ }+ }+ return {reached: false, sequence};+}++/**+ * Read a PNG's real pixel dimensions out of its IHDR header.+ *+ * These frames are ELEMENT screenshots, so their size is the subject's box,+ * not the viewport's. An earlier revision recorded the viewport here and+ * published receipts claiming 1280x720 for images that are 1216x420 — the+ * pixels were genuine, the stated dimensions were not. The viewport stays in+ * its own sensor row, where it belongs.+ */+function pngShot(file: string, bytes: Buffer): Shot {+ return {+ file,+ sha256: createHash('sha256').update(bytes).digest('hex'),+ width: bytes.readUInt32BE(16),+ height: bytes.readUInt32BE(20),+ };+}++async function capture(+ page: Page,+ state: string,+ rendered: Record<string, unknown>,+) {+ const pill = page.locator(PILL);+ const box = await pill.boundingBox();+ if (box == null) {+ throw new Error(`${state}: the pill has no layout box`);+ }+ const bytes = await page.locator('.astryx-chat-layout').screenshot({+ animations: 'disabled',+ });+ const file = `chat-layout-${state}.png`;+ fs.writeFileSync(path.join(OUTPUT, file), bytes);+ const dimensions = await page.evaluate(() => ({+ width: window.innerWidth,+ height: window.innerHeight,+ dpr: window.devicePixelRatio,+ }));+ const receipt: Receipt = {+ state,+ storyId: STORY_ID,+ theme: await page.evaluate(+ () =>+ document+ .querySelector('[data-astryx-theme]')+ ?.getAttribute('data-astryx-theme') ?? 'neutral',+ ),+ colorMode: await page.evaluate(+ () => getComputedStyle(document.documentElement).colorScheme,+ ),+ direction: await page+ .locator('.astryx-chat-layout')+ .evaluate(element => getComputedStyle(element).direction),+ viewport: {width: dimensions.width, height: dimensions.height},+ devicePixelRatio: dimensions.dpr,+ rendered,+ geometry: {+ selectorCount: await page.locator(PILL).count(),+ width: Math.round(box.width),+ height: Math.round(box.height),+ },+ settled: {fontsReady: true, pageErrors: pageErrors.length},+ image: pngShot(file, bytes),+ };+ receipts.push(receipt);+ return receipt;+}++test('the scroll affordance is keyboard reachable exactly while it is visible', async ({+ page,+}) => {+ const root = await openStory(page);+ const before = page.getByRole('button', {name: 'Before chat', exact: true});+ const pill = page.locator(PILL);+ const SWEEP = 6;++ // Order matters in every block below: assert the state, probe focus with+ // preventScroll, capture the frame, and only THEN walk Tab. Sequential focus+ // navigation scrolls each stop into view, and this affordance's visibility is+ // a function of scroll position — measured, not assumed: an earlier revision+ // swept first and photographed a "hidden" state that Tab had already scrolled+ // 174px away from the bottom and made visible. The sweep is recorded as+ // evidence of the real tab order; the assertion is the focus probe, because a+ // button that refuses focus() is not in the sequential tab order.++ // ---- hidden: the resting state, where the defect lived -------------------+ // Precondition: the fixture must actually overflow, or "hidden at rest" and+ // "visible when scrolled up" would both pass without proving anything.+ expect(+ await scrollRange(root),+ 'the fixture must overflow by more than the 100px button threshold',+ ).toBeGreaterThan(150);+ expect(await distanceFromBottom(root)).toBeLessThan(2);+ await expect(pill).toHaveCSS('visibility', 'hidden');+ expect(+ await affordanceAcceptsFocus(page),+ 'a control that paints nothing must refuse focus (WCAG 2.2 SC 2.4.7)',+ ).toBe(false);+ const restFrame = await capture(page, 'rest-hidden', {+ pillVisibility: await pillVisibility(page),+ affordanceAcceptsFocus: false,+ distanceFromBottomPx: await distanceFromBottom(root),+ });+ restFrame.rendered.tabOrderObserved = (+ await tabWithinLayout(page, before, SWEEP)+ ).sequence;++ // ---- visible: the reader scrolls away from the newest message ------------+ await scrollToTop(root);+ await expect(pill).toHaveCSS('visibility', 'visible');+ expect(await distanceFromBottom(root)).toBeGreaterThan(100);+ expect(+ await affordanceAcceptsFocus(page),+ 'the visible affordance must keep its keyboard access',+ ).toBe(true);+ await expect(+ page.getByRole('button', {name: 'Scroll to bottom'}),+ ).toHaveAccessibleName('Scroll to bottom');+ const visibleFrame = await capture(page, 'scrolled-up-visible', {+ pillVisibility: await pillVisibility(page),+ affordanceAcceptsFocus: true,+ accessibleName: 'Scroll to bottom',+ distanceFromBottomPx: await distanceFromBottom(root),+ });+ const visibleSweep = await tabWithinLayout(page, before, SWEEP);+ visibleFrame.rendered.tabOrderObserved = visibleSweep.sequence;+ visibleFrame.rendered.reachedByTabAfterPresses = visibleSweep.sequence.length;+ expect(+ visibleSweep.reached,+ `Tab never reached the visible affordance: ${describeStops(visibleSweep.sequence)}`,+ ).toBe(true);++ // ---- re-hidden: activating it returns to the bottom ----------------------+ // The sweep above left focus on the affordance, so Enter activates it. Wait+ // for the scroll spring to SETTLE at the bottom rather than merely for the+ // pill to hide: hiding happens at the 100px threshold, while the animation+ // is still running, and anything that nudges the scroller in that window+ // flips the affordance back.+ await page.keyboard.press('Enter');+ await expect+ .poll(async () => distanceFromBottom(root), {timeout: 5000})+ .toBeLessThan(2);+ await expect(pill).toHaveCSS('visibility', 'hidden');+ expect(+ await affordanceAcceptsFocus(page),+ 'after returning to the bottom the affordance must refuse focus again',+ ).toBe(false);+ const returnedFrame = await capture(page, 'returned-hidden', {+ pillVisibility: await pillVisibility(page),+ affordanceAcceptsFocus: false,+ activatedWith: 'Enter',+ distanceFromBottomPx: await distanceFromBottom(root),+ });+ returnedFrame.rendered.tabOrderObserved = (+ await tabWithinLayout(page, before, SWEEP)+ ).sequence;++ expect(pageErrors).toEqual([]);+});++test('the pill tracks the theme element-size token instead of a fixed 32px', async ({+ page,+}) => {+ // Butter resolves --size-element-md to 40px; Neutral resolves it to 32px.+ // Both are shipped themes, so this is a real theme pair, not a mutated arm.+ const sizes: Record<string, {token: string; pill: number; button: number}> =+ {};++ for (const theme of ['neutral', 'butter']) {+ const root = await openStory(page, {theme});+ await scrollToTop(root);+ const pill = page.locator(PILL);+ await expect(pill).toHaveCSS('visibility', 'visible');++ const token = await pill.evaluate(element =>+ getComputedStyle(element).getPropertyValue('--size-element-md').trim(),+ );+ const pillHeight = (await pill.boundingBox())?.height ?? 0;+ const buttonHeight =+ (await page.getByRole('button', {name: 'Scroll to bottom'}).boundingBox())+ ?.height ?? 0;++ sizes[theme] = {+ token,+ pill: Math.round(pillHeight),+ button: Math.round(buttonHeight),+ };++ // The pill clips its own content (`overflow: hidden`), so it must be at+ // least as tall as the Button it wraps in every theme. Neutral also shrinks+ // its md Button to `calc(--size-element-md - 8px)`, so the two are equal+ // only where a theme leaves the Button at the full token height.+ expect(+ sizes[theme].pill,+ `${theme}: the pill must not be shorter than the Button it clips`,+ ).toBeGreaterThanOrEqual(sizes[theme].button);+ await capture(page, `token-size-${theme}`, {+ theme,+ sizeElementMd: token,+ pillHeightPx: sizes[theme].pill,+ buttonHeightPx: sizes[theme].button,+ clippedPx: Math.max(0, sizes[theme].button - sizes[theme].pill),+ });+ }++ // The themes must actually disagree, or the pair proves nothing. Butter+ // resolves the token to 40px and leaves its md Button at the full token+ // height; Neutral resolves it to 32px and shrinks the Button by 8px.+ expect(sizes.butter.token).not.toBe(sizes.neutral.token);+ expect(sizes.butter.pill).toBeGreaterThan(sizes.neutral.pill);+ expect(sizes.butter.button).toBeGreaterThan(sizes.neutral.button);++ // ---- regression arm -----------------------------------------------------+ // ARM: pre-fix literal+ // BASE: this head+ // DELTA: one injected rule restoring the removed literal on the pill —+ // `height: 32px; max-width: 32px` — and nothing else.+ // UNRELATED DELTA: none+ const root = await openStory(page, {theme: 'butter'});+ await scrollToTop(root);+ await page.addStyleTag({+ content: `${PILL} { height: 32px !important; max-width: 32px !important; }`,+ });+ const clippedPill = (await page.locator(PILL).boundingBox())?.height ?? 0;+ const clippedButton =+ (await page.getByRole('button', {name: 'Scroll to bottom'}).boundingBox())+ ?.height ?? 0;+ await capture(page, 'token-size-butter-prefix-literal', {+ theme: 'butter',+ arm: 'pre-fix literal (height: 32px; max-width: 32px)',+ pillHeightPx: Math.round(clippedPill),+ buttonHeightPx: Math.round(clippedButton),+ clippedPx: Math.round(clippedButton - clippedPill),+ });++ // What the fix prevents: under Butter the old literal left the Button taller+ // than the pill that clips it.+ expect(Math.round(clippedButton)).toBeGreaterThan(Math.round(clippedPill));+ expect(pageErrors).toEqual([]);+});