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

1122 lines
40 KiB
TypeScript

import { useEffect, useState, type CSSProperties, type ReactNode } from 'react';
import type {
MatchDetailResponse,
MatchEventType,
MatchSummaryResponse,
} from '@lolympus/contracts';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { Link, useSearchParams } from 'react-router';
import {
useCommunityLeaderboard,
useDdragonManifest,
useMatches,
useMatchesPage,
} from '../api/hooks';
import nextMatchArtwork from '../assets/next-match-hero.webp';
import pixelMedal from '../assets/pixel-medal-first.svg';
import HomeHallOfFame from '../components/HomeHallOfFame';
import { championIconUrl, profileIconUrl } from '../lib/ddragon';
import { rankLeaderboardByLane } from '../lib/internal-stats-presentation';
import { MATCH_EVENT_LABEL } from '../lib/match-event-type';
import { LANE_LABELS } from '../lib/riot-history';
import { mapIdToLabel } from '../api/mappers';
import { DEFAULT_COMMUNITY_ID } from '../config';
import {
Button,
EmptyNote,
ErrorNote,
PanelHeader,
PlainPage,
Skeleton,
pageWidthClass,
} from '../ui';
import {
getHistoryMatchTitle,
getHomeMatchEnrollment,
getHomeMatchSchedule,
getNextMatchBanner,
getMatchStageLabel,
} from './home-match-presentation';
const UPCOMING_MATCH_LIST_LIMIT = 4;
const MATCH_ARCHIVE_PAGE_SIZE = 10;
const HOME_HISTORY_LIMIT = 4;
const HOME_RANKING_LIMIT = 5;
const DEFAULT_MAP_ID = 11;
const SCHEDULE_LIST_CLASS = 'divide-y divide-line border-y border-line';
const SCHEDULE_ROW_CLASS =
'grid grid-cols-[minmax(0,1fr)_auto] gap-x-3 gap-y-2 px-2 py-3.5 md:grid-cols-[7.5rem_minmax(0,1fr)_auto] md:items-center md:gap-4';
const RANKING_COLUMNS_CLASS =
'grid grid-cols-[1.5rem_minmax(0,1fr)_3rem] items-center gap-3 px-3';
const NEXT_MATCH_CONTENT_CLASS =
'flex min-h-[16rem] items-center py-8 md:min-h-[clamp(22rem,29vw,30rem)] md:py-12';
/** 순위 카드의 슬라이드 순서. undefined는 종합 순위. */
const RANKING_SLIDES = [
undefined,
'TOP',
'JUNGLE',
'MIDDLE',
'BOTTOM',
'UTILITY',
] as const;
const RANKING_SLIDE_INTERVAL_MS = 5000;
const GENERIC_MATCH_NAME = /^(?:정기\s*)?내전$/u;
const DECISION_LABELS = {
walkover: '부전승',
forfeit: '기권승',
administrative: '판정승',
draw: '무승부',
} as const;
function NextMatch({ match }: { match: MatchDetailResponse }) {
const schedule = getHomeMatchSchedule(match.scheduledAt);
const { title, status, capacity, canApply } = getNextMatchBanner(match);
return (
<Link
to={`/match/${match._id}`}
aria-labelledby="next-match-label next-match-title"
aria-describedby="next-match-schedule next-match-status"
className="lts-home-hero group relative isolate block overflow-hidden focus-visible:-outline-offset-4 focus-visible:outline-primary"
>
<img
src={nextMatchArtwork}
alt=""
fetchPriority="high"
className="absolute inset-y-0 left-1/2 -z-20 h-full w-full max-w-[112rem] -translate-x-1/2 object-cover object-[75%_center] md:object-center"
/>
<div
className={`${pageWidthClass()} ${NEXT_MATCH_CONTENT_CLASS}`}
>
<div className="w-full max-w-xl">
<p
id="next-match-label"
className="text-sm font-semibold text-white/80 md:text-base"
>
다음 내전
</p>
<h1
id="next-match-title"
className="mt-3 text-[clamp(2rem,5vw,3.5rem)] font-extrabold leading-[1.15] tracking-tight text-white [overflow-wrap:anywhere] group-hover:underline group-hover:decoration-2 group-hover:underline-offset-8"
>
{title}
</h1>
<p
id="next-match-schedule"
className="tabular mt-4 text-base font-semibold text-white/90 md:mt-6 md:text-xl"
>
{schedule ? (
<time dateTime={match.scheduledAt}>
{schedule.date} {schedule.time}
</time>
) : '일정 미정'}
</p>
<p id="next-match-status" className="tabular mt-3 text-sm text-white/85 md:text-base">
<strong className={canApply ? 'font-semibold text-brand-coral' : 'font-semibold'}>
{status}
</strong>
{' · '}
{capacity}
{match.mapId !== DEFAULT_MAP_ID && (
<> · {mapIdToLabel(match.mapId)}</>
)}
</p>
</div>
</div>
</Link>
);
}
function NextMatchSkeleton() {
return (
<section className="bg-sunken" aria-busy="true" aria-label="다음 내전">
<span role="status" className="sr-only">다음 내전을 불러오는 중</span>
<div className={`${pageWidthClass()} ${NEXT_MATCH_CONTENT_CLASS}`}>
<div className="w-full max-w-xl">
<h1 className="text-sm font-semibold text-content-muted md:text-base">다음 내전</h1>
<div className="mt-3">
<Skeleton width="80%" height="clamp(2.3rem,5.75vw,4.025rem)" radius={2} />
</div>
<div className="mt-4 md:mt-6">
<Skeleton width="min(16rem,70%)" height="1.75rem" index={1} />
</div>
<div className="mt-3">
<Skeleton width="min(12rem,55%)" height="1.5rem" index={2} />
</div>
</div>
</div>
</section>
);
}
function UpcomingMatchesSkeleton({ title, limit }: { title: string; limit: number }) {
return (
<section aria-busy="true" aria-label={title}>
<PanelHeader title={title} variant="section" />
<span role="status" className="sr-only">{title}을 불러오는 중</span>
<ScheduleRowsSkeleton limit={limit} />
</section>
);
}
function UpcomingMatches({
matches,
title = '이어지는 내전',
actions,
footer,
}: {
matches: MatchDetailResponse[];
title?: string;
actions?: ReactNode;
footer?: ReactNode;
}) {
return (
<section>
<PanelHeader title={title} variant="section" actions={actions} />
<ul className={SCHEDULE_LIST_CLASS}>
{matches.map((match) => (
<li key={match._id}>
<ScheduleMatchRow match={match} />
</li>
))}
</ul>
{matches.length === 0 && (
<EmptyNote size="sm" title="이 페이지에 표시할 일정이 없습니다." />
)}
{footer}
</section>
);
}
function ScheduleMatchRow({ match }: { match: MatchDetailResponse }) {
const { capacity, label } = getHomeMatchEnrollment(match);
return (
<ScheduleRow
href={`/match/${match._id}`}
scheduledAt={match.scheduledAt}
title={match.title}
meta={`참가 ${capacity}`}
result={<ScheduleStatus match={match} label={match.status === 'recruiting' ? label : undefined} />}
/>
);
}
function ScheduleStatus({
match,
label = getMatchStageLabel(match),
}: {
match: Pick<MatchSummaryResponse, 'status' | 'eventProgress'>;
label?: string;
}) {
const stage = match.eventProgress?.stage ?? match.status;
const statusColor = stage === 'in-progress'
? 'text-leaf'
: stage === 'auction'
? 'text-gold'
: 'text-content-muted';
return (
<span className={`inline-flex min-h-6 items-center gap-1.5 whitespace-nowrap rounded-full border border-current/25 px-2.5 py-0.5 text-xs font-semibold ${statusColor}`}>
{label}
</span>
);
}
function ScheduleRow({
href,
scheduledAt,
title,
meta,
result,
resultBelowOnMobile = false,
}: {
href: string;
scheduledAt: string;
title: string;
meta: ReactNode;
result: ReactNode;
resultBelowOnMobile?: boolean;
}) {
const schedule = getHomeMatchSchedule(scheduledAt);
return (
<Link
to={href}
className={`${SCHEDULE_ROW_CLASS} group transition-colors hover:bg-sunken focus-visible:-outline-offset-2`}
>
<time
dateTime={schedule ? scheduledAt : undefined}
className="tabular flex flex-wrap items-baseline gap-x-2 md:block"
>
<span className="text-[15px] font-semibold leading-snug text-content">
{schedule ? `${schedule.month}/${schedule.day} (${schedule.weekday})` : '일정 미정'}
</span>
{schedule && (
<span className="text-xs text-content-subtle md:mt-0.5 md:block">
{schedule.time}
</span>
)}
</time>
<div className="col-span-2 col-start-1 row-start-2 min-w-0 md:col-span-1 md:col-start-2 md:row-start-1">
<h3 className="text-[15px] font-semibold leading-snug text-content [overflow-wrap:anywhere] group-hover:underline group-hover:underline-offset-2">
{title}
</h3>
<p className="tabular mt-0.5 text-[13px] text-content-subtle">
{meta}
</p>
</div>
<div className={`flex min-w-0 items-center gap-2 md:col-start-3 md:row-start-1 md:max-w-72 md:justify-self-end ${
resultBelowOnMobile
? 'col-span-2 col-start-1 row-start-3 md:col-span-1'
: 'col-start-2 row-start-1'
}`}>
<span className="min-w-0 text-[13px]">
{result}
</span>
<ChevronRight className="hidden size-4 shrink-0 text-content-muted md:block" aria-hidden="true" />
</div>
</Link>
);
}
function HistoryResult({ match }: { match: MatchSummaryResponse }) {
const result = match.historyResult;
const teamLabelClass = 'min-w-0 text-content-muted [overflow-wrap:anywhere]';
if (match.status === 'finished' && result) {
switch (result.type) {
case 'score': {
const label = result.winnerTeamName
? `${result.winnerTeamName} 승`
: undefined;
return (
<span className="flex min-w-0 items-baseline gap-1.5">
<strong className="tabular shrink-0 font-bold text-content">
{result.teamAWins}:{result.teamBWins}
</strong>
{label && (
<span
className={teamLabelClass}
title={label}
>
{label}
</span>
)}
</span>
);
}
case 'winners': {
const label = result.teamNames.join(', ');
return (
<span className="flex min-w-0 items-baseline gap-1.5">
<strong className="shrink-0 font-semibold text-content">
{result.teamNames.length > 1 ? '공동 1위' : '우승'}
</strong>
<span
className={teamLabelClass}
title={label}
>
{label}
</span>
</span>
);
}
case 'decision': {
return (
<span className="flex min-w-0 items-baseline gap-1.5">
<strong className="shrink-0 font-semibold text-content">
{DECISION_LABELS[result.decision]}
</strong>
{result.winnerTeamName && (
<span
className={teamLabelClass}
title={result.winnerTeamName}
>
{result.winnerTeamName}
</span>
)}
</span>
);
}
}
}
if (match.status === 'team-built' || match.status === 'in-progress') {
return <ScheduleStatus match={match} />;
}
return (
<span className="text-content-muted">
{getMatchStageLabel(match)}
</span>
);
}
function ScheduleRowsSkeleton({
limit,
resultBelowOnMobile = false,
}: {
limit: number;
resultBelowOnMobile?: boolean;
}) {
return (
<ul className={SCHEDULE_LIST_CLASS} aria-hidden="true">
{Array.from({ length: limit }, (_, index) => (
<li key={index} className={SCHEDULE_ROW_CLASS}>
<div className="flex items-center gap-2 md:block md:space-y-0.5">
<Skeleton width={76} height={21} index={index} />
<Skeleton width={32} height={16} index={index} />
</div>
<div className="col-span-2 col-start-1 row-start-2 min-w-0 space-y-0.5 md:col-span-1 md:col-start-2 md:row-start-1">
<Skeleton width="60%" height={21} index={index} />
<Skeleton width={64} height={20} index={index} />
</div>
<div className={`flex items-center gap-2 md:col-start-3 md:row-start-1 md:justify-self-end ${
resultBelowOnMobile
? 'col-span-2 col-start-1 row-start-3 md:col-span-1'
: 'col-start-2 row-start-1'
}`}>
<Skeleton
width={resultBelowOnMobile ? 96 : 64}
height={resultBelowOnMobile ? 20 : 24}
radius={resultBelowOnMobile ? 3 : 'rounded'}
index={index}
/>
<span className="hidden size-4 md:block" />
</div>
</li>
))}
</ul>
);
}
function HistoryRecords({
matches,
eventLabel,
}: {
matches: MatchSummaryResponse[];
eventLabel: string;
}) {
if (matches.length === 0) {
return <EmptyNote size="sm" title={`아직 ${eventLabel} 기록이 없습니다.`} />;
}
const rows = matches.map((match) => {
const schedule = getHomeMatchSchedule(match.scheduledAt);
return {
match,
title: getHistoryMatchTitle(match.title, schedule),
href: `/match/${match._id}`,
map:
match.mapId === DEFAULT_MAP_ID ? undefined : mapIdToLabel(match.mapId),
};
});
return (
<ul className={SCHEDULE_LIST_CLASS}>
{rows.map(({ match, title, href, map }) => (
<li key={match._id}>
<ScheduleRow
href={href}
scheduledAt={match.scheduledAt}
title={title}
meta={<>참가 {match.participants.length}명{map && <> · {map}</>}</>}
result={<HistoryResult match={match} />}
resultBelowOnMobile
/>
</li>
))}
</ul>
);
}
function RecentMatchResults({ matches }: { matches: MatchSummaryResponse[] }) {
if (matches.length === 0) {
return <EmptyNote size="sm" title="아직 종료된 내전이 없습니다." />;
}
return (
<ul className="divide-y divide-line border-y border-line">
{matches.map((match) => {
const schedule = getHomeMatchSchedule(match.scheduledAt);
const name = getHistoryMatchTitle(match.title, schedule).trim();
const result = match.historyResult;
const winners = getWinnerTeams(match);
const meta = [
schedule?.time,
match.teams.length > 2 && `${match.teams.length}팀`,
match.mapId !== DEFAULT_MAP_ID && mapIdToLabel(match.mapId),
].filter(Boolean);
const isDraw =
result?.type === 'decision'
? result.decision === 'draw'
: result?.type === 'score' && winners.length === 0;
const winnerLabel =
result?.type === 'winners'
? winners.length > 1
? '공동 1위'
: '우승'
: result?.type === 'decision' && result.decision !== 'draw'
? DECISION_LABELS[result.decision]
: '승리';
return (
<li key={match._id}>
<Link
to={`/match/${match._id}`}
className={`${RECENT_RESULT_ROW_CLASS} group transition-colors hover:bg-sunken focus-visible:-outline-offset-2`}
>
<div className="tabular flex items-baseline gap-2 md:block">
<p className="text-[15px] font-semibold leading-snug text-content">
{schedule ? (
<time dateTime={match.scheduledAt}>
{schedule.month}/{schedule.day} ({schedule.weekday})
</time>
) : (
'일정 미정'
)}
</p>
{meta.length > 0 && (
<p className="text-xs text-content-muted md:mt-0.5">
{meta.join(' · ')}
</p>
)}
</div>
<div className="min-w-0 space-y-2">
{/* 날짜만으로 구분되는 "내전"은 이름을 반복하지 않는다. */}
{!GENERIC_MATCH_NAME.test(name) && (
<p className="truncate text-xs text-content-muted" title={name}>
{name}
</p>
)}
{winners.map((team) => (
<WinnerTeam key={team.name} team={team} label={winnerLabel} />
))}
{winners.length === 0 && (
<p className="text-sm text-content-muted">
{isDraw ? '무승부' : '결과 미집계'}
</p>
)}
</div>
<div className="flex items-center gap-2 md:justify-self-end">
{result?.type === 'score' && (
<strong className="tabular whitespace-nowrap text-[15px] font-bold text-content">
{Math.max(result.teamAWins, result.teamBWins)} :{' '}
{Math.min(result.teamAWins, result.teamBWins)}
</strong>
)}
<ChevronRight
className="hidden size-4 text-content-muted md:block"
aria-hidden="true"
/>
</div>
</Link>
</li>
);
})}
</ul>
);
}
const RECENT_RESULT_ROW_CLASS =
'grid gap-2 px-2 py-3.5 md:grid-cols-[7.5rem_minmax(0,1fr)_auto] md:items-center md:gap-4';
const POSITION_ORDER = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
interface WinnerTeamSummary {
name: string;
members: MatchSummaryResponse['participants'];
}
/** 결과에 담긴 우승팀 이름을 팀 구성과 맞춰 멤버를 포지션 순으로 돌려준다. */
function getWinnerTeams(match: MatchSummaryResponse): WinnerTeamSummary[] {
const result = match.historyResult;
if (match.status !== 'finished' || !result) return [];
const names =
result.type === 'winners'
? result.teamNames
: result.winnerTeamName
? [result.winnerTeamName]
: [];
const participants = new Map(
match.participants.map((participant) => [participant.userId, participant]),
);
return names.map((name) => {
// 같은 이름의 팀이 여럿이면 누가 우승했는지 알 수 없으므로 멤버를 비운다.
const candidates = match.teams.filter(
(team) => (team.name.trim() || `${team.teamIndex}팀`) === name,
);
const members =
candidates.length === 1
? [...candidates[0].members]
.sort(
(a, b) =>
POSITION_ORDER.indexOf(a.assignedPosition) -
POSITION_ORDER.indexOf(b.assignedPosition),
)
.flatMap((member) => {
const participant = participants.get(member.userId);
return participant ? [participant] : [];
})
: [];
return { name, members };
});
}
function WinnerTeam({ team, label }: { team: WinnerTeamSummary; label: string }) {
const { data: manifest } = useDdragonManifest();
const memberNames = team.members
.map((member) => member.gameName)
.filter(Boolean)
.join(' · ');
return (
<div className="min-w-0">
<p className="flex min-w-0 items-center gap-1.5">
<img src={pixelMedal} alt="" className="size-4 shrink-0 [image-rendering:pixelated]" />
<span className="shrink-0 text-xs font-semibold text-gold">{label}</span>
<strong className="truncate text-[15px] font-semibold text-content group-hover:underline">
{team.name}
</strong>
</p>
{team.members.length > 0 && (
<div className="mt-1.5 flex min-w-0 items-center gap-2.5">
<span className="flex shrink-0 -space-x-1.5">
{team.members.map((member) => (
<img
key={member.userId}
src={profileIconUrl(manifest, member.profileIconId ?? 0)}
alt=""
className="size-7 rounded-full bg-sunken-strong object-cover ring-2 ring-body"
loading="lazy"
/>
))}
</span>
{memberNames && (
<span className="truncate text-xs text-content-muted" title={memberNames}>
{memberNames}
</span>
)}
</div>
)}
</div>
);
}
function RecentMatchResultsSkeleton({ limit }: { limit: number }) {
return (
<div className="divide-y divide-line border-y border-line" aria-hidden="true">
{Array.from({ length: limit }, (_, index) => (
<div key={index} className={RECENT_RESULT_ROW_CLASS}>
<div className="flex items-center gap-2 md:block md:space-y-0.5">
<Skeleton width={80} height={21} index={index} />
<Skeleton width={48} height={16} index={index} />
</div>
<div className="min-w-0">
<div className="flex items-center gap-1.5">
<Skeleton width={16} height={16} index={index} />
<Skeleton width="min(10rem,70%)" height={23} index={index} />
</div>
<div className="mt-1.5 flex min-w-0 items-center gap-2.5">
<div className="flex shrink-0 -space-x-1.5">
{Array.from({ length: 5 }, (_, memberIndex) => (
<Skeleton key={memberIndex} width={28} height={28} radius="rounded" index={index} />
))}
</div>
<Skeleton width="35%" height={16} index={index} />
</div>
</div>
<div className="flex items-center gap-2 md:justify-self-end">
<Skeleton width={40} height={23} index={index} />
<span className="hidden size-4 md:block" />
</div>
</div>
))}
</div>
);
}
const RANK_BADGE_CLASS = [
'bg-gold text-accent-content',
'bg-sunken-strong text-content',
'bg-gold-tint text-gold',
] as const;
function RankingSkeleton() {
return (
<div className="min-h-[17.5rem]" aria-hidden="true">
{Array.from({ length: HOME_RANKING_LIMIT }, (_, index) => (
<div key={index} className={`${RANKING_COLUMNS_CLASS} py-2.5`}>
<Skeleton width={24} height={24} radius="rounded" index={index} />
<div className="flex min-w-0 items-center gap-2">
<Skeleton width={36} height={36} radius="rounded" index={index} className="shrink-0" />
<div className="min-w-0 flex-1 space-y-1">
<Skeleton width="80%" height={16} index={index} />
<Skeleton width="95%" height={12} index={index} />
</div>
</div>
<Skeleton width={40} height={20} index={index} className="justify-self-end" />
</div>
))}
</div>
);
}
/** 현재 시즌 순위표의 앞부분. 전적 화면과 같은 집계를 그대로 보여준다. */
function RankingPreview({ statsPath }: { statsPath: string }) {
const leaderboardQuery = useCommunityLeaderboard({ seasonId: 'current' });
const { data: manifest } = useDdragonManifest();
const [slide, setSlide] = useState(0);
const [direction, setDirection] = useState<1 | -1>(1);
const [paused, setPaused] = useState(false);
const [touchStartX, setTouchStartX] = useState<number>();
const lane = RANKING_SLIDES[slide];
const allRows = leaderboardQuery.data?.rows ?? [];
const rows = (lane ? rankLeaderboardByLane(allRows, lane) : allRows).slice(
0,
HOME_RANKING_LIMIT,
);
const label = lane ? LANE_LABELS[lane] : '종합';
const move = (step: 1 | -1) => {
setDirection(step);
setSlide(
(current) => (current + step + RANKING_SLIDES.length) % RANKING_SLIDES.length,
);
};
// key가 바뀌면 목록이 새로 붙으면서 넘긴 방향에서 들어오는 애니메이션이 다시 돈다.
const slideStyle = {
'--lts-rank-slide-from': `${direction * 1.5}rem`,
} as CSSProperties;
// 읽거나 누르려는 동안에는 멈추고, 직접 넘기면 그 슬라이드부터 다시 센다.
useEffect(() => {
if (leaderboardQuery.isPending || paused || window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
return;
}
const timer = window.setTimeout(() => move(1), RANKING_SLIDE_INTERVAL_MS);
return () => window.clearTimeout(timer);
}, [leaderboardQuery.isPending, paused, slide]);
return (
<aside
aria-busy={leaderboardQuery.isPending}
onMouseEnter={() => setPaused(true)}
onMouseLeave={() => setPaused(false)}
onFocus={() => setPaused(true)}
onBlur={() => setPaused(false)}
onTouchStart={(event) => setTouchStartX(event.touches[0]?.clientX)}
onTouchEnd={(event) => {
const endX = event.changedTouches[0]?.clientX;
if (leaderboardQuery.isPending || touchStartX === undefined || endX === undefined) return;
const distance = endX - touchStartX;
if (Math.abs(distance) > 48) move(distance < 0 ? 1 : -1);
setTouchStartX(undefined);
}}
>
<PanelHeader
title={`시즌 ${label} 순위`}
variant="section"
actions={
<Link
to={`${statsPath}?view=ranking`}
className="inline-flex items-center gap-0.5 whitespace-nowrap text-[13px] font-semibold text-content-muted hover:text-content hover:underline"
>
선수 전적·순위 보기
<ChevronRight className="size-4" aria-hidden="true" />
</Link>
}
/>
<div className="overflow-hidden rounded-2xl bg-sunken p-2">
{leaderboardQuery.isPending ? (
<>
<span role="status" className="sr-only">시즌 순위를 불러오는 중</span>
<RankingSkeleton />
</>
) : leaderboardQuery.isError ? (
<p className="p-3 text-sm text-content-muted">
순위를 불러오지 못했습니다.
</p>
) : rows.length === 0 ? (
<div
key={slide}
style={slideStyle}
className="lts-rank-slide grid min-h-[17.5rem] place-items-center"
>
<EmptyNote size="sm" title="아직 집계된 순위가 없습니다." />
</div>
) : (
<ol
key={slide}
style={slideStyle}
className="lts-rank-slide min-h-[17.5rem]"
>
{rows.map((row, index) => (
<li key={row.userId}>
<Link
to={`/users/${row.userId}/history?queueGroup=internal`}
className={`${RANKING_COLUMNS_CLASS} group rounded-xl py-2.5 transition-colors hover:bg-card focus-visible:-outline-offset-2`}
>
<span
className={`tabular grid size-6 place-items-center rounded-full text-xs font-bold ${
RANK_BADGE_CLASS[index] ?? 'text-content-muted'
}`}
>
{index + 1}
<span className="sr-only">위</span>
</span>
<span className="flex min-w-0 items-center gap-2">
<img
src={profileIconUrl(manifest, row.profileIconId)}
alt=""
className="size-9 shrink-0 rounded-full bg-sunken-strong object-cover"
loading="lazy"
/>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-semibold text-content group-hover:text-primary">
{row.summonerName}
</span>
<span className="tabular block text-xs text-content-muted">
{row.games}전 {row.wins}승 {row.losses}패
</span>
</span>
<span className="hidden shrink-0 items-center gap-0.5 min-[420px]:flex lg:hidden">
{row.topChampions.slice(0, 3).map((champion) => {
const icon = championIconUrl(manifest, champion.championId);
return icon ? (
<img
key={champion.championId}
src={icon}
alt=""
className="size-6 rounded-full object-cover"
loading="lazy"
/>
) : null;
})}
</span>
</span>
<strong
className={`tabular text-right text-sm ${
row.winRate >= 50 ? 'text-win' : 'text-content-muted'
}`}
>
<span className="sr-only">승률 </span>
{row.winRate}%
</strong>
</Link>
</li>
))}
</ol>
)}
<div className="flex items-center justify-center gap-1 pt-1">
<button
type="button"
aria-label="이전 순위"
disabled={leaderboardQuery.isPending}
className="grid size-8 place-items-center rounded-full text-content-muted transition-colors hover:bg-card hover:text-content disabled:pointer-events-none disabled:opacity-40"
onClick={() => move(-1)}
>
<ChevronLeft className="size-4" aria-hidden="true" />
</button>
<p
className="tabular min-w-12 text-center text-[13px] text-content-muted"
aria-live={paused ? 'polite' : 'off'}
>
<span className="sr-only">{label} 순위, </span>
<strong className="font-bold text-content">{slide + 1}</strong> /{' '}
{RANKING_SLIDES.length}
</p>
<button
type="button"
aria-label="다음 순위"
disabled={leaderboardQuery.isPending}
className="grid size-8 place-items-center rounded-full text-content-muted transition-colors hover:bg-card hover:text-content disabled:pointer-events-none disabled:opacity-40"
onClick={() => move(1)}
>
<ChevronRight className="size-4" aria-hidden="true" />
</button>
</div>
</div>
</aside>
);
}
interface MatchPaginationProps {
label: string;
page: number;
pageCount: number;
total: number;
isFetching: boolean;
onPrevious: () => void;
onNext: () => void;
}
function MatchPagination({
label,
page,
pageCount,
total,
isFetching,
onPrevious,
onNext,
}: MatchPaginationProps) {
return (
<nav aria-label={label} className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1 px-2 py-2.5">
<span className="tabular text-xs text-content-muted">
총 {total.toLocaleString('ko-KR')}개 · {page} / {pageCount}
</span>
<div className="flex items-center gap-1">
<Button
label="이전"
size="sm"
variant="ghost"
icon={<ChevronLeft className="size-4" aria-hidden="true" />}
isDisabled={page <= 1 || isFetching}
onClick={onPrevious}
/>
<Button
label="다음"
size="sm"
variant="ghost"
endContent={<ChevronRight className="size-4" aria-hidden="true" />}
isDisabled={page >= pageCount || isFetching}
onClick={onNext}
/>
</div>
</nav>
);
}
export default function HomePage({ eventType }: { eventType?: MatchEventType }) {
const showArchive = eventType !== undefined;
const selectedEventType = eventType ?? 'inhouse';
const eventLabel = MATCH_EVENT_LABEL[selectedEventType];
const [timelineNow] = useState(() => new Date().toISOString());
const [searchParams, setSearchParams] = useSearchParams();
function getPage(key: 'page' | 'activePage') {
const page = Number(searchParams.get(key));
return showArchive && Number.isSafeInteger(page) && page > 0 ? page : 1;
}
const historyPage = getPage('page');
const activePage = getPage('activePage');
const historyLimit = showArchive ? MATCH_ARCHIVE_PAGE_SIZE : HOME_HISTORY_LIMIT;
const activeLimit = showArchive ? MATCH_ARCHIVE_PAGE_SIZE : UPCOMING_MATCH_LIST_LIMIT;
function setPage(key: 'page' | 'activePage', page: number) {
setSearchParams((previous) => {
const params = new URLSearchParams(previous);
if (page > 1) params.set(key, String(page));
else params.delete(key);
return params;
}, { preventScrollReset: true });
}
const upcomingMatchesQuery = useMatches({
eventType: selectedEventType,
view: 'upcoming',
asOf: timelineNow,
limit: UPCOMING_MATCH_LIST_LIMIT,
sort: 'asc',
});
const activeMatchesQuery = useMatchesPage({
eventType: selectedEventType,
view: 'active',
asOf: timelineNow,
limit: activeLimit,
page: activePage,
sort: 'desc',
});
const historyMatchesQuery = useMatchesPage({
eventType: selectedEventType,
view: 'history',
asOf: timelineNow,
limit: historyLimit,
page: historyPage,
sort: 'desc',
includeResults: true,
});
if (!DEFAULT_COMMUNITY_ID) {
return (
<PlainPage className="lts-overview py-16">
<ErrorNote
title="커뮤니티가 설정되지 않았습니다"
description="apps/web/.env.development의 VITE_DEFAULT_COMMUNITY_ID를 먼저 설정해주세요."
/>
</PlainPage>
);
}
const allUpcomingMatches = upcomingMatchesQuery.data ?? [];
const [nextMatch, ...upcomingMatches] = allUpcomingMatches;
const bannerMatch = showArchive ? undefined : nextMatch;
const isBannerLoading = !showArchive && upcomingMatchesQuery.isPending;
const visibleUpcomingMatches = showArchive ? allUpcomingMatches : upcomingMatches;
const historyTotal = historyMatchesQuery.data?.total ?? 0;
const activeTotal = activeMatchesQuery.data?.total ?? 0;
const activePageCount = Math.max(
1,
Math.ceil(activeTotal / (activeMatchesQuery.data?.limit ?? activeLimit)),
);
const historyPageCount = Math.max(
1,
Math.ceil(historyTotal / (historyMatchesQuery.data?.limit ?? historyLimit)),
);
const isHistoryPageLoading =
historyMatchesQuery.isPending ||
(historyMatchesQuery.isFetching && historyMatchesQuery.isPlaceholderData);
const isActivePageLoading =
activeMatchesQuery.isPending ||
(activeMatchesQuery.isFetching && activeMatchesQuery.isPlaceholderData);
const hasHistoryError =
Boolean(historyMatchesQuery.error) && !historyMatchesQuery.data;
const statsPath = `/communities/${DEFAULT_COMMUNITY_ID}/internal-stats`;
const UpcomingStatusHeading = showArchive ? 'p' : 'h1';
const contentSpacing = 'space-y-8 pb-10 md:pb-16';
const contentTopPadding = bannerMatch || isBannerLoading ? 'pt-10 md:pt-16' : 'pt-5 sm:pt-6';
const content = (
<div className={`${pageWidthClass()} ${contentSpacing} ${contentTopPadding}`}>
{showArchive && (
<header>
<h1 className="text-2xl font-bold">{eventLabel} 일정</h1>
</header>
)}
{activeMatchesQuery.isError && !activeMatchesQuery.data ? (
<ErrorNote title="진행 중인 일정을 불러오지 못했습니다"
action={<Button size="sm" label="다시 시도" onClick={() => void activeMatchesQuery.refetch()} />} />
) : isActivePageLoading ? (
<UpcomingMatchesSkeleton
title="진행 중인 일정"
limit={activeMatchesQuery.data?.matches.length || activeLimit}
/>
) : activeMatchesQuery.data &&
(activeMatchesQuery.data.matches.length > 0 || activePage > 1) ? (
<UpcomingMatches
matches={activeMatchesQuery.data.matches}
title="진행 중인 일정"
actions={!showArchive && (
<Link
to="/inhouse"
className="inline-flex min-h-6 items-center gap-0.5 text-[13px] font-semibold text-content-muted hover:text-content hover:underline"
>
전체 일정
<ChevronRight className="size-4" aria-hidden="true" />
</Link>
)}
footer={showArchive && (activePageCount > 1 || activePage > 1) && (
<MatchPagination
label="진행 중인 일정 페이지"
page={activePage}
pageCount={activePageCount}
total={activeTotal}
isFetching={activeMatchesQuery.isFetching}
onPrevious={() => setPage('activePage', Math.min(activePage - 1, activePageCount))}
onNext={() => setPage('activePage', activePage + 1)}
/>
)}
/>
) : null}
{upcomingMatchesQuery.isPending ? (
<UpcomingMatchesSkeleton
title={showArchive ? '다가오는 일정' : '이어지는 내전'}
limit={showArchive ? UPCOMING_MATCH_LIST_LIMIT : UPCOMING_MATCH_LIST_LIMIT - 1}
/>
) : upcomingMatchesQuery.isError && !upcomingMatchesQuery.data ? (
<div className="flex flex-wrap items-center gap-3">
<UpcomingStatusHeading className="text-sm text-content-muted">
{eventLabel} 일정을 불러오지 못했습니다
</UpcomingStatusHeading>
<button
type="button"
className="min-h-8 text-sm font-semibold underline"
onClick={() => void upcomingMatchesQuery.refetch()}
>
다시 시도
</button>
</div>
) : !nextMatch ? (
<UpcomingStatusHeading className="text-sm text-content-muted">
예정된 {eventLabel}이 없습니다
</UpcomingStatusHeading>
) : null}
{visibleUpcomingMatches.length > 0 && (
<UpcomingMatches
matches={visibleUpcomingMatches}
title={showArchive ? '다가오는 일정' : undefined}
/>
)}
<div
className={
showArchive
? undefined
: 'grid items-start gap-8 lg:grid-cols-[minmax(0,1fr)_20rem]'
}
>
<section aria-busy={isHistoryPageLoading} aria-live="polite">
<PanelHeader
title={showArchive ? '종료된 일정과 결과' : '최근 내전 결과'}
variant="section"
actions={
<Link
to={showArchive ? statsPath : '/inhouse'}
className="inline-flex items-center gap-0.5 text-[13px] font-semibold text-content-muted hover:text-content hover:underline"
>
{showArchive ? '전적 검색' : '전체 내전 기록'}
<ChevronRight className="size-4" aria-hidden="true" />
</Link>
}
/>
{isHistoryPageLoading ? (
<>
<span role="status" className="sr-only">{showArchive ? '종료된 일정과 결과' : '최근 내전 결과'}를 불러오는 중</span>
{showArchive ? (
<ScheduleRowsSkeleton limit={historyLimit} resultBelowOnMobile />
) : (
<RecentMatchResultsSkeleton limit={historyLimit} />
)}
</>
) : hasHistoryError ? (
<div className="p-4">
<ErrorNote
title={`지난 ${eventLabel} 기록을 불러오지 못했습니다`}
action={
<Button
label="다시 시도"
size="sm"
variant="secondary"
onClick={() => void historyMatchesQuery.refetch()}
/>
}
/>
</div>
) : showArchive ? (
<HistoryRecords
matches={historyMatchesQuery.data?.matches ?? []}
eventLabel={eventLabel}
/>
) : (
<RecentMatchResults matches={historyMatchesQuery.data?.matches ?? []} />
)}
{showArchive && !hasHistoryError && (historyTotal > 0 || historyPage > 1) && (
<MatchPagination
label="종료된 일정 페이지"
page={historyPage}
pageCount={historyPageCount}
total={historyTotal}
isFetching={historyMatchesQuery.isFetching}
onPrevious={() => setPage('page', Math.min(historyPage - 1, historyPageCount))}
onNext={() => setPage('page', historyPage + 1)}
/>
)}
</section>
{!showArchive && <RankingPreview statsPath={statsPath} />}
</div>
</div>
);
return (
<main className="[--color-skeleton:var(--color-text-disabled)]">
{isBannerLoading ? <NextMatchSkeleton /> : bannerMatch && <NextMatch match={bannerMatch} />}
{content}
{!showArchive && (
<HomeHallOfFame introReady={!upcomingMatchesQuery.isPending} />
)}
</main>
);
}