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

Chat - 읽지 않음 마커

원문 보기 위키 갱신

Chat - 읽지 않음 마커 (Unread marker)

사용자가 자리를 비운 사이 도착한 메시지를 채팅 스레드 안의 인라인 구분선으로 강조합니다.

출처: MUI X documentation

본문

개요 (Overview)

활성 대화에 읽지 않은 메시지가 있을 때 메시지 목록 안에 읽지 않음 마커가 인라인으로 나타납니다. 마커는 첫 번째 읽지 않은 메시지 위치에 배치되며, 대화의 unreadCount가 0이 되면(사용자가 따라잡으면) 사라집니다. 이는 옵트인(opt-in) 기능으로, 기능을 켜기 전까지는 아무것도 렌더링되지 않으며 사용자 지정 레이아웃에 컴포넌트를 직접 포함시킬 수도 있습니다. 날짜 기반 스레드 구분선에 대해서는 날짜 구분선 페이지를 참고하세요.

읽지 않음 마커 활성화 (Enabling the unread marker)

ChatBox(features={{ unreadMarker: true }} 또는 독립형 ChatMessageList에서)에 전달하면 읽지 않은 경계에 마커가 렌더링됩니다:

<ChatBox adapter={adapter} features={{ unreadMarker: true }} />

활성화되면 unreadMarker 슬롯으로 렌더링되는 컴포넌트를 사용자 지정하거나 slotProps.unreadMarker로 props를 전달할 수 있습니다. 라벨 텍스트는 unreadMarkerLabel 로케일 키로 지역화할 수 있습니다.

:::info 마커 슬롯 사용자 지정은 기능이 활성화된 동안에만 적용됩니다. features.unreadMarker가 없으면 slots.unreadMarker와 slotProps.unreadMarker는 효과가 없습니다. :::

마커 위치 정하는 방법 (How the marker is positioned)

마커의 위치는 메시지 플래그가 아니라 활성 대화의 읽음 상태에서 파생됩니다:

  • conversation.unreadCount가 0보다 크면 마커는 첫 번째 읽지 않은 메시지 위에 렌더링됩니다 — 인덱스 messages.length - unreadCount 위치 (unreadCount가 메시지 수를 초과하면 첫 번째 메시지로 제한됨).
  • unreadCount가 설정되지 않았거나(또는 0) conversation.readState가 'unread'이면 마커는 첫 번째 메시지 위에 렌더링됩니다.
  • 그 외의 경우(사용자가 따라잡음)에는 아무것도 렌더링되지 않습니다 — features.unreadMarker가 켜져 있어도 마찬가지입니다.

unreadCount와 readState가 어떻게 설정되고 업데이트되는지에 대해서는 읽음 확인 페이지를 참고하세요.

독립형 사용법 (Standalone usage)

ChatUnreadMarker는 사용자 지정 메시지 레이아웃에 직접 포함할 수 있습니다. 메시지마다 한 번씩 렌더링하고 필수 messageId prop을 전달하세요 — 이 컴포넌트는 자신이 기준으로 삼는 메시지를 식별하며, 해당 메시지가 읽지 않은 경계에 있을 때만 렌더링됩니다(그 외 위치에서는 null을 반환합니다).

:::warning ChatMessageList에 사용자 지정 renderItem을 전달하면 features prop이 무시됩니다 — features.unreadMarker도 포함해서요. 아래처럼 renderItem 안에 ChatUnreadMarker를 포함시켜 마커를 유지하세요. :::

import * as React from 'react';
import Box from '@mui/material/Box';
import { ChatUnreadMarker } from '@mui/x-chat';
import type { ChatConversation, ChatMessage } from '@mui/x-chat/headless';
import { ScopedChat } from 'docs/src/modules/components/chat-playground/sharedProviders';
import { MessageBubble } from 'docs/src/modules/components/chat-playground/MessageBubble';
import { users } from 'docs/src/modules/components/chat-playground/data';

const CONVERSATION_ID = 'standalone-thread';

const conversation: ChatConversation = {
  id: CONVERSATION_ID,
  title: 'Standalone thread',
  participants: [users.me, users.assistant],
  unreadCount: 2,
  readState: 'unread',
};

const base = Date.UTC(2026, 4, 3, 8, 30, 0);

const messages: ChatMessage[] = Array.from({ length: 5 }, (_, i) => ({
  id: `standalone-msg-${i}`,
  conversationId: CONVERSATION_ID,
  role: i % 2 === 0 ? ('assistant' as const) : ('user' as const),
  author: i % 2 === 0 ? users.assistant : users.me,
  createdAt: new Date(base + i * 60_000).toISOString(),
  parts: [{ type: 'text', text: `Message ${i + 1}` }],
}));

export default function UnreadMarkerStandalone() {
  return (
    <ScopedChat
      conversations={[conversation]}
      messages={messages}
      activeConversationId={CONVERSATION_ID}
    >
      <Box sx={{ width: '100%' }}>
        {messages.map((message) => (
          <React.Fragment key={message.id}>
            <ChatUnreadMarker messageId={message.id} />
            <MessageBubble messageId={message.id} />
          </React.Fragment>
        ))}
      </Box>
    </ScopedChat>
  );
}

