1111 lines
38 KiB
TypeScript
1111 lines
38 KiB
TypeScript
import { useMemo, useState } from "react";
|
|
import { useQueryClient } from "@tanstack/react-query";
|
|
import { Link, useParams, useSearchParams } from "react-router";
|
|
import {
|
|
useChampionStats,
|
|
useDdragonManifest,
|
|
useRecentMatches,
|
|
useRecentSummary,
|
|
useRefreshUserHistory,
|
|
useUserInternalHistory,
|
|
useUserHistoryProfile,
|
|
type UserHistoryFilters,
|
|
} from "../api/hooks";
|
|
import { useRiotRefreshSocket } from "../api/useRiotRefreshSocket";
|
|
import type {
|
|
ApiChampionStatsRow,
|
|
ApiEnqueueRefreshResult,
|
|
ApiTierInfo,
|
|
ApiRiotRefreshEvent,
|
|
ApiRecentMatchView,
|
|
DdragonManifest,
|
|
RiotQueueGroup,
|
|
RiotRankFilter,
|
|
} from "../api/types";
|
|
import { DEFAULT_COMMUNITY_ID } from "../config";
|
|
import { ApiError } from "../lib/api";
|
|
import {
|
|
championDisplayName,
|
|
championIconUrl,
|
|
itemIconUrl,
|
|
profileIconUrl,
|
|
} from "../lib/ddragon";
|
|
import {
|
|
isRiotQueueGroup,
|
|
isRiotRankFilter,
|
|
LANE_LABELS,
|
|
QUEUE_GROUP_TABS,
|
|
RANK_FILTER_TABS,
|
|
} from "../lib/riot-history";
|
|
|
|
type ChampionSortKey = "games" | "winRate" | "kda" | "avgCsPerMin";
|
|
|
|
const SORT_LABELS: Record<ChampionSortKey, string> = {
|
|
games: "게임 수",
|
|
winRate: "승률",
|
|
kda: "KDA",
|
|
avgCsPerMin: "분당 CS",
|
|
};
|
|
|
|
const TIER_NAMES: Record<string, string> = {
|
|
IRON: "아이언",
|
|
BRONZE: "브론즈",
|
|
SILVER: "실버",
|
|
GOLD: "골드",
|
|
PLATINUM: "플래티넘",
|
|
EMERALD: "에메랄드",
|
|
DIAMOND: "다이아몬드",
|
|
MASTER: "마스터",
|
|
GRANDMASTER: "그랜드마스터",
|
|
CHALLENGER: "챌린저",
|
|
};
|
|
|
|
function normalizeRank(rank: string | undefined) {
|
|
switch (rank) {
|
|
case "I":
|
|
return "1";
|
|
case "II":
|
|
return "2";
|
|
case "III":
|
|
return "3";
|
|
case "IV":
|
|
return "4";
|
|
default:
|
|
return rank;
|
|
}
|
|
}
|
|
|
|
function formatRankBadge(tier: ApiTierInfo | undefined) {
|
|
if (!tier) return "U";
|
|
const tierInitial =
|
|
tier.tier === "GRANDMASTER" ? "GM" : tier.tier.slice(0, 1);
|
|
const rank = normalizeRank(tier.rank);
|
|
return rank ? `${tierInitial}${rank}` : tierInitial;
|
|
}
|
|
|
|
function formatRankDetail(tier: ApiTierInfo | undefined) {
|
|
if (!tier) return "랭크 정보 없음";
|
|
const tierName = TIER_NAMES[tier.tier] ?? tier.tier;
|
|
const rank = normalizeRank(tier.rank);
|
|
const label = rank ? `${tierName} ${rank}` : tierName;
|
|
return `${label} - ${tier.leaguePoints} LP`;
|
|
}
|
|
|
|
function rankBadgeClass(tier: ApiTierInfo | undefined) {
|
|
switch (tier?.tier) {
|
|
case "CHALLENGER":
|
|
return "border-amber-500/60 bg-amber-100 text-amber-900 dark:border-amber-400/40 dark:bg-amber-400/20 dark:text-amber-200";
|
|
case "GRANDMASTER":
|
|
return "border-red-500/60 bg-red-100 text-red-800 dark:border-red-400/40 dark:bg-red-400/20 dark:text-red-200";
|
|
case "MASTER":
|
|
return "border-fuchsia-500/60 bg-fuchsia-100 text-fuchsia-800 dark:border-fuchsia-400/40 dark:bg-fuchsia-400/20 dark:text-fuchsia-200";
|
|
case "DIAMOND":
|
|
return "border-cyan-500/60 bg-cyan-100 text-cyan-800 dark:border-cyan-400/40 dark:bg-cyan-400/20 dark:text-cyan-200";
|
|
case "EMERALD":
|
|
return "border-emerald-500/60 bg-emerald-100 text-emerald-800 dark:border-emerald-400/40 dark:bg-emerald-400/20 dark:text-emerald-200";
|
|
case "PLATINUM":
|
|
return "border-teal-500/60 bg-teal-100 text-teal-800 dark:border-teal-400/40 dark:bg-teal-400/20 dark:text-teal-200";
|
|
case "GOLD":
|
|
return "border-amber-500/70 bg-amber-100 text-amber-900 dark:border-yellow-400/40 dark:bg-yellow-400/20 dark:text-yellow-200";
|
|
case "SILVER":
|
|
return "border-slate-400/60 bg-slate-100 text-slate-700 dark:border-slate-300/40 dark:bg-slate-300/15 dark:text-slate-200";
|
|
case "BRONZE":
|
|
return "border-orange-600/60 bg-orange-100 text-orange-800 dark:border-orange-500/40 dark:bg-orange-500/20 dark:text-orange-200";
|
|
case "IRON":
|
|
return "border-stone-500/60 bg-stone-100 text-stone-700 dark:border-stone-400/40 dark:bg-stone-400/15 dark:text-stone-300";
|
|
default:
|
|
return "border-base-content/30 bg-transparent text-base-content/50";
|
|
}
|
|
}
|
|
|
|
function RankBadge({ tier }: { tier?: ApiTierInfo }) {
|
|
const tooltip = formatRankDetail(tier);
|
|
|
|
return (
|
|
<span className="tooltip tooltip-bottom" data-tip={tooltip}>
|
|
<span
|
|
className={`inline-flex h-[18px] min-w-[20px] shrink-0 items-center justify-center whitespace-nowrap rounded-[3px] border px-1 text-[10px] font-black leading-none ${rankBadgeClass(tier)}`}
|
|
aria-label={tooltip}
|
|
>
|
|
{formatRankBadge(tier)}
|
|
</span>
|
|
</span>
|
|
);
|
|
}
|
|
|
|
function ResponsiveTierLabel({ tier }: { tier?: ApiTierInfo }) {
|
|
return (
|
|
<span className="inline-flex items-center gap-1.5 whitespace-nowrap">
|
|
<RankBadge tier={tier} />
|
|
<span className="hidden font-bold text-base-content/55 sm:inline">
|
|
{formatRankDetail(tier)}
|
|
</span>
|
|
</span>
|
|
);
|
|
}
|
|
|
|
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 >= 55) return "text-blue-400";
|
|
if (value >= 50) return "text-amber-400";
|
|
return "text-base-content/50";
|
|
}
|
|
|
|
function kdaClass(value: number) {
|
|
if (value >= 4) return "text-amber-400";
|
|
if (value >= 3) return "text-emerald-400";
|
|
return "text-base-content/60";
|
|
}
|
|
|
|
function FilterButton({
|
|
active,
|
|
children,
|
|
onClick,
|
|
}: {
|
|
active: boolean;
|
|
children: React.ReactNode;
|
|
onClick: () => void;
|
|
}) {
|
|
return (
|
|
<button
|
|
type="button"
|
|
onClick={onClick}
|
|
className={`px-3 py-2 text-[12px] font-semibold border-b-2 transition-colors ${
|
|
active
|
|
? "border-primary text-primary bg-primary/5"
|
|
: "border-transparent text-base-content/45 hover:text-base-content"
|
|
}`}
|
|
>
|
|
{children}
|
|
</button>
|
|
);
|
|
}
|
|
|
|
function ChampionIcon({
|
|
championId,
|
|
manifest,
|
|
size = "md",
|
|
}: {
|
|
championId: number;
|
|
manifest: DdragonManifest | null | undefined;
|
|
size?: "sm" | "md" | "lg";
|
|
}) {
|
|
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" : "w-8 h-8";
|
|
|
|
return (
|
|
<div className={`${sizeClass} bg-base-content/10 overflow-hidden shrink-0`}>
|
|
{iconUrl ? (
|
|
<img
|
|
src={iconUrl}
|
|
alt={displayName}
|
|
className="w-full h-full object-cover"
|
|
loading="lazy"
|
|
/>
|
|
) : null}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function SummaryCard({
|
|
label,
|
|
value,
|
|
sub,
|
|
}: {
|
|
label: string;
|
|
value: React.ReactNode;
|
|
sub?: React.ReactNode;
|
|
}) {
|
|
return (
|
|
<div className="border border-base-content/8 bg-base-100 p-4">
|
|
<div className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
|
|
{label}
|
|
</div>
|
|
<div className="mt-2 text-2xl font-black text-base-content tabular-nums">
|
|
{value}
|
|
</div>
|
|
{sub && (
|
|
<div className="mt-1 text-[11px] text-base-content/40">{sub}</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function ChampionStatsTable({
|
|
rows,
|
|
manifest,
|
|
selectedChampionId,
|
|
onChampionSelect,
|
|
}: {
|
|
rows: ApiChampionStatsRow[];
|
|
manifest: DdragonManifest | null | undefined;
|
|
selectedChampionId?: number;
|
|
onChampionSelect: (championId: number | null) => void;
|
|
}) {
|
|
if (rows.length === 0) {
|
|
return (
|
|
<div className="border border-base-content/10 bg-base-100 px-4 py-10 text-center text-sm text-base-content/35">
|
|
조건에 맞는 챔피언 통계가 아직 없습니다.
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className="border border-base-content/10 bg-base-100 overflow-hidden">
|
|
<div className="overflow-x-auto">
|
|
<table className="w-full text-left min-w-[860px]">
|
|
<thead>
|
|
<tr className="bg-base-200/50 border-b border-base-content/10 text-[11px] text-base-content/35 uppercase tracking-wider">
|
|
<th className="px-3 py-2.5">챔피언</th>
|
|
<th className="px-3 py-2.5 text-center">승률</th>
|
|
<th className="px-3 py-2.5 text-center">게임</th>
|
|
<th className="px-3 py-2.5 text-center">승/패</th>
|
|
<th className="px-3 py-2.5 text-center">KDA</th>
|
|
<th className="px-3 py-2.5 text-center">킬</th>
|
|
<th className="px-3 py-2.5 text-center">데스</th>
|
|
<th className="px-3 py-2.5 text-center">어시스트</th>
|
|
<th className="px-3 py-2.5 text-center">멀티킬</th>
|
|
<th className="px-3 py-2.5 text-center">CS</th>
|
|
<th className="px-3 py-2.5 text-center">필터</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{rows.map((row) => {
|
|
const displayName =
|
|
championDisplayName(manifest, row.championId) ??
|
|
String(row.championId);
|
|
const selected = selectedChampionId === row.championId;
|
|
return (
|
|
<tr
|
|
key={row.championId}
|
|
className="border-b border-base-content/5 last:border-b-0 hover:bg-base-content/[0.02]"
|
|
>
|
|
<td className="px-3 py-2.5">
|
|
<div className="flex items-center gap-2">
|
|
<ChampionIcon
|
|
championId={row.championId}
|
|
manifest={manifest}
|
|
/>
|
|
<span className="text-[13px] font-bold text-base-content">
|
|
{displayName}
|
|
</span>
|
|
</div>
|
|
</td>
|
|
<td
|
|
className={`px-3 py-2.5 text-center text-[13px] font-bold ${ratioClass(row.winRate)}`}
|
|
>
|
|
{row.winRate}%
|
|
</td>
|
|
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
|
|
{row.games}
|
|
</td>
|
|
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums text-base-content/55">
|
|
<span className="text-blue-400">{row.wins}</span> /{" "}
|
|
<span className="text-red-400">{row.losses}</span>
|
|
</td>
|
|
<td
|
|
className={`px-3 py-2.5 text-center text-[13px] font-bold tabular-nums ${kdaClass(row.kda)}`}
|
|
>
|
|
{row.kda}
|
|
</td>
|
|
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
|
|
{row.totalKills}
|
|
</td>
|
|
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
|
|
{row.totalDeaths}
|
|
</td>
|
|
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
|
|
{row.totalAssists}
|
|
</td>
|
|
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums text-base-content/55">
|
|
{row.doubleKills}/{row.tripleKills}/{row.quadraKills}/
|
|
{row.pentaKills}
|
|
</td>
|
|
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
|
|
{row.avgCs} · {row.avgCsPerMin}/m
|
|
</td>
|
|
<td className="px-3 py-2.5 text-center">
|
|
<button
|
|
type="button"
|
|
className={`text-[11px] px-2 py-1 border ${
|
|
selected
|
|
? "border-primary/40 bg-primary/10 text-primary"
|
|
: "border-base-content/10 text-base-content/40 hover:text-base-content"
|
|
}`}
|
|
onClick={() =>
|
|
onChampionSelect(selected ? null : row.championId)
|
|
}
|
|
>
|
|
{selected ? "해제" : "보기"}
|
|
</button>
|
|
</td>
|
|
</tr>
|
|
);
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function ItemGrid({
|
|
match,
|
|
manifest,
|
|
}: {
|
|
match: ApiRecentMatchView;
|
|
manifest: DdragonManifest | null | undefined;
|
|
}) {
|
|
const slots = [...match.items, match.trinket];
|
|
return (
|
|
<div className="grid grid-cols-4 gap-1 w-[92px]">
|
|
{slots.map((itemId, index) => {
|
|
const url = itemIconUrl(manifest, itemId);
|
|
return (
|
|
<div
|
|
key={`${match.matchId}-item-${index}`}
|
|
className="w-5 h-5 bg-base-content/8 overflow-hidden border border-base-content/5"
|
|
>
|
|
{url ? (
|
|
<img
|
|
src={url}
|
|
alt=""
|
|
className="w-full h-full object-cover"
|
|
loading="lazy"
|
|
/>
|
|
) : null}
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function TeamMini({
|
|
match,
|
|
manifest,
|
|
}: {
|
|
match: ApiRecentMatchView;
|
|
manifest: DdragonManifest | null | undefined;
|
|
}) {
|
|
return (
|
|
<div className="grid sm:grid-cols-2 gap-2 text-[11px]">
|
|
{match.teams.map((team) => (
|
|
<div
|
|
key={`${match.matchId}-${team.side}`}
|
|
className={`space-y-0.5 ${team.win ? "text-base-content/70" : "text-base-content/35"}`}
|
|
>
|
|
{team.participants.map((participant) => {
|
|
const championName =
|
|
championDisplayName(manifest, participant.championId) ??
|
|
String(participant.championId);
|
|
return (
|
|
<div
|
|
key={`${participant.puuid}-${participant.championId}`}
|
|
className="flex items-center gap-1 min-w-0"
|
|
>
|
|
<ChampionIcon
|
|
championId={participant.championId}
|
|
manifest={manifest}
|
|
size="sm"
|
|
/>
|
|
<span className="truncate">
|
|
{participant.gameName || championName}
|
|
</span>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function RecentMatchCard({
|
|
match,
|
|
manifest,
|
|
}: {
|
|
match: ApiRecentMatchView;
|
|
manifest: DdragonManifest | null | undefined;
|
|
}) {
|
|
const championName =
|
|
championDisplayName(manifest, match.championId) ?? String(match.championId);
|
|
const accent = match.win ? "border-l-blue-500" : "border-l-red-500";
|
|
const resultClass = match.win ? "text-blue-400" : "text-red-400";
|
|
|
|
return (
|
|
<article
|
|
className={`border border-l-4 ${accent} border-base-content/10 bg-base-100`}
|
|
>
|
|
<div className="p-4 grid lg:grid-cols-[120px_1fr_120px_1.5fr_32px] gap-4 items-center">
|
|
<div className="text-center lg:text-left">
|
|
<div className={`text-[12px] font-black ${resultClass}`}>
|
|
{match.remake ? "다시하기" : match.win ? "승리" : "패배"}
|
|
</div>
|
|
<div className="text-[11px] text-base-content/35 mt-1">
|
|
{match.queueLabel}
|
|
</div>
|
|
<div className="text-[11px] text-base-content/25">
|
|
{formatDate(match.gameCreation)}
|
|
</div>
|
|
<div className="text-[11px] text-base-content/25">
|
|
{formatDuration(match.gameDuration)}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-3 min-w-0">
|
|
<ChampionIcon
|
|
championId={match.championId}
|
|
manifest={manifest}
|
|
size="lg"
|
|
/>
|
|
<div className="min-w-0">
|
|
<div className="font-bold text-base-content truncate">
|
|
{championName}
|
|
</div>
|
|
<div className="text-[11px] text-base-content/35">
|
|
Lv.{match.championLevel} ·{" "}
|
|
{(LANE_LABELS[match.teamPosition] ?? match.teamPosition) ||
|
|
"포지션 없음"}
|
|
</div>
|
|
<div className="mt-1 text-[10px] text-base-content/30">
|
|
스펠 {match.summonerSpells.join(" / ")}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="text-center">
|
|
<div className="text-lg font-black tabular-nums">
|
|
<span>{match.kills}</span>
|
|
<span className="text-base-content/25"> / </span>
|
|
<span className="text-red-400">{match.deaths}</span>
|
|
<span className="text-base-content/25"> / </span>
|
|
<span>{match.assists}</span>
|
|
</div>
|
|
<div
|
|
className={`text-[12px] font-bold tabular-nums ${kdaClass(match.kda)}`}
|
|
>
|
|
{match.deaths === 0 ? "Perfect" : `${match.kda} 평점`}
|
|
</div>
|
|
<div className="mt-1 text-[11px] text-base-content/35">
|
|
킬 관여 {match.killParticipation}%
|
|
</div>
|
|
</div>
|
|
|
|
<div className="grid sm:grid-cols-[100px_1fr] gap-4 items-center">
|
|
<div className="space-y-1 text-[11px] text-base-content/45">
|
|
<div>
|
|
CS{" "}
|
|
<span className="font-bold text-base-content/70">
|
|
{match.totalCs}
|
|
</span>{" "}
|
|
({match.csPerMin}/m)
|
|
</div>
|
|
<div>
|
|
시야{" "}
|
|
<span className="font-bold text-base-content/70">
|
|
{match.visionScore}
|
|
</span>{" "}
|
|
제어와드 {match.controlWardsBought}
|
|
</div>
|
|
<div>
|
|
피해량{" "}
|
|
<span className="font-bold text-base-content/70">
|
|
{match.damageDealtToChampions.toLocaleString()}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
<div className="flex items-start gap-3">
|
|
<ItemGrid match={match} manifest={manifest} />
|
|
<TeamMini match={match} manifest={manifest} />
|
|
</div>
|
|
</div>
|
|
|
|
<div className="hidden lg:flex justify-end">
|
|
<div
|
|
className={`w-2 h-14 ${match.win ? "bg-blue-500/70" : "bg-red-500/70"}`}
|
|
/>
|
|
</div>
|
|
</div>
|
|
</article>
|
|
);
|
|
}
|
|
|
|
export default function UserHistoryPage() {
|
|
const { userId } = useParams();
|
|
const queryClient = useQueryClient();
|
|
const [searchParams, setSearchParams] = useSearchParams();
|
|
const [championSearch, setChampionSearch] = useState("");
|
|
const [sortKey, setSortKey] = useState<ChampionSortKey>("games");
|
|
const [refreshResult, setRefreshResult] =
|
|
useState<ApiEnqueueRefreshResult | null>(null);
|
|
const [refreshNotice, setRefreshNotice] = useState<string | null>(null);
|
|
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 visibleChampionRows = useMemo(() => {
|
|
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]);
|
|
}, [
|
|
championSearch,
|
|
championStatsQuery.data?.champions,
|
|
ddragon,
|
|
internalFirstPage?.championStats.champions,
|
|
isInternalQueue,
|
|
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<Record<string, string | number | null>>) {
|
|
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);
|
|
}
|
|
|
|
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 (
|
|
<main className="max-w-6xl mx-auto px-4 py-20 text-center">
|
|
<span className="text-sm text-amber-600">
|
|
`VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다.
|
|
</span>
|
|
</main>
|
|
);
|
|
}
|
|
|
|
if (profileQuery.isLoading) {
|
|
return (
|
|
<main className="max-w-6xl mx-auto px-4 py-20 text-center">
|
|
<span className="text-sm text-base-content/40">
|
|
소환사 전적을 불러오는 중...
|
|
</span>
|
|
</main>
|
|
);
|
|
}
|
|
|
|
if (profileQuery.error || !profile) {
|
|
return (
|
|
<main className="max-w-6xl mx-auto px-4 py-20 text-center">
|
|
<h2 className="text-lg font-bold mb-2">소환사를 찾을 수 없습니다</h2>
|
|
<Link to="/" className="btn btn-ghost btn-sm mt-4">
|
|
홈으로 돌아가기
|
|
</Link>
|
|
</main>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<main className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
|
|
<Link
|
|
to="/"
|
|
className="inline-flex items-center gap-1 text-xs text-base-content/40 hover:text-base-content transition-colors mb-5"
|
|
>
|
|
← 목록으로
|
|
</Link>
|
|
|
|
<section className="border border-base-content/10 bg-base-100 p-5 mb-5">
|
|
<div className="flex flex-col sm:flex-row sm:items-center gap-4">
|
|
<div className="w-16 h-16 bg-base-content/10 overflow-hidden shrink-0">
|
|
<img
|
|
src={profileIconUrl(ddragon, profile.profileIconId)}
|
|
alt=""
|
|
className="w-full h-full object-cover"
|
|
/>
|
|
</div>
|
|
<div className="flex-1 min-w-0">
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<h1 className="text-2xl font-black text-base-content">
|
|
{profile.gameName}
|
|
</h1>
|
|
<span className="text-sm text-base-content/35">
|
|
#{profile.tagLine}
|
|
</span>
|
|
</div>
|
|
<div className="mt-2 flex flex-wrap items-center gap-3 text-xs text-base-content/40">
|
|
<span>Lv.{profile.summonerLevel}</span>
|
|
<ResponsiveTierLabel tier={primaryTier} />
|
|
<span>시즌: {profile.season.label}</span>
|
|
<span>최근 저장: {formatLastFetched(profile.lastFetchedAt)}</span>
|
|
</div>
|
|
</div>
|
|
<div className="border border-dashed border-base-content/10 px-3 py-2 text-[11px] text-base-content/35 sm:text-right space-y-2">
|
|
<div>
|
|
{isInternalQueue ? (
|
|
<>
|
|
{/* 내전 탭은 토너먼트 결과 DB를 조회합니다. */}
|
|
{/* Riot API 갱신 없이 수집된 내전 결과를 다시 불러옵니다. */}
|
|
내전 기록이 확인되지 않을 경우 버튼을 눌러 갱신 (테스트)
|
|
</>
|
|
) : (
|
|
<>
|
|
{/* 이 페이지는 저장된 경기 DB만 조회합니다. */}
|
|
<br />
|
|
{/* Riot API 갱신은 버튼 클릭 시 큐에서 처리합니다. */}
|
|
아래 버튼을 누르면 기록이 갱신됩니다.
|
|
</>
|
|
)}
|
|
</div>
|
|
<button
|
|
type="button"
|
|
className="btn btn-primary btn-xs px-3"
|
|
disabled={refreshMutation.isPending || !userId}
|
|
onClick={handleRefresh}
|
|
>
|
|
{isInternalQueue
|
|
? "내전 기록 다시 불러오기"
|
|
: refreshMutation.isPending
|
|
? "요청 중..."
|
|
: "정보 갱신"}
|
|
</button>
|
|
{!isInternalQueue && (
|
|
<div className="text-[10px] text-base-content/25">
|
|
갱신 소켓: {refreshSocket.connectionStatus}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
{(refreshNotice || refreshSocket.error) && (
|
|
<div className="mt-4 border border-primary/15 bg-primary/5 px-3 py-2 text-xs text-base-content/55">
|
|
{refreshNotice ?? refreshSocket.error}
|
|
</div>
|
|
)}
|
|
</section>
|
|
|
|
<section className="border border-base-content/10 bg-base-100 mb-5">
|
|
<div className="flex flex-wrap border-b border-base-content/8">
|
|
{QUEUE_GROUP_TABS.map((tab) => (
|
|
<FilterButton
|
|
key={tab.value}
|
|
active={queueGroup === tab.value}
|
|
onClick={() =>
|
|
updateSearch({ queueGroup: tab.value, championId: null })
|
|
}
|
|
>
|
|
{tab.label}
|
|
</FilterButton>
|
|
))}
|
|
</div>
|
|
<div className="flex flex-wrap items-center justify-between gap-3 px-3 py-2">
|
|
{!isInternalQueue ? (
|
|
<div className="flex flex-wrap">
|
|
{RANK_FILTER_TABS.map((tab) => (
|
|
<FilterButton
|
|
key={tab.value}
|
|
active={rank === tab.value}
|
|
onClick={() =>
|
|
updateSearch({ rank: tab.value, championId: null })
|
|
}
|
|
>
|
|
{tab.label}
|
|
</FilterButton>
|
|
))}
|
|
</div>
|
|
) : (
|
|
<div className="px-3 py-2 text-[11px] text-base-content/40">
|
|
내전 탭은 토너먼트 코드 결과 수집 데이터를 기준으로 집계합니다.
|
|
</div>
|
|
)}
|
|
{selectedChampionName && (
|
|
<button
|
|
type="button"
|
|
className="text-[11px] px-2.5 py-1 border border-primary/30 text-primary bg-primary/5"
|
|
onClick={() => updateSearch({ championId: null })}
|
|
>
|
|
{selectedChampionName} 필터 해제
|
|
</button>
|
|
)}
|
|
{profile.seasons.length > 0 && (
|
|
<select
|
|
value={filters.seasonId ?? profile.season.id}
|
|
onChange={(event) =>
|
|
updateSearch({ seasonId: event.target.value, championId: null })
|
|
}
|
|
className="border border-base-content/10 bg-transparent px-3 py-2 text-xs"
|
|
>
|
|
{profile.seasons.map((season) => (
|
|
<option key={season.id} value={season.id}>
|
|
{season.label}
|
|
</option>
|
|
))}
|
|
</select>
|
|
)}
|
|
</div>
|
|
</section>
|
|
|
|
<section className="mb-6">
|
|
<h2 className="text-sm font-bold text-base-content mb-3">
|
|
최근 {summary?.windowSize ?? 20}게임 전적 요약
|
|
</h2>
|
|
<div className="grid sm:grid-cols-2 lg:grid-cols-5 gap-3">
|
|
<SummaryCard
|
|
label="승률"
|
|
value={`${summary?.winRate ?? 0}%`}
|
|
sub={`${summary?.wins ?? 0}승 ${summary?.losses ?? 0}패`}
|
|
/>
|
|
<SummaryCard
|
|
label="KDA"
|
|
value={summary?.kda ?? 0}
|
|
sub={`${summary?.avgKills ?? 0} / ${summary?.avgDeaths ?? 0} / ${summary?.avgAssists ?? 0}`}
|
|
/>
|
|
<SummaryCard
|
|
label="최고 평점"
|
|
value={summary?.bestRating?.rating ?? "-"}
|
|
sub={
|
|
summary?.bestRating
|
|
? `${summary.bestRating.kills}/${summary.bestRating.deaths}/${summary.bestRating.assists}`
|
|
: "기록 없음"
|
|
}
|
|
/>
|
|
<SummaryCard
|
|
label="연승/연패"
|
|
value={
|
|
summary?.streak
|
|
? `${summary.streak.count}${summary.streak.type === "win" ? "연승" : "연패"}`
|
|
: "-"
|
|
}
|
|
sub="가장 최근 경기 기준"
|
|
/>
|
|
<div className="border border-base-content/8 bg-base-100 p-4">
|
|
<div className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
|
|
자주 플레이한 챔피언
|
|
</div>
|
|
<div className="mt-3 flex items-center gap-3">
|
|
{(summary?.topChampions ?? []).map((champion) => (
|
|
<button
|
|
type="button"
|
|
key={champion.championId}
|
|
className="text-center group"
|
|
onClick={() =>
|
|
updateSearch({ championId: champion.championId })
|
|
}
|
|
>
|
|
<ChampionIcon
|
|
championId={champion.championId}
|
|
manifest={ddragon}
|
|
/>
|
|
<div className="mt-1 text-[10px] text-base-content/40 group-hover:text-primary">
|
|
{champion.winRate}%
|
|
</div>
|
|
</button>
|
|
))}
|
|
{(summary?.topChampions ?? []).length === 0 && (
|
|
<span className="text-[11px] text-base-content/25">
|
|
기록 없음
|
|
</span>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</section>
|
|
|
|
<section className="mb-6">
|
|
<div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3 mb-3">
|
|
<div>
|
|
<h2 className="text-sm font-bold text-base-content">챔피언 통계</h2>
|
|
<p className="mt-1 text-[11px] text-base-content/35">
|
|
저장된 데이터를 기준으로 집계합니다. 최신 데이터가 반영되지 않을
|
|
수 있습니다.
|
|
</p>
|
|
</div>
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<input
|
|
value={championSearch}
|
|
onChange={(event) => setChampionSearch(event.target.value)}
|
|
placeholder="챔피언 검색"
|
|
className="border border-base-content/10 bg-transparent px-3 py-2 text-xs focus:outline-none focus:border-primary/30"
|
|
/>
|
|
<select
|
|
value={sortKey}
|
|
onChange={(event) =>
|
|
setSortKey(event.target.value as ChampionSortKey)
|
|
}
|
|
className="border border-base-content/10 bg-transparent px-3 py-2 text-xs"
|
|
>
|
|
{(Object.keys(SORT_LABELS) as ChampionSortKey[]).map((key) => (
|
|
<option key={key} value={key}>
|
|
{SORT_LABELS[key]}순
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
</div>
|
|
<ChampionStatsTable
|
|
rows={visibleChampionRows}
|
|
manifest={ddragon}
|
|
selectedChampionId={championId}
|
|
onChampionSelect={(nextChampionId) =>
|
|
updateSearch({ championId: nextChampionId })
|
|
}
|
|
/>
|
|
</section>
|
|
|
|
<section>
|
|
<div className="flex items-center justify-between gap-3 mb-3">
|
|
<h2 className="text-sm font-bold text-base-content">매치 히스토리</h2>
|
|
<span className="text-[11px] text-base-content/35">
|
|
최근 저장: {formatLastFetched(historyLastFetchedAt)}
|
|
</span>
|
|
</div>
|
|
|
|
{matchesLoading ? (
|
|
<div className="border border-base-content/10 bg-base-100 px-4 py-10 text-center text-sm text-base-content/35">
|
|
최근 경기를 불러오는 중...
|
|
</div>
|
|
) : matches.length === 0 ? (
|
|
<div className="border border-base-content/10 bg-base-100 px-4 py-10 text-center text-sm text-base-content/35">
|
|
조건에 맞는 최근 경기 기록이 없습니다.
|
|
</div>
|
|
) : (
|
|
<div className="space-y-2">
|
|
{matches.map((match) => (
|
|
<RecentMatchCard
|
|
key={match.matchId}
|
|
match={match}
|
|
manifest={ddragon}
|
|
/>
|
|
))}
|
|
</div>
|
|
)}
|
|
|
|
{hasNextPage && (
|
|
<button
|
|
type="button"
|
|
className="mt-3 w-full border border-base-content/15 bg-base-100 py-3 text-sm font-bold text-base-content/60 hover:border-primary/30 hover:text-primary disabled:opacity-40"
|
|
disabled={isFetchingNextPage}
|
|
onClick={() =>
|
|
isInternalQueue
|
|
? internalHistoryQuery.fetchNextPage()
|
|
: recentMatchesQuery.fetchNextPage()
|
|
}
|
|
>
|
|
{isFetchingNextPage ? "불러오는 중..." : "+ 더 보기"}
|
|
</button>
|
|
)}
|
|
</section>
|
|
</main>
|
|
);
|
|
}
|