diff --git a/apps/web/src/components/ChatMessage.tsx b/apps/web/src/components/ChatMessage.tsx new file mode 100644 index 0000000..ea4da49 --- /dev/null +++ b/apps/web/src/components/ChatMessage.tsx @@ -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 ( +
+ {mine ? '나' : name} + {children} +
+ ); +} + +/** 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; diff --git a/apps/web/src/components/ChatPanel.tsx b/apps/web/src/components/ChatPanel.tsx index fe1239a..404fda4 100644 --- a/apps/web/src/components/ChatPanel.tsx +++ b/apps/web/src/components/ChatPanel.tsx @@ -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>(new Set()); - const listRef = useRef(null); + const { ref: listRef, pin } = useStickToBottom(); const inputRef = useRef(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 &&

채팅

}
{chat.length === 0 &&

아직 메시지가 없어요. Enter를 누르면 바로 입력할 수 있어요.

} - {chat - .filter((m) => !m.from || !hidden.has(m.from.id)) - .map((m) => ( -
- {m.from?.nickname ?? '알림'} + {chat.map((m, i) => + m.from ? ( + + {m.text} + + ) : ( +
+ 알림 {m.text} - {m.from && m.from.id !== me.id && ( - - )}
- ))} + ), + )}
@@ -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(); }} > 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); diff --git a/apps/web/src/games/catchmind/index.tsx b/apps/web/src/games/catchmind/index.tsx index 6b2068b..4ebe4d0 100644 --- a/apps/web/src/games/catchmind/index.tsx +++ b/apps/web/src/games/catchmind/index.tsx @@ -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 - {m.solversOnly && 맞힌 사람끼리} - {who} + + {who} + {m.solversOnly && 맞힌 사람끼리} + {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 ( -
  • +
  • {body}
  • ); diff --git a/apps/web/src/games/liar/index.tsx b/apps/web/src/games/liar/index.tsx index abcca42..92306fd 100644 --- a/apps/web/src/games/liar/index.tsx +++ b/apps/web/src/games/liar/index.tsx @@ -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; 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(null); - useEffect(() => { - listRef.current?.scrollTo({ top: listRef.current.scrollHeight }); - }, [v.descriptions.length]); + const { ref: listRef } = useStickToBottom(); return (

    📝 설명 기록

    @@ -375,13 +371,13 @@ function Descriptions({ v, players, me }: { v: LiarView; players: Record d.round === r) .map((d) => ( -
  • +
  • {nick(players, d.from)} {d.text ?? '(시간이 지나 넘어갔어요)'}
  • ))} {v.phase.kind === 'describe' && v.phase.round === r && v.phase.speaker && ( -
  • +
  • {nick(players, v.phase.speaker)} {v.phase.speaker === me ? '내 차례예요. 한 문장으로 설명해 주세요…' : '설명하는 중…'}
  • @@ -395,18 +391,16 @@ function Descriptions({ v, players, me }: { v: LiarView; players: Record l && { from: l.k === 'chat' ? l.from : null, at: l.at }; function ChatBox({ v, players, me, act }: { v: LiarView; players: Record; me: string | null; act: (a: unknown) => void }) { const [text, setText] = useState(''); - const listRef = useRef(null); + const { ref: listRef, pin } = useStickToBottom(); 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💬 토론 채팅
    {lines.length === 0 &&

    아직 메시지가 없어요.

    } - {lines.map((l) => + {lines.map((l, i) => l.k === 'sys' ? (
    📢 {eventText(l.e, players)}
    ) : ( -
    - {nick(players, l.from)} + {l.text} -
    + ), )}
    @@ -437,6 +430,7 @@ function ChatBox({ v, players, me, act }: { v: LiarView; players: Record setText(e.target.value)} maxLength={200} placeholder="누가 라이어일까요?" aria-label="토론 채팅 메시지" enterKeyHint="send" /> diff --git a/apps/web/src/games/mafia/index.tsx b/apps/web/src/games/mafia/index.tsx index 29ef1d7..39844f4 100644 --- a/apps/web/src/games/mafia/index.tsx +++ b/apps/web/src/games/mafia/index.tsx @@ -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; me: string | null; act: (a: unknown) => void }) { const tabs = useMemo(() => { @@ -400,7 +400,7 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record('day'); const [text, setText] = useState(''); const [seen, setSeen] = useState>({}); - const listRef = useRef(null); + const { ref: listRef, pin } = useStickToBottom(); 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 { 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
    {lines.length === 0 &&

    아직 메시지가 없어요.

    } - {lines.map((l) => + {lines.map((l, i) => l.k === 'sys' ? (
    📢 {eventText(l.e, players)}
    ) : ( -
    - {nick(players, l.m.from)} + {l.m.text} -
    + ), )}
    @@ -480,6 +479,7 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record () { + const ref = useRef(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 }; +} diff --git a/apps/web/src/pages/RoomPage.tsx b/apps/web/src/pages/RoomPage.tsx index 5c36b5c..dddc1f7 100644 --- a/apps/web/src/pages/RoomPage.tsx +++ b/apps/web/src/pages/RoomPage.tsx @@ -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 (