본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Chat - 스크롤링

원문 보기 위키 갱신

Chat - 스크롤링 (Scrolling)

자동 스크롤, scroll-to-bottom 어포던스(affordance), 스크롤 시 자동 과거 기록 로딩으로 새 메시지를 계속 볼 수 있게 해줘요.

출처: MUI X documentation

본문

인터랙티브 플레이그라운드 (Interactive playground)

scroll-to-bottom 어포던스를 실제로 사용해 보세요. 미리보기 안에서 위로 스크롤하면 '최신으로 이동(jump-to-latest)' 버튼이 나타나요. 각 scrollBehavior도 직접 시도해 볼 수 있어요.

import * as React from 'react';
import Alert from '@mui/material/Alert';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import type { SxProps, Theme } from '@mui/system';
import { ChatMessageList, ChatScrollToBottomAffordance } from '@mui/x-chat';
import {
  useChat,
  useChatStore,
  type ChatConversation,
  type ChatMessage,
} from '@mui/x-chat/headless';
import { PlaygroundCard } from 'docs/src/modules/components/chat-playground/PlaygroundCard';
import { ScopedChat } from 'docs/src/modules/components/chat-playground/sharedProviders';
import { MessageBubble } from 'docs/src/modules/components/chat-playground/MessageBubble';
import {
  ChoiceControl,
  DividerLabel,
  NumberControl,
} from 'docs/src/modules/components/chat-playground/controls';
import {
  useCustomizations,
  type CustomizationDef,
} from 'docs/src/modules/components/chat-playground/useCustomizations';
import { users } from 'docs/src/modules/components/chat-playground/data';

const conversation: ChatConversation = {
  id: 'scroll-playground',
  title: 'Scroll preview',
  participants: [users.me, users.assistant],
};

function buildMessages(count: number): ChatMessage[] {
  return Array.from({ length: count }, (_, i) => ({
    id: `scroll-msg-${i}`,
    conversationId: conversation.id,
    role: (i % 2 === 0 ? 'assistant' : 'user') as 'assistant' | 'user',
    author: i % 2 === 0 ? users.assistant : users.me,
    createdAt: new Date(Date.UTC(2026, 4, 3, 9, 0, i)).toISOString(),
    status: 'read',
    parts: [{ type: 'text', text: `Message ${i + 1} of ${count}` }],
  }));
}

function buildAppendedMessage(n: number): ChatMessage {
  return {
    id: `scroll-extra-${n}`,
    conversationId: conversation.id,
    role: 'assistant',
    author: users.assistant,
    createdAt: new Date(Date.UTC(2026, 4, 3, 10, 0, n)).toISOString(),
    status: 'read',
    parts: [
      {
        type: 'text',
        text: `New message #${n} arrived while you were scrolled up.`,
      },
    ],
  };
}

type ScrollBehavior = 'auto' | 'instant' | 'smooth';

type ClassKey = 'root';

const CLASS_DEFS: ReadonlyArray<CustomizationDef<ClassKey>> = [
  { name: 'root', description: 'The floating affordance button.' },
];

/**
 * Renders the live message list and appends a message on demand.
 *
 * The list is fed from live store state (`useChat().messages`), not the seed
 * array, so an appended message shows up as a pure append — which is what grows
 * the affordance's `unseenMessageCount` badge while the user is scrolled up.
 *
 * `appendRequest` is a counter owned by the parent (bumped by the "Append
 * message" button). Adding a message to a chat is a store operation, so we call
 * the public `useChatStore().addMessage()` from inside the provider rather than
 * plumbing a callback back out to the button. Each new counter value appends one
 * assistant message; `addMessage` is idempotent per id, so re-runs are harmless.
 */
