An open source design system that's fully customizable and agent ready
TypeScript
fix(ChatLayout): the scroll button follows a page that scrolls (#10779)
Christopher Chedeaud49271d818f4
diff --git a/.changeset/chat-layout-document-scroll-button.md b/.changeset/chat-layout-document-scroll-button.mdnew file mode 100644index 0000000000..e23d71b345--- /dev/null+++ b/.changeset/chat-layout-document-scroll-button.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] ChatLayout's scroll-to-bottom button now appears when `scrollRef` names the document's scroller and the reader scrolls the page up. The stream scroll also stops following there, so a streaming reply no longer pulls that reader back to the newest message.+@vjeuxdiff --git a/packages/core/src/Chat/ChatLayout.test.tsx b/packages/core/src/Chat/ChatLayout.test.tsxindex a6433f510f..d7f90cfe25 100644--- a/packages/core/src/Chat/ChatLayout.test.tsx+++ b/packages/core/src/Chat/ChatLayout.test.tsx@@ -142,6 +142,54 @@ describe('ChatLayout — default scroll button keyboard reachability', () => {// geometry was verified in a browser; see the PR for measurements.// ---------------------------------------------------------------------------+describe('ChatLayout — a page that scrolls the document', () => {+ // The page's root element scrolls, and the browser raises the scroll at the+ // document. The root's offsetHeight is the page's height; its clientHeight+ // is the viewport's.+ const root = document.documentElement;+ const geometry = {scrollHeight: 3000, clientHeight: 700, offsetHeight: 3000};++ beforeEach(() => {+ vi.stubGlobal('requestAnimationFrame', () => 0);+ vi.stubGlobal('cancelAnimationFrame', () => {});+ for (const [property, value] of Object.entries(geometry)) {+ Object.defineProperty(root, property, {value, configurable: true});+ }+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ for (const property of Object.keys(geometry)) {+ Reflect.deleteProperty(root, property);+ }+ root.scrollTop = 0;+ });++ function scrollPageTo(top: number) {+ root.scrollTop = top;+ act(() => {+ document.dispatchEvent(new Event('scroll'));+ });+ }++ it('shows the scroll-to-bottom button when the reader scrolls the page up from its end', () => {+ const scrollRef = {current: root};+ render(+ <ChatLayout composer={<div>composer</div>} scrollRef={scrollRef}>+ <div>msg</div>+ </ChatLayout>,+ );+ const hiddenPill = () =>+ screen.getByLabelText('Scroll to bottom').closest('[inert]');++ scrollPageTo(2300);+ expect(hiddenPill()).not.toBeNull();++ scrollPageTo(2000);+ expect(hiddenPill()).toBeNull();+ });+});+describe('ChatLayout — self-scroll layout contract (#2573)', () => {it('root is a flex column so the dock height is part of the 100%', () => {render(diff --git a/packages/core/src/Chat/__tests__/useChatStreamScrollPage.a11y.browser.spec.ts b/packages/core/src/Chat/__tests__/useChatStreamScrollPage.a11y.browser.spec.tsnew file mode 100644index 0000000000..cfcb6247df--- /dev/null+++ b/packages/core/src/Chat/__tests__/useChatStreamScrollPage.a11y.browser.spec.ts@@ -0,0 +1,156 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useChatStreamScrollPage.a11y.browser.spec.ts+ * @input The actual source hook, React, esbuild, and native Chromium and+ * WebKit viewports+ * @output Evidence that the stream scroll follows a page whose document+ * scrolls: the reader's scroll up shows the scroll button and stops follow+ * @position Covers the page's own scroll, which jsdom cannot raise: a browser+ * fires it at the document, and only a layout engine moves the root.+ */++import {once} from 'node:events';+import {createServer, type Server} from 'node:http';+import {fileURLToPath} from 'node:url';+import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {build} from 'esbuild';++const SETTLE_TIMEOUT_MS = 6000;+let server: Server;+let origin: string;++test.beforeAll(async () => {+ const result = await build({+ entryPoints: [+ fileURLToPath(+ new URL('./useChatStreamScrollPage.fixture.tsx', import.meta.url),+ ),+ ],+ bundle: true,+ write: false,+ format: 'iife',+ jsx: 'automatic',+ alias: {+ react: fileURLToPath(import.meta.resolve('react')),+ 'react/jsx-runtime': fileURLToPath(+ import.meta.resolve('react/jsx-runtime'),+ ),+ 'react-dom/client': fileURLToPath(+ import.meta.resolve('react-dom/client'),+ ),+ },+ define: {'process.env.NODE_ENV': '"production"'},+ });+ const script = result.outputFiles[0].contents;+ server = createServer((request, response) => {+ if (request.url === '/fixture.js') {+ response.writeHead(200, {'Content-Type': 'text/javascript'});+ response.end(script);+ } else if (request.url === '/') {+ response.writeHead(200, {'Content-Type': 'text/html'});+ response.end(+ '<!doctype html><meta charset="utf-8"><title>Chat page scroll regression</title><body style="margin:0"><div id="root"></div><script src="/fixture.js"></script></body>',+ );+ } else {+ response.writeHead(204);+ response.end();+ }+ });+ server.listen(0, '127.0.0.1');+ await once(server, 'listening');+ const address = server.address();+ if (!address || typeof address === 'string') {+ throw new Error('Missing fixture address');+ }+ origin = `http://127.0.0.1:${address.port}`;+});++test.afterAll(async () => {+ if (server) {+ await new Promise<void>((resolve, reject) =>+ server.close(error => (error ? reject(error) : resolve())),+ );+ }+});++async function pageGap(page: Page) {+ return page.evaluate(() => {+ const root = document.documentElement;+ return root.scrollHeight - root.clientHeight - root.scrollTop;+ });+}++function signal(page: Page) {+ return page.locator('output');+}++// WebKit animates a wheel scroll over several frames. The page is at rest+// when two reads 100 ms apart agree.+async function restingTop(page: Page) {+ let last = -1;+ await expect+ .poll(+ async () => {+ const top = await page.evaluate(+ () => document.documentElement.scrollTop,+ );+ const isStill = top === last;+ last = top;+ return isStill;+ },+ {timeout: SETTLE_TIMEOUT_MS, intervals: [100]},+ )+ .toBe(true);+ return last;+}++async function scrollPageUp(page: Page) {+ await page.mouse.move(200, 200);+ await page.mouse.wheel(0, -600);+ await expect+ .poll(async () => pageGap(page), {timeout: SETTLE_TIMEOUT_MS})+ .toBeGreaterThan(100);+ return restingTop(page);+}++test.beforeEach(async ({page}) => {+ const errors: string[] = [];+ page.on('pageerror', error => errors.push(error.message));+ await page.goto(origin);+ await expect+ .poll(async () => pageGap(page), {timeout: SETTLE_TIMEOUT_MS})+ .toBeLessThanOrEqual(1);+ expect(errors).toEqual([]);+});++test('opens at the end of the page, following, with no scroll button', async ({+ page,+}) => {+ await expect(signal(page)).toHaveAttribute('data-locked', 'true');+ await expect(signal(page)).toHaveAttribute('data-scrolled-up', 'false');+});++test('shows the scroll button and stops following when the reader scrolls the page up', async ({+ page,+}) => {+ await scrollPageUp(page);+ await expect(signal(page)).toHaveAttribute('data-scrolled-up', 'true');+ await expect(signal(page)).toHaveAttribute('data-locked', 'false');+});++test('leaves a reader who scrolled up in place when messages arrive', async ({+ page,+}) => {+ const before = await scrollPageUp(page);+ await page.getByRole('button', {name: 'Append messages'}).click();+ // Two frames give a locked spring time to move; an unlocked page stays.+ await page.evaluate(async () => {+ await new Promise(resolve => {+ requestAnimationFrame(() => requestAnimationFrame(resolve));+ });+ });+ await page.waitForTimeout(300);+ const after = await page.evaluate(() => document.documentElement.scrollTop);+ expect(Math.abs(after - before)).toBeLessThanOrEqual(1);+});diff --git a/packages/core/src/Chat/__tests__/useChatStreamScrollPage.fixture.tsx b/packages/core/src/Chat/__tests__/useChatStreamScrollPage.fixture.tsxnew file mode 100644index 0000000000..a6c6440c75--- /dev/null+++ b/packages/core/src/Chat/__tests__/useChatStreamScrollPage.fixture.tsx@@ -0,0 +1,45 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useChatStreamScrollPage.fixture.tsx+ * @input The actual scroll hook, on a page whose document scrolls+ * @output A deterministic browser fixture for the page-scroll regression+ * @position Test-only entry, excluded from the production package build+ */++import {useEffect, useRef, useState} from 'react';+import {createRoot} from 'react-dom/client';+import {useChatStreamScroll} from '../useChatStreamScroll';++function App() {+ const scrollRef = useRef<HTMLElement>(document.documentElement);+ const {scrollIfLocked, isLocked, isScrolledUp} = useChatStreamScroll({+ scrollRef,+ });+ const [extra, setExtra] = useState(0);+ useEffect(() => scrollIfLocked(), [extra, scrollIfLocked]);+ return (+ <main style={{paddingBlockEnd: 64}}>+ <div style={{height: 2400}}>Earlier messages</div>+ <div>Latest message</div>+ {extra > 0 && <div style={{height: extra}}>New messages</div>}+ <div style={{position: 'fixed', insetInline: 0, bottom: 0}}>+ <button type="button" onClick={() => setExtra(value => value + 400)}>+ Append messages+ </button>+ <output+ data-locked={String(isLocked)}+ data-scrolled-up={String(isScrolledUp)}+ />+ </div>+ </main>+ );+}++const root = document.getElementById('root');+if (!root) {+ throw new Error('Missing fixture root');+}+createRoot(root).render(<App />);diff --git a/packages/core/src/Chat/useChatStreamScroll.test.tsx b/packages/core/src/Chat/useChatStreamScroll.test.tsxindex bd550079ab..8fd76a7219 100644--- a/packages/core/src/Chat/useChatStreamScroll.test.tsx+++ b/packages/core/src/Chat/useChatStreamScroll.test.tsx@@ -379,3 +379,102 @@ describe('useChatStreamScroll — spring cancellation', () => {expect(rafQueue).toHaveLength(1);});});++describe('useChatStreamScroll — the page as the scroller', () => {+ // A page scrolls its root element, and the browser raises the scroll at+ // the document. The root's offsetHeight is the page's height; its+ // clientHeight is the viewport's.+ const root = document.documentElement;++ function setPageGeometry({+ scrollHeight,+ clientHeight,+ }: {+ scrollHeight: number;+ clientHeight: number;+ }) {+ Object.defineProperty(root, 'scrollHeight', {+ value: scrollHeight,+ configurable: true,+ });+ Object.defineProperty(root, 'clientHeight', {+ value: clientHeight,+ configurable: true,+ });+ Object.defineProperty(root, 'offsetHeight', {+ value: scrollHeight,+ configurable: true,+ });+ }++ function PageHarness({+ api,+ }: {+ api: {current: UseChatStreamScrollReturn | null};+ }) {+ const scrollRef = useRef<HTMLElement>(root);+ api.current = useChatStreamScroll({scrollRef});+ return null;+ }++ function scrollPageTo(top: number, target: EventTarget = document) {+ root.scrollTop = top;+ act(() => {+ target.dispatchEvent(new Event('scroll'));+ });+ }++ function renderPage() {+ const api: {current: UseChatStreamScrollReturn | null} = {current: null};+ setPageGeometry({scrollHeight: 3000, clientHeight: 700});+ const utils = render(<PageHarness api={api} />);+ flushRaf();+ scrollPageTo(2300);+ return {api, ...utils};+ }++ afterEach(() => {+ for (const property of ['scrollHeight', 'clientHeight', 'offsetHeight']) {+ Reflect.deleteProperty(root, property);+ }+ root.scrollTop = 0;+ });++ it('opens at the bottom, following, with no scroll button', () => {+ const {api} = renderPage();+ expect(root.scrollTop).toBe(2300);+ expect(api.current!.isScrolledUp).toBe(false);+ expect(api.current!.isLocked).toBe(true);+ });++ it('shows the scroll button and stops following when the reader scrolls the page up', () => {+ const {api} = renderPage();+ scrollPageTo(2000);+ expect(api.current!.isScrolledUp).toBe(true);+ expect(api.current!.isLocked).toBe(false);+ });++ it('follows again, with no scroll button, once the page comes to rest at the bottom', () => {+ const {api} = renderPage();+ scrollPageTo(2000);+ scrollPageTo(2300);+ act(() => {+ document.dispatchEvent(new Event('scrollend'));+ });+ expect(api.current!.isScrolledUp).toBe(false);+ expect(api.current!.isLocked).toBe(true);+ });++ it('ignores the scroll of an element inside the page', () => {+ const {api} = renderPage();+ const panel = document.createElement('div');+ document.body.append(panel);+ try {+ scrollPageTo(2000, panel);+ expect(api.current!.isScrolledUp).toBe(false);+ expect(api.current!.isLocked).toBe(true);+ } finally {+ panel.remove();+ }+ });+});diff --git a/packages/core/src/Chat/useChatStreamScroll.ts b/packages/core/src/Chat/useChatStreamScroll.tsindex 52ca376dfe..e20a2ff001 100644--- a/packages/core/src/Chat/useChatStreamScroll.ts+++ b/packages/core/src/Chat/useChatStreamScroll.ts@@ -4,7 +4,8 @@/*** @file useChatStreamScroll.ts- * @input Uses React refs, state, callbacks, useMediaQuery+ * @input Uses React refs, state, callbacks, useMediaQuery, and the input+ * stream's document scroll events when the page itself scrolls* @output Exports useChatStreamScroll hook for AI chat scroll behavior* @position Utility hook — used by ChatLayout, also usable standalone*@@ -34,6 +35,7 @@import {useCallback, useEffect, useRef, useState} from 'react';import {useMediaQuery} from '../hooks/useMediaQuery';import {setScrollAnchoringOff} from '../privateAttributes/scrollAnchoring.stylex';+import {subscribeInput} from '../utils/inputStream';// =============================================================================// Types@@ -363,8 +365,8 @@ export function useChatStreamScroll({// --- Event listeners ---- // Syncs scroll and scrollend listeners on the stream container with- // `enabled`.+ // Syncs the scroll and scrollend listeners with `enabled`: the stream+ // container's own, or the document's when the container scrolls the page.useEffect(() => {const el = scrollRef.current;if (!el || !enabled) {@@ -373,10 +375,16 @@ export function useChatStreamScroll({lastScrollTopRef.current = el.scrollTop;markFollowing(el, lockedRef.current);+ const doc = el.ownerDocument;+ const scrollsPage =+ el === doc.scrollingElement || el === doc.documentElement;+ // The root's offsetHeight is the page's height. Its clientHeight is the+ // viewport's, which is what the reader sees.+ const shownHeight = () => (scrollsPage ? el.clientHeight : el.offsetHeight);const onScroll = () => {- const {scrollTop, scrollHeight, offsetHeight} = el;- const dist = scrollHeight - scrollTop - offsetHeight;+ const {scrollTop, scrollHeight} = el;+ const dist = scrollHeight - scrollTop - shownHeight();// Button visibilitysetIsScrolledUp(dist > buttonThreshold);@@ -397,14 +405,29 @@ export function useChatStreamScroll({};const onScrollEnd = () => {- const dist = el.scrollHeight - el.scrollTop - el.offsetHeight;+ const dist = el.scrollHeight - el.scrollTop - shownHeight();if (dist <= lockThreshold) {setLocked(true);}};- el.addEventListener('scroll', onScroll, {passive: true});- el.addEventListener('scrollend', onScrollEnd);+ // A scroll of the page fires at the document, not at its root element.+ const view = scrollsPage ? doc.defaultView : null;+ const stopPageListeners: (() => void)[] = [];+ if (view != null) {+ const atDocument = (listener: () => void) => (event: Event) => {+ if (event.target === doc) {+ listener();+ }+ };+ stopPageListeners.push(+ subscribeInput(view, 'scroll', atDocument(onScroll)),+ subscribeInput(view, 'scrollend', atDocument(onScrollEnd)),+ );+ } else {+ el.addEventListener('scroll', onScroll, {passive: true});+ el.addEventListener('scrollend', onScrollEnd);+ }// Initial scroll to bottom — content already present at mount.requestAnimationFrame(() => {@@ -416,6 +439,9 @@ export function useChatStreamScroll({});return () => {+ for (const stop of stopPageListeners) {+ stop();+ }el.removeEventListener('scroll', onScroll);el.removeEventListener('scrollend', onScrollEnd);markFollowing(el, false);