1436 lines
62 KiB
TypeScript
1436 lines
62 KiB
TypeScript
/**
|
||
* 관리자 → 퀴즈 (제작된 퀴즈): 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<QuizVisibility, string> = { private: '비공개', partial: '일부공개', public: '전체공개' };
|
||
const VIS_CLASS: Record<QuizVisibility, string> = { private: '', partial: 'warn', public: 'ok' };
|
||
|
||
// ------------------------------------------------------------------ list
|
||
export function QuizzesPage() {
|
||
const role = useSession((s) => s.role);
|
||
const [all, setAll] = useState(false);
|
||
const [list, setList] = useState<QuizSummary[] | null>(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 (
|
||
<>
|
||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||
<h1>퀴즈</h1>
|
||
{role === 'superadmin' && (
|
||
<label className="field-inline">
|
||
<input type="checkbox" checked={all} onChange={(e) => setAll(e.target.checked)} /> 모든 관리자 퀴즈 보기
|
||
</label>
|
||
)}
|
||
</div>
|
||
<p className="muted">
|
||
직접 만든 퀴즈예요. 일반 퀴즈는 방 설정에서 "제작된 퀴즈"를 고르면 곡이 순서대로(또는 섞어서) 전부 나오고, 듣고맞추기에서만 쓸 수 있어요. 🆚 이지선다 퀴즈는 파일로 만들고(조회수는
|
||
서버가 토픽 + MV로 불러와요), 이지선다 모드에서만 쓸 수 있어요.
|
||
</p>
|
||
{fromFile && (
|
||
<QuizFileImport
|
||
mode="create"
|
||
onClose={() => 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 && <PlaylistSheet onClose={() => setToSheet(false)} />}
|
||
<div className="quiz-grid">
|
||
{list?.map((q) => (
|
||
<Link key={q.id} to={`/admin/quizzes/${q.id}`} className="quiz-card">
|
||
<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}` : ''}
|
||
</span>
|
||
</span>
|
||
<span className="muted small">수정 {new Date(q.updatedAt).toLocaleString('ko-KR', { dateStyle: 'short', timeStyle: 'short' })}</span>
|
||
</Link>
|
||
))}
|
||
{adding ? (
|
||
<form
|
||
className="quiz-card add"
|
||
onSubmit={(e) => {
|
||
e.preventDefault();
|
||
void create();
|
||
}}
|
||
>
|
||
<label className="field">
|
||
퀴즈 이름
|
||
<input className="input" autoFocus maxLength={60} value={name} onChange={(e) => setName(e.target.value)} placeholder="예) 2000년대 발라드 명곡" />
|
||
</label>
|
||
<div className="row">
|
||
<button className="btn btn-primary btn-sm" disabled={!name.trim()}>
|
||
확인
|
||
</button>
|
||
<button type="button" className="btn btn-sm" onClick={() => (setAdding(false), setName(''))}>
|
||
취소
|
||
</button>
|
||
</div>
|
||
</form>
|
||
) : (
|
||
<button type="button" className="quiz-card add plus" onClick={() => setAdding(true)}>
|
||
<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>
|
||
)}
|
||
{!toSheet && (
|
||
<button type="button" className="quiz-card add plus" onClick={() => setToSheet(true)}>
|
||
<span aria-hidden>🔗</span> 재생목록으로 엑셀 만들기
|
||
<small className="muted">유튜브·유튜브 뮤직·스포티파이 → 파일로 만들기용 엑셀</small>
|
||
</button>
|
||
)}
|
||
</div>
|
||
{list && list.length === 0 && !adding && <p className="muted">아직 만든 퀴즈가 없어요. "퀴즈 추가"를 눌러 시작해 보세요.</p>}
|
||
</>
|
||
);
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 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<QuizItem, 'titleAnswers' | 'artistAnswers' | 'hints' | 'fromFile' | 'auto' | 'startSec' | 'highlightSec' | 'views' | 'viewsAuto'>;
|
||
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<T extends QuizItem>(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<string>('');
|
||
const [draft, setDraft] = useState<Draft | null>(null);
|
||
const [db, setDb] = useState<Record<number, DbInfo | null>>({});
|
||
const [tab, setTab] = useState<'songs' | 'settings'>('songs');
|
||
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; kind: QuizKind } | 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}`)
|
||
.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<boolean> => {
|
||
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<typeof payload>;
|
||
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 = <T extends QuizItem>(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<typeof payload>;
|
||
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<number>());
|
||
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<number, DbInfo> }>('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 <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 (
|
||
<>
|
||
<div className="quiz-head">
|
||
<Link to="/admin/quizzes" className="btn btn-sm btn-ghost">
|
||
← 퀴즈 목록
|
||
</Link>
|
||
<h1 className="grow">{draft.name || '이름 없는 퀴즈'}</h1>
|
||
{dirty ? <span className="badge warn" role="status">● 저장하지 않은 변경이 있어요</span> : <span className="muted small">저장됨</span>}
|
||
{kind === 'duel' && (
|
||
<button
|
||
type="button"
|
||
className="btn"
|
||
disabled={!draft.items.some((i) => i.id && i.viewsAuto && i.viewsAuto.state !== 'pending')}
|
||
onClick={() => void refreshViews()}
|
||
title="자동으로 불러온 곡의 토픽·MV 조회수를 지금 값으로 다시 불러와요 (직접 넣은 조회수는 그대로)"
|
||
>
|
||
🔄 조회수 다시 불러오기
|
||
</button>
|
||
)}
|
||
<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">
|
||
{busy ? '저장 중…' : '저장'} <span className="kbd">Ctrl+S</span>
|
||
</button>
|
||
</div>
|
||
{owner && (
|
||
<p className="muted small" style={{ marginTop: -8 }}>
|
||
{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 }}>
|
||
<button type="button" role="tab" aria-selected={tab === 'songs'} className={tab === 'songs' ? 'on' : ''} onClick={() => setTab('songs')}>
|
||
곡 목록 ({draft.items.length})
|
||
</button>
|
||
<button type="button" role="tab" aria-selected={tab === 'settings'} className={tab === 'settings' ? 'on' : ''} onClick={() => setTab('settings')}>
|
||
설정
|
||
</button>
|
||
</div>
|
||
{isNew && (
|
||
<div className="card stack">
|
||
<b>곡을 어떻게 넣을까요?</b>
|
||
<div className="row">
|
||
<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>
|
||
</div>
|
||
</div>
|
||
)}
|
||
{tab === 'songs' ? (
|
||
<SongsTab
|
||
kind={kind}
|
||
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' } })}
|
||
onRefreshViews={(itemId) => void refreshViews([itemId])}
|
||
/>
|
||
) : (
|
||
<SettingsTab kind={kind} draft={draft} onChange={set} onDelete={() => setConfirmDelete(true)} />
|
||
)}
|
||
{leaveTo && (
|
||
<Sheet label="저장하지 않은 변경" onClose={() => setLeaveTo(null)}>
|
||
<h2>저장하지 않은 변경이 있어요</h2>
|
||
<p className="muted">이대로 나가면 바꾼 내용이 사라져요.</p>
|
||
<div className="stack">
|
||
<button
|
||
type="button"
|
||
className="btn btn-block btn-primary"
|
||
onClick={() =>
|
||
void save().then((ok) => {
|
||
if (!ok) return;
|
||
const to = leaveTo;
|
||
setLeaveTo(null);
|
||
dirtyRef.current = false;
|
||
nav(to);
|
||
})
|
||
}
|
||
>
|
||
저장하고 나가기
|
||
</button>
|
||
<button
|
||
type="button"
|
||
className="btn btn-block btn-danger"
|
||
onClick={() => {
|
||
const to = leaveTo;
|
||
setLeaveTo(null);
|
||
dirtyRef.current = false;
|
||
nav(to);
|
||
}}
|
||
>
|
||
저장하지 않고 나가기
|
||
</button>
|
||
<button type="button" className="btn btn-block" onClick={() => setLeaveTo(null)}>
|
||
취소
|
||
</button>
|
||
</div>
|
||
</Sheet>
|
||
)}
|
||
{confirmDelete && (
|
||
<ConfirmSheet
|
||
title="이 퀴즈를 지울까요?"
|
||
body={`"${draft.name}"와 곡 목록이 지워지고 방에서 고를 수 없게 돼요. 서버 노래 DB의 곡과 별칭은 그대로예요.`}
|
||
confirm="퀴즈 지우기"
|
||
danger
|
||
onClose={() => 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<number, DbInfo | null>;
|
||
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<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 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<QuizItem>) => 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 (
|
||
<div className={`songs-layout quiz ${selected ? 'with-panel' : ''}`}>
|
||
<div className="stack" style={{ gap: 12, minWidth: 0 }}>
|
||
{fileOpen ? (
|
||
<QuizFileImport
|
||
mode="into"
|
||
kind={kind}
|
||
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 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}곡 제외)` : ''}. 저장해야 반영돼요.`);
|
||
}}
|
||
/>
|
||
) : (
|
||
<AddSong onAdd={add} onImport={() => setImportOpen(true)} onFile={() => setFileOpen(true)} />
|
||
)}
|
||
{items.length === 0 ? (
|
||
<p className="muted">아직 곡이 없어요. 위에서 제목·가수로 찾거나 유튜브 주소를 붙여 넣어 추가해 주세요.</p>
|
||
) : (
|
||
<div className="table-wrap">
|
||
{duel && items.some((i) => i.viewsAuto?.state === 'pending') && (
|
||
<p className="muted small" role="status" style={{ margin: '8px 10px' }}>
|
||
⏳ 토픽·MV 조회수를 불러오는 중이에요 ({items.filter((i) => i.viewsAuto?.state === 'pending').length}곡 남음). 다 불러오면 저절로 채워져요.
|
||
</p>
|
||
)}
|
||
{duel && items.some((i) => i.views === null && i.viewsAuto?.state !== 'pending') && (
|
||
<p className="warn-text small" style={{ margin: '8px 10px' }}>
|
||
조회수가 없는 곡 {items.filter((i) => i.views === null && i.viewsAuto?.state !== 'pending').length}곡은 게임에 나오지 않아요. 곡을 눌러 조회수를 직접 넣거나 다시
|
||
불러와 주세요.{items.some((i) => i.views === null && !i.viewsAuto) && ' 새로 넣은 곡은 저장하면 불러와요.'}
|
||
</p>
|
||
)}
|
||
<table className="data-table quiz-songs">
|
||
<thead>
|
||
<tr>
|
||
<th style={{ width: 28 }} aria-label="순서 옮기기" />
|
||
<th style={{ width: 44 }}>번호</th>
|
||
<th>노래</th>
|
||
<th>{duel ? '조회수' : '추가 정답'}</th>
|
||
{duel && <th>비고</th>}
|
||
<th>길이</th>
|
||
<th>재생 위치</th>
|
||
<th style={{ width: 120 }} />
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{items.map((it, i) => (
|
||
<tr
|
||
key={it.key}
|
||
className={`${sel === it.key ? 'sel' : ''} ${overKey === it.key && dragKey !== it.key ? 'drop' : ''} ${dragKey === it.key ? 'dragging' : ''}`}
|
||
onClick={() => 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' }}
|
||
>
|
||
<td className="drag" aria-hidden title="끌어서 순서 바꾸기">
|
||
⠿
|
||
</td>
|
||
<td className="mono">{i + 1}</td>
|
||
<td>
|
||
<b>{it.title}</b>
|
||
<div className="muted small">
|
||
{it.artist}
|
||
{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>
|
||
{duel ? (
|
||
<>
|
||
<td className="mono small" title={it.views !== null ? `${it.views.toLocaleString('ko-KR')}회` : undefined}>
|
||
<ViewsCell item={it} />
|
||
</td>
|
||
<td className="small">{duelViewsNote(it) ?? <span className="muted">-</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()}>
|
||
<div className="row" style={{ gap: 4, flexWrap: 'nowrap' }}>
|
||
<button type="button" className="btn btn-sm btn-ghost" disabled={i === 0} aria-label={`${i + 1}번 위로`} onClick={() => move(i, i - 1)}>
|
||
▲
|
||
</button>
|
||
<button type="button" className="btn btn-sm btn-ghost" disabled={i === items.length - 1} aria-label={`${i + 1}번 아래로`} onClick={() => move(i, i + 1)}>
|
||
▼
|
||
</button>
|
||
<button type="button" className="btn btn-sm btn-ghost" aria-label={`${it.title} 빼기`} onClick={() => remove(it.key)}>
|
||
✕
|
||
</button>
|
||
</div>
|
||
</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
)}
|
||
</div>
|
||
{selected && (
|
||
<ItemPanel
|
||
key={selected.key}
|
||
duel={duel}
|
||
item={selected}
|
||
index={items.indexOf(selected)}
|
||
total={items.length}
|
||
db={selected.songId ? db[selected.songId] : null}
|
||
defaultStartAt={settings.startAt}
|
||
onPatch={(p) => 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}
|
||
/>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
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);
|
||
const [video, setVideo] = useState<VideoInfo | null>(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<VideoInfo>('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 (
|
||
<div className="card stack" style={{ gap: 10 }}>
|
||
<form
|
||
className="row"
|
||
onSubmit={(e) => {
|
||
e.preventDefault();
|
||
void search();
|
||
}}
|
||
>
|
||
<input className="input grow" value={q} onChange={(e) => setQ(e.target.value)} placeholder="곡 추가: 제목·가수로 찾기 (예: 아이유 좋은 날) 또는 유튜브 주소 붙여넣기" aria-label="곡 추가 검색" />
|
||
<button className="btn btn-primary" disabled={busy || !q.trim()}>
|
||
{busy ? '찾는 중…' : '찾기'}
|
||
</button>
|
||
{(dbHits || ytHits || video) && (
|
||
<button type="button" className="btn" onClick={reset}>
|
||
닫기
|
||
</button>
|
||
)}
|
||
<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 && (
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<span className="field">서버 노래 DB {dbHits.length ? `(${dbHits.length}곡)` : ''}</span>
|
||
{dbHits.length === 0 && <span className="muted small">서버 DB에서 못 찾았어요. 유튜브에서 찾아보세요.</span>}
|
||
{dbHits.map((s) => (
|
||
<div key={s.id} className="cand">
|
||
<span className="grow">
|
||
<b>{s.title}</b> <span className="muted small">· {s.artist}{s.year ? ` · ${s.year}` : ''} · {mmss(s.durationSec)}</span>
|
||
{s.status !== 'matched' && <span className="warn-text small"> — 확정된 영상 없음{s.videoId ? ' (후보 영상으로 추가)' : ''}</span>}
|
||
</span>
|
||
<button
|
||
type="button"
|
||
className="btn btn-sm"
|
||
disabled={!s.videoId}
|
||
onClick={() => done(onAdd({ songId: s.id, videoId: s.videoId!, title: s.title, artist: s.artist, durationSec: s.durationSec }))}
|
||
>
|
||
추가
|
||
</button>
|
||
</div>
|
||
))}
|
||
<div className="row">
|
||
<button type="button" className="btn btn-sm" disabled={busy} onClick={() => void searchYt()}>
|
||
🔎 유튜브에서 찾기
|
||
</button>
|
||
<span className="muted small">서버 DB에 없거나 다른 영상을 쓰고 싶을 때</span>
|
||
</div>
|
||
</div>
|
||
)}
|
||
{ytHits && (
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<span className="field">유튜브 검색 결과</span>
|
||
{ytHits.length === 0 && <span className="muted small">결과가 없어요. 유튜브 주소를 직접 붙여 넣어 주세요.</span>}
|
||
{ytHits.map((r) => (
|
||
<div key={r.videoId} className="cand">
|
||
<span className="grow">
|
||
<b>{r.title}</b> <span className="muted small">· {r.artist} · {mmss(r.durationSec)}</span>
|
||
{r.songId && <span className="badge ok" style={{ marginLeft: 6 }}>서버 DB에 있는 곡</span>}
|
||
</span>
|
||
<a className="btn btn-sm btn-ghost" href={`https://youtu.be/${r.videoId}`} target="_blank" rel="noreferrer" aria-label={`${r.title} 유튜브에서 보기`}>
|
||
↗
|
||
</a>
|
||
<button type="button" className="btn btn-sm" onClick={() => done(onAdd({ songId: r.songId, videoId: r.videoId, title: r.title, artist: r.artist, durationSec: r.durationSec }))}>
|
||
추가
|
||
</button>
|
||
</div>
|
||
))}
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
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 (
|
||
<div className="video-add">
|
||
<YtPreview videoId={v.videoId} start={0} apiRef={api} />
|
||
<form
|
||
className="stack"
|
||
style={{ gap: 8 }}
|
||
onSubmit={(e) => {
|
||
e.preventDefault();
|
||
if (title.trim() && artist.trim()) onAdd({ songId: v.songId, videoId: v.videoId, title: title.trim(), artist: artist.trim(), durationSec: v.durationSec });
|
||
}}
|
||
>
|
||
<span className="muted small">
|
||
영상: {v.videoTitle} · {v.channel}
|
||
{v.songId && <span className="badge ok" style={{ marginLeft: 6 }}>서버 DB에 있는 곡</span>}
|
||
</span>
|
||
<label className="field">
|
||
제목 (정답)
|
||
<input className="input" value={title} maxLength={200} onChange={(e) => setTitle(e.target.value)} />
|
||
</label>
|
||
<label className="field">
|
||
가수
|
||
<input className="input" value={artist} maxLength={200} onChange={(e) => setArtist(e.target.value)} />
|
||
</label>
|
||
<button className="btn btn-primary" disabled={!title.trim() || !artist.trim()}>
|
||
이 영상으로 추가
|
||
</button>
|
||
</form>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 플레이리스트 가져오기
|
||
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<ImportStatus, [string, string]> = {
|
||
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<ImportJob | null>(null);
|
||
const [busy, setBusy] = useState(false);
|
||
const [pick, setPick] = useState<Set<number>>(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<Record<string, number>>((a, r) => ((a[r.status] = (a[r.status] ?? 0) + 1), a), {});
|
||
return (
|
||
<div className="card stack" style={{ gap: 10 }}>
|
||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||
<b>🔗 플레이리스트 가져오기</b>
|
||
<button type="button" className="btn btn-sm btn-ghost" onClick={onClose} aria-label="닫기">
|
||
✕
|
||
</button>
|
||
</div>
|
||
<form
|
||
className="row"
|
||
onSubmit={(e) => {
|
||
e.preventDefault();
|
||
if (url.trim()) void begin();
|
||
}}
|
||
>
|
||
<input className="input grow" value={url} onChange={(e) => setUrl(e.target.value)} placeholder="유튜브·유튜브 뮤직·스포티파이 플레이리스트 주소" aria-label="플레이리스트 주소" />
|
||
<button className="btn btn-primary" disabled={busy || !url.trim() || job?.status === 'running'}>
|
||
{busy ? '불러오는 중…' : '가져오기'}
|
||
</button>
|
||
</form>
|
||
<p className="muted small" style={{ margin: 0 }}>
|
||
서버 DB에 있는 곡은 그 곡으로, 유튜브 플레이리스트는 그 영상으로, 스포티파이는 유튜브 뮤직에서 원곡을 찾아 넣어요. 확인이 끝나면 넣을 곡을 고를 수 있어요.
|
||
</p>
|
||
{job && (
|
||
<>
|
||
<div className="stack" style={{ gap: 4 }}>
|
||
<span className="small">
|
||
<b>{job.name || '플레이리스트'}</b> · {job.status === 'running' ? `확인 중 ${job.done}/${job.total}곡` : job.status === 'failed' ? `실패: ${job.error}` : `${job.total}곡 확인 끝`}
|
||
{rows.length > 0 && (
|
||
<span className="muted">
|
||
{' '}
|
||
· {(Object.keys(IMPORT_LABEL) as ImportStatus[])
|
||
.filter((k) => counts[k])
|
||
.map((k) => `${IMPORT_LABEL[k][0]} ${counts[k]}`)
|
||
.join(' · ')}
|
||
</span>
|
||
)}
|
||
</span>
|
||
<progress className="yt-progress" max={job.total} value={job.done} />
|
||
</div>
|
||
{rows.length > 0 && (
|
||
<div className="table-wrap" style={{ maxHeight: 460, overflowY: 'auto' }}>
|
||
<table className="data-table">
|
||
<thead>
|
||
<tr>
|
||
<th style={{ width: 36 }}>
|
||
<input
|
||
type="checkbox"
|
||
aria-label="모두 고르기"
|
||
checked={rows.filter(usable).every((r) => pick.has(r.n))}
|
||
onChange={(e) => setPick(e.target.checked ? new Set(rows.filter(usable).map((r) => r.n)) : new Set())}
|
||
/>
|
||
</th>
|
||
<th style={{ width: 40 }}>#</th>
|
||
<th>노래</th>
|
||
<th>상태</th>
|
||
<th>길이</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{rows.map((r) => (
|
||
<tr key={r.n}>
|
||
<td>
|
||
<input
|
||
type="checkbox"
|
||
aria-label={`${r.title} 넣기`}
|
||
disabled={!usable(r)}
|
||
checked={pick.has(r.n) && usable(r)}
|
||
onChange={(e) => {
|
||
const next = new Set(pick);
|
||
if (e.target.checked) next.add(r.n);
|
||
else next.delete(r.n);
|
||
setPick(next);
|
||
}}
|
||
/>
|
||
</td>
|
||
<td className="mono">{r.n}</td>
|
||
<td>
|
||
<b>{r.title}</b>
|
||
<div className="muted small">
|
||
{r.artist}
|
||
{(r.source.title !== r.title || r.source.artist !== r.artist) && <span> · 원래: {r.source.artist} - {r.source.title}</span>}
|
||
</div>
|
||
</td>
|
||
<td className="small">
|
||
<span className={`badge ${IMPORT_LABEL[r.status][1]}`}>{IMPORT_LABEL[r.status][0]}</span>
|
||
{inList(r) && <span className="badge" style={{ marginLeft: 4 }}>이미 목록에 있음</span>}
|
||
{r.note && <div className="muted">{r.note}</div>}
|
||
{r.videoId && (
|
||
<a className="small" href={`https://youtu.be/${r.videoId}`} target="_blank" rel="noreferrer">
|
||
영상 보기 ↗
|
||
</a>
|
||
)}
|
||
</td>
|
||
<td className="mono small">{mmss(r.durationSec)}</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
)}
|
||
{job.status === 'done' && (
|
||
<div className="row">
|
||
<button type="button" className="btn btn-primary" disabled={!chosen.length} onClick={() => onApply(chosen, false)}>
|
||
고른 {chosen.length}곡 목록 뒤에 추가
|
||
</button>
|
||
<button type="button" className="btn btn-danger" disabled={!chosen.length} onClick={() => setConfirmReplace(true)}>
|
||
지금 목록을 지우고 바꾸기
|
||
</button>
|
||
<span className="muted small">"확인 필요"는 영상을 보고 맞으면 체크해 주세요. "못 찾음"은 추가한 뒤 직접 넣어 주세요.</span>
|
||
</div>
|
||
)}
|
||
</>
|
||
)}
|
||
{confirmReplace && (
|
||
<ConfirmSheet
|
||
title="지금 목록을 바꿀까요?"
|
||
body={`지금 곡 목록 ${existing.length}곡과 그 곡들의 정답·위치 설정이 사라지고 고른 ${chosen.length}곡으로 바뀌어요. 저장하기 전에는 되돌릴 수 있어요(저장하지 않고 나가기).`}
|
||
confirm="목록 바꾸기"
|
||
danger
|
||
onClose={() => setConfirmReplace(false)}
|
||
onConfirm={() => onApply(chosen, true)}
|
||
/>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** 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 (
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<div className="row" style={{ gap: 6 }}>
|
||
{values.map((v) => (
|
||
<button key={v} type="button" className="chip x" aria-pressed="true" onClick={() => onChange(values.filter((x) => x !== v))} aria-label={`${v} 빼기`}>
|
||
{v}
|
||
</button>
|
||
))}
|
||
</div>
|
||
<input
|
||
className="input"
|
||
value={text}
|
||
aria-label={label}
|
||
placeholder={placeholder}
|
||
maxLength={200}
|
||
onChange={(e) => setText(e.target.value)}
|
||
onKeyDown={(e) => {
|
||
if (e.key === 'Enter' || e.key === ',') {
|
||
e.preventDefault();
|
||
commit();
|
||
}
|
||
}}
|
||
onBlur={commit}
|
||
/>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** 이지선다 조회수 칸: 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 <span className="muted">불러오는 중…{total && ` (${total})`}</span>;
|
||
if (item.views === null) return a ? <span className="warn-text">없음</span> : <span className="muted">저장하면 불러와요</span>;
|
||
return (
|
||
<>
|
||
{total}
|
||
{a?.state === 'done' && (
|
||
<div className="muted">{[a.topicViews !== null && `토픽 ${viewsLabel(a.topicViews)}`, a.mvViews !== null && `MV ${viewsLabel(a.mvViews)}`].filter(Boolean).join(' · ')}</div>
|
||
)}
|
||
</>
|
||
);
|
||
}
|
||
|
||
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<QuizItem>) => 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<VideoInfo>('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 (
|
||
<aside className="song-panel stack" aria-label="곡 편집">
|
||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||
<b>{index + 1}번 곡</b>
|
||
<button type="button" className="btn btn-sm btn-ghost" onClick={onClose} aria-label="닫기">
|
||
✕
|
||
</button>
|
||
</div>
|
||
<PositionEditor
|
||
videoId={item.videoId}
|
||
durationSec={item.durationSec}
|
||
auto={item.auto}
|
||
startSec={item.startSec}
|
||
highlightSec={item.highlightSec}
|
||
dbHighlightSec={db === undefined ? undefined : db && db.videoId === item.videoId ? db.highlightSec : null}
|
||
defaultStartAt={defaultStartAt}
|
||
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">
|
||
{duel ? '가수' : item.fromFile ? '설명 (정답과 같이 공개돼요)' : '가수'}
|
||
<input className="input" value={item.artist} maxLength={200} onChange={(e) => onPatch({ artist: e.target.value })} />
|
||
</label>
|
||
{duel && (
|
||
<div className="field">
|
||
조회수
|
||
{a ? (
|
||
<div className="stack small" style={{ gap: 4 }} role="status">
|
||
{a.state === 'pending' ? (
|
||
<span className="muted">토픽·MV 조회수를 불러오는 중이에요…</span>
|
||
) : a.state === 'failed' ? (
|
||
<span className="warn-text">{a.error}</span>
|
||
) : (
|
||
<>
|
||
<span>
|
||
<b>{fullViews(item.views)}</b> = 토픽 {fullViews(a.topicViews)} + MV {fullViews(a.mvViews)}
|
||
</span>
|
||
<span className="muted">
|
||
{a.topicId && (
|
||
<a href={`https://youtu.be/${a.topicId}`} target="_blank" rel="noreferrer">
|
||
토픽 영상 ↗
|
||
</a>
|
||
)}
|
||
{a.topicId && a.mvId && ' · '}
|
||
{a.mvId && (
|
||
<a href={`https://youtu.be/${a.mvId}`} target="_blank" rel="noreferrer">
|
||
MV ↗
|
||
</a>
|
||
)}
|
||
{a.at && ` · ${new Date(a.at).toLocaleString('ko-KR')}에 불러옴`}
|
||
</span>
|
||
{duelViewsNote(item) && <span className="badge warn" style={{ alignSelf: 'flex-start' }}>비고: {duelViewsNote(item)}</span>}
|
||
</>
|
||
)}
|
||
</div>
|
||
) : (
|
||
<span className="muted small">
|
||
{item.views === null ? '저장하면 토픽·MV 조회수를 자동으로 불러와요.' : item.fromFile ? '파일에 적힌 조회수를 써요.' : '직접 넣은 조회수를 써요.'}
|
||
</span>
|
||
)}
|
||
<input
|
||
className="input"
|
||
value={viewsText}
|
||
inputMode="numeric"
|
||
aria-label="조회수 직접 넣기"
|
||
placeholder={a ? '직접 넣기 (예: 1234567, 123만, 1.2억)' : '예: 1234567, 123만, 1.2억 (비우면 자동)'}
|
||
onChange={(e) => {
|
||
setViewsText(e.target.value);
|
||
const v = parseViews(e.target.value);
|
||
// a number of one's own replaces the fetched one; emptying the box goes back to 자동 (fetched on save)
|
||
if (v !== undefined && (v !== null || !a)) onPatch({ views: v, viewsAuto: null });
|
||
}}
|
||
aria-invalid={viewsBad}
|
||
/>
|
||
{viewsBad ? <span className="field-error small">조회수를 읽을 수 없어요.</span> : !a && item.views !== null && <span className="muted small">{item.views.toLocaleString('ko-KR')}회</span>}
|
||
{onRefreshViews && (
|
||
<button type="button" className="btn btn-sm" style={{ alignSelf: 'flex-start' }} disabled={a?.state === 'pending'} onClick={onRefreshViews}>
|
||
🔄 {a ? '조회수 다시 불러오기' : '자동으로 불러오기 (토픽 + MV)'}
|
||
</button>
|
||
)}
|
||
</div>
|
||
)}
|
||
{!duel && (
|
||
<>
|
||
<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)" />
|
||
</div>
|
||
<div className="field">
|
||
가수 추가 정답
|
||
<ChipsInput values={item.artistAnswers} onChange={(artistAnswers) => onPatch({ artistAnswers })} label="가수 추가 정답" placeholder="다른 표기 입력 후 Enter (예: IU)" />
|
||
</div>
|
||
</>
|
||
)}
|
||
{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) && (
|
||
<>
|
||
<br />
|
||
이미 정답으로 인정되는 별칭: {[...db.titleAliases, ...db.artistAliases].join(', ')}
|
||
</>
|
||
)}
|
||
</p>
|
||
) : (
|
||
<p className="muted small">서버 노래 DB에 없는 곡이에요. 이 퀴즈 안에서만 쓰여요.</p>
|
||
)}
|
||
<form
|
||
className="row"
|
||
onSubmit={(e) => {
|
||
e.preventDefault();
|
||
if (url.trim()) void changeVideo();
|
||
}}
|
||
>
|
||
<input className="input grow" value={url} onChange={(e) => setUrl(e.target.value)} placeholder="다른 유튜브 주소로 바꾸기" aria-label="영상 바꾸기" />
|
||
<button className="btn btn-sm" disabled={!url.trim()}>
|
||
바꾸기
|
||
</button>
|
||
</form>
|
||
<div className="row">
|
||
<label className="field-inline">
|
||
순서
|
||
<input
|
||
className="input sm"
|
||
type="number"
|
||
min={1}
|
||
max={total}
|
||
value={pos}
|
||
onChange={(e) => setPos(e.target.value)}
|
||
onBlur={() => {
|
||
const n = Math.min(total, Math.max(1, Math.round(Number(pos)) || index + 1));
|
||
onMove(n - 1);
|
||
setPos(String(n));
|
||
}}
|
||
onKeyDown={(e) => e.key === 'Enter' && (e.target as HTMLInputElement).blur()}
|
||
aria-label="순서 번호"
|
||
/>
|
||
번으로
|
||
</label>
|
||
<span className="grow" />
|
||
<button type="button" className="btn btn-sm btn-danger" onClick={onRemove}>
|
||
목록에서 빼기
|
||
</button>
|
||
</div>
|
||
</aside>
|
||
);
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 설정
|
||
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]);
|
||
return (
|
||
<div className="settings card ink" style={{ maxWidth: 860 }}>
|
||
<div className="hd">
|
||
<h2>퀴즈 설정</h2>
|
||
<span className="small" style={{ fontWeight: 700 }}>
|
||
방에서 이 퀴즈를 고르면 아래 값이 방 설정의 기본값이 돼요(방장이 바꿀 수 있어요)
|
||
</span>
|
||
</div>
|
||
<div className="bd">
|
||
<Section title="퀴즈 이름">
|
||
<input className="input" value={draft.name} maxLength={60} onChange={(e) => onChange({ name: e.target.value })} aria-label="퀴즈 이름" />
|
||
</Section>
|
||
<Section title="설명">
|
||
<textarea className="input" rows={3} value={draft.description} maxLength={500} onChange={(e) => onChange({ description: e.target.value })} aria-label="퀴즈 설명" placeholder="방에서 퀴즈를 고를 때 보이는 설명" />
|
||
</Section>
|
||
<Section title="공개방식">
|
||
<Seg label="공개방식" value={draft.visibility} disabled={false} onChange={(visibility) => onChange({ visibility })} options={QUIZ_VISIBILITIES.map((v) => ({ v: v.id, label: v.label }))} />
|
||
<p className="muted small" style={{ marginTop: 6 }}>
|
||
{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="문제 순서"
|
||
value={s.order}
|
||
disabled={false}
|
||
onChange={(order) => setS({ order })}
|
||
options={[
|
||
{ v: 'ordered', label: '순서대로' },
|
||
{ v: 'random', label: '무작위' },
|
||
]}
|
||
/>
|
||
</Section>
|
||
)}
|
||
<Section title="재생위치 기본" tip="곡마다 정한 '처음' 위치 또는 '하이라이트' 위치에서 틀어요">
|
||
<Seg
|
||
label="재생위치 기본"
|
||
value={s.startAt}
|
||
disabled={false}
|
||
onChange={(startAt) => setS({ startAt })}
|
||
options={[
|
||
{ v: 'start', label: '처음부터' },
|
||
{ v: 'highlight', label: '하이라이트부터' },
|
||
]}
|
||
/>
|
||
</Section>
|
||
{!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}>
|
||
퀴즈 지우기
|
||
</button>
|
||
</section>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|