4단계 방·대기실: 방 만들기(게스트 포함)·6자리 코드·열린 방 목록(🔒 비밀번호 방), 인원 무제한 대기실(방장·준비·넘기기·내보내기·60초 자리 유지), 방 설정 전체 즉시 반영, 조건에 맞는 곡 N곡 + 원곡 확인 중 곡 수(1분마다 다시 셈), 대기실 채팅, 서버 재시작 안내

- 서버 테스트 49개, 브라우저 e2e(e2e/rooms.e2e.ts, 3명) 11단계
- 사용자 결정(추천안)은 docs/12 "4단계 확인"

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-18 21:07:54 +09:00
parent c018bc5a9d
commit 735ddd0322
24 changed files with 2391 additions and 15 deletions

View File

@@ -0,0 +1,114 @@
/**
* Room chat (docs/06): one-line log, system lines centred, my unconfirmed lines at the bottom.
* Stage 4 uses it in the waiting room; the answer block and "입력 중" come with the game chat (stage 6).
*/
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { CHAT_MAX, type ChatLine } from '@mq/shared/lite';
/** Fixed colour per user (joke-app --name-h). */
function hue(id: string): number {
let h = 0;
for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) >>> 0;
return h % 360;
}
export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: ChatLine[]; pending: { n: string; text: string }[]; meId: string; myName: string; onSend: (text: string) => void }) {
const [text, setText] = useState('');
const [stuck, setStuck] = useState(true);
const [unseen, setUnseen] = useState(false);
const logRef = useRef<HTMLDivElement>(null);
const lastSent = useRef('');
// Changes whenever a line arrives, also once the log is capped at 200 lines.
const tick = `${lines.at(-1)?.seq ?? 0}:${pending.length}`;
// Auto-scroll only while the reader is at the bottom (docs/06 위로 스크롤하면 멈춤).
useLayoutEffect(() => {
const el = logRef.current;
if (!el) return;
if (stuck) el.scrollTop = el.scrollHeight;
else setUnseen(true);
}, [tick]);
useEffect(() => {
if (stuck) setUnseen(false);
}, [stuck]);
const toBottom = () => {
const el = logRef.current;
if (el) el.scrollTop = el.scrollHeight;
setStuck(true);
};
const submit = () => {
const t = text.trim();
if (!t) return;
onSend(t.slice(0, CHAT_MAX));
lastSent.current = t;
setText('');
toBottom();
};
return (
<section className="card chat" aria-label="채팅">
<div
className="chat-log"
ref={logRef}
role="log"
aria-live="polite"
onScroll={(e) => {
const el = e.currentTarget;
setStuck(el.scrollHeight - el.scrollTop - el.clientHeight < 24);
}}
>
{lines.length === 0 && pending.length === 0 && <div className="chat-sys">아직 대화가 없어요. 먼저 인사해 보세요!</div>}
{lines.map((l) =>
l.userId === null ? (
<div key={l.seq} className="chat-sys">
— {l.text} —
</div>
) : (
<div key={l.seq} className={`chat-line ${l.userId === meId ? 'me' : ''}`}>
<b style={{ ['--name-h' as string]: hue(l.userId) }}>{l.nickname}</b>
<span>{l.text}</span>
</div>
),
)}
{pending.map((p) => (
<div key={p.n} className="chat-line me pending" aria-label="보내는 중">
<b style={{ ['--name-h' as string]: hue(meId) }}>{myName}</b>
<span>{p.text}</span>
</div>
))}
</div>
{unseen && !stuck && (
<button type="button" className="btn btn-sm chat-new" onClick={toBottom}>
새 메시지 ↓
</button>
)}
<form
className="chat-input"
onSubmit={(e) => {
e.preventDefault();
submit();
}}
>
<input
className="input"
value={text}
maxLength={CHAT_MAX}
placeholder="메시지 입력 (Enter)"
aria-label="채팅 입력"
onChange={(e) => setText(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Escape') setText('');
else if (e.key === 'ArrowUp' && !text && lastSent.current) {
e.preventDefault();
setText(lastSent.current);
}
}}
/>
<button className="btn btn-primary" disabled={!text.trim()}>
보내기
</button>
</form>
</section>
);
}

View File

