채팅: 가리기 삭제, 100줄이 찬 뒤에도 맨 아래 고정(+새 메시지 수), 이름 줄과 말풍선으로 이름·내용 구분

- 공통 ChatMessage(이름 줄 + 말풍선, 내 말은 오른쪽, 이어 말하면 이름 한 번) — 방 채팅·마피아·라이어 게임, 그림 맞히기 이름 표시
- useStickToBottom: 개수 대신 목록 내용 변화를 보고 맨 아래 유지, 위로 올려 읽는 중엔 그대로, 보내면 다시 맨 아래
- 휴대폰 채팅 버튼의 새 메시지 수도 100줄 뒤에 0이 되던 문제(마지막 본 id 기준으로)
- e2e/chat.e2e.ts: PC 대기실·게임 옆 칸·휴대폰 시트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-13 03:48:56 +09:00
parent 115969515c
commit 65c56d3ae7
11 changed files with 370 additions and 60 deletions

View File

@@ -0,0 +1,29 @@
/**
* One chat message, shared by the room chat and the games with their own chat (마피아, 라이어 게임): the name sits on
* its own small coloured line above a bubble with the text, so who said it and what they said never run together.
* My own messages sit on the right without a name; a run of messages from the same person shows the name once.
* Hidden names stay in the DOM for screen readers (`.sr-only`).
*/
import type { CSSProperties, ReactNode } from 'react';
/** Hues that stay readable as text on the panel in both themes (lightness comes from `--chat-name-l`). */
const HUES = [212, 152, 28, 275, 335, 188, 48, 0, 248, 100];
export function nameHue(id: string): number {
let h = 0;
for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) >>> 0;
return HUES[h % HUES.length]!;
}
export function ChatMessage({ from, name, mine = false, cont = false, className, children }: { from: string; name: string; mine?: boolean; cont?: boolean; className?: string; children: ReactNode }) {
return (
<div className={`chat-line${mine ? ' mine' : ''}${cont ? ' cont' : ''}${className ? ` ${className}` : ''}`} style={{ '--name-h': nameHue(from) } as CSSProperties}>
<strong className={`chat-name${mine || cont ? ' sr-only' : ''}`}>{mine ? '나' : name}</strong>
<span className="chat-text">{children}</span>
</div>
);
}
/** Same sender as the message right before, within 2 minutes: the name is not repeated. */
type RunKey = { from?: string | null; at: number } | undefined;
export const sameRun = (prev: RunKey, cur: RunKey): boolean => !!prev && !!cur?.from && prev.from === cur.from && cur.at - prev.at < 120_000;

View File

@@ -3,20 +3,22 @@ import { useEffect, useRef, useState } from 'react';
import { CHAT_MAX, EMOTE_LABEL, EMOTES, type PublicUser, type RoomView } from '@bg/shared/lite';
import { create } from 'zustand';
import { socket, useRoom } from '../net/socket';
import { useStickToBottom } from '../lib/useStickToBottom';
import { BotActivity } from './BotActivity';
import { ChatMessage, sameRun } from './ChatMessage';
/** Id of the newest chat line shown in an open chat panel (ids only grow; the list itself keeps the last 100). */
export const useChatSeen = create<{ seen: number }>(() => ({ seen: 0 }));
export function ChatPanel({ room, me, title = true }: { room: RoomView; me: PublicUser; title?: boolean }) {
const chat = useRoom((s) => s.chat);
const [text, setText] = useState('');
const [hidden, setHidden] = useState<Set<string>>(new Set());
const listRef = useRef<HTMLDivElement>(null);
const { ref: listRef, pin } = useStickToBottom<HTMLDivElement>();
const inputRef = useRef<HTMLInputElement>(null);
const lastId = chat.at(-1)?.id ?? 0;
useEffect(() => {
useChatSeen.setState({ seen: chat.length });
listRef.current?.scrollTo({ top: listRef.current.scrollHeight });
}, [chat.length]);
useChatSeen.setState({ seen: lastId });
}, [lastId]);
// Enter anywhere (outside inputs) focuses chat — PC shortcut (docs/07 §3.5).
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
@@ -34,24 +36,18 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
{title && <h2 style={{ fontSize: '1.1rem' }}>채팅</h2>}
<div ref={listRef} className="chat-list" aria-live="polite">
{chat.length === 0 && <p className="muted small">아직 메시지가 없어요. Enter를 누르면 바로 입력할 수 있어요.</p>}
{chat
.filter((m) => !m.from || !hidden.has(m.from.id))
.map((m) => (
<div key={m.id} className="chat-line">
<strong>{m.from?.nickname ?? '알림'}</strong>
{chat.map((m, i) =>
m.from ? (
<ChatMessage key={m.id} from={m.from.id} name={m.from.nickname} mine={m.from.id === me.id} cont={sameRun(chatKey(chat[i - 1]), chatKey(m))}>
{m.text}
</ChatMessage>
) : (
<div key={m.id} className="chat-line sys">
<strong className="sr-only">알림</strong>
{m.text}
{m.from && m.from.id !== me.id && (
<button
className="muted small"
style={{ border: 0, background: 'none', cursor: 'pointer' }}
title="이 사람의 채팅 가리기"
onClick={() => setHidden(new Set([...hidden, m.from!.id]))}
>
가리기
</button>
)}
</div>
))}
),
)}
</div>
<BotActivity room={room} only="typing" />
<div className="emote-row">
@@ -69,6 +65,7 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
e.preventDefault();
if (text.trim()) socket.send({ t: 'chat', text: text.trim().slice(0, CHAT_MAX) });
setText('');
pin();
}}
>
<input
@@ -92,6 +89,8 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
);
}
const chatKey = (m: { from?: { id: string } | null; at: number } | undefined) => m && { from: m.from?.id ?? null, at: m.at };
/** Floating emote bubbles (both layouts). */
export function EmoteBubbles({ room }: { room: RoomView }) {
const emotes = useRoom((s) => s.emotes);