Files
music_quiz/apps/web/src/pages/Home.tsx

146 lines
5.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** 첫 화면 (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">
<section className="welcome" aria-labelledby="hero-title">
<div className="bigLP" aria-hidden />
<h1 id="hero-title">
전주 1초, 채팅 한 줄.
<br />
누가 먼저 맞히나.
</h1>
<p>방 만들고 링크 하나 보내면 끝. 인원 제한 없이 같이 듣고, 채팅으로 제목을 먼저 치는 사람이 점수를 가져가요.</p>
<div className="acts">
<button className="btn btn-mustard btn-lg" onClick={() => void create()} disabled={busy}>
+ 방 만들기
</button>
<button className="btn btn-lg" onClick={() => setJoining((j) => !j)} aria-expanded={joining}>
코드로 참여
</button>
</div>
{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">
<h2 id="me-title">반가워요!</h2>
<div className="row">
<Avatar user={me} size={48} />
<div>
<div style={{ fontWeight: 800, fontSize: '1.1rem' }}>{me.nickname}</div>
<div className="muted small">{me.kind === 'member' ? '디스코드 계정으로 로그인했어요' : '게스트로 참여 중이에요'}</div>
</div>
</div>
</section>
) : (
<LoginBox next="/" />
)}
</div>
<div className="rooms-head">
<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>
{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>
);
}