@@ -0,0 +1,448 @@
/**
* 방 설정 (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,
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="문제 수">
<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>
</>
);
}

View File

@@ -12,6 +12,7 @@ import { Home } from './pages/Home';
const LoginPage = lazy(() => import('./pages/LoginPage'));
const NotFound = lazy(() => import('./pages/NotFound'));
const AdminApp = lazy(() => import('./pages/admin/AdminApp'));
const RoomPage = lazy(() => import('./pages/RoomPage'));
function Announcement() {
const text = useSession((s) => s.announcement);
@@ -53,6 +54,7 @@ function Shell() {
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/r/:code" element={<RoomPage />} />
<Route path="/admin/*" element={<AdminApp />} />
<Route path="*" element={<NotFound />} />
</Routes>

183
apps/web/src/net/socket.ts Normal file
View File

@@ -0,0 +1,183 @@
/**
* One WebSocket per tab (docs/01): reconnects with backoff, re-joins the room, keeps the server clock offset (docs/12 Q1).
*/
import { create } from 'zustand';
import type { ChatLine, RoomView, ServerMessage } from '@mq/shared/lite';
import { toast } from '../store/toast';
type Status = 'idle' | 'connecting' | 'open' | 'reconnecting';
interface RoomState {
status: Status;
code: string | null;
room: RoomView | null;
/** serverNow ≈ Date.now() + offset */
offset: number;
rtt: number | null;
/** Join failed with this message (wrong password, unknown room…). */
joinError: string | null;
left: null | 'leave' | 'kicked' | 'closed' | 'elsewhere';
/** Room chat in seq order (docs/06), last CHAT_KEEP lines. */
chat: ChatLine[];
/** My lines not confirmed by the server yet: always drawn at the bottom (docs/06 지연 없는 전송). */
pending: { n: string; text: string }[];
}
const CHAT_KEEP = 200;
/** The room this tab was last in: tells "the server restarted and the room is gone" apart from a wrong code. */
const LAST_ROOM_KEY = 'mq:lastRoom';
export const ROOM_GONE_TEXT = '서버가 업데이트되면서 방이 닫혔어요. 방을 새로 만들어 주세요.';
export const useRoom = create<RoomState>(() => ({ status: 'idle', code: null, room: null, offset: 0, rtt: null, joinError: null, left: null, chat: [], pending: [] }));
let ws: WebSocket | null = null;
let retry = 0;
let password: string | undefined;
let pingTimer: ReturnType<typeof setInterval> | null = null;
/** A join is on its way: the next error is the join's answer. */
let joining = false;
let nonce = 0;
function lastRoom(): string | null {
try {
return sessionStorage.getItem(LAST_ROOM_KEY);
} catch {
return null;
}
}
function setLastRoom(code: string | null): void {
try {
if (code) sessionStorage.setItem(LAST_ROOM_KEY, code);
else sessionStorage.removeItem(LAST_ROOM_KEY);
} catch {
/* private mode */
}
}
function sendJoin(code: string): void {
joining = true;
send({ t: 'join', code, password });
}
const samples: { sent: number; received: number; server: number }[] = [];
function send(m: unknown): void {
if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify(m));
}
function syncClock(): void {
for (let i = 0; i < 5; i++) setTimeout(() => send({ t: 'ping', c: Date.now() }), i * 150);
}
function onMessage(m: ServerMessage): void {
switch (m.t) {
case 'welcome': {
useRoom.setState({ status: 'open', offset: m.serverNow - Date.now() });
retry = 0;
syncClock();
const code = useRoom.getState().code;
if (code) sendJoin(code);
return;
}
case 'pong': {
samples.push({ sent: m.c, received: Date.now(), server: m.s });
if (samples.length > 10) samples.shift();
let best: { offset: number; rtt: number } | null = null;
for (const s of samples) {
const rtt = s.received - s.sent;
const offset = s.server - (s.sent + rtt / 2);
if (!best || rtt < best.rtt) best = { offset, rtt };
}
if (best) useRoom.setState({ offset: best.offset, rtt: best.rtt });
return;
}
case 'room':
if (m.room.code === useRoom.getState().code) {
joining = false;
setLastRoom(m.room.code);
useRoom.setState({ room: m.room, joinError: null, left: null });
}
return;
case 'left':
if (m.code === useRoom.getState().code) {
setLastRoom(null);
useRoom.setState({ room: null, left: m.reason, chat: [], pending: [] });
}
return;
case 'chatlog':
// (Re)joined: the server's log is the truth; unconfirmed lines from before a drop are gone.
if (m.code === useRoom.getState().code) useRoom.setState({ chat: m.lines.slice(-CHAT_KEEP), pending: [] });
return;
case 'chat':
if (m.code === useRoom.getState().code) {
const st = useRoom.getState();
useRoom.setState({
chat: [...st.chat, m.line].slice(-CHAT_KEEP),
pending: m.line.n ? st.pending.filter((p) => p.n !== m.line.n) : st.pending,
});
}
return;
case 'notice':
toast(m.text);
return;
case 'error': {
const st = useRoom.getState();
if (joining && st.code) {
joining = false;
// The room was there a moment ago (this tab was in it): the server restarted and rooms live in memory (docs/04 결정 1).
// Kept after that, so a refresh still explains it.
const gone = m.message.includes('찾을 수 없') && lastRoom() === st.code;
useRoom.setState({ room: null, joinError: gone ? ROOM_GONE_TEXT : m.message });
} else toast(m.message, 'error');
return;
}
}
}
function connect(): void {
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
ws = new WebSocket(`${proto}://${location.host}/ws`);
useRoom.setState({ status: retry ? 'reconnecting' : 'connecting' });
ws.onmessage = (e) => onMessage(JSON.parse(String(e.data)) as ServerMessage);
ws.onclose = () => {
ws = null;
if (useRoom.getState().status === 'idle') return;
useRoom.setState({ status: 'reconnecting' });
const wait = Math.min(10_000, 500 * 2 ** retry++);
setTimeout(() => useRoom.getState().status !== 'idle' && connect(), wait);
};
}
export const socket = {
start(): void {
if (ws) return;
connect();
pingTimer ??= setInterval(syncClock, 30_000);
},
stop(): void {
useRoom.setState({ status: 'idle' });
ws?.close();
ws = null;
if (pingTimer) clearInterval(pingTimer);
pingTimer = null;
},
join(code: string, pw?: string): void {
password = pw;
const st = useRoom.getState();
useRoom.setState({ code, room: null, joinError: null, left: null, ...(st.code === code ? {} : { chat: [], pending: [] }) });
socket.start();
sendJoin(code);
},
leave(): void {
send({ t: 'leave' });
setLastRoom(null);
useRoom.setState({ code: null, room: null, chat: [], pending: [] });
},
chat(text: string): void {
const n = `${Date.now().toString(36)}${(nonce++).toString(36)}`;
useRoom.setState((st) => ({ pending: [...st.pending, { n, text }] }));
send({ t: 'chat', text, n });
},
send,
};
/** Server clock (ms) for countdowns and synced playback. */
export const serverNow = () => Date.now() + useRoom.getState().offset;

