제작된 퀴즈 1~3단계: 관리자 → 퀴즈(목록·추가·곡 목록: 서버 DB/유튜브 검색·주소로 추가, 끌어서·▲▼·번호로 순서, 복수정답은 연결된 DB 곡 별칭에도, 영상 바꾸기 / 설정: 설명·공개방식(비공개·일부공개·전체공개)·문제 순서·재생위치 기본·방 규칙). 저장은 버튼·Ctrl+S로만, 안 저장 시 탭 제목·표시·나가기 확인. 곡마다 처음·하이라이트 위치 편집기(영상+큰 재생바, 끌기·지금 위치로·여기서 듣기·±1초, 자동=0초+DB 하이라이트, 연령제한은 받아 둔 음원). 방 설정 '직접 선택 / 제작된 퀴즈'(검색·비공개/일부공개 먼저), 고르면 퀴즈 설정이 방 설정으로, 듣고맞추기·곡 전부, 곡별 위치로 재생, 플레이 수. 퀴즈당 곡 수·계정당 퀴즈 수 제한(사이트 설정, 기본 무제한). '퀴즈 저장·불러오기'는 '진행 저장·불러오기'로 이름 변경
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
872
apps/web/src/pages/admin/QuizzesPage.tsx
Normal file
872
apps/web/src/pages/admin/QuizzesPage.tsx
Normal file
@@ -0,0 +1,872 @@
|
||||
/**
|
||||
* 관리자 → 퀴즈 (제작된 퀴즈): 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,
|
||||
LISTEN_SECS,
|
||||
QUIZ_VISIBILITIES,
|
||||
listenLabel,
|
||||
type QuizDetail,
|
||||
type QuizItem,
|
||||
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';
|
||||
|
||||
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 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">직접 만든 퀴즈예요. 방 설정에서 "제작된 퀴즈"를 고르면 이 퀴즈의 곡이 순서대로(또는 섞어서) 전부 나와요. 듣고맞추기에서만 쓸 수 있어요.</p>
|
||||
<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 }}>
|
||||
<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>
|
||||
)}
|
||||
</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;
|
||||
}
|
||||
|
||||
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>>({});
|
||||
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 } | null>(null);
|
||||
|
||||
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 });
|
||||
})
|
||||
.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 save = useCallback(async (): Promise<boolean> => {
|
||||
if (!draft) return false;
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await apiCall<{ quiz: QuizDetail }>('PUT', `/api/admin/quizzes/${id}`, payload(draft));
|
||||
// keep the client keys (selection) of items that were already there, in order
|
||||
const d = toDraft(r.quiz);
|
||||
d.items = d.items.map((it, i) => ({ ...it, key: draft.items[i]?.key ?? it.key }));
|
||||
setDraft(d);
|
||||
setSaved(JSON.stringify(payload(d)));
|
||||
toast('저장했어요.');
|
||||
// DB facts of newly linked songs
|
||||
const fresh = await apiCall<{ db: Record<number, DbInfo> }>('GET', `/api/admin/quizzes/${id}`);
|
||||
setDb(fresh.db);
|
||||
return true;
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error');
|
||||
return false;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [draft, id]);
|
||||
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 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>}
|
||||
<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 }}>
|
||||
만든 사람 {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" disabled title="곧 추가돼요">
|
||||
🔗 플레이리스트 가져오기 (준비 중)
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" onClick={() => setParams({})}>
|
||||
✋ 직접 하나씩 추가
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tab === 'songs' ? (
|
||||
<SongsTab items={draft.items} db={db} settings={draft.settings} onItems={(items) => set({ items })} />
|
||||
) : (
|
||||
<SettingsTab 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({ items, db, settings, onItems }: { items: DraftItem[]; db: Record<number, DbInfo>; settings: QuizSettings; onItems: (items: DraftItem[]) => 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'>) => {
|
||||
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() };
|
||||
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 }}>
|
||||
<AddSong onAdd={add} />
|
||||
{items.length === 0 ? (
|
||||
<p className="muted">아직 곡이 없어요. 위에서 제목·가수로 찾거나 유튜브 주소를 붙여 넣어 추가해 주세요.</p>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="data-table quiz-songs">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ width: 28 }} aria-label="순서 옮기기" />
|
||||
<th style={{ width: 44 }}>번호</th>
|
||||
<th>노래</th>
|
||||
<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.songId && <span className="badge" style={{ marginLeft: 6 }}>DB에 없음</span>}
|
||||
</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>
|
||||
<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}
|
||||
item={selected}
|
||||
index={items.indexOf(selected)}
|
||||
total={items.length}
|
||||
db={selected.songId ? (db[selected.songId] ?? null) : 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)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AddSong({ onAdd }: { onAdd: (it: Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'auto' | 'startSec' | 'highlightSec'>) => boolean }) {
|
||||
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>
|
||||
)}
|
||||
</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: Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'auto' | 'startSec' | 'highlightSec'>) => 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>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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>
|
||||
);
|
||||
}
|
||||
|
||||
function ItemPanel({
|
||||
item,
|
||||
index,
|
||||
total,
|
||||
db,
|
||||
defaultStartAt,
|
||||
onPatch,
|
||||
onMove,
|
||||
onRemove,
|
||||
onClose,
|
||||
isDuplicate,
|
||||
}: {
|
||||
item: DraftItem;
|
||||
index: number;
|
||||
total: number;
|
||||
db: DbInfo | null;
|
||||
defaultStartAt: 'start' | 'highlight';
|
||||
onPatch: (p: Partial<QuizItem>) => void;
|
||||
onMove: (to: number) => void;
|
||||
onRemove: () => void;
|
||||
onClose: () => void;
|
||||
isDuplicate: (videoId: string) => boolean;
|
||||
}) {
|
||||
const [url, setUrl] = useState('');
|
||||
const [pos, setPos] = useState(String(index + 1));
|
||||
useEffect(() => setPos(String(index + 1)), [index]);
|
||||
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 && db.videoId === item.videoId ? db.highlightSec : null}
|
||||
defaultStartAt={defaultStartAt}
|
||||
onChange={onPatch}
|
||||
/>
|
||||
<label className="field">
|
||||
제목 (정답)
|
||||
<input className="input" value={item.title} maxLength={200} onChange={(e) => onPatch({ title: e.target.value })} />
|
||||
</label>
|
||||
<label className="field">
|
||||
가수
|
||||
<input className="input" value={item.artist} maxLength={200} onChange={(e) => onPatch({ artist: e.target.value })} />
|
||||
</label>
|
||||
<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.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({ draft, onChange, onDelete }: { draft: Draft; onChange: (p: Partial<Draft>) => void; onDelete: () => void }) {
|
||||
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>
|
||||
<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>
|
||||
<Section title="듣고맞출시간">
|
||||
<Seg label="듣고맞출시간" value={s.listenSec} disabled={false} onChange={(listenSec) => setS({ listenSec })} options={LISTEN_SECS.map((v) => ({ v, label: listenLabel(v) }))} />
|
||||
</Section>
|
||||
<PlayRules c={s} ro={false} listening onPatch={(p) => setS(p as Partial<QuizSettings>)} />
|
||||
<section className="sec">
|
||||
<button type="button" className="btn btn-danger btn-sm" onClick={onDelete}>
|
||||
퀴즈 지우기
|
||||
</button>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user