456 lines
19 KiB
TypeScript
456 lines
19 KiB
TypeScript
/**
|
|
* 방 설정 (docs/04, docs/12): host edits, everyone else sees the same panel read-only.
|
|
* Every change is sent at once as a partial patch; the server validates and broadcasts.
|
|
*/
|
|
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
|
import {
|
|
COUNTS,
|
|
HINT_TIMES,
|
|
LEVELS,
|
|
LISTEN_SECS,
|
|
LYRICS_SECS,
|
|
MODES,
|
|
REVEAL_SECS,
|
|
VOTE_RULES,
|
|
listenLabel,
|
|
voteLabel,
|
|
type RoomConfig,
|
|
type VoteRule,
|
|
} from '@mq/shared/lite';
|
|
import { apiCall } from '../net/api';
|
|
|
|
export interface CatalogMeta {
|
|
genres: { id: string; name: string; grp: 'region' | 'style' | 'theme' }[];
|
|
years: { min: number; max: number };
|
|
}
|
|
|
|
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 }) {
|
|
return (
|
|
<div className="seg" role="radiogroup" aria-label={label}>
|
|
{options.map((o) => (
|
|
<button key={String(o.v)} type="button" role="radio" aria-checked={o.v === value} className={o.v === value ? 'on' : ''} disabled={disabled && o.v !== value} onClick={() => !disabled && onChange(o.v)}>
|
|
{o.label}
|
|
</button>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function Section({ title, children, tip }: { title: string; children: ReactNode; tip?: string }) {
|
|
return (
|
|
<section className="sec">
|
|
<div className="label">
|
|
{title}
|
|
{tip && (
|
|
<span className="info" tabIndex={0} aria-label={tip} data-tip={tip}>
|
|
!
|
|
</span>
|
|
)}
|
|
</div>
|
|
{children}
|
|
</section>
|
|
);
|
|
}
|
|
|
|
const STAR_COLOR = (n: number) => (n <= 3 ? 'var(--star-1)' : n <= 6 ? 'var(--star-2)' : n <= 8 ? 'var(--star-3)' : 'var(--star-4)');
|
|
|
|
function Stars({ level, onChange, disabled }: { level: number; onChange: (n: number) => void; disabled: boolean }) {
|
|
const [hover, setHover] = useState<number | null>(null);
|
|
const shown = hover ?? level;
|
|
const [name, desc] = LEVELS[shown - 1]!;
|
|
return (
|
|
<div className="diff">
|
|
<div className="stars" role="radiogroup" aria-label="난이도" onMouseLeave={() => setHover(null)}>
|
|
{Array.from({ length: 10 }, (_, i) => {
|
|
const n = i + 1;
|
|
const filled = n <= shown;
|
|
return (
|
|
<button
|
|
key={n}
|
|
type="button"
|
|
role="radio"
|
|
aria-checked={n === level}
|
|
aria-label={`${n}단계 ${LEVELS[i]![0]}`}
|
|
className="star-btn"
|
|
disabled={disabled}
|
|
onMouseEnter={() => !disabled && setHover(n)}
|
|
onFocus={() => !disabled && setHover(n)}
|
|
onClick={() => onChange(n)}
|
|
>
|
|
<svg viewBox="0 0 24 24" width="26" height="26" aria-hidden>
|
|
<path
|
|
d="M12 2.6l2.9 6.1 6.6.8-4.9 4.6 1.3 6.6L12 17.4l-5.9 3.3 1.3-6.6-4.9-4.6 6.6-.8z"
|
|
fill={filled ? STAR_COLOR(n) : 'none'}
|
|
stroke={STAR_COLOR(n)}
|
|
strokeWidth="2"
|
|
strokeLinejoin="round"
|
|
/>
|
|
</svg>
|
|
</button>
|
|
);
|
|
})}
|
|
</div>
|
|
<div className="t">
|
|
<b>
|
|
{shown}단계 · {name}
|
|
</b>
|
|
<span>{desc}</span>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** Two-handle year range (docs/04 연도, 참고 이미지 1.png) + 부터/까지 selects + decade chips. */
|
|
function YearRange({ from, to, min, max, onChange, disabled }: { from: number | null; to: number | null; min: number; max: number; onChange: (f: number | null, t: number | null) => void; disabled: boolean }) {
|
|
const f = from ?? min;
|
|
const t = to ?? max;
|
|
const pos = (y: number) => ((y - min) / Math.max(1, max - min)) * 100;
|
|
const years = Array.from({ length: max - min + 1 }, (_, i) => min + i);
|
|
const set = (a: number, b: number) => onChange(a <= min ? null : a, b >= max ? null : b);
|
|
const decades = [1980, 1990, 2000, 2010, 2020].filter((d) => d + 9 >= min && d <= max);
|
|
return (
|
|
<div className="stack" style={{ gap: 10 }}>
|
|
<div className="yr">
|
|
<div className="track" />
|
|
<div className="fill" style={{ left: `${pos(f)}%`, width: `${pos(t) - pos(f)}%` }} />
|
|
<span className="bub dn" style={{ left: `${pos(f)}%` }}>
|
|
{f}
|
|
</span>
|
|
<span className="bub up" style={{ left: `${pos(t)}%` }}>
|
|
{t}
|
|
</span>
|
|
<input type="range" min={min} max={max} value={f} disabled={disabled} aria-label="시작 연도" onChange={(e) => set(Math.min(Number(e.target.value), t), t)} />
|
|
<input type="range" min={min} max={max} value={t} disabled={disabled} aria-label="끝 연도" onChange={(e) => set(f, Math.max(Number(e.target.value), f))} />
|
|
</div>
|
|
<div className="row" style={{ flexWrap: 'nowrap' }}>
|
|
<select className="input year-sel" value={f} disabled={disabled} aria-label="부터" onChange={(e) => set(Number(e.target.value), Math.max(t, Number(e.target.value)))}>
|
|
{years.map((y) => (
|
|
<option key={y} value={y}>
|
|
{y}년부터
|
|
</option>
|
|
))}
|
|
</select>
|
|
<select className="input year-sel" value={t} disabled={disabled} aria-label="까지" onChange={(e) => set(Math.min(f, Number(e.target.value)), Number(e.target.value))}>
|
|
{years.map((y) => (
|
|
<option key={y} value={y}>
|
|
{y}년까지
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
<div className="row">
|
|
<button type="button" className="chip" aria-pressed={from === null && to === null} disabled={disabled} onClick={() => onChange(null, null)}>
|
|
전체
|
|
</button>
|
|
{decades.map((d) => (
|
|
<button key={d} type="button" className="chip" aria-pressed={from === Math.max(d, min) && to === Math.min(d + 9, max)} disabled={disabled} onClick={() => onChange(Math.max(d, min), Math.min(d + 9, max))}>
|
|
{d === 2000 ? '2000년대' : `${String(d).slice(2)}년대`}
|
|
</button>
|
|
))}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** 가수 선택 (docs/04 가수노래): search → add chip; tapping a chip removes it. */
|
|
function ArtistPicker({ selected, onChange, disabled }: { selected: { id: number; name: string }[]; onChange: (ids: number[]) => void; disabled: boolean }) {
|
|
const [q, setQ] = useState('');
|
|
const [hits, setHits] = useState<{ id: number; name: string; songs: number }[]>([]);
|
|
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
useEffect(() => {
|
|
if (timer.current) clearTimeout(timer.current);
|
|
if (!q.trim()) return setHits([]);
|
|
timer.current = setTimeout(() => {
|
|
apiCall<{ artists: { id: number; name: string; songs: number }[] }>('GET', `/api/artists?q=${encodeURIComponent(q.trim())}`)
|
|
.then((r) => setHits(r.artists))
|
|
.catch(() => setHits([]));
|
|
}, 200);
|
|
}, [q]);
|
|
const ids = selected.map((a) => a.id);
|
|
return (
|
|
<div className="stack" style={{ gap: 8 }}>
|
|
<div className="row" aria-label="선택한 가수">
|
|
{selected.length === 0 && <span className="muted small">아직 고른 가수가 없어요 (1명 이상 필요)</span>}
|
|
{selected.map((a) => (
|
|
<button key={a.id} type="button" className="chip x" aria-pressed="true" disabled={disabled} onClick={() => onChange(ids.filter((x) => x !== a.id))} aria-label={`${a.name} 빼기`}>
|
|
{a.name}
|
|
</button>
|
|
))}
|
|
</div>
|
|
{!disabled && (
|
|
<>
|
|
<input className="input" placeholder="가수 이름 검색" value={q} onChange={(e) => setQ(e.target.value)} aria-label="가수 검색" />
|
|
{hits.length > 0 && (
|
|
<div className="artist-hits" role="listbox" aria-label="가수 검색 결과">
|
|
{hits.map((h) => (
|
|
<button
|
|
key={h.id}
|
|
type="button"
|
|
role="option"
|
|
aria-selected={ids.includes(h.id)}
|
|
className="artist-hit"
|
|
onClick={() => onChange(ids.includes(h.id) ? ids.filter((x) => x !== h.id) : [...ids, h.id])}
|
|
>
|
|
<b>{h.name}</b>
|
|
<span className="muted small">{h.songs}곡</span>
|
|
</button>
|
|
))}
|
|
</div>
|
|
)}
|
|
</>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export function RoomSettings({
|
|
config,
|
|
editable,
|
|
meta,
|
|
artists,
|
|
pool,
|
|
hasPassword,
|
|
onPatch,
|
|
onPassword,
|
|
}: {
|
|
config: RoomConfig;
|
|
editable: boolean;
|
|
meta: CatalogMeta | null;
|
|
artists: { id: number; name: string }[];
|
|
pool: { playable: number; total: number };
|
|
hasPassword: boolean;
|
|
onPatch: (p: Patch) => void;
|
|
onPassword: (v: string | null) => void;
|
|
}) {
|
|
const ro = !editable;
|
|
const c = config;
|
|
const [title, setTitle] = useState(c.title);
|
|
const [pw, setPw] = useState('');
|
|
useEffect(() => setTitle(c.title), [c.title]);
|
|
const groups: [string, 'region' | 'style' | 'theme'][] = [
|
|
['지역', 'region'],
|
|
['장르', 'style'],
|
|
['테마', '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';
|
|
return (
|
|
<div className="settings card ink">
|
|
<div className="hd">
|
|
<h2>방 설정</h2>
|
|
<span className="small" style={{ fontWeight: 700 }}>
|
|
{editable ? '바꾸면 바로 모두에게 보여요' : '방장만 바꿀 수 있어요'}
|
|
</span>
|
|
</div>
|
|
<div className="bd">
|
|
<Section title="방 이름">
|
|
<input
|
|
className="input"
|
|
value={title}
|
|
maxLength={40}
|
|
disabled={ro}
|
|
onChange={(e) => setTitle(e.target.value)}
|
|
onBlur={() => title.trim() !== c.title && onPatch({ title: title.trim() })}
|
|
onKeyDown={(e) => e.key === 'Enter' && (e.target as HTMLInputElement).blur()}
|
|
aria-label="방 이름"
|
|
/>
|
|
</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}` }))} />
|
|
<div className="subbox">
|
|
{listening ? (
|
|
<>
|
|
<div>
|
|
<div className="label">듣고맞출시간</div>
|
|
<Seg label="듣고맞출시간" value={c.listenSec} disabled={ro} onChange={(listenSec) => onPatch({ listenSec })} options={LISTEN_SECS.map((v) => ({ v, label: listenLabel(v) }))} />
|
|
</div>
|
|
<div>
|
|
<div className="label">재생위치</div>
|
|
<Seg
|
|
label="재생위치"
|
|
value={c.startAt}
|
|
disabled={ro}
|
|
onChange={(startAt) => onPatch({ startAt })}
|
|
options={[
|
|
{ v: 'start', label: '처음부터' },
|
|
{ v: 'highlight', label: '하이라이트부터' },
|
|
]}
|
|
/>
|
|
</div>
|
|
{c.mode === 'artist' && (
|
|
<div>
|
|
<div className="label">가수 선택</div>
|
|
<ArtistPicker selected={artists} disabled={ro} onChange={(artistIds) => onPatch({ artistIds })} />
|
|
</div>
|
|
)}
|
|
</>
|
|
) : (
|
|
<div>
|
|
<div className="label">보고맞출시간</div>
|
|
<Seg label="보고맞출시간" value={c.lyricsSec} disabled={ro} onChange={(lyricsSec) => onPatch({ lyricsSec })} options={LYRICS_SECS.map((v) => ({ v, label: v ? `${v}초` : '무제한' }))} />
|
|
</div>
|
|
)}
|
|
</div>
|
|
</Section>
|
|
<Section title="장르 · 여러 개 선택 가능">
|
|
<div className="chipgroup">
|
|
<span className="g">전체</span>
|
|
<div className="row">
|
|
<button type="button" className="chip" aria-pressed={c.genres.length === 0} disabled={ro} onClick={() => onPatch({ genres: [] })}>
|
|
전체
|
|
</button>
|
|
</div>
|
|
{groups.map(([label, grp]) => (
|
|
<GenreRow key={grp} label={label}>
|
|
{meta?.genres
|
|
.filter((g) => g.grp === grp)
|
|
.map((g) => (
|
|
<button key={g.id} type="button" className="chip" aria-pressed={c.genres.includes(g.id)} disabled={ro} onClick={() => toggleGenre(g.id)}>
|
|
{g.name}
|
|
</button>
|
|
))}
|
|
</GenreRow>
|
|
))}
|
|
</div>
|
|
<p className="muted small" style={{ marginTop: 6 }}>
|
|
같은 줄은 "또는", 다른 줄끼리는 "그리고"예요. 예) K-POP + 발라드 = 국내 발라드
|
|
</p>
|
|
</Section>
|
|
<Section title="연도">
|
|
{meta && <YearRange from={c.yearFrom} to={c.yearTo} min={meta.years.min} max={meta.years.max} disabled={ro} onChange={(yearFrom, yearTo) => onPatch({ yearFrom, yearTo })} />}
|
|
</Section>
|
|
<Section title="난이도 · 고른 단계의 곡만 나와요">
|
|
<Stars level={c.level} disabled={ro} onChange={(level) => onPatch({ level })} />
|
|
<div className="tiers">
|
|
<span>
|
|
<i style={{ background: 'var(--star-1)' }} />
|
|
1~3 쉬움
|
|
</span>
|
|
<span>
|
|
<i style={{ background: 'var(--star-2)' }} />
|
|
4~6 보통
|
|
</span>
|
|
<span>
|
|
<i style={{ background: 'var(--star-3)' }} />
|
|
7~8 어려움
|
|
</span>
|
|
<span>
|
|
<i style={{ background: 'var(--star-4)' }} />
|
|
9~10 극악
|
|
</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)} />
|
|
</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="방 공개"
|
|
value={c.visibility}
|
|
disabled={ro}
|
|
onChange={(visibility) => onPatch({ visibility })}
|
|
options={[
|
|
{ v: 'public', label: '공개' },
|
|
{ v: 'private', label: '비공개(코드로만)' },
|
|
{ v: 'password', label: '비밀번호' },
|
|
]}
|
|
/>
|
|
{c.visibility === 'password' && editable && (
|
|
<form
|
|
className="row"
|
|
style={{ marginTop: 8 }}
|
|
onSubmit={(e) => {
|
|
e.preventDefault();
|
|
if (pw.trim()) onPassword(pw.trim());
|
|
setPw('');
|
|
}}
|
|
>
|
|
<input className="input grow" style={{ maxWidth: 220 }} placeholder={hasPassword ? '새 비밀번호' : '비밀번호 정하기'} value={pw} maxLength={40} onChange={(e) => setPw(e.target.value)} aria-label="방 비밀번호" />
|
|
<button className="btn btn-sm">{hasPassword ? '바꾸기' : '정하기'}</button>
|
|
{hasPassword ? <span className="badge ok">비밀번호 있음</span> : <span className="field-error small">비밀번호를 정해야 잠겨요</span>}
|
|
</form>
|
|
)}
|
|
{c.visibility === 'password' && !editable && hasPassword && <p className="muted small" style={{ marginTop: 6 }}>🔒 비밀번호로 잠긴 방이에요</p>}
|
|
{c.visibility === 'private' && <p className="muted small" style={{ marginTop: 6 }}>방 목록에 나오지 않아요. 코드나 링크로만 들어올 수 있어요.</p>}
|
|
</Section>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function GenreRow({ label, children }: { label: string; children: ReactNode }) {
|
|
return (
|
|
<>
|
|
<span className="g">{label}</span>
|
|
<div className="row">{children}</div>
|
|
</>
|
|
);
|
|
}
|