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:
EJClaw
2026-10-15 01:32:51 +09:00
parent 2745af8f61
commit 9abda88046
84 changed files with 13399 additions and 21 deletions

View 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" /> 우리 팀 &nbsp; <span className="lg-ring en" /> 상대 팀 &nbsp; <b className="accent">✕</b> 우리 팀 데스 &nbsp; <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>
);
}

View 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} />}
</>
);
}

View 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>
);
}

View 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>
);
}

View 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>
);
}

View 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> 우리 팀이 처치 &nbsp; <b className="accent">✕</b> 상대 팀이 처치 &nbsp; <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>
);
}