From 78a8f136d0fc2352f98f81059f431ab16d156531 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=EB=8B=A4=ED=98=84=20=28Dahyeon=20Park=29?= Date: Thu, 16 Apr 2026 22:33:00 +0900 Subject: [PATCH] feat(web): add auction page --- apps/web/src/pages/AuctionPage.tsx | 1072 ++++++++++++++++++++++++++++ 1 file changed, 1072 insertions(+) create mode 100644 apps/web/src/pages/AuctionPage.tsx diff --git a/apps/web/src/pages/AuctionPage.tsx b/apps/web/src/pages/AuctionPage.tsx new file mode 100644 index 00000000..0478e23f --- /dev/null +++ b/apps/web/src/pages/AuctionPage.tsx @@ -0,0 +1,1072 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { Link, useLocation, useParams } from 'react-router'; +import { + useAuction, + useAuctionHistory, + useDdragonManifest, + useMatch, + useMe, + useUndoAuction, +} from '../api/hooks'; +import { + mapApiAuctionToAuctionState, + type AuctionStateView, +} from '../api/mappers'; +import { useAuctionSocket } from '../api/useAuctionSocket'; +import { + DEFAULT_COMMUNITY_ID, + setDevCaptainTeamIndex, + useDevCaptainTeamIndex, +} from '../config'; +import { ApiError } from '../lib/api'; +import { + championDisplayName, + championIconUrl, + profileIconUrl, +} from '../lib/ddragon'; +import { + positionIcon, + positionLabel, + teamIndexColorClasses, + teamIndexLabel, +} from '../lib/league'; +import type { + ApiAuction, + ApiRiotLaneStats, + ApiTierInfo, + Position, +} from '../api/types'; + +type CaptainRole = { + teamIndex: number; +}; + +const TIER_NAMES: Record = { + IRON: '아이언', + BRONZE: '브론즈', + SILVER: '실버', + GOLD: '골드', + PLATINUM: '플래티넘', + EMERALD: '에메랄드', + DIAMOND: '다이아몬드', + MASTER: '마스터', + GRANDMASTER: '그랜드마스터', + CHALLENGER: '챌린저', +}; + +function formatPoints(value: number) { + return value.toLocaleString(); +} + +function relativeTime(dateLike: string) { + const seconds = Math.max( + 0, + Math.floor((Date.now() - new Date(dateLike).getTime()) / 1000), + ); + if (seconds < 60) return `${seconds}초 전`; + const minutes = Math.floor(seconds / 60); + if (minutes < 60) return `${minutes}분 전`; + const hours = Math.floor(minutes / 60); + if (hours < 24) return `${hours}시간 전`; + return `${Math.floor(hours / 24)}일 전`; +} + +function normalizeRank(rank: string | undefined) { + switch (rank) { + case 'I': + return '1'; + case 'II': + return '2'; + case 'III': + return '3'; + case 'IV': + return '4'; + default: + return rank; + } +} + +function formatRankBadge(tier: ApiTierInfo | undefined) { + if (!tier) return 'U'; + const tierInitial = + tier.tier === 'GRANDMASTER' ? 'GM' : tier.tier.slice(0, 1); + const rank = normalizeRank(tier.rank); + return rank ? `${tierInitial}${rank}` : tierInitial; +} + +function formatRankDetail(tier: ApiTierInfo | undefined) { + if (!tier) return '랭크 정보 없음'; + const tierName = TIER_NAMES[tier.tier] ?? tier.tier; + const rank = normalizeRank(tier.rank); + const label = rank ? `${tierName} ${rank}` : tierName; + return `${label} - ${tier.leaguePoints} LP`; +} + +function rankBadgeClass(tier: ApiTierInfo | undefined) { + switch (tier?.tier) { + case 'CHALLENGER': + return 'border-amber-500/60 bg-amber-100 text-amber-900 dark:border-amber-400/40 dark:bg-amber-400/20 dark:text-amber-200'; + case 'GRANDMASTER': + return 'border-red-500/60 bg-red-100 text-red-800 dark:border-red-400/40 dark:bg-red-400/20 dark:text-red-200'; + case 'MASTER': + return 'border-fuchsia-500/60 bg-fuchsia-100 text-fuchsia-800 dark:border-fuchsia-400/40 dark:bg-fuchsia-400/20 dark:text-fuchsia-200'; + case 'DIAMOND': + return 'border-cyan-500/60 bg-cyan-100 text-cyan-800 dark:border-cyan-400/40 dark:bg-cyan-400/20 dark:text-cyan-200'; + case 'EMERALD': + return 'border-emerald-500/60 bg-emerald-100 text-emerald-800 dark:border-emerald-400/40 dark:bg-emerald-400/20 dark:text-emerald-200'; + case 'PLATINUM': + return 'border-teal-500/60 bg-teal-100 text-teal-800 dark:border-teal-400/40 dark:bg-teal-400/20 dark:text-teal-200'; + case 'GOLD': + return 'border-amber-500/70 bg-amber-100 text-amber-900 dark:border-yellow-400/40 dark:bg-yellow-400/20 dark:text-yellow-200'; + case 'SILVER': + return 'border-slate-400/60 bg-slate-100 text-slate-700 dark:border-slate-300/40 dark:bg-slate-300/15 dark:text-slate-200'; + case 'BRONZE': + return 'border-orange-600/60 bg-orange-100 text-orange-800 dark:border-orange-500/40 dark:bg-orange-500/20 dark:text-orange-200'; + case 'IRON': + return 'border-stone-500/60 bg-stone-100 text-stone-700 dark:border-stone-400/40 dark:bg-stone-400/15 dark:text-stone-300'; + default: + return 'border-base-content/30 bg-transparent text-base-content/50'; + } +} + +function RankBadge({ tier }: { tier?: ApiTierInfo }) { + const tooltip = formatRankDetail(tier); + + return ( + + + {formatRankBadge(tier)} + + + ); +} + +function ResponsiveTierLabel({ tier }: { tier?: ApiTierInfo }) { + return ( + + + + {formatRankDetail(tier)} + + + ); +} + +function isCurrentBidder( + currentBidder: AuctionStateView['currentBidder'], + team: Pick, +) { + return currentBidder?.teamIndex === team.teamIndex; +} + +function getAuctionUpdatedAt(auction: ApiAuction | null | undefined) { + if (!auction) return 0; + return Date.parse(auction.updatedAt ?? auction.createdAt ?? '') || 0; +} + +function pickLatestAuction( + socketAuction: ApiAuction | null, + queryAuction: ApiAuction | undefined, +) { + if (!socketAuction) return queryAuction ?? null; + if (!queryAuction) return socketAuction; + return getAuctionUpdatedAt(queryAuction) > getAuctionUpdatedAt(socketAuction) + ? queryAuction + : socketAuction; +} + +const AUCTION_MAX_TEAM_SIZE = 5; +const LANE_ROWS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP']; +const POSITION_TO_RIOT_LANE = { + TOP: 'TOP', + JGL: 'JUNGLE', + MID: 'MIDDLE', + ADC: 'BOTTOM', + SUP: 'UTILITY', +} as const; + +function PosBadge({ pos }: { pos: Position }) { + return ( + + + {positionLabel[pos]} + + ); +} + +function TimerBar({ timer, maxTimer }: { timer: number; maxTimer: number }) { + const pct = maxTimer > 0 ? (timer / maxTimer) * 100 : 0; + const urgent = timer <= 5; + + return ( +
+
+
+ ); +} + +function getWinRate(stats: ApiRiotLaneStats) { + return stats.games > 0 ? Math.round((stats.wins / stats.games) * 100) : 0; +} + +function getWinRateClass(winRate: number) { + if (winRate >= 55) return 'text-blue-400'; + if (winRate >= 50) return 'text-base-content'; + return 'text-red-400'; +} + +function formatKdaRatio(stats: ApiRiotLaneStats) { + if (stats.avgDeaths === 0) return 'Perfect'; + return ((stats.avgKills + stats.avgAssists) / stats.avgDeaths).toFixed(2); +} + +function RecentSoloStats({ + player, +}: { + player: NonNullable; +}) { + const primaryStats = player.recentStats.primary; + + if (!primaryStats) { + return ( +
+

+ 최근 솔로랭크 +

+
+ 최근 솔로랭크 기록이 없습니다 +
+
+ ); + } + + const primaryWinRate = getWinRate(primaryStats); + const primaryKdaRatio = formatKdaRatio(primaryStats); + + return ( +
+
+
+

+ 최근 솔로랭크 +

+
+ + {positionLabel[player.mainPosition]} + + {player.recentStats.primarySource === 'overall' ? ( + + 전체 기준 + + ) : null} +
+
+
+ {primaryWinRate}% +
+
+ +
+
+ 전적 + + {primaryStats.wins}W{' '} + {primaryStats.losses}L + +
+
+ KDA + + {primaryStats.avgKills}/{primaryStats.avgDeaths}/{primaryStats.avgAssists} + = 3 ? 'text-emerald-400' : 'text-base-content/50'}`} + > + ({primaryKdaRatio}) + + +
+
+ 분당 CS + + {primaryStats.avgCsPerMin} + +
+
+ +
+ {LANE_ROWS.map((position) => { + const laneStats = + player.recentStats.byLane[POSITION_TO_RIOT_LANE[position]]; + const isMainLane = position === player.mainPosition; + + return ( +
+ + {positionLabel[position]} + + {laneStats && laneStats.games > 0 ? ( + + {laneStats.wins}W {laneStats.losses}L · {laneStats.avgKills}/ + {laneStats.avgDeaths}/{laneStats.avgAssists} ·{' '} + {laneStats.avgCsPerMin} CS/min + + ) : ( + — + )} +
+ ); + })} +
+
+ ); +} + +function TeamPanel({ + team, + isActive, + isLeft, + historyBackTo, +}: { + team: AuctionStateView['teams'][number]; + isActive: boolean; + isLeft: boolean; + historyBackTo: string; +}) { + const { data: ddragon } = useDdragonManifest(); + const tone = teamIndexColorClasses(team.teamIndex); + const teamSize = team.members.length + 1; + const isFull = teamSize >= AUCTION_MAX_TEAM_SIZE; + + return ( +
+
+
+
+
+ + {teamIndexLabel(team.teamIndex, team.name)} + + + 팀장: {team.captainName} + +
+ + {formatPoints(team.points)}P + +
+
+ + 팀장 포함 {teamSize}/{AUCTION_MAX_TEAM_SIZE} + + {isFull && 정원 완료} +
+
+ +
+ {team.members.length === 0 ? ( +
+ 아직 멤버가 없습니다 +
+ ) : ( + team.members.map((member) => ( +
+ +
+ +
+ +
+ + {member.summonerName} + +
+ + + {positionLabel[member.assignedPosition]} + + + {member.cost} + +
+ )) + )} + + {Array.from({ + length: Math.max(0, AUCTION_MAX_TEAM_SIZE - 1 - team.members.length), + }).map((_, index) => ( +
+
+ — +
+ ))} +
+
+ ); +} + +function PlayerSpotlight({ + state, + historyBackTo, +}: { + state: AuctionStateView; + historyBackTo: string; +}) { + const { data: ddragon } = useDdragonManifest(); + const player = state.currentPlayer; + if (!player) return null; + + return ( +
+
+
+ + + +
+
+ + {player.summonerName} + + + #{player.tag} + +
+
+ +
+
+ + + {' '} + {positionLabel[player.subPosition]} + +
+
+
+
+ +
+
+

+ 숙련도 높은 챔피언 +

+
+ {player.masteries.length > 0 ? ( + player.masteries.map((mastery) => { + const iconUrl = championIconUrl(ddragon, mastery.championId); + const displayName = + championDisplayName(ddragon, mastery.championId) ?? + String(mastery.championId); + return ( +
+
+ {iconUrl ? ( + {displayName} + ) : null} +
+
+
+ {displayName} +
+
+ Lv.{mastery.level} · {(mastery.points / 1000).toFixed(0)}K +
+
+
+ ); + }) + ) : ( +
+ 숙련도 데이터가 없습니다. +
+ )} +
+
+ + +
+ + {(state.phase === 'bidding' || state.phase === 'sold') && ( +
+
+ + {state.phase === 'sold' ? '낙찰가' : '현재 입찰가'} + +
+ {state.currentBidder && ( + + {teamIndexLabel(state.currentBidder.teamIndex)} + + )} + + {state.currentBid > 0 ? formatPoints(state.currentBid) : '—'} + +
+
+
+ )} + {state.phase === 'passed' && ( +
+ + 유찰{' '} + {state.auctionRound === 1 + ? '— 마지막에 다시 등장합니다' + : '— 강제 배정 대상'} + +
+ )} +
+ ); +} + +function BidControls({ + state, + captainRole, + onBid, +}: { + state: AuctionStateView; + captainRole: CaptainRole | null; + onBid: (teamIndex: number, amount: number) => void; +}) { + const [bidAmount, setBidAmount] = useState(100); + const minBid = state.currentBid + 10; + const activeTeam = captainRole + ? state.teams.find((team) => team.teamIndex === captainRole.teamIndex) + : null; + const activeTeamSize = activeTeam ? activeTeam.members.length + 1 : 0; + const isActiveTeamFull = activeTeamSize >= AUCTION_MAX_TEAM_SIZE; + + useEffect(() => { + setBidAmount(Math.max(minBid, Math.ceil(minBid / 10) * 10)); + }, [state.currentBid, minBid]); + + if (state.phase !== 'bidding') return null; + + if (!activeTeam) { + return ( +
+ 관전자 모드입니다. 우측 상단에서 조작자 역할을 선택하면 입찰할 수 있습니다. +
+ ); + } + + const presets = [50, 100, 150, 200, 300, 500]; + + return ( +
+
+ {presets.map((preset) => ( + + ))} + + setBidAmount(Math.max(minBid, Number(event.target.value))) + } + min={minBid} + disabled={isActiveTeamFull} + className="w-24 text-xs px-2 py-1 border border-base-content/10 bg-transparent text-base-content tabular-nums text-right focus:outline-none focus:border-primary/30" + /> +
+ +
+ ); +} + +function BidLog({ bids }: { bids: AuctionStateView['bids'] }) { + const endRef = useRef(null); + + useEffect(() => { + endRef.current?.scrollIntoView({ behavior: 'smooth' }); + }, [bids.length]); + + if (bids.length === 0) return null; + + return ( +
+
+ + 입찰 기록 + +
+
+ {bids.map((bid, index) => ( +
+ + {teamIndexLabel(bid.teamIndex)} + + → + + {formatPoints(bid.amount)}P + +
+ ))} +
+
+
+ ); +} + +export default function AuctionPage() { + const { id } = useParams(); + const location = useLocation(); + const queryClient = useQueryClient(); + const meQuery = useMe(); + const currentUser = + meQuery.data?.memberships.find( + (membership) => membership.community?._id === DEFAULT_COMMUNITY_ID, + )?.user ?? null; + const canManageAuction = + import.meta.env.DEV || + currentUser?.role === 'owner' || + currentUser?.role === 'admin'; + const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); + const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID, { + refetchInterval: 5000, + }); + const historyQuery = useAuctionHistory(id, DEFAULT_COMMUNITY_ID, { + enabled: canManageAuction, + refetchInterval: 3000, + }); + const undoMutation = useUndoAuction(DEFAULT_COMMUNITY_ID); + const socket = useAuctionSocket(id); + const captainTeamIndex = useDevCaptainTeamIndex(); + const [now, setNow] = useState(() => Date.now()); + const [assignedPosition, setAssignedPosition] = useState('MID'); + const historyBackTo = `${location.pathname}${location.search}${location.hash}`; + + useEffect(() => { + const timer = window.setInterval(() => setNow(Date.now()), 1000); + return () => window.clearInterval(timer); + }, []); + + const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data); + const auctionState = + liveAuction && matchQuery.data + ? mapApiAuctionToAuctionState(liveAuction, matchQuery.data, new Date(now)) + : null; + const availableTeamIndexes = useMemo(() => { + const indexes = new Set((auctionState?.teams ?? []).map((team) => team.teamIndex)); + return [...indexes].sort((left, right) => left - right); + }, [auctionState?.teams]); + const captainRole: CaptainRole | null = + captainTeamIndex === null + ? null + : { + teamIndex: captainTeamIndex, + }; + + useEffect(() => { + if (auctionState?.currentPlayer) { + setAssignedPosition(auctionState.currentPlayer.mainPosition); + } + }, [auctionState?.currentPlayer?.id]); + + useEffect(() => { + if (availableTeamIndexes.length === 0) return; + if (captainTeamIndex !== null && !availableTeamIndexes.includes(captainTeamIndex)) { + setDevCaptainTeamIndex(availableTeamIndexes[0]); + } + }, [availableTeamIndexes, captainTeamIndex]); + + if (!DEFAULT_COMMUNITY_ID) { + return ( +
+ + `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. + +
+ ); + } + + if (matchQuery.isLoading || (auctionQuery.isLoading && !socket.auction)) { + return ( +
+ 경매를 연결하는 중... +
+ ); + } + + if (auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404 && !socket.auction) { + return ( +
+

경매가 아직 시작되지 않았습니다

+ + 내전 상세로 돌아가기 + +
+ ); + } + + if (!auctionState || !matchQuery.data) { + return ( +
+ + 경매 상태를 불러오지 못했습니다. + +
+ ); + } + + const phaseLabel: Record = { + waiting: '경매 준비 중...', + presenting: '다음 선수 등장', + bidding: '입찰 진행 중', + sold: '낙찰!', + passed: '유찰 — 다음 선수로', + complete: '경매 완료', + }; + const errorMessage = + socket.error ?? + (auctionQuery.error instanceof Error ? auctionQuery.error.message : null); + + function handleUndo(sequence: number) { + if (!id) return; + if (!window.confirm(`${sequence}번 액션 직전으로 되돌릴까요?`)) return; + undoMutation.mutate( + { matchId: id, sequence }, + { + onSuccess: async () => { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: ['auction', DEFAULT_COMMUNITY_ID, id], + }), + queryClient.invalidateQueries({ + queryKey: ['auction-history', DEFAULT_COMMUNITY_ID, id], + }), + queryClient.invalidateQueries({ + queryKey: ['match', DEFAULT_COMMUNITY_ID, id], + }), + ]); + }, + }, + ); + } + + const undoPanel = canManageAuction ? ( +
+
+ 되돌리기 (Undo) +
+
+ {historyQuery.data?.length ? ( + historyQuery.data.map((entry) => ( + + )) + ) : ( +
+ 기록이 없습니다 +
+ )} +
+
+ ) : null; + + return ( +
+ + + + + 내전 상세로 + + + {errorMessage && ( +
+ {errorMessage} +
+ )} + + {undoMutation.error instanceof Error && ( +
+ {undoMutation.error.message} +
+ )} + +
+
+

+ 경매 팀빌딩 +

+

+ {Math.min(auctionState.currentPlayerIndex + 1, Math.max(auctionState.totalPlayers, 1))} /{' '} + {auctionState.totalPlayers} 선수 +

+
+
+
+ + {phaseLabel[auctionState.phase]} + + {auctionState.phase === 'bidding' && ( + + {auctionState.timer}s + + )} +
+
+ 소켓: {socket.connectionStatus} + {/* 임시 운영용: 로그인/권한 확인 없이 조작자 역할을 선택할 수 있게 열어둔다. */} + +
+
+
+ + {auctionState.phase === 'bidding' && ( + + )} + +
+
+ {auctionState.teams.map((team) => ( + + ))} +
+ +
+ {auctionState.phase === 'complete' ? ( + <> +
+
+ 경매 완료 +
+
+ 모든 선수가 팀에 배정되었습니다. +
+ + 결과 확인 + +
+ {undoPanel} + + ) : ( + <> + + + {auctionState.phase === 'sold' && auctionState.currentBidder && ( +
+ {teamIndexLabel(auctionState.currentBidder.teamIndex)} 낙찰 + {' '}— {formatPoints(auctionState.currentBid)}P +
+ )} + + + socket.placeBid({ teamIndex, amount }) + } + /> + + + {canManageAuction && ( +
+
+ Auction Controls +
+ {auctionState.phase === 'presenting' && ( + + )} + {auctionState.phase === 'bidding' && ( +
+ + +
+ )} + {(auctionState.phase === 'sold' || + auctionState.phase === 'passed') && ( + + )} +
+ )} + {undoPanel} + + )} +
+
+
+ ); +}