feat: improve tournament workflows and prune outdated docs

This commit is contained in:
dahyeon committed 2026-11-10 15:31:19 +09:00
1 parent da7b502936
commit 38a89b5374
53 files changed
+3308 -3276

No files matched your search

+51 -42
View File
@@ -1263,9 +1263,7 @@ function PlayerSpotlight({
);
}
// serverTimeOffsetMs는 5초마다 갱신되지만 비교자에 넣지 않는다. deadline이 바뀌는
// 순간(phase/currentBid 변화)에 항상 함께 리렌더되어 최신 offset이 반영되므로,
// 굳이 5초마다 리렌더할 필요가 없다.
// 서버 시간 차이만 바뀐 폴링에서는 카드를 다시 렌더하지 않는다.
const MemoPlayerSpotlight = memo(
PlayerSpotlight,
(previous, next) =>
@@ -1277,6 +1275,8 @@ const MemoPlayerSpotlight = memo(
next.state.currentPlayer,
) &&
previous.state.phase === next.state.phase &&
previous.state.deadline === next.state.deadline &&
previous.state.maxTimer === next.state.maxTimer &&
previous.state.currentBid === next.state.currentBid &&
previous.state.currentBidder?.teamIndex ===
next.state.currentBidder?.teamIndex &&
@@ -1293,6 +1293,8 @@ function PlayerProfileDetails({
bidStatus?: React.ReactNode;
}) {
const { data: ddragon } = useDdragonManifest();
const [historyPlayerId, setHistoryPlayerId] = useState<string>();
const isHistoryOpen = historyPlayerId === player.userId;
const [tabState, setTabState] = useState<{
playerId: string;
tab: PlayerProfileTab;
@@ -1311,7 +1313,7 @@ function PlayerProfileDetails({
player.userId,
{ queueGroup: "internal" },
DEFAULT_COMMUNITY_ID,
activeTab === "internal",
isHistoryOpen && activeTab === "internal",
);
const internalFirstPage = internalHistoryQuery.data?.pages[0];
const tierHistory =
@@ -1384,7 +1386,15 @@ function PlayerProfileDetails({
</div>
{bidStatus}
{import.meta.env.DEV && bidStatus ? (
<details
key={player.userId}
className="border-t border-line"
onToggle={(event) => setHistoryPlayerId(event.currentTarget.open ? player.userId : undefined)}
>
<summary className="cursor-pointer px-4 py-3 text-sm font-semibold text-content hover:bg-sunken">
선수 전적 보기
</summary>
{isHistoryOpen && (bidStatus ? (
<AuctionAstryxTabs<PlayerProfileTab>
label="선수 전적 종류"
value={activeTab}
@@ -1419,7 +1429,8 @@ function PlayerProfileDetails({
</div>
<div className={historyPanelClass}>{historyPanel}</div>
</>
)}
))}
</details>
</>
);
}
@@ -1624,7 +1635,7 @@ function PlayerBidStatus({
<div className="flex items-center justify-between px-4 py-3">
<div className="flex flex-col gap-0.5">
<span className="text-xs text-base-content/30 uppercase tracking-wider font-semibold">
{isSold ? "낙찰가" : "현재 입찰가"}
{isSold ? "낙찰가" : "현재 최고가"}
</span>
<span
className={`text-xs font-bold ${statusTone}`}
@@ -1724,18 +1735,10 @@ function BidControls({
if (state.phase !== "bidding") return null;
if (!activeTeam) {
return (
<div className="border border-base-content/10 bg-base-100 px-4 py-3 text-sm text-base-content/40">
관전자 모드입니다. 우측 상단에서 조작자 역할을 선택하면 입찰할 수
있습니다.
</div>
);
}
if (!activeTeam) return null;
// 경매는 "현재가보다 얼마 더?"로 생각하므로 절대값이 아니라 증분 프리셋으로 제공한다.
const bidIncrements = [10, 50, 100, 200];
const teamTone = teamIndexColorClasses(activeTeam.teamIndex);
const handlePlaceBid = () => onBid(activeTeam.teamIndex, effectiveBidAmount);
const isBidDisabled =
isBidPending ||
@@ -1751,15 +1754,14 @@ function BidControls({
? "입찰 마감 확인 중"
: !canAffordNextBid
? `입찰 불가 (다음 ${formatPoints(minBid)}P · 최대 ${formatPoints(maxBid)}P)`
: `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 입찰 (${formatPoints(effectiveBidAmount)}P)`;
const bidButtonToneClassName = `${teamTone.border} ${teamTone.bg} ${teamTone.text} hover:bg-base-content/5`;
: `${formatPoints(effectiveBidAmount)}P 입찰`;
return (
<>
<div className="border border-base-content/10 bg-base-100 p-4">
<div className="lts-panel p-4" aria-label={`${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 입찰`}>
<div className="mb-3 grid grid-cols-2 gap-2 text-xs sm:grid-cols-3">
<div className="border border-base-content/10 px-2.5 py-2">
<div className="text-base-content/30">보유</div>
<div className="text-content-muted">잔여 포인트</div>
<div className="mt-0.5 font-bold tabular-nums text-base-content">
{formatPoints(activeTeam.points)}P
</div>
@@ -1816,6 +1818,7 @@ function BidControls({
{/* 타이핑 중에는 클램프하지 않고(자릿수 입력 방해 방지) blur 시점에만 보정한다. */}
<input
type="number"
aria-label="입찰 포인트"
value={bidAmount}
onChange={(event) => setBidAmount(Number(event.target.value))}
onBlur={(event) =>
@@ -1832,24 +1835,26 @@ function BidControls({
className="lts-input w-24 tabular-nums text-right"
/>
</div>
<button
<Btn
onClick={handlePlaceBid}
disabled={isBidDisabled}
className={`w-full py-2 text-xs font-bold uppercase tracking-wide border transition-colors disabled:opacity-30 disabled:cursor-not-allowed ${bidButtonToneClassName}`}
variant="primary"
className="w-full min-h-11"
>
{bidButtonLabel}
</button>
</Btn>
</div>
{/* 모바일 sticky 입찰 바: 스크롤 위치와 무관하게 항상 입찰 가능하게 한다. */}
<div className="fixed inset-x-0 bottom-0 z-40 border-t border-base-content/10 bg-base-100/95 px-4 pt-3 pb-[calc(env(safe-area-inset-bottom)+0.75rem)] backdrop-blur xl:hidden">
<button
<Btn
onClick={handlePlaceBid}
disabled={isBidDisabled}
className={`w-full py-3 text-sm font-bold uppercase tracking-wide border transition-colors disabled:opacity-30 disabled:cursor-not-allowed ${bidButtonToneClassName}`}
variant="primary"
className="w-full min-h-11"
>
{bidButtonLabel}
</button>
</Btn>
</div>
</>
);
@@ -1867,12 +1872,13 @@ function BidLog({ bids }: { bids: AuctionStateView["bids"] }) {
if (bids.length === 0) return null;
return (
<div className="border border-base-content/10 bg-base-100 overflow-hidden">
<div className="px-3 py-1.5 border-b border-base-content/8 bg-base-200/40">
<span className="text-xs font-bold uppercase tracking-wider text-base-content/30">
입찰 기록
</span>
</div>
<details className="lts-panel overflow-hidden" onToggle={(event) => {
const list = scrollRef.current;
if (event.currentTarget.open && list) list.scrollTop = list.scrollHeight;
}}>
<summary className="cursor-pointer px-4 py-3 text-sm font-semibold hover:bg-sunken">
입찰 기록 · {bids.length}건
</summary>
<div ref={scrollRef} className="max-h-28 overflow-y-auto p-2 space-y-0.5">
{bids.map((bid, index) => (
<div
@@ -1891,7 +1897,7 @@ function BidLog({ bids }: { bids: AuctionStateView["bids"] }) {
</div>
))}
</div>
</div>
</details>
);
}
@@ -2401,15 +2407,6 @@ export default function AuctionPage() {
visualPreview={visualPreview}
/>
{auctionState.phase === "sold" && auctionState.currentBidder && (
<div
className={`text-center py-3 border text-sm font-bold ${`${teamIndexColorClasses(auctionState.currentBidder.teamIndex).border} ${teamIndexColorClasses(auctionState.currentBidder.teamIndex).bg} ${teamIndexColorClasses(auctionState.currentBidder.teamIndex).text}`}`}
>
{teamIndexLabel(auctionState.currentBidder.teamIndex)} 낙찰 —{" "}
{formatPoints(auctionState.currentBid)}P
</div>
)}
<BidControls
state={auctionState}
captainRole={captainRole}
@@ -2422,6 +2419,18 @@ export default function AuctionPage() {
})
}
/>
<section className="auction-team-summary lts-panel px-4 py-3" aria-label="팀 포인트 요약">
<h2 className="text-sm font-bold">팀 포인트</h2>
<ul className="mt-2 grid grid-cols-2 gap-x-4 gap-y-2 text-sm">
{auctionState.teams.map((team) => (
<li key={team.teamIndex} className="flex flex-wrap items-baseline justify-between gap-x-1 border-t border-line pt-2">
<span className="min-w-0 break-words text-content-muted">{teamIndexLabel(team.teamIndex, team.name)}</span>
<strong className="tabular">{formatPoints(team.points)}P</strong>
<span className="basis-full text-xs text-content-muted">{getAuctionTeamSize(team)}/{AUCTION_MAX_TEAM_SIZE}명</span>
</li>
))}
</ul>
</section>
<MemoBidLog bids={auctionState.bids} />
{canManageAuction && (
File diff suppressed because it is too large. Load diff
+413 -422
View File
@@ -1,149 +1,252 @@
import { useState } from 'react';
import {
CalendarDays,
ChevronLeft,
ChevronRight,
Map as MapIcon,
Users,
} from 'lucide-react';
import { Link } from 'react-router';
import { mapApiMatchToMatchDetail } from '../api/mappers';
import { useCommunity, useMatches, useMatchesPage } from '../api/hooks';
import type {
MatchDetailResponse,
MatchSummaryResponse,
} from '@lolympus/contracts';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { Link, useSearchParams } from 'react-router';
import { useMatches, useMatchesPage } from '../api/hooks';
import { mapIdToLabel } from '../api/mappers';
import { DEFAULT_COMMUNITY_ID } from '../config';
import {
Button,
EmptyNote,
ErrorNote,
MetaDot,
PageBody,
PageHero,
Panel,
PanelHeader,
Pill,
PlainPage,
Skeleton,
type PillTone,
} from '../ui';
import {
getHistoryMatchTitle,
getHomeMatchEnrollment,
getHomeMatchSchedule,
HOME_MATCH_STATUS,
} from './home-match-presentation';
const UPCOMING_GRID_MATCH_LIMIT = 3;
const UPCOMING_MATCH_LIST_LIMIT = UPCOMING_GRID_MATCH_LIMIT + 1;
const UPCOMING_MATCH_LIST_LIMIT = 4;
const HISTORY_MATCH_PAGE_SIZE = 10;
const HOME_HISTORY_LIMIT = 5;
const DEFAULT_MAP_ID = 11;
const STATUS_PRESENTATION: Record<
string,
{ label: string; tone: PillTone; live?: boolean }
> = {
recruiting: { label: '모집중', tone: 'live', live: true },
'team-built': { label: '팀빌딩', tone: 'gold' },
'in-progress': { label: '진행중', tone: 'accent', live: true },
finished: { label: '종료', tone: 'neutral' },
};
const DECISION_LABELS = {
walkover: '부전승',
forfeit: '기권승',
administrative: '판정승',
draw: '무승부',
} as const;
function StatusPill({ status, onInk }: { status: string; onInk?: boolean }) {
const presentation = STATUS_PRESENTATION[status] ?? {
label: status,
tone: 'neutral' as const,
};
const tone =
onInk && presentation.tone === 'neutral' ? 'ink' : presentation.tone;
function NextMatch({ match }: { match?: MatchDetailResponse }) {
if (!match) {
return (
<h1 className="text-sm font-medium text-content-muted">
예정된 내전이 없습니다
</h1>
);
}
const schedule = getHomeMatchSchedule(match.scheduledAt);
const enrollment = getHomeMatchEnrollment(match);
const href = `/match/${match._id}`;
return (
<Pill tone={tone} dot={presentation.live} pulse={presentation.live}>
{presentation.label}
</Pill>
<header className="flex flex-col gap-3 rounded-xl border border-line bg-card p-4 sm:flex-row sm:items-center sm:justify-between sm:gap-6 sm:p-5">
<div className="min-w-0">
<p className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5 text-sm text-content-muted">
<span className="font-semibold">다음 내전</span>
{schedule && (
<time
dateTime={match.scheduledAt}
className="tabular font-semibold text-content"
>
{schedule.date} · {schedule.time}
</time>
)}
</p>
<h1 className="mt-1 break-words text-xl font-bold leading-snug sm:text-2xl">
{match.title}
</h1>
<p className="tabular mt-1 flex flex-wrap items-baseline gap-x-2 gap-y-0.5 text-sm text-content-muted">
{match.status !== 'recruiting' && (
<span>{HOME_MATCH_STATUS[match.status]} ·</span>
)}
<span>{enrollment.capacity} ·</span>
<strong className="font-semibold text-content">
{enrollment.label}
</strong>
{match.mapId !== DEFAULT_MAP_ID && (
<span>· {mapIdToLabel(match.mapId)}</span>
)}
</p>
</div>
{enrollment.canApply ? (
<div className="shrink-0">
<Button label="참가 신청" variant="primary" size="md" href={href} />
</div>
) : (
<Link
to={href}
className="inline-flex min-h-10 w-fit shrink-0 items-center gap-1 text-sm font-semibold text-content hover:underline"
>
내전 보기
<ChevronRight className="size-4" aria-hidden="true" />
</Link>
)}
</header>
);
}
function formatCompactDateTime(dateLike: string) {
const date = new Date(dateLike);
if (Number.isNaN(date.getTime())) return '';
const weekday = new Intl.DateTimeFormat('ko-KR', {
weekday: 'short',
}).format(date);
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${date.getMonth() + 1}/${date.getDate()} (${weekday}) ${hours}:${minutes}`;
function UpcomingMatches({ matches }: { matches: MatchDetailResponse[] }) {
return (
<Panel>
<PanelHeader title="이어지는 내전" />
<ul className="divide-y divide-line">
{matches.map((match) => {
const schedule = getHomeMatchSchedule(match.scheduledAt);
const { capacity, label } = getHomeMatchEnrollment(match);
return (
<li key={match._id}>
<Link
to={`/match/${match._id}`}
className="group grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 px-4 py-3 transition-colors hover:bg-sunken sm:grid-cols-[8rem_minmax(0,1fr)_auto_1rem] sm:px-5"
>
<time
dateTime={match.scheduledAt}
className="tabular col-start-1 text-xs text-content-muted"
>
{schedule?.compact ?? '일정 미정'}
</time>
<h3 className="col-start-1 mt-0.5 truncate text-[15px] font-semibold text-content group-hover:underline sm:col-start-2 sm:row-start-1 sm:mt-0">
{match.title}
</h3>
<p className="tabular col-start-1 mt-1 text-[13px] text-content-muted sm:col-start-3 sm:row-start-1 sm:mt-0">
{match.status === 'recruiting'
? label
: HOME_MATCH_STATUS[match.status]}{' '}
· {capacity}
</p>
<ChevronRight
className="col-start-2 row-span-3 row-start-1 size-4 text-content-muted sm:col-start-4 sm:row-span-1"
aria-hidden="true"
/>
</Link>
</li>
);
})}
</ul>
</Panel>
);
}
/** 정원 대비 신청 인원. 숫자와 막대를 함께 보여 남은 자리를 바로 읽게 한다. */
function CapacityMeter({
current,
max,
onInk = false,
}: {
current: number;
max: number;
onInk?: boolean;
}) {
const ratio = max > 0 ? Math.min(1, current / max) : 0;
const isFull = max > 0 && current >= max;
return (
<span className="inline-flex items-center gap-2">
<span className="tabular whitespace-nowrap">
<strong className={onInk ? 'text-on-ink' : 'text-content'}>
{current}
</strong>
/{max}명
</span>
<span
aria-hidden="true"
className={`h-1.5 w-16 overflow-hidden rounded-full ${onInk ? 'bg-white/15' : 'bg-sunken-strong'}`}
function HistoryResult({ match }: { match: MatchSummaryResponse }) {
const result = match.historyResult;
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="min-w-0 break-words text-content-muted md:truncate"
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="min-w-0 break-words text-content-muted md:truncate"
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="min-w-0 break-words text-content-muted md:truncate"
title={result.winnerTeamName}
>
{result.winnerTeamName}
</span>
)}
</span>
);
}
}
}
if (match.status === 'team-built' || match.status === 'in-progress') {
return (
<Pill
tone={match.status === 'in-progress' ? 'live' : 'neutral'}
dot={match.status === 'in-progress'}
>
<span
className={`block h-full rounded-full ${isFull ? 'bg-brand-coral' : 'bg-brand-leaf'}`}
style={{ width: `${ratio * 100}%` }}
/>
</span>
{HOME_MATCH_STATUS[match.status]}
</Pill>
);
}
return (
<span className="text-content-muted">
{HOME_MATCH_STATUS[match.status]}
</span>
);
}
function HistoryTableColGroup() {
return (
<colgroup>
<col className="w-[168px]" />
<col />
<col className="w-[96px]" />
<col className="w-[132px]" />
<col className="w-[72px]" />
</colgroup>
);
}
function HistoryTableHeader() {
return (
<thead>
<tr>
<th scope="col">날짜</th>
<th scope="col">내전</th>
<th scope="col">상태</th>
<th scope="col">맵</th>
<th scope="col" className="!text-right">
참가
</th>
</tr>
</thead>
);
}
function HistoryRecordsSkeleton({
rows = HISTORY_MATCH_PAGE_SIZE,
}: {
rows?: number;
}) {
const historySkeletons = Array.from({ length: rows });
function HistoryTableColumns() {
return (
<>
<div className="hidden overflow-x-auto md:block">
<table className="lts-table table-fixed">
<HistoryTableColGroup />
<HistoryTableHeader />
<colgroup>
<col className="w-36" />
<col />
<col className="w-44" />
<col className="w-16" />
</colgroup>
<thead>
<tr>
<th scope="col">일정</th>
<th scope="col">내전</th>
<th scope="col">결과</th>
<th scope="col" className="!text-right">
참가
</th>
</tr>
</thead>
</>
);
}
function HistoryRecordsSkeleton({ limit }: { limit: number }) {
const rows = Array.from({ length: limit });
return (
<>
<div className="hidden md:block">
<table className="lts-table table-fixed" aria-hidden="true">
<HistoryTableColumns />
<tbody>
{historySkeletons.map((_, index) => (
{rows.map((_, index) => (
<tr key={index}>
<td>
<Skeleton width={96} height={14} index={index} />
@@ -152,10 +255,7 @@ function HistoryRecordsSkeleton({
<Skeleton width="60%" height={14} index={index} />
</td>
<td>
<Skeleton width={48} height={20} radius="rounded" />
</td>
<td>
<Skeleton width={80} height={14} index={index} />
<Skeleton width={56} height={14} index={index} />
</td>
<td>
<Skeleton width={28} height={14} className="ml-auto" />
@@ -165,8 +265,8 @@ function HistoryRecordsSkeleton({
</tbody>
</table>
</div>
<div className="divide-y divide-line md:hidden">
{historySkeletons.map((_, index) => (
<div className="divide-y divide-line md:hidden" aria-hidden="true">
{rows.map((_, index) => (
<div key={index} className="space-y-2 px-4 py-3">
<Skeleton width={110} height={12} index={index} />
<Skeleton width="70%" height={16} index={index} />
@@ -177,22 +277,78 @@ function HistoryRecordsSkeleton({
);
}
function HomePageSkeleton() {
function HistoryRecords({ matches }: { matches: MatchSummaryResponse[] }) {
if (matches.length === 0) {
return <EmptyNote size="sm" title="아직 내전 기록이 없습니다." />;
}
const rows = matches.map((match) => {
const schedule = getHomeMatchSchedule(match.scheduledAt);
return {
match,
title: getHistoryMatchTitle(match.title, schedule),
href: `/match/${match._id}`,
schedule: schedule?.compact ?? '일정 미정',
map:
match.mapId === DEFAULT_MAP_ID ? undefined : mapIdToLabel(match.mapId),
};
});
return (
<div aria-busy="true" aria-live="polite">
<span className="sr-only">매치 목록을 불러오는 중...</span>
<PageHero
eyebrow="다음 내전"
title={<span className="opacity-0">내전을 불러오는 중</span>}
meta={<span className="opacity-0">일정</span>}
/>
<PageBody className="space-y-5">
<Panel>
<PanelHeader title="지난 내전" />
<HistoryRecordsSkeleton />
</Panel>
</PageBody>
</div>
<>
<div className="hidden md:block">
<table className="lts-table table-fixed">
<HistoryTableColumns />
<tbody>
{rows.map(({ match, title, href, schedule, map }) => (
<tr key={match._id} className="transition-colors hover:bg-sunken">
<td className="tabular whitespace-nowrap text-[13px] text-content-muted">
<time dateTime={match.scheduledAt}>{schedule}</time>
</td>
<td>
<Link
to={href}
className="block truncate font-semibold text-content hover:underline"
title={match.title}
>
{title}
</Link>
{map && <p className="text-xs text-content-muted">{map}</p>}
</td>
<td className="text-[13px]">
<HistoryResult match={match} />
</td>
<td className="tabular whitespace-nowrap text-right text-[13px] text-content-muted">
{match.participants.length}명
</td>
</tr>
))}
</tbody>
</table>
</div>
<ul className="divide-y divide-line md:hidden">
{rows.map(({ match, title, href, schedule, map }) => (
<li key={match._id}>
<Link
to={href}
className="group block px-4 py-3 transition-colors hover:bg-sunken"
>
<div className="tabular flex flex-wrap justify-between gap-x-3 text-xs text-content-muted">
<time dateTime={match.scheduledAt}>{schedule}</time>
<span>{match.participants.length}명</span>
</div>
<p className="mt-0.5 break-words text-[15px] font-semibold leading-snug text-content group-hover:underline">
{title}
</p>
<div className="mt-1 flex flex-wrap items-baseline gap-x-2 gap-y-1 text-[13px]">
<HistoryResult match={match} />
{map && <span className="text-content-muted">· {map}</span>}
</div>
</Link>
</li>
))}
</ul>
</>
);
}
@@ -213,13 +369,10 @@ function HistoryPagination({
onPrevious,
onNext,
}: HistoryPaginationProps) {
const hasPrevious = page > 1;
const hasNext = page < pageCount;
return (
<div className="flex items-center justify-between gap-3 border-t border-line px-4 py-2.5 sm:px-5">
<span className="tabular text-xs text-content-subtle">
총 {total}개 · {page} / {pageCount}
<div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1 border-t border-line px-4 py-2.5 sm:px-5">
<span className="tabular text-xs text-content-muted">
총 {total.toLocaleString('ko-KR')}개 · {page} / {pageCount}
</span>
<div className="flex items-center gap-1">
<Button
@@ -227,7 +380,7 @@ function HistoryPagination({
size="sm"
variant="ghost"
icon={<ChevronLeft className="size-4" aria-hidden="true" />}
isDisabled={!hasPrevious || isFetching}
isDisabled={page <= 1 || isFetching}
onClick={onPrevious}
/>
<Button
@@ -235,7 +388,7 @@ function HistoryPagination({
size="sm"
variant="ghost"
endContent={<ChevronRight className="size-4" aria-hidden="true" />}
isDisabled={!hasNext || isFetching}
isDisabled={page >= pageCount || isFetching}
onClick={onNext}
/>
</div>
@@ -245,29 +398,38 @@ function HistoryPagination({
export default function HomePage() {
const [timelineNow] = useState(() => new Date().toISOString());
const [historyPage, setHistoryPage] = useState(1);
const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID);
const upcomingMatchesQuery = useMatches(
{
limit: UPCOMING_MATCH_LIST_LIMIT,
scheduledFrom: timelineNow,
sort: 'asc',
},
DEFAULT_COMMUNITY_ID,
);
const historyMatchesQuery = useMatchesPage(
{
limit: HISTORY_MATCH_PAGE_SIZE,
page: historyPage,
scheduledTo: timelineNow,
sort: 'desc',
},
DEFAULT_COMMUNITY_ID,
);
const [searchParams, setSearchParams] = useSearchParams();
const showArchive = searchParams.get('history') === 'all';
const requestedPage = Number(searchParams.get('page'));
const historyPage =
showArchive && Number.isSafeInteger(requestedPage) && requestedPage > 0
? requestedPage
: 1;
const historyLimit = showArchive
? HISTORY_MATCH_PAGE_SIZE
: HOME_HISTORY_LIMIT;
function setHistoryPage(page: number) {
const params = new URLSearchParams(searchParams);
if (page > 1) params.set('page', String(page));
else params.delete('page');
setSearchParams(params, { preventScrollReset: true });
}
const upcomingMatchesQuery = useMatches({
limit: UPCOMING_MATCH_LIST_LIMIT,
scheduledFrom: timelineNow,
sort: 'asc',
});
const historyMatchesQuery = useMatchesPage({
limit: historyLimit,
page: historyPage,
scheduledTo: timelineNow,
sort: 'desc',
includeResults: true,
});
if (!DEFAULT_COMMUNITY_ID) {
return (
<PlainPage className="py-16">
<PlainPage className="lts-overview py-16">
<ErrorNote
title="커뮤니티가 설정되지 않았습니다"
description="apps/web/.env.development의 VITE_DEFAULT_COMMUNITY_ID를 먼저 설정해주세요."
@@ -276,277 +438,106 @@ export default function HomePage() {
);
}
if (upcomingMatchesQuery.isLoading) {
return <HomePageSkeleton />;
}
if (upcomingMatchesQuery.error) {
return (
<PlainPage className="py-16">
<ErrorNote
title="매치 목록을 불러오지 못했습니다"
action={
<Button
label="다시 시도"
size="sm"
variant="secondary"
onClick={() => void upcomingMatchesQuery.refetch()}
/>
}
/>
</PlainPage>
);
}
const upcomingMatches =
upcomingMatchesQuery.data?.map(mapApiMatchToMatchDetail) ?? [];
const historyMatches =
historyMatchesQuery.data?.matches.map((match) => ({
...mapApiMatchToMatchDetail(match),
rawStatus: match.status,
compactDateTime: formatCompactDateTime(match.scheduledAt),
})) ?? [];
const [nextMatch, ...upcomingMatches] = upcomingMatchesQuery.data ?? [];
const historyTotal = historyMatchesQuery.data?.total ?? 0;
const historyLimit =
historyMatchesQuery.data?.limit ?? HISTORY_MATCH_PAGE_SIZE;
const historyPageCount = Math.max(1, Math.ceil(historyTotal / historyLimit));
const historyPageCount = Math.max(
1,
Math.ceil(historyTotal / (historyMatchesQuery.data?.limit ?? historyLimit)),
);
const isHistoryPageLoading =
historyMatchesQuery.isLoading ||
(historyMatchesQuery.isFetching && historyMatchesQuery.isPlaceholderData);
const hasHistoryError =
Boolean(historyMatchesQuery.error) && !historyMatchesQuery.data;
const goToPreviousHistoryPage = () =>
setHistoryPage((page) => Math.max(1, page - 1));
const goToNextHistoryPage = () => setHistoryPage((page) => page + 1);
const nextMatch = upcomingMatches[0];
const upcomingCards = upcomingMatches.slice(1, 1 + UPCOMING_GRID_MATCH_LIMIT);
const statsPath = `/communities/${DEFAULT_COMMUNITY_ID}/internal-stats`;
const communityName = communityQuery.data?.name ?? 'LOLYMPUS';
return (
<>
{nextMatch ? (
<PageHero
eyebrow="다음 내전"
title={
<Link to={`/match/${nextMatch.id}`} className="hover:underline">
{nextMatch.title}
</Link>
}
badges={<StatusPill status={nextMatch.status} onInk />}
meta={
<>
<span className="inline-flex items-center gap-1.5">
<CalendarDays className="size-4" aria-hidden="true" />
{nextMatch.date} {nextMatch.time}
</span>
<MetaDot />
<span className="inline-flex items-center gap-1.5">
<MapIcon className="size-4" aria-hidden="true" />
{nextMatch.map}
</span>
<MetaDot />
<span className="inline-flex items-center gap-1.5">
<Users className="size-4" aria-hidden="true" />
<CapacityMeter
current={nextMatch.participants.length}
max={nextMatch.maxParticipants}
onInk
/>
</span>
</>
}
description={nextMatch.description || undefined}
actions={
<Button
label={
nextMatch.status === 'recruiting'
? '참가 신청하러 가기'
: '내전 보기'
}
variant="primary"
size="lg"
href={`/match/${nextMatch.id}`}
/>
}
/>
<PlainPage className="lts-overview space-y-5 pt-5 pb-16 sm:pt-6">
{showArchive ? (
<div className="flex flex-wrap items-center justify-between gap-3">
<h1 className="text-2xl font-bold">전체 내전 일정</h1>
<Link to="/" className="text-sm font-semibold hover:underline">
내전 홈
</Link>
</div>
) : upcomingMatchesQuery.isLoading ? (
<h1 className="text-sm text-content-muted" aria-busy="true">
내전 일정을 불러오는 중
</h1>
) : upcomingMatchesQuery.isError && !upcomingMatchesQuery.data ? (
<div className="flex flex-wrap items-center gap-3">
<h1 className="text-sm text-content-muted">
내전 일정을 불러오지 못했습니다
</h1>
<button
type="button"
className="min-h-8 text-sm font-semibold underline"
onClick={() => void upcomingMatchesQuery.refetch()}
>
다시 시도
</button>
</div>
) : (
<PageHero
eyebrow={communityName}
title="예정된 내전이 없습니다"
meta="새 내전이 열리면 이곳에 가장 먼저 표시됩니다."
actions={
<Button
label="내전 전적 보기"
variant="primary"
size="lg"
href={statsPath}
/>
}
/>
<NextMatch match={nextMatch} />
)}
<PageBody className="space-y-5">
{upcomingCards.length > 0 && (
<Panel>
<PanelHeader title="이어지는 내전" count={upcomingCards.length} />
<ul className="grid divide-y divide-line sm:grid-cols-3 sm:divide-x sm:divide-y-0">
{upcomingCards.map((match) => (
<li key={match.id} className="min-w-0">
<Link
to={`/match/${match.id}`}
className="group block h-full px-4 py-4 transition-colors hover:bg-sunken sm:px-5"
>
<div className="flex items-start justify-between gap-2">
<h3 className="min-w-0 truncate text-[15px] font-bold text-content group-hover:text-primary">
{match.title}
</h3>
<StatusPill status={match.status} />
</div>
<p className="mt-2 text-[13px] text-content-muted">
{match.date} {match.time}
</p>
<div className="mt-1 flex items-center gap-2 text-[13px] text-content-subtle">
<span>{match.map}</span>
<MetaDot />
<CapacityMeter
current={match.participants.length}
max={match.maxParticipants}
/>
</div>
</Link>
</li>
))}
</ul>
</Panel>
)}
{!showArchive && upcomingMatches.length > 0 && (
<UpcomingMatches matches={upcomingMatches} />
)}
<Panel aria-busy={isHistoryPageLoading} aria-live="polite">
<PanelHeader
title="지난 내전"
count={historyTotal > 0 ? historyTotal : undefined}
actions={
<Link
to={statsPath}
className="inline-flex items-center gap-0.5 text-[13px] font-semibold text-primary hover:underline"
>
전적·순위 보기
<ChevronRight className="size-4" aria-hidden="true" />
</Link>
}
/>
{isHistoryPageLoading ? (
<HistoryRecordsSkeleton rows={HISTORY_MATCH_PAGE_SIZE} />
) : hasHistoryError ? (
<div className="p-4">
<ErrorNote
title="지난 내전 기록을 불러오지 못했습니다"
action={
<Button
label="다시 시도"
size="sm"
variant="secondary"
onClick={() => void historyMatchesQuery.refetch()}
/>
}
/>
</div>
) : (
<>
{/* 데스크톱: 표 */}
<div className="hidden overflow-x-auto md:block">
<table className="lts-table table-fixed">
<HistoryTableColGroup />
<HistoryTableHeader />
<tbody>
{historyMatches.length > 0 ? (
historyMatches.map((match) => (
<tr
key={match.id}
className="transition-colors hover:bg-sunken"
>
<td className="tabular whitespace-nowrap text-[13px] text-content-muted">
{match.compactDateTime || match.date}
</td>
<td>
<Link
to={`/match/${match.id}`}
className="block truncate font-semibold text-content hover:text-primary"
>
{match.title}
</Link>
</td>
<td>
<StatusPill status={match.rawStatus} />
</td>
<td className="truncate text-[13px] text-content-muted">
{match.map}
</td>
<td className="tabular whitespace-nowrap text-right text-[13px] text-content-muted">
{match.participants.length}명
</td>
</tr>
))
) : (
<tr>
<td colSpan={5}>
<EmptyNote
size="sm"
title="아직 내전 기록이 없습니다."
/>
</td>
</tr>
)}
</tbody>
</table>
</div>
{/* 모바일: 목록 */}
<div className="divide-y divide-line md:hidden">
{historyMatches.length > 0 ? (
historyMatches.map((match) => (
<Link
key={match.id}
to={`/match/${match.id}`}
className="block px-4 py-3 transition-colors hover:bg-sunken"
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="tabular text-xs text-content-subtle">
{match.compactDateTime ||
`${match.date} ${match.time}`}
</div>
<div className="mt-0.5 break-words text-[15px] font-semibold leading-snug text-content">
{match.title}
</div>
</div>
<StatusPill status={match.rawStatus} />
</div>
<div className="mt-1.5 flex items-center gap-2 text-xs text-content-subtle">
<span>{match.map}</span>
<MetaDot />
<span>{match.participants.length}명</span>
</div>
</Link>
))
) : (
<EmptyNote size="sm" title="아직 내전 기록이 없습니다." />
)}
</div>
</>
)}
{!hasHistoryError && historyTotal > 0 && (
<HistoryPagination
page={historyPage}
pageCount={historyPageCount}
total={historyTotal}
isFetching={historyMatchesQuery.isFetching}
onPrevious={goToPreviousHistoryPage}
onNext={goToNextHistoryPage}
<Panel aria-busy={isHistoryPageLoading} aria-live="polite">
<PanelHeader
title={showArchive ? '지난 일정 전체' : '최근 내전 일정'}
actions={
<Link
to={statsPath}
className="inline-flex 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>
}
/>
{isHistoryPageLoading ? (
<HistoryRecordsSkeleton limit={historyLimit} />
) : hasHistoryError ? (
<div className="p-4">
<ErrorNote
title="지난 내전 기록을 불러오지 못했습니다"
action={
<Button
label="다시 시도"
size="sm"
variant="secondary"
onClick={() => void historyMatchesQuery.refetch()}
/>
}
/>
)}
</Panel>
</PageBody>
</>
</div>
) : (
<HistoryRecords matches={historyMatchesQuery.data?.matches ?? []} />
)}
{showArchive && !hasHistoryError && historyTotal > 0 && (
<HistoryPagination
page={historyPage}
pageCount={historyPageCount}
total={historyTotal}
isFetching={historyMatchesQuery.isFetching}
onPrevious={() => setHistoryPage(Math.max(1, historyPage - 1))}
onNext={() => setHistoryPage(historyPage + 1)}
/>
)}
{!showArchive && historyTotal > HOME_HISTORY_LIMIT && (
<div className="border-t border-line px-4 py-2.5 text-right sm:px-5">
<Link
to="/?history=all"
className="text-sm text-content-muted hover:underline"
>
전체 일정 기록
</Link>
</div>
)}
</Panel>
</PlainPage>
);
}
+33 -62
View File
@@ -1,5 +1,5 @@
import { Link, useLocation, useParams } from "react-router";
import { useDdragonManifest, useInternalMatchDetail } from "../api/hooks";
import { useCompetition, useDdragonManifest, useInternalMatchDetail } from "../api/hooks";
import type { ApiInternalMatchDetailResponse, TeamSide } from "../api/types";
import { DEFAULT_COMMUNITY_ID } from "../config";
import {
@@ -11,6 +11,7 @@ import {
teamIndexLabel,
} from "../lib/league";
import { internalMatchGamePath } from "../lib/internal-match-routes";
import { groupRecordedSets } from "../lib/internal-match-series";
import { LANE_LABELS } from "../lib/riot-history";
import { ItemIcon } from "../components/ItemTooltip";
@@ -100,11 +101,13 @@ function GamePanel({
communityId,
matchId,
game,
ordinal,
manifest,
}: {
communityId: string;
matchId: string;
game: ApiInternalMatchDetailResponse["games"][number];
ordinal?: number;
manifest: ReturnType<typeof useDdragonManifest>["data"];
}) {
const location = useLocation();
@@ -114,9 +117,12 @@ function GamePanel({
<section className="lts-panel overflow-hidden">
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-line px-4 py-3 sm:px-5">
<div>
<h2 className="text-sm font-black text-base-content">
{game.gameNumber}경기
</h2>
<h3 className="text-sm font-black text-base-content">
{ordinal === undefined ? `전체 ${game.gameNumber}세트` : `${ordinal}세트`}
{ordinal !== undefined && ordinal !== game.gameNumber && (
<span className="ml-2 text-xs font-medium text-content-muted">전체 {game.gameNumber}</span>
)}
</h3>
<p className="mt-1 text-xs text-base-content/35">
{formatDateTime(game.gameCreation)} ·{" "}
{formatDuration(game.gameDuration)} ·{" "}
@@ -247,8 +253,14 @@ function GamePanel({
export default function InternalMatchDetailPage() {
const { cid, matchId } = useParams();
const location = useLocation();
const communityId = cid ?? DEFAULT_COMMUNITY_ID;
const requestedBack = location.state?.backTo;
const backTo = typeof requestedBack === "string" && requestedBack.startsWith("/") && !requestedBack.startsWith("//")
? requestedBack
: `/communities/${communityId}/internal-stats`;
const detailQuery = useInternalMatchDetail(matchId, communityId);
const competition = useCompetition(matchId, communityId);
const { data: ddragon } = useDdragonManifest();
const detail = detailQuery.data;
@@ -266,7 +278,7 @@ export default function InternalMatchDetailPage() {
<EmptyNote
title="내전 기록을 찾을 수 없습니다"
action={
<Btn to={`/communities/${communityId}/internal-stats`}>
<Btn to={backTo}>
내전 전적으로
</Btn>
}
@@ -275,20 +287,14 @@ export default function InternalMatchDetailPage() {
);
}
const isHeadToHead = detail.match.teams.length === 2;
const primarySeries = isHeadToHead ? detail.match.seriesResults[0] : undefined;
const teamName = (teamIndex: number) =>
teamIndexLabel(
teamIndex,
detail.match.teams.find((team) => team.teamIndex === teamIndex)?.name,
);
const groups = groupRecordedSets(detail, competition.data);
return (
<>
<PageHero
width="xl"
crumbs={[
{ label: "전적", to: `/communities/${communityId}/internal-stats` },
{ label: "전적", to: backTo },
{ label: detail.match.title },
]}
title={detail.match.title}
@@ -298,52 +304,13 @@ export default function InternalMatchDetailPage() {
<MetaDot />
<span>{detail.match.teams.length}팀</span>
<MetaDot />
<span>{detail.match.gameCount}경기</span>
<span>{detail.games.length}세트 수집</span>
</>
}
actions={
primarySeries ? (
<div
className="flex items-center gap-4"
aria-label={`시리즈 결과 ${teamName(primarySeries.teamAIndex)} ${primarySeries.teamAWins} 대 ${primarySeries.teamBWins} ${teamName(primarySeries.teamBIndex)}`}
>
<span
className={`max-w-32 truncate text-sm font-bold ${primarySeries.winnerTeamIndex === primarySeries.teamAIndex ? "text-on-ink" : "text-on-ink-muted"}`}
>
{teamName(primarySeries.teamAIndex)}
</span>
<span className="tabular flex items-baseline gap-2 text-4xl font-extrabold">
<span
className={
primarySeries.winnerTeamIndex === primarySeries.teamAIndex
? "text-brand-coral"
: "text-on-ink-muted"
}
>
{primarySeries.teamAWins}
</span>
<span className="text-xl text-on-ink-muted">:</span>
<span
className={
primarySeries.winnerTeamIndex === primarySeries.teamBIndex
? "text-brand-coral"
: "text-on-ink-muted"
}
>
{primarySeries.teamBWins}
</span>
</span>
<span
className={`max-w-32 truncate text-sm font-bold ${primarySeries.winnerTeamIndex === primarySeries.teamBIndex ? "text-on-ink" : "text-on-ink-muted"}`}
>
{teamName(primarySeries.teamBIndex)}
</span>
</div>
) : (
<Btn to={`/match/${detail.match.matchId}`} variant="primary">
대진표 보기
{detail.match.teams.length === 2 ? "내전 보기" : "대진표 보기"}
</Btn>
)
}
/>
<PageBody width="xl" className="space-y-4">
@@ -352,14 +319,18 @@ export default function InternalMatchDetailPage() {
<EmptyNote title="수집된 경기 기록이 없습니다" />
</Panel>
)}
{detail.games.map((game) => (
<GamePanel
key={game.riotMatchId}
communityId={communityId}
matchId={detail.match.matchId}
game={game}
manifest={ddragon}
/>
{groups.map((group) => (
<section key={group.id} className="space-y-3">
<h2 className="flex flex-wrap items-baseline gap-x-2 px-1 text-base font-bold">
{group.label}
<span className="text-xs font-medium text-content-muted">
{group.series ? "시리즈" : "대진"} · {group.sets.length}세트 수집
</span>
</h2>
{group.sets.map(({ game, official }) => (
<GamePanel key={game.riotMatchId} communityId={communityId} matchId={detail.match.matchId} game={game} ordinal={official?.ordinal} manifest={ddragon} />
))}
</section>
))}
</PageBody>
</>
+15 -2
View File
@@ -1,5 +1,6 @@
import { useMsal } from "@azure/msal-react";
import { KeyRound } from "lucide-react";
import { Link, useSearchParams } from "react-router";
import {
isMsalConfigured,
MSAL_API_SCOPE,
@@ -7,7 +8,7 @@ import {
} from "../lib/auth/msal.config";
import { Button, ErrorNote, PlainPage } from "../ui";
function LoginButton() {
function LoginButton({ returnPath }: { returnPath?: string }) {
const { instance } = useMsal();
return (
@@ -20,6 +21,9 @@ function LoginButton() {
void instance.loginRedirect({
scopes: [MSAL_API_SCOPE],
prompt: "select_account",
redirectStartPage: returnPath
? new URL(returnPath, window.location.origin).href
: undefined,
})
}
/>
@@ -27,6 +31,10 @@ function LoginButton() {
}
export default function LoginPage() {
const [params] = useSearchParams();
const next = params.get("next");
const returnPath = next && /^\/match\/[a-f\d]{24}$/i.test(next) ? next : undefined;
return (
<PlainPage width="md" className="py-16 sm:py-24">
<div className="lts-panel mx-auto max-w-sm p-6 sm:p-8">
@@ -40,7 +48,7 @@ export default function LoginPage() {
</p>
<div className="mt-6">
{isMsalConfigured && msalInstance ? (
<LoginButton />
<LoginButton returnPath={returnPath} />
) : (
<ErrorNote
title="로그인을 사용할 수 없습니다"
@@ -48,6 +56,11 @@ export default function LoginPage() {
/>
)}
</div>
{returnPath && (
<Link to={returnPath} className="mt-4 inline-block text-sm font-semibold text-primary hover:underline">
내전 상세로 돌아가기
</Link>
)}
</div>
</PlainPage>
);
+112 -43
View File
@@ -18,6 +18,7 @@ import {
MetaDot,
PageBody,
PageHero,
Panel,
Pill,
PlainPage,
type PillTone,
@@ -991,13 +992,80 @@ function AdminAddParticipantModal({
);
}
function MatchRegistration({
match,
canJoin,
checkingAccount,
initialPosition,
joining,
error,
onJoin,
}: {
match: MatchDetailView;
canJoin: boolean;
checkingAccount: boolean;
initialPosition: Position;
joining: boolean;
error: Error | null;
onJoin: (position: Position) => void;
}) {
const [selectedPosition, setSelectedPosition] = useState<Position>();
const position = selectedPosition ?? initialPosition;
const count = match.participants.length;
const remaining = Math.max(0, match.maxParticipants - count);
const progress = match.maxParticipants > 0 ? Math.min(100, count / match.maxParticipants * 100) : 0;
return (
<Panel className="mb-5 px-4 py-4 sm:px-5" aria-labelledby="match-registration-title">
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 id="match-registration-title" className="text-base font-bold">참가 신청</h2>
<Pill tone={match.joined ? "live" : remaining > 0 ? "neutral" : "gold"}>
{count}/{match.maxParticipants}명
</Pill>
</div>
<p className="mt-2 font-semibold" role="status">
{match.joined ? "참가 신청 완료" : remaining > 0 ? `${remaining}자리 남음` : "정원이 찼습니다"}
</p>
<div className="mt-2 h-2 overflow-hidden rounded-full bg-sunken-strong" aria-hidden="true">
<div className="h-full rounded-full bg-brand-coral" style={{ width: `${progress}%` }} />
</div>
{!match.joined && remaining > 0 && (
checkingAccount ? (
<p className="mt-4 text-sm text-content-muted">참가 권한을 확인하고 있습니다.</p>
) : canJoin ? (
<form className="mt-4 flex flex-wrap items-end justify-between gap-4" onSubmit={(event) => {
event.preventDefault();
if (!joining) onJoin(position);
}}>
<fieldset disabled={joining}>
<legend className="mb-2 text-sm font-semibold">1순위 희망 포지션</legend>
<div className="flex flex-wrap gap-2">
{POSITION_ORDER.map((role) => (
<label key={role} className="cursor-pointer">
<input type="radio" name="preferred-position" value={role} checked={role === position} onChange={() => setSelectedPosition(role)} className="peer sr-only" />
<span className="inline-flex min-h-9 items-center rounded-full border border-line-strong px-3 text-sm peer-checked:border-transparent peer-checked:bg-secondary peer-checked:text-secondary-content peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2">
{positionLabel[role]}
</span>
</label>
))}
</div>
</fieldset>
<Btn type="submit" variant="primary" size="lg" disabled={joining}>
{joining ? "신청 중…" : "참가 신청"}
</Btn>
</form>
) : (
<div className="mt-4"><Btn to={`/login?next=${encodeURIComponent(`/match/${match.id}`)}`} variant="primary">로그인하고 참가하기</Btn></div>
)
)}
{error && <ErrorNote className="mt-4" title="참가 신청을 완료하지 못했습니다" description={error.message} />}
</Panel>
);
}
function ParticipantTable({
participants,
maxParticipants,
joined,
canJoin,
onJoin,
isJoining,
canManage,
onOpenAddParticipant,
onRemoveParticipant,
@@ -1007,10 +1075,6 @@ function ParticipantTable({
}: {
participants: ParticipantView[];
maxParticipants: number;
joined: boolean;
canJoin: boolean;
onJoin: () => void;
isJoining: boolean;
canManage: boolean;
onOpenAddParticipant: () => void;
onRemoveParticipant: (userId: string) => void;
@@ -1078,13 +1142,6 @@ function ParticipantTable({
참가자 ({participants.length}/{maxParticipants})
</h3>
<div className="flex flex-wrap items-center justify-end gap-2">
<Btn
onClick={onJoin}
disabled={!canJoin || joined || isJoining}
variant="primary" size="sm"
>
{joined ? "참가 완료" : isJoining ? "신청 중..." : "참가 신청"}
</Btn>
{canManage && (
<Btn
onClick={onOpenAddParticipant}
@@ -1271,13 +1328,6 @@ function ParticipantTable({
</tbody>
</table>
</div>
{participants.length < maxParticipants && (
<div className="px-4 py-2.5 border-t border-base-content/5 text-center bg-base-200/20">
<span className="text-xs text-base-content/25">
{maxParticipants - participants.length}자리 남음
</span>
</div>
)}
</div>
);
}
@@ -1451,19 +1501,27 @@ export default function MatchDetailPage() {
const collectResultByRiotMatchMutation =
useCollectTournamentResultByRiotMatch(DEFAULT_COMMUNITY_ID);
const preferredPositions = currentUser?.preferredPositions.length
? [...currentUser.preferredPositions].sort((left, right) => left.priority - right.priority)
: buildDefaultPreferredPositions();
const matchQueryKey = matchQuery.queryKey;
const joinMatchMutation = useMutation({
mutationFn: () =>
apiFetch(
mutationFn: (position: Position) => {
const positions = [position, ...preferredPositions.map((entry) => entry.position)];
return apiFetch<MatchDetailResponse>(
`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants`,
{
method: "POST",
body: JSON.stringify({
preferredPositions: currentUser?.preferredPositions.length
? currentUser.preferredPositions.slice(0, 5)
: buildDefaultPreferredPositions(),
preferredPositions: [...new Set(positions)].slice(0, 5).map((entry, index) => ({
position: entry,
priority: index + 1,
})),
}),
},
),
);
},
onSuccess: async () => {
await Promise.all([
queryClient.invalidateQueries({
@@ -1474,10 +1532,11 @@ export default function MatchDetailPage() {
}),
]);
},
onError: () => {
void queryClient.invalidateQueries({ queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null] });
},
});
const matchQueryKey = matchQuery.queryKey;
const addParticipantMutation = useMutation({
mutationFn: ({
userId,
@@ -1791,6 +1850,8 @@ export default function MatchDetailPage() {
auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404;
const activeAuction = auctionNotStarted ? null : auctionQuery.data;
const showAuctionLink = Boolean(activeAuction);
const hasTeamProgress = Boolean(competitionQuery.data?.teams.length) &&
(match.status === "in-progress" || match.status === "finished");
const auctionParticipantPool = buildAuctionParticipantPool(
matchQuery.data.participants,
);
@@ -1929,16 +1990,27 @@ export default function MatchDetailPage() {
}
description={match.description || undefined}
actions={
showAuctionLink ? (
<Btn to={`/match/${match.id}/auction`} variant="primary" size="lg">
경매 보기
hasTeamProgress ? (
<Btn to={`/match/${match.id}/team`} variant="primary" size="lg">
팀 경기 현황
</Btn>
) : showAuctionLink && match.status !== "recruiting" ? (
<Btn to={`/match/${match.id}/auction`} variant="primary" size="lg">경매 보기</Btn>
) : undefined
}
/>
<PageBody>
{joinMatchMutation.error instanceof Error && (
<ErrorNote className="mb-4" title="요청을 처리하지 못했습니다" description={joinMatchMutation.error.message} />
<PageBody className={!usesTabbedLayout && match.status !== "recruiting" ? "pt-12" : undefined}>
{match.status === "recruiting" && (
<MatchRegistration
key={match.id}
match={match}
canJoin={canUseMemberActions}
checkingAccount={isCheckingPermissions && !canUseMemberActions}
initialPosition={preferredPositions[0]?.position ?? "TOP"}
joining={joinMatchMutation.isPending}
error={joinMatchMutation.error}
onJoin={joinMatchMutation.mutate}
/>
)}
{startAuctionMutation.error instanceof Error && (
@@ -2044,6 +2116,7 @@ export default function MatchDetailPage() {
{showCompetitionResults && (
<CompetitionResults
competition={competitionQuery.data}
showTeamLink={!hasTeamProgress}
view={
usesTabbedLayout
? activeMatchTab === "games"
@@ -2097,10 +2170,6 @@ export default function MatchDetailPage() {
<ParticipantTable
participants={match.participants}
maxParticipants={match.maxParticipants}
joined={match.joined}
canJoin={canUseMemberActions}
onJoin={() => joinMatchMutation.mutate()}
isJoining={joinMatchMutation.isPending}
canManage={canManageAuction}
onOpenAddParticipant={() => setAddParticipantOpen(true)}
onRemoveParticipant={(userId) =>
@@ -2480,13 +2549,13 @@ export default function MatchDetailPage() {
{match.teams.map((team) => (
<TeamCard key={team.teamIndex} team={team} />
))}
{showAuctionLink && (
{showAuctionLink && hasTeamProgress && (
<div className="flex justify-end">
<Btn
to={`/match/${match.id}/auction`}
variant="primary"
variant="secondary"
>
경매 페이지 열기
경매 기록 보기
</Btn>
</div>
)}
+75 -40
View File
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { Link, useLocation, useParams } from "react-router";
import { Link, useLocation, useNavigate, useParams } from "react-router";
import {
Area,
AreaChart,
@@ -13,7 +13,7 @@ import {
XAxis,
YAxis,
} from "recharts";
import { useDdragonManifest, useInternalMatchDetail } from "../api/hooks";
import { useCompetition, useDdragonManifest, useInternalMatchDetail } from "../api/hooks";
import type { ApiInternalMatchDetailResponse, TeamSide } from "../api/types";
import { DEFAULT_COMMUNITY_ID } from "../config";
import {
@@ -30,6 +30,8 @@ import {
internalMatchGamePath,
} from "../lib/internal-match-routes";
import { selectInternalMatchGame } from "../lib/internal-match-game-selection";
import { groupRecordedSets, type RecordedSeries } from "../lib/internal-match-series";
import { getSeriesHistoryResultLabel, shouldDisplaySeriesHistoryScore } from "../components/competition/competition-series-history";
import { LANE_LABELS } from "../lib/riot-history";
import {
filterTimelineEvents,
@@ -241,18 +243,6 @@ function getTeamName(
);
}
function resolveSelectedSeries(
detail: ApiInternalMatchDetailResponse,
selectedGame: MatchGameDetail,
) {
const teamIndexes = selectedGame.teams.map((team) => team.teamIndex);
return detail.match.seriesResults.find(
(series) =>
teamIndexes.includes(series.teamAIndex) &&
teamIndexes.includes(series.teamBIndex),
);
}
function WinBadge({ win }: { win: boolean }) {
return win ? (
<span className="inline-flex items-center border border-accent/60 bg-accent px-2 py-0.5 text-xs font-black text-accent-content">
@@ -1514,21 +1504,27 @@ function ScoreboardTables({
function GameTabs({
detail,
groups,
group,
communityId,
currentGameNumber,
navigationState,
}: {
detail: ApiInternalMatchDetailResponse;
groups: RecordedSeries[];
group: RecordedSeries;
communityId: string;
currentGameNumber: number;
navigationState: MatchGameNavigationState | undefined;
}) {
const navigate = useNavigate();
const currentRef = useRef<HTMLAnchorElement | null>(null);
const currentIndex = detail.games.findIndex(
const games = group.sets.map(({ game }) => game);
const currentIndex = games.findIndex(
(game) => game.gameNumber === currentGameNumber,
);
const previousGame = detail.games[currentIndex - 1];
const nextGame = detail.games[currentIndex + 1];
const previousGame = games[currentIndex - 1];
const nextGame = games[currentIndex + 1];
const pathFor = (gameNumber: number) =>
internalMatchGamePath(communityId, detail.match.matchId, gameNumber);
@@ -1541,9 +1537,25 @@ function GameTabs({
return (
<nav
className="lts-panel sticky top-[60px] z-30 flex items-center gap-1 p-1"
className="lts-panel sticky top-(--app-header-height) z-30 p-1"
aria-label="세트 선택"
>
<label className="flex min-w-0 items-center gap-2 border-b border-line px-2 py-1.5 text-xs font-semibold text-content-muted">
<span className="shrink-0">대진</span>
<select
className="lts-select min-w-0"
value={group.id}
onChange={(event) => {
const next = groups.find((candidate) => candidate.id === event.target.value);
if (next) void navigate(pathFor(next.sets[0].game.gameNumber), { state: navigationState });
}}
>
{groups.map((candidate) => (
<option key={candidate.id} value={candidate.id}>{candidate.label}</option>
))}
</select>
</label>
<div className="flex items-center gap-1">
<Link
to={previousGame ? pathFor(previousGame.gameNumber) : "#"}
state={navigationState}
@@ -1555,7 +1567,7 @@ function GameTabs({
<ChevronLeft className="size-4" aria-hidden="true" />
</Link>
<div className="no-scrollbar flex min-w-0 flex-1 gap-1 overflow-x-auto">
{detail.games.map((game) => {
{group.sets.map(({ game, official }) => {
const winnerTeam = game.teams.find((team) => team.win);
const active = game.gameNumber === currentGameNumber;
return (
@@ -1571,7 +1583,12 @@ function GameTabs({
: "text-content-muted hover:bg-sunken hover:text-content"
}`}
>
<span className="font-bold">{game.gameNumber}세트</span>
<span className="font-bold">
{official ? `${official.ordinal}세트` : `전체 ${game.gameNumber}세트`}
</span>
{official && official.ordinal !== game.gameNumber && (
<span className="text-xs opacity-80">전체 {game.gameNumber}</span>
)}
<span
className={`max-w-28 truncate text-xs ${active ? "opacity-80" : "text-content-subtle"}`}
>
@@ -1593,6 +1610,7 @@ function GameTabs({
>
<ChevronRight className="size-4" aria-hidden="true" />
</Link>
</div>
</nav>
);
}
@@ -1600,22 +1618,25 @@ function GameTabs({
function MatchScoreHero({
detail,
selectedGame,
group,
backTarget,
}: {
detail: ApiInternalMatchDetailResponse;
selectedGame: MatchGameDetail;
group: RecordedSeries;
backTarget: MatchGameBackTarget;
}) {
const selectedSeries = resolveSelectedSeries(detail, selectedGame);
const selectedSeries = group.series;
const officialGame = group.sets.find(({ game }) => game === selectedGame)?.official;
const setLabel = officialGame ? `${officialGame.ordinal}세트` : `전체 ${selectedGame.gameNumber}세트`;
const [leftTeam, rightTeam] = selectedGame.teams;
const leftScore =
selectedSeries?.teamAIndex === leftTeam?.teamIndex
? selectedSeries?.teamAWins
: selectedSeries?.teamBWins;
const rightScore =
selectedSeries?.teamBIndex === rightTeam?.teamIndex
? selectedSeries?.teamBWins
: selectedSeries?.teamAWins;
const getScore = (side: TeamSide) => selectedSeries?.entries.find(
(entry) => entry.teamId === officialGame?.teams[side].teamId,
)?.gameWins;
const leftScore = leftTeam && getScore(leftTeam.side);
const rightScore = rightTeam && getScore(rightTeam.side);
const showSeriesScore = selectedSeries && shouldDisplaySeriesHistoryScore(selectedSeries) && leftScore !== undefined && rightScore !== undefined;
const decision = selectedSeries?.status === "completed" ? getSeriesHistoryResultLabel(selectedSeries) : null;
const sideTone = (side: TeamSide) =>
side === "blue" ? "text-[#8fb6ff]" : "text-[#ff99a5]";
@@ -1624,19 +1645,25 @@ function MatchScoreHero({
width="xl"
crumbs={[
{ label: backTarget.label, to: backTarget.to },
{ label: `${selectedGame.gameNumber}세트` },
{ label: setLabel },
]}
title={
<>
{detail.match.title}
<span className="ml-2 text-on-ink-muted">
{selectedGame.gameNumber}세트
{setLabel}
</span>
</>
}
meta={
<>
<span>{formatDateTime(selectedGame.gameCreation)}</span>
{officialGame && officialGame.ordinal !== selectedGame.gameNumber && (
<>
<MetaDot />
<span>전체 {selectedGame.gameNumber}세트</span>
</>
)}
<MetaDot />
<span className="tabular">
{formatDuration(selectedGame.gameDuration)}
@@ -1662,14 +1689,16 @@ function MatchScoreHero({
</div>
</div>
<div className="text-center">
<div className="tabular flex items-baseline gap-2.5 text-4xl font-extrabold">
<span>{leftScore ?? (leftTeam.win ? 1 : 0)}</span>
<span className="text-xl text-on-ink-muted">:</span>
<span>{rightScore ?? (rightTeam.win ? 1 : 0)}</span>
</div>
<div className="mt-0.5 text-[11px] font-semibold text-on-ink-muted">
시리즈 스코어
</div>
{showSeriesScore ? (
<>
<div className="tabular text-4xl font-extrabold">{leftScore} : {rightScore}</div>
<div className="mt-0.5 text-xs font-semibold text-on-ink-muted">
{selectedSeries.status === "in-progress" ? "시리즈 진행 스코어" : "시리즈 스코어"}
</div>
</>
) : (
<div className="text-sm font-semibold text-on-ink-muted">{decision ?? "세트 결과"}</div>
)}
</div>
<div className="min-w-0">
<div
@@ -1700,6 +1729,7 @@ export default function MatchGameDetailPage() {
const resolvedMatchId = matchId ?? id;
const requestedGameNumber = Number(gameNumber);
const detailQuery = useInternalMatchDetail(resolvedMatchId, communityId);
const competition = useCompetition(resolvedMatchId, communityId);
const { data: ddragon } = useDdragonManifest();
const detail = detailQuery.data;
const fallbackBackTo = resolvedMatchId
@@ -1732,7 +1762,9 @@ export default function MatchGameDetailPage() {
requestedGameNumber,
);
if (!selectedGame) {
const groups = groupRecordedSets(detail, competition.data);
const group = groups.find(({ sets }) => sets.some(({ game }) => game === selectedGame));
if (!selectedGame || !group) {
const hasRecordedGames = detail.games.length > 0;
const requestedGameLabel =
Number.isSafeInteger(requestedGameNumber) && requestedGameNumber > 0
@@ -1762,11 +1794,14 @@ export default function MatchGameDetailPage() {
<MatchScoreHero
detail={detail}
selectedGame={selectedGame}
group={group}
backTarget={backTarget}
/>
<PageBody width="xl">
<GameTabs
detail={detail}
groups={groups}
group={group}
communityId={communityId}
currentGameNumber={selectedGame.gameNumber}
navigationState={navigationState}
+15 -7
View File
@@ -23,7 +23,7 @@ import {
sortTeamMembersForRoster,
} from "./match-team-progress-view";
import { PageBody, PageHero } from "../ui";
import { PageBody, PageHero, PlainPage } from "../ui";
export default function MatchTeamProgressPage() {
const { id } = useParams();
const [searchParams] = useSearchParams();
@@ -187,6 +187,7 @@ export default function MatchTeamProgressPage() {
</span>
}
meta="다음 상대와 세트별 토너먼트 코드를 한곳에서 확인할 수 있습니다."
flush
actions={
<Link
to={`/match/${id}/team?select=1`}
@@ -197,9 +198,9 @@ export default function MatchTeamProgressPage() {
</Link>
}
/>
<PageBody>
<section className="mb-8" aria-labelledby="active-series-heading">
<PlainPage>
<div className={team ? "mb-8 grid items-start gap-6 lg:grid-cols-[minmax(0,1.6fr)_minmax(0,1fr)]" : "mb-8"}>
<section aria-labelledby="active-series-heading">
<SectionHeading
id="active-series-heading"
title="다음 경기"
@@ -229,16 +230,22 @@ export default function MatchTeamProgressPage() {
) : (
<EmptyState message="현재 준비하거나 진행할 대진이 없습니다." />
)}
<Link
to={`/match/${id}?tab=bracket`}
className="mt-3 inline-flex min-h-10 items-center text-sm font-semibold text-primary hover:underline"
>
전체 대진표 보기
</Link>
</section>
{team && (
<section className="mb-8" aria-labelledby="roster-heading">
<section aria-labelledby="roster-heading">
<SectionHeading
id="roster-heading"
title="팀 구성"
description={`${team.members.length}명의 라인업을 포지션 순서로 보여줍니다.`}
/>
<ul className="divide-y divide-base-content/10 border border-base-content/10 bg-base-100">
<ul className="lts-panel divide-y divide-line">
{sortTeamMembersForRoster(team.members).map((member) => (
<li
key={member.userId}
@@ -264,6 +271,7 @@ export default function MatchTeamProgressPage() {
</ul>
</section>
)}
</div>
<section className="mb-6" aria-labelledby="completed-heading">
<SectionHeading
@@ -311,7 +319,7 @@ export default function MatchTeamProgressPage() {
<EmptyState message="아직 종료된 대진이 없습니다." />
)}
</section>
</PageBody>
</PlainPage>
</>
);
}
+106 -273
View File
@@ -411,55 +411,6 @@ function ItemGrid({
);
}
function TeamMini({
match,
manifest,
ownerParticipantId,
}: {
match: ApiRecentMatchView;
manifest: DdragonManifest | null | undefined;
ownerParticipantId: string;
}) {
return (
<div className="grid flex-1 grid-cols-2 gap-x-3 text-[10px] leading-tight min-w-0">
{match.teams.map((team) => (
<div key={`${match.matchId}-${team.side}`} className="min-w-0">
{team.participants.map((participant) => {
const championName =
championDisplayName(manifest, participant.championId) ??
String(participant.championId);
const isOwner = participant.puuid === ownerParticipantId;
return (
<div
key={`${participant.puuid}-${participant.championId}`}
className="flex items-center gap-1 min-w-0"
>
<ChampionIcon
championId={participant.championId}
manifest={manifest}
size="xs"
className={
isOwner ? "ring-1 ring-primary ring-inset" : undefined
}
/>
<span
className={`truncate ${
isOwner
? "font-bold text-base-content/80"
: "text-base-content/40"
}`}
>
{participant.gameName || championName}
</span>
</div>
);
})}
</div>
))}
</div>
);
}
type MatchDetailScales = {
maxDamage: number;
};
@@ -884,146 +835,56 @@ function RecentMatchCard({
loss: "border-loss-line bg-loss-tint",
remake: "border-line bg-card",
}[outcome];
const bar = { win: "bg-win", loss: "bg-loss", remake: "bg-content-disabled" }[
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];
const toggleSurface = {
win: "lg:bg-win/15 lg:text-win",
loss: "lg:bg-loss/15 lg:text-loss",
remake: "lg:bg-sunken-strong",
}[outcome];
return (
<article
className={`relative overflow-hidden rounded-box border ${surface}`}
>
<span aria-hidden="true" className={`absolute inset-y-0 left-0 w-1.5 ${bar}`} />
<div className="grid items-center gap-3 py-3 pl-5 pr-3 lg:grid-cols-[112px_1fr_120px_1.5fr_36px] lg:pr-0">
<div className="text-center lg:text-left">
<div className={`text-sm font-extrabold ${resultClass}`}>
{match.remake ? "다시하기" : match.win ? "승리" : "패배"}
</div>
<div className="text-xs font-bold text-base-content/45 mt-1">
{match.queueLabel}
</div>
<div className="mt-1 text-xs text-base-content/25">
{formatDate(match.gameCreation)}
</div>
<div className="text-xs text-base-content/25">
{formatDuration(match.gameDuration)}
</div>
<article className={`relative overflow-hidden rounded-box border ${surface}`}>
<span aria-hidden="true" className={`absolute inset-y-0 left-0 w-1 ${bar}`} />
<div className="grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-2 py-3 pl-4 pr-2 sm:grid-cols-[minmax(0,1fr)_auto_auto] sm:gap-x-5 sm:px-5">
<div className="col-span-2 flex flex-wrap items-baseline gap-x-2 text-xs text-content-muted sm:col-span-3">
<strong className={`text-sm ${resultClass}`}>{match.remake ? "다시하기" : match.win ? "승리" : "패배"}</strong>
<span>{formatDate(match.gameCreation)} · {match.queueLabel}</span>
</div>
<div className="flex items-center gap-2 min-w-0">
<ChampionIcon
championId={match.championId}
manifest={manifest}
size="lg"
/>
<LoadoutIcons
summonerSpells={match.summonerSpells}
perks={match.perks}
manifest={manifest}
/>
<div className="flex min-w-0 items-center gap-2">
<ChampionIcon championId={match.championId} manifest={manifest} />
<div className="min-w-0">
<div className="font-bold text-base-content truncate">
{championName}
</div>
<div className="text-xs text-base-content/35">
Lv.{match.championLevel} ·{" "}
{(LANE_LABELS[match.teamPosition] ?? match.teamPosition) ||
"포지션 없음"}
<div className="truncate font-bold text-content" title={championName}>{championName}</div>
<div className="text-xs text-content-muted">
{LANE_LABELS[match.teamPosition] ?? (match.teamPosition || "포지션 미확인")}
</div>
</div>
</div>
<div className="text-center">
<div className="text-lg font-bold tabular-nums">
<span>{match.kills}</span>
<span className="text-base-content/25"> / </span>
<span className="text-loss">{match.deaths}</span>
<span className="text-base-content/25"> / </span>
<span>{match.assists}</span>
</div>
<div
className={`text-xs font-bold tabular-nums ${kdaClass(match.kda)}`}
>
{match.deaths === 0 ? "Perfect" : `${match.kda} KDA`}
</div>
<div className="mt-1 text-xs text-base-content/35">
킬 관여 {match.killParticipation}%
</div>
</div>
<div className="grid sm:grid-cols-[100px_1fr] gap-3 items-center min-w-0">
<div className="space-y-1 text-xs 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 min-w-0">
<ItemGrid
items={match.items}
trinket={match.trinket}
manifest={manifest}
itemKey={match.matchId}
/>
<TeamMini
match={match}
manifest={manifest}
ownerParticipantId={ownerParticipantId}
/>
</div>
</div>
<div className="flex justify-end lg:-my-3 lg:self-stretch">
<button
type="button"
onClick={() => setExpanded((current) => !current)}
className={`flex h-10 w-full items-center justify-center gap-1 rounded-field border border-line-strong bg-card text-content-muted transition-colors hover:text-content sm:w-auto sm:px-3 lg:h-full lg:w-9 lg:rounded-none lg:border-0 lg:px-0 ${toggleSurface}`}
aria-expanded={expanded}
aria-label={expanded ? "상세 전적 접기" : "상세 전적 펼치기"}
>
<span className="text-xs font-bold lg:hidden">
{expanded ? "상세 접기" : "상세 보기"}
</span>
{expanded ? (
<ChevronUp className="h-4 w-4" aria-hidden="true" />
) : (
<ChevronDown className="h-4 w-4" aria-hidden="true" />
)}
</button>
<div className="tabular whitespace-nowrap text-right">
<strong className="text-sm sm:text-base">{match.kills} / {match.deaths} / {match.assists}</strong>
<div className="text-xs text-content-muted">{match.deaths === 0 ? "Perfect" : `${match.kda} KDA`}</div>
</div>
<button
type="button"
onClick={() => setExpanded((current) => !current)}
className="col-span-2 flex min-h-9 items-center justify-end gap-1 rounded-field px-2 text-xs font-semibold text-content-muted hover:text-content focus-visible:-outline-offset-2 sm:col-span-1"
aria-expanded={expanded}
aria-label={expanded ? "상세 전적 접기" : "상세 전적 펼치기"}
>
{expanded ? "상세 접기" : "상세 보기"}
{expanded ? <ChevronUp className="size-4" aria-hidden="true" /> : <ChevronDown className="size-4" aria-hidden="true" />}
</button>
</div>
{expanded && (
<div className="border-t border-line bg-card">
<MatchDetailTabs
match={match}
manifest={manifest}
ownerParticipantId={ownerParticipantId}
/>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 border-b border-line px-4 py-3 text-xs text-content-muted">
<LoadoutIcons summonerSpells={match.summonerSpells} perks={match.perks} manifest={manifest} />
<span>Lv.{match.championLevel} · {formatDuration(match.gameDuration)}</span>
<span>킬 관여 {match.killParticipation}%</span>
<span>CS {match.totalCs} ({match.csPerMin}/분)</span>
<span>시야 {match.visionScore} · 제어와드 {match.controlWardsBought}</span>
<span>챔피언 피해량 {match.damageDealtToChampions.toLocaleString()}</span>
</div>
<MatchDetailTabs match={match} manifest={manifest} ownerParticipantId={ownerParticipantId} />
</div>
)}
</article>
@@ -1036,45 +897,14 @@ function SkeletonBlock({ className = "" }: { className?: string }) {
function MatchCardSkeleton() {
return (
<article className="border border-l-4 border-l-base-content/10 border-base-content/10 bg-base-100">
<div className="grid items-center gap-3 p-3 lg:grid-cols-[120px_1fr_120px_1.5fr_40px]">
<div className="space-y-1.5">
<SkeletonBlock className="h-3.5 w-12" />
<SkeletonBlock className="h-2.5 w-16" />
<SkeletonBlock className="h-2.5 w-20" />
</div>
<article className="space-y-2 rounded-box border border-line bg-card p-4">
<SkeletonBlock className="h-3 w-32" />
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2">
<SkeletonBlock className="h-12 w-12" />
<div className="grid grid-cols-2 gap-0.5">
{Array.from({ length: 4 }).map((_, index) => (
<SkeletonBlock key={index} className="h-5 w-5" />
))}
</div>
<div className="space-y-1.5">
<SkeletonBlock className="h-3.5 w-24" />
<SkeletonBlock className="h-2.5 w-16" />
</div>
</div>
<div className="flex flex-col items-center gap-1.5">
<SkeletonBlock className="size-9 rounded-field" />
<SkeletonBlock className="h-4 w-20" />
<SkeletonBlock className="h-2.5 w-12" />
</div>
<div className="flex items-start gap-3">
<div className="grid grid-cols-3 gap-1">
{Array.from({ length: 6 }).map((_, index) => (
<SkeletonBlock key={index} className="h-6 w-6" />
))}
</div>
<SkeletonBlock className="h-6 w-6" />
<div className="grid flex-1 grid-cols-2 gap-x-3 gap-y-1">
{Array.from({ length: 10 }).map((_, index) => (
<SkeletonBlock key={index} className="h-2.5 w-full" />
))}
</div>
</div>
<div className="hidden justify-end lg:flex">
<SkeletonBlock className="h-8 w-8" />
</div>
<SkeletonBlock className="h-4 w-16" />
</div>
</article>
);
@@ -1422,7 +1252,7 @@ export default function UserHistoryPage() {
</div>
))}
<div className="lts-panel sticky top-[60px] z-30 p-1">
<div className="lts-panel sticky top-(--app-header-height) z-30 p-1">
<div
className="no-scrollbar flex gap-1 overflow-x-auto"
role="tablist"
@@ -1442,70 +1272,64 @@ export default function UserHistoryPage() {
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-3">
{!isInternalQueue ? (
<div
className="flex flex-wrap gap-1.5"
role="group"
aria-label="큐 종류"
>
{RANK_FILTER_TABS.map((tab) => (
<Chip
key={tab.value}
selected={rank === tab.value}
onClick={() =>
updateSearch({ rank: tab.value, championId: null })
}
>
{tab.label}
</Chip>
))}
</div>
) : (
<p className="text-[13px] text-content-muted">
토너먼트 코드로 수집한 내전 결과만 집계합니다.
</p>
)}
<div className="flex flex-wrap items-center gap-2">
{selectedChampionName && (
<Chip
selected
onClick={() => updateSearch({ championId: null })}
aria-label={`${selectedChampionName} 필터 해제`}
>
{selectedChampionName}
<X className="size-3.5" aria-hidden="true" />
</Chip>
)}
{profile.seasons.length > 0 && (
<select
aria-label="시즌"
value={filters.seasonId ?? profile.season.id}
onChange={(event) =>
updateSearch({
seasonId: event.target.value,
championId: null,
})
}
className="lts-select !w-auto"
>
{profile.seasons.map((season) => (
<option key={season.id} value={season.id}>
{season.label}
</option>
))}
</select>
)}
</div>
</div>
{profile.tierHistory.length > 0 && !isInternalQueue && (
<Suspense fallback={<div className="lts-panel h-[180px]" />}>
<TierHistoryChart entries={profile.tierHistory} />
</Suspense>
)}
<Panel>
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-line px-4 py-3 sm:px-5">
{!isInternalQueue ? (
<div
className="flex flex-wrap gap-1.5"
role="group"
aria-label="큐 종류"
>
{RANK_FILTER_TABS.map((tab) => (
<Chip
key={tab.value}
selected={rank === tab.value}
onClick={() =>
updateSearch({ rank: tab.value, championId: null })
}
>
{tab.label}
</Chip>
))}
</div>
) : (
<p className="text-[13px] text-content-muted">
토너먼트 코드로 수집한 내전 결과만 집계합니다.
</p>
)}
<div className="flex flex-wrap items-center gap-2">
{selectedChampionName && (
<Chip
selected
onClick={() => updateSearch({ championId: null })}
aria-label={`${selectedChampionName} 필터 해제`}
>
{selectedChampionName}
<X className="size-3.5" aria-hidden="true" />
</Chip>
)}
{profile.seasons.length > 0 && (
<select
aria-label="시즌"
value={filters.seasonId ?? profile.season.id}
onChange={(event) =>
updateSearch({
seasonId: event.target.value,
championId: null,
})
}
className="lts-select !w-auto"
>
{profile.seasons.map((season) => (
<option key={season.id} value={season.id}>
{season.label}
</option>
))}
</select>
)}
</div>
</div>
<PanelHeader
title={`최근 ${summary?.windowSize ?? 20}게임 요약`}
description={
@@ -1587,6 +1411,15 @@ export default function UserHistoryPage() {
</div>
</Panel>
{profile.tierHistory.length > 0 && !isInternalQueue && (
<details className="lts-panel">
<summary className="cursor-pointer px-4 py-3 text-sm font-semibold">티어 그래프</summary>
<Suspense fallback={<div className="h-[180px]" />}>
<TierHistoryChart entries={profile.tierHistory} />
</Suspense>
</details>
)}
<div
className="flex items-center gap-1.5"
role="tablist"
+25 -8
View File
@@ -126,6 +126,7 @@ export default function LegacyImportPage() {
const [windowStart, setWindowStart] = useState(toInputValue(DEFAULT_START));
const [windowEnd, setWindowEnd] = useState('');
const [message, setMessage] = useState<string | null>(null);
const [memberSearch, setMemberSearch] = useState('');
const [overrides, setOverrides] = useState<
Record<string, MemberWindowOverride>
>({});
@@ -146,6 +147,10 @@ export default function LegacyImportPage() {
const startMutation = useStartLegacyImport(communityId);
const cancelMutation = useCancelLegacyImport(communityId);
const members = membersQuery.data?.members ?? [];
const memberSearchTerm = memberSearch.trim().toLowerCase();
const filteredMembers = members.filter((member) =>
`${member.displayName} ${member.gameName}#${member.tagLine}`.toLowerCase().includes(memberSearchTerm),
);
const manageableMemberships =
meQuery.data?.memberships.filter((membership) => {
@@ -296,13 +301,23 @@ export default function LegacyImportPage() {
)}
</section>
<section className="border border-base-content/10 bg-base-100 overflow-hidden mb-6">
<div className="px-4 py-3 border-b border-base-content/10">
<h2 className="text-sm font-bold">멤버별 윈도우</h2>
<p className="mt-1 text-xs text-base-content/35">
<details className="lts-panel overflow-hidden mb-6">
<summary className="cursor-pointer px-4 py-3 text-sm font-bold">
멤버별 수집 기간 설정 · {members.length}명
</summary>
<div className="border-y border-line px-4 py-3">
<p className="text-sm text-content-muted">
기본 시작일은 2024-05-01이며, 필요하면 멤버별 시작/종료 시간을 조정할 수 있습니다.
비활성 멤버는 종료일이 마지막 업데이트 시각으로 잡힙니다.
</p>
<input
type="search"
value={memberSearch}
onChange={(event) => setMemberSearch(event.target.value)}
aria-label="멤버 이름 또는 Riot ID 검색"
placeholder="멤버 이름 또는 Riot ID 검색"
className="lts-input mt-3 w-full sm:max-w-xs"
/>
</div>
<div className="overflow-x-auto">
<table className="lts-table min-w-[900px]">
@@ -316,7 +331,7 @@ export default function LegacyImportPage() {
</tr>
</thead>
<tbody>
{members.map((member) => {
{filteredMembers.map((member) => {
const override =
overrides[member.userId] ?? defaultMemberOverride(member);
return (
@@ -336,6 +351,7 @@ export default function LegacyImportPage() {
<td className="px-3 py-2">
<input
type="datetime-local"
aria-label={`${member.displayName} 수집 시작 시간`}
value={override.startTime}
onChange={(event) =>
setOverrides((current) => {
@@ -357,6 +373,7 @@ export default function LegacyImportPage() {
<td className="px-3 py-2">
<input
type="datetime-local"
aria-label={`${member.displayName} 수집 종료 시간`}
value={override.endTime}
onChange={(event) =>
setOverrides((current) => {
@@ -378,17 +395,17 @@ export default function LegacyImportPage() {
</tr>
);
})}
{members.length === 0 && (
{filteredMembers.length === 0 && (
<tr>
<td colSpan={5} className="px-4 py-8 text-center text-sm text-base-content/35">
Riot 계정이 있는 멤버가 없습니다.
{memberSearchTerm ? '검색 조건에 맞는 멤버가 없습니다.' : 'Riot 계정이 있는 멤버가 없습니다.'}
</td>
</tr>
)}
</tbody>
</table>
</div>
</section>
</details>
<section className="space-y-3">
<h2 className="text-sm font-bold">작업 이력</h2>
+107 -64
View File
@@ -1,8 +1,9 @@
import { useMemo, useState } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import type {
MatchDetailResponse,
MatchGameMode,
MatchLifecycleStatus,
MatchScheduleItemView,
} from '@lolympus/contracts';
import { Link, useParams } from 'react-router';
@@ -16,7 +17,7 @@ import {
import type { MatchMutationRequest } from '../../api/types';
import { DEFAULT_COMMUNITY_ID } from '../../config';
import { Btn } from "../../ui/Btn";
import { Btn, Chip, ErrorNote, LoadingNote, Pill, type PillTone } from '../../ui';
import { AdminNotice, AdminPage } from '../../components/AdminPage';
const DEFAULT_FORM: MatchMutationRequest = {
title: '',
@@ -38,6 +39,24 @@ const GAME_MODE_LABEL: Record<MatchGameMode, string> = {
'double-elimination': '더블 엘리미네이션',
};
const MATCH_STATES = {
recruiting: { label: '모집 중', tone: 'live' },
'team-built': { label: '팀빌딩 완료', tone: 'gold' },
'in-progress': { label: '진행 중', tone: 'accent' },
finished: { label: '종료', tone: 'neutral' },
} satisfies Record<MatchLifecycleStatus, { label: string; tone: PillTone }>;
const matchStatusFilters = Object.keys(MATCH_STATES) as MatchLifecycleStatus[];
function matchModeDetail(match: MatchDetailResponse) {
if (match.gameMode === 'round-robin' && match.roundRobinMaxRounds) {
return `최대 ${match.roundRobinMaxRounds}라운드`;
}
if (match.gameMode === 'double-elimination') {
return match.doubleEliminationResetFinalEnabled ? '결승 리셋 허용' : '결승 리셋 없음';
}
}
function resolveRoundRobinFullRoundCount(maxParticipants?: number) {
const teamCount = Math.floor(Number(maxParticipants ?? 10) / 5);
if (teamCount < 2) return 0;
@@ -147,7 +166,8 @@ export default function MatchAdminPage() {
const communityId = cid ?? DEFAULT_COMMUNITY_ID;
const queryClient = useQueryClient();
const meQuery = useMe();
const matchesQuery = useMatches({ limit: 200 }, communityId);
const [statusFilter, setStatusFilter] = useState<MatchLifecycleStatus>();
const matchesQuery = useMatches({ limit: 200, status: statusFilter }, communityId);
const createMutation = useCreateMatch(communityId);
const updateMutation = useUpdateMatch(communityId);
const deleteMutation = useDeleteMatch(communityId);
@@ -155,6 +175,11 @@ export default function MatchAdminPage() {
const [showForm, setShowForm] = useState(false);
const [form, setForm] = useState(makeForm());
const [message, setMessage] = useState<string | null>(null);
const formHeading = useRef<HTMLHeadingElement>(null);
useEffect(() => {
if (showForm) formHeading.current?.focus();
}, [showForm, editing]);
const currentUser =
meQuery.data?.memberships.find(
@@ -246,7 +271,34 @@ export default function MatchAdminPage() {
createMutation.mutate(payload, callbacks);
}
if (!canManage && !meQuery.isPending) {
function matchActions(match: MatchDetailResponse) {
return (
<div className="flex flex-wrap gap-2">
<Btn onClick={() => openEdit(match)} variant="secondary">수정</Btn>
{match.status === 'recruiting' && (
<Btn
variant="destructive"
disabled={deleteMutation.isPending}
onClick={() => {
if (!window.confirm('이 내전을 삭제할까요?')) return;
deleteMutation.mutate(match._id, {
onSuccess: invalidate,
onError: (error) => setMessage(error instanceof Error ? error.message : '삭제 실패'),
});
}}
>
삭제
</Btn>
)}
</div>
);
}
if (meQuery.isLoading) {
return <AdminNotice title="권한 확인 중" />;
}
if (!canManage) {
return (
<AdminNotice title="권한이 필요합니다">
<p className="mt-2 text-sm text-base-content/40">
@@ -262,8 +314,16 @@ export default function MatchAdminPage() {
title="내전 관리"
description="내전 생성, 모집 정원, 게임 모드와 공지 내용을 관리합니다."
>
<div className="mb-4 flex flex-wrap items-center justify-end gap-2">
<Btn variant="primary" onClick={openCreate}>
<div className="mb-4 flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-wrap gap-2" role="group" aria-label="내전 상태 필터">
<Chip selected={!statusFilter} onClick={() => setStatusFilter(undefined)}>전체</Chip>
{matchStatusFilters.map((status) => (
<Chip key={status} selected={statusFilter === status} onClick={() => setStatusFilter(status)}>
{MATCH_STATES[status].label}
</Chip>
))}
</div>
<Btn variant="primary" onClick={openCreate}>
새 내전 만들기
</Btn>
</div>
@@ -277,7 +337,7 @@ export default function MatchAdminPage() {
{showForm && (
<section className="mb-6 border border-base-content/10 bg-base-100 p-4">
<div className="mb-4 flex items-center justify-between gap-3">
<h2 className="text-sm font-bold">
<h2 ref={formHeading} tabIndex={-1} className="scroll-mt-28 text-sm font-bold">
{editing ? '내전 수정' : '새 내전'}
</h2>
<button
@@ -484,9 +544,42 @@ export default function MatchAdminPage() {
</section>
)}
<section className="lts-panel overflow-hidden">
<div className="overflow-x-auto">
<table className="lts-table min-w-[900px]">
{matchesQuery.isLoading ? (
<LoadingNote label="내전 목록을 불러오는 중" />
) : matchesQuery.isError ? (
<ErrorNote title="내전 목록을 불러오지 못했습니다" action={<Btn onClick={() => void matchesQuery.refetch()}>다시 시도</Btn>} />
) : matches.length === 0 ? (
<p role="status" className="lts-panel p-6 text-center text-sm text-content-muted">
{statusFilter ? '이 상태의 내전이 없습니다.' : '등록된 내전이 없습니다.'}
</p>
) : (
<section className="lts-panel overflow-hidden" aria-label="내전 목록">
<ul className="divide-y divide-line lg:hidden">
{matches.map((match) => (
<li key={match._id} className="space-y-2 px-4 py-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<Link to={`/match/${match._id}`} className="min-w-0 break-words text-sm font-bold hover:text-primary">
{match.title}
</Link>
<Pill tone={MATCH_STATES[match.status].tone}>{MATCH_STATES[match.status].label}</Pill>
</div>
<p className="text-xs text-content-muted">
{formatDate(match.scheduledAt)} · {match.participants.length}/{match.maxParticipants}명
</p>
<details className="text-sm">
<summary className="cursor-pointer py-2 font-semibold">상세·관리</summary>
<p className="mb-2 text-xs text-content-muted">
{GAME_MODE_LABEL[match.gameMode ?? 'pair']}
{matchModeDetail(match) && ` · ${matchModeDetail(match)}`}
</p>
{match.description && <p className="mb-3 break-words text-sm text-content-muted">{match.description}</p>}
{matchActions(match)}
</details>
</li>
))}
</ul>
<div className="hidden overflow-x-auto lg:block">
<table className="lts-table">
<thead>
<tr className="bg-base-200/40 border-b border-base-content/10 text-xs uppercase tracking-wider text-base-content/35">
<th className="px-3 py-2">시간</th>
@@ -511,74 +604,24 @@ export default function MatchAdminPage() {
{match.description || '-'}
</div>
</td>
<td className="px-3 py-2 text-xs">{match.status}</td>
<td className="px-3 py-2 text-xs"><Pill tone={MATCH_STATES[match.status].tone}>{MATCH_STATES[match.status].label}</Pill></td>
<td className="px-3 py-2 text-xs tabular-nums">
{match.participants.length}/{match.maxParticipants}
</td>
<td className="px-3 py-2 text-xs">
{GAME_MODE_LABEL[match.gameMode ?? 'pair']}
{match.gameMode === 'round-robin' &&
match.roundRobinMaxRounds && (
<span className="block text-xs text-base-content/30">
최대 {match.roundRobinMaxRounds}R
</span>
)}
{match.gameMode === 'double-elimination' && (
<span className="block text-xs text-base-content/30">
GF 리셋{' '}
{match.doubleEliminationResetFinalEnabled
? '허용'
: '없음'}
</span>
)}
<span className="block text-xs text-content-muted">{matchModeDetail(match)}</span>
</td>
<td className="px-3 py-2 text-right">
<div className="inline-flex gap-2">
<button
type="button"
className="text-xs px-2 py-1 border border-base-content/10 text-base-content/50 hover:text-primary"
onClick={() => openEdit(match)}
>
수정
</button>
<button
type="button"
className="text-xs px-2 py-1 border border-loss-line text-loss hover:bg-loss-tint"
disabled={
deleteMutation.isPending ||
match.status !== 'recruiting'
}
title={
match.status === 'recruiting'
? '내전 삭제'
: '팀 구성이 확정된 내전 기록은 삭제할 수 없습니다.'
}
onClick={() => {
if (!window.confirm('이 내전을 삭제할까요?')) return;
deleteMutation.mutate(match._id, {
onSuccess: invalidate,
onError: (error) =>
setMessage(error instanceof Error ? error.message : '삭제 실패'),
});
}}
>
삭제
</button>
</div>
<div className="inline-block">{matchActions(match)}</div>
</td>
</tr>
))}
{matches.length === 0 && (
<tr>
<td colSpan={6} className="px-4 py-10 text-center text-sm text-base-content/35">
등록된 내전이 없습니다.
</td>
</tr>
)}
</tbody>
</table>
</div>
</section>
)}
</AdminPage>
);
}
@@ -15,7 +15,7 @@ import type {
} from '../../api/types';
import { DEFAULT_COMMUNITY_ID } from '../../config';
import { Btn } from "../../ui/Btn";
import { Btn, Chip, ErrorNote, LoadingNote } from '../../ui';
import { AdminNotice, AdminPage } from '../../components/AdminPage';
const STATES: TournamentCodeState[] = [
'available',
@@ -23,7 +23,16 @@ const STATES: TournamentCodeState[] = [
'released',
'used',
'expired',
'voided',
];
const STATE_LABELS: Record<TournamentCodeState, string> = {
available: '사용 가능',
reserved: '경기 배정',
released: '배정 해제',
used: '사용 완료',
expired: '만료',
voided: '폐기',
};
function formatDate(value: string | undefined) {
if (!value) return '-';
@@ -186,22 +195,21 @@ export default function TournamentCodesPage() {
description="외부에서 생성한 코드를 업로드하고, 매치에 자동 할당되는 풀을 관리합니다."
>
<section className="grid sm:grid-cols-5 gap-3 mb-6">
<div className="mb-4 flex flex-wrap gap-2" role="group" aria-label="토너먼트 코드 상태 필터">
<Chip selected={stateFilter === ''} onClick={() => setStateFilter('')}>전체</Chip>
{STATES.map((state) => (
<div key={state} className="border border-base-content/10 bg-base-100 p-4">
<div className="text-xs uppercase tracking-wider text-base-content/30">
{state}
</div>
<div className="mt-2 text-2xl font-black tabular-nums">
{counts?.[state] ?? 0}
</div>
</div>
<Chip key={state} selected={stateFilter === state} onClick={() => setStateFilter(state)}>
{STATE_LABELS[state]}
{counts && <span className="tabular">{counts[state] ?? 0}</span>}
</Chip>
))}
</section>
</div>
<section className="border border-base-content/10 bg-base-100 p-4 mb-6">
<details className="lts-panel mb-4">
<summary className="cursor-pointer px-4 py-3 text-sm font-bold">토너먼트 코드 일괄 등록</summary>
<div className="border-t border-line p-4">
<div className="flex items-center justify-between gap-3 mb-3">
<h2 className="text-sm font-bold">Bulk 업로드</h2>
<span className="text-sm font-semibold">입력 형식</span>
<div className="flex gap-1">
<button
type="button"
@@ -220,6 +228,7 @@ export default function TournamentCodesPage() {
</div>
</div>
<textarea
aria-label="등록할 토너먼트 코드"
value={text}
onChange={(event) => setText(event.target.value)}
rows={7}
@@ -238,26 +247,20 @@ export default function TournamentCodesPage() {
>
{uploadMutation.isPending ? '업로드 중...' : '업로드'}
</Btn>
{message && <span className="text-xs text-base-content/45">{message}</span>}
{message && <span role="status" className="text-sm text-content-muted">{message}</span>}
</div>
</section>
</div>
</details>
<section className="lts-panel overflow-hidden">
<div className="px-4 py-3 border-b border-base-content/10 flex items-center justify-between gap-3">
<h2 className="text-sm font-bold">코드 목록</h2>
<select
value={stateFilter}
onChange={(event) => setStateFilter(event.target.value as TournamentCodeState | '')}
className="lts-select"
>
<option value="">전체</option>
{STATES.map((state) => (
<option key={state} value={state}>
{state}
</option>
))}
</select>
</div>
{listQuery.isLoading ? (
<LoadingNote label="코드 목록을 불러오는 중" />
) : listQuery.isError ? (
<ErrorNote title="코드 목록을 불러오지 못했습니다" action={<Btn onClick={() => void listQuery.refetch()}>다시 시도</Btn>} />
) : (
<div className="overflow-x-auto">
<table className="lts-table min-w-[900px]">
<thead>
@@ -276,7 +279,7 @@ export default function TournamentCodesPage() {
<td className="px-3 py-2 font-mono text-xs font-bold">
{code.code}
</td>
<td className="px-3 py-2 text-xs">{code.state}</td>
<td className="px-3 py-2 text-xs">{STATE_LABELS[code.state]}</td>
<td className="px-3 py-2 text-xs text-base-content/50">
{formatDate(code.expiresAt)}
</td>
@@ -304,7 +307,7 @@ export default function TournamentCodesPage() {
})
}
>
available 환원
사용 가능으로 복원
</button>
)}
{code.state === 'available' && (
@@ -337,6 +340,7 @@ export default function TournamentCodesPage() {
</tbody>
</table>
</div>
)}
</section>
</AdminPage>
);
+4
View File
@@ -369,6 +369,10 @@
}
@media (min-width: 920px) {
.auction-visual-preview .auction-team-summary {
display: none;
}
.auction-visual-preview .auction-preview-grid {
gap: var(--spacing-5);
grid-template-columns: minmax(0, 1fr) minmax(0, 1.2fr);
@@ -0,0 +1,86 @@
import type { MatchDetailResponse } from '@lolympus/contracts';
const scheduleFormatter = new Intl.DateTimeFormat('ko-KR', {
timeZone: 'Asia/Seoul',
month: 'numeric',
day: 'numeric',
weekday: 'short',
hour: '2-digit',
minute: '2-digit',
hourCycle: 'h23',
});
export const HOME_MATCH_STATUS = {
recruiting: '모집 중',
'team-built': '팀빌딩',
'in-progress': '진행 중',
finished: '종료',
} as const;
export function getHomeMatchSchedule(scheduledAt: string) {
const value = new Date(scheduledAt);
if (Number.isNaN(value.getTime())) return;
const { month, day, weekday, hour, minute } = Object.fromEntries(
scheduleFormatter
.formatToParts(value)
.map(({ type, value }) => [type, value]),
);
const time = `${hour}:${minute}`;
return {
date: `${month}월 ${day}일 (${weekday})`,
compact: `${month}/${day} (${weekday}) ${time}`,
month,
day,
weekday,
hour,
minute,
time,
};
}
export function getHistoryMatchTitle(
title: string,
schedule: ReturnType<typeof getHomeMatchSchedule>,
) {
if (!schedule) return title;
// Only shorten a generic date-based title when its entire date and time match the row.
const generic =
/^(\d{1,2})\/(\d{1,2})\s*\(([월화수목금토일])\)\s*(\d{1,2})(?:시(?:\s*(\d{1,2})분)?|:(\d{2}))\s*(정기\s*내전|내전)$/u.exec(
title.trim(),
);
if (!generic) return title;
const [, month, day, weekday, hour, minutes, colonMinutes, name] = generic;
return Number(month) === Number(schedule.month) &&
Number(day) === Number(schedule.day) &&
weekday === schedule.weekday &&
Number(hour) === Number(schedule.hour) &&
Number(minutes ?? colonMinutes ?? 0) === Number(schedule.minute)
? name
: title;
}
export function getHomeMatchEnrollment(
match: Pick<
MatchDetailResponse,
'status' | 'joined' | 'participants' | 'maxParticipants'
>,
) {
const current = match.participants.length;
const remaining = match.maxParticipants - current;
const isRecruiting = match.status === 'recruiting';
const canApply = isRecruiting && remaining > 0 && !match.joined;
const capacity =
match.maxParticipants > 0
? `${current}/${match.maxParticipants}명`
: `${current}명`;
const label =
isRecruiting && match.joined
? '참가 완료'
: canApply
? `${remaining}자리 남음`
: '모집 마감';
return { canApply, capacity, label };
}