An open source design system that's fully customizable and agent ready
TypeScript
fix(ChatLayout): the newest message rests above a fixed dock (#10676)
Christopher Chedeau1b06024bead1
diff --git a/.changeset/chat-layout-fixed-dock-room.md b/.changeset/chat-layout-fixed-dock-room.mdnew file mode 100644index 0000000000..0177c62dfb--- /dev/null+++ b/.changeset/chat-layout-fixed-dock-room.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] ChatLayout with a `scrollRef` now rests the newest message above the fixed composer dock at the scroll's end. The message area's end padding holds the dock's height and follows it as the composer grows.+@vjeuxdiff --git a/docs/specs/components/Chat/ChatLayout.spec.md b/docs/specs/components/Chat/ChatLayout.spec.mdindex 2b49e26036..6e5aeb02a7 100644--- a/docs/specs/components/Chat/ChatLayout.spec.md+++ b/docs/specs/components/Chat/ChatLayout.spec.md@@ -122,17 +122,17 @@ has a safe theme-independent baseline, so it stays closed under## Behavioral and layout contract-| ID | Invariant | Basis |-| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |-| 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. | Current source and tests |-| 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. | Current source and tests |-| FR3 | With no `scrollRef`, the root MUST be the scroll container and the dock MUST be `position: sticky`. | Current source and tests |-| FR4 | With a `scrollRef`, the root MUST NOT become a scroll container and the dock MUST be `position: fixed`. | Current source and tests |-| FR5 | `emptyState` MUST replace `children` exactly when `children` is `null`, `undefined`, `false`, or an empty array, and MUST NOT replace any other children. | Current source and tests |-| FR6 | `scrollButton` MUST distinguish three cases: omitted selects the wired default, `null` renders nothing, and a supplied node replaces the default. | Current source and tests |-| 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. | Current source, tests, and docs |-| FR8 | The layout MUST publish its scroll container and message content refs through `ChatLayoutContext` so the message list can register the observed content box. | Current source |-| 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` |+| ID | Invariant | Basis |+| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |+| 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. | Current source and tests |+| 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. | Current source and tests |+| FR3 | With no `scrollRef`, the root MUST be the scroll container and the dock MUST be `position: sticky`. | Current source and tests |+| FR4 | With a `scrollRef`, the root MUST NOT become a scroll container and the dock MUST be `position: fixed`. The message area's end padding MUST hold the dock's height, so the newest message rests above the dock at the scroll's end. | Current source and tests |+| FR5 | `emptyState` MUST replace `children` exactly when `children` is `null`, `undefined`, `false`, or an empty array, and MUST NOT replace any other children. | Current source and tests |+| FR6 | `scrollButton` MUST distinguish three cases: omitted selects the wired default, `null` renders nothing, and a supplied node replaces the default. | Current source and tests |+| 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. | Current source, tests, and docs |+| FR8 | The layout MUST publish its scroll container and message content refs through `ChatLayoutContext` so the message list can register the observed content box. | Current source |+| 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` |### Allowed variation@@ -147,20 +147,23 @@ has a safe theme-independent baseline, so it stays closed under### 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 |+| 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 newest message rests above it at the scroll's 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. ChatLayoutMUST NOT add a `ResizeObserver`, media query, or animation frame of its own forpresentation the CSS container/flex model already resolves- (`architecture:component-style-authoring/INV2`).+ (`architecture:component-style-authoring/INV2`). A fixed dock is out of+ flow, so flex layout cannot reserve its height. That height reaches the+ message area through PR2's pooled observer. Its first call carries no size,+ so the mount reads the dock's height once.- **PR2 — Shared observation only.** Content-size observation reaches the browserthrough the pooled `observeResize` utility used by `useChatNewMessages`, never aper-instance observer.@@ -230,15 +233,15 @@ The `chat-layout` target itself is declared on the Chat family document## 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; `useChatNewMessages.test.tsx` conditional list case | empty array; populated children | Treating populated children as empty hides the transcript | `audit:ChatLayout/§4` |-| FR6 | `ChatLayout.test.tsx` scroll-button cases | custom node | Rendering the default in place of a supplied node fails | `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 | `ChatLayout.test.tsx` "first-fill scroll positioning" cases; `useChatNewMessages.test.tsx` conditional-list case | 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` |+| 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 and the room for a fixed dock | no `scrollRef`; external `scrollRef`; a growing composer | Swapping sticky and fixed detaches the dock from the element that actually scrolls; dropping the room leaves the newest message under the fixed dock | `audit:ChatLayout/§4` |+| FR5 | `ChatLayout.test.tsx` empty-state cases; `useChatNewMessages.test.tsx` conditional list case | empty array; populated children | Treating populated children as empty hides the transcript | `audit:ChatLayout/§4` |+| FR6 | `ChatLayout.test.tsx` scroll-button cases | custom node | Rendering the default in place of a supplied node fails | `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 | `ChatLayout.test.tsx` "first-fill scroll positioning" cases; `useChatNewMessages.test.tsx` conditional-list case | 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` |Read from source, with no focused test yet:diff --git a/packages/core/src/Chat/ChatLayout.test.tsx b/packages/core/src/Chat/ChatLayout.test.tsxindex baa7325352..a6433f510f 100644--- a/packages/core/src/Chat/ChatLayout.test.tsx+++ b/packages/core/src/Chat/ChatLayout.test.tsx@@ -186,8 +186,61 @@ describe('ChatLayout — self-scroll layout contract (#2573)', () => {);expect(dock).toHaveStyle({position: 'fixed'});});++ it('makes room at the message area\u2019s end for a fixed dock\u2019s height, so the newest message rests above it', () => {+ const rect = stubDockHeight(142);+ const scrollRef = {current: document.documentElement};+ render(+ <ChatLayout+ composer={<div>composer</div>}+ data-testid="layout"+ scrollRef={scrollRef}>+ <div>msg</div>+ </ChatLayout>,+ );+ const messageArea = screen.getByTestId('layout')+ .firstElementChild as HTMLElement;+ expect(endRoom(messageArea)).toBe(142);+ rect.mockRestore();+ });++ it('adds no room for the dock in self-scroll mode, where the sticky dock is in flow', () => {+ const rect = stubDockHeight(142);+ render(+ <ChatLayout composer={<div>composer</div>} data-testid="layout">+ <div>msg</div>+ </ChatLayout>,+ );+ const messageArea = screen.getByTestId('layout')+ .firstElementChild as HTMLElement;+ expect(endRoom(messageArea)).toBe(0);+ rect.mockRestore();+ });});+// The dock: the layout root's last child. jsdom has no layout, so its height+// is stubbed; every other element measures 0.+function stubDockHeight(height: number) {+ return vi+ .spyOn(HTMLElement.prototype, 'getBoundingClientRect')+ .mockImplementation(function (this: HTMLElement) {+ const parent = this.parentElement;+ const isDock =+ parent?.getAttribute('data-testid') === 'layout' &&+ parent.lastElementChild === this;+ return new DOMRect(0, 0, 390, isDock ? height : 0);+ });+}++// The room the message area's end padding adds to the density's own padding,+// CSS px: the `+ Npx` of its functional style.+function endRoom(element: HTMLElement): number {+ const match = /--[\w-]+:\s*calc\([^;]*\+\s*(-?[\d.]+)px\)/.exec(+ element.getAttribute('style') ?? '',+ );+ return match == null ? 0 : Number(match[1]);+}+// ---------------------------------------------------------------------------// First-fill scroll positioning//@@ -244,6 +297,37 @@ describe('ChatLayout — first-fill scroll positioning', () => {vi.unstubAllGlobals();});+ it('follows a fixed dock that grows, as a composer does with a second line', () => {+ const rect = stubDockHeight(142);+ const scrollRef = {current: document.documentElement};+ render(+ <ChatLayout+ composer={<div>composer</div>}+ data-testid="layout"+ scrollRef={scrollRef}>+ <div>msg</div>+ </ChatLayout>,+ );+ const layout = screen.getByTestId('layout');+ const messageArea = layout.firstElementChild as HTMLElement;+ const dock = layout.lastElementChild as HTMLElement;+ expect(endRoom(messageArea)).toBe(142);+ const observation = activeObservations.find(o => o.element === dock);+ act(() => {+ observation?.callback(+ [+ {+ target: dock,+ borderBoxSize: [{blockSize: 166, inlineSize: 390}],+ } as unknown as ResizeObserverEntry,+ ],+ {} as ResizeObserver,+ );+ });+ expect(endRoom(messageArea)).toBe(166);+ rect.mockRestore();+ });+function setGeometry(el: HTMLElement, scrollHeight: number) {Object.defineProperty(el, 'scrollHeight', {value: scrollHeight,diff --git a/packages/core/src/Chat/ChatLayout.tsx b/packages/core/src/Chat/ChatLayout.tsxindex 4469396c2a..b2c2b3255e 100644--- a/packages/core/src/Chat/ChatLayout.tsx+++ b/packages/core/src/Chat/ChatLayout.tsx@@ -5,7 +5,7 @@/*** @file ChatLayout.tsx* @input Uses React, StyleX, theme tokens, useChatStreamScroll, useChatNewMessages,- * useChatKeyboard+ * useChatKeyboard, the pooled resize observer* @output Exports ChatLayout component and ChatLayoutProps* @position Layout shell for full chat interfaces — messages in page flow, composer fixed to bottom*@@ -19,6 +19,9 @@* exactly 100% with no overflow, and long content grows past the root so* self-scroll mode scrolls (#2573). In external-scrollRef mode the dock* is position: fixed (out of flow) and the message area fills the root.+ * There the message area's end padding also holds the dock's height, which+ * the pooled resize observer reports. So the newest message rests above the+ * dock at the scroll's end, as it does in self-scroll mode.** Software keyboard (useChatKeyboard): the dock rests above the keyboard.* The message area's end padding lets the newest message scroll above it.@@ -35,7 +38,7 @@* - /packages/cli/assets/templates/blocks/components/ChatLayout/ (block examples)*/-import {type ReactNode, useMemo, useRef} from 'react';+import {type ReactNode, useCallback, useMemo, useRef, useState} from 'react';import * as stylex from '@stylexjs/stylex';import {focusVars, spacingVars} from '../theme/tokens.stylex';import {focusOutlineStyles} from '../utils/focusOutline.stylex';@@ -50,6 +53,7 @@ import {KeyboardSurfaceContext} from './keyboardSurface';import {themeProps} from '../utils/themeProps';import {useMergedRefs} from '../hooks/useMergedRefs';+import {observeResize} from '../utils/sharedResizeObserver';import {registerEnglishFallback,useComponentTranslator,@@ -151,11 +155,11 @@ const styles = stylex.create({paddingInline: 0,},- // The end padding grows by the part of the keyboard over the dock. So the- // newest message can scroll above the lifted composer, with no element- // added for it.- messageAreaKeyboard: (lift: number) => ({- paddingBlockEnd: `calc(${spacingVars['--spacing-6']} + ${lift}px)`,+ // The end padding grows by the part of the keyboard over the dock and, for+ // a fixed dock, by the dock's height. So the newest message can scroll+ // above the composer, with no element added for it.+ messageAreaEndRoom: (room: number) => ({+ paddingBlockEnd: `calc(${spacingVars['--spacing-6']} + ${room}px)`,}),emptyState: {@@ -353,6 +357,32 @@ export function ChatLayout({scrollToBottom: scroll.scrollToBottom,});+ // --- Fixed dock's height ---+ // A fixed dock is out of flow, so the message area makes room for it. The+ // room is the dock's border-box height, as the pooled observer reports it.+ // The padding changes only the message area, so it never resizes the dock.+ // React calls the returned unsubscribe when the dock detaches or the+ // scroll mode changes.+ const [dockHeight, setDockHeight] = useState(0);+ const observeDock = useCallback(+ (dock: HTMLDivElement | null) => {+ if (dock == null || isSelfScrolling) {+ return undefined;+ }+ return observeResize(dock, entry => {+ // The pooled observer's first call carries no size. The mount reads+ // the dock once, so the first paint has the room.+ const height =+ entry.borderBoxSize?.[0]?.blockSize ??+ dock.getBoundingClientRect().height;+ setDockHeight(Math.round(height));+ });+ },+ [isSelfScrolling],+ );+ const dockRef = useMergedRefs(keyboard.dockRef, observeDock);+ const endRoom = keyboard.lift + (isSelfScrolling ? 0 : dockHeight);+const defaultScrollButton = (<ChatLayoutScrollButtonisVisible={scroll.isScrolledUp || newMsgs.hasNewMessages}@@ -420,7 +450,7 @@ export function ChatLayout({{...stylex.props(styles.messageArea,currentDensity.messageArea,- keyboard.lift > 0 && styles.messageAreaKeyboard(keyboard.lift),+ endRoom > 0 && styles.messageAreaEndRoom(endRoom),)}>{showEmpty && emptyState ? (<div {...stylex.props(styles.emptyState)}>{emptyState}</div>@@ -431,7 +461,7 @@ export function ChatLayout({{/* Dock container — sticky/fixed, holds blur + scroll button + composer */}<div- ref={keyboard.dockRef}+ ref={dockRef}{...stylex.props(styles.dockContainer,isSelfScrolling