채팅 연속 입력 전부 전송(짧은 연타 허용 + 보내기 대기열), 사람도 '입력 중' 표시, 오른쪽 위 소리 크기(0~100, 기본 50)
- 서버 방 채팅: 0.5초 고정 간격 대신 토큰 버킷(4줄 연속, 초당 2줄) — 도배는 여전히 막음 - 웹: useChatOutbox(방 채팅·마피아·라이어 게임)로 빠르게 친 줄도 순서대로 전송 - typing 메시지(방 채팅 / 게임 공개 채팅만, 마피아 밤 채널은 보내지 않음), BotActivity에 사람 표시 - VolumeControl: 사이트 머리글·방 막대 오른쪽 위, 설정 페이지에도 슬라이더 - e2e/chat.e2e.ts: 연타 7줄, 입력 중, 소리 크기 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -226,3 +226,43 @@ describe('윷놀이 room rules', () => {
|
||||
expect(st.view.turnSeq).toBe((room.game!.state as any).turnSeq);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Room chat (2026-10-13)', () => {
|
||||
test('a quick burst of lines all goes through; a flood is still stopped', () => {
|
||||
const { room, clock, conn } = harness();
|
||||
const a = conn('A');
|
||||
const b = conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
for (let i = 0; i < 4; i++) expect(room.chat('A', `줄 ${i}`)).toBeNull();
|
||||
expect(room.chat('A', '도배')).toBe('조금 천천히 보내 주세요.');
|
||||
clock.advance(500);
|
||||
expect(room.chat('A', '0.5초 뒤')).toBeNull();
|
||||
expect(b.msgs.filter((m) => m.t === 'chat').map((m) => (m as { text: string }).text)).toEqual(['줄 0', '줄 1', '줄 2', '줄 3', '0.5초 뒤']);
|
||||
});
|
||||
|
||||
test('"입력 중" reaches the others (not me), repeats within a second are dropped, off always goes', () => {
|
||||
const { room, clock, conn } = harness();
|
||||
const a = conn('A');
|
||||
const b = conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
const typingOf = (c: { msgs: ServerMessage[] }) => c.msgs.filter((m) => m.t === 'typing');
|
||||
room.typing('A', true, 'room');
|
||||
room.typing('A', true, 'room');
|
||||
expect(typingOf(b)).toEqual([{ t: 'typing', from: 'A', on: true, ch: 'room' }]);
|
||||
expect(typingOf(a)).toHaveLength(0);
|
||||
clock.advance(1000);
|
||||
room.typing('A', true, 'room');
|
||||
room.typing('A', false, 'room');
|
||||
expect(typingOf(b)).toHaveLength(3);
|
||||
// Game chat signal only while a game with its own chat runs (omok has none).
|
||||
room.typing('A', true, 'game');
|
||||
expect(typingOf(b)).toHaveLength(3);
|
||||
// Chat off: nothing.
|
||||
room.configure('A', { chatEnabled: false });
|
||||
clock.advance(1000);
|
||||
room.typing('A', true, 'room');
|
||||
expect(typingOf(b)).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,6 +14,7 @@ import { BotBrain, type BotActivity } from '../ai/brain';
|
||||
import type { Llm } from '../ai/llm';
|
||||
import type { LogEntry, RoomStore } from './store';
|
||||
import { applyLocks, type EffectiveGame, type SiteSettings } from '../admin/settings';
|
||||
import { TokenBucket } from '../ws/rate-limit';
|
||||
|
||||
export interface Conn {
|
||||
userId: string;
|
||||
@@ -151,6 +152,9 @@ export class Room {
|
||||
private flushTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private recentCs = new Map<string, number[]>();
|
||||
private lastChatAt = new Map<string, number>();
|
||||
private chatBuckets = new Map<string, TokenBucket>();
|
||||
/** When each person last said they were typing (to drop repeats within a second). */
|
||||
private typingAt = new Map<string, number>();
|
||||
private consecutiveErrors = 0;
|
||||
private readonly now: () => number;
|
||||
/** Plays the computer players' moves (docs/06 §12). */
|
||||
@@ -798,8 +802,11 @@ export class Room {
|
||||
if (!this.isParticipant(userId)) return '방에 들어와야 채팅할 수 있어요.';
|
||||
if (this.gameChatOnly()) return '게임 중에는 게임 화면의 채팅을 써 주세요.';
|
||||
const now = this.now();
|
||||
if (now - (this.lastChatAt.get(userId) ?? 0) < 500) return '조금 천천히 보내 주세요.';
|
||||
this.lastChatAt.set(userId, now);
|
||||
// A few lines in a row go through (people often send 2~3 quick lines); a flood still stops.
|
||||
let bucket = this.chatBuckets.get(userId);
|
||||
if (!bucket) this.chatBuckets.set(userId, (bucket = new TokenBucket(2, 4, now)));
|
||||
if (!bucket.take(now)) return '조금 천천히 보내 주세요.';
|
||||
this.typingAt.delete(userId);
|
||||
const clean = text.replace(/[\u0000-\u001f\u007f]/g, ' ').trim();
|
||||
if (!clean) return null;
|
||||
const msg: Extract<ServerMessage, { t: 'chat' }> = {
|
||||
@@ -820,6 +827,21 @@ export class Room {
|
||||
return (this.status === 'playing' || this.status === 'paused') && !!this.def.ownChat;
|
||||
}
|
||||
|
||||
/**
|
||||
* "입력 중" for people, like the computers'. Room chat: only while the room chat is open. Game chat: only in games
|
||||
* with their own chat, and the client only sends it from the public channel (마피아 낮, 라이어 토론).
|
||||
*/
|
||||
typing(userId: string, on: boolean, ch: 'room' | 'game'): void {
|
||||
if (!this.isParticipant(userId)) return;
|
||||
if (ch === 'room' ? !this.config.chatEnabled || this.gameChatOnly() : !this.gameChatOnly()) return;
|
||||
const now = this.now();
|
||||
if (on) {
|
||||
if (now - (this.typingAt.get(userId) ?? -Infinity) < 1000) return;
|
||||
this.typingAt.set(userId, now);
|
||||
} else this.typingAt.delete(userId);
|
||||
for (const [id, c] of this.conns) if (id !== userId) c.send({ t: 'typing', from: userId, on, ch });
|
||||
}
|
||||
|
||||
emote(userId: string, id: string): void {
|
||||
if (!this.isParticipant(userId) || this.gameChatOnly()) return;
|
||||
const now = this.now();
|
||||
|
||||
@@ -208,6 +208,9 @@ export class Gateway {
|
||||
case 'emote':
|
||||
room.emote(u, m.id);
|
||||
return;
|
||||
case 'typing':
|
||||
room.typing(u, m.on, m.ch);
|
||||
return;
|
||||
case 'rematch':
|
||||
e = room.rematch(u);
|
||||
break;
|
||||
|
||||
@@ -1,18 +1,30 @@
|
||||
import type { RoomView } from '@bg/shared/lite';
|
||||
import { useRoom } from '../net/socket';
|
||||
|
||||
/**
|
||||
* What the computers are doing right now (docs/06 §12.1): "🤖 컴퓨터 1 생각 중…", "💬 컴퓨터 2 입력 중…".
|
||||
* What the computers are doing right now (docs/06 §12.1): "🤖 컴퓨터 1 생각 중…", "💬 컴퓨터 2 입력 중…", and people
|
||||
* typing ("💬 고양이 입력 중…", `ch`: the room chat or the game's own public chat).
|
||||
* Not announced to screen readers: the chat line or the move that follows is.
|
||||
*/
|
||||
export function BotActivity({ room, only }: { room: RoomView; only?: 'typing' }) {
|
||||
export function BotActivity({ room, only, ch }: { room: RoomView; only?: 'typing'; ch?: 'room' | 'game' }) {
|
||||
const typing = useRoom((s) => s.typing);
|
||||
const me = useRoom((s) => s.me?.id);
|
||||
const entries = Object.entries(room.botActivity ?? {}).filter(([, a]) => !only || a === only);
|
||||
if (!entries.length) return null;
|
||||
const name = (id: string) => room.seats.find((s) => s?.user.id === id)?.user.nickname ?? '컴퓨터';
|
||||
const people = ch ? Object.entries(typing).filter(([id, t]) => t.ch === ch && id !== me) : [];
|
||||
if (!entries.length && !people.length) return null;
|
||||
const name = (id: string, fallback: string) =>
|
||||
room.seats.find((s) => s?.user.id === id)?.user.nickname ?? room.spectators.find((u) => u.id === id)?.nickname ?? fallback;
|
||||
return (
|
||||
<div className="bot-activity small" aria-hidden>
|
||||
{entries.map(([id, a]) => (
|
||||
<span key={id} data-activity={a}>
|
||||
{a === 'typing' ? '💬' : '🤖'} {name(id)} {a === 'typing' ? '입력 중' : '생각 중'}
|
||||
{a === 'typing' ? '💬' : '🤖'} {name(id, '컴퓨터')} {a === 'typing' ? '입력 중' : '생각 중'}
|
||||
<span className="bot-dots" />
|
||||
</span>
|
||||
))}
|
||||
{people.map(([id]) => (
|
||||
<span key={id} data-activity="typing" data-person>
|
||||
💬 {name(id, '누군가')} 입력 중
|
||||
<span className="bot-dots" />
|
||||
</span>
|
||||
))}
|
||||
|
||||
@@ -3,6 +3,7 @@ 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 { useChatOutbox, useTypingSignal } from '../lib/chat-input';
|
||||
import { useStickToBottom } from '../lib/useStickToBottom';
|
||||
import { BotActivity } from './BotActivity';
|
||||
import { ChatMessage, sameRun } from './ChatMessage';
|
||||
@@ -15,6 +16,8 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
|
||||
const [text, setText] = useState('');
|
||||
const { ref: listRef, pin } = useStickToBottom<HTMLDivElement>();
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const send = useChatOutbox((t) => socket.send({ t: 'chat', text: t }), 550);
|
||||
const typing = useTypingSignal('room', room.chatEnabled);
|
||||
const lastId = chat.at(-1)?.id ?? 0;
|
||||
useEffect(() => {
|
||||
useChatSeen.setState({ seen: lastId });
|
||||
@@ -49,7 +52,7 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
<BotActivity room={room} only="typing" />
|
||||
<BotActivity room={room} only="typing" ch="room" />
|
||||
<div className="emote-row">
|
||||
{EMOTES.map((id) => (
|
||||
<button key={id} type="button" onClick={() => socket.send({ t: 'emote', id })}>
|
||||
@@ -63,8 +66,9 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
|
||||
style={{ flexWrap: 'nowrap' }}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (text.trim()) socket.send({ t: 'chat', text: text.trim().slice(0, CHAT_MAX) });
|
||||
if (text.trim()) send(text.trim().slice(0, CHAT_MAX));
|
||||
setText('');
|
||||
typing.stop();
|
||||
pin();
|
||||
}}
|
||||
>
|
||||
@@ -73,7 +77,11 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
|
||||
className="input"
|
||||
style={{ flex: 1, minHeight: 44 }}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onChange={(e) => {
|
||||
setText(e.target.value);
|
||||
typing.onText(e.target.value);
|
||||
}}
|
||||
onBlur={typing.stop}
|
||||
onKeyDown={(e) => e.key === 'Escape' && (e.currentTarget as HTMLInputElement).blur()}
|
||||
maxLength={CHAT_MAX}
|
||||
placeholder="메시지 입력 (Enter)"
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/** PC top menu (docs/07-ui-ux.md §3.2): 로고·메뉴, 오른쪽에 테마 버튼과 로그인/계정 메뉴. */
|
||||
/** PC top menu (docs/07-ui-ux.md §3.2): 로고·메뉴, 오른쪽에 소리 크기·테마 버튼과 로그인/계정 메뉴. */
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, NavLink, useNavigate } from 'react-router';
|
||||
import { api } from '../net/api';
|
||||
import { useSession } from '../store/session';
|
||||
import { Avatar, ConfirmSheet } from './ui';
|
||||
import { VolumeControl } from './VolumeControl';
|
||||
|
||||
export function SiteHeader() {
|
||||
const { me, siteName, role } = useSession();
|
||||
@@ -21,7 +22,10 @@ export function SiteHeader() {
|
||||
<NavLink to="/games">게임 목록</NavLink>
|
||||
{role !== 'user' && <NavLink to="/admin">관리자</NavLink>}
|
||||
</nav>
|
||||
<ThemeToggle />
|
||||
<div className="header-tools">
|
||||
<VolumeControl />
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
{me ? (
|
||||
<AccountMenu />
|
||||
) : (
|
||||
|
||||
84
apps/web/src/components/VolumeControl.tsx
Normal file
84
apps/web/src/components/VolumeControl.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* Site volume (top right of the site header and the room bar): a speaker button that opens a 0~100 slider.
|
||||
* Default 50 (the sounds play at half their old level). 0 or "소리 끄기" mutes everything. This device only.
|
||||
*/
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { sfx } from '../lib/feedback';
|
||||
import { useSession } from '../store/session';
|
||||
|
||||
export function volumeIcon(sound: boolean, volume: number): string {
|
||||
if (!sound || volume <= 0) return '🔇';
|
||||
return volume < 34 ? '🔈' : volume < 67 ? '🔉' : '🔊';
|
||||
}
|
||||
|
||||
export function VolumeControl({ className = 'theme-toggle', label }: { className?: string; label?: boolean }) {
|
||||
const sound = useSession((s) => s.settings.sound);
|
||||
const volume = useSession((s) => s.settings.volume);
|
||||
const updateSettings = useSession((s) => s.updateSettings);
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onDown = (e: PointerEvent) => !ref.current?.contains(e.target as Node) && setOpen(false);
|
||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false);
|
||||
document.addEventListener('pointerdown', onDown);
|
||||
document.addEventListener('keydown', onKey);
|
||||
return () => {
|
||||
document.removeEventListener('pointerdown', onDown);
|
||||
document.removeEventListener('keydown', onKey);
|
||||
};
|
||||
}, [open]);
|
||||
const shown = sound ? volume : 0;
|
||||
const icon = volumeIcon(sound, volume);
|
||||
return (
|
||||
<div className="volume-control" ref={ref}>
|
||||
<button
|
||||
type="button"
|
||||
className={className}
|
||||
aria-label={`소리 크기 ${shown}`}
|
||||
title={`소리 크기 ${shown}`}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
>
|
||||
{label ? (
|
||||
<>
|
||||
<span className="rb-ico">{icon}</span>
|
||||
<span className="rb-lbl">{shown}</span>
|
||||
</>
|
||||
) : (
|
||||
<span aria-hidden>{icon}</span>
|
||||
)}
|
||||
</button>
|
||||
{open && (
|
||||
<div className="volume-pop" role="dialog" aria-label="소리 크기">
|
||||
<div className="row" style={{ justifyContent: 'space-between', flexWrap: 'nowrap', gap: 8 }}>
|
||||
<strong>소리 크기</strong>
|
||||
<output className="volume-num" aria-live="polite">
|
||||
{shown}
|
||||
</output>
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={100}
|
||||
step={5}
|
||||
value={shown}
|
||||
aria-label="소리 크기 (0~100)"
|
||||
onChange={(e) => updateSettings({ volume: Number(e.target.value), sound: Number(e.target.value) > 0 })}
|
||||
onPointerUp={() => sfx.good()}
|
||||
onKeyUp={() => sfx.click()}
|
||||
/>
|
||||
<div className="row" style={{ justifyContent: 'space-between', flexWrap: 'nowrap', gap: 8 }}>
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => updateSettings(sound && volume > 0 ? { sound: false } : { sound: true, volume: volume > 0 ? volume : 50 })}>
|
||||
{sound && volume > 0 ? '🔇 끄기' : '🔊 켜기'}
|
||||
</button>
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => (updateSettings({ sound: true, volume: 50 }), sfx.good())}>
|
||||
기본(50)
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { ChatMessage, nameHue, sameRun } from '../../components/ChatMessage';
|
||||
import { useStickToBottom } from '../../lib/useStickToBottom';
|
||||
import { useChatOutbox, useTypingSignal } from '../../lib/chat-input';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -396,6 +397,7 @@ const runKey = (l: Line | undefined) => l && { from: l.k === 'chat' ? l.from : n
|
||||
function ChatBox({ v, players, me, act }: { v: LiarView; players: Record<string, PublicUser>; me: string | null; act: (a: unknown) => void }) {
|
||||
const [text, setText] = useState('');
|
||||
const { ref: listRef, pin } = useStickToBottom<HTMLDivElement>();
|
||||
const send = useChatOutbox((t: string) => act({ type: 'chat', text: t }), 750);
|
||||
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 })),
|
||||
@@ -403,6 +405,7 @@ function ChatBox({ v, players, me, act }: { v: LiarView; players: Record<string,
|
||||
].sort((a, b) => a.at - b.at || (a.k === b.k ? 0 : a.k === 'sys' ? -1 : 1));
|
||||
const talk = v.phase.kind === 'discussion' || v.phase.kind === 'vote';
|
||||
const canWrite = !!v.my?.canChat && talk;
|
||||
const typing = useTypingSignal('game', canWrite);
|
||||
const why = !me || !v.my ? '관전 중에는 채팅을 쓸 수 없어요.' : talk ? (v.my.chatWhy ?? '') : v.phase.kind === 'describe' ? '토론 채팅은 설명이 다 끝나면 열려요.' : (v.my.chatWhy ?? '');
|
||||
return (
|
||||
<section className="lg-box lg-chat" aria-label="토론 채팅">
|
||||
@@ -428,12 +431,25 @@ function ChatBox({ v, players, me, act }: { v: LiarView; players: Record<string,
|
||||
e.preventDefault();
|
||||
const t = text.trim();
|
||||
if (!t) return;
|
||||
act({ type: 'chat', text: t.slice(0, 200) });
|
||||
send(t.slice(0, 200));
|
||||
setText('');
|
||||
typing.stop();
|
||||
pin();
|
||||
}}
|
||||
>
|
||||
<input className="input" value={text} onChange={(e) => setText(e.target.value)} maxLength={200} placeholder="누가 라이어일까요?" aria-label="토론 채팅 메시지" enterKeyHint="send" />
|
||||
<input
|
||||
className="input"
|
||||
value={text}
|
||||
onChange={(e) => {
|
||||
setText(e.target.value);
|
||||
typing.onText(e.target.value);
|
||||
}}
|
||||
onBlur={typing.stop}
|
||||
maxLength={200}
|
||||
placeholder="누가 라이어일까요?"
|
||||
aria-label="토론 채팅 메시지"
|
||||
enterKeyHint="send"
|
||||
/>
|
||||
<button className="btn btn-primary btn-sm">보내기</button>
|
||||
</form>
|
||||
) : (
|
||||
|
||||
@@ -14,6 +14,7 @@ import { useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { ChatMessage, sameRun } from '../../components/ChatMessage';
|
||||
import { useStickToBottom } from '../../lib/useStickToBottom';
|
||||
import { useChatOutbox, useTypingSignal } from '../../lib/chat-input';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -401,6 +402,8 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record<string
|
||||
const [text, setText] = useState('');
|
||||
const [seen, setSeen] = useState<Record<string, number>>({});
|
||||
const { ref: listRef, pin } = useStickToBottom<HTMLDivElement>();
|
||||
// Lines typed quickly all go out, one per CHAT_GAP_MS (the game refuses faster ones).
|
||||
const send = useChatOutbox<{ channel: Channel; text: string }>((m) => act({ type: 'chat', ...m }), 750);
|
||||
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}`;
|
||||
@@ -424,6 +427,8 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record<string
|
||||
useEffect(pin, [cur, pin]);
|
||||
const ch = v.channels.find((c) => c.channel === cur);
|
||||
const canWrite = !!ch?.canWrite;
|
||||
// "입력 중" only from the public 전체 chat (night channels stay secret).
|
||||
const typing = useTypingSignal('game', canWrite && cur === 'day');
|
||||
const why = ch ? ch.why : me ? '이 채팅은 읽기만 할 수 있어요.' : '관전 중에는 채팅을 쓸 수 없어요.';
|
||||
const onTabKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
|
||||
@@ -477,15 +482,20 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record<string
|
||||
e.preventDefault();
|
||||
const t = text.trim();
|
||||
if (!t) return;
|
||||
act({ type: 'chat', channel: cur, text: t.slice(0, 200) });
|
||||
send({ channel: cur, text: t.slice(0, 200) });
|
||||
setText('');
|
||||
typing.stop();
|
||||
pin();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
className="input"
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onChange={(e) => {
|
||||
setText(e.target.value);
|
||||
typing.onText(e.target.value);
|
||||
}}
|
||||
onBlur={typing.stop}
|
||||
maxLength={200}
|
||||
placeholder={`${CHANNEL_KO[cur]} 채팅에 쓰기`}
|
||||
aria-label={`${CHANNEL_KO[cur]} 채팅 메시지`}
|
||||
|
||||
71
apps/web/src/lib/chat-input.ts
Normal file
71
apps/web/src/lib/chat-input.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* Chat input helpers shared by the room chat and the games with their own chat (마피아, 라이어 게임).
|
||||
*
|
||||
* - `useChatOutbox`: every line typed is sent, in order. The server allows a short burst and then about one line
|
||||
* per `gapMs`; lines typed faster than that wait in a small queue instead of being refused ("조금 천천히").
|
||||
* - `useTypingSignal`: tells the others "입력 중" while there is text in the box (renewed every 2 s, cleared when the
|
||||
* box is emptied or the line is sent, and when the box goes away).
|
||||
*/
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
import { socket } from '../net/socket';
|
||||
|
||||
const MAX_QUEUE = 10;
|
||||
|
||||
export function useChatOutbox<T = string>(send: (item: T) => void, gapMs: number) {
|
||||
const queue = useRef<T[]>([]);
|
||||
const last = useRef(-Infinity);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const sendRef = useRef(send);
|
||||
sendRef.current = send;
|
||||
const pump = useCallback(() => {
|
||||
timer.current = null;
|
||||
const wait = last.current + gapMs - Date.now();
|
||||
if (wait > 0) {
|
||||
timer.current = setTimeout(pump, wait);
|
||||
return;
|
||||
}
|
||||
const next = queue.current.shift();
|
||||
if (next === undefined) return;
|
||||
last.current = Date.now();
|
||||
sendRef.current(next);
|
||||
if (queue.current.length) timer.current = setTimeout(pump, gapMs);
|
||||
}, [gapMs]);
|
||||
useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []);
|
||||
return useCallback(
|
||||
(item: T) => {
|
||||
if (queue.current.length >= MAX_QUEUE) return;
|
||||
queue.current.push(item);
|
||||
if (!timer.current) pump();
|
||||
},
|
||||
[pump],
|
||||
);
|
||||
}
|
||||
|
||||
const RENEW_MS = 2000;
|
||||
|
||||
export function useTypingSignal(ch: 'room' | 'game', enabled = true) {
|
||||
const sentAt = useRef(0);
|
||||
const on = useRef(false);
|
||||
const stop = useCallback(() => {
|
||||
if (!on.current) return;
|
||||
on.current = false;
|
||||
sentAt.current = 0;
|
||||
socket.send({ t: 'typing', on: false, ch });
|
||||
}, [ch]);
|
||||
const onText = useCallback(
|
||||
(text: string) => {
|
||||
if (!enabled || !text.trim()) return stop();
|
||||
const now = Date.now();
|
||||
if (on.current && now - sentAt.current < RENEW_MS) return;
|
||||
on.current = true;
|
||||
sentAt.current = now;
|
||||
socket.send({ t: 'typing', on: true, ch });
|
||||
},
|
||||
[ch, enabled, stop],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!enabled) stop();
|
||||
}, [enabled, stop]);
|
||||
useEffect(() => stop, [stop]);
|
||||
return { onText, stop };
|
||||
}
|
||||
@@ -34,6 +34,8 @@ interface RoomStore {
|
||||
result: GameResultView | null;
|
||||
chat: ChatLine[];
|
||||
emotes: { id: number; from: string; emote: string }[];
|
||||
/** People typing right now: user id → where and until when (ms, local clock). */
|
||||
typing: Record<string, { ch: 'room' | 'game'; until: number }>;
|
||||
pending: number | null;
|
||||
slow: boolean;
|
||||
rttMs: number | null;
|
||||
@@ -42,6 +44,14 @@ interface RoomStore {
|
||||
kicked: boolean;
|
||||
}
|
||||
|
||||
/** A "입력 중" signal lasts this long unless renewed (the typer renews it every couple of seconds). */
|
||||
const TYPING_MS = 5000;
|
||||
const withoutTyping = (t: RoomStore['typing'], id: string | undefined): RoomStore['typing'] => {
|
||||
if (!id || !(id in t)) return t;
|
||||
const { [id]: _gone, ...rest } = t;
|
||||
return rest;
|
||||
};
|
||||
|
||||
export const useRoom = create<RoomStore>(() => ({
|
||||
status: 'idle',
|
||||
me: null,
|
||||
@@ -52,6 +62,7 @@ export const useRoom = create<RoomStore>(() => ({
|
||||
result: null,
|
||||
chat: [],
|
||||
emotes: [],
|
||||
typing: {},
|
||||
pending: null,
|
||||
slow: false,
|
||||
rttMs: null,
|
||||
@@ -208,7 +219,7 @@ class GameSocket {
|
||||
join(code: string, as: 'player' | 'spectator' = 'player'): void {
|
||||
const cur = useRoom.getState();
|
||||
if (cur.code !== code) {
|
||||
useRoom.setState({ code, room: null, roomSeq: -1, game: null, result: null, chat: [], joinError: null, kicked: false, pending: null });
|
||||
useRoom.setState({ code, room: null, roomSeq: -1, game: null, result: null, chat: [], typing: {}, joinError: null, kicked: false, pending: null });
|
||||
}
|
||||
this.start();
|
||||
this.send({ t: 'join', code, as });
|
||||
@@ -216,14 +227,14 @@ class GameSocket {
|
||||
|
||||
leave(): void {
|
||||
this.send({ t: 'leave' });
|
||||
useRoom.setState({ code: null, room: null, roomSeq: -1, game: null, result: null, chat: [], pending: null });
|
||||
useRoom.setState({ code: null, room: null, roomSeq: -1, game: null, result: null, chat: [], typing: {}, pending: null });
|
||||
}
|
||||
|
||||
/** Left the room page (홈, 규칙…) without leaving: the seat stays, but the room no longer counts us as there. */
|
||||
detach(code: string): void {
|
||||
if (useRoom.getState().code !== code) return;
|
||||
this.send({ t: 'detach' });
|
||||
useRoom.setState({ code: null, room: null, roomSeq: -1, game: null, result: null, chat: [], pending: null });
|
||||
useRoom.setState({ code: null, room: null, roomSeq: -1, game: null, result: null, chat: [], typing: {}, pending: null });
|
||||
}
|
||||
|
||||
/** Sends a game action; returns false when not connected. */
|
||||
@@ -290,7 +301,17 @@ class GameSocket {
|
||||
useRoom.setState({ result: m.result });
|
||||
break;
|
||||
case 'chat':
|
||||
useRoom.setState({ chat: [...st.chat, { id: this.chatId++, from: m.from, text: m.text, at: m.at }].slice(-100) });
|
||||
useRoom.setState({ chat: [...st.chat, { id: this.chatId++, from: m.from, text: m.text, at: m.at }].slice(-100), typing: withoutTyping(st.typing, m.from?.id) });
|
||||
break;
|
||||
case 'typing':
|
||||
if (m.on) {
|
||||
const until = Date.now() + TYPING_MS;
|
||||
useRoom.setState({ typing: { ...st.typing, [m.from]: { ch: m.ch, until } } });
|
||||
setTimeout(() => {
|
||||
const cur = useRoom.getState().typing[m.from];
|
||||
if (cur && cur.until <= Date.now()) useRoom.setState((s) => ({ typing: withoutTyping(s.typing, m.from) }));
|
||||
}, TYPING_MS + 50);
|
||||
} else useRoom.setState({ typing: withoutTyping(st.typing, m.from) });
|
||||
break;
|
||||
case 'emote': {
|
||||
const id = this.chatId++;
|
||||
|
||||
@@ -58,6 +58,12 @@ export default function MePage() {
|
||||
<Seg label="글자 크기" value={settings.fontScale} options={[['normal', '보통'], ['large', '크게'], ['xlarge', '아주 크게']]} onChange={(fontScale) => updateSettings({ fontScale })} />
|
||||
<Seg label="화면 색" value={settings.theme} options={[['auto', '자동'], ['light', '밝게'], ['dark', '어둡게']]} onChange={(theme) => updateSettings({ theme })} />
|
||||
<Seg label="소리" value={settings.sound ? 'on' : 'off'} options={[['on', '켜기'], ['off', '끄기']]} onChange={(v) => updateSettings({ sound: v === 'on' })} />
|
||||
<label className="stack" style={{ gap: 4 }}>
|
||||
<span style={{ fontWeight: 700 }}>
|
||||
소리 크기 <span className="muted">{settings.volume} (기본 50, 이 기기에만 저장)</span>
|
||||
</span>
|
||||
<input type="range" min={0} max={100} step={5} value={settings.volume} aria-label="소리 크기 (0~100)" style={{ accentColor: 'var(--primary)' }} onChange={(e) => updateSettings({ volume: Number(e.target.value) })} />
|
||||
</label>
|
||||
<Seg label="진동" value={settings.vibrate ? 'on' : 'off'} options={[['on', '켜기'], ['off', '끄기']]} onChange={(v) => updateSettings({ vibrate: v === 'on' })} />
|
||||
<Seg
|
||||
label="돌·카드 놓기"
|
||||
|
||||
@@ -15,6 +15,7 @@ import type { GameUI } from '../games/types';
|
||||
import { sounds } from '../lib/feedback';
|
||||
import { ChatPanel, EmoteBubbles, useChatSeen } from '../components/ChatPanel';
|
||||
import { BotActivity } from '../components/BotActivity';
|
||||
import { VolumeControl } from '../components/VolumeControl';
|
||||
import { useWide } from '../lib/media';
|
||||
import { GameHelp } from '../components/GameHelp';
|
||||
import { PlayerName } from '../components/PlayerCard';
|
||||
@@ -210,6 +211,7 @@ function Room({ code, me }: { code: string; me: PublicUser }) {
|
||||
<ChatButton onOpen={() => setChatOpen(true)} />
|
||||
</span>
|
||||
)}
|
||||
<VolumeControl className="btn btn-ghost btn-sm rb-btn" label />
|
||||
<button className="btn btn-ghost btn-sm rb-btn" onClick={() => nav(`/rules/${room.gameId}`)} aria-label="규칙 보기">
|
||||
<span className="rb-ico">📖</span>
|
||||
<span className="rb-lbl">규칙</span>
|
||||
@@ -681,7 +683,7 @@ function GameView({ room, ui, me, players, pending, slow }: { room: RoomView; ui
|
||||
{status}
|
||||
<GameHelp room={room} ui={ui} title={gameName(room.gameId)} me={me.id} players={players} />
|
||||
</div>
|
||||
<BotActivity room={room} />
|
||||
<BotActivity room={room} ch={ui.ownChat ? 'game' : undefined} />
|
||||
{room.status === 'paused' && room.hostId === me.id && (
|
||||
<button className="btn btn-danger btn-block" onClick={() => socket.send({ t: 'void' })}>
|
||||
⏹ 게임 끝내기(무효)
|
||||
|
||||
@@ -668,6 +668,47 @@ label.field {
|
||||
.theme-toggle:hover {
|
||||
background: var(--surface-2);
|
||||
}
|
||||
.header-tools {
|
||||
margin-left: auto;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
.header-tools .theme-toggle {
|
||||
margin-left: 0;
|
||||
}
|
||||
/* Site volume: speaker button + a small slider panel under it. */
|
||||
.volume-control {
|
||||
position: relative;
|
||||
}
|
||||
.volume-pop {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: calc(100% + 6px);
|
||||
width: 240px;
|
||||
padding: 12px 14px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.16);
|
||||
z-index: 45;
|
||||
animation: anim-slide-up 0.15s ease-out both;
|
||||
}
|
||||
.volume-pop input[type='range'] {
|
||||
width: 100%;
|
||||
accent-color: var(--primary);
|
||||
min-height: 32px;
|
||||
}
|
||||
.volume-num {
|
||||
font-weight: 800;
|
||||
font-variant-numeric: tabular-nums;
|
||||
min-width: 2.5em;
|
||||
text-align: right;
|
||||
}
|
||||
.header-user {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -163,6 +163,57 @@ try {
|
||||
await b.getByRole('button', { name: '채팅', exact: true }).waitFor();
|
||||
});
|
||||
|
||||
await step('빠르게 여러 번 Enter: 전부 순서대로 들어감', async () => {
|
||||
await a.waitForTimeout(1500);
|
||||
const input = a.locator('.chat-panel input[aria-label="메시지"]').first();
|
||||
for (let i = 1; i <= 7; i++) {
|
||||
await input.fill(`연타 ${i}`);
|
||||
await input.press('Enter');
|
||||
}
|
||||
for (let i = 1; i <= 7; i++) await a.locator('.chat-line', { hasText: `연타 ${i}` }).waitFor({ timeout: 10_000 });
|
||||
const got = await a.locator('.chat-line .chat-text', { hasText: /^연타 \d$/ }).allInnerTexts();
|
||||
if (got.join(',') !== [1, 2, 3, 4, 5, 6, 7].map((i) => `연타 ${i}`).join(',')) throw new Error(`order/lost: ${got.join(',')}`);
|
||||
// The other side got them all too (phone sheet closed: the badge counts 7).
|
||||
await b.getByRole('button', { name: '채팅, 새 메시지 7개' }).waitFor({ timeout: 5000 });
|
||||
});
|
||||
|
||||
await step('사람도 "입력 중" 표시: 치는 동안 보이고, 보내면 사라짐', async () => {
|
||||
const input = a.locator('.chat-panel input[aria-label="메시지"]').first();
|
||||
await input.fill('지금 치는 중');
|
||||
await b.getByRole('button', { name: /^채팅/ }).click();
|
||||
const sheet = b.getByRole('dialog', { name: '채팅' });
|
||||
await sheet.locator('[data-person]', { hasText: '호랑이 입력 중' }).waitFor({ timeout: 5000 });
|
||||
await b.waitForTimeout(300);
|
||||
await b.screenshot({ path: join(SHOTS, 'chat-typing-phone.png') });
|
||||
await input.press('Enter');
|
||||
await sheet.locator('[data-person]').waitFor({ state: 'detached', timeout: 5000 });
|
||||
// Nobody sees their own typing.
|
||||
await sheet.locator('input[aria-label="메시지"]').fill('나도 치는 중');
|
||||
await a.locator('[data-person]', { hasText: '고양이 입력 중' }).waitFor({ timeout: 5000 });
|
||||
if (await b.locator('[data-person]', { hasText: '고양이' }).count()) throw new Error('sees own typing');
|
||||
await sheet.locator('input[aria-label="메시지"]').fill('');
|
||||
await a.locator('[data-person]').waitFor({ state: 'detached', timeout: 5000 });
|
||||
await sheet.getByRole('button', { name: '닫기' }).click();
|
||||
});
|
||||
|
||||
await step('소리 크기: 방 막대 오른쪽 위, 기본 50, 0~100', async () => {
|
||||
const btn = a.locator('.room-bar').getByRole('button', { name: /^소리 크기/ });
|
||||
if ((await btn.getAttribute('aria-label')) !== '소리 크기 50') throw new Error(`default: ${await btn.getAttribute('aria-label')}`);
|
||||
await btn.click();
|
||||
const slider = a.getByRole('slider', { name: '소리 크기 (0~100)' });
|
||||
if ((await slider.getAttribute('min')) !== '0' || (await slider.getAttribute('max')) !== '100') throw new Error('range');
|
||||
await slider.fill('30');
|
||||
await a.locator('.room-bar').getByRole('button', { name: '소리 크기 30' }).waitFor();
|
||||
await a.waitForTimeout(300);
|
||||
await a.screenshot({ path: join(SHOTS, 'volume-room-pc.png') });
|
||||
await a.keyboard.press('Escape');
|
||||
const saved = await a.evaluate(() => JSON.parse(localStorage.getItem('bg.settings') ?? '{}').volume);
|
||||
if (saved !== 30) throw new Error(`not saved: ${saved}`);
|
||||
// Phone room bar has it too.
|
||||
await b.locator('.room-bar').getByRole('button', { name: /^소리 크기/ }).waitFor();
|
||||
await b.screenshot({ path: join(SHOTS, 'volume-roombar-phone.png') });
|
||||
});
|
||||
|
||||
await step('게임 중(PC 옆 칸): 새 메시지마다 맨 아래', async () => {
|
||||
await a.getByRole('button', { name: '▶ 게임 시작' }).click();
|
||||
await a.getByRole('button', { name: '시작하기' }).click();
|
||||
|
||||
@@ -36,6 +36,7 @@ export const ClientMessage = z.discriminatedUnion('t', [
|
||||
z.object({ t: z.literal('act'), cs: z.number().int().min(1), a: z.unknown() }),
|
||||
z.object({ t: z.literal('chat'), text: z.string().min(1).max(CHAT_MAX) }),
|
||||
z.object({ t: z.literal('emote'), id: z.string().max(20) }),
|
||||
z.object({ t: z.literal('typing'), on: z.boolean(), ch: z.enum(['room', 'game']).default('room') }),
|
||||
z.object({ t: z.literal('rematch') }),
|
||||
z.object({ t: z.literal('void') }),
|
||||
z.object({ t: z.literal('sync') }),
|
||||
|
||||
@@ -96,6 +96,8 @@ export type ServerMessage =
|
||||
| { t: 'reject'; cs: number; reason: string }
|
||||
| { t: 'chat'; from: PublicUser | null; text: string; at: number; channel?: string }
|
||||
| { t: 'emote'; from: string; id: string }
|
||||
/** Someone is typing (room chat, or the game's public chat when the game has its own). Expires on its own after a few seconds. */
|
||||
| { t: 'typing'; from: string; on: boolean; ch: 'room' | 'game' }
|
||||
| { t: 'result'; seq: number; result: GameResultView }
|
||||
| { t: 'notice'; code: string; message: string }
|
||||
| { t: 'error'; code: string; message: string }
|
||||
|
||||
Reference in New Issue
Block a user