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

Chat - 레이아웃(Layout)

원문 보기 위키 갱신

채팅 서피스에서 대화(conversation)와 스레드(thread) 패널을 구성하고, 레이아웃과 반응형 동작을 완전히 제어할 수 있어요.

출처: MUI X documentation

본문

개요(Overview)

ChatLayout은 채팅 서피스에서 대화 패널(conversation pane) 과 스레드 패널(thread pane) 을 배치해요. 주변의 런타임 설정은 ChatProvider에 위임되며, 패널 내용을 자식으로 제공하면 ChatLayout은 각 자식을 패널에 할당하고 배치할 뿐이에요.

구성 구조

가장 일반적인 ChatLayout 구성은 다음과 같아요:

ChatLayout
  ChatConversationList              ← 대화 항목이 있는 사이드바
  ChatConversation                  ← 스레드 셸(shell), 활성 대화를 파생
    ChatConversationHeader          ← 구분선 스타일이 있는 헤더 바
      ChatConversationTitle         ← 대화 이름
      ChatConversationSubtitle      ← 보조 줄(참여자, 상태 등)
      ChatConversationHeaderActions ← 동작 영역(보관, 음소거, 컨텍스트 메뉴)
    ChatMessageList                 ← 스크롤 가능한 메시지 영역
      ChatMessageGroup              ← 같은 작성자의 연속 메시지를 그룹화
        ChatMessage                 ← 개별 메시지 행
          ChatMessageAvatar         ← 작성자 아바타
          ChatMessageContent        ← 버블(bubble) + 내부 파트 렌더러
          ChatMessageMeta           ← 타임스탬프, 상태 표시기
          ChatMessageActions        ← 호버 동작 메뉴
    ChatComposer                    ← 컴포저 폼 (border-top)
      ChatComposerTextArea          ← 자동 크기 조절 textarea
      ChatComposerToolbar           ← 버튼 행
        ChatComposerAttachButton
        ChatComposerSendButton

ChatLayout은 @mui/x-chat/headless에서 내보내지며, 트리에서 그 아래의 모든 컴포넌트는 @mui/x-chat에서 내보내져요.

두 패널 레이아웃

기본 구성은 대화 목록과 활성 스레드를 나란히 렌더링해요. 사이드바에서 대화를 선택해 스레드를 전환하세요:

'use client';
import * as React from 'react';
import AttachIcon from '@mui/icons-material/AttachFile';
import SendIcon from '@mui/icons-material/Send';
import Box from '@mui/material/Box';
import {
  ChatComposer,
  ChatComposerAttachButton,
  ChatComposerSendButton,
  ChatComposerTextArea,
  ChatComposerToolbar,
  ChatConversation,
  ChatConversationHeader,
  ChatConversationList,
  ChatConversationSubtitle,
  ChatConversationTitle,
  ChatMessageGroup,
  ChatMessageList,
} from '@mui/x-chat';
import { ChatLayout, ChatProvider } from '@mui/x-chat/headless';
import type {
  ChatConversation as ChatConversationModel,
  ChatMessage,
} from '@mui/x-chat/headless';
import {
  createEchoAdapter,
  syncConversationPreview,
} from 'docs/data/chat/core/examples/shared/demoUtils';
import {
  inboxConversations,
  inboxThreads,
} from 'docs/data/chat/core/examples/shared/demoData';

const adapter = createEchoAdapter({
  respond: (text) =>
    `Received: "${text}". This demo renders ChatLayout with an explicit conversation pane and thread pane.`,
});

