제작된 퀴즈 1~3단계: 관리자 → 퀴즈(목록·추가·곡 목록: 서버 DB/유튜브 검색·주소로 추가, 끌어서·▲▼·번호로 순서, 복수정답은 연결된 DB 곡 별칭에도, 영상 바꾸기 / 설정: 설명·공개방식(비공개·일부공개·전체공개)·문제 순서·재생위치 기본·방 규칙). 저장은 버튼·Ctrl+S로만, 안 저장 시 탭 제목·표시·나가기 확인. 곡마다 처음·하이라이트 위치 편집기(영상+큰 재생바, 끌기·지금 위치로·여기서 듣기·±1초, 자동=0초+DB 하이라이트, 연령제한은 받아 둔 음원). 방 설정 '직접 선택 / 제작된 퀴즈'(검색·비공개/일부공개 먼저), 고르면 퀴즈 설정이 방 설정으로, 듣고맞추기·곡 전부, 곡별 위치로 재생, 플레이 수. 퀴즈당 곡 수·계정당 퀴즈 수 제한(사이트 설정, 기본 무제한). '퀴즈 저장·불러오기'는 '진행 저장·불러오기'로 이름 변경
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -59,7 +59,7 @@ export function NicknameForm({ onDone }: { onDone?: () => void }) {
|
||||
export function GuestWarning() {
|
||||
return (
|
||||
<p className="guest-warning small" role="note">
|
||||
게스트는 사이트에 들어오지 않은 채 하루가 지나면 계정이 지워져요. 퀴즈 저장은 디스코드 로그인 계정만 할 수 있어요.
|
||||
게스트는 사이트에 들어오지 않은 채 하루가 지나면 계정이 지워져요. 진행 저장은 디스코드 로그인 계정만 할 수 있어요.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
VOTE_RULES,
|
||||
listenLabel,
|
||||
voteLabel,
|
||||
type QuizSummary,
|
||||
type RoomConfig,
|
||||
type VoteRule,
|
||||
} from '@mq/shared/lite';
|
||||
@@ -26,7 +27,7 @@ export interface CatalogMeta {
|
||||
|
||||
type Patch = Partial<RoomConfig>;
|
||||
|
||||
function Seg<T extends string | number>({ value, options, onChange, disabled, label }: { value: T; options: { v: T; label: ReactNode }[]; onChange: (v: T) => void; disabled: boolean; label: string }) {
|
||||
export function Seg<T extends string | number>({ value, options, onChange, disabled, label }: { value: T; options: { v: T; label: ReactNode }[]; onChange: (v: T) => void; disabled: boolean; label: string }) {
|
||||
return (
|
||||
<div className="seg" role="radiogroup" aria-label={label}>
|
||||
{options.map((o) => (
|
||||
@@ -38,7 +39,7 @@ function Seg<T extends string | number>({ value, options, onChange, disabled, la
|
||||
);
|
||||
}
|
||||
|
||||
function Section({ title, children, tip }: { title: string; children: ReactNode; tip?: string }) {
|
||||
export function Section({ title, children, tip }: { title: string; children: ReactNode; tip?: string }) {
|
||||
return (
|
||||
<section className="sec">
|
||||
<div className="label">
|
||||
@@ -214,9 +215,17 @@ export function RoomSettings({
|
||||
hasPassword,
|
||||
onPatch,
|
||||
onPassword,
|
||||
allowQuiz = true,
|
||||
picking: pickingProp,
|
||||
onPicking,
|
||||
}: {
|
||||
config: RoomConfig;
|
||||
editable: boolean;
|
||||
/** 제작된 퀴즈 / 직접 선택 (off on the admin's 새 방 기본값 page). */
|
||||
allowQuiz?: boolean;
|
||||
/** 제작된 퀴즈 chosen but no quiz picked yet (kept by the room page so 게임 시작 waits for a quiz). */
|
||||
picking?: boolean;
|
||||
onPicking?: (on: boolean) => void;
|
||||
meta: CatalogMeta | null;
|
||||
artists: { id: number; name: string }[];
|
||||
pool: { playable: number; total: number };
|
||||
@@ -235,8 +244,16 @@ export function RoomSettings({
|
||||
['테마', 'theme'],
|
||||
];
|
||||
const toggleGenre = (id: string) => onPatch({ genres: c.genres.includes(id) ? c.genres.filter((g) => g !== id) : [...c.genres, id] });
|
||||
const vote = (rules: readonly VoteRule[]) => rules.map((v) => ({ v, label: voteLabel(v) }));
|
||||
const listening = c.mode !== 'lyrics';
|
||||
// 제작된 퀴즈 chosen but no quiz picked yet: only on this screen until a quiz is picked
|
||||
const [pickingOwn, setPickingOwn] = useState(false);
|
||||
const picking = pickingProp ?? pickingOwn;
|
||||
const setPicking = onPicking ?? setPickingOwn;
|
||||
useEffect(() => {
|
||||
if (c.quizId) setPicking(false);
|
||||
}, [c.quizId]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const source: 'pick' | 'quiz' = c.quizId || picking ? 'quiz' : 'pick';
|
||||
const quiz = source === 'quiz';
|
||||
return (
|
||||
<div className="settings card ink">
|
||||
<div className="hd">
|
||||
@@ -258,8 +275,38 @@ export function RoomSettings({
|
||||
aria-label="방 이름"
|
||||
/>
|
||||
</Section>
|
||||
{allowQuiz && (
|
||||
<Section title="문제 고르기">
|
||||
<Seg
|
||||
label="문제 고르기"
|
||||
value={source}
|
||||
disabled={ro}
|
||||
onChange={(v) => {
|
||||
if (v === 'pick') {
|
||||
setPicking(false);
|
||||
if (c.quizId) onPatch({ quizId: null });
|
||||
} else {
|
||||
setPicking(true);
|
||||
if (c.mode !== 'listen') onPatch({ mode: 'listen' });
|
||||
}
|
||||
}}
|
||||
options={[
|
||||
{ v: 'pick', label: '🎛 직접 선택' },
|
||||
{ v: 'quiz', label: '📋 제작된 퀴즈' },
|
||||
]}
|
||||
/>
|
||||
{quiz && <QuizPicker chosen={c.quizId ? { id: c.quizId, name: c.quizName } : null} songs={pool.playable} ro={ro} onPick={(quizId) => onPatch({ quizId })} />}
|
||||
</Section>
|
||||
)}
|
||||
<Section title="모드">
|
||||
<Seg label="모드" value={c.mode} disabled={ro} onChange={(mode) => onPatch({ mode })} options={MODES.map((m) => ({ v: m.id, label: `${m.icon} ${m.label}` }))} />
|
||||
<Seg
|
||||
label="모드"
|
||||
value={c.mode}
|
||||
disabled={ro || quiz}
|
||||
onChange={(mode) => onPatch({ mode })}
|
||||
options={MODES.map((m) => ({ v: m.id, label: `${m.icon} ${m.label}` }))}
|
||||
/>
|
||||
{quiz && <p className="muted small" style={{ marginTop: 6 }}>제작된 퀴즈는 듣고맞추기로만 할 수 있어요.</p>}
|
||||
<div className="subbox">
|
||||
{listening ? (
|
||||
<>
|
||||
@@ -295,6 +342,8 @@ export function RoomSettings({
|
||||
)}
|
||||
</div>
|
||||
</Section>
|
||||
{!quiz && (
|
||||
<>
|
||||
<Section title="장르 · 여러 개 선택 가능">
|
||||
<div className="chipgroup">
|
||||
<span className="g">전체</span>
|
||||
@@ -343,73 +392,24 @@ export function RoomSettings({
|
||||
</span>
|
||||
</div>
|
||||
</Section>
|
||||
<Section title="정답방식">
|
||||
<Seg
|
||||
label="정답방식"
|
||||
value={c.answer}
|
||||
disabled={ro}
|
||||
onChange={(answer) => onPatch({ answer })}
|
||||
options={[
|
||||
{ v: 'title', label: '제목만' },
|
||||
{ v: 'artist', label: '가수만' },
|
||||
{ v: 'both', label: '제목+가수 (순서 무관)' },
|
||||
]}
|
||||
/>
|
||||
</Section>
|
||||
<Section title="정답인식 · 켜면 그 요소까지 똑같이 쳐야 정답">
|
||||
<div className="row">
|
||||
{(
|
||||
[
|
||||
['space', '띄어쓰기'],
|
||||
['number', '숫자'],
|
||||
['symbol', '특수문자'],
|
||||
] as const
|
||||
).map(([k, label]) => (
|
||||
<button key={k} type="button" className={`toggle ${c.strict[k] ? 'on' : ''}`} aria-pressed={c.strict[k]} disabled={ro} onClick={() => onPatch({ strict: { ...c.strict, [k]: !c.strict[k] } })}>
|
||||
<i aria-hidden />
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
<Section title="힌트공개">
|
||||
<Seg
|
||||
label="힌트공개"
|
||||
value={c.hint}
|
||||
disabled={ro}
|
||||
onChange={(hint) => onPatch({ hint })}
|
||||
options={[{ v: 'none' as const, label: '없음' }, ...HINT_TIMES.map((v) => ({ v, label: `${v}초` })), { v: 'manual' as const, label: '직접선택' }]}
|
||||
/>
|
||||
{c.hint === 'manual' && (
|
||||
<div className="subbox">
|
||||
<div className="label">힌트인원(이상)</div>
|
||||
<Seg label="힌트인원" value={c.hintVotes} disabled={ro} onChange={(hintVotes) => onPatch({ hintVotes: hintVotes as RoomConfig['hintVotes'] })} options={vote(VOTE_RULES.filter((v) => v !== 'none'))} />
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
<Section title="스킵인원(이상)" tip="이번문제 스킵을 위해 스킵을 눌러야하는 인원 설정">
|
||||
<Seg label="스킵인원" value={c.skipVotes} disabled={ro} onChange={(skipVotes) => onPatch({ skipVotes })} options={vote(VOTE_RULES)} />
|
||||
</Section>
|
||||
{listening && (
|
||||
<Section title="다시듣기인원(이상)" tip="이번문제를 모두 같이 다시 들으려면 다시듣기를 눌러야하는 인원 설정">
|
||||
<Seg label="다시듣기인원" value={c.replayVotes} disabled={ro} onChange={(replayVotes) => onPatch({ replayVotes })} options={vote(VOTE_RULES)} />
|
||||
</>
|
||||
)}
|
||||
<PlayRules c={c} ro={ro} listening={listening} onPatch={onPatch} />
|
||||
{quiz ? (
|
||||
<Section title="문제 수">
|
||||
<p className="small" style={{ margin: 0 }}>{c.quizId ? `퀴즈에 든 곡 전부 (${pool.playable.toLocaleString()}문제)` : '퀴즈를 고르면 그 퀴즈의 곡 전부가 나와요'}</p>
|
||||
</Section>
|
||||
) : (
|
||||
<Section title="문제 수">
|
||||
<Seg
|
||||
label="문제 수"
|
||||
value={c.count}
|
||||
disabled={ro}
|
||||
onChange={(count) => onPatch({ count })}
|
||||
options={COUNTS.map((v) => ({ v, label: v ? String(v) : `무제한(${pool.playable.toLocaleString()})` }))}
|
||||
/>
|
||||
</Section>
|
||||
)}
|
||||
<Section title="다음 문제까지" tip="정답을 공개한 뒤 다음 문제로 넘어가기까지 기다리는 시간. 그동안 노래는 계속 나와요">
|
||||
<Seg label="다음 문제까지" value={c.revealSec} disabled={ro} onChange={(revealSec) => onPatch({ revealSec })} options={REVEAL_SECS.map((v) => ({ v, label: `${v}초` }))} />
|
||||
</Section>
|
||||
<Section title="다음문제인원(이상)" tip="정답 공개 중에 바로 다음 문제로 넘어가려면 다음 문제를 눌러야하는 인원 설정">
|
||||
<Seg label="다음문제인원" value={c.nextVotes} disabled={ro} onChange={(nextVotes) => onPatch({ nextVotes })} options={vote(VOTE_RULES)} />
|
||||
</Section>
|
||||
<Section title="문제 수">
|
||||
<Seg
|
||||
label="문제 수"
|
||||
value={c.count}
|
||||
disabled={ro}
|
||||
onChange={(count) => onPatch({ count })}
|
||||
options={COUNTS.map((v) => ({ v, label: v ? String(v) : `무제한(${pool.playable.toLocaleString()})` }))}
|
||||
/>
|
||||
</Section>
|
||||
<Section title="방 공개">
|
||||
<Seg
|
||||
label="방 공개"
|
||||
@@ -453,3 +453,141 @@ function GenreRow({ label, children }: { label: string; children: ReactNode }) {
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** 정답방식 … 다음문제인원: the rules a room plays by; also the defaults of a 제작된 퀴즈 (관리자 → 퀴즈 → 설정). */
|
||||
export function PlayRules({
|
||||
c,
|
||||
ro,
|
||||
listening,
|
||||
onPatch,
|
||||
}: {
|
||||
c: Pick<RoomConfig, 'answer' | 'strict' | 'hint' | 'hintVotes' | 'skipVotes' | 'replayVotes' | 'revealSec' | 'nextVotes'>;
|
||||
ro: boolean;
|
||||
listening: boolean;
|
||||
onPatch: (p: Patch) => void;
|
||||
}) {
|
||||
const vote = (rules: readonly VoteRule[]) => rules.map((v) => ({ v, label: voteLabel(v) }));
|
||||
return (
|
||||
<>
|
||||
<Section title="정답방식">
|
||||
<Seg
|
||||
label="정답방식"
|
||||
value={c.answer}
|
||||
disabled={ro}
|
||||
onChange={(answer) => onPatch({ answer })}
|
||||
options={[
|
||||
{ v: 'title', label: '제목만' },
|
||||
{ v: 'artist', label: '가수만' },
|
||||
{ v: 'both', label: '제목+가수 (순서 무관)' },
|
||||
]}
|
||||
/>
|
||||
</Section>
|
||||
<Section title="정답인식 · 켜면 그 요소까지 똑같이 쳐야 정답">
|
||||
<div className="row">
|
||||
{(
|
||||
[
|
||||
['space', '띄어쓰기'],
|
||||
['number', '숫자'],
|
||||
['symbol', '특수문자'],
|
||||
] as const
|
||||
).map(([k, label]) => (
|
||||
<button key={k} type="button" className={`toggle ${c.strict[k] ? 'on' : ''}`} aria-pressed={c.strict[k]} disabled={ro} onClick={() => onPatch({ strict: { ...c.strict, [k]: !c.strict[k] } })}>
|
||||
<i aria-hidden />
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
<Section title="힌트공개">
|
||||
<Seg
|
||||
label="힌트공개"
|
||||
value={c.hint}
|
||||
disabled={ro}
|
||||
onChange={(hint) => onPatch({ hint })}
|
||||
options={[{ v: 'none' as const, label: '없음' }, ...HINT_TIMES.map((v) => ({ v, label: `${v}초` })), { v: 'manual' as const, label: '직접선택' }]}
|
||||
/>
|
||||
{c.hint === 'manual' && (
|
||||
<div className="subbox">
|
||||
<div className="label">힌트인원(이상)</div>
|
||||
<Seg label="힌트인원" value={c.hintVotes} disabled={ro} onChange={(hintVotes) => onPatch({ hintVotes: hintVotes as RoomConfig['hintVotes'] })} options={vote(VOTE_RULES.filter((v) => v !== 'none'))} />
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
<Section title="스킵인원(이상)" tip="이번문제 스킵을 위해 스킵을 눌러야하는 인원 설정">
|
||||
<Seg label="스킵인원" value={c.skipVotes} disabled={ro} onChange={(skipVotes) => onPatch({ skipVotes })} options={vote(VOTE_RULES)} />
|
||||
</Section>
|
||||
{listening && (
|
||||
<Section title="다시듣기인원(이상)" tip="이번문제를 모두 같이 다시 들으려면 다시듣기를 눌러야하는 인원 설정">
|
||||
<Seg label="다시듣기인원" value={c.replayVotes} disabled={ro} onChange={(replayVotes) => onPatch({ replayVotes })} options={vote(VOTE_RULES)} />
|
||||
</Section>
|
||||
)}
|
||||
<Section title="다음 문제까지" tip="정답을 공개한 뒤 다음 문제로 넘어가기까지 기다리는 시간. 그동안 노래는 계속 나와요">
|
||||
<Seg label="다음 문제까지" value={c.revealSec} disabled={ro} onChange={(revealSec) => onPatch({ revealSec })} options={REVEAL_SECS.map((v) => ({ v, label: `${v}초` }))} />
|
||||
</Section>
|
||||
<Section title="다음문제인원(이상)" tip="정답 공개 중에 바로 다음 문제로 넘어가려면 다음 문제를 눌러야하는 인원 설정">
|
||||
<Seg label="다음문제인원" value={c.nextVotes} disabled={ro} onChange={(nextVotes) => onPatch({ nextVotes })} options={vote(VOTE_RULES)} />
|
||||
</Section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const VIS: Record<string, string> = { private: '비공개', partial: '일부공개' };
|
||||
|
||||
/** 제작된 퀴즈 list with a search box; not-public quizzes come first, marked. */
|
||||
function QuizPicker({ chosen, songs, ro, onPick }: { chosen: { id: number; name: string } | null; songs: number; ro: boolean; onPick: (id: number) => void }) {
|
||||
const [open, setOpen] = useState(!chosen);
|
||||
const [q, setQ] = useState('');
|
||||
const [list, setList] = useState<QuizSummary[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!open || ro) return;
|
||||
const t = setTimeout(() => {
|
||||
apiCall<{ quizzes: QuizSummary[] }>('GET', `/api/made-quizzes?q=${encodeURIComponent(q.trim())}`)
|
||||
.then((r) => (setList(r.quizzes), setError(null)))
|
||||
.catch((e: Error) => setError(e.message));
|
||||
}, 200);
|
||||
return () => clearTimeout(t);
|
||||
}, [q, open, ro]);
|
||||
useEffect(() => {
|
||||
if (chosen) setOpen(false);
|
||||
}, [chosen?.id]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
return (
|
||||
<div className="subbox stack" style={{ gap: 8 }}>
|
||||
{chosen ? (
|
||||
<div className="row">
|
||||
<span className="grow">
|
||||
<b>📋 {chosen.name}</b> <span className="muted small">· {songs}곡</span>
|
||||
</span>
|
||||
{!ro && (
|
||||
<button type="button" className="btn btn-sm" onClick={() => setOpen(!open)}>
|
||||
{open ? '닫기' : '다른 퀴즈 고르기'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<span className="muted small">{ro ? '방장이 아직 퀴즈를 고르지 않았어요.' : '아래에서 퀴즈를 골라 주세요.'}</span>
|
||||
)}
|
||||
{open && !ro && (
|
||||
<>
|
||||
<input className="input" value={q} onChange={(e) => setQ(e.target.value)} placeholder="퀴즈 이름 검색" aria-label="퀴즈 이름 검색" />
|
||||
{error && <span className="field-error small">{error}</span>}
|
||||
<div className="quiz-pick" role="listbox" aria-label="제작된 퀴즈 목록">
|
||||
{list?.length === 0 && <span className="muted small" style={{ padding: 10 }}>{q.trim() ? '검색 결과가 없어요.' : '고를 수 있는 퀴즈가 없어요.'}</span>}
|
||||
{list?.map((x) => (
|
||||
<button key={x.id} type="button" role="option" aria-selected={chosen?.id === x.id} className="quiz-pick-item" onClick={() => onPick(x.id)}>
|
||||
<span className="row" style={{ gap: 6 }}>
|
||||
{VIS[x.visibility] && <span className="badge warn">{VIS[x.visibility]}</span>}
|
||||
<b>{x.name}</b>
|
||||
</span>
|
||||
{x.description && <span className="muted small clamp2">{x.description}</span>}
|
||||
<span className="muted small">
|
||||
{x.songs}곡 · 만든 사람 {x.ownerName} · 플레이 {x.plays}번
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ export function GameScreen({ room, game }: { room: RoomView; game: GameView }) {
|
||||
: `${game.mode === 'artist' ? '🎤 가수노래' : '🎧 듣고맞추기'} · ${listenLabel(c.listenSec)} · ${c.startAt === 'highlight' ? '하이라이트부터' : '처음부터'}`}
|
||||
</span>
|
||||
<span className="badge dark">정답: {c.answer === 'title' ? '제목만' : c.answer === 'artist' ? '가수만' : '제목+가수'}</span>
|
||||
<span className="badge dark">★{c.level}</span>
|
||||
<span className="badge dark">{c.quizId ? `📋 ${c.quizName}` : `★${c.level}`}</span>
|
||||
<div className="grow" />
|
||||
{voteBtn('hint', '💡', '힌트', 'Ctrl+I')}
|
||||
{reveal ? voteBtn('next', '⏭', '다음 문제', 'Ctrl+K') : voteBtn('skip', '⏭', '스킵', 'Ctrl+K')}
|
||||
@@ -353,9 +353,9 @@ function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-lg"
|
||||
onClick={() => (me.kind === 'member' ? setSave(true) : toast('퀴즈 저장은 디스코드로 로그인하면 쓸 수 있어요.', 'error'))}
|
||||
onClick={() => (me.kind === 'member' ? setSave(true) : toast('진행 저장은 디스코드로 로그인하면 쓸 수 있어요.', 'error'))}
|
||||
>
|
||||
💾 퀴즈 저장
|
||||
💾 진행 저장
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
@@ -380,8 +380,8 @@ function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
|
||||
</ol>
|
||||
</section>
|
||||
{save && (
|
||||
<Sheet label="퀴즈 저장" onClose={() => setSave(false)}>
|
||||
<h2>퀴즈 저장</h2>
|
||||
<Sheet label="진행 저장" onClose={() => setSave(false)}>
|
||||
<h2>진행 저장</h2>
|
||||
<p className="muted small">방 설정, 지금까지 나온 곡, 참가자 점수를 내 계정에 저장해요. 불러오면 나온 곡은 빼고 이어서 할 수 있어요.</p>
|
||||
<form
|
||||
className="stack"
|
||||
|
||||
@@ -32,6 +32,7 @@ export default function RoomPage() {
|
||||
const unlocked = usePlayer((s) => s.unlocked);
|
||||
const [confirmStart, setConfirmStart] = useState(false);
|
||||
const [loadOpen, setLoadOpen] = useState(false);
|
||||
const [quizPicking, setQuizPicking] = useState(false);
|
||||
const [meta, setMeta] = useState<CatalogMeta | null>(null);
|
||||
const [pw, setPw] = useState('');
|
||||
const [confirmLeave, setConfirmLeave] = useState(false);
|
||||
@@ -99,7 +100,8 @@ export default function RoomPage() {
|
||||
const genreName = (id: string) => meta?.genres.find((g) => g.id === id)?.name ?? id;
|
||||
const link = `${location.origin}/r/${room.code}`;
|
||||
const needArtist = c.mode === 'artist' && c.artistIds.length === 0;
|
||||
const short = c.count !== 0 && room.pool.playable < c.count;
|
||||
const needQuiz = quizPicking && !c.quizId;
|
||||
const short = !c.quizId && c.count !== 0 && room.pool.playable < c.count;
|
||||
const start = () => (short && room.pool.playable > 0 ? setConfirmStart(true) : send({ t: 'start' }));
|
||||
const playing = room.status === 'playing' && !!game;
|
||||
|
||||
@@ -179,20 +181,22 @@ export default function RoomPage() {
|
||||
<section className="pool-banner" aria-live="polite">
|
||||
<div className="grow">
|
||||
<h2>
|
||||
조건에 맞는 곡 <span className="mono">{room.pool.playable.toLocaleString()}</span>곡
|
||||
{c.quizId ? '퀴즈 곡' : '조건에 맞는 곡'} <span className="mono">{room.pool.playable.toLocaleString()}</span>곡
|
||||
</h2>
|
||||
<p className="small">{configSummary(c, genreName).join(' · ')} · {c.count ? `${c.count}문제` : '무제한'}</p>
|
||||
<p className="small">{configSummary(c, genreName).join(' · ')} · {c.quizId ? `${room.pool.playable}문제` : c.count ? `${c.count}문제` : '무제한'}</p>
|
||||
{room.pool.total > room.pool.playable && (
|
||||
<p className="small" style={{ opacity: 0.85 }}>
|
||||
원곡 확인 중인 곡 {(room.pool.total - room.pool.playable).toLocaleString()}곡은 확인이 끝나면 나와요
|
||||
</p>
|
||||
)}
|
||||
{needArtist && <p className="small">가수를 1명 이상 골라 주세요.</p>}
|
||||
{needQuiz && <p className="small">방 설정에서 제작된 퀴즈를 골라 주세요.</p>}
|
||||
{!needArtist && short && room.pool.playable > 0 && <p className="small">문제 수보다 곡이 적어서 {room.pool.playable}문제만 나와요.</p>}
|
||||
{!needArtist && room.pool.playable === 0 && room.pool.total === 0 && <p className="small">이 조건에 맞는 곡이 없어요. 장르·연도·난이도를 넓혀 보세요.</p>}
|
||||
{!needArtist && !c.quizId && room.pool.playable === 0 && room.pool.total === 0 && <p className="small">이 조건에 맞는 곡이 없어요. 장르·연도·난이도를 넓혀 보세요.</p>}
|
||||
{!!c.quizId && room.pool.playable === 0 && <p className="small">이 퀴즈에는 아직 곡이 없어요.</p>}
|
||||
</div>
|
||||
{isHost ? (
|
||||
<button className="btn btn-mustard btn-lg" disabled={needArtist || room.pool.playable === 0} onClick={start}>
|
||||
<button className="btn btn-mustard btn-lg" disabled={needArtist || needQuiz || room.pool.playable === 0} onClick={start}>
|
||||
게임 시작
|
||||
</button>
|
||||
) : (
|
||||
@@ -211,8 +215,8 @@ export default function RoomPage() {
|
||||
)}
|
||||
{isHost && (
|
||||
<div className="row">
|
||||
<button type="button" className="btn btn-sm" onClick={() => (me.kind === 'member' ? setLoadOpen(true) : toast('퀴즈 저장·불러오기는 디스코드로 로그인하면 쓸 수 있어요.', 'error'))}>
|
||||
📂 퀴즈 불러오기
|
||||
<button type="button" className="btn btn-sm" onClick={() => (me.kind === 'member' ? setLoadOpen(true) : toast('진행 저장·불러오기는 디스코드로 로그인하면 쓸 수 있어요.', 'error'))}>
|
||||
📂 진행 불러오기
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
@@ -235,6 +239,8 @@ export default function RoomPage() {
|
||||
hasPassword={room.hasPassword}
|
||||
onPatch={patch}
|
||||
onPassword={(value) => send({ t: 'password', value })}
|
||||
picking={quizPicking}
|
||||
onPicking={setQuizPicking}
|
||||
/>
|
||||
</main>
|
||||
)}
|
||||
@@ -282,13 +288,13 @@ function LoadSheet({ onClose }: { onClose: () => void }) {
|
||||
void refresh();
|
||||
}, []);
|
||||
return (
|
||||
<Sheet label="퀴즈 불러오기" onClose={onClose}>
|
||||
<h2>퀴즈 불러오기</h2>
|
||||
<Sheet label="진행 불러오기" onClose={onClose}>
|
||||
<h2>진행 불러오기</h2>
|
||||
<p className="muted small">불러오면 저장할 때의 설정과 점수가 돌아오고, 시작하면 이미 나온 곡은 빼고 이어서 나와요. (계정당 20개)</p>
|
||||
{list === null ? (
|
||||
<p className="muted">불러오는 중…</p>
|
||||
) : list.length === 0 ? (
|
||||
<p className="muted">저장한 퀴즈가 없어요. 게임이 끝난 뒤 결과 화면에서 저장할 수 있어요.</p>
|
||||
<p className="muted">저장한 진행이 없어요. 게임이 끝난 뒤 결과 화면에서 "진행 저장"을 누르면 푼 곡과 점수가 저장돼요.</p>
|
||||
) : (
|
||||
<ul className="saved-list">
|
||||
{list.map((q) => (
|
||||
|
||||
@@ -10,6 +10,7 @@ import { toast } from '../../store/toast';
|
||||
import { ConfirmSheet } from '../../components/ui';
|
||||
import { SongsPage } from './SongsPage';
|
||||
import { YoutubePage } from './YoutubePage';
|
||||
import { QuizEditor, QuizzesPage } from './QuizzesPage';
|
||||
import { ArtistsPage, CollectPage, GenresPage, RoomsPage, StatsPage } from './AdminMore';
|
||||
import { RoomSettings, type CatalogMeta } from '../../components/RoomSettings';
|
||||
import { DEFAULT_ROOM_CONFIG, type RoomConfig } from '@mq/shared/lite';
|
||||
@@ -69,6 +70,8 @@ export default function AdminApp() {
|
||||
<NavLink to="/admin/genres">🏷 장르</NavLink>
|
||||
<NavLink to="/admin/collect">📥 수집</NavLink>
|
||||
<NavLink to="/admin/stats">📈 통계</NavLink>
|
||||
<div className="sep">퀴즈</div>
|
||||
<NavLink to="/admin/quizzes">📋 퀴즈</NavLink>
|
||||
<div className="sep">운영</div>
|
||||
<NavLink to="/admin/rooms">🚪 방</NavLink>
|
||||
<NavLink to="/admin/site">⚙️ 사이트</NavLink>
|
||||
@@ -85,6 +88,8 @@ export default function AdminApp() {
|
||||
<Route path="artists" element={<ArtistsPage />} />
|
||||
<Route path="genres" element={<GenresPage />} />
|
||||
<Route path="stats" element={<StatsPage />} />
|
||||
<Route path="quizzes" element={<QuizzesPage />} />
|
||||
<Route path="quizzes/:id" element={<QuizEditor />} />
|
||||
<Route path="rooms" element={<RoomsPage />} />
|
||||
<Route path="site" element={<SiteSettings />} />
|
||||
{isSuper && <Route path="users" element={<UsersPage />} />}
|
||||
@@ -185,6 +190,8 @@ interface Site {
|
||||
questionLimitSec: number;
|
||||
roomDefaults: Partial<RoomConfig>;
|
||||
roomLocks: string[];
|
||||
quizMaxSongs: number;
|
||||
quizMaxPerUser: number;
|
||||
}
|
||||
|
||||
/** Settings an admin can pin for every room (사이트 → 잠금). */
|
||||
@@ -254,6 +261,19 @@ function SiteSettings() {
|
||||
<input className="input" type="number" min={10} max={600} value={s.questionLimitSec} onChange={(e) => setS({ ...s, questionLimitSec: Number(e.target.value) })} />
|
||||
<span className="muted small">듣고맞출시간이 1초~1분인 방에서 이 시간 안에 아무도 못 맞히면 정답을 공개해요. "끝까지"는 곡이 끝날 때까지예요.</span>
|
||||
</label>
|
||||
<fieldset className="card stack" style={{ margin: 0 }}>
|
||||
<legend style={{ fontWeight: 800, padding: '0 6px' }}>제작된 퀴즈 제한</legend>
|
||||
<div className="form-grid">
|
||||
<label className="field">
|
||||
퀴즈 하나에 넣을 수 있는 곡 수 (0 = 무제한)
|
||||
<input className="input" type="number" min={0} max={5000} value={s.quizMaxSongs} onChange={(e) => setS({ ...s, quizMaxSongs: Math.max(0, Math.round(Number(e.target.value)) || 0) })} />
|
||||
</label>
|
||||
<label className="field">
|
||||
한 계정이 만들 수 있는 퀴즈 수 (0 = 무제한)
|
||||
<input className="input" type="number" min={0} max={1000} value={s.quizMaxPerUser} onChange={(e) => setS({ ...s, quizMaxPerUser: Math.max(0, Math.round(Number(e.target.value)) || 0) })} />
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset className="card stack" style={{ margin: 0 }}>
|
||||
<legend style={{ fontWeight: 800, padding: '0 6px' }}>채팅 도배 방지</legend>
|
||||
<label className="check">
|
||||
@@ -317,6 +337,7 @@ function RoomDefaults({ site, onChange }: { site: Site; onChange: (p: Partial<Si
|
||||
<RoomSettings
|
||||
config={config}
|
||||
editable
|
||||
allowQuiz={false}
|
||||
meta={meta}
|
||||
artists={[]}
|
||||
pool={pool}
|
||||
|
||||
324
apps/web/src/pages/admin/PositionEditor.tsx
Normal file
324
apps/web/src/pages/admin/PositionEditor.tsx
Normal file
@@ -0,0 +1,324 @@
|
||||
/**
|
||||
* 시작·하이라이트 위치 편집 (관리자 → 퀴즈 → 곡): the video with sound and a big seek bar carrying two markers,
|
||||
* [처음] and [하이라이트]. Drag a marker, or move it to where the video is now (지금 위치로); click a marker label to
|
||||
* listen from there. 자동 (default): start at 0 and the server DB highlight; moving a marker turns 자동 off.
|
||||
* 연령제한 videos refuse embedding (error 150): the server's downloaded audio plays instead when it has one.
|
||||
*/
|
||||
import { useEffect, useRef, useState, type PointerEvent as RPointerEvent } from 'react';
|
||||
import { apiCall } from '../../net/api';
|
||||
import { loadYt } from './SongsPage';
|
||||
|
||||
interface Media {
|
||||
play(): void;
|
||||
pause(): void;
|
||||
seek(sec: number): void;
|
||||
time(): number;
|
||||
duration(): number;
|
||||
playing(): boolean;
|
||||
destroy(): void;
|
||||
}
|
||||
|
||||
const fmt = (s: number | null | undefined) => {
|
||||
if (s == null || !Number.isFinite(s)) return '-:--';
|
||||
const t = Math.max(0, s);
|
||||
return `${Math.floor(t / 60)}:${(t % 60).toFixed(1).padStart(4, '0')}`;
|
||||
};
|
||||
|
||||
export interface Positions {
|
||||
auto: boolean;
|
||||
startSec: number | null;
|
||||
highlightSec: number | null;
|
||||
}
|
||||
|
||||
export function PositionEditor({
|
||||
videoId,
|
||||
durationSec,
|
||||
auto,
|
||||
startSec,
|
||||
highlightSec,
|
||||
dbHighlightSec,
|
||||
defaultStartAt,
|
||||
onChange,
|
||||
}: Positions & {
|
||||
videoId: string;
|
||||
durationSec: number | null;
|
||||
/** The server DB highlight of this video (유튜브 "가장 많이 다시 본 구간"), used while 자동. */
|
||||
dbHighlightSec: number | null;
|
||||
defaultStartAt: 'start' | 'highlight';
|
||||
onChange: (p: Positions) => void;
|
||||
}) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
const media = useRef<Media | null>(null);
|
||||
const [now, setNow] = useState(0);
|
||||
const [dur, setDur] = useState<number>(durationSec ?? 0);
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const [mode, setMode] = useState<'video' | 'audio' | 'blocked' | 'loading'>('loading');
|
||||
const bar = useRef<HTMLDivElement>(null);
|
||||
const drag = useRef<'start' | 'highlight' | 'seek' | null>(null);
|
||||
|
||||
// the player: YouTube first, the server's audio file when YouTube refuses (연령제한)
|
||||
useEffect(() => {
|
||||
let dead = false;
|
||||
let timer: ReturnType<typeof setInterval> | null = null;
|
||||
const useAudio = async () => {
|
||||
try {
|
||||
const { src } = await apiCall<{ src: string }>('GET', `/api/admin/quizzes/pick/audio/${videoId}`);
|
||||
if (dead) return;
|
||||
const a = new Audio(src);
|
||||
a.preload = 'auto';
|
||||
a.addEventListener('loadedmetadata', () => setDur(a.duration));
|
||||
a.addEventListener('play', () => setPlaying(true));
|
||||
a.addEventListener('pause', () => setPlaying(false));
|
||||
media.current = {
|
||||
play: () => void a.play(),
|
||||
pause: () => a.pause(),
|
||||
seek: (s) => (a.currentTime = s),
|
||||
time: () => a.currentTime,
|
||||
duration: () => a.duration || 0,
|
||||
playing: () => !a.paused,
|
||||
destroy: () => (a.pause(), a.removeAttribute('src')),
|
||||
};
|
||||
setMode('audio');
|
||||
} catch {
|
||||
if (!dead) setMode('blocked');
|
||||
}
|
||||
};
|
||||
void loadYt().then(() => {
|
||||
if (dead || !host.current) return;
|
||||
const el = document.createElement('div');
|
||||
host.current.replaceChildren(el);
|
||||
const p = new window.YT.Player(el, {
|
||||
videoId,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
playerVars: { rel: 0, playsinline: 1, controls: 1 },
|
||||
events: {
|
||||
onReady: () => {
|
||||
if (dead) return;
|
||||
setMode('video');
|
||||
const d = p.getDuration?.();
|
||||
if (d) setDur(d);
|
||||
},
|
||||
onStateChange: (e: { data: number }) => {
|
||||
setPlaying(e.data === 1);
|
||||
const d = p.getDuration?.();
|
||||
if (d) setDur(d);
|
||||
},
|
||||
onError: (e: { data: number }) => {
|
||||
if (dead) return;
|
||||
if (e.data === 150 || e.data === 101) {
|
||||
p.destroy?.();
|
||||
host.current?.replaceChildren();
|
||||
void useAudio();
|
||||
} else setMode('blocked');
|
||||
},
|
||||
},
|
||||
});
|
||||
media.current = {
|
||||
play: () => p.playVideo?.(),
|
||||
pause: () => p.pauseVideo?.(),
|
||||
seek: (s) => p.seekTo?.(s, true),
|
||||
time: () => p.getCurrentTime?.() ?? 0,
|
||||
duration: () => p.getDuration?.() ?? 0,
|
||||
playing: () => p.getPlayerState?.() === 1,
|
||||
destroy: () => p.destroy?.(),
|
||||
};
|
||||
});
|
||||
timer = setInterval(() => {
|
||||
const m = media.current;
|
||||
if (m && drag.current !== 'seek') setNow(m.time());
|
||||
}, 100);
|
||||
return () => {
|
||||
dead = true;
|
||||
if (timer) clearInterval(timer);
|
||||
media.current?.destroy();
|
||||
media.current = null;
|
||||
};
|
||||
}, [videoId]);
|
||||
|
||||
const length = dur || durationSec || 0;
|
||||
const autoStart = 0;
|
||||
const autoHighlight = dbHighlightSec ?? (length ? Math.round(length * 0.3) : null);
|
||||
const start = auto ? autoStart : (startSec ?? 0);
|
||||
const highlight = auto ? autoHighlight : highlightSec;
|
||||
const pct = (s: number | null) => (s == null || !length ? 0 : Math.min(100, Math.max(0, (s / length) * 100)));
|
||||
const at = (clientX: number) => {
|
||||
const r = bar.current!.getBoundingClientRect();
|
||||
return Math.round(Math.min(1, Math.max(0, (clientX - r.left) / r.width)) * length * 10) / 10;
|
||||
};
|
||||
/** Manual positions from now on: both markers keep where they are, the moved one changes. */
|
||||
const setMarker = (which: 'start' | 'highlight', sec: number) => {
|
||||
const s = Math.round(Math.min(Math.max(0, sec), length || sec) * 10) / 10;
|
||||
onChange({
|
||||
auto: false,
|
||||
startSec: which === 'start' ? s : start,
|
||||
highlightSec: which === 'highlight' ? s : (highlight ?? null),
|
||||
});
|
||||
};
|
||||
const listen = (sec: number) => {
|
||||
const m = media.current;
|
||||
if (!m) return;
|
||||
m.seek(sec);
|
||||
m.play();
|
||||
setNow(sec);
|
||||
};
|
||||
|
||||
const onDown = (e: RPointerEvent<HTMLDivElement>) => {
|
||||
if (!length) return;
|
||||
const t = e.target as HTMLElement;
|
||||
const which = t.dataset.marker as 'start' | 'highlight' | undefined;
|
||||
drag.current = which ?? 'seek';
|
||||
(e.currentTarget as HTMLDivElement).setPointerCapture(e.pointerId);
|
||||
if (!which) {
|
||||
const s = at(e.clientX);
|
||||
setNow(s);
|
||||
media.current?.seek(s);
|
||||
}
|
||||
};
|
||||
const onMove = (e: RPointerEvent<HTMLDivElement>) => {
|
||||
const d = drag.current;
|
||||
if (!d || !length) return;
|
||||
const s = at(e.clientX);
|
||||
if (d === 'seek') {
|
||||
setNow(s);
|
||||
media.current?.seek(s);
|
||||
} else setMarker(d, s);
|
||||
};
|
||||
const onUp = () => {
|
||||
drag.current = null;
|
||||
};
|
||||
const nudge = (which: 'start' | 'highlight', delta: number) => setMarker(which, (which === 'start' ? start : (highlight ?? 0)) + delta);
|
||||
|
||||
return (
|
||||
<div className="pos-editor stack" style={{ gap: 10 }}>
|
||||
<div className={`yt-preview ${mode === 'audio' || mode === 'blocked' ? 'hidden-video' : ''}`} ref={host} aria-label="유튜브 영상" />
|
||||
{mode === 'audio' && <p className="muted small">유튜브가 다른 사이트 재생을 막은 영상(연령제한)이라 서버가 받아 둔 소리만 나와요.</p>}
|
||||
{mode === 'blocked' && <p className="warn-text">이 영상은 다른 사이트에서 재생할 수 없어요(연령제한·퍼가기 금지). 서버에 받아 둔 음원도 없어서 위치를 들어 보며 정할 수 없어요.</p>}
|
||||
<div className="row" style={{ gap: 8 }}>
|
||||
<button type="button" className="btn btn-sm" disabled={mode === 'loading' || mode === 'blocked'} onClick={() => (playing ? media.current?.pause() : media.current?.play())} aria-label={playing ? '일시정지' : '재생'}>
|
||||
{playing ? '⏸' : '▶'}
|
||||
</button>
|
||||
<span className="mono small">
|
||||
{fmt(now)} / {fmt(length || null)}
|
||||
</span>
|
||||
<span className="grow" />
|
||||
<label className="toggle-inline" title="켜면 처음은 0초, 하이라이트는 서버 DB 값(유튜브 '가장 많이 다시 본 구간')">
|
||||
<button
|
||||
type="button"
|
||||
className={`toggle ${auto ? 'on' : ''}`}
|
||||
aria-pressed={auto}
|
||||
onClick={() =>
|
||||
onChange(auto ? { auto: false, startSec: 0, highlightSec: autoHighlight } : { auto: true, startSec: null, highlightSec: null })
|
||||
}
|
||||
>
|
||||
<i aria-hidden />
|
||||
자동
|
||||
</button>
|
||||
</label>
|
||||
</div>
|
||||
<div
|
||||
className={`pos-bar ${auto ? 'auto' : ''}`}
|
||||
ref={bar}
|
||||
onPointerDown={onDown}
|
||||
onPointerMove={onMove}
|
||||
onPointerUp={onUp}
|
||||
onPointerCancel={onUp}
|
||||
role="slider"
|
||||
aria-label="재생 위치"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={Math.round(length)}
|
||||
aria-valuenow={Math.round(now)}
|
||||
tabIndex={0}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
|
||||
const s = Math.max(0, Math.min(length, now + (e.key === 'ArrowRight' ? 5 : -5)));
|
||||
media.current?.seek(s);
|
||||
setNow(s);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="pos-played" style={{ width: `${pct(now)}%` }} />
|
||||
<div className="pos-head" style={{ left: `${pct(now)}%` }} />
|
||||
<div className="pos-marker start" data-marker="start" style={{ left: `${pct(start)}%` }} title={`처음 ${fmt(start)}`}>
|
||||
<span data-marker="start">처음</span>
|
||||
</div>
|
||||
{highlight != null && (
|
||||
<div className="pos-marker hl" data-marker="highlight" style={{ left: `${pct(highlight)}%` }} title={`하이라이트 ${fmt(highlight)}`}>
|
||||
<span data-marker="highlight">하이라이트</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="pos-rows">
|
||||
<MarkerRow
|
||||
label="처음"
|
||||
cls="start"
|
||||
sec={start}
|
||||
on={defaultStartAt === 'start'}
|
||||
onListen={() => listen(start)}
|
||||
onNow={() => setMarker('start', media.current?.time() ?? now)}
|
||||
onNudge={(d) => nudge('start', d)}
|
||||
disabled={mode === 'loading' || mode === 'blocked'}
|
||||
/>
|
||||
<MarkerRow
|
||||
label="하이라이트"
|
||||
cls="hl"
|
||||
sec={highlight}
|
||||
on={defaultStartAt === 'highlight'}
|
||||
onListen={() => highlight != null && listen(highlight)}
|
||||
onNow={() => setMarker('highlight', media.current?.time() ?? now)}
|
||||
onNudge={(d) => nudge('highlight', d)}
|
||||
disabled={mode === 'loading' || mode === 'blocked'}
|
||||
/>
|
||||
</div>
|
||||
<p className="muted small">
|
||||
{auto
|
||||
? `자동: 처음은 0초, 하이라이트는 ${dbHighlightSec != null ? '서버 DB 값' : '아직 서버 DB 값이 없어 곡 길이의 30% 지점'}이에요. 표시를 옮기면 자동이 꺼져요.`
|
||||
: '표시를 끌거나 "지금 위치로"를 눌러 정해요. 재생바를 누르면 그 위치로 이동해요.'}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MarkerRow({
|
||||
label,
|
||||
cls,
|
||||
sec,
|
||||
on,
|
||||
onListen,
|
||||
onNow,
|
||||
onNudge,
|
||||
disabled,
|
||||
}: {
|
||||
label: string;
|
||||
cls: string;
|
||||
sec: number | null;
|
||||
on: boolean;
|
||||
onListen: () => void;
|
||||
onNow: () => void;
|
||||
onNudge: (d: number) => void;
|
||||
disabled: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className="pos-row">
|
||||
<span className={`pos-dot ${cls}`} aria-hidden />
|
||||
<b style={{ minWidth: 76 }}>
|
||||
{label}
|
||||
{on && <span className="muted small"> (기본)</span>}
|
||||
</b>
|
||||
<span className="mono">{fmt(sec)}</span>
|
||||
<span className="grow" />
|
||||
<button type="button" className="btn btn-sm btn-ghost" disabled={disabled} onClick={() => onNudge(-1)} aria-label={`${label} 1초 앞으로`}>
|
||||
−1초
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-ghost" disabled={disabled} onClick={() => onNudge(1)} aria-label={`${label} 1초 뒤로`}>
|
||||
+1초
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm" disabled={disabled || sec == null} onClick={onListen}>
|
||||
▶ 여기서 듣기
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-primary" disabled={disabled} onClick={onNow}>
|
||||
지금 위치로
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -859,7 +859,7 @@ declare global {
|
||||
}
|
||||
|
||||
let ytApi: Promise<void> | null = null;
|
||||
function loadYt(): Promise<void> {
|
||||
export function loadYt(): Promise<void> {
|
||||
ytApi ??= new Promise<void>((resolve) => {
|
||||
if (window.YT?.Player) return resolve();
|
||||
const prev = window.onYouTubeIframeAPIReady;
|
||||
|
||||
@@ -345,7 +345,45 @@ input.input.sm { width: 76px; }
|
||||
.yt-recent li { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; min-width: 0; }
|
||||
.yt-log { max-height: 220px; overflow: auto; margin-top: 6px; }
|
||||
.lyrics { white-space: pre-wrap; font: inherit; font-size: 0.85rem; background: var(--surface-2); padding: 10px; border-radius: 8px; max-height: 260px; overflow: auto; }
|
||||
|
||||
/* 방 설정 → 제작된 퀴즈 */
|
||||
.quiz-pick { display: flex; flex-direction: column; border: 1.5px solid var(--line); border-radius: 10px; max-height: 320px; overflow-y: auto; background: var(--surface); }
|
||||
.quiz-pick-item { display: flex; flex-direction: column; gap: 3px; padding: 9px 12px; border: 0; border-bottom: 1px solid var(--line); background: none; font: inherit; color: var(--text); cursor: pointer; text-align: left; }
|
||||
.quiz-pick-item[aria-selected='true'] { background: var(--primary-soft); }
|
||||
.quiz-pick-item:hover { background: color-mix(in srgb, var(--primary-soft) 60%, transparent); }
|
||||
/* admin quizzes (관리자 → 퀴즈) */
|
||||
.quiz-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 12px; }
|
||||
.quiz-card { display: flex; flex-direction: column; gap: 6px; min-height: 120px; padding: 14px 16px; background: var(--surface); border: 2px solid var(--ink); border-radius: 14px; color: var(--text); text-decoration: none; box-shadow: 3px 3px 0 var(--ink); font: inherit; text-align: left; }
|
||||
.quiz-card:hover { background: var(--primary-soft); }
|
||||
.quiz-card .nm { font-size: 1.05rem; }
|
||||
.quiz-card.add { border-style: dashed; box-shadow: none; }
|
||||
.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; }
|
||||
.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; }
|
||||
.quiz-songs td.drag { cursor: grab; color: var(--text-sub); user-select: none; }
|
||||
.quiz-songs tr.dragging td { opacity: 0.45; }
|
||||
.quiz-songs tr.drop td { box-shadow: inset 0 3px 0 var(--primary); }
|
||||
.video-add { display: grid; grid-template-columns: minmax(0, 320px) 1fr; gap: 14px; align-items: start; }
|
||||
@media (max-width: 800px) { .video-add { grid-template-columns: 1fr; } }
|
||||
.yt-preview.hidden-video { display: none; }
|
||||
.pos-bar { position: relative; height: 54px; margin: 18px 4px 4px; border: 2px solid var(--ink); border-radius: 10px; background: var(--surface-2); cursor: pointer; touch-action: none; }
|
||||
.pos-bar:focus-visible { outline: 3px solid var(--primary); outline-offset: 2px; }
|
||||
.pos-played { position: absolute; left: 0; top: 0; bottom: 0; background: color-mix(in srgb, var(--primary) 22%, transparent); border-radius: 8px 0 0 8px; pointer-events: none; }
|
||||
.pos-head { position: absolute; top: -4px; bottom: -4px; width: 2px; margin-left: -1px; background: var(--ink); pointer-events: none; }
|
||||
.pos-marker { position: absolute; top: -16px; bottom: -2px; width: 4px; margin-left: -2px; border-radius: 2px; cursor: ew-resize; }
|
||||
.pos-marker span { position: absolute; top: -6px; left: 50%; transform: translateX(-50%); white-space: nowrap; font-size: 0.72rem; font-weight: 800; padding: 1px 6px; border-radius: 6px; color: #fff; cursor: ew-resize; }
|
||||
.pos-marker.start, .pos-marker.start span, .pos-dot.start { background: var(--correct); }
|
||||
.pos-marker.hl, .pos-marker.hl span, .pos-dot.hl { background: var(--coral); }
|
||||
.pos-marker.hl span { top: auto; bottom: -20px; }
|
||||
.pos-bar.auto .pos-marker { opacity: 0.55; }
|
||||
.pos-rows { display: flex; flex-direction: column; gap: 6px; margin-top: 14px; }
|
||||
.pos-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
.pos-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; }
|
||||
@media (max-width: 1100px) { .songs-layout.with-panel { grid-template-columns: 1fr; } .song-panel { position: static; max-height: none; } }
|
||||
@media (max-width: 1300px) { .songs-layout.with-panel.quiz { grid-template-columns: 1fr; } }
|
||||
|
||||
/* ---------------------------------------------------------------- toasts */
|
||||
.toasts { position: fixed; left: 50%; bottom: 24px; transform: translateX(-50%); display: flex; flex-direction: column; gap: 8px; z-index: 100; pointer-events: none; }
|
||||
|
||||
Reference in New Issue
Block a user