All files / web/src/arcade-games/know-your-world/hooks useMagnifierZoom.ts

0% Statements 0/247
0% Branches 0/1
0% Functions 0/1
0% Lines 0/247

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 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * Magnifier Zoom Hook
 *
 * Manages zoom state, animation, and threshold-based capping for the magnifier.
 * Handles smooth zoom transitions, pausing at precision mode threshold, and
 * coordinating with pointer lock state.
 */

import { useSpring, useSpringRef } from '@react-spring/web'
import { type RefObject, useEffect, useRef, useState } from 'react'
import { getMagnifierDimensions } from '../utils/magnifierDimensions'
import {
  calculateMaxZoomAtThreshold,
  calculateScreenPixelRatio,
  isAboveThreshold,
} from '../utils/screenPixelRatio'

export interface UseMagnifierZoomOptions {
  /** The container element (for calculating dimensions) */
  containerRef: RefObject<HTMLDivElement>
  /** The SVG element (for calculating dimensions) */
  svgRef: RefObject<SVGSVGElement>
  /** The SVG viewBox string (e.g., "0 0 1000 500") */
  viewBox: string
  /** Precision mode threshold in px/px (e.g., 20) */
  threshold: number
  /** Whether pointer lock is currently active */
  pointerLocked: boolean
  /** Initial zoom level */
  initialZoom?: number
  /** Disable threshold-based zoom capping (useful for mobile where there's no pointer lock alternative) */
  disableThresholdCapping?: boolean
}

export interface UseMagnifierZoomReturn {
  /** Current target zoom level (may be capped) */
  targetZoom: number
  /** Set the target zoom level */
  setTargetZoom: (zoom: number) => void
  /** The animated spring value for zoom (spring object, not a number) */
  zoomSpring: any // Spring value that can be used with animated.div
  /** Get the current animated zoom value */
  getCurrentZoom: () => number
  /** Reference to the uncapped adaptive zoom (for pointer lock transitions) */
  uncappedAdaptiveZoomRef: React.MutableRefObject<number | null>
}

/**
 * Custom hook for managing magnifier zoom state and animation.
 *
 * This hook encapsulates:
 * - Zoom state management (target zoom, uncapped zoom ref)
 * - React Spring animation with configurable easing
 * - Automatic pause/resume at precision mode threshold
 * - Zoom capping when not in pointer lock mode
 * - Recalculation when pointer lock state changes
 *
 * @param options - Configuration options
 * @returns Zoom state and control methods
 */
