An open source design system that's fully customizable and agent ready
TypeScript
fix(chat): position the first fill instantly + scrollToBottom({behavior: 'instant'}) (#3795) (#3800)
Yueqian Yang4812e5b08660
diff --git a/.changeset/chat-initial-scroll.md b/.changeset/chat-initial-scroll.mdnew file mode 100644index 0000000000..0d9817e93c--- /dev/null+++ b/.changeset/chat-initial-scroll.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Chat: opening a conversation that already has content (history, replay, session switching) no longer spring-scrolls from the top — the first fill positions instantly, whether the content is present at mount or arrives asynchronously. Subsequent growth (streaming) springs as before. `useChatStreamScroll`'s `scrollToBottom` accepts `{behavior: 'instant'}` for one-frame programmatic jumps, mirroring the DOM's `scrollTo({behavior})`. Exports the `ChatScrollToBottomOptions` type. (#3795)+@yyq1025diff --git a/packages/core/src/Chat/ChatLayout.test.tsx b/packages/core/src/Chat/ChatLayout.test.tsxindex 970bee0b92..ce0de2fd2c 100644--- a/packages/core/src/Chat/ChatLayout.test.tsx+++ b/packages/core/src/Chat/ChatLayout.test.tsx@@ -1,8 +1,11 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {describe, it, expect} from 'vitest';-import {render, screen} from '@testing-library/react';+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';+import {act, render, screen} from '@testing-library/react';import {ChatLayout} from './ChatLayout';+import {ChatMessageList} from './ChatMessageList';+import {ChatMessage} from './ChatMessage';+import {ChatMessageBubble} from './ChatMessageBubble';describe('ChatLayout', () => {it('renders children in the message area', () => {@@ -99,3 +102,125 @@ describe('ChatLayout', () => {expect(screen.queryByRole('button')).toBeNull();});});++// ---------------------------------------------------------------------------+// First-fill scroll positioning+//+// jsdom has no layout, so geometry is stubbed and only the synchronous+// paths are asserted (see useChatStreamScroll.test.tsx for the rationale).+// The ResizeObserver stub mirrors useChatNewMessages.test.tsx.+// ---------------------------------------------------------------------------++type ObserverEntry = {element: Element; callback: ResizeObserverCallback};+let activeObservations: ObserverEntry[] = [];++class FakeResizeObserver {+ callback: ResizeObserverCallback;+ observed = new Set<Element>();++ constructor(cb: ResizeObserverCallback) {+ this.callback = cb;+ }++ observe(el: Element) {+ this.observed.add(el);+ activeObservations.push({element: el, callback: this.callback});+ this.callback([{target: el} as ResizeObserverEntry], this);+ }++ unobserve(el: Element) {+ this.observed.delete(el);+ activeObservations = activeObservations.filter(o => o.element !== el);+ }++ disconnect() {+ for (const el of this.observed) {+ activeObservations = activeObservations.filter(o => o.element !== el);+ }+ this.observed.clear();+ }+}++describe('ChatLayout — first-fill scroll positioning', () => {+ let rafQueue: FrameRequestCallback[] = [];++ beforeEach(() => {+ activeObservations = [];+ rafQueue = [];+ vi.stubGlobal('ResizeObserver', FakeResizeObserver);+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {+ rafQueue.push(cb);+ return rafQueue.length;+ });+ vi.stubGlobal('cancelAnimationFrame', () => {});+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ function setGeometry(el: HTMLElement, scrollHeight: number) {+ Object.defineProperty(el, 'scrollHeight', {+ value: scrollHeight,+ configurable: true,+ });+ Object.defineProperty(el, 'clientHeight', {value: 400, configurable: true});+ Object.defineProperty(el, 'offsetHeight', {+ value: 400,+ configurable: true,+ });+ }++ function fireContentResize() {+ act(() => {+ for (const {element, callback} of [...activeObservations]) {+ callback([{target: element} as ResizeObserverEntry], null!);+ }+ });+ }++ function renderLayout() {+ render(+ <ChatLayout composer={<div>composer</div>} data-testid="layout">+ <ChatMessageList>+ <ChatMessage sender="assistant">+ <ChatMessageBubble>Hello</ChatMessageBubble>+ </ChatMessage>+ </ChatMessageList>+ </ChatLayout>,+ );+ return screen.getByTestId('layout');+ }++ it('positions async-loaded content synchronously on the first fill', () => {+ const root = renderLayout();+ // Mounted while content is short (loading) — not scrollable.+ setGeometry(root, 400);+ act(() => rafQueue.splice(0).forEach(cb => cb(0)));+ expect(root.scrollTop).toBe(0);++ // Content lands: the message list's ResizeObserver fires.+ setGeometry(root, 1400);+ fireContentResize();+ // Positioned in the same synchronous step — no animation frames.+ expect(root.scrollTop).toBe(1000);+ });++ it('springs on growth after the first fill — animation owns it', () => {+ const root = renderLayout();+ setGeometry(root, 400);+ act(() => rafQueue.splice(0).forEach(cb => cb(0)));++ // First fill: instant.+ setGeometry(root, 1400);+ fireContentResize();+ expect(root.scrollTop).toBe(1000);++ // Streaming growth: nothing moves until animation frames run.+ rafQueue.length = 0;+ setGeometry(root, 1800);+ fireContentResize();+ expect(root.scrollTop).toBe(1000);+ expect(rafQueue.length).toBeGreaterThan(0);+ });+});diff --git a/packages/core/src/Chat/index.ts b/packages/core/src/Chat/index.tsindex dceb0f38ef..923d20c8ca 100644--- a/packages/core/src/Chat/index.ts+++ b/packages/core/src/Chat/index.ts@@ -59,6 +59,7 @@ export type {export {useChatStreamScroll} from './useChatStreamScroll';export type {+ ChatScrollToBottomOptions,UseChatStreamScrollOptions,UseChatStreamScrollReturn,} from './useChatStreamScroll';diff --git a/packages/core/src/Chat/useChatStreamScroll.test.tsx b/packages/core/src/Chat/useChatStreamScroll.test.tsxnew file mode 100644index 0000000000..d9177e775f--- /dev/null+++ b/packages/core/src/Chat/useChatStreamScroll.test.tsx@@ -0,0 +1,168 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';+import {act, render} from '@testing-library/react';+import {useRef} from 'react';+import {+ useChatStreamScroll,+ type UseChatStreamScrollOptions,+ type UseChatStreamScrollReturn,+} from './useChatStreamScroll';++// ---------------------------------------------------------------------------+// Test infrastructure+//+// jsdom has no layout engine, so these tests cover only the SYNCHRONOUS+// scroll paths (instant positioning, lock state, rAF scheduling decisions).+// The spring physics itself (frame-by-frame integration, scrollend re-lock,+// user-scroll detection) is layout/browser-dependent and is verified+// manually via Storybook — mocking it here would only test the mock.+// ---------------------------------------------------------------------------++let rafQueue: FrameRequestCallback[] = [];++function flushRaf() {+ // One flush = one frame: callbacks scheduled during a flush run next flush.+ const frame = rafQueue;+ rafQueue = [];+ act(() => {+ for (const cb of frame) {+ cb(performance.now());+ }+ });+}++beforeEach(() => {+ rafQueue = [];+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {+ rafQueue.push(cb);+ return rafQueue.length;+ });+ vi.stubGlobal('cancelAnimationFrame', () => {});+});++afterEach(() => {+ vi.unstubAllGlobals();+});++function setGeometry(+ el: HTMLElement,+ {scrollHeight, clientHeight}: {scrollHeight: number; clientHeight: number},+) {+ Object.defineProperty(el, 'scrollHeight', {+ value: scrollHeight,+ configurable: true,+ });+ Object.defineProperty(el, 'clientHeight', {+ value: clientHeight,+ configurable: true,+ });+ Object.defineProperty(el, 'offsetHeight', {+ value: clientHeight,+ configurable: true,+ });+}++function Harness({+ options,+ api,+}: {+ options?: Partial<UseChatStreamScrollOptions>;+ api: {current: UseChatStreamScrollReturn | null};+}) {+ const scrollRef = useRef<HTMLDivElement>(null);+ api.current = useChatStreamScroll({scrollRef, ...options});+ return <div ref={scrollRef} data-testid="scroller" />;+}++function renderHook(options?: Partial<UseChatStreamScrollOptions>) {+ const api: {current: UseChatStreamScrollReturn | null} = {current: null};+ const utils = render(<Harness options={options} api={api} />);+ const el = utils.getByTestId('scroller');+ return {api, el, ...utils};+}++describe('useChatStreamScroll — initial positioning', () => {+ it('default: jumps to the bottom on mount when content is scrollable', () => {+ const {el} = renderHook();+ setGeometry(el, {scrollHeight: 1000, clientHeight: 400});+ flushRaf();+ expect(el.scrollTop).toBe(600);+ });++ it('positions the first async fill in one synchronous step', () => {+ const {api, el} = renderHook();+ // Mount while loading — nothing scrollable yet.+ setGeometry(el, {scrollHeight: 400, clientHeight: 400});+ flushRaf();+ expect(el.scrollTop).toBe(0);++ // Async content lands; the layout's ResizeObserver calls scrollIfLocked.+ setGeometry(el, {scrollHeight: 1200, clientHeight: 400});+ act(() => api.current!.scrollIfLocked());+ // Positioned synchronously — no animation frames needed.+ expect(el.scrollTop).toBe(800);++ // Subsequent growth (streaming) goes back to the spring: nothing moves+ // until animation frames run.+ setGeometry(el, {scrollHeight: 1600, clientHeight: 400});+ act(() => api.current!.scrollIfLocked());+ expect(el.scrollTop).toBe(800);+ });++ it('consumes the pending first fill via the mount jump too', () => {+ const {api, el} = renderHook();+ // Content already present at mount.+ setGeometry(el, {scrollHeight: 1000, clientHeight: 400});+ flushRaf();+ expect(el.scrollTop).toBe(600);++ // Growth after the mount jump is streaming — spring path, not instant.+ setGeometry(el, {scrollHeight: 1400, clientHeight: 400});+ act(() => api.current!.scrollIfLocked());+ expect(el.scrollTop).toBe(600);+ });++ it('default: starts locked', () => {+ const {api} = renderHook();+ expect(api.current!.isLocked).toBe(true);+ });+});++describe("useChatStreamScroll — scrollToBottom({behavior: 'instant'})", () => {+ it('jumps synchronously without scheduling animation frames', () => {+ const {api, el} = renderHook();+ setGeometry(el, {scrollHeight: 1000, clientHeight: 400});+ flushRaf(); // consume the mount jump+ el.scrollTop = 100; // user scrolled up++ rafQueue = [];+ act(() => api.current!.scrollToBottom({behavior: 'instant'}));+ expect(el.scrollTop).toBe(600);+ expect(rafQueue).toHaveLength(0);+ });++ it('re-locks after an instant jump', () => {+ const {api, el} = renderHook();+ setGeometry(el, {scrollHeight: 1000, clientHeight: 400});+ flushRaf();+ act(() => api.current!.unlock());+ expect(api.current!.isLocked).toBe(false);++ act(() => api.current!.scrollToBottom({behavior: 'instant'}));+ expect(api.current!.isLocked).toBe(true);+ expect(el.scrollTop).toBe(600);+ });++ it('default scrollToBottom animates instead of jumping', () => {+ const {api, el} = renderHook();+ setGeometry(el, {scrollHeight: 1000, clientHeight: 400});+ flushRaf();+ el.scrollTop = 100;++ act(() => api.current!.scrollToBottom());+ // Spring path: position is untouched until animation frames run.+ expect(el.scrollTop).toBe(100);+ expect(rafQueue.length).toBeGreaterThan(0);+ });+});diff --git a/packages/core/src/Chat/useChatStreamScroll.ts b/packages/core/src/Chat/useChatStreamScroll.tsindex 7f71e1ed3c..345cb652e9 100644--- a/packages/core/src/Chat/useChatStreamScroll.ts+++ b/packages/core/src/Chat/useChatStreamScroll.ts@@ -12,6 +12,9 @@* - Locked (default): content growth auto-scrolls to bottom via rAF spring* - Scrolling up (any source): unlocks immediately* - Scrolling settles at bottom: re-locks on scrollend+ * - The first fill positions instantly (whether content is present at+ * mount or arrives async); only subsequent growth springs+ * - `scrollToBottom({behavior: 'instant'})` jumps in one frame, no animation** Uses scroll direction (lastScrollTop comparison) to detect user* intent — works for wheel, touch, scrollbar drag, keyboard, everything.@@ -28,6 +31,18 @@ import {useCallback, useEffect, useRef, useState} from 'react';// Types// =============================================================================+export interface ChatScrollToBottomOptions {+ /**+ * `'instant'` jumps to the bottom in a single frame instead of running+ * the spring animation. Use for programmatic positioning (opening a+ * conversation, restoring a session) — keep the default `'spring'` for+ * user-initiated scrolls like the scroll-to-bottom button. Mirrors the+ * DOM's `scrollTo({behavior})`.+ * @default 'spring'+ */+ behavior?: 'instant' | 'spring';+}+export interface UseChatStreamScrollOptions {/*** Ref to the scrollable container element.@@ -81,7 +96,7 @@ export interface UseChatStreamScrollReturn {isLocked: boolean;/** Scroll to the bottom of the container and re-lock. */- scrollToBottom: () => void;+ scrollToBottom: (options?: ChatScrollToBottomOptions) => void;/** Scroll so a specific element is at the top of the visible area. No lock change. */scrollToMessage: (el: HTMLElement) => void;@@ -118,6 +133,9 @@ export function useChatStreamScroll({const [isLocked, setIsLocked] = useState(true);const lockedRef = useRef(true);+ // True until the initial fill has been positioned — consumed by the first+ // scrollIfLocked that sees scrollable content.+ const initialFillPendingRef = useRef(true);const velocityRef = useRef(0);const animatingRef = useRef(false);const lastTickRef = useRef<number | undefined>(undefined);@@ -179,14 +197,36 @@ export function useChatStreamScroll({}}, [animate]);+ // Jump to the bottom in a single frame — cancels any in-flight spring so+ // a later animation tick can't fight the assignment.+ const jumpToBottom = useCallback(() => {+ const el = scrollRef.current;+ if (!el) {+ return;+ }+ animatingRef.current = false;+ velocityRef.current = 0;+ lastTickRef.current = undefined;+ el.scrollTop = el.scrollHeight - el.clientHeight;+ lastScrollTopRef.current = el.scrollTop;+ }, [scrollRef]);+// --- Public API ---- const scrollToBottom = useCallback(() => {- lockedRef.current = true;- setIsLocked(true);- setIsScrolledUp(false);- startAnimation();- }, [startAnimation]);+ const scrollToBottom = useCallback(+ (options?: ChatScrollToBottomOptions) => {+ lockedRef.current = true;+ setIsLocked(true);+ setIsScrolledUp(false);+ initialFillPendingRef.current = false;+ if (options?.behavior === 'instant') {+ jumpToBottom();+ return;+ }+ startAnimation();+ },+ [startAnimation, jumpToBottom],+ );const scrollToMessage = useCallback((el: HTMLElement) => {@@ -232,10 +272,25 @@ export function useChatStreamScroll({if (!enabled) {return;}- if (lockedRef.current) {- startAnimation();+ if (!lockedRef.current) {+ return;+ }+ // Initial fill: content appearing for the first time (e.g. an+ // async-loaded conversation) positions in one frame instead of+ // spring-flying from the top. Stays pending through empty/loading+ // resizes until the container is actually scrollable.+ const el = scrollRef.current;+ if (+ initialFillPendingRef.current &&+ el &&+ el.scrollHeight > el.clientHeight+ ) {+ initialFillPendingRef.current = false;+ jumpToBottom();+ return;}- }, [enabled, startAnimation]);+ startAnimation();+ }, [enabled, startAnimation, jumpToBottom, scrollRef]);// --- Event listeners ---@@ -314,11 +369,12 @@ export function useChatStreamScroll({el.addEventListener('wheel', onWheel, {passive: true});el.addEventListener('touchmove', onTouchMove, {passive: true});- // Initial scroll to bottom+ // Initial scroll to bottom — content already present at mount.requestAnimationFrame(() => {if (el.scrollHeight > el.clientHeight) {el.scrollTop = el.scrollHeight - el.clientHeight;lastScrollTopRef.current = el.scrollTop;+ initialFillPendingRef.current = false;}});