function ScrollPreview({
  scrollBehavior,
  buttonSx,
  appendRequest,
}: ScrollPreviewProps) {
  const { messages: liveMessages } = useChat();
  const store = useChatStore();

  React.useEffect(() => {
    if (appendRequest > 0) {
      store.addMessage(buildAppendedMessage(appendRequest));
    }
  }, [store, appendRequest]);

  return (
    <Box
      sx={{
        width: '100%',
        height: 360,
        overflow: 'hidden',
        display: 'flex',
      }}
    >
      <ChatMessageList
        items={liveMessages.map((m) => m.id)}
        autoScroll={false}
        renderItem={({ id }) => <MessageBubble key={id} messageId={id} />}
        overlay={
          <ChatScrollToBottomAffordance
            scrollBehavior={scrollBehavior}
            sx={buttonSx}
          />
        }
      />
    </Box>
  );
}

interface ScrollPreviewProps {
  scrollBehavior: ScrollBehavior;
  buttonSx: SxProps<Theme>;
  appendRequest: number;
}

export default function ChatScrollToBottomAffordancePlayground() {
  const [count, setCount] = React.useState(20);
  const [scrollBehavior, setScrollBehavior] =
    React.useState<ScrollBehavior>('smooth');
  // Bumped by the "Append message" button; consumed by `ScrollPreview` inside
  // the provider to append one message to the live store.
  const [appendRequest, setAppendRequest] = React.useState(0);
  const classesCustomizations = useCustomizations<ClassKey>(CLASS_DEFS);
  const messages = React.useMemo(() => buildMessages(count), [count]);

  const buttonSx = classesCustomizations.toClassesSx();

  return (
    <PlaygroundCard
      title="ChatScrollToBottomAffordance"
      description="Floating jump-to-latest button — appears once the user scrolls away from the bottom."
      previewMinHeight={360}
      span={2}
      classCustomizations={classesCustomizations.customizations}
      onClassesReset={classesCustomizations.reset}
      controls={
        <React.Fragment>
          <DividerLabel>props</DividerLabel>
          <ChoiceControl<ScrollBehavior>
            label="scrollBehavior"
            value={scrollBehavior}
            options={['smooth', 'auto', 'instant'] as const}
            onChange={setScrollBehavior}
            helperText="ScrollIntoView behavior used when the button is clicked."
          />
          <DividerLabel>fixture data</DividerLabel>
          <NumberControl
            label="message count"
            value={count}
            min={5}
            max={60}
            // Changing the seed re-mounts the provider (see ScopedChat), which
            // discards any appended messages and resets scroll state. Reset the
            // append counter to match so the fresh provider starts clean.
            onChange={(next) => {
              setCount(next);
              setAppendRequest(0);
            }}
          />
          <Button
            variant="outlined"
            size="small"
            onClick={() => setAppendRequest((prev) => prev + 1)}
          >
            Append message
          </Button>
          <Alert severity="info" sx={{ fontSize: '0.75rem', py: 0 }}>
            Scroll up inside the preview to make the affordance appear. Auto-scroll
            is disabled in this preview so the affordance stays reachable. Append
            messages while scrolled up to see the unseen-count badge.
          </Alert>
        </React.Fragment>
      }
      preview={
        <ScopedChat
          conversations={[conversation]}
          messages={messages}
          activeConversationId={conversation.id}
        >
          <ScrollPreview
            scrollBehavior={scrollBehavior}
            buttonSx={buttonSx}
            appendRequest={appendRequest}
          />
        </ScopedChat>
      }
    />
  );
}

메시지 목록은 사용자의 개입 없이도 새 메시지와 스트리밍 콘텐츠가 계속 보이도록 스크롤 위치를 자동 관리해요. 사용자는 여전히 위로 스크롤해 이전 메시지를 읽을 수 있고 위치를 잃지 않아요.

자동 스크롤 (Auto-scrolling)

메시지 목록은 다음 경우에 자동으로 아래로 스크롤돼요:

  • 사용자가 새 메시지를 보낼 때 (설정과 무관하게 항상 활성).
  • 사용자가 바닥 근처에 있는 동안 어시스턴트로부터 새 메시지가 도착할 때.
  • 스트리밍 콘텐츠가 커질 때 (토큰 단위 갱신).