export default function LayoutTwoPaneStandalone() {
  const [activeConversationId, setActiveConversationId] = React.useState(
    () => inboxConversations[0].id,
  );
  const [conversations, setConversations] = React.useState<ChatConversationModel[]>(
    () => inboxConversations.map((conversation) => ({ ...conversation })),
  );
  const [threads, setThreads] = React.useState<Record<string, ChatMessage[]>>(() =>
    Object.fromEntries(
      Object.entries(inboxThreads).map(([id, messages]) => [
        id,
        messages.map((message) => ({ ...message })),
      ]),
    ),
  );

  const messages = threads[activeConversationId] ?? [];

  const renderItem = React.useCallback(
    (params: { id: string }) => (
      <ChatMessageGroup key={params.id} messageId={params.id} />
    ),
    [],
  );

  return (
    <ChatProvider
      adapter={adapter}
      activeConversationId={activeConversationId}
      conversations={conversations}
      messages={messages}
      onActiveConversationChange={(nextId) => {
        if (nextId) {
          setActiveConversationId(nextId);
        }
      }}
      onMessagesChange={(nextMessages) => {
        setThreads((prev) => ({
          ...prev,
          [activeConversationId]: nextMessages,
        }));
        setConversations((prev) =>
          syncConversationPreview(prev, activeConversationId, nextMessages),
        );
      }}
      onConversationsChange={setConversations}
    >
      <Box
        sx={{
          height: 500,
          overflow: 'hidden',
        }}
      >
        <ChatLayout
          style={{ height: '100%' }}
          slotProps={{
            conversationsPane: {
              style: {
                width: '280px',
                flex: '0 0 280px',
              },
            },
          }}
        >
          <ChatConversationList
            slotProps={{ root: { 'aria-label': 'Conversations' } }}
          />
          <ChatConversation>
            <ChatConversationHeader>
              <Box sx={{ minWidth: 0 }}>
                <ChatConversationTitle />
                <ChatConversationSubtitle />
              </Box>
            </ChatConversationHeader>
            <ChatMessageList renderItem={renderItem} />
            <ChatComposer>
              <ChatComposerTextArea
                aria-label="Message"
                placeholder="Type a message…"
              />
              <ChatComposerToolbar>
                <ChatComposerAttachButton>
                  <AttachIcon />
                </ChatComposerAttachButton>
                <ChatComposerSendButton>
                  <SendIcon />
                </ChatComposerSendButton>
              </ChatComposerToolbar>
            </ChatComposer>
          </ChatConversation>
        </ChatLayout>
      </Box>
    </ChatProvider>
  );
}

패널 크기 조정

ChatLayout은 각 패널을 슬롯으로 감싸요: conversationsPane과 threadPane(플렉스 컨테이너용 root 포함). 기본적으로 스레드 패널은 남은 너비를 채우도록 flex가 적용돼요. slotProps를 사용해 고정된 사이드바 너비를 설정하세요:

<ChatLayout
  slotProps={{
    conversationsPane: { style: { width: '280px', flex: '0 0 280px' } },
  }}
>

각 패널 슬롯은 pane 소유 상태('conversations' 또는 'thread')를 받으므로, 커스텀 슬롯 컴포넌트가 하나의 구현으로 두 패널을 모두 스타일링할 수 있어요.

스레드 전용 모드

애플리케이션이 대화를 외부에서 관리할 때는 ChatLayout 안에 스레드 패널만 렌더링하세요. 아래 데모는 provider, 메시지 목록, 컴포저를 유지하되 대화 패널은 생략해요:

'use client';
import * as React from 'react';
import AttachIcon from '@mui/icons-material/AttachFile';
import SendIcon from '@mui/icons-material/Send';
import Box from '@mui/material/Box';
import {
  ChatComposer,
  ChatComposerAttachButton,
  ChatComposerSendButton,
  ChatComposerTextArea,
  ChatComposerToolbar,
  ChatConversation,
  ChatConversationHeader,
  ChatConversationSubtitle,
  ChatConversationTitle,
  ChatMessageGroup,
  ChatMessageList,
} from '@mui/x-chat';
import { ChatLayout, ChatProvider } from '@mui/x-chat/headless';
import { createEchoAdapter } from 'docs/data/chat/core/examples/shared/demoUtils';
import {
  minimalConversation,
  minimalMessages,
} from 'docs/data/chat/core/examples/shared/demoData';

const adapter = createEchoAdapter({
  respond: (text) =>
    `Received: "${text}". Only the thread pane is mounted in this ChatLayout example.`,
});

export default function LayoutThreadOnlyStandalone() {
  const renderItem = React.useCallback(
    (params: { id: string }) => (
      <ChatMessageGroup key={params.id} messageId={params.id} />
    ),
    [],
  );

  return (
    <ChatProvider
      adapter={adapter}
      initialActiveConversationId={minimalConversation.id}
      initialConversations={[minimalConversation]}
      initialMessages={minimalMessages}
    >
      <Box
        sx={{
          height: 460,
          overflow: 'hidden',
        }}
      >
        <ChatLayout style={{ height: '100%' }}>
          <ChatConversation>
            <ChatConversationHeader>
              <Box sx={{ minWidth: 0 }}>
                <ChatConversationTitle />
                <ChatConversationSubtitle />
              </Box>
            </ChatConversationHeader>
            <ChatMessageList renderItem={renderItem} />
            <ChatComposer>
              <ChatComposerTextArea
                aria-label="Message"
                placeholder="Type a message…"
              />
              <ChatComposerToolbar>
                <ChatComposerAttachButton>
                  <AttachIcon />
                </ChatComposerAttachButton>
                <ChatComposerSendButton>
                  <SendIcon />
                </ChatComposerSendButton>
              </ChatComposerToolbar>
            </ChatComposer>
          </ChatConversation>
        </ChatLayout>
      </Box>
    </ChatProvider>
  );
}

