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

Chat - 코드 블록(Code blocks)

원문 보기 위키 갱신

`ChatCodeBlock` 컴포넌트를 사용해 언어 라벨과 복사 버튼이 있는 코드를 표시해요.

출처: MUI X documentation

본문

ChatCodeBlock은 언어 라벨과 원클릭 복사 버튼을 보여주는 헤더 바가 있는 코드 펜스(fenced code block)를 렌더링해요.

인터랙티브 플레이그라운드

아래 데모에서 언어와 내용을 실시간으로 바꿔볼 수 있어요:

import * as React from 'react';
import Box from '@mui/material/Box';
import { ChatCodeBlock } from '@mui/x-chat';
import { PlaygroundCard } from 'docs/src/modules/components/chat-playground/PlaygroundCard';
import {
  DividerLabel,
  SelectControl,
  TextControl,
} from 'docs/src/modules/components/chat-playground/controls';
import {
  useCustomizations,
  type CustomizationDef,
} from 'docs/src/modules/components/chat-playground/useCustomizations';

const SAMPLES: Record<string, string> = {
  tsx: `import { ChatBox } from '@mui/x-chat';

export function MyChat() {
  return <ChatBox adapter={adapter} />;
}`,
  bash: `pnpm add @mui/x-chat
pnpm add @mui/material @emotion/react`,
  json: `{
  "name": "@mui/x-chat",
  "version": "8.0.0",
  "main": "./dist/index.js"
}`,
  css: `.MuiChatComposer-root {
  border-radius: 16px;
  box-shadow: var(--mui-shadows-1);
}`,
};

type Language = keyof typeof SAMPLES;

type HighlighterChoice = 'none' | 'tokens';