접근성 (Accessibility)

마커 루트는 role="separator"로 렌더링되므로 보조 기술이 이를 메시지 콘텐츠가 아니라 스레드 구분선으로 안내합니다. 보이는 라벨(기본값 "New messages")이 안내되는 텍스트입니다 — label prop 또는 unreadMarkerLabel 로케일 키로 덮어쓰면 안내 문구를 지역화할 수 있습니다. 렌더링된 루트는 data-has-boundary="true" 속성을 지닙니다.

메시지 목록의 전체 키보드 내비게이션 및 화면 판독기 모델에 대해서는 메시지 목록 접근성 섹션을 참고하세요.

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

아래 데모는 첫 번째 읽지 않은 메시지 위에 읽지 않음 마커가 렌더링되는 것을 보여 줍니다:

import * as React from 'react';
import Box from '@mui/material/Box';
import { ChatUnreadMarker } from '@mui/x-chat';
import type { ChatConversation, 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 {
  DividerLabel,
  NumberControl,
  TextControl,
} 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_ID = 'unread-playground';

function buildMessages(count: number): ChatMessage[] {
  const base = Date.UTC(2026, 4, 3, 8, 30, 0);
  return Array.from({ length: count }, (_, i) => ({
    id: `unread-msg-${i}`,
    conversationId: CONVERSATION_ID,
    role: 'assistant' as const,
    author: users.assistant,
    createdAt: new Date(base + i * 60_000).toISOString(),
    status: i < Math.floor(count / 2) ? ('read' as const) : ('sent' as const),
    parts: [{ type: 'text', text: `Message ${i + 1}` }],
  }));
}

type ClassKey = 'root' | 'label';

const CLASS_DEFS: ReadonlyArray<CustomizationDef<ClassKey>> = [
  { name: 'root', description: 'The unread marker row.' },
  {
    name: 'label',
    selector: '.MuiChatUnreadMarker-label',
    description: 'The "New messages" label inside the divider.',
  },
];

export default function ChatUnreadMarkerPlayground() {
  const [count, setCount] = React.useState(4);
  const [boundary, setBoundary] = React.useState(2);
  const [label, setLabel] = React.useState('');
  const classesCustomizations = useCustomizations<ClassKey>(CLASS_DEFS);
  const messages = React.useMemo(() => buildMessages(count), [count]);
  const safeBoundary = Math.min(boundary, count - 1);

  // The headless UnreadMarker derives its boundary from the conversation's
  // `unreadCount` (boundary = messageCount - unreadCount). Keep it in sync with
  // the slider so the marker renders at the selected index for any message count.
  const conversation = React.useMemo<ChatConversation>(
    () => ({
      id: CONVERSATION_ID,
      title: 'Unread thread',
      participants: [users.me, users.assistant],
      unreadCount: count - safeBoundary,
      readState: 'unread',
    }),
    [count, safeBoundary],
  );

  const markerSx = classesCustomizations.toClassesSx();

  return (
    <PlaygroundCard
      title="ChatUnreadMarker"
      description="Divider rendered when a message sits at the unread boundary."
      previewMinHeight={260}
      classCustomizations={classesCustomizations.customizations}
      onClassesReset={classesCustomizations.reset}
      controls={
        <React.Fragment>
          <DividerLabel>fixture (thread shape)</DividerLabel>
          <NumberControl
            label="message count"
            value={count}
            min={2}
            max={6}
            onChange={setCount}
          />
          <NumberControl
            label="boundary index"
            value={safeBoundary}
            min={0}
            max={Math.max(0, count - 1)}
            onChange={setBoundary}
            helperText="Where the marker is rendered — drives messageId prop."
          />
          <DividerLabel>props</DividerLabel>
          <TextControl
            label="label"
            value={label}
            onChange={setLabel}
            helperText="Empty = locale default (New messages)."
          />
        </React.Fragment>
      }
      preview={
        <ScopedChat
          conversations={[conversation]}
          messages={messages}
          activeConversationId={conversation.id}
        >
          <Box sx={{ width: '100%' }}>
            {messages.map((message, i) => (
              <React.Fragment key={message.id}>
                {i === safeBoundary ? (
                  <ChatUnreadMarker
                    messageId={message.id}
                    label={label || undefined}
                    sx={markerSx}
                  />
                ) : null}
                <MessageBubble messageId={message.id} />
              </React.Fragment>
            ))}
          </Box>
        </ScopedChat>
      }
    />
  );
}

ChatUnreadMarker API

데모 (Demos)

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

가져오기 (Import)

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

Note: ref는 루트 요소로 전달됩니다.

제공된 다른 모든 props는 루트 요소(네이티브 요소)에 전달됩니다.

CSS

규칙 이름 (Rule name)

Global class Rule name Description
- label 라벨 요소에 적용되는 스타일.
- root 루트 요소에 적용되는 스타일.

소스 코드 (Source code)

이 페이지에서 찾지 못한 정보가 있다면 컴포넌트 구현을 살펴보세요.

더 알아보기 (Learn more)