Skip to content
Source
Sign inSign up
samwillis/one-million-boxes
Open History to see the last commit

quota-context.tsx

298 lines9.3 KB

1import { createContext, useCallback, useContext, useEffect, useState } from "react"
2import { MAX_QUOTA, QUOTA_REFILL_INTERVAL_MS, QUOTA_STORAGE_KEY } from "../lib/config"
3import type { ReactNode } from "react"
4​
5// Re-export for backward compatibility
6export { MAX_QUOTA }
7export const QUOTA_KEY = QUOTA_STORAGE_KEY
8export const REFILL_INTERVAL_MS = QUOTA_REFILL_INTERVAL_MS
9const LOCAL_BOXES_KEY = `boxes:local-completed`
10​
11export interface QuotaState {
12 remaining: number
13 lastRefillAt: number
14 version: number
16​
17export interface BonusPosition {
18 x: number
19 y: number
21​
22export interface QuotaContextValue {
23 /** Current remaining quota tokens */
24 remaining: number
25 /** Maximum quota tokens */
26 max: number
27 /** Seconds until next refill (0 if full) */
28 refillIn: number
29 /** Browser-clock refill deadline, aligned with the latest server quota response. */
30 nextRefillAt: number | null
31 /** Counts blocked draw attempts so repeated clicks can restart move feedback. */
32 emptyMoveAttempts: number
33 /** Signal an out-of-moves response from the server. */
34 notifyNoMoves: () => void
35 /** Number of bonus tokens earned (for toast animation), resets after reading */
36 bonusCount: number
37 /** Screen position where bonus toast should appear */
38 bonusPosition: BonusPosition | null
39 /** Set the position for the bonus toast (called by GameCanvas) */
40 setBonusPosition: (pos: BonusPosition | null) => void
41 /** Clear the bonus count after showing toast */
42 clearBonus: () => void
43 /** Optimistically consume a token. Returns false if no tokens available. */
44 consume: () => boolean
45 /** Sync quota state from server response. Use this instead of manual refunds. */
46 syncFromServer: (remaining: number, refillIn?: number, boxesClaimed?: number) => void
47 /** Legacy refund for error cases where server doesn't respond */
48 refund: () => void
49 /** Local user's total completed boxes count (persisted in localStorage) */
50 localBoxesCompleted: number
52​
53const QuotaContext = createContext<QuotaContextValue | null>(null)
54​
55function loadQuota(): QuotaState {
56 try {
57 const stored = localStorage.getItem(QUOTA_KEY)
58 if (stored) {
59 const state = JSON.parse(stored) as QuotaState
60​
61 // Calculate refills since last visit
62 const now = Date.now()
63 const elapsed = now - state.lastRefillAt
64 const refills = Math.floor(elapsed / REFILL_INTERVAL_MS)
65​
66 if (refills > 0) {
67 state.remaining = Math.min(MAX_QUOTA, state.remaining + refills)
68 state.lastRefillAt += refills * REFILL_INTERVAL_MS
69 }
70​
71 return state
72 }
73 } catch {
74 // Ignore parse errors
75 }
76​
77 return {
78 remaining: MAX_QUOTA,
79 lastRefillAt: Date.now(),
80 version: 1,
81 }
83​
84function saveQuota(state: QuotaState): void {
85 localStorage.setItem(QUOTA_KEY, JSON.stringify(state))
87​
88function loadLocalBoxes(): number {
89 try {
90 const stored = localStorage.getItem(LOCAL_BOXES_KEY)
91 if (stored) {
92 return parseInt(stored, 10) || 0
93 }
94 } catch {
95 // Ignore parse errors
96 }
97 return 0
99​
100export function QuotaProvider({ children }: { children: ReactNode }) {
101 const [state, setState] = useState<QuotaState>(() => loadQuota())
102 const [refillIn, setRefillIn] = useState(0)
103 const [emptyMoveAttempts, setEmptyMoveAttempts] = useState(0)
104 const notifyNoMoves = useCallback(() => setEmptyMoveAttempts((count) => count + 1), [])
105 const [bonusCount, setBonusCount] = useState(0)
106 const [bonusPosition, setBonusPosition] = useState<BonusPosition | null>(null)
107 const [localBoxesCompleted, setLocalBoxesCompleted] = useState(loadLocalBoxes)
108​
109 // Persist to localStorage
110 useEffect(() => {
111 saveQuota(state)
112 }, [state])
113​
114 // Refill timer - check every 1 second
115 // Uses functional update to avoid stale closure issues
116 useEffect(() => {
117 const interval = setInterval(() => {
118 const now = Date.now()
119​
120 setState((s) => {
121 const elapsed = now - s.lastRefillAt
122 const refills = Math.floor(elapsed / REFILL_INTERVAL_MS)
123​
124 if (refills > 0 && s.remaining < MAX_QUOTA) {
125 const newRemaining = Math.min(MAX_QUOTA, s.remaining + refills)
126 const newLastRefillAt = s.lastRefillAt + refills * REFILL_INTERVAL_MS
127​
128 // Update refillIn based on new state
129 const timeSinceNewRefill = now - newLastRefillAt
130 const timeUntilNext = Math.max(0, REFILL_INTERVAL_MS - timeSinceNewRefill)
131 setRefillIn(Math.ceil(timeUntilNext / 1000))
132​
133 return {
134 ...s,
135 remaining: newRemaining,
136 lastRefillAt: newLastRefillAt,
137 }
138 }
139​
140 // No refill needed, just update the countdown
141 const timeSinceLastRefill = now - s.lastRefillAt
142 const timeUntilNext = Math.max(0, REFILL_INTERVAL_MS - timeSinceLastRefill)
143 setRefillIn(Math.ceil(timeUntilNext / 1000))
144​
145 return s // No state change
146 })
147 }, 1000)
148​
149 return () => clearInterval(interval)
150 }, [])
151​
152 // Cross-tab sync via storage event
153 useEffect(() => {
154 const handler = (e: StorageEvent) => {
155 if (e.key === QUOTA_KEY && e.newValue) {
156 setState(JSON.parse(e.newValue))
157 }
158 if (e.key === LOCAL_BOXES_KEY && e.newValue) {
159 setLocalBoxesCompleted(parseInt(e.newValue, 10) || 0)
160 }
161 }
162​
163 window.addEventListener(`storage`, handler)
164 return () => window.removeEventListener(`storage`, handler)
165 }, [])
166​
167 // Optimistically consume a token (called before server request)
168 const consume = useCallback(() => {
169 if (state.remaining <= 0) {
170 notifyNoMoves()
171 return false
172 }
173​
174 setState((s) => ({
175 ...s,
176 remaining: s.remaining - 1,
177 // A full meter has no pending refill. Start its clock on the first spend,
178 // rather than immediately refilling from time spent idle at full quota.
179 lastRefillAt: s.remaining === MAX_QUOTA ? Date.now() : s.lastRefillAt,
180 }))
181​
182 return true
183 }, [state.remaining, notifyNoMoves])
184​
185 // Sync quota from server response (includes any refunds for completed boxes)
186 const syncFromServer = useCallback(
187 (remaining: number, serverRefillIn?: number, boxesClaimed?: number) => {
188 const now = Date.now()
189​
190 // Track bonus for toast animation and increment local boxes count
191 if (boxesClaimed && boxesClaimed > 0) {
192 setBonusCount(boxesClaimed)
193 setLocalBoxesCompleted((prev) => {
194 const newCount = prev + boxesClaimed
195 try {
196 localStorage.setItem(LOCAL_BOXES_KEY, String(newCount))
197 } catch {
198 // Ignore storage errors
199 }
200 return newCount
201 })
202 }
203​
204 // Calculate lastRefillAt to align with server's refillIn
205 // This ensures the interval timer computes the same countdown
206 setState((s) => {
207 let newLastRefillAt: number
208 if (serverRefillIn !== undefined && serverRefillIn >= 0) {
209 if (serverRefillIn === 0 && remaining < MAX_QUOTA) {
210 // Server says refill is imminent (less than 1 second away)
211 // Set lastRefillAt so client will refill on next timer tick
212 newLastRefillAt = now - REFILL_INTERVAL_MS
213 setRefillIn(0)
214 } else if (serverRefillIn > 0) {
215 // Server says "next refill in X seconds"
216 // So lastRefillAt should be: now - (interval - X*1000)
217 // Clamp serverRefillIn to interval to prevent future timestamps
218 const clampedRefillMs = Math.min(serverRefillIn * 1000, REFILL_INTERVAL_MS)
219 newLastRefillAt = now - (REFILL_INTERVAL_MS - clampedRefillMs)
220 setRefillIn(Math.floor(clampedRefillMs / 1000))
221 } else {
222 // refillIn=0 and quota is full - no pending refill
223 newLastRefillAt = now
224 setRefillIn(0)
225 }
226 } else {
227 // No server refillIn provided - keep current timing
228 newLastRefillAt = s.lastRefillAt
229 }
230​
231 return {
232 ...s,
233 remaining: Math.min(MAX_QUOTA, Math.max(0, remaining)),
234 lastRefillAt: newLastRefillAt,
235 }
236 })
237 },
238 [],
239 )
240​
241 // Clear bonus count and position after toast is shown
242 const clearBonus = useCallback(() => {
243 setBonusCount(0)
244 setBonusPosition(null)
245 }, [])
246​
247 // Legacy refund for network errors where server doesn't respond
248 const refund = useCallback(() => {
249 setState((s) => ({
250 ...s,
251 remaining: Math.min(MAX_QUOTA, s.remaining + 1),
252 }))
253 }, [])
254​
255 useEffect(() => {
256 let active = true
257 fetch("/api/quota", { cache: "no-store" })
258 .then((response) => response.json())
259 .then((result) => {
260 if (active && result.ok) syncFromServer(result.quotaRemaining, result.refillIn)
261 })
262 .catch(() => {})
263 return () => {
264 active = false
265 }
266 }, [syncFromServer])
267​
268 return (
269 <QuotaContext.Provider
270 value={{
271 remaining: state.remaining,
272 max: MAX_QUOTA,
273 refillIn,
274 nextRefillAt: state.remaining < MAX_QUOTA ? state.lastRefillAt + REFILL_INTERVAL_MS : null,
275 emptyMoveAttempts,
276 notifyNoMoves,
277 bonusCount,
278 bonusPosition,
279 setBonusPosition,
280 clearBonus,
281 consume,
282 syncFromServer,
283 refund,
284 localBoxesCompleted,
285 }}
286 >
287 {children}
288 </QuotaContext.Provider>
289 )
291​
292export function useQuota(): QuotaContextValue {
293 const ctx = useContext(QuotaContext)
294 if (!ctx) {
295 throw new Error(`useQuota must be used within QuotaProvider`)
296 }
297 return ctx