Files
music_quiz/apps/web/src/components/ChatPanel.tsx

188 lines
6.2 KiB
TypeScript

/**
* Room chat (docs/06): one-line log, system lines centred, my unconfirmed lines at the bottom,
* the 정답 줄 + 5줄 블록 drawn as one item, "입력 중" above the input. The game screen uses the big variant.
*/
import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react';
import { CHAT_MAX, type ChatLine } from '@mq/shared/lite';
import { userHue } from './ui';
export interface ChatHandle {
focus(): void;
}
function typingText(names: string[]): string {
if (names.length === 1) return `${names[0]}님이 입력 중…`;
if (names.length === 2) return `${names[0]}, ${names[1]}님이 입력 중…`;
return `${names[0]}, ${names[1]} 외 ${names.length - 2}명이 입력 중…`;
}
export const ChatPanel = forwardRef<
ChatHandle,
{
lines: ChatLine[];
pending: { n: string; text: string }[];
meId: string;
myName: string;
onSend: (text: string) => void;
/** 입력 중 signal: true on start and every 2s while typing, false when cleared or sent. */
onTyping?: (on: boolean) => void;
typing?: string[];
big?: boolean;
}
>(function ChatPanel({ lines, pending, meId, myName, onSend, onTyping, typing = [], big }, ref) {
const [text, setText] = useState('');
const [stuck, setStuck] = useState(true);
const [unseen, setUnseen] = useState(false);
const logRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const lastSent = useRef('');
const typingAt = useRef(0);
// Changes whenever a line arrives, also once the log is capped at 200 lines.
const tick = `${lines.at(-1)?.seq ?? 0}:${pending.length}`;
useImperativeHandle(ref, () => ({ focus: () => inputRef.current?.focus() }), []);
// Auto-scroll only while the reader is at the bottom (docs/06 위로 스크롤하면 멈춤).
useLayoutEffect(() => {
const el = logRef.current;
if (!el) return;
if (stuck) el.scrollTop = el.scrollHeight;
else setUnseen(true);
}, [tick]);
useEffect(() => {
if (stuck) setUnseen(false);
}, [stuck]);
const toBottom = () => {
const el = logRef.current;
if (el) el.scrollTop = el.scrollHeight;
setStuck(true);
};
const stopTyping = () => {
if (typingAt.current) onTyping?.(false);
typingAt.current = 0;
};
const submit = () => {
const t = text.trim();
if (!t) return;
onSend(t.slice(0, CHAT_MAX));
lastSent.current = t;
setText('');
typingAt.current = 0;
toBottom();
};
const others = typing.filter((n) => n !== myName);
return (
<section className={`card chat ${big ? 'big' : ''}`} aria-label="채팅">
<div
className="chat-log"
ref={logRef}
role="log"
aria-live="polite"
onScroll={(e) => {
const el = e.currentTarget;
setStuck(el.scrollHeight - el.scrollTop - el.clientHeight < 24);
}}
>
{lines.length === 0 && pending.length === 0 && <div className="chat-sys">아직 대화가 없어요. 먼저 인사해 보세요!</div>}
{lines.map((l) =>
l.answer ? (
<div key={l.seq} className={`answer-item ${l.answer.none ? 'none' : ''}`}>
{l.userId ? (
<div className={`chat-line ok ${l.userId === meId ? 'me' : ''}`}>
<b style={{ ['--name-h' as string]: userHue(l.userId) }}>{l.nickname}</b>
<span>{l.text}</span> <span aria-label="정답">✔</span>
</div>
) : (
<div className="chat-sys">— {l.text} —</div>
)}
<div className="ans-gap" />
<div className="ans-gap" />
<div className="ans-text">
<span>{l.answer.text}</span>
</div>
<div className="ans-gap" />
<div className="ans-gap" />
</div>
) : l.userId === null ? (
<div key={l.seq} className="chat-sys">
— {l.text} —
</div>
) : (
<div key={l.seq} className={`chat-line ${l.userId === meId ? 'me' : ''}`}>
<b style={{ ['--name-h' as string]: userHue(l.userId) }}>{l.nickname}</b>
<span>{l.text}</span>
</div>
),
)}
{pending.map((p) => (
<div key={p.n} className="chat-line me pending" aria-label="보내는 중">
<b style={{ ['--name-h' as string]: userHue(meId) }}>{myName}</b>
<span>{p.text}</span>
</div>
))}
</div>
{unseen && !stuck && (
<button type="button" className="btn btn-sm chat-new" onClick={toBottom}>
새 메시지 ↓
</button>
)}
{onTyping && (
<div className="typing" aria-live="off">
{others.length > 0 && (
<>
<span className="dots" aria-hidden>
<i />
<i />
<i />
</span>
{typingText(others)}
</>
)}
</div>
)}
<form
className="chat-input"
onSubmit={(e) => {
e.preventDefault();
submit();
}}
>
<input
ref={inputRef}
className="input"
value={text}
maxLength={CHAT_MAX}
placeholder={big ? '정답이나 채팅 입력 (Enter)' : '메시지 입력 (Enter)'}
aria-label="채팅 입력"
autoComplete="off"
onChange={(e) => {
const v = e.target.value;
setText(v);
if (!onTyping) return;
if (!v.trim()) return stopTyping();
if (Date.now() - typingAt.current > 2000) {
typingAt.current = Date.now();
onTyping(true);
}
}}
onBlur={stopTyping}
onKeyDown={(e) => {
if (e.key === 'Escape') {
setText('');
stopTyping();
} else if (e.key === 'ArrowUp' && !text && lastSent.current) {
e.preventDefault();
setText(lastSent.current);
}
}}
/>
<button className="btn btn-primary" disabled={!text.trim()}>
보내기
</button>
</form>
</section>
);
});