All files / web/src/hooks useCelebrationWindDown.ts

95.3% Statements 203/213
75.86% Branches 22/29
100% Functions 6/6
95.3% Lines 203/213

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 2141x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 7x 11x     11x 1x 6x 6x 6x 6x 6x 6x     6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 1x 1x 1x 1x 1x 30x 30x 30x 14x 14x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 10x 10x 14x 3x 3x 3x 3x 3x 7x 7x 7x 7x 14x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 14x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 7x 7x 7x 3x 3x         3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 7x 7x 7x 7x 7x 7x 7x 7x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x  
/**
 * Hook for managing celebration wind-down state
 *
 * Tracks when a skill unlock celebration started and provides
 * smooth progress updates via requestAnimationFrame.
 */
 
import { useCallback, useEffect, useRef, useState } from 'react'
import { windDownProgress } from '@/utils/interpolate'
 
// =============================================================================
// Types & Constants
// =============================================================================
 
interface CelebrationState {
  skillId: string
  startedAt: number
  confettiFired: boolean
}
 
const CELEBRATION_STORAGE_KEY = 'skill-celebration-state'
 
// =============================================================================
// localStorage Helpers
// =============================================================================
 
function getCelebrationState(): CelebrationState | null {
  if (typeof window === 'undefined') return null
 
  try {
    const stored = localStorage.getItem(CELEBRATION_STORAGE_KEY)
    if (!stored) return null
    return JSON.parse(stored) as CelebrationState
  } catch {
    return null
  }
}
 
function setCelebrationState(state: CelebrationState): void {
  if (typeof window === 'undefined') return
 
  try {
    localStorage.setItem(CELEBRATION_STORAGE_KEY, JSON.stringify(state))
  } catch {
    // Ignore localStorage errors
  }
}
 
function markConfettiFired(skillId: string): void {
  const state = getCelebrationState()
  if (state && state.skillId === skillId) {
    setCelebrationState({ ...state, confettiFired: true })
  }
}
 
// =============================================================================
// Hook
// =============================================================================
 
interface UseCelebrationWindDownOptions {
  /** The skill ID that was unlocked */
  skillId: string
  /** Whether this mode requires a tutorial (celebration only for tutorial-required skills) */
  tutorialRequired: boolean
  /** Whether to enable the celebration (pass false to skip) */
  enabled?: boolean
  /** Speed multiplier for testing (1 = normal, 10 = 10x faster, 60 = see full transition in 1 second) */
  speedMultiplier?: number
  /** Force a specific progress value (for Storybook stories) */
  forceProgress?: number
}
 
interface UseCelebrationWindDownResult {
  /** Progress from 0 (full celebration) to 1 (fully normal) */
  progress: number
  /** Whether confetti should be fired (only true once per skill) */
  shouldFireConfetti: boolean
  /** Current oscillation value for wiggle animation (-1 to 1) */
  oscillation: number
  /** Mark confetti as fired (call after firing) */
  onConfettiFired: () => void
  /** Whether we're in celebration mode at all */
  isCelebrating: boolean
}
 
export function useCelebrationWindDown({
  skillId,
  tutorialRequired,
  enabled = true,
  speedMultiplier = 1,
  forceProgress,
}: UseCelebrationWindDownOptions): UseCelebrationWindDownResult {
  const [progress, setProgress] = useState(1) // Start at 1 (normal) until we check state
  const [shouldFireConfetti, setShouldFireConfetti] = useState(false)
  const [oscillation, setOscillation] = useState(0)
  const [isCelebrating, setIsCelebrating] = useState(false)
 
  const rafIdRef = useRef<number | null>(null)
  const confettiFiredRef = useRef(false)
  const startTimeRef = useRef<number | null>(null)
 
  const onConfettiFired = useCallback(() => {
    if (skillId) {
      markConfettiFired(skillId)
      confettiFiredRef.current = true
      setShouldFireConfetti(false)
    }
  }, [skillId])
 
  useEffect(() => {
    // If forceProgress is set, use it directly (for Storybook)
    if (forceProgress !== undefined) {
      setProgress(forceProgress)
      setIsCelebrating(forceProgress < 1)
      // Still calculate oscillation for wiggle
      const osc = Math.sin(Date.now() / 250)
      setOscillation(osc)
 
      // Keep updating oscillation
      const animate = () => {
        const osc = Math.sin(Date.now() / 250)
        setOscillation(osc)
        rafIdRef.current = requestAnimationFrame(animate)
      }
      rafIdRef.current = requestAnimationFrame(animate)
 
      return () => {
        if (rafIdRef.current !== null) {
          cancelAnimationFrame(rafIdRef.current)
        }
      }
    }
 
    // Don't celebrate if disabled or no tutorial required
    if (!enabled || !tutorialRequired || !skillId) {
      setProgress(1)
      setIsCelebrating(false)
      setShouldFireConfetti(false)
      return
    }
 
    // Check existing celebration state
    const existingState = getCelebrationState()
 
    if (!existingState || existingState.skillId !== skillId) {
      // New skill unlock! Start fresh celebration
      const newState: CelebrationState = {
        skillId,
        startedAt: Date.now(),
        confettiFired: false,
      }
      setCelebrationState(newState)
      startTimeRef.current = Date.now()
      setProgress(0)
      setIsCelebrating(true)
      setShouldFireConfetti(true)
      confettiFiredRef.current = false
    } else {
      // Existing celebration - calculate current progress
      startTimeRef.current = existingState.startedAt
      const elapsed = (Date.now() - existingState.startedAt) * speedMultiplier
      const currentProgress = windDownProgress(elapsed)
      setProgress(currentProgress)
      setIsCelebrating(currentProgress < 1)
 
      // Only fire confetti if it hasn't been fired yet
      if (!existingState.confettiFired && !confettiFiredRef.current) {
        setShouldFireConfetti(true)
      }
    }
 
    // Animation loop for smooth updates
    const animate = () => {
      const state = getCelebrationState()
      if (!state || state.skillId !== skillId) {
        setProgress(1)
        setIsCelebrating(false)
        return
      }
 
      // Apply speed multiplier to elapsed time
      const elapsed = (Date.now() - state.startedAt) * speedMultiplier
      const newProgress = windDownProgress(elapsed)
 
      setProgress(newProgress)
      setIsCelebrating(newProgress < 1)
 
      // Oscillation for wiggle (period of ~500ms, also sped up)
      const osc = Math.sin((Date.now() * speedMultiplier) / 250)
      setOscillation(osc)
 
      if (newProgress < 1) {
        rafIdRef.current = requestAnimationFrame(animate)
      }
    }
 
    rafIdRef.current = requestAnimationFrame(animate)
 
    return () => {
      if (rafIdRef.current !== null) {
        cancelAnimationFrame(rafIdRef.current)
      }
    }
  }, [skillId, tutorialRequired, enabled, speedMultiplier, forceProgress])
 
  return {
    progress,
    shouldFireConfetti,
    oscillation,
    onConfettiFired,
    isCelebrating,
  }
}