An open source design system that's fully customizable and agent ready
TypeScript
feat(Chat): scroll-to-bottom button with streaming label expansion (#1191)
Cindy Zhang1c69d2fb7a63
diff --git a/apps/storybook/stories/Chat.stories.tsx b/apps/storybook/stories/Chat.stories.tsxindex f67c3b101d..ea8f2078ac 100644--- a/apps/storybook/stories/Chat.stories.tsx+++ b/apps/storybook/stories/Chat.stories.tsx@@ -610,3 +610,60 @@ For server state, use a library like **TanStack Query** or **SWR**.`}</XDSMarkdo</div>),};++export const ScrollToBottom: StoryObj = {+ name: 'Scroll to Bottom',+ render: () => {+ const [messages, setMessages] = useState(+ Array.from({length: 30}, (_, i) => ({+ id: i + 1,+ sender: i % 2 === 0 ? ('user' as const) : ('assistant' as const),+ text:+ i % 2 === 0+ ? `User message #${i + 1}`+ : `This is assistant response #${i + 1}. It has enough content to require scrolling through the message list.`,+ })),+ );++ const addNewMessage = useCallback(() => {+ setMessages(prev => [+ ...prev,+ {+ id: prev.length + 1,+ sender: 'assistant' as const,+ text: `New message arrived at ${new Date().toLocaleTimeString()}. Scroll up to see the button expand with a "New messages" label.`,+ },+ ]);+ }, []);++ return (+ <div style={{height: 400, display: 'flex', flexDirection: 'column'}}>+ <div+ style={{+ padding: '8px 16px',+ borderBottom: '1px solid var(--color-border)',+ display: 'flex',+ gap: 8,+ alignItems: 'center',+ }}>+ <XDSButton+ label="Add message"+ variant="secondary"+ size="sm"+ onClick={addNewMessage}+ />+ <span style={{fontSize: 12, color: 'var(--color-text-secondary)'}}>+ Scroll up, then click "Add message" to see the button expand+ </span>+ </div>+ <XDSChatMessageList>+ {messages.map(msg => (+ <XDSChatMessage key={msg.id} sender={msg.sender}>+ <XDSChatMessageBubble>{msg.text}</XDSChatMessageBubble>+ </XDSChatMessage>+ ))}+ </XDSChatMessageList>+ </div>+ );+ },+};diff --git a/packages/core/src/Chat/XDSChatMessageList.test.tsx b/packages/core/src/Chat/XDSChatMessageList.test.tsxindex 8d3b96ab8b..075a540eef 100644--- a/packages/core/src/Chat/XDSChatMessageList.test.tsx+++ b/packages/core/src/Chat/XDSChatMessageList.test.tsx@@ -54,13 +54,13 @@ describe('XDSChatMessageList', () => {expect(screen.getByTestId('chat-list')).toBeTruthy();});- it('has new messages button (hidden by default)', () => {+ it('has scroll-to-bottom button (hidden by default)', () => {render(<XDSChatMessageList><div>msg</div></XDSChatMessageList>,);- const button = screen.getByLabelText(/New messages/);+ const button = screen.getByRole('button', {name: /Scroll to bottom/});expect(button).toBeTruthy();});});diff --git a/packages/core/src/Chat/XDSChatMessageList.tsx b/packages/core/src/Chat/XDSChatMessageList.tsxindex e118584381..67cf49627f 100644--- a/packages/core/src/Chat/XDSChatMessageList.tsx+++ b/packages/core/src/Chat/XDSChatMessageList.tsx@@ -2,13 +2,14 @@/*** @file XDSChatMessageList.tsx- * @input Uses React, StyleX, XDSChatListContext, XDSButton, theme tokens+ * @input Uses React, StyleX, XDSChatListContext, XDSIcon, theme tokens, useAutoScroll* @output Exports XDSChatMessageList component and XDSChatMessageListProps* @position Scrollable message container — holds XDSChatMessage children with auto-scroll** Renders a scrollable container with role="log" for chat message histories.- * Handles auto-scroll (pins to bottom during streaming), a "New messages"- * indicator when scrolled up, and onScrollToTopAction for infinite scroll.+ * Handles auto-scroll (pins to bottom during streaming), a floating+ * scroll-to-bottom button when scrolled up, and a "New messages" label+ * that expands into the button via width animation when new content arrives.** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/Chat/index.ts (exports)@@ -29,14 +30,15 @@ import {colorVars,spacingVars,radiusVars,- typeScaleVars,- fontWeightVars,durationVars,easeVars,+ shadowVars,} from '../theme/tokens.stylex';import {XDSChatListContext, type XDSChatDensity} from './XDSChatContext';import {xdsClassName, mergeProps} from '../utils';import {XDSSpinner} from '../Spinner';+import {XDSIcon} from '../Icon';+import {XDSButton} from '../Button';import {useAutoScroll} from './useAutoScroll';export interface XDSChatMessageListProps {@@ -65,6 +67,19 @@ export interface XDSChatMessageListProps {*/scrollThreshold?: number;+ /**+ * Distance from bottom (in px) beyond which the scroll-to-bottom button appears.+ * @default 100+ */+ scrollUpThreshold?: number;++ /**+ * Label shown in the scroll-to-bottom button when new messages arrive.+ * Revealed via a width animation on the button.+ * @default 'New messages'+ */+ newMessagesLabel?: string;+/*** Custom content when the list has no messages.*/@@ -147,39 +162,52 @@ const styles = stylex.create({justifyContent: 'center',paddingBlock: spacingVars['--spacing-3'],},- newMessagesButton: {++ // --- Scroll-to-bottom button ---+ // Container controls dimensions and clips content. The XDSButton inside+ // is always full-size; the container's width transition reveals the label.+ // Opaque popover bg on the container prevents hover tint bleed-through.+ // `contain: layout style` isolates reflow from the scroll area.+ scrollButtonContainer: {position: 'absolute',bottom: spacingVars['--spacing-3'],left: '50%',- transform: 'translateX(-50%)',- display: 'inline-flex',- alignItems: 'center',- gap: spacingVars['--spacing-1'],- paddingBlock: spacingVars['--spacing-1-5'],- paddingInline: spacingVars['--spacing-3'],- backgroundColor: colorVars['--color-accent'],- color: colorVars['--color-on-accent'],- border: 'none',+ contain: 'layout style',+ overflow: 'hidden',borderRadius: radiusVars['--radius-full'],- cursor: 'pointer',- fontSize: typeScaleVars['--text-supporting-size'],- fontWeight: fontWeightVars['--font-weight-semibold'],- boxShadow: '0 2px 8px rgba(0,0,0,0.15)',- transitionProperty: 'opacity, transform',- transitionDuration: durationVars['--duration-fast'],- transitionTimingFunction: easeVars['--ease-standard'],+ backgroundColor: colorVars['--color-background-popover'],+ boxShadow: shadowVars['--shadow-med'],+ height: '32px',zIndex: 1,+ transitionProperty: 'opacity, transform, max-width',+ transitionTimingFunction: easeVars['--ease-standard'],+ transitionDuration: durationVars['--duration-fast-max'],},- newMessagesHidden: {+ scrollButtonContainerHidden: {opacity: 0,pointerEvents: 'none',+ maxWidth: '32px',transform: 'translate(-50%, 8px)',+ transitionDelay: '0ms',},- newMessagesVisible: {+ scrollButtonContainerVisible: {opacity: 1,pointerEvents: 'auto',transform: 'translate(-50%, 0)',+ transitionDelay: '150ms',+ },+ scrollButtonCollapsed: {+ maxWidth: '32px',},+ scrollButtonExpanded: {+ maxWidth: '200px',+ },+ scrollButton: {+ [radiusVars['--radius-element'] as string]: radiusVars['--radius-full'],+ whiteSpace: 'nowrap',+ paddingInline: spacingVars['--spacing-2'],+ },+emptyState: {display: 'flex',alignItems: 'center',@@ -189,6 +217,59 @@ const styles = stylex.create({},});+// =============================================================================+// Sub-components+// =============================================================================++/**+ * Animated scroll-to-bottom button.+ *+ * - Icon-only ghost XDSButton (chevron down) when the user is scrolled up+ * - Expands via max-width animation to reveal label when new messages arrive+ * - Container provides opaque popover surface so ghost hover tint doesn't bleed+ *+ * Structure: container (positioning, fade, opaque surface) → XDSButton (ghost)+ * The label is always in the DOM but clipped by `max-width: 0` + `overflow: hidden`.+ * `contain: layout style` on the container isolates reflow from the scroll area.+ */+function ScrollToBottomButton({+ isScrolledUp,+ hasNewMessages,+ label,+ onClick,+}: {+ isScrolledUp: boolean;+ hasNewMessages: boolean;+ label: string;+ onClick: () => void;+}) {+ const isVisible = isScrolledUp || hasNewMessages;++ return (+ <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}>+ {label}+ </XDSButton>+ </div>+ );+}+// =============================================================================// Component// =============================================================================@@ -196,13 +277,16 @@ const styles = stylex.create({/*** Scrollable container for chat messages with auto-scroll and infinite scroll support.*- * Pins to the bottom when the user is near the end. Shows a "New messages" button- * when scrolled up. Supports loading older messages via `onScrollToTopAction`.+ * Pins to the bottom when the user is near the end. Shows a muted+ * scroll-to-bottom icon button when scrolled up. When new messages+ * arrive while scrolled up, the button expands to show a+ * "New messages" label. Supports loading older messages via+ * `onScrollToTopAction`.** @example* ```* <XDSChatMessageList>- * <XDSChatMessage sender="assistant" name="Navi" avatar={<XDSAvatar name="Navi" size="sm" />}>+ * <XDSChatMessage sender="assistant" name="Navi" avatar={<XDSAvatar name="Navi" size="md" />}>* <XDSChatMessageBubble>Hello!</XDSChatMessageBubble>* </XDSChatMessage>* <XDSChatMessage sender="user" name="Cindy">@@ -215,6 +299,8 @@ export function XDSChatMessageList({children,hasAutoScroll = true,scrollThreshold = 12,+ scrollUpThreshold = 100,+ newMessagesLabel = 'New messages',emptyState,onScrollToTopAction,density = 'balanced',@@ -226,11 +312,17 @@ export function XDSChatMessageList({}: XDSChatMessageListProps) {const {scrollRef,- showNewMessages,+ isScrolledUp,+ hasNewMessages,handleScroll,+ scrollToBottom,dismissNewMessages,onContentChange,- } = useAutoScroll({enabled: hasAutoScroll, threshold: scrollThreshold});+ } = useAutoScroll({+ enabled: hasAutoScroll,+ threshold: scrollThreshold,+ scrollUpThreshold,+ });const sentinelRef = useRef<HTMLDivElement>(null);const [isLoadingTop, startTransition] = useTransition();@@ -288,6 +380,15 @@ export function XDSChatMessageList({[ref, scrollRef],);+ // Click handler: dismiss new messages (scrolls to bottom) or just scroll+ const handleButtonClick = useCallback(() => {+ if (hasNewMessages) {+ dismissNewMessages();+ } else {+ scrollToBottom();+ }+ }, [hasNewMessages, dismissNewMessages, scrollToBottom]);+return (<XDSChatListContext.Provider value={contextValue}><div {...stylex.props(styles.outer)}>@@ -311,7 +412,7 @@ export function XDSChatMessageList({{/* Loading spinner at top */}{isLoadingTop && (<div {...stylex.props(styles.loadingTop)}>- <XDSSpinner size="sm" />+ <XDSSpinner size="md" /></div>)}@@ -327,19 +428,13 @@ export function XDSChatMessageList({</div></div>- {/* New messages button */}- <button- type="button"- aria-label="New messages — scroll to bottom"- onClick={dismissNewMessages}- {...stylex.props(- styles.newMessagesButton,- showNewMessages- ? styles.newMessagesVisible- : styles.newMessagesHidden,- )}>- New messages ↓- </button>+ {/* Scroll-to-bottom button: icon-only when scrolled up, expands with label on new messages */}+ <ScrollToBottomButton+ isScrolledUp={isScrolledUp}+ hasNewMessages={hasNewMessages}+ label={newMessagesLabel}+ onClick={handleButtonClick}+ /></div></XDSChatListContext.Provider>);diff --git a/packages/core/src/Chat/useAutoScroll.ts b/packages/core/src/Chat/useAutoScroll.tsindex abcb592255..2e4d2cccf0 100644--- a/packages/core/src/Chat/useAutoScroll.ts+++ b/packages/core/src/Chat/useAutoScroll.ts@@ -5,13 +5,24 @@* @input Uses React refs, state, and effects* @output Exports useAutoScroll hook for scroll-pinning behavior* @position Utility hook — used by XDSChatMessageList, also usable standalone+ *+ * Exposes two scroll states:+ * - `isScrolledUp` — true when the user has scrolled away from the bottom+ * (beyond `scrollUpThreshold`), regardless of whether new content arrived.+ * Drives a scroll-to-bottom affordance.+ * - `hasNewMessages` — true when new content arrived while scrolled up.+ * Layers on top of isScrolledUp to add a "new messages" notification.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Chat/index.ts (exports)+ * - /packages/core/src/Chat/XDSChatMessageList.tsx (consumer)*/import {useCallback, useEffect, useRef, useState} from 'react';export interface UseAutoScrollOptions {/**- * Whether auto-scroll is enabled.+ * Whether auto-scroll behavior is enabled.* @default true*/enabled?: boolean;@@ -21,14 +32,24 @@ export interface UseAutoScrollOptions {* @default 12*/threshold?: number;++ /**+ * Distance from bottom (in px) beyond which `isScrolledUp` becomes true.+ * Controls when the scroll-to-bottom button appears.+ * @default 100+ */+ scrollUpThreshold?: number;}export interface UseAutoScrollReturn {/** Ref to attach to the scrollable container element. */scrollRef: React.RefObject<HTMLDivElement | null>;- /** Whether the "new messages" indicator should be shown. */- showNewMessages: boolean;+ /** Whether the user has scrolled up beyond `scrollUpThreshold`. */+ isScrolledUp: boolean;++ /** Whether new content arrived while the user is scrolled up. */+ hasNewMessages: boolean;/** Scroll handler — attach to onScroll on the scrollable element. */handleScroll: () => void;@@ -46,17 +67,20 @@ export interface UseAutoScrollReturn {/*** Hook that manages auto-scroll behavior for scrollable containers.*- * Pins to the bottom when the user is near the end. Shows a "new messages"- * indicator when new content arrives while scrolled up.+ * Pins to the bottom when the user is near the end. Tracks two+ * orthogonal states: whether the user has scrolled up (for a+ * scroll-to-bottom affordance) and whether new content arrived+ * while scrolled up (for a "new messages" notification).** @example* ```- * const {scrollRef, showNewMessages, handleScroll, dismissNewMessages} = useAutoScroll();+ * const {scrollRef, isScrolledUp, hasNewMessages, handleScroll, scrollToBottom, dismissNewMessages} = useAutoScroll();** return (* <div ref={scrollRef} onScroll={handleScroll}>* {messages}- * {showNewMessages && <button onClick={dismissNewMessages}>New messages</button>}+ * {isScrolledUp && <button onClick={scrollToBottom}>↓</button>}+ * {hasNewMessages && <button onClick={dismissNewMessages}>New messages</button>}* </div>* );* ```@@ -64,9 +88,11 @@ export interface UseAutoScrollReturn {export function useAutoScroll({enabled = true,threshold = 12,+ scrollUpThreshold = 100,}: UseAutoScrollOptions = {}): UseAutoScrollReturn {const scrollRef = useRef<HTMLDivElement | null>(null);- const [showNewMessages, setShowNewMessages] = useState(false);+ const [hasNewMessages, setHasNewMessages] = useState(false);+ const [isScrolledUp, setIsScrolledUp] = useState(false);const isNearBottomRef = useRef(true);const scrollToBottom = useCallback((smooth = true) => {@@ -82,33 +108,33 @@ export function useAutoScroll({}}, []);- const checkNearBottom = useCallback(() => {+ const handleScroll = useCallback(() => {const el = scrollRef.current;- if (!el) return true;+ if (!el) return;const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;- return distanceFromBottom <= threshold;- }, [threshold]);-- const handleScroll = useCallback(() => {- const nearBottom = checkNearBottom();+ const nearBottom = distanceFromBottom <= threshold;isNearBottomRef.current = nearBottom;++ // Track whether user is scrolled up beyond the visible threshold+ setIsScrolledUp(distanceFromBottom > scrollUpThreshold);+if (nearBottom) {- setShowNewMessages(false);+ setHasNewMessages(false);}- }, [checkNearBottom]);+ }, [threshold, scrollUpThreshold]);const onContentChange = useCallback(() => {if (!enabled) return;if (isNearBottomRef.current) {scrollToBottom(true);} else {- setShowNewMessages(true);+ setHasNewMessages(true);}}, [enabled, scrollToBottom]);const dismissNewMessages = useCallback(() => {scrollToBottom();- setShowNewMessages(false);+ setHasNewMessages(false);}, [scrollToBottom]);// Scroll to bottom on mount@@ -118,7 +144,8 @@ export function useAutoScroll({return {scrollRef,- showNewMessages,+ isScrolledUp,+ hasNewMessages,handleScroll,scrollToBottom,dismissNewMessages,