// Simple demo "highlighter" — splits on whitespace and shades the tokens.
function tokensHighlighter(code: string): React.ReactNode {
  return code.split(/(\s+)/).map((part, i) => {
    if (/^\s+$/.test(part)) {
      return part;
    }
    if (
      /^(import|export|function|return|const|let|var|from|class|interface)$/.test(
        part,
      )
    ) {
      return (
        <span key={i} style={{ color: '#c084fc' }}>
          {part}
        </span>
      );
    }
    if (/^["'`].*/.test(part)) {
      return (
        <span key={i} style={{ color: '#fda4af' }}>
          {part}
        </span>
      );
    }
    if (/^\d+$/.test(part)) {
      return (
        <span key={i} style={{ color: '#fbbf24' }}>
          {part}
        </span>
      );
    }
    return part;
  });
}

const HIGHLIGHTERS: Record<
  HighlighterChoice,
  ((code: string, language: string) => React.ReactNode) | undefined
> = {
  none: undefined,
  tokens: tokensHighlighter,
};

type ClassKey = 'root' | 'header' | 'languageLabel' | 'copyButton' | 'pre' | 'code';

const CLASS_DEFS: ReadonlyArray<CustomizationDef<ClassKey>> = [
  { name: 'root', description: 'The outer code block container.' },
  {
    name: 'header',
    selector: '.MuiChatCodeBlock-header',
    description: 'The header row (language label + copy).',
  },
  {
    name: 'languageLabel',
    selector: '.MuiChatCodeBlock-languageLabel',
    description: 'The language identifier label.',
  },
  {
    name: 'copyButton',
    selector: '.MuiChatCodeBlock-copyButton',
    description: 'The copy button.',
  },
  {
    name: 'pre',
    selector: '.MuiChatCodeBlock-pre',
    description: 'The <pre> wrapper.',
  },
  {
    name: 'code',
    selector: '.MuiChatCodeBlock-code',
    description: 'The <code> element.',
  },
];

export default function ChatCodeBlockPlayground() {
  const [language, setLanguage] = React.useState<Language>('tsx');
  const [code, setCode] = React.useState(SAMPLES.tsx);
  const [highlighter, setHighlighter] = React.useState<HighlighterChoice>('none');
  const classesCustomizations = useCustomizations<ClassKey>(CLASS_DEFS);

  React.useEffect(() => {
    setCode(SAMPLES[language]);
  }, [language]);

  const blockSx = classesCustomizations.toClassesSx();

  return (
    <PlaygroundCard
      title="ChatCodeBlock"
      description="Standalone ChatCodeBlock — switch the language and plug in a syntax highlighter."
      previewMinHeight={260}
      classCustomizations={classesCustomizations.customizations}
      onClassesReset={classesCustomizations.reset}
      controls={
        <React.Fragment>
          <DividerLabel>props</DividerLabel>
          <SelectControl<Language>
            label="language"
            value={language}
            options={(Object.keys(SAMPLES) as Language[]).map((value) => ({
              value,
            }))}
            onChange={setLanguage}
          />
          <SelectControl<HighlighterChoice>
            label="highlighter"
            value={highlighter}
            options={[
              { value: 'none', label: 'none (raw)' },
              { value: 'tokens', label: 'tokens (realistic reference)' },
            ]}
            onChange={setHighlighter}
            helperText="Hook to plug in Shiki/Prism/Highlight.js."
          />
          <TextControl
            label="children (code)"
            value={code}
            onChange={setCode}
            multiline
            rows={5}
          />
        </React.Fragment>
      }
      preview={
        <Box sx={{ width: '100%' }}>
          <ChatCodeBlock
            language={language}
            highlighter={HIGHLIGHTERS[highlighter]}
            sx={blockSx}
          >
            {code}
          </ChatCodeBlock>
        </Box>
      }
    />
  );
}

가져오기(Import)

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

채팅에서 자동 렌더링

ChatBox를 사용할 때 마크다운 어시스턴트 메시지의 모든 코드 펜스는 자동으로 ChatCodeBlock으로 렌더링돼요. 추가 구성이 필요 없어요 — 내장 마크다운 렌더러는 만나는 모든 펜스 코드 블록에 대해 ChatCodeBlock을 생성해요.

```python
def greet(name):
    return f"Hello, {name}!"
```

여는 백틱 뒤에 지정한 언어(예: python)가 아래 데모처럼 헤더 바에 표시돼요:

'use client';
import * as React from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import { ChatBox, ChatCodeBlock } from '@mui/x-chat';
import {
  createChunkStream,
  createTextResponseChunks,
  randomId,
} from 'docs/data/chat/core/examples/shared/demoUtils';
import {
  demoUsers,
  minimalConversation,
  createTextMessage,
} from 'docs/data/chat/core/examples/shared/demoData';

const CONVERSATION_ID = minimalConversation.id;

const PYTHON_SNIPPET = `def flatten(lst):
    result = []
    for item in lst:
        if isinstance(item, list):
            result.extend(flatten(item))
        else:
            result.append(item)
    return result`;

const ASSISTANT_REPLY = `Here's a recursive Python function that flattens a nested list:

\`\`\`python
${PYTHON_SNIPPET}
\`\`\`

It works by iterating over each item — if the item is itself a list it recurses, otherwise it appends the value directly.`;

const INITIAL_MESSAGES = [
  createTextMessage({
    id: 'cb-msg-1',
    conversationId: CONVERSATION_ID,
    role: 'user',
    text: 'Write me a Python function to flatten a nested list.',
    createdAt: '2026-03-15T10:00:00.000Z',
    author: demoUsers.you,
  }),
  createTextMessage({
    id: 'cb-msg-2',
    conversationId: CONVERSATION_ID,
    role: 'assistant',
    text: ASSISTANT_REPLY,
    createdAt: '2026-03-15T10:00:05.000Z',
    author: demoUsers.agent,
  }),
];

// Minimal keyword highlighter — no library needed for the demo
const KW_AT_START = /^(def|for|if|else|return|in|isinstance)(?=\W|$)/;
const KW_ANYWHERE = /\b(?:def|for|if|else|return|in|isinstance)\b/;

function highlightPython(code: string): React.ReactNode {
  const lines = code.split('\n');
  return lines.map((line, lineIndex) => {
    const tokens: React.ReactNode[] = [];
    let rest = line;
    let key = 0;

    while (rest.length > 0) {
      const kwMatch = KW_AT_START.exec(rest);
      if (kwMatch) {
        tokens.push(
          <span key={key} style={{ color: '#c792ea' }}>
            {kwMatch[1]}
          </span>,
        );
        rest = rest.slice(kwMatch[1].length);
        key += 1;
        continue;
      }

      const nextIdx = rest.search(KW_ANYWHERE);
      const end = nextIdx <= 0 ? 1 : nextIdx;
      tokens.push(rest.slice(0, end));
      rest = rest.slice(end);
      key += 1;
    }

    return (
      <React.Fragment key={lineIndex}>
        {tokens}
        {lineIndex < lines.length - 1 ? '\n' : null}
      </React.Fragment>
    );
  });
}

export default function CodeBlock() {
  const adapter = React.useMemo(
    () => ({
      async sendMessage() {
        const messageId = randomId();
        return createChunkStream(
          createTextResponseChunks(messageId, ASSISTANT_REPLY, {
            author: demoUsers.agent,
          }),
          { delayMs: 40 },
        );
      },
    }),
    [],
  );

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      <ChatBox
        adapter={adapter}
        initialActiveConversationId={CONVERSATION_ID}
        initialConversations={[minimalConversation]}
        initialMessages={INITIAL_MESSAGES}
        sx={{
          height: 500,
          border: '1px solid',
          borderColor: 'divider',
          borderRadius: 1,
        }}
      />
      <div>
        <Typography variant="subtitle2" sx={{ mb: 1, color: 'text.secondary' }}>
          Standalone with custom highlighter
        </Typography>
        <ChatCodeBlock language="python" highlighter={highlightPython}>
          {PYTHON_SNIPPET}
        </ChatCodeBlock>
      </div>
    </Box>
  );
}

