퀴즈 편집 수정: 저장 중에 바꾼 내용이 응답으로 덮여 사라지고 '저장됨'으로 보이던 것(보낸 내용과 지금 내용이 다르면 지금 내용을 두고 새 곡 id만 붙임, 저장 안 됨 유지). 새로 추가한 서버 DB 곡의 하이라이트가 DB 값 대신 곡 길이 30%로 보이고 자동을 끄면 그 값으로 굳던 것(추가 즉시 /quizzes/pick/songs로 DB 정보를 받고, 받기 전엔 자동 스위치·표시 이동 잠금). e2e/quiz.e2e.ts로 두 경로 회귀 확인

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-22 13:26:10 +09:00
parent a0907b551b
commit e44df482a6
6 changed files with 202 additions and 34 deletions

View File

@@ -42,8 +42,8 @@ export function PositionEditor({
}: Positions & {
videoId: string;
durationSec: number | null;
/** The server DB highlight of this video (유튜브 "가장 많이 다시 본 구간"), used while 자동. */
dbHighlightSec: number | null;
/** The server DB highlight of this video (유튜브 "가장 많이 다시 본 구간"), used while 자동; undefined while it loads. */
dbHighlightSec: number | null | undefined;
defaultStartAt: 'start' | 'highlight';
onChange: (p: Positions) => void;
}) {
@@ -138,7 +138,8 @@ export function PositionEditor({
const length = dur || durationSec || 0;
const autoStart = 0;
const autoHighlight = dbHighlightSec ?? (length ? Math.round(length * 0.3) : null);
const dbLoading = dbHighlightSec === undefined;
const autoHighlight = dbLoading ? null : (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)));
@@ -148,6 +149,8 @@ export function PositionEditor({
};
/** Manual positions from now on: both markers keep where they are, the moved one changes. */
const setMarker = (which: 'start' | 'highlight', sec: number) => {
// 자동 → 직접 needs the DB highlight first, or the other marker would be fixed at a guess
if (dbLoading && auto) return;
const s = Math.round(Math.min(Math.max(0, sec), length || sec) * 10) / 10;
onChange({
auto: false,
@@ -207,6 +210,7 @@ export function PositionEditor({
type="button"
className={`toggle ${auto ? 'on' : ''}`}
aria-pressed={auto}
disabled={dbLoading}
onClick={() =>
onChange(auto ? { auto: false, startSec: 0, highlightSec: autoHighlight } : { auto: true, startSec: null, highlightSec: null })
}
@@ -271,7 +275,9 @@ export function PositionEditor({
/>
</div>
<p className="muted small">
{auto
{dbLoading
? '서버 DB 하이라이트를 불러오는 중이에요…'
: auto
? `자동: 처음은 0초, 하이라이트는 ${dbHighlightSec != null ? '서버 DB 값' : '아직 서버 DB 값이 없어 곡 길이의 30% 지점'}이에요. 표시를 옮기면 자동이 꺼져요.`
: '표시를 끌거나 "지금 위치로"를 눌러 정해요. 재생바를 누르면 그 위치로 이동해요.'}
</p>

View File

@@ -144,7 +144,7 @@ export function QuizEditor() {
const nav = useNavigate();
const [saved, setSaved] = useState<string>('');
const [draft, setDraft] = useState<Draft | null>(null);
const [db, setDb] = useState<Record<number, DbInfo>>({});
const [db, setDb] = useState<Record<number, DbInfo | null>>({});
const [tab, setTab] = useState<'songs' | 'settings'>('songs');
const [busy, setBusy] = useState(false);
const [leaveTo, setLeaveTo] = useState<string | null>(null);
@@ -169,21 +169,28 @@ export function QuizEditor() {
const dirtyRef = useRef(dirty);
dirtyRef.current = dirty;
const draftRef = useRef(draft);
draftRef.current = draft;
const save = useCallback(async (): Promise<boolean> => {
if (!draft) return false;
const sent = draftRef.current;
if (!sent) return false;
const sentJson = JSON.stringify(payload(sent));
setBusy(true);
try {
const r = await apiCall<{ quiz: QuizDetail; reviews: { pending: number } }>('PUT', `/api/admin/quizzes/${id}`, payload(draft));
// keep the client keys (selection) of items that were already there, in order
const r = await apiCall<{ quiz: QuizDetail; reviews: { pending: number } }>('PUT', `/api/admin/quizzes/${id}`, JSON.parse(sentJson));
// what the server keeps, with the client keys (selection) of the items as sent (same order)
const d = toDraft(r.quiz);
d.items = d.items.map((it, i) => ({ ...it, key: draft.items[i]?.key ?? it.key }));
setDraft(d);
d.items = d.items.map((it, i) => ({ ...it, key: sent.items[i]?.key ?? it.key }));
setSaved(JSON.stringify(payload(d)));
// edits made while the request was on its way stay (and stay unsaved); new items get their ids
const now = draftRef.current;
if (!now || JSON.stringify(payload(now)) === sentJson) setDraft(d);
else {
const ids = new Map(d.items.map((it) => [it.key, it.id]));
setDraft({ ...now, items: now.items.map((it) => (it.id || !ids.has(it.key) ? it : { ...it, id: ids.get(it.key) })) });
}
toast(r.reviews.pending ? `저장했어요. 서버 DB에 없거나 다른 곡 ${r.reviews.pending}곡이 관리자 검토 대기에 있어요.` : '저장했어요.');
useReviewCount.getState().refresh();
// 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');
@@ -191,7 +198,20 @@ export function QuizEditor() {
} finally {
setBusy(false);
}
}, [draft, id]);
}, [id]);
// DB facts (aliases, the DB highlight for 자동) of songs added since loading: fetched as soon as they appear
const asked = useRef(new Set<number>());
useEffect(() => {
if (!draft) return;
const missing = [...new Set(draft.items.map((i) => i.songId).filter((x): x is number => !!x && !(x in db) && !asked.current.has(x)))];
if (!missing.length) return;
for (const x of missing) asked.current.add(x);
apiCall<{ db: Record<number, DbInfo> }>('GET', `/api/admin/quizzes/pick/songs?ids=${missing.join(',')}`)
.then((r) => setDb((cur) => ({ ...cur, ...Object.fromEntries(missing.map((x) => [x, r.db[x] ?? null])) })))
.catch(() => {
for (const x of missing) asked.current.delete(x);
});
}, [draft, db]);
const saveRef = useRef(save);
saveRef.current = save;
@@ -388,7 +408,7 @@ function SongsTab({
setImportOpen,
}: {
items: DraftItem[];
db: Record<number, DbInfo>;
db: Record<number, DbInfo | null>;
settings: QuizSettings;
onItems: (items: DraftItem[]) => void;
importOpen: boolean;
@@ -528,7 +548,7 @@ function SongsTab({
item={selected}
index={items.indexOf(selected)}
total={items.length}
db={selected.songId ? (db[selected.songId] ?? null) : null}
db={selected.songId ? db[selected.songId] : null}
defaultStartAt={settings.startAt}
onPatch={(p) => patch(selected.key, p)}
onMove={(to) => move(items.indexOf(selected), to)}
@@ -936,7 +956,8 @@ function ItemPanel({
item: DraftItem;
index: number;
total: number;
db: DbInfo | null;
/** undefined: still loading the DB facts of the linked song. */
db: DbInfo | null | undefined;
defaultStartAt: 'start' | 'highlight';
onPatch: (p: Partial<QuizItem>) => void;
onMove: (to: number) => void;
@@ -973,7 +994,7 @@ function ItemPanel({
auto={item.auto}
startSec={item.startSec}
highlightSec={item.highlightSec}
dbHighlightSec={db && db.videoId === item.videoId ? db.highlightSec : null}
dbHighlightSec={db === undefined ? undefined : db && db.videoId === item.videoId ? db.highlightSec : null}
defaultStartAt={defaultStartAt}
onChange={onPatch}
/>