|
| 1 | +/** |
| 2 | + * Cooldowns Context |
| 3 | + * 提供共享的 Cooldowns 数据,减少重复请求 |
| 4 | + */ |
| 5 | + |
| 6 | +import { createContext, useContext, useEffect, useState, useCallback, type ReactNode } from 'react'; |
| 7 | +import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query'; |
| 8 | +import { getTransport } from '@/lib/transport'; |
| 9 | +import type { Cooldown } from '@/lib/transport'; |
| 10 | + |
| 11 | +interface CooldownsContextValue { |
| 12 | + cooldowns: Cooldown[]; |
| 13 | + isLoading: boolean; |
| 14 | + getCooldownForProvider: (providerId: number, clientType?: string) => Cooldown | undefined; |
| 15 | + isProviderInCooldown: (providerId: number, clientType?: string) => boolean; |
| 16 | + getRemainingSeconds: (cooldown: Cooldown) => number; |
| 17 | + formatRemaining: (cooldown: Cooldown) => string; |
| 18 | + clearCooldown: (providerId: number) => void; |
| 19 | + isClearingCooldown: boolean; |
| 20 | +} |
| 21 | + |
| 22 | +const CooldownsContext = createContext<CooldownsContextValue | null>(null); |
| 23 | + |
| 24 | +interface CooldownsProviderProps { |
| 25 | + children: ReactNode; |
| 26 | +} |
| 27 | + |
| 28 | +export function CooldownsProvider({ children }: CooldownsProviderProps) { |
| 29 | + const queryClient = useQueryClient(); |
| 30 | + // Force re-render counter to trigger updates when cooldowns expire |
| 31 | + const [refreshKey, setRefreshKey] = useState(0); |
| 32 | + |
| 33 | + const { |
| 34 | + data: cooldowns = [], |
| 35 | + isLoading, |
| 36 | + } = useQuery({ |
| 37 | + queryKey: ['cooldowns'], |
| 38 | + queryFn: () => getTransport().getCooldowns(), |
| 39 | + staleTime: 5000, |
| 40 | + }); |
| 41 | + |
| 42 | + // Subscribe to cooldown_update WebSocket event |
| 43 | + useEffect(() => { |
| 44 | + const transport = getTransport(); |
| 45 | + const unsubscribe = transport.subscribe('cooldown_update', () => { |
| 46 | + queryClient.invalidateQueries({ queryKey: ['cooldowns'] }); |
| 47 | + }); |
| 48 | + |
| 49 | + return () => { |
| 50 | + unsubscribe(); |
| 51 | + }; |
| 52 | + }, [queryClient]); |
| 53 | + |
| 54 | + // Mutation for clearing cooldown |
| 55 | + const clearCooldownMutation = useMutation({ |
| 56 | + mutationFn: (providerId: number) => getTransport().clearCooldown(providerId), |
| 57 | + onSuccess: () => { |
| 58 | + queryClient.invalidateQueries({ queryKey: ['cooldowns'] }); |
| 59 | + }, |
| 60 | + }); |
| 61 | + |
| 62 | + // Setup timeouts for each cooldown to force re-render when they expire |
| 63 | + useEffect(() => { |
| 64 | + if (cooldowns.length === 0) { |
| 65 | + return; |
| 66 | + } |
| 67 | + |
| 68 | + const timeouts: number[] = []; |
| 69 | + |
| 70 | + cooldowns.forEach((cooldown) => { |
| 71 | + const until = new Date(cooldown.untilTime).getTime(); |
| 72 | + const now = Date.now(); |
| 73 | + const delay = until - now; |
| 74 | + |
| 75 | + if (delay > 0) { |
| 76 | + const timeout = setTimeout(() => { |
| 77 | + setRefreshKey((prev) => prev + 1); |
| 78 | + }, delay + 100); |
| 79 | + timeouts.push(timeout); |
| 80 | + } |
| 81 | + }); |
| 82 | + |
| 83 | + return () => { |
| 84 | + timeouts.forEach((timeout) => clearTimeout(timeout)); |
| 85 | + }; |
| 86 | + }, [cooldowns]); |
| 87 | + |
| 88 | + const getCooldownForProvider = useCallback((providerId: number, clientType?: string) => { |
| 89 | + return cooldowns.find((cd: Cooldown) => { |
| 90 | + const matchesProvider = cd.providerID === providerId; |
| 91 | + const matchesClientType = |
| 92 | + cd.clientType === '' || |
| 93 | + cd.clientType === 'all' || |
| 94 | + (clientType && cd.clientType === clientType); |
| 95 | + |
| 96 | + if (!matchesProvider || !matchesClientType) { |
| 97 | + return false; |
| 98 | + } |
| 99 | + |
| 100 | + const untilTime = |
| 101 | + cd.untilTime || ((cd as unknown as Record<string, unknown>).until as string); |
| 102 | + if (!untilTime) { |
| 103 | + return false; |
| 104 | + } |
| 105 | + const until = new Date(untilTime).getTime(); |
| 106 | + const now = Date.now(); |
| 107 | + return until > now; |
| 108 | + }); |
| 109 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 110 | + }, [cooldowns, refreshKey]); |
| 111 | + |
| 112 | + const isProviderInCooldown = useCallback((providerId: number, clientType?: string) => { |
| 113 | + return !!getCooldownForProvider(providerId, clientType); |
| 114 | + }, [getCooldownForProvider]); |
| 115 | + |
| 116 | + const getRemainingSeconds = useCallback((cooldown: Cooldown) => { |
| 117 | + const untilTime = |
| 118 | + cooldown.untilTime || ((cooldown as unknown as Record<string, unknown>).until as string); |
| 119 | + if (!untilTime) return 0; |
| 120 | + |
| 121 | + const until = new Date(untilTime); |
| 122 | + const now = new Date(); |
| 123 | + const diff = until.getTime() - now.getTime(); |
| 124 | + return Math.max(0, Math.floor(diff / 1000)); |
| 125 | + }, []); |
| 126 | + |
| 127 | + const formatRemaining = useCallback((cooldown: Cooldown) => { |
| 128 | + const seconds = getRemainingSeconds(cooldown); |
| 129 | + |
| 130 | + if (Number.isNaN(seconds) || seconds === 0) return 'Expired'; |
| 131 | + |
| 132 | + const hours = Math.floor(seconds / 3600); |
| 133 | + const minutes = Math.floor((seconds % 3600) / 60); |
| 134 | + const secs = seconds % 60; |
| 135 | + |
| 136 | + if (hours > 0) { |
| 137 | + return `${String(hours).padStart(2, '0')}h ${String(minutes).padStart(2, '0')}m ${String(secs).padStart(2, '0')}s`; |
| 138 | + } else if (minutes > 0) { |
| 139 | + return `${String(minutes).padStart(2, '0')}m ${String(secs).padStart(2, '0')}s`; |
| 140 | + } else { |
| 141 | + return `${String(secs).padStart(2, '0')}s`; |
| 142 | + } |
| 143 | + }, [getRemainingSeconds]); |
| 144 | + |
| 145 | + const clearCooldown = useCallback((providerId: number) => { |
| 146 | + clearCooldownMutation.mutate(providerId); |
| 147 | + }, [clearCooldownMutation]); |
| 148 | + |
| 149 | + return ( |
| 150 | + <CooldownsContext.Provider |
| 151 | + value={{ |
| 152 | + cooldowns, |
| 153 | + isLoading, |
| 154 | + getCooldownForProvider, |
| 155 | + isProviderInCooldown, |
| 156 | + getRemainingSeconds, |
| 157 | + formatRemaining, |
| 158 | + clearCooldown, |
| 159 | + isClearingCooldown: clearCooldownMutation.isPending, |
| 160 | + }} |
| 161 | + > |
| 162 | + {children} |
| 163 | + </CooldownsContext.Provider> |
| 164 | + ); |
| 165 | +} |
| 166 | + |
| 167 | +export function useCooldownsContext() { |
| 168 | + const context = useContext(CooldownsContext); |
| 169 | + if (!context) { |
| 170 | + throw new Error('useCooldownsContext must be used within CooldownsProvider'); |
| 171 | + } |
| 172 | + return context; |
| 173 | +} |
| 174 | + |
| 175 | +// Optional hook that doesn't throw when used outside provider |
| 176 | +export function useCooldownFromContext(providerId: number, clientType?: string): Cooldown | undefined { |
| 177 | + const context = useContext(CooldownsContext); |
| 178 | + return context?.getCooldownForProvider(providerId, clientType); |
| 179 | +} |
0 commit comments