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

Chat - 메시지 액션

원문 보기 위키 갱신

Chat - 메시지 액션 (Message actions)

호버나 포커스 시 메시지별 액션 버튼을 드러내어 복사, 수정, 삭제 및 커스텀 작업을 수행하는 방법에 대해 알아봅니다.

출처: MUI X documentation

본문

ChatMessageActions는 호버 시, 키보드 드릴인(포커스된 메시지에서 Enter), 또는 초점이 바 안에 있을 때 나타나는 액션 바를 렌더링합니다. 액션 영역은 메시지 행의 actions 그리드 영역을 차지하며, 드러나는 데는 짧은 opacity 전환이 사용됩니다.

플레이그라운드 (Playground)

액션 버튼, variant, density를 토글해 호버 시 드러나는 툴바를 미리 볼 수 있습니다.

import * as React from 'react';
import CopyIcon from '@mui/icons-material/ContentCopy';
import ThumbsUpIcon from '@mui/icons-material/ThumbUp';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import Tooltip from '@mui/material/Tooltip';
import {
  ChatMessage as ChatMessageComponent,
  ChatMessageActions,
  ChatMessageAvatar,
  ChatMessageContent,
  ChatMessageGroup,
} from '@mui/x-chat';
import type {
  ChatConversation,
  ChatDensity,
  ChatMessage,
  ChatVariant,
} from '@mui/x-chat/headless';
import { PlaygroundCard } from 'docs/src/modules/components/chat-playground/PlaygroundCard';
import {
  ChatChrome,
  ScopedChat,
} from 'docs/src/modules/components/chat-playground/sharedProviders';
import {
  ChoiceControl,
  DividerLabel,
  SwitchControl,
} 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: 'actions-playground',
  title: 'Actions',
  participants: [users.me, users.assistant],
};

type Role = 'assistant' | 'user';
type Status = 'sent' | 'read' | 'streaming';

function makeMessage(role: Role, status: Status, text: string): ChatMessage {
  const author = role === 'user' ? users.me : users.assistant;
  return {
    id: `actions-${role}-${status}`,
    conversationId: conversation.id,
    role,
    author,
    createdAt: '2026-05-03T09:30:00.000Z',
    status,
    parts: [{ type: 'text', text }],
  };
}

type ClassKey = 'actions';

const CLASS_DEFS: ReadonlyArray<CustomizationDef<ClassKey>> = [
  {
    name: 'actions',
    selector: '.MuiChatMessage-actions',
    description: 'The hover-revealed action toolbar.',
  },
];

export default function ChatMessageActionsPlayground() {
  const [showCopy, setShowCopy] = React.useState(true);
  const [showLike, setShowLike] = React.useState(true);
  const [revealed, setRevealed] = React.useState(true);
  const [variant, setVariant] = React.useState<ChatVariant>('default');
  const [density, setDensity] = React.useState<ChatDensity>('standard');
  const classesCustomizations = useCustomizations<ClassKey>(CLASS_DEFS);
  const message = React.useMemo(
    () =>
      makeMessage(
        'assistant',
        'read',
        'Toggle "reveal actions", or hover this bubble.',
      ),
    [],
  );

  const wrapperSx = classesCustomizations.toClassesSx();

  return (
    <PlaygroundCard
      title="ChatMessageActions"
      description="Hover-revealed action toolbar (copy, regenerate, react…) anchored under the bubble."
      previewMinHeight={220}
      span={2}
      classCustomizations={classesCustomizations.customizations}
      onClassesReset={classesCustomizations.reset}
      controls={
        <React.Fragment>
          <DividerLabel>composition (children)</DividerLabel>
          <SwitchControl
            label="copy action"
            checked={showCopy}
            onChange={setShowCopy}
          />
          <SwitchControl
            label="like action"
            checked={showLike}
            onChange={setShowLike}
          />
          <DividerLabel>visibility</DividerLabel>
          <SwitchControl
            label="reveal actions"
            checked={revealed}
            onChange={setRevealed}
          />
          <DividerLabel>chrome provider</DividerLabel>
          <ChoiceControl<ChatVariant>
            label="ChatChrome.variant"
            value={variant}
            options={['default', 'compact'] as const}
            onChange={setVariant}
          />
          <ChoiceControl<ChatDensity>
            label="ChatChrome.density"
            value={density}
            options={['compact', 'standard', 'comfortable'] as const}
            onChange={setDensity}
          />
        </React.Fragment>
      }
      preview={
        <ScopedChat
          conversations={[conversation]}
          messages={[message]}
          activeConversationId={conversation.id}
        >
          <ChatChrome variant={variant} density={density}>
            <Box
              sx={{
                width: '100%',
                ...(revealed && {
                  '& .MuiChatMessage-actions': {
                    opacity: 1,
                    visibility: 'visible',
                  },
                }),
                ...wrapperSx,
              }}
            >
              <ChatMessageGroup messageId={message.id}>
                <ChatMessageComponent messageId={message.id}>
                  <ChatMessageAvatar />
                  <ChatMessageContent />
                  <ChatMessageActions>
                    {showCopy ? (
                      <Tooltip title="Copy">
                        <IconButton size="small" aria-label="Copy">
                          <CopyIcon />
                        </IconButton>
                      </Tooltip>
                    ) : null}
                    {showLike ? (
                      <Tooltip title="Like">
                        <IconButton size="small" aria-label="Like">
                          <ThumbsUpIcon />
                        </IconButton>
                      </Tooltip>
                    ) : null}
                  </ChatMessageActions>
                </ChatMessageComponent>
              </ChatMessageGroup>
            </Box>
          </ChatChrome>
        </ScopedChat>
      }
    />
  );
}