export function useMagnifierZoom(options: UseMagnifierZoomOptions): UseMagnifierZoomReturn {
  const {
    containerRef,
    svgRef,
    viewBox,
    threshold,
    pointerLocked,
    initialZoom = 10,
    disableThresholdCapping = false,
  } = options

  const [targetZoom, setTargetZoom] = useState(initialZoom)
  const uncappedAdaptiveZoomRef = useRef<number | null>(null)

  // Set up React Spring animation for smooth zoom transitions
  const springRef = useSpringRef()
  const [magnifierSpring, magnifierApi] = useSpring(
    () => ({
      ref: springRef,
      zoom: targetZoom,
      config: {
        // Very slow, smooth animation for zoom
        // Lower tension + higher mass = longer, more gradual transitions
        tension: 30,
        friction: 30,
        mass: 4,
      },
    }),
    []
  )

  // Handle pointer lock state changes - recalculate zoom with capping
  useEffect(() => {
    // Skip capping logic entirely when disabled (e.g., on mobile)
    if (disableThresholdCapping) {
      return
    }

    // When pointer lock is released, cap zoom if it exceeds threshold
    if (!pointerLocked && uncappedAdaptiveZoomRef.current !== null) {
      const containerElement = containerRef.current
      const svgElement = svgRef.current

      if (!containerElement || !svgElement) {
        return
      }

      const containerRect = containerElement.getBoundingClientRect()
      const svgRect = svgElement.getBoundingClientRect()
      const { width: magnifierWidth } = getMagnifierDimensions(
        containerRect.width,
        containerRect.height
      )
      const viewBoxParts = viewBox.split(' ').map(Number)
      const viewBoxWidth = viewBoxParts[2]

      if (!viewBoxWidth || Number.isNaN(viewBoxWidth)) {
        return
      }

      const uncappedZoom = uncappedAdaptiveZoomRef.current
      const screenPixelRatio = calculateScreenPixelRatio({
        magnifierWidth,
        viewBoxWidth,
        svgWidth: svgRect.width,
        zoom: uncappedZoom,
      })

      // Cap zoom if it exceeds threshold
      if (isAboveThreshold(screenPixelRatio, threshold)) {
        const maxZoom = calculateMaxZoomAtThreshold(threshold, magnifierWidth, svgRect.width)
        const cappedZoom = Math.min(uncappedZoom, maxZoom)
        setTargetZoom(cappedZoom)
      }
    }

    // When pointer lock is acquired, update target zoom to uncapped value
    if (pointerLocked && uncappedAdaptiveZoomRef.current !== null) {
      setTargetZoom(uncappedAdaptiveZoomRef.current)
    }
  }, [pointerLocked, containerRef, svgRef, viewBox, threshold, disableThresholdCapping])

  // Handle pause/resume at threshold
  useEffect(() => {
    const currentZoom = magnifierSpring.zoom.get()
    const zoomIsAnimating = Math.abs(currentZoom - targetZoom) > 0.01

    // Skip threshold checking when capping is disabled (e.g., on mobile)
    // In this case, just ensure the animation runs without pausing
    if (disableThresholdCapping) {
      magnifierApi.resume()
      magnifierApi.start({ zoom: targetZoom })
      return
    }

    // Check if CURRENT zoom is at/above threshold (zoom is capped)
    let currentScreenPixelRatio = 0
    const currentIsAtThreshold =
      !pointerLocked &&
      containerRef.current &&
      svgRef.current &&
      (() => {
        const containerRect = containerRef.current.getBoundingClientRect()
        const svgRect = svgRef.current.getBoundingClientRect()
        const { width: magnifierWidth } = getMagnifierDimensions(
          containerRect.width,
          containerRect.height
        )
        const viewBoxParts = viewBox.split(' ').map(Number)
        const viewBoxWidth = viewBoxParts[2]

        if (!viewBoxWidth || Number.isNaN(viewBoxWidth)) return false

        currentScreenPixelRatio = calculateScreenPixelRatio({
          magnifierWidth,
          viewBoxWidth,
          svgWidth: svgRect.width,
          zoom: currentZoom,
        })

        return isAboveThreshold(currentScreenPixelRatio, threshold)
      })()

    // Check if TARGET zoom is at/above threshold
    let targetScreenPixelRatio = 0
    const targetIsAtThreshold =
      !pointerLocked &&
      containerRef.current &&
      svgRef.current &&
      (() => {
        const containerRect = containerRef.current.getBoundingClientRect()
        const svgRect = svgRef.current.getBoundingClientRect()
        const { width: magnifierWidth } = getMagnifierDimensions(
          containerRect.width,
          containerRect.height
        )
        const viewBoxParts = viewBox.split(' ').map(Number)
        const viewBoxWidth = viewBoxParts[2]

        if (!viewBoxWidth || Number.isNaN(viewBoxWidth)) return false

        targetScreenPixelRatio = calculateScreenPixelRatio({
          magnifierWidth,
          viewBoxWidth,
          svgWidth: svgRect.width,
          zoom: targetZoom,
        })

        return isAboveThreshold(targetScreenPixelRatio, threshold)
      })()

    // Pause if:
    // - Currently at threshold AND
    // - Animating toward higher zoom AND
    // - Target is also at threshold
    const shouldPause = currentIsAtThreshold && zoomIsAnimating && targetIsAtThreshold

    if (shouldPause) {
      magnifierApi.pause()
    } else {
      // Resume/update animation
      // CRITICAL: Always resume first in case spring was paused
      magnifierApi.resume()
      magnifierApi.start({ zoom: targetZoom })
    }
  }, [
    targetZoom, // Effect runs when target zoom changes
    pointerLocked, // Effect runs when pointer lock state changes
    viewBox,
    threshold,
    containerRef,
    svgRef,
    magnifierApi,
    disableThresholdCapping,
    // NOTE: Do NOT include magnifierSpring.zoom here!
    // Spring values don't trigger React effects correctly.
    // We read spring.zoom.get() inside the effect, but don't depend on it.
  ])

  return {
    targetZoom,
    setTargetZoom,
    zoomSpring: magnifierSpring.zoom, // Return the spring object, not .get()
    getCurrentZoom: () => magnifierSpring.zoom.get(),
    uncappedAdaptiveZoomRef,
  }
}