import { lazy, memo, Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, 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"; import { useAuction, useAuctionHistory, useDdragonManifest, useMatch, useMe, useResetAuction, useUndoAuction, useUserHistoryProfile, useUserInternalHistory, } from "../api/hooks"; import { mapApiAuctionToAuctionState, type AuctionPlayerView, type AuctionStateView, } from "../api/mappers"; import { useAuctionSocket, type BidLatencyDiagnostics, } 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 { internalMatchGamePath } from "../lib/internal-match-routes"; import { RankBadge } from "../components/RankBadge"; import { formatRankDetail } from "../components/rankBadgeUtils"; import type { ApiAuction, ApiAuctionChatMessage, ApiTierInfo, ApiRecentMatchView, ApiTierHistoryEntry, ApiRiotLaneStats, ApiUser, ApiUserInternalHistoryResponse, Position, } from "../api/types"; import { LANE_LABELS } from "../lib/riot-history"; const TierHistoryChart = lazy(() => import("../components/TierHistoryChart")); type CaptainRole = { teamIndex: number; }; function formatPoints(value: number) { return value.toLocaleString(); } function createClientRequestId(): string { if (typeof crypto !== "undefined" && "randomUUID" in crypto) { return crypto.randomUUID(); } return `${Date.now()}-${Math.random().toString(16).slice(2)}`; } 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 formatChatTime(dateLike: string) { return new Intl.DateTimeFormat("ko-KR", { hour: "2-digit", minute: "2-digit", }).format(new Date(dateLike)); } function resolveChatSenderLabel( currentUser: ApiUser | null, captainRole: CaptainRole | null, ) { const primaryRiotAccount = currentUser?.riotAccounts.find((entry) => entry.isPrimary) ?? currentUser?.riotAccounts[0]; if (primaryRiotAccount?.gameName) { return primaryRiotAccount.tagLine ? `${primaryRiotAccount.gameName}#${primaryRiotAccount.tagLine}` : primaryRiotAccount.gameName; } if (currentUser?.kakaoTalkNickname) return currentUser.kakaoTalkNickname; if (currentUser?.discordNickname) return currentUser.discordNickname; if (captainRole) return `${teamIndexLabel(captainRole.teamIndex)} 팀장`; return "관전자"; } 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 getAuctionRevision(auction: ApiAuction | null | undefined) { return typeof auction?.revision === "number" ? auction.revision : null; } function pickLatestAuction( socketAuction: ApiAuction | null, queryAuction: ApiAuction | undefined, ) { if (!socketAuction) return queryAuction ?? null; if (!queryAuction) return socketAuction; if ( socketAuction.auctionLifecycleId && queryAuction.auctionLifecycleId && socketAuction.auctionLifecycleId === queryAuction.auctionLifecycleId ) { const socketRevision = getAuctionRevision(socketAuction); const queryRevision = getAuctionRevision(queryAuction); if (socketRevision !== null && queryRevision !== null) { return queryRevision > socketRevision ? queryAuction : socketAuction; } } return getAuctionUpdatedAt(queryAuction) > getAuctionUpdatedAt(socketAuction) ? queryAuction : socketAuction; } const AUCTION_MAX_TEAM_SIZE = 5; const AUCTION_MIN_BID_POINTS = 10; 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; const LIVE_TIMER_TICK_MS = 100; const PROFILE_TIER_ORDER = [ "IRON", "BRONZE", "SILVER", "GOLD", "PLATINUM", "EMERALD", "DIAMOND", "MASTER", "GRANDMASTER", "CHALLENGER", ]; const PROFILE_APEX_TIERS = new Set(["MASTER", "GRANDMASTER", "CHALLENGER"]); const PROFILE_RANK_INDEX: Record = { IV: 0, III: 1, II: 2, I: 3, }; function getAuctionTeamSize(team: AuctionStateView["teams"][number]) { return team.members.length + 1; } function getReservedPointsAfterCurrentBid( team: AuctionStateView["teams"][number], ) { const remainingSlotsAfterCurrentBid = Math.max( 0, AUCTION_MAX_TEAM_SIZE - getAuctionTeamSize(team) - 1, ); return remainingSlotsAfterCurrentBid * AUCTION_MIN_BID_POINTS; } 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) ? `${Math.round(value)}ms` : "-"; } function formatBidLatencyDiagnostics( diagnostics: BidLatencyDiagnostics | null, ) { if (!diagnostics) return null; const serverDeadlineTimestampMS = diagnostics.bidDiagnostics?.currentBidRoundDeadlineTimestampMS; const serverTimestampMS = diagnostics.bidDiagnostics?.currentServerTimestampMS; const serverRemainingMS = typeof diagnostics.serverObservedRemainingBidRoundTimeMS === "number" ? diagnostics.serverObservedRemainingBidRoundTimeMS : typeof serverDeadlineTimestampMS === "number" && typeof serverTimestampMS === "number" ? serverDeadlineTimestampMS - serverTimestampMS : undefined; const timing = diagnostics.bidServerTiming; const parts = [ `RTT ${formatLatencyMs(diagnostics.serverRoundTripDurationMS)}`, `gateway ${formatLatencyMs(timing?.gatewayTotalDurationMS)}`, `service ${formatLatencyMs(timing?.serviceTotalDurationMS)}`, `redis ${formatLatencyMs(timing?.redisBidCommandDurationMS)}`, `context ${formatLatencyMs(timing?.redisBidContextReadDurationMS)}`, ]; if (timing?.fallbackFullStatePath) { parts.push("fallback full-state"); } if (typeof diagnostics.clientObservedRemainingBidRoundTimeMS === "number") { parts.push( `client-left ${formatLatencyMs( diagnostics.clientObservedRemainingBidRoundTimeMS, )}`, ); } if (typeof serverRemainingMS === "number") { parts.push(`server-left ${formatLatencyMs(serverRemainingMS)}`); } return parts.join(" · "); } function getSoloTierHistory(entries: ApiTierHistoryEntry[]) { return entries.filter((entry) => entry.queueType === "RANKED_SOLO_5x5"); } function getProfileTierValue( tier: Pick, ) { const tierIndex = PROFILE_TIER_ORDER.indexOf(tier.tier); const base = Math.max(0, tierIndex) * 400; if (PROFILE_APEX_TIERS.has(tier.tier)) { return base + (tier.leaguePoints ?? 0); } return ( base + (PROFILE_RANK_INDEX[tier.rank ?? "IV"] ?? 0) * 100 + (tier.leaguePoints ?? 0) ); } function tierHistoryEntryToTierInfo(entry: ApiTierHistoryEntry): ApiTierInfo { return { queueType: entry.queueType, tier: entry.tier, rank: entry.rank ?? "", leaguePoints: entry.leaguePoints ?? 0, wins: entry.wins ?? 0, losses: entry.losses ?? 0, fetchedAt: entry.recordedAt, }; } function getPeakSoloTier( currentTier: ApiTierInfo | undefined, tierHistory: ApiTierHistoryEntry[], ) { const candidates = tierHistory.map(tierHistoryEntryToTierInfo); if (currentTier?.queueType === "RANKED_SOLO_5x5") { candidates.push(currentTier); } return candidates.reduce((peak, tier) => { if (!peak) return tier; return getProfileTierValue(tier) > getProfileTierValue(peak) ? tier : peak; }, undefined); } 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, ) { if (!deadline) return 0; const deadlineTimestampMS = Date.parse(deadline); if (!Number.isFinite(deadlineTimestampMS)) return 0; return Math.max( 0, (deadlineTimestampMS - (Date.now() + serverTimeOffsetMs)) / 1000, ); } function useLiveRemainingSeconds( deadline: string | undefined, serverTimeOffsetMs: number, enabled: boolean, ) { const [remainingSeconds, setRemainingSeconds] = useState(() => getLiveRemainingSeconds(deadline, serverTimeOffsetMs), ); useEffect(() => { let timeoutId: ReturnType | null = null; let timerId: ReturnType | null = null; const updateRemainingSeconds = () => { const nextRemainingSeconds = getLiveRemainingSeconds( deadline, serverTimeOffsetMs, ); setRemainingSeconds(nextRemainingSeconds); if (nextRemainingSeconds <= 0 && timerId) { window.clearInterval(timerId); timerId = null; } }; timeoutId = window.setTimeout(updateRemainingSeconds, 0); if (!enabled) { return () => { if (timeoutId) window.clearTimeout(timeoutId); }; } timerId = window.setInterval(updateRemainingSeconds, LIVE_TIMER_TICK_MS); return () => { if (timeoutId) window.clearTimeout(timeoutId); if (timerId) window.clearInterval(timerId); }; }, [deadline, enabled, serverTimeOffsetMs]); return remainingSeconds; } function useIsDeadlineExpired( deadline: string | undefined, serverTimeOffsetMs: number, enabled: boolean, ) { const [isExpired, setIsExpired] = useState( () => getLiveRemainingSeconds(deadline, serverTimeOffsetMs) <= 0, ); useEffect(() => { let syncTimeoutId: ReturnType | null = null; let expireTimeoutId: ReturnType | null = null; const remainingMs = getLiveRemainingSeconds(deadline, serverTimeOffsetMs) * 1000; syncTimeoutId = window.setTimeout(() => { setIsExpired(remainingMs <= 0); }, 0); if (enabled && remainingMs > 0) { expireTimeoutId = window.setTimeout(() => { setIsExpired(true); }, remainingMs); } return () => { if (syncTimeoutId) window.clearTimeout(syncTimeoutId); if (expireTimeoutId) window.clearTimeout(expireTimeoutId); }; }, [deadline, enabled, serverTimeOffsetMs]); return isExpired; } function AuctionTimerText({ deadline, serverTimeOffsetMs, }: { deadline: string | undefined; serverTimeOffsetMs: number; }) { const timer = useLiveRemainingSeconds(deadline, serverTimeOffsetMs, true); return ( {timer.toFixed(1)}s ); } function TimerBar({ deadline, heightClassName = "h-1.5", maxTimer, serverTimeOffsetMs, }: { deadline: string | undefined; heightClassName?: string; maxTimer: number; serverTimeOffsetMs: number; }) { const barRef = useRef(null); const serverTimeOffsetRef = useRef(serverTimeOffsetMs); useEffect(() => { serverTimeOffsetRef.current = serverTimeOffsetMs; }, [serverTimeOffsetMs]); useLayoutEffect(() => { const bar = barRef.current; if (!bar) return; let animationFrameId: number | null = null; let urgentTimeoutId: ReturnType | null = null; const remainingSeconds = getLiveRemainingSeconds( deadline, serverTimeOffsetRef.current, ); const nextScale = maxTimer > 0 ? Math.max(0, Math.min(1, remainingSeconds / maxTimer)) : 0; bar.style.transition = "none"; bar.style.transform = `scaleX(${nextScale})`; 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, ); } animationFrameId = window.requestAnimationFrame(() => { const currentRemainingSeconds = getLiveRemainingSeconds( deadline, serverTimeOffsetRef.current, ); bar.style.transition = `transform ${Math.round( currentRemainingSeconds * 1000, )}ms linear`; bar.style.transform = "scaleX(0)"; }); return () => { if (animationFrameId !== null) { window.cancelAnimationFrame(animationFrameId); } if (urgentTimeoutId) window.clearTimeout(urgentTimeoutId); }; }, [deadline, maxTimer]); 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} ) : ( — )}
); })}
); } 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 ProfileTierSummary({ label, tier, }: { label: string; tier: ApiTierInfo | undefined; }) { return (
{formatRankDetail(tier)}{" "} ({label})
); } 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, historyBackTo, }: { match: ApiRecentMatchView; ddragon: ReturnType["data"]; historyBackTo: string; }) { 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 ? internalMatchGamePath( DEFAULT_COMMUNITY_ID, match.internalMatchId, 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]; isActive: boolean; isLeft: boolean; historyBackTo: string; }) { const { data: ddragon } = useDdragonManifest(); const tone = teamIndexColorClasses(team.teamIndex); const teamSize = getAuctionTeamSize(team); 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) => (
—
))}
); } const MemoTeamPanel = memo(TeamPanel); function PlayerSpotlight({ state, captainRole, serverTimeOffsetMs, historyBackTo, }: { state: AuctionStateView; captainRole: CaptainRole | null; serverTimeOffsetMs: number; historyBackTo: string; }) { const player = state.currentPlayer; if (!player) return null; 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.auctionRound === next.state.auctionRound, ); function PlayerProfileDetails({ player, historyBackTo, }: { 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 : getSoloTierHistory(historyProfileQuery.data?.tierHistory ?? []); const peakSoloTier = getPeakSoloTier(player.tier, tierHistory); return ( <>
{player.summonerName} #{player.tag}
{" "} {positionLabel[player.subPosition]}
setActiveTab("internal")} > 내전 setActiveTab("solo")} > 솔로랭크
{activeTab === "internal" ? ( ) : ( )}
); } const MemoPlayerProfileDetails = memo( PlayerProfileDetails, (previous, next) => areSameAuctionPlayerProfile(previous.player, next.player) && previous.historyBackTo === next.historyBackTo, ); function areSameAuctionPlayerProfile( previous: AuctionPlayerView | null, next: AuctionPlayerView | null, ) { if (previous === next) return true; if (!previous || !next) return false; return ( previous.userId === next.userId && previous.summonerName === next.summonerName && previous.tag === next.tag && previous.mainPosition === next.mainPosition && previous.subPosition === next.subPosition && previous.profileIconId === next.profileIconId && previous.passCount === next.passCount && JSON.stringify(previous.tier) === JSON.stringify(next.tier) && JSON.stringify(previous.tierHistory) === JSON.stringify(next.tierHistory) && JSON.stringify(previous.masteries) === JSON.stringify(next.masteries) && JSON.stringify(previous.recentStats) === JSON.stringify(next.recentStats) ); } 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" || isSold) && (
{isSold ? "낙찰가" : "현재 입찰가"} {statusText}
{state.currentBidder && ( {teamIndexLabel(state.currentBidder.teamIndex)} )}
{/* 타이머를 입찰가 박스 하단에 붙여 시선 이동 없이 마감 임박을 전달한다. */} {state.phase === "bidding" && ( )}
)} {state.phase === "passed" && (
유찰{" "} {state.auctionRound === 1 ? "— 마지막에 다시 등장합니다" : "— 강제 배정 대상"}
)} ); } function BidControls({ state, captainRole, isBidPending, serverTimeOffsetMs, onBid, }: { state: AuctionStateView; captainRole: CaptainRole | null; isBidPending: boolean; serverTimeOffsetMs: number; onBid: (teamIndex: number, amount: number) => void; }) { const minBid = state.currentBid + AUCTION_MIN_BID_POINTS; const activeTeam = captainRole ? state.teams.find((team) => team.teamIndex === captainRole.teamIndex) : null; const activeTeamSize = activeTeam ? getAuctionTeamSize(activeTeam) : 0; const isActiveTeamFull = activeTeamSize >= AUCTION_MAX_TEAM_SIZE; const reservedPoints = activeTeam ? getReservedPointsAfterCurrentBid(activeTeam) : 0; const maxBid = activeTeam ? getMaxBidForTeam(activeTeam) : 0; const defaultBidAmount = Math.max(minBid, Math.ceil(minBid / 10) * 10); const bidContextKey = `${activeTeam?.teamIndex ?? "spectator"}:${maxBid}:${minBid}`; const [bidDraft, setBidDraft] = useState({ contextKey: bidContextKey, amount: activeTeam ? Math.min(maxBid, defaultBidAmount) : defaultBidAmount, }); const bidAmount = bidDraft.contextKey === bidContextKey ? bidDraft.amount : activeTeam ? Math.min(maxBid, defaultBidAmount) : defaultBidAmount; const setBidAmount = (amount: number) => { setBidDraft({ contextKey: bidContextKey, amount }); }; const canAffordNextBid = !isActiveTeamFull && maxBid >= minBid; const isBidExpired = useIsDeadlineExpired( state.deadline, serverTimeOffsetMs, state.phase === "bidding", ); const effectiveBidAmount = activeTeam ? Math.min(maxBid, Math.max(minBid, bidAmount)) : Math.max(minBid, bidAmount); if (state.phase !== "bidding") return null; if (!activeTeam) { return (
관전자 모드입니다. 우측 상단에서 조작자 역할을 선택하면 입찰할 수 있습니다.
); } // 경매는 "현재가보다 얼마 더?"로 생각하므로 절대값이 아니라 증분 프리셋으로 제공한다. 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(maxBid)}P
보존
{formatPoints(reservedPoints)}P
{bidIncrements.map((increment) => { const presetBid = state.currentBid + increment; const isSelected = bidAmount === presetBid; return ( ); })} {/* 타이핑 중에는 클램프하지 않고(자릿수 입력 방해 방지) 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"] }) { const scrollRef = useRef(null); useEffect(() => { const scrollContainer = scrollRef.current; if (!scrollContainer) return; scrollContainer.scrollTop = scrollContainer.scrollHeight; }, [bids.length]); if (bids.length === 0) return null; return (
입찰 기록
{bids.map((bid, index) => (
{teamIndexLabel(bid.teamIndex)} → {formatPoints(bid.amount)}P
))}
); } const MemoBidLog = memo(BidLog); export default function AuctionPage() { const { id } = useParams(); const location = useLocation(); const navigate = useNavigate(); 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 resetAuctionMutation = useResetAuction(DEFAULT_COMMUNITY_ID); const socket = useAuctionSocket(id); const captainTeamIndex = useDevCaptainTeamIndex(); const [assignedPositionDraft, setAssignedPositionDraft] = useState<{ playerId: string | null; position: Position; }>({ playerId: null, position: "MID" }); const [showCancelModal, setShowCancelModal] = useState(false); 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 clearAuctionDataAfterCancel = useCallback(async () => { if (!id) return; const auctionQueryKey = ["auction", DEFAULT_COMMUNITY_ID, id] as const; const auctionHistoryQueryKey = [ "auction-history", DEFAULT_COMMUNITY_ID, id, ] as const; await Promise.all([ queryClient.cancelQueries({ queryKey: auctionQueryKey, exact: true }), queryClient.cancelQueries({ queryKey: auctionHistoryQueryKey, exact: true, }), ]); queryClient.removeQueries({ queryKey: auctionQueryKey, exact: true }); queryClient.removeQueries({ queryKey: auctionHistoryQueryKey, exact: true, }); await queryClient.invalidateQueries({ queryKey: ["match", DEFAULT_COMMUNITY_ID, id], exact: true, }); }, [id, queryClient]); useEffect(() => { if (!showCancelModal) return; cancelConfirmInputRef.current?.focus(); }, [showCancelModal]); const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data); const auctionState = useMemo( () => liveAuction && matchQuery.data ? mapApiAuctionToAuctionState(liveAuction, matchQuery.data) : null, [liveAuction, matchQuery.data], ); const currentPlayerId = auctionState?.currentPlayer?.id ?? null; const assignedPosition = assignedPositionDraft.playerId === currentPlayerId ? assignedPositionDraft.position : (auctionState?.currentPlayer?.mainPosition ?? "MID"); const setAssignedPosition = (position: Position) => { setAssignedPositionDraft({ playerId: currentPlayerId, position }); }; 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, }; const chatSenderLabel = resolveChatSenderLabel(currentUser, captainRole); useEffect(() => { if (availableTeamIndexes.length === 0) return; if ( captainTeamIndex !== null && !availableTeamIndexes.includes(captainTeamIndex) ) { setDevCaptainTeamIndex(availableTeamIndexes[0]); } }, [availableTeamIndexes, captainTeamIndex]); useEffect(() => { if (!socket.resetAt || !id) return; void clearAuctionDataAfterCancel().finally(() => { navigate(`/match/${id}`, { replace: true }); }); }, [clearAuctionDataAfterCancel, id, navigate, socket.resetAt]); 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); const bidLatencyMessage = formatBidLatencyDiagnostics( socket.bidLatencyDiagnostics, ); const matchSideEffectMessage = resolveMatchSideEffectMessage( auctionState.matchSideEffectStatus, ); function confirmUndo() { if (undoTargetSequence === null) return; const sequence = undoTargetSequence; setUndoTargetSequence(null); handleUndo(sequence); } function handleUndo(sequence: number) { if (!id) return; undoMutation.mutate( { auctionActionRequestId: createClientRequestId(), clientObservedAuctionLifecycleId: liveAuction?.auctionLifecycleId, clientObservedCurrentAuctionPlayerOrderIndex: liveAuction?.currentAuctionPlayerOrderIndex, clientObservedCurrentBidRoundPlayerUserId: liveAuction?.currentBidRoundPlayerUserId, clientObservedPhase: liveAuction?.phase, clientObservedRevision: liveAuction?.revision, 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], }), ]); }, }, ); } function handleResetAuction() { if (!id || !canConfirmAuctionCancel) return; resetAuctionMutation.mutate( { auctionActionRequestId: createClientRequestId(), clientObservedAuctionLifecycleId: liveAuction?.auctionLifecycleId, clientObservedCurrentAuctionPlayerOrderIndex: liveAuction?.currentAuctionPlayerOrderIndex, clientObservedCurrentBidRoundPlayerUserId: liveAuction?.currentBidRoundPlayerUserId, clientObservedPhase: liveAuction?.phase, clientObservedRevision: liveAuction?.revision, matchId: id, }, { onSuccess: async () => { setShowCancelModal(false); setCancelConfirmText(""); await clearAuctionDataAfterCancel(); navigate(`/match/${id}`, { replace: true }); }, }, ); } const undoPanel = canManageAuction ? (
되돌리기 (Undo)
{historyQuery.data?.length ? ( historyQuery.data.map((entry) => ( )) ) : (
기록이 없습니다
)}
) : null; return (
내전 상세로 {errorMessage && (
{errorMessage}
)} {import.meta.env.DEV && canManageAuction && bidLatencyMessage && (
입찰 계측 · {bidLatencyMessage}
)} {undoMutation.error instanceof Error && (
{undoMutation.error.message}
)} {resetAuctionMutation.error instanceof Error && (
{resetAuctionMutation.error.message}
)}

경매 팀빌딩

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

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

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

)} {undoPanel} )}
socket.sendChatMessage({ displayName: chatSenderLabel, message, }) } className="h-[420px]" />
{undoTargetSequence !== null && (
setUndoTargetSequence(null)} >
event.stopPropagation()} >

되돌리기 확인

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

)} {showCancelModal && (

경매 진행 취소

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

setCancelConfirmText(event.target.value)} onKeyDown={(event) => { if (event.key === "Escape") { setShowCancelModal(false); setCancelConfirmText(""); } if (event.key === "Enter" && canConfirmAuctionCancel) { handleResetAuction(); } }} className="mt-2 h-10 w-full border border-base-content/15 bg-base-100 px-3 text-sm text-base-content outline-none transition-colors focus:border-red-400/60" placeholder="예" />
)}
); } type PoolTab = "waiting" | "passed"; // 풀 리스트는 경매 등장 순서를 노출하면 안 되므로 게임명 알파벳 순으로 독립 정렬한다. 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, historyBackTo, }: { state: AuctionStateView; historyBackTo: string; }) { const { data: ddragon } = useDdragonManifest(); const [tab, setTab] = useState("waiting"); const { waitingPool, passedPool } = useMemo(() => { const captainIds = new Set(state.teams.map((team) => team.captainUserId)); const memberIds = new Set( state.teams.flatMap((team) => team.members.map((member) => member.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; const waiting = state.auctionOrder .slice(startIndex) .filter( (player) => !captainIds.has(player.userId) && !memberIds.has(player.userId) && !passedIds.has(player.userId) && player.userId !== currentId, ) .sort(comparePoolPlayers); const passed = [...state.passedQueue].sort(comparePoolPlayers); return { waitingPool: waiting, passedPool: passed }; }, [state]); const activePool = tab === "waiting" ? waitingPool : passedPool; return (
setTab("waiting")} /> setTab("passed")} />
{activePool.length === 0 ? (
{tab === "waiting" ? "대기 중인 유저가 없습니다" : "유찰된 유저가 없습니다"}
) : (
    {activePool.map((player) => ( ))}
)}
); } 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 && previous.state.auctionOrder === next.state.auctionOrder && previous.state.passedQueue === next.state.passedQueue && previous.state.teams === next.state.teams, ); function PoolTabButton({ label, count, active, onClick, }: { label: string; count: number; active: boolean; onClick: () => void; }) { return ( ); } function PoolListItem({ player, ddragon, historyBackTo, showPassCount, }: { player: AuctionPlayerView; ddragon: ReturnType["data"]; historyBackTo: string; showPassCount: boolean; }) { return (
  • {player.summonerName} {showPassCount && player.passCount > 0 ? ( {player.passCount}회 유찰 ) : null}
  • ); } function ChatPanel({ messages, connectionStatus, senderLabel, onSend, className = "", }: { messages: ApiAuctionChatMessage[]; connectionStatus: ReturnType["connectionStatus"]; senderLabel: string; onSend: (message: string) => void; className?: string; }) { const [draft, setDraft] = useState(""); const messagesScrollRef = useRef(null); const trimmedDraft = draft.trim(); const isConnected = connectionStatus === "connected"; const canSend = isConnected && trimmedDraft.length > 0; useEffect(() => { const scrollContainer = messagesScrollRef.current; if (!scrollContainer) return; scrollContainer.scrollTop = scrollContainer.scrollHeight; }, [messages.length]); function handleSubmit(event: FormEvent) { event.preventDefault(); if (!canSend) return; onSend(trimmedDraft); setDraft(""); } function handleKeyDown(event: KeyboardEvent) { if (event.key !== "Enter" || event.shiftKey) return; event.preventDefault(); if (!canSend) return; onSend(trimmedDraft); setDraft(""); } const statusLabel = connectionStatus === "connected" ? "실시간" : connectionStatus === "connecting" ? "연결 중" : "오프라인"; return (
    채팅
    {statusLabel}
    {messages.length === 0 ? (
    아직 메시지가 없습니다
    ) : (
      {messages.map((message) => (
    1. {message.displayName}

      {message.message}

    2. ))}
    )}
    {senderLabel} {draft.length}/300