View File

@@ -1,10 +1,59 @@
/** 첫 화면 (docs/03): 소개 + 방 만들기/코드로 참여, 시작하기, 열린 방 목록. Rooms arrive in stage 4. */
/** 첫 화면 (docs/03): 소개 + 방 만들기/코드로 참여, 시작하기, 열린 방 목록 (docs/11 Q17). */
import { useEffect, useState, type FormEvent } from 'react';
import { useNavigate } from 'react-router';
import { useSession } from '../store/session';
import { LoginBox } from '../components/LoginBox';
import { Avatar } from '../components/ui';
import { apiCall } from '../net/api';
import { toast } from '../store/toast';
interface PublicRoom {
code: string;
title: string;
host: string;
players: number;
status: 'lobby' | 'playing';
hasPassword: boolean;
summary: string[];
pool: number;
}
export function Home() {
const me = useSession((s) => s.me);
const nav = useNavigate();
const [rooms, setRooms] = useState<PublicRoom[] | null>(null);
const [filter, setFilter] = useState<'all' | 'lobby' | 'playing'>('all');
const [joining, setJoining] = useState(false);
const [code, setCode] = useState('');
const [busy, setBusy] = useState(false);
useEffect(() => {
const load = () => void apiCall<{ rooms: PublicRoom[] }>('GET', '/api/rooms').then((r) => setRooms(r.rooms)).catch(() => {});
load();
const t = setInterval(load, 5000);
return () => clearInterval(t);
}, []);
const create = async () => {
if (!me) return toast('먼저 디스코드로 로그인하거나 게스트로 시작해 주세요.', 'error');
setBusy(true);
try {
const r = await apiCall<{ code: string }>('POST', '/api/rooms', {});
nav(`/r/${r.code}`);
} catch (e) {
toast((e as Error).message, 'error');
} finally {
setBusy(false);
}
};
const join = (e: FormEvent) => {
e.preventDefault();
const c = code.replace(/\D/g, '');
if (c.length !== 6) return toast('방 코드는 숫자 6자리예요.', 'error');
nav(`/r/${c}`);
};
const shown = (rooms ?? []).filter((r) => filter === 'all' || r.status === filter);
return (
<main className="page">
<div className="hero">
@@ -17,14 +66,19 @@ export function Home() {
</h1>
<p>방 만들고 링크 하나 보내면 끝. 인원 제한 없이 같이 듣고, 채팅으로 제목을 먼저 치는 사람이 점수를 가져가요.</p>
<div className="acts">
<button className="btn btn-mustard btn-lg" disabled title="방 기능을 준비하고 있어요">
<button className="btn btn-mustard btn-lg" onClick={() => void create()} disabled={busy}>
+ 방 만들기
</button>
<button className="btn btn-lg" disabled title="방 기능을 준비하고 있어요">
<button className="btn btn-lg" onClick={() => setJoining((j) => !j)} aria-expanded={joining}>
코드로 참여
</button>
</div>
<p className="note">방 만들기는 곧 열려요. 지금은 로그인만 먼저 해 볼 수 있어요.</p>
{joining && (
<form className="row code-join" onSubmit={join}>
<input className="input" inputMode="numeric" autoFocus placeholder="방 코드 6자리" value={code} maxLength={7} onChange={(e) => setCode(e.target.value)} aria-label="방 코드" />
<button className="btn btn-mustard">들어가기</button>
</form>
)}
</section>
{me ? (
<section className="login-card" aria-labelledby="me-title">
@@ -42,9 +96,50 @@ export function Home() {
)}
</div>
<div className="rooms-head">
<h2>열린 방 0</h2>
<h2>열린 방 {rooms?.length ?? 0}</h2>
{(
[
['all', '전체'],
['lobby', '대기 중'],
['playing', '진행 중 (중간 참여 가능)'],
] as const
).map(([k, label]) => (
<button key={k} type="button" className="chip" aria-pressed={filter === k} onClick={() => setFilter(k)}>
{label}
</button>
))}
</div>
<div className="empty">아직 열린 방이 없어요.</div>
{rooms && shown.length === 0 ? (
<div className="empty">{rooms.length ? '이 조건의 방이 없어요.' : '아직 열린 방이 없어요. 첫 방을 만들어 보세요!'}</div>
) : (
<div className="rooms">
{shown.map((r) => (
<article key={r.code} className="room-card">
<div className="row" style={{ flexWrap: 'nowrap' }}>
<span className="t grow">{r.title}</span>
{r.status === 'playing' ? <span className="badge live">진행 중</span> : <span className="badge teal">대기</span>}
</div>
<div className="meta">
{r.summary.map((s) => (
<span key={s} className="badge">
{s}
</span>
))}
{r.hasPassword && <span className="badge">🔒 비밀번호</span>}
</div>
<div className="row">
<span className="muted small">
방장 {r.host} · {r.players}명
</span>
<div className="grow" />
<button className="btn btn-sm" onClick={() => nav(`/r/${r.code}`)}>
{r.status === 'playing' ? '중간 참여' : '들어가기'}
</button>
</div>
</article>
))}
</div>
)}
</main>
);
}

View File

@@ -0,0 +1,223 @@
/**
* 대기실 /r/:code (docs/03, docs/04): players, live "조건에 맞는 곡 N곡", settings (host edits, everyone sees it at once).
* Games start in stage 5: the start button is shown but disabled until then.
*/
import { useEffect, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router';
import { configSummary, type RoomConfig } from '@mq/shared/lite';
import { apiCall } from '../net/api';
import { socket, useRoom } from '../net/socket';
import { useSession } from '../store/session';
import { toast } from '../store/toast';
import { Avatar, ConfirmSheet } from '../components/ui';
import { LoginBox } from '../components/LoginBox';
import { RoomSettings, type CatalogMeta } from '../components/RoomSettings';
import { ChatPanel } from '../components/ChatPanel';
const LEFT_TEXT: Record<string, string> = {
kicked: '방장이 방에서 내보냈어요.',
closed: '오래 접속하지 않아 방에서 나갔어요.',
elsewhere: '다른 방에 들어가서 이 방에서는 나갔어요.',
leave: '방에서 나왔어요.',
};
export default function RoomPage() {
const { code = '' } = useParams();
const me = useSession((s) => s.me);
const nav = useNavigate();
const { room, joinError, left, status, chat, pending } = useRoom();
const [meta, setMeta] = useState<CatalogMeta | null>(null);
const [pw, setPw] = useState('');
const [confirmLeave, setConfirmLeave] = useState(false);
useEffect(() => {
void apiCall<CatalogMeta>('GET', '/api/catalog/meta').then(setMeta).catch(() => {});
}, []);
useEffect(() => {
if (!me || !/^\d{6}$/.test(code)) return;
socket.join(code);
}, [me, code]);
useEffect(() => {
if (left && left !== 'leave') {
toast(LEFT_TEXT[left]!, 'error', 5000);
nav('/', { replace: true });
}
}, [left, nav]);
if (!me) {
return (
<main className="page narrow stack">
<h1>방에 들어가려면 먼저 이름을 정해 주세요</h1>
<LoginBox next={`/r/${code}`} />
</main>
);
}
if (!/^\d{6}$/.test(code)) return <JoinError text="방 코드는 숫자 6자리예요." />;
if (!room) {
if (joinError?.includes('비밀번호')) {
return (
<main className="page narrow stack">
<h1>비밀번호가 필요한 방이에요</h1>
<form
className="stack"
onSubmit={(e) => {
e.preventDefault();
socket.join(code, pw);
}}
>
<input className="input" type="password" autoFocus placeholder="방 비밀번호" value={pw} onChange={(e) => setPw(e.target.value)} aria-label="방 비밀번호" />
{joinError.includes('틀렸') && <p className="field-error">{joinError}</p>}
<button className="btn btn-primary">들어가기</button>
</form>
</main>
);
}
if (joinError) return <JoinError text={joinError} />;
return <div className="page muted">{status === 'reconnecting' ? '다시 연결하는 중…' : '방에 들어가는 중…'}</div>;
}
const isHost = room.hostId === me.id;
const c = room.config;
const send = (m: unknown) => socket.send(m);
const patch = (p: Partial<RoomConfig>) => send({ t: 'config', patch: p });
const myReady = room.players.find((p) => p.id === me.id)?.ready ?? false;
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;
return (
<>
<div className="roombar">
<Link to="/" className="btn btn-sm btn-ghost">
← 방 목록
</Link>
<h1 className="room-title">{c.title || '이름 없는 방'}</h1>
<span className="room-code" aria-label={`방 코드 ${room.code}`}>
{room.code.slice(0, 3)} {room.code.slice(3)}
</span>
<button
type="button"
className="btn btn-sm"
onClick={() =>
navigator.clipboard?.writeText(link).then(
() => toast('링크를 복사했어요.'),
() => toast(link, 'info', 6000),
)
}
>
링크 복사
</button>
<div className="grow" />
<span className="badge teal">{room.status === 'lobby' ? '대기 중' : '게임 중'}</span>
<span className="muted small">참가 {room.players.length}명 · 제한 없음</span>
<button type="button" className="btn btn-sm" onClick={() => setConfirmLeave(true)}>
🚪 나가기
</button>
</div>
<main className="room-main">
<div className="stack" style={{ minWidth: 0 }}>
<section className="card">
<div className="row" style={{ marginBottom: 10 }}>
<h2>참가자 {room.players.length}</h2>
<span className="muted small">인원 제한 없음 · 게임 중에도 들어올 수 있어요</span>
</div>
<ul className="players">
{room.players.map((p) => (
<li key={p.id} className={`pl ${p.id === room.hostId ? 'host' : ''} ${p.online ? '' : 'off'}`}>
<Avatar user={p} size={34} />
<span className="name">{p.nickname}</span>
<span className="r">
{p.id === room.hostId ? (
<span title="방장" aria-label="방장">
👑
</span>
) : !p.online ? (
<span className="badge">접속 끊김</span>
) : p.ready ? (
<span className="badge teal">준비</span>
) : (
<span className="badge">대기</span>
)}
</span>
{isHost && p.id !== me.id && (
<span className="pl-actions">
{p.online && (
<button type="button" className="btn btn-sm btn-ghost" onClick={() => send({ t: 'host', userId: p.id })} aria-label={`${p.nickname}에게 방장 넘기기`}>
방장
</button>
)}
<button type="button" className="btn btn-sm btn-ghost" onClick={() => send({ t: 'kick', userId: p.id })} aria-label={`${p.nickname} 내보내기`}>
내보내기
</button>
</span>
)}
</li>
))}
</ul>
</section>
<section className="pool-banner" aria-live="polite">
<div className="grow">
<h2>
조건에 맞는 곡 <span className="mono">{room.pool.playable.toLocaleString()}</span>곡
</h2>
<p className="small">{configSummary(c, genreName).join(' · ')} · {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>}
{!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>}
</div>
{isHost ? (
<button className="btn btn-mustard btn-lg" disabled title="게임 진행은 다음 업데이트에서 열려요">
게임 시작
</button>
) : (
<button className={`btn btn-lg ${myReady ? 'btn-primary' : 'btn-mustard'}`} onClick={() => send({ t: 'ready', on: !myReady })} aria-pressed={myReady}>
{myReady ? '준비 완료 ✓' : '준비'}
</button>
)}
</section>
<ChatPanel lines={chat} pending={pending} meId={me.id} myName={me.nickname} onSend={(t) => socket.chat(t)} />
<p className="muted small">게임 진행(노래 재생·채팅 정답)은 다음 업데이트에서 열려요. 지금은 방을 만들고 설정을 맞추면서 대화할 수 있어요.</p>
</div>
<RoomSettings
config={c}
editable={isHost && room.status === 'lobby'}
meta={meta}
artists={room.artists}
pool={room.pool}
hasPassword={room.hasPassword}
onPatch={patch}
onPassword={(value) => send({ t: 'password', value })}
/>
</main>
{confirmLeave && (
<ConfirmSheet
title="방에서 나갈까요?"
confirm="나가기"
onConfirm={() => {
socket.leave();
nav('/');
}}
onClose={() => setConfirmLeave(false)}
/>
)}
</>
);
}
function JoinError({ text }: { text: string }) {
return (
<main className="page narrow stack">
<h1>방에 들어갈 수 없어요</h1>
<p className="muted">{text}</p>
<Link className="btn" to="/">
방 목록으로
</Link>
</main>
);
}

View File

@@ -191,6 +191,95 @@ textarea.input { padding: 10px 14px; min-height: 90px; resize: vertical; }
.rooms-head { display: flex; align-items: center; gap: 12px; margin: 30px 0 12px; flex-wrap: wrap; }
.empty { border: 2px dashed var(--line); border-radius: 16px; padding: 28px; text-align: center; color: var(--text-sub); font-weight: 650; }
/* home: room cards, code join */
.rooms { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 14px; }
.room-card { background: var(--surface); border: 1.5px solid var(--line); border-radius: 16px; padding: 16px 18px; display: flex; flex-direction: column; gap: 9px; }
.room-card .t { font-weight: 800; font-size: 1.1rem; letter-spacing: -0.02em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.room-card .meta { display: flex; flex-wrap: wrap; gap: 5px; }
.code-join { margin-top: 12px; position: relative; }
.code-join .input { max-width: 200px; border-color: #1e1b18; background: #fffdf8; color: #1e1b18; }
/* room (docs/03 대기실) */
.roombar { display: flex; align-items: center; gap: 12px; padding: 10px 28px; border-bottom: 1.5px solid var(--line); background: var(--surface-2); flex-wrap: wrap; }
.room-title { font-size: 1.25rem; max-width: 40vw; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.room-code { font-weight: 800; letter-spacing: 0.12em; background: var(--surface); border: 2px dashed var(--ink); border-radius: 9px; padding: 3px 10px; font-variant-numeric: tabular-nums; }
.room-main { display: grid; grid-template-columns: minmax(0, 1fr) 560px; gap: 22px; padding: 22px 28px; max-width: 1440px; margin: 0 auto; align-items: start; }
.players { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 8px; }
.pl { display: flex; align-items: center; gap: 9px; padding: 8px 10px; border-radius: 12px; background: var(--surface); border: 1.5px solid var(--line); font-weight: 700; position: relative; min-width: 0; }
.pl .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pl .r { margin-left: auto; flex: none; }
.pl.host { border: 2px solid var(--ink); }
.pl.off { opacity: 0.55; }
.pl-actions { display: none; position: absolute; right: 6px; top: 50%; transform: translateY(-50%); background: var(--surface); border-radius: 8px; box-shadow: 0 0 0 1.5px var(--line); }
.pl:hover .pl-actions, .pl:focus-within .pl-actions { display: flex; }
.pool-banner { display: flex; align-items: center; gap: 16px; background: #1f6f78; color: #fff; border: 2px solid var(--ink); border-radius: 16px; padding: 18px 20px; box-shadow: 4px 4px 0 var(--ink); }
.pool-banner h2 { font-size: 1.3rem; }
.pool-banner .btn:not(.btn-mustard):not(.btn-primary) { color: #1e1b18; }
.settings { padding: 0; overflow: hidden; }
/* chat (docs/06 한 줄 로그; waiting room) */
.chat { display: flex; flex-direction: column; gap: 8px; position: relative; padding: 14px 16px; }
.chat-log { height: 280px; overflow-y: auto; font-size: 0.95rem; line-height: 1.7; overscroll-behavior: contain; }
.chat-line { padding: 0 6px; border-radius: 6px; overflow-wrap: anywhere; }
.chat-line b { font-weight: 800; margin-right: 8px; color: hsl(var(--name-h, 200) 55% 38%); }
.chat-line.me { background: var(--surface-2); }
:root[data-theme='dark'] .chat-line b { color: hsl(var(--name-h, 200) 65% 72%); }
@media (prefers-color-scheme: dark) {
:root[data-theme='auto'] .chat-line b { color: hsl(var(--name-h, 200) 65% 72%); }
}
.chat-line.pending { opacity: 0.55; }
.chat-sys { text-align: center; font-size: 0.8rem; color: var(--text-sub); }
.chat-new { position: absolute; right: 22px; bottom: 70px; box-shadow: 2px 2px 0 var(--ink); }
.chat-input { display: flex; gap: 8px; }
.chat-input .input { flex: 1; }
.settings .hd { display: flex; align-items: center; justify-content: space-between; padding: 14px 20px; border-bottom: 2px solid var(--ink); background: var(--mustard); color: #1e1b18; }
.settings .bd { padding: 4px 20px 18px; }
.sec { padding: 14px 0; border-bottom: 1.5px dashed var(--line); }
.sec:last-child { border-bottom: 0; }
.label { font-size: 0.83rem; font-weight: 700; color: var(--text-sub); margin-bottom: 8px; display: flex; align-items: center; gap: 6px; }
.subbox { margin-top: 10px; background: var(--surface-2); border-radius: 12px; padding: 12px 14px; display: flex; flex-direction: column; gap: 10px; }
.seg { display: flex; border: 2px solid var(--ink); border-radius: 11px; overflow: hidden; background: var(--surface); }
.seg button { flex: 1; min-height: 38px; border: 0; border-right: 1.5px solid var(--ink); background: transparent; font: inherit; font-weight: 700; font-size: 0.88rem; color: var(--ink); padding: 0 6px; cursor: pointer; }
.seg button:last-child { border-right: 0; }
.seg button.on { background: var(--ink); color: var(--surface); }
.seg button:disabled { cursor: default; color: var(--text-sub); }
.seg button.on:disabled { color: var(--surface); }
.chipgroup { display: grid; grid-template-columns: 40px 1fr; gap: 6px 8px; align-items: start; }
.chipgroup .g { font-size: 0.8rem; font-weight: 700; color: var(--text-sub); padding-top: 6px; }
.chip:disabled { cursor: default; }
.chip.x::after { content: '×'; font-weight: 800; opacity: 0.8; }
.toggle { min-height: 36px; padding: 0 12px; border-radius: 9px; border: 2px solid var(--ink); display: inline-flex; align-items: center; gap: 8px; font: inherit; font-weight: 700; font-size: 0.9rem; background: var(--surface); color: var(--ink); cursor: pointer; }
.toggle i { width: 26px; height: 15px; border-radius: 9px; background: var(--surface-3); position: relative; display: inline-block; }
.toggle i::after { content: ''; position: absolute; top: 2px; left: 2px; width: 11px; height: 11px; border-radius: 50%; background: #fff; border: 1.5px solid var(--ink); box-sizing: border-box; transition: left 0.12s; }
.toggle.on { background: var(--primary-soft); }
.toggle.on i { background: var(--primary); }
.toggle.on i::after { left: 13px; }
.toggle:disabled { cursor: default; }
.info { width: 16px; height: 16px; border-radius: 50%; border: 1.5px solid var(--text-sub); color: var(--text-sub); font-size: 11px; font-weight: 900; display: inline-flex; align-items: center; justify-content: center; position: relative; top: -4px; cursor: help; }
.info:hover::after, .info:focus::after { content: attr(data-tip); position: absolute; left: 22px; top: -6px; background: var(--ink); color: var(--surface); font-size: 0.8rem; font-weight: 600; padding: 7px 10px; border-radius: 8px; white-space: nowrap; z-index: 5; }
.diff { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }
.diff .t { flex: 1; min-width: 160px; }
.diff .t b { font-size: 1.1rem; font-weight: 850; letter-spacing: -0.03em; display: block; }
.diff .t span { font-size: 0.83rem; color: var(--text-sub); }
.stars { display: flex; gap: 1px; }
.star-btn { background: none; border: 0; padding: 1px; cursor: pointer; line-height: 0; }
.star-btn:disabled { cursor: default; }
.tiers { display: flex; gap: 10px; margin-top: 8px; font-size: 0.77rem; color: var(--text-sub); font-weight: 650; flex-wrap: wrap; }
.tiers i { display: inline-block; width: 9px; height: 9px; border-radius: 3px; margin-right: 4px; vertical-align: -1px; }
.yr { position: relative; height: 62px; margin: 0 10px; }
.yr .track { position: absolute; top: 27px; left: 0; right: 0; height: 7px; border-radius: 9px; background: var(--surface-3); }
.yr .fill { position: absolute; top: 27px; height: 7px; background: var(--primary); border-radius: 9px; }
.yr .bub { position: absolute; margin-left: -24px; width: 48px; text-align: center; background: var(--primary); color: #fff; font-weight: 800; font-size: 0.85rem; border-radius: 7px; padding: 1px 0; pointer-events: none; }
.yr .bub.up { top: 0; }
.yr .bub.dn { top: 42px; }
.yr input[type='range'] { position: absolute; top: 20px; left: -10px; width: calc(100% + 20px); margin: 0; background: none; pointer-events: none; -webkit-appearance: none; appearance: none; height: 21px; }
.yr input[type='range']::-webkit-slider-thumb { pointer-events: auto; -webkit-appearance: none; width: 21px; height: 21px; border-radius: 50%; background: #fff; border: 2.5px solid var(--ink); cursor: pointer; }
.yr input[type='range']::-moz-range-thumb { pointer-events: auto; width: 17px; height: 17px; border-radius: 50%; background: #fff; border: 2.5px solid var(--ink); cursor: pointer; }
.yr input[type='range']:disabled::-webkit-slider-thumb { cursor: default; }
.year-sel { flex: 1; text-align: center; font-weight: 800; }
.artist-hits { display: flex; flex-direction: column; border: 1.5px solid var(--line); border-radius: 10px; max-height: 220px; overflow-y: auto; background: var(--surface); }
.artist-hit { display: flex; justify-content: space-between; align-items: center; gap: 10px; padding: 8px 12px; border: 0; border-bottom: 1px solid var(--line); background: none; font: inherit; color: var(--text); cursor: pointer; text-align: left; }
.artist-hit[aria-selected='true'] { background: var(--primary-soft); }
/* ---------------------------------------------------------------- admin (docs/02: side menu + content, .data-table) */
.admin-layout { display: grid; grid-template-columns: 220px 1fr; min-height: calc(100vh - 66px); }
.admin-side { background: var(--surface-2); border-right: 2px solid var(--ink); padding: 16px 12px; display: flex; flex-direction: column; gap: 3px; }
@@ -248,6 +337,8 @@ input.input.sm { width: 76px; }
.admin-side .sep { display: none; }
.admin-side a { white-space: nowrap; }
.admin-main { padding: 16px; }
.room-main { grid-template-columns: 1fr; padding: 16px; }
.roombar { padding: 10px 16px; }
}
@media (max-width: 600px) {
.site-header-inner { padding: 0 12px; gap: 10px; }