660 lines
22 KiB
TypeScript
660 lines
22 KiB
TypeScript
import { useDeferredValue, useEffect } from "react";
|
|
import {
|
|
ArrowDown,
|
|
ArrowDownUp,
|
|
CalendarDays,
|
|
List,
|
|
Search,
|
|
Users,
|
|
X,
|
|
} from "lucide-react";
|
|
import { useLocation, useParams, useSearchParams } from "react-router";
|
|
import {
|
|
useCommunity,
|
|
useCommunityInternalStatsMatches,
|
|
useCommunityLeaderboard,
|
|
useCommunityStatsSeasons,
|
|
useDdragonManifest,
|
|
useTeamInsights,
|
|
} from "../api/hooks";
|
|
import { DEFAULT_COMMUNITY_ID } from "../config";
|
|
import { Btn, Chip } from "../ui";
|
|
import { filterLeaderboardRows } from "../lib/internal-stats-presentation";
|
|
import {
|
|
internalMatchDetailPath,
|
|
internalMatchGamePath,
|
|
} from "../lib/internal-match-routes";
|
|
import { LANE_LABELS } from "../lib/riot-history";
|
|
import {
|
|
StatsEvent,
|
|
StatsEventJump,
|
|
} from "../components/internal-stats/StatsEvent";
|
|
import { StatsLeaderboard } from "../components/internal-stats/StatsLeaderboard";
|
|
import { StatsSummary } from "../components/internal-stats/StatsSummary";
|
|
import {
|
|
StatsFeedback,
|
|
StatsLaneSelect,
|
|
StatsSeasonControls,
|
|
} from "../components/internal-stats/StatsShared";
|
|
import {
|
|
parseStatsLane,
|
|
statsRoot,
|
|
statsTarget,
|
|
statsPeriod,
|
|
useStatsRestoration,
|
|
} from "../components/internal-stats/stats-navigation";
|
|
import {
|
|
STATS_SORTS,
|
|
parseStatsSort,
|
|
sortStatsRows,
|
|
} from "../components/internal-stats/stats-model";
|
|
|
|
type Changes = Record<string, string | null>;
|
|
export default function CommunityInternalStatsView() {
|
|
const { cid } = useParams();
|
|
const communityId = cid ?? DEFAULT_COMMUNITY_ID;
|
|
const location = useLocation();
|
|
const [params, setParams] = useSearchParams();
|
|
const ranking = ["ranking", "players"].includes(params.get("view") ?? "");
|
|
const seasonId = params.get("seasonId") || "current";
|
|
const lane = parseStatsLane(params.get("lane"));
|
|
const sort = parseStatsSort(params.get("sort"));
|
|
const direction = params.get("dir") === "asc" ? "asc" : "desc";
|
|
const minimum = ["0", "5", "10", "20"].includes(params.get("min") ?? "")
|
|
? Number(params.get("min"))
|
|
: 5;
|
|
const queryKey = ranking ? "playerQ" : "matchQ";
|
|
const query = params.get(queryKey) ?? params.get("q") ?? "";
|
|
const keyword = useDeferredValue(query.trim().slice(0, 100));
|
|
const format = params.get("format"),
|
|
playerId = params.get("player");
|
|
const from = params.get("from") ?? "",
|
|
to = params.get("to") ?? "";
|
|
const invalidDates = Boolean(from && to && from > to);
|
|
const champion = Number(params.get("championId"));
|
|
const championId =
|
|
Number.isInteger(champion) && champion > 0 ? champion : undefined;
|
|
const scope = { seasonId, championId };
|
|
const community = useCommunity(communityId);
|
|
const seasons = useCommunityStatsSeasons(communityId);
|
|
const insights = useTeamInsights({ seasonId }, communityId);
|
|
const leaderboard = useCommunityLeaderboard(
|
|
{ ...scope, lane, query: ranking ? keyword : undefined },
|
|
communityId,
|
|
ranking,
|
|
);
|
|
const matchesQuery = useCommunityInternalStatsMatches(
|
|
{
|
|
...scope,
|
|
query: keyword,
|
|
format: format === "pair" || format === "tournament" ? format : undefined,
|
|
playerId: playerId ?? undefined,
|
|
from: from || undefined,
|
|
to: to || undefined,
|
|
limit: 4,
|
|
},
|
|
communityId,
|
|
!ranking && !invalidDates,
|
|
);
|
|
const { data: manifest } = useDdragonManifest();
|
|
const matches =
|
|
matchesQuery.data?.pages.flatMap((page) => page.matches) ?? [];
|
|
const pageCount = matchesQuery.data?.pages.length ?? 0;
|
|
const requestedPages = Math.max(
|
|
1,
|
|
Math.min(30, Number(params.get("pages")) || 1),
|
|
);
|
|
const {
|
|
fetchNextPage,
|
|
hasNextPage,
|
|
isFetchingNextPage,
|
|
isFetchNextPageError,
|
|
} = matchesQuery;
|
|
useEffect(() => {
|
|
if (
|
|
!ranking &&
|
|
pageCount > 0 &&
|
|
pageCount < requestedPages &&
|
|
hasNextPage &&
|
|
!isFetchingNextPage &&
|
|
!isFetchNextPageError
|
|
)
|
|
void fetchNextPage();
|
|
}, [
|
|
ranking,
|
|
pageCount,
|
|
requestedPages,
|
|
hasNextPage,
|
|
isFetchingNextPage,
|
|
isFetchNextPageError,
|
|
fetchNextPage,
|
|
]);
|
|
const season =
|
|
insights.data?.season ??
|
|
leaderboard.data?.season ??
|
|
matchesQuery.data?.pages[0]?.season;
|
|
const sortedRows = sortStatsRows(
|
|
leaderboard.data?.rows ?? [],
|
|
sort,
|
|
minimum,
|
|
direction,
|
|
);
|
|
const visibleRows = filterLeaderboardRows(
|
|
sortedRows,
|
|
keyword,
|
|
leaderboard.data?.matchedUserIds,
|
|
).filter((row) => params.get("qualified") !== "1" || row.games >= minimum);
|
|
const current = location.pathname + location.search,
|
|
root = statsRoot(communityId);
|
|
const playerHref = (id: string) =>
|
|
statsTarget(`${root}/players/${id}`, params, current);
|
|
const eventHref = (id: string) =>
|
|
statsTarget(internalMatchDetailPath(communityId, id), params, current);
|
|
const gameHref = (id: string, number: number) =>
|
|
statsTarget(
|
|
internalMatchGamePath(communityId, id, number),
|
|
params,
|
|
current,
|
|
);
|
|
useStatsRestoration(
|
|
ranking
|
|
? !leaderboard.isPending
|
|
: !matchesQuery.isPending &&
|
|
(pageCount >= requestedPages || !hasNextPage),
|
|
);
|
|
function update(changes: Changes, replace = false) {
|
|
const next = new URLSearchParams(params);
|
|
Object.entries(changes).forEach(([key, value]) =>
|
|
value ? next.set(key, value) : next.delete(key),
|
|
);
|
|
setParams(next, { replace, preventScrollReset: true });
|
|
}
|
|
function changeView(next: boolean) {
|
|
update({ view: next ? "ranking" : null, [queryKey]: query, q: null });
|
|
}
|
|
function resetFilters() {
|
|
update(
|
|
ranking
|
|
? {
|
|
playerQ: null,
|
|
q: null,
|
|
lane: null,
|
|
min: null,
|
|
sort: null,
|
|
dir: null,
|
|
qualified: null,
|
|
championId: null,
|
|
}
|
|
: {
|
|
matchQ: null,
|
|
q: null,
|
|
format: null,
|
|
from: null,
|
|
to: null,
|
|
player: null,
|
|
playerName: null,
|
|
pages: null,
|
|
championId: null,
|
|
},
|
|
);
|
|
}
|
|
function participationHref(id: string) {
|
|
const next = new URLSearchParams(params);
|
|
["view", "q", "matchQ", "format", "pages"].forEach((k) => next.delete(k));
|
|
next.set("player", id);
|
|
next.set(
|
|
"playerName",
|
|
sortedRows.find((row) => row.userId === id)?.summonerName ??
|
|
"선택한 선수",
|
|
);
|
|
return `${root}?${next}`;
|
|
}
|
|
const active: Array<{ text: string; clear: Changes }> = [
|
|
...(query
|
|
? [{ text: `검색: ${query}`, clear: { [queryKey]: null, q: null } }]
|
|
: []),
|
|
...(championId
|
|
? [{ text: "챔피언 필터", clear: { championId: null } }]
|
|
: []),
|
|
...(ranking
|
|
? [
|
|
...(lane
|
|
? [{ text: `${LANE_LABELS[lane]} 플레이`, clear: { lane: null } }]
|
|
: []),
|
|
...(minimum !== 5
|
|
? [
|
|
{
|
|
text: minimum ? `최소 ${minimum}판` : "판수 제한 없음",
|
|
clear: { min: null },
|
|
},
|
|
]
|
|
: []),
|
|
]
|
|
: [
|
|
...(format
|
|
? [
|
|
{
|
|
text: format === "pair" ? "두 팀 내전" : "대회",
|
|
clear: { format: null },
|
|
},
|
|
]
|
|
: []),
|
|
...(from || to
|
|
? [
|
|
{
|
|
text: `${from || "처음"} ~ ${to || "마지막"}`,
|
|
clear: { from: null, to: null },
|
|
},
|
|
]
|
|
: []),
|
|
...(playerId
|
|
? [
|
|
{
|
|
text: `${params.get("playerName") ?? "선택한 선수"} 참가 내전`,
|
|
clear: { player: null, playerName: null },
|
|
},
|
|
]
|
|
: []),
|
|
]),
|
|
];
|
|
const staleLane = lane && leaderboard.data && leaderboard.data.lane !== lane;
|
|
const reset = <Btn onClick={resetFilters}>검색 조건 초기화</Btn>;
|
|
return (
|
|
<div className="internal-stats">
|
|
<main className="is-page" id="internal-stats-main">
|
|
<header className="is-page-heading">
|
|
<div>
|
|
<p className="is-eyebrow">{community.data?.name ?? "COMMUNITY"}</p>
|
|
<h1>내전 전적</h1>
|
|
<p className="is-muted">
|
|
함께한 경기와 선수들의 기록을 만나보세요.
|
|
</p>
|
|
</div>
|
|
<StatsSeasonControls
|
|
value={seasonId}
|
|
seasons={seasons.data?.seasons}
|
|
label={season?.label}
|
|
onChange={(value) => update({ seasonId: value, pages: null })}
|
|
/>
|
|
</header>
|
|
{insights.data ? (
|
|
<StatsSummary
|
|
data={insights.data}
|
|
href={(highlight) =>
|
|
statsTarget(
|
|
highlight.isSingleGame &&
|
|
highlight.internalMatchId &&
|
|
highlight.gameNumber
|
|
? internalMatchGamePath(
|
|
communityId,
|
|
highlight.internalMatchId,
|
|
highlight.gameNumber,
|
|
)
|
|
: `${root}/players/${highlight.userId}`,
|
|
new URLSearchParams({ seasonId }),
|
|
current,
|
|
)
|
|
}
|
|
/>
|
|
) : (
|
|
<StatsFeedback
|
|
type={insights.isError ? "error" : "loading"}
|
|
title={
|
|
insights.isError
|
|
? "시즌 요약을 불러오지 못했습니다"
|
|
: "시즌 요약을 불러오는 중입니다"
|
|
}
|
|
action={
|
|
insights.isError && (
|
|
<Btn onClick={() => void insights.refetch()}>다시 시도</Btn>
|
|
)
|
|
}
|
|
/>
|
|
)}
|
|
<div className="is-view-tabs" role="tablist" aria-label="전적 보기">
|
|
{[false, true].map((isRank) => (
|
|
<button
|
|
key={String(isRank)}
|
|
role="tab"
|
|
id={isRank ? "stats-tab-players" : "stats-tab-matches"}
|
|
aria-selected={ranking === isRank}
|
|
aria-controls="stats-panel"
|
|
tabIndex={ranking === isRank ? 0 : -1}
|
|
onClick={() => changeView(isRank)}
|
|
onKeyDown={(event) => {
|
|
if (
|
|
["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)
|
|
) {
|
|
event.preventDefault();
|
|
const next =
|
|
event.key === "Home"
|
|
? false
|
|
: event.key === "End"
|
|
? true
|
|
: !isRank;
|
|
changeView(next);
|
|
document
|
|
.getElementById(
|
|
next ? "stats-tab-players" : "stats-tab-matches",
|
|
)
|
|
?.focus();
|
|
}
|
|
}}
|
|
>
|
|
{isRank ? <Users size={17} /> : <List size={17} />}
|
|
{isRank ? "선수 전적·순위" : "최근 내전"}
|
|
<span>
|
|
{isRank
|
|
? (insights.data?.totals?.players ?? "—")
|
|
: (insights.data?.totals?.matches ?? "—")}
|
|
</span>
|
|
</button>
|
|
))}
|
|
<span className="is-tabs-caption">
|
|
{season?.label} · {statsPeriod(season)}
|
|
</span>
|
|
</div>
|
|
<section
|
|
role="tabpanel"
|
|
id="stats-panel"
|
|
aria-labelledby={ranking ? "stats-tab-players" : "stats-tab-matches"}
|
|
>
|
|
<div className="is-filter-bar">
|
|
<label className="is-search">
|
|
<Search size={18} />
|
|
<input
|
|
type="search"
|
|
maxLength={100}
|
|
aria-label={ranking ? "선수 검색" : "내전·팀·선수 검색"}
|
|
placeholder={
|
|
ranking ? "선수 이름 검색" : "내전명, 팀명, 선수 이름 검색"
|
|
}
|
|
value={query}
|
|
onChange={(e) =>
|
|
update(
|
|
{ [queryKey]: e.target.value, q: null, pages: null },
|
|
true,
|
|
)
|
|
}
|
|
/>
|
|
{query && (
|
|
<button
|
|
aria-label="검색어 지우기"
|
|
onClick={() =>
|
|
update({ [queryKey]: null, q: null, pages: null }, true)
|
|
}
|
|
>
|
|
<X size={16} />
|
|
</button>
|
|
)}
|
|
</label>
|
|
{ranking ? (
|
|
<>
|
|
<StatsLaneSelect
|
|
value={lane}
|
|
onChange={(value) => update({ lane: value })}
|
|
/>
|
|
<label className="is-select">
|
|
<span>순위 기준</span>
|
|
<select
|
|
aria-label="최소 판수"
|
|
value={minimum}
|
|
onChange={(e) => update({ min: e.target.value })}
|
|
>
|
|
{[0, 5, 10, 20].map((n) => (
|
|
<option key={n} value={n}>
|
|
{n ? `최소 ${n}판` : "모든 선수"}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
<label className="is-sort-select">
|
|
<ArrowDownUp size={16} />
|
|
<select
|
|
aria-label="순위 정렬"
|
|
value={sort}
|
|
onChange={(e) =>
|
|
update({ sort: e.target.value, dir: null })
|
|
}
|
|
>
|
|
{Object.entries(STATS_SORTS).map(([key, label]) => (
|
|
<option value={key} key={key}>
|
|
{label} 순
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
</>
|
|
) : (
|
|
<>
|
|
<div
|
|
className="is-type-filters"
|
|
role="group"
|
|
aria-label="내전 유형"
|
|
>
|
|
{[
|
|
["", "전체"],
|
|
["pair", "두 팀 내전"],
|
|
["tournament", "대회"],
|
|
].map(([value, label]) => (
|
|
<Chip
|
|
key={value}
|
|
selected={(format ?? "") === value}
|
|
onClick={() => update({ format: value, pages: null })}
|
|
>
|
|
{label}
|
|
</Chip>
|
|
))}
|
|
</div>
|
|
<div className="is-date-range">
|
|
<CalendarDays size={16} />
|
|
<label>
|
|
<span className="sr-only">시작일</span>
|
|
<input
|
|
aria-label="시작일"
|
|
type="date"
|
|
value={from}
|
|
onInput={(e) =>
|
|
update({ from: e.currentTarget.value, pages: null })
|
|
}
|
|
/>
|
|
</label>
|
|
<span>—</span>
|
|
<label>
|
|
<span className="sr-only">종료일</span>
|
|
<input
|
|
aria-label="종료일"
|
|
type="date"
|
|
value={to}
|
|
onInput={(e) =>
|
|
update({ to: e.currentTarget.value, pages: null })
|
|
}
|
|
/>
|
|
</label>
|
|
</div>
|
|
</>
|
|
)}
|
|
</div>
|
|
{active.length > 0 && (
|
|
<div className="is-active-filters">
|
|
<span>적용 조건</span>
|
|
{active.map((item) => (
|
|
<button
|
|
key={item.text}
|
|
onClick={() => update({ ...item.clear, pages: null })}
|
|
aria-label={`${item.text} 해제`}
|
|
>
|
|
{item.text}
|
|
<X size={13} />
|
|
</button>
|
|
))}
|
|
<button className="is-reset" onClick={resetFilters}>
|
|
전체 초기화
|
|
</button>
|
|
</div>
|
|
)}
|
|
{ranking ? (
|
|
<>
|
|
<div className="is-result-heading">
|
|
<div>
|
|
<h2>
|
|
{STATS_SORTS[sort]} 순 <span>{visibleRows.length}명</span>
|
|
</h2>
|
|
<p>
|
|
{lane
|
|
? `${LANE_LABELS[lane]} 플레이만 집계`
|
|
: "전체 포지션"}{" "}
|
|
·{" "}
|
|
{minimum
|
|
? `${minimum}판 미만은 기준 미달로 뒤에 표시`
|
|
: "판수 제한 없음"}
|
|
</p>
|
|
</div>
|
|
<label className="is-checkbox">
|
|
<input
|
|
type="checkbox"
|
|
checked={params.get("qualified") === "1"}
|
|
onChange={(e) =>
|
|
update({ qualified: e.target.checked ? "1" : null })
|
|
}
|
|
/>
|
|
기준 충족 선수만
|
|
</label>
|
|
</div>
|
|
{leaderboard.isPending ? (
|
|
<StatsFeedback
|
|
type="loading"
|
|
title="선수 전적을 불러오는 중입니다"
|
|
/>
|
|
) : leaderboard.isError || staleLane ? (
|
|
<StatsFeedback
|
|
type="error"
|
|
title="선수 전적을 불러오지 못했습니다"
|
|
action={
|
|
<Btn onClick={() => void leaderboard.refetch()}>
|
|
다시 시도
|
|
</Btn>
|
|
}
|
|
>
|
|
선택한 시즌과 검색 조건은 유지됩니다.
|
|
</StatsFeedback>
|
|
) : visibleRows.length ? (
|
|
<StatsLeaderboard
|
|
rows={visibleRows}
|
|
minimum={minimum}
|
|
lane={lane}
|
|
sort={sort}
|
|
direction={direction}
|
|
onSort={(key) =>
|
|
update({
|
|
sort: key,
|
|
dir:
|
|
sort === key && direction === "desc" ? "asc" : "desc",
|
|
})
|
|
}
|
|
playerHref={playerHref}
|
|
participationHref={participationHref}
|
|
manifest={manifest}
|
|
/>
|
|
) : (
|
|
<StatsFeedback
|
|
type="empty"
|
|
title="조건에 맞는 선수가 없습니다"
|
|
action={reset}
|
|
>
|
|
검색어, 포지션 또는 최소 판수를 바꿔 보세요.
|
|
</StatsFeedback>
|
|
)}
|
|
</>
|
|
) : invalidDates ? (
|
|
<StatsFeedback
|
|
type="error"
|
|
title="조회 기간을 확인해 주세요"
|
|
action={reset}
|
|
>
|
|
종료일을 시작일과 같거나 이후 날짜로 선택해 주세요.
|
|
</StatsFeedback>
|
|
) : matchesQuery.isPending ? (
|
|
<StatsFeedback
|
|
type="loading"
|
|
title="경기 기록을 불러오는 중입니다"
|
|
/>
|
|
) : matchesQuery.isError && !matches.length ? (
|
|
<StatsFeedback
|
|
type="error"
|
|
title="경기 기록을 불러오지 못했습니다"
|
|
action={
|
|
<Btn onClick={() => void matchesQuery.refetch()}>다시 시도</Btn>
|
|
}
|
|
>
|
|
선택한 시즌과 검색 조건은 유지됩니다.
|
|
</StatsFeedback>
|
|
) : (
|
|
<>
|
|
<div className="is-result-heading">
|
|
<h2>
|
|
경기 기록 <span>{matches.length}회</span>
|
|
</h2>
|
|
<p role="status">
|
|
{matches.length}개 표시
|
|
{hasNextPage ? " · 이전 기록 더 있음" : " · 조회 완료"}
|
|
</p>
|
|
</div>
|
|
{matches.length ? (
|
|
<div className="is-events-layout">
|
|
<StatsEventJump matches={matches} />
|
|
<div className="is-events-list">
|
|
{matches.map((match) => (
|
|
<StatsEvent
|
|
key={match.matchId}
|
|
match={match}
|
|
eventHref={eventHref(match.matchId)}
|
|
gameHref={(number) => gameHref(match.matchId, number)}
|
|
/>
|
|
))}
|
|
{matchesQuery.isFetchNextPageError && (
|
|
<StatsFeedback
|
|
type="error"
|
|
title="이전 기록을 불러오지 못했습니다"
|
|
action={
|
|
<Btn onClick={() => void fetchNextPage()}>
|
|
다시 시도
|
|
</Btn>
|
|
}
|
|
/>
|
|
)}
|
|
{hasNextPage && (
|
|
<button
|
|
className="is-load-more"
|
|
disabled={isFetchingNextPage}
|
|
onClick={() => update({ pages: String(pageCount + 1) })}
|
|
>
|
|
{isFetchingNextPage
|
|
? "이전 내전을 불러오는 중"
|
|
: "이전 내전 더 보기"}
|
|
<ArrowDown size={16} />
|
|
</button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
) : (
|
|
<StatsFeedback
|
|
type="empty"
|
|
title="조건에 맞는 내전이 없습니다"
|
|
action={reset}
|
|
>
|
|
날짜나 검색어를 바꾸면 다른 내전을 찾을 수 있습니다.
|
|
</StatsFeedback>
|
|
)}
|
|
</>
|
|
)}
|
|
</section>
|
|
<footer className="is-page-footer">
|
|
<span>LOLYMPUS · 함께하는 모든 게임의 기록</span>
|
|
<span>한국 시간 기준 · 원본 없는 세트는 상세 지표 집계에서 제외</span>
|
|
</footer>
|
|
</main>
|
|
</div>
|
|
);
|
|
}
|