자동 스크롤 동작은 **버퍼(buffer)**로 제어돼요. 사용자가 바닥에서 buffer 픽셀보다 더 멀리 스크롤하면, 사용자가 이전 메시지를 방해받지 않고 읽을 수 있도록 자동 스크롤이 멈춰요. 동일한 버퍼가 메시지 목록의 onReachBottom 콜백에 대한 하단 영역을 정의하며, 뷰포트가 그 영역에 들어갈 때마다 한 번씩 호출돼요.

구성 (Configuration)

ChatBox의 features prop으로 자동 스크롤을 제어해요. 기본 버퍼는 150px예요:

// Default — auto-scroll on with a 150px buffer
<ChatBox adapter={adapter} />

// Custom 300px buffer threshold
<ChatBox adapter={adapter} features={{ autoScroll: { buffer: 300 } }} />

// Disable auto-scroll entirely
<ChatBox adapter={adapter} features={{ autoScroll: false }} />

자동 스크롤이 비활성화되면 사용자는 여전히 scroll-to-bottom 어포던스를 사용해 수동으로 바닥까지 스크롤할 수 있어요.

메시지를 보내고, 긴 답변이 스트리밍되는 동안 위로 스크롤해 보세요. 바닥에서 buffer 픽셀보다 멀어지면 자동 스크롤이 멈추고, 다시 그 안으로 스크롤하면 재개돼요.

'use client';
import * as React from 'react';
import Box from '@mui/material/Box';
import FormControlLabel from '@mui/material/FormControlLabel';
import Stack from '@mui/material/Stack';
import Switch from '@mui/material/Switch';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import Typography from '@mui/material/Typography';
import { ChatBox } from '@mui/x-chat';
import type { ChatMessage } from '@mui/x-chat/headless';
import { createEchoAdapter } from 'docs/data/chat/core/examples/shared/demoUtils';
import {
  createTextMessage,
  demoUsers,
  minimalConversation,
} from 'docs/data/chat/core/examples/shared/demoData';

// A handful of short messages so the list overflows and there is room to scroll
// up while a reply streams in.
const filler: ChatMessage[] = Array.from({ length: 12 }, (_, i) =>
  createTextMessage({
    id: `buffer-msg-${i}`,
    conversationId: minimalConversation.id,
    role: i % 2 === 0 ? 'user' : 'assistant',
    createdAt: new Date(Date.UTC(2026, 2, 15, 9, 30, i)).toISOString(),
    text:
      i % 2 === 0
        ? `Question ${i / 2 + 1}: how does the buffer threshold work?`
        : `Answer ${Math.ceil(i / 2)}: auto-scroll keeps following until you scroll past it.`,
  }),
);

const initialMessages: ChatMessage[] = filler;

// A long, multi-sentence reply so streaming lasts long enough to scroll during it.
const longReply = [
  'Auto-scroll keeps the newest content in view while a response streams in.',
  'It only follows along while you stay close to the bottom of the list.',
  'The buffer is the distance, in pixels, from the bottom where following stops.',
  'Scroll up past the buffer and the list stops chasing the stream.',
  'That lets you read earlier messages without the view yanking back down.',
  'Scroll back within the buffer and auto-scroll resumes immediately.',
  'A larger buffer keeps following even when you nudge the list up a little.',
  'A smaller buffer pauses sooner, the moment you start scrolling away.',
  'When auto-scroll is off, the stream never moves the viewport for you.',
  'Use the scroll-to-bottom affordance to jump back to the latest message.',
].join(' ');

const adapter = createEchoAdapter({
  agent: demoUsers.agent,
  delayMs: 120,
  respond: () => longReply,
});

type Buffer = 150 | 300 | 600;

export default function AutoScrollBuffer() {
  const [autoScroll, setAutoScroll] = React.useState(true);
  const [buffer, setBuffer] = React.useState<Buffer>(150);

  return (
    <Box sx={{ width: '100%', maxWidth: 560, mx: 'auto' }}>
      <Stack
        spacing={2}
        sx={{
          mb: 1.5,
          flexDirection: { xs: 'column', sm: 'row' },
          alignItems: { xs: 'flex-start', sm: 'center' },
        }}
      >
        <FormControlLabel
          control={
            <Switch
              checked={autoScroll}
              onChange={(event) => setAutoScroll(event.target.checked)}
            />
          }
          label="Auto-scroll"
        />
        <div>
          <Typography variant="caption" color="text.secondary" component="div">
            buffer (px)
          </Typography>
          <ToggleButtonGroup
            exclusive
            size="small"
            value={buffer}
            disabled={!autoScroll}
            onChange={(_event, next) => {
              if (next != null) {
                setBuffer(next);
              }
            }}
          >
            <ToggleButton value={150}>150</ToggleButton>
            <ToggleButton value={300}>300</ToggleButton>
            <ToggleButton value={600}>600</ToggleButton>
          </ToggleButtonGroup>
        </div>
      </Stack>
      <ChatBox
        adapter={adapter}
        initialActiveConversationId={minimalConversation.id}
        initialConversations={[minimalConversation]}
        initialMessages={initialMessages}
        features={{ autoScroll: autoScroll ? { buffer } : false }}
        sx={{
          height: 420,
          border: '1px solid',
          borderColor: 'divider',
          borderRadius: 1,
        }}
      />
    </Box>
  );
}

:::info 사용자가 메시지를 보낼 때 바닥으로 스크롤하는 것은 autoScroll 설정과 관계없이 항상 활성화돼요. :::

Scroll-to-bottom 어포던스 (Scroll-to-bottom affordance)

사용자가 바닥에서 멀리 스크롤하면 떠 있는 버튼이 나타나요. 클릭하면 최신 메시지로 부드럽게 스크롤돼요. 이 페이지 상단의 인터랙티브 플레이그라운드에서 직접 시도해 보세요.

어포던스는 기본적으로 활성화돼 있어요. 다음과 같이 비활성화할 수 있어요:

<ChatBox adapter={adapter} features={{ scrollToBottom: false }} />

이 어포던스는 읽지 않은 메시지 수 배지와, 그 수가 있을 때 포함하는 aria-label도 지원해요.

어포던스의 접근 가능한 이름은 scrollToBottomLabel과 scrollToBottomWithCountLabel 로케일 문자열에서 가져와요 — 번역 방법은 Localization 문서를 참고하세요. 메시지 목록은 또한 시각적으로 숨겨진 role="status" 라이브 영역(messageListStatus 슬롯)도 렌더링해서, 스트리밍 응답의 시작과 완료를 스크린 리더에 알려줘요. 전체 키보드 및 스크린 리더 모델은 Accessibility 페이지와 Message list—Accessibility를 참고하세요.

ref로 프로그래밍 방식으로 스크롤하기 (Scrolling programmatically with a ref)

ChatMessageList 컴포넌트는 프로그래밍 방식 스크롤 제어를 위한 ref 핸들을 제공해요:

import { ChatMessageList } from '@mui/x-chat';
import type { MessageListRootHandle } from '@mui/x-chat/headless';

const listRef = React.useRef<MessageListRootHandle>(null);

// Scroll to bottom programmatically
listRef.current?.scrollToBottom({ behavior: 'smooth' });

<ChatMessageList ref={listRef} />;

자식 컴포넌트에서 스크롤 상태 접근 (Accessing scroll state from child components)

메시지 목록 안의 자식 컴포넌트는 컨텍스트를 통해 스크롤 상태에 접근할 수 있어요:

import { useMessageListContext } from '@mui/x-chat/headless';

function CustomScrollIndicator() {
  const { isAtBottom, unseenMessageCount, scrollToBottom } = useMessageListContext();

  if (isAtBottom) return null;
  return (
    <button onClick={() => scrollToBottom({ behavior: 'smooth' })}>
      {unseenMessageCount} new messages
    </button>
  );
}
Property Type Description
isAtBottom boolean Whether the scroll position is at the bottom
unseenMessageCount number Messages added since the user scrolled away
scrollToBottom (options?) => void Scroll to the latest message

메시지 기록 로딩 (Loading message history)

사용자가 메시지 목록의 맨 위로 스크롤하면, adapter의 listMessages 메서드를 통해 이전 메시지들이 자동으로 로드돼요. 메시지 목록은 prepend 중에 현재 스크롤 위치를 유지해 사용자가 위치를 잃지 않게 해줘요.

:::success 기록을 prepend해도 스크롤 점프가 절대 발생하지 않아요. 목록은 첫 번째 보이는 메시지에 고정되고, 이전 메시지들이 렌더링된 후 위치를 복원해요. :::

adapter는 hasMore 플래그로 더 많은 기록이 있는지 여부를 알려줘요:

async listMessages({ conversationId, cursor }) {
  const res = await fetch(`/api/conversations/${conversationId}/messages?cursor=${cursor ?? ''}`);
  const { messages, nextCursor, hasMore } = await res.json();
  return { messages, cursor: nextCursor, hasMore };
},

hasMore가 true면 메시지 목록은 사용자가 위로 스크롤할 때 계속 이전 메시지를 로드해요. hasMore가 false면 사용자가 맨 위에 도달해도 더 이상 기록을 요청하지 않아요.

기록 로딩 상태를 프로그래밍 방식으로 확인할 수도 있어요:

const { hasMoreHistory, loadMoreHistory } = useChat();

// Trigger manually if needed
await loadMoreHistory();

추가 자료 (See also)

  • Message list — 날짜 구분선, 그룹화, 밀도에 대한 자세한 내용
  • Streaming — 자동 스크롤이 스트리밍 콘텐츠를 따라가는 방법
  • Adapter — 기록 로딩을 담당하는 listMessages 메서드

ChatMessageList API

데모 (Demos)

이 React 컴포넌트의 사용 예시와 자세한 내용은 컴포넌트 데모 페이지를 참고하세요:

임포트 (Import)

import { ChatMessageList } from '@mui/x-chat/ChatMessageList';
// or
import { ChatMessageList } from '@mui/x-chat';

Props

Name Type Default Required Description
autoScroll { buffer?: number } | bool true No
enableRovingFocus bool true No
features { dateDivider?: bool, streamingIndicator?: 'auto' | bool, unreadMarker?: bool } - No
onReachBottom func - No
onReachTop func - No
overlay node null No
renderItem func - No

Note: The ref is forwarded to the root element.

Any other props supplied will be provided to the root element (native element).

CSS

규칙 이름 (Rule name)

Global class Rule name Description
- content Styles applied to the message list content element.
- root Styles applied to the message list root element.
- scroller Styles applied to the message list scroller element.

소스 코드 (Source code)

이 페이지에서 원하는 정보를 찾지 못했다면, 컴포넌트 구현을 직접 살펴보면 더 자세한 내용을 확인할 수 있어요.

ChatScrollToBottomAffordance API

데모 (Demos)

이 React 컴포넌트의 사용 예시와 자세한 내용은 컴포넌트 데모 페이지를 참고하세요:

임포트 (Import)

import { ChatScrollToBottomAffordance } from '@mui/x-chat/ChatIndicators';
// or
import { ChatScrollToBottomAffordance } from '@mui/x-chat';

Note: The ref is forwarded to the root element.

Any other props supplied will be provided to the root element (native element).

CSS

규칙 이름 (Rule name)

Global class Rule name Description
- root Styles applied to the root element.

소스 코드 (Source code)

이 페이지에서 원하는 정보를 찾지 못했다면, 컴포넌트 구현을 직접 살펴보면 더 자세한 내용을 확인할 수 있어요.

더 알아보기 (Learn more)