단독 사용(Standalone usage)

ChatCodeBlock을 단독 컴포넌트로 사용하려면 children(React 노드가 아니라 일반 문자열로 된 코드 — 마크업을 주입하려면 highlighter를 사용하세요)과 선택적 language를 전달하세요:

<ChatCodeBlock language="typescript">
  {`const greet = (name: string) => \`Hello, \${name}!\`;`}
</ChatCodeBlock>

복사 버튼

복사 버튼을 클릭하면 원시 코드 문자열이 클립보드에 복사되고 2초 동안 체크 표시 아이콘이 보여요. 복사 동작은 Clipboard API(navigator.clipboard.writeText)를 사용해요.

비보안(http://) 출처와 비동기 Clipboard API가 없는 구형 브라우저에서는 컴포넌트가 동기 방식의 document.execCommand('copy') 경로로 폴백해요. 복사가 완전히 실패하면 버튼의 접근 가능한 라벨과 툴팁이 2초 동안 "Copy failed"로 표시돼요.

언어 라벨

language를 임의의 문자열로 설정하세요 — 헤더에 그대로 표시돼요:

<ChatCodeBlock language="bash">{`pnpm add @mui/x-chat`}</ChatCodeBlock>

언어를 제공하지 않으면 헤더는 빈 라벨 영역으로 여전히 렌더링되고, 복사 버튼이 유일하게 보이는 콘텐츠가 돼요.

구문 강조(Syntax highlighting)

ChatCodeBlock은 의도적으로 구문 강조 라이브러리를 번들하지 않아요. 선호하는 라이브러리(Shiki, Prism, highlight.js 등)를 통합하려면 highlighter 함수를 전달하세요:

<ChatCodeBlock
  language="python"
  highlighter={(code, language) => highlight(code, language)}
>
  {pythonSnippet}
</ChatCodeBlock>

highlighter prop은 (code, language)를 받아 React 노드를 반환해야 해요. 생략하면 원시 코드 문자열이 강조 없이 표시돼요. 이 함수는 매 렌더링마다 호출되므로, 스트리밍되는 코드가 늘어남에 따라 강조가 동기화 상태를 유지해요. 이 페이지의 라이브 데모는 동작하는 동기 구현을 보여줘요: 플레이그라운드의 tokens 옵션과 "Automatic rendering" 섹션 아래 데모의 단독 블록이 그것이에요.

비동기 하이라이터 (Shiki)

Shiki와 같은 일부 라이브러리는 비동기로 강조해요. ChatCodeBlock을 효과(effect)에서 하이라이트를 해결하고 준비될 때까지 원시 코드로 폴백하는 컴포넌트로 감싸세요:

import { ChatCodeBlock } from '@mui/x-chat';
import { codeToHtml } from 'shiki';

function ShikiBlock({ code, language }) {
  const [html, setHtml] = React.useState(null);

  React.useEffect(() => {
    let active = true;
    codeToHtml(code, { lang: language, theme: 'github-light' }).then((result) => {
      if (active) {
        setHtml(result);
      }
    });
    return () => {
      active = false;
    };
  }, [code, language]);

  return (
    <ChatCodeBlock
      language={language}
      // Fall back to the raw code until the async highlight resolves,
      // so the block never renders empty mid-stream.
      highlighter={(rawCode) =>
        html ? <span dangerouslySetInnerHTML={{ __html: html }} /> : rawCode
      }
    >
      {code}
    </ChatCodeBlock>
  );
}

비동기 하이라이터는 렌더링 후에 해결되므로 항상 원시 코드(또는 이전 결과)를 폴백으로 반환하세요 — 스트리밍 중에는 새 하이라이트가 해결될 때까지 블록이 잠시 이전 강조를 보여줘요. HTML 문자열을 반환하는 하이라이터는 dangerouslySetInnerHTML로 주입되며 — 그 출력의 sanitizing은 여러분이 책임져야 해요. 내장 마크다운 렌더링은 원시 HTML을 주입하지 않아요.

ChatBox에서 렌더링 커스터마이징

ChatBox 안에서 코드 펜스가 렌더링되는 방식을 커스터마이징하려면 ChatMessageContent의 partProps.text.renderText를 여러분 자신의 코드 블록 컴포넌트를 사용하는 커스텀 마크다운 렌더러로 재정의하세요. renderText 계약과 텍스트 파트 데이터 모델은 Text and markdown을 참고하세요.

<ChatBox
  adapter={adapter}
  slotProps={{
    content: {
      partProps: {
        text: {
          renderText: (text) => <MyMarkdownWithCustomCodeBlocks content={text} />,
        },
      },
    },
  }}
/>

접근성(Accessibility)

메시지 목록 안에서 복사 버튼은 drill-in 모델을 따르며, 사용자가 포커스된 메시지에서 Enter를 누를 때까지 Tab 순서에서 벗어나 있어 전체 목록을 단일 Tab 정지점으로 유지해요. 마우스 클릭은 항상 동작하며, 단독 사용에서는 버튼이 자연스러운 Tab 순서를 유지해요.

버튼의 접근 가능한 이름은 복사 상태를 반영해요 — "Copy", 그다음 2초 동안 "Copied!" 또는 "Copy failed".

전체 키보드 탐색 모델은 Message list—Accessibility를 참고하세요.

CSS 클래스

권위 있는 목록은 ChatCodeBlock API 페이지에서 생성돼요.

클래스 이름 설명
.MuiChatCodeBlock-root 루트 컨테이너
.MuiChatCodeBlock-header 헤더 바
.MuiChatCodeBlock-languageLabel 언어 라벨 텍스트
.MuiChatCodeBlock-copyButton 클립보드 복사 버튼
.MuiChatCodeBlock-pre Pre 요소 래퍼
.MuiChatCodeBlock-code Code 요소

같이 보기

ChatCodeBlock API

데모(Demos)

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

가져오기(Import)

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

Props

이름 타입 기본값 필수 설명
children string - 예
highlighter function(code: string, language: string) => React.ReactNode - 아니요
language string - 아니요

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

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

CSS

규칙 이름(Rule name)

전역 클래스 규칙 이름 설명
- code 코드 요소에 적용되는 스타일.
- copyButton 복사 버튼 요소에 적용되는 스타일.
- header 헤더 요소에 적용되는 스타일.
- languageLabel 언어 라벨 요소에 적용되는 스타일.
- pre pre 요소에 적용되는 스타일.
- root 루트 요소에 적용되는 스타일.

소스 코드

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