All files / web/src/contexts GameCompletionContext.tsx

100% Statements 45/45
100% Branches 3/3
100% Functions 2/2
100% Lines 45/45

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 461x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 2x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 7x 7x  
'use client'
 
import { createContext, useContext, useRef, type ReactNode } from 'react'
 
type GameCompleteCallback = (gameState: Record<string, unknown>) => void
 
const GameCompletionContext = createContext<GameCompleteCallback | null>(null)
 
/**
 * Provides a game completion callback that game providers can call
 * when transitioning to the 'results' phase.
 *
 * Used by PracticeGameModeProvider to detect game completion
 * without needing a separate socket connection.
 */
export function GameCompletionProvider({
  onGameComplete,
  children,
}: {
  onGameComplete: GameCompleteCallback
  children: ReactNode
}) {
  // Use ref to avoid re-renders when callback identity changes
  const callbackRef = useRef(onGameComplete)
  callbackRef.current = onGameComplete
 
  // Stable callback that reads from ref
  const stableCallback = useRef<GameCompleteCallback>((gameState) => {
    callbackRef.current(gameState)
  }).current
 
  return (
    <GameCompletionContext.Provider value={stableCallback}>
      {children}
    </GameCompletionContext.Provider>
  )
}
 
/**
 * Returns the game completion callback if available (i.e., inside a GameCompletionProvider).
 * Returns null if not in a practice/game-break context.
 */
export function useGameCompletionCallback(): GameCompleteCallback | null {
  return useContext(GameCompletionContext)
}