채팅 - 타이핑 표시
채팅 - 타이핑 표시 (Typing indicators)
다른 참여자들이 실시간으로 메시지를 작성 중일 때 사용자에게 알릴 수 있어요.
본문
:::info 타이핑 표시는 _사람_의 존재 — 다른 참여자가 메시지를 작성 중인 상태 — 를 반영합니다. _어시스턴트_가 응답을 생성하는 동안 표시되는 애니메이션 점은 streaming indicator를 참고하세요. :::
인터랙티브 플레이그라운드 (Interactive playground)
현재 대화에서 어떤 사용자들이 타이핑 중으로 표시될지 토글해 보세요.
import * as React from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import { ChatTypingIndicator } from '@mui/x-chat';
import { PlaygroundCard } from 'docs/src/modules/components/chat-playground/PlaygroundCard';
import {
ScopedChat,
TypingEffect,
} from 'docs/src/modules/components/chat-playground/sharedProviders';
import { emptyConversation } from 'docs/src/modules/components/chat-playground/sharedFixtures';
import {
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 candidates = [users.alice, users.mira];
type ClassKey = 'root';
const CLASS_DEFS: ReadonlyArray<CustomizationDef<ClassKey>> = [
{ name: 'root', description: 'The typing indicator container.' },
];
export default function ChatTypingIndicatorPlayground() {
const [count, setCount] = React.useState(1);
const classesCustomizations = useCustomizations<ClassKey>(CLASS_DEFS);
const userIds = React.useMemo(
() => candidates.slice(0, count).map((u) => u.id),
[count],
);
const indicatorSx = classesCustomizations.toClassesSx();
const label = React.useMemo(() => {
if (count === 0) {
return '(renders nothing)';
}
const names = candidates.slice(0, count).map((u) => u.displayName ?? u.id);
return `${names.join(', ')}${count === 1 ? ' is typing' : ' are typing'}`;
}, [count]);
return (
<PlaygroundCard
title="ChatTypingIndicator"
description="Renders when participants are typing in the active conversation."
previewMinHeight={140}
classCustomizations={classesCustomizations.customizations}
onClassesReset={classesCustomizations.reset}
controls={
<React.Fragment>
<DividerLabel>state (store)</DividerLabel>
<NumberControl
label="users typing"
value={count}
min={0}
max={candidates.length}
onChange={setCount}
helperText="Calls store.setTypingUser() — not a component prop."
/>
</React.Fragment>
}
preview={
<ScopedChat
conversations={[emptyConversation]}
activeConversationId={emptyConversation.id}
>
<TypingEffect conversationId={emptyConversation.id} userIds={userIds} />
<Box sx={{ width: '100%' }}>
<ChatTypingIndicator sx={indicatorSx} />
<Typography
variant="caption"
color="text.secondary"
sx={{ display: 'block', mt: 1 }}
>
count: {count} · data-count="{count}" · label: {label}
</Typography>
</Box>
</ScopedChat>
}
/>
);
}
타이핑 표시는 채팅 UI에서 "Alice Chen is typing"이나 "Alice Chen, Mira Patel are typing" 같은 라벨을 보여줘요. 이 기능은 어댑터의 setTyping() 메서드(발신)를 실시간 typing 이벤트(수신)와 연결해서, 로컬 컴포저의 타이핑 상태와 원격 참여자들의 타이핑 상태가 동기화되도록 합니다.
타이핑 표시가 동작하는 방식 (How typing indicators work)
타이핑 표시는 두 방향의 통신을 포함해요.
- 발신 (Outbound): 로컬 사용자가 컴포저에 타이핑하면 어댑터의
setTyping()메서드가 백엔드에 알립니다. - 수신 (Inbound): 다른 사용자가 타이핑하면 백엔드가 어댑터의
subscribe()메서드를 통해typing이벤트를 푸시하고, 런타임이 스토어를 업데이트합니다.
setTyping()과 subscribe()는 모두 선택적인 어댑터 메서드예요. 백엔드에 presence 채널이 없으면 생략하면 되고, 그러면 표시기는 결코 렌더링되지 않습니다.
타이핑 상태 보내기 (Sending typing state)
백엔드에 타이핑 표시를 보내려면 어댑터에 setTyping()을 구현하세요.
런타임은 기본적으로 setTyping()을 호출하지 않아요. features.typingSignal(기본값 false)을 활성화하면 자동 계약이 작동합니다. 즉, 런타임이 활성 대화에 대해 빈 값('') ⇄ 비어있지 않은 값 컴포저 전환 시 setTyping()을 호출합니다 — 값이 비어있지 않게 되면 { isTyping: true }, 다시 비게 되면 { isTyping: false }입니다. 메시지를 보낼 때(전송하면 컴포저가 비워짐)도 포함됩니다. 대화를 전환하면 이전 대화에는 { isTyping: false }를, 새 초안이 비어있지 않으면 새 대화에는 { isTyping: true }를 보냅니다. setTyping() 실패는 개발 전용 경고로 삼켜지고, 내장된 idle 타임아웃은 없습니다. setTyping()이 undefined이면 자동 호출은 조용한 no-op이에요. 전체 계약은 Real-time adapters를 참고하세요.
async setTyping({ conversationId, isTyping }) {
await fetch('/api/typing', {
method: 'POST',
body: JSON.stringify({ conversationId, isTyping }),
});
},
플래그가 꺼져 있을 때(기본값)는 호출을 직접 연결하세요. 예를 들어 컴포저 텍스트 영역의 onChange를 리슨해서, 사용자가 타이핑을 시작하면 adapter.setTyping({ conversationId, isTyping: true })를 호출하고, 멈추면(컴포저가 비워지거나 메시지를 보낼 때 등) adapter.setTyping({ conversationId, isTyping: false })를 호출합니다. features.typingSignal을 켜기 전에 이 수동 연결을 제거하세요. 그렇지 않으면 수동과 자동 호출이 이중으로 발생합니다.
타이핑 상태 받기 (Receiving typing state)
다른 사용자의 타이핑 표시를 받으려면 subscribe()를 구현하고 onEvent 콜백을 통해 typing 이벤트를 내보내세요.
subscribe({ onEvent }) {
const ws = new WebSocket('/api/ws');
ws.onmessage = (e) => {
const event = JSON.parse(e.data);
// event: { type: 'typing', conversationId, userId, isTyping }
onEvent(event);
};
return () => ws.close();
},
런타임은 스토어에 대화별 타이핑 상태를 추적합니다. typingByConversation[conversationId][userId]처럼요.
타이핑 타임아웃 동작 (Typing timeout behavior)
런타임은 수신 또는 발신 상태에 대해 오래된(stale) 타이핑 상태를 처리하는 내장 타임아웃을 포함하지 않아요. 스토어는 isTyping: true가 있는 모든 typing 이벤트에서 즉시 업데이트됩니다. 사용자가 브라우저 탭을 닫는 것처럼 이후에 isTyping: false 이벤트가 오지 않으면, 표시기는 무기한으로 계속 보입니다.
오래된 표시기를 막으려면 타임아웃 로직을 직접 구현하세요.
features.typingSignal이 꺼져 있을 때 흔한 패턴은 컴포저의 onChange 핸들러에서 짧은 idle 기간 후 타이핑 상태를 리셋하는 것입니다.
// In your composer onChange handler
let typingTimeout: ReturnType<typeof setTimeout> | null = null;
function handleComposerChange(value: string) {
if (value !== '') {
adapter.setTyping({ conversationId, isTyping: true });
if (typingTimeout) {
clearTimeout(typingTimeout);
}
typingTimeout = setTimeout(() => {
adapter.setTyping({ conversationId, isTyping: false });
}, 3000);
} else {
if (typingTimeout) {
clearTimeout(typingTimeout);
}
adapter.setTyping({ conversationId, isTyping: false });
}
}
features.typingSignal이 켜져 있으면 런타임이 setTyping() 호출을 주도하므로, idle 만료 로직을 어댑터의 setTyping() 구현 안으로 옮기세요. isTyping: true를 받을 때마다 타이머를 리셋하고, 타이머가 발화하면 isTyping: false를 보내면 됩니다.
let idleTimeout: ReturnType<typeof setTimeout> | null = null;
async setTyping({ conversationId, isTyping }) {
if (idleTimeout) {
clearTimeout(idleTimeout);
}
await postTyping({ conversationId, isTyping });
if (isTyping) {
idleTimeout = setTimeout(() => {
postTyping({ conversationId, isTyping: false });
}, 3000);
}
},
또는 서버 측에서 타임아웃 창 이후 타이핑 상태를 만료시켜 정리를 처리할 수도 있어요.
표시기 컴포넌트 참조 (Indicator component reference)
ChatTypingIndicator 컴포넌트는 headless Indicators.TypingIndicator 프리미티브를 감쌉니다. 활성 대화의 타이핑 상태를 읽고, 표시 이름을 다음에서 결정합니다.
- 대화 참여자
- 스레드에 이미 존재하는 메시지 작성자
- 더 풍부한 사용자 데이터가 없을 때의 원시 사용자 ID
정중한 live region(aria-live="polite")을 렌더링하고 다음과 같은 라벨을 표시해요.
- "Alice Chen is typing"
- "Alice Chen, Mira Patel are typing"
일반적인 배치 (Typical placement)
표시기를 스레드 헤더나 컴포저 바로 위에 배치하세요.
import { ChatTypingIndicator } from '@mui/x-chat';
<ChatTypingIndicator />;
아무도 타이핑하지 않으면 컴포넌트는 아무것도 렌더링하지 않습니다.
표시기 모양 커스터마이즈 (Customizing the indicator appearance)
ChatTypingIndicator는 커스텀 렌더링을 위한 root slot을 노출해요. slot은 타이핑 중인 사용자와 개수를 포함한 owner state를 받습니다.
import { ChatTypingIndicator } from '@mui/x-chat';
<ChatTypingIndicator
slots={{
root: ({ ownerState, children, ...props }) => (
<div {...props} className="my-typing-indicator">
{ownerState.count > 1 ? `${ownerState.count} people are typing` : children}
</div>
),
}}
/>;
완전히 스타일이 없는 렌더링이 필요하다면 @mui/x-chat/headless의 headless Indicators.TypingIndicator를 사용하세요. 같은 slot과 owner state입니다.
루트 요소는 타이핑 중인 사용자 수를 가진 data-count 속성을 노출하며, CSS에서 타겟팅할 수 있어요.
.my-typing-indicator[data-count='1'] {
font-style: italic;
}
같은 선택자는 styled()와 sx 선택자에서도 동작합니다.
라벨 커스터마이즈 (Customizing the label)
표시되는 문자열은 localeText.typingIndicatorLabel(users)에서 옵니다. 기본값은 단일 사용자를 "Alice Chen is typing", 여러 사용자를 "Alice Chen, Mira Patel are typing"으로 포맷해요. ChatBox 또는 ChatRoot의 localeText prop을 통해 재정의해서 문구를 바꾸거나 번역할 수 있어요.
<ChatBox
localeText={{
typingIndicatorLabel: (users) =>
users.length === 1
? `${users[0].displayName ?? users[0].id} tippt …`
: 'Mehrere Personen tippen …',
}}
/>
displayName은 ChatLocaleTypingUser(Pick<ChatUser, 'id' | 'displayName'>)에서 선택사항이므로, ?? users[0].id 폴백이 "undefined tippt" 렌더링을 피하게 해줍니다. 재정의 가능한 문자열의 전체 목록은 Localization을 참고하세요.
Owner state
커스텀 slot은 다음을 받습니다.
| 속성 (Property) | 타입 (Type) | 설명 (Description) |
|---|---|---|
users |
ChatUser[] |
참여자/메시지 작성자에서 결정된 타이핑 사용자. 각자 id와 선택적 displayName, avatarUrl이 있음 |
count |
number |
현재 타이핑 중인 사용자 수 |
label |
string |
결정된 지역화 라벨(예: "Alice Chen is typing") |
activeConversationId |
string | undefined |
표시기가 읽고 있는 대화 |
표시 문자열은 users를 직접 조합하지 말고 ownerState.label(이미 children으로 렌더링됨)에서 가져와야 합니다.
Chat Box와 함께 사용 (Using with Chat Box)
ChatBox는 기본적으로 타이핑 표시기를 렌더링하지 않아요. slots.typingIndicator / slotProps.typingIndicator 항목이 ChatBox slot 타입에 존재하지만, 현재 이 위젯을 위한 내장 렌더 위치는 없습니다.
ChatBox는 자식들을 채팅 provider 트리 안에 렌더링하므로, 거기에 배치한 타이핑 표시기는 실시간 타이핑 상태를 읽을 수 있어요.
import { ChatBox, ChatTypingIndicator } from '@mui/x-chat';
<ChatBox adapter={adapter}>
<ChatTypingIndicator />
</ChatBox>;
자식들은 내장 레이아웃 뒤에 렌더링되므로, 표시기를 자신의 스타일링으로 배치하세요. 또는 배치를 완전히 제어하려면 아래 Using the indicator standalone 섹션의 독립 ChatRoot 컴포지션을 사용하세요.
수신 표시는 어댑터의 subscribe()가 typing 이벤트를 내보내야 합니다. 발신 자동 신호는 opt-in이며 features.typingSignal로 기본 꺼져 있어요(위 Sending typing state 참고).
표시기를 독립적으로 사용 (Using the indicator standalone)
ChatRoot로 커스텀 레이아웃을 만들 때는 provider 트리 안 어디든 표시기를 배치하세요.
import { ChatRoot } from '@mui/x-chat/headless';
import { ChatTypingIndicator } from '@mui/x-chat';
<ChatRoot adapter={adapter}>
{/* Your custom message list */}
<ChatTypingIndicator />
{/* Your custom composer */}
</ChatRoot>;
함께 보기 (See also)
setTyping()과subscribe()메서드에 대한 자세한 내용은 Adapter를 참고하세요.- 타이핑 라벨 번역은 Localization을 참고하세요.
ChatTypingIndicatorAPI 참조.
ChatTypingIndicator API
데모 (Demos)
이 React 컴포넌트 사용법에 대한 예시와 자세한 내용은 컴포넌트 데모 페이지를 참고하세요.
가져오기 (Import)
import { ChatTypingIndicator } from '@mui/x-chat/ChatIndicators';
// or
import { ChatTypingIndicator } from '@mui/x-chat';
Note: The
refis 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)
이 페이지에서 정보를 찾지 못했다면, 컴포넌트 구현을 살펴보는 것을 고려해 보세요.