M2: 사이트 서버 · 사이트 v1 - gvr.tkrmagid.kr 배포
- site/server: Discord OAuth2 + 봇 토큰 멤버 확인, 세션, 1회용 등록 코드·기기 키 인증, 게임 PC WebSocket 중계(JSON·음성 바이너리), 15초 무응답 잠금, 게임 이미지 캐시, 관리 CLI - site/web: 타임라인·따라 읽기 재생(단어 강조·이어듣기·현장 모드·재생 게인)·필터·검색·실시간·교정, 발로란트/롤 경기 상세, 잠금 화면(관리자 등록 코드), 모바일, 효과음 - deploy/site: Dockerfile·compose·deploy.sh·make-env.sh (.5, 포트 2972) - 앱 코어: 사이트 필터 묶음(킬·라운드)과 유저 필터 규칙 맞춤, hello 에 서버 ID Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
113
site/web/src/App.tsx
Normal file
113
site/web/src/App.tsx
Normal file
@@ -0,0 +1,113 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Navigate, Route, Routes } from 'react-router';
|
||||
import { MotionConfig } from 'framer-motion';
|
||||
import { AuthProvider, DataProvider, StatusProvider, useAuth, useStatus } from './store/app';
|
||||
import { useReducedMotion } from './store/settings';
|
||||
import { player } from './store/player';
|
||||
import { resumeAudio } from './lib/audio';
|
||||
import { Header } from './components/Header';
|
||||
import { LockOverlay } from './components/LockOverlay';
|
||||
import { LoginPage } from './components/LoginPage';
|
||||
import { PlayerBar } from './components/PlayerBar';
|
||||
import { Spinner } from './components/common';
|
||||
import { TimelinePage } from './pages/TimelinePage';
|
||||
import { MatchPage } from './pages/MatchPage';
|
||||
import { MatchesPage, UserPage, UsersPage } from './pages/UserPages';
|
||||
|
||||
/** Space 재생/일시정지 · ←/→ 이전/다음 발화 · / 검색 */
|
||||
function useShortcuts() {
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
const t = e.target as HTMLElement;
|
||||
const typing = t.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(t.tagName);
|
||||
if (e.ctrlKey || e.metaKey || e.altKey) return;
|
||||
if (e.key === '/' && !typing) {
|
||||
e.preventDefault();
|
||||
document.getElementById('gvr-search')?.focus();
|
||||
return;
|
||||
}
|
||||
if (typing) return;
|
||||
if (e.key === ' ' || e.code === 'Space') {
|
||||
if (t.tagName === 'BUTTON' || t.tagName === 'A') t.blur();
|
||||
e.preventDefault();
|
||||
player.toggle();
|
||||
} else if (e.key === 'ArrowRight') {
|
||||
e.preventDefault();
|
||||
player.next();
|
||||
} else if (e.key === 'ArrowLeft') {
|
||||
e.preventDefault();
|
||||
player.prev();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
// 첫 사용자 제스처에서 AudioContext 를 깨워 효과음이 바로 나게
|
||||
const wake = () => resumeAudio();
|
||||
window.addEventListener('pointerdown', wake, { once: true });
|
||||
return () => {
|
||||
window.removeEventListener('keydown', onKey);
|
||||
window.removeEventListener('pointerdown', wake);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
|
||||
function Shell() {
|
||||
const { locked, epoch } = useStatus();
|
||||
useShortcuts();
|
||||
return (
|
||||
<div className={`shell${locked ? ' is-locked' : ''}`}>
|
||||
<div className="app" aria-hidden={locked || undefined}>
|
||||
<Header />
|
||||
<div className="content" key={epoch}>
|
||||
<Routes>
|
||||
<Route path="/" element={<TimelinePage />} />
|
||||
<Route path="/matches" element={<MatchesPage />} />
|
||||
<Route path="/matches/:id" element={<MatchPage />} />
|
||||
<Route path="/users" element={<UsersPage />} />
|
||||
<Route path="/users/:id" element={<UserPage />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</div>
|
||||
<PlayerBar />
|
||||
</div>
|
||||
<LockOverlay />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Gate() {
|
||||
const { auth } = useAuth();
|
||||
if (auth.status === 'loading')
|
||||
return (
|
||||
<div className="boot">
|
||||
<img src="/icon-192.png" alt="" />
|
||||
<Spinner label="겜녹이 여는 중" />
|
||||
</div>
|
||||
);
|
||||
if (auth.status === 'anon') {
|
||||
// 서버가 OAuth 결과를 ?login=... 으로 알려 준다
|
||||
const q = new URLSearchParams(window.location.search).get('login');
|
||||
return <LoginPage notMember={q === 'not_member'} error={q === 'error' || q === 'invalid' ? '로그인 중 문제가 생겼습니다. 다시 시도해 주세요.' : undefined} />;
|
||||
}
|
||||
if (auth.status === 'not_member') return <LoginPage notMember />;
|
||||
return (
|
||||
<StatusProvider>
|
||||
<DataProvider>
|
||||
<Shell />
|
||||
</DataProvider>
|
||||
</StatusProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export function App() {
|
||||
const reduce = useReducedMotion();
|
||||
useEffect(() => {
|
||||
document.documentElement.classList.toggle('reduce-motion', reduce);
|
||||
}, [reduce]);
|
||||
return (
|
||||
<MotionConfig reducedMotion={reduce ? 'always' : 'never'}>
|
||||
<AuthProvider>
|
||||
<Gate />
|
||||
</AuthProvider>
|
||||
</MotionConfig>
|
||||
);
|
||||
}
|
||||
184
site/web/src/components/EventRow.tsx
Normal file
184
site/web/src/components/EventRow.tsx
Normal file
@@ -0,0 +1,184 @@
|
||||
import { memo } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import type { ChatData, EventItem, KillData, ObjectData, PlayerRef, RoundEndData } from '@gvr/shared';
|
||||
import { CharIcon, PName, TimeCell } from './common';
|
||||
import { CHANNEL_KO, MULTI_KO, OBJECT_GLYPH, objectName, roundResultKo } from '../lib/game';
|
||||
import { useReducedMotion } from '../store/settings';
|
||||
import { realTip } from '../lib/format';
|
||||
|
||||
export function KillLine({ d, game, iconSize = 22 }: { d: KillData; game: 'valorant' | 'lol'; iconSize?: number }) {
|
||||
return (
|
||||
<>
|
||||
{d.killer ? (
|
||||
<>
|
||||
<CharIcon c={d.killer.character} size={iconSize} />
|
||||
<PName p={d.killer} />
|
||||
</>
|
||||
) : (
|
||||
<span className="dim">{game === 'lol' ? '처형' : '낙사'}</span>
|
||||
)}
|
||||
{d.weapon?.icon ? <img className="wk" src={d.weapon.icon} alt={d.weapon.name} title={d.weapon.name} /> : d.weapon ? <span className="dim wname">{d.weapon.name}</span> : null}
|
||||
<span className="arrow">▶</span>
|
||||
<CharIcon c={d.victim.character} size={iconSize} />
|
||||
<PName p={d.victim} />
|
||||
{d.headshot && <span className="dim">헤드샷</span>}
|
||||
{d.assists?.length > 0 && game === 'lol' && (
|
||||
<span className="dim">
|
||||
· 어시{' '}
|
||||
{d.assists.map((a: PlayerRef, i: number) => (
|
||||
<span key={i}>
|
||||
{i > 0 && ', '}
|
||||
<PName p={a} strong={false} />
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function isAllyDeath(e: EventItem) {
|
||||
const d = e.data as KillData;
|
||||
return e.type === 'kill' && (d.ally === false || (d.ally == null && !!d.victim?.userId));
|
||||
}
|
||||
|
||||
/** 이벤트 내용 (킬 · 채팅 · 오브젝트 · 스파이크 · 멀티킬) */
|
||||
export function EventBody({ e, iconSize = 22 }: { e: EventItem; iconSize?: number }) {
|
||||
switch (e.type) {
|
||||
case 'kill':
|
||||
return (
|
||||
<div className={`ev ${isAllyDeath(e) ? 'death' : 'kill'}`}>
|
||||
<KillLine d={e.data as KillData} game={e.game} iconSize={iconSize} />
|
||||
</div>
|
||||
);
|
||||
case 'multikill':
|
||||
case 'ace': {
|
||||
const d = e.data as { player?: PlayerRef; count?: number };
|
||||
return (
|
||||
<div className="ev kill multi">
|
||||
<CharIcon c={d.player?.character} size={iconSize} />
|
||||
<PName p={d.player} />
|
||||
<span className="kbadge">{e.type === 'ace' ? '에이스' : MULTI_KO[d.count ?? 2] ?? `${d.count}킬`}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
case 'chat': {
|
||||
const d = e.data as ChatData;
|
||||
return (
|
||||
<div className={`ev chat ${e.game}`}>
|
||||
<span aria-hidden>💬</span>
|
||||
<span className={`ctag ch-${d.channel}`}>{CHANNEL_KO[d.channel] ?? d.channel}</span>
|
||||
<PName p={d.sender} />
|
||||
{d.sender.character && <span className="dim">({d.sender.character.name})</span>}
|
||||
<span className="ctext">{d.text}</span>
|
||||
{d.source === 'ocr' && (
|
||||
<span className="ocr" title="게임 화면에서 글자 인식(OCR)으로 읽은 채팅">
|
||||
OCR
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
case 'object': {
|
||||
const d = e.data as ObjectData & { icon?: string | null };
|
||||
const name = objectName(d.object, d.subtype);
|
||||
const destroyed = d.object === 'tower' || d.object === 'inhibitor';
|
||||
return (
|
||||
<div className={`ev obj${d.ally === false ? ' enemy' : ''}`}>
|
||||
{d.icon ? <img className="oi" src={d.icon} alt="" /> : <span aria-hidden>{OBJECT_GLYPH[d.object] ?? '◆'}</span>}
|
||||
{destroyed ? (
|
||||
<span>
|
||||
{d.ally === false ? '우리' : '상대'} <b className="gold">{name}</b> 파괴
|
||||
</span>
|
||||
) : (
|
||||
<span>
|
||||
{d.ally === false ? '상대 팀' : '우리 팀'} <b className="gold">{name}</b> 처치
|
||||
</span>
|
||||
)}
|
||||
{d.killer && (
|
||||
<span className="dim">
|
||||
· <PName p={d.killer} strong={false} />
|
||||
{d.object === 'dragon' || d.object === 'baron' ? ' 강타' : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
case 'spike': {
|
||||
const d = e.data as { action?: string; site?: string; player?: PlayerRef };
|
||||
const act = d.action === 'defuse' ? '해체' : d.action === 'detonate' ? '폭발' : '설치';
|
||||
return (
|
||||
<div className="ev spike">
|
||||
<span className="spike-ic">◆</span> 스파이크 {act}
|
||||
{d.site && <span className="dim">· {d.site} 사이트</span>}
|
||||
{d.player && (
|
||||
<span className="dim">
|
||||
· <PName p={d.player} strong={false} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
default:
|
||||
return <div className="ev">{e.type}</div>;
|
||||
}
|
||||
}
|
||||
|
||||
export const SEPARATOR_TYPES = new Set(['round_end', 'match_start', 'match_end']);
|
||||
|
||||
/** 라운드 종료 · 경기 시작/종료 구분선 (와이프 연출) */
|
||||
export const SeparatorRow = memo(function SeparatorRow({ e }: { e: EventItem }) {
|
||||
const reduce = useReducedMotion();
|
||||
let pill = '';
|
||||
let text = '';
|
||||
let score = '';
|
||||
let cls = '';
|
||||
if (e.type === 'round_end') {
|
||||
const d = e.data as RoundEndData & { winner?: string };
|
||||
const win = d.win ?? d.winner === 'ally';
|
||||
pill = `R${d.round}`;
|
||||
text = `${win ? '승리' : '패배'} · ${roundResultKo(d.result)}`;
|
||||
score = `${d.score.ally} : ${d.score.enemy}`;
|
||||
cls = win ? 'win' : 'loss';
|
||||
} else if (e.type === 'match_start') {
|
||||
const d = e.data as { map?: string; mode?: string };
|
||||
pill = '경기 시작';
|
||||
text = [d.map, d.mode].filter(Boolean).join(' · ');
|
||||
cls = 'start';
|
||||
} else {
|
||||
const d = e.data as { win?: boolean; score?: { ally: number; enemy: number } };
|
||||
pill = '경기 종료';
|
||||
text = d.win == null ? '' : d.win ? '승리' : '패배';
|
||||
score = d.score ? `${d.score.ally} : ${d.score.enemy}` : '';
|
||||
cls = d.win ? 'win' : 'loss';
|
||||
}
|
||||
return (
|
||||
<div className={`sep ${cls} g-${e.game}`} data-tip={realTip(e.ts)}>
|
||||
<span className="pill">{pill}</span>
|
||||
<span className="sep-text">{text}</span>
|
||||
{score && <span className="score mono">{score}</span>}
|
||||
<span className="sep-time mono">{e.time.primary}</span>
|
||||
<span className="sep-line">
|
||||
<motion.i
|
||||
initial={reduce ? false : { scaleX: 0 }}
|
||||
whileInView={{ scaleX: 1 }}
|
||||
viewport={{ once: true }}
|
||||
transition={{ duration: 0.7, ease: [0.2, 0.7, 0.2, 1] }}
|
||||
/>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
export const EventRow = memo(function EventRow({ e }: { e: EventItem }) {
|
||||
if (SEPARATOR_TYPES.has(e.type)) return <SeparatorRow e={e} />;
|
||||
return (
|
||||
<div className={`it evrow t-${e.type}`} data-id={e.id}>
|
||||
<TimeCell time={e.time} />
|
||||
<span className="av-spacer" />
|
||||
<div className="body">
|
||||
<EventBody e={e} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
193
site/web/src/components/Header.tsx
Normal file
193
site/web/src/components/Header.tsx
Normal file
@@ -0,0 +1,193 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { NavLink, useLocation, useNavigate, useSearchParams } from 'react-router';
|
||||
import { AnimatePresence, motion } from 'framer-motion';
|
||||
import { useAuth, useData, useStatus } from '../store/app';
|
||||
import { settings, useSettings, type SfxKind } from '../store/settings';
|
||||
import { sfx, SFX_LABEL } from '../lib/sfx';
|
||||
import { resumeAudio } from '../lib/audio';
|
||||
import { Avatar, Brand } from './common';
|
||||
import { IGear, ILogout, ISearch } from './Icons';
|
||||
|
||||
function SettingsPopover({ onClose }: { onClose: () => void }) {
|
||||
const s = useSettings();
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
const down = (e: PointerEvent) => {
|
||||
if (ref.current && !ref.current.contains(e.target as Node) && !(e.target as HTMLElement).closest('.gear-btn')) onClose();
|
||||
};
|
||||
const key = (e: KeyboardEvent) => e.key === 'Escape' && onClose();
|
||||
document.addEventListener('pointerdown', down);
|
||||
document.addEventListener('keydown', key);
|
||||
return () => {
|
||||
document.removeEventListener('pointerdown', down);
|
||||
document.removeEventListener('keydown', key);
|
||||
};
|
||||
}, [onClose]);
|
||||
return (
|
||||
<motion.div
|
||||
ref={ref}
|
||||
className="popover"
|
||||
initial={{ opacity: 0, y: -6, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, y: -6, scale: 0.98 }}
|
||||
transition={{ duration: 0.16 }}
|
||||
role="dialog"
|
||||
aria-label="설정"
|
||||
>
|
||||
<h5>효과음</h5>
|
||||
<label className="row">
|
||||
<span>전체 볼륨</span>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={s.volume}
|
||||
onChange={(e) => settings.set({ volume: Number(e.target.value) })}
|
||||
onPointerUp={() => {
|
||||
resumeAudio();
|
||||
sfx('click');
|
||||
}}
|
||||
/>
|
||||
<span className="mono val">{Math.round(s.volume * 100)}</span>
|
||||
</label>
|
||||
{(Object.keys(SFX_LABEL) as SfxKind[]).map((k) => (
|
||||
<label className="row check" key={k}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={s.sfx[k]}
|
||||
onChange={(e) => {
|
||||
settings.set({ sfx: { ...s.sfx, [k]: e.target.checked } });
|
||||
resumeAudio();
|
||||
if (e.target.checked) window.setTimeout(() => sfx(k), 30);
|
||||
}}
|
||||
/>
|
||||
<span>{SFX_LABEL[k]}</span>
|
||||
<button
|
||||
className="mini-btn"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
resumeAudio();
|
||||
window.setTimeout(() => sfx(k), 30);
|
||||
}}
|
||||
>
|
||||
미리 듣기
|
||||
</button>
|
||||
</label>
|
||||
))}
|
||||
<h5>화면</h5>
|
||||
<label className="row check">
|
||||
<input type="checkbox" checked={s.reduceMotion} onChange={(e) => settings.set({ reduceMotion: e.target.checked })} />
|
||||
<span>모션 줄이기</span>
|
||||
</label>
|
||||
<div className="pop-foot">단축키: Space 재생 · ←/→ 이전·다음 발화 · / 검색 · Esc 닫기</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SearchBox() {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const loc = useLocation();
|
||||
const nav = useNavigate();
|
||||
const onTimeline = loc.pathname === '/';
|
||||
const urlQ = onTimeline ? params.get('q') ?? '' : '';
|
||||
const [v, setV] = useState(urlQ);
|
||||
useEffect(() => setV(urlQ), [urlQ]);
|
||||
const timer = useRef<number | null>(null);
|
||||
const commit = (q: string) => {
|
||||
if (!onTimeline) {
|
||||
nav(q ? `/?q=${encodeURIComponent(q)}` : '/');
|
||||
return;
|
||||
}
|
||||
const p = new URLSearchParams(params);
|
||||
if (q) p.set('q', q);
|
||||
else p.delete('q');
|
||||
setParams(p, { replace: true });
|
||||
};
|
||||
return (
|
||||
<form
|
||||
className="search"
|
||||
role="search"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (timer.current) window.clearTimeout(timer.current);
|
||||
commit(v.trim());
|
||||
}}
|
||||
>
|
||||
<ISearch width={16} height={16} />
|
||||
<input
|
||||
id="gvr-search"
|
||||
value={v}
|
||||
placeholder="대화 내용 검색 (예: 스파이크)"
|
||||
onChange={(e) => {
|
||||
const q = e.target.value;
|
||||
setV(q);
|
||||
if (!onTimeline) return;
|
||||
if (timer.current) window.clearTimeout(timer.current);
|
||||
timer.current = window.setTimeout(() => commit(q.trim()), 350);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') (e.target as HTMLInputElement).blur();
|
||||
}}
|
||||
aria-label="대화 내용 검색"
|
||||
/>
|
||||
<kbd>/</kbd>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export function Header() {
|
||||
const { auth, logout } = useAuth();
|
||||
const { overview } = useData();
|
||||
const { device, locked, conn } = useStatus();
|
||||
const [open, setOpen] = useState(false);
|
||||
const me = auth.status === 'ok' ? auth.me.user : null;
|
||||
const rec = overview?.recording;
|
||||
const nav = [
|
||||
['/', '타임라인'],
|
||||
['/matches', '경기'],
|
||||
['/users', '유저'],
|
||||
] as const;
|
||||
return (
|
||||
<header className="topbar">
|
||||
<NavLink to="/" className="brand-link" aria-label="겜녹이 홈">
|
||||
<Brand />
|
||||
</NavLink>
|
||||
<nav className="nav">
|
||||
{nav.map(([to, label]) => (
|
||||
<NavLink key={to} to={to} end={to === '/'} className={({ isActive }) => `chip${isActive ? ' on' : ''}`} onClick={() => sfx('click')}>
|
||||
{label}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
<SearchBox />
|
||||
<div className="hdr-right">
|
||||
{rec?.active && !locked && (
|
||||
<div className="rec" title={rec.since ? `녹음 시작 ${new Date(rec.since).toLocaleTimeString('ko-KR', { hour12: false })}` : undefined}>
|
||||
<i /> <span className="rec-txt">녹음 중{rec.channel ? ` · #${rec.channel}` : ''} · {rec.participants.length}명</span>
|
||||
<span className="rec-short">녹음 중</span>
|
||||
</div>
|
||||
)}
|
||||
{device && (
|
||||
<div className={`conn ${locked ? 'off' : conn === 'open' ? 'on' : 'warn'}`} title={conn === 'open' ? '실시간 연결됨' : '실시간 연결 재시도 중'}>
|
||||
<span className="dot" />
|
||||
<span className="conn-txt">{locked ? '게임 PC 연결 해제됨' : conn === 'open' ? '게임 PC 연결됨' : '실시간 재연결 중'}</span>
|
||||
</div>
|
||||
)}
|
||||
<button className="icon-btn gear-btn" onClick={() => setOpen((o) => !o)} aria-label="설정" title="효과음 · 모션 설정">
|
||||
<IGear />
|
||||
</button>
|
||||
<AnimatePresence>{open && <SettingsPopover onClose={() => setOpen(false)} />}</AnimatePresence>
|
||||
{me && (
|
||||
<div className="me">
|
||||
<Avatar name={me.name} src={me.avatar} color="#5865f2" size={26} />
|
||||
<span className="me-nm">{me.name}</span>
|
||||
<button className="icon-btn" onClick={logout} title="로그아웃" aria-label="로그아웃">
|
||||
<ILogout width={16} height={16} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
98
site/web/src/components/Icons.tsx
Normal file
98
site/web/src/components/Icons.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
import type { SVGProps } from 'react';
|
||||
|
||||
const base = (p: SVGProps<SVGSVGElement>) => ({ width: 18, height: 18, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round' as const, strokeLinejoin: 'round' as const, 'aria-hidden': true, ...p });
|
||||
|
||||
export const IPlay = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)} fill="currentColor" stroke="none">
|
||||
<path d="M7 4.5v15a1 1 0 0 0 1.5.86l12-7.5a1 1 0 0 0 0-1.72l-12-7.5A1 1 0 0 0 7 4.5z" />
|
||||
</svg>
|
||||
);
|
||||
export const IPause = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)} fill="currentColor" stroke="none">
|
||||
<rect x="5.5" y="4" width="4.5" height="16" rx="1.2" />
|
||||
<rect x="14" y="4" width="4.5" height="16" rx="1.2" />
|
||||
</svg>
|
||||
);
|
||||
export const IPrev = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)} fill="currentColor" stroke="none">
|
||||
<rect x="4" y="5" width="2.6" height="14" rx="1" />
|
||||
<path d="M20 5.6v12.8a.9.9 0 0 1-1.38.76L8.8 12.76a.9.9 0 0 1 0-1.52l9.82-6.4A.9.9 0 0 1 20 5.6z" />
|
||||
</svg>
|
||||
);
|
||||
export const INext = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)} fill="currentColor" stroke="none">
|
||||
<rect x="17.4" y="5" width="2.6" height="14" rx="1" />
|
||||
<path d="M4 5.6v12.8a.9.9 0 0 0 1.38.76l9.82-6.4a.9.9 0 0 0 0-1.52L5.38 4.84A.9.9 0 0 0 4 5.6z" />
|
||||
</svg>
|
||||
);
|
||||
export const IEdit = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="M12 20h9" />
|
||||
<path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z" />
|
||||
</svg>
|
||||
);
|
||||
export const ISearch = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<circle cx="11" cy="11" r="7" />
|
||||
<path d="m20 20-3.5-3.5" />
|
||||
</svg>
|
||||
);
|
||||
export const IGear = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
|
||||
</svg>
|
||||
);
|
||||
export const ILogout = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
|
||||
<path d="m16 17 5-5-5-5" />
|
||||
<path d="M21 12H9" />
|
||||
</svg>
|
||||
);
|
||||
export const ILoop = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="m17 2 4 4-4 4" />
|
||||
<path d="M3 11v-1a4 4 0 0 1 4-4h14" />
|
||||
<path d="m7 22-4-4 4-4" />
|
||||
<path d="M21 13v1a4 4 0 0 1-4 4H3" />
|
||||
</svg>
|
||||
);
|
||||
export const IVolume = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="M11 5 6 9H2v6h4l5 4V5z" />
|
||||
<path d="M15.5 8.5a5 5 0 0 1 0 7" />
|
||||
<path d="M19 5a10 10 0 0 1 0 14" />
|
||||
</svg>
|
||||
);
|
||||
export const IUsers = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
|
||||
<circle cx="9" cy="7" r="4" />
|
||||
<path d="M23 21v-2a4 4 0 0 0-3-3.87" />
|
||||
<path d="M16 3.13a4 4 0 0 1 0 7.75" />
|
||||
</svg>
|
||||
);
|
||||
export const IClose = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="M18 6 6 18M6 6l12 12" />
|
||||
</svg>
|
||||
);
|
||||
export const IWaves = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg {...base(p)}>
|
||||
<path d="M2 12h2M6 8v8M10 5v14M14 8v8M18 10v4M22 12h0" />
|
||||
</svg>
|
||||
);
|
||||
export const IDiscord = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg width={22} height={22} viewBox="0 0 24 24" fill="currentColor" aria-hidden {...p}>
|
||||
<path d="M20.3 4.4A19.6 19.6 0 0 0 15.4 3l-.6 1.3a18 18 0 0 0-5.6 0L8.6 3a19.6 19.6 0 0 0-4.9 1.5C.6 9.1-.3 13.6.1 18a19.8 19.8 0 0 0 6 3l1.3-2a12.8 12.8 0 0 1-2-1l.5-.4a14 14 0 0 0 12.2 0l.5.4-2 1 1.3 2a19.7 19.7 0 0 0 6-3c.5-5.1-.8-9.6-3.6-13.6zM8 15.3c-1.2 0-2.2-1.1-2.2-2.4S6.8 10.5 8 10.5s2.2 1.1 2.2 2.4-1 2.4-2.2 2.4zm8 0c-1.2 0-2.2-1.1-2.2-2.4s1-2.4 2.2-2.4 2.2 1.1 2.2 2.4-1 2.4-2.2 2.4z" />
|
||||
</svg>
|
||||
);
|
||||
export const IPlug = (p: SVGProps<SVGSVGElement>) => (
|
||||
<svg width={34} height={34} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.8} strokeLinecap="round" strokeLinejoin="round" aria-hidden {...p}>
|
||||
<path d="M9 2v5M15 2v5" />
|
||||
<path d="M6 7h12v4a6 6 0 0 1-12 0V7z" />
|
||||
<path d="M12 17v5" />
|
||||
<path d="m3 3 18 18" stroke="#ff4655" />
|
||||
</svg>
|
||||
);
|
||||
135
site/web/src/components/LockOverlay.tsx
Normal file
135
site/web/src/components/LockOverlay.tsx
Normal file
@@ -0,0 +1,135 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { AnimatePresence, motion } from 'framer-motion';
|
||||
import { useAuth, useStatus } from '../store/app';
|
||||
import { fmtAgo, fmtWhen } from '../lib/format';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { api } from '../lib/api';
|
||||
import { IPlug } from './Icons';
|
||||
|
||||
/** 게임 PC 연결 해제 잠금. 다시 연결되면 열리는 전환과 함께 자동으로 사라진다. */
|
||||
export function LockOverlay() {
|
||||
const { device, serverOk, locked, recheck } = useStatus();
|
||||
const { logout, auth } = useAuth();
|
||||
const isOwner = auth.status === 'ok' && auth.me.isOwner;
|
||||
const [code, setCode] = useState<{ code: string; expiresAt: number } | null>(null);
|
||||
const [codeErr, setCodeErr] = useState<string | null>(null);
|
||||
const [, force] = useState(0);
|
||||
const [checking, setChecking] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!locked) return;
|
||||
const t = window.setInterval(() => force((n) => n + 1), 15000);
|
||||
return () => window.clearInterval(t);
|
||||
}, [locked]);
|
||||
|
||||
const notRegistered = device && !device.registered;
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{locked && device && (
|
||||
<motion.div
|
||||
key="lock"
|
||||
className="lock"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0, transition: { duration: 0.6, delay: 0.25 } }}
|
||||
role="alertdialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="lock-title"
|
||||
>
|
||||
<div className="lock-veil" />
|
||||
<motion.div
|
||||
className="lock-box"
|
||||
initial={{ opacity: 0, y: 24, scale: 0.97 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1, transition: { duration: 0.35 } }}
|
||||
exit={{ opacity: 0, scale: 1.08, y: -10, filter: 'blur(6px)', transition: { duration: 0.5, ease: [0.4, 0, 0.2, 1] } }}
|
||||
>
|
||||
<div className="lock-ic">
|
||||
<IPlug />
|
||||
</div>
|
||||
<div className="t h" id="lock-title">
|
||||
{notRegistered ? '등록된 게임 PC가 없습니다' : '게임 PC 프로그램과 연결이 끊어졌습니다'}
|
||||
</div>
|
||||
<div className="d">
|
||||
기록은 게임 PC에만 저장되어 있어서, 프로그램이 켜져 있을 때만 볼 수 있어요.
|
||||
<br />
|
||||
{notRegistered ? '게임 PC에서 겜녹이 프로그램을 등록하면 자동으로 열립니다.' : '프로그램이 다시 연결되면 자동으로 열립니다.'}
|
||||
</div>
|
||||
<div className="st">
|
||||
<div>
|
||||
<span className="muted">사이트 서버</span>
|
||||
{serverOk === false ? <span className="c-r">● 응답 없음</span> : <span className="c-g">● 정상</span>}
|
||||
</div>
|
||||
<div>
|
||||
<span className="muted">등록된 게임 PC</span>
|
||||
<span>
|
||||
{device.name ?? '없음'} {device.version && <span className="dim">(v{device.version})</span>}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="muted">프로그램 상태</span>
|
||||
<span className="c-r">
|
||||
● {notRegistered ? '등록 안 됨' : '연결 해제됨'}
|
||||
{device.lastSeen ? ` · 마지막 응답 ${fmtWhen(device.lastSeen)} (${fmtAgo(device.lastSeen)})` : ''}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="muted">다시 확인</span>
|
||||
<span className="c-y">
|
||||
5초마다 자동 확인 중
|
||||
<span className="dots">
|
||||
<i />
|
||||
<i />
|
||||
<i />
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{isOwner && (
|
||||
<div className="lock-reg">
|
||||
{code ? (
|
||||
<div>
|
||||
게임 PC 겜녹이 설정 → <b>저장 · 사이트</b> 탭에 이 코드를 입력하세요
|
||||
<div className="lock-code">{code.code}</div>
|
||||
<span className="dim">{fmtWhen(code.expiresAt)}까지 유효 · 한 번만 쓸 수 있음</span>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
className="btn"
|
||||
onClick={async () => {
|
||||
sfx('click');
|
||||
setCodeErr(null);
|
||||
try {
|
||||
setCode(await api.registrationCode());
|
||||
} catch {
|
||||
setCodeErr('코드를 만들지 못했습니다');
|
||||
}
|
||||
}}
|
||||
>
|
||||
🔑 {notRegistered ? '게임 PC 등록 코드 만들기' : '게임 PC 다시 등록 (새 코드)'}
|
||||
</button>
|
||||
)}
|
||||
{codeErr && <div className="c-r">{codeErr}</div>}
|
||||
</div>
|
||||
)}
|
||||
<div className="lock-btns">
|
||||
<button
|
||||
className="btn"
|
||||
disabled={checking}
|
||||
onClick={async () => {
|
||||
sfx('click');
|
||||
setChecking(true);
|
||||
await recheck();
|
||||
window.setTimeout(() => setChecking(false), 600);
|
||||
}}
|
||||
>
|
||||
↻ {checking ? '확인 중…' : '지금 다시 확인'}
|
||||
</button>
|
||||
<button className="btn" onClick={logout}>
|
||||
로그아웃
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
}
|
||||
79
site/web/src/components/LoginPage.tsx
Normal file
79
site/web/src/components/LoginPage.tsx
Normal file
@@ -0,0 +1,79 @@
|
||||
import { motion } from 'framer-motion';
|
||||
import { IDiscord } from './Icons';
|
||||
|
||||
/** 블러 처리된 가짜 화면 (로그인 뒤 배경) */
|
||||
function FakeBackdrop() {
|
||||
return (
|
||||
<div className="login-bg" aria-hidden>
|
||||
<div className="fb-top" />
|
||||
<div className="fb-main">
|
||||
<div className="fb-side">
|
||||
{Array.from({ length: 5 }, (_, i) => (
|
||||
<i key={i} style={{ background: ['#3987e5', '#e5743f', '#1fb383', '#9085e9', '#c98500'][i] }} />
|
||||
))}
|
||||
</div>
|
||||
<div className="fb-list">
|
||||
{Array.from({ length: 9 }, (_, i) => (
|
||||
<div key={i} className={i === 3 ? 'hot' : ''}>
|
||||
<b />
|
||||
<span style={{ width: `${40 + ((i * 37) % 45)}%` }} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="fb-right">
|
||||
<div />
|
||||
<div />
|
||||
</div>
|
||||
</div>
|
||||
<div className="fb-foot" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LoginPage({ notMember = false, error }: { notMember?: boolean; error?: string }) {
|
||||
return (
|
||||
<div className="login">
|
||||
<FakeBackdrop />
|
||||
<div className="login-veil" />
|
||||
<motion.div className="login-box" initial={{ opacity: 0, y: 18 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.45, ease: [0.2, 0.8, 0.2, 1] }}>
|
||||
<picture>
|
||||
<source srcSet="/banner.webp" type="image/webp" />
|
||||
<img className="ban" src="/banner.png" alt="겜녹이 Game Voice Recorder" />
|
||||
</picture>
|
||||
<div className="in">
|
||||
{notMember ? (
|
||||
<>
|
||||
<div className="t h">들어올 수 없는 계정입니다</div>
|
||||
<div className="nm-warn">M&L 서버 멤버만 들어올 수 있습니다</div>
|
||||
<div className="d">겜녹이 봇이 있는 디스코드 서버(M&L)에 참여한 계정으로 다시 로그인해 주세요.</div>
|
||||
<a className="dc" href="/auth/discord">
|
||||
<IDiscord />
|
||||
다른 계정으로 로그인
|
||||
</a>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="t h">디스코드 계정으로 로그인</div>
|
||||
{error && <div className="nm-warn">{error}</div>}
|
||||
<div className="d">
|
||||
겜녹이 봇이 있는 디스코드 서버(M&L)의 멤버만 들어올 수 있어요.
|
||||
<br />
|
||||
로그인하면 녹음된 대화와 경기 기록을 볼 수 있습니다.
|
||||
</div>
|
||||
<a className="dc" href="/auth/discord">
|
||||
<IDiscord />
|
||||
Discord로 로그인
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
<div className="st">
|
||||
<span>
|
||||
<span className="c-g">●</span> 사이트 서버 정상
|
||||
</span>
|
||||
<span>🔒 HTTPS · gvr.tkrmagid.kr</span>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
162
site/web/src/components/PlayerBar.tsx
Normal file
162
site/web/src/components/PlayerBar.tsx
Normal file
@@ -0,0 +1,162 @@
|
||||
import { useEffect, useMemo, useRef, type MouseEvent } from 'react';
|
||||
import WaveSurfer from 'wavesurfer.js';
|
||||
import { player, usePlayer, type SceneInfo } from '../store/player';
|
||||
import { settings, useSettings } from '../store/settings';
|
||||
import { useData } from '../store/app';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { fmtClock, fmtSec } from '../lib/format';
|
||||
import { Avatar } from './common';
|
||||
import { IClose, ILoop, INext, IPause, IPlay, IPrev, IVolume } from './Icons';
|
||||
|
||||
const RATES = [1, 1.25, 1.5, 2];
|
||||
|
||||
function SceneLanes({ scene }: { scene: SceneInfo }) {
|
||||
const { userById } = useData();
|
||||
const ts = usePlayer((s) => s.sceneTs);
|
||||
const lanes = useMemo(() => [...new Set(scene.items.map((i) => i.userId))], [scene]);
|
||||
const span = Math.max(1, scene.end - scene.start);
|
||||
const seek = (e: MouseEvent<HTMLDivElement>) => {
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
player.seekScene(((e.clientX - r.left) / r.width) * span);
|
||||
};
|
||||
const pos = ts == null ? 0 : Math.min(1, Math.max(0, (ts - scene.start) / span));
|
||||
return (
|
||||
<div className="lanes" onClick={seek} title="눌러서 이동">
|
||||
{lanes.map((uid) => {
|
||||
const u = userById(uid);
|
||||
return (
|
||||
<div className="lane" key={uid}>
|
||||
<span className="lane-nm" style={{ color: u?.color }}>
|
||||
{u?.name ?? '?'}
|
||||
</span>
|
||||
<div className="lane-track">
|
||||
{scene.items
|
||||
.filter((i) => i.userId === uid)
|
||||
.map((i) => {
|
||||
const on = ts != null && ts >= i.ts && ts <= i.endTs;
|
||||
return (
|
||||
<i
|
||||
key={i.id}
|
||||
className={on ? 'on' : ''}
|
||||
style={{ left: `${((i.ts - scene.start) / span) * 100}%`, width: `${Math.max(0.4, ((i.endTs - i.ts) / span) * 100)}%`, background: u?.color ?? '#5b6b7b' }}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div className="lane-cursor" style={{ left: `calc(64px + (100% - 64px) * ${pos})` }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PlayerBar() {
|
||||
const s = usePlayer((x) => x);
|
||||
const cfg = useSettings();
|
||||
const { userById } = useData();
|
||||
const waveRef = useRef<HTMLDivElement>(null);
|
||||
const wsRef = useRef<WaveSurfer | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!waveRef.current) return;
|
||||
const mobile = window.matchMedia('(max-width: 720px)').matches;
|
||||
const ws = WaveSurfer.create({
|
||||
container: waveRef.current,
|
||||
media: player.el,
|
||||
height: mobile ? 30 : 52,
|
||||
waveColor: '#33495e',
|
||||
progressColor: '#ff4655',
|
||||
cursorColor: '#ffffff',
|
||||
cursorWidth: 2,
|
||||
barWidth: 3,
|
||||
barGap: 3,
|
||||
barRadius: 2,
|
||||
normalize: true,
|
||||
interact: true,
|
||||
dragToSeek: true,
|
||||
});
|
||||
wsRef.current = ws;
|
||||
player.attachWave(ws);
|
||||
return () => {
|
||||
player.attachWave(null);
|
||||
ws.destroy();
|
||||
wsRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const lol = s.item?.game?.type === 'lol';
|
||||
useEffect(() => {
|
||||
wsRef.current?.setOptions({ progressColor: lol ? '#c8aa6e' : '#ff4655' });
|
||||
}, [lol]);
|
||||
|
||||
const user = userById(s.item?.userId);
|
||||
const idle = s.mode === 'idle';
|
||||
const scene = s.mode === 'scene' ? s.scene : null;
|
||||
const click = (fn: () => void) => () => {
|
||||
sfx('click');
|
||||
fn();
|
||||
};
|
||||
|
||||
return (
|
||||
<footer className={`playerbar${lol ? ' lol' : ''}${idle ? ' idle' : ''}`} aria-label="플레이어">
|
||||
<button className="pb-skip" onClick={() => player.prev()} title="이전 발화 (←)" aria-label="이전 발화">
|
||||
<IPrev width={20} height={20} />
|
||||
</button>
|
||||
<button className="ctrl" onClick={() => player.toggle()} title="재생/일시정지 (Space)" aria-label={s.playing ? '일시정지' : '재생'}>
|
||||
{s.playing ? <IPause width={20} height={20} /> : <IPlay width={20} height={20} style={{ marginLeft: 3 }} />}
|
||||
</button>
|
||||
<button className="pb-skip" onClick={() => player.next()} title="다음 발화 (→)" aria-label="다음 발화">
|
||||
<INext width={20} height={20} />
|
||||
</button>
|
||||
<span className="mono muted pb-time">
|
||||
{scene ? `${fmtClock(s.time * 1000)} / ${fmtClock(s.duration * 1000)}` : `${fmtSec(s.time)} / ${fmtSec(s.duration)}`}
|
||||
</span>
|
||||
<div className="pb-now">
|
||||
{scene ? (
|
||||
<>
|
||||
<span className="scene-tag">현장 모드</span>
|
||||
<span className="pb-now-txt">
|
||||
<b>{scene.label}</b>
|
||||
<small>{scene.items.length}개 발화 겹쳐 듣기</small>
|
||||
</span>
|
||||
</>
|
||||
) : s.item ? (
|
||||
<>
|
||||
<Avatar user={user} size={30} />
|
||||
<span className="pb-now-txt">
|
||||
<b style={{ color: user?.color }}>{user?.name ?? '알 수 없음'}</b>
|
||||
<small className="mono">{s.item.time.primary}</small>
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="pb-hint">발화를 누르면 여기서 재생됩니다 · Space · ←/→</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="wave-box">
|
||||
<div ref={waveRef} className="wave" style={{ display: scene || s.message || idle ? 'none' : undefined }} />
|
||||
{scene && <SceneLanes scene={scene} />}
|
||||
{!scene && s.message && <div className="pb-msg">🗑 {s.message}</div>}
|
||||
{idle && !s.message && <div className="wave-empty" />}
|
||||
</div>
|
||||
<button className={`chip${cfg.continuous ? ' on' : ''}`} onClick={click(() => settings.set({ continuous: !cfg.continuous }))} title="끝나면 다음 발화로 자동으로 넘어갑니다">
|
||||
<ILoop width={14} height={14} /> 이어듣기
|
||||
</button>
|
||||
<button className="chip mono" onClick={click(() => settings.set({ rate: RATES[(RATES.indexOf(cfg.rate) + 1) % RATES.length] }))} title="재생 속도">
|
||||
{cfg.rate}x
|
||||
</button>
|
||||
<button
|
||||
className={`chip${cfg.normalize ? ' on-mint' : ''}`}
|
||||
onClick={click(() => settings.set({ normalize: !cfg.normalize }))}
|
||||
title={s.item?.audio ? `보정 게인 ${s.item.audio.gainDb > 0 ? '+' : ''}${s.item.audio.gainDb.toFixed(1)} dB` : '사람마다 다른 마이크 음량을 재생할 때 맞춥니다'}
|
||||
>
|
||||
<IVolume width={14} height={14} /> 보정 음량
|
||||
</button>
|
||||
{!idle && (
|
||||
<button className="icon-btn pb-close" onClick={click(() => player.stop())} title="닫기" aria-label="플레이어 닫기">
|
||||
<IClose width={16} height={16} />
|
||||
</button>
|
||||
)}
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
33
site/web/src/components/TalkBars.tsx
Normal file
33
site/web/src/components/TalkBars.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import { useMemo } from 'react';
|
||||
import type { UtteranceItem } from '@gvr/shared';
|
||||
import { useData } from '../store/app';
|
||||
import { fmtDuration } from '../lib/format';
|
||||
|
||||
export function TalkBars({ utts }: { utts: UtteranceItem[] }) {
|
||||
const { userById } = useData();
|
||||
const rows = useMemo(() => {
|
||||
const m = new Map<string, number>();
|
||||
for (const u of utts) if (!u.noise) m.set(u.userId, (m.get(u.userId) ?? 0) + (u.endTs - u.ts));
|
||||
return [...m].sort((a, b) => b[1] - a[1]);
|
||||
}, [utts]);
|
||||
const max = rows[0]?.[1] ?? 1;
|
||||
if (!rows.length) return <div className="dim small">아직 발화가 없습니다</div>;
|
||||
return (
|
||||
<div className="talkbars">
|
||||
{rows.map(([uid, ms]) => {
|
||||
const u = userById(uid);
|
||||
return (
|
||||
<div key={uid} className="tb-row" data-tip={`${u?.name ?? '?'} · ${fmtDuration(ms)}`}>
|
||||
<div className="kv">
|
||||
<span>{u?.name ?? '알 수 없음'}</span>
|
||||
<span className="mono">{fmtDuration(ms)}</span>
|
||||
</div>
|
||||
<div className="bar">
|
||||
<i style={{ width: `${(ms / max) * 100}%`, background: u?.color ?? '#5b6b7b' }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
64
site/web/src/components/TimelineRows.tsx
Normal file
64
site/web/src/components/TimelineRows.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
import { Fragment } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import type { MatchSummary, TimelineItem, UtteranceItem } from '@gvr/shared';
|
||||
import { UtteranceRow } from './UtteranceRow';
|
||||
import { EventRow } from './EventRow';
|
||||
import { itemMatch } from '../lib/game';
|
||||
import { fmtWhen } from '../lib/format';
|
||||
import { useReducedMotion } from '../store/settings';
|
||||
|
||||
/** 경기가 바뀌는 지점에 넣는 맥락 구분선 */
|
||||
function ContextDivider({ m, matchId }: { m?: MatchSummary; matchId: string | null }) {
|
||||
if (!matchId)
|
||||
return (
|
||||
<div className="div ctx">
|
||||
<span>경기 밖 · 현실 시간</span>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className={`div ctx g-${m?.game ?? 'valorant'}`}>
|
||||
<span className="pill">{m?.game === 'lol' ? 'LoL' : 'VALORANT'}</span>
|
||||
<span>{m ? `${m.map.name} · ${m.mode} · ${fmtWhen(m.startedAt)} 시작` : '경기'}</span>
|
||||
{m?.score && <span className="score mono">{`${m.score.ally} : ${m.score.enemy}`}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TimelineRows({
|
||||
items,
|
||||
matches,
|
||||
newIds,
|
||||
onUpdate,
|
||||
}: {
|
||||
items: TimelineItem[];
|
||||
matches: Map<string, MatchSummary>;
|
||||
newIds: Set<string>;
|
||||
onUpdate: (it: UtteranceItem) => void;
|
||||
}) {
|
||||
const reduce = useReducedMotion();
|
||||
let prevMatch: string | null | undefined = undefined;
|
||||
return (
|
||||
<>
|
||||
{items.map((it) => {
|
||||
const mid = itemMatch(it);
|
||||
const divider = mid !== prevMatch ? <ContextDivider m={mid ? matches.get(mid) : undefined} matchId={mid} /> : null;
|
||||
prevMatch = mid;
|
||||
const row = it.kind === 'utterance' ? <UtteranceRow item={it} onUpdate={onUpdate} /> : <EventRow e={it} />;
|
||||
const isNew = newIds.has(it.id);
|
||||
return (
|
||||
<Fragment key={it.id}>
|
||||
{divider}
|
||||
<motion.div
|
||||
className={`row-wrap${isNew ? ' is-new' : ''}`}
|
||||
initial={isNew && !reduce ? { opacity: 0, x: -24, height: 0 } : false}
|
||||
animate={{ opacity: 1, x: 0, height: 'auto' }}
|
||||
transition={{ duration: 0.45, ease: [0.2, 0.8, 0.2, 1] }}
|
||||
>
|
||||
{row}
|
||||
</motion.div>
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
222
site/web/src/components/UtteranceRow.tsx
Normal file
222
site/web/src/components/UtteranceRow.tsx
Normal file
@@ -0,0 +1,222 @@
|
||||
import { memo, useEffect, useRef, useState, type MouseEvent } from 'react';
|
||||
import type { UtteranceItem, Word } from '@gvr/shared';
|
||||
import { player, useIsActive, useLocalTime, usePlayer } from '../store/player';
|
||||
import { useData } from '../store/app';
|
||||
import { api } from '../lib/api';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { realTip } from '../lib/format';
|
||||
import { Avatar, TimeCell } from './common';
|
||||
import { IEdit } from './Icons';
|
||||
|
||||
const STATUS: Record<UtteranceItem['status'], [string, string]> = {
|
||||
realtime: ['실시간', 'st-rt'],
|
||||
precise: ['정밀', 'st-pr'],
|
||||
pending: ['처리 중', 'st-pd'],
|
||||
failed: ['인식 실패', 'st-fail'],
|
||||
};
|
||||
|
||||
export function MiniWave({ n = 5, live = false }: { n?: number; live?: boolean }) {
|
||||
const hs = [6, 12, 5, 9, 4, 11, 7, 13, 5, 8, 10, 6, 12, 4, 9, 7];
|
||||
return (
|
||||
<span className={`mini-wave${live ? ' live' : ''}`} aria-hidden>
|
||||
{Array.from({ length: n }, (_, i) => (
|
||||
<i key={i} style={{ height: hs[i % hs.length], animationDelay: `${(i * 0.09).toFixed(2)}s` }} />
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function wordClick(e: MouseEvent, item: UtteranceItem, w: Word) {
|
||||
e.stopPropagation();
|
||||
player.seekTo(item, w.s);
|
||||
}
|
||||
|
||||
/** 재생 중인 발화: 재생 위치에 따라 단어 강조 (이 컴포넌트만 매 프레임 갱신) */
|
||||
function ActiveWords({ item }: { item: UtteranceItem }) {
|
||||
const t = useLocalTime(item.ts);
|
||||
return (
|
||||
<>
|
||||
{item.words.map((w, i) => {
|
||||
const cls = t < 0 ? '' : t >= w.e ? 'done' : t >= w.s ? 'now' : 'todo';
|
||||
return (
|
||||
<span key={i}>
|
||||
<span className={`w ${cls}`} onClick={(e) => wordClick(e, item, w)}>
|
||||
{w.w}
|
||||
</span>{' '}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Text({ item, active }: { item: UtteranceItem; active: boolean }) {
|
||||
if (item.noise)
|
||||
return (
|
||||
<span className="noise">
|
||||
[잡음] <MiniWave />
|
||||
</span>
|
||||
);
|
||||
if (item.status === 'pending' && !item.text)
|
||||
return (
|
||||
<span className="pending">
|
||||
<MiniWave n={16} live /> <span className="dim">음성 인식 중…</span>
|
||||
</span>
|
||||
);
|
||||
if (!item.text) return <span className="dim">{item.status === 'failed' ? '(인식하지 못함)' : '(내용 없음)'}</span>;
|
||||
if (!item.words.length) return <>{item.text}</>;
|
||||
if (active) return <ActiveWords item={item} />;
|
||||
return (
|
||||
<>
|
||||
{item.words.map((w, i) => (
|
||||
<span key={i}>
|
||||
<span className="w" onClick={(e) => wordClick(e, item, w)}>
|
||||
{w.w}
|
||||
</span>{' '}
|
||||
</span>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Editor({ item, onDone }: { item: UtteranceItem; onDone: (it?: UtteranceItem) => void }) {
|
||||
const [text, setText] = useState(item.text ?? '');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const ref = useRef<HTMLInputElement>(null);
|
||||
useEffect(() => {
|
||||
ref.current?.focus();
|
||||
ref.current?.select();
|
||||
}, []);
|
||||
const save = async () => {
|
||||
const v = text.trim();
|
||||
if (!v || v === item.text) return onDone();
|
||||
setBusy(true);
|
||||
setErr(null);
|
||||
try {
|
||||
const it = await api.correct(item.id, v);
|
||||
sfx('click');
|
||||
onDone(it);
|
||||
} catch {
|
||||
setErr('저장하지 못했습니다');
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className="editor" onClick={(e) => e.stopPropagation()}>
|
||||
<input
|
||||
ref={ref}
|
||||
value={text}
|
||||
disabled={busy}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') void save();
|
||||
if (e.key === 'Escape') {
|
||||
e.stopPropagation();
|
||||
onDone();
|
||||
}
|
||||
}}
|
||||
aria-label="발화 텍스트 교정"
|
||||
/>
|
||||
<button className="btn primary sm" disabled={busy} onClick={() => void save()}>
|
||||
저장
|
||||
</button>
|
||||
<button className="btn sm" disabled={busy} onClick={() => onDone()}>
|
||||
취소
|
||||
</button>
|
||||
{err && <span className="err">{err}</span>}
|
||||
<div className="hint">고친 문장은 교정 사전과 학습 데이터에 반영됩니다 · Enter 저장 · Esc 취소</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface Props {
|
||||
item: UtteranceItem;
|
||||
variant?: 'full' | 'compact';
|
||||
/** compact 에서 시간 칸에 쓸 라벨 (예: 라운드 시간만) */
|
||||
timeText?: string;
|
||||
sub?: string;
|
||||
onUpdate?: (it: UtteranceItem) => void;
|
||||
}
|
||||
|
||||
export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full', timeText, sub, onUpdate }: Props) {
|
||||
const { userById } = useData();
|
||||
const user = userById(item.userId);
|
||||
const active = useIsActive(item);
|
||||
const playing = usePlayer((s) => active && s.playing);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [st, stCls] = STATUS[item.status];
|
||||
|
||||
const click = () => {
|
||||
if (editing) return;
|
||||
if (active && player.state.mode === 'single') player.toggle();
|
||||
else void player.play(item);
|
||||
};
|
||||
const edit = (e: MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
sfx('click');
|
||||
setEditing(true);
|
||||
};
|
||||
const done = (it?: UtteranceItem) => {
|
||||
setEditing(false);
|
||||
if (it) onUpdate?.(it);
|
||||
};
|
||||
|
||||
const badges = (
|
||||
<>
|
||||
{(item.status !== 'precise' || variant === 'full') && <span className={`sbadge ${stCls}`}>{st}</span>}
|
||||
{item.corrected && <span className="sbadge st-fix">교정됨</span>}
|
||||
{!item.audio && <span className="sbadge st-del" title="음성 보관 기간(7일)이 지나 삭제됨">음성 삭제됨</span>}
|
||||
{active && <span className="playing-tag">{playing ? '▶ 재생 중' : '❚❚ 일시정지'}</span>}
|
||||
</>
|
||||
);
|
||||
const editBtn = !item.noise && item.status !== 'pending' && onUpdate && (
|
||||
<button className="icon-btn edit-btn" title="텍스트 교정" aria-label="텍스트 교정" onClick={edit}>
|
||||
<IEdit width={15} height={15} />
|
||||
</button>
|
||||
);
|
||||
|
||||
if (variant === 'compact') {
|
||||
return (
|
||||
<div className={`l utt${active ? ' cur' : ''}${item.noise ? ' is-noise' : ''}`} onClick={click} data-id={item.id}>
|
||||
<span className="t mono" data-tip={realTip(item.ts)}>
|
||||
{timeText ?? item.time.primary}
|
||||
</span>
|
||||
<div className="lb">
|
||||
<b style={{ color: user?.color }}>{user?.name ?? '알 수 없음'}</b>
|
||||
{sub && <span className="dim sub"> · {sub}</span>} {badges}
|
||||
{editing ? (
|
||||
<Editor item={item} onDone={done} />
|
||||
) : (
|
||||
<div className="txt">
|
||||
<Text item={item} active={active} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{!editing && editBtn}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`it utt${active ? ' playing' : ''}${item.noise ? ' is-noise' : ''}`} onClick={click} data-id={item.id}>
|
||||
<TimeCell time={item.time} real={!item.game} />
|
||||
<Avatar user={user} size={30} />
|
||||
<div className="body">
|
||||
<div className="who">
|
||||
<span style={{ color: user?.color ?? '#8696a6' }}>{user?.name ?? '알 수 없음'}</span>
|
||||
{sub && <span className="dim sub">· {sub}</span>}
|
||||
{badges}
|
||||
</div>
|
||||
{editing ? (
|
||||
<Editor item={item} onDone={done} />
|
||||
) : (
|
||||
<div className="txt">
|
||||
<Text item={item} active={active} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{!editing && editBtn}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
105
site/web/src/components/common.tsx
Normal file
105
site/web/src/components/common.tsx
Normal file
@@ -0,0 +1,105 @@
|
||||
import type { CSSProperties, ReactNode } from 'react';
|
||||
import type { PlayerRef, TimeLabel, User } from '@gvr/shared';
|
||||
import { useData } from '../store/app';
|
||||
import { realTip } from '../lib/format';
|
||||
|
||||
export function Brand({ compact = false }: { compact?: boolean }) {
|
||||
return (
|
||||
<div className={`brand${compact ? ' compact' : ''}`}>
|
||||
<img src="/icon-192.png" alt="" />
|
||||
<div>
|
||||
<div className="nm">겜녹이</div>
|
||||
{!compact && <div className="en">GAME VOICE RECORDER</div>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Avatar({ user, size = 28, name, color, src }: { user?: User | null; size?: number; name?: string; color?: string; src?: string | null }) {
|
||||
const nm = user?.name ?? name ?? '?';
|
||||
const bg = user?.color ?? color ?? '#3a4654';
|
||||
const img = user?.avatar ?? src;
|
||||
const style: CSSProperties = { width: size, height: size, fontSize: Math.round(size * 0.42), background: bg };
|
||||
return (
|
||||
<span className="av" style={style} title={nm}>
|
||||
{img ? <img src={img} alt="" /> : nm.slice(0, 1)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** 요원 · 챔피언 아이콘. icon 이 null 이면 이름 첫 글자 */
|
||||
export function CharIcon({ c, size = 24, className = '' }: { c?: { name: string; icon: string | null } | null; size?: number; className?: string }) {
|
||||
if (!c) return null;
|
||||
const style: CSSProperties = { width: size, height: size };
|
||||
return c.icon ? (
|
||||
<img className={`ag ${className}`} src={c.icon} alt={c.name} title={c.name} style={style} loading="lazy" />
|
||||
) : (
|
||||
<span className={`ag ag-fallback ${className}`} style={{ ...style, fontSize: Math.round(size * 0.45) }} title={c.name}>
|
||||
{c.name.slice(0, 1)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** 플레이어 이름: 디스코드 유저와 연결돼 있으면 유저 색 */
|
||||
export function PName({ p, strong = true }: { p: PlayerRef | null | undefined; strong?: boolean }) {
|
||||
const { userById } = useData();
|
||||
if (!p) return <span className="dim">?</span>;
|
||||
const u = userById(p.userId);
|
||||
const Tag = strong ? 'b' : 'span';
|
||||
return <Tag style={u ? { color: u.color } : undefined}>{u?.name ?? p.name}</Tag>;
|
||||
}
|
||||
|
||||
export function UserName({ id, fallback = '알 수 없음' }: { id: string | undefined; fallback?: string }) {
|
||||
const { userById } = useData();
|
||||
const u = userById(id);
|
||||
return <b style={{ color: u?.color ?? '#8696a6' }}>{u?.name ?? fallback}</b>;
|
||||
}
|
||||
|
||||
/** 시간 칸: 주 표시 + 보조 표시, 마우스를 올리면 현실 시간 */
|
||||
export function TimeCell({ time, real = false, className = '' }: { time: TimeLabel; real?: boolean; className?: string }) {
|
||||
return (
|
||||
<div className={`time mono ${real ? 'real' : ''} ${className}`} data-tip={realTip(time.real)}>
|
||||
{time.primary}
|
||||
<small>{time.secondary ?? (real ? '현실 시간' : '')}</small>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Panel({ title, right, children, className = '' }: { title: ReactNode; right?: ReactNode; children: ReactNode; className?: string }) {
|
||||
return (
|
||||
<section className={`panel ${className}`}>
|
||||
<h4>
|
||||
<span>{title}</span>
|
||||
{right && <span className="ph-right">{right}</span>}
|
||||
</h4>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function Spinner({ label = '불러오는 중' }: { label?: string }) {
|
||||
return (
|
||||
<div className="spinner" role="status">
|
||||
<i />
|
||||
<i />
|
||||
<i />
|
||||
<span>{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBox({ error, onRetry }: { error: unknown; onRetry?: () => void }) {
|
||||
const code = (error as { code?: string; status?: number })?.code;
|
||||
const status = (error as { status?: number })?.status;
|
||||
const msg = code === 'device_offline' ? '게임 PC와 연결이 끊어져 있습니다' : status === 404 ? '찾을 수 없습니다' : code === 'network' ? '네트워크 오류' : '불러오지 못했습니다';
|
||||
return (
|
||||
<div className="errbox">
|
||||
<span>{msg}</span>
|
||||
{onRetry && (
|
||||
<button className="btn" onClick={onRetry}>
|
||||
다시 시도
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
123
site/web/src/lib/api.ts
Normal file
123
site/web/src/lib/api.ts
Normal file
@@ -0,0 +1,123 @@
|
||||
import type {
|
||||
DeviceStatus,
|
||||
MatchDetail,
|
||||
MatchSummary,
|
||||
Overview,
|
||||
TimelinePage,
|
||||
UserProfile,
|
||||
User,
|
||||
UtteranceItem,
|
||||
GameType,
|
||||
} from '@gvr/shared';
|
||||
|
||||
/** 전역 신호: 401 → 로그인 화면, 503 device_offline → 잠금 화면 */
|
||||
type Signal = 'unauthorized' | 'not_member' | 'device_offline';
|
||||
const listeners = new Set<(s: Signal) => void>();
|
||||
export function onApiSignal(fn: (s: Signal) => void): () => void {
|
||||
listeners.add(fn);
|
||||
return () => listeners.delete(fn);
|
||||
}
|
||||
const emit = (s: Signal) => listeners.forEach((fn) => fn(s));
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
public code: string,
|
||||
) {
|
||||
super(`${status} ${code}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(path, {
|
||||
credentials: 'include',
|
||||
...init,
|
||||
headers: { accept: 'application/json', ...(init.body ? { 'content-type': 'application/json' } : {}), ...init.headers },
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(0, 'network');
|
||||
}
|
||||
if (res.ok) {
|
||||
if (res.status === 204) return undefined as T;
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
let code = 'error';
|
||||
try {
|
||||
code = ((await res.json()) as { error?: string }).error ?? code;
|
||||
} catch {
|
||||
/* 본문 없음 */
|
||||
}
|
||||
if (res.status === 401) emit('unauthorized');
|
||||
else if (res.status === 403 && code === 'not_member') emit('not_member');
|
||||
else if (res.status === 503 && code === 'device_offline') emit('device_offline');
|
||||
throw new ApiError(res.status, code);
|
||||
}
|
||||
|
||||
export interface Me {
|
||||
user: { id: string; name: string; avatar: string | null };
|
||||
isOwner: boolean;
|
||||
}
|
||||
export interface StatusResponse {
|
||||
device: DeviceStatus;
|
||||
server: { version: string };
|
||||
}
|
||||
|
||||
export interface TimelineQuery {
|
||||
users?: string[];
|
||||
game?: GameType | 'none';
|
||||
match?: string;
|
||||
from?: number;
|
||||
to?: number;
|
||||
q?: string;
|
||||
types?: string[];
|
||||
hideNoise?: boolean;
|
||||
cursor?: string | null;
|
||||
limit?: number;
|
||||
order?: 'asc' | 'desc';
|
||||
}
|
||||
|
||||
function qs(o: Record<string, string | number | undefined | null>): string {
|
||||
const p = new URLSearchParams();
|
||||
for (const [k, v] of Object.entries(o)) if (v !== undefined && v !== null && v !== '') p.set(k, String(v));
|
||||
const s = p.toString();
|
||||
return s ? `?${s}` : '';
|
||||
}
|
||||
|
||||
export const api = {
|
||||
/** /auth/me 는 401/403 을 신호로 돌리지 않고 호출자가 직접 처리한다 */
|
||||
async me(): Promise<{ ok: true; me: Me } | { ok: false; reason: 'anon' | 'not_member' }> {
|
||||
const res = await fetch('/auth/me', { credentials: 'include', headers: { accept: 'application/json' } });
|
||||
if (res.ok) return { ok: true, me: (await res.json()) as Me };
|
||||
if (res.status === 403) return { ok: false, reason: 'not_member' };
|
||||
return { ok: false, reason: 'anon' };
|
||||
},
|
||||
logout: () => fetch('/auth/logout', { method: 'POST', credentials: 'include' }),
|
||||
/** 관리자(OWNER_DISCORD_IDS) 전용: 게임 PC 1회용 등록 코드 (10분) */
|
||||
registrationCode: () => request<{ code: string; expiresAt: number }>('/admin/registration-code', { method: 'POST' }),
|
||||
status: () => request<StatusResponse>('/api/status'),
|
||||
overview: () => request<Overview>('/api/overview'),
|
||||
users: () => request<User[]>('/api/users'),
|
||||
user: (id: string) => request<UserProfile>(`/api/users/${encodeURIComponent(id)}`),
|
||||
timeline: (q: TimelineQuery) =>
|
||||
request<TimelinePage>(
|
||||
`/api/timeline${qs({
|
||||
users: q.users?.length ? q.users.join(',') : undefined,
|
||||
game: q.game,
|
||||
match: q.match,
|
||||
from: q.from,
|
||||
to: q.to,
|
||||
q: q.q,
|
||||
types: q.types?.length ? q.types.join(',') : undefined,
|
||||
hideNoise: q.hideNoise ? 1 : undefined,
|
||||
cursor: q.cursor,
|
||||
limit: q.limit ?? 100,
|
||||
order: q.order,
|
||||
})}`,
|
||||
),
|
||||
matches: (o: { game?: GameType; limit?: number; before?: number } = {}) => request<MatchSummary[]>(`/api/matches${qs(o)}`),
|
||||
match: (id: string) => request<MatchDetail>(`/api/matches/${encodeURIComponent(id)}`),
|
||||
correct: (id: string, text: string) =>
|
||||
request<UtteranceItem>(`/api/utterances/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ text }) }),
|
||||
};
|
||||
38
site/web/src/lib/audio.ts
Normal file
38
site/web/src/lib/audio.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
/** 공용 AudioContext 와 출력 체인 (플레이어 + 효과음) */
|
||||
let ctx: AudioContext | null = null;
|
||||
let playerBus: GainNode | null = null;
|
||||
let sfxBus: GainNode | null = null;
|
||||
|
||||
export function audioCtx(): AudioContext {
|
||||
if (!ctx) {
|
||||
ctx = new AudioContext({ latencyHint: 'interactive' });
|
||||
// 플레이어: 발화별 게인(+최대 20dB) 뒤에 리미터를 둬서 클리핑을 막는다
|
||||
const limiter = ctx.createDynamicsCompressor();
|
||||
limiter.threshold.value = -3;
|
||||
limiter.knee.value = 2;
|
||||
limiter.ratio.value = 20;
|
||||
limiter.attack.value = 0.002;
|
||||
limiter.release.value = 0.12;
|
||||
playerBus = ctx.createGain();
|
||||
playerBus.connect(limiter).connect(ctx.destination);
|
||||
sfxBus = ctx.createGain();
|
||||
sfxBus.connect(ctx.destination);
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export function resumeAudio() {
|
||||
const c = audioCtx();
|
||||
if (c.state === 'suspended') void c.resume();
|
||||
}
|
||||
|
||||
export function playerOutput(): GainNode {
|
||||
audioCtx();
|
||||
return playerBus!;
|
||||
}
|
||||
export function sfxOutput(): GainNode {
|
||||
audioCtx();
|
||||
return sfxBus!;
|
||||
}
|
||||
|
||||
export const dbToGain = (db: number) => Math.pow(10, db / 20);
|
||||
86
site/web/src/lib/filters.ts
Normal file
86
site/web/src/lib/filters.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import type { GameType, TimelineItem } from '@gvr/shared';
|
||||
import type { TimelineQuery } from './api';
|
||||
import { itemGame, itemMatch, typeGroup, type TypeGroup } from './game';
|
||||
|
||||
/** URL 쿼리에 남기는 타임라인 필터 (공유 가능한 링크) */
|
||||
export interface Filters {
|
||||
users: string[];
|
||||
game: GameType | 'none' | null;
|
||||
match: string | null;
|
||||
from: number | undefined;
|
||||
to: number | undefined;
|
||||
q: string;
|
||||
types: TypeGroup[];
|
||||
hideNoise: boolean;
|
||||
order: 'asc' | 'desc' | null;
|
||||
}
|
||||
|
||||
const num = (v: string | null) => (v && !isNaN(Number(v)) ? Number(v) : undefined);
|
||||
|
||||
export function parseFilters(p: URLSearchParams): Filters {
|
||||
const game = p.get('game');
|
||||
const order = p.get('order');
|
||||
return {
|
||||
users: p.get('users')?.split(',').filter(Boolean) ?? [],
|
||||
game: game === 'valorant' || game === 'lol' || game === 'none' ? game : null,
|
||||
match: p.get('match') || null,
|
||||
from: num(p.get('from')),
|
||||
to: num(p.get('to')),
|
||||
q: p.get('q') ?? '',
|
||||
types: (p.get('types')?.split(',').filter(Boolean) ?? []) as TypeGroup[],
|
||||
hideNoise: p.get('hideNoise') === '1',
|
||||
order: order === 'asc' || order === 'desc' ? order : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function writeFilters(f: Filters): URLSearchParams {
|
||||
const p = new URLSearchParams();
|
||||
if (f.users.length) p.set('users', f.users.join(','));
|
||||
if (f.game) p.set('game', f.game);
|
||||
if (f.match) p.set('match', f.match);
|
||||
if (f.from != null) p.set('from', String(f.from));
|
||||
if (f.to != null) p.set('to', String(f.to));
|
||||
if (f.q) p.set('q', f.q);
|
||||
if (f.types.length) p.set('types', f.types.join(','));
|
||||
if (f.hideNoise) p.set('hideNoise', '1');
|
||||
if (f.order) p.set('order', f.order);
|
||||
return p;
|
||||
}
|
||||
|
||||
/** 경기 필터가 있으면 경기 기록처럼 시간순(asc), 아니면 최신순(desc) */
|
||||
export const effectiveOrder = (f: Filters): 'asc' | 'desc' => f.order ?? (f.match ? 'asc' : 'desc');
|
||||
|
||||
export function toQuery(f: Filters): TimelineQuery {
|
||||
return {
|
||||
users: f.users,
|
||||
game: f.game ?? undefined,
|
||||
match: f.match ?? undefined,
|
||||
from: f.from,
|
||||
to: f.to,
|
||||
q: f.q || undefined,
|
||||
types: f.types,
|
||||
hideNoise: f.hideNoise,
|
||||
order: effectiveOrder(f),
|
||||
};
|
||||
}
|
||||
|
||||
/** 실시간으로 들어온 항목이 지금 필터에 맞는지 (서버 필터와 같은 규칙) */
|
||||
export function matchesFilter(it: TimelineItem, f: Filters): boolean {
|
||||
if (f.from != null && it.ts < f.from) return false;
|
||||
if (f.to != null && it.ts > f.to) return false;
|
||||
const g = itemGame(it);
|
||||
if (f.game === 'none' && g) return false;
|
||||
if (f.game && f.game !== 'none' && g !== f.game) return false;
|
||||
if (f.match && itemMatch(it) !== f.match) return false;
|
||||
if (f.types.length && !f.types.includes(typeGroup(it))) return false;
|
||||
const kw = f.q.trim().toLowerCase();
|
||||
if (it.kind === 'utterance') {
|
||||
if (f.users.length && !f.users.includes(it.userId)) return false;
|
||||
if (f.hideNoise && it.noise) return false;
|
||||
if (kw && !(it.text ?? '').toLowerCase().includes(kw)) return false;
|
||||
} else {
|
||||
if (f.users.length && it.userId && !f.users.includes(it.userId)) return false;
|
||||
if (kw && !(it.type === 'chat' && String(it.data?.text ?? '').toLowerCase().includes(kw))) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
71
site/web/src/lib/format.ts
Normal file
71
site/web/src/lib/format.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { fmtReal } from '@gvr/shared';
|
||||
|
||||
export { fmtClock, fmtReal } from '@gvr/shared';
|
||||
|
||||
const TZ = 'Asia/Seoul';
|
||||
const dayKey = (ts: number) => new Intl.DateTimeFormat('en-CA', { timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit' }).format(ts);
|
||||
|
||||
/** "오늘 23:41" / "어제 21:10" / "10월 7일 21:10" */
|
||||
export function fmtWhen(ts: number): string {
|
||||
const hm = new Intl.DateTimeFormat('ko-KR', { timeZone: TZ, hour: '2-digit', minute: '2-digit', hour12: false }).format(ts);
|
||||
const k = dayKey(ts);
|
||||
if (k === dayKey(Date.now())) return `오늘 ${hm}`;
|
||||
if (k === dayKey(Date.now() - 86400000)) return `어제 ${hm}`;
|
||||
const md = new Intl.DateTimeFormat('ko-KR', { timeZone: TZ, month: 'long', day: 'numeric' }).format(ts);
|
||||
return `${md} ${hm}`;
|
||||
}
|
||||
|
||||
export function fmtHM(ts: number): string {
|
||||
return new Intl.DateTimeFormat('ko-KR', { timeZone: TZ, hour: '2-digit', minute: '2-digit', hour12: false }).format(ts);
|
||||
}
|
||||
|
||||
export function fmtDate(ts: number): string {
|
||||
return new Intl.DateTimeFormat('ko-KR', { timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit' }).format(ts).replace(/\.\s?/g, '-').replace(/-$/, '');
|
||||
}
|
||||
|
||||
/** "12분 전" */
|
||||
export function fmtAgo(ts: number, now = Date.now()): string {
|
||||
const s = Math.max(0, Math.round((now - ts) / 1000));
|
||||
if (s < 60) return '방금';
|
||||
const m = Math.round(s / 60);
|
||||
if (m < 60) return `${m}분 전`;
|
||||
const h = Math.round(m / 60);
|
||||
if (h < 24) return `${h}시간 전`;
|
||||
return `${Math.round(h / 24)}일 전`;
|
||||
}
|
||||
|
||||
/** 492000 → "8분 12초" */
|
||||
export function fmtDuration(ms: number): string {
|
||||
const s = Math.round(ms / 1000);
|
||||
const h = Math.floor(s / 3600);
|
||||
const m = Math.floor((s % 3600) / 60);
|
||||
const ss = s % 60;
|
||||
if (h) return `${h}시간 ${String(m).padStart(2, '0')}분`;
|
||||
if (m) return `${m}분 ${String(ss).padStart(2, '0')}초`;
|
||||
return `${ss}초`;
|
||||
}
|
||||
|
||||
/** 초 → "0:01.4" */
|
||||
export function fmtSec(sec: number): string {
|
||||
if (!isFinite(sec) || sec < 0) sec = 0;
|
||||
const m = Math.floor(sec / 60);
|
||||
const s = sec - m * 60;
|
||||
return `${m}:${s.toFixed(1).padStart(4, '0')}`;
|
||||
}
|
||||
|
||||
export function realTip(ts: number) {
|
||||
return `현실 시간 ${fmtWhen(ts).split(' ')[0]} ${fmtReal(ts)}`;
|
||||
}
|
||||
|
||||
/** "YYYY-MM-DD" (KST) ↔ ms */
|
||||
export function dateInputValue(ms: number | undefined): string {
|
||||
if (ms == null) return '';
|
||||
return dayKey(ms);
|
||||
}
|
||||
export function dateInputToMs(v: string, end = false): number | undefined {
|
||||
if (!v) return undefined;
|
||||
const t = Date.parse(`${v}T${end ? '23:59:59.999' : '00:00:00'}+09:00`);
|
||||
return isNaN(t) ? undefined : t;
|
||||
}
|
||||
|
||||
export const k = (n: number) => (Math.abs(n) >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
|
||||
97
site/web/src/lib/game.ts
Normal file
97
site/web/src/lib/game.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import type { EventItem, MatchDetail, TimelineItem } from '@gvr/shared';
|
||||
|
||||
export const ROUND_RESULT_KO: Record<string, string> = {
|
||||
Elimination: '섬멸',
|
||||
'Bomb detonated': '스파이크 폭발',
|
||||
'Bomb defused': '스파이크 해체',
|
||||
'Round timer expired': '시간 초과',
|
||||
Surrendered: '항복',
|
||||
};
|
||||
export const roundResultKo = (r: string | undefined) => (r ? ROUND_RESULT_KO[r] ?? r : '');
|
||||
|
||||
export const OBJECT_KO: Record<string, string> = {
|
||||
dragon: '드래곤',
|
||||
baron: '내셔 남작',
|
||||
herald: '협곡의 전령',
|
||||
grub: '공허 유충',
|
||||
tower: '포탑',
|
||||
inhibitor: '억제기',
|
||||
atakhan: '아타칸',
|
||||
};
|
||||
export const DRAGON_KO: Record<string, string> = {
|
||||
infernal: '화염',
|
||||
ocean: '바다',
|
||||
mountain: '대지',
|
||||
cloud: '바람',
|
||||
hextech: '마법공학',
|
||||
chemtech: '화학공학',
|
||||
elder: '장로',
|
||||
};
|
||||
export function objectName(object: string, subtype?: string) {
|
||||
if (object === 'dragon' && subtype && DRAGON_KO[subtype]) return `${DRAGON_KO[subtype]} 드래곤`;
|
||||
return OBJECT_KO[object] ?? object;
|
||||
}
|
||||
export const OBJECT_GLYPH: Record<string, string> = {
|
||||
dragon: '🐉',
|
||||
baron: '👾',
|
||||
herald: '🦀',
|
||||
grub: '🪲',
|
||||
tower: '🗼',
|
||||
inhibitor: '💠',
|
||||
atakhan: '😈',
|
||||
};
|
||||
|
||||
export const CHANNEL_KO: Record<string, string> = { team: '팀', all: '전체', party: '파티', system: '시스템' };
|
||||
export const MULTI_KO = ['', '', '더블 킬', '트리플 킬', '쿼드라 킬', '펜타 킬'];
|
||||
|
||||
/** 발로란트 게임 좌표 → 미니맵 비율 (valorant-api.com 맵 변환값) */
|
||||
export function valorantUV(t: { xMultiplier: number; yMultiplier: number; xScalarToAdd: number; yScalarToAdd: number }, p: { x: number; y: number }) {
|
||||
return { u: p.y * t.xMultiplier + t.xScalarToAdd, v: p.x * t.yMultiplier + t.yScalarToAdd };
|
||||
}
|
||||
/** 롤 게임 좌표 → 지도 비율 (y축 뒤집기) */
|
||||
export function lolUV(t: { minX: number; minY: number; maxX: number; maxY: number }, p: { x: number; y: number }) {
|
||||
return { u: (p.x - t.minX) / (t.maxX - t.minX), v: 1 - (p.y - t.minY) / (t.maxY - t.minY) };
|
||||
}
|
||||
export function toUV(m: MatchDetail, p: { x: number; y: number } | null | undefined): { u: number; v: number } | null {
|
||||
if (!p || !m.mapTransform) return null;
|
||||
if ('valorant' in m.mapTransform) return valorantUV(m.mapTransform.valorant, p);
|
||||
if ('lol' in m.mapTransform) return lolUV(m.mapTransform.lol, p);
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 롤 오브젝트 기본 위치 (이벤트에 좌표가 없을 때) */
|
||||
export const LOL_OBJECT_POS: Record<string, { x: number; y: number }> = {
|
||||
dragon: { x: 9866, y: 4414 },
|
||||
baron: { x: 4942, y: 10395 },
|
||||
herald: { x: 4942, y: 10395 },
|
||||
grub: { x: 4942, y: 10395 },
|
||||
atakhan: { x: 7400, y: 7400 },
|
||||
};
|
||||
|
||||
/** 이벤트 종류 필터 그룹 (URL types 값) */
|
||||
export type TypeGroup = 'utterance' | 'kill' | 'chat' | 'object' | 'round';
|
||||
export const TYPE_GROUPS: { id: TypeGroup; label: string; icon: string }[] = [
|
||||
{ id: 'utterance', label: '발화', icon: '🎙' },
|
||||
{ id: 'kill', label: '킬·데스', icon: '⚔' },
|
||||
{ id: 'chat', label: '채팅', icon: '💬' },
|
||||
{ id: 'object', label: '오브젝트', icon: '🐉' },
|
||||
{ id: 'round', label: '라운드', icon: '🏆' },
|
||||
];
|
||||
export function typeGroup(it: TimelineItem): TypeGroup {
|
||||
if (it.kind === 'utterance') return 'utterance';
|
||||
switch ((it as EventItem).type) {
|
||||
case 'kill':
|
||||
case 'multikill':
|
||||
case 'ace':
|
||||
return 'kill';
|
||||
case 'chat':
|
||||
return 'chat';
|
||||
case 'object':
|
||||
return 'object';
|
||||
default:
|
||||
return 'round';
|
||||
}
|
||||
}
|
||||
|
||||
export const itemGame = (it: TimelineItem) => (it.kind === 'utterance' ? it.game?.type ?? null : it.game);
|
||||
export const itemMatch = (it: TimelineItem) => (it.kind === 'utterance' ? it.game?.matchId ?? null : it.matchId);
|
||||
108
site/web/src/lib/live.ts
Normal file
108
site/web/src/lib/live.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import type { BrowserMessage } from '@gvr/shared';
|
||||
|
||||
/**
|
||||
* 브라우저 WS `/ws` 클라이언트. 끊기면 지수 백오프(1s → 15s, 지터)로 다시 붙는다.
|
||||
* 메시지는 구독자에게 그대로 전달한다 ({type:'status'} + 5장 이벤트).
|
||||
*/
|
||||
export type LiveConn = 'connecting' | 'open' | 'closed';
|
||||
|
||||
type MsgFn = (m: BrowserMessage) => void;
|
||||
type ConnFn = (c: LiveConn) => void;
|
||||
|
||||
class LiveSocket {
|
||||
private ws: WebSocket | null = null;
|
||||
private attempt = 0;
|
||||
private timer: number | null = null;
|
||||
private stopped = true;
|
||||
private msgFns = new Set<MsgFn>();
|
||||
private connFns = new Set<ConnFn>();
|
||||
conn: LiveConn = 'closed';
|
||||
|
||||
start() {
|
||||
if (!this.stopped) return;
|
||||
this.stopped = false;
|
||||
this.connect();
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.stopped = true;
|
||||
if (this.timer) window.clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
this.ws?.close();
|
||||
this.ws = null;
|
||||
this.setConn('closed');
|
||||
}
|
||||
|
||||
/** 즉시 재연결 시도 (잠금 화면의 "지금 다시 확인") */
|
||||
kick() {
|
||||
if (this.stopped || this.conn === 'open') return;
|
||||
if (this.timer) window.clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
this.attempt = 0;
|
||||
this.connect();
|
||||
}
|
||||
|
||||
onMessage(fn: MsgFn) {
|
||||
this.msgFns.add(fn);
|
||||
return () => {
|
||||
this.msgFns.delete(fn);
|
||||
};
|
||||
}
|
||||
onConn(fn: ConnFn) {
|
||||
this.connFns.add(fn);
|
||||
return () => {
|
||||
this.connFns.delete(fn);
|
||||
};
|
||||
}
|
||||
|
||||
private setConn(c: LiveConn) {
|
||||
this.conn = c;
|
||||
this.connFns.forEach((fn) => fn(c));
|
||||
}
|
||||
|
||||
private connect() {
|
||||
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
let ws: WebSocket;
|
||||
try {
|
||||
ws = new WebSocket(`${proto}://${location.host}/ws`);
|
||||
} catch {
|
||||
this.schedule();
|
||||
return;
|
||||
}
|
||||
this.ws = ws;
|
||||
this.setConn('connecting');
|
||||
ws.onopen = () => {
|
||||
this.attempt = 0;
|
||||
this.setConn('open');
|
||||
};
|
||||
ws.onmessage = (e) => {
|
||||
let m: BrowserMessage;
|
||||
try {
|
||||
m = JSON.parse(String(e.data)) as BrowserMessage;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
this.msgFns.forEach((fn) => fn(m));
|
||||
};
|
||||
ws.onclose = () => {
|
||||
if (this.ws !== ws) return;
|
||||
this.ws = null;
|
||||
this.setConn('closed');
|
||||
this.schedule();
|
||||
};
|
||||
ws.onerror = () => ws.close();
|
||||
}
|
||||
|
||||
private schedule() {
|
||||
if (this.stopped) return;
|
||||
const base = Math.min(15000, 1000 * 2 ** this.attempt);
|
||||
this.attempt++;
|
||||
const delay = base * (0.75 + Math.random() * 0.5);
|
||||
this.timer = window.setTimeout(() => {
|
||||
this.timer = null;
|
||||
this.connect();
|
||||
}, delay);
|
||||
}
|
||||
}
|
||||
|
||||
export const live = new LiveSocket();
|
||||
118
site/web/src/lib/sfx.ts
Normal file
118
site/web/src/lib/sfx.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import { audioCtx, sfxOutput } from './audio';
|
||||
import { settings, type SfxKind } from '../store/settings';
|
||||
|
||||
/**
|
||||
* 효과음은 전부 Web Audio 로 즉석 합성한다 (음원 파일 · 라이선스 없음).
|
||||
* 사용자 제스처 전에는 AudioContext 가 잠겨 있으므로 조용히 건너뛴다.
|
||||
*/
|
||||
let noiseBuf: AudioBuffer | null = null;
|
||||
function noise(ctx: AudioContext) {
|
||||
if (!noiseBuf) {
|
||||
noiseBuf = ctx.createBuffer(1, ctx.sampleRate * 0.6, ctx.sampleRate);
|
||||
const d = noiseBuf.getChannelData(0);
|
||||
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
|
||||
}
|
||||
const s = ctx.createBufferSource();
|
||||
s.buffer = noiseBuf;
|
||||
return s;
|
||||
}
|
||||
|
||||
function env(ctx: AudioContext, peak: number, attack: number, decay: number, at: number) {
|
||||
const g = ctx.createGain();
|
||||
g.gain.setValueAtTime(0.0001, at);
|
||||
g.gain.exponentialRampToValueAtTime(peak, at + attack);
|
||||
g.gain.exponentialRampToValueAtTime(0.0001, at + attack + decay);
|
||||
return g;
|
||||
}
|
||||
|
||||
function tone(ctx: AudioContext, out: AudioNode, type: OscillatorType, f0: number, f1: number, at: number, dur: number, peak: number) {
|
||||
const o = ctx.createOscillator();
|
||||
o.type = type;
|
||||
o.frequency.setValueAtTime(f0, at);
|
||||
o.frequency.exponentialRampToValueAtTime(f1, at + dur);
|
||||
const g = env(ctx, peak, 0.004, dur, at);
|
||||
o.connect(g).connect(out);
|
||||
o.start(at);
|
||||
o.stop(at + dur + 0.05);
|
||||
}
|
||||
|
||||
const SYNTH: Record<SfxKind, (ctx: AudioContext, out: AudioNode, t: number) => void> = {
|
||||
// 짧은 틱
|
||||
click(ctx, out, t) {
|
||||
tone(ctx, out, 'sine', 2100, 1500, t, 0.03, 0.18);
|
||||
const n = noise(ctx);
|
||||
const hp = ctx.createBiquadFilter();
|
||||
hp.type = 'highpass';
|
||||
hp.frequency.value = 4000;
|
||||
n.connect(hp).connect(env(ctx, 0.08, 0.001, 0.015, t)).connect(out);
|
||||
n.start(t);
|
||||
n.stop(t + 0.03);
|
||||
},
|
||||
// 재생 시작: 위로 올라가는 두 음
|
||||
play(ctx, out, t) {
|
||||
tone(ctx, out, 'triangle', 660, 680, t, 0.08, 0.22);
|
||||
tone(ctx, out, 'triangle', 990, 1000, t + 0.065, 0.12, 0.2);
|
||||
},
|
||||
// 킬: 짧은 사각파 블립 + 하강
|
||||
kill(ctx, out, t) {
|
||||
const bp = ctx.createBiquadFilter();
|
||||
bp.type = 'bandpass';
|
||||
bp.frequency.value = 1400;
|
||||
bp.Q.value = 1.2;
|
||||
bp.connect(out);
|
||||
tone(ctx, bp, 'square', 1250, 520, t, 0.09, 0.3);
|
||||
tone(ctx, out, 'sine', 180, 90, t, 0.12, 0.25);
|
||||
},
|
||||
// 라운드 전환: 대역 통과 잡음 스윕 (휙)
|
||||
round(ctx, out, t) {
|
||||
const n = noise(ctx);
|
||||
const bp = ctx.createBiquadFilter();
|
||||
bp.type = 'bandpass';
|
||||
bp.Q.value = 2.5;
|
||||
bp.frequency.setValueAtTime(300, t);
|
||||
bp.frequency.exponentialRampToValueAtTime(3800, t + 0.32);
|
||||
const g = ctx.createGain();
|
||||
g.gain.setValueAtTime(0.0001, t);
|
||||
g.gain.exponentialRampToValueAtTime(0.5, t + 0.16);
|
||||
g.gain.exponentialRampToValueAtTime(0.0001, t + 0.42);
|
||||
n.connect(bp).connect(g).connect(out);
|
||||
n.start(t);
|
||||
n.stop(t + 0.45);
|
||||
},
|
||||
// 새 발화 알림: 맑은 두 음 종소리
|
||||
chime(ctx, out, t) {
|
||||
for (const [f, d, p] of [
|
||||
[1046.5, 0.7, 0.16],
|
||||
[1568, 0.55, 0.1],
|
||||
[2093, 0.3, 0.04],
|
||||
] as const) {
|
||||
tone(ctx, out, 'sine', f, f * 0.998, t, d, p);
|
||||
}
|
||||
tone(ctx, out, 'sine', 1318.5, 1318, t + 0.09, 0.6, 0.12);
|
||||
},
|
||||
};
|
||||
|
||||
let last: Partial<Record<SfxKind, number>> = {};
|
||||
export function sfx(kind: SfxKind) {
|
||||
const s = settings.get();
|
||||
if (!s.sfx[kind] || s.volume <= 0) return;
|
||||
const ctx = audioCtx();
|
||||
if (ctx.state !== 'running') return;
|
||||
const now = ctx.currentTime;
|
||||
// 같은 효과음이 몰려도 귀가 아프지 않게 60ms 안 중복은 생략
|
||||
if ((last[kind] ?? -1) > now - 0.06) return;
|
||||
last = { ...last, [kind]: now };
|
||||
const out = ctx.createGain();
|
||||
out.gain.value = s.volume * 0.7;
|
||||
out.connect(sfxOutput());
|
||||
SYNTH[kind](ctx, out, now + 0.005);
|
||||
window.setTimeout(() => out.disconnect(), 1500);
|
||||
}
|
||||
|
||||
export const SFX_LABEL: Record<SfxKind, string> = {
|
||||
click: '버튼 클릭 틱',
|
||||
play: '재생 시작',
|
||||
kill: '킬 이벤트',
|
||||
round: '라운드 전환',
|
||||
chime: '새 발화 알림',
|
||||
};
|
||||
13
site/web/src/main.tsx
Normal file
13
site/web/src/main.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router';
|
||||
import { App } from './App';
|
||||
import './styles.css';
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</StrictMode>,
|
||||
);
|
||||
371
site/web/src/pages/LolMatch.tsx
Normal file
371
site/web/src/pages/LolMatch.tsx
Normal file
@@ -0,0 +1,371 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useSearchParams } from 'react-router';
|
||||
import { motion } from 'framer-motion';
|
||||
import type { EventItem, KillData, MatchDetail, MatchPlayer, ObjectData, TimelineItem, UtteranceItem } from '@gvr/shared';
|
||||
import { player, usePlayer } from '../store/player';
|
||||
import { useData } from '../store/app';
|
||||
import { useReducedMotion } from '../store/settings';
|
||||
import { LOL_OBJECT_POS, OBJECT_GLYPH, objectName, toUV } from '../lib/game';
|
||||
import { fmtClock, k, realTip } from '../lib/format';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { CharIcon, Panel } from '../components/common';
|
||||
import { UtteranceRow } from '../components/UtteranceRow';
|
||||
import { EventBody, SeparatorRow } from '../components/EventRow';
|
||||
import { TalkBars } from '../components/TalkBars';
|
||||
import { IWaves } from '../components/Icons';
|
||||
import { matchMeta } from './MatchPage';
|
||||
|
||||
const WIN = 60000; // 지도에 보이는 구간: 선택 시각 ±60초
|
||||
type ObjEvent = EventItem & { data: ObjectData & { icon?: string | null; location?: { x: number; y: number } } };
|
||||
|
||||
function ObjIcon({ e, size = 18 }: { e: ObjEvent; size?: number }) {
|
||||
return e.data.icon ? (
|
||||
<img className="oi" src={e.data.icon} alt={objectName(e.data.object, e.data.subtype)} style={{ width: size, height: size }} />
|
||||
) : (
|
||||
<span style={{ fontSize: size * 0.8 }}>{OBJECT_GLYPH[e.data.object] ?? '◆'}</span>
|
||||
);
|
||||
}
|
||||
|
||||
function GoldGraph({ m, center, onPick }: { m: MatchDetail; center: number; onPick: (t: number) => void }) {
|
||||
const W = 470;
|
||||
const H = 80;
|
||||
const gd = m.goldDiff ?? [];
|
||||
const dur = (m.endedAt ?? m.startedAt + (gd[gd.length - 1]?.t ?? 1)) - m.startedAt;
|
||||
const maxAbs = Math.max(1000, ...gd.map((g) => Math.abs(g.diff)));
|
||||
const mid = 34;
|
||||
const x = (t: number) => (t / dur) * W;
|
||||
const y = (d: number) => mid - (d / maxAbs) * 30;
|
||||
const line = gd.map((g, i) => `${i ? 'L' : 'M'}${x(g.t).toFixed(1)} ${y(g.diff).toFixed(1)}`).join(' ');
|
||||
const area = gd.length ? `${line} L${x(gd[gd.length - 1].t).toFixed(1)} ${mid} L0 ${mid} Z` : '';
|
||||
const objs = m.events.filter((e): e is ObjEvent => e.type === 'object' && e.data.object !== 'tower' && e.data.object !== 'inhibitor');
|
||||
const towers = m.events.filter((e): e is ObjEvent => e.type === 'object' && (e.data.object === 'tower' || e.data.object === 'inhibitor'));
|
||||
const ts = usePlayer((s) => s.sceneTs);
|
||||
const [hover, setHover] = useState<number | null>(null);
|
||||
const play = ts != null && ts >= m.startedAt && ts <= m.startedAt + dur ? ts - m.startedAt : null;
|
||||
const at = (clientX: number, el: Element) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
return Math.max(0, Math.min(dur, ((clientX - r.left) / r.width) * dur));
|
||||
};
|
||||
const nearest = (t: number) => gd.reduce((b, g) => (Math.abs(g.t - t) < Math.abs(b.t - t) ? g : b), gd[0]);
|
||||
const final = gd[gd.length - 1]?.diff ?? 0;
|
||||
const hv = hover != null && gd.length ? nearest(hover) : null;
|
||||
return (
|
||||
<div className="goldgraph">
|
||||
<div className="gold-h">
|
||||
<span>골드 차이 (우리 팀 − 상대)</span>
|
||||
<span className="gold-final">
|
||||
최종 {final >= 0 ? '+' : ''}
|
||||
{k(final)}
|
||||
</span>
|
||||
</div>
|
||||
<svg
|
||||
viewBox={`0 0 ${W} ${H}`}
|
||||
width="100%"
|
||||
height={H}
|
||||
preserveAspectRatio="none"
|
||||
onMouseMove={(e) => setHover(at(e.clientX, e.currentTarget))}
|
||||
onMouseLeave={() => setHover(null)}
|
||||
onClick={(e) => onPick(at(e.clientX, e.currentTarget))}
|
||||
role="img"
|
||||
aria-label="골드 차이 그래프"
|
||||
>
|
||||
<line x1="0" y1={mid} x2={W} y2={mid} stroke="#2a3542" />
|
||||
<path d={area} fill="rgba(200,170,110,.12)" />
|
||||
<path d={line} fill="none" stroke="#c8aa6e" strokeWidth="2" vectorEffect="non-scaling-stroke" />
|
||||
<rect x={x(center - WIN)} y="0" width={x(2 * WIN)} height={H - 18} fill="rgba(10,200,185,.07)" />
|
||||
{objs.map((e) => (
|
||||
<image key={e.id} href={e.data.icon ?? undefined} x={x(e.ts - m.startedAt) - 8} y={H - 17} width="16" height="16" preserveAspectRatio="xMidYMid meet" />
|
||||
))}
|
||||
{towers.map((e) => (
|
||||
<rect key={e.id} x={x(e.ts - m.startedAt) - 1.5} y={H - 12} width="3" height="8" rx="1.5" fill={e.data.ally === false ? '#ff4655' : '#0ac8b9'} />
|
||||
))}
|
||||
{play != null && <line x1={x(play)} y1="0" x2={x(play)} y2={H - 18} stroke="#ff4655" strokeDasharray="3 3" vectorEffect="non-scaling-stroke" />}
|
||||
{hv && (
|
||||
<>
|
||||
<line x1={x(hv.t)} y1="0" x2={x(hv.t)} y2={H - 18} stroke="#f0e6d2" strokeOpacity=".5" vectorEffect="non-scaling-stroke" />
|
||||
<circle cx={x(hv.t)} cy={y(hv.diff)} r="3.5" fill="#c8aa6e" stroke="#010a13" strokeWidth="2" />
|
||||
</>
|
||||
)}
|
||||
</svg>
|
||||
{hv && (
|
||||
<div className="gold-tip" style={{ left: `${(x(hv.t) / W) * 100}%` }}>
|
||||
<span className="mono">{fmtClock(hv.t)}</span> · {hv.diff >= 0 ? '우리 팀 +' : '상대 +'}
|
||||
{k(Math.abs(hv.diff))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LolMap({ m, center }: { m: MatchDetail; center: number }) {
|
||||
const ts = usePlayer((s) => s.sceneTs);
|
||||
const reduce = useReducedMotion();
|
||||
const t0 = m.startedAt + center - WIN;
|
||||
const t1 = m.startedAt + center + WIN;
|
||||
const evs = m.events.filter((e) => e.ts >= t0 && e.ts <= t1);
|
||||
const kills = evs.filter((e) => e.type === 'kill');
|
||||
const objs = evs.filter((e): e is ObjEvent => e.type === 'object');
|
||||
const pts = kills.map((e) => toUV(m, (e.data as KillData).location)).filter((p): p is { u: number; v: number } => !!p);
|
||||
let ring: { u: number; v: number; r: number } | null = null;
|
||||
if (pts.length >= 3) {
|
||||
const cu = pts.reduce((s, p) => s + p.u, 0) / pts.length;
|
||||
const cv = pts.reduce((s, p) => s + p.v, 0) / pts.length;
|
||||
const r = Math.max(...pts.map((p) => Math.hypot(p.u - cu, p.v - cv)));
|
||||
if (r < 0.2) ring = { u: cu, v: cv, r: r + 0.04 };
|
||||
}
|
||||
return (
|
||||
<div className="map-sq lol-map">
|
||||
{m.map.image && <img src={m.map.image} alt="소환사의 협곡" />}
|
||||
{ring && <div className="mk ring" style={{ left: `${ring.u * 100}%`, top: `${ring.v * 100}%`, width: `${ring.r * 200}%`, height: `${ring.r * 200}%` }} />}
|
||||
{objs.map((e) => {
|
||||
const uv = toUV(m, e.data.location ?? LOL_OBJECT_POS[e.data.object]);
|
||||
if (!uv) return null;
|
||||
const hot = ts != null && ts - e.ts >= 0 && ts - e.ts < 5000;
|
||||
return (
|
||||
<div key={e.id} className={`mk o${hot ? ' hot' : ''}`} style={{ left: `${uv.u * 100}%`, top: `${uv.v * 100}%` }} data-tip={`${e.time.primary} ${objectName(e.data.object, e.data.subtype)}`}>
|
||||
<ObjIcon e={e} size={26} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{kills.map((e) => {
|
||||
const d = e.data as KillData;
|
||||
const uv = toUV(m, d.location);
|
||||
if (!uv) return null;
|
||||
const allyKill = d.ally ?? !!d.killer?.userId;
|
||||
const recent = ts != null && ts - e.ts >= 0 && ts - e.ts < 4000;
|
||||
const future = ts != null && ts >= t0 && ts <= t1 && e.ts > ts;
|
||||
return (
|
||||
<div
|
||||
key={e.id}
|
||||
className={`mk kill ${allyKill ? 'ally' : 'enemy'}${recent ? ' recent' : ''}${future ? ' future' : ''}`}
|
||||
style={{ left: `${uv.u * 100}%`, top: `${uv.v * 100}%` }}
|
||||
data-tip={`${e.time.primary} ${d.killer?.name ?? '?'} → ${d.victim.name}`}
|
||||
>
|
||||
{recent && d.killer && (
|
||||
<motion.span className={`mk-p ${allyKill ? '' : 'en'}`} initial={reduce ? false : { scale: 0.3, opacity: 0 }} animate={{ scale: 1, opacity: 1 }}>
|
||||
<CharIcon c={d.killer.character} size={26} />
|
||||
</motion.span>
|
||||
)}
|
||||
<span className="x">✕</span>
|
||||
{recent && !reduce && <span className="ping" />}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ObjSummary({ m }: { m: MatchDetail }) {
|
||||
const objs = m.events.filter((e): e is ObjEvent => e.type === 'object');
|
||||
const dragons = objs.filter((e) => e.data.object === 'dragon' && e.data.ally !== false);
|
||||
const barons = objs.filter((e) => e.data.object === 'baron' && e.data.ally !== false);
|
||||
const grubs = objs.filter((e) => e.data.object === 'grub' && e.data.ally !== false);
|
||||
const towersUs = objs.filter((e) => (e.data.object === 'tower' || e.data.object === 'inhibitor') && e.data.ally !== false).length;
|
||||
const towersThem = objs.filter((e) => (e.data.object === 'tower' || e.data.object === 'inhibitor') && e.data.ally === false).length;
|
||||
return (
|
||||
<div className="obj-sum">
|
||||
{dragons.length > 0 && (
|
||||
<span>
|
||||
{dragons.map((d) => (
|
||||
<ObjIcon key={d.id} e={d} />
|
||||
))}{' '}
|
||||
드래곤 {dragons.length}
|
||||
</span>
|
||||
)}
|
||||
{barons.map((b) => (
|
||||
<span key={b.id}>
|
||||
<ObjIcon e={b} /> 바론 {b.time.primary}
|
||||
</span>
|
||||
))}
|
||||
<span>
|
||||
{objs.find((o) => o.data.object === 'tower') && <ObjIcon e={objs.find((o) => o.data.object === 'tower')!} />} 포탑 {towersUs} : {towersThem}
|
||||
</span>
|
||||
{grubs.length > 0 && (
|
||||
<span>
|
||||
<ObjIcon e={grubs[0]} /> 공허 유충 {grubs.length}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LolScoreboard({ players }: { players: MatchPlayer[] }) {
|
||||
const { userById } = useData();
|
||||
return (
|
||||
<table className="score-tbl lol">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>소환사</th>
|
||||
<th>K/D/A</th>
|
||||
<th>CS</th>
|
||||
<th>골드</th>
|
||||
</tr>
|
||||
</thead>
|
||||
{[true, false].map((ally) => (
|
||||
<tbody key={String(ally)} className={ally ? 'ally' : 'enemy'}>
|
||||
<tr className="team-row">
|
||||
<td colSpan={4}>{ally ? '우리 팀' : '상대 팀'}</td>
|
||||
</tr>
|
||||
{players
|
||||
.filter((p) => p.ally === ally)
|
||||
.map((p) => {
|
||||
const u = userById(p.userId);
|
||||
return (
|
||||
<tr key={p.puuid} className={u ? 'linked' : ''}>
|
||||
<td>
|
||||
<div className="lp">
|
||||
<CharIcon c={p.character} size={28} className="ch" />
|
||||
<div>
|
||||
{u ? <b style={{ color: u.color }}>{u.name}</b> : <span>{p.tag ? `${p.name}#${p.tag}` : p.name}</span>}
|
||||
<div className="items">
|
||||
{(p.items ?? []).slice(0, 6).map((it, i) =>
|
||||
it.icon ? <img key={i} src={it.icon} alt={it.name} title={it.name} /> : <i key={i} title={it.name} />,
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="mono">
|
||||
{p.kills}/{p.deaths}/{p.assists}
|
||||
</td>
|
||||
<td className="mono">{p.cs ?? '—'}</td>
|
||||
<td className="mono">{p.gold != null ? k(p.gold) : '—'}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
))}
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
function LolRow({ it, m, onPick }: { it: TimelineItem; m: MatchDetail; onPick: (t: number) => void }) {
|
||||
const active = usePlayer((s) => it.kind === 'event' && s.sceneTs != null && s.sceneTs - it.ts >= 0 && s.sceneTs - it.ts < 3000);
|
||||
if (it.kind === 'utterance') {
|
||||
const char = m.players.find((p) => p.userId === it.userId)?.character.name;
|
||||
return <UtteranceRow item={it} variant="compact" sub={char} />;
|
||||
}
|
||||
if (it.type === 'match_start' || it.type === 'match_end') return <SeparatorRow e={it} />;
|
||||
return (
|
||||
<div className={`l evl${active ? ' flash' : ''}${it.type === 'object' ? ' glow' : ''}`} onClick={() => onPick(it.ts - m.startedAt)} data-tip={realTip(it.ts)}>
|
||||
<span className="t mono">{it.time.primary}</span>
|
||||
<EventBody e={it} iconSize={24} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 킬이 가장 몰린 구간 (기본 선택 시각) */
|
||||
function densest(m: MatchDetail) {
|
||||
const ks = m.events.filter((e) => e.type === 'kill').map((e) => e.ts - m.startedAt);
|
||||
let best = ks[0] ?? 0;
|
||||
let bestN = 0;
|
||||
for (const t of ks) {
|
||||
const n = ks.filter((x) => Math.abs(x - t) <= WIN).length;
|
||||
if (n > bestN) {
|
||||
bestN = n;
|
||||
best = t;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
export function LolMatch({ m }: { m: MatchDetail }) {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const meta = matchMeta(m);
|
||||
const def = useMemo(() => densest(m), [m]);
|
||||
const picked = params.get('t') != null ? Number(params.get('t')) * 1000 : def;
|
||||
// 재생 중이면 지도 구간이 재생 위치를 따라간다 (5초 단위)
|
||||
const follow = usePlayer((s) => (s.sceneTs != null && s.sceneTs >= m.startedAt && s.sceneTs <= (m.endedAt ?? Infinity) ? Math.round((s.sceneTs - m.startedAt) / 5000) * 5000 : null));
|
||||
const center = follow ?? picked;
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const items = useMemo(() => [...m.utterances, ...m.events].sort((a, b) => a.ts - b.ts), [m]);
|
||||
const pick = (t: number) => {
|
||||
sfx('click');
|
||||
const p = new URLSearchParams(params);
|
||||
p.set('t', String(Math.round(t / 1000)));
|
||||
setParams(p, { replace: true });
|
||||
};
|
||||
const curId = usePlayer((s) => (s.mode === 'single' ? s.item?.id ?? null : null));
|
||||
useEffect(() => {
|
||||
if (curId) listRef.current?.querySelector(`[data-id="${curId}"]`)?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
|
||||
}, [curId]);
|
||||
// 처음 열 때 선택 구간으로 스크롤
|
||||
useEffect(() => {
|
||||
const target = items.find((i) => i.ts >= m.startedAt + picked - 15000);
|
||||
if (target) listRef.current?.querySelector(`[data-id="${target.id}"]`)?.scrollIntoView({ block: 'start' });
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [m.id]);
|
||||
|
||||
const scene = () =>
|
||||
player.startScene({
|
||||
start: m.startedAt + center - WIN,
|
||||
end: m.startedAt + center + WIN,
|
||||
label: `소환사의 협곡 · ${fmtClock(center - WIN)} ~ ${fmtClock(center + WIN)}`,
|
||||
items: m.utterances,
|
||||
});
|
||||
|
||||
return (
|
||||
<main className="match lol theme-lol">
|
||||
<div className="mtop">
|
||||
<div>
|
||||
<div className="eyebrow">MATCH DETAIL · LEAGUE OF LEGENDS</div>
|
||||
<div className="mtitle h">
|
||||
{m.map.name}{' '}
|
||||
{m.score && (
|
||||
<span className="score">
|
||||
<span className="a">{m.score.ally}</span> <span className="dim colon">:</span> <span className="b">{m.score.enemy}</span>
|
||||
</span>
|
||||
)}
|
||||
{m.win != null && <span className={`res-badge ${m.win ? 'win' : 'loss'}`}>{m.win ? '승리' : '패배'}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="meta">
|
||||
{m.mode} · {meta.when} 시작 · {meta.dur}
|
||||
<br />
|
||||
대화 {m.utterances.length}개 · 킬 {meta.kills} · 오브젝트 {meta.objs} · 우리 팀 5명 중 {meta.voiced}명 음성 기록
|
||||
</div>
|
||||
<GoldGraph m={m} center={center} onPick={pick} />
|
||||
</div>
|
||||
<div className="mgrid">
|
||||
<Panel
|
||||
className="map-panel"
|
||||
title={`킬 · 오브젝트 위치 (${fmtClock(Math.max(0, center - WIN))} ~ ${fmtClock(center + WIN)})`}
|
||||
right={
|
||||
<button className="mini-btn" onClick={scene} title="이 구간의 발화를 실제 순서대로 겹쳐 재생">
|
||||
<IWaves width={12} height={12} /> 현장 모드
|
||||
</button>
|
||||
}
|
||||
>
|
||||
<div className="map-area lol-map-area">
|
||||
<LolMap m={m} center={center} />
|
||||
</div>
|
||||
<ObjSummary m={m} />
|
||||
<div className="map-legend">
|
||||
<div>
|
||||
<span className="lg-ring" /> 우리 팀 <span className="lg-ring en" /> 상대 팀 <b className="accent">✕</b> 우리 팀 데스 <b className="hex">✕</b> 상대 데스
|
||||
</div>
|
||||
<div className="dim">위치는 경기 후 타임라인 좌표를 지도 위에 옮긴 것입니다. 그래프나 목록을 누르면 구간이 바뀝니다.</div>
|
||||
</div>
|
||||
</Panel>
|
||||
<Panel className="feed-panel" title="대화 · 킬 · 오브젝트 (게임 시간)" right="현실 시간은 마우스를 올리면 표시">
|
||||
<div className="feed scroll" ref={listRef}>
|
||||
{items.map((it) => (
|
||||
<div key={it.id} data-id={it.id}>
|
||||
<LolRow it={it} m={m} onPick={pick} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Panel>
|
||||
<Panel className="sb-panel" title="스코어보드" right="경기 종료 기준">
|
||||
<div className="scroll">
|
||||
<LolScoreboard players={m.players} />
|
||||
<h4 className="sub-h">
|
||||
<span>이 경기 발화량</span>
|
||||
</h4>
|
||||
<TalkBars utts={m.utterances as UtteranceItem[]} />
|
||||
</div>
|
||||
</Panel>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
61
site/web/src/pages/MatchPage.tsx
Normal file
61
site/web/src/pages/MatchPage.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link, useParams } from 'react-router';
|
||||
import type { MatchDetail } from '@gvr/shared';
|
||||
import { api } from '../lib/api';
|
||||
import { useStatus } from '../store/app';
|
||||
import { player } from '../store/player';
|
||||
import { ErrorBox, Spinner } from '../components/common';
|
||||
import { ValorantMatch } from './ValorantMatch';
|
||||
import { LolMatch } from './LolMatch';
|
||||
import { fmtDuration, fmtWhen } from '../lib/format';
|
||||
|
||||
export function matchMeta(m: MatchDetail) {
|
||||
const kills = m.events.filter((e) => e.type === 'kill').length;
|
||||
const chats = m.events.filter((e) => e.type === 'chat').length;
|
||||
const objs = m.events.filter((e) => e.type === 'object').length;
|
||||
const voiced = new Set(m.utterances.map((u) => u.userId)).size;
|
||||
return { kills, chats, objs, voiced, when: fmtWhen(m.startedAt), dur: m.endedAt ? fmtDuration(m.endedAt - m.startedAt) : '진행 중' };
|
||||
}
|
||||
|
||||
export function MatchPage() {
|
||||
const { id = '' } = useParams();
|
||||
const { epoch } = useStatus();
|
||||
const [m, setM] = useState<MatchDetail | null>(null);
|
||||
const [err, setErr] = useState<unknown>(null);
|
||||
const [n, setN] = useState(0);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
setErr(null);
|
||||
api
|
||||
.match(id)
|
||||
.then((d) => alive && setM(d))
|
||||
.catch((e) => alive && setErr(e));
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [id, epoch, n]);
|
||||
useEffect(() => {
|
||||
if (m) player.setQueue([...m.utterances, ...m.events]);
|
||||
}, [m]);
|
||||
if (err)
|
||||
return (
|
||||
<main className="page-pad">
|
||||
<ErrorBox error={err} onRetry={() => setN((x) => x + 1)} />
|
||||
</main>
|
||||
);
|
||||
if (!m || m.id !== id)
|
||||
return (
|
||||
<main className="page-pad">
|
||||
<Spinner label="경기 기록 불러오는 중" />
|
||||
</main>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<div className="crumbs">
|
||||
<Link to="/matches">← 경기 목록</Link>
|
||||
<Link to={`/?match=${encodeURIComponent(m.id)}`}>타임라인에서 보기</Link>
|
||||
</div>
|
||||
{m.game === 'lol' ? <LolMatch m={m} /> : <ValorantMatch m={m} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
159
site/web/src/pages/Sidebar.tsx
Normal file
159
site/web/src/pages/Sidebar.tsx
Normal file
@@ -0,0 +1,159 @@
|
||||
import type { MatchDetail, MatchSummary, User } from '@gvr/shared';
|
||||
import type { Filters } from '../lib/filters';
|
||||
import { Avatar, CharIcon } from '../components/common';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { dateInputToMs, dateInputValue, fmtHM, fmtWhen } from '../lib/format';
|
||||
import { TYPE_GROUPS } from '../lib/game';
|
||||
|
||||
type Update = (p: Partial<Filters>) => void;
|
||||
|
||||
export function toggleUser(f: Filters, users: User[], id: string): string[] {
|
||||
const all = users.filter((u) => !u.excluded).map((u) => u.id);
|
||||
const cur = f.users.length ? f.users : all;
|
||||
const nextSet = cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id];
|
||||
if (!nextSet.length) return [id];
|
||||
return all.every((x) => nextSet.includes(x)) ? [] : nextSet;
|
||||
}
|
||||
|
||||
export function MatchItem({ m, on, onClick }: { m: MatchSummary; on?: boolean; onClick?: () => void }) {
|
||||
const dur = m.endedAt ? Math.round((m.endedAt - m.startedAt) / 60000) : null;
|
||||
const res = m.win == null ? '' : m.win ? '승' : '패';
|
||||
const Tag = onClick ? 'button' : 'div';
|
||||
return (
|
||||
<Tag className={`match g-${m.game}${on ? ' on' : ''}${m.win === false ? ' loss' : ''}`} onClick={onClick}>
|
||||
<span className="res" />
|
||||
<div className="mi">
|
||||
<div>
|
||||
<b>{m.map.name}</b> {m.score && <span className="mono">{`${m.score.ally} : ${m.score.enemy}`}</span>}
|
||||
</div>
|
||||
<div className="t">
|
||||
{m.game === 'lol' ? '롤 · ' : ''}
|
||||
{m.mode} · {fmtHM(m.startedAt)}
|
||||
{dur != null ? ` · ${dur}분` : ''}
|
||||
{m.status === 'live' && <span className="live-dot"> · 진행 중</span>}
|
||||
</div>
|
||||
</div>
|
||||
{res && <span className={`badge ${m.win ? 'b-win' : 'b-loss'}`}>{res}</span>}
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
|
||||
export function Sidebar({ f, update, users, matches, detail }: { f: Filters; update: Update; users: User[]; matches: MatchSummary[]; detail: MatchDetail | null }) {
|
||||
const isOn = (id: string) => (f.users.length ? f.users.includes(id) : true);
|
||||
const charOf = (uid: string) => detail?.players.find((p) => p.userId === uid)?.character;
|
||||
const tap = (fn: () => void) => () => {
|
||||
sfx('click');
|
||||
fn();
|
||||
};
|
||||
const today = matches.length ? fmtWhen(matches[0].startedAt).split(' ')[0] : '';
|
||||
return (
|
||||
<aside className="side">
|
||||
<div>
|
||||
<h4>유저</h4>
|
||||
{users.map((u) => {
|
||||
const on = !u.excluded && isOn(u.id);
|
||||
const c = charOf(u.id);
|
||||
return (
|
||||
<button
|
||||
key={u.id}
|
||||
className={`urow${on ? ' sel' : ''}${u.excluded ? ' excluded' : ''}`}
|
||||
onClick={u.excluded ? undefined : tap(() => update({ users: toggleUser(f, users, u.id) }))}
|
||||
disabled={u.excluded}
|
||||
aria-pressed={on}
|
||||
title={u.excluded ? '/녹음제외 를 사용한 유저입니다' : undefined}
|
||||
>
|
||||
<span className={`chk${on ? ' on' : ''}`} />
|
||||
<Avatar user={u} />
|
||||
{c && <CharIcon c={c} size={22} className="side-ag" />}
|
||||
<span className={`n${on ? '' : ' muted'}`}>{u.name}</span>
|
||||
{u.excluded ? <span className="badge b-excl">녹음 제외</span> : <span className="c">{c?.name ?? ''}</span>}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div>
|
||||
<h4>게임</h4>
|
||||
<div className="chips-wrap">
|
||||
<button className={`chip val${f.game === 'valorant' ? ' on' : ''}`} onClick={tap(() => update({ game: f.game === 'valorant' ? null : 'valorant', match: null }))}>
|
||||
발로란트
|
||||
</button>
|
||||
<button className={`chip lol${f.game === 'lol' ? ' on' : ''}`} onClick={tap(() => update({ game: f.game === 'lol' ? null : 'lol', match: null }))}>
|
||||
롤
|
||||
</button>
|
||||
<button className={`chip${f.game === 'none' ? ' on' : ''}`} onClick={tap(() => update({ game: f.game === 'none' ? null : 'none', match: null }))}>
|
||||
게임 외 대화
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="side-matches">
|
||||
<h4>
|
||||
경기 <span className="dim">{today && `· ${today}`}</span>
|
||||
</h4>
|
||||
<div className="mlist">
|
||||
{matches.length === 0 && <div className="dim small">경기 기록 없음</div>}
|
||||
{matches.map((m) => (
|
||||
<MatchItem key={m.id} m={m} on={f.match === m.id} onClick={tap(() => update({ match: f.match === m.id ? null : m.id, order: null }))} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<h4>날짜</h4>
|
||||
<div className="dates">
|
||||
<input type="date" value={dateInputValue(f.from)} max={dateInputValue(f.to)} onChange={(e) => update({ from: dateInputToMs(e.target.value) })} aria-label="시작 날짜" />
|
||||
<span className="dim">~</span>
|
||||
<input type="date" value={dateInputValue(f.to)} min={dateInputValue(f.from)} onChange={(e) => update({ to: dateInputToMs(e.target.value, true) })} aria-label="끝 날짜" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="side-foot">
|
||||
<label className="switch">
|
||||
<input type="checkbox" checked={f.hideNoise} onChange={(e) => update({ hideNoise: e.target.checked })} />
|
||||
<span className="sw" />
|
||||
잡음 숨기기
|
||||
</label>
|
||||
<button className="link-btn" onClick={tap(() => update({ users: [], game: null, match: null, from: undefined, to: undefined, q: '', types: [], hideNoise: false, order: null }))}>
|
||||
필터 초기화
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
/** 휴대폰: 필터를 가로 칩 줄로 접는다 */
|
||||
export function MobileFilters({ f, update, users, matches }: { f: Filters; update: Update; users: User[]; matches: MatchSummary[] }) {
|
||||
const cur = matches.find((m) => m.id === f.match);
|
||||
const typeOn = (id: string) => f.types.includes(id as never);
|
||||
return (
|
||||
<div className="m-chips">
|
||||
<label className={`chip sel-chip${f.match ? ' on' : ''}`}>
|
||||
{cur ? `${cur.map.name} ${cur.score ? `${cur.score.ally}:${cur.score.enemy}` : ''}` : '모든 경기'}
|
||||
<select value={f.match ?? ''} onChange={(e) => update({ match: e.target.value || null, order: null })} aria-label="경기 선택">
|
||||
<option value="">모든 경기</option>
|
||||
{matches.map((m) => (
|
||||
<option key={m.id} value={m.id}>
|
||||
{m.map.name} {m.score ? `${m.score.ally}:${m.score.enemy}` : ''} · {fmtHM(m.startedAt)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{users
|
||||
.filter((u) => !u.excluded)
|
||||
.map((u) => {
|
||||
const on = f.users.includes(u.id);
|
||||
return (
|
||||
<button key={u.id} className={`chip${on ? ' on-user' : ''}`} style={on ? { borderColor: u.color, color: '#fff', background: `${u.color}33` } : undefined} onClick={() => update({ users: on ? f.users.filter((x) => x !== u.id) : [...f.users, u.id] })}>
|
||||
<span className="udot" style={{ background: u.color }} />
|
||||
{u.name}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{TYPE_GROUPS.map((t) => (
|
||||
<button key={t.id} className={`chip${typeOn(t.id) ? ' on' : ''}`} onClick={() => update({ types: typeOn(t.id) ? f.types.filter((x) => x !== t.id) : [...f.types, t.id] })}>
|
||||
{t.icon} {t.label}
|
||||
</button>
|
||||
))}
|
||||
<button className={`chip${f.hideNoise ? ' on' : ''}`} onClick={() => update({ hideNoise: !f.hideNoise })}>
|
||||
잡음 숨기기
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
353
site/web/src/pages/TimelinePage.tsx
Normal file
353
site/web/src/pages/TimelinePage.tsx
Normal file
@@ -0,0 +1,353 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useSearchParams } from 'react-router';
|
||||
import type { MatchDetail, MatchSummary, TimelineItem, UtteranceItem } from '@gvr/shared';
|
||||
import { api } from '../lib/api';
|
||||
import { effectiveOrder, matchesFilter, parseFilters, toQuery, writeFilters, type Filters } from '../lib/filters';
|
||||
import { TYPE_GROUPS, type TypeGroup } from '../lib/game';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { fmtReal, fmtWhen } from '../lib/format';
|
||||
import { useAuth, useData, useLive, useStatus } from '../store/app';
|
||||
import { player, usePlayer } from '../store/player';
|
||||
import { TimelineRows } from '../components/TimelineRows';
|
||||
import { Avatar, ErrorBox, Spinner } from '../components/common';
|
||||
import { IWaves } from '../components/Icons';
|
||||
import { MobileFilters, Sidebar } from './Sidebar';
|
||||
import { TalkBars } from '../components/TalkBars';
|
||||
|
||||
function NowPlayingCard() {
|
||||
const item = usePlayer((s) => (s.mode === 'single' ? s.item : null));
|
||||
const scene = usePlayer((s) => (s.mode === 'scene' ? s.scene : null));
|
||||
const { userById } = useData();
|
||||
if (scene)
|
||||
return (
|
||||
<div className="card">
|
||||
<h5>현장 모드</h5>
|
||||
<div className="np-scene">
|
||||
<b>{scene.label}</b>
|
||||
<div className="dim small">
|
||||
{fmtReal(scene.start)} ~ {fmtReal(scene.end)} · 발화 {scene.items.length}개를 실제 순서대로 겹쳐 재생
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
if (!item)
|
||||
return (
|
||||
<div className="card">
|
||||
<h5>재생 중인 발화</h5>
|
||||
<div className="dim small">발화를 누르면 음량 보정 · 인식 정보가 여기에 보입니다.</div>
|
||||
</div>
|
||||
);
|
||||
const u = userById(item.userId);
|
||||
const conf = item.confidence ?? 0;
|
||||
return (
|
||||
<div className="card">
|
||||
<h5>재생 중인 발화</h5>
|
||||
<div className="np-head">
|
||||
<Avatar user={u} size={40} />
|
||||
<div>
|
||||
<b>{u?.name ?? '알 수 없음'}</b>
|
||||
<div className="dim small">
|
||||
{item.time.primary} · {fmtReal(item.ts)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="kv">
|
||||
<span className="muted">재생 보정 게인</span>
|
||||
<span className="mono" style={{ color: 'var(--mint)' }}>
|
||||
{item.audio ? `${item.audio.gainDb > 0 ? '+' : ''}${item.audio.gainDb.toFixed(1)} dB` : '—'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="kv">
|
||||
<span className="muted">길이</span>
|
||||
<span className="mono">{((item.endTs - item.ts) / 1000).toFixed(1)}초</span>
|
||||
</div>
|
||||
<div className="kv">
|
||||
<span className="muted">인식 모델</span>
|
||||
<span className="mono">{item.model ?? '처리 중'}</span>
|
||||
</div>
|
||||
<div className="kv">
|
||||
<span className="muted">인식 신뢰도</span>
|
||||
<span className="mono">{item.confidence != null ? `${Math.round(conf * 100)}%` : '—'}</span>
|
||||
</div>
|
||||
<div className="bar">
|
||||
<i style={{ width: `${conf * 100}%`, background: 'var(--mint)' }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RightPanel({ items, detail }: { items: TimelineItem[]; detail: MatchDetail | null }) {
|
||||
const { auth } = useAuth();
|
||||
const { overview, userById } = useData();
|
||||
const meId = auth.status === 'ok' ? auth.me.user.id : null;
|
||||
const mine = detail?.players.find((p) => p.userId === meId);
|
||||
const utts = useMemo(() => (detail ? detail.utterances : items.filter((i): i is UtteranceItem => i.kind === 'utterance')), [detail, items]);
|
||||
const rounds = detail?.rounds?.length ?? 0;
|
||||
const rec = overview?.recording;
|
||||
return (
|
||||
<div className="right">
|
||||
<NowPlayingCard />
|
||||
{detail && mine && (
|
||||
<div className="card">
|
||||
<h5>
|
||||
이 경기 · {userById(meId)?.name ?? mine.name}
|
||||
</h5>
|
||||
<div className="stat4">
|
||||
<div>
|
||||
<b className="h">{mine.kills}</b>
|
||||
<span>킬</span>
|
||||
</div>
|
||||
<div>
|
||||
<b className="h">{mine.deaths}</b>
|
||||
<span>데스</span>
|
||||
</div>
|
||||
<div>
|
||||
<b className="h">{mine.assists}</b>
|
||||
<span>어시</span>
|
||||
</div>
|
||||
{detail.game === 'valorant' ? (
|
||||
<div>
|
||||
<b className="h accent">{rounds && mine.score != null ? Math.round(mine.score / rounds) : '—'}</b>
|
||||
<span>ACS</span>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<b className="h gold">{mine.cs ?? '—'}</b>
|
||||
<span>CS</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{!detail && rec && (
|
||||
<div className="card">
|
||||
<h5>녹음 상태</h5>
|
||||
{rec.active ? (
|
||||
<>
|
||||
<div className="kv">
|
||||
<span className="muted">채널</span>
|
||||
<span>#{rec.channel}</span>
|
||||
</div>
|
||||
<div className="kv">
|
||||
<span className="muted">시작</span>
|
||||
<span className="mono">{rec.since ? fmtWhen(rec.since) : '—'}</span>
|
||||
</div>
|
||||
<div className="avs">
|
||||
{rec.participants.map((id) => (
|
||||
<Avatar key={id} user={userById(id)} size={30} />
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="dim small">지금은 녹음하고 있지 않습니다.</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="card">
|
||||
<h5>{detail ? '이 경기 발화량' : '지금 목록의 발화량'}</h5>
|
||||
<TalkBars utts={utts} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TimelinePage() {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const f = useMemo(() => parseFilters(params), [params]);
|
||||
const order = effectiveOrder(f);
|
||||
const key = writeFilters(f).toString();
|
||||
const { epoch } = useStatus();
|
||||
const { users } = useData();
|
||||
const [items, setItems] = useState<TimelineItem[]>([]);
|
||||
const [next, setNext] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<unknown>(null);
|
||||
const [newIds, setNewIds] = useState<Set<string>>(() => new Set());
|
||||
const [matches, setMatches] = useState<MatchSummary[]>([]);
|
||||
const [detail, setDetail] = useState<MatchDetail | null>(null);
|
||||
const req = useRef(0);
|
||||
const [reload, setReload] = useState(0);
|
||||
const itemsRef = useRef(items);
|
||||
itemsRef.current = items;
|
||||
const scrollRef = useRef<HTMLElement>(null);
|
||||
const sentinel = useRef<HTMLDivElement>(null);
|
||||
|
||||
const update = useCallback((p: Partial<Filters>) => setParams(writeFilters({ ...parseFilters(params), ...p })), [params, setParams]);
|
||||
|
||||
// 첫 페이지
|
||||
useEffect(() => {
|
||||
const my = ++req.current;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setItems([]);
|
||||
setNext(null);
|
||||
scrollRef.current?.scrollTo({ top: 0 });
|
||||
api
|
||||
.timeline({ ...toQuery(f), limit: 100 })
|
||||
.then((p) => {
|
||||
if (my !== req.current) return;
|
||||
setItems(p.items);
|
||||
setNext(p.next);
|
||||
})
|
||||
.catch((e) => my === req.current && setError(e))
|
||||
.finally(() => my === req.current && setLoading(false));
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [key, epoch, reload]);
|
||||
|
||||
const loadMore = useCallback(() => {
|
||||
if (!next || loading) return;
|
||||
const my = req.current;
|
||||
setLoading(true);
|
||||
api
|
||||
.timeline({ ...toQuery(f), cursor: next, limit: 100 })
|
||||
.then((p) => {
|
||||
if (my !== req.current) return;
|
||||
setItems((prev) => {
|
||||
const seen = new Set(prev.map((i) => i.id));
|
||||
return [...prev, ...p.items.filter((i) => !seen.has(i.id))];
|
||||
});
|
||||
setNext(p.next);
|
||||
})
|
||||
.catch((e) => my === req.current && setError(e))
|
||||
.finally(() => my === req.current && setLoading(false));
|
||||
}, [next, loading, f]);
|
||||
|
||||
// 무한 스크롤
|
||||
useEffect(() => {
|
||||
const el = sentinel.current;
|
||||
if (!el || !next) return;
|
||||
const io = new IntersectionObserver((es) => es.some((e) => e.isIntersecting) && loadMore(), { root: scrollRef.current, rootMargin: '600px' });
|
||||
io.observe(el);
|
||||
return () => io.disconnect();
|
||||
}, [loadMore, next]);
|
||||
|
||||
// 사이드바 경기 목록 · 선택한 경기 상세
|
||||
useEffect(() => {
|
||||
api
|
||||
.matches({ limit: 15, game: f.game === 'valorant' || f.game === 'lol' ? f.game : undefined })
|
||||
.then(setMatches)
|
||||
.catch(() => {});
|
||||
}, [f.game, epoch]);
|
||||
useEffect(() => {
|
||||
setDetail(null);
|
||||
if (!f.match) return;
|
||||
let alive = true;
|
||||
api
|
||||
.match(f.match)
|
||||
.then((d) => alive && setDetail(d))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [f.match, epoch]);
|
||||
|
||||
useEffect(() => player.setQueue(items), [items]);
|
||||
|
||||
// 이어듣기로 넘어간 발화를 화면에 보이게
|
||||
const curId = usePlayer((s) => (s.mode === 'single' ? s.item?.id ?? null : null));
|
||||
useEffect(() => {
|
||||
if (!curId) return;
|
||||
const el = scrollRef.current?.querySelector(`[data-id="${curId}"]`);
|
||||
el?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
|
||||
}, [curId]);
|
||||
|
||||
const markNew = (id: string) => {
|
||||
setNewIds((s) => new Set(s).add(id));
|
||||
window.setTimeout(
|
||||
() =>
|
||||
setNewIds((s) => {
|
||||
const n = new Set(s);
|
||||
n.delete(id);
|
||||
return n;
|
||||
}),
|
||||
2500,
|
||||
);
|
||||
};
|
||||
|
||||
useLive((e) => {
|
||||
if (e.type === 'utterance.created' || e.type === 'event.created') {
|
||||
const it = e.data;
|
||||
if (!matchesFilter(it, f)) return;
|
||||
const prev = itemsRef.current;
|
||||
if (prev.some((p) => p.id === it.id)) return;
|
||||
if (order === 'asc' && next) return; // 시간순: 끝까지 불러온 뒤에만 아래에 붙인다
|
||||
setItems((cur) => (cur.some((p) => p.id === it.id) ? cur : order === 'desc' ? [it, ...cur] : [...cur, it]));
|
||||
markNew(it.id);
|
||||
if (it.kind === 'utterance') sfx('chime');
|
||||
else if (it.type === 'kill') sfx('kill');
|
||||
else if (it.type === 'round_end') sfx('round');
|
||||
} else if (e.type === 'utterance.updated') {
|
||||
setItems((prev) => prev.map((p) => (p.id === e.data.id ? e.data : p)));
|
||||
}
|
||||
});
|
||||
|
||||
const onUpdate = useCallback((it: UtteranceItem) => setItems((prev) => prev.map((p) => (p.id === it.id ? it : p))), []);
|
||||
const matchMap = useMemo(() => new Map(matches.map((m) => [m.id, m])), [matches]);
|
||||
if (detail && !matchMap.has(detail.id)) matchMap.set(detail.id, detail);
|
||||
|
||||
const toggleType = (t: TypeGroup) => {
|
||||
sfx('click');
|
||||
update({ types: f.types.includes(t) ? f.types.filter((x) => x !== t) : [...f.types, t] });
|
||||
};
|
||||
|
||||
const startScene = () => {
|
||||
const utts = items.filter((i): i is UtteranceItem => i.kind === 'utterance' && !!i.audio).sort((a, b) => a.ts - b.ts);
|
||||
if (!utts.length) return;
|
||||
const sel = player.state.item;
|
||||
const startTs = sel && utts.some((u) => u.id === sel.id) ? sel.ts : utts[0].ts;
|
||||
const end = Math.max(...utts.map((u) => u.endTs));
|
||||
const m = f.match ? matchMap.get(f.match) : undefined;
|
||||
player.startScene({ start: startTs - 500, end: end + 300, label: `${m?.map.name ?? '경기'} · ${fmtReal(startTs)}부터`, items: utts });
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="tl-main">
|
||||
<Sidebar f={f} update={update} users={users} matches={matches} detail={detail} />
|
||||
<section className="tl" ref={scrollRef}>
|
||||
<MobileFilters f={f} update={update} users={users} matches={matches} />
|
||||
<div className="filters">
|
||||
<button className={`chip${f.types.length === 0 ? ' on' : ''}`} onClick={() => update({ types: [] })}>
|
||||
전체
|
||||
</button>
|
||||
{TYPE_GROUPS.map((t) => (
|
||||
<button key={t.id} className={`chip${f.types.includes(t.id) ? ' on' : ''}`} onClick={() => toggleType(t.id)}>
|
||||
<span aria-hidden>{t.icon}</span> {t.label}
|
||||
</button>
|
||||
))}
|
||||
<span className="grow" />
|
||||
{f.match && (
|
||||
<button className="chip scene-btn" onClick={startScene} title="불러온 발화를 실제 시각 순서대로 겹쳐서 재생합니다">
|
||||
<IWaves width={14} height={14} /> 현장 모드
|
||||
</button>
|
||||
)}
|
||||
<button className="chip" onClick={() => update({ order: order === 'desc' ? 'asc' : 'desc' })} title="정렬 순서">
|
||||
{order === 'desc' ? '최신순 ↓' : '시간순 ↑'}
|
||||
</button>
|
||||
</div>
|
||||
{(f.q || f.from || f.to) && (
|
||||
<div className="active-filters">
|
||||
{f.q && (
|
||||
<button className="chip on-soft" onClick={() => update({ q: '' })}>
|
||||
“{f.q}” 검색 ✕
|
||||
</button>
|
||||
)}
|
||||
{(f.from || f.to) && (
|
||||
<button className="chip on-soft" onClick={() => update({ from: undefined, to: undefined })}>
|
||||
기간 지정 ✕
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="rows">
|
||||
<TimelineRows items={items} matches={matchMap} newIds={newIds} onUpdate={onUpdate} />
|
||||
</div>
|
||||
{error != null && <ErrorBox error={error} onRetry={() => setReload((n) => n + 1)} />}
|
||||
{!loading && !error && items.length === 0 && <div className="empty">조건에 맞는 기록이 없습니다.</div>}
|
||||
{loading && <Spinner />}
|
||||
{!loading && !next && items.length > 0 && <div className="list-end">{order === 'desc' ? '가장 오래된 기록입니다' : '마지막 기록입니다'}</div>}
|
||||
<div ref={sentinel} className="sentinel" />
|
||||
</section>
|
||||
<RightPanel items={items} detail={detail} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
200
site/web/src/pages/UserPages.tsx
Normal file
200
site/web/src/pages/UserPages.tsx
Normal file
@@ -0,0 +1,200 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router';
|
||||
import type { GameType, MatchSummary, User, UserProfile } from '@gvr/shared';
|
||||
import { api } from '../lib/api';
|
||||
import { useStatus } from '../store/app';
|
||||
import { fmtDuration, fmtWhen } from '../lib/format';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { Avatar, ErrorBox, Spinner } from '../components/common';
|
||||
import { MatchItem } from './Sidebar';
|
||||
|
||||
function useLoad<T>(fn: () => Promise<T>, deps: unknown[]) {
|
||||
const { epoch } = useStatus();
|
||||
const [data, setData] = useState<T | null>(null);
|
||||
const [err, setErr] = useState<unknown>(null);
|
||||
const [n, setN] = useState(0);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
setErr(null);
|
||||
fn()
|
||||
.then((d) => alive && setData(d))
|
||||
.catch((e) => alive && setErr(e));
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [...deps, epoch, n]);
|
||||
return { data, err, retry: () => setN((x) => x + 1) };
|
||||
}
|
||||
|
||||
export function UsersPage() {
|
||||
const { data, err, retry } = useLoad<User[]>(() => api.users(), []);
|
||||
if (err) return <main className="page-pad"><ErrorBox error={err} onRetry={retry} /></main>;
|
||||
if (!data) return <main className="page-pad"><Spinner /></main>;
|
||||
return (
|
||||
<main className="page-pad">
|
||||
<h2 className="page-h h">유저</h2>
|
||||
<div className="user-grid">
|
||||
{data.map((u) => (
|
||||
<Link key={u.id} to={`/users/${u.id}`} className="user-card" style={{ borderTopColor: u.color }} onClick={() => sfx('click')}>
|
||||
<Avatar user={u} size={52} />
|
||||
<div>
|
||||
<b style={{ color: u.color }}>{u.name}</b>
|
||||
<div className="dim small">{u.riot.map((r) => r.riotId).join(' · ') || 'Riot 계정 연결 안 됨'}</div>
|
||||
</div>
|
||||
{u.excluded && <span className="badge b-excl">녹음 제외</span>}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function MatchesPage() {
|
||||
const [game, setGame] = useState<GameType | null>(null);
|
||||
const nav = useNavigate();
|
||||
const { data, err, retry } = useLoad<MatchSummary[]>(() => api.matches({ limit: 50, game: game ?? undefined }), [game]);
|
||||
const groups = useMemo(() => {
|
||||
const g = new Map<string, MatchSummary[]>();
|
||||
for (const m of data ?? []) {
|
||||
const d = fmtWhen(m.startedAt).split(' ')[0];
|
||||
g.set(d, [...(g.get(d) ?? []), m]);
|
||||
}
|
||||
return [...g];
|
||||
}, [data]);
|
||||
return (
|
||||
<main className="page-pad">
|
||||
<div className="page-h-row">
|
||||
<h2 className="page-h h">경기</h2>
|
||||
<div className="chips-wrap">
|
||||
<button className={`chip${!game ? ' on' : ''}`} onClick={() => setGame(null)}>
|
||||
전체
|
||||
</button>
|
||||
<button className={`chip val${game === 'valorant' ? ' on' : ''}`} onClick={() => setGame('valorant')}>
|
||||
발로란트
|
||||
</button>
|
||||
<button className={`chip lol${game === 'lol' ? ' on' : ''}`} onClick={() => setGame('lol')}>
|
||||
롤
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{err != null && <ErrorBox error={err} onRetry={retry} />}
|
||||
{!data && !err && <Spinner />}
|
||||
{data && data.length === 0 && <div className="empty">경기 기록이 없습니다.</div>}
|
||||
{groups.map(([day, ms]) => (
|
||||
<section key={day} className="match-day">
|
||||
<h4>{day}</h4>
|
||||
<div className="match-cards">
|
||||
{ms.map((m) => (
|
||||
<MatchItem key={m.id} m={m} onClick={() => nav(`/matches/${encodeURIComponent(m.id)}`)} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function WordCloud({ words, color }: { words: { w: string; n: number }[]; color: string }) {
|
||||
const max = words[0]?.n ?? 1;
|
||||
const shuffled = useMemo(() => [...words].sort((a, b) => (a.w < b.w ? -1 : 1)), [words]);
|
||||
return (
|
||||
<div className="cloud">
|
||||
{shuffled.map((x) => {
|
||||
const r = x.n / max;
|
||||
return (
|
||||
<Link key={x.w} to={`/?q=${encodeURIComponent(x.w)}`} style={{ fontSize: 13 + r * 22, opacity: 0.45 + r * 0.55, color: r > 0.6 ? color : undefined }} data-tip={`${x.n}번 · 눌러서 검색`}>
|
||||
{x.w}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function UserPage() {
|
||||
const { id = '' } = useParams();
|
||||
const { data, err, retry } = useLoad<UserProfile>(() => api.user(id), [id]);
|
||||
if (err) return <main className="page-pad"><ErrorBox error={err} onRetry={retry} /></main>;
|
||||
if (!data || data.user.id !== id) return <main className="page-pad"><Spinner /></main>;
|
||||
const { user, stats, matches } = data;
|
||||
const top = stats.topWords.slice(0, 10);
|
||||
const max = top[0]?.n ?? 1;
|
||||
const wins = matches.filter((m) => m.win).length;
|
||||
return (
|
||||
<main className="page-pad user-page">
|
||||
<div className="user-hero" style={{ ['--uc' as string]: user.color }}>
|
||||
<Avatar user={user} size={76} />
|
||||
<div>
|
||||
<h2 className="h" style={{ color: user.color }}>
|
||||
{user.name} {user.excluded && <span className="badge b-excl">녹음 제외</span>}
|
||||
</h2>
|
||||
<div className="riot">
|
||||
{user.riot.length ? user.riot.map((r) => <span key={r.puuid} className="chip">🎮 {r.riotId}</span>) : <span className="dim">연결된 Riot 계정 없음</span>}
|
||||
</div>
|
||||
</div>
|
||||
<Link className="btn" to={`/?users=${user.id}`}>
|
||||
이 유저 대화만 보기 →
|
||||
</Link>
|
||||
</div>
|
||||
<div className="tiles">
|
||||
<div className="tile">
|
||||
<span>말한 시간</span>
|
||||
<b className="h">{fmtDuration(stats.talkMs)}</b>
|
||||
</div>
|
||||
<div className="tile">
|
||||
<span>발화 수</span>
|
||||
<b className="h">{stats.count.toLocaleString()}개</b>
|
||||
</div>
|
||||
<div className="tile">
|
||||
<span>평균 발화 길이</span>
|
||||
<b className="h">{stats.count ? (stats.talkMs / stats.count / 1000).toFixed(1) : 0}초</b>
|
||||
</div>
|
||||
<div className="tile">
|
||||
<span>함께한 경기</span>
|
||||
<b className="h">
|
||||
{matches.length}판 <small className="dim">{matches.length ? `${wins}승 ${matches.length - wins}패` : ''}</small>
|
||||
</b>
|
||||
</div>
|
||||
</div>
|
||||
<div className="user-grid2">
|
||||
<section className="panel">
|
||||
<h4>
|
||||
<span>자주 쓰는 단어</span>
|
||||
</h4>
|
||||
{top.length === 0 ? (
|
||||
<div className="dim small">아직 기록이 없습니다</div>
|
||||
) : (
|
||||
<>
|
||||
<WordCloud words={stats.topWords} color={user.color} />
|
||||
<div className="wordbars">
|
||||
{top.map((w) => (
|
||||
<div key={w.w} className="wb" data-tip={`${w.w} · ${w.n}번`}>
|
||||
<span className="wb-w">{w.w}</span>
|
||||
<span className="bar">
|
||||
<i style={{ width: `${(w.n / max) * 100}%`, background: user.color }} />
|
||||
</span>
|
||||
<span className="mono dim">{w.n}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
<section className="panel">
|
||||
<h4>
|
||||
<span>연결된 Riot 계정 경기</span>
|
||||
</h4>
|
||||
<div className="mlist">
|
||||
{matches.length === 0 && <div className="dim small">경기 기록 없음</div>}
|
||||
{matches.map((m) => (
|
||||
<Link key={m.id} to={`/matches/${encodeURIComponent(m.id)}`} className="mlink">
|
||||
<MatchItem m={m} />
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
355
site/web/src/pages/ValorantMatch.tsx
Normal file
355
site/web/src/pages/ValorantMatch.tsx
Normal file
@@ -0,0 +1,355 @@
|
||||
import { useEffect, useMemo, useRef, type MouseEvent } from 'react';
|
||||
import { useSearchParams } from 'react-router';
|
||||
import { motion } from 'framer-motion';
|
||||
import type { ChatData, EventItem, KillData, MatchDetail, MatchPlayer, MatchRound, TimelineItem, UtteranceItem } from '@gvr/shared';
|
||||
import { player, usePlayer } from '../store/player';
|
||||
import { useAuth, useData } from '../store/app';
|
||||
import { useReducedMotion } from '../store/settings';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { toUV, roundResultKo, CHANNEL_KO } from '../lib/game';
|
||||
import { fmtClock, realTip } from '../lib/format';
|
||||
import { CharIcon, PName, Panel } from '../components/common';
|
||||
import { UtteranceRow } from '../components/UtteranceRow';
|
||||
import { KillLine, SeparatorRow } from '../components/EventRow';
|
||||
import { IPlay, IWaves } from '../components/Icons';
|
||||
import { matchMeta } from './MatchPage';
|
||||
|
||||
const BUY_MS = 30000;
|
||||
/** "R7 · 0:38" → "0:38" */
|
||||
const short = (p: string) => p.replace(/^R\d+\s*·\s*/, '');
|
||||
|
||||
function RoundStrip({ rounds, sel, onSelect }: { rounds: MatchRound[]; sel: number; onSelect: (n: number) => void }) {
|
||||
return (
|
||||
<div className="rounds" role="tablist" aria-label="라운드">
|
||||
{rounds.map((r) => (
|
||||
<button
|
||||
key={r.num}
|
||||
role="tab"
|
||||
aria-selected={r.num === sel}
|
||||
className={`rb ${r.win ? 'win' : 'loss'}${r.num === sel ? ' sel' : ''}${r.num === 13 ? ' half' : ''}`}
|
||||
onClick={() => onSelect(r.num)}
|
||||
data-tip={`R${r.num} ${r.win ? '승리' : '패배'} · ${roundResultKo(r.result)} · ${r.score.ally}:${r.score.enemy}`}
|
||||
>
|
||||
{r.num}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ValMap({ m, round, events }: { m: MatchDetail; round: MatchRound; events: EventItem[] }) {
|
||||
const ts = usePlayer((s) => s.sceneTs);
|
||||
const reduce = useReducedMotion();
|
||||
const inRound = ts != null && ts >= round.startedAt && ts <= round.endedAt + 2000;
|
||||
const kills = events.filter((e) => e.type === 'kill');
|
||||
const spikes = events.filter((e) => e.type === 'spike');
|
||||
const span = round.endedAt - round.startedAt;
|
||||
const progress = inRound ? Math.min(1, (ts! - round.startedAt) / span) : 0;
|
||||
const seek = (e: MouseEvent<HTMLDivElement>) => {
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
const off = ((e.clientX - r.left) / r.width) * span;
|
||||
player.startScene({ start: round.startedAt, end: round.endedAt, label: `ROUND ${round.num} 현장 모드`, items: m.utterances });
|
||||
player.seekScene(off);
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<div className="map-area">
|
||||
{m.map.image ? (
|
||||
<div className="map-sq">
|
||||
<img src={m.map.image} alt={`${m.map.name} 미니맵`} />
|
||||
{spikes.map((e) => {
|
||||
const uv = toUV(m, e.data.location);
|
||||
return uv ? (
|
||||
<div key={e.id} className="mk spike" style={{ left: `${uv.u * 100}%`, top: `${uv.v * 100}%` }} data-tip={`${short(e.time.primary)} 스파이크 설치`}>
|
||||
설치
|
||||
</div>
|
||||
) : null;
|
||||
})}
|
||||
{kills.map((e) => {
|
||||
const d = e.data as KillData;
|
||||
const uv = toUV(m, d.location);
|
||||
if (!uv) return null;
|
||||
const past = !inRound || e.ts <= ts!;
|
||||
const recent = inRound && ts! - e.ts >= 0 && ts! - e.ts < 3500;
|
||||
const ally = d.ally ?? !!d.killer?.userId;
|
||||
return (
|
||||
<div
|
||||
key={e.id}
|
||||
className={`mk kill ${ally ? 'ally' : 'enemy'}${past ? '' : ' future'}${recent ? ' recent' : ''}`}
|
||||
style={{ left: `${uv.u * 100}%`, top: `${uv.v * 100}%` }}
|
||||
data-tip={`${short(e.time.primary)} ${d.killer?.name ?? '?'} → ${d.victim.name}${d.weapon ? ` (${d.weapon.name})` : ''}`}
|
||||
>
|
||||
{recent && (
|
||||
<motion.span className="mk-pop" initial={reduce ? false : { scale: 0.3, opacity: 0 }} animate={{ scale: 1, opacity: 1 }}>
|
||||
<CharIcon c={d.victim.character} size={30} />
|
||||
</motion.span>
|
||||
)}
|
||||
<span className="x">✕</span>
|
||||
{recent && !reduce && <span className="ping" />}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="map-missing">미니맵 이미지 없음</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="timebar">
|
||||
<span className="mono muted">{inRound ? fmtClock(Math.max(0, ts! - round.startedAt - BUY_MS)) : '0:00'}</span>
|
||||
<div className="tb" onClick={seek} title="눌러서 이 시점부터 현장 모드로 듣기">
|
||||
<i style={{ width: `${progress * 100}%` }} />
|
||||
<span className="buy" style={{ width: `${(BUY_MS / span) * 100}%` }} />
|
||||
{kills.map((e) => (
|
||||
<b key={e.id} className={(e.data as KillData).ally ? 'ally' : ''} style={{ left: `${((e.ts - round.startedAt) / span) * 100}%` }} />
|
||||
))}
|
||||
</div>
|
||||
<span className="mono muted">{fmtClock(span - BUY_MS)}</span>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function FeedRow({ it, meId }: { it: TimelineItem; meId: string | null }) {
|
||||
const active = usePlayer((s) => s.sceneTs != null && it.kind === 'event' && s.sceneTs - it.ts >= 0 && s.sceneTs - it.ts < 2500);
|
||||
if (it.kind === 'utterance') return <UtteranceRow item={it} variant="compact" timeText={short(it.time.primary)} />;
|
||||
const e = it;
|
||||
if (e.type === 'round_end') return <SeparatorRow e={e} />;
|
||||
if (e.type === 'kill') {
|
||||
const d = e.data as KillData;
|
||||
return (
|
||||
<div className={`k${d.killer?.userId && d.killer.userId === meId ? ' me' : ''}${d.ally === false ? ' death' : ''}${active ? ' flash' : ''}`} data-tip={realTip(e.ts)}>
|
||||
<span className="t mono">{short(e.time.primary)}</span>
|
||||
<KillLine d={d} game="valorant" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (e.type === 'chat') {
|
||||
const d = e.data as ChatData;
|
||||
return (
|
||||
<div className="l chat-l" data-tip={realTip(e.ts)}>
|
||||
<span className="t mono">{short(e.time.primary)}</span>
|
||||
<div className="lb">
|
||||
<span className="ctag ch-team">💬 {CHANNEL_KO[d.channel] ?? d.channel}</span> <PName p={d.sender} /> {d.text}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (e.type === 'spike')
|
||||
return (
|
||||
<div className="l spike-l">
|
||||
<span className="t mono">{short(e.time.primary)}</span>
|
||||
<div className="lb">
|
||||
<span className="spike-ic">◆</span> 스파이크 설치 {e.data.site ? `· ${e.data.site} 사이트` : ''}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
function Scoreboard({ players, rounds }: { players: MatchPlayer[]; rounds: number }) {
|
||||
const { userById } = useData();
|
||||
const acs = (p: MatchPlayer) => (rounds && p.score != null ? Math.round(p.score / rounds) : null);
|
||||
const top = Math.max(...players.map((p) => acs(p) ?? 0));
|
||||
const team = (ally: boolean) => players.filter((p) => p.ally === ally).sort((a, b) => (acs(b) ?? 0) - (acs(a) ?? 0));
|
||||
return (
|
||||
<table className="score-tbl">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>플레이어</th>
|
||||
<th>K</th>
|
||||
<th>D</th>
|
||||
<th>A</th>
|
||||
<th>ACS</th>
|
||||
</tr>
|
||||
</thead>
|
||||
{[true, false].map((ally) => (
|
||||
<tbody key={String(ally)} className={ally ? 'ally' : 'enemy'}>
|
||||
<tr className="team-row">
|
||||
<td colSpan={5}>{ally ? '우리 팀' : '상대 팀'}</td>
|
||||
</tr>
|
||||
{team(ally).map((p) => {
|
||||
const u = userById(p.userId);
|
||||
return (
|
||||
<tr key={p.puuid} className={u ? 'linked' : ''} style={u ? { background: `${u.color}14` } : undefined}>
|
||||
<td>
|
||||
<CharIcon c={p.character} size={22} />{' '}
|
||||
{u ? <b style={{ color: u.color }}>{u.name}</b> : <span>{p.tag ? `${p.name}#${p.tag}` : p.name}</span>} <span className="dim">{p.character.name}</span>
|
||||
</td>
|
||||
<td>{p.kills}</td>
|
||||
<td>{p.deaths}</td>
|
||||
<td>{p.assists}</td>
|
||||
<td className={acs(p) === top ? 'accent' : ''}>{acs(p) ?? '—'}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
))}
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
function Economy({ m, sel, onSelect }: { m: MatchDetail; sel: number; onSelect: (n: number) => void }) {
|
||||
const allyIds = new Set(m.players.filter((p) => p.ally).map((p) => p.puuid));
|
||||
const data = (m.rounds ?? []).map((r) => {
|
||||
let total = 0;
|
||||
let spent = 0;
|
||||
for (const [id, e] of Object.entries(r.economy ?? {})) {
|
||||
if (!allyIds.has(id)) continue;
|
||||
total += e.spent + e.remaining;
|
||||
spent += e.spent;
|
||||
}
|
||||
return { r, total, spent };
|
||||
});
|
||||
const max = Math.max(1, ...data.map((d) => d.total));
|
||||
if (!data.some((d) => d.total)) return <div className="dim small">경제 기록 없음</div>;
|
||||
return (
|
||||
<>
|
||||
<div className="eco" role="list">
|
||||
{data.map(({ r, total, spent }) => (
|
||||
<button
|
||||
key={r.num}
|
||||
role="listitem"
|
||||
className={`eco-bar${r.num === sel ? ' sel' : ''}`}
|
||||
onClick={() => onSelect(r.num)}
|
||||
data-tip={`R${r.num} · 팀 크레딧 ${total.toLocaleString()} · 사용 ${spent.toLocaleString()}`}
|
||||
>
|
||||
<i style={{ height: `${(total / max) * 100}%` }}>
|
||||
<em style={{ height: `${total ? (spent / total) * 100 : 0}%` }} />
|
||||
</i>
|
||||
<span className={r.win ? 'w' : 'l'} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="eco-legend dim">
|
||||
막대 높이 = 라운드 시작 시 팀 보유 크레딧 · 진한 부분 = 사용 · 아래 점 = <span className="mint">승</span>/패
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ValorantMatch({ m }: { m: MatchDetail }) {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const { auth } = useAuth();
|
||||
const meId = auth.status === 'ok' ? auth.me.user.id : null;
|
||||
const rounds = m.rounds ?? [];
|
||||
const selNum = Number(params.get('round')) || rounds[0]?.num || 1;
|
||||
const round = rounds.find((r) => r.num === selNum) ?? rounds[0];
|
||||
const meta = matchMeta(m);
|
||||
const feedRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const select = (n: number) => {
|
||||
if (n === selNum) return;
|
||||
sfx('round');
|
||||
const p = new URLSearchParams(params);
|
||||
p.set('round', String(n));
|
||||
setParams(p, { replace: true });
|
||||
};
|
||||
|
||||
// 재생이 다음 라운드로 넘어가면 라운드 선택도 따라간다
|
||||
const playRound = usePlayer((s) => {
|
||||
if (s.sceneTs == null || s.sceneTs < m.startedAt || (m.endedAt && s.sceneTs > m.endedAt)) return null;
|
||||
return rounds.find((r) => s.sceneTs! >= r.startedAt && s.sceneTs! <= r.endedAt + 4000)?.num ?? null;
|
||||
});
|
||||
useEffect(() => {
|
||||
if (playRound && playRound !== selNum) select(playRound);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [playRound]);
|
||||
|
||||
const roundItems = useMemo(() => {
|
||||
if (!round) return [];
|
||||
const inR = (t: number) => t >= round.startedAt && t <= round.endedAt + 1000;
|
||||
return [...m.utterances.filter((u) => inR(u.ts)), ...m.events.filter((e) => inR(e.ts) && e.type !== 'match_end' && e.type !== 'match_start')].sort((a, b) => a.ts - b.ts);
|
||||
}, [m, round]);
|
||||
const roundEvents = roundItems.filter((i): i is EventItem => i.kind === 'event');
|
||||
const roundUtts = roundItems.filter((i): i is UtteranceItem => i.kind === 'utterance');
|
||||
|
||||
const curId = usePlayer((s) => (s.mode === 'single' ? s.item?.id ?? null : null));
|
||||
useEffect(() => {
|
||||
if (curId) feedRef.current?.querySelector(`[data-id="${curId}"]`)?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
|
||||
}, [curId]);
|
||||
|
||||
if (!round) return <main className="page-pad">라운드 기록이 없습니다.</main>;
|
||||
|
||||
const playRoundAll = () => {
|
||||
const first = roundUtts.find((u) => u.audio);
|
||||
if (first) void player.play(first);
|
||||
};
|
||||
const scene = () => player.startScene({ start: round.startedAt, end: round.endedAt, label: `${m.map.name} · ROUND ${round.num}`, items: m.utterances });
|
||||
|
||||
return (
|
||||
<main className="match val">
|
||||
<div className="mtop">
|
||||
{m.map.image && <img className="map-thumb" src={m.map.image} alt="" />}
|
||||
<div>
|
||||
<div className="eyebrow">MATCH DETAIL · VALORANT</div>
|
||||
<div className="mtitle h">
|
||||
{m.map.name}{' '}
|
||||
{m.score && (
|
||||
<span className="score">
|
||||
<span className="a">{m.score.ally}</span> <span className="dim colon">:</span> <span className="b">{m.score.enemy}</span>
|
||||
</span>
|
||||
)}
|
||||
{m.win != null && <span className={`res-badge ${m.win ? 'win' : 'loss'}`}>{m.win ? '승리' : '패배'}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="meta">
|
||||
{m.mode} · {meta.when} 시작 · {meta.dur}
|
||||
<br />
|
||||
대화 {m.utterances.length}개 · 킬 이벤트 {meta.kills}개 · 채팅 {meta.chats}개
|
||||
</div>
|
||||
<RoundStrip rounds={rounds} sel={round.num} onSelect={select} />
|
||||
</div>
|
||||
<div className="mgrid">
|
||||
<Panel
|
||||
className="map-panel"
|
||||
title={`ROUND ${round.num} · 킬 위치 (재생 시점 연동)`}
|
||||
right={`${m.map.name} 미니맵 · 게임 좌표 변환`}
|
||||
>
|
||||
<ValMap m={m} round={round} events={roundEvents} />
|
||||
<div className="map-legend dim">
|
||||
<b className="mint">✕</b> 우리 팀이 처치 <b className="accent">✕</b> 상대 팀이 처치 <span className="spike-ic">◆</span> 스파이크
|
||||
</div>
|
||||
</Panel>
|
||||
<Panel
|
||||
className="feed-panel"
|
||||
title={`ROUND ${round.num} · 대화 + 킬피드`}
|
||||
right={
|
||||
<span className="ph-btns">
|
||||
<button className="mini-btn" onClick={playRoundAll}>
|
||||
<IPlay width={11} height={11} /> 라운드 이어듣기
|
||||
</button>
|
||||
<button className="mini-btn" onClick={scene} title="겹친 발화를 실제 순서대로 섞어서 재생">
|
||||
<IWaves width={12} height={12} /> 현장 모드
|
||||
</button>
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<div className="feed scroll" ref={feedRef}>
|
||||
<div className="round-head">
|
||||
<span className={`pill ${round.win ? 'win' : 'loss'}`}>R{round.num}</span>
|
||||
<span>{round.win ? '승리' : '패배'} · {roundResultKo(round.result)}</span>
|
||||
<span className="mono score">
|
||||
{round.score.ally} : {round.score.enemy}
|
||||
</span>
|
||||
</div>
|
||||
{roundItems.length === 0 && <div className="dim small">이 라운드에는 기록이 없습니다</div>}
|
||||
{roundItems.map((it) => (
|
||||
<div key={it.id} data-id={it.id}>
|
||||
<FeedRow it={it} meId={meId} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Panel>
|
||||
<Panel className="sb-panel" title="스코어보드">
|
||||
<div className="scroll">
|
||||
<Scoreboard players={m.players} rounds={rounds.length} />
|
||||
<h4 className="sub-h">
|
||||
<span>라운드별 우리 팀 크레딧</span>
|
||||
</h4>
|
||||
<Economy m={m} sel={round.num} onSelect={select} />
|
||||
</div>
|
||||
</Panel>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
151
site/web/src/store/app.tsx
Normal file
151
site/web/src/store/app.tsx
Normal file
@@ -0,0 +1,151 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import type { DeviceStatus, LiveEvent, Overview, User } from '@gvr/shared';
|
||||
import { api, onApiSignal, type Me } from '../lib/api';
|
||||
import { live, type LiveConn } from '../lib/live';
|
||||
|
||||
// ── 로그인 ───────────────────────────────────────────
|
||||
type AuthState = { status: 'loading' } | { status: 'anon' } | { status: 'not_member' } | { status: 'ok'; me: Me };
|
||||
const AuthCtx = createContext<{ auth: AuthState; logout: () => void }>({ auth: { status: 'loading' }, logout: () => {} });
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [auth, setAuth] = useState<AuthState>({ status: 'loading' });
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
api
|
||||
.me()
|
||||
.then((r) => alive && setAuth(r.ok ? { status: 'ok', me: r.me } : { status: r.reason }))
|
||||
.catch(() => alive && setAuth({ status: 'anon' }));
|
||||
const off = onApiSignal((s) => {
|
||||
if (s === 'unauthorized') setAuth({ status: 'anon' });
|
||||
if (s === 'not_member') setAuth({ status: 'not_member' });
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
off();
|
||||
};
|
||||
}, []);
|
||||
const logout = useCallback(() => {
|
||||
void api.logout().finally(() => setAuth({ status: 'anon' }));
|
||||
}, []);
|
||||
return <AuthCtx.Provider value={{ auth, logout }}>{children}</AuthCtx.Provider>;
|
||||
}
|
||||
export const useAuth = () => useContext(AuthCtx);
|
||||
|
||||
// ── 게임 PC 연결 상태 + 실시간 이벤트 ─────────────────
|
||||
interface StatusValue {
|
||||
device: DeviceStatus | null;
|
||||
serverOk: boolean | null;
|
||||
conn: LiveConn;
|
||||
locked: boolean;
|
||||
/** 잠금이 풀릴 때마다 1씩 증가 → 페이지를 새로 불러오는 키 */
|
||||
epoch: number;
|
||||
recheck: () => Promise<void>;
|
||||
}
|
||||
const StatusCtx = createContext<StatusValue>(null as unknown as StatusValue);
|
||||
|
||||
type LiveFn = (e: LiveEvent) => void;
|
||||
const liveSubs = new Set<LiveFn>();
|
||||
/** 5장 실시간 이벤트 구독 */
|
||||
export function useLive(fn: LiveFn) {
|
||||
const ref = useRef(fn);
|
||||
ref.current = fn;
|
||||
useEffect(() => {
|
||||
const h: LiveFn = (e) => ref.current(e);
|
||||
liveSubs.add(h);
|
||||
return () => {
|
||||
liveSubs.delete(h);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
|
||||
export function StatusProvider({ children }: { children: ReactNode }) {
|
||||
const [device, setDevice] = useState<DeviceStatus | null>(null);
|
||||
const [serverOk, setServerOk] = useState<boolean | null>(null);
|
||||
const [conn, setConn] = useState<LiveConn>(live.conn);
|
||||
const [epoch, setEpoch] = useState(0);
|
||||
|
||||
const recheck = useCallback(async () => {
|
||||
live.kick();
|
||||
try {
|
||||
const s = await api.status();
|
||||
setServerOk(true);
|
||||
setDevice(s.device);
|
||||
} catch {
|
||||
setServerOk(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void recheck();
|
||||
live.start();
|
||||
const offConn = live.onConn(setConn);
|
||||
const offMsg = live.onMessage((m) => {
|
||||
if (m.type === 'status') {
|
||||
setServerOk(true);
|
||||
setDevice(m.data.device);
|
||||
} else liveSubs.forEach((fn) => fn(m));
|
||||
});
|
||||
const offSig = onApiSignal((s) => {
|
||||
if (s === 'device_offline') setDevice((d) => ({ registered: d?.registered ?? true, online: false, name: d?.name ?? null, lastSeen: d?.lastSeen ?? null, version: d?.version ?? null }));
|
||||
});
|
||||
return () => {
|
||||
offConn();
|
||||
offMsg();
|
||||
offSig();
|
||||
live.stop();
|
||||
};
|
||||
}, [recheck]);
|
||||
|
||||
const locked = !!device && (!device.registered || !device.online);
|
||||
|
||||
// 잠겨 있는 동안 5초마다 상태 재확인 (WS 가 살아 있어도 이중 확인)
|
||||
useEffect(() => {
|
||||
if (!locked) return;
|
||||
const t = window.setInterval(() => void recheck(), 5000);
|
||||
return () => window.clearInterval(t);
|
||||
}, [locked, recheck]);
|
||||
|
||||
// 잠금 해제 → epoch 증가
|
||||
const wasLocked = useRef(false);
|
||||
useEffect(() => {
|
||||
if (wasLocked.current && !locked) setEpoch((e) => e + 1);
|
||||
wasLocked.current = locked;
|
||||
}, [locked]);
|
||||
|
||||
const value = useMemo(() => ({ device, serverOk, conn, locked, epoch, recheck }), [device, serverOk, conn, locked, epoch, recheck]);
|
||||
return <StatusCtx.Provider value={value}>{children}</StatusCtx.Provider>;
|
||||
}
|
||||
export const useStatus = () => useContext(StatusCtx);
|
||||
|
||||
// ── 개요 · 유저 ──────────────────────────────────────
|
||||
interface DataValue {
|
||||
overview: Overview | null;
|
||||
users: User[];
|
||||
userById: (id: string | undefined | null) => User | undefined;
|
||||
}
|
||||
const DataCtx = createContext<DataValue>({ overview: null, users: [], userById: () => undefined });
|
||||
|
||||
export function DataProvider({ children }: { children: ReactNode }) {
|
||||
const { epoch, locked } = useStatus();
|
||||
const [overview, setOverview] = useState<Overview | null>(null);
|
||||
useEffect(() => {
|
||||
if (locked) return;
|
||||
let alive = true;
|
||||
api
|
||||
.overview()
|
||||
.then((o) => alive && setOverview(o))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [epoch, locked]);
|
||||
useLive((e) => {
|
||||
if (e.type === 'users.updated') setOverview((o) => (o ? { ...o, users: e.data } : o));
|
||||
if (e.type === 'recording.state') setOverview((o) => (o ? { ...o, recording: e.data } : o));
|
||||
});
|
||||
const users = overview?.users ?? [];
|
||||
const map = useMemo(() => new Map(users.map((u) => [u.id, u])), [users]);
|
||||
const userById = useCallback((id: string | undefined | null) => (id ? map.get(id) : undefined), [map]);
|
||||
return <DataCtx.Provider value={{ overview, users, userById }}>{children}</DataCtx.Provider>;
|
||||
}
|
||||
export const useData = () => useContext(DataCtx);
|
||||
399
site/web/src/store/player.ts
Normal file
399
site/web/src/store/player.ts
Normal file
@@ -0,0 +1,399 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
import type WaveSurfer from 'wavesurfer.js';
|
||||
import type { EventItem, TimelineItem, UtteranceItem } from '@gvr/shared';
|
||||
import { audioCtx, dbToGain, playerOutput, resumeAudio } from '../lib/audio';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { settings } from './settings';
|
||||
|
||||
/**
|
||||
* 플레이어 엔진.
|
||||
* - single: 발화 하나를 <audio> 로 재생. MediaElementSource → GainNode(발화별 gainDb) → 리미터.
|
||||
* 재생 시 음량 정규화 설계: 조용한 사람은 gainDb 만큼 키워서 들린다.
|
||||
* - scene : "현장 모드". 구간 안 발화들을 실제 시각 순서대로 Web Audio 에 예약해 겹쳐서 재생.
|
||||
* sceneTs(현실 시각 ms 재생 위치)는 두 모드 공통이라 단어 강조 · 미니맵 연동이 같은 값을 쓴다.
|
||||
*/
|
||||
export interface SceneInfo {
|
||||
start: number;
|
||||
end: number;
|
||||
label: string;
|
||||
items: UtteranceItem[];
|
||||
}
|
||||
export interface PlayerState {
|
||||
mode: 'idle' | 'single' | 'scene';
|
||||
item: UtteranceItem | null;
|
||||
playing: boolean;
|
||||
loading: boolean;
|
||||
/** single: 파일 안 초 / scene: 구간 시작부터 초 */
|
||||
time: number;
|
||||
duration: number;
|
||||
sceneTs: number | null;
|
||||
scene: SceneInfo | null;
|
||||
message: string | null;
|
||||
}
|
||||
|
||||
export const DELETED_MSG = '음성 보관 기간(7일)이 지나 삭제됨';
|
||||
|
||||
interface SceneSlot {
|
||||
item: UtteranceItem;
|
||||
offset: number;
|
||||
buf: Promise<AudioBuffer | null> | null;
|
||||
pending: boolean;
|
||||
src: AudioBufferSourceNode | null;
|
||||
}
|
||||
|
||||
class Player {
|
||||
state: PlayerState = { mode: 'idle', item: null, playing: false, loading: false, time: 0, duration: 0, sceneTs: null, scene: null, message: null };
|
||||
private subs = new Set<() => void>();
|
||||
readonly el: HTMLAudioElement;
|
||||
private srcNode: MediaElementAudioSourceNode | null = null;
|
||||
private itemGain: GainNode | null = null;
|
||||
private ws: WaveSurfer | null = null;
|
||||
private loadedUrl: string | null = null;
|
||||
private token = 0;
|
||||
private raf = 0;
|
||||
private queue: UtteranceItem[] = [];
|
||||
private events: EventItem[] = [];
|
||||
private lastTs: number | null = null;
|
||||
// scene
|
||||
private slots: SceneSlot[] = [];
|
||||
private t0 = 0;
|
||||
private sceneElapsed = 0;
|
||||
private sceneRate = 1;
|
||||
private bufCache = new Map<string, Promise<AudioBuffer | null>>();
|
||||
|
||||
constructor() {
|
||||
this.el = new Audio();
|
||||
this.el.preload = 'auto';
|
||||
this.el.addEventListener('play', () => this.set({ playing: true }));
|
||||
this.el.addEventListener('playing', () => this.loop());
|
||||
this.el.addEventListener('pause', () => {
|
||||
if (this.state.mode === 'single') this.set({ playing: false });
|
||||
});
|
||||
this.el.addEventListener('ended', () => this.onEnded());
|
||||
let prev = settings.get();
|
||||
settings.subscribe(() => {
|
||||
const s = settings.get();
|
||||
if (s.rate !== prev.rate) this.applyRate(s.rate);
|
||||
if (s.normalize !== prev.normalize) this.applyGain();
|
||||
prev = s;
|
||||
});
|
||||
}
|
||||
|
||||
// ── 외부 구독 ──
|
||||
subscribe = (f: () => void) => {
|
||||
this.subs.add(f);
|
||||
return () => {
|
||||
this.subs.delete(f);
|
||||
};
|
||||
};
|
||||
getState = () => this.state;
|
||||
private set(p: Partial<PlayerState>) {
|
||||
this.state = { ...this.state, ...p };
|
||||
this.subs.forEach((f) => f());
|
||||
}
|
||||
|
||||
attachWave(ws: WaveSurfer | null) {
|
||||
this.ws = ws;
|
||||
this.loadedUrl = null;
|
||||
}
|
||||
|
||||
/** 현재 화면의 목록 (이어듣기 · ←/→ · 킬 효과음 기준) */
|
||||
setQueue(items: TimelineItem[]) {
|
||||
this.queue = items.filter((i): i is UtteranceItem => i.kind === 'utterance').sort((a, b) => a.ts - b.ts);
|
||||
this.events = items
|
||||
.filter((i): i is EventItem => i.kind === 'event' && (i.type === 'kill' || i.type === 'round_end' || i.type === 'multikill' || i.type === 'ace'))
|
||||
.sort((a, b) => a.ts - b.ts);
|
||||
}
|
||||
|
||||
private ensureGraph() {
|
||||
resumeAudio();
|
||||
if (this.srcNode) return;
|
||||
const ctx = audioCtx();
|
||||
this.srcNode = ctx.createMediaElementSource(this.el);
|
||||
this.itemGain = ctx.createGain();
|
||||
this.srcNode.connect(this.itemGain).connect(playerOutput());
|
||||
}
|
||||
|
||||
private gainFor(item: UtteranceItem | null) {
|
||||
if (!item?.audio || !settings.get().normalize) return 1;
|
||||
return dbToGain(item.audio.gainDb);
|
||||
}
|
||||
private applyGain() {
|
||||
if (this.itemGain) this.itemGain.gain.value = this.gainFor(this.state.item);
|
||||
}
|
||||
private applyRate(rate: number) {
|
||||
this.el.playbackRate = rate;
|
||||
if (this.state.mode === 'scene') {
|
||||
const was = this.state.playing;
|
||||
this.pauseScene();
|
||||
this.sceneRate = rate;
|
||||
if (was) this.resumeScene();
|
||||
}
|
||||
}
|
||||
|
||||
// ── single ──
|
||||
async play(item: UtteranceItem, seekSec = 0, opts: { auto?: boolean } = {}) {
|
||||
this.ensureGraph();
|
||||
if (this.state.mode === 'scene') this.stopScene();
|
||||
const my = ++this.token;
|
||||
const duration = (item.endTs - item.ts) / 1000;
|
||||
if (!item.audio) {
|
||||
this.el.pause();
|
||||
this.set({ mode: 'single', item, playing: false, loading: false, message: DELETED_MSG, time: 0, duration, sceneTs: item.ts, scene: null });
|
||||
return;
|
||||
}
|
||||
this.set({ mode: 'single', item, loading: true, message: null, time: seekSec, duration: item.audio.durationMs / 1000, sceneTs: item.ts + seekSec * 1000, scene: null });
|
||||
this.applyGain();
|
||||
const url = item.audio.url;
|
||||
if (this.loadedUrl !== url) {
|
||||
this.el.pause();
|
||||
try {
|
||||
if (this.ws) await this.ws.load(url);
|
||||
else this.el.src = url;
|
||||
this.loadedUrl = url;
|
||||
} catch {
|
||||
if (my !== this.token) return;
|
||||
this.set({ loading: false, playing: false, message: '음성을 불러오지 못했습니다' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (my !== this.token) return;
|
||||
this.el.playbackRate = settings.get().rate;
|
||||
try {
|
||||
this.el.currentTime = seekSec;
|
||||
await this.el.play();
|
||||
if (!opts.auto) sfx('play');
|
||||
} catch {
|
||||
if (my === this.token) this.set({ message: '재생할 수 없습니다' });
|
||||
}
|
||||
if (my === this.token) this.set({ loading: false });
|
||||
}
|
||||
|
||||
seekTo(item: UtteranceItem, sec: number) {
|
||||
if (this.state.mode === 'single' && this.state.item?.id === item.id && this.loadedUrl === item.audio?.url) {
|
||||
this.el.currentTime = sec;
|
||||
if (this.el.paused) void this.el.play();
|
||||
this.tick();
|
||||
return;
|
||||
}
|
||||
void this.play(item, sec);
|
||||
}
|
||||
|
||||
toggle() {
|
||||
const s = this.state;
|
||||
if (s.mode === 'single' && s.item) {
|
||||
if (!s.item.audio) return;
|
||||
if (this.el.paused) {
|
||||
resumeAudio();
|
||||
void this.el.play();
|
||||
sfx('play');
|
||||
} else this.el.pause();
|
||||
} else if (s.mode === 'scene') {
|
||||
if (s.playing) this.pauseScene();
|
||||
else {
|
||||
if (this.sceneElapsed >= (s.scene!.end - s.scene!.start)) this.sceneElapsed = 0;
|
||||
this.resumeScene();
|
||||
}
|
||||
} else if (this.queue.length) {
|
||||
void this.play(this.queue.find((q) => q.audio) ?? this.queue[0]);
|
||||
}
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.token++;
|
||||
this.el.pause();
|
||||
this.stopScene();
|
||||
this.set({ mode: 'idle', item: null, playing: false, loading: false, sceneTs: null, scene: null, message: null, time: 0 });
|
||||
}
|
||||
|
||||
private neighbor(dir: 1 | -1): UtteranceItem | null {
|
||||
const cur = this.state.item;
|
||||
const q = this.queue.filter((i) => i.audio || i === cur);
|
||||
if (!q.length) return null;
|
||||
if (!cur) return dir === 1 ? q[0] : q[q.length - 1];
|
||||
const idx = q.findIndex((i) => i.id === cur.id);
|
||||
if (idx >= 0) return q[idx + dir] ?? null;
|
||||
return dir === 1 ? q.find((i) => i.ts > cur.ts) ?? null : [...q].reverse().find((i) => i.ts < cur.ts) ?? null;
|
||||
}
|
||||
next() {
|
||||
const n = this.neighbor(1);
|
||||
if (n) void this.play(n);
|
||||
}
|
||||
prev() {
|
||||
if (this.state.mode === 'single' && this.el.currentTime > 1.5) {
|
||||
this.el.currentTime = 0;
|
||||
return;
|
||||
}
|
||||
const p = this.neighbor(-1);
|
||||
if (p) void this.play(p);
|
||||
}
|
||||
private onEnded() {
|
||||
if (this.state.mode !== 'single') return;
|
||||
this.tick();
|
||||
if (settings.get().continuous) {
|
||||
const n = this.neighbor(1);
|
||||
if (n) {
|
||||
void this.play(n, 0, { auto: true });
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.set({ playing: false });
|
||||
}
|
||||
|
||||
// ── scene (현장 모드) ──
|
||||
startScene(scene: SceneInfo) {
|
||||
this.ensureGraph();
|
||||
this.token++;
|
||||
this.el.pause();
|
||||
this.stopScene();
|
||||
const items = scene.items.filter((i) => i.audio && i.ts < scene.end && i.endTs > scene.start).sort((a, b) => a.ts - b.ts);
|
||||
this.slots = items.map((item) => ({ item, offset: item.ts - scene.start, buf: null, pending: false, src: null }));
|
||||
this.sceneRate = settings.get().rate;
|
||||
this.sceneElapsed = 0;
|
||||
this.set({ mode: 'scene', item: null, scene: { ...scene, items }, message: items.length ? null : '이 구간에는 들을 수 있는 발화가 없습니다', time: 0, duration: (scene.end - scene.start) / 1000, sceneTs: scene.start });
|
||||
sfx('play');
|
||||
this.resumeScene(0.15);
|
||||
}
|
||||
seekScene(ms: number) {
|
||||
if (this.state.mode !== 'scene') return;
|
||||
const was = this.state.playing;
|
||||
this.pauseScene();
|
||||
this.sceneElapsed = Math.max(0, ms);
|
||||
this.set({ time: this.sceneElapsed / 1000, sceneTs: this.state.scene!.start + this.sceneElapsed });
|
||||
if (was) this.resumeScene();
|
||||
}
|
||||
private resumeScene(lead = 0.03) {
|
||||
const ctx = audioCtx();
|
||||
this.t0 = ctx.currentTime + lead - this.sceneElapsed / 1000 / this.sceneRate;
|
||||
this.set({ playing: true });
|
||||
this.loop();
|
||||
}
|
||||
private pauseScene() {
|
||||
if (this.state.mode !== 'scene') return;
|
||||
if (this.state.playing) this.sceneElapsed = this.elapsed();
|
||||
for (const s of this.slots) {
|
||||
try {
|
||||
s.src?.stop();
|
||||
} catch {
|
||||
/* 이미 끝남 */
|
||||
}
|
||||
s.src = null;
|
||||
s.pending = false;
|
||||
}
|
||||
this.set({ playing: false });
|
||||
}
|
||||
private stopScene() {
|
||||
this.pauseScene();
|
||||
this.slots = [];
|
||||
}
|
||||
private elapsed() {
|
||||
return Math.max(0, (audioCtx().currentTime - this.t0) * this.sceneRate * 1000);
|
||||
}
|
||||
private fetchBuf(url: string) {
|
||||
let p = this.bufCache.get(url);
|
||||
if (!p) {
|
||||
p = fetch(url, { credentials: 'include' })
|
||||
.then((r) => (r.ok ? r.arrayBuffer() : Promise.reject(new Error(String(r.status)))))
|
||||
.then((ab) => audioCtx().decodeAudioData(ab))
|
||||
.catch(() => null);
|
||||
if (this.bufCache.size > 200) this.bufCache.clear();
|
||||
this.bufCache.set(url, p);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
private schedule() {
|
||||
const el = this.elapsed();
|
||||
const ctx = audioCtx();
|
||||
const normalize = settings.get().normalize;
|
||||
for (const s of this.slots) {
|
||||
if (s.src || s.pending) continue;
|
||||
const durMs = s.item.endTs - s.item.ts;
|
||||
if (s.offset > el + 6000 || s.offset + durMs < el) continue;
|
||||
s.pending = true;
|
||||
s.buf ??= this.fetchBuf(s.item.audio!.url);
|
||||
const slots = this.slots;
|
||||
void s.buf.then((buf) => {
|
||||
if (!buf || this.slots !== slots || !this.state.playing || !s.pending || s.src) return;
|
||||
const at = this.t0 + s.offset / 1000 / this.sceneRate;
|
||||
const now = ctx.currentTime;
|
||||
const src = ctx.createBufferSource();
|
||||
src.buffer = buf;
|
||||
src.playbackRate.value = this.sceneRate;
|
||||
const g = ctx.createGain();
|
||||
g.gain.value = normalize && s.item.audio ? dbToGain(s.item.audio.gainDb) : 1;
|
||||
src.connect(g).connect(playerOutput());
|
||||
if (at >= now) src.start(at);
|
||||
else {
|
||||
const into = (now - at) * this.sceneRate;
|
||||
if (into >= buf.duration) return;
|
||||
src.start(now, into);
|
||||
}
|
||||
s.src = src;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ── 시계 ──
|
||||
private loop() {
|
||||
if (this.raf) return;
|
||||
let lastSchedule = 0;
|
||||
const step = (t: number) => {
|
||||
this.raf = 0;
|
||||
if (!this.state.playing) {
|
||||
this.tick();
|
||||
return;
|
||||
}
|
||||
if (this.state.mode === 'scene' && t - lastSchedule > 200) {
|
||||
lastSchedule = t;
|
||||
this.schedule();
|
||||
}
|
||||
this.tick();
|
||||
if (this.state.playing) this.raf = requestAnimationFrame(step);
|
||||
};
|
||||
this.raf = requestAnimationFrame(step);
|
||||
}
|
||||
private tick() {
|
||||
const s = this.state;
|
||||
let sceneTs: number | null = null;
|
||||
let time = s.time;
|
||||
if (s.mode === 'single' && s.item) {
|
||||
time = this.el.currentTime;
|
||||
sceneTs = s.item.ts + time * 1000;
|
||||
} else if (s.mode === 'scene' && s.scene) {
|
||||
const el = s.playing ? this.elapsed() : this.sceneElapsed;
|
||||
time = el / 1000;
|
||||
sceneTs = s.scene.start + el;
|
||||
if (s.playing && sceneTs >= s.scene.end + 300) {
|
||||
this.sceneElapsed = s.scene.end - s.scene.start;
|
||||
this.pauseScene();
|
||||
sceneTs = s.scene.end;
|
||||
time = this.sceneElapsed / 1000;
|
||||
}
|
||||
}
|
||||
// 재생 위치가 킬 · 라운드 종료 시각을 지나가면 효과음
|
||||
if (sceneTs != null && this.lastTs != null && s.playing && sceneTs > this.lastTs && sceneTs - this.lastTs < 1500) {
|
||||
for (const e of this.events) {
|
||||
if (e.ts > this.lastTs && e.ts <= sceneTs) sfx(e.type === 'round_end' ? 'round' : 'kill');
|
||||
}
|
||||
}
|
||||
this.lastTs = sceneTs;
|
||||
if (time !== s.time || sceneTs !== s.sceneTs) this.set({ time, sceneTs });
|
||||
}
|
||||
}
|
||||
|
||||
export const player = new Player();
|
||||
|
||||
export function usePlayer<T>(sel: (s: PlayerState) => T): T {
|
||||
return useSyncExternalStore(player.subscribe, () => sel(player.state));
|
||||
}
|
||||
|
||||
/** 이 발화가 지금 재생 중(또는 선택됨)인지 */
|
||||
export function useIsActive(it: { id: string; ts: number; endTs: number }): boolean {
|
||||
return usePlayer((s) =>
|
||||
s.mode === 'single' ? s.item?.id === it.id : s.mode === 'scene' && s.sceneTs != null && s.sceneTs >= it.ts && s.sceneTs <= it.endTs,
|
||||
);
|
||||
}
|
||||
/** 발화 시작 기준 재생 위치(초). 재생 위치가 없으면 -1 */
|
||||
export function useLocalTime(ts: number): number {
|
||||
return usePlayer((s) => (s.sceneTs == null ? -1 : (s.sceneTs - ts) / 1000));
|
||||
}
|
||||
72
site/web/src/store/settings.ts
Normal file
72
site/web/src/store/settings.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
|
||||
export type SfxKind = 'click' | 'play' | 'kill' | 'round' | 'chime';
|
||||
export interface Settings {
|
||||
volume: number; // 효과음 전체 볼륨 0..1
|
||||
sfx: Record<SfxKind, boolean>;
|
||||
reduceMotion: boolean;
|
||||
rate: number;
|
||||
continuous: boolean;
|
||||
normalize: boolean;
|
||||
}
|
||||
|
||||
const KEY = 'gvr.settings.v1';
|
||||
const DEFAULTS: Settings = {
|
||||
volume: 0.5,
|
||||
sfx: { click: true, play: true, kill: true, round: true, chime: true },
|
||||
reduceMotion: false,
|
||||
rate: 1,
|
||||
continuous: true,
|
||||
normalize: true,
|
||||
};
|
||||
|
||||
function load(): Settings {
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY);
|
||||
if (!raw) return DEFAULTS;
|
||||
const v = JSON.parse(raw) as Partial<Settings>;
|
||||
return { ...DEFAULTS, ...v, sfx: { ...DEFAULTS.sfx, ...(v.sfx ?? {}) } };
|
||||
} catch {
|
||||
return DEFAULTS;
|
||||
}
|
||||
}
|
||||
|
||||
let state: Settings = load();
|
||||
const subs = new Set<() => void>();
|
||||
|
||||
export const settings = {
|
||||
get: () => state,
|
||||
set(patch: Partial<Settings>) {
|
||||
state = { ...state, ...patch };
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify(state));
|
||||
} catch {
|
||||
/* 사생활 보호 모드 등 */
|
||||
}
|
||||
subs.forEach((f) => f());
|
||||
},
|
||||
subscribe(f: () => void) {
|
||||
subs.add(f);
|
||||
return () => {
|
||||
subs.delete(f);
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export function useSettings(): Settings {
|
||||
return useSyncExternalStore(settings.subscribe, settings.get);
|
||||
}
|
||||
|
||||
const mq = typeof window !== 'undefined' ? window.matchMedia('(prefers-reduced-motion: reduce)') : null;
|
||||
/** 시스템 설정(prefers-reduced-motion) 또는 앱의 "모션 줄이기" */
|
||||
export function useReducedMotion(): boolean {
|
||||
const s = useSettings();
|
||||
const sys = useSyncExternalStore(
|
||||
(f) => {
|
||||
mq?.addEventListener('change', f);
|
||||
return () => mq?.removeEventListener('change', f);
|
||||
},
|
||||
() => !!mq?.matches,
|
||||
);
|
||||
return s.reduceMotion || sys;
|
||||
}
|
||||
3204
site/web/src/styles.css
Normal file
3204
site/web/src/styles.css
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user