useLongRunningTransitionState.ts52 lines · main
1import { useEffect, useRef, useState } from 'react'
2
3import {
4 getPersistedTransitionStartTime,
5 getRemainingTransitionTimeMs,
6 hoursToMilliseconds,
7 MAX_PERSISTED_TRANSITION_AGE_HOURS,
8} from '@/lib/project-transition-state'
9
10interface UseLongRunningTransitionStateParams {
11 storageKey: string | null
12 thresholdMs: number
13}
14
15export const useLongRunningTransitionState = ({
16 storageKey,
17 thresholdMs,
18}: UseLongRunningTransitionStateParams) => {
19 const [isTakingLongerThanExpected, setIsTakingLongerThanExpected] = useState(false)
20 const fallbackStartTimeRef = useRef<number | null>(null)
21
22 useEffect(() => {
23 const now = Date.now()
24 const fallbackStartTime = fallbackStartTimeRef.current ?? now
25 fallbackStartTimeRef.current = fallbackStartTime
26
27 const startTime = storageKey
28 ? getPersistedTransitionStartTime(
29 storageKey,
30 now,
31 hoursToMilliseconds(MAX_PERSISTED_TRANSITION_AGE_HOURS)
32 )
33 : fallbackStartTime
34
35 const remainingThresholdMs = getRemainingTransitionTimeMs({
36 startTimeMs: startTime,
37 thresholdMs,
38 now,
39 })
40
41 if (remainingThresholdMs === 0) {
42 setIsTakingLongerThanExpected(true)
43 return
44 }
45
46 setIsTakingLongerThanExpected(false)
47 const timeoutId = setTimeout(() => setIsTakingLongerThanExpected(true), remainingThresholdMs)
48 return () => clearTimeout(timeoutId)
49 }, [storageKey, thresholdMs])
50
51 return isTakingLongerThanExpected
52}