/** * 관리자 → 퀴즈 (제작된 퀴즈): my quizzes, then one quiz's editor — 곡 목록 (add by search or address, edit, reorder, * extra answers) and 설정 (description, room defaults, order, 공개방식). Saving is by hand: 저장 button or Ctrl+S; * unsaved changes show in the tab title and above the editor, and leaving asks first. */ 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, PENDING_VIEWS, QUIZ_VISIBILITIES, duelViewsNote, listenLabel, parseViews, viewsLabel, type DuelViews, type QuizDetail, type QuizItem, type QuizKind, type QuizSettings, type QuizSummary, type QuizVisibility, } from '@mq/shared/lite'; import { apiCall } from '../../net/api'; import { useSession } from '../../store/session'; import { toast } from '../../store/toast'; import { ConfirmSheet, Sheet } from '../../components/ui'; import { PlayRules, Section, Seg } from '../../components/RoomSettings'; import { YtPreview } from './SongsPage'; import { PositionEditor } from './PositionEditor'; import { useReviewCount } from './reviewCount'; import { QuizFileImport, exportQuiz } from './QuizFile'; import { PlaylistSheet } from './PlaylistSheet'; const mmss = (s: number | null | undefined) => (s == null ? '-' : `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, '0')}`); const VIS_LABEL: Record = { private: '비공개', partial: '일부공개', public: '전체공개' }; const VIS_CLASS: Record = { private: '', partial: 'warn', public: 'ok' }; // ------------------------------------------------------------------ list export function QuizzesPage() { const role = useSession((s) => s.role); const [all, setAll] = useState(false); const [list, setList] = useState(null); const [name, setName] = useState(''); const [adding, setAdding] = useState(false); const [fromFile, setFromFile] = useState(false); const [toSheet, setToSheet] = useState(false); const nav = useNavigate(); const load = useCallback(() => { apiCall<{ quizzes: QuizSummary[] }>('GET', `/api/admin/quizzes${all ? '?all=1' : ''}`) .then((r) => setList(r.quizzes)) .catch((e: Error) => toast(e.message, 'error')); }, [all]); useEffect(load, [load]); const create = async () => { if (!name.trim()) return; try { const r = await apiCall<{ id: number }>('POST', '/api/admin/quizzes', { name: name.trim() }); nav(`/admin/quizzes/${r.id}?new=1`); } catch (e) { toast((e as Error).message, 'error'); } }; return ( <>

퀴즈

{role === 'superadmin' && ( )}

직접 만든 퀴즈예요. 일반 퀴즈는 방 설정에서 "제작된 퀴즈"를 고르면 곡이 순서대로(또는 섞어서) 전부 나오고, 듣고맞추기에서만 쓸 수 있어요. 🆚 이지선다 퀴즈는 파일로 만들고(조회수는 서버가 토픽 + MV로 불러와요), 이지선다 모드에서만 쓸 수 있어요.

