채팅 소리(스타크래프트 같은 "띠릭"): 새 채팅 줄마다(내가 보낸 줄도) 맑은 두 음이 올라가는 짧은 소리. 크기는 게임 소리 기준(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:
EJClaw
2026-10-14 09:42:31 +09:00
parent e0139f412e
commit b7d5b3ad75
10 changed files with 212 additions and 7 deletions

View File

@@ -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('');

View File

@@ -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('');

View 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);
});

View File

@@ -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 {

View File

@@ -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) {

View File

@@ -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');