import { lazy, Suspense, useState } from "react"; import { useQueryClient } from "@tanstack/react-query"; import { ArrowDown, RefreshCw, X } from "lucide-react"; import { useLocation, useParams, useSearchParams } from "react-router"; import { Chip, EmptyNote, ErrorNote, MetaDot, PageBody, PageHero, Panel, PanelHeader, PlainPage, } from "../ui"; import { useChampionStats, useDdragonManifest, useInternalMatchDetail, useRecentMatches, useRecentSummary, useRefreshUserHistory, useUserInternalHistory, useUserHistoryProfile, type UserHistoryFilters, } from "../api/hooks"; import { useRiotRefreshSocket } from "../api/useRiotRefreshSocket"; import type { ApiChampionStatsRow, ApiEnqueueRefreshResult, ApiInternalMatchDetailResponse, ApiRiotRefreshEvent, ApiRecentMatchTeam, ApiRecentMatchTeamParticipant, ApiRecentMatchView, DdragonManifest, RiotQueueGroup, RiotRankFilter, } from "../api/types"; import { DEFAULT_COMMUNITY_ID } from "../config"; import { ApiError } from "../lib/api"; import { championDisplayName, championIconUrl, profileIconUrl, } from "../lib/ddragon"; import { isRiotQueueGroup, isRiotRankFilter, LANE_LABELS, QUEUE_GROUP_TABS, RANK_FILTER_TABS, } from "../lib/riot-history"; import { multiKillLabel, rankPositionRates, } from "../lib/multi-kill"; import { ResponsiveTierLabel } from "../components/RankBadge"; import { formatRankDetail } from "../components/rankBadgeUtils"; import { InternalGameAnalysisPanel, InternalGameDetailTabBar, type InternalGameDetailTab, } from "../components/InternalGameAnalysisTabs"; import { ItemIcon, RuneIcon, RuneStyleIcon, SummonerSpellIcon, } from "../components/ItemTooltip"; import { Btn } from "../ui/Btn"; // recharts가 무거워 메인 번들에서 분리한다 (전적 페이지에서만 로드). const TierHistoryChart = lazy(() => import("../components/TierHistoryChart")); type ChampionSortKey = "games" | "winRate" | "kda" | "avgCsPerMin"; type HistoryLocationState = { backTo?: unknown; }; function resolveBackTo(state: unknown) { if (!state || typeof state !== "object") return "/"; const backTo = (state as HistoryLocationState).backTo; if ( typeof backTo !== "string" || !backTo.startsWith("/") || backTo.startsWith("//") ) { return "/"; } return backTo; } function formatDuration(seconds: number) { const minutes = Math.floor(seconds / 60); const rest = seconds % 60; return `${minutes}:${String(rest).padStart(2, "0")}`; } function formatDate(ms: number) { return new Intl.DateTimeFormat("ko-KR", { month: "long", day: "numeric", hour: "2-digit", minute: "2-digit", }).format(new Date(ms)); } function formatLastFetched(value: string | null | undefined) { if (!value) return "저장된 갱신 시각 없음"; return new Intl.DateTimeFormat("ko-KR", { month: "long", day: "numeric", hour: "2-digit", minute: "2-digit", }).format(new Date(value)); } function formatEta(seconds: number) { if (seconds < 60) return `${Math.max(1, Math.ceil(seconds))}초`; return `${Math.ceil(seconds / 60)}분`; } function formatRefreshError(error: unknown) { if (error instanceof ApiError) { const data = error.data; if ( typeof data === "object" && data !== null && "retryAfterSeconds" in data && typeof data.retryAfterSeconds === "number" ) { return `잠시 후 다시 시도해 주세요. 약 ${formatEta(data.retryAfterSeconds)} 뒤에 요청할 수 있습니다.`; } return error.message; } return error instanceof Error ? error.message : "갱신 요청에 실패했습니다."; } 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 QueueTab({ active, children, onClick, }: { active: boolean; children: React.ReactNode; onClick: () => void; }) { return ( ); } function ChampionIcon({ championId, manifest, size = "md", className = "", }: { championId: number; manifest: DdragonManifest | null | undefined; size?: "xs" | "sm" | "md" | "lg"; className?: string; }) { const iconUrl = championIconUrl(manifest, championId); const displayName = championDisplayName(manifest, championId) ?? String(championId); const sizeClass = size === "lg" ? "w-12 h-12" : size === "sm" ? "w-5 h-5" : size === "xs" ? "w-4 h-4" : "w-8 h-8"; return (
{iconUrl ? ( {displayName} ) : null}
); } function SummaryCard({ label, value, sub, valueClassName = "text-content-strong", }: { label: string; value: React.ReactNode; sub?: React.ReactNode; valueClassName?: string; }) { return (
{label}
{value}
{sub &&
{sub}
}
); } function SortableHeader({ sortKey, activeKey, onSort, children, }: { sortKey: ChampionSortKey; activeKey: ChampionSortKey; onSort: (key: ChampionSortKey) => void; children: React.ReactNode; }) { const active = sortKey === activeKey; return ( ); } function ChampionStatsTable({ rows, manifest, selectedChampionId, onChampionSelect, sortKey, onSort, }: { rows: ApiChampionStatsRow[]; manifest: DdragonManifest | null | undefined; selectedChampionId?: number; onChampionSelect: (championId: number | null) => void; sortKey: ChampionSortKey; onSort: (key: ChampionSortKey) => void; }) { if (rows.length === 0) { return (
조건에 맞는 챔피언 통계가 아직 없습니다.
); } return (
승률 게임 KDA CS {rows.map((row) => { const displayName = championDisplayName(manifest, row.championId) ?? String(row.championId); const selected = selectedChampionId === row.championId; const multiKills = [ ["더블", row.doubleKills], ["트리플", row.tripleKills], ["쿼드라", row.quadraKills], ["펜타", row.pentaKills], ].filter(([, count]) => Number(count) > 0); return ( ); })}
챔피언 평균 K / D / A 멀티킬 매치
{displayName}
{row.winRate}% {row.wins}승 {row.losses}패
{row.games} {row.kda} {row.avgKills} /{" "} {row.avgDeaths} /{" "} {row.avgAssists} {multiKills.length > 0 ? multiKills .map(([label, count]) => `${label} ${count}`) .join(" · ") : "—"} {row.avgCs}{" "} ({row.avgCsPerMin}/분) onChampionSelect(selected ? null : row.championId) } > {selected ? "해제" : "보기"}
); } function ItemSlot({ itemId, manifest, trinket = false, }: { itemId: number; manifest: DdragonManifest | null | undefined; trinket?: boolean; }) { return ( ); } function ItemGrid({ items, trinket, manifest, itemKey, variant = "card", }: { items: number[]; trinket: number; manifest: DdragonManifest | null | undefined; itemKey: string; variant?: "card" | "detail"; }) { // 6칸을 항상 채워 트링켓이 밀리지 않도록 빈 슬롯으로 패딩한다. const coreItems = [...items.slice(0, 6)]; while (coreItems.length < 6) coreItems.push(0); const gridCols = variant === "detail" ? "grid-cols-6" : "grid-cols-3"; return (
{coreItems.map((itemId, index) => ( ))}
); } type MatchDetailScales = { maxDamage: number; }; function formatCompactNumber(value: number) { const safeValue = Number.isFinite(value) ? value : 0; const abs = Math.abs(safeValue); if (abs >= 1000) { return `${(safeValue / 1000).toFixed(1).replace(/\.0$/, "")}k`; } return safeValue.toLocaleString(); } function resolveParticipantKda(participant: ApiRecentMatchTeamParticipant) { const score = participant.kills + participant.assists; return participant.deaths === 0 ? score : Math.round((score / participant.deaths) * 10) / 10; } function barPercent(value: number, max: number) { if (!Number.isFinite(value) || !Number.isFinite(max) || max <= 0) return 0; return Math.max(0, Math.min(100, Math.round((value / max) * 100))); } function LoadoutIcons({ summonerSpells, perks, manifest, }: { summonerSpells: [number, number]; perks: ApiRecentMatchTeamParticipant["perks"]; manifest: DdragonManifest | null | undefined; }) { return (
); } function DetailStatBar({ label, value, max, fillClass, }: { label: string; value: number; max: number; fillClass: string; }) { return (
{label} {formatCompactNumber(value)}
); } function TeamHeader({ team }: { team: ApiRecentMatchTeam }) { const sideLabel = team.side === 100 ? "블루팀" : "레드팀"; const sideClass = team.side === 100 ? "text-win" : "text-loss"; const resultClass = team.win ? "text-win" : "text-loss"; return (
{sideLabel} {team.win ? "승리" : "패배"}
드래곤 {team.objectives?.dragon ?? 0} 바론 {team.objectives?.baron ?? 0} 타워 {team.objectives?.tower ?? 0}
); } function ParticipantRow({ participant, manifest, ownerParticipantId, scales, teamSide, teamKills, }: { participant: ApiRecentMatchTeamParticipant; manifest: DdragonManifest | null | undefined; ownerParticipantId: string; scales: MatchDetailScales; teamSide: 100 | 200; teamKills: number; }) { const championName = championDisplayName(manifest, participant.championId) ?? String(participant.championId); const championUrl = championIconUrl(manifest, participant.championId); const participantName = participant.gameName || championName; const isOwner = participant.puuid === ownerParticipantId; const kda = resolveParticipantKda(participant); const fillClass = teamSide === 100 ? "bg-blue-400/70" : "bg-red-400/70"; const killParticipation = teamKills > 0 ? Math.round( ((participant.kills + participant.assists) / teamKills) * 100, ) : 0; return (
{championUrl ? ( {championName} ) : null} {participant.championLevel > 0 && ( {participant.championLevel} )}
{participantName}
{participant.tier && (
{formatRankDetail(participant.tier)}
)}
{participant.kills} / {participant.deaths} / {participant.assists}
{participant.deaths === 0 ? "Perfect" : kda} · {killParticipation}%
시야 {participant.visionScore}
와드 {participant.wardsPlaced}/{participant.wardsKilled} · 제어{" "} {participant.controlWardsBought}
CS {participant.totalCs}{" "} ({participant.csPerMin}/m)
골드 {formatCompactNumber(participant.goldEarned)}
); } function MatchDetailPanel({ match, manifest, ownerParticipantId, }: { match: ApiRecentMatchView; manifest: DdragonManifest | null | undefined; ownerParticipantId: string; }) { const teams = [...match.teams].sort((left, right) => left.side - right.side); const participants = teams.flatMap((team) => team.participants); const scales: MatchDetailScales = { maxDamage: Math.max( 1, ...participants.map((participant) => participant.damageDealtToChampions), ), }; if (participants.length === 0) { return (
이 경기의 상세 팀 데이터가 아직 없습니다.
); } return (
{teams.map((team) => (
{(() => { const teamKills = team.participants.reduce( (sum, participant) => sum + participant.kills, 0, ); return (
소환사
KDA
피해량
와드
CS · 골드
아이템
{team.participants.map((participant) => ( ))}
); })()}
))}
); } function resolveInternalDetailGame( detail: ApiInternalMatchDetailResponse | undefined, match: ApiRecentMatchView, ) { if (!detail) return undefined; return detail.games.find( (game) => game.riotMatchId === match.matchId && (match.gameNumber === undefined || game.gameNumber === match.gameNumber), ); } function MatchDetailTabs({ match, manifest, ownerParticipantId, }: { match: ApiRecentMatchView; manifest: DdragonManifest | null | undefined; ownerParticipantId: string; }) { const [activeTab, setActiveTab] = useState("scoreboard"); const hasInternalAnalysis = Boolean(match.internalMatchId); const detailQuery = useInternalMatchDetail( hasInternalAnalysis && activeTab !== "scoreboard" ? match.internalMatchId : undefined, DEFAULT_COMMUNITY_ID, ); const selectedGame = resolveInternalDetailGame(detailQuery.data, match); const scoreboard = ( ); if (!hasInternalAnalysis) { return scoreboard; } function renderTabContent() { if (activeTab === "scoreboard") { return scoreboard; } if (detailQuery.isLoading) { return (
상세 분석 데이터를 불러오는 중...
); } if (detailQuery.error || !detailQuery.data || !selectedGame) { return (
상세 분석 데이터를 불러오지 못했습니다.
); } return (
); } return ( <>
{renderTabContent()} ); } /** 접힌 행에서 양 팀 10명을 챔피언과 이름으로 훑어보게 한다. */ function MatchRoster({ teams, manifest, ownerParticipantId, }: { teams: ApiRecentMatchTeam[]; manifest: DdragonManifest | null | undefined; ownerParticipantId: string; }) { if (teams.length === 0) return null; return (
{teams.map((team) => (
    {team.participants.map((participant) => (
  • {participant.gameName}
  • ))}
))}
); } function RecentMatchCard({ match, manifest, ownerParticipantId, }: { match: ApiRecentMatchView; manifest: DdragonManifest | null | undefined; ownerParticipantId: string; }) { const multiKill = multiKillLabel(match.largestMultiKill); const championName = championDisplayName(manifest, match.championId) ?? String(match.championId); const outcome = match.remake ? "remake" : match.win ? "win" : "loss"; const surface = { win: "bg-win-tint", loss: "bg-loss-tint", remake: "bg-card", }[outcome]; const bar = { win: "bg-win", loss: "bg-loss", remake: "bg-content-disabled" }[outcome]; const resultClass = { win: "text-win", loss: "text-loss", remake: "text-content-muted", }[outcome]; return (
); } function SkeletonBlock({ className = "" }: { className?: string }) { return
; } function MatchCardSkeleton() { return (
); } function MatchListSkeleton({ count = 5 }: { count?: number }) { return (
{Array.from({ length: count }).map((_, index) => ( ))}
); } function HistoryPageSkeleton() { return (
{Array.from({ length: 5 }).map((_, index) => (
))}
); } export default function UserHistoryPage() { const { userId } = useParams(); const location = useLocation(); const queryClient = useQueryClient(); const [searchParams, setSearchParams] = useSearchParams(); const [backTo] = useState(() => resolveBackTo(location.state)); const [championSearch, setChampionSearch] = useState(""); const [sortKey, setSortKey] = useState("games"); const [refreshResult, setRefreshResult] = useState(null); const [refreshNotice, setRefreshNotice] = useState(null); const view = searchParams.get("view") === "champions" ? "champions" : "matches"; const queueGroupParam = searchParams.get("queueGroup"); const rankParam = searchParams.get("rank"); const queueGroup: RiotQueueGroup = isRiotQueueGroup(queueGroupParam) ? queueGroupParam : "summoners-rift"; const isInternalQueue = queueGroup === "internal"; const rank: RiotRankFilter = !isInternalQueue && isRiotRankFilter(rankParam) ? rankParam : "all"; const championIdParam = Number(searchParams.get("championId")); const championId = Number.isFinite(championIdParam) && championIdParam > 0 ? championIdParam : undefined; const filters: UserHistoryFilters = { queueGroup, rank, championId, seasonId: searchParams.get("seasonId") ?? undefined, }; const aggregateFilters: UserHistoryFilters = { queueGroup, rank, seasonId: filters.seasonId, }; const { data: ddragon } = useDdragonManifest(); const profileQuery = useUserHistoryProfile(userId, DEFAULT_COMMUNITY_ID); const standardHistoryEnabled = !isInternalQueue; const championStatsQuery = useChampionStats( userId, aggregateFilters, DEFAULT_COMMUNITY_ID, standardHistoryEnabled, ); const summaryQuery = useRecentSummary( userId, filters, DEFAULT_COMMUNITY_ID, standardHistoryEnabled, ); const recentMatchesQuery = useRecentMatches( userId, filters, DEFAULT_COMMUNITY_ID, standardHistoryEnabled, ); const internalHistoryQuery = useUserInternalHistory( userId, filters, DEFAULT_COMMUNITY_ID, isInternalQueue, ); const refreshMutation = useRefreshUserHistory(userId, DEFAULT_COMMUNITY_ID); const profile = profileQuery.data; const primaryTier = profile?.tiers.find((tier) => tier.queueType === "RANKED_SOLO_5x5") ?? profile?.tiers[0]; const internalPages = internalHistoryQuery.data?.pages ?? []; const internalFirstPage = internalPages[0]; const summary = isInternalQueue ? internalFirstPage?.summary : summaryQuery.data; const matches = isInternalQueue ? internalPages.flatMap((page) => page.matches) : (recentMatchesQuery.data?.pages.flatMap((page) => page.matches) ?? []); const historyLastFetchedAt = isInternalQueue ? internalFirstPage?.lastFetchedAt : recentMatchesQuery.data?.pages[0]?.lastFetchedAt; const matchesLoading = isInternalQueue ? internalHistoryQuery.isLoading : recentMatchesQuery.isLoading; const hasNextPage = isInternalQueue ? internalHistoryQuery.hasNextPage : recentMatchesQuery.hasNextPage; const isFetchingNextPage = isInternalQueue ? internalHistoryQuery.isFetchingNextPage : recentMatchesQuery.isFetchingNextPage; const selectedChampionName = championId ? (championDisplayName(ddragon, championId) ?? String(championId)) : null; const positionRates = rankPositionRates(summary?.positionRates ?? {}); const visibleChampionRows = (() => { const rows = isInternalQueue ? (internalFirstPage?.championStats.champions ?? []) : (championStatsQuery.data?.champions ?? []); const keyword = championSearch.trim().toLowerCase(); return rows .filter((row) => { if (!keyword) return true; const displayName = championDisplayName(ddragon, row.championId) ?? String(row.championId); return displayName.toLowerCase().includes(keyword); }) .sort((left, right) => right[sortKey] - left[sortKey]); })(); const refreshSocket = useRiotRefreshSocket({ puuid: isInternalQueue ? undefined : profile?.puuid, parentJobId: refreshResult?.parentJobId, onEvent: (event: ApiRiotRefreshEvent) => { if (!profile || event.puuid !== profile.puuid) return; void invalidateHistoryQueries(); if (event.state === "completed") { setRefreshNotice("갱신이 완료되어 전적을 다시 불러왔습니다."); } if (event.state === "failed") { setRefreshNotice( event.error ? `갱신 실패: ${event.error}` : "갱신에 실패했습니다. 잠시 후 다시 시도해 주세요.", ); } }, }); function updateSearch(next: Partial>) { const params = new URLSearchParams(searchParams); for (const [key, value] of Object.entries(next)) { if (value === null || value === undefined || value === "") { params.delete(key); } else { params.set(key, String(value)); } } setSearchParams(params, { state: { backTo } }); } async function invalidateHistoryQueries() { await Promise.all([ queryClient.invalidateQueries({ queryKey: [ "user-history-profile", DEFAULT_COMMUNITY_ID, userId ?? null, ], }), queryClient.invalidateQueries({ queryKey: ["user-champion-stats", DEFAULT_COMMUNITY_ID, userId ?? null], }), queryClient.invalidateQueries({ queryKey: ["user-recent-summary", DEFAULT_COMMUNITY_ID, userId ?? null], }), queryClient.invalidateQueries({ queryKey: ["user-recent-matches", DEFAULT_COMMUNITY_ID, userId ?? null], }), queryClient.invalidateQueries({ queryKey: [ "user-internal-history", DEFAULT_COMMUNITY_ID, userId ?? null, ], }), ]); } function handleRefresh() { if (!userId) return; if (isInternalQueue) { setRefreshResult(null); setRefreshNotice("과거의 토너먼트 결과 수집 데이터를 다시 조회합니다."); void queryClient.invalidateQueries({ queryKey: [ "user-internal-history", DEFAULT_COMMUNITY_ID, userId ?? null, ], }); return; } refreshMutation.mutate( { queueGroups: [queueGroup], priority: "high" }, { onSuccess: (result) => { setRefreshResult(result); const alreadyQueued = result.subJobs.every( (job) => job.alreadyQueued, ); setRefreshNotice( alreadyQueued ? `이미 갱신 작업이 대기 중입니다. 예상 ${formatEta(result.totalEtaSeconds)} 후 반영됩니다.` : `갱신을 요청했습니다. 예상 ${formatEta(result.totalEtaSeconds)} 후 반영됩니다.`, ); }, onError: (error) => { setRefreshNotice(formatRefreshError(error)); }, }, ); } if (!DEFAULT_COMMUNITY_ID) { return (
`VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다.
); } if (profileQuery.isLoading) { return ; } if (profileQuery.error || !profile) { return ( 내전 목록으로 } /> ); } const refreshNoticeIsError = Boolean(refreshSocket.error) || Boolean(refreshNotice?.startsWith("갱신 실패")); return ( <> {profile.summonerLevel}
} title={ <> {profile.gameName} #{profile.tagLine} } meta={ <> {profile.season.label} 최근 갱신 {formatLastFetched(profile.lastFetchedAt)} } actions={ } /> {(refreshNotice || refreshSocket.error) && (refreshNoticeIsError ? ( ) : (
))}
{QUEUE_GROUP_TABS.map((tab) => ( updateSearch({ queueGroup: tab.value, championId: null }) } > {tab.label} ))}
{!isInternalQueue ? (
{RANK_FILTER_TABS.map((tab) => ( updateSearch({ rank: tab.value, championId: null }) } > {tab.label} ))}
) : (

토너먼트 코드로 수집한 내전 결과만 집계합니다.

)}
{selectedChampionName && ( updateSearch({ championId: null })} aria-label={`${selectedChampionName} 필터 해제`} > {selectedChampionName} )} {profile.seasons.length > 0 && ( )}
선호 포지션
{positionRates.length > 0 ? (
    {positionRates.map(({ lane, rate }) => (
  • {LANE_LABELS[lane] ?? lane} {rate}%
  • ))}
) : (
기록 없음
)}
자주 플레이한 챔피언
{(summary?.topChampions ?? []).map((champion) => { const wins = Math.round( (champion.games * champion.winRate) / 100, ); return ( ); })} {(summary?.topChampions ?? []).length === 0 && ( 기록 없음 )}
{profile.tierHistory.length > 0 && !isInternalQueue && (

티어 그래프

}>
)}
updateSearch({ view: null })} > 매치 히스토리 updateSearch({ view: "champions" })} > 챔피언 통계 최근 저장 {formatLastFetched(historyLastFetchedAt)}
{view === "champions" && (

챔피언 통계

저장된 데이터를 기준으로 집계합니다. 최신 데이터가 반영되지 않을 수 있습니다.

setChampionSearch(event.target.value)} placeholder="챔피언 검색" className="lts-input" />
updateSearch({ championId: nextChampionId }) } sortKey={sortKey} onSort={setSortKey} />
)} {view === "matches" && (

매치 히스토리

{matchesLoading ? ( ) : matches.length === 0 ? ( ) : (
{matches.map((match) => ( ))}
)} {hasNextPage && ( isInternalQueue ? internalHistoryQuery.fetchNextPage() : recentMatchesQuery.fetchNextPage() } > 더 보기 )}
)}
); }