채팅: 가리기 삭제, 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:
29
apps/web/src/components/ChatMessage.tsx
Normal file
29
apps/web/src/components/ChatMessage.tsx
Normal 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;
|
||||
@@ -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);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
/** 그림 맞히기 화면 (docs/games/catchmind.md §5.5, §9). */
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react';
|
||||
import type { CanvasOp, CatchmindOptions, CatchmindView, ChatView, TurnEndReason } from '@bg/games/catchmind';
|
||||
import type { PublicUser, ServerMessage } from '@bg/shared/lite';
|
||||
import { nameHue } from '../../components/ChatMessage';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
@@ -126,7 +127,10 @@ const CSS = `
|
||||
.cm-chat-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 3px; overflow-y: auto; min-height: 120px; max-height: 260px; }
|
||||
.cm-side .cm-chat-list { max-height: 340px; }
|
||||
.cm-line { font-size: .95rem; line-height: 1.35; word-break: break-word; }
|
||||
.cm-line b { margin-right: 6px; }
|
||||
.cm-line b .cm-tag { margin: 0 0 0 6px; }
|
||||
.cm-line b { display: block; font-size: .8rem; font-weight: 800; color: hsl(var(--name-h, 212) 70% var(--chat-name-l)); }
|
||||
.cm-line:not(.sys):not(.react) { background: var(--surface-2); border-radius: 4px 12px 12px 12px; padding: 4px 10px; align-self: flex-start; max-width: 100%; }
|
||||
.cm-line.mine { background: var(--primary-soft); }
|
||||
.cm-line.sys { color: var(--success); font-weight: 800; }
|
||||
.cm-line.close { color: var(--warning); }
|
||||
.cm-line.blocked { color: var(--text-sub); font-style: italic; }
|
||||
@@ -847,8 +851,10 @@ function chatLine(m: ChatView, me: string | null, players: Record<string, Public
|
||||
cls: '',
|
||||
body: (
|
||||
<>
|
||||
{m.solversOnly && <span className="cm-tag">맞힌 사람끼리</span>}
|
||||
<b>{who}</b>
|
||||
<b>
|
||||
{who}
|
||||
{m.solversOnly && <span className="cm-tag">맞힌 사람끼리</span>}
|
||||
</b>
|
||||
{m.text}
|
||||
</>
|
||||
),
|
||||
@@ -911,7 +917,7 @@ function GuessPanel({ v, me, players, act, pending }: { v: CatchmindView; me: st
|
||||
{v.chat.map((m) => {
|
||||
const { cls, body } = chatLine(m, me, players, v.drawer);
|
||||
return (
|
||||
<li key={m.id} className={`cm-line ${cls}`}>
|
||||
<li key={m.id} className={`cm-line ${cls}${m.from === me ? ' mine' : ''}`} style={{ '--name-h': nameHue(m.from) } as CSSProperties}>
|
||||
{body}
|
||||
</li>
|
||||
);
|
||||
|
||||
@@ -5,13 +5,15 @@
|
||||
* (`ownChat`), so nobody can hint the word around the game. The word sits on a hold-to-see card (screen sharing,
|
||||
* people next to you). Descriptions are a separate, round-by-round list next to the free-talk chat.
|
||||
*/
|
||||
import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import type { LiarFinal, LiarOptions, LiarView, PublicEvent } from '@bg/games/liar';
|
||||
import { TOPIC_IDS, TOPIC_KO } from '@bg/games/liar/topics';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { ChatMessage, nameHue, sameRun } from '../../components/ChatMessage';
|
||||
import { useStickToBottom } from '../../lib/useStickToBottom';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -99,17 +101,14 @@ button.lg-tile { cursor: pointer; }
|
||||
.lg-tag.liar { background: #b91c1c; }
|
||||
.lg-desc { margin: 0; padding: 0; list-style: none; display: grid; gap: 5px; }
|
||||
.lg-desc li { background: var(--surface-2); border-radius: 10px; padding: 6px 10px; line-height: 1.4; overflow-wrap: anywhere; }
|
||||
.lg-desc li strong { margin-right: 6px; }
|
||||
.lg-desc li.mine strong { color: var(--primary); }
|
||||
.lg-desc li strong { display: block; font-size: .8rem; font-weight: 800; color: hsl(var(--name-h, 212) 70% var(--chat-name-l)); }
|
||||
.lg-desc li.mine { background: var(--primary-soft); }
|
||||
.lg-desc li.skip { color: var(--text-sub); font-style: italic; }
|
||||
.lg-desc li.now { border: 2px dashed #7c3aed; background: transparent; color: var(--text-sub); }
|
||||
.lg-round { font-size: .82rem; font-weight: 800; color: var(--text-sub); margin-top: 2px; }
|
||||
.lg-chat { flex: 1; min-height: 0; padding: 0; overflow: hidden; gap: 0; }
|
||||
.lg-chat h2 { padding: 10px 12px 6px; border-bottom: 1px solid var(--border); }
|
||||
.lg-msgs { flex: 1; min-height: 140px; overflow-y: auto; padding: 8px 10px; display: flex; flex-direction: column; gap: 5px; }
|
||||
.lg-msg { line-height: 1.4; overflow-wrap: anywhere; }
|
||||
.lg-msg strong { margin-right: 6px; }
|
||||
.lg-msg.mine strong { color: var(--primary); }
|
||||
.lg-msg.sys { font-size: .86rem; font-weight: 700; color: var(--text-sub); background: var(--surface-2); border-radius: 8px; padding: 3px 8px; }
|
||||
.lg-form { display: flex; gap: 6px; padding: 8px; border-top: 1px solid var(--border); flex-wrap: nowrap; }
|
||||
.lg-form .input { flex: 1; min-height: 44px; min-width: 0; }
|
||||
@@ -359,10 +358,7 @@ function Players({ v, players, me, pick, pending }: { v: LiarView; players: Reco
|
||||
|
||||
function Descriptions({ v, players, me }: { v: LiarView; players: Record<string, PublicUser>; me: string | null }) {
|
||||
const rounds = Array.from({ length: v.rounds }, (_, i) => i + 1).filter((r) => r === 1 || v.descriptions.some((d) => d.round === r) || (v.phase.kind === 'describe' && v.phase.round >= r));
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
listRef.current?.scrollTo({ top: listRef.current.scrollHeight });
|
||||
}, [v.descriptions.length]);
|
||||
const { ref: listRef } = useStickToBottom<HTMLDivElement>();
|
||||
return (
|
||||
<section className="lg-box" aria-label="설명 기록">
|
||||
<h2>📝 설명 기록</h2>
|
||||
@@ -375,13 +371,13 @@ function Descriptions({ v, players, me }: { v: LiarView; players: Record<string,
|
||||
{v.descriptions
|
||||
.filter((d) => d.round === r)
|
||||
.map((d) => (
|
||||
<li key={d.n} className={`${d.from === me ? 'mine' : ''}${d.text === null ? ' skip' : ''}`}>
|
||||
<li key={d.n} className={`${d.from === me ? 'mine' : ''}${d.text === null ? ' skip' : ''}`} style={{ '--name-h': nameHue(d.from) } as CSSProperties}>
|
||||
<strong>{nick(players, d.from)}</strong>
|
||||
{d.text ?? '(시간이 지나 넘어갔어요)'}
|
||||
</li>
|
||||
))}
|
||||
{v.phase.kind === 'describe' && v.phase.round === r && v.phase.speaker && (
|
||||
<li className="now">
|
||||
<li className="now" style={{ '--name-h': nameHue(v.phase.speaker) } as CSSProperties}>
|
||||
<strong>{nick(players, v.phase.speaker)}</strong>
|
||||
{v.phase.speaker === me ? '내 차례예요. 한 문장으로 설명해 주세요…' : '설명하는 중…'}
|
||||
</li>
|
||||
@@ -395,18 +391,16 @@ function Descriptions({ v, players, me }: { v: LiarView; players: Record<string,
|
||||
}
|
||||
|
||||
type Line = ({ k: 'chat'; text: string; from: string; key: string } | { k: 'sys'; e: PublicEvent }) & { at: number };
|
||||
const runKey = (l: Line | undefined) => l && { from: l.k === 'chat' ? l.from : null, at: l.at };
|
||||
|
||||
function ChatBox({ v, players, me, act }: { v: LiarView; players: Record<string, PublicUser>; me: string | null; act: (a: unknown) => void }) {
|
||||
const [text, setText] = useState('');
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const { ref: listRef, pin } = useStickToBottom<HTMLDivElement>();
|
||||
const lines: Line[] = [
|
||||
...v.events.filter((e) => e.t !== 'phase' || e.kind === 'discussion' || e.kind === 'vote' || e.kind === 'guess').map((e) => ({ k: 'sys' as const, e, at: e.at })),
|
||||
...v.chat.map((m) => ({ k: 'chat' as const, text: m.text, from: m.from, key: `c${m.n}`, at: m.at })),
|
||||
// Stable sort: same moment keeps the event order, announcements before chat.
|
||||
].sort((a, b) => a.at - b.at || (a.k === b.k ? 0 : a.k === 'sys' ? -1 : 1));
|
||||
useEffect(() => {
|
||||
listRef.current?.scrollTo({ top: listRef.current.scrollHeight });
|
||||
}, [v.chat.length, v.events.length]);
|
||||
const talk = v.phase.kind === 'discussion' || v.phase.kind === 'vote';
|
||||
const canWrite = !!v.my?.canChat && talk;
|
||||
const why = !me || !v.my ? '관전 중에는 채팅을 쓸 수 없어요.' : talk ? (v.my.chatWhy ?? '') : v.phase.kind === 'describe' ? '토론 채팅은 설명이 다 끝나면 열려요.' : (v.my.chatWhy ?? '');
|
||||
@@ -415,16 +409,15 @@ function ChatBox({ v, players, me, act }: { v: LiarView; players: Record<string,
|
||||
<h2>💬 토론 채팅</h2>
|
||||
<div ref={listRef} className="lg-msgs" aria-live="polite">
|
||||
{lines.length === 0 && <p className="muted small" style={{ margin: 0 }}>아직 메시지가 없어요.</p>}
|
||||
{lines.map((l) =>
|
||||
{lines.map((l, i) =>
|
||||
l.k === 'sys' ? (
|
||||
<div key={`e${l.e.n}`} className="lg-msg sys">
|
||||
📢 {eventText(l.e, players)}
|
||||
</div>
|
||||
) : (
|
||||
<div key={l.key} className={`lg-msg${l.from === me ? ' mine' : ''}`}>
|
||||
<strong>{nick(players, l.from)}</strong>
|
||||
<ChatMessage key={l.key} className="lg-msg" from={l.from} name={nick(players, l.from)} mine={l.from === me} cont={sameRun(runKey(lines[i - 1]), runKey(l))}>
|
||||
{l.text}
|
||||
</div>
|
||||
</ChatMessage>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
@@ -437,6 +430,7 @@ function ChatBox({ v, players, me, act }: { v: LiarView; players: Record<string,
|
||||
if (!t) return;
|
||||
act({ type: 'chat', text: t.slice(0, 200) });
|
||||
setText('');
|
||||
pin();
|
||||
}}
|
||||
>
|
||||
<input className="input" value={text} onChange={(e) => setText(e.target.value)} maxLength={200} placeholder="누가 라이어일까요?" aria-label="토론 채팅 메시지" enterKeyHint="send" />
|
||||
|
||||
@@ -12,6 +12,8 @@ import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { ChatMessage, sameRun } from '../../components/ChatMessage';
|
||||
import { useStickToBottom } from '../../lib/useStickToBottom';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -117,9 +119,6 @@ button.mf-tile { cursor: pointer; }
|
||||
.mf-tab[data-ch='lovers'][aria-selected='true'] { background: #fce7f3; color: #831843; box-shadow: inset 0 -3px 0 #db2777; }
|
||||
.mf-tab .n { display: inline-block; margin-left: 4px; min-width: 1.4em; border-radius: 999px; background: #dc2626; color: #fff; font-size: .72rem; padding: 0 5px; }
|
||||
.mf-msgs { flex: 1; min-height: 160px; overflow-y: auto; padding: 8px 10px; display: flex; flex-direction: column; gap: 5px; }
|
||||
.mf-msg { line-height: 1.4; overflow-wrap: anywhere; }
|
||||
.mf-msg strong { margin-right: 6px; }
|
||||
.mf-msg.mine strong { color: var(--primary); }
|
||||
.mf-msg.sys { font-size: .86rem; font-weight: 700; color: var(--text-sub); background: var(--surface-2); border-radius: 8px; padding: 3px 8px; }
|
||||
.mf-msg.sys.hot { color: var(--danger); }
|
||||
.mf-form { display: flex; gap: 6px; padding: 8px; border-top: 1px solid var(--border); flex-wrap: nowrap; }
|
||||
@@ -391,6 +390,7 @@ function Players({ v, players, me, pick, pending }: { v: MafiaView; players: Rec
|
||||
// ---------------------------------------------------------------- chat
|
||||
|
||||
type Line = ({ k: 'chat'; m: ChatView } | { k: 'sys'; e: PublicEvent }) & { at: number };
|
||||
const runKey = (l: Line | undefined) => l && { from: l.k === 'chat' ? l.m.from : null, at: l.at };
|
||||
|
||||
function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record<string, PublicUser>; me: string | null; act: (a: unknown) => void }) {
|
||||
const tabs = useMemo(() => {
|
||||
@@ -400,7 +400,7 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record<string
|
||||
const [tab, setTab] = useState<Channel>('day');
|
||||
const [text, setText] = useState('');
|
||||
const [seen, setSeen] = useState<Record<string, number>>({});
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const { ref: listRef, pin } = useStickToBottom<HTMLDivElement>();
|
||||
const cur: Channel = tabs.includes(tab) ? tab : 'day';
|
||||
// Day → 전체; night → the first private channel I may write in (only on my own screen).
|
||||
const phaseKey = `${v.day}-${v.phase.kind}`;
|
||||
@@ -420,8 +420,8 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record<string
|
||||
}, [v.chat, v.events, cur]);
|
||||
useEffect(() => {
|
||||
setSeen((s) => ({ ...s, [cur]: count(cur) }));
|
||||
listRef.current?.scrollTo({ top: listRef.current.scrollHeight });
|
||||
}, [cur, v.chat.length, v.events.length]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(pin, [cur, pin]);
|
||||
const ch = v.channels.find((c) => c.channel === cur);
|
||||
const canWrite = !!ch?.canWrite;
|
||||
const why = ch ? ch.why : me ? '이 채팅은 읽기만 할 수 있어요.' : '관전 중에는 채팅을 쓸 수 없어요.';
|
||||
@@ -458,16 +458,15 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record<string
|
||||
</div>
|
||||
<div ref={listRef} className="mf-msgs" role="tabpanel" aria-label={`${CHANNEL_KO[cur]} 채팅 내용`} aria-live="polite" data-channel={cur}>
|
||||
{lines.length === 0 && <p className="muted small" style={{ margin: 0 }}>아직 메시지가 없어요.</p>}
|
||||
{lines.map((l) =>
|
||||
{lines.map((l, i) =>
|
||||
l.k === 'sys' ? (
|
||||
<div key={`e${l.e.n}`} className={`mf-msg sys${l.e.t === 'death' || l.e.t === 'end' ? ' hot' : ''}`}>
|
||||
📢 {eventText(l.e, players)}
|
||||
</div>
|
||||
) : (
|
||||
<div key={l.m.key} className={`mf-msg${l.m.from === me ? ' mine' : ''}`}>
|
||||
<strong>{nick(players, l.m.from)}</strong>
|
||||
<ChatMessage key={l.m.key} className="mf-msg" from={l.m.from} name={nick(players, l.m.from)} mine={l.m.from === me} cont={sameRun(runKey(lines[i - 1]), runKey(l))}>
|
||||
{l.m.text}
|
||||
</div>
|
||||
</ChatMessage>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
@@ -480,6 +479,7 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record<string
|
||||
if (!t) return;
|
||||
act({ type: 'chat', channel: cur, text: t.slice(0, 200) });
|
||||
setText('');
|
||||
pin();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
|
||||
46
apps/web/src/lib/useStickToBottom.ts
Normal file
46
apps/web/src/lib/useStickToBottom.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Keeps a scrolling chat list at its newest (bottom) line. It reacts to what is actually in the list (a DOM
|
||||
* observer), not to a message count: the room chat keeps only the last 100 lines, so once full the count stopped
|
||||
* changing and the list stopped following new messages. If the reader scrolls up to read older lines it stays put
|
||||
* until they come back near the bottom (or `pin()` is called, e.g. after sending a message).
|
||||
*/
|
||||
import { useCallback, useLayoutEffect, useRef } from 'react';
|
||||
|
||||
const NEAR_PX = 48;
|
||||
|
||||
export function useStickToBottom<T extends HTMLElement>() {
|
||||
const ref = useRef<T>(null);
|
||||
const pinned = useRef(true);
|
||||
const toBottom = useCallback(() => {
|
||||
const el = ref.current;
|
||||
if (el) el.scrollTop = el.scrollHeight;
|
||||
}, []);
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
pinned.current = true;
|
||||
toBottom();
|
||||
const onScroll = () => {
|
||||
pinned.current = el.scrollHeight - el.scrollTop - el.clientHeight <= NEAR_PX;
|
||||
};
|
||||
const stick = () => {
|
||||
if (pinned.current) toBottom();
|
||||
};
|
||||
el.addEventListener('scroll', onScroll, { passive: true });
|
||||
const mo = new MutationObserver(stick);
|
||||
mo.observe(el, { childList: true, subtree: true, characterData: true });
|
||||
// The list itself changing size (sheet opening, phone rotating, the input row growing) keeps the bottom too.
|
||||
const ro = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(stick);
|
||||
ro?.observe(el);
|
||||
return () => {
|
||||
el.removeEventListener('scroll', onScroll);
|
||||
mo.disconnect();
|
||||
ro?.disconnect();
|
||||
};
|
||||
}, [toBottom]);
|
||||
const pin = useCallback(() => {
|
||||
pinned.current = true;
|
||||
toBottom();
|
||||
}, [toBottom]);
|
||||
return { ref, pin };
|
||||
}
|
||||
@@ -838,9 +838,8 @@ function FairnessCheck({
|
||||
// ---------------------------------------------------------------- chat
|
||||
|
||||
function ChatButton({ onOpen }: { onOpen: () => void }) {
|
||||
const total = useRoom((s) => s.chat.length);
|
||||
const seen = useChatSeen((s) => s.seen);
|
||||
const unread = Math.max(0, total - seen);
|
||||
const unread = useRoom((s) => s.chat.filter((m) => m.id > seen).length);
|
||||
return (
|
||||
<button className="btn btn-ghost btn-sm rb-btn" onClick={onOpen} aria-label={`채팅${unread ? `, 새 메시지 ${unread}개` : ''}`}>
|
||||
<span className="rb-ico">💬</span>
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
--primary-press: #1d4fd0;
|
||||
--primary-text: #ffffff;
|
||||
--primary-soft: #dbe7ff;
|
||||
--chat-name-l: 36%;
|
||||
--success: #15803d;
|
||||
--success-soft: #dcfce7;
|
||||
--warning: #b45309;
|
||||
@@ -39,6 +40,7 @@
|
||||
--primary-press: #4a7de0;
|
||||
--primary-text: #0b1020;
|
||||
--primary-soft: #1e2a44;
|
||||
--chat-name-l: 72%;
|
||||
--success: #4ade80;
|
||||
--success-soft: #133222;
|
||||
--warning: #fbbf24;
|
||||
@@ -64,6 +66,7 @@
|
||||
--primary-press: #4a7de0;
|
||||
--primary-text: #0b1020;
|
||||
--primary-soft: #1e2a44;
|
||||
--chat-name-l: 72%;
|
||||
--success: #4ade80;
|
||||
--success-soft: #133222;
|
||||
--warning: #fbbf24;
|
||||
@@ -881,12 +884,54 @@ button.header-user {
|
||||
.game-side .chat-list {
|
||||
max-height: none;
|
||||
}
|
||||
/* One message: a small coloured name line above a bubble (components/ChatMessage.tsx). Mine sit on the right. */
|
||||
.chat-line {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 2px;
|
||||
font-size: 0.95rem;
|
||||
line-height: 1.4;
|
||||
max-width: 100%;
|
||||
}
|
||||
.chat-line strong {
|
||||
margin-right: 6px;
|
||||
.chat-line.cont {
|
||||
margin-top: -3px;
|
||||
}
|
||||
.chat-name:not(.sr-only) {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 800;
|
||||
padding-left: 4px;
|
||||
color: hsl(var(--name-h, 212) 70% var(--chat-name-l));
|
||||
}
|
||||
.chat-text {
|
||||
background: var(--surface-2);
|
||||
color: var(--text);
|
||||
border-radius: 4px 14px 14px 14px;
|
||||
padding: 5px 11px;
|
||||
max-width: min(100%, 34em);
|
||||
overflow-wrap: anywhere;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
.chat-line.cont .chat-text {
|
||||
border-top-left-radius: 14px;
|
||||
}
|
||||
.chat-line.mine {
|
||||
align-items: flex-end;
|
||||
}
|
||||
.chat-line.mine .chat-text {
|
||||
background: var(--primary-soft);
|
||||
border-radius: 14px 4px 14px 14px;
|
||||
}
|
||||
.chat-line.mine.cont .chat-text {
|
||||
border-top-right-radius: 14px;
|
||||
}
|
||||
/* Notices (no sender): centred, quiet, no bubble. */
|
||||
.chat-line.sys {
|
||||
align-items: center;
|
||||
align-self: stretch;
|
||||
text-align: center;
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-sub);
|
||||
}
|
||||
/* One line of quick reactions; the rest scrolls sideways instead of stacking rows. */
|
||||
.emote-row {
|
||||
|
||||
@@ -115,6 +115,7 @@
|
||||
- 방 막대 버튼은 마우스 환경에서 40px(막대 52px 안에 여유), 터치 기기에서는 48px.
|
||||
- 방 안(대기실·게임·결과)에서는 사이트 상단 메뉴를 숨기고 방 막대(← 홈 · 게임 이름 · 🔗 방 코드 · 📖 규칙 · ⚙️ 설정 · 🚪 나가기) 한 줄만 둔다. 판이 그만큼 커진다. 높이 계산은 CSS 변수 `--site-h`(방 안에서는 0)를 쓴다.
|
||||
- 채팅의 빠른 반응(이모지·짧은 말)은 한 줄. 넘치면 옆으로 밀어 본다.
|
||||
- 채팅 한 줄은 이름(작은 글씨, 사람마다 다른 색)과 말풍선(내용)을 위아래로 나눠 보여 준다. 내 말은 오른쪽, 같은 사람이 이어서 말하면 이름은 한 번만. 목록은 늘 맨 아래(새 말)에 붙어 있고, 위로 올려 읽는 중에는 움직이지 않다가 내가 보내거나 아래로 내려오면 다시 붙는다(2026-10-13). 사람별 채팅 가리기는 없앴다(사용자 요청, 2026-10-13. 필요하면 방장이 내보내기).
|
||||
- 결과 창: 진한 버튼은 [🔁 한 판 더] 하나(누르면 그 방 대기실로 돌아간다, docs/06 §결과). [판 보기]·[▶ 다시 보기]는 한 줄에 나란히, [방 나가기]는 글자 버튼, 공정성 확인은 접어 둔다.
|
||||
|
||||
### 3.6 관리자 (PC)
|
||||
|
||||
@@ -67,7 +67,7 @@ try {
|
||||
await a.screenshot({ path: join(SHOTS, 'ai-1-typing.png') });
|
||||
await a.waitForFunction((n) => [...document.querySelectorAll('.chat-line')].slice(n).some((l) => l.querySelector('strong')?.textContent === '컴퓨터 1'), before + 1, { timeout: 30_000 });
|
||||
const lines = await a.locator('.chat-line').allInnerTexts();
|
||||
console.log(' omok chat:', lines.map((l) => l.replace(/\n/g, ' ').replace(/가리기$/, '')).join(' | '));
|
||||
console.log(' omok chat:', lines.map((l) => l.replace(/\n/g, ' ')).join(' | '));
|
||||
await a.screenshot({ path: join(SHOTS, 'ai-2-answer.png') });
|
||||
});
|
||||
|
||||
|
||||
191
e2e/chat.e2e.ts
Normal file
191
e2e/chat.e2e.ts
Normal file
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* E2E: the room chat stays at the newest line (also after more than 100 lines, when the list is full), lets the reader
|
||||
* scroll up without jumping, shows who said what as a name line + bubble, and has no "가리기" button any more.
|
||||
* PC lobby + PC in-game side panel + phone chat sheet (unread badge past 100 lines too).
|
||||
* Run: E2E_PORT=4641 bun e2e/chat.e2e.ts (needs apps/web/dist built)
|
||||
*/
|
||||
import { chromium, type Page } from 'playwright-core';
|
||||
import { mkdirSync, mkdtempSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { loadConfig } from '../apps/server/src/config';
|
||||
import { startServer } from '../apps/server/src/server';
|
||||
|
||||
const PORT = Number(process.env.E2E_PORT ?? 4641);
|
||||
const ORIGIN = `http://localhost:${PORT}`;
|
||||
const SHOTS = process.env.E2E_SHOTS ?? join(import.meta.dir, '../test-results');
|
||||
mkdirSync(SHOTS, { recursive: true });
|
||||
|
||||
const dbDir = mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'bg-e2e-'));
|
||||
const app = startServer({
|
||||
config: loadConfig({ PORT: String(PORT), DB_PATH: join(dbDir, 'app.db'), PUBLIC_ORIGIN: ORIGIN }),
|
||||
log: () => {},
|
||||
staticDir: join(import.meta.dir, '../apps/web/dist'),
|
||||
});
|
||||
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true });
|
||||
let failed = false;
|
||||
const step = async (name: string, fn: () => Promise<void>) => {
|
||||
const t0 = performance.now();
|
||||
try {
|
||||
await fn();
|
||||
console.log(`✓ ${name} (${Math.round(performance.now() - t0)}ms)`);
|
||||
} catch (e) {
|
||||
failed = true;
|
||||
console.log(`✗ ${name}: ${(e as Error).message.split('\n')[0]}`);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
/** Send one chat line through the input (the server allows one line per 0.5 s per person). */
|
||||
async function say(p: Page, text: string) {
|
||||
const input = p.locator('.chat-panel input[aria-label="메시지"]').first();
|
||||
await input.fill(text);
|
||||
await input.press('Enter');
|
||||
}
|
||||
/** The list is scrolled to its end and the newest line is inside the list's visible box (and the window). */
|
||||
async function atBottom(p: Page, list = '.chat-list') {
|
||||
return p.evaluate((sel) => {
|
||||
const el = [...document.querySelectorAll<HTMLElement>(sel)].find((e) => e.offsetParent !== null);
|
||||
if (!el) return { ok: false, why: 'no list' };
|
||||
const last = el.lastElementChild as HTMLElement | null;
|
||||
const gap = el.scrollHeight - el.scrollTop - el.clientHeight;
|
||||
if (!last) return { ok: false, why: 'empty' };
|
||||
const lb = last.getBoundingClientRect();
|
||||
const eb = el.getBoundingClientRect();
|
||||
const inList = lb.bottom <= eb.bottom + 2 && lb.top >= eb.top - 2;
|
||||
const inWindow = lb.bottom <= window.innerHeight + 2 && lb.top >= 0;
|
||||
return { ok: gap <= 2 && inList && inWindow, why: `gap ${gap}, inList ${inList}, inWindow ${inWindow}, last "${last.textContent}"` };
|
||||
}, list);
|
||||
}
|
||||
async function expectBottom(p: Page, label: string) {
|
||||
// Give the observer a frame.
|
||||
await p.waitForTimeout(120);
|
||||
const r = await atBottom(p);
|
||||
if (!r.ok) throw new Error(`${label}: not at the newest line (${r.why})`);
|
||||
}
|
||||
|
||||
try {
|
||||
const ctxA = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ko-KR' });
|
||||
const ctxB = await browser.newContext({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true, locale: 'ko-KR' });
|
||||
const a = await ctxA.newPage();
|
||||
const b = await ctxB.newPage();
|
||||
const errors: string[] = [];
|
||||
for (const p of [a, b]) p.on('pageerror', (e) => errors.push(e.message));
|
||||
for (const p of [a, b]) await p.addInitScript(() => localStorage.setItem('bg:qs:omok', '1'));
|
||||
|
||||
let code = '';
|
||||
await step('A 방 만들기, B 휴대폰으로 입장', async () => {
|
||||
await a.goto(ORIGIN + '/');
|
||||
await a.getByRole('button', { name: '+ 방 만들기' }).click();
|
||||
await a.getByRole('dialog', { name: '게임 고르기' }).getByRole('button', { name: /오목/ }).click();
|
||||
await a.getByLabel('내 이름(닉네임)').fill('호랑이');
|
||||
await a.getByRole('button', { name: '이 이름으로 시작하기' }).click();
|
||||
await a.waitForURL(/\/r\/\d{6}$/);
|
||||
code = a.url().slice(-6);
|
||||
await b.goto(`${ORIGIN}/r/${code}`);
|
||||
await b.getByLabel('내 이름(닉네임)').fill('고양이');
|
||||
await b.getByRole('button', { name: '이 이름으로 입장하기' }).click();
|
||||
await a.getByLabel('자리').getByText('고양이').waitFor();
|
||||
});
|
||||
|
||||
await step('대기실(PC): 110줄이 넘어도 맨 아래 고정, 이름과 말풍선 구분, 가리기 없음', async () => {
|
||||
// B talks from the chat sheet on the phone; A from the inline panel. 2 people × 0.55 s ≈ 110 lines in 30 s.
|
||||
await b.getByRole('button', { name: /^채팅/ }).click();
|
||||
const sheet = b.getByRole('dialog', { name: '채팅' });
|
||||
await sheet.waitFor();
|
||||
const count = () => a.locator('.chat-list .chat-line').count();
|
||||
let extra = 0;
|
||||
for (let i = 1; i <= 90 && extra < 6; i++) {
|
||||
await Promise.all([say(a, `호랑이 메시지 ${i}`), (async () => {
|
||||
const input = sheet.locator('input[aria-label="메시지"]');
|
||||
await input.fill(`고양이 메시지 ${i}${i % 9 === 0 ? ' — 조금 긴 문장도 줄이 바뀌어서 말풍선 안에 잘 들어가는지 확인해요.' : ''}`);
|
||||
await input.press('Enter');
|
||||
})()]);
|
||||
await a.waitForTimeout(600);
|
||||
// Keep going a few rounds after the list is full (100 lines): that is when following new lines used to stop.
|
||||
if ((await count()) >= 100) extra++;
|
||||
}
|
||||
if (extra < 6) throw new Error(`the list never filled up (${await count()} lines)`);
|
||||
await sheet.locator('input[aria-label="메시지"]').fill('꽉 찬 뒤의 마지막 메시지');
|
||||
await sheet.locator('input[aria-label="메시지"]').press('Enter');
|
||||
await a.locator('.chat-line', { hasText: '꽉 찬 뒤의 마지막 메시지' }).waitFor();
|
||||
await expectBottom(a, 'PC lobby');
|
||||
await expectBottom(b, 'phone sheet');
|
||||
if (await a.getByRole('button', { name: '가리기' }).count()) throw new Error('가리기 button still there');
|
||||
if (await a.getByText('가리기', { exact: true }).count()) throw new Error('가리기 text still there');
|
||||
// Someone else's line: a name line and a separate bubble. My own: right side, no visible name.
|
||||
const other = a.locator('.chat-line:not(.mine):not(.cont)', { hasText: '고양이 메시지' }).last();
|
||||
await other.locator('.chat-name').waitFor();
|
||||
if ((await other.locator('.chat-name').innerText()) !== '고양이') throw new Error('name line text');
|
||||
const nb = (await other.locator('.chat-name').boundingBox())!;
|
||||
const tb = (await other.locator('.chat-text').boundingBox())!;
|
||||
if (!(nb.y + nb.height <= tb.y + 1)) throw new Error('name is not above the bubble');
|
||||
const mine = a.locator('.chat-line.mine').last();
|
||||
if (((await mine.locator('.chat-name').boundingBox())?.width ?? 0) > 1) throw new Error('my own name should be visually hidden (screen readers only)');
|
||||
const lb = (await a.locator('.chat-list').boundingBox())!;
|
||||
const mb = (await mine.locator('.chat-text').boundingBox())!;
|
||||
if (mb.x + mb.width < lb.x + lb.width - 30) throw new Error('my bubble is not on the right');
|
||||
await a.screenshot({ path: join(SHOTS, 'chat-lobby-pc.png') });
|
||||
await b.screenshot({ path: join(SHOTS, 'chat-sheet-phone.png') });
|
||||
});
|
||||
|
||||
await step('위로 올려 읽는 중에는 새 메시지가 와도 그대로, 내가 보내면 다시 맨 아래', async () => {
|
||||
await a.locator('.chat-list').evaluate((el) => (el.scrollTop = 0));
|
||||
await a.waitForTimeout(100);
|
||||
await b.getByRole('dialog', { name: '채팅' }).locator('input[aria-label="메시지"]').fill('읽는 중에 온 메시지');
|
||||
await b.getByRole('dialog', { name: '채팅' }).locator('input[aria-label="메시지"]').press('Enter');
|
||||
await a.locator('.chat-line', { hasText: '읽는 중에 온 메시지' }).waitFor({ state: 'attached' });
|
||||
await a.waitForTimeout(150);
|
||||
const top = await a.locator('.chat-list').evaluate((el) => el.scrollTop);
|
||||
if (top > 5) throw new Error(`jumped while reading (scrollTop ${top})`);
|
||||
await say(a, '이제 다시 아래로');
|
||||
await a.locator('.chat-line', { hasText: '이제 다시 아래로' }).waitFor();
|
||||
await expectBottom(a, 'after sending');
|
||||
});
|
||||
|
||||
await step('휴대폰: 시트를 닫아도 새 메시지 수(100줄이 꽉 찬 뒤에도), 다시 열면 맨 아래', async () => {
|
||||
const sheet = b.getByRole('dialog', { name: '채팅' });
|
||||
await sheet.getByRole('button', { name: '닫기' }).click();
|
||||
await a.waitForTimeout(600);
|
||||
for (let i = 1; i <= 3; i++) {
|
||||
await say(a, `안 읽은 메시지 ${i}`);
|
||||
await a.waitForTimeout(560);
|
||||
}
|
||||
await b.getByRole('button', { name: '채팅, 새 메시지 3개' }).waitFor({ timeout: 5000 });
|
||||
await b.getByRole('button', { name: /^채팅/ }).click();
|
||||
await sheet.locator('.chat-line', { hasText: '안 읽은 메시지 3' }).waitFor();
|
||||
await expectBottom(b, 'phone sheet reopened');
|
||||
await b.emulateMedia({ colorScheme: 'dark' });
|
||||
await b.waitForTimeout(200);
|
||||
await b.screenshot({ path: join(SHOTS, 'chat-sheet-phone-dark.png') });
|
||||
await b.emulateMedia({ colorScheme: 'light' });
|
||||
await sheet.getByRole('button', { name: '닫기' }).click();
|
||||
await b.getByRole('button', { name: '채팅', exact: true }).waitFor();
|
||||
});
|
||||
|
||||
await step('게임 중(PC 옆 칸): 새 메시지마다 맨 아래', async () => {
|
||||
await a.getByRole('button', { name: '▶ 게임 시작' }).click();
|
||||
await a.getByRole('button', { name: '시작하기' }).click();
|
||||
await a.locator('.game-side .chat-list').waitFor();
|
||||
await expectBottom(a, 'game side on open');
|
||||
for (let i = 1; i <= 6; i++) {
|
||||
await say(a, `게임 중 메시지 ${i}`);
|
||||
await a.waitForTimeout(560);
|
||||
await expectBottom(a, `game side #${i}`);
|
||||
}
|
||||
await a.screenshot({ path: join(SHOTS, 'chat-game-pc.png') });
|
||||
await a.emulateMedia({ colorScheme: 'dark' });
|
||||
await a.waitForTimeout(200);
|
||||
await a.screenshot({ path: join(SHOTS, 'chat-game-pc-dark.png') });
|
||||
});
|
||||
|
||||
if (errors.length) throw new Error(`page errors: ${errors.join(' | ')}`);
|
||||
} catch (e) {
|
||||
failed = true;
|
||||
console.error(e);
|
||||
} finally {
|
||||
await browser.close();
|
||||
await app.stop();
|
||||
}
|
||||
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
|
||||
process.exit(failed ? 1 : 0);
|
||||
Reference in New Issue
Block a user