스레드 전용 모드에서는 활성 대화가 전체 ChatLayout 컨테이너를 채워요.

완전한 재구성(Full recomposition)

ChatLayout은 패널을 어디에 둘지만 결정하므로, 개별 Material UI 컴포넌트로 스레드를 직접 조립할 수 있어요. 이 접근 방식을 사용해 헤더와 메시지 목록 사이에 추가 UI를 삽입하거나 스레드 패널 내의 컨트롤을 이동할 수 있어요.

아래 예시는 올인원(all-in-one) 컴포넌트인 ChatBox에 번들된 기본 레이아웃에 의존하지 않는, 완전히 조립된 스레드 패널을 보여줘요:

import {
  ChatConversation,
  ChatConversationHeader,
  ChatConversationTitle,
  ChatConversationSubtitle,
  ChatConversationHeaderActions,
  ChatMessageList,
  ChatMessageGroup,
  ChatComposer,
  ChatComposerTextArea,
  ChatComposerToolbar,
  ChatComposerSendButton,
} from '@mui/x-chat';
import Box from '@mui/material/Box';

function CustomThread() {
  return (
    <ChatConversation sx={{ height: '100%' }}>
      <ChatConversationHeader>
        <ChatConversationTitle />
        <ChatConversationSubtitle />
        <Box sx={{ flex: 1 }} />
        <ChatConversationHeaderActions />
      </ChatConversationHeader>

      {/* Custom pinned notice between header and messages */}
      <Box
        sx={{
          px: 2,
          py: 0.75,
          bgcolor: 'warning.light',
          color: 'warning.contrastText',
          fontSize: 'caption.fontSize',
        }}
      >
        Responses are AI-generated. Verify before acting.
      </Box>

      <ChatMessageList
        renderItem={({ id, index }) => (
          <ChatMessageGroup index={index} messageId={id} />
        )}
      />

      <ChatComposer>
        <ChatComposerTextArea placeholder="Type a message…" />
        <ChatComposerToolbar>
          <ChatComposerSendButton />
        </ChatComposerToolbar>
      </ChatComposer>
    </ChatConversation>
  );
}
'use client';
import * as React from 'react';
import Box from '@mui/material/Box';
import {
  ChatComposer,
  ChatComposerSendButton,
  ChatComposerTextArea,
  ChatComposerToolbar,
  ChatConversation,
  ChatConversationHeader,
  ChatConversationHeaderActions,
  ChatConversationSubtitle,
  ChatConversationTitle,
  ChatMessageGroup,
  ChatMessageList,
} from '@mui/x-chat';
import { ChatLayout, ChatProvider } from '@mui/x-chat/headless';
import { createEchoAdapter } from 'docs/data/chat/core/examples/shared/demoUtils';
import {
  minimalConversation,
  minimalMessages,
} from 'docs/data/chat/core/examples/shared/demoData';

const adapter = createEchoAdapter({
  respond: (text) =>
    `Received: "${text}". This thread is recomposed from individual components, with a pinned notice between the header and the messages.`,
});

export default function LayoutRecomposedStandalone() {
  const renderItem = React.useCallback(
    (params: { id: string; index: number }) => (
      <ChatMessageGroup key={params.id} index={params.index} messageId={params.id} />
    ),
    [],
  );

  return (
    <ChatProvider
      adapter={adapter}
      initialActiveConversationId={minimalConversation.id}
      initialConversations={[minimalConversation]}
      initialMessages={minimalMessages}
    >
      <Box
        sx={{
          height: 420,
          overflow: 'hidden',
        }}
      >
        <ChatLayout style={{ height: '100%' }}>
          <ChatConversation sx={{ height: '100%' }}>
            <ChatConversationHeader>
              <Box sx={{ minWidth: 0 }}>
                <ChatConversationTitle />
                <ChatConversationSubtitle />
              </Box>
              <Box sx={{ flex: 1 }} />
              <ChatConversationHeaderActions />
            </ChatConversationHeader>

            {/* Custom pinned notice between header and messages */}
            <Box
              sx={{
                px: 2,
                py: 0.75,
                bgcolor: 'warning.light',
                color: 'warning.contrastText',
                fontSize: 'caption.fontSize',
              }}
            >
              Responses are AI-generated. Verify before acting.
            </Box>

            <ChatMessageList renderItem={renderItem} />

            <ChatComposer>
              <ChatComposerTextArea
                aria-label="Message"
                placeholder="Type a message…"
              />
              <ChatComposerToolbar>
                <ChatComposerSendButton />
              </ChatComposerToolbar>
            </ChatComposer>
          </ChatConversation>
        </ChatLayout>
      </Box>
    </ChatProvider>
  );
}