임포트 (Import)

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

:::info ChatBox는 actions 그리드 영역을 예약하고 messageActions slot(또는 선언형 extraActions)을 스타일링된 바 안에 감쌉니다. 하나를 제공하기 전까지는 어떤 액션도 렌더링되지 않습니다. ChatMessageActions를 직접 임포트해야 하는 것은 커스텀 레이아웃을 만들 때뿐입니다. :::

표시 동작 (Visibility behavior)

액션 바는 기본적으로 숨겨져 있으며 다음 경우에 표시됩니다.

  • 사용자가 부모 ChatMessage 행 위에 호버할 때
  • 사용자가 포커스된 메시지에서 Enter로 드릴인할 때 (메시지 목록이 행에 data-actionable="true"를 설정합니다. 키보드 탐색 참고)
  • 초점이 액션 바 자체 안에 있을 때 (:focus-within)

숨겨져 있는 동안 바는 opacity: 0 외에도 visibility: hidden을 사용하므로, 액션 버튼들이 탭 순서와 히트 테스팅에서 제거됩니다. 채팅을 탭으로 이동할 때 보이지 않는 컨트롤에 멈추지 않습니다. 드러내는 데는 짧은 opacity 전환이 사용됩니다. 사용자가 축소된 움직임(reduced motion)을 선호하면 전환이 비활성화됩니다.

/* Selectors used by the built-in styles */
.MuiChatMessage-root:hover .MuiChatMessage-actions,
.MuiChatMessage-root[data-actionable='true'] .MuiChatMessage-actions,
.MuiChatMessage-actions:focus-within {
  opacity: 1;
  visibility: visible;
}

컴포넌트 구조 (Component anatomy)

ChatMessageActions는 메시지 행 레이아웃에서 actions 그리드 영역을 차지합니다.

ChatMessage (grid)
  ├── ChatMessageAvatar    → grid-area: avatar
  ├── ChatMessageContent   → grid-area: content
  ├── ChatMessageMeta      → grid-area: meta
  └── ChatMessageActions   → grid-area: actions

내장 스타일은 바를 버블 아래에 고정된 작은 상승된 칩(종이 배경, 둥근 모서리, 그림자)으로 렌더링합니다. 현재 사용자 자신의 메시지에서는 행의 끝(justify-self: end)에 정렬되어 오른쪽 정렬된 버블과 일치합니다. 둘 다 .MuiChatMessage-actions 클래스를 통해 재정의할 수 있습니다.

커스텀 액션 추가 (Adding custom actions)

ChatMessageActions는 액션 버튼으로 채우는 <div>(또는 커스텀 slot 요소)를 렌더링합니다. ChatBox를 사용할 때는 messageActions slot을 제공해 액션 행을 렌더링합니다. ChatBox는 제공하기 전까지 어떤 액션도 렌더링하지 않습니다. 컴포넌트는 { messageId }를 받고 스타일링된 호버 시 드러나는 바 안에 감싸집니다.

:::info 메시지 액션을 커스터마이즈하는 방법에는 세 가지가 있습니다.

  • extraActions는 컴포넌트를 작성하지 않고 선언형 버튼을 추가합니다(slotProps.messageActions의 함수 형태는 메시지 컨텍스트를 받습니다).
  • ChatBox의 messageActions slot은 직접 만든 액션 행 컴포넌트를 렌더링합니다. { messageId }를 받으며, useMessage() 훅으로 메시지 데이터를 읽습니다. null을 전달하면 extraActions가 제공돼도 액션을 완전히 숨깁니다.
  • 독립형 ChatMessageActions 컴포넌트(커스텀 레이아웃)는 actions slot을 노출하며, 이 slot의 prop 콜백은 메시지 소유자 상태를 받습니다. :::