{fromFile && ( setFromFile(false)} onCreate={async (quizName, items, kind) => { try { 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'); } }} /> )} {toSheet && setToSheet(false)} />}
{list?.map((q) => ( {q.name} {q.description && {q.description}} {q.kind === 'duel' && 🆚 이지선다} {VIS_LABEL[q.visibility]} {q.songs}곡 · 플레이 {q.plays}번{all ? ` · ${q.ownerName}` : ''} 수정 {new Date(q.updatedAt).toLocaleString('ko-KR', { dateStyle: 'short', timeStyle: 'short' })} ))} {adding ? (
{ e.preventDefault(); void create(); }} >
) : ( )} {!fromFile && ( )} {!toSheet && ( )}
{list && list.length === 0 && !adding &&

아직 만든 퀴즈가 없어요. "퀴즈 추가"를 눌러 시작해 보세요.

} ); } // ------------------------------------------------------------------ editor type DraftItem = QuizItem & { key: string }; interface Draft { name: string; description: string; visibility: QuizVisibility; settings: QuizSettings; items: DraftItem[]; } export interface DbInfo { titleAliases: string[]; artistAliases: string[]; highlightSec: number | null; durationSec: number | null; videoId: string | null; } /** A song picked in the editor (search, address, playlist): answers, hints and positions start empty. */ type NewSong = Omit; const fresh = (it: NewSong): QuizItem => ({ ...it, titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, auto: true, startSec: null, highlightSec: null, views: null, viewsAuto: null }); /** 이지선다 조회수 자동: what the server fetched, put into the editor's copy (songs still 자동 there with the same video). */ type FetchedViews = { id: number; videoId: string; views: number | null; viewsAuto: DuelViews }; function withFetched(items: T[], fetched: FetchedViews[]): T[] { const by = new Map(fetched.map((f) => [f.id, f])); return items.map((it) => { const f = it.id ? by.get(it.id) : undefined; return f && it.viewsAuto && f.videoId === it.videoId ? { ...it, views: f.views, viewsAuto: f.viewsAuto } : it; }); } let keySeq = 0; const newKey = () => `k${++keySeq}`; const toDraft = (q: QuizDetail): Draft => ({ name: q.name, description: q.description, visibility: q.visibility, settings: { ...DEFAULT_QUIZ_SETTINGS, ...q.settings }, items: q.items.map((i) => ({ ...i, key: newKey() })), }); /** What is compared for "저장 안 됨" and sent to the server (client keys left out). */ const payload = (d: Draft) => ({ ...d, items: d.items.map(({ key: _, ...i }) => i) }); export function QuizEditor() { const { id } = useParams(); const [params, setParams] = useSearchParams(); const nav = useNavigate(); const [saved, setSaved] = useState(''); const [draft, setDraft] = useState(null); const [db, setDb] = useState>({}); const [tab, setTab] = useState<'songs' | 'settings'>('songs'); const [busy, setBusy] = useState(false); const [leaveTo, setLeaveTo] = useState(null); const [confirmDelete, setConfirmDelete] = useState(false); const [owner, setOwner] = useState<{ ownerName: string; plays: number; kind: QuizKind } | null>(null); const [importOpen, setImportOpen] = useState(false); const [fileOpen, setFileOpen] = useState(false); const load = useCallback(() => { apiCall<{ quiz: QuizDetail; db: Record }>('GET', `/api/admin/quizzes/${id}`) .then((r) => { const d = toDraft(r.quiz); setDraft(d); setSaved(JSON.stringify(payload(d))); setDb(r.db); setOwner({ ownerName: r.quiz.ownerName, plays: r.quiz.plays, kind: r.quiz.kind }); }) .catch((e: Error) => toast(e.message, 'error')); }, [id]); useEffect(load, [load]); const dirty = !!draft && JSON.stringify(payload(draft)) !== saved; const dirtyRef = useRef(dirty); dirtyRef.current = dirty; const draftRef = useRef(draft); draftRef.current = draft; const save = useCallback(async (): Promise => { const sent = draftRef.current; if (!sent) return false; const sentJson = JSON.stringify(payload(sent)); setBusy(true); try { const r = await apiCall<{ quiz: QuizDetail; reviews: { pending: number } }>('PUT', `/api/admin/quizzes/${id}`, JSON.parse(sentJson)); // what the server keeps, with the client keys (selection) of the items as sent (same order) const d = toDraft(r.quiz); d.items = d.items.map((it, i) => ({ ...it, key: sent.items[i]?.key ?? it.key })); setSaved(JSON.stringify(payload(d))); // edits made while the request was on its way stay (and stay unsaved); new items get their ids const now = draftRef.current; if (!now || JSON.stringify(payload(now)) === sentJson) setDraft(d); else { const ids = new Map(d.items.map((it) => [it.key, it.id])); setDraft({ ...now, items: now.items.map((it) => (it.id || !ids.has(it.key) ? it : { ...it, id: ids.get(it.key) })) }); } toast(r.reviews.pending ? `저장했어요. 서버 DB에 없거나 다른 곡 ${r.reviews.pending}곡이 관리자 검토 대기에 있어요.` : '저장했어요.'); useReviewCount.getState().refresh(); return true; } catch (e) { toast((e as Error).message, 'error'); return false; } finally { setBusy(false); } }, [id]); // 이지선다 조회수 자동: while songs wait, the server's results are taken in (also into the saved copy: not a change) const waiting = !!draft?.items.some((i) => i.viewsAuto?.state === 'pending'); useEffect(() => { if (!waiting) return; const t = setInterval(() => { apiCall<{ items: FetchedViews[] }>('GET', `/api/admin/quizzes/${id}/views`) .then((r) => { setDraft((d) => (d ? { ...d, items: withFetched(d.items, r.items) } : d)); setSaved((json) => { if (!json) return json; const p = JSON.parse(json) as ReturnType; return JSON.stringify({ ...p, items: withFetched(p.items, r.items) }); }); }) .catch(() => {}); }, 2000); return () => clearInterval(t); }, [waiting, id]); const refreshViews = useCallback( async (itemIds?: number[]) => { try { const r = await apiCall<{ queued: number }>('POST', `/api/admin/quizzes/${id}/views`, itemIds ? { itemIds } : {}); if (!r.queued) return toast('다시 불러올 곡이 없어요. 새로 넣은 곡은 저장하면 불러와요.'); const ids = itemIds ? new Set(itemIds) : null; // waiting from now on (a written number named here becomes 자동): the poll above brings the results const mark = (items: T[]) => items.map((it) => (it.id && (ids ? ids.has(it.id) : it.viewsAuto) ? { ...it, viewsAuto: { ...(it.viewsAuto ?? PENDING_VIEWS), state: 'pending' as const } } : it)); setDraft((d) => (d ? { ...d, items: mark(d.items) } : d)); setSaved((json) => { if (!json) return json; const p = JSON.parse(json) as ReturnType; return JSON.stringify({ ...p, items: mark(p.items) }); }); toast(`${r.queued}곡의 조회수를 다시 불러와요.`); } catch (e) { toast((e as Error).message, 'error'); } }, [id], ); // DB facts (aliases, the DB highlight for 자동) of songs added since loading: fetched as soon as they appear const asked = useRef(new Set()); useEffect(() => { if (!draft) return; const missing = [...new Set(draft.items.map((i) => i.songId).filter((x): x is number => !!x && !(x in db) && !asked.current.has(x)))]; if (!missing.length) return; for (const x of missing) asked.current.add(x); apiCall<{ db: Record }>('GET', `/api/admin/quizzes/pick/songs?ids=${missing.join(',')}`) .then((r) => setDb((cur) => ({ ...cur, ...Object.fromEntries(missing.map((x) => [x, r.db[x] ?? null])) }))) .catch(() => { for (const x of missing) asked.current.delete(x); }); }, [draft, db]); const saveRef = useRef(save); saveRef.current = save; // Ctrl+S / ⌘S useEffect(() => { const onKey = (e: KeyboardEvent) => { if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') { e.preventDefault(); if (dirtyRef.current) void saveRef.current(); else toast('바뀐 내용이 없어요.'); } }; window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey); }, []); // tab title + leaving the page useEffect(() => { const prev = document.title; return () => { document.title = prev; }; }, []); useEffect(() => { if (draft) document.title = `${dirty ? '● 저장 안 됨 · ' : ''}${draft.name} · 퀴즈 편집`; }, [dirty, draft]); useEffect(() => { const onUnload = (e: BeforeUnloadEvent) => { if (!dirtyRef.current) return; e.preventDefault(); e.returnValue = ''; }; window.addEventListener('beforeunload', onUnload); // links inside the site: our own 저장하고 나가기 / 그냥 나가기 / 취소 const onClick = (e: MouseEvent) => { if (!dirtyRef.current || e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey) return; const a = (e.target as HTMLElement).closest?.('a[href]') as HTMLAnchorElement | null; if (!a || a.target === '_blank') return; const url = new URL(a.href, location.href); if (url.origin !== location.origin || url.pathname === location.pathname) return; e.preventDefault(); e.stopPropagation(); setLeaveTo(url.pathname + url.search); }; document.addEventListener('click', onClick, true); return () => { window.removeEventListener('beforeunload', onUnload); document.removeEventListener('click', onClick, true); }; }, []); if (!draft) return

불러오는 중…

; const set = (p: Partial) => setDraft({ ...draft, ...p }); const kind: QuizKind = owner?.kind ?? 'normal'; const isNew = params.get('new') === '1' && draft.items.length === 0; return ( <>
← 퀴즈 목록

{draft.name || '이름 없는 퀴즈'}

{dirty ? ● 저장하지 않은 변경이 있어요 : 저장됨} {kind === 'duel' && ( )}
{owner && (

{kind === 'duel' && 🆚 이지선다} 만든 사람 {owner.ownerName} · {draft.items.length}곡 · 플레이 {owner.plays}번 ·{' '} {VIS_LABEL[draft.visibility]}

)}
{isNew && (
곡을 어떻게 넣을까요?
)} {tab === 'songs' ? ( set({ items })} importOpen={importOpen} setImportOpen={setImportOpen} fileOpen={fileOpen} setFileOpen={setFileOpen} onHints={() => draft.settings.hint === 'none' && set({ settings: { ...draft.settings, hint: 'manual' } })} onRefreshViews={(itemId) => void refreshViews([itemId])} /> ) : ( setConfirmDelete(true)} /> )} {leaveTo && ( setLeaveTo(null)}>

저장하지 않은 변경이 있어요

이대로 나가면 바꾼 내용이 사라져요.

)} {confirmDelete && ( setConfirmDelete(false)} onConfirm={() => void apiCall('DELETE', `/api/admin/quizzes/${id}`) .then(() => { dirtyRef.current = false; toast('퀴즈를 지웠어요.'); nav('/admin/quizzes'); }) .catch((e: Error) => toast(e.message, 'error')) } /> )} ); } // ------------------------------------------------------------------ 곡 목록 interface DbHit { id: number; title: string; artist: string; year: number | null; videoId: string | null; status: string; durationSec: number | null; highlightSec: number | null; } interface YtHit { videoId: string; title: string; artist: string; durationSec: number | null; songId: number | null; } interface VideoInfo { videoId: string; videoTitle: string; channel: string; title: string; artist: string; songId: number | null; durationSec: number | null; } 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, onItems, importOpen, setImportOpen, fileOpen, setFileOpen, onHints, onRefreshViews, }: { kind: QuizKind; items: DraftItem[]; db: Record; settings: QuizSettings; onItems: (items: DraftItem[]) => void; importOpen: boolean; setImportOpen: (on: boolean) => void; fileOpen: boolean; setFileOpen: (on: boolean) => void; /** Songs with their own hints came in: hints should not stay off. */ onHints: () => void; onRefreshViews: (itemId: number) => void; }) { const [sel, setSel] = useState(null); const [dragKey, setDragKey] = useState(null); const [overKey, setOverKey] = useState(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'); return false; } const n: DraftItem = { ...fresh(it), key: newKey() }; onItems([...items, n]); toast(`${items.length + 1}번에 추가했어요: ${it.title}`); return true; }; const patch = (key: string, p: Partial) => onItems(items.map((i) => (i.key === key ? { ...i, ...p } : i))); const move = (from: number, to: number) => { if (to < 0 || to >= items.length || from === to) return; const next = [...items]; const [x] = next.splice(from, 1); next.splice(to, 0, x!); onItems(next); }; const remove = (key: string) => { onItems(items.filter((i) => i.key !== key)); if (sel === key) setSel(null); }; return (
{fileOpen ? ( setFileOpen(false)} onApply={(rows, replace) => { const added = rows.map((r) => ({ ...r, key: newKey() })); onItems(replace ? added : [...items, ...added]); setSel(null); setFileOpen(false); if (rows.some((r) => r.hints.length)) onHints(); toast(`${added.length}곡을 ${replace ? '새 목록으로 넣었어요' : '목록 뒤에 추가했어요'}. 저장해야 반영돼요.`); }} /> ) : importOpen ? ( setImportOpen(false)} onApply={(rows, replace) => { const base = replace ? [] : items; const seen = new Set(base.flatMap((x) => [x.videoId, x.songId ? `s${x.songId}` : ''])); const added: DraftItem[] = []; for (const r of rows) { if (seen.has(r.videoId!) || (r.songId && seen.has(`s${r.songId}`))) continue; seen.add(r.videoId!); if (r.songId) seen.add(`s${r.songId}`); // answers worked out by the server (other names, 한글 발음 …, docs/13) const it = fresh({ songId: r.songId, videoId: r.videoId!, title: r.title, artist: r.artist, durationSec: r.durationSec }); added.push({ ...it, titleAnswers: r.titleAnswers ?? [], artistAnswers: r.artistAnswers ?? [], key: newKey() }); } onItems([...base, ...added]); setSel(null); setImportOpen(false); toast(`${added.length}곡을 ${replace ? '새 목록으로 넣었어요' : '목록 뒤에 추가했어요'}${rows.length > added.length ? ` (이미 있는 ${rows.length - added.length}곡 제외)` : ''}. 저장해야 반영돼요.`); }} /> ) : ( setImportOpen(true)} onFile={() => setFileOpen(true)} /> )} {items.length === 0 ? (

아직 곡이 없어요. 위에서 제목·가수로 찾거나 유튜브 주소를 붙여 넣어 추가해 주세요.

) : (
{duel && items.some((i) => i.viewsAuto?.state === 'pending') && (

⏳ 토픽·MV 조회수를 불러오는 중이에요 ({items.filter((i) => i.viewsAuto?.state === 'pending').length}곡 남음). 다 불러오면 저절로 채워져요.

)} {duel && items.some((i) => i.views === null && i.viewsAuto?.state !== 'pending') && (

조회수가 없는 곡 {items.filter((i) => i.views === null && i.viewsAuto?.state !== 'pending').length}곡은 게임에 나오지 않아요. 곡을 눌러 조회수를 직접 넣거나 다시 불러와 주세요.{items.some((i) => i.views === null && !i.viewsAuto) && ' 새로 넣은 곡은 저장하면 불러와요.'}

)} {duel && } {items.map((it, i) => ( setSel(sel === it.key ? null : it.key)} draggable onDragStart={(e) => { setDragKey(it.key); e.dataTransfer.effectAllowed = 'move'; }} onDragOver={(e) => { if (!dragKey) return; e.preventDefault(); setOverKey(it.key); }} onDrop={(e) => { e.preventDefault(); const from = items.findIndex((x) => x.key === dragKey); if (from >= 0) move(from, i); setDragKey(null); setOverKey(null); }} onDragEnd={() => (setDragKey(null), setOverKey(null))} style={{ cursor: 'pointer' }} > {duel ? ( <> ) : ( )} ))}
번호 노래 {duel ? '조회수' : '추가 정답'}비고길이 재생 위치
⠿ {i + 1} {it.title}
{it.artist} {it.fromFile ? 파일 : !it.songId && DB에 없음}
{it.hints.length > 0 &&
힌트: {it.hints.join(' → ')}
}
{duelViewsNote(it) ?? -}{[...it.titleAnswers, ...it.artistAnswers].join(', ') || -}{mmss(it.durationSec ?? (it.songId ? db[it.songId]?.durationSec : null))} {it.auto ? 자동 : `처음 ${mmss(it.startSec ?? 0)} · 하이라이트 ${mmss(it.highlightSec)}`} e.stopPropagation()}>
)}
{selected && ( patch(selected.key, p)} onMove={(to) => move(items.indexOf(selected), to)} onRemove={() => remove(selected.key)} onClose={() => setSel(null)} isDuplicate={(videoId) => items.some((x) => x.key !== selected.key && x.videoId === videoId)} onRefreshViews={selected.id ? () => onRefreshViews(selected.id!) : null} /> )}
); } function AddSong({ onAdd, onImport, onFile }: { onAdd: (it: NewSong) => boolean; onImport: () => void; onFile: () => void }) { const [q, setQ] = useState(''); const [dbHits, setDbHits] = useState(null); const [ytHits, setYtHits] = useState(null); const [video, setVideo] = useState(null); const [busy, setBusy] = useState(false); const reset = () => (setDbHits(null), setYtHits(null), setVideo(null)); const search = async () => { const text = q.trim(); if (!text) return; reset(); setBusy(true); try { if (looksLikeUrl(text)) setVideo(await apiCall('POST', '/api/admin/quizzes/pick/video', { url: text })); else setDbHits((await apiCall<{ songs: DbHit[] }>('GET', `/api/admin/quizzes/pick/db?q=${encodeURIComponent(text)}`)).songs); } catch (e) { toast((e as Error).message, 'error'); } finally { setBusy(false); } }; const searchYt = async () => { setBusy(true); try { setYtHits((await apiCall<{ results: YtHit[] }>('GET', `/api/admin/quizzes/pick/youtube?q=${encodeURIComponent(q.trim())}`)).results); } catch (e) { toast((e as Error).message, 'error'); } finally { setBusy(false); } }; const done = (ok: boolean) => { if (!ok) return; reset(); setQ(''); }; return (
{ e.preventDefault(); void search(); }} > setQ(e.target.value)} placeholder="곡 추가: 제목·가수로 찾기 (예: 아이유 좋은 날) 또는 유튜브 주소 붙여넣기" aria-label="곡 추가 검색" /> {(dbHits || ytHits || video) && ( )}
{video && done(onAdd(it))} />} {dbHits && (
서버 노래 DB {dbHits.length ? `(${dbHits.length}곡)` : ''} {dbHits.length === 0 && 서버 DB에서 못 찾았어요. 유튜브에서 찾아보세요.} {dbHits.map((s) => (
{s.title} · {s.artist}{s.year ? ` · ${s.year}` : ''} · {mmss(s.durationSec)} {s.status !== 'matched' && — 확정된 영상 없음{s.videoId ? ' (후보 영상으로 추가)' : ''}}
))}
서버 DB에 없거나 다른 영상을 쓰고 싶을 때
)} {ytHits && (
유튜브 검색 결과 {ytHits.length === 0 && 결과가 없어요. 유튜브 주소를 직접 붙여 넣어 주세요.} {ytHits.map((r) => (
{r.title} · {r.artist} · {mmss(r.durationSec)} {r.songId && 서버 DB에 있는 곡} ↗
))}
)}
); } function VideoAdd({ v, onAdd }: { v: VideoInfo; onAdd: (it: NewSong) => void }) { const [title, setTitle] = useState(v.title); const [artist, setArtist] = useState(v.artist); const api = useRef<{ time(): number | undefined } | null>(null); return (
{ e.preventDefault(); if (title.trim() && artist.trim()) onAdd({ songId: v.songId, videoId: v.videoId, title: title.trim(), artist: artist.trim(), durationSec: v.durationSec }); }} > 영상: {v.videoTitle} · {v.channel} {v.songId && 서버 DB에 있는 곡}
); } // ------------------------------------------------------------------ 플레이리스트 가져오기 type ImportStatus = 'db' | 'video' | 'found' | 'check' | 'missing' | 'blocked'; interface ImportRow { n: number; source: { title: string; artist: string }; title: string; artist: string; titleAnswers: string[]; artistAnswers: string[]; durationSec: number | null; videoId: string | null; songId: number | null; status: ImportStatus; note: string; } interface ImportJob { id: string; name: string; status: 'running' | 'done' | 'failed'; done: number; total: number; rows: ImportRow[]; error: string | null; } const IMPORT_LABEL: Record = { db: ['서버 DB', 'ok'], video: ['유튜브 영상', 'teal'], found: ['찾음', 'ok'], check: ['확인 필요', 'warn'], missing: ['못 찾음', ''], blocked: ['재생 불가', ''], }; const usable = (r: ImportRow) => !!r.videoId && r.status !== 'missing' && r.status !== 'blocked'; function PlaylistImport({ existing, onApply, onClose }: { existing: QuizItem[]; onApply: (rows: ImportRow[], replace: boolean) => void; onClose: () => void }) { const [url, setUrl] = useState(''); const [job, setJob] = useState(null); const [busy, setBusy] = useState(false); const [pick, setPick] = useState>(new Set()); const [confirmReplace, setConfirmReplace] = useState(false); const picked = useRef(false); useEffect(() => { if (!job || job.status !== 'running') return; const t = setTimeout(() => { apiCall<{ job: ImportJob }>('GET', `/api/admin/quizzes/pick/playlist/${job.id}`) .then((r) => setJob(r.job)) .catch((e: Error) => toast(e.message, 'error')); }, 1000); return () => clearTimeout(t); }, [job]); // pre-tick what is safe once the rows are in: DB songs, the playlist's own videos, confident matches useEffect(() => { if (job?.status === 'done' && !picked.current) { picked.current = true; setPick(new Set(job.rows.filter((r) => usable(r) && r.status !== 'check').map((r) => r.n))); } }, [job]); const begin = async () => { setBusy(true); picked.current = false; try { setJob((await apiCall<{ job: ImportJob }>('POST', '/api/admin/quizzes/pick/playlist', { url: url.trim() })).job); } catch (e) { toast((e as Error).message, 'error'); } finally { setBusy(false); } }; const rows = job?.rows ?? []; const chosen = rows.filter((r) => pick.has(r.n) && usable(r)); const inList = (r: ImportRow) => existing.some((x) => x.videoId === r.videoId || (r.songId && x.songId === r.songId)); const counts = rows.reduce>((a, r) => ((a[r.status] = (a[r.status] ?? 0) + 1), a), {}); return (
🔗 플레이리스트 가져오기
{ e.preventDefault(); if (url.trim()) void begin(); }} > setUrl(e.target.value)} placeholder="유튜브·유튜브 뮤직·스포티파이 플레이리스트 주소" aria-label="플레이리스트 주소" />