CustomThread을 @mui/x-chat/headless의 ChatProvider로 감싸 런타임 상태를 어댑터에 연결하세요.

패널 할당

ChatLayout은 직접 자식을 검사해 각 자식이 어느 패널에 속하는지 결정해요. ChatConversationList는 자동으로 대화 패널에, ChatConversation은 스레드 패널에 할당돼요.

패널 자식을 다른 컴포넌트(styled(), React.memo(), 또는 커스텀 래퍼)로 감싸면 ChatLayout은 더 이상 그것을 식별할 수 없어요. 식별되지 않은 자식은 위치 기반 할당으로 대체됩니다: 자식이 하나면 스레드 패널을 채우고, 자식이 여러 개면 먼저 대화 패널을 채운 다음 스레드 패널을 채워요. 이 대체에 의존하는 대신 직접 자식에 pane prop을 명시적으로 설정하세요:

<ChatLayout>
  <MySidebar pane="conversations" />
  <MyThread pane="thread" />
</ChatLayout>

개발 모드에서 ChatLayout은 일부 자식은 식별할 수 있지만 나머지는 그렇지 못할 때 콘솔에 경고를 출력해요.

반응형 레이아웃

ChatLayout은 중단점(breakpoint) 동작을 강요하지 않아요. 언제 두 패널을 모두 표시할지, 언제 대화 목록만 표시할지, 언제 활성 스레드만 표시할지 결정하는 것은 여러분의 몫이에요.

아래 슬라이더를 드래그해 같은 구성을 다음 사이에서 전환하세요:

  • 600px 이상에서는 두 패널 레이아웃
  • 600px 미만에서는 단일 패널 대화 목록 또는 스레드

아래 데모는 로직을 명시적으로 유지해서, 라우트 기반 탐색, 드로어(drawer), 또는 다른 반응형 패턴으로 교체할 수 있어요:

'use client';
import * as React from 'react';
import AttachIcon from '@mui/icons-material/AttachFile';
import BackIcon from '@mui/icons-material/ArrowBack';
import SendIcon from '@mui/icons-material/Send';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import Slider from '@mui/material/Slider';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
import {
  ChatComposer,
  ChatComposerAttachButton,
  ChatComposerSendButton,
  ChatComposerTextArea,
  ChatComposerToolbar,
  ChatConversation,
  ChatConversationHeader,
  ChatConversationList,
  ChatConversationSubtitle,
  ChatConversationTitle,
  ChatMessageGroup,
  ChatMessageList,
} from '@mui/x-chat';
import { ChatLayout, ChatProvider } from '@mui/x-chat/headless';
import type {
  ChatConversation as ChatConversationModel,
  ChatMessage,
} from '@mui/x-chat/headless';
import {
  createEchoAdapter,
  syncConversationPreview,
} from 'docs/data/chat/core/examples/shared/demoUtils';
import {
  inboxConversations,
  inboxThreads,
} from 'docs/data/chat/core/examples/shared/demoData';

const adapter = createEchoAdapter({
  respond: (text) =>
    `Received: "${text}". This responsive example switches ChatLayout between two-pane and single-pane compositions.`,
});