'use client';
import * as React from 'react';
import IconButton from '@mui/material/IconButton';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import { ChatBox } from '@mui/x-chat';
import { createEchoAdapter } from 'docs/data/chat/core/examples/shared/demoUtils';
import {
  minimalConversation,
  minimalMessages,
} from 'docs/data/chat/core/examples/shared/demoData';

function MyMessageActions() {
  return (
    <React.Fragment>
      <IconButton size="small" aria-label="Copy">
        <ContentCopyIcon fontSize="small" />
      </IconButton>
      <IconButton size="small" aria-label="Edit">
        <EditIcon fontSize="small" />
      </IconButton>
      <IconButton size="small" aria-label="Delete">
        <DeleteIcon fontSize="small" />
      </IconButton>
    </React.Fragment>
  );
}

const adapter = createEchoAdapter();

export default function BasicMessageActions() {
  return (
    <ChatBox
      adapter={adapter}
      initialActiveConversationId={minimalConversation.id}
      initialConversations={[minimalConversation]}
      initialMessages={minimalMessages}
      slots={{
        messageActions: MyMessageActions,
      }}
      sx={{
        height: 500,
        border: '1px solid',
        borderColor: 'divider',
        borderRadius: 1,
      }}
    />
  );
}

메시지 컨텍스트 접근 (Accessing message context)

messageActions slot에 전달하는 컴포넌트는 messageId prop을 받습니다. 이를 useMessage() 훅(@mui/x-chat/headless에서 export)에 전달해 현재 메시지를 읽고, 사용자와 어시스턴트 메시지에 서로 다른 액션을 표시할 수 있습니다. 실행 시 액션에는 useChatActions()로 접근합니다. 이 훅은 메시지 상태를 구독하지 않고 sendMessage, retry, regenerate 등을 반환하므로, 응답이 스트리밍되는 동안 툴바가 다시 렌더링되지 않습니다.

'use client';
import * as React from 'react';
import IconButton from '@mui/material/IconButton';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import EditIcon from '@mui/icons-material/Edit';
import RefreshIcon from '@mui/icons-material/Refresh';
import { ChatBox } from '@mui/x-chat';
import { useChatActions, useMessage } 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';

function RoleBasedActions({ messageId }: { messageId: string }) {
  const message = useMessage(messageId);
  // `useChatActions` exposes the runtime actions without subscribing to message
  // state, so the toolbar never re-renders as the conversation streams.
  const chat = useChatActions();
  const role = message?.role;

  return (
    <React.Fragment>
      <IconButton size="small" aria-label="Copy">
        <ContentCopyIcon fontSize="small" />
      </IconButton>
      {role === 'assistant' && (
        <IconButton
          size="small"
          aria-label="Regenerate"
          onClick={() => chat.regenerate(messageId)}
        >
          <RefreshIcon fontSize="small" />
        </IconButton>
      )}
      {role === 'user' && (
        <IconButton size="small" aria-label="Edit">
          <EditIcon fontSize="small" />
        </IconButton>
      )}
    </React.Fragment>
  );
}

const adapter = createEchoAdapter();

export default function RoleBasedMessageActions() {
  return (
    <ChatBox
      adapter={adapter}
      initialActiveConversationId={minimalConversation.id}
      initialConversations={[minimalConversation]}
      initialMessages={minimalMessages}
      slots={{
        messageActions: RoleBasedActions,
      }}
      sx={{
        height: 500,
        border: '1px solid',
        borderColor: 'divider',
        borderRadius: 1,
      }}
    />
  );
}

선언형으로 액션 추가 (Adding actions declaratively)

messageActions slot 컴포넌트를 교체하는 대신 slotProps.messageActions에 함수를 전달하고 extraActions를 반환할 수 있습니다. 함수는 메시지 컨텍스트를 받으므로 특정 행을 타게팅할 수 있습니다. 예를 들어 어시스턴트 응답에 작동하는 "Regenerate" 버튼을 만들 수 있습니다. 각 액션의 onClick은 (event, { message, chat })를 받습니다. chat.regenerate(message.id)를 호출해 런타임을 통해 새 응답을 요청합니다.

