From a4215f86fb29c64ddd6b23c9deb7778819ee2dd9 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Fri, 24 Jul 2026 22:36:53 -0700 Subject: [PATCH] fix(web): satisfy React hook lint rules --- apps/web/src/api/useAuctionSocket.ts | 220 ++++++++++-------- apps/web/src/api/useRiotRefreshSocket.ts | 56 +++-- apps/web/src/components/DevAuthSwitcher.tsx | 24 +- apps/web/src/components/RankBadge.tsx | 45 +--- apps/web/src/components/TierHistoryChart.tsx | 30 ++- apps/web/src/components/rankBadgeUtils.ts | 45 ++++ apps/web/src/pages/AuctionPage.tsx | 52 +++-- apps/web/src/pages/admin/LegacyImportPage.tsx | 158 +++++++------ 8 files changed, 374 insertions(+), 256 deletions(-) create mode 100644 apps/web/src/components/rankBadgeUtils.ts diff --git a/apps/web/src/api/useAuctionSocket.ts b/apps/web/src/api/useAuctionSocket.ts index d411f43a..f0bcb3fb 100644 --- a/apps/web/src/api/useAuctionSocket.ts +++ b/apps/web/src/api/useAuctionSocket.ts @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from 'react'; import { io, type Socket } from 'socket.io-client'; import { API_BASE_URL, useAuthUserId } from '../config'; import { acquireAccessToken } from '../lib/auth/token-provider'; @@ -140,6 +140,9 @@ function mergeChatMessages( export function useAuctionSocket(matchId: string | undefined) { const authUserId = useAuthUserId(); + const connectionKey = matchId + ? JSON.stringify([matchId, authUserId ?? null]) + : null; const socketRef = useRef(null); const pendingBidTimeoutsRef = useRef< Record> @@ -166,9 +169,14 @@ export function useAuctionSocket(matchId: string | undefined) { Record >({}); const [resetAt, setResetAt] = useState(null); - const [connectionStatus, setConnectionStatus] = - useState('idle'); - const [error, setError] = useState(null); + const [connectionState, setConnectionState] = useState<{ + key: string; + status: ConnectionStatus; + }>({ key: '', status: 'idle' }); + const [errorState, setErrorState] = useState<{ + key: string; + message: string | null; + }>({ key: '', message: null }); const [serverTimeOffsetMs, setServerTimeOffsetMs] = useState(0); const [serverRoundTripMs, setServerRoundTripMs] = useState( null, @@ -176,53 +184,50 @@ export function useAuctionSocket(matchId: string | undefined) { const [bidLatencyDiagnostics, setBidLatencyDiagnostics] = useState(null); - function syncLatestConfirmedBidPointAmountFromAuction( - nextAuction: ApiAuction, - ) { - latestConfirmedBidPointAmountRef.current = - resolveCurrentBidPointAmount(nextAuction); - } + const commitAuctionState = useCallback( + (nextAuction: ApiAuction, source = 'socket-state'): boolean => { + const currentAuction = latestAuctionRef.current; + const applied = shouldApplyIncomingAuctionState( + currentAuction, + nextAuction, + ); + const currentRevision = + typeof currentAuction?.revision === 'number' + ? currentAuction.revision + : -1; + const incomingRevision = + typeof nextAuction?.revision === 'number' ? nextAuction.revision : -1; + // 단조성을 깨고 적용되는 경우(=revision이 같거나 뒤로 가는데도 반영됨). + // force-resync/lifecycle 교체로만 발생하며, "2~3 버전 롤백"의 직접 증거가 된다. + const isBackwardApply = + applied && + currentRevision >= 0 && + incomingRevision >= 0 && + incomingRevision <= currentRevision; + addNewRelicPageAction('AuctionClientStateApply', { + matchId: matchId ?? 'none', + source, + applied, + isBackwardApply, + revisionDelta: incomingRevision - currentRevision, + ...describeAuctionForTelemetry('current', currentAuction), + ...describeAuctionForTelemetry('incoming', nextAuction), + }); - function commitAuctionState( - nextAuction: ApiAuction, - source = 'socket-state', - ): boolean { - const currentAuction = latestAuctionRef.current; - const applied = shouldApplyIncomingAuctionState(currentAuction, nextAuction); - const currentRevision = - typeof currentAuction?.revision === 'number' - ? currentAuction.revision - : -1; - const incomingRevision = - typeof nextAuction?.revision === 'number' ? nextAuction.revision : -1; - // 단조성을 깨고 적용되는 경우(=revision이 같거나 뒤로 가는데도 반영됨). - // force-resync/lifecycle 교체로만 발생하며, "2~3 버전 롤백"의 직접 증거가 된다. - const isBackwardApply = - applied && - currentRevision >= 0 && - incomingRevision >= 0 && - incomingRevision <= currentRevision; - addNewRelicPageAction('AuctionClientStateApply', { - matchId: matchId ?? 'none', - source, - applied, - isBackwardApply, - revisionDelta: incomingRevision - currentRevision, - ...describeAuctionForTelemetry('current', currentAuction), - ...describeAuctionForTelemetry('incoming', nextAuction), - }); + if (!applied) { + return false; + } - if (!applied) { - return false; - } + latestAuctionRef.current = nextAuction; + latestConfirmedBidPointAmountRef.current = + resolveCurrentBidPointAmount(nextAuction); + setAuction(nextAuction); + return true; + }, + [matchId], + ); - latestAuctionRef.current = nextAuction; - syncLatestConfirmedBidPointAmountFromAuction(nextAuction); - setAuction(nextAuction); - return true; - } - - function commitBidDelta(payload: BidDeltaPayload): boolean { + const commitBidDelta = useCallback((payload: BidDeltaPayload): boolean => { const currentAuction = latestAuctionRef.current; const nextAuction = applyBidDelta(currentAuction, payload); if (!nextAuction || nextAuction === currentAuction) { @@ -230,10 +235,18 @@ export function useAuctionSocket(matchId: string | undefined) { } latestAuctionRef.current = nextAuction; - syncLatestConfirmedBidPointAmountFromAuction(nextAuction); + latestConfirmedBidPointAmountRef.current = + resolveCurrentBidPointAmount(nextAuction); setAuction(nextAuction); return true; - } + }, []); + + const setError = useCallback( + (message: string | null) => { + setErrorState({ key: connectionKey ?? '', message }); + }, + [connectionKey], + ); function applyFallbackServerTimestamp(currentServerTimestampMS?: number) { if (hasSyncedServerTimeRef.current) return; @@ -345,14 +358,47 @@ export function useAuctionSocket(matchId: string | undefined) { }); } + const clearPendingBidRequest = useCallback((bidRequestId: string) => { + const timeoutId = pendingBidTimeoutsRef.current[bidRequestId]; + if (timeoutId) clearTimeout(timeoutId); + delete pendingBidTimeoutsRef.current[bidRequestId]; + setPendingBidRequests((current) => { + const next = { ...current }; + delete next[bidRequestId]; + return next; + }); + }, []); + + const clearPendingActionRequest = useCallback( + (auctionActionRequestId: string) => { + const timeoutId = + pendingActionTimeoutsRef.current[auctionActionRequestId]; + if (timeoutId) clearTimeout(timeoutId); + delete pendingActionTimeoutsRef.current[auctionActionRequestId]; + setPendingActionRequests((current) => { + const next = { ...current }; + delete next[auctionActionRequestId]; + return next; + }); + }, + [], + ); + + const clearPendingActionRequests = useCallback(() => { + Object.values(pendingActionTimeoutsRef.current).forEach((timeoutId) => + clearTimeout(timeoutId), + ); + pendingActionTimeoutsRef.current = {}; + setPendingActionRequests({}); + }, []); + useEffect(() => { - if (!matchId) { + if (!matchId || !connectionKey) { return; } + const activeConnectionKey = connectionKey; let disposed = false; - setConnectionStatus('connecting'); - setError(null); void (async () => { const accessToken = await acquireAccessToken().catch((error) => { @@ -373,7 +419,11 @@ export function useAuctionSocket(matchId: string | undefined) { socketRef.current = socket; socket.on('connect', () => { - setConnectionStatus('connected'); + setConnectionState({ + key: activeConnectionKey, + status: 'connected', + }); + setError(null); socket.emit('join', { matchId }); requestServerTimeSync(socket); if (timeSyncIntervalRef.current) { @@ -387,7 +437,10 @@ export function useAuctionSocket(matchId: string | undefined) { socket.on('disconnect', () => { clearTimeSyncTimers(); - setConnectionStatus('disconnected'); + setConnectionState({ + key: activeConnectionKey, + status: 'disconnected', + }); }); socket.on('state', (nextAuction: ApiAuction) => { @@ -520,42 +573,20 @@ export function useAuctionSocket(matchId: string | undefined) { hasSyncedServerTimeRef.current = false; setPendingBidRequests({}); setPendingActionRequests({}); - setConnectionStatus('idle'); setServerTimeOffsetMs(0); setServerRoundTripMs(null); setBidLatencyDiagnostics(null); }; - }, [authUserId, matchId]); - - function clearPendingBidRequest(bidRequestId: string) { - const timeoutId = pendingBidTimeoutsRef.current[bidRequestId]; - if (timeoutId) clearTimeout(timeoutId); - delete pendingBidTimeoutsRef.current[bidRequestId]; - setPendingBidRequests((current) => { - const next = { ...current }; - delete next[bidRequestId]; - return next; - }); - } - - function clearPendingActionRequest(auctionActionRequestId: string) { - const timeoutId = pendingActionTimeoutsRef.current[auctionActionRequestId]; - if (timeoutId) clearTimeout(timeoutId); - delete pendingActionTimeoutsRef.current[auctionActionRequestId]; - setPendingActionRequests((current) => { - const next = { ...current }; - delete next[auctionActionRequestId]; - return next; - }); - } - - function clearPendingActionRequests() { - Object.values(pendingActionTimeoutsRef.current).forEach((timeoutId) => - clearTimeout(timeoutId), - ); - pendingActionTimeoutsRef.current = {}; - setPendingActionRequests({}); - } + }, [ + authUserId, + clearPendingActionRequests, + clearPendingBidRequest, + commitAuctionState, + commitBidDelta, + connectionKey, + matchId, + setError, + ]); function emit(eventName: string, payload?: unknown) { const socket = socketRef.current; @@ -737,9 +768,16 @@ export function useAuctionSocket(matchId: string | undefined) { const currentAuction = auction; const visibleAuction = currentAuction && currentAuction.matchId === matchId ? currentAuction : null; - const visibleConnectionStatus: ConnectionStatus = matchId - ? connectionStatus - : 'idle'; + const visibleConnectionStatus: ConnectionStatus = + connectionKey === null + ? 'idle' + : connectionState.key === connectionKey + ? connectionState.status + : 'connecting'; + const visibleError = + connectionKey !== null && errorState.key === connectionKey + ? errorState.message + : null; return { auction: visibleAuction, @@ -750,7 +788,7 @@ export function useAuctionSocket(matchId: string | undefined) { pendingBidRequests, resetAt, connectionStatus: visibleConnectionStatus, - error, + error: visibleError, bidLatencyDiagnostics, serverRoundTripMs: matchId ? serverRoundTripMs : null, serverTimeOffsetMs: matchId ? serverTimeOffsetMs : 0, diff --git a/apps/web/src/api/useRiotRefreshSocket.ts b/apps/web/src/api/useRiotRefreshSocket.ts index c53aa443..6ef241ee 100644 --- a/apps/web/src/api/useRiotRefreshSocket.ts +++ b/apps/web/src/api/useRiotRefreshSocket.ts @@ -1,5 +1,5 @@ import { useEffect, useRef, useState } from 'react'; -import { io, type Socket } from 'socket.io-client'; +import { io } from 'socket.io-client'; import { API_BASE_URL } from '../config'; import type { ApiRiotRefreshEvent } from './types'; @@ -19,37 +19,43 @@ export function useRiotRefreshSocket({ parentJobId?: string; onEvent: (event: ApiRiotRefreshEvent) => void; }) { - const socketRef = useRef(null); + const subscriptionKey = + puuid || parentJobId ? JSON.stringify([puuid, parentJobId]) : null; const onEventRef = useRef(onEvent); - const [connectionStatus, setConnectionStatus] = - useState('idle'); - const [error, setError] = useState(null); + const [connectionState, setConnectionState] = useState<{ + key: string; + status: ConnectionStatus; + error: string | null; + }>({ key: '', status: 'idle', error: null }); useEffect(() => { onEventRef.current = onEvent; }, [onEvent]); useEffect(() => { - if (!puuid && !parentJobId) { - setConnectionStatus('idle'); + if (!subscriptionKey) { return; } - setConnectionStatus('connecting'); - setError(null); - const socket = io(`${API_BASE_URL}/riot-refresh`, { transports: ['websocket'], }); - socketRef.current = socket; socket.on('connect', () => { - setConnectionStatus('connected'); + setConnectionState({ + key: subscriptionKey, + status: 'connected', + error: null, + }); socket.emit('subscribe', { puuid, parentJobId }); }); socket.on('disconnect', () => { - setConnectionStatus('disconnected'); + setConnectionState((current) => ({ + key: subscriptionKey, + status: 'disconnected', + error: current.key === subscriptionKey ? current.error : null, + })); }); socket.on('riot-refresh', (event: ApiRiotRefreshEvent) => { @@ -57,17 +63,29 @@ export function useRiotRefreshSocket({ }); socket.on('error', (payload: { message?: string }) => { - setConnectionStatus('error'); - setError(payload.message ?? '전적 갱신 소켓 연결 중 오류가 발생했습니다.'); + setConnectionState({ + key: subscriptionKey, + status: 'error', + error: + payload.message ?? '전적 갱신 소켓 연결 중 오류가 발생했습니다.', + }); }); return () => { socket.removeAllListeners(); socket.disconnect(); - socketRef.current = null; - setConnectionStatus('idle'); }; - }, [parentJobId, puuid]); + }, [parentJobId, puuid, subscriptionKey]); - return { connectionStatus, error }; + const hasCurrentConnection = + subscriptionKey !== null && connectionState.key === subscriptionKey; + return { + connectionStatus: + subscriptionKey === null + ? 'idle' + : hasCurrentConnection + ? connectionState.status + : 'connecting', + error: hasCurrentConnection ? connectionState.error : null, + }; } diff --git a/apps/web/src/components/DevAuthSwitcher.tsx b/apps/web/src/components/DevAuthSwitcher.tsx index b631cb1c..ff2c2758 100644 --- a/apps/web/src/components/DevAuthSwitcher.tsx +++ b/apps/web/src/components/DevAuthSwitcher.tsx @@ -1,20 +1,30 @@ -import { useEffect, useState } from 'react'; +import { useState } from 'react'; import { useQueryClient } from '@tanstack/react-query'; import { setAuthUserId, useAuthUserId } from '../config'; export default function DevAuthSwitcher() { const authUserId = useAuthUserId(); - const queryClient = useQueryClient(); - const [inputValue, setInputValue] = useState(authUserId ?? ''); - - useEffect(() => { - setInputValue(authUserId ?? ''); - }, [authUserId]); if (!import.meta.env.DEV) { return null; } + return ( + + ); +} + +function DevAuthSwitcherForm({ + authUserId, +}: { + authUserId: string | null; +}) { + const queryClient = useQueryClient(); + const [inputValue, setInputValue] = useState(authUserId ?? ''); + function updateAuthUserId(nextValue: string | null) { setAuthUserId(nextValue); void queryClient.invalidateQueries(); diff --git a/apps/web/src/components/RankBadge.tsx b/apps/web/src/components/RankBadge.tsx index a62bd1df..45252a92 100644 --- a/apps/web/src/components/RankBadge.tsx +++ b/apps/web/src/components/RankBadge.tsx @@ -1,21 +1,9 @@ import type { ApiTierInfo } from "../api/types"; +import { formatRankBadge, formatRankDetail } from "./rankBadgeUtils"; type RankBadgeSize = "sm" | "md"; type RankBadgeTooltipPlacement = "left" | "bottom"; -const TIER_NAMES: Record = { - IRON: "아이언", - BRONZE: "브론즈", - SILVER: "실버", - GOLD: "골드", - PLATINUM: "플래티넘", - EMERALD: "에메랄드", - DIAMOND: "다이아몬드", - MASTER: "마스터", - GRANDMASTER: "그랜드마스터", - CHALLENGER: "챌린저", -}; - const SIZE_CLASSES: Record = { sm: "h-[17px] min-w-[18px]", md: "h-[18px] min-w-[20px]", @@ -26,21 +14,6 @@ const TOOLTIP_CLASSES: Record = { bottom: "tooltip-bottom", }; -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 rankBadgeClass(tier: ApiTierInfo | undefined) { switch (tier?.tier) { case "CHALLENGER": @@ -68,22 +41,6 @@ function rankBadgeClass(tier: ApiTierInfo | undefined) { } } -export 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; -} - -export 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`; -} - export function RankBadge({ tier, size = "md", diff --git a/apps/web/src/components/TierHistoryChart.tsx b/apps/web/src/components/TierHistoryChart.tsx index 220ab749..03b42b2e 100644 --- a/apps/web/src/components/TierHistoryChart.tsx +++ b/apps/web/src/components/TierHistoryChart.tsx @@ -67,6 +67,7 @@ const TIER_COMPACT_NAMES: Record = { }; type PeriodKey = "30" | "90" | "all"; +type PeriodFilter = { key: PeriodKey; cutoffTimestamp: number }; type SummaryVariant = "footer" | "inline"; type SummaryDirection = "up" | "down" | "flat"; @@ -314,18 +315,17 @@ export default function TierHistoryChart({ const [queue, setQueue] = useState( availableQueues[0] ?? "RANKED_SOLO_5x5", ); - const [period, setPeriod] = useState("all"); + const [periodFilter, setPeriodFilter] = useState({ + key: "all", + cutoffTimestamp: 0, + }); + const period = periodFilter.key; const activeQueue = availableQueues.includes(queue) ? queue : (availableQueues[0] ?? "RANKED_SOLO_5x5"); const points = useMemo(() => { - const periodDays = - PERIOD_OPTIONS.find((option) => option.key === period)?.days ?? null; - const cutoff = - periodDays === null ? 0 : Date.now() - periodDays * 24 * 60 * 60 * 1000; - return entries .filter((entry) => entry.queueType === activeQueue) .map((entry) => ({ @@ -337,9 +337,9 @@ export default function TierHistoryChart({ wins: entry.wins, losses: entry.losses, })) - .filter((point) => point.ts >= cutoff) + .filter((point) => point.ts >= periodFilter.cutoffTimestamp) .sort((left, right) => left.ts - right.ts); - }, [entries, activeQueue, period]); + }, [entries, activeQueue, periodFilter.cutoffTimestamp]); // 티어 경계(가로 점선) 후보 — 데이터 범위 안에 드는 티어 floor만. const tierLines = useMemo(() => { @@ -408,7 +408,19 @@ export default function TierHistoryChart({ - setOverrides((current) => ({ - ...current, - [member.userId]: { - ...current[member.userId], - startTime: event.target.value, - endTime: current[member.userId]?.endTime ?? '', - }, - })) - } - className="border border-base-content/10 bg-transparent px-2 py-1 text-xs" - /> - - - - setOverrides((current) => ({ - ...current, - [member.userId]: { - ...current[member.userId], - startTime: current[member.userId]?.startTime ?? '', - endTime: event.target.value, - }, - })) - } - className="border border-base-content/10 bg-transparent px-2 py-1 text-xs" - /> - - - ))} + {members.map((member) => { + const override = + overrides[member.userId] ?? defaultMemberOverride(member); + return ( + + + {member.displayName} + + + {member.gameName}#{member.tagLine} + + + {member.isActivated ? '활성' : '비활성'} + + + + setOverrides((current) => { + const currentOverride = + current[member.userId] ?? + defaultMemberOverride(member); + return { + ...current, + [member.userId]: { + ...currentOverride, + startTime: event.target.value, + }, + }; + }) + } + className="border border-base-content/10 bg-transparent px-2 py-1 text-xs" + /> + + + + setOverrides((current) => { + const currentOverride = + current[member.userId] ?? + defaultMemberOverride(member); + return { + ...current, + [member.userId]: { + ...currentOverride, + endTime: event.target.value, + }, + }; + }) + } + className="border border-base-content/10 bg-transparent px-2 py-1 text-xs" + /> + + + ); + })} {members.length === 0 && (