Files
lolympus-tournament-support/apps/web/src/pages/CommunityInternalStatsPage.tsx
T

816 lines
29 KiB
TypeScript

import { useState } from 'react';
import type { CompetitionDetailResponse } from '@lolympus/contracts';
import { ChevronDown, Search, X } from 'lucide-react';
import { Link, useLocation, useParams, useSearchParams } from 'react-router';
import {
useCommunity,
useCompetition,
useCommunityInternalStatsMatches,
useCommunityLeaderboard,
useDdragonManifest,
useTeamInsights,
} from '../api/hooks';
import type {
ApiInternalMatchCard,
ApiLeaderHighlight,
ApiLeaderboardRow,
} from '../api/types';
import { DEFAULT_COMMUNITY_ID } from '../config';
import {
championDisplayName,
championIconUrl,
profileIconUrl,
} from '../lib/ddragon';
import {
internalMatchDetailPath,
internalMatchGamePath,
} from '../lib/internal-match-routes';
import {
getHistoryMatchTitle,
getHomeMatchSchedule,
} from './home-match-presentation';
import {
getSeriesHistoryResultLabel,
shouldDisplaySeriesHistoryScore,
} from '../components/competition/competition-series-history';
import {
Btn,
Chip,
EmptyNote,
ErrorNote,
LoadingNote,
Panel,
PanelHeader,
PlainPage,
Skeleton,
} from '../ui';
type Manifest = ReturnType<typeof useDdragonManifest>['data'];
function ratioClass(value: number) {
if (value >= 60) return 'text-loss';
if (value >= 50) return 'text-win';
return 'text-content-muted';
}
function kdaClass(value: number) {
if (value >= 5) return 'text-gold';
if (value >= 3) return 'text-leaf';
return 'text-content-muted';
}
function ChampionChip({
championId,
manifest,
}: {
championId: number;
manifest: Manifest;
}) {
const icon = championIconUrl(manifest, championId);
const name = championDisplayName(manifest, championId) ?? String(championId);
return (
<span
className="size-7 overflow-hidden rounded-full bg-sunken-strong"
title={name}
>
{icon ? (
<img
src={icon}
alt={name}
className="size-full scale-[1.15] object-cover"
loading="lazy"
/>
) : null}
</span>
);
}
function OfficialMatchResult({
competition,
}: {
competition: CompetitionDetailResponse;
}) {
const { projection, teams } = competition;
const teamName = (id: string) =>
teams.find(({ teamId }) => teamId === id)?.name ?? '팀 미확인';
const outcome = projection.outcome;
if (projection.phase === 'cancelled') return '취소';
if (projection.phase !== 'completed' || !outcome) return '결과 확정 전';
switch (outcome.type) {
case 'double-elimination':
return `우승 · ${teamName(outcome.championTeamId)}`;
case 'round-robin':
return outcome.leaderTeamIds.length > 0
? `${outcome.leaderTeamIds.length > 1 ? '공동 1위' : '우승'} · ${outcome.leaderTeamIds.map(teamName).join(', ')}`
: '대회 종료';
case 'paired-series': {
if (projection.series.length !== 1) return '시리즈 종료';
const series = projection.series[0];
if (!shouldDisplaySeriesHistoryScore(series))
return getSeriesHistoryResultLabel(series) ?? '시리즈 종료';
const [left, right] = series.entries;
return `${teamName(left.teamId ?? '')} ${left.gameWins} : ${right.gameWins} ${teamName(right.teamId ?? '')}`;
}
}
}
function MatchCard({
match,
communityId,
}: {
match: ApiInternalMatchCard;
communityId: string;
}) {
const [open, setOpen] = useState(false);
const competition = useCompetition(match.matchId, communityId, open);
const location = useLocation();
const backTo = `${location.pathname}${location.search}`;
const recordedGames = match.games.filter(
({ winnerTeamIndex }) => winnerTeamIndex !== null,
);
const schedule = getHomeMatchSchedule(match.scheduledAt);
return (
<li>
<details
className="group"
onToggle={(event) => setOpen(event.currentTarget.open)}
>
<summary className="grid cursor-pointer list-none grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-2 px-4 py-3.5 hover:bg-sunken focus-visible:-outline-offset-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,auto)_auto] sm:px-5 [&::-webkit-details-marker]:hidden">
<span className="min-w-0">
<span className="tabular block text-xs text-content-muted">
<time dateTime={match.scheduledAt}>
{schedule?.compact ?? '일정 미정'}
</time>{' '}
· {match.teams.length}팀
</span>
<strong className="mt-1 block break-words text-base font-semibold leading-snug">
{getHistoryMatchTitle(match.title, schedule)}
</strong>
</span>
<span className="col-start-1 row-start-2 text-sm text-content-muted sm:col-start-2 sm:row-start-1">
{competition.data ? (
<strong className="font-semibold text-content">
<OfficialMatchResult competition={competition.data} />
</strong>
) : (
`${recordedGames.length}세트 수집`
)}
</span>
<ChevronDown
className="col-start-2 row-span-2 row-start-1 size-4 text-content-muted transition-transform group-open:rotate-180 sm:col-start-3 sm:row-span-1"
aria-hidden="true"
/>
</summary>
{open && (
<div className="border-t border-line bg-sunken px-4 py-3 sm:px-5">
<div className="flex flex-wrap items-center justify-between gap-2 text-sm">
<p className="text-content-muted">
{competition.isLoading
? '공식 결과를 확인하는 중'
: competition.data
? '수집된 세트 기록'
: '공식 시리즈 정보를 확인할 수 없습니다'}
</p>
<Link
className="font-semibold hover:underline"
to={internalMatchDetailPath(communityId, match.matchId)}
state={{ backTo }}
>
내전 기록 전체 보기 →
</Link>
</div>
{recordedGames.length > 0 && (
<ul className="mt-2 divide-y divide-line text-sm">
{recordedGames.map((game) => {
const winner = match.teams.find(
({ teamIndex }) => teamIndex === game.winnerTeamIndex,
);
return (
<li
key={game.gameNumber}
className="flex flex-wrap items-center justify-between gap-x-3 py-2"
>
<span className="tabular">
전체 {game.gameNumber}세트 ·{' '}
{winner ? `${winner.name} 승` : '팀 미확인'}
</span>
{game.riotMatchId && (
<Link
className="font-semibold hover:underline"
to={internalMatchGamePath(
communityId,
match.matchId,
game.gameNumber,
)}
state={{ backTo, backLabel: '내전 전적으로' }}
>
상세 분석
</Link>
)}
</li>
);
})}
</ul>
)}
</div>
)}
</details>
</li>
);
}
function HighlightCell({
title,
highlight,
suffix = '',
}: {
title: string;
highlight: ApiLeaderHighlight | null | undefined;
suffix?: string;
}) {
const location = useLocation();
return (
<div className="min-w-0 px-4 py-3.5 sm:px-5">
<div className="text-xs font-semibold text-content-subtle">{title}</div>
<div className="tabular mt-1 text-[22px] font-extrabold leading-tight text-content">
{highlight ? `${highlight.metric}${suffix}` : '—'}
</div>
{highlight ? (
<Link
to={`/users/${highlight.userId}/history?queueGroup=internal`}
state={{ backTo: `${location.pathname}${location.search}` }}
className="mt-0.5 block truncate text-[13px] font-medium text-content-muted hover:text-primary"
>
{highlight.summonerName}
</Link>
) : (
<div className="mt-0.5 text-[13px] text-content-subtle">기록 없음</div>
)}
</div>
);
}
function LeaderboardTable({
rows,
ranks,
manifest,
onSelectPlayer,
}: {
rows: ApiLeaderboardRow[];
ranks: ReadonlyMap<string, number>;
manifest: Manifest;
onSelectPlayer: (id: string) => void;
}) {
const location = useLocation();
const [showMetrics, setShowMetrics] = useState(false);
const metricClass = showMetrics ? '' : 'hidden 2xl:table-cell';
const historyBackTo = `${location.pathname}${location.search}${location.hash}`;
return (
<>
<div className="border-b border-line px-4 py-2 2xl:hidden">
<Chip
selected={showMetrics}
onClick={() => setShowMetrics(!showMetrics)}
>
상세 지표
</Chip>
</div>
<div className="overflow-x-auto">
<table
className={showMetrics ? 'lts-table min-w-[760px]' : 'lts-table'}
>
<thead>
<tr>
<th scope="col" className="w-12 !text-center">
순위
</th>
<th scope="col">소환사</th>
<th scope="col" className="!text-right">
승률
</th>
<th scope="col" className="!text-right">
전적
</th>
<th scope="col" className={`${metricClass} !text-right`}>
KDA
</th>
<th scope="col" className={`${metricClass} !text-right`}>
GPM
</th>
<th scope="col" className={`${metricClass} !text-right`}>
킬관여
</th>
<th scope="col" className={`${metricClass} !text-right`}>
분당 CS
</th>
<th scope="col" className={metricClass}>
주 챔피언
</th>
</tr>
</thead>
<tbody>
{rows.map((row) => {
const rank = ranks.get(row.userId) ?? 0;
return (
<tr
key={row.userId}
className="transition-colors hover:bg-sunken"
>
<td className="tabular text-center">
{rank <= 3 ? (
<span
className={`inline-grid size-6 place-items-center rounded-full text-xs font-extrabold ${
rank === 1
? 'bg-gold text-accent-content'
: 'bg-sunken-strong text-content-muted'
}`}
>
{rank}
</span>
) : (
<span className="text-[13px] text-content-subtle">
{rank}
</span>
)}
</td>
<td>
<Link
to={`/users/${row.userId}/history?queueGroup=internal`}
state={{ backTo: historyBackTo }}
className="group flex items-center gap-2.5"
>
<img
src={profileIconUrl(manifest, row.profileIconId)}
alt=""
className="hidden size-8 shrink-0 rounded-full sm:block bg-sunken-strong object-cover"
loading="lazy"
/>
<span className="break-words font-semibold text-content group-hover:text-primary">
{row.summonerName}
</span>
</Link>
<button
type="button"
className="mt-1 text-xs text-content-muted hover:underline"
onClick={() => onSelectPlayer(row.userId)}
>
참가 내전
</button>
</td>
<td
className={`tabular text-right font-bold ${ratioClass(row.winRate)}`}
>
{row.winRate}%
</td>
<td className="tabular whitespace-nowrap text-right text-[13px] text-content-muted">
{row.games}전 {row.wins}승 {row.losses}패
</td>
<td
className={`tabular text-right font-semibold ${metricClass} ${kdaClass(row.kda)}`}
>
{row.kda}
</td>
<td
className={`tabular text-right text-[13px] ${metricClass}`}
>
{row.avgGoldPerMin}
</td>
<td
className={`tabular text-right text-[13px] ${metricClass}`}
>
{row.avgKillParticipation}%
</td>
<td
className={`tabular text-right text-[13px] ${metricClass}`}
>
{row.avgCsPerMin}
</td>
<td className={metricClass}>
<div className="flex gap-1">
{row.topChampions.map((champion) => (
<ChampionChip
key={champion.championId}
championId={champion.championId}
manifest={manifest}
/>
))}
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</>
);
}
function SideWinRate({
blue,
red,
sampleSize,
}: {
blue: number;
red: number;
sampleSize: number;
}) {
if (sampleSize === 0 || blue + red === 0) {
return <p className="text-sm text-content-muted">진영 승률 집계 없음</p>;
}
return (
<div>
<p className="text-sm font-semibold">진영 승률</p>
<div className="tabular mt-2 flex justify-between gap-2 text-xs font-semibold">
<span>블루 {blue}%</span>
<span>레드 {red}%</span>
</div>
<div
className="mt-2 flex h-1.5 gap-0.5 overflow-hidden rounded-full bg-sunken-strong"
aria-hidden="true"
>
<span className="bg-win" style={{ width: `${blue}%` }} />
<span className="bg-loss" style={{ width: `${red}%` }} />
</div>
<p className="tabular mt-2 text-xs text-content-muted">
{sampleSize}세트 집계
</p>
</div>
);
}
export default function CommunityInternalStatsPage() {
const { cid } = useParams();
const communityId = cid ?? DEFAULT_COMMUNITY_ID;
const [searchParams, setSearchParams] = useSearchParams();
const isRanking = searchParams.get('view') === 'ranking';
const seasonId = searchParams.get('seasonId') || 'current';
const query = searchParams.get('q') ?? '';
const keyword = query.trim().toLocaleLowerCase('ko-KR');
const format = searchParams.get('format');
const playerId = searchParams.get('player');
const championId = Number(searchParams.get('championId'));
const filters = {
seasonId,
championId:
Number.isFinite(championId) && championId > 0 ? championId : undefined,
limit: 12,
};
const communityQuery = useCommunity(communityId);
const matchesQuery = useCommunityInternalStatsMatches(
filters,
communityId,
!isRanking,
);
const leaderboardQuery = useCommunityLeaderboard(filters, communityId);
const insightsQuery = useTeamInsights(filters, communityId);
const { data: ddragon } = useDdragonManifest();
const matches =
matchesQuery.data?.pages.flatMap((page) => page.matches) ?? [];
const season =
insightsQuery.data?.season ??
leaderboardQuery.data?.season ??
matchesQuery.data?.pages[0]?.season;
const insights = insightsQuery.data;
const leaderboardRows = leaderboardQuery.data?.rows ?? [];
const player = leaderboardRows.find((row) => row.userId === playerId);
const visibleMatches = matches.filter((match) => {
const matchType = match.teams.length === 2 ? 'pair' : 'tournament';
return (
((format !== 'pair' && format !== 'tournament') ||
matchType === format) &&
(!playerId ||
match.teams.some((team) =>
team.members.some((member) => member.userId === playerId),
)) &&
match.title.toLocaleLowerCase('ko-KR').includes(keyword)
);
});
const visiblePlayers = leaderboardRows.filter((row) =>
row.summonerName.toLocaleLowerCase('ko-KR').includes(keyword),
);
const hasMatchFilters = Boolean(
keyword || format === 'pair' || format === 'tournament' || playerId,
);
const title = isRanking ? '선수 순위' : '최근 내전';
if (!communityId) {
return (
<PlainPage className="lts-overview py-16">
<ErrorNote
title="커뮤니티가 설정되지 않았습니다"
description="VITE_DEFAULT_COMMUNITY_ID 설정이 필요합니다."
/>
</PlainPage>
);
}
function updateParam(key: string, value: string) {
const params = new URLSearchParams(searchParams);
if (key === 'view' || key === 'seasonId' || key === 'player') {
params.delete('q');
params.delete('format');
params.delete('player');
}
if (key === 'player') params.delete('view');
if (value) params.set(key, value);
else params.delete(key);
setSearchParams(params, { replace: key === 'q', preventScrollReset: true });
}
return (
<div className="min-h-[calc(100vh-var(--app-header-height))]">
<PlainPage className="lts-overview">
<header className="flex flex-wrap items-end justify-between gap-4">
<div>
<p className="text-sm text-content-muted">
{communityQuery.data?.name ?? '커뮤니티'}
</p>
<h1 className="mt-1 text-2xl font-bold tracking-tight sm:text-[30px]">
내전 전적
</h1>
</div>
<div className="flex flex-wrap items-center gap-3">
<Link
to="/?history=all"
className="text-sm font-semibold text-content-muted hover:underline"
>
전체 일정 기록
</Link>
<label className="flex items-center gap-2 text-sm font-semibold">
시즌
<select
className="lts-select !w-auto"
value={seasonId}
onChange={(event) =>
updateParam('seasonId', event.target.value)
}
>
<option value="current">현재 시즌</option>
<option value="all">전체 시즌</option>
{seasonId !== 'current' && seasonId !== 'all' && (
<option value={seasonId}>{season?.label ?? seasonId}</option>
)}
</select>
</label>
</div>
</header>
<div className="mt-6 grid gap-5 lg:grid-cols-[minmax(0,1fr)_16rem]">
<section className="min-w-0" aria-labelledby="internal-stats-heading">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex gap-1.5" role="group" aria-label="전적 보기">
<Chip
selected={!isRanking}
onClick={() => updateParam('view', '')}
>
최근 내전
</Chip>
<Chip
selected={isRanking}
onClick={() => updateParam('view', 'ranking')}
>
선수 순위
</Chip>
</div>
<label className="flex h-10 w-full items-center gap-2 rounded-full border border-line-strong bg-card px-3 text-content-muted focus-within:border-content-muted sm:w-60">
<Search className="size-4 shrink-0" aria-hidden="true" />
<input
type="search"
aria-label={isRanking ? '선수 검색' : '내전명 검색'}
placeholder={isRanking ? '선수 이름 검색' : '내전명 검색'}
value={query}
onChange={(event) => updateParam('q', event.target.value)}
className="min-w-0 flex-1 text-sm text-content focus-visible:outline-none"
/>
</label>
</div>
<Panel className="mt-4 overflow-hidden">
<div className="flex flex-wrap items-center justify-between gap-2 border-b border-line px-4 py-3 sm:px-5">
<h2 id="internal-stats-heading" className="text-base font-bold">
{title}{' '}
<span className="tabular ml-1 text-sm font-medium text-content-muted">
{isRanking ? visiblePlayers.length : visibleMatches.length}
</span>
</h2>
{isRanking ? (
<span className="text-xs text-content-muted">승률 순</span>
) : (
<div
className="flex flex-wrap gap-1.5"
role="group"
aria-label="내전 유형"
>
<Chip
selected={format !== 'pair' && format !== 'tournament'}
onClick={() => updateParam('format', '')}
>
전체
</Chip>
<Chip
selected={format === 'pair'}
onClick={() => updateParam('format', 'pair')}
>
두 팀 내전
</Chip>
<Chip
selected={format === 'tournament'}
onClick={() => updateParam('format', 'tournament')}
>
대회
</Chip>
</div>
)}
</div>
{!isRanking && playerId && (
<div className="border-b border-line px-4 py-2">
<Chip
selected
onClick={() => updateParam('player', '')}
aria-label="선수 필터 해제"
>
{player?.summonerName ?? '선택한 선수'} 참가 내전{' '}
<X className="size-3.5" aria-hidden="true" />
</Chip>
</div>
)}
{isRanking ? (
leaderboardQuery.isLoading ? (
<LoadingNote label="순위를 불러오는 중" />
) : leaderboardQuery.isError && !leaderboardQuery.data ? (
<div className="p-4">
<ErrorNote
title="순위를 불러오지 못했습니다"
action={
<Btn
size="sm"
onClick={() => void leaderboardQuery.refetch()}
>
다시 시도
</Btn>
}
/>
</div>
) : visiblePlayers.length === 0 ? (
<EmptyNote
size="sm"
title={
keyword
? '조건에 맞는 선수가 없습니다'
: '아직 집계할 내전 기록이 없습니다'
}
/>
) : (
<LeaderboardTable
rows={visiblePlayers}
ranks={
new Map(
leaderboardRows.map((row, index) => [
row.userId,
index + 1,
]),
)
}
manifest={ddragon}
onSelectPlayer={(id) => updateParam('player', id)}
/>
)
) : (
<>
{matchesQuery.isLoading ? (
<LoadingNote label="내전 기록을 불러오는 중" />
) : matchesQuery.isError && !matchesQuery.data ? (
<div className="p-4">
<ErrorNote
title="내전 기록을 불러오지 못했습니다"
action={
<Btn
size="sm"
onClick={() => void matchesQuery.refetch()}
>
다시 시도
</Btn>
}
/>
</div>
) : visibleMatches.length === 0 ? (
<EmptyNote
size="sm"
title={
hasMatchFilters
? '불러온 기록에 일치하는 내전이 없습니다'
: '아직 수집된 내전 결과가 없습니다'
}
/>
) : (
<ul className="divide-y divide-line">
{visibleMatches.map((match) => (
<MatchCard
key={match.matchId}
match={match}
communityId={communityId}
/>
))}
</ul>
)}
{matchesQuery.hasNextPage && (
<div className="space-y-2 border-t border-line p-3">
{hasMatchFilters && (
<p className="text-center text-xs text-content-muted">
필터는 불러온 {matches.length}건에 적용됩니다.
</p>
)}
{matchesQuery.isFetchNextPageError && (
<p
role="status"
className="text-center text-sm text-content-muted"
>
이전 기록을 불러오지 못했습니다.
</p>
)}
<Btn
variant="ghost"
className="w-full"
disabled={matchesQuery.isFetchingNextPage}
loading={matchesQuery.isFetchingNextPage}
onClick={() => void matchesQuery.fetchNextPage()}
>
{matchesQuery.isFetchNextPageError
? '다시 시도'
: '이전 기록 더 보기'}
</Btn>
</div>
)}
</>
)}
</Panel>
</section>
<aside className="space-y-3" aria-label="시즌 정보">
<Panel>
<PanelHeader title="시즌 요약" description={season?.label} />
<div className="p-4">
{insightsQuery.isLoading ? (
<Skeleton width="100%" height={52} />
) : insights ? (
<SideWinRate
blue={insights.sideWinRate.blue}
red={insights.sideWinRate.red}
sampleSize={insights.sideWinRate.bluePicks}
/>
) : (
<ErrorNote
title="시즌 요약을 불러오지 못했습니다"
action={
<Btn
size="sm"
onClick={() => void insightsQuery.refetch()}
>
다시 시도
</Btn>
}
/>
)}
</div>
</Panel>
{insights && (
<details className="lts-panel">
<summary className="cursor-pointer px-4 py-3 text-sm font-semibold">
시즌 기록
</summary>
<div className="divide-y divide-line border-t border-line">
<HighlightCell title="최고 KDA" highlight={insights.topKda} />
<HighlightCell
title="누적 킬"
highlight={insights.mostKills}
/>
<HighlightCell
title="단일 경기 GPM"
highlight={insights.topTeamGpm}
/>
<HighlightCell
title="킬 관여율"
highlight={insights.topKillParticipation}
suffix="%"
/>
<HighlightCell
title="분당 CS"
highlight={insights.bestFarm}
/>
</div>
</details>
)}
</aside>
</div>
</PlainPage>
</div>
);
}