이지선다 모드: 조회수가 더 높은 곡 고르기. 이지선다 퀴즈는 조회수가 든 파일로 만들고(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

@@ -4,7 +4,12 @@ import { DEFAULT_QUIZ_SETTINGS, QUIZ_ROOM_KEYS, type QuizSettings } from './cust
const roomPart = RoomConfigSchema.pick(Object.fromEntries(QUIZ_ROOM_KEYS.map((k) => [k, true])) as { [K in (typeof QUIZ_ROOM_KEYS)[number]]: true });
export const QuizSettingsSchema = roomPart.extend({ order: z.enum(['ordered', 'random']) });
export const QuizSettingsSchema = roomPart.extend({
order: z.enum(['ordered', 'random']),
// added with 이지선다: settings saved before have none
duelSec: RoomConfigSchema.shape.duelSec.default(DEFAULT_QUIZ_SETTINGS.duelSec),
duelFlow: RoomConfigSchema.shape.duelFlow.default(DEFAULT_QUIZ_SETTINGS.duelFlow),
});
const answers = z.array(z.string().trim().min(1).max(200)).max(30);
const sec = z.number().min(0).max(36000).nullable();
@@ -24,6 +29,7 @@ export const QuizItemSchema = z.object({
auto: z.boolean(),
startSec: sec,
highlightSec: sec,
views: z.number().int().min(0).max(1e15).nullable().default(null),
}).refine((it) => it.fromFile || it.artist.length > 0, { path: ['artist'], message: '가수를 넣어 주세요.' });
export const QuizSaveSchema = z.object({

View File

@@ -12,8 +12,11 @@ export const QUIZ_VISIBILITIES = [
] as const;
export type QuizVisibility = (typeof QUIZ_VISIBILITIES)[number]['id'];
/** 일반 퀴즈 (듣고맞추기) or 이지선다 퀴즈 (조회수가 더 높은 곡 고르기): each is played only in its own mode. */
export type QuizKind = 'normal' | 'duel';
/** Room settings a quiz carries as its defaults (the host may still change them in the room). */
export const QUIZ_ROOM_KEYS = ['listenSec', 'startAt', 'answer', 'strict', 'hint', 'hintVotes', 'skipVotes', 'replayVotes', 'revealSec', 'nextVotes'] as const;
export const QUIZ_ROOM_KEYS = ['listenSec', 'startAt', 'answer', 'strict', 'hint', 'hintVotes', 'skipVotes', 'replayVotes', 'revealSec', 'nextVotes', 'duelSec', 'duelFlow'] as const;
export type QuizRoomDefaults = Pick<RoomConfig, (typeof QUIZ_ROOM_KEYS)[number]>;
export interface QuizSettings extends QuizRoomDefaults {
@@ -46,10 +49,13 @@ export interface QuizItem {
auto: boolean;
startSec: number | null;
highlightSec: number | null;
/** 이지선다 퀴즈: the video's view count as written in the file (null = not given; such songs are left out of games). */
views: number | null;
}
export interface QuizSummary {
id: number;
kind: QuizKind;
name: string;
description: string;
visibility: QuizVisibility;

View File

@@ -2,7 +2,7 @@
export * from './nickname';
export * from './types';
export * from './room-config';
export type { ChatLine, RoomView, RoomPlayerView, ServerMessage, GameView, GameScore, GameHistoryItem, GamePhase } from './protocol';
export type { ChatLine, RoomView, RoomPlayerView, ServerMessage, GameView, GameScore, GameHistoryItem, GamePhase, DuelCard, DuelResult, DuelSide, DuelView } from './protocol';
export * from './custom-quiz';
export * from './quiz-file';
export * from './sheet';

View File

@@ -31,6 +31,8 @@ export const ClientMessage = z.discriminatedUnion('t', [
/** Vote toggles (docs/05 스킵·힌트, docs/12 Q3·Q4). */
z.object({ t: z.literal('vote'), kind: z.enum(['skip', 'hint', 'replay', 'next']) }),
z.object({ t: z.literal('typing'), on: z.boolean() }),
/** 이지선다: pick card A or B (again until the time is up; the same card again keeps it). */
z.object({ t: z.literal('pick'), n: z.number().int().min(1), side: z.enum(['a', 'b']) }),
/** Host game controls: pause/resume, end now, 이어풀기, 다시 하기 (back to the waiting room). */
z.object({ t: z.literal('game'), action: z.enum(['pause', 'resume', 'end', 'continue', 'again']) }),
/** Host: leave this player out of this question only (not ready for 30s, docs/12 Q1). */
@@ -88,6 +90,36 @@ export interface GameScore {
/** Average answer time of the questions this player got (tie-break, docs/05 점수). */
avgMs: number | null;
online: boolean;
/** 이지선다: 역배 wins (alone on the right card against 2 or more). */
reverse?: number;
}
export type DuelSide = 'a' | 'b';
/** One card of an 이지선다 question. `views` is hidden until the reveal (연속 방식: the song that stayed shows its own). */
export interface DuelCard {
side: DuelSide;
videoId: string;
title: string;
artist: string;
/** Where this song starts playing (재생위치) and its volume factor (소리 크기 맞추기). */
startSec: number;
gain: number;
views: number | null;
/** Who is on this card right now. */
picks: string[];
}
/** What the reveal of an 이지선다 question shows: the higher card (both when equal) and the points everyone got. */
export interface DuelResult {
winner: DuelSide | 'both';
gains: { id: string; points: number; reverse: boolean }[];
}
export interface DuelView {
flow: import('./room-config').DuelFlow;
cards: DuelCard[];
result: DuelResult | null;
}
export interface GameHistoryItem {
@@ -102,6 +134,12 @@ export interface GameHistoryItem {
winner: string | null;
ms: number | null;
how: 'correct' | 'skip' | 'timeout' | 'end';
/** 이지선다: both songs with their views, the higher one and who got points. */
duel?: {
cards: { side: DuelSide; title: string; artist: string; videoId: string; views: number }[];
winner: DuelSide | 'both';
gains: { id: string; nickname: string; points: number; reverse: boolean }[];
};
}
/** Game state for everyone (docs/05). Never has the video id or the answer of the running question. */
@@ -143,6 +181,8 @@ export interface GameView {
revealUntil: number | null;
/** 이어풀기 possible: songs left that this quiz has not played. */
left: number;
/** 이지선다 only: the two cards of this question. */
duel?: DuelView;
}
export type ServerMessage =

View File

@@ -2,7 +2,7 @@
import { expect, test } from 'bun:test';
import { decodeCsv, parseCsv, readSheetFile, readXlsx, writeXlsx } from './sheet';
import { deflatedZip } from './zip-fixture';
import { guessColumns, headerRow, parseQuizRows, parseSec, parseVideoId, quizTemplateRows, quizToRows } from './quiz-file';
import { guessColumns, headerRow, parseQuizRows, parseSec, parseVideoId, parseViews, quizTemplateRows, quizToRows } from './quiz-file';
test('reads an Excel-style workbook: shared strings, rich text, numbers, gaps, sheet order and names', async () => {
const x = deflatedZip({
@@ -74,8 +74,8 @@ test('rows → quiz songs: as written, 순번 order, bad links / no answer / rep
test('our export reads back to the same songs (answers, own positions, several hints) and the template is valid', () => {
const items = [
{ songId: null, videoId: 'iIIjS6yDMQo', title: '감옥탈출', artist: '트레일러', titleAnswers: ['구토할배'], artistAnswers: ['trailer'], hints: ['방탈출', '플래시'], fromFile: true, durationSec: null, auto: false, startSec: 12, highlightSec: 61.5 },
{ songId: 3, videoId: 'x0-xFqvJ-U8', title: '갓 오브 워 2', artist: '', titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, durationSec: 200, auto: true, startSec: null, highlightSec: null },
{ songId: null, videoId: 'iIIjS6yDMQo', title: '감옥탈출', artist: '트레일러', titleAnswers: ['구토할배'], artistAnswers: ['trailer'], hints: ['방탈출', '플래시'], fromFile: true, durationSec: null, auto: false, startSec: 12, highlightSec: 61.5, views: null },
{ songId: 3, videoId: 'x0-xFqvJ-U8', title: '갓 오브 워 2', artist: '', titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, durationSec: 200, auto: true, startSec: null, highlightSec: null, views: null },
];
const { rows } = quizToRows(items);
const text = rows.map((r) => r.map((c) => (c === null ? '' : String(c))));
@@ -96,3 +96,43 @@ test('video links and times', () => {
expect(parseVideoId('https://example.com/watch?v=VO88htcm09E')).toBeNull();
expect([parseSec('95'), parseSec('1:35'), parseSec('01:01:01'), parseSec('1분 5초'), parseSec(''), parseSec('조금')]).toEqual([95, 95, 3661, 65, null, undefined]);
});
test('조회수 as people write it', () => {
expect(parseViews('1234567')).toBe(1234567);
expect(parseViews('1,234,567')).toBe(1234567);
expect(parseViews('1,234,567회')).toBe(1234567);
expect(parseViews('123만')).toBe(1230000);
expect(parseViews('1.2억')).toBe(120000000);
expect(parseViews('1억 2,345만')).toBe(123450000);
expect(parseViews('3.4M')).toBe(3400000);
expect(parseViews('12K views')).toBe(12000);
expect(parseViews('1.2345E+9')).toBe(1234500000);
expect(parseViews('')).toBeNull();
expect(parseViews('많음')).toBeUndefined();
});
test('이지선다 파일: 제목·가수·조회수, rows without views are left out, export and template read back', () => {
const rows = [
['순번', '유튜브 링크', '제목', '가수', '조회수'],
['2', 'https://youtu.be/iIIjS6yDMQo', '감옥탈출', '트레일러', '1.2억'],
['1', 'x0-xFqvJ-U8', '갓 오브 워', '', '3,456,789'],
['3', 'https://youtu.be/Es6JbQQE79g', '조회수 없음', '누구', ''],
['4', 'https://youtu.be/VO88htcm09E', '이상한 값', '누구', '많음'],
];
const cols = guessColumns(rows[0]!);
expect(cols).toEqual(['order', 'link', 'answer', 'desc', 'views']);
const p = parseQuizRows(rows, cols, 0, 'duel');
expect(p.items.map((i) => [i.title, i.artist, i.views])).toEqual([
['갓 오브 워', '', 3456789],
['감옥탈출', '트레일러', 120000000],
]);
expect(p.rows.filter((r) => r.problem).map((r) => [r.line, r.problem])).toEqual([
[4, '조회수가 비어 있어요'],
[5, '조회수를 읽을 수 없어요 (많음)'],
]);
const { rows: out } = quizToRows(p.items, 'duel');
const text = out.map((r) => r.map((c) => (c === null ? '' : String(c))));
expect(parseQuizRows(text, guessColumns(text[0]!), 0, 'duel').items).toEqual(p.items);
const t = quizTemplateRows('duel').rows.map((r) => r.map((c) => (c === null ? '' : String(c))));
expect(parseQuizRows(t, guessColumns(t[0]!), 0, 'duel').items).toHaveLength(1);
});

View File

@@ -3,9 +3,9 @@
* Values are used as written (no DB lookup): 정답 = the answer, 설명 = shown with it on the reveal, 힌트 columns in order
* before the 초성 hint.
*/
import type { QuizItem } from './custom-quiz';
import type { QuizItem, QuizKind } from './custom-quiz';
export type QuizColumn = 'link' | 'answer' | 'desc' | 'hint' | 'answers' | 'descAnswers' | 'order' | 'start' | 'highlight';
export type QuizColumn = 'link' | 'answer' | 'desc' | 'hint' | 'answers' | 'descAnswers' | 'order' | 'start' | 'highlight' | 'views';
export const QUIZ_COLUMN_LABEL: Record<QuizColumn, string> = {
link: '유튜브 영상 링크',
@@ -17,8 +17,33 @@ export const QUIZ_COLUMN_LABEL: Record<QuizColumn, string> = {
order: '순번',
start: '시작(초)',
highlight: '하이라이트(초)',
views: '조회수',
};
/** 이지선다 퀴즈 files call the same columns 제목 / 가수 (shown on the cards). */
export const DUEL_COLUMN_LABEL: Partial<Record<QuizColumn, string>> = { answer: '제목', desc: '가수' };
/** The columns each kind of quiz file uses, in the order the column pickers list them. */
export const QUIZ_FILE_COLUMNS: Record<QuizKind, QuizColumn[]> = {
normal: ['link', 'answer', 'desc', 'hint', 'answers', 'descAnswers', 'order', 'start', 'highlight'],
duel: ['link', 'answer', 'desc', 'views', 'order', 'start', 'highlight'],
};
/**
* 조회수 as people write it: 1234567 · 1,234,567 · 1234567회 · 123만 · 1.2억 · 1억 2,345만 · 3.4M · 12K (Excel's 1.2E+9 too).
* '' → null; anything else → undefined (invalid).
*/
export function parseViews(s: string): number | null | undefined {
const t = s.trim().replace(/[,\s]/g, '').replace(/(회|views?|조회수?)$/i, '');
if (!t) return null;
if (/^\d+(\.\d+)?(e\+?\d+)?$/i.test(t)) return Math.round(Number(t));
const en = /^(\d+(?:\.\d+)?)([kmb])$/i.exec(t);
if (en) return Math.round(Number(en[1]) * { k: 1e3, m: 1e6, b: 1e9 }[en[2]!.toLowerCase() as 'k' | 'm' | 'b']);
const ko = /^(?:(\d+(?:\.\d+)?)억)?(?:(\d+(?:\.\d+)?)만)?(?:(\d+(?:\.\d+)?)천)?(\d+)?$/.exec(t);
if (ko && (ko[1] || ko[2] || ko[3])) return Math.round(Number(ko[1] ?? 0) * 1e8 + Number(ko[2] ?? 0) * 1e4 + Number(ko[3] ?? 0) * 1e3 + Number(ko[4] ?? 0));
return undefined;
}
/** Accepts https://youtu.be/ID, youtube.com/watch?v=ID, /shorts/ID, /embed/ID, /live/ID, music.youtube.com or the bare ID. */
export function parseVideoId(s: string): string | null {
const t = s.trim();
@@ -43,6 +68,7 @@ export function guessColumns(header: string[]): (QuizColumn | null)[] {
const out: (QuizColumn | null)[] = header.map(() => null);
const taken = new Set<QuizColumn>();
const rules: [QuizColumn, RegExp][] = [
['views', /조회수|조회|재생수|views?|viewcount/],
['order', /순번|순서|^order$|^no\.?$/],
['link', /링크|주소|url|영상|유튜브|youtube|video|link/],
['descAnswers', /(설명|가수|노래|artist).*(다른|추가|복수)정답|(다른|추가|복수)정답.*(설명|가수|노래|artist)/],
@@ -107,8 +133,10 @@ export interface ParsedQuizFile {
/**
* Sheet rows (header at `headerAt`) → quiz songs. Empty rows are skipped silently; rows with a bad link, no answer or a
* video already used above are listed with the reason and left out. A 순번 column decides the order (rows without one last).
* 이지선다 (`kind` duel): 정답 = 제목, 설명 = 가수, and every song needs its 조회수.
*/
export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[], headerAt = 0): ParsedQuizFile {
export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[], headerAt = 0, kind: QuizKind = 'normal'): ParsedQuizFile {
const duel = kind === 'duel';
const at = (c: QuizColumn) => columns.indexOf(c);
const hintCols = columns.flatMap((c, i) => (c === 'hint' ? [i] : []));
const cell = (r: string[], i: number) => (i >= 0 ? (r[i] ?? '').trim() : '');
@@ -130,15 +158,22 @@ export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[],
const link = cell(r, at('link'));
const videoId = parseVideoId(link);
const title = cell(r, at('answer')).slice(0, 200);
const views = duel ? parseViews(cell(r, at('views'))) : null;
const problem = !link
? '링크가 비어 있어요'
: !videoId
? '유튜브 링크가 아니에요'
: !title
? '정답이 비어 있어요'
: seen.has(videoId)
? `${seen.get(videoId)}번째 줄과 같은 영상이에요`
: null;
? duel
? '제목이 비어 있어요'
: '정답이 비어 있어요'
: views === null && duel
? '조회수가 비어 있어요'
: views === undefined
? `조회수를 읽을 수 없어요 (${cell(r, at('views')).slice(0, 30)})`
: seen.has(videoId)
? `${seen.get(videoId)}번째 줄과 같은 영상이에요`
: null;
if (problem) {
out.push({ line, item: null, problem, link });
continue;
@@ -156,14 +191,15 @@ export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[],
videoId: videoId!,
title,
artist: cell(r, at('desc')).slice(0, 200),
titleAnswers: splitAnswers(cell(r, at('answers'))).filter((a) => a !== title),
artistAnswers: splitAnswers(cell(r, at('descAnswers'))),
hints: hintCols.map((i) => cell(r, i).slice(0, 200)).filter(Boolean).slice(0, 5),
titleAnswers: duel ? [] : splitAnswers(cell(r, at('answers'))).filter((a) => a !== title),
artistAnswers: duel ? [] : splitAnswers(cell(r, at('descAnswers'))),
hints: duel ? [] : hintCols.map((i) => cell(r, i).slice(0, 200)).filter(Boolean).slice(0, 5),
fromFile: true,
durationSec: null,
auto: !own,
startSec: own ? (start ?? 0) : null,
highlightSec: own ? (highlight ?? null) : null,
views: duel ? (views ?? null) : null,
},
});
}
@@ -171,7 +207,12 @@ export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[],
}
/** Quiz songs → sheet rows with the headers this file format reads back (내보내기, 빈 양식). */
export function quizToRows(items: QuizItem[]): { rows: (string | number | null)[][]; widths: number[] } {
export function quizToRows(items: QuizItem[], kind: QuizKind = 'normal'): { rows: (string | number | null)[][]; widths: number[] } {
if (kind === 'duel') {
const header = ['순번', QUIZ_COLUMN_LABEL.link, '제목', '가수', '조회수', '시작(초)', '하이라이트(초)'];
const rows = items.map((it, i) => [i + 1, `https://youtu.be/${it.videoId}`, it.title, it.artist, it.views, it.auto ? null : (it.startSec ?? 0), it.auto ? null : it.highlightSec]);
return { rows: [header, ...rows], widths: [6, 32, 30, 24, 16, 10, 14] };
}
const hintN = Math.max(1, ...items.map((i) => i.hints.length));
const hintHeads = hintN === 1 ? ['힌트'] : Array.from({ length: hintN }, (_, i) => `힌트${i + 1}`);
const header = ['순번', QUIZ_COLUMN_LABEL.link, '정답', '설명', ...hintHeads, '다른 정답(;로 구분)', '설명 다른 정답(;로 구분)', '시작(초)', '하이라이트(초)'];
@@ -190,7 +231,14 @@ export function quizToRows(items: QuizItem[]): { rows: (string | number | null)[
}
/** 빈 양식: the headers and one example row. */
export function quizTemplateRows(): { rows: (string | number | null)[][]; widths: number[] } {
export function quizTemplateRows(kind: QuizKind = 'normal'): { rows: (string | number | null)[][]; widths: number[] } {
if (kind === 'duel')
return quizToRows(
[
{ songId: null, videoId: 'v7bnOxV4jAc', title: '라일락', artist: '아이유', titleAnswers: [], artistAnswers: [], hints: [], fromFile: true, durationSec: null, auto: true, startSec: null, highlightSec: null, views: 123456789 },
],
'duel',
);
return quizToRows([
{
songId: null,
@@ -205,6 +253,7 @@ export function quizTemplateRows(): { rows: (string | number | null)[][]; widths
auto: true,
startSec: null,
highlightSec: null,
views: null,
},
]);
}

View File

@@ -1,11 +1,11 @@
import { z } from 'zod';
import { COUNTS, DEFAULT_ROOM_CONFIG, HINT_TIMES, LISTEN_SECS, LYRICS_SECS, REVEAL_SECS, VOTE_RULES, type RoomConfig } from './room-config';
import { COUNTS, DEFAULT_ROOM_CONFIG, DUEL_SECS, HINT_TIMES, LISTEN_SECS, LYRICS_SECS, REVEAL_SECS, VOTE_RULES, type RoomConfig } from './room-config';
const lit = <T extends readonly (string | number)[]>(xs: T) => z.union(xs.map((x) => z.literal(x)) as unknown as [z.ZodLiteral<T[number]>, z.ZodLiteral<T[number]>]);
export const RoomConfigSchema = z.object({
title: z.string().trim().max(40),
mode: z.enum(['listen', 'artist', 'lyrics']),
mode: z.enum(['listen', 'artist', 'lyrics', 'duel']),
listenSec: lit(LISTEN_SECS),
startAt: z.enum(['start', 'highlight']),
artistIds: z.array(z.number().int().positive()).max(50),
@@ -24,6 +24,8 @@ export const RoomConfigSchema = z.object({
nextVotes: z.enum(VOTE_RULES),
count: lit(COUNTS),
visibility: z.enum(['public', 'private', 'password']),
duelSec: lit(DUEL_SECS),
duelFlow: z.enum(['pairs', 'chain']),
quizId: z.number().int().positive().nullable(),
quizName: z.string().max(60),
});
@@ -36,7 +38,7 @@ export function applyConfigPatch(cur: RoomConfig, patch: unknown): RoomConfig |
if (!r.success) return `설정 값이 올바르지 않아요: ${r.error.issues.map((i) => i.path.join('.')).join(', ')}`;
const c = r.data as RoomConfig;
if (c.yearFrom && c.yearTo && c.yearFrom > c.yearTo) return '시작 연도가 끝 연도보다 늦어요.';
if (c.quizId && c.mode !== 'listen') return '제작된 퀴즈는 듣고맞추기에서만 할 수 있어요.';
if (c.quizId && c.mode !== 'listen' && c.mode !== 'duel') return '제작된 퀴즈는 듣고맞추기나 이지선다에서만 할 수 있어요.';
return c;
}

View File

@@ -7,6 +7,7 @@ export const MODES = [
{ id: 'listen', label: '듣고맞추기', icon: '🎧' },
{ id: 'artist', label: '가수노래 맞추기', icon: '🎤' },
{ id: 'lyrics', label: '가사보고 맞추기', icon: '📜' },
{ id: 'duel', label: '이지선다', icon: '🆚' },
] as const;
export type Mode = (typeof MODES)[number]['id'];
@@ -22,6 +23,14 @@ export type VoteRule = (typeof VOTE_RULES)[number];
export const COUNTS = [10, 20, 30, 50, 100, 0] as const;
/** 다음 문제까지: seconds the answer stays on screen (the music goes on) before the next question. */
export const REVEAL_SECS = [5, 10, 15, 30] as const;
/** 이지선다 제한 시간: seconds to pick a card. */
export const DUEL_SECS = [10, 15, 20, 30, 45, 60, 90] as const;
/** 이지선다 진행: pairs = 매번 새 두 곡, chain = 조회수가 더 높은 곡이 남고 새 곡과 다시 비교. */
export const DUEL_FLOWS = [
{ id: 'pairs', label: '매번 새 두 곡' },
{ id: 'chain', label: '이긴 곡이 남기 (연속)' },
] as const;
export type DuelFlow = (typeof DUEL_FLOWS)[number]['id'];
export interface RoomConfig {
title: string;
@@ -49,7 +58,10 @@ export interface RoomConfig {
nextVotes: VoteRule;
count: (typeof COUNTS)[number];
visibility: 'public' | 'private' | 'password';
/** 제작된 퀴즈: the chosen quiz (listen mode only, every song of it); null = 직접 선택 (장르·연도·난이도). */
/** 이지선다: seconds to pick (the cards can be changed until then). */
duelSec: (typeof DUEL_SECS)[number];
duelFlow: DuelFlow;
/** 제작된 퀴즈: the chosen quiz (일반 퀴즈 = listen mode, 이지선다 퀴즈 = duel mode); null = 직접 선택 (장르·연도·난이도). */
quizId: number | null;
/** Name of that quiz, filled in by the server for room cards. */
quizName: string;
@@ -76,6 +88,8 @@ export const DEFAULT_ROOM_CONFIG: RoomConfig = {
nextVotes: '1/3',
count: 30,
visibility: 'public',
duelSec: 30,
duelFlow: 'pairs',
quizId: null,
quizName: '',
};
@@ -113,6 +127,11 @@ export function listenLabel(s: number): string {
/** One-line summary for room cards (docs/03 열린 방 목록). */
export function configSummary(c: RoomConfig, genreName: (id: string) => string = (x) => x): string[] {
const out: string[] = [];
if (c.mode === 'duel') {
out.push(`🆚 이지선다 · ${c.duelSec}초`, c.duelFlow === 'chain' ? '이긴 곡이 남기' : '매번 새 두 곡');
if (c.quizId) out.unshift(`📋 ${c.quizName || '이지선다 퀴즈'}`);
return out;
}
if (c.quizId) {
out.push(`📋 ${c.quizName || '제작된 퀴즈'}`, `🎧 ${listenLabel(c.listenSec)}${c.startAt === 'highlight' ? ' · 하이라이트' : ''}`);
if (c.answer !== 'title') out.push(c.answer === 'both' ? '제목+가수' : '가수만');
@@ -128,3 +147,10 @@ export function configSummary(c: RoomConfig, genreName: (id: string) => string =
out.push(`공개 ${c.revealSec}초`);
return out;
}
/** 조회수 for people: 1.2억 · 3,456만 · 9,999 (exact numbers go in a tooltip). */
export function viewsLabel(n: number): string {
if (n >= 1e8) return `${(Math.floor(n / 1e7) / 10).toLocaleString('ko-KR')}억`;
if (n >= 1e4) return `${Math.floor(n / 1e4).toLocaleString('ko-KR')}만`;
return n.toLocaleString('ko-KR');
}