퀴즈 파일 A단계: 관리자 → 퀴즈 '파일로 만들기'(.xlsx·.csv를 브라우저가 라이브러리 없이 읽음, 열 이름으로 링크·정답·설명·힌트·순번 인식, 시트 선택, 잘못된 링크·중복 영상 표시), 편집 화면 '파일에서 가져오기'(뒤에 추가·목록 바꾸기)·'엑셀로 내보내기'·빈 양식. 파일 곡은 적힌 값 그대로(DB 연결·검토 대기 없음). 곡별 힌트를 하나씩 보여 준 뒤 초성 힌트(자동은 N초마다, 투표는 한 번에 하나)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -217,12 +217,15 @@ export function GameScreen({ room, game }: { room: RoomView; game: GameView }) {
|
||||
</div>
|
||||
)}
|
||||
<div className="row" style={{ marginTop: 8 }}>
|
||||
{game.hint ? (
|
||||
<span className="hint">
|
||||
{game.hint} <small>초성 힌트</small>
|
||||
{(game.hints ?? []).map((h, i) => (
|
||||
<span key={i} className="hint">
|
||||
{h.text} <small>{h.chosung ? '초성 힌트' : `힌트 ${i + 1}`}</small>
|
||||
</span>
|
||||
))}
|
||||
{game.hintAtSec !== null && game.phase === 'play' ? (
|
||||
<span className="small muted">
|
||||
{game.hints?.length ? '다음 힌트' : '힌트'}는 {Math.max(0, Math.ceil(game.hintAtSec - elapsed / 1000))}초 뒤에 공개돼요
|
||||
</span>
|
||||
) : game.hintAtSec !== null && game.phase === 'play' ? (
|
||||
<span className="small muted">힌트는 {Math.max(0, Math.ceil(game.hintAtSec - elapsed / 1000))}초 뒤에 공개돼요</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
299
apps/web/src/pages/admin/QuizFile.tsx
Normal file
299
apps/web/src/pages/admin/QuizFile.tsx
Normal file
@@ -0,0 +1,299 @@
|
||||
/**
|
||||
* 퀴즈 파일 (관리자 → 퀴즈): 파일로 만들기 (a new quiz from .xlsx / .csv), 파일에서 가져오기 (into the open quiz),
|
||||
* 엑셀로 내보내기 and 빈 양식. The browser reads the file; columns are recognised by their headers and can be changed.
|
||||
* Values are used as written — bad links and repeated videos are listed and left out.
|
||||
*/
|
||||
import { useMemo, useState } from 'react';
|
||||
import {
|
||||
QUIZ_COLUMN_LABEL,
|
||||
guessColumns,
|
||||
headerRow,
|
||||
parseQuizRows,
|
||||
quizTemplateRows,
|
||||
quizToRows,
|
||||
readSheetFile,
|
||||
writeXlsx,
|
||||
type QuizColumn,
|
||||
type QuizItem,
|
||||
type Sheet,
|
||||
} from '@mq/shared/lite';
|
||||
import { toast } from '../../store/toast';
|
||||
import { ConfirmSheet } from '../../components/ui';
|
||||
|
||||
const MAX_BYTES = 20 * 1024 * 1024;
|
||||
const COLUMN_ORDER: QuizColumn[] = ['link', 'answer', 'desc', 'hint', 'answers', 'descAnswers', 'order', 'start', 'highlight'];
|
||||
|
||||
function download(name: string, bytes: Uint8Array) {
|
||||
const url = URL.createObjectURL(new Blob([bytes as Uint8Array<ArrayBuffer>], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }));
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${name.replace(/[\\/:*?"<>|]/g, ' ').trim() || '퀴즈'}.xlsx`;
|
||||
document.body.append(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
/** 엑셀로 내보내기: the songs as a file this screen reads back. */
|
||||
export function exportQuiz(name: string, items: QuizItem[]) {
|
||||
const { rows, widths } = quizToRows(items);
|
||||
download(name, writeXlsx(name, rows, widths));
|
||||
}
|
||||
|
||||
export function downloadTemplate() {
|
||||
const { rows, widths } = quizTemplateRows();
|
||||
download('퀴즈 양식', writeXlsx('퀴즈', rows, widths));
|
||||
}
|
||||
|
||||
export function QuizFileImport({
|
||||
mode,
|
||||
existing = [],
|
||||
onCreate,
|
||||
onApply,
|
||||
onClose,
|
||||
}: {
|
||||
/** create: 파일로 만들기 (new quiz) · into: 파일에서 가져오기 (the open quiz). */
|
||||
mode: 'create' | 'into';
|
||||
existing?: QuizItem[];
|
||||
onCreate?: (name: string, items: QuizItem[]) => Promise<void>;
|
||||
onApply?: (items: QuizItem[], replace: boolean) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [file, setFile] = useState<{ name: string; sheets: Sheet[] } | null>(null);
|
||||
const [sheetIdx, setSheetIdx] = useState(0);
|
||||
const [columns, setColumns] = useState<(QuizColumn | null)[]>([]);
|
||||
const [headerAt, setHeaderAt] = useState(0);
|
||||
const [name, setName] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [confirmReplace, setConfirmReplace] = useState(false);
|
||||
|
||||
const pickSheet = (sheets: Sheet[], i: number) => {
|
||||
const rows = sheets[i]?.rows ?? [];
|
||||
const h = headerRow(rows);
|
||||
setSheetIdx(i);
|
||||
setHeaderAt(h);
|
||||
setColumns(guessColumns(rows[h] ?? []));
|
||||
};
|
||||
const open = async (f: File) => {
|
||||
if (f.size > MAX_BYTES) return toast('파일이 너무 커요(20MB까지).', 'error');
|
||||
try {
|
||||
const sheets = (await readSheetFile(f.name, new Uint8Array(await f.arrayBuffer()))).filter((s) => s.rows.length > 0);
|
||||
if (!sheets.length) return toast('파일에 내용이 없어요.', 'error');
|
||||
setFile({ name: f.name, sheets });
|
||||
setName(f.name.replace(/\.[^.]+$/, '').slice(0, 60));
|
||||
// the sheet that has the most usable rows
|
||||
const best = sheets.map((s, i) => [i, parseQuizRows(s.rows, guessColumns(s.rows[headerRow(s.rows)] ?? []), headerRow(s.rows)).items.length] as const).sort((a, b) => b[1] - a[1])[0]![0];
|
||||
pickSheet(sheets, best);
|
||||
} catch (e) {
|
||||
toast((e as Error).message || '파일을 읽지 못했어요.', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
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 bad = parsed?.rows.filter((r) => r.problem) ?? [];
|
||||
const items = parsed?.items ?? [];
|
||||
const inList = new Set(existing.map((x) => x.videoId));
|
||||
const appendable = items.filter((x) => !inList.has(x.videoId));
|
||||
const width = Math.max(header.length, ...(sheet?.rows.slice(headerAt, headerAt + 20).map((r) => r.length) ?? [0]));
|
||||
|
||||
const setColumn = (i: number, v: QuizColumn | null) =>
|
||||
setColumns((cur) => {
|
||||
const next = [...cur];
|
||||
while (next.length < width) next.push(null);
|
||||
// one column per use (힌트 may be several)
|
||||
if (v && v !== 'hint') for (let k = 0; k < next.length; k++) if (next[k] === v) next[k] = null;
|
||||
next[i] = v;
|
||||
return next;
|
||||
});
|
||||
|
||||
const create = async () => {
|
||||
if (!onCreate || !name.trim() || !items.length) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await onCreate(name.trim(), items);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="card stack" style={{ gap: 12 }}>
|
||||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||||
<b>📄 {mode === 'create' ? '파일로 만들기' : '파일에서 가져오기'}</b>
|
||||
<button type="button" className="btn btn-sm btn-ghost" onClick={onClose} aria-label="닫기">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
<div className="row">
|
||||
<label className="btn btn-primary">
|
||||
{file ? '다른 파일 고르기' : '파일 고르기 (.xlsx, .csv)'}
|
||||
<input
|
||||
type="file"
|
||||
accept=".xlsx,.csv,.tsv,.txt,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/csv"
|
||||
hidden
|
||||
aria-label="퀴즈 파일"
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0];
|
||||
e.target.value = '';
|
||||
if (f) void open(f);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<button type="button" className="btn" onClick={downloadTemplate}>
|
||||
📥 빈 양식 받기
|
||||
</button>
|
||||
{file && <span className="muted small">{file.name}</span>}
|
||||
</div>
|
||||
{!file && (
|
||||
<p className="muted small" style={{ margin: 0 }}>
|
||||
한 줄에 한 곡씩, 첫 줄은 열 이름이에요. <b>유튜브 영상 링크</b>와 <b>정답</b>(예: 게임 제목)은 꼭 있어야 하고, <b>설명</b>(예: 노래 제목)은 정답을 공개할 때 같이
|
||||
보여요. <b>힌트</b> 열은 문제마다 먼저 나오고, 그다음 힌트로 초성이 나와요. <b>순번</b> 열이 있으면 그 순서대로 넣어요. 적힌 값은 고치지 않고 그대로 써요.
|
||||
</p>
|
||||
)}
|
||||
{file && sheet && (
|
||||
<>
|
||||
{file.sheets.length > 1 && (
|
||||
<label className="field-inline">
|
||||
시트
|
||||
<select className="input sm" style={{ width: 'auto' }} value={sheetIdx} onChange={(e) => pickSheet(file.sheets, Number(e.target.value))} aria-label="시트">
|
||||
{file.sheets.map((s, i) => (
|
||||
<option key={i} value={i}>
|
||||
{s.name} ({Math.max(0, s.rows.length - 1)}줄)
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<span className="field">열 {missing.length ? '— 아래에서 골라 주세요' : '(열 이름으로 찾았어요. 다르면 바꿔 주세요)'}</span>
|
||||
<div className="file-cols">
|
||||
{Array.from({ length: width }, (_, i) => (
|
||||
<label key={i} className="file-col">
|
||||
<span className="small clamp1" title={header[i] ?? ''}>
|
||||
{header[i]?.trim() || `${i + 1}번째 열`}
|
||||
</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) => (
|
||||
<option key={c} value={c}>
|
||||
{QUIZ_COLUMN_LABEL[c]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{missing.length > 0 && <span className="warn-text small">{missing.map((c) => QUIZ_COLUMN_LABEL[c]).join(', ')} 열을 골라 주세요.</span>}
|
||||
</div>
|
||||
{!missing.length && parsed && (
|
||||
<>
|
||||
<div className="small">
|
||||
<b>{items.length}곡</b>
|
||||
{bad.length > 0 && <span className="warn-text"> · 빠지는 줄 {bad.length}개</span>}
|
||||
{mode === 'into' && items.length > appendable.length && <span className="muted"> · 이미 목록에 있는 영상 {items.length - appendable.length}곡</span>}
|
||||
</div>
|
||||
{bad.length > 0 && (
|
||||
<div className="table-wrap" style={{ maxHeight: 200, overflowY: 'auto' }}>
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ width: 60 }}>줄</th>
|
||||
<th>빠지는 이유</th>
|
||||
<th>링크</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{bad.map((r) => (
|
||||
<tr key={r.line}>
|
||||
<td className="mono">{r.line}</td>
|
||||
<td className="warn-text small">{r.problem}</td>
|
||||
<td className="small">
|
||||
<span className="clamp1" style={{ maxWidth: 360 }}>
|
||||
{r.link || '-'}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{items.length > 0 && (
|
||||
<div className="table-wrap" style={{ maxHeight: 420, overflowY: 'auto' }}>
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ width: 44 }}>#</th>
|
||||
<th>정답</th>
|
||||
<th>설명</th>
|
||||
<th>힌트</th>
|
||||
<th>영상</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.map((it, i) => (
|
||||
<tr key={it.videoId}>
|
||||
<td className="mono">{i + 1}</td>
|
||||
<td>
|
||||
<b>{it.title}</b>
|
||||
{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>
|
||||
<td className="small">
|
||||
<a href={`https://youtu.be/${it.videoId}`} target="_blank" rel="noreferrer">
|
||||
{it.videoId} ↗
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{mode === 'create' ? (
|
||||
<form
|
||||
className="row"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void create();
|
||||
}}
|
||||
>
|
||||
<label className="field-inline grow">
|
||||
퀴즈 이름
|
||||
<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>
|
||||
</form>
|
||||
) : (
|
||||
<div className="row">
|
||||
<button type="button" className="btn btn-primary" disabled={!appendable.length} onClick={() => onApply?.(appendable, false)}>
|
||||
{appendable.length}곡 목록 뒤에 추가
|
||||
</button>
|
||||
<button type="button" className="btn btn-danger" disabled={!items.length} onClick={() => setConfirmReplace(true)}>
|
||||
지금 목록을 지우고 바꾸기
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{confirmReplace && (
|
||||
<ConfirmSheet
|
||||
title="지금 목록을 바꿀까요?"
|
||||
body={`지금 곡 목록 ${existing.length}곡과 그 곡들의 정답·위치 설정이 사라지고 파일의 ${items.length}곡으로 바뀌어요. 저장하기 전에는 되돌릴 수 있어요(저장하지 않고 나가기).`}
|
||||
confirm="목록 바꾸기"
|
||||
danger
|
||||
onClose={() => setConfirmReplace(false)}
|
||||
onConfirm={() => onApply?.(items, true)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import { PlayRules, Section, Seg } from '../../components/RoomSettings';
|
||||
import { YtPreview } from './SongsPage';
|
||||
import { PositionEditor } from './PositionEditor';
|
||||
import { useReviewCount } from './reviewCount';
|
||||
import { QuizFileImport, exportQuiz } from './QuizFile';
|
||||
|
||||
const mmss = (s: number | null | undefined) => (s == null ? '-' : `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, '0')}`);
|
||||
const VIS_LABEL: Record<QuizVisibility, string> = { private: '비공개', partial: '일부공개', public: '전체공개' };
|
||||
@@ -36,6 +37,7 @@ export function QuizzesPage() {
|
||||
const [list, setList] = useState<QuizSummary[] | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [fromFile, setFromFile] = useState(false);
|
||||
const nav = useNavigate();
|
||||
const load = useCallback(() => {
|
||||
apiCall<{ quizzes: QuizSummary[] }>('GET', `/api/admin/quizzes${all ? '?all=1' : ''}`)
|
||||
@@ -63,6 +65,21 @@ export function QuizzesPage() {
|
||||
)}
|
||||
</div>
|
||||
<p className="muted">직접 만든 퀴즈예요. 방 설정에서 "제작된 퀴즈"를 고르면 이 퀴즈의 곡이 순서대로(또는 섞어서) 전부 나와요. 듣고맞추기에서만 쓸 수 있어요.</p>
|
||||
{fromFile && (
|
||||
<QuizFileImport
|
||||
mode="create"
|
||||
onClose={() => setFromFile(false)}
|
||||
onCreate={async (quizName, items) => {
|
||||
try {
|
||||
const r = await apiCall<{ id: number }>('POST', '/api/admin/quizzes/file', { name: quizName, items });
|
||||
toast(`"${quizName}" 퀴즈를 ${items.length}곡으로 만들었어요.`);
|
||||
nav(`/admin/quizzes/${r.id}`);
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error');
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<div className="quiz-grid">
|
||||
{list?.map((q) => (
|
||||
<Link key={q.id} to={`/admin/quizzes/${q.id}`} className="quiz-card">
|
||||
@@ -103,6 +120,12 @@ export function QuizzesPage() {
|
||||
<span aria-hidden>+</span> 퀴즈 추가
|
||||
</button>
|
||||
)}
|
||||
{!fromFile && (
|
||||
<button type="button" className="quiz-card add plus" onClick={() => setFromFile(true)}>
|
||||
<span aria-hidden>📄</span> 파일로 만들기
|
||||
<small className="muted">엑셀(.xlsx)·CSV</small>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{list && list.length === 0 && !adding && <p className="muted">아직 만든 퀴즈가 없어요. "퀴즈 추가"를 눌러 시작해 보세요.</p>}
|
||||
</>
|
||||
@@ -126,6 +149,10 @@ export interface DbInfo {
|
||||
videoId: string | null;
|
||||
}
|
||||
|
||||
/** 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 });
|
||||
|
||||
let keySeq = 0;
|
||||
const newKey = () => `k${++keySeq}`;
|
||||
const toDraft = (q: QuizDetail): Draft => ({
|
||||
@@ -151,6 +178,7 @@ export function QuizEditor() {
|
||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||
const [owner, setOwner] = useState<{ ownerName: string; plays: number } | null>(null);
|
||||
const [importOpen, setImportOpen] = useState(false);
|
||||
const [fileOpen, setFileOpen] = useState(false);
|
||||
|
||||
const load = useCallback(() => {
|
||||
apiCall<{ quiz: QuizDetail; db: Record<number, DbInfo> }>('GET', `/api/admin/quizzes/${id}`)
|
||||
@@ -274,6 +302,9 @@ 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>
|
||||
<button type="button" className="btn btn-primary" disabled={busy || !dirty} onClick={() => void save()} title="Ctrl+S">
|
||||
{busy ? '저장 중…' : '저장'} <span className="kbd">Ctrl+S</span>
|
||||
</button>
|
||||
@@ -298,6 +329,9 @@ export function QuizEditor() {
|
||||
<button type="button" className="btn" onClick={() => (setParams({}), setTab('songs'), setImportOpen(true))}>
|
||||
🔗 플레이리스트 가져오기
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={() => (setParams({}), setTab('songs'), setFileOpen(true))}>
|
||||
📄 파일에서 가져오기
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" onClick={() => setParams({})}>
|
||||
✋ 직접 하나씩 추가
|
||||
</button>
|
||||
@@ -305,7 +339,17 @@ export function QuizEditor() {
|
||||
</div>
|
||||
)}
|
||||
{tab === 'songs' ? (
|
||||
<SongsTab items={draft.items} db={db} settings={draft.settings} onItems={(items) => set({ items })} importOpen={importOpen} setImportOpen={setImportOpen} />
|
||||
<SongsTab
|
||||
items={draft.items}
|
||||
db={db}
|
||||
settings={draft.settings}
|
||||
onItems={(items) => set({ items })}
|
||||
importOpen={importOpen}
|
||||
setImportOpen={setImportOpen}
|
||||
fileOpen={fileOpen}
|
||||
setFileOpen={setFileOpen}
|
||||
onHints={() => draft.settings.hint === 'none' && set({ settings: { ...draft.settings, hint: 'manual' } })}
|
||||
/>
|
||||
) : (
|
||||
<SettingsTab draft={draft} onChange={set} onDelete={() => setConfirmDelete(true)} />
|
||||
)}
|
||||
@@ -406,6 +450,9 @@ function SongsTab({
|
||||
onItems,
|
||||
importOpen,
|
||||
setImportOpen,
|
||||
fileOpen,
|
||||
setFileOpen,
|
||||
onHints,
|
||||
}: {
|
||||
items: DraftItem[];
|
||||
db: Record<number, DbInfo | null>;
|
||||
@@ -413,17 +460,21 @@ function SongsTab({
|
||||
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;
|
||||
}) {
|
||||
const [sel, setSel] = useState<string | null>(null);
|
||||
const [dragKey, setDragKey] = useState<string | null>(null);
|
||||
const [overKey, setOverKey] = useState<string | null>(null);
|
||||
const selected = items.find((i) => i.key === sel) ?? null;
|
||||
const add = (it: Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'auto' | 'startSec' | 'highlightSec'>) => {
|
||||
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 = { ...it, titleAnswers: [], artistAnswers: [], auto: true, startSec: null, highlightSec: null, key: newKey() };
|
||||
const n: DraftItem = { ...fresh(it), key: newKey() };
|
||||
onItems([...items, n]);
|
||||
toast(`${items.length + 1}번에 추가했어요: ${it.title}`);
|
||||
return true;
|
||||
@@ -443,28 +494,42 @@ function SongsTab({
|
||||
return (
|
||||
<div className={`songs-layout quiz ${selected ? 'with-panel' : ''}`}>
|
||||
<div className="stack" style={{ gap: 12, minWidth: 0 }}>
|
||||
{importOpen ? (
|
||||
{fileOpen ? (
|
||||
<QuizFileImport
|
||||
mode="into"
|
||||
existing={items}
|
||||
onClose={() => 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 ? (
|
||||
<PlaylistImport
|
||||
existing={items}
|
||||
onClose={() => setImportOpen(false)}
|
||||
onApply={(rows, replace) => {
|
||||
const base = replace ? [] : items;
|
||||
const seen = new Set(base.flatMap((x) => [x.videoId, x.songId ? `s${x.songId}` : '']));
|
||||
const fresh: DraftItem[] = [];
|
||||
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}`);
|
||||
fresh.push({ songId: r.songId, videoId: r.videoId!, title: r.title, artist: r.artist, durationSec: r.durationSec, titleAnswers: [], artistAnswers: [], auto: true, startSec: null, highlightSec: null, key: newKey() });
|
||||
added.push({ ...fresh({ songId: r.songId, videoId: r.videoId!, title: r.title, artist: r.artist, durationSec: r.durationSec }), key: newKey() });
|
||||
}
|
||||
onItems([...base, ...fresh]);
|
||||
onItems([...base, ...added]);
|
||||
setSel(null);
|
||||
setImportOpen(false);
|
||||
toast(`${fresh.length}곡을 ${replace ? '새 목록으로 넣었어요' : '목록 뒤에 추가했어요'}${rows.length > fresh.length ? ` (이미 있는 ${rows.length - fresh.length}곡 제외)` : ''}. 저장해야 반영돼요.`);
|
||||
toast(`${added.length}곡을 ${replace ? '새 목록으로 넣었어요' : '목록 뒤에 추가했어요'}${rows.length > added.length ? ` (이미 있는 ${rows.length - added.length}곡 제외)` : ''}. 저장해야 반영돼요.`);
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<AddSong onAdd={add} onImport={() => setImportOpen(true)} />
|
||||
<AddSong onAdd={add} onImport={() => setImportOpen(true)} onFile={() => setFileOpen(true)} />
|
||||
)}
|
||||
{items.length === 0 ? (
|
||||
<p className="muted">아직 곡이 없어요. 위에서 제목·가수로 찾거나 유튜브 주소를 붙여 넣어 추가해 주세요.</p>
|
||||
@@ -516,8 +581,9 @@ function SongsTab({
|
||||
<b>{it.title}</b>
|
||||
<div className="muted small">
|
||||
{it.artist}
|
||||
{!it.songId && <span className="badge" style={{ marginLeft: 6 }}>DB에 없음</span>}
|
||||
{it.fromFile ? <span className="badge" style={{ marginLeft: 6 }}>파일</span> : !it.songId && <span className="badge" style={{ marginLeft: 6 }}>DB에 없음</span>}
|
||||
</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>
|
||||
<td className="mono small">{mmss(it.durationSec ?? (it.songId ? db[it.songId]?.durationSec : null))}</td>
|
||||
@@ -561,7 +627,7 @@ function SongsTab({
|
||||
);
|
||||
}
|
||||
|
||||
function AddSong({ onAdd, onImport }: { onAdd: (it: Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'auto' | 'startSec' | 'highlightSec'>) => boolean; onImport: () => void }) {
|
||||
function AddSong({ onAdd, onImport, onFile }: { onAdd: (it: NewSong) => boolean; onImport: () => void; onFile: () => void }) {
|
||||
const [q, setQ] = useState('');
|
||||
const [dbHits, setDbHits] = useState<DbHit[] | null>(null);
|
||||
const [ytHits, setYtHits] = useState<YtHit[] | null>(null);
|
||||
@@ -618,6 +684,9 @@ function AddSong({ onAdd, onImport }: { onAdd: (it: Omit<QuizItem, 'titleAnswers
|
||||
<button type="button" className="btn" onClick={onImport}>
|
||||
🔗 플레이리스트 가져오기
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={onFile}>
|
||||
📄 파일
|
||||
</button>
|
||||
</form>
|
||||
{video && <VideoAdd v={video} onAdd={(it) => done(onAdd(it))} />}
|
||||
{dbHits && (
|
||||
@@ -672,7 +741,7 @@ function AddSong({ onAdd, onImport }: { onAdd: (it: Omit<QuizItem, 'titleAnswers
|
||||
);
|
||||
}
|
||||
|
||||
function VideoAdd({ v, onAdd }: { v: VideoInfo; onAdd: (it: Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'auto' | 'startSec' | 'highlightSec'>) => void }) {
|
||||
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);
|
||||
@@ -1003,9 +1072,13 @@ function ItemPanel({
|
||||
<input className="input" value={item.title} maxLength={200} onChange={(e) => onPatch({ title: e.target.value })} />
|
||||
</label>
|
||||
<label className="field">
|
||||
가수
|
||||
{item.fromFile ? '설명 (정답과 같이 공개돼요)' : '가수'}
|
||||
<input className="input" value={item.artist} maxLength={200} onChange={(e) => onPatch({ artist: e.target.value })} />
|
||||
</label>
|
||||
<div className="field">
|
||||
힌트 (적은 순서대로 하나씩 나오고, 마지막에 초성 힌트가 나와요)
|
||||
<ChipsInput values={item.hints} onChange={(hints) => onPatch({ hints: hints.slice(0, 5) })} label="힌트" placeholder="힌트 입력 후 Enter (예: 액션 RPG)" />
|
||||
</div>
|
||||
<div className="field">
|
||||
제목 추가 정답 (복수정답)
|
||||
<ChipsInput values={item.titleAnswers} onChange={(titleAnswers) => onPatch({ titleAnswers })} label="제목 추가 정답" placeholder="다른 표기 입력 후 Enter (예: 좋은날, Good Day)" />
|
||||
@@ -1014,7 +1087,9 @@ function ItemPanel({
|
||||
가수 추가 정답
|
||||
<ChipsInput values={item.artistAnswers} onChange={(artistAnswers) => onPatch({ artistAnswers })} label="가수 추가 정답" placeholder="다른 표기 입력 후 Enter (예: IU)" />
|
||||
</div>
|
||||
{item.songId ? (
|
||||
{item.fromFile ? (
|
||||
<p className="muted small">파일에서 넣은 곡이에요. 적힌 값 그대로 쓰고, 서버 노래 DB 검토에는 올라가지 않아요.</p>
|
||||
) : item.songId ? (
|
||||
<p className="muted small">
|
||||
서버 노래 #{item.songId}와 연결된 곡이에요. 추가 정답은 저장할 때 서버 DB 별칭에도 들어가요.
|
||||
{db && (db.titleAliases.length > 0 || db.artistAliases.length > 0) && (
|
||||
|
||||
@@ -360,6 +360,9 @@ input.input.sm { width: 76px; }
|
||||
.quiz-card.plus { align-items: center; justify-content: center; font-weight: 800; cursor: pointer; gap: 4px; }
|
||||
.quiz-card.plus span { font-size: 1.6rem; }
|
||||
.clamp2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
|
||||
.clamp1 { display: block; max-width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.file-cols { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 8px; }
|
||||
.file-col { display: flex; flex-direction: column; gap: 4px; min-width: 0; font-weight: 700; }
|
||||
.quiz-head { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
|
||||
.quiz-head h1 { margin: 0; }
|
||||
.songs-layout.with-panel.quiz { grid-template-columns: minmax(0, 1fr) 520px; }
|
||||
|
||||
Reference in New Issue
Block a user