채팅 소리(스타크래프트 같은 "띠릭"): 새 채팅 줄마다(내가 보낸 줄도) 맑은 두 음이 올라가는 짧은 소리. 크기는 게임 소리 기준(0.15)의 90%로 소리 크기 설정을 그대로 따르고, 소리 끄기면 안 남. 몰려 온 줄은 한 번만. 방에 (다시) 들어올 때 서버가 다시 보내는 지난 채팅은 replay 표시로 조용히. 마피아·라이어 게임 안 채팅도 같은 소리. feedback.test.ts, room.test.ts, chat.e2e.ts에 확인 추가
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -239,6 +239,22 @@ describe('Room chat (2026-10-13)', () => {
|
||||
expect(b.msgs.filter((m) => m.t === 'chat').map((m) => (m as { text: string }).text)).toEqual(lines);
|
||||
});
|
||||
|
||||
test('lines sent before joining come back marked as replay; live lines are not', () => {
|
||||
const { room, conn } = harness();
|
||||
const a = conn('A');
|
||||
room.join(a, 'player');
|
||||
room.chat('A', '먼저 한 말');
|
||||
const b = conn('B');
|
||||
room.join(b, 'player');
|
||||
room.chat('A', '지금 한 말');
|
||||
const got = b.msgs.filter((m) => m.t === 'chat').map((m) => [(m as { text: string }).text, (m as { replay?: true }).replay ?? false]);
|
||||
expect(got).toEqual([
|
||||
['먼저 한 말', true],
|
||||
['지금 한 말', false],
|
||||
]);
|
||||
expect((a.msgs.find((m) => m.t === 'chat') as { replay?: true }).replay).toBeUndefined();
|
||||
});
|
||||
|
||||
test('typing at a person\'s pace (a line every 0.4 s) never waits', () => {
|
||||
const { room, clock, conn } = harness();
|
||||
room.join(conn('A'), 'player');
|
||||
|
||||
@@ -530,7 +530,7 @@ export class Room {
|
||||
const st = this.stateMessage(u, undefined, true);
|
||||
if (st) conn.send(st);
|
||||
if (this.status === 'finished' && this.lastResult) conn.send({ t: 'result', seq: this.seq, result: this.lastResult });
|
||||
for (const m of this.chatLog) conn.send(m);
|
||||
for (const m of this.chatLog) conn.send({ ...m, replay: true });
|
||||
this.scheduleTimer();
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ 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, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { haptic, sfx, sounds, tone, useChatSound } from '../../lib/feedback';
|
||||
import { cssEsc, useBanner, type BannerTone } from '../card-fx';
|
||||
import { ChatMessage, nameHue, sameRun } from '../../components/ChatMessage';
|
||||
import { useStickToBottom } from '../../lib/useStickToBottom';
|
||||
@@ -779,6 +779,8 @@ function useLiarFx(v: LiarView, me: string | null, players: Record<string, Publi
|
||||
}
|
||||
|
||||
function LiarBoard({ view: v, me, players, act, pending }: BoardProps<LiarView>) {
|
||||
// The room chat is closed while playing, so the 토론 chat lines play the chat sound.
|
||||
useChatSound(v.chat.at(-1)?.n);
|
||||
const ph = v.phase;
|
||||
const my = v.my;
|
||||
const [announce, setAnnounce] = useState('');
|
||||
|
||||
@@ -11,7 +11,7 @@ import type { Channel, ChatView, MafiaOptions, MafiaView, PlayerView, PrivateRes
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { haptic, noise, sfx, sounds, tone, useChatSound } from '../../lib/feedback';
|
||||
import { useBanner, type BannerTone } from '../card-fx';
|
||||
import { ChatMessage, sameRun } from '../../components/ChatMessage';
|
||||
import { useStickToBottom } from '../../lib/useStickToBottom';
|
||||
@@ -854,6 +854,8 @@ function useMafiaFx(v: MafiaView, players: Record<string, PublicUser>, showBanne
|
||||
}
|
||||
|
||||
function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView>) {
|
||||
// The room chat is closed while playing, so this game's own chat lines play the chat sound.
|
||||
useChatSound(v.chat.at(-1)?.key);
|
||||
const ph = v.phase;
|
||||
const my = v.my;
|
||||
const [announce, setAnnounce] = useState('');
|
||||
|
||||
111
apps/web/src/lib/feedback.test.ts
Normal file
111
apps/web/src/lib/feedback.test.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import { beforeEach, expect, mock, test } from 'bun:test';
|
||||
|
||||
/** A fake Web Audio graph that records every oscillator note: frequency, start and peak level. */
|
||||
interface Note {
|
||||
freq: number;
|
||||
start: number;
|
||||
peak: number;
|
||||
}
|
||||
let notes: Note[] = [];
|
||||
let master: FakeParam | null = null;
|
||||
class FakeParam {
|
||||
value = 0;
|
||||
peak = 0;
|
||||
setValueAtTime(v: number) {
|
||||
this.value = v;
|
||||
this.peak = Math.max(this.peak, v);
|
||||
}
|
||||
exponentialRampToValueAtTime(v: number) {
|
||||
this.peak = Math.max(this.peak, v);
|
||||
}
|
||||
}
|
||||
class FakeCtx {
|
||||
state = 'running';
|
||||
currentTime = 0;
|
||||
destination = {};
|
||||
resume() {}
|
||||
createGain() {
|
||||
const gain = new FakeParam();
|
||||
return {
|
||||
gain,
|
||||
connect: (to: unknown) => {
|
||||
if (to === this.destination) master = gain;
|
||||
return to;
|
||||
},
|
||||
};
|
||||
}
|
||||
createOscillator() {
|
||||
const frequency = new FakeParam();
|
||||
let g: { gain: FakeParam } | null = null;
|
||||
return {
|
||||
type: 'sine',
|
||||
frequency,
|
||||
connect(to: { gain: FakeParam }) {
|
||||
g = to;
|
||||
return { connect: () => {} };
|
||||
},
|
||||
start(t: number) {
|
||||
notes.push({ freq: frequency.value, start: t, peak: g!.gain.peak });
|
||||
},
|
||||
stop() {},
|
||||
};
|
||||
}
|
||||
}
|
||||
(globalThis as any).AudioContext = FakeCtx;
|
||||
|
||||
// The real settings store needs a page (document); only the sound settings matter here.
|
||||
let settings = { sound: true, volume: 100 };
|
||||
mock.module('../store/session', () => ({ useSession: { getState: () => ({ settings }) } }));
|
||||
const { CHAT_LEVEL, GAME_LEVEL, chatSound, sounds } = await import('./feedback');
|
||||
|
||||
const setVolume = (volume: number, sound = true) => {
|
||||
settings = { sound, volume };
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
notes = [];
|
||||
});
|
||||
|
||||
test('chat sound is 10% under the game sounds', () => {
|
||||
expect(GAME_LEVEL).toBe(0.15);
|
||||
expect(CHAT_LEVEL).toBeCloseTo(GAME_LEVEL * 0.9, 10);
|
||||
setVolume(100);
|
||||
sounds.myTurn(); // a typical game sound at the usual level
|
||||
const game = Math.max(...notes.map((n) => n.peak));
|
||||
notes = [];
|
||||
chatSound();
|
||||
// Notes playing at the same moment add up; the loudest moment of the chat sound is 90% of a game sound.
|
||||
const byStart = new Map<number, number>();
|
||||
for (const n of notes) byStart.set(n.start, (byStart.get(n.start) ?? 0) + n.peak);
|
||||
const loudest = Math.max(...byStart.values());
|
||||
expect(loudest).toBeCloseTo(game * 0.9, 6);
|
||||
// Two rising notes ("띠릭").
|
||||
const mains = [...new Set(notes.map((n) => n.start))].sort().map((t) => Math.min(...notes.filter((n) => n.start === t).map((n) => n.freq)));
|
||||
expect(mains).toEqual([1568, 2093]);
|
||||
});
|
||||
|
||||
test('chat sound follows the volume setting and is silent when sound is off', async () => {
|
||||
await new Promise((r) => setTimeout(r, 100)); // past the burst guard
|
||||
setVolume(50);
|
||||
chatSound();
|
||||
expect(notes.length).toBeGreaterThan(0);
|
||||
expect(master!.value).toBe(0.5);
|
||||
notes = [];
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
setVolume(50, false);
|
||||
chatSound();
|
||||
expect(notes).toEqual([]);
|
||||
});
|
||||
|
||||
test('lines arriving in a burst share one sound', async () => {
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
setVolume(100);
|
||||
chatSound();
|
||||
const one = notes.length;
|
||||
chatSound();
|
||||
chatSound();
|
||||
expect(notes.length).toBe(one);
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
chatSound();
|
||||
expect(notes.length).toBe(one * 2);
|
||||
});
|
||||
@@ -4,6 +4,7 @@
|
||||
* are now volume 100, so the default plays them at half). Games use `sfx.*` (shared palette) or `tone`/`noise`
|
||||
* directly for something of their own.
|
||||
*/
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useSession } from '../store/session';
|
||||
|
||||
let ctx: AudioContext | null = null;
|
||||
@@ -187,6 +188,37 @@ export const sounds = {
|
||||
buzz: () => tone(180, 260, 'square', 0.08),
|
||||
};
|
||||
|
||||
/** The usual level of a game sound at volume 100 (`tone`'s default). */
|
||||
export const GAME_LEVEL = 0.15;
|
||||
/** Chat sound: 10% under the game sounds (it follows the same volume setting). */
|
||||
export const CHAT_LEVEL = GAME_LEVEL * 0.9;
|
||||
let lastChatAt = -Infinity;
|
||||
|
||||
/**
|
||||
* StarCraft-like chat "띠릭": two quick, glassy notes going up (sine + a soft octave on top), about 0.2 s.
|
||||
* The layers of a note add up to CHAT_LEVEL at most. Lines arriving in a burst share one sound.
|
||||
*/
|
||||
export function chatSound(): void {
|
||||
const now = performance.now();
|
||||
if (now - lastChatAt < 80) return;
|
||||
lastChatAt = now;
|
||||
const main = CHAT_LEVEL * 0.8;
|
||||
const air = CHAT_LEVEL * 0.2;
|
||||
tone(1568, 70, 'sine', main, 0, { attack: 3, slideTo: 1661 });
|
||||
tone(3136, 50, 'sine', air, 0, { attack: 3 });
|
||||
tone(2093, 140, 'sine', main, 65, { attack: 3 });
|
||||
tone(4186, 90, 'sine', air, 65, { attack: 3 });
|
||||
}
|
||||
|
||||
/** Plays the chat sound whenever `lastKey` (the newest live chat line) changes after the first render. */
|
||||
export function useChatSound(lastKey: string | number | undefined): void {
|
||||
const prev = useRef(lastKey);
|
||||
useEffect(() => {
|
||||
if (lastKey !== undefined && lastKey !== prev.current) chatSound();
|
||||
prev.current = lastKey;
|
||||
}, [lastKey]);
|
||||
}
|
||||
|
||||
export function haptic(pattern: number | number[]): void {
|
||||
if (!useSession.getState().settings.vibrate) return;
|
||||
try {
|
||||
|
||||
@@ -15,6 +15,8 @@ export interface ChatLine {
|
||||
from: PublicUser | null;
|
||||
text: string;
|
||||
at: number;
|
||||
/** Arrived just now (not resent history on joining): plays the chat sound. */
|
||||
live: boolean;
|
||||
}
|
||||
|
||||
export interface GameState {
|
||||
@@ -307,7 +309,7 @@ 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), typing: withoutTyping(st.typing, m.from?.id) });
|
||||
useRoom.setState({ chat: [...st.chat, { id: this.chatId++, from: m.from, text: m.text, at: m.at, live: !m.replay }].slice(-100), typing: withoutTyping(st.typing, m.from?.id) });
|
||||
break;
|
||||
case 'typing':
|
||||
if (m.on) {
|
||||
|
||||
@@ -13,7 +13,7 @@ import { useSession } from '../store/session';
|
||||
import { OptionSync, withLocks } from '../lib/option-sync';
|
||||
import { loadGameUI } from '../games/registry';
|
||||
import type { GameUI } from '../games/types';
|
||||
import { sounds } from '../lib/feedback';
|
||||
import { sounds, useChatSound } from '../lib/feedback';
|
||||
import { ChatPanel, EmoteBubbles, useChatSeen } from '../components/ChatPanel';
|
||||
import { BotActivity } from '../components/BotActivity';
|
||||
import { VolumeControl } from '../components/VolumeControl';
|
||||
@@ -119,6 +119,12 @@ function Room({ code, me }: { code: string; me: PublicUser }) {
|
||||
}, [room]);
|
||||
|
||||
useTurnTitle(ui, game?.view, me.id);
|
||||
// Every new room chat line (mine too, like StarCraft) plays the chat sound; history resent on joining does not.
|
||||
const lastLiveChat = useRoom((s) => {
|
||||
const l = s.chat.at(-1);
|
||||
return l?.live ? l.id : undefined;
|
||||
});
|
||||
useChatSound(lastLiveChat);
|
||||
// Inside a room the room bar replaces the site header, so the board gets that height back.
|
||||
useEffect(() => {
|
||||
document.documentElement.classList.add('in-room');
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* 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) + narrowed PC window (720–1099px) chat button.
|
||||
* PC lobby + PC in-game side panel + phone chat sheet (unread badge past 100 lines too) + narrowed PC window (720–1099px) chat button
|
||||
* + chat sound on live lines only.
|
||||
* Run: E2E_PORT=4641 bun e2e/chat.e2e.ts (needs apps/web/dist built)
|
||||
*/
|
||||
import { chromium, type Page } from 'playwright-core';
|
||||
@@ -241,6 +242,38 @@ try {
|
||||
if (await a.locator('.room-bar').getByRole('button', { name: /^채팅/ }).count()) throw new Error('chat button still on the wide bar');
|
||||
});
|
||||
|
||||
await step('채팅 소리: 새 줄마다 "띠릭"(보낸 사람도), 다시 들어올 때 받는 지난 줄은 조용히', async () => {
|
||||
// Count the chat sound's first note (1568 Hz) as it is scheduled.
|
||||
const rec = () => {
|
||||
const w = window as unknown as { __chatBeeps: number };
|
||||
w.__chatBeeps = 0;
|
||||
const orig = AudioParam.prototype.setValueAtTime;
|
||||
AudioParam.prototype.setValueAtTime = function (v: number, t: number) {
|
||||
if (v === 1568) w.__chatBeeps++;
|
||||
return orig.call(this, v, t);
|
||||
};
|
||||
};
|
||||
const beeps = (p: Page) => p.evaluate(() => (window as unknown as { __chatBeeps: number }).__chatBeeps);
|
||||
await b.addInitScript(rec);
|
||||
await a.evaluate(rec);
|
||||
await b.evaluate(rec);
|
||||
await a.waitForTimeout(200);
|
||||
await say(a, '소리 확인');
|
||||
await b.waitForFunction(() => (window as unknown as { __chatBeeps: number }).__chatBeeps === 1, null, { timeout: 5000 });
|
||||
await a.waitForFunction(() => (window as unknown as { __chatBeeps: number }).__chatBeeps === 1, null, { timeout: 5000 });
|
||||
// Reload: the room resends its chat history, which must not beep.
|
||||
await b.reload();
|
||||
await b.getByRole('button', { name: /^채팅/ }).click();
|
||||
const sheet = b.getByRole('dialog', { name: '채팅' });
|
||||
await sheet.locator('.chat-line', { hasText: '소리 확인' }).waitFor();
|
||||
await b.waitForTimeout(500);
|
||||
if ((await beeps(b)) !== 0) throw new Error(`history beeped ${await beeps(b)} times`);
|
||||
await say(a, '다시 들어온 뒤');
|
||||
await sheet.locator('.chat-line', { hasText: '다시 들어온 뒤' }).waitFor();
|
||||
await b.waitForFunction(() => (window as unknown as { __chatBeeps: number }).__chatBeeps === 1, null, { 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')}`);
|
||||
|
||||
@@ -109,7 +109,8 @@ export type ServerMessage =
|
||||
/** Events of streaming actions (e.g. drawing), relayed without a full view (docs/games/catchmind.md §5.5). */
|
||||
| { t: 'stream'; seq: number; events: unknown[]; cs?: number }
|
||||
| { t: 'reject'; cs: number; reason: string }
|
||||
| { t: 'chat'; from: PublicUser | null; text: string; at: number; channel?: string }
|
||||
/** `replay`: an earlier line resent on (re)joining, so the client shows it without the chat sound. */
|
||||
| { t: 'chat'; from: PublicUser | null; text: string; at: number; channel?: string; replay?: true }
|
||||
| { 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' }
|
||||
|
||||
Reference in New Issue
Block a user