서버 DB에 있는 곡은 그 곡으로, 유튜브 플레이리스트는 그 영상으로, 스포티파이는 유튜브 뮤직에서 원곡을 찾아 넣어요. 확인이 끝나면 넣을 곡을 고를 수 있어요.

{job && ( <>
{job.name || '플레이리스트'} · {job.status === 'running' ? `확인 중 ${job.done}/${job.total}곡` : job.status === 'failed' ? `실패: ${job.error}` : `${job.total}곡 확인 끝`} {rows.length > 0 && ( {' '} · {(Object.keys(IMPORT_LABEL) as ImportStatus[]) .filter((k) => counts[k]) .map((k) => `${IMPORT_LABEL[k][0]} ${counts[k]}`) .join(' · ')} )}
{rows.length > 0 && (
{rows.map((r) => ( ))}
pick.has(r.n))} onChange={(e) => setPick(e.target.checked ? new Set(rows.filter(usable).map((r) => r.n)) : new Set())} /> # 노래 상태 길이
{ const next = new Set(pick); if (e.target.checked) next.add(r.n); else next.delete(r.n); setPick(next); }} /> {r.n} {r.title}
{r.artist} {(r.source.title !== r.title || r.source.artist !== r.artist) && · 원래: {r.source.artist} - {r.source.title}}
{IMPORT_LABEL[r.status][0]} {inList(r) && 이미 목록에 있음} {r.note &&
{r.note}
} {r.videoId && ( 영상 보기 ↗ )}
{mmss(r.durationSec)}
)} {job.status === 'done' && (
"확인 필요"는 영상을 보고 맞으면 체크해 주세요. "못 찾음"은 추가한 뒤 직접 넣어 주세요.
)} )} {confirmReplace && ( setConfirmReplace(false)} onConfirm={() => onApply(chosen, true)} /> )}
); } /** Chips with an input: Enter or , adds, ✕ removes. */ function ChipsInput({ values, onChange, label, placeholder }: { values: string[]; onChange: (v: string[]) => void; label: string; placeholder: string }) { const [text, setText] = useState(''); const commit = () => { const t = text.trim(); if (t && !values.includes(t)) onChange([...values, t]); setText(''); }; return (
{values.map((v) => ( ))}
setText(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); commit(); } }} onBlur={commit} />
); } /** 이지선다 조회수 칸: the number the game uses, how it stands when fetched (토픽 · MV each). */ function ViewsCell({ item }: { item: QuizItem }) { const a = item.viewsAuto; const total = item.views !== null ? `${viewsLabel(item.views)}회` : null; if (a?.state === 'pending') return 불러오는 중…{total && ` (${total})`}; if (item.views === null) return a ? 없음 : 저장하면 불러와요; return ( <> {total} {a?.state === 'done' && (
{[a.topicViews !== null && `토픽 ${viewsLabel(a.topicViews)}`, a.mvViews !== null && `MV ${viewsLabel(a.mvViews)}`].filter(Boolean).join(' · ')}
)} ); } const fullViews = (n: number | null) => (n === null ? '-' : `${n.toLocaleString('ko-KR')}회`); function ItemPanel({ duel, item, index, total, db, defaultStartAt, onPatch, onMove, onRemove, onClose, isDuplicate, onRefreshViews, }: { duel: boolean; item: DraftItem; index: number; total: number; /** undefined: still loading the DB facts of the linked song. */ db: DbInfo | null | undefined; defaultStartAt: 'start' | 'highlight'; onPatch: (p: Partial) => void; onMove: (to: number) => void; onRemove: () => void; onClose: () => void; isDuplicate: (videoId: string) => boolean; /** 이지선다: fetch this saved song's views again (null: not saved yet — saving fetches them). */ onRefreshViews: (() => void) | null; }) { const [url, setUrl] = useState(''); const [pos, setPos] = useState(String(index + 1)); useEffect(() => setPos(String(index + 1)), [index]); // 자동 songs show the fetched numbers above; the box is for a number of one's own const [viewsText, setViewsText] = useState(item.viewsAuto || item.views === null ? '' : String(item.views)); const isAuto = !!item.viewsAuto; useEffect(() => { if (isAuto) setViewsText(''); }, [isAuto]); const viewsBad = parseViews(viewsText) === undefined; const a = item.viewsAuto; const changeVideo = async () => { try { const v = await apiCall('POST', '/api/admin/quizzes/pick/video', { url: url.trim() }); if (isDuplicate(v.videoId)) return toast('이미 목록에 있는 영상이에요.', 'error'); // a different video: the old positions belong to the old video onPatch({ videoId: v.videoId, songId: v.songId ?? item.songId, durationSec: v.durationSec ?? null, auto: true, startSec: null, highlightSec: null }); setUrl(''); toast('영상을 바꿨어요. 저장해야 반영돼요.'); } catch (e) { toast((e as Error).message, 'error'); } }; return ( ); } // ------------------------------------------------------------------ 설정 function SettingsTab({ kind, draft, onChange, onDelete }: { kind: QuizKind; draft: Draft; onChange: (p: Partial) => void; onDelete: () => void }) { const duel = kind === 'duel'; const s = draft.settings; const setS = (p: Partial) => onChange({ settings: { ...s, ...p } }); const vis = useMemo(() => QUIZ_VISIBILITIES.find((v) => v.id === draft.visibility)!, [draft.visibility]); return (

퀴즈 설정

방에서 이 퀴즈를 고르면 아래 값이 방 설정의 기본값이 돼요(방장이 바꿀 수 있어요)
onChange({ name: e.target.value })} aria-label="퀴즈 이름" />