From e50a6833363d6f8dce64240c4312993dc86abf4c Mon Sep 17 00:00:00 2001 From: dahyeon Date: Wed, 24 Jun 2026 02:47:10 -0700 Subject: [PATCH] feat: enhance auction internal profile --- .../community-stats.service.spec.ts | 50 + .../community-stats.service.ts | 4 +- .../match-history/match-history.types.ts | 2 + apps/web/src/api/types.ts | 2 + apps/web/src/index.css | 45 + apps/web/src/pages/AuctionPage.tsx | 1510 +++++++++++++---- 6 files changed, 1248 insertions(+), 365 deletions(-) diff --git a/apps/api/src/modules/community-stats/community-stats.service.spec.ts b/apps/api/src/modules/community-stats/community-stats.service.spec.ts index dd58fe4a..4c340dd4 100644 --- a/apps/api/src/modules/community-stats/community-stats.service.spec.ts +++ b/apps/api/src/modules/community-stats/community-stats.service.spec.ts @@ -191,4 +191,54 @@ describe('CommunityStatsService', () => { response, ); }); + + it('includes internal match route fields in user internal history matches', async () => { + const communityId = new mongoose.Types.ObjectId(); + const matchId = new mongoose.Types.ObjectId(); + const userId = new mongoose.Types.ObjectId(); + const participant = record(matchId); + participant.userId = userId.toString(); + participant.gameNumber = 2; + participant.riotMatchId = 'KR_1234'; + + const cacheService = { + get: jest.fn().mockResolvedValue(null), + set: jest.fn().mockResolvedValue(undefined), + } as unknown as jest.Mocked; + const service = new CommunityStatsService( + {} as ConnectionService, + cacheService, + {} as MatchStatsRepository, + {} as MatchStatsService, + ); + (service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset = + jest.fn().mockResolvedValue({ + season: { + id: 'all', + label: '전체', + startTime: null, + endTime: null, + }, + matches: [], + records: [participant], + detailsByMatchId: new Map(), + }); + + const response = await service.getUserInternalHistory({ + communityId, + userId, + filters: { limit: 5 }, + }); + + expect(response.matches[0]).toMatchObject({ + matchId: 'KR_1234', + internalMatchId: matchId.toString(), + gameNumber: 2, + queueLabel: '내전', + }); + expect(cacheService.set).toHaveBeenCalledWith( + expect.stringContaining(`userInternal:v2:${userId.toString()}`), + response, + ); + }); }); diff --git a/apps/api/src/modules/community-stats/community-stats.service.ts b/apps/api/src/modules/community-stats/community-stats.service.ts index 98179bd8..9244dee8 100644 --- a/apps/api/src/modules/community-stats/community-stats.service.ts +++ b/apps/api/src/modules/community-stats/community-stats.service.ts @@ -293,7 +293,7 @@ export class CommunityStatsService { filters: CommunityStatsFilters; }): Promise { const key = this.cacheKey( - `userInternal:${params.userId.toString()}`, + `userInternal:v2:${params.userId.toString()}`, params.communityId, params.filters, ); @@ -789,6 +789,8 @@ export class CommunityStatsService { ?.find((game) => game.riotMatchId === record.riotMatchId); return { matchId: record.riotMatchId, + internalMatchId: record.matchId, + gameNumber: record.gameNumber, queueId: 0, queueLabel: '내전', gameCreation: record.gameCreation, diff --git a/apps/api/src/modules/match-history/match-history.types.ts b/apps/api/src/modules/match-history/match-history.types.ts index 800a132a..29d7393d 100644 --- a/apps/api/src/modules/match-history/match-history.types.ts +++ b/apps/api/src/modules/match-history/match-history.types.ts @@ -135,6 +135,8 @@ export interface RecentMatchTeamParticipantView { export interface RecentMatchView { matchId: string; + internalMatchId?: string; + gameNumber?: number; queueId: number; queueLabel: string; gameCreation: number; diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index 7df6726a..4a338cdf 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -661,6 +661,8 @@ export interface ApiRecentMatchTeam { export interface ApiRecentMatchView { matchId: string; + internalMatchId?: string; + gameNumber?: number; queueId: number; queueLabel: string; gameCreation: number; diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 6466857d..4fccb9fa 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -122,6 +122,51 @@ body { --color-base-300: oklch(95% 0 0); /* 구분선/보더 */ } +/* ── 실시간 입찰 피드백 모션 ── + 입찰가 갱신 시 pop(스케일 펄스), 내가 밀렸을 때 shake(주의 환기). */ +@keyframes lts-bid-pop { + 0% { + transform: scale(1); + } + 35% { + transform: scale(1.14); + } + 100% { + transform: scale(1); + } +} +@keyframes lts-outbid-shake { + 0%, + 100% { + transform: translateX(0); + } + 20% { + transform: translateX(-3px); + } + 40% { + transform: translateX(3px); + } + 60% { + transform: translateX(-2px); + } + 80% { + transform: translateX(2px); + } +} +.animate-bid-pop { + animation: lts-bid-pop 0.45s cubic-bezier(0.34, 1.56, 0.64, 1); + transform-origin: right center; +} +.animate-outbid-shake { + animation: lts-outbid-shake 0.4s ease-in-out; +} +@media (prefers-reduced-motion: reduce) { + .animate-bid-pop, + .animate-outbid-shake { + animation: none; + } +} + /* poro.gg style: 모든 모서리 각지게 */ *, *::before, diff --git a/apps/web/src/pages/AuctionPage.tsx b/apps/web/src/pages/AuctionPage.tsx index 91ab2a31..254482f8 100644 --- a/apps/web/src/pages/AuctionPage.tsx +++ b/apps/web/src/pages/AuctionPage.tsx @@ -9,10 +9,10 @@ import { useState, type FormEvent, type KeyboardEvent, -} from 'react'; -import { useQueryClient } from '@tanstack/react-query'; -import { AlertTriangle, SendHorizontal } from 'lucide-react'; -import { Link, useLocation, useNavigate, useParams } from 'react-router'; +} from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { AlertTriangle, SendHorizontal } from "lucide-react"; +import { Link, useLocation, useNavigate, useParams } from "react-router"; import { useAuction, useAuctionHistory, @@ -22,44 +22,48 @@ import { useResetAuction, useUndoAuction, useUserHistoryProfile, -} from '../api/hooks'; + useUserInternalHistory, +} from "../api/hooks"; import { mapApiAuctionToAuctionState, type AuctionPlayerView, type AuctionStateView, -} from '../api/mappers'; +} from "../api/mappers"; import { useAuctionSocket, type BidLatencyDiagnostics, -} from '../api/useAuctionSocket'; +} from "../api/useAuctionSocket"; import { DEFAULT_COMMUNITY_ID, setDevCaptainTeamIndex, useDevCaptainTeamIndex, -} from '../config'; -import { ApiError } from '../lib/api'; +} from "../config"; +import { ApiError } from "../lib/api"; import { championDisplayName, championIconUrl, profileIconUrl, -} from '../lib/ddragon'; +} from "../lib/ddragon"; import { positionIcon, positionLabel, teamIndexColorClasses, teamIndexLabel, -} from '../lib/league'; -import { RankBadge, ResponsiveTierLabel } from '../components/RankBadge'; +} from "../lib/league"; +import { RankBadge, ResponsiveTierLabel } from "../components/RankBadge"; import type { ApiAuction, ApiAuctionChatMessage, + ApiRecentMatchView, ApiTierHistoryEntry, ApiRiotLaneStats, ApiUser, + ApiUserInternalHistoryResponse, Position, -} from '../api/types'; +} from "../api/types"; +import { LANE_LABELS } from "../lib/riot-history"; -const TierHistoryChart = lazy(() => import('../components/TierHistoryChart')); +const TierHistoryChart = lazy(() => import("../components/TierHistoryChart")); type CaptainRole = { teamIndex: number; @@ -70,7 +74,7 @@ function formatPoints(value: number) { } function createClientRequestId(): string { - if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) { + if (typeof crypto !== "undefined" && "randomUUID" in crypto) { return crypto.randomUUID(); } return `${Date.now()}-${Math.random().toString(16).slice(2)}`; @@ -90,9 +94,9 @@ function relativeTime(dateLike: string) { } function formatChatTime(dateLike: string) { - return new Intl.DateTimeFormat('ko-KR', { - hour: '2-digit', - minute: '2-digit', + return new Intl.DateTimeFormat("ko-KR", { + hour: "2-digit", + minute: "2-digit", }).format(new Date(dateLike)); } @@ -111,23 +115,23 @@ function resolveChatSenderLabel( if (currentUser?.kakaoTalkNickname) return currentUser.kakaoTalkNickname; if (currentUser?.discordNickname) return currentUser.discordNickname; if (captainRole) return `${teamIndexLabel(captainRole.teamIndex)} 팀장`; - return '관전자'; + return "관전자"; } function isCurrentBidder( - currentBidder: AuctionStateView['currentBidder'], - team: Pick, + 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; + return Date.parse(auction.updatedAt ?? auction.createdAt ?? "") || 0; } function getAuctionRevision(auction: ApiAuction | null | undefined) { - return typeof auction?.revision === 'number' ? auction.revision : null; + return typeof auction?.revision === "number" ? auction.revision : null; } function pickLatestAuction( @@ -154,22 +158,22 @@ function pickLatestAuction( const AUCTION_MAX_TEAM_SIZE = 5; const AUCTION_MIN_BID_POINTS = 10; -const LANE_ROWS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP']; +const LANE_ROWS: Position[] = ["TOP", "JGL", "MID", "ADC", "SUP"]; const POSITION_TO_RIOT_LANE = { - TOP: 'TOP', - JGL: 'JUNGLE', - MID: 'MIDDLE', - ADC: 'BOTTOM', - SUP: 'UTILITY', + TOP: "TOP", + JGL: "JUNGLE", + MID: "MIDDLE", + ADC: "BOTTOM", + SUP: "UTILITY", } as const; const LIVE_TIMER_TICK_MS = 100; -function getAuctionTeamSize(team: AuctionStateView['teams'][number]) { +function getAuctionTeamSize(team: AuctionStateView["teams"][number]) { return team.members.length + 1; } function getReservedPointsAfterCurrentBid( - team: AuctionStateView['teams'][number], + team: AuctionStateView["teams"][number], ) { const remainingSlotsAfterCurrentBid = Math.max( 0, @@ -178,14 +182,14 @@ function getReservedPointsAfterCurrentBid( return remainingSlotsAfterCurrentBid * AUCTION_MIN_BID_POINTS; } -function getMaxBidForTeam(team: AuctionStateView['teams'][number]) { +function getMaxBidForTeam(team: AuctionStateView["teams"][number]) { return Math.max(0, team.points - getReservedPointsAfterCurrentBid(team)); } function formatLatencyMs(value: number | undefined) { - return typeof value === 'number' && Number.isFinite(value) + return typeof value === "number" && Number.isFinite(value) ? `${Math.round(value)}ms` - : '-'; + : "-"; } function formatBidLatencyDiagnostics( @@ -195,14 +199,15 @@ function formatBidLatencyDiagnostics( const serverDeadlineTimestampMS = diagnostics.bidDiagnostics?.currentBidRoundDeadlineTimestampMS; - const serverTimestampMS = diagnostics.bidDiagnostics?.currentServerTimestampMS; + const serverTimestampMS = + diagnostics.bidDiagnostics?.currentServerTimestampMS; const serverRemainingMS = - typeof diagnostics.serverObservedRemainingBidRoundTimeMS === 'number' + typeof diagnostics.serverObservedRemainingBidRoundTimeMS === "number" ? diagnostics.serverObservedRemainingBidRoundTimeMS - : typeof serverDeadlineTimestampMS === 'number' && - typeof serverTimestampMS === 'number' - ? serverDeadlineTimestampMS - serverTimestampMS - : undefined; + : typeof serverDeadlineTimestampMS === "number" && + typeof serverTimestampMS === "number" + ? serverDeadlineTimestampMS - serverTimestampMS + : undefined; const timing = diagnostics.bidServerTiming; const parts = [ `RTT ${formatLatencyMs(diagnostics.serverRoundTripDurationMS)}`, @@ -213,35 +218,67 @@ function formatBidLatencyDiagnostics( ]; if (timing?.fallbackFullStatePath) { - parts.push('fallback full-state'); + parts.push("fallback full-state"); } - if (typeof diagnostics.clientObservedRemainingBidRoundTimeMS === 'number') { + if (typeof diagnostics.clientObservedRemainingBidRoundTimeMS === "number") { parts.push( `client-left ${formatLatencyMs( diagnostics.clientObservedRemainingBidRoundTimeMS, )}`, ); } - if (typeof serverRemainingMS === 'number') { + if (typeof serverRemainingMS === "number") { parts.push(`server-left ${formatLatencyMs(serverRemainingMS)}`); } - return parts.join(' · '); + return parts.join(" · "); } function getSoloTierHistory(entries: ApiTierHistoryEntry[]) { - return entries.filter((entry) => entry.queueType === 'RANKED_SOLO_5x5'); + return entries.filter((entry) => entry.queueType === "RANKED_SOLO_5x5"); +} + +type PlayerProfileTab = "internal" | "solo"; +const INTERNAL_PROFILE_TOP_CHAMPION_LIMIT = 6; +const INTERNAL_PROFILE_RECENT_MATCH_LIMIT = 5; + +function formatAuctionHistoryDate(ms: number) { + return new Intl.DateTimeFormat("ko-KR", { + month: "short", + day: "numeric", + }).format(new Date(ms)); } function PosBadge({ pos }: { pos: Position }) { return ( - + {positionLabel[pos]} ); } +// 티어 뱃지(RankBadge)와 같은 높이의 텍스트 칩. 포지션 키(TOP/JGL/MID/ADC/SUP)는 +// 전부 3글자라 폭이 통일된다. 색은 중립 톤으로 둬서 컬러풀한 티어 뱃지와 경쟁하지 않게 한다. +function PosTag({ pos }: { pos: Position }) { + return ( + + {/* 자간(음수 letter-spacing)·장평(scaleX)을 글자에만 적용해 칩 폭을 더 줄인다. */} + + {pos} + + + ); +} + function getLiveRemainingSeconds( deadline: string | undefined, serverTimeOffsetMs: number, @@ -289,10 +326,7 @@ function useLiveRemainingSeconds( }; } - timerId = window.setInterval( - updateRemainingSeconds, - LIVE_TIMER_TICK_MS, - ); + timerId = window.setInterval(updateRemainingSeconds, LIVE_TIMER_TICK_MS); return () => { if (timeoutId) window.clearTimeout(timeoutId); @@ -349,7 +383,7 @@ function AuctionTimerText({ return ( {timer.toFixed(1)}s @@ -358,10 +392,12 @@ function AuctionTimerText({ function TimerBar({ deadline, + heightClassName = "h-1.5", maxTimer, serverTimeOffsetMs, }: { deadline: string | undefined; + heightClassName?: string; maxTimer: number; serverTimeOffsetMs: number; }) { @@ -383,21 +419,22 @@ function TimerBar({ serverTimeOffsetRef.current, ); const nextScale = - maxTimer > 0 - ? Math.max(0, Math.min(1, remainingSeconds / maxTimer)) - : 0; + maxTimer > 0 ? Math.max(0, Math.min(1, remainingSeconds / maxTimer)) : 0; - bar.style.transition = 'none'; + bar.style.transition = "none"; bar.style.transform = `scaleX(${nextScale})`; - bar.classList.toggle('bg-red-500', remainingSeconds <= 5); - bar.classList.toggle('bg-primary', remainingSeconds > 5); + bar.classList.toggle("bg-red-500", remainingSeconds <= 5); + bar.classList.toggle("bg-primary", remainingSeconds > 5); void bar.offsetWidth; if (remainingSeconds > 5) { - urgentTimeoutId = window.setTimeout(() => { - bar.classList.remove('bg-primary'); - bar.classList.add('bg-red-500'); - }, (remainingSeconds - 5) * 1000); + urgentTimeoutId = window.setTimeout( + () => { + bar.classList.remove("bg-primary"); + bar.classList.add("bg-red-500"); + }, + (remainingSeconds - 5) * 1000, + ); } animationFrameId = window.requestAnimationFrame(() => { @@ -408,7 +445,7 @@ function TimerBar({ bar.style.transition = `transform ${Math.round( currentRemainingSeconds * 1000, )}ms linear`; - bar.style.transform = 'scaleX(0)'; + bar.style.transform = "scaleX(0)"; }); return () => { @@ -420,11 +457,13 @@ function TimerBar({ }, [deadline, maxTimer]); return ( -
+
); @@ -435,20 +474,20 @@ function getWinRate(stats: ApiRiotLaneStats) { } function getWinRateClass(winRate: number) { - if (winRate >= 55) return 'text-blue-400'; - if (winRate >= 50) return 'text-base-content'; - return 'text-red-400'; + 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'; + if (stats.avgDeaths === 0) return "Perfect"; return ((stats.avgKills + stats.avgAssists) / stats.avgDeaths).toFixed(2); } function RecentSoloStats({ player, }: { - player: NonNullable; + player: NonNullable; }) { const primaryStats = player.recentStats.primary; @@ -479,10 +518,8 @@ function RecentSoloStats({ {positionLabel[player.mainPosition]} - {player.recentStats.primarySource === 'overall' ? ( - - 전체 기준 - + {player.recentStats.primarySource === "overall" ? ( + 전체 기준 ) : null}
@@ -497,16 +534,17 @@ function RecentSoloStats({
전적 - {primaryStats.wins}W{' '} + {primaryStats.wins}W{" "} {primaryStats.losses}L
KDA - {primaryStats.avgKills}/{primaryStats.avgDeaths}/{primaryStats.avgAssists} + {primaryStats.avgKills}/{primaryStats.avgDeaths}/ + {primaryStats.avgAssists} = 3 ? 'text-emerald-400' : 'text-base-content/50'}`} + className={`ml-1 font-bold ${Number(primaryKdaRatio) >= 3 ? "text-emerald-400" : "text-base-content/50"}`} > ({primaryKdaRatio}) @@ -529,16 +567,19 @@ function RecentSoloStats({ return (
- + {positionLabel[position]} {laneStats && laneStats.games > 0 ? ( {laneStats.wins}W {laneStats.losses}L · {laneStats.avgKills}/ - {laneStats.avgDeaths}/{laneStats.avgAssists} ·{' '} - {laneStats.avgCsPerMin} CS/min + {laneStats.avgDeaths}/{laneStats.avgAssists} ) : ( — @@ -551,13 +592,411 @@ function RecentSoloStats({ ); } +function PlayerProfileTabButton({ + active, + children, + onClick, +}: { + active: boolean; + children: string; + onClick: () => void; +}) { + return ( + + ); +} + +function AuctionProfileMetric({ + label, + value, + sub, +}: { + label: string; + value: string | number; + sub: string; +}) { + return ( +
+
+ {label} +
+
+ {value} +
+
{sub}
+
+ ); +} + +function InternalChampionSummary({ + champion, + ddragon, +}: { + champion: { + championId: number; + games: number; + winRate: number; + avgRating?: number; + kda?: number; + }; + ddragon: ReturnType["data"]; +}) { + const iconUrl = championIconUrl(ddragon, champion.championId); + const displayName = + championDisplayName(ddragon, champion.championId) ?? + String(champion.championId); + const rating = champion.avgRating ?? champion.kda ?? 0; + + return ( +
+
+ {iconUrl ? ( + {displayName} + ) : null} +
+
+
+ {displayName} +
+
+ {champion.games}게임 · {champion.winRate}% · 평점 {rating} +
+
+
+ ); +} + +function InternalRecentMatchRow({ + match, + ddragon, +}: { + match: ApiRecentMatchView; + ddragon: ReturnType["data"]; +}) { + const iconUrl = championIconUrl(ddragon, match.championId); + const championName = + championDisplayName(ddragon, match.championId) ?? String(match.championId); + const resultTone = match.win ? "text-blue-400" : "text-red-400"; + const detailPath = + match.internalMatchId && match.gameNumber + ? `/match/${match.internalMatchId}/game/${match.gameNumber}` + : null; + const content = ( + <> +
+ {iconUrl ? ( + {championName} + ) : null} +
+
+
+ + {match.remake ? "다시하기" : match.win ? "승리" : "패배"} + + + {championName} + +
+
+ {formatAuctionHistoryDate(match.gameCreation)} ·{" "} + {LANE_LABELS[match.teamPosition] ?? match.teamPosition} +
+
+
+
+ {match.kills}/{match.deaths}/{match.assists} +
+
{match.deaths === 0 ? "Perfect" : `${match.kda} 평점`}
+
+ + ); + const className = + "flex items-center gap-2 border border-base-content/8 px-2.5 py-2"; + + if (!detailPath) return
{content}
; + + return ( + + {content} + + ); +} + +function InternalHistorySkeleton() { + return ( +
+
+
+
+
+ +
+ {Array.from({ length: 2 }).map((_, index) => ( +
+
+
+
+
+ ))} +
+ +
+ {["champions", "matches"].map((section) => ( +
+
+
+ {Array.from({ length: 3 }).map((_, index) => ( +
+
+
+
+
+
+
+ ))} +
+
+ ))} +
+
+ ); +} + +function InternalHistorySnapshot({ + player, + ddragon, + historyBackTo, + isLoading, + firstPage, +}: { + player: NonNullable; + ddragon: ReturnType["data"]; + historyBackTo: string; + isLoading: boolean; + firstPage: ApiUserInternalHistoryResponse | undefined; +}) { + const summary = firstPage?.summary; + const matches = (firstPage?.matches ?? []).slice( + 0, + INTERNAL_PROFILE_RECENT_MATCH_LIMIT, + ); + const topChampions = (firstPage?.championStats.champions ?? []).slice( + 0, + INTERNAL_PROFILE_TOP_CHAMPION_LIMIT, + ); + + if (isLoading) { + return ; + } + + if (!summary && matches.length === 0) { + return ( +
+
+ 저장된 내전 기록이 없습니다 +
+ + 내전 전적 페이지 보기 + +
+ ); + } + + return ( +
+
+

+ 최근 {summary?.windowSize ?? matches.length}게임 내전 요약 +

+ + 자세히 + +
+ +
+ + +
+ +
+
+
+ 자주 플레이한 챔피언 +
+
+ {topChampions.length > 0 ? ( + topChampions.map((champion) => ( + + )) + ) : ( +
기록 없음
+ )} +
+
+ +
+
+ 최근 내전 +
+
+ {matches.length > 0 ? ( + matches.map((match) => ( + + )) + ) : ( +
기록 없음
+ )} +
+
+
+
+ ); +} + +function SoloRankSnapshot({ + player, + ddragon, + tierHistory, +}: { + player: NonNullable; + ddragon: ReturnType["data"]; + tierHistory: ApiTierHistoryEntry[]; +}) { + return ( + <> + {tierHistory.length > 0 && ( + + } + > + + + )} + +
+
+

+ 숙련도 높은 챔피언 +

+
+ {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 +
+
+
+ ); + }) + ) : ( +
+ 숙련도 데이터가 없습니다. +
+ )} +
+
+ + +
+ + ); +} + function TeamPanel({ team, isActive, isLeft, historyBackTo, }: { - team: AuctionStateView['teams'][number]; + team: AuctionStateView["teams"][number]; isActive: boolean; isLeft: boolean; historyBackTo: string; @@ -569,15 +1008,17 @@ function TeamPanel({ return (
- + {teamIndexLabel(team.teamIndex, team.name)} @@ -592,7 +1033,9 @@ function TeamPanel({ 팀장 포함 {teamSize}/{AUCTION_MAX_TEAM_SIZE} - {isFull && 정원 완료} + {isFull && ( + 정원 완료 + )}
@@ -657,9 +1100,13 @@ const MemoTeamPanel = memo(TeamPanel); function PlayerSpotlight({ state, + captainRole, + serverTimeOffsetMs, historyBackTo, }: { state: AuctionStateView; + captainRole: CaptainRole | null; + serverTimeOffsetMs: number; historyBackTo: string; }) { const player = state.currentPlayer; @@ -668,22 +1115,31 @@ function PlayerSpotlight({ return (
- +
); } +// serverTimeOffsetMs는 5초마다 갱신되지만 비교자에 넣지 않는다. deadline이 바뀌는 +// 순간(phase/currentBid 변화)에 항상 함께 리렌더되어 최신 offset이 반영되므로, +// 굳이 5초마다 리렌더할 필요가 없다. const MemoPlayerSpotlight = memo( PlayerSpotlight, (previous, next) => previous.historyBackTo === next.historyBackTo && + previous.captainRole?.teamIndex === next.captainRole?.teamIndex && areSameAuctionPlayerProfile( previous.state.currentPlayer, next.state.currentPlayer, ) && previous.state.phase === next.state.phase && previous.state.currentBid === next.state.currentBid && - previous.state.currentBidder?.teamIndex === next.state.currentBidder?.teamIndex && + previous.state.currentBidder?.teamIndex === + next.state.currentBidder?.teamIndex && previous.state.auctionRound === next.state.auctionRound, ); @@ -691,16 +1147,31 @@ function PlayerProfileDetails({ player, historyBackTo, }: { - player: NonNullable; + player: NonNullable; historyBackTo: string; }) { const { data: ddragon } = useDdragonManifest(); + const [tabState, setTabState] = useState<{ + playerId: string; + tab: PlayerProfileTab; + }>({ playerId: player.userId, tab: "internal" }); + const activeTab = + tabState.playerId === player.userId ? tabState.tab : "internal"; + const setActiveTab = (tab: PlayerProfileTab) => + setTabState({ playerId: player.userId, tab }); const snapshotSoloTierHistory = getSoloTierHistory(player.tierHistory); const historyProfileQuery = useUserHistoryProfile( player.userId, DEFAULT_COMMUNITY_ID, snapshotSoloTierHistory.length === 0, ); + const internalHistoryQuery = useUserInternalHistory( + player.userId, + { queueGroup: "internal" }, + DEFAULT_COMMUNITY_ID, + activeTab === "internal", + ); + const internalFirstPage = internalHistoryQuery.data?.pages[0]; const tierHistory = snapshotSoloTierHistory.length > 0 ? snapshotSoloTierHistory @@ -744,7 +1215,7 @@ function PlayerProfileDetails({ src={positionIcon[player.subPosition]} alt="" className="w-3.5 h-3.5 object-contain inline" - />{' '} + />{" "} {positionLabel[player.subPosition]}
@@ -752,67 +1223,44 @@ function PlayerProfileDetails({
- {tierHistory.length > 0 && ( - - } +
+ setActiveTab("internal")} > - + setActiveTab("solo")} + > + 솔로랭크 + +
+ +
+ {activeTab === "internal" ? ( + - - )} - -
-
-

- 숙련도 높은 챔피언 -

-
- {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 -
-
-
- ); - }) - ) : ( -
- 숙련도 데이터가 없습니다. -
- )} -
-
- - + ) : ( + + )}
); @@ -846,15 +1294,186 @@ function areSameAuctionPlayerProfile( ); } -function PlayerBidStatus({ state }: { state: AuctionStateView }) { +const OUTBID_ALERT_RESET_MS = 4000; + +// 입찰가가 오를 때 이전값→새값으로 굴려 "방금 올랐다"를 몸으로 느끼게 한다. +function useCountUp(value: number, durationMs = 450) { + const [display, setDisplay] = useState(value); + const displayRef = useRef(value); + + useEffect(() => { + displayRef.current = display; + }, [display]); + + useEffect(() => { + const from = displayRef.current; + const to = value; + if (from === to) return; + // 라운드가 바뀌어 입찰가가 초기화/감소하거나 동작 줄이기(reduced-motion)가 켜져 있으면 + // 역방향/불필요한 롤링 없이 즉시 스냅(duration 0). reduced-motion은 CSS 미디어 쿼리로는 + // JS rAF 애니메이션을 막을 수 없어 여기서 직접 확인한다. + const prefersReducedMotion = + typeof window !== 'undefined' && + window.matchMedia?.('(prefers-reduced-motion: reduce)').matches; + const effectiveDuration = to < from || prefersReducedMotion ? 0 : durationMs; + + let rafId = 0; + const start = performance.now(); + const tick = (now: number) => { + const progress = + effectiveDuration > 0 + ? Math.min(1, (now - start) / effectiveDuration) + : 1; + const eased = 1 - Math.pow(1 - progress, 3); + setDisplay(Math.round(from + (to - from) * eased)); + if (progress < 1) { + rafId = window.requestAnimationFrame(tick); + } + }; + rafId = window.requestAnimationFrame(tick); + + return () => window.cancelAnimationFrame(rafId); + }, [value, durationMs]); + + return display; +} + +function AnimatedBidPoints({ + amount, + className = "", +}: { + amount: number; + className?: string; +}) { + const display = useCountUp(amount); + const [popToken, setPopToken] = useState(0); + const isFirstRenderRef = useRef(true); + + // 값이 바뀔 때마다 key를 갱신해 pop 애니메이션을 처음부터 재생한다. + useEffect(() => { + if (isFirstRenderRef.current) { + isFirstRenderRef.current = false; + return; + } + const timeoutId = window.setTimeout( + () => setPopToken((token) => token + 1), + 0, + ); + return () => window.clearTimeout(timeoutId); + }, [amount]); + + return ( + 0 ? "animate-bid-pop" : ""} ${className}`} + > + {amount > 0 ? formatPoints(display) : "—"} + + ); +} + +// 내가 최고가였다가 다른 팀에게 밀린 "순간"을 일정 시간 동안만 강조한다. +function useJustOutbid( + currentBidderTeamIndex: number | undefined, + myTeamIndex: number | null, +) { + const [justOutbid, setJustOutbid] = useState(false); + const previousBidderRef = useRef(currentBidderTeamIndex); + + useEffect(() => { + const previousBidder = previousBidderRef.current; + previousBidderRef.current = currentBidderTeamIndex; + + const becameOutbid = + myTeamIndex !== null && + previousBidder === myTeamIndex && + currentBidderTeamIndex !== undefined && + currentBidderTeamIndex !== myTeamIndex; + + if (!becameOutbid) { + // 내가 다시 최고가가 되거나 라운드가 바뀌면 해제. + const clearId = window.setTimeout(() => setJustOutbid(false), 0); + return () => window.clearTimeout(clearId); + } + + const setId = window.setTimeout(() => setJustOutbid(true), 0); + const resetId = window.setTimeout( + () => setJustOutbid(false), + OUTBID_ALERT_RESET_MS, + ); + return () => { + window.clearTimeout(setId); + window.clearTimeout(resetId); + }; + }, [currentBidderTeamIndex, myTeamIndex]); + + return justOutbid; +} + +function PlayerBidStatus({ + state, + captainRole, + serverTimeOffsetMs, +}: { + state: AuctionStateView; + captainRole: CaptainRole | null; + serverTimeOffsetMs: number; +}) { + const myTeamIndex = captainRole?.teamIndex ?? null; + const currentBidderTeamIndex = state.currentBidder?.teamIndex; + const iAmHighestBidder = + myTeamIndex !== null && currentBidderTeamIndex === myTeamIndex; + const justOutbid = useJustOutbid(currentBidderTeamIndex, myTeamIndex); + const isSold = state.phase === "sold"; + const hasBid = state.currentBid > 0 && state.currentBidder != null; + + // 컨테이너 톤: 내가 최고가(안심·초록) / 밀린 순간(주의·빨강) / 중립. + const containerTone = iAmHighestBidder + ? "border-emerald-500/30 bg-emerald-500/[0.06]" + : justOutbid + ? "border-red-500/40 bg-red-500/[0.08] animate-outbid-shake" + : "border-base-content/8 bg-base-content/[0.02]"; + const amountTone = iAmHighestBidder ? "text-emerald-400" : "text-amber-400"; + + // 상태 라벨은 항상 "나" 1인칭 기준으로 분기한다. + let statusText: string; + let statusTone: string; + if (isSold) { + statusText = iAmHighestBidder ? "내가 낙찰!" : "낙찰 완료"; + statusTone = iAmHighestBidder ? "text-emerald-400" : "text-base-content/30"; + } else if (!hasBid) { + statusText = "첫 입찰 대기 중"; + statusTone = "text-base-content/30"; + } else if (iAmHighestBidder) { + statusText = "내가 최고 입찰 중"; + statusTone = "text-emerald-400"; + } else if (justOutbid && currentBidderTeamIndex !== undefined) { + statusText = `${teamIndexLabel(currentBidderTeamIndex)}에게 밀렸어요`; + statusTone = "text-red-400"; + } else if (currentBidderTeamIndex !== undefined) { + statusText = `${teamIndexLabel(currentBidderTeamIndex)} 입찰 중`; + statusTone = "text-base-content/45"; + } else { + statusText = "입찰 중"; + statusTone = "text-base-content/45"; + } + return ( <> - {(state.phase === 'bidding' || state.phase === 'sold') && ( -
-
- - {state.phase === 'sold' ? '낙찰가' : '현재 입찰가'} - + {(state.phase === "bidding" || isSold) && ( +
+
+
+ + {isSold ? "낙찰가" : "현재 입찰가"} + + + {statusText} + +
{state.currentBidder && ( )} - - {state.currentBid > 0 ? formatPoints(state.currentBid) : '—'} - +
+ {/* 타이머를 입찰가 박스 하단에 붙여 시선 이동 없이 마감 임박을 전달한다. */} + {state.phase === "bidding" && ( + + )}
)} - {state.phase === 'passed' && ( + {state.phase === "passed" && (
- 유찰{' '} + 유찰{" "} {state.auctionRound === 1 - ? '— 마지막에 다시 등장합니다' - : '— 강제 배정 대상'} + ? "— 마지막에 다시 등장합니다" + : "— 강제 배정 대상"}
)} @@ -912,7 +1541,7 @@ function BidControls({ const isBidExpired = useIsDeadlineExpired( state.deadline, serverTimeOffsetMs, - state.phase === 'bidding', + state.phase === "bidding", ); const effectiveBidAmount = activeTeam ? Math.min(maxBid, Math.max(minBid, bidAmount)) @@ -923,103 +1552,140 @@ function BidControls({ setBidAmount(activeTeam ? Math.min(maxBid, nextBid) : nextBid); }, [activeTeam, maxBid, minBid]); - if (state.phase !== 'bidding') return null; + if (state.phase !== "bidding") return null; if (!activeTeam) { return (
- 관전자 모드입니다. 우측 상단에서 조작자 역할을 선택하면 입찰할 수 있습니다. + 관전자 모드입니다. 우측 상단에서 조작자 역할을 선택하면 입찰할 수 + 있습니다.
); } - const presets = [50, 100, 150, 200, 300, 500]; + // 경매는 "현재가보다 얼마 더?"로 생각하므로 절대값이 아니라 증분 프리셋으로 제공한다. + const bidIncrements = [10, 50, 100, 200]; + const teamTone = teamIndexColorClasses(activeTeam.teamIndex); + const handlePlaceBid = () => onBid(activeTeam.teamIndex, effectiveBidAmount); + const isBidDisabled = + isBidPending || + !canAffordNextBid || + isBidExpired || + effectiveBidAmount > maxBid || + effectiveBidAmount <= state.currentBid; + const bidButtonLabel = isActiveTeamFull + ? `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 정원 완료 (${activeTeamSize}/${AUCTION_MAX_TEAM_SIZE})` + : isBidPending + ? "입찰 반영 중..." + : isBidExpired + ? "입찰 마감 확인 중" + : !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`; return ( -
-
-
-
보유
-
- {formatPoints(activeTeam.points)}P + <> +
+
+
+
보유
+
+ {formatPoints(activeTeam.points)}P +
+
+
+
이번 최대
+
+ {formatPoints(maxBid)}P +
+
+
+
보존
+
+ {formatPoints(reservedPoints)}P +
-
-
이번 최대
-
- {formatPoints(maxBid)}P -
-
-
-
보존
-
- {formatPoints(reservedPoints)}P -
-
-
-
- {presets.map((preset) => ( +
+ {bidIncrements.map((increment) => { + const presetBid = state.currentBid + increment; + const isSelected = bidAmount === presetBid; + return ( + + ); + })} - ))} - - setBidAmount(Math.min(maxBid, Math.max(minBid, Number(event.target.value)))) - } - min={minBid} - max={maxBid} - disabled={isBidPending || !canAffordNextBid} - 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" - /> + {/* 타이핑 중에는 클램프하지 않고(자릿수 입력 방해 방지) blur 시점에만 보정한다. */} + setBidAmount(Number(event.target.value))} + onBlur={(event) => + setBidAmount( + Math.min( + maxBid, + Math.max(minBid, Number(event.target.value) || minBid), + ), + ) + } + min={minBid} + max={maxBid} + disabled={isBidPending || !canAffordNextBid} + 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" + /> +
+
- -
+ + {/* 모바일 sticky 입찰 바: 스크롤 위치와 무관하게 항상 입찰 가능하게 한다. */} +
+ +
+ ); } -function BidLog({ bids }: { bids: AuctionStateView['bids'] }) { +function BidLog({ bids }: { bids: AuctionStateView["bids"] }) { const scrollRef = useRef(null); useEffect(() => { @@ -1039,7 +1705,10 @@ function BidLog({ bids }: { bids: AuctionStateView['bids'] }) {
{bids.map((bid, index) => ( -
+
@@ -1070,8 +1739,8 @@ export default function AuctionPage() { )?.user ?? null; const canManageAuction = import.meta.env.DEV || - currentUser?.role === 'owner' || - currentUser?.role === 'admin'; + currentUser?.role === "owner" || + currentUser?.role === "admin"; const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID, { refetchInterval: 5000, @@ -1084,18 +1753,21 @@ export default function AuctionPage() { const resetAuctionMutation = useResetAuction(DEFAULT_COMMUNITY_ID); const socket = useAuctionSocket(id); const captainTeamIndex = useDevCaptainTeamIndex(); - const [assignedPosition, setAssignedPosition] = useState('MID'); + const [assignedPosition, setAssignedPosition] = useState("MID"); const [showCancelModal, setShowCancelModal] = useState(false); - const [cancelConfirmText, setCancelConfirmText] = useState(''); + const [cancelConfirmText, setCancelConfirmText] = useState(""); + const [undoTargetSequence, setUndoTargetSequence] = useState( + null, + ); const cancelConfirmInputRef = useRef(null); const historyBackTo = `${location.pathname}${location.search}${location.hash}`; - const canConfirmAuctionCancel = cancelConfirmText.trim() === '예'; + const canConfirmAuctionCancel = cancelConfirmText.trim() === "예"; async function clearAuctionDataAfterCancel() { if (!id) return; - const auctionQueryKey = ['auction', DEFAULT_COMMUNITY_ID, id] as const; + const auctionQueryKey = ["auction", DEFAULT_COMMUNITY_ID, id] as const; const auctionHistoryQueryKey = [ - 'auction-history', + "auction-history", DEFAULT_COMMUNITY_ID, id, ] as const; @@ -1113,7 +1785,7 @@ export default function AuctionPage() { exact: true, }); await queryClient.invalidateQueries({ - queryKey: ['match', DEFAULT_COMMUNITY_ID, id], + queryKey: ["match", DEFAULT_COMMUNITY_ID, id], exact: true, }); } @@ -1132,7 +1804,9 @@ export default function AuctionPage() { [liveAuction, matchQuery.data], ); const availableTeamIndexes = useMemo(() => { - const indexes = new Set((auctionState?.teams ?? []).map((team) => team.teamIndex)); + const indexes = new Set( + (auctionState?.teams ?? []).map((team) => team.teamIndex), + ); return [...indexes].sort((left, right) => left - right); }, [auctionState?.teams]); const captainRole: CaptainRole | null = @@ -1151,7 +1825,10 @@ export default function AuctionPage() { useEffect(() => { if (availableTeamIndexes.length === 0) return; - if (captainTeamIndex !== null && !availableTeamIndexes.includes(captainTeamIndex)) { + if ( + captainTeamIndex !== null && + !availableTeamIndexes.includes(captainTeamIndex) + ) { setDevCaptainTeamIndex(availableTeamIndexes[0]); } }, [availableTeamIndexes, captainTeamIndex]); @@ -1176,16 +1853,27 @@ export default function AuctionPage() { if (matchQuery.isLoading || (auctionQuery.isLoading && !socket.auction)) { return (
- 경매를 연결하는 중... + + 경매를 연결하는 중... +
); } - if (auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404 && !socket.auction) { + if ( + auctionQuery.error instanceof ApiError && + auctionQuery.error.status === 404 && + !socket.auction + ) { return (
-

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

- +

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

+ 내전 상세로 돌아가기
@@ -1202,13 +1890,13 @@ export default function AuctionPage() { ); } - const phaseLabel: Record = { - waiting: '경매 준비 중...', - presenting: '다음 선수 등장', - bidding: '입찰 진행 중', - sold: '낙찰!', - passed: '유찰 — 다음 선수로', - complete: '경매 완료', + const phaseLabel: Record = { + waiting: "경매 준비 중...", + presenting: "다음 선수 등장", + bidding: "입찰 진행 중", + sold: "낙찰!", + passed: "유찰 — 다음 선수로", + complete: "경매 완료", }; const errorMessage = socket.error ?? @@ -1220,9 +1908,15 @@ export default function AuctionPage() { auctionState.matchSideEffectStatus, ); + function confirmUndo() { + if (undoTargetSequence === null) return; + const sequence = undoTargetSequence; + setUndoTargetSequence(null); + handleUndo(sequence); + } + function handleUndo(sequence: number) { if (!id) return; - if (!window.confirm(`${sequence}번 액션 직전으로 되돌릴까요?`)) return; undoMutation.mutate( { auctionActionRequestId: createClientRequestId(), @@ -1240,13 +1934,13 @@ export default function AuctionPage() { onSuccess: async () => { await Promise.all([ queryClient.invalidateQueries({ - queryKey: ['auction', DEFAULT_COMMUNITY_ID, id], + queryKey: ["auction", DEFAULT_COMMUNITY_ID, id], }), queryClient.invalidateQueries({ - queryKey: ['auction-history', DEFAULT_COMMUNITY_ID, id], + queryKey: ["auction-history", DEFAULT_COMMUNITY_ID, id], }), queryClient.invalidateQueries({ - queryKey: ['match', DEFAULT_COMMUNITY_ID, id], + queryKey: ["match", DEFAULT_COMMUNITY_ID, id], }), ]); }, @@ -1271,7 +1965,7 @@ export default function AuctionPage() { { onSuccess: async () => { setShowCancelModal(false); - setCancelConfirmText(''); + setCancelConfirmText(""); await clearAuctionDataAfterCancel(); navigate(`/match/${id}`, { replace: true }); }, @@ -1290,7 +1984,7 @@ export default function AuctionPage() {
{phaseLabel[auctionState.phase]} - {auctionState.phase === 'bidding' && ( + {auctionState.phase === "bidding" && ( 소켓: {socket.connectionStatus} {/* 임시 운영용: 로그인/권한 확인 없이 조작자 역할을 선택할 수 있게 열어둔다. */} setAssignedPosition(event.target.value as Position)} + onChange={(event) => + setAssignedPosition(event.target.value as Position) + } className="border border-base-content/10 bg-transparent px-2 py-2 text-xs" > @@ -1535,7 +2242,9 @@ export default function AuctionPage() { onClick={() => socket.markSold(assignedPosition)} disabled={socket.isAuctionActionPending} > - {socket.isAuctionActionPending ? '반영 중...' : '낙찰 처리'} + {socket.isAuctionActionPending + ? "반영 중..." + : "낙찰 처리"}
)} - {(auctionState.phase === 'sold' || - auctionState.phase === 'passed') && ( + {(auctionState.phase === "sold" || + auctionState.phase === "passed") && ( )}
@@ -1566,7 +2279,7 @@ export default function AuctionPage() { type="button" className="btn btn-outline btn-error btn-sm inline-flex items-center gap-1.5 px-4 text-xs" onClick={() => { - setCancelConfirmText(''); + setCancelConfirmText(""); setShowCancelModal(true); }} disabled={resetAuctionMutation.isPending} @@ -1575,7 +2288,8 @@ export default function AuctionPage() { 경매 진행 취소

- 경매 데이터와 진행 기록을 삭제하고 내전을 모집 상태로 되돌립니다. + 경매 데이터와 진행 기록을 삭제하고 내전을 모집 상태로 + 되돌립니다.

@@ -1616,6 +2330,50 @@ export default function AuctionPage() { />
+ {undoTargetSequence !== null && ( +
setUndoTargetSequence(null)} + > +
event.stopPropagation()} + > +

+ 되돌리기 확인 +

+

+ #{undoTargetSequence}번 액션 직전 상태로 되돌릴까요? 이후 진행 + 내역은 사라집니다. +

+
+ + +
+
+
+ )} + {showCancelModal && (

- 정말 경매를 취소하고 모집 상태로 되돌리시겠습니까? - 경매 데이터, 입찰 기록, 팀 배정 정보가 삭제됩니다. + 정말 경매를 취소하고 모집 상태로 되돌리시겠습니까? 경매 + 데이터, 입찰 기록, 팀 배정 정보가 삭제됩니다.

@@ -1654,11 +2412,11 @@ export default function AuctionPage() { value={cancelConfirmText} onChange={(event) => setCancelConfirmText(event.target.value)} onKeyDown={(event) => { - if (event.key === 'Escape') { + if (event.key === "Escape") { setShowCancelModal(false); - setCancelConfirmText(''); + setCancelConfirmText(""); } - if (event.key === 'Enter' && canConfirmAuctionCancel) { + if (event.key === "Enter" && canConfirmAuctionCancel) { handleResetAuction(); } }} @@ -1672,7 +2430,7 @@ export default function AuctionPage() { className="btn btn-ghost btn-sm px-4 text-xs" onClick={() => { setShowCancelModal(false); - setCancelConfirmText(''); + setCancelConfirmText(""); }} disabled={resetAuctionMutation.isPending} > @@ -1687,8 +2445,8 @@ export default function AuctionPage() { } > {resetAuctionMutation.isPending - ? '취소 처리 중...' - : '경매 취소 진행'} + ? "취소 처리 중..." + : "경매 취소 진행"}
@@ -1698,18 +2456,24 @@ export default function AuctionPage() { ); } -type PoolTab = 'waiting' | 'passed'; +type PoolTab = "waiting" | "passed"; // 풀 리스트는 경매 등장 순서를 노출하면 안 되므로 게임명 알파벳 순으로 독립 정렬한다. -const POOL_COLLATOR = new Intl.Collator(['ko', 'en'], { sensitivity: 'base' }); +const POOL_COLLATOR = new Intl.Collator(["ko", "en"], { sensitivity: "base" }); function comparePoolPlayers(a: AuctionPlayerView, b: AuctionPlayerView) { return POOL_COLLATOR.compare(a.summonerName, b.summonerName); } -function PoolPanel({ state }: { state: AuctionStateView }) { +function PoolPanel({ + state, + historyBackTo, +}: { + state: AuctionStateView; + historyBackTo: string; +}) { const { data: ddragon } = useDdragonManifest(); - const [tab, setTab] = useState('waiting'); + const [tab, setTab] = useState("waiting"); const { waitingPool, passedPool } = useMemo(() => { const captainIds = new Set(state.teams.map((team) => team.captainUserId)); @@ -1718,13 +2482,13 @@ function PoolPanel({ state }: { state: AuctionStateView }) { team.members.map((member) => member.userId), ), ); - const passedIds = new Set( - state.passedQueue.map((player) => player.userId), - ); + const passedIds = new Set(state.passedQueue.map((player) => player.userId)); const currentId = state.currentPlayer?.userId; const startIndex = - state.phase === 'complete' ? state.totalPlayers : state.currentPlayerIndex + 1; + state.phase === "complete" + ? state.totalPlayers + : state.currentPlayerIndex + 1; const waiting = state.auctionOrder .slice(startIndex) @@ -1742,7 +2506,7 @@ function PoolPanel({ state }: { state: AuctionStateView }) { return { waitingPool: waiting, passedPool: passed }; }, [state]); - const activePool = tab === 'waiting' ? waitingPool : passedPool; + const activePool = tab === "waiting" ? waitingPool : passedPool; return (
@@ -1750,23 +2514,23 @@ function PoolPanel({ state }: { state: AuctionStateView }) { setTab('waiting')} + active={tab === "waiting"} + onClick={() => setTab("waiting")} /> setTab('passed')} + active={tab === "passed"} + onClick={() => setTab("passed")} />
{activePool.length === 0 ? (
- {tab === 'waiting' - ? '대기 중인 유저가 없습니다' - : '유찰된 유저가 없습니다'} + {tab === "waiting" + ? "대기 중인 유저가 없습니다" + : "유찰된 유저가 없습니다"}
) : (
    @@ -1775,7 +2539,8 @@ function PoolPanel({ state }: { state: AuctionStateView }) { key={player.userId} player={player} ddragon={ddragon} - showPassCount={tab === 'passed'} + historyBackTo={historyBackTo} + showPassCount={tab === "passed"} /> ))}
@@ -1788,6 +2553,7 @@ function PoolPanel({ state }: { state: AuctionStateView }) { const MemoPoolPanel = memo( PoolPanel, (previous, next) => + previous.historyBackTo === next.historyBackTo && previous.state.phase === next.state.phase && previous.state.currentPlayerIndex === next.state.currentPlayerIndex && previous.state.currentPlayer?.userId === next.state.currentPlayer?.userId && @@ -1814,8 +2580,8 @@ function PoolTabButton({ onClick={onClick} className={`relative px-1 pt-3 pb-2.5 mr-5 text-xs font-semibold transition-colors ${ active - ? 'text-base-content' - : 'text-base-content/40 hover:text-base-content/70' + ? "text-base-content" + : "text-base-content/40 hover:text-base-content/70" }`} > {label} @@ -1832,30 +2598,40 @@ function PoolTabButton({ function PoolListItem({ player, ddragon, + historyBackTo, showPassCount, }: { player: AuctionPlayerView; - ddragon: ReturnType['data']; + ddragon: ReturnType["data"]; + historyBackTo: string; showPassCount: boolean; }) { return ( -
  • - -
    - - {player.summonerName} - - - {showPassCount && player.passCount > 0 ? ( - - {player.passCount}회 유찰 +
  • + + +
    + + {player.summonerName} - ) : null} -
    + + + {showPassCount && player.passCount > 0 ? ( + + {player.passCount}회 유찰 + + ) : null} +
  • + ); } @@ -1865,18 +2641,18 @@ function ChatPanel({ connectionStatus, senderLabel, onSend, - className = '', + className = "", }: { messages: ApiAuctionChatMessage[]; - connectionStatus: ReturnType['connectionStatus']; + connectionStatus: ReturnType["connectionStatus"]; senderLabel: string; onSend: (message: string) => void; className?: string; }) { - const [draft, setDraft] = useState(''); + const [draft, setDraft] = useState(""); const messagesScrollRef = useRef(null); const trimmedDraft = draft.trim(); - const isConnected = connectionStatus === 'connected'; + const isConnected = connectionStatus === "connected"; const canSend = isConnected && trimmedDraft.length > 0; useEffect(() => { @@ -1889,23 +2665,23 @@ function ChatPanel({ event.preventDefault(); if (!canSend) return; onSend(trimmedDraft); - setDraft(''); + setDraft(""); } function handleKeyDown(event: KeyboardEvent) { - if (event.key !== 'Enter' || event.shiftKey) return; + if (event.key !== "Enter" || event.shiftKey) return; event.preventDefault(); if (!canSend) return; onSend(trimmedDraft); - setDraft(''); + setDraft(""); } const statusLabel = - connectionStatus === 'connected' - ? '실시간' - : connectionStatus === 'connecting' - ? '연결 중' - : '오프라인'; + connectionStatus === "connected" + ? "실시간" + : connectionStatus === "connecting" + ? "연결 중" + : "오프라인"; return (
    {statusLabel}
    -
    +
    {messages.length === 0 ? (
    아직 메시지가 없습니다 @@ -1950,7 +2729,10 @@ function ChatPanel({ )}
    -
    +
    {senderLabel} {draft.length}/300 @@ -1980,13 +2762,13 @@ function ChatPanel({ } function resolveMatchSideEffectMessage( - status: AuctionStateView['matchSideEffectStatus'], + status: AuctionStateView["matchSideEffectStatus"], ): string | null { - if (status === 'pending' || status === 'processing') { - return '팀 편성, 토너먼트 코드, 결과 수집 예약을 반영 중입니다.'; + if (status === "pending" || status === "processing") { + return "팀 편성, 토너먼트 코드, 결과 수집 예약을 반영 중입니다."; } - if (status === 'failed') { - return '팀 편성 후속 처리에 실패했습니다. 운영진 확인이 필요합니다.'; + if (status === "failed") { + return "팀 편성 후속 처리에 실패했습니다. 운영진 확인이 필요합니다."; } return null; }