'use client';
import * as React from 'react';
import RefreshIcon from '@mui/icons-material/Refresh';
import { ChatBox } from '@mui/x-chat';
import { createEchoAdapter } from 'docs/data/chat/core/examples/shared/demoUtils';
import {
  minimalConversation,
  minimalMessages,
} from 'docs/data/chat/core/examples/shared/demoData';

const adapter = createEchoAdapter();

export default function ExtraActionsMessageActions() {
  return (
    <ChatBox
      adapter={adapter}
      initialActiveConversationId={minimalConversation.id}
      initialConversations={[minimalConversation]}
      initialMessages={minimalMessages}
      slotProps={{
        messageActions: ({ message }) =>
          message?.role === 'assistant'
            ? {
                extraActions: [
                  {
                    id: 'regenerate',
                    label: 'Regenerate',
                    icon: <RefreshIcon fontSize="small" />,
                    onClick: (event, { chat }) => chat.regenerate(message.id),
                  },
                ],
              }
            : {},
      }}
      sx={{
        height: 500,
        border: '1px solid',
        borderColor: 'divider',
        borderRadius: 1,
      }}
    />
  );
}

소유자 상태 (Owner state)

독립형 ChatMessageActions 컴포넌트는 메시지 컨텍스트를 owner state로 actions slot에 전달하므로, slot 컴포넌트가 조건부로 스타일을 적용할 수 있습니다(ChatBox messageActions slot을 사용할 때는 useMessage(messageId)로 같은 데이터를 읽으세요).

Property Type Description
messageId string ID of the current message
message ChatMessage | null The full message object, or null if not found
role ChatRole | undefined Role of the message author (undefined until resolved)
status ChatMessageStatus | undefined Current status of the message (undefined until resolved)
streaming boolean Whether the message is streaming
error boolean Whether the message is in an error state
isGrouped boolean Whether the message is in a group
variant ChatVariant Current chrome variant
density ChatDensity Current chrome density
resolvedAuthor ResolvedMessageAuthor | null Resolved author display data
showAvatar boolean Whether an avatar column is rendered
isOwnMessage boolean Whether the message belongs to the current user (controls right-side alignment)

Slots

Slot Default element Description
actions div The action bar container

함께 보기 (See also)

  • 전체 메시지 레이아웃과 시각적 표현은 Message appearance를 참고하세요.
  • 액션 바를 드러내는 키보드 탐색 모델(Enter로 드릴인, Escape로 나가기)은 Message list—Accessibility를 참고하세요.

ChatMessageActions API

데모 (Demos)

이 React 컴포넌트의 사용 예시와 세부 사항은 컴포넌트 데모 페이지를 방문하세요.

임포트 (Import)

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

Props

Name Type Default Required Description
extraActions Array<{ disabled?: bool, icon?: node, id: string, label: string, onClick: func }> - No
message { author?: { avatarUrl?: string, displayName?: string, id: string, isOnline?: bool, metadata?: object, role?: 'assistant' | 'system' | 'user' }, conversationId?: string, createdAt?: string, editedAt?: string, id: string, metadata?: object, parts: Array<{ data: any, id?: string, transient?: bool, type: object } | { filename?: string, mediaType: string, type: 'file', url: string } | { sourceId: string, text?: string, title?: string, type: 'source-document' } | { sourceId: string, title?: string, type: 'source-url', url: string } | { state?: 'done' | 'streaming', text: string, type: 'reasoning' } | { state?: 'done' | 'streaming', text: string, type: 'text' } | { toolInvocation: { approval?: object, approvalId?: string, callProviderMetadata?: object, errorText?: string, input?: any, output?: any, preliminary?: bool, providerExecuted?: bool, state: 'approval-requested' | 'approval-responded' | 'input-available' | 'input-streaming' | 'output-available' | 'output-denied' | 'output-error', title?: string, toolCallId: string, toolName: string }, type: 'dynamic-tool' } | { toolInvocation: { approval?: object, approvalId?: string, callProviderMetadata?: object, errorText?: string, input?: any, output?: any, preliminary?: bool, providerExecuted?: bool, state: 'approval-requested' | 'approval-responded' | 'input-available' | 'input-streaming' | 'output-available' | 'output-denied' | 'output-error', title?: string, toolCallId: string, toolName: string }, type: 'tool' } | { type: 'step-start' }>, role: 'assistant' | 'system' | 'user', status?: 'cancelled' | 'error' | 'pending' | 'read' | 'sending' | 'sent' | 'streaming', updatedAt?: string } - No

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

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

소스 코드 (Source code)

이 페이지에서 원하는 정보를 찾지 못했다면 컴포넌트의 구현을 살펴보는 것을 고려해보세요.

더 알아보기 (Learn more)