5~7단계 게임: 숨긴 유튜브 동기화 재생(전원 준비·버퍼링이면 모두 멈춤·30초 늦은 사람 제외·재생 오류 곡 교체), 정답 판정·점수·정답 블록, 입력 중·단축키, 힌트·스킵·다시듣기 투표, 3모드, 결과·이어풀기·다시 하기, 퀴즈 저장·불러오기 + 마지막 사람이 나가면 방 바로 닫기

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-18 22:11:14 +09:00
parent af2dce5b50
commit 7266fc8d25
27 changed files with 3461 additions and 46 deletions

View File

@@ -1,26 +1,47 @@
/**
* Room chat (docs/06): one-line log, system lines centred, my unconfirmed lines at the bottom.
* Stage 4 uses it in the waiting room; the answer block and "입력 중" come with the game chat (stage 6).
* Room chat (docs/06): one-line log, system lines centred, my unconfirmed lines at the bottom,
* the 정답 줄 + 5줄 블록 drawn as one item, "입력 중" above the input. The game screen uses the big variant.
*/
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react';
import { CHAT_MAX, type ChatLine } from '@mq/shared/lite';
import { userHue } from './ui';
/** Fixed colour per user (joke-app --name-h). */
function hue(id: string): number {
let h = 0;
for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) >>> 0;
return h % 360;
export interface ChatHandle {
focus(): void;
}
export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: ChatLine[]; pending: { n: string; text: string }[]; meId: string; myName: string; onSend: (text: string) => void }) {
function typingText(names: string[]): string {
if (names.length === 1) return `${names[0]}님이 입력 중…`;
if (names.length === 2) return `${names[0]}, ${names[1]}님이 입력 중…`;
return `${names[0]}, ${names[1]} 외 ${names.length - 2}명이 입력 중…`;
}
export const ChatPanel = forwardRef<
ChatHandle,
{
lines: ChatLine[];
pending: { n: string; text: string }[];
meId: string;
myName: string;
onSend: (text: string) => void;
/** 입력 중 signal: true on start and every 2s while typing, false when cleared or sent. */
onTyping?: (on: boolean) => void;
typing?: string[];
big?: boolean;
}
>(function ChatPanel({ lines, pending, meId, myName, onSend, onTyping, typing = [], big }, ref) {
const [text, setText] = useState('');
const [stuck, setStuck] = useState(true);
const [unseen, setUnseen] = useState(false);
const logRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const lastSent = useRef('');
const typingAt = useRef(0);
// Changes whenever a line arrives, also once the log is capped at 200 lines.
const tick = `${lines.at(-1)?.seq ?? 0}:${pending.length}`;
useImperativeHandle(ref, () => ({ focus: () => inputRef.current?.focus() }), []);
// Auto-scroll only while the reader is at the bottom (docs/06 위로 스크롤하면 멈춤).
useLayoutEffect(() => {
const el = logRef.current;
@@ -37,17 +58,23 @@ export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: Cha
if (el) el.scrollTop = el.scrollHeight;
setStuck(true);
};
const stopTyping = () => {
if (typingAt.current) onTyping?.(false);
typingAt.current = 0;
};
const submit = () => {
const t = text.trim();
if (!t) return;
onSend(t.slice(0, CHAT_MAX));
lastSent.current = t;
setText('');
typingAt.current = 0;
toBottom();
};
const others = typing.filter((n) => n !== myName);
return (
<section className="card chat" aria-label="채팅">
<section className={`card chat ${big ? 'big' : ''}`} aria-label="채팅">
<div
className="chat-log"
ref={logRef}
@@ -60,20 +87,38 @@ export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: Cha
>
{lines.length === 0 && pending.length === 0 && <div className="chat-sys">아직 대화가 없어요. 먼저 인사해 보세요!</div>}
{lines.map((l) =>
l.userId === null ? (
l.answer ? (
<div key={l.seq} className={`answer-item ${l.answer.none ? 'none' : ''}`}>
{l.userId ? (
<div className={`chat-line ok ${l.userId === meId ? 'me' : ''}`}>
<b style={{ ['--name-h' as string]: userHue(l.userId) }}>{l.nickname}</b>
<span>{l.text}</span> <span aria-label="정답">✔</span>
</div>
) : (
<div className="chat-sys">— {l.text} —</div>
)}
<div className="ans-gap" />
<div className="ans-gap" />
<div className="ans-text">
<span>{l.answer.text}</span>
</div>
<div className="ans-gap" />
<div className="ans-gap" />
</div>
) : l.userId === null ? (
<div key={l.seq} className="chat-sys">
— {l.text} —
</div>
) : (
<div key={l.seq} className={`chat-line ${l.userId === meId ? 'me' : ''}`}>
<b style={{ ['--name-h' as string]: hue(l.userId) }}>{l.nickname}</b>
<b style={{ ['--name-h' as string]: userHue(l.userId) }}>{l.nickname}</b>
<span>{l.text}</span>
</div>
),
)}
{pending.map((p) => (
<div key={p.n} className="chat-line me pending" aria-label="보내는 중">
<b style={{ ['--name-h' as string]: hue(meId) }}>{myName}</b>
<b style={{ ['--name-h' as string]: userHue(meId) }}>{myName}</b>
<span>{p.text}</span>
</div>
))}
@@ -83,6 +128,20 @@ export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: Cha
새 메시지 ↓
</button>
)}
{onTyping && (
<div className="typing" aria-live="off">
{others.length > 0 && (
<>
<span className="dots" aria-hidden>
<i />
<i />
<i />
</span>
{typingText(others)}
</>
)}
</div>
)}
<form
className="chat-input"
onSubmit={(e) => {
@@ -91,15 +150,29 @@ export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: Cha
}}
>
<input
ref={inputRef}
className="input"
value={text}
maxLength={CHAT_MAX}
placeholder="메시지 입력 (Enter)"
placeholder={big ? '정답이나 채팅 입력 (Enter)' : '메시지 입력 (Enter)'}
aria-label="채팅 입력"
onChange={(e) => setText(e.target.value)}
autoComplete="off"
onChange={(e) => {
const v = e.target.value;
setText(v);
if (!onTyping) return;
if (!v.trim()) return stopTyping();
if (Date.now() - typingAt.current > 2000) {
typingAt.current = Date.now();
onTyping(true);
}
}}
onBlur={stopTyping}
onKeyDown={(e) => {
if (e.key === 'Escape') setText('');
else if (e.key === 'ArrowUp' && !text && lastSent.current) {
if (e.key === 'Escape') {
setText('');
stopTyping();
} else if (e.key === 'ArrowUp' && !text && lastSent.current) {
e.preventDefault();
setText(lastSent.current);
}
@@ -111,4 +184,4 @@ export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: Cha
</form>
</section>
);
}
});

444
apps/web/src/net/player.ts Normal file
View File

@@ -0,0 +1,444 @@
/**
* Hidden YouTube IFrame player with server-timed playback (docs/12 Q1, prototype tools/prototypes/iframe-sync).
* - prepare: load muted at the start position, wait until really PLAYING (an ad would come first), pause, seek back → ready
* (reloads by itself at 8s and 16s)
* - play: at server time `startAt` unmute and play from `atSec`; stop by playback POSITION at `endSec`
* (checked every frame + 10ms); 0.3s drift correction every second; buffering > 0.5s → stall; muted / not playing
* 0.3s after the start → blocked
* A fake player (localStorage mq:fakePlayer = "1") lets e2e runs play 30 questions without YouTube.
*/
import { create } from 'zustand';
export type AudioEvent = 'ready' | 'blocked' | 'stall' | 'clipEnd' | 'error';
export interface PlayerState {
/** The browser let us play sound (entry click done). */
unlocked: boolean;
/** Sound was blocked: show the big "눌러서 소리 켜기" button. */
needsGesture: boolean;
/** Loading for this question (for "음원 준비 중…"). */
loading: boolean;
/** Playing right now (for the LP spin). */
playing: boolean;
/** Last known position / clip window for the progress bar. */
pos: number;
clip: { start: number; end: number | null } | null;
volume: number;
}
const VOLUME_KEY = 'mq:volume';
const readVolume = () => {
try {
const v = Number(localStorage.getItem(VOLUME_KEY));
return Number.isFinite(v) && localStorage.getItem(VOLUME_KEY) !== null ? Math.max(0, Math.min(100, v)) : 70;
} catch {
return 70;
}
};
export const usePlayer = create<PlayerState>(() => ({ unlocked: false, needsGesture: false, loading: false, playing: false, pos: 0, clip: null, volume: readVolume() }));
/** A harmless video the entry click plays at volume 0 to get sound permission (SG워너비 광, Topic — known to embed). */
const UNLOCK_VIDEO = 'VO88htcm09E';
interface Engine {
init(): Promise<void>;
unlock(): void;
load(id: string, startSec: number): void;
seek(sec: number): void;
play(): void;
pause(): void;
mute(on: boolean): void;
isMuted(): boolean;
volume(v: number): void;
time(): number;
/** YT.PlayerState: -1 unstarted, 0 ended, 1 playing, 2 paused, 3 buffering, 5 cued */
state(): number;
videoId(): string | null;
}
type Listener = { onState?: (s: number) => void; onError?: (code: number) => void; onBlocked?: () => void };
// ---------------------------------------------------------------- real YouTube engine
declare global {
interface Window {
YT?: any;
onYouTubeIframeAPIReady?: () => void;
mqPlayer?: unknown;
}
}
function youtubeEngine(l: Listener): Engine {
let player: any = null;
let ready: Promise<void> | null = null;
let current: string | null = null;
// The player object exists before onReady, its methods only after.
const call = (m: string, ...a: unknown[]): unknown => (typeof player?.[m] === 'function' ? player[m](...a) : undefined);
return {
init() {
ready ??= new Promise<void>((resolve) => {
const host = document.createElement('div');
host.setAttribute('aria-hidden', 'true');
// Off screen, not display:none (a hidden iframe may not play).
host.style.cssText = 'position:fixed;left:-10000px;top:0;width:200px;height:200px;overflow:hidden;pointer-events:none';
const el = document.createElement('div');
host.appendChild(el);
document.body.appendChild(host);
const make = () => {
player = new window.YT.Player(el, {
width: 200,
height: 200,
playerVars: { autoplay: 0, controls: 0, disablekb: 1, fs: 0, rel: 0, playsinline: 1, iv_load_policy: 3 },
events: {
onReady: () => resolve(),
onStateChange: (e: { data: number }) => l.onState?.(e.data),
onError: (e: { data: number }) => l.onError?.(e.data),
onAutoplayBlocked: () => l.onBlocked?.(),
},
});
};
if (window.YT?.Player) make();
else {
const prev = window.onYouTubeIframeAPIReady;
window.onYouTubeIframeAPIReady = () => {
prev?.();
make();
};
const s = document.createElement('script');
s.src = 'https://www.youtube.com/iframe_api';
document.head.appendChild(s);
}
});
return ready;
},
unlock() {
if (typeof player?.loadVideoById !== 'function') return;
// Inside the click: play something with sound on (volume 0), so later starts are allowed (docs/12 Q1 소리 허용).
player.setVolume(0);
player.unMute();
if (current) player.playVideo();
else {
current = UNLOCK_VIDEO;
player.loadVideoById({ videoId: UNLOCK_VIDEO, startSeconds: 30 });
}
},
load(id, startSec) {
current = id;
player.loadVideoById({ videoId: id, startSeconds: startSec });
},
seek: (sec) => call('seekTo', sec, true),
play: () => call('playVideo'),
pause: () => call('pauseVideo'),
mute: (on) => call(on ? 'mute' : 'unMute'),
isMuted: () => !!call('isMuted'),
volume: (v) => call('setVolume', v),
time: () => (call('getCurrentTime') as number | undefined) ?? 0,
state: () => (call('getPlayerState') as number | undefined) ?? -1,
videoId: () => current,
};
}
// ---------------------------------------------------------------- fake engine for e2e (no network)
function fakeEngine(l: Listener): Engine {
let state = -1;
let base = 0;
let since = 0;
let current: string | null = null;
let muted = false;
const set = (s: number) => {
state = s;
l.onState?.(s);
};
const fake = { loadMs: 40, failNext: 0 as number, stallNext: false };
(window as unknown as { mqFake: typeof fake }).mqFake = fake;
const time = () => (state === 1 ? base + (performance.now() - since) / 1000 : base);
return {
init: () => Promise.resolve(),
unlock: () => {},
load(id, startSec) {
current = id;
base = startSec;
set(3);
if (fake.failNext) {
const code = fake.failNext;
fake.failNext = 0;
setTimeout(() => l.onError?.(code), 30);
return;
}
setTimeout(() => {
since = performance.now();
set(1);
}, fake.loadMs);
},
seek(sec) {
base = sec;
since = performance.now();
},
play() {
since = performance.now();
if (fake.stallNext) {
fake.stallNext = false;
set(3);
return;
}
if (fake.loadMs > 100) {
// slow network: buffers before playing
set(3);
setTimeout(() => {
since = performance.now();
set(1);
}, fake.loadMs);
return;
}
set(1);
},
pause() {
base = time();
set(2);
},
mute: (on) => (muted = on),
isMuted: () => muted,
volume: () => {},
time,
state: () => state,
videoId: () => current,
};
}
// ---------------------------------------------------------------- controller
let engine: Engine | null = null;
let report: (n: number, ev: AudioEvent, code?: number) => void = () => {};
let now: () => number = Date.now;
/** Every command bumps the token; async steps of older commands stop. */
let token = 0;
let curN = 0;
let loop: { raf: number; iv: ReturnType<typeof setInterval>; drift: ReturnType<typeof setInterval> } | null = null;
let bufferingSince: number | null = null;
let stallSent = false;
let pendingReady: { n: number; tk: number; at: number } | null = null;
let timeline: { startAt: number; atSec: number; endSec: number | null } | null = null;
const useFake = () => {
try {
return localStorage.getItem('mq:fakePlayer') === '1';
} catch {
return false;
}
};
function eng(): Engine {
if (!engine) {
const l: Listener = {
onState: (s) => {
if (s === 3 && timeline) bufferingSince ??= performance.now();
else bufferingSince = null;
if (s === 0 && timeline) clipEnded();
},
onError: (code) => {
usePlayer.setState({ loading: false });
report(curN, 'error', code);
},
onBlocked: () => blocked(),
};
engine = useFake() ? fakeEngine(l) : youtubeEngine(l);
window.mqPlayer = { pos: () => engine!.time(), state: () => engine!.state(), muted: () => engine!.isMuted(), video: () => engine!.videoId() };
}
return engine;
}
const waitFor = (pred: () => boolean, ms: number, tk: number) =>
new Promise<boolean>((res) => {
const t0 = performance.now();
const iv = setInterval(() => {
if (tk !== token) return (clearInterval(iv), res(false));
if (pred()) return (clearInterval(iv), res(true));
if (performance.now() - t0 > ms) return (clearInterval(iv), res(false));
}, 20);
});
function stopLoop(): void {
if (!loop) return;
cancelAnimationFrame(loop.raf);
clearInterval(loop.iv);
clearInterval(loop.drift);
loop = null;
}
function blocked(): void {
if (!timeline) return;
usePlayer.setState({ needsGesture: true, playing: false });
report(curN, 'blocked');
}
function clipEnded(): void {
if (!timeline) return;
const e = eng();
e.pause();
stopLoop();
timeline = null;
usePlayer.setState({ playing: false, pos: e.time() });
report(curN, 'clipEnd');
}
export const player = {
/** Wire reports to the server and the server clock. */
setup(r: typeof report, serverNow: () => number): void {
report = r;
now = serverNow;
},
/** Load the API early (waiting room), so the entry click can unlock at once. */
warm(): void {
void eng().init();
},
/** Call inside a click: "참가 (소리 켜기)" / "눌러서 소리 켜기". */
unlock(): void {
const e = eng();
e.unlock();
const held = pendingReady;
pendingReady = null;
usePlayer.setState({ unlocked: true, needsGesture: false });
const tk = token;
const release = () => held && held.tk === token && report(held.n, 'ready');
if (useFake()) return void release();
void waitFor(() => e.state() === 1, 5000, tk).then(async () => {
e.volume(usePlayer.getState().volume);
if (tk !== token || timeline) return;
e.pause();
if (!held) return;
// The question was waiting for this click: back to the position everyone resumes from, then ready.
await waitFor(() => e.state() === 2, 2000, tk);
if (tk !== token) return;
e.seek(held.at);
release();
});
},
async prepare(n: number, videoId: string, startSec: number, endSec: number | null): Promise<void> {
const tk = ++token;
curN = n;
stopLoop();
timeline = null;
pendingReady = null;
usePlayer.setState({ loading: true, playing: false, pos: startSec, clip: { start: startSec, end: endSec } });
const e = eng();
await e.init();
if (tk !== token) return;
e.mute(true);
const load = () => {
if (e.videoId() === videoId && e.state() !== -1 && e.state() !== 5) {
e.seek(startSec);
e.play();
} else e.load(videoId, startSec);
};
load();
// Not playing yet: reload at 8s and 16s (docs/12 Q1), then keep waiting for the host's decision.
let ok = await waitFor(() => e.state() === 1, 8000, tk);
if (!ok && tk === token) (e.load(videoId, startSec), (ok = await waitFor(() => e.state() === 1, 8000, tk)));
if (!ok && tk === token) (e.load(videoId, startSec), (ok = await waitFor(() => e.state() === 1, 600_000, tk)));
if (!ok || tk !== token) return;
e.pause();
await waitFor(() => e.state() === 2, 3000, tk);
if (tk !== token) return;
e.seek(startSec);
usePlayer.setState({ loading: false, pos: startSec });
if (usePlayer.getState().needsGesture) pendingReady = { n, tk, at: startSec };
else report(n, 'ready');
},
play(n: number, startAt: number, atSec: number, endSec: number | null): void {
const tk = ++token;
curN = n;
stopLoop();
pendingReady = null;
const e = eng();
timeline = { startAt, atSec, endSec };
stallSent = false;
bufferingSince = null;
usePlayer.setState({ clip: { start: usePlayer.getState().clip?.start ?? atSec, end: endSec }, pos: atSec });
const go = () => {
if (tk !== token) return;
e.volume(usePlayer.getState().volume);
e.mute(false);
if (Math.abs(e.time() - atSec) > 0.15) e.seek(atSec);
e.play();
usePlayer.setState({ playing: true });
// 소리 확인 (docs/12 Q1): 0.3s later it must be unmuted and playing.
setTimeout(() => {
if (tk !== token || !timeline) return;
if (e.isMuted() || (e.state() !== 1 && e.state() !== 3)) blocked();
}, 300);
const check = () => {
if (tk !== token || !timeline) return;
const t = e.time();
if (endSec !== null && t >= endSec) return clipEnded();
if (bufferingSince !== null && !stallSent && performance.now() - bufferingSince > 500) {
stallSent = true;
report(n, 'stall');
}
if (loop) loop.raf = requestAnimationFrame(check);
};
loop = {
raf: requestAnimationFrame(check),
iv: setInterval(check, 10),
drift: setInterval(() => {
if (tk !== token || !timeline || e.state() !== 1) return;
const expected = atSec + (now() - startAt) / 1000;
const t = e.time();
usePlayer.setState({ pos: t });
if (Math.abs(t - expected) > 0.3) e.seek(expected);
}, 1000),
};
};
const wait = startAt - now();
if (wait > 0) setTimeout(go, wait);
else go();
},
pause(): void {
token++;
stopLoop();
timeline = null;
pendingReady = null;
const e = engine;
if (e && e.state() === 1) e.pause();
usePlayer.setState({ playing: false, loading: false, pos: e?.time() ?? 0 });
},
/** 정답 공개: the music goes on for the reveal (docs/05 정답 공개), then stops. */
reveal(ms: number): void {
const tk = ++token;
stopLoop();
timeline = null;
const e = engine;
if (!e || !e.videoId() || e.videoId() === UNLOCK_VIDEO || usePlayer.getState().needsGesture) return;
e.volume(usePlayer.getState().volume);
e.mute(false);
e.play();
usePlayer.setState({ playing: true, loading: false });
setTimeout(() => {
if (tk !== token) return;
e.pause();
usePlayer.setState({ playing: false });
}, ms);
},
stop(): void {
player.pause();
usePlayer.setState({ clip: null, pos: 0 });
},
setVolume(v: number): void {
const vol = Math.max(0, Math.min(100, Math.round(v)));
usePlayer.setState({ volume: vol });
try {
localStorage.setItem(VOLUME_KEY, String(vol));
} catch {
/* private mode */
}
engine?.volume(vol);
},
time(): number {
return engine?.time() ?? 0;
},
};

View File

@@ -2,8 +2,9 @@
* One WebSocket per tab (docs/01): reconnects with backoff, re-joins the room, keeps the server clock offset (docs/12 Q1).
*/
import { create } from 'zustand';
import type { ChatLine, RoomView, ServerMessage } from '@mq/shared/lite';
import type { ChatLine, GameView, RoomView, ServerMessage } from '@mq/shared/lite';
import { toast } from '../store/toast';
import { player } from './player';
type Status = 'idle' | 'connecting' | 'open' | 'reconnecting';
@@ -21,6 +22,12 @@ interface RoomState {
chat: ChatLine[];
/** My lines not confirmed by the server yet: always drawn at the bottom (docs/06 지연 없는 전송). */
pending: { n: string; text: string }[];
/** The running game (docs/05), null in the waiting room. */
game: GameView | null;
/** Who is typing (docs/06 입력 중). */
typing: string[];
/** Last 퀴즈 저장 result. */
saved: { id: number; name: string } | null;
}
const CHAT_KEEP = 200;
@@ -28,7 +35,7 @@ const CHAT_KEEP = 200;
const LAST_ROOM_KEY = 'mq:lastRoom';
export const ROOM_GONE_TEXT = '서버가 업데이트되면서 방이 닫혔어요. 방을 새로 만들어 주세요.';
export const useRoom = create<RoomState>(() => ({ status: 'idle', code: null, room: null, offset: 0, rtt: null, joinError: null, left: null, chat: [], pending: [] }));
export const useRoom = create<RoomState>(() => ({ status: 'idle', code: null, room: null, offset: 0, rtt: null, joinError: null, left: null, chat: [], pending: [], game: null, typing: [], saved: null }));
let ws: WebSocket | null = null;
let retry = 0;
@@ -37,6 +44,7 @@ let pingTimer: ReturnType<typeof setInterval> | null = null;
/** A join is on its way: the next error is the join's answer. */
let joining = false;
let nonce = 0;
let myId = '';
function lastRoom(): string | null {
try {
@@ -70,6 +78,7 @@ function syncClock(): void {
function onMessage(m: ServerMessage): void {
switch (m.t) {
case 'welcome': {
myId = m.userId;
useRoom.setState({ status: 'open', offset: m.serverNow - Date.now() });
retry = 0;
syncClock();
@@ -99,13 +108,40 @@ function onMessage(m: ServerMessage): void {
case 'left':
if (m.code === useRoom.getState().code) {
setLastRoom(null);
useRoom.setState({ room: null, left: m.reason, chat: [], pending: [] });
player.stop();
useRoom.setState({ room: null, left: m.reason, chat: [], pending: [], game: null, typing: [] });
}
return;
case 'chatlog':
// (Re)joined: the server's log is the truth; unconfirmed lines from before a drop are gone.
if (m.code === useRoom.getState().code) useRoom.setState({ chat: m.lines.slice(-CHAT_KEEP), pending: [] });
return;
case 'game': {
if (m.code !== useRoom.getState().code) return;
const prev = useRoom.getState().game;
const g = m.game;
if (!g || g.phase === 'result') player.stop();
else if (g.phase === 'reveal' && prev?.phase !== 'reveal' && g.mode !== 'lyrics' && g.participants.includes(myId)) player.reveal(Math.max(0, (g.revealUntil ?? 0) - serverNow() - 150));
useRoom.setState({ game: g });
return;
}
case 'prepare':
if (m.code === useRoom.getState().code) void player.prepare(m.n, m.videoId, m.startSec, m.endSec);
return;
case 'play':
if (m.code === useRoom.getState().code) player.play(m.n, m.startAt, m.atSec, m.endSec);
return;
case 'pause':
if (m.code === useRoom.getState().code) player.pause();
return;
case 'typing':
if (m.code === useRoom.getState().code) useRoom.setState({ typing: m.ids });
return;
case 'saved':
useRoom.setState({ saved: { id: m.id, name: m.name } });
toast(`"${m.name}"(으)로 저장했어요.`);
return;
case 'answer':
case 'chat':
if (m.code === useRoom.getState().code) {
const st = useRoom.getState();
@@ -166,14 +202,15 @@ export const socket = {
join(code: string, pw?: string): void {
password = pw;
const st = useRoom.getState();
useRoom.setState({ code, room: null, joinError: null, left: null, ...(st.code === code ? {} : { chat: [], pending: [] }) });
useRoom.setState({ code, room: null, joinError: null, left: null, ...(st.code === code ? {} : { chat: [], pending: [], game: null, typing: [] }) });
socket.start();
sendJoin(code);
},
leave(): void {
send({ t: 'leave' });
setLastRoom(null);
useRoom.setState({ code: null, room: null, chat: [], pending: [] });
player.stop();
useRoom.setState({ code: null, room: null, chat: [], pending: [], game: null, typing: [] });
},
chat(text: string): void {
const n = `${Date.now().toString(36)}${(nonce++).toString(36)}`;
@@ -185,3 +222,5 @@ export const socket = {
/** Server clock (ms) for countdowns and synced playback. */
export const serverNow = () => Date.now() + useRoom.getState().offset;
player.setup((n, ev, code) => send({ t: 'audio', n, ev, code }), serverNow);

View File

@@ -0,0 +1,395 @@
/**
* 게임 화면 (docs/03 게임 화면, docs/05, docs/06): black top bar with votes, stage (LP / lyrics card / hint), big chat,
* scoreboard on the left, past questions on the right, results at the end.
*/
import { useEffect, useRef, useState } from 'react';
import { listenLabel, type GameHistoryItem, type GameView, type RoomView } from '@mq/shared/lite';
import { serverNow, socket, useRoom } from '../net/socket';
import { player, usePlayer } from '../net/player';
import { useSession } from '../store/session';
import { toast } from '../store/toast';
import { Avatar, ConfirmSheet, Sheet } from '../components/ui';
import { ChatPanel, type ChatHandle } from '../components/ChatPanel';
const LATE_MS = 30_000;
/** Re-render every `ms` (timers, countdown). */
function useNow(ms: number): number {
const [, set] = useState(0);
useEffect(() => {
const iv = setInterval(() => set((x) => x + 1), ms);
return () => clearInterval(iv);
}, [ms]);
return serverNow();
}
const fmt = (sec: number) => `${Math.floor(sec / 60)}:${String(Math.floor(sec % 60)).padStart(2, '0')}`;
const secs = (ms: number | null) => (ms === null ? '' : `${(ms / 1000).toFixed(1)}초`);
function Stars({ n }: { n: number | null }) {
if (!n) return null;
const color = n <= 3 ? 'var(--star-1)' : n <= 6 ? 'var(--star-2)' : n <= 8 ? 'var(--star-3)' : 'var(--star-4)';
return (
<span className="mini-stars" style={{ color }} aria-label={`난이도 ${n}단계`}>
★{n}
</span>
);
}
export function GameScreen({ room, game }: { room: RoomView; game: GameView }) {
const me = useSession((s) => s.me)!;
const { chat, pending, typing } = useRoom();
const p = usePlayer();
const now = useNow(200);
const chatRef = useRef<ChatHandle>(null);
const [confirmEnd, setConfirmEnd] = useState(false);
const isHost = room.hostId === me.id;
const c = room.config;
const send = (m: unknown) => socket.send(m);
const vote = (kind: 'skip' | 'hint' | 'replay') => send({ t: 'vote', kind });
const name = (id: string) => room.players.find((x) => x.id === id)?.nickname ?? game.scores.find((x) => x.id === id)?.nickname ?? '?';
const inQuestion = game.participants.includes(me.id) && !game.excluded.includes(me.id);
const listening = game.mode !== 'lyrics';
useEffect(() => {
player.warm();
}, []);
// Shortcuts (docs/06): Ctrl+I 힌트, Ctrl+K 스킵, Ctrl+R 다시듣기 — only on the game screen; any key focuses the chat.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey) {
const k = e.key.toLowerCase();
const kind = k === 'i' ? 'hint' : k === 'k' ? 'skip' : k === 'r' ? 'replay' : null;
if (kind) {
e.preventDefault();
vote(kind);
}
return;
}
const t = e.target as HTMLElement | null;
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable)) return;
if (document.querySelector('.sheet')) return;
if (e.key.length === 1 || e.key === 'Enter') chatRef.current?.focus();
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, []); // eslint-disable-line react-hooks/exhaustive-deps
if (game.phase === 'result') return <ResultScreen room={room} game={game} />;
const elapsed = game.clock.elapsedMs + (game.clock.runningSince !== null ? Math.max(0, now - game.clock.runningSince) : 0);
const countdown = game.startAt !== null && now < game.startAt && !game.paused ? Math.ceil((game.startAt - now) / 1000) : 0;
const reveal = game.phase === 'reveal' ? game.history.at(-1) : undefined;
const voteBtn = (kind: 'skip' | 'hint' | 'replay', icon: string, label: string, key: string) => {
const need = game.need[kind];
const n = game.votes[kind].length;
const on = game.votes[kind].includes(me.id);
const off = need === null && (kind !== 'hint' || c.hint === 'none');
return (
<button type="button" className={`btn btn-sm gbtn ${on ? 'on' : ''}`} aria-pressed={on} disabled={kind === 'replay' && need === null} onClick={() => vote(kind)} title={off ? `${label}가 꺼져 있어요` : undefined}>
{icon} {label}
{need !== null && (
<span className="mono">
{' '}
{n}/{need}
</span>
)}
<span className="kbd">{key}</span>
</button>
);
};
const question = c.answer === 'title' ? '이 노래 제목은?' : c.answer === 'artist' ? '이 노래 부른 가수는?' : '제목과 가수를 한 줄에!';
const clipLen = game.clipSec;
const clipPos = p.clip ? Math.max(0, p.pos - p.clip.start) : 0;
const late = isHost ? game.waiting.filter((w) => now - w.since >= LATE_MS) : [];
return (
<div className="game">
<div className="gbar">
<div className="q">
문제 {game.n} <span>/ {game.total}</span>
</div>
<span className="badge dark">
{game.mode === 'lyrics'
? `📜 가사보고 맞추기 · ${c.lyricsSec ? `${c.lyricsSec}초` : '무제한'}`
: `${game.mode === 'artist' ? '🎤 가수노래' : '🎧 듣고맞추기'} · ${listenLabel(c.listenSec)} · ${c.startAt === 'highlight' ? '하이라이트부터' : '처음부터'}`}
</span>
<span className="badge dark">정답: {c.answer === 'title' ? '제목만' : c.answer === 'artist' ? '가수만' : '제목+가수'}</span>
<span className="badge dark">★{c.level}</span>
<div className="grow" />
{voteBtn('hint', '💡', '힌트', 'Ctrl+I')}
{voteBtn('skip', '⏭', '스킵', 'Ctrl+K')}
{listening && voteBtn('replay', '🔁', '다시듣기', 'Ctrl+R')}
{listening && (
<label className="vol" title="볼륨">
🔊
<input type="range" min={0} max={100} value={p.volume} onChange={(e) => player.setVolume(Number(e.target.value))} aria-label="볼륨" />
</label>
)}
{isHost && (
<>
<button type="button" className="btn btn-sm gbtn" onClick={() => send({ t: 'game', action: game.paused?.reason === 'host' ? 'resume' : 'pause' })}>
{game.paused?.reason === 'host' ? '▶ 계속' : '⏸ 일시정지'}
</button>
<button type="button" className="btn btn-sm gbtn" onClick={() => setConfirmEnd(true)}>
⏹ 끝내기
</button>
</>
)}
</div>
<div className="ggrid">
<aside className="side scoreboard" aria-label="점수판">
<h3>점수판 · {game.scores.length}명</h3>
<ol>
{game.scores.map((s, i) => {
// ties share a rank (same score and same average time)
const rank = 1 + game.scores.findIndex((o) => o.score === s.score && o.avgMs === s.avgMs);
return (
<li key={s.id} className={`sb ${s.id === me.id ? 'me' : ''} ${i === 0 && s.score > 0 ? 'first' : ''} ${s.online ? '' : 'off'}`}>
<span className="rk">{rank}</span>
<Avatar user={{ id: s.id, nickname: s.nickname, avatar: room.players.find((x) => x.id === s.id)?.avatar ?? null }} size={26} />
<span className="nm">
{s.nickname}
{s.id === me.id && ' (나)'}
{game.votes.skip.includes(s.id) && <span title="스킵"> ⏭</span>}
{s.id === room.hostId && <span title="방장"> 👑</span>}
</span>
<span className="sc mono">{s.score}</span>
</li>
);
})}
</ol>
</aside>
<div className="gcenter">
<section className={`stage ${reveal ? 'revealed' : ''}`} aria-live="polite">
{reveal ? (
<RevealCard item={reveal} />
) : (
<>
{listening ? <div className={`lp ${p.playing && !game.paused ? 'spin' : ''}`} aria-hidden /> : null}
<div className="sinfo">
<div className="mode">
{game.paused
? game.paused.reason === 'host'
? '⏸ 방장이 잠시 멈췄어요'
: `⏸ 잠시 멈춤 — ${game.paused.who.map(name).join(', ') || '누군가'}님 ${game.paused.reason === 'blocked' ? '소리 켜는 중' : '버퍼링 중'}`
: game.phase === 'prepare'
? game.waiting.length
? `${game.waiting.map((w) => name(w.id)).slice(0, 3).join(', ')}${game.waiting.length > 3 ? ` 외 ${game.waiting.length - 3}명` : ''}님 음원 준비 중…`
: '음원 준비 중…'
: countdown
? `${game.n}번째 문제`
: listening
? game.clipOver
? '재생이 끝났어요 · 계속 맞혀 보세요'
: `${game.n}번째 곡 재생 중 · 앨범아트와 제목은 정답 뒤에 공개`
: `${game.n}번째 가사`}
</div>
{game.mode === 'artist' && room.artists.length > 0 && <div className="small muted">선택한 가수: {room.artists.map((a) => a.name).join(', ')}</div>}
{countdown ? <div className="countdown mono">{countdown}</div> : <div className="big">{question}</div>}
{game.lyrics && (
<div className="lyrics-card">
{game.lyrics.map((l, i) => (
<div key={i}>{l}</div>
))}
</div>
)}
{listening && clipLen !== null && (
<>
<div className="bar" aria-hidden>
<i style={{ width: `${Math.min(100, (clipPos / Math.max(0.1, clipLen)) * 100)}%` }} />
</div>
<div className="times small">
<span>{fmt(clipPos)}</span>
<span>{fmt(clipLen)}</span>
</div>
</>
)}
{game.clock.limitMs !== null && game.phase === 'play' && (
<div className="limit small muted">
남은 시간 <b className="mono">{Math.max(0, Math.ceil((game.clock.limitMs - elapsed) / 1000))}초</b>
</div>
)}
<div className="row" style={{ marginTop: 8 }}>
{game.hint ? (
<span className="hint">
{game.hint} <small>초성 힌트</small>
</span>
) : game.hintAtSec !== null && game.phase === 'play' ? (
<span className="small muted">힌트는 {Math.max(0, Math.ceil(game.hintAtSec - elapsed / 1000))}초 뒤에 공개돼요</span>
) : null}
</div>
</div>
</>
)}
{!inQuestion && game.phase !== 'reveal' && (
<div className="stage-note">{game.excluded.includes(me.id) ? '음원을 불러오지 못해 이번 문제는 빠졌어요. 다음 문제부터 다시 같이 해요.' : '다음 문제부터 같이 해요. 지금은 채팅만 할 수 있어요.'}</div>
)}
{late.length > 0 && (
<div className="late">
{late.map((w) => (
<button key={w.id} type="button" className="btn btn-sm" onClick={() => send({ t: 'exclude', userId: w.id })}>
{name(w.id)}님 빼고 이번 문제 진행
</button>
))}
</div>
)}
</section>
<ChatPanel
ref={chatRef}
big
lines={chat}
pending={pending}
meId={me.id}
myName={me.nickname}
onSend={(t) => socket.chat(t)}
onTyping={(on) => send({ t: 'typing', on })}
typing={typing.filter((id) => id !== me.id).map(name)}
/>
</div>
<aside className="side hist" aria-label="지난 문제">
<h3>지난 문제</h3>
{game.history.length === 0 && <p className="small muted">아직 없어요</p>}
{[...game.history].reverse().map((h) => (
<div key={h.n} className="h">
<span className="n">{h.n}</span>
<span className="t">{h.title}</span> - {h.artist}
<div className="m">
<Stars n={h.level} />
{h.winner ? `${h.winner} · ${secs(h.ms)}` : h.how === 'skip' ? '스킵됨 (정답자 없음)' : '시간 초과 (정답자 없음)'}
</div>
</div>
))}
</aside>
</div>
{listening && (!p.unlocked || p.needsGesture) && inQuestion && (
<div className="unlock-overlay">
<button type="button" className="btn btn-mustard btn-lg" onClick={() => player.unlock()} autoFocus>
🔊 {p.needsGesture ? '눌러서 소리 켜기' : '참가 (소리 켜기)'}
</button>
<p className="small">브라우저가 소리를 막지 않도록 한 번 눌러 주세요.</p>
</div>
)}
{confirmEnd && <ConfirmSheet title="게임을 끝낼까요?" body="지금까지 점수로 결과를 보여 줘요." confirm="끝내기" danger onConfirm={() => send({ t: 'game', action: 'end' })} onClose={() => setConfirmEnd(false)} />}
</div>
);
}
function RevealCard({ item }: { item: GameHistoryItem }) {
return (
<div className="reveal">
{item.videoId ? <img className="art" src={`https://i.ytimg.com/vi/${item.videoId}/hqdefault.jpg`} alt="" /> : <div className="art lp" aria-hidden />}
<div className="sinfo">
<div className="mode">{item.winner ? `🎉 ${item.winner}님 정답! · ${secs(item.ms)}` : item.how === 'skip' ? '⏭ 스킵 · 정답자 없음' : '⌛ 시간 초과 · 정답자 없음'}</div>
<div className="big">
{item.title} <span className="muted">- {item.artist}</span>
</div>
<div className="small muted">
{[item.year, ...item.genres].filter(Boolean).join(' · ')} <Stars n={item.level} />
</div>
</div>
</div>
);
}
function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
const me = useSession((s) => s.me)!;
const isHost = room.hostId === me.id;
const [save, setSave] = useState(false);
const [name, setName] = useState('');
const send = (m: unknown) => socket.send(m);
const fastest = new Map<string, GameHistoryItem>();
for (const h of game.history) if (h.winnerId && h.ms !== null && (!fastest.get(h.winnerId) || fastest.get(h.winnerId)!.ms! > h.ms)) fastest.set(h.winnerId, h);
return (
<main className="page result stack">
<div className="row">
<h1>🏁 게임 결과</h1>
<span className="muted">{game.history.length}문제</span>
</div>
<section className="card ink">
<table className="data-table rank">
<thead>
<tr>
<th>순위</th>
<th>이름</th>
<th>점수</th>
<th>맞힌 곡</th>
<th>가장 빨리 맞힌 곡</th>
</tr>
</thead>
<tbody>
{game.scores.map((s, i) => {
const f = fastest.get(s.id);
return (
<tr key={s.id} className={s.id === me.id ? 'sel' : ''}>
<td className="mono">{i === 0 && s.score > 0 ? '🥇' : i === 1 && s.score > 0 ? '🥈' : i === 2 && s.score > 0 ? '🥉' : i + 1}</td>
<td>{s.nickname}</td>
<td className="mono">{s.score}</td>
<td className="mono">{s.correct}</td>
<td>{f ? `${f.title} · ${secs(f.ms)}` : '-'}</td>
</tr>
);
})}
</tbody>
</table>
</section>
<div className="row">
{isHost ? (
<>
<button className="btn btn-mustard btn-lg" disabled={game.left === 0} title={game.left === 0 ? '조건에 맞는 곡을 모두 풀었어요' : undefined} onClick={() => send({ t: 'game', action: 'continue' })}>
▶ 이어풀기 {game.left > 0 && <span className="small">(남은 곡 {game.left})</span>}
</button>
<button className="btn btn-lg" onClick={() => send({ t: 'game', action: 'again' })}>
↺ 다시 하기
</button>
<button
className="btn btn-lg"
onClick={() => (me.kind === 'member' ? setSave(true) : toast('퀴즈 저장은 디스코드로 로그인하면 쓸 수 있어요.', 'error'))}
>
💾 퀴즈 저장
</button>
</>
) : (
<span className="muted">방장이 이어풀기나 다시 하기를 고르면 바로 시작돼요.</span>
)}
<div className="grow" />
</div>
<section className="card">
<h2 style={{ marginBottom: 10 }}>이번 게임 곡 목록</h2>
<ol className="songlist">
{game.history.map((h) => (
<li key={h.n}>
<span className="mono muted">{h.n}.</span> <b>{h.title}</b> - {h.artist} <Stars n={h.level} />{' '}
{h.videoId && (
<a href={`https://youtu.be/${h.videoId}`} target="_blank" rel="noreferrer">
https://youtu.be/{h.videoId}
</a>
)}{' '}
<span className="small muted">{h.winner ? `${h.winner} ${secs(h.ms)}` : h.how === 'skip' ? '스킵' : '시간 초과'}</span>
</li>
))}
</ol>
</section>
{save && (
<Sheet label="퀴즈 저장" onClose={() => setSave(false)}>
<h2>퀴즈 저장</h2>
<p className="muted small">방 설정, 지금까지 나온 곡, 참가자 점수를 내 계정에 저장해요. 불러오면 나온 곡은 빼고 이어서 할 수 있어요.</p>
<form
className="stack"
onSubmit={(e) => {
e.preventDefault();
if (!name.trim()) return;
send({ t: 'save', name: name.trim() });
setSave(false);
}}
>
<input className="input" autoFocus maxLength={40} placeholder="퀴즈 이름 (예: 금요일 발라드)" value={name} onChange={(e) => setName(e.target.value)} aria-label="퀴즈 이름" />
<button className="btn btn-primary btn-block" disabled={!name.trim()}>
저장
</button>
</form>
</Sheet>
)}
</main>
);
}

View File

@@ -1,6 +1,6 @@
/**
* 대기실 /r/:code (docs/03, docs/04): players, live "조건에 맞는 곡 N곡", settings (host edits, everyone sees it at once).
* Games start in stage 5: the start button is shown but disabled until then.
* While a game runs the same page shows the game screen (GameScreen).
*/
import { useEffect, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router';
@@ -9,10 +9,12 @@ import { apiCall } from '../net/api';
import { socket, useRoom } from '../net/socket';
import { useSession } from '../store/session';
import { toast } from '../store/toast';
import { Avatar, ConfirmSheet } from '../components/ui';
import { Avatar, ConfirmSheet, Sheet } from '../components/ui';
import { LoginBox } from '../components/LoginBox';
import { RoomSettings, type CatalogMeta } from '../components/RoomSettings';
import { ChatPanel } from '../components/ChatPanel';
import { player, usePlayer } from '../net/player';
import { GameScreen } from './GameScreen';
const LEFT_TEXT: Record<string, string> = {
kicked: '방장이 방에서 내보냈어요.',
@@ -25,17 +27,29 @@ export default function RoomPage() {
const { code = '' } = useParams();
const me = useSession((s) => s.me);
const nav = useNavigate();
const { room, joinError, left, status, chat, pending } = useRoom();
const { room, joinError, left, status, chat, pending, game, typing } = useRoom();
const unlocked = usePlayer((s) => s.unlocked);
const [confirmStart, setConfirmStart] = useState(false);
const [loadOpen, setLoadOpen] = useState(false);
const [meta, setMeta] = useState<CatalogMeta | null>(null);
const [pw, setPw] = useState('');
const [confirmLeave, setConfirmLeave] = useState(false);
useEffect(() => {
void apiCall<CatalogMeta>('GET', '/api/catalog/meta').then(setMeta).catch(() => {});
// The YouTube player loads while people wait, so the entry click can turn the sound on at once (docs/12 Q1).
player.warm();
}, []);
useEffect(() => {
if (!me || !/^\d{6}$/.test(code)) return;
socket.join(code);
// Going anywhere else in the app (← 방 목록, logo, browser back) leaves the room, so an empty room closes at once.
// Checked a tick later: React StrictMode re-mounts on the same path, and a refresh keeps the 60s place instead.
return () => {
setTimeout(() => {
if (location.pathname !== `/r/${code}` && useRoom.getState().code === code) socket.leave();
}, 0);
};
}, [me, code]);
useEffect(() => {
if (left && left !== 'leave') {
@@ -85,6 +99,8 @@ export default function RoomPage() {
const link = `${location.origin}/r/${room.code}`;
const needArtist = c.mode === 'artist' && c.artistIds.length === 0;
const short = c.count !== 0 && room.pool.playable < c.count;
const start = () => (short && room.pool.playable > 0 ? setConfirmStart(true) : send({ t: 'start' }));
const playing = room.status === 'playing' && !!game;
return (
<>
@@ -109,12 +125,15 @@ export default function RoomPage() {
링크 복사
</button>
<div className="grow" />
<span className="badge teal">{room.status === 'lobby' ? '대기 중' : '게임 중'}</span>
<span className={`badge ${room.status === 'lobby' ? 'teal' : 'live'}`}>{room.status === 'lobby' ? '대기 중' : '게임 중'}</span>
<span className="muted small">참가 {room.players.length}명 · 제한 없음</span>
<button type="button" className="btn btn-sm" onClick={() => setConfirmLeave(true)}>
🚪 나가기
</button>
</div>
{playing ? (
<GameScreen room={room} game={game} />
) : (
<main className="room-main">
<div className="stack" style={{ minWidth: 0 }}>
<section className="card">
@@ -172,7 +191,7 @@ export default function RoomPage() {
{!needArtist && room.pool.playable === 0 && room.pool.total === 0 && <p className="small">이 조건에 맞는 곡이 없어요. 장르·연도·난이도를 넓혀 보세요.</p>}
</div>
{isHost ? (
<button className="btn btn-mustard btn-lg" disabled title="게임 진행은 다음 업데이트에서 열려요">
<button className="btn btn-mustard btn-lg" disabled={needArtist || room.pool.playable === 0} onClick={start}>
게임 시작
</button>
) : (
@@ -181,8 +200,30 @@ export default function RoomPage() {
</button>
)}
</section>
<ChatPanel lines={chat} pending={pending} meId={me.id} myName={me.nickname} onSend={(t) => socket.chat(t)} />
<p className="muted small">게임 진행(노래 재생·채팅 정답)은 다음 업데이트에서 열려요. 지금은 방을 만들고 설정을 맞추면서 대화할 수 있어요.</p>
{c.mode !== 'lyrics' && !unlocked && (
<section className="card sound-card row">
<span className="grow">🔊 노래가 들리도록 게임 전에 한 번 눌러 주세요. 브라우저가 소리를 막을 수 있어요.</span>
<button type="button" className="btn btn-mustard" onClick={() => player.unlock()}>
참가 (소리 켜기)
</button>
</section>
)}
{isHost && (
<div className="row">
<button type="button" className="btn btn-sm" onClick={() => (me.kind === 'member' ? setLoadOpen(true) : toast('퀴즈 저장·불러오기는 디스코드로 로그인하면 쓸 수 있어요.', 'error'))}>
📂 퀴즈 불러오기
</button>
</div>
)}
<ChatPanel
lines={chat}
pending={pending}
meId={me.id}
myName={me.nickname}
onSend={(t) => socket.chat(t)}
onTyping={(on) => send({ t: 'typing', on })}
typing={typing.filter((id) => id !== me.id).map((id) => room.players.find((x) => x.id === id)?.nickname ?? '?')}
/>
</div>
<RoomSettings
config={c}
@@ -195,6 +236,17 @@ export default function RoomPage() {
onPassword={(value) => send({ t: 'password', value })}
/>
</main>
)}
{confirmStart && (
<ConfirmSheet
title={`조건에 맞는 곡이 ${room.pool.playable}곡뿐이에요`}
body={`${c.count}문제 대신 ${room.pool.playable}문제로 시작할까요? 설정을 넓히면 곡이 늘어나요.`}
confirm="그대로 시작"
onConfirm={() => send({ t: 'start' })}
onClose={() => setConfirmStart(false)}
/>
)}
{loadOpen && <LoadSheet onClose={() => setLoadOpen(false)} />}
{confirmLeave && (
<ConfirmSheet
title="방에서 나갈까요?"
@@ -210,6 +262,68 @@ export default function RoomPage() {
);
}
interface SavedQuiz {
id: number;
name: string;
questions: number;
players: number;
updatedAt: number;
}
/** 퀴즈 불러오기 (docs/12 Q8): my saved quizzes; loading restores settings, songs asked and scores. */
function LoadSheet({ onClose }: { onClose: () => void }) {
const [list, setList] = useState<SavedQuiz[] | null>(null);
const refresh = () =>
apiCall<{ quizzes: SavedQuiz[] }>('GET', '/api/quizzes')
.then((r) => setList(r.quizzes))
.catch(() => setList([]));
useEffect(() => {
void refresh();
}, []);
return (
<Sheet label="퀴즈 불러오기" onClose={onClose}>
<h2>퀴즈 불러오기</h2>
<p className="muted small">불러오면 저장할 때의 설정과 점수가 돌아오고, 시작하면 이미 나온 곡은 빼고 이어서 나와요. (계정당 20개)</p>
{list === null ? (
<p className="muted">불러오는 중…</p>
) : list.length === 0 ? (
<p className="muted">저장한 퀴즈가 없어요. 게임이 끝난 뒤 결과 화면에서 저장할 수 있어요.</p>
) : (
<ul className="saved-list">
{list.map((q) => (
<li key={q.id}>
<div className="grow">
<b>{q.name}</b>
<div className="small muted">
{q.questions}문제 · {q.players}명 · {new Date(q.updatedAt).toLocaleString('ko-KR', { dateStyle: 'short', timeStyle: 'short' })}
</div>
</div>
<button
type="button"
className="btn btn-sm btn-primary"
onClick={() => {
socket.send({ t: 'load', id: q.id });
onClose();
}}
>
불러오기
</button>
<button
type="button"
className="btn btn-sm btn-ghost"
aria-label={`${q.name} 지우기`}
onClick={() => void apiCall('DELETE', `/api/quizzes/${q.id}`).then(refresh, () => toast('지우지 못했어요.', 'error'))}
>
지우기
</button>
</li>
))}
</ul>
)}
</Sheet>
);
}
function JoinError({ text }: { text: string }) {
return (
<main className="page narrow stack">

View File

@@ -159,6 +159,7 @@ interface Site {
chatFloodGuard: boolean;
chatRatePerSec: number;
chatBurst: number;
questionLimitSec: number;
}
function SiteSettings() {
@@ -206,6 +207,11 @@ function SiteSettings() {
금칙어 (쉼표로 구분, 닉네임·채팅에 적용)
<textarea className="input" value={words} onChange={(e) => setWords(e.target.value)} />
</label>
<label className="field" style={{ maxWidth: 320 }}>
문제 하나의 제한 시간 (초, 짧은 클립 모드)
<input className="input" type="number" min={10} max={600} value={s.questionLimitSec} onChange={(e) => setS({ ...s, questionLimitSec: Number(e.target.value) })} />
<span className="muted small">듣고맞출시간이 1초~1분인 방에서 이 시간 안에 아무도 못 맞히면 정답을 공개해요. "끝까지"는 곡이 끝날 때까지예요.</span>
</label>
<fieldset className="card stack" style={{ margin: 0 }}>
<legend style={{ fontWeight: 800, padding: '0 6px' }}>채팅 도배 방지</legend>
<label className="check">

View File

@@ -328,6 +328,100 @@ input.input.sm { width: 76px; }
.sheet { background: var(--surface); border: 2px solid var(--ink); border-radius: 18px; box-shadow: 6px 6px 0 var(--ink); padding: 22px; width: min(420px, 100%); display: flex; flex-direction: column; gap: 14px; }
.sheet:focus { outline: none; }
/* ---------------------------------------------------------------- game (docs/03 게임 화면, mockups/game.html) */
.kbd { display: inline-block; font-size: 0.72rem; font-weight: 750; padding: 0 5px; border-radius: 5px; border: 1.5px solid currentColor; opacity: 0.7; line-height: 1.5; }
.game { display: flex; flex-direction: column; min-height: calc(100vh - 64px - 56px); }
.gbar { display: flex; align-items: center; gap: 12px; padding: 9px 24px; background: #1e1b18; color: #f5efe3; flex-wrap: wrap; }
.gbar .q { font-weight: 850; font-size: 1.15rem; letter-spacing: -0.02em; }
.gbar .q span { opacity: 0.55; font-weight: 700; }
.badge.dark { background: #3a352f; color: #f5efe3; }
.gbtn { background: #2a2622; color: #fff; border-color: #f5efe3; box-shadow: 0 2px 0 #f5efe3; }
.gbtn.on { background: var(--mustard); color: #1e1b18; }
.gbtn:disabled { opacity: 0.45; }
.vol { display: inline-flex; align-items: center; gap: 6px; font-size: 0.9rem; }
.vol input { width: 90px; accent-color: var(--mustard); }
.ggrid { flex: 1; display: grid; grid-template-columns: 250px minmax(0, 1fr) 280px; gap: 16px; padding: 16px 20px; min-height: 0; max-width: 1600px; width: 100%; margin: 0 auto; }
.side { background: var(--surface); border: 1.5px solid var(--line); border-radius: var(--radius); padding: 14px; overflow-y: auto; max-height: calc(100vh - 190px); }
.side h3 { font-size: 0.85rem; font-weight: 800; color: var(--text-sub); margin-bottom: 8px; }
.scoreboard ol { list-style: none; margin: 0; padding: 0; }
.sb { display: flex; align-items: center; gap: 8px; padding: 6px; border-radius: 10px; font-weight: 700; font-size: 0.93rem; transition: transform 0.3s; }
.sb .rk { width: 20px; text-align: center; font-weight: 850; color: var(--text-sub); }
.sb .nm { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; }
.sb .sc { margin-left: auto; font-weight: 850; font-size: 1.05rem; }
.sb.me { background: var(--primary-soft); }
.sb.first .rk { color: var(--mustard); font-size: 1.1rem; }
.sb.off { opacity: 0.5; }
.gcenter { display: flex; flex-direction: column; gap: 12px; min-width: 0; min-height: 0; }
.stage { min-height: 190px; flex: none; background: var(--surface); border: 2px solid var(--ink); border-radius: var(--radius); display: flex; align-items: center; gap: 26px; padding: 16px 28px; position: relative; overflow: hidden; }
.stage .lp, .reveal .art.lp { width: 150px; height: 150px; border-radius: 50%; background: repeating-radial-gradient(circle at center, #1c1a1f 0 5px, #2a2830 5px 6.5px); position: relative; flex: none; box-shadow: 6px 6px 0 #174f56; }
.stage .lp::after { content: '?'; position: absolute; inset: 47px; border-radius: 50%; background: var(--mustard); display: flex; align-items: center; justify-content: center; font-weight: 900; font-size: 30px; color: #1e1b18; }
.stage .lp.spin { animation: lpspin 1.8s linear infinite; }
@keyframes lpspin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .stage .lp.spin { animation: none; } }
.sinfo { flex: 1; min-width: 0; }
.sinfo .mode { font-size: 0.87rem; font-weight: 750; color: var(--text-sub); }
.sinfo .big { font-size: 1.7rem; font-weight: 850; letter-spacing: -0.03em; margin: 4px 0 10px; }
.countdown { font-size: 3.2rem; font-weight: 900; line-height: 1.1; color: var(--primary); }
.bar { height: 10px; border-radius: 9px; background: var(--surface-3); overflow: hidden; }
.bar i { display: block; height: 100%; background: var(--primary); transition: width 0.2s linear; }
.times { display: flex; justify-content: space-between; color: var(--text-sub); font-weight: 700; margin-top: 4px; }
.limit { margin-top: 4px; }
.hint { display: inline-flex; align-items: center; gap: 10px; background: #fbf3e0; color: #1e1b18; border: 2px dashed #1e1b18; border-radius: 12px; padding: 6px 14px; font-weight: 850; font-size: 1.4rem; letter-spacing: 0.14em; }
.hint small { font-size: 0.75rem; letter-spacing: 0; font-weight: 750; color: #6b6157; }
.lyrics-card { background: var(--surface-2); border-radius: 12px; padding: 10px 16px; font-size: 1.1rem; font-weight: 700; line-height: 1.75; margin-bottom: 8px; }
.stage-note { position: absolute; left: 0; right: 0; bottom: 0; background: var(--warning-soft); padding: 6px 16px; font-weight: 700; font-size: 0.87rem; }
.late { position: absolute; right: 14px; top: 12px; display: flex; flex-direction: column; gap: 6px; }
.reveal { display: flex; align-items: center; gap: 24px; width: 100%; }
.reveal .art { width: 150px; height: 150px; object-fit: cover; border: 2px solid var(--ink); border-radius: 12px; flex: none; box-shadow: 5px 5px 0 #174f56; }
.chat.big { flex: 1; min-height: 340px; border: 2px solid var(--ink); padding: 12px 18px 14px; }
.chat.big .chat-log { height: auto; flex: 1; min-height: 240px; max-height: 52vh; font-size: 1.07rem; line-height: 1.62; }
.chat.big .input { min-height: 56px; font-size: 1.15rem; border-width: 2.5px; }
.chat-line.ok, .chat-line.ok b { color: var(--correct) !important; font-weight: 800; }
.ans-gap { height: 1.62em; }
.ans-text { height: 1.62em; text-align: center; font-weight: 900; font-size: 1.3rem; letter-spacing: -0.02em; }
.ans-text span { border-bottom: 4px solid var(--mustard); padding: 0 6px; }
.answer-item.none .ans-text { color: var(--text-sub); }
.answer-item.none .ans-text span { border-bottom-color: var(--line); }
.typing { font-size: 0.83rem; color: var(--text-sub); font-weight: 650; min-height: 1.3em; display: flex; align-items: center; gap: 6px; }
.dots { display: inline-flex; gap: 3px; }
.dots i { width: 5px; height: 5px; border-radius: 50%; background: var(--text-sub); animation: dot 1s infinite; }
.dots i:nth-child(2) { animation-delay: 0.15s; }
.dots i:nth-child(3) { animation-delay: 0.3s; }
@keyframes dot { 50% { opacity: 0.2; } }
.hist .h { padding: 8px 4px; border-bottom: 1.5px dashed var(--line); font-size: 0.9rem; }
.hist .h:last-child { border-bottom: 0; }
.hist .t { font-weight: 800; }
.hist .m { color: var(--text-sub); font-size: 0.8rem; margin-top: 2px; display: flex; align-items: center; gap: 6px; }
.hist .n { display: inline-block; width: 22px; font-weight: 850; color: var(--text-sub); }
.mini-stars { font-weight: 850; font-size: 0.8rem; }
.unlock-overlay { position: fixed; inset: 0; z-index: 40; background: rgba(20, 18, 14, 0.55); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; color: #fff; text-align: center; padding: 20px; }
.unlock-overlay .btn { font-size: 1.3rem; min-height: 64px; padding: 0 28px; }
.sound-card { background: var(--warning-soft); border-color: var(--ink); }
.result .rank td, .result .rank th { font-size: 0.95rem; }
.songlist { margin: 0; padding-left: 0; list-style: none; display: flex; flex-direction: column; gap: 6px; }
.songlist a { font-size: 0.85rem; }
.saved-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; max-height: 50vh; overflow-y: auto; }
.saved-list li { display: flex; align-items: center; gap: 8px; border: 1.5px solid var(--line); border-radius: 10px; padding: 8px 10px; }
@media (max-width: 1100px) {
.ggrid { grid-template-columns: minmax(0, 1fr); }
.ggrid .side { max-height: none; }
.scoreboard { order: 2; }
.scoreboard ol { display: flex; gap: 6px; overflow-x: auto; }
.scoreboard .sb { flex: none; border: 1.5px solid var(--line); }
.hist { order: 3; max-height: 220px !important; }
}
@media (max-width: 600px) {
.gbar { padding: 8px 12px; gap: 8px; }
.gbar .kbd { display: none; }
.ggrid { padding: 10px; gap: 10px; }
.stage { min-height: 0; padding: 10px 14px; gap: 14px; }
.stage .lp, .reveal .art, .reveal .art.lp { width: 72px; height: 72px; box-shadow: 3px 3px 0 #174f56; }
.stage .lp::after { inset: 24px; font-size: 16px; }
.sinfo .big { font-size: 1.2rem; margin: 2px 0 6px; }
.countdown { font-size: 2.2rem; }
.chat.big .chat-log { max-height: 46vh; }
}
/* ---------------------------------------------------------------- responsive */
@media (max-width: 960px) {
.hero { grid-template-columns: 1fr; }