An open source design system that's fully customizable and agent ready
TypeScript
refactor(Chat): extract scroll behavior into composable hooks (#1286)
Cindy Zhang0dee5563fbb2
diff --git a/apps/storybook/stories/ChatLayout.stories.tsx b/apps/storybook/stories/ChatLayout.stories.tsxindex 76d290a171..7f8097b4fe 100644--- a/apps/storybook/stories/ChatLayout.stories.tsx+++ b/apps/storybook/stories/ChatLayout.stories.tsx@@ -14,6 +14,7 @@ import {type XDSChatComposerToken,type XDSChatComposerTrigger,type XDSChatToolCallItem,+} from '@xds/core/Chat';import {XDSMarkdown} from '@xds/core/Markdown';import {XDSToken} from '@xds/core/Token';@@ -331,6 +332,7 @@ export const FullAIChat: StoryObj = {},]);setFiles([]);+setTimeout(() => {streamResponse("I'll check the Card component for the same issue.",@@ -587,6 +589,7 @@ export const PanelView: StoryObj = {},]);setFiles([]);+setTimeout(() => {streamResponse('Checking the component now.',diff --git a/packages/core/src/Chat/XDSChatLayout.test.tsx b/packages/core/src/Chat/XDSChatLayout.test.tsxindex 11cd46884e..189e6495bb 100644--- a/packages/core/src/Chat/XDSChatLayout.test.tsx+++ b/packages/core/src/Chat/XDSChatLayout.test.tsx@@ -89,9 +89,11 @@ describe('XDSChatLayout', () => {expect(screen.getByTestId('my-layout')).toBeTruthy();});- it('renders scroll-to-bottom button', () => {+ it('renders scrollButton slot', () => {render(- <XDSChatLayout composer={<div>composer</div>}>+ <XDSChatLayout+ composer={<div>composer</div>}+ scrollButton={<button>Scroll to bottom</button>}><div>msg</div></XDSChatLayout>,);diff --git a/packages/core/src/Chat/XDSChatLayout.tsx b/packages/core/src/Chat/XDSChatLayout.tsxindex 458264d455..85f21082c6 100644--- a/packages/core/src/Chat/XDSChatLayout.tsx+++ b/packages/core/src/Chat/XDSChatLayout.tsx@@ -2,14 +2,13 @@/*** @file XDSChatLayout.tsx- * @input Uses React, StyleX, theme tokens, useAutoScroll+ * @input Uses React, StyleX, theme tokens, useXDSChatStreamScroll, useXDSChatNewMessages* @output Exports XDSChatLayout component and XDSChatLayoutProps* @position Layout shell for full chat interfaces — messages in page flow, composer fixed to bottom*- * Arranges a chat page: messages flow naturally in the page, composer is- * fixed to the bottom with a frosted glass backdrop. Owns auto-scroll- * behavior and the scroll-to-bottom button. Uses ResizeObserver on the- * message content area to detect new content.+ * Structural layout only — scroll behavior is delegated to hooks.+ * Provides the scroll container ref and content ref, renders the+ * scroll-to-bottom button, frosted glass dock, and message area.** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/Chat/index.ts (exports)@@ -26,19 +25,12 @@ import {} from 'react';import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';-import {- colorVars,- spacingVars,- radiusVars,- shadowVars,- durationVars,- easeVars,-} from '../theme/tokens.stylex';+import {spacingVars} from '../theme/tokens.stylex';import {xdsClassName, mergeProps} from '../utils';+import {useXDSChatStreamScroll} from './useXDSChatStreamScroll';+import {useXDSChatNewMessages} from './useXDSChatNewMessages';+import {XDSChatLayoutScrollButton} from './XDSChatLayoutScrollButton';import {XDSChatLayoutContext} from './XDSChatContext';-import {useAutoScroll} from './useAutoScroll';-import {XDSIcon} from '../Icon';-import {XDSButton} from '../Button';// =============================================================================// Types@@ -46,6 +38,17 @@ import {XDSButton} from '../Button';type Density = 'compact' | 'balanced' | 'spacious';+/** Imperative handle for XDSChatLayout scroll controls. */+export interface XDSChatLayoutHandle {+ /** Scroll a message to the top and unlock for stream-in. */+ /** Scroll to bottom and re-lock. */+ scrollToBottom: () => void;+ /** Navigate to a message, no lock change. */+ scrollToMessage: (el: HTMLElement) => void;+ /** Scroll to the last message. */+ scrollToLastMessage: () => void;+}+export interface XDSChatLayoutProps {/** Ref forwarded to the root element. */ref?: React.Ref<HTMLDivElement>;@@ -67,34 +70,28 @@ export interface XDSChatLayoutProps {*/emptyState?: ReactNode;+ /**+ * Scroll-to-bottom button rendered above the composer in the dock.+ * Defaults to XDSChatLayoutScrollButton with useXDSChatStreamScroll.+ * Pass a custom ReactNode to override, or `null` to hide.+ */+ scrollButton?: ReactNode | null;+/*** External scroll container ref. When provided, auto-scroll and* scroll-to-bottom target this element instead of the layout root.** @example* ```- * // Scroll with the page body* const scrollRef = useRef(document.documentElement);* <XDSChatLayout scrollRef={scrollRef} composer={...}>...</XDSChatLayout>* ```*- * When omitted, the layout root itself is the scroll container- * (`overflow-y: auto`). This is the default for full-page and- * panel chat layouts.+ * When omitted, the layout root itself is the scroll container.*/scrollRef?: React.RefObject<HTMLElement | null>;- /**- * Whether auto-scroll behavior is enabled.- * @default true- */- hasAutoScroll?: boolean;- /**- * Label shown in the scroll-to-bottom button when new messages arrive.- * @default 'New messages'- */- newMessagesLabel?: string;/** StyleX overrides. */xstyle?: StyleXStyles;@@ -120,9 +117,14 @@ const styles = stylex.create({rootScrollable: {overflowY: 'auto',overflowX: 'hidden',+ // Hide scrollbar during programmatic scroll animation+ // to prevent flash. Restored when animation settles.+ scrollbarWidth: {+ default: null,+ ':is([data-xds-scrolling])': 'none',+ },},- // --- Message area ---messageArea: {display: 'flex',flexDirection: 'column',@@ -141,7 +143,6 @@ const styles = stylex.create({paddingInline: spacingVars['--spacing-4'],},- // --- Empty state ---emptyState: {display: 'flex',alignItems: 'center',@@ -150,7 +151,7 @@ const styles = stylex.create({minHeight: 200,},- // --- Dock container — holds blur layer + composer as siblings ---+ // --- Dock container ---dockContainer: {bottom: 0,left: 0,@@ -166,7 +167,6 @@ const styles = stylex.create({position: 'sticky',},- // --- Blur layer (absolute within dock container) ---blurLayer: {position: 'absolute',bottom: 0,@@ -176,7 +176,6 @@ const styles = stylex.create({backdropFilter: 'blur(12px)',WebkitBackdropFilter: 'blur(12px)',},-blurLayerCompact: {height: 80,maskImage: 'linear-gradient(to bottom, transparent, black 24px)',@@ -193,13 +192,11 @@ const styles = stylex.create({WebkitMaskImage: 'linear-gradient(to bottom, transparent, black 48px)',},- // --- Composer dock ---dock: {position: 'relative',zIndex: 1,pointerEvents: 'auto',},-dockCompact: {paddingInline: spacingVars['--spacing-2'],paddingBlockEnd: spacingVars['--spacing-2'],@@ -213,7 +210,6 @@ const styles = stylex.create({paddingBlockEnd: spacingVars['--spacing-3'],},- // --- Dock inner wrapper ---dockInner: {marginInline: 'auto',},@@ -227,45 +223,6 @@ const styles = stylex.create({maxWidth: 800,},- // --- Scroll-to-bottom button ---- // Wrapper centers the button above the composer inside the dock container.- scrollButtonWrapper: {- display: 'flex',- justifyContent: 'center',- paddingBlockEnd: spacingVars['--spacing-3'],- },- scrollButtonContainer: {- pointerEvents: 'auto',- contain: 'layout style',- overflow: 'hidden',- borderRadius: radiusVars['--radius-full'],- backgroundColor: colorVars['--color-background-popover'],- boxShadow: shadowVars['--shadow-med'],- height: '32px',- transitionProperty: 'opacity, transform, max-width',- transitionTimingFunction: easeVars['--ease-standard'],- transitionDuration: durationVars['--duration-fast-max'],- },- scrollButtonContainerHidden: {- opacity: 0,- pointerEvents: 'none',- maxWidth: '32px',- },- scrollButtonContainerVisible: {- opacity: 1,- pointerEvents: 'auto',- },- scrollButtonCollapsed: {- maxWidth: '32px',- },- scrollButtonExpanded: {- maxWidth: '200px',- },- scrollButton: {- [radiusVars['--radius-element'] as string]: radiusVars['--radius-full'],- whiteSpace: 'nowrap',- paddingInline: spacingVars['--spacing-2'],- },});// =============================================================================@@ -288,79 +245,17 @@ function hasVisibleContent(children: ReactNode): boolean {// Sub-components// =============================================================================-function ScrollToBottomButton({- isScrolledUp,- hasNewMessages,- label,- onClick,-}: {- isScrolledUp: boolean;- hasNewMessages: boolean;- label: string;- onClick: () => void;-}) {- const isVisible = isScrolledUp || hasNewMessages;-- return (- <div- {...stylex.props(styles.scrollButtonWrapper)}>- <div- {...stylex.props(- styles.scrollButtonContainer,- isVisible- ? styles.scrollButtonContainerVisible- : styles.scrollButtonContainerHidden,- hasNewMessages- ? styles.scrollButtonExpanded- : styles.scrollButtonCollapsed,- )}>- <XDSButton- label={hasNewMessages ? label : 'Scroll to bottom'}- aria-label={hasNewMessages ? label : 'Scroll to bottom'}- icon={<XDSIcon icon="chevronDown" size="md" />}- variant="ghost"- size="md"- onClick={onClick}- xstyle={styles.scrollButton}>- {hasNewMessages ? label : undefined}- </XDSButton>- </div>- </div>- );-}// =============================================================================// Component// =============================================================================-/**- * Layout shell for full chat interfaces.- *- * Messages flow naturally in the page. The composer is fixed to- * the bottom with a frosted glass dock. The layout owns auto-scroll- * behavior — it observes the message content area via ResizeObserver- * and scrolls to bottom when new content arrives (if the user is- * near the bottom). Shows a scroll-to-bottom button when scrolled up.- *- * @example- * ```- * <XDSChatLayout- * composer={<XDSChatComposer onSubmit={handleSubmit} />}- * emptyState={<EmptyState />}- * >- * <XDSChatMessageList>- * {messages.map(msg => <XDSChatMessage key={msg.id} {...msg} />)}- * </XDSChatMessageList>- * </XDSChatLayout>- * ```- */export function XDSChatLayout({children,composer,emptyState,+ scrollButton,scrollRef: externalScrollRef,- hasAutoScroll = true,- newMessagesLabel = 'New messages',xstyle,className,style,@@ -368,10 +263,8 @@ export function XDSChatLayout({ref,}: XDSChatLayoutProps) {const rootRef = useRef<HTMLDivElement>(null);- const dockRef = useRef<HTMLDivElement>(null);- const scrollListenerRef = useRef<(() => void) | null>(null);- const contentElRef = useRef<HTMLElement | null>(null);- const contentObserverRef = useRef<ResizeObserver | null>(null);++ const contentRef = useRef<HTMLElement>(null);const scrollContainerRef =externalScrollRef ?? (rootRef as React.RefObject<HTMLElement | null>);@@ -379,30 +272,39 @@ export function XDSChatLayout({const [density, setDensity] = useState<Density>('balanced');- // --- Auto-scroll ---- const {- scrollRef,- isScrolledUp,- hasNewMessages,- handleScroll,- handleScrollEnd,- handleUserScroll,- scrollToBottom,- dismissNewMessages,- onContentChange,- scrollToBottomIfLocked,- } = useAutoScroll({- enabled: hasAutoScroll,- scrollContainerRef,+ // --- Default scroll behavior ---+ const scroll = useXDSChatStreamScroll({scrollRef: scrollContainerRef});+ const newMsgs = useXDSChatNewMessages({+ contentRef,+ isLocked: scroll.isLocked,+ onResize: scroll.scrollIfLocked,});+ const defaultScrollButton = (+ <XDSChatLayoutScrollButton+ isVisible={scroll.isScrolledUp || newMsgs.hasNewMessages}+ label={newMsgs.hasNewMessages ? 'New messages' : undefined}+ onClick={() => {+ newMsgs.dismiss();+ scroll.scrollToBottom();+ }}+ />+ );+- // Single ResizeObserver for both density (root width) and content- // changes (new messages). Checks entry.target to dispatch.- const lastMessageRef = useRef<Element | null>(null);+ // --- Content ref callback for message list ---+ const setContentRef = useCallback((el: HTMLElement | null) => {+ (contentRef as React.MutableRefObject<HTMLElement | null>).current = el;+ }, []);- // Density observer — watches root width for breakpoints.+ // --- Layout context ---+ const layoutContext = useMemo(+ () => ({scrollContainerRef, contentRef: setContentRef}),+ [scrollContainerRef, setContentRef],+ );++ // --- Density observer ---useEffect(() => {const root = rootRef.current;if (!root) return;@@ -413,100 +315,19 @@ export function XDSChatLayout({return () => observer.disconnect();}, []);- // Content ref callback — observe the message list for height changes.- // Two behaviors:- // - New message appended (last element changed) → onContentChange- // (auto-scrolls if near bottom, shows "new messages" if scrolled up)- // - Existing message growing (streaming) → just auto-scroll if near- // bottom, but don't flag "new messages"- const contentRef = useCallback(- (el: HTMLElement | null) => {- if (contentObserverRef.current) {- contentObserverRef.current.disconnect();- contentObserverRef.current = null;- }- contentElRef.current = el;- if (el) {- const observer = new ResizeObserver(() => {- const messages = el.getElementsByClassName('xds-chat-message');- const last =- messages.length > 0 ? messages[messages.length - 1] : null;- if (last && last !== lastMessageRef.current) {- // New message — auto-scroll or show "new messages"- lastMessageRef.current = last;- onContentChange();- } else {- // Existing content growing (streaming) — auto-scroll only,- // don't flag "new messages"- scrollToBottomIfLocked();- }- });- observer.observe(el);- contentObserverRef.current = observer;- }- },- [onContentChange, scrollToBottomIfLocked],- );-- // --- Layout context ---- const layoutContextValue = useMemo(- () => ({- scrollContainerRef,- contentRef,- }),- [scrollContainerRef, contentRef],- );---// --- Merge refs ---- // Callback ref attaches scroll listener and triggers initial scroll.const setRootRef = useCallback((el: HTMLDivElement | null) => {- // Detach previous listener- if (scrollListenerRef.current) {- scrollListenerRef.current();- scrollListenerRef.current = null;- }-(rootRef as React.MutableRefObject<HTMLDivElement | null>).current = el;-- if (el) {- const scrollEl = scrollRef.current;- if (scrollEl) {- scrollEl.addEventListener('scroll', handleScroll, {passive: true});- scrollEl.addEventListener('scrollend', handleScrollEnd);- scrollEl.addEventListener('wheel', handleUserScroll, {passive: true});- scrollEl.addEventListener('touchstart', handleUserScroll, {passive: true});- scrollListenerRef.current = () => {- scrollEl.removeEventListener('scroll', handleScroll);- scrollEl.removeEventListener('scrollend', handleScrollEnd);- scrollEl.removeEventListener('wheel', handleUserScroll);- scrollEl.removeEventListener('touchstart', handleUserScroll);- };- // Defer to next frame so content has laid out- requestAnimationFrame(() => scrollToBottom(false));- }- }-if (typeof ref === 'function') {ref(el);} else if (ref) {(ref as React.MutableRefObject<HTMLDivElement | null>).current = el;}},- [ref, scrollRef, handleScroll, handleScrollEnd, handleUserScroll, scrollToBottom],+ [ref],);- // --- Scroll button handler ---- const handleButtonClick = useCallback(() => {- if (hasNewMessages) {- dismissNewMessages();- } else {- scrollToBottom();- }- }, [hasNewMessages, dismissNewMessages, scrollToBottom]);-// --- Derived styles ---const showEmpty = !hasVisibleContent(children);@@ -539,7 +360,7 @@ export function XDSChatLayout({: styles.dockInnerBalanced;return (- <XDSChatLayoutContext.Provider value={layoutContextValue}>+ <XDSChatLayoutContext.Provider value={layoutContext}><divref={setRootRef}data-testid={testId}@@ -555,9 +376,7 @@ export function XDSChatLayout({style,)}>{/* Message area */}- <div- {...stylex.props(styles.messageArea, messageAreaStyle)}->+ <div {...stylex.props(styles.messageArea, messageAreaStyle)}>{showEmpty && emptyState ? (<div {...stylex.props(styles.emptyState)}>{emptyState}</div>) : (@@ -567,23 +386,17 @@ export function XDSChatLayout({{/* Dock container — sticky/fixed, holds blur + scroll button + composer */}<div- ref={dockRef}{...stylex.props(styles.dockContainer,isSelfScrolling? styles.dockContainerSticky: styles.dockContainerFixed,)}>- {/* Frosted glass layer — behind composer */}- <div {...stylex.props(styles.blurLayer, blurLayerStyle)} />-{/* Scroll-to-bottom button */}- <ScrollToBottomButton- isScrolledUp={isScrolledUp}- hasNewMessages={hasNewMessages}- label={newMessagesLabel}- onClick={handleButtonClick}- />+ {scrollButton === undefined ? defaultScrollButton : scrollButton}++ {/* Frosted glass layer */}+ <div {...stylex.props(styles.blurLayer, blurLayerStyle)} />{/* Composer */}<div {...stylex.props(styles.dock, dockStyle)}>diff --git a/packages/core/src/Chat/XDSChatLayoutScrollButton.tsx b/packages/core/src/Chat/XDSChatLayoutScrollButton.tsxnew file mode 100644index 0000000000..50ff2c7c09--- /dev/null+++ b/packages/core/src/Chat/XDSChatLayoutScrollButton.tsx@@ -0,0 +1,117 @@+'use client';++/**+ * @file XDSChatLayoutScrollButton.tsx+ * @input Uses React, StyleX, XDSButton, XDSIcon, theme tokens+ * @output Exports XDSChatLayoutScrollButton component+ * @position Composable scroll-to-bottom button for use inside XDSChatLayout+ *+ * Renders inside the layout's dock container. Fades in when visible,+ * expands to show a label when provided (e.g. "New messages").+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Chat/index.ts (exports)+ */++import * as stylex from '@stylexjs/stylex';+import {+ colorVars,+ spacingVars,+ radiusVars,+ shadowVars,+ durationVars,+ easeVars,+} from '../theme/tokens.stylex';+import {XDSIcon} from '../Icon';+import {XDSButton} from '../Button';++// =============================================================================+// Types+// =============================================================================++export interface XDSChatLayoutScrollButtonProps {+ /** Whether the button is visible. */+ isVisible: boolean;+ /** Optional label — expands the button (e.g. "New messages"). */+ label?: string;+ /** Click handler. */+ onClick: () => void;+}++// =============================================================================+// Styles+// =============================================================================++const styles = stylex.create({+ wrapper: {+ display: 'flex',+ justifyContent: 'center',+ paddingBlockEnd: spacingVars['--spacing-3'],+ },+ container: {+ pointerEvents: 'auto',+ contain: 'layout style',+ overflow: 'hidden',+ borderRadius: radiusVars['--radius-full'],+ backgroundColor: colorVars['--color-background-popover'],+ boxShadow: shadowVars['--shadow-med'],+ height: '32px',+ transitionProperty: 'opacity, transform, max-width',+ transitionTimingFunction: easeVars['--ease-standard'],+ transitionDuration: durationVars['--duration-fast-max'],+ },+ hidden: {+ opacity: 0,+ pointerEvents: 'none',+ maxWidth: '32px',+ },+ visible: {+ opacity: 1,+ pointerEvents: 'auto',+ },+ collapsed: {+ maxWidth: '32px',+ },+ expanded: {+ maxWidth: '200px',+ },+ button: {+ [radiusVars['--radius-element'] as string]: radiusVars['--radius-full'],+ whiteSpace: 'nowrap',+ paddingInline: spacingVars['--spacing-2'],+ },+});++// =============================================================================+// Component+// =============================================================================++export function XDSChatLayoutScrollButton({+ isVisible,+ label,+ onClick,+}: XDSChatLayoutScrollButtonProps) {+ return (+ <div {...stylex.props(styles.wrapper)}>+ <div+ {...stylex.props(+ styles.container,+ isVisible ? styles.visible : styles.hidden,+ label ? styles.expanded : styles.collapsed,+ )}>+ <XDSButton+ label={label ?? 'Scroll to bottom'}+ aria-label={label ?? 'Scroll to bottom'}+ icon={<XDSIcon icon="chevronDown" size="md" />}+ variant="ghost"+ size="md"+ onClick={onClick}+ xstyle={styles.button}>+ {label ?? undefined}+ </XDSButton>+ </div>+ </div>+ );+}++XDSChatLayoutScrollButton.displayName = 'XDSChatLayoutScrollButton';diff --git a/packages/core/src/Chat/XDSChatMessageList.tsx b/packages/core/src/Chat/XDSChatMessageList.tsxindex 1ca5f7d6a6..9a850c2bce 100644--- a/packages/core/src/Chat/XDSChatMessageList.tsx+++ b/packages/core/src/Chat/XDSChatMessageList.tsx@@ -12,7 +12,7 @@** Auto-scroll and the scroll-to-bottom button are owned by* XDSChatLayout. When used standalone (without a layout), the list- * is purely presentational — compose useAutoScroll yourself if needed.+ * is purely presentational — compose useXDSChatStreamScroll yourself if needed.** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/Chat/index.ts (exports)@@ -137,7 +137,7 @@ const styles = stylex.create({* Supports loading older messages via `onScrollToTopAction`.** Auto-scroll and the scroll-to-bottom button are owned by- * XDSChatLayout. Use useAutoScroll for standalone scroll control.+ * XDSChatLayout. Use useXDSChatStreamScroll for standalone scroll control.** @example* ```diff --git a/packages/core/src/Chat/index.ts b/packages/core/src/Chat/index.tsindex e7f9c649dd..a59082faac 100644--- a/packages/core/src/Chat/index.ts+++ b/packages/core/src/Chat/index.ts@@ -56,10 +56,13 @@ export type {XDSChatSystemMessageVariant,} from './XDSChatSystemMessage';-export {useAutoScroll} from './useAutoScroll';-export type {UseAutoScrollOptions, UseAutoScrollReturn} from './useAutoScroll';+export {useXDSChatStreamScroll} from './useXDSChatStreamScroll';+export type {UseXDSChatStreamScrollOptions, UseXDSChatStreamScrollReturn} from './useXDSChatStreamScroll';+export {useXDSChatNewMessages} from './useXDSChatNewMessages';+export type {UseXDSChatNewMessagesOptions, UseXDSChatNewMessagesReturn} from './useXDSChatNewMessages';export type {XDSChatMessageSender, XDSChatDensity} from './XDSChatContext';+export {useXDSChatLayoutContext} from './XDSChatContext';export {XDSChatToolCalls} from './XDSChatToolCalls';export type {@@ -69,4 +72,6 @@ export type {} from './XDSChatToolCalls';export {XDSChatLayout} from './XDSChatLayout';+export {XDSChatLayoutScrollButton} from './XDSChatLayoutScrollButton';+export type {XDSChatLayoutScrollButtonProps} from './XDSChatLayoutScrollButton';export type {XDSChatLayoutProps} from './XDSChatLayout';diff --git a/packages/core/src/Chat/useAutoScroll.ts b/packages/core/src/Chat/useAutoScroll.tsdeleted file mode 100644index c1c9ca9e84..0000000000--- a/packages/core/src/Chat/useAutoScroll.ts+++ /dev/null@@ -1,187 +0,0 @@-'use client';--/**- * @file useAutoScroll.ts- * @input Uses React refs, state, and effects- * @output Exports useAutoScroll hook for scroll-pinning behavior- * @position Utility hook — used by XDSChatLayout, also usable standalone- *- * Scroll-lock model:- * - **Locked** (default): content changes auto-scroll to bottom- * - **Unlocked**: user manually scrolled, auto-scroll stops- * - **Re-locked**: user clicks scroll-to-bottom button- *- * Uses `scrollend` to distinguish user scrolls from programmatic ones.- * Programmatic scrolls (scrollToBottom) set a flag before scrolling;- * when `scrollend` fires without that flag, it was a user scroll → unlock.- *- * SYNC: When modified, update:- * - /packages/core/src/Chat/index.ts (exports)- * - /packages/core/src/Chat/XDSChatLayout.tsx (consumer)- */--import {useCallback, useEffect, useRef, useState} from 'react';--export interface UseAutoScrollOptions {- /**- * Whether auto-scroll behavior is enabled.- * @default true- */- enabled?: boolean;-- /**- * Distance from bottom (in px) beyond which the scroll-to-bottom- * button becomes visible.- * @default 100- */- scrollUpThreshold?: number;-- /**- * External scroll container ref. When provided, scroll logic targets- * this element instead of creating its own.- */- scrollContainerRef?: React.RefObject<HTMLElement | null>;-}--export interface UseAutoScrollReturn {- /** Ref to attach to the scrollable container element. */- scrollRef: React.RefObject<HTMLDivElement | null>;-- /** Whether the user has scrolled up (shows scroll-to-bottom button). */- isScrolledUp: boolean;-- /** Whether new content arrived while unlocked. */- hasNewMessages: boolean;-- /** Scroll handler — attach to onScroll. */- handleScroll: () => void;-- /** Scrollend handler — attach to scrollend. */- handleScrollEnd: () => void;-- /** User input handler — attach to wheel/touchstart to interrupt programmatic scrolls. */- handleUserScroll: () => void;-- /** Scroll to the bottom of the container. */- scrollToBottom: (smooth?: boolean) => void;-- /** Dismiss the new messages indicator, re-lock, and scroll to bottom. */- dismissNewMessages: () => void;-- /** New message appended — flag "new messages" if unlocked. */- onContentChange: () => void;-- /** Content grew — auto-scroll if locked, no flag. */- scrollToBottomIfLocked: () => void;-}--/**- * Hook that manages scroll-lock auto-scroll behavior.- *- * Starts locked (pinned to bottom). User scrolling unlocks (detected- * via `scrollend` without the programmatic flag). Clicking the- * scroll-to-bottom button re-locks.- */-export function useAutoScroll({- enabled = true,- scrollUpThreshold = 100,- scrollContainerRef,-}: UseAutoScrollOptions = {}): UseAutoScrollReturn {- const internalRef = useRef<HTMLDivElement | null>(null);- const scrollRef = (scrollContainerRef ??- internalRef) as React.RefObject<HTMLDivElement | null>;-- const [hasNewMessages, setHasNewMessages] = useState(false);- const [isScrolledUp, setIsScrolledUp] = useState(false);-- // Scroll lock: true = auto-scroll follows content- const lockedRef = useRef(true);- // Flag set before programmatic scrolls, cleared on scrollend- const isProgrammaticRef = useRef(false);-- const scrollToBottom = useCallback((smooth = true) => {- const el = scrollRef.current;- if (!el) return;- isProgrammaticRef.current = true;- if (typeof el.scrollTo === 'function') {- el.scrollTo({- top: el.scrollHeight,- behavior: smooth ? 'smooth' : 'instant',- });- } else {- el.scrollTop = el.scrollHeight;- }- }, []);-- // User input (wheel/touch) interrupts any in-progress programmatic scroll- const handleUserScroll = useCallback(() => {- isProgrammaticRef.current = false;- }, []);-- // On scroll: unlock if user scrolled past threshold- const handleScroll = useCallback(() => {- const el = scrollRef.current;- if (!el) return;- const distanceFromBottom =- el.scrollHeight - el.scrollTop - el.clientHeight;- setIsScrolledUp(distanceFromBottom > scrollUpThreshold);-- if (!isProgrammaticRef.current && distanceFromBottom > scrollUpThreshold) {- lockedRef.current = false;- }- }, [scrollUpThreshold]);-- // On scroll end: lock if at bottom, clear programmatic flag- const handleScrollEnd = useCallback(() => {- isProgrammaticRef.current = false;-- const el = scrollRef.current;- if (!el) return;- const distanceFromBottom =- el.scrollHeight - el.scrollTop - el.clientHeight;- if (distanceFromBottom <= scrollUpThreshold) {- lockedRef.current = true;- setHasNewMessages(false);- }- }, [scrollUpThreshold]);-- const onContentChange = useCallback(() => {- if (!enabled) return;- if (!lockedRef.current) {- setHasNewMessages(true);- }- }, [enabled]);-- const scrollToBottomIfLocked = useCallback(() => {- if (!enabled) return;- if (lockedRef.current) {- scrollToBottom(true);- }- }, [enabled, scrollToBottom]);-- const dismissNewMessages = useCallback(() => {- lockedRef.current = true;- isProgrammaticRef.current = true;- setIsScrolledUp(false);- setHasNewMessages(false);- scrollToBottom();- }, [scrollToBottom]);-- // Scroll to bottom on mount- useEffect(() => {- scrollToBottom(false);- }, []);-- return {- scrollRef,- isScrolledUp,- hasNewMessages,- handleScroll,- handleScrollEnd,- handleUserScroll,- scrollToBottom,- dismissNewMessages,- onContentChange,- scrollToBottomIfLocked,- };-}diff --git a/packages/core/src/Chat/useXDSChatNewMessages.ts b/packages/core/src/Chat/useXDSChatNewMessages.tsnew file mode 100644index 0000000000..94bf29b47b--- /dev/null+++ b/packages/core/src/Chat/useXDSChatNewMessages.ts@@ -0,0 +1,103 @@+'use client';++/**+ * @file useXDSChatNewMessages.ts+ * @input Uses React refs, state, ResizeObserver+ * @output Exports useXDSChatNewMessages hook for detecting new chat messages+ * @position Utility hook — used by XDSChatLayout, also usable standalone+ *+ * Observes a content element via ResizeObserver and tracks the last+ * .xds-chat-message element. When a new message appears (last element+ * changes), flags hasNewMessages if the scroll is unlocked.+ *+ * Also calls onResize on every content height change so the scroll+ * hook can follow growing content (streaming).+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Chat/index.ts (exports)+ */++import {useCallback, useEffect, useRef, useState} from 'react';++// =============================================================================+// Types+// =============================================================================++export interface UseXDSChatNewMessagesOptions {+ /**+ * Ref to the content element to observe (message list inner div).+ * Can be a callback ref or a regular ref.+ */+ contentRef: React.RefObject<HTMLElement | null>;++ /**+ * Whether the scroll is currently locked (following content).+ * When locked, new messages don't flag — the user is already at the bottom.+ */+ isLocked: boolean;++ /**+ * Called on every content height change (new message or streaming growth).+ * Use to trigger scroll-if-locked in the scroll hook.+ */+ onResize?: () => void;+}++export interface UseXDSChatNewMessagesReturn {+ /** Whether new messages arrived while the scroll was unlocked. */+ hasNewMessages: boolean;++ /** Dismiss the new messages flag. */+ dismiss: () => void;+}++// =============================================================================+// Hook+// =============================================================================++export function useXDSChatNewMessages({+ contentRef,+ isLocked,+ onResize,+}: UseXDSChatNewMessagesOptions): UseXDSChatNewMessagesReturn {+ const [hasNewMessages, setHasNewMessages] = useState(false);+ const lastMessageRef = useRef<Element | null>(null);+ const isLockedRef = useRef(isLocked);+ isLockedRef.current = isLocked;++ const onResizeRef = useRef(onResize);+ onResizeRef.current = onResize;++ // Observe content for height changes+ useEffect(() => {+ const el = contentRef.current;+ if (!el) return;++ const observer = new ResizeObserver(() => {+ // Notify scroll hook of any height change+ onResizeRef.current?.();++ // Check if a new message was appended+ const messages = el.getElementsByClassName('xds-chat-message');+ const last =+ messages.length > 0 ? messages[messages.length - 1] : null;++ if (last && last !== lastMessageRef.current) {+ lastMessageRef.current = last;+ // Only flag if unlocked — user is scrolled up+ if (!isLockedRef.current) {+ setHasNewMessages(true);+ }+ }+ });++ observer.observe(el);+ return () => observer.disconnect();+ }, [contentRef]);++ const dismiss = useCallback(() => {+ setHasNewMessages(false);+ }, []);++ return {hasNewMessages, dismiss};+}diff --git a/packages/core/src/Chat/useXDSChatStreamScroll.ts b/packages/core/src/Chat/useXDSChatStreamScroll.tsnew file mode 100644index 0000000000..88e83c0278--- /dev/null+++ b/packages/core/src/Chat/useXDSChatStreamScroll.ts@@ -0,0 +1,332 @@+'use client';++/**+ * @file useXDSChatStreamScroll.ts+ * @input Uses React refs, state, callbacks+ * @output Exports useXDSChatStreamScroll hook for AI chat scroll behavior+ * @position Utility hook — used by XDSChatLayout, also usable standalone+ *+ * Spring-based scroll-to-bottom with lock/unlock:+ * - 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+ *+ * Uses scroll direction (lastScrollTop comparison) to detect user+ * intent — works for wheel, touch, scrollbar drag, keyboard, everything.+ * Tracks scrollHeight/offsetHeight changes to ignore Chrome synthetic+ * scroll events caused by content resize.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Chat/index.ts (exports)+ */++import {useCallback, useEffect, useRef, useState} from 'react';++// =============================================================================+// Types+// =============================================================================++export interface UseXDSChatStreamScrollOptions {+ /**+ * Ref to the scrollable container element.+ */+ scrollRef: React.RefObject<HTMLElement | null>;++ /**+ * Whether scroll behavior is enabled.+ * @default true+ */+ enabled?: boolean;++ /**+ * Distance from bottom (in px) within which scrollend re-locks.+ * Keep small so users aren't yanked back from a slight scroll.+ * @default 10+ */+ lockThreshold?: number;++ /**+ * Distance from bottom (in px) beyond which the scroll-to-bottom+ * button becomes visible.+ * @default 100+ */+ buttonThreshold?: number;++ /**+ * Spring damping — how quickly the animation settles.+ * @default 0.7+ */+ damping?: number;++ /**+ * Spring stiffness — how fast the animation accelerates.+ * @default 0.05+ */+ stiffness?: number;++ /**+ * Spring mass — higher = slower animation.+ * @default 1.25+ */+ mass?: number;+}++export interface UseXDSChatStreamScrollReturn {+ /** Whether the user has scrolled up past buttonThreshold. */+ isScrolledUp: boolean;++ /** Whether auto-scroll is locked (following content). */+ isLocked: boolean;++ /** Scroll to the bottom of the container and re-lock. */+ scrollToBottom: () => void;++ /** Scroll so a specific element is at the top of the visible area. No lock change. */+ scrollToMessage: (el: HTMLElement) => void;++ /** Lock auto-scroll and scroll to bottom. */+ lock: () => void;++ /** Unlock auto-scroll. */+ unlock: () => void;++ /** Scroll to bottom if currently locked. Call on content resize. */+ scrollIfLocked: () => void;++ /** Scroll to the last message in the container. */+ scrollToLastMessage: () => void;+}++// =============================================================================+// Hook+// =============================================================================++const SIXTY_FPS_MS = 1000 / 60;++export function useXDSChatStreamScroll({+ scrollRef,+ enabled = true,+ lockThreshold = 10,+ buttonThreshold = 100,+ damping = 0.7,+ stiffness = 0.05,+ mass = 1.25,+}: UseXDSChatStreamScrollOptions): UseXDSChatStreamScrollReturn {+ const [isScrolledUp, setIsScrolledUp] = useState(false);+ const [isLocked, setIsLocked] = useState(true);++ const lockedRef = useRef(true);+ const velocityRef = useRef(0);+ const animatingRef = useRef(false);+ const lastTickRef = useRef<number | undefined>(undefined);++ // For scroll direction detection+ const lastScrollTopRef = useRef(0);+ // For synthetic scroll detection+ const lastScrollHeightRef = useRef(0);+ const lastOffsetHeightRef = useRef(0);++ // --- Spring animation ---++ const animate = useCallback(() => {+ const el = scrollRef.current;+ if (!el || !lockedRef.current) {+ animatingRef.current = false;+ lastTickRef.current = undefined;+ velocityRef.current = 0;+ return;+ }++ if (el.scrollHeight <= el.clientHeight) {+ animatingRef.current = false;+ lastTickRef.current = undefined;+ velocityRef.current = 0;+ return;+ }++ const target = el.scrollHeight - el.clientHeight;+ const diff = target - el.scrollTop;++ if (Math.abs(diff) < 0.5 && Math.abs(velocityRef.current) < 0.1) {+ el.scrollTop = target;+ animatingRef.current = false;+ lastTickRef.current = undefined;+ velocityRef.current = 0;+ return;+ }++ const now = performance.now();+ const tickDelta = lastTickRef.current+ ? (now - lastTickRef.current) / SIXTY_FPS_MS+ : 1;+ lastTickRef.current = now;++ velocityRef.current =+ (damping * velocityRef.current + stiffness * diff) / mass;+ el.scrollTop += velocityRef.current * tickDelta;++ requestAnimationFrame(animate);+ }, [scrollRef, damping, stiffness, mass]);++ const startAnimation = useCallback(() => {+ if (!animatingRef.current && lockedRef.current) {+ animatingRef.current = true;+ lastTickRef.current = undefined;+ requestAnimationFrame(animate);+ }+ }, [animate]);++ // --- Public API ---++ const scrollToBottom = useCallback(() => {+ lockedRef.current = true;+ setIsLocked(true);+ setIsScrolledUp(false);+ startAnimation();+ }, [startAnimation]);++ const scrollToMessage = useCallback(+ (el: HTMLElement) => {+ const container = scrollRef.current;+ if (!container) return;+ const containerRect = container.getBoundingClientRect();+ const elRect = el.getBoundingClientRect();+ const offset = elRect.top - containerRect.top + container.scrollTop;+ container.scrollTo({top: offset, behavior: 'instant'});+ lastScrollTopRef.current = container.scrollTop;+ },+ [scrollRef],+ );++ const scrollToLastMessage = useCallback(() => {+ const container = scrollRef.current;+ if (!container) return;+ const messages = container.getElementsByClassName('xds-chat-message');+ const last = messages[messages.length - 1];+ if (last instanceof HTMLElement) {+ scrollToMessage(last);+ }+ }, [scrollRef, scrollToMessage]);++ const lock = useCallback(() => {+ lockedRef.current = true;+ setIsLocked(true);+ setIsScrolledUp(false);+ startAnimation();+ }, [startAnimation]);++ const unlock = useCallback(() => {+ lockedRef.current = false;+ animatingRef.current = false;+ setIsLocked(false);+ }, [scrollRef]);++ const scrollIfLocked = useCallback(() => {+ if (!enabled) return;+ if (lockedRef.current) {+ startAnimation();+ }+ }, [enabled, startAnimation]);++ // --- Event listeners ---++ useEffect(() => {+ const el = scrollRef.current;+ if (!el || !enabled) return;++ // Initialize tracking values+ lastScrollTopRef.current = el.scrollTop;+ lastScrollHeightRef.current = el.scrollHeight;+ lastOffsetHeightRef.current = el.offsetHeight;++ const onScroll = () => {+ const {scrollTop, scrollHeight, offsetHeight} = el;+ const dist = scrollHeight - scrollTop - offsetHeight;++ // Button visibility+ setIsScrolledUp(dist > buttonThreshold);++ // Detect synthetic scroll — Chrome fires scroll events when+ // scrollHeight or offsetHeight changes (content resize, keyboard).+ const scrollHeightChanged = scrollHeight !== lastScrollHeightRef.current;+ const offsetHeightChanged = offsetHeight !== lastOffsetHeightRef.current;+ lastScrollHeightRef.current = scrollHeight;+ lastOffsetHeightRef.current = offsetHeight;++ if (scrollHeightChanged || offsetHeightChanged) {+ // Synthetic scroll from resize — don't change lock state+ lastScrollTopRef.current = scrollTop;+ return;+ }++ // Scroll direction — unlock on scroll up+ const isScrollingUp = scrollTop < lastScrollTopRef.current;+ lastScrollTopRef.current = scrollTop;++ if (isScrollingUp && lockedRef.current) {+ lockedRef.current = false;+ animatingRef.current = false;+ setIsLocked(false);+ }+ };++ const onScrollEnd = () => {+ const dist = el.scrollHeight - el.scrollTop - el.offsetHeight;+ if (dist <= lockThreshold) {+ lockedRef.current = true;+ setIsLocked(true);+ }+ };++ // Wheel up while animating — interrupt immediately.+ // onScroll direction detection covers most cases, but wheel fires+ // before the scroll position updates so we can react faster.+ const onWheel = (e: WheelEvent) => {+ if (e.deltaY < 0 && animatingRef.current) {+ lockedRef.current = false;+ animatingRef.current = false;+ setIsLocked(false);+ }+ };++ // Touch move — user is dragging, take control+ const onTouchMove = () => {+ if (animatingRef.current) {+ lockedRef.current = false;+ animatingRef.current = false;+ setIsLocked(false);+ }+ };++ el.addEventListener('scroll', onScroll, {passive: true});+ el.addEventListener('scrollend', onScrollEnd);+ el.addEventListener('wheel', onWheel, {passive: true});+ el.addEventListener('touchmove', onTouchMove, {passive: true});++ // Initial scroll to bottom+ requestAnimationFrame(() => {+ if (el.scrollHeight > el.clientHeight) {+ el.scrollTop = el.scrollHeight - el.clientHeight;+ lastScrollTopRef.current = el.scrollTop;+ }+ });++ return () => {+ el.removeEventListener('scroll', onScroll);+ el.removeEventListener('scrollend', onScrollEnd);+ el.removeEventListener('wheel', onWheel);+ el.removeEventListener('touchmove', onTouchMove);+ };+ }, [scrollRef, enabled, lockThreshold, buttonThreshold]);++ return {+ isScrolledUp,+ isLocked,+ scrollToBottom,+ scrollToMessage,+ lock,+ unlock,+ scrollIfLocked,+ scrollToLastMessage,+ };+}