export default function LayoutResponsiveStandalone() {
  const [width, setWidth] = React.useState(720);
  const [activeConversationId, setActiveConversationId] = React.useState<
    string | undefined
  >(() => inboxConversations[0].id);
  const [conversations, setConversations] = React.useState<ChatConversationModel[]>(
    () => inboxConversations.map((conversation) => ({ ...conversation })),
  );
  const [threads, setThreads] = React.useState<Record<string, ChatMessage[]>>(() =>
    Object.fromEntries(
      Object.entries(inboxThreads).map(([id, messages]) => [
        id,
        messages.map((message) => ({ ...message })),
      ]),
    ),
  );

  const isNarrow = width < 600;
  const effectiveConversationId = activeConversationId ?? inboxConversations[0].id;
  const messages = threads[effectiveConversationId] ?? [];
  const showList = !isNarrow || !activeConversationId;
  const showThread = !isNarrow || Boolean(activeConversationId);

  const renderItem = React.useCallback(
    (params: { id: string }) => (
      <ChatMessageGroup key={params.id} messageId={params.id} />
    ),
    [],
  );

  return (
    <Box sx={{ width: '100%' }}>
      <Box sx={{ px: 1, pb: 2, display: 'flex', alignItems: 'center', gap: 2 }}>
        <Typography variant="body2" sx={{ whiteSpace: 'nowrap' }}>
          Container width
        </Typography>
        <Slider
          value={width}
          onChange={(_, value) => setWidth(value as number)}
          min={320}
          max={900}
          valueLabelDisplay="auto"
          valueLabelFormat={(value) => `${value}px`}
        />
        <Typography
          variant="body2"
          sx={{ whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums' }}
        >
          {width}px
        </Typography>
      </Box>
      <Box
        sx={{
          width,
          maxWidth: '100%',
          mx: 'auto',
          transition: 'width 200ms ease',
        }}
      >
        <ChatProvider
          adapter={adapter}
          activeConversationId={activeConversationId}
          conversations={conversations}
          messages={messages}
          onActiveConversationChange={setActiveConversationId}
          onMessagesChange={(nextMessages) => {
            if (!effectiveConversationId) {
              return;
            }

            setThreads((prev) => ({
              ...prev,
              [effectiveConversationId]: nextMessages,
            }));
            setConversations((prev) =>
              syncConversationPreview(prev, effectiveConversationId, nextMessages),
            );
          }}
          onConversationsChange={setConversations}
        >
          <Box
            sx={{
              height: 500,
              overflow: 'hidden',
            }}
          >
            <ChatLayout
              style={{ height: '100%' }}
              slotProps={{
                conversationsPane: {
                  style: isNarrow
                    ? { flex: 1 }
                    : { width: '280px', flex: '0 0 280px' },
                },
              }}
            >
              {showList && (
                <ChatConversationList
                  slotProps={{ root: { 'aria-label': 'Conversations' } }}
                />
              )}
              {showThread && (
                <ChatConversation>
                  <ChatConversationHeader>
                    {isNarrow && activeConversationId ? (
                      <Tooltip title="Back to conversations">
                        <IconButton
                          size="small"
                          aria-label="Back to conversations"
                          onClick={() => setActiveConversationId(undefined)}
                          sx={{ mr: 1 }}
                        >
                          <BackIcon />
                        </IconButton>
                      </Tooltip>
                    ) : null}
                    <Box sx={{ minWidth: 0 }}>
                      <ChatConversationTitle />
                      <ChatConversationSubtitle />
                    </Box>
                  </ChatConversationHeader>
                  <ChatMessageList renderItem={renderItem} />
                  <ChatComposer>
                    <ChatComposerTextArea
                      aria-label="Message"
                      placeholder="Type a message…"
                    />
                    <ChatComposerToolbar>
                      <ChatComposerAttachButton>
                        <AttachIcon />
                      </ChatComposerAttachButton>
                      <ChatComposerSendButton>
                        <SendIcon />
                      </ChatComposerSendButton>
                    </ChatComposerToolbar>
                  </ChatComposer>
                </ChatConversation>
              )}
            </ChatLayout>
          </Box>
        </ChatProvider>
      </Box>
    </Box>
  );
}

단일 패널로 축소할 때는 탐색을 접근 가능하게 유지하세요: 대화 목록에 라벨을 지정하고(예: aria-label="Conversations"), 좁은 모드의 뒤로 가기 컨트롤에 aria-label="Back to conversations" 같은 명시적 라벨을 지정하세요. 위 데모가 그렇게 하고 있어요.

명시적인 반응형 로직 덕분에 좁은 모드 전환을 커스터마이징하기 쉬워요.

ChatLayout을 감싸는 부모 요소에 명시적인 치수를 설정하세요:

<Box sx={{ height: 500 }}>
  <ChatLayout>{/* conversation pane + thread pane */}</ChatLayout>
</Box>

이 페이지 뒤에 있는 스타일 없는(unstyled) 프리미티브에 대해서는 headless 레이아웃 문서를 참고하세요.

ChatLayout API

데모(Demos)

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

가져오기(Import)

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

참고: ref는 루트 요소로 전달돼요.

제공되는 다른 모든 props는 루트 요소(네이티브 요소)로 전달돼요.

슬롯(Slots)

이름 기본값 클래스 설명
root undefined -
conversationsPane undefined -
threadPane undefined -

소스 코드

이 페이지에서 정보를 찾지 못했다면, 컴포넌트 구현을 살펴보며 더 자세히 확인해 보세요.