이지선다 모드: 조회수가 더 높은 곡 고르기. 이지선다 퀴즈는 조회수가 든 파일로 만들고(custom_quizzes.kind='duel', custom_quiz_items.views, 013 마이그레이션; 1,234,567·123만·1.2억도 읽음, 조회수 없는 줄은 빠짐) 이지선다에서만, 일반 퀴즈는 듣고맞추기에서만 쓴다. 서버 game/duel.ts: 문제마다 A/B 카드, 카드를 누르면 고른 것(시간 전까지 바꾸기), 시간이 끝나면 조회수 공개·높은 쪽 1점·역배(혼자 맞히고 반대쪽 2명 이상) 2점·같으면 둘 다 정답, 매번 새 두 곡/연속(이긴 곡이 조회수를 보인 채 A로 남음). 화면 DuelScreen: 고른 사람 프로필이 카드 밑에, 카드마다 숨은 플레이어(net/duel-player.ts)로 각자 듣고 다시 누르면 멈춘 곳부터 이어서. 방 설정 이지선다(제한 시간 기본 30초·진행 방식·재생위치·문제 수, 이지선다 퀴즈만 목록에), 결과 화면 역배 성공 수. 관리자 파일로 만들기 종류 선택(조회수 열이 있으면 이지선다), 조회수 편집·내보내기·빈 양식. 폰 점수판 가로 스크롤 키보드 접근(axe). 서버 테스트 146개, e2e duel(실제 유튜브 이어 듣기 포함)·game·quiz·admin·rooms·login·a11y 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-23 21:02:43 +09:00
parent 3c5e26f9b7
commit 666c236a8e
33 changed files with 1789 additions and 136 deletions

View File

@@ -28,8 +28,10 @@ export const ChatPanel = forwardRef<
onTyping?: (on: boolean) => void;
typing?: string[];
big?: boolean;
/** Input hint (the game screen: 정답이나 채팅; 이지선다 has no answers to type). */
placeholder?: string;
}
>(function ChatPanel({ lines, pending, meId, myName, onSend, onTyping, typing = [], big }, ref) {
>(function ChatPanel({ lines, pending, meId, myName, onSend, onTyping, typing = [], big, placeholder }, ref) {
const [text, setText] = useState('');
const [stuck, setStuck] = useState(true);
const [unseen, setUnseen] = useState(false);
@@ -154,7 +156,7 @@ export const ChatPanel = forwardRef<
className="input"
value={text}
maxLength={CHAT_MAX}
placeholder={big ? '정답이나 채팅 입력 (Enter)' : '메시지 입력 (Enter)'}
placeholder={placeholder ?? (big ? '정답이나 채팅 입력 (Enter)' : '메시지 입력 (Enter)')}
aria-label="채팅 입력"
autoComplete="off"
onChange={(e) => {

View File

@@ -5,6 +5,8 @@
import { useEffect, useRef, useState, type ReactNode } from 'react';
import {
COUNTS,
DUEL_FLOWS,
DUEL_SECS,
HINT_TIMES,
LEVELS,
LISTEN_SECS,
@@ -14,6 +16,7 @@ import {
VOTE_RULES,
listenLabel,
voteLabel,
type QuizKind,
type QuizSummary,
type RoomConfig,
type VoteRule,
@@ -244,7 +247,8 @@ export function RoomSettings({
['테마', 'theme'],
];
const toggleGenre = (id: string) => onPatch({ genres: c.genres.includes(id) ? c.genres.filter((g) => g !== id) : [...c.genres, id] });
const listening = c.mode !== 'lyrics';
const duel = c.mode === 'duel';
const listening = c.mode !== 'lyrics' && !duel;
// 제작된 퀴즈 chosen but no quiz picked yet: only on this screen until a quiz is picked
const [pickingOwn, setPickingOwn] = useState(false);
const picking = pickingProp ?? pickingOwn;
@@ -252,8 +256,20 @@ export function RoomSettings({
useEffect(() => {
if (c.quizId) setPicking(false);
}, [c.quizId]); // eslint-disable-line react-hooks/exhaustive-deps
const source: 'pick' | 'quiz' = c.quizId || picking ? 'quiz' : 'pick';
const source: 'pick' | 'quiz' = c.quizId || picking || duel ? 'quiz' : 'pick';
const quiz = source === 'quiz';
const duelMax = c.duelFlow === 'chain' ? Math.max(0, pool.playable - 1) : Math.floor(pool.playable / 2);
// 일반 퀴즈 → 듣고맞추기 only, 이지선다 → 이지선다 퀴즈 only: another mode leaves the chosen quiz (the server drops it)
const pickMode = (mode: RoomConfig['mode']) => {
if (mode === c.mode) return;
if (mode === 'duel') {
setPicking(true);
onPatch({ mode });
} else if (duel || (quiz && mode !== 'listen')) {
setPicking(false);
onPatch(c.quizId && !duel ? { mode, quizId: null } : { mode });
} else onPatch({ mode });
};
return (
<div className="settings card ink">
<div className="hd">
@@ -275,7 +291,12 @@ export function RoomSettings({
aria-label="방 이름"
/>
</Section>
{allowQuiz && (
{allowQuiz && duel && (
<Section title="이지선다 퀴즈" tip="조회수가 든 파일로 만든 이지선다 퀴즈만 고를 수 있어요">
<QuizPicker kind="duel" chosen={c.quizId ? { id: c.quizId, name: c.quizName } : null} songs={pool.playable} ro={ro} onPick={(quizId) => onPatch({ quizId })} />
</Section>
)}
{allowQuiz && !duel && (
<Section title="문제 고르기">
<Seg
label="문제 고르기"
@@ -295,20 +316,48 @@ export function RoomSettings({
{ v: 'quiz', label: '📋 제작된 퀴즈' },
]}
/>
{quiz && <QuizPicker chosen={c.quizId ? { id: c.quizId, name: c.quizName } : null} songs={pool.playable} ro={ro} onPick={(quizId) => onPatch({ quizId })} />}
{quiz && <QuizPicker kind="normal" chosen={c.quizId ? { id: c.quizId, name: c.quizName } : null} songs={pool.playable} ro={ro} onPick={(quizId) => onPatch({ quizId })} />}
</Section>
)}
<Section title="모드">
<Seg
label="모드"
value={c.mode}
disabled={ro || quiz}
onChange={(mode) => onPatch({ mode })}
options={MODES.map((m) => ({ v: m.id, label: `${m.icon} ${m.label}` }))}
disabled={ro}
onChange={pickMode}
options={MODES.filter((m) => allowQuiz || m.id !== 'duel').map((m) => ({ v: m.id, label: `${m.icon} ${m.label}` }))}
/>
{quiz && <p className="muted small" style={{ marginTop: 6 }}>제작된 퀴즈는 듣고맞추기로만 할 수 있어요.</p>}
{quiz && !duel && <p className="muted small" style={{ marginTop: 6 }}>제작된 퀴즈는 듣고맞추기로 해요. 다른 모드를 고르면 직접 선택으로 바뀌어요.</p>}
{duel && <p className="muted small" style={{ marginTop: 6 }}>두 곡 중 유튜브 조회수가 더 높은 곡을 고르는 모드예요. 카드를 누르면 그 노래가 나오고, 그 카드를 고른 게 돼요.</p>}
<div className="subbox">
{listening ? (
{duel ? (
<>
<div>
<div className="label">제한 시간</div>
<Seg label="제한 시간" value={c.duelSec} disabled={ro} onChange={(duelSec) => onPatch({ duelSec })} options={DUEL_SECS.map((v) => ({ v, label: `${v}초` }))} />
</div>
<div>
<div className="label">진행 방식</div>
<Seg label="진행 방식" value={c.duelFlow} disabled={ro} onChange={(duelFlow) => onPatch({ duelFlow })} options={DUEL_FLOWS.map((f) => ({ v: f.id, label: f.label }))} />
<p className="muted small" style={{ marginTop: 6 }}>
{c.duelFlow === 'chain' ? '조회수가 더 높은 곡이 조회수를 보여 준 채 남고, 새 곡과 다시 비교해요.' : '문제마다 새로운 두 곡이 나와요.'}
</p>
</div>
<div>
<div className="label">재생위치</div>
<Seg
label="재생위치"
value={c.startAt}
disabled={ro}
onChange={(startAt) => onPatch({ startAt })}
options={[
{ v: 'start', label: '처음부터' },
{ v: 'highlight', label: '하이라이트부터' },
]}
/>
</div>
</>
) : listening ? (
<>
<div>
<div className="label">듣고맞출시간</div>
@@ -394,8 +443,18 @@ export function RoomSettings({
</Section>
</>
)}
<PlayRules c={c} ro={ro} listening={listening} onPatch={onPatch} />
{quiz ? (
<PlayRules c={c} ro={ro} listening={listening} duel={duel} onPatch={onPatch} />
{duel ? (
<Section title="문제 수">
<Seg
label="문제 수"
value={c.count}
disabled={ro}
onChange={(count) => onPatch({ count })}
options={COUNTS.map((v) => ({ v, label: v ? String(v) : `전부(${duelMax.toLocaleString()})` }))}
/>
</Section>
) : quiz ? (
<Section title="문제 수">
<p className="small" style={{ margin: 0 }}>{c.quizId ? `퀴즈에 든 곡 전부 (${pool.playable.toLocaleString()}문제)` : '퀴즈를 고르면 그 퀴즈의 곡 전부가 나와요'}</p>
</Section>
@@ -459,14 +518,28 @@ export function PlayRules({
c,
ro,
listening,
duel = false,
onPatch,
}: {
c: Pick<RoomConfig, 'answer' | 'strict' | 'hint' | 'hintVotes' | 'skipVotes' | 'replayVotes' | 'revealSec' | 'nextVotes'>;
ro: boolean;
listening: boolean;
/** 이지선다: no answers to type, hints, skip or replay — only how long the result stays. */
duel?: boolean;
onPatch: (p: Patch) => void;
}) {
const vote = (rules: readonly VoteRule[]) => rules.map((v) => ({ v, label: voteLabel(v) }));
const after = (
<>
<Section title="다음 문제까지" tip={duel ? '결과(조회수)를 보여 준 뒤 다음 문제로 넘어가기까지 기다리는 시간' : '정답을 공개한 뒤 다음 문제로 넘어가기까지 기다리는 시간. 그동안 노래는 계속 나와요'}>
<Seg label="다음 문제까지" value={c.revealSec} disabled={ro} onChange={(revealSec) => onPatch({ revealSec })} options={REVEAL_SECS.map((v) => ({ v, label: `${v}초` }))} />
</Section>
<Section title="다음문제인원(이상)" tip={duel ? '결과를 보는 중에 바로 다음 문제로 넘어가려면 다음 문제를 눌러야하는 인원 설정' : '정답 공개 중에 바로 다음 문제로 넘어가려면 다음 문제를 눌러야하는 인원 설정'}>
<Seg label="다음문제인원" value={c.nextVotes} disabled={ro} onChange={(nextVotes) => onPatch({ nextVotes })} options={vote(VOTE_RULES)} />
</Section>
</>
);
if (duel) return after;
return (
<>
<Section title="정답방식">
@@ -521,12 +594,7 @@ export function PlayRules({
<Seg label="다시듣기인원" value={c.replayVotes} disabled={ro} onChange={(replayVotes) => onPatch({ replayVotes })} options={vote(VOTE_RULES)} />
</Section>
)}
<Section title="다음 문제까지" tip="정답을 공개한 뒤 다음 문제로 넘어가기까지 기다리는 시간. 그동안 노래는 계속 나와요">
<Seg label="다음 문제까지" value={c.revealSec} disabled={ro} onChange={(revealSec) => onPatch({ revealSec })} options={REVEAL_SECS.map((v) => ({ v, label: `${v}초` }))} />
</Section>
<Section title="다음문제인원(이상)" tip="정답 공개 중에 바로 다음 문제로 넘어가려면 다음 문제를 눌러야하는 인원 설정">
<Seg label="다음문제인원" value={c.nextVotes} disabled={ro} onChange={(nextVotes) => onPatch({ nextVotes })} options={vote(VOTE_RULES)} />
</Section>
{after}
</>
);
}
@@ -534,7 +602,7 @@ export function PlayRules({
const VIS: Record<string, string> = { private: '비공개', partial: '일부공개' };
/** 제작된 퀴즈 list with a search box; not-public quizzes come first, marked. */
function QuizPicker({ chosen, songs, ro, onPick }: { chosen: { id: number; name: string } | null; songs: number; ro: boolean; onPick: (id: number) => void }) {
function QuizPicker({ kind, chosen, songs, ro, onPick }: { kind: QuizKind; chosen: { id: number; name: string } | null; songs: number; ro: boolean; onPick: (id: number) => void }) {
const [open, setOpen] = useState(!chosen);
const [q, setQ] = useState('');
const [list, setList] = useState<QuizSummary[] | null>(null);
@@ -542,12 +610,12 @@ function QuizPicker({ chosen, songs, ro, onPick }: { chosen: { id: number; name:
useEffect(() => {
if (!open || ro) return;
const t = setTimeout(() => {
apiCall<{ quizzes: QuizSummary[] }>('GET', `/api/made-quizzes?q=${encodeURIComponent(q.trim())}`)
apiCall<{ quizzes: QuizSummary[] }>('GET', `/api/made-quizzes?kind=${kind}&q=${encodeURIComponent(q.trim())}`)
.then((r) => (setList(r.quizzes), setError(null)))
.catch((e: Error) => setError(e.message));
}, 200);
return () => clearTimeout(t);
}, [q, open, ro]);
}, [q, open, ro, kind]);
useEffect(() => {
if (chosen) setOpen(false);
}, [chosen?.id]); // eslint-disable-line react-hooks/exhaustive-deps
@@ -571,8 +639,12 @@ function QuizPicker({ chosen, songs, ro, onPick }: { chosen: { id: number; name:
<>
<input className="input" value={q} onChange={(e) => setQ(e.target.value)} placeholder="퀴즈 이름 검색" aria-label="퀴즈 이름 검색" />
{error && <span className="field-error small">{error}</span>}
<div className="quiz-pick" role="listbox" aria-label="제작된 퀴즈 목록">
{list?.length === 0 && <span className="muted small" style={{ padding: 10 }}>{q.trim() ? '검색 결과가 없어요.' : '고를 수 있는 퀴즈가 없어요.'}</span>}
<div className="quiz-pick" role="listbox" aria-label={kind === 'duel' ? '이지선다 퀴즈 목록' : '제작된 퀴즈 목록'}>
{list?.length === 0 && (
<span className="muted small" style={{ padding: 10 }}>
{q.trim() ? '검색 결과가 없어요.' : kind === 'duel' ? '고를 수 있는 이지선다 퀴즈가 없어요. 관리자 → 퀴즈 → 파일로 만들기에서 조회수가 든 파일로 만들 수 있어요.' : '고를 수 있는 퀴즈가 없어요.'}
</span>
)}
{list?.map((x) => (
<button key={x.id} type="button" role="option" aria-selected={chosen?.id === x.id} className="quiz-pick-item" onClick={() => onPick(x.id)}>
<span className="row" style={{ gap: 6 }}>

View File

@@ -0,0 +1,162 @@
/**
* 이지선다 cards: every player listens on their own screen (no shared timeline, docs: 이지선다).
* One hidden player per card, both loaded muted when a question starts, so tapping a card plays it at once and going back
* to the other card goes on where it stopped. Tapping the card that is playing pauses it. A song that stays for the next
* question (연속 방식) keeps its player and position.
*/
import { create } from 'zustand';
import type { DuelSide } from '@mq/shared/lite';
import { cardEngine, usePlayer, type Engine } from './player';
export interface DuelPlayerState {
/** The card playing right now. */
playing: DuelSide | null;
/** Videos that cannot be played here (deleted / embedding off), by video id. */
broken: Record<string, number>;
}
export const useDuelPlayer = create<DuelPlayerState>(() => ({ playing: null, broken: {} }));
interface Slot {
engine: Engine;
ready: Promise<void>;
videoId: string | null;
startSec: number;
gain: number;
/** The video was asked for (preload or a tap): a tap plays it instead of loading it again. */
loaded: boolean;
/** Bumped by every command, so an older preload stops before pausing a song the player started meanwhile. */
tk: number;
}
const slots = new Map<DuelSide, Slot>();
let key = '';
function make(): Slot {
const s: Slot = {
engine: null as unknown as Engine,
ready: Promise.resolve(),
videoId: null,
startSec: 0,
gain: 1,
loaded: false,
tk: 0,
};
s.engine = cardEngine({
onError: (code) => {
if (!s.videoId) return;
useDuelPlayer.setState((st) => ({ broken: { ...st.broken, [s.videoId!]: code }, playing: st.playing && slots.get(st.playing) === s ? null : st.playing }));
},
onState: (state) => {
// the song ended by itself
if (state === 0 && useDuelPlayer.getState().playing && slots.get(useDuelPlayer.getState().playing!) === s) useDuelPlayer.setState({ playing: null });
},
});
s.ready = s.engine.init();
return s;
}
const waitFor = (pred: () => boolean, ms: number, s: Slot, tk: number) =>
new Promise<boolean>((res) => {
const t0 = performance.now();
const iv = setInterval(() => {
if (tk !== s.tk) return (clearInterval(iv), res(false));
if (pred()) return (clearInterval(iv), res(true));
if (performance.now() - t0 > ms) return (clearInterval(iv), res(false));
}, 30);
});
/** Load muted and stop at the start position, so the first tap starts right away. */
async function preload(s: Slot): Promise<void> {
const tk = ++s.tk;
await s.ready;
if (tk !== s.tk || !s.videoId) return;
const e = s.engine;
e.mute(true);
e.load(s.videoId, s.startSec);
s.loaded = true;
if (!(await waitFor(() => e.state() === 1, 15_000, s, tk))) return;
e.pause();
await waitFor(() => e.state() === 2, 3000, s, tk);
if (tk !== s.tk) return;
e.seek(s.startSec);
}
// for e2e checks, like window.mqPlayer
(window as unknown as { mqDuel: unknown }).mqDuel = {
state: (side: DuelSide) => slots.get(side)?.engine.state() ?? null,
time: (side: DuelSide) => slots.get(side)?.engine.time() ?? null,
muted: (side: DuelSide) => slots.get(side)?.engine.isMuted() ?? null,
video: (side: DuelSide) => slots.get(side)?.videoId ?? null,
};
const volumeOf = (s: Slot) => Math.round(usePlayer.getState().volume * s.gain);
usePlayer.subscribe((st, prev) => {
if (st.volume === prev.volume) return;
for (const s of slots.values()) s.engine.volume(volumeOf(s));
});
export const duelPlayer = {
/** A new question (`k` changes): both cards load muted at their start position; a song still on the cards keeps its player. */
setup(k: string, cards: { side: DuelSide; videoId: string; startSec: number; gain: number }[]): void {
if (k === key) return;
key = k;
const old = new Map(slots);
for (const s of old.values()) {
s.tk++;
s.engine.pause();
}
useDuelPlayer.setState({ playing: null });
const next = new Map<DuelSide, Slot>();
const free = [...old.values()].filter((s) => !cards.some((c) => c.videoId === s.videoId));
for (const c of cards) {
const same = [...old.values()].find((s) => s.videoId === c.videoId);
if (same) {
next.set(c.side, same);
continue;
}
const s = free.shift() ?? make();
s.videoId = c.videoId;
s.startSec = c.startSec;
s.gain = c.gain;
s.loaded = false;
next.set(c.side, s);
void preload(s);
}
slots.clear();
for (const [side, s] of next) slots.set(side, s);
},
/** Tap on a card: play it (from where it stopped), stop the other one; the card that is playing pauses. */
toggle(side: DuelSide): void {
const s = slots.get(side);
if (!s?.videoId) return;
const st = useDuelPlayer.getState();
if (st.playing === side) {
s.engine.pause();
useDuelPlayer.setState({ playing: null });
return;
}
for (const [other, o] of slots) if (other !== side) o.engine.pause();
const tk = ++s.tk;
const e = s.engine;
const id = s.videoId;
e.volume(volumeOf(s));
e.mute(false);
if (s.loaded) e.play();
else {
s.loaded = true;
void s.ready.then(() => tk === s.tk && e.load(id, s.startSec));
}
useDuelPlayer.setState({ playing: side });
},
stop(): void {
key = '';
for (const s of slots.values()) {
s.tk++;
s.engine.pause();
}
useDuelPlayer.setState({ playing: null });
},
};

View File

@@ -45,7 +45,7 @@ export const usePlayer = create<PlayerState>(() => ({ unlocked: false, needsGest
/** 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 {
export interface Engine {
init(): Promise<void>;
unlock(): void;
load(id: string, startSec: number): void;
@@ -61,7 +61,7 @@ interface Engine {
videoId(): string | null;
}
type Listener = { onState?: (s: number) => void; onError?: (code: number) => void; onBlocked?: () => void };
export type Listener = { onState?: (s: number) => void; onError?: (code: number) => void; onBlocked?: () => void };
// ---------------------------------------------------------------- real YouTube engine
declare global {
@@ -301,6 +301,11 @@ function fakeEngine(l: Listener): Engine {
};
}
/** A player of its own (이지선다 cards: one per card, so switching cards goes on where each stopped). */
export function cardEngine(l: Listener): Engine {
return useFake() ? fakeEngine(l) : youtubeEngine(l);
}
// ---------------------------------------------------------------- controller
let engine: Engine | null = null;
let report: (n: number, ev: AudioEvent, code?: number) => void = () => {};

View File

@@ -5,6 +5,7 @@ import { create } from 'zustand';
import type { ChatLine, GameView, RoomView, ServerMessage } from '@mq/shared/lite';
import { toast } from '../store/toast';
import { player } from './player';
import { duelPlayer } from './duel-player';
import { noteServerBuild } from './update';
type Status = 'idle' | 'connecting' | 'open' | 'reconnecting';
@@ -111,6 +112,7 @@ function onMessage(m: ServerMessage): void {
if (m.code === useRoom.getState().code) {
setLastRoom(null);
player.stop();
duelPlayer.stop();
useRoom.setState({ room: null, left: m.reason, chat: [], pending: [], game: null, typing: [] });
}
return;
@@ -122,8 +124,8 @@ function onMessage(m: ServerMessage): void {
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));
if (!g || g.phase === 'result') (player.stop(), duelPlayer.stop());
else if (g.phase === 'reveal' && prev?.phase !== 'reveal' && g.mode !== 'lyrics' && g.mode !== 'duel' && g.participants.includes(myId)) player.reveal(Math.max(0, (g.revealUntil ?? 0) - serverNow() - 150));
useRoom.setState({ game: g });
return;
}
@@ -215,6 +217,7 @@ export const socket = {
send({ t: 'leave' });
setLastRoom(null);
player.stop();
duelPlayer.stop();
useRoom.setState({ code: null, room: null, chat: [], pending: [], game: null, typing: [] });
},
chat(text: string): void {

View File

@@ -0,0 +1,251 @@
/**
* 이지선다 게임 화면: two cards A and B. Tapping a card plays that song on this screen and is the pick (it can change
* until the time is up); everyone's picks show as small avatars under the cards. After the time the views come out,
* the higher card wins and points go to the players on it (역배: alone against 2 or more = 2 points).
*/
import { useEffect, useRef, useState } from 'react';
import { viewsLabel, type DuelCard, type GameView, type RoomView } from '@mq/shared/lite';
import { serverNow, socket, useRoom } from '../net/socket';
import { player, usePlayer } from '../net/player';
import { duelPlayer, useDuelPlayer } from '../net/duel-player';
import { useSession } from '../store/session';
import { Avatar, ConfirmSheet } from '../components/ui';
import { ChatPanel, type ChatHandle } from '../components/ChatPanel';
import { ResultScreen } from './GameScreen';
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 views = (n: number) => `${viewsLabel(n)}회`;
export function DuelScreen({ room, game }: { room: RoomView; game: GameView }) {
const me = useSession((s) => s.me)!;
const { chat, pending, typing, code } = useRoom();
const volume = usePlayer((s) => s.volume);
const { playing, broken } = useDuelPlayer();
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 d = game.duel!;
const send = (m: unknown) => socket.send(m);
const name = (id: string) => room.players.find((x) => x.id === id)?.nickname ?? game.scores.find((x) => x.id === id)?.nickname ?? '?';
const user = (id: string) => ({ id, nickname: name(id), avatar: room.players.find((x) => x.id === id)?.avatar ?? null });
const result = game.phase === 'reveal' ? d.result : null;
const mine = d.cards.find((x) => x.picks.includes(me.id))?.side ?? null;
// a new question: both cards load (muted) on this screen; leaving the game stops them
const qKey = `${code}:${game.n}:${d.cards.map((x) => x.videoId).join(',')}`;
useEffect(() => {
if (game.phase === 'result') return duelPlayer.stop();
duelPlayer.setup(qKey, d.cards);
}, [qKey, game.phase]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => () => duelPlayer.stop(), []);
// Ctrl+K during the reveal = 다음 문제; any other key goes to the chat
const phaseRef = useRef(game.phase);
phaseRef.current = game.phase;
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === 'k') {
e.preventDefault();
if (phaseRef.current === 'reveal') send({ t: 'vote', kind: 'next' });
return;
}
if (e.ctrlKey || e.metaKey || e.altKey) return;
const t = e.target as HTMLElement | null;
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.tagName === 'BUTTON' || 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 limit = game.clock.limitMs ?? 30_000;
const left = Math.max(0, Math.ceil((limit - elapsed) / 1000));
const revealLeft = Math.max(0, Math.ceil(((game.revealUntil ?? now) - now) / 1000));
const tap = (card: DuelCard) => {
duelPlayer.toggle(card.side);
if (game.phase === 'play' && !game.paused && mine !== card.side) send({ t: 'pick', n: game.n, side: card.side });
};
const need = game.need.next;
const nextOn = game.votes.next.includes(me.id);
return (
<main className="game duel">
<div className="gbar" role="toolbar" aria-label="게임 조작">
<div className="q">
문제 {game.n} <span>/ {game.total}</span>
</div>
<span className="badge dark">
🆚 이지선다 · {c.duelSec}초 · {d.flow === 'chain' ? '이긴 곡이 남기' : '매번 새 두 곡'}
</span>
{c.quizId && <span className="badge dark">📋 {c.quizName}</span>}
<div className="grow" />
{result && (
<button type="button" className={`btn btn-sm gbtn ${nextOn ? 'on' : ''}`} aria-pressed={nextOn} disabled={need === null} onClick={() => send({ t: 'vote', kind: 'next' })}>
⏭ 다음 문제
{need !== null && (
<span className="mono">
{' '}
{game.votes.next.length}/{need}
</span>
)}
<span className="kbd">Ctrl+K</span>
</button>
)}
<label className="vol" title="볼륨">
🔊
<input type="range" min={0} max={100} value={volume} onChange={(e) => player.setVolume(Number(e.target.value))} aria-label="볼륨" />
</label>
{isHost && (
<>
<button type="button" className="btn btn-sm gbtn" disabled={game.phase !== 'play'} onClick={() => send({ t: 'game', action: game.paused ? 'resume' : 'pause' })}>
{game.paused ? '▶ 계속' : '⏸ 일시정지'}
</button>
<button type="button" className="btn btn-sm gbtn" onClick={() => setConfirmEnd(true)}>
⏹ 끝내기
</button>
</>
)}
</div>
<div className="ggrid">
<aside className="side scoreboard" aria-label="점수판">
<h2>점수판 · {game.scores.length}명</h2>
{/* phone: the list scrolls sideways, so it takes keyboard focus (axe scrollable-region-focusable) */}
<ol tabIndex={0} aria-label="순위">
{game.scores.map((s, i) => {
const rank = 1 + game.scores.findIndex((o) => o.score === s.score && o.avgMs === s.avgMs);
const gain = result?.gains.find((g) => g.id === s.id);
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={user(s.id)} size={26} />
<span className="nm">
{s.nickname}
{s.id === me.id && ' (나)'}
{s.id === room.hostId && <span title="방장"> 👑</span>}
</span>
{gain && <span className={`gain ${gain.reverse ? 'rev' : ''}`}>+{gain.points}</span>}
<span className="sc mono">{s.score}</span>
</li>
);
})}
</ol>
</aside>
<div className="gcenter">
<section className="stage duel-stage" aria-live="polite">
<div className="duel-head">
<div className="big">{result ? (result.winner === 'both' ? '조회수가 똑같아요! 둘 다 정답' : `${result.winner === 'a' ? 'A' : 'B'}의 조회수가 더 높아요!`) : '어느 곡의 유튜브 조회수가 더 높을까요?'}</div>
{result ? (
<div className="small muted">
{result.gains.find((g) => g.reverse) ? `⚡ 역배 성공! ${name(result.gains.find((g) => g.reverse)!.id)}님 +2점 · ` : ''}
{game.n >= game.total ? '결과까지' : '다음 문제까지'} <b className="mono">{revealLeft}초</b>
</div>
) : game.paused ? (
<div className="small muted">⏸ 방장이 잠시 멈췄어요</div>
) : (
<>
<div className="bar" aria-hidden>
<i style={{ width: `${Math.min(100, (elapsed / limit) * 100)}%` }} />
</div>
<div className="small muted">
남은 시간 <b className="mono">{left}초</b> · 카드를 누르면 그 노래가 나오고 그 카드를 고른 거예요. 시간 안에는 몇 번이든 바꿀 수 있어요.
</div>
</>
)}
</div>
<div className="duel-cards">
{d.cards.map((card) => {
const won = result && (result.winner === 'both' || result.winner === card.side);
return (
<button
key={card.side}
type="button"
className={`duel-card ${mine === card.side ? 'mine' : ''} ${playing === card.side ? 'playing' : ''} ${result ? (won ? 'won' : 'lost') : ''}`}
aria-pressed={mine === card.side}
aria-label={`${card.side.toUpperCase()} ${card.title} ${card.artist}${mine === card.side ? ' (내가 고른 곡)' : ''}`}
onClick={() => tap(card)}
>
<span className="duel-side" aria-hidden>
{card.side.toUpperCase()}
</span>
<img className="duel-thumb" src={`https://i.ytimg.com/vi/${card.videoId}/hqdefault.jpg`} alt="" />
<span className="duel-title">{card.title}</span>
{card.artist && <span className="duel-artist muted">{card.artist}</span>}
<span className="duel-views" title={card.views !== null ? `${card.views.toLocaleString('ko-KR')}회` : undefined}>
{card.views !== null ? `조회수 ${views(card.views)}` : '조회수 ?'}
</span>
<span className="duel-state small">
{broken[card.videoId]
? '이 영상은 여기서 재생할 수 없어요 (고를 수는 있어요)'
: playing === card.side
? '♪ 재생 중 · 다시 누르면 멈춰요'
: mine === card.side
? '✔ 내가 고른 곡 · 눌러서 듣기'
: '▶ 눌러서 듣고 고르기'}
</span>
<span className="duel-picks" aria-label={`${card.side.toUpperCase()}를 고른 사람 ${card.picks.length}명`}>
{card.picks.map((id) => {
const g = result?.gains.find((x) => x.id === id);
return (
<span key={id} className="duel-pick" title={name(id)}>
<Avatar user={user(id)} size={24} />
{g && <b className={`gain ${g.reverse ? 'rev' : ''}`}>+{g.points}</b>}
</span>
);
})}
</span>
</button>
);
})}
</div>
</section>
<ChatPanel
ref={chatRef}
big
placeholder="채팅 입력 (Enter)"
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="지난 문제">
<h2>지난 문제</h2>
{game.history.length === 0 && <p className="small muted">아직 없어요</p>}
{[...game.history].reverse().map((h) => {
const x = h.duel!;
return (
<div key={h.n} className="h">
<span className="n">{h.n}</span>
{x.cards.map((cd, i) => (
<span key={cd.side} className={x.winner === 'both' || x.winner === cd.side ? 't' : 'muted'}>
{i > 0 && <span className="muted"> vs </span>}
{cd.title} <span className="small">({views(cd.views)})</span>
</span>
))}
<div className="m">{x.gains.length ? x.gains.map((g) => `${g.nickname} +${g.points}${g.reverse ? ' 역배' : ''}`).join(', ') : '맞힌 사람 없음'}</div>
</div>
);
})}
</aside>
</div>
{confirmEnd && <ConfirmSheet title="게임을 끝낼까요?" body="지금까지 점수로 결과를 보여 줘요." confirm="끝내기" danger onConfirm={() => send({ t: 'game', action: 'end' })} onClose={() => setConfirmEnd(false)} />}
</main>
);
}

View File

@@ -3,7 +3,7 @@
* 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 { listenLabel, viewsLabel, 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';
@@ -146,7 +146,8 @@ export function GameScreen({ room, game }: { room: RoomView; game: GameView }) {
<div className="ggrid">
<aside className="side scoreboard" aria-label="점수판">
<h2>점수판 · {game.scores.length}명</h2>
<ol>
{/* phone: the list scrolls sideways, so it takes keyboard focus (axe scrollable-region-focusable) */}
<ol tabIndex={0} aria-label="순위">
{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);
@@ -304,12 +305,13 @@ function RevealCard({ item, left, last }: { item: GameHistoryItem; left: number;
);
}
function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
export 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 duel = game.mode === 'duel';
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 (
@@ -325,8 +327,8 @@ function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
<th>순위</th>
<th>이름</th>
<th>점수</th>
<th>맞힌 곡</th>
<th>가장 빨리 맞힌 곡</th>
<th>{duel ? '맞힌 문제' : '맞힌 곡'}</th>
<th>{duel ? '역배 성공' : '가장 빨리 맞힌 곡'}</th>
</tr>
</thead>
<tbody>
@@ -338,7 +340,7 @@ function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
<td>{s.nickname}</td>
<td className="mono">{s.score}</td>
<td className="mono">{s.correct}</td>
<td>{f ? `${f.title} · ${secs(f.ms)}` : '-'}</td>
<td>{duel ? <span className="mono">{s.reverse ?? 0}</span> : f ? `${f.title} · ${secs(f.ms)}` : '-'}</td>
</tr>
);
})}
@@ -369,7 +371,23 @@ function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
<section className="card">
<h2 style={{ marginBottom: 10 }}>이번 게임 곡 목록</h2>
<ol className="songlist">
{game.history.map((h) => (
{game.history.map((h) =>
h.duel ? (
<li key={h.n}>
<span className="mono muted">{h.n}.</span>{' '}
{h.duel.cards.map((cd, i) => (
<span key={cd.side}>
{i > 0 && ' vs '}
{h.duel!.winner === 'both' || h.duel!.winner === cd.side ? <b>{cd.title}</b> : cd.title}
{cd.artist && ` - ${cd.artist}`} <span className="small muted">({viewsLabel(cd.views)}회)</span>{' '}
<a href={`https://youtu.be/${cd.videoId}`} target="_blank" rel="noreferrer" className="small">
영상
</a>
</span>
))}{' '}
<span className="small muted">{h.duel.gains.length ? h.duel.gains.map((g) => `${g.nickname} +${g.points}${g.reverse ? ' 역배' : ''}`).join(', ') : '맞힌 사람 없음'}</span>
</li>
) : (
<li key={h.n}>
<span className="mono muted">{h.n}.</span> <b>{h.title}</b> - {h.artist} <Stars n={h.level} />{' '}
{h.videoId && (
@@ -379,7 +397,8 @@ function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
)}{' '}
<span className="small muted">{h.winner ? `${h.winner} ${secs(h.ms)}` : h.how === 'skip' ? '스킵' : '시간 초과'}</span>
</li>
))}
),
)}
</ol>
</section>
{save && (

View File

@@ -15,6 +15,7 @@ import { RoomSettings, type CatalogMeta } from '../components/RoomSettings';
import { ChatPanel } from '../components/ChatPanel';
import { player, usePlayer } from '../net/player';
import { GameScreen } from './GameScreen';
import { DuelScreen } from './DuelScreen';
const LEFT_TEXT: Record<string, string> = {
kicked: '방장이 방에서 내보냈어요.',
@@ -100,7 +101,11 @@ export default function RoomPage() {
const genreName = (id: string) => meta?.genres.find((g) => g.id === id)?.name ?? id;
const link = `${location.origin}/r/${room.code}`;
const needArtist = c.mode === 'artist' && c.artistIds.length === 0;
const needQuiz = quizPicking && !c.quizId;
const duel = c.mode === 'duel';
const needQuiz = (quizPicking || duel) && !c.quizId;
// 이지선다: two songs a question (매번 새 두 곡) or one new song after the first two (연속)
const duelMax = duel ? (c.duelFlow === 'chain' ? Math.max(0, room.pool.playable - 1) : Math.floor(room.pool.playable / 2)) : 0;
const questions = duel ? (c.count ? Math.min(c.count, duelMax) : duelMax) : c.quizId ? room.pool.playable : c.count;
const short = !c.quizId && 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;
@@ -135,7 +140,7 @@ export default function RoomPage() {
</button>
</section>
{playing ? (
<GameScreen room={room} game={game} />
game.mode === 'duel' ? <DuelScreen room={room} game={game} /> : <GameScreen room={room} game={game} />
) : (
<main className="room-main">
<div className="stack" style={{ minWidth: 0 }}>
@@ -183,20 +188,21 @@ export default function RoomPage() {
<h2>
{c.quizId ? '퀴즈 곡' : '조건에 맞는 곡'} <span className="mono">{room.pool.playable.toLocaleString()}</span>곡
</h2>
<p className="small">{configSummary(c, genreName).join(' · ')} · {c.quizId ? `${room.pool.playable}문제` : c.count ? `${c.count}문제` : '무제한'}</p>
<p className="small">{configSummary(c, genreName).join(' · ')} · {c.quizId || questions ? `${questions}문제` : '무제한'}</p>
{room.pool.total > room.pool.playable && (
<p className="small" style={{ opacity: 0.85 }}>
원곡 확인 중인 곡 {(room.pool.total - room.pool.playable).toLocaleString()}곡은 확인이 끝나면 나와요
</p>
)}
{needArtist && <p className="small">가수를 1명 이상 골라 주세요.</p>}
{needQuiz && <p className="small">방 설정에서 제작된 퀴즈를 골라 주세요.</p>}
{needQuiz && <p className="small">{duel ? '방 설정에서 이지선다 퀴즈를 골라 주세요.' : '방 설정에서 제작된 퀴즈를 골라 주세요.'}</p>}
{duel && !!c.quizId && room.pool.playable === 1 && <p className="small">이지선다에는 조회수가 있는 곡이 2곡 이상 있어야 해요.</p>}
{!needArtist && short && room.pool.playable > 0 && <p className="small">문제 수보다 곡이 적어서 {room.pool.playable}문제만 나와요.</p>}
{!needArtist && !c.quizId && room.pool.playable === 0 && room.pool.total === 0 && <p className="small">이 조건에 맞는 곡이 없어요. 장르·연도·난이도를 넓혀 보세요.</p>}
{!!c.quizId && room.pool.playable === 0 && <p className="small">이 퀴즈에는 아직 곡이 없어요.</p>}
</div>
{isHost ? (
<button className="btn btn-mustard btn-lg" disabled={needArtist || needQuiz || room.pool.playable === 0} onClick={start}>
<button className="btn btn-mustard btn-lg" disabled={needArtist || needQuiz || room.pool.playable === 0 || (duel && duelMax === 0)} onClick={start}>
게임 시작
</button>
) : (
@@ -205,7 +211,7 @@ export default function RoomPage() {
</button>
)}
</section>
{c.mode !== 'lyrics' && !unlocked && (
{c.mode !== 'lyrics' && !duel && !unlocked && (
<section className="card sound-card row">
<span className="grow">🔊 노래가 들리도록 게임 전에 한 번 눌러 주세요. 브라우저가 소리를 막을 수 있어요.</span>
<button type="button" className="btn btn-mustard" onClick={() => player.unlock()}>

View File

@@ -5,7 +5,10 @@
*/
import { useMemo, useState } from 'react';
import {
DUEL_COLUMN_LABEL,
QUIZ_COLUMN_LABEL,
QUIZ_FILE_COLUMNS,
viewsLabel,
guessColumns,
headerRow,
parseQuizRows,
@@ -15,13 +18,15 @@ import {
writeXlsx,
type QuizColumn,
type QuizItem,
type QuizKind,
type Sheet,
} from '@mq/shared/lite';
import { toast } from '../../store/toast';
import { ConfirmSheet } from '../../components/ui';
import { Seg } from '../../components/RoomSettings';
const MAX_BYTES = 20 * 1024 * 1024;
const COLUMN_ORDER: QuizColumn[] = ['link', 'answer', 'desc', 'hint', 'answers', 'descAnswers', 'order', 'start', 'highlight'];
const colLabel = (c: QuizColumn, kind: QuizKind) => (kind === 'duel' ? (DUEL_COLUMN_LABEL[c] ?? QUIZ_COLUMN_LABEL[c]) : QUIZ_COLUMN_LABEL[c]);
function download(name: string, bytes: Uint8Array) {
const url = URL.createObjectURL(new Blob([bytes as Uint8Array<ArrayBuffer>], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }));
@@ -35,18 +40,19 @@ function download(name: string, bytes: Uint8Array) {
}
/** 엑셀로 내보내기: the songs as a file this screen reads back. */
export function exportQuiz(name: string, items: QuizItem[]) {
const { rows, widths } = quizToRows(items);
export function exportQuiz(name: string, items: QuizItem[], kind: QuizKind = 'normal') {
const { rows, widths } = quizToRows(items, kind);
download(name, writeXlsx(name, rows, widths));
}
export function downloadTemplate() {
const { rows, widths } = quizTemplateRows();
download('퀴즈 양식', writeXlsx('퀴즈', rows, widths));
export function downloadTemplate(kind: QuizKind = 'normal') {
const { rows, widths } = quizTemplateRows(kind);
download(kind === 'duel' ? '이지선다 양식' : '퀴즈 양식', writeXlsx(kind === 'duel' ? '이지선다' : '퀴즈', rows, widths));
}
export function QuizFileImport({
mode,
kind: fixedKind,
existing = [],
onCreate,
onApply,
@@ -54,8 +60,10 @@ export function QuizFileImport({
}: {
/** create: 파일로 만들기 (new quiz) · into: 파일에서 가져오기 (the open quiz). */
mode: 'create' | 'into';
/** The open quiz's kind (into); 파일로 만들기 picks it (a 조회수 column means 이지선다). */
kind?: QuizKind;
existing?: QuizItem[];
onCreate?: (name: string, items: QuizItem[]) => Promise<void>;
onCreate?: (name: string, items: QuizItem[], kind: QuizKind) => Promise<void>;
onApply?: (items: QuizItem[], replace: boolean) => void;
onClose: () => void;
}) {
@@ -66,13 +74,18 @@ export function QuizFileImport({
const [name, setName] = useState('');
const [busy, setBusy] = useState(false);
const [confirmReplace, setConfirmReplace] = useState(false);
const [chosenKind, setChosenKind] = useState<QuizKind>(fixedKind ?? 'normal');
const kind = fixedKind ?? chosenKind;
const pickSheet = (sheets: Sheet[], i: number) => {
const rows = sheets[i]?.rows ?? [];
const h = headerRow(rows);
setSheetIdx(i);
setHeaderAt(h);
setColumns(guessColumns(rows[h] ?? []));
const cols = guessColumns(rows[h] ?? []);
setColumns(cols);
// a 조회수 column: this is an 이지선다 file
if (!fixedKind) setChosenKind(cols.includes('views') ? 'duel' : 'normal');
};
const open = async (f: File) => {
if (f.size > MAX_BYTES) return toast('파일이 너무 커요(20MB까지).', 'error');
@@ -91,8 +104,9 @@ export function QuizFileImport({
const sheet = file?.sheets[sheetIdx];
const header = sheet?.rows[headerAt] ?? [];
const parsed = useMemo(() => (sheet ? parseQuizRows(sheet.rows, columns, headerAt) : null), [sheet, columns, headerAt]);
const missing = (['link', 'answer'] as const).filter((c) => !columns.includes(c));
const parsed = useMemo(() => (sheet ? parseQuizRows(sheet.rows, columns, headerAt, kind) : null), [sheet, columns, headerAt, kind]);
const missing = (kind === 'duel' ? (['link', 'answer', 'views'] as const) : (['link', 'answer'] as const)).filter((c) => !columns.includes(c));
const duel = kind === 'duel';
const bad = parsed?.rows.filter((r) => r.problem) ?? [];
const items = parsed?.items ?? [];
const inList = new Set(existing.map((x) => x.videoId));
@@ -113,7 +127,7 @@ export function QuizFileImport({
if (!onCreate || !name.trim() || !items.length) return;
setBusy(true);
try {
await onCreate(name.trim(), items);
await onCreate(name.trim(), items, kind);
} finally {
setBusy(false);
}
@@ -122,11 +136,26 @@ export function QuizFileImport({
return (
<div className="card stack" style={{ gap: 12 }}>
<div className="row" style={{ justifyContent: 'space-between' }}>
<b>📄 {mode === 'create' ? '파일로 만들기' : '파일에서 가져오기'}</b>
<b>
📄 {mode === 'create' ? '파일로 만들기' : '파일에서 가져오기'}
{fixedKind === 'duel' && ' (이지선다)'}
</b>
<button type="button" className="btn btn-sm btn-ghost" onClick={onClose} aria-label="닫기">
✕
</button>
</div>
{!fixedKind && (
<Seg
label="퀴즈 종류"
value={chosenKind}
disabled={false}
onChange={setChosenKind}
options={[
{ v: 'normal', label: '🎧 일반 퀴즈 (듣고맞추기)' },
{ v: 'duel', label: '🆚 이지선다 (조회수 비교)' },
]}
/>
)}
<div className="row">
<label className="btn btn-primary">
{file ? '다른 파일 고르기' : '파일 고르기 (.xlsx, .csv)'}
@@ -142,12 +171,18 @@ export function QuizFileImport({
}}
/>
</label>
<button type="button" className="btn" onClick={downloadTemplate}>
<button type="button" className="btn" onClick={() => downloadTemplate(kind)}>
📥 빈 양식 받기
</button>
{file && <span className="muted small">{file.name}</span>}
</div>
{!file && (
{!file && duel && (
<p className="muted small" style={{ margin: 0 }}>
한 줄에 한 곡씩, 첫 줄은 열 이름이에요. <b>유튜브 영상 링크</b>, <b>제목</b>, <b>조회수</b>는 꼭 있어야 하고 <b>가수</b>는 카드에 같이 보여요. 조회수는 1234567, 1,234,567,
123만, 1.2억처럼 써도 돼요. 게임에서는 곡을 무작위로 두 개씩 짝지어 A/B 카드로 보여 줘요.
</p>
)}
{!file && !duel && (
<p className="muted small" style={{ margin: 0 }}>
한 줄에 한 곡씩, 첫 줄은 열 이름이에요. <b>유튜브 영상 링크</b>와 <b>정답</b>(예: 게임 제목)은 꼭 있어야 하고, <b>설명</b>(예: 노래 제목)은 정답을 공개할 때 같이
보여요. <b>힌트</b> 열은 문제마다 먼저 나오고, 그다음 힌트로 초성이 나와요. <b>순번</b> 열이 있으면 그 순서대로 넣어요. 적힌 값은 고치지 않고 그대로 써요.
@@ -177,16 +212,17 @@ export function QuizFileImport({
</span>
<select className="input sm" value={columns[i] ?? ''} onChange={(e) => setColumn(i, (e.target.value || null) as QuizColumn | null)} aria-label={`${header[i] || `${i + 1}번째 열`} 쓰임`}>
<option value="">안 씀</option>
{COLUMN_ORDER.map((c) => (
{QUIZ_FILE_COLUMNS[kind].map((c) => (
<option key={c} value={c}>
{QUIZ_COLUMN_LABEL[c]}
{colLabel(c, kind)}
</option>
))}
{columns[i] && !QUIZ_FILE_COLUMNS[kind].includes(columns[i]!) && <option value={columns[i]!}>{colLabel(columns[i]!, kind)} (이 종류에서는 안 씀)</option>}
</select>
</label>
))}
</div>
{missing.length > 0 && <span className="warn-text small">{missing.map((c) => QUIZ_COLUMN_LABEL[c]).join(', ')} 열을 골라 주세요.</span>}
{missing.length > 0 && <span className="warn-text small">{missing.map((c) => colLabel(c, kind)).join(', ')} 열을 골라 주세요.</span>}
</div>
{!missing.length && parsed && (
<>
@@ -227,9 +263,9 @@ export function QuizFileImport({
<thead>
<tr>
<th style={{ width: 44 }}>#</th>
<th>정답</th>
<th>설명</th>
<th>힌트</th>
<th>{duel ? '제목' : '정답'}</th>
<th>{duel ? '가수' : '설명'}</th>
<th>{duel ? '조회수' : '힌트'}</th>
<th>영상</th>
</tr>
</thead>
@@ -242,7 +278,13 @@ export function QuizFileImport({
{it.titleAnswers.length > 0 && <div className="muted small">또는 {it.titleAnswers.join(', ')}</div>}
</td>
<td className="small">{it.artist || <span className="muted">-</span>}</td>
<td className="small">{[...it.hints, '초성'].join(' → ')}</td>
{duel ? (
<td className="small mono" title={`${it.views?.toLocaleString('ko-KR')}회`}>
{viewsLabel(it.views ?? 0)}회
</td>
) : (
<td className="small">{[...it.hints, '초성'].join(' → ')}</td>
)}
<td className="small">
<a href={`https://youtu.be/${it.videoId}`} target="_blank" rel="noreferrer">
{it.videoId} ↗
@@ -266,8 +308,8 @@ export function QuizFileImport({
퀴즈 이름
<input className="input grow" value={name} maxLength={60} onChange={(e) => setName(e.target.value)} aria-label="퀴즈 이름" />
</label>
<button className="btn btn-primary" disabled={busy || !name.trim() || !items.length}>
{busy ? '만드는 중…' : `${items.length}곡으로 만들기`}
<button className="btn btn-primary" disabled={busy || !name.trim() || items.length < (duel ? 2 : 1)}>
{busy ? '만드는 중…' : `${items.length}곡으로 ${duel ? '이지선다 ' : ''}만들기`}
</button>
</form>
) : (

View File

@@ -7,11 +7,16 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
import {
DEFAULT_QUIZ_SETTINGS,
DUEL_FLOWS,
DUEL_SECS,
LISTEN_SECS,
QUIZ_VISIBILITIES,
listenLabel,
parseViews,
viewsLabel,
type QuizDetail,
type QuizItem,
type QuizKind,
type QuizSettings,
type QuizSummary,
type QuizVisibility,
@@ -64,15 +69,18 @@ export function QuizzesPage() {
</label>
)}
</div>
<p className="muted">직접 만든 퀴즈예요. 방 설정에서 "제작된 퀴즈"를 고르면 이 퀴즈의 곡이 순서대로(또는 섞어서) 전부 나와요. 듣고맞추기에서만 쓸 수 있어요.</p>
<p className="muted">
직접 만든 퀴즈예요. 일반 퀴즈는 방 설정에서 "제작된 퀴즈"를 고르면 곡이 순서대로(또는 섞어서) 전부 나오고, 듣고맞추기에서만 쓸 수 있어요. 🆚 이지선다 퀴즈는 조회수가 든 파일로 만들고, 이지선다
모드에서만 쓸 수 있어요.
</p>
{fromFile && (
<QuizFileImport
mode="create"
onClose={() => setFromFile(false)}
onCreate={async (quizName, items) => {
onCreate={async (quizName, items, kind) => {
try {
const r = await apiCall<{ id: number }>('POST', '/api/admin/quizzes/file', { name: quizName, items });
toast(`"${quizName}" 퀴즈를 ${items.length}곡으로 만들었어요.`);
const r = await apiCall<{ id: number }>('POST', '/api/admin/quizzes/file', { name: quizName, items, kind });
toast(`"${quizName}" ${kind === 'duel' ? '이지선다 ' : ''}퀴즈를 ${items.length}곡으로 만들었어요.`);
nav(`/admin/quizzes/${r.id}`);
} catch (e) {
toast((e as Error).message, 'error');
@@ -86,6 +94,7 @@ export function QuizzesPage() {
<b className="nm">{q.name}</b>
{q.description && <span className="muted small clamp2">{q.description}</span>}
<span className="row small" style={{ gap: 6 }}>
{q.kind === 'duel' && <span className="badge teal">🆚 이지선다</span>}
<span className={`badge ${VIS_CLASS[q.visibility]}`}>{VIS_LABEL[q.visibility]}</span>
<span className="muted">
{q.songs}곡 · 플레이 {q.plays}번{all ? ` · ${q.ownerName}` : ''}
@@ -123,7 +132,7 @@ export function QuizzesPage() {
{!fromFile && (
<button type="button" className="quiz-card add plus" onClick={() => setFromFile(true)}>
<span aria-hidden>📄</span> 파일로 만들기
<small className="muted">엑셀(.xlsx)·CSV</small>
<small className="muted">엑셀(.xlsx)·CSV · 일반 / 이지선다</small>
</button>
)}
</div>
@@ -150,8 +159,8 @@ export interface DbInfo {
}
/** A song picked in the editor (search, address, playlist): answers, hints and positions start empty. */
type NewSong = Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'hints' | 'fromFile' | 'auto' | 'startSec' | 'highlightSec'>;
const fresh = (it: NewSong): QuizItem => ({ ...it, titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, auto: true, startSec: null, highlightSec: null });
type NewSong = Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'hints' | 'fromFile' | 'auto' | 'startSec' | 'highlightSec' | 'views'>;
const fresh = (it: NewSong): QuizItem => ({ ...it, titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, auto: true, startSec: null, highlightSec: null, views: null });
let keySeq = 0;
const newKey = () => `k${++keySeq}`;
@@ -176,7 +185,7 @@ export function QuizEditor() {
const [busy, setBusy] = useState(false);
const [leaveTo, setLeaveTo] = useState<string | null>(null);
const [confirmDelete, setConfirmDelete] = useState(false);
const [owner, setOwner] = useState<{ ownerName: string; plays: number } | null>(null);
const [owner, setOwner] = useState<{ ownerName: string; plays: number; kind: QuizKind } | null>(null);
const [importOpen, setImportOpen] = useState(false);
const [fileOpen, setFileOpen] = useState(false);
@@ -187,7 +196,7 @@ export function QuizEditor() {
setDraft(d);
setSaved(JSON.stringify(payload(d)));
setDb(r.db);
setOwner({ ownerName: r.quiz.ownerName, plays: r.quiz.plays });
setOwner({ ownerName: r.quiz.ownerName, plays: r.quiz.plays, kind: r.quiz.kind });
})
.catch((e: Error) => toast(e.message, 'error'));
}, [id]);
@@ -292,6 +301,7 @@ export function QuizEditor() {
if (!draft) return <p className="muted">불러오는 중…</p>;
const set = (p: Partial<Draft>) => setDraft({ ...draft, ...p });
const kind: QuizKind = owner?.kind ?? 'normal';
const isNew = params.get('new') === '1' && draft.items.length === 0;
return (
@@ -302,7 +312,7 @@ export function QuizEditor() {
</Link>
<h1 className="grow">{draft.name || '이름 없는 퀴즈'}</h1>
{dirty ? <span className="badge warn" role="status">● 저장하지 않은 변경이 있어요</span> : <span className="muted small">저장됨</span>}
<button type="button" className="btn" disabled={!draft.items.length} onClick={() => exportQuiz(draft.name, draft.items)} title="곡 목록을 다시 올릴 수 있는 엑셀 파일로 받아요">
<button type="button" className="btn" disabled={!draft.items.length} onClick={() => exportQuiz(draft.name, draft.items, kind)} title="곡 목록을 다시 올릴 수 있는 엑셀 파일로 받아요">
📥 엑셀로 내보내기
</button>
<button type="button" className="btn btn-primary" disabled={busy || !dirty} onClick={() => void save()} title="Ctrl+S">
@@ -311,7 +321,8 @@ export function QuizEditor() {
</div>
{owner && (
<p className="muted small" style={{ marginTop: -8 }}>
만든 사람 {owner.ownerName} · {draft.items.length}곡 · 플레이 {owner.plays}번 · <span className={`badge ${VIS_CLASS[draft.visibility]}`}>{VIS_LABEL[draft.visibility]}</span>
{kind === 'duel' && <span className="badge teal">🆚 이지선다</span>} 만든 사람 {owner.ownerName} · {draft.items.length}곡 · 플레이 {owner.plays}번 ·{' '}
<span className={`badge ${VIS_CLASS[draft.visibility]}`}>{VIS_LABEL[draft.visibility]}</span>
</p>
)}
<div className="seg" role="tablist" style={{ maxWidth: 360 }}>
@@ -340,6 +351,7 @@ export function QuizEditor() {
)}
{tab === 'songs' ? (
<SongsTab
kind={kind}
items={draft.items}
db={db}
settings={draft.settings}
@@ -351,7 +363,7 @@ export function QuizEditor() {
onHints={() => draft.settings.hint === 'none' && set({ settings: { ...draft.settings, hint: 'manual' } })}
/>
) : (
<SettingsTab draft={draft} onChange={set} onDelete={() => setConfirmDelete(true)} />
<SettingsTab kind={kind} draft={draft} onChange={set} onDelete={() => setConfirmDelete(true)} />
)}
{leaveTo && (
<Sheet label="저장하지 않은 변경" onClose={() => setLeaveTo(null)}>
@@ -444,6 +456,7 @@ interface VideoInfo {
const looksLikeUrl = (s: string) => /^(https?:\/\/|www\.|youtu\.?be|m\.youtube|music\.youtube)/i.test(s.trim()) || /^[\w-]{11}$/.test(s.trim());
function SongsTab({
kind,
items,
db,
settings,
@@ -454,6 +467,7 @@ function SongsTab({
setFileOpen,
onHints,
}: {
kind: QuizKind;
items: DraftItem[];
db: Record<number, DbInfo | null>;
settings: QuizSettings;
@@ -469,6 +483,7 @@ function SongsTab({
const [dragKey, setDragKey] = useState<string | null>(null);
const [overKey, setOverKey] = useState<string | null>(null);
const selected = items.find((i) => i.key === sel) ?? null;
const duel = kind === 'duel';
const add = (it: NewSong) => {
if (items.some((x) => x.videoId === it.videoId || (it.songId && x.songId === it.songId))) {
toast('이미 목록에 있는 곡이에요.', 'error');
@@ -497,6 +512,7 @@ function SongsTab({
{fileOpen ? (
<QuizFileImport
mode="into"
kind={kind}
existing={items}
onClose={() => setFileOpen(false)}
onApply={(rows, replace) => {
@@ -535,13 +551,18 @@ function SongsTab({
<p className="muted">아직 곡이 없어요. 위에서 제목·가수로 찾거나 유튜브 주소를 붙여 넣어 추가해 주세요.</p>
) : (
<div className="table-wrap">
{duel && items.some((i) => i.views === null) && (
<p className="warn-text small" style={{ margin: '8px 10px' }}>
조회수가 없는 곡 {items.filter((i) => i.views === null).length}곡은 게임에 나오지 않아요. 곡을 눌러 조회수를 넣어 주세요.
</p>
)}
<table className="data-table quiz-songs">
<thead>
<tr>
<th style={{ width: 28 }} aria-label="순서 옮기기" />
<th style={{ width: 44 }}>번호</th>
<th>노래</th>
<th>추가 정답</th>
<th>{duel ? '조회수' : '추가 정답'}</th>
<th>길이</th>
<th>재생 위치</th>
<th style={{ width: 120 }} />
@@ -585,7 +606,13 @@ function SongsTab({
</div>
{it.hints.length > 0 && <div className="muted small">힌트: {it.hints.join(' → ')}</div>}
</td>
<td className="small">{[...it.titleAnswers, ...it.artistAnswers].join(', ') || <span className="muted">-</span>}</td>
{duel ? (
<td className="mono small" title={it.views !== null ? `${it.views.toLocaleString('ko-KR')}회` : undefined}>
{it.views !== null ? `${viewsLabel(it.views)}회` : <span className="warn-text">없음</span>}
</td>
) : (
<td className="small">{[...it.titleAnswers, ...it.artistAnswers].join(', ') || <span className="muted">-</span>}</td>
)}
<td className="mono small">{mmss(it.durationSec ?? (it.songId ? db[it.songId]?.durationSec : null))}</td>
<td className="small">{it.auto ? <span className="muted">자동</span> : `처음 ${mmss(it.startSec ?? 0)} · 하이라이트 ${mmss(it.highlightSec)}`}</td>
<td onClick={(e) => e.stopPropagation()}>
@@ -611,6 +638,7 @@ function SongsTab({
{selected && (
<ItemPanel
key={selected.key}
duel={duel}
item={selected}
index={items.indexOf(selected)}
total={items.length}
@@ -1011,6 +1039,7 @@ function ChipsInput({ values, onChange, label, placeholder }: { values: string[]
}
function ItemPanel({
duel,
item,
index,
total,
@@ -1022,6 +1051,7 @@ function ItemPanel({
onClose,
isDuplicate,
}: {
duel: boolean;
item: DraftItem;
index: number;
total: number;
@@ -1037,6 +1067,8 @@ function ItemPanel({
const [url, setUrl] = useState('');
const [pos, setPos] = useState(String(index + 1));
useEffect(() => setPos(String(index + 1)), [index]);
const [viewsText, setViewsText] = useState(item.views === null ? '' : String(item.views));
const viewsBad = parseViews(viewsText) === undefined;
const changeVideo = async () => {
try {
const v = await apiCall<VideoInfo>('POST', '/api/admin/quizzes/pick/video', { url: url.trim() });
@@ -1068,13 +1100,32 @@ function ItemPanel({
onChange={onPatch}
/>
<label className="field">
제목 (정답)
{duel ? '제목 (카드에 보여요)' : '제목 (정답)'}
<input className="input" value={item.title} maxLength={200} onChange={(e) => onPatch({ title: e.target.value })} />
</label>
<label className="field">
{item.fromFile ? '설명 (정답과 같이 공개돼요)' : '가수'}
{duel ? '가수' : item.fromFile ? '설명 (정답과 같이 공개돼요)' : '가수'}
<input className="input" value={item.artist} maxLength={200} onChange={(e) => onPatch({ artist: e.target.value })} />
</label>
{duel && (
<label className="field">
조회수 (예: 1234567, 123만, 1.2억)
<input
className="input"
value={viewsText}
inputMode="numeric"
onChange={(e) => {
setViewsText(e.target.value);
const v = parseViews(e.target.value);
if (v !== undefined) onPatch({ views: v });
}}
aria-invalid={viewsBad}
/>
{viewsBad ? <span className="field-error small">조회수를 읽을 수 없어요.</span> : item.views !== null && <span className="muted small">{item.views.toLocaleString('ko-KR')}회</span>}
</label>
)}
{!duel && (
<>
<div className="field">
힌트 (적은 순서대로 하나씩 나오고, 마지막에 초성 힌트가 나와요)
<ChipsInput values={item.hints} onChange={(hints) => onPatch({ hints: hints.slice(0, 5) })} label="힌트" placeholder="힌트 입력 후 Enter (예: 액션 RPG)" />
@@ -1087,6 +1138,8 @@ function ItemPanel({
가수 추가 정답
<ChipsInput values={item.artistAnswers} onChange={(artistAnswers) => onPatch({ artistAnswers })} label="가수 추가 정답" placeholder="다른 표기 입력 후 Enter (예: IU)" />
</div>
</>
)}
{item.fromFile ? (
<p className="muted small">파일에서 넣은 곡이에요. 적힌 값 그대로 쓰고, 서버 노래 DB 검토에는 올라가지 않아요.</p>
) : item.songId ? (
@@ -1144,7 +1197,8 @@ function ItemPanel({
}
// ------------------------------------------------------------------ 설정
function SettingsTab({ draft, onChange, onDelete }: { draft: Draft; onChange: (p: Partial<Draft>) => void; onDelete: () => void }) {
function SettingsTab({ kind, draft, onChange, onDelete }: { kind: QuizKind; draft: Draft; onChange: (p: Partial<Draft>) => void; onDelete: () => void }) {
const duel = kind === 'duel';
const s = draft.settings;
const setS = (p: Partial<QuizSettings>) => onChange({ settings: { ...s, ...p } });
const vis = useMemo(() => QUIZ_VISIBILITIES.find((v) => v.id === draft.visibility)!, [draft.visibility]);
@@ -1169,6 +1223,16 @@ function SettingsTab({ draft, onChange, onDelete }: { draft: Draft; onChange: (p
{vis.help}
</p>
</Section>
{duel ? (
<>
<Section title="제한 시간" tip="카드를 고를 수 있는 시간. 그 안에는 몇 번이든 바꿀 수 있어요">
<Seg label="제한 시간" value={s.duelSec} disabled={false} onChange={(duelSec) => setS({ duelSec })} options={DUEL_SECS.map((v) => ({ v, label: `${v}초` }))} />
</Section>
<Section title="진행 방식" tip="곡은 늘 무작위로 짝지어요">
<Seg label="진행 방식" value={s.duelFlow} disabled={false} onChange={(duelFlow) => setS({ duelFlow })} options={DUEL_FLOWS.map((f) => ({ v: f.id, label: f.label }))} />
</Section>
</>
) : (
<Section title="문제 순서" tip="문제 수는 퀴즈에 든 곡 전부예요">
<Seg
label="문제 순서"
@@ -1181,6 +1245,7 @@ function SettingsTab({ draft, onChange, onDelete }: { draft: Draft; onChange: (p
]}
/>
</Section>
)}
<Section title="재생위치 기본" tip="곡마다 정한 '처음' 위치 또는 '하이라이트' 위치에서 틀어요">
<Seg
label="재생위치 기본"
@@ -1193,10 +1258,12 @@ function SettingsTab({ draft, onChange, onDelete }: { draft: Draft; onChange: (p
]}
/>
</Section>
<Section title="듣고맞출시간">
<Seg label="듣고맞출시간" value={s.listenSec} disabled={false} onChange={(listenSec) => setS({ listenSec })} options={LISTEN_SECS.map((v) => ({ v, label: listenLabel(v) }))} />
</Section>
<PlayRules c={s} ro={false} listening onPatch={(p) => setS(p as Partial<QuizSettings>)} />
{!duel && (
<Section title="듣고맞출시간">
<Seg label="듣고맞출시간" value={s.listenSec} disabled={false} onChange={(listenSec) => setS({ listenSec })} options={LISTEN_SECS.map((v) => ({ v, label: listenLabel(v) }))} />
</Section>
)}
<PlayRules c={s} ro={false} listening duel={duel} onPatch={(p) => setS(p as Partial<QuizSettings>)} />
<section className="sec">
<button type="button" className="btn btn-danger btn-sm" onClick={onDelete}>
퀴즈 지우기

View File

@@ -473,6 +473,33 @@ input.input.sm { width: 76px; }
.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; }
/* 이지선다: two cards A / B, avatars of who picked each */
.duel-stage { flex-direction: column; align-items: stretch; gap: 14px; padding: 16px 20px; }
.duel-head .big { font-size: 1.45rem; font-weight: 850; letter-spacing: -0.03em; margin-bottom: 8px; }
.duel-head .bar { margin-bottom: 6px; }
.duel-cards { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.duel-card { position: relative; display: flex; flex-direction: column; align-items: flex-start; gap: 4px; padding: 12px; text-align: left; font: inherit; color: var(--text); background: var(--surface); border: 2px solid var(--ink); border-radius: var(--radius); box-shadow: 4px 4px 0 var(--ink); cursor: pointer; min-width: 0; transition: transform 0.1s, box-shadow 0.1s; }
.duel-card:hover { background: color-mix(in srgb, var(--primary-soft) 45%, var(--surface)); }
.duel-card:active { transform: translate(2px, 2px); box-shadow: 2px 2px 0 var(--ink); }
.duel-card.mine { background: var(--primary-soft); border-color: var(--primary); box-shadow: 4px 4px 0 var(--primary); }
.duel-card.playing .duel-thumb { outline: 4px solid var(--mustard); }
.duel-card.won { border-color: var(--correct); box-shadow: 4px 4px 0 var(--correct); background: var(--correct-soft); }
.duel-card.lost { background: var(--surface-2); box-shadow: 2px 2px 0 var(--ink); }
.duel-side { position: absolute; top: -12px; left: -10px; width: 34px; height: 34px; border-radius: 50%; background: var(--mustard); color: #1e1b18; border: 2px solid var(--ink); display: flex; align-items: center; justify-content: center; font-weight: 900; font-size: 1.05rem; z-index: 1; }
.duel-thumb { width: 100%; aspect-ratio: 16 / 9; object-fit: cover; border-radius: 10px; border: 1.5px solid var(--line); background: var(--surface-2); margin-bottom: 4px; }
.duel-title { font-weight: 850; font-size: 1.12rem; letter-spacing: -0.02em; line-height: 1.3; overflow-wrap: anywhere; }
.duel-artist { font-size: 0.9rem; font-weight: 650; }
.duel-views { margin-top: 2px; font-weight: 850; font-size: 1.05rem; color: var(--primary); }
.duel-card.won .duel-views { color: var(--correct); }
.duel-state { color: var(--text-sub); font-weight: 700; }
.duel-picks { display: flex; flex-wrap: wrap; gap: 4px; min-height: 26px; margin-top: 4px; }
.duel-pick { display: inline-flex; align-items: center; gap: 2px; }
.gain { font-weight: 900; font-size: 0.82rem; color: var(--correct); }
.gain.rev { color: #9a4510; }
:root[data-theme='dark'] .gain.rev { color: var(--mustard); }
@media (prefers-color-scheme: dark) { :root[data-theme='auto'] .gain.rev { color: var(--mustard); } }
.sb .gain { margin-left: 4px; }
@media (max-width: 1100px) {
.ggrid { grid-template-columns: minmax(0, 1fr); }
.ggrid .side { max-height: none; }
@@ -491,6 +518,10 @@ input.input.sm { width: 76px; }
.sinfo .big { font-size: 1.2rem; margin: 2px 0 6px; }
.countdown { font-size: 2.2rem; }
.chat.big .chat-log { max-height: 46vh; }
.duel-cards { gap: 10px; }
.duel-card { padding: 8px; }
.duel-title { font-size: 0.98rem; }
.duel-head .big { font-size: 1.1rem; }
}
/* ---------------------------------------------------------------- responsive */