All files / web/src/arcade-games/know-your-world/features/precision usePrecisionCalculations.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * Precision Calculations Hook
 *
 * Pure calculation hook for precision mode threshold detection.
 * Unlike usePrecisionMode, this hook does NOT manage pointer lock state -
 * it receives pointerLocked as an input, avoiding circular dependencies.
 *
 * Dependency flow (no cycles):
 * ```
 * useCanUsePrecisionMode() → canUsePrecisionMode
 *          ↓
 * usePointerLock({ canUsePrecisionMode }) → pointerLocked
 *          ↓
 * useMagnifierZoom({ pointerLocked }) → currentZoom
 *          ↓
 * usePrecisionCalculations({ currentZoom, pointerLocked }) → isAtThreshold, shouldCapZoom
 * ```
 */

'use client'

import type { RefObject } from 'react'
import { useMemo } from 'react'

import { useCanUsePrecisionMode } from '../../hooks/useDeviceCapabilities'
import {
  calculateMaxZoomAtThreshold,
  calculateScreenPixelRatio,
  isAboveThreshold,
} from '../../utils/screenPixelRatio'
import { PRECISION_MODE_THRESHOLD } from '../shared/constants'
import { parseViewBox } from '../shared/viewportUtils'

// ============================================================================
// Types
// ============================================================================

export interface UsePrecisionCalculationsOptions {
  /** Container element ref for dimension calculations */
  containerRef: RefObject<HTMLDivElement | null>
  /** SVG element ref for viewport calculations */
  svgRef: RefObject<SVGSVGElement | null>
  /** SVG viewBox string */
  viewBox: string
  /** Current zoom level (from useMagnifierZoom) */
  currentZoom: number
  /** Whether pointer lock is active (from usePointerLock) */
  pointerLocked: boolean
}

export interface UsePrecisionCalculationsReturn {
  /** Whether device supports precision mode (pointer lock + fine pointer) */
  canUsePrecisionMode: boolean
  /** Whether current zoom is at or above threshold (precision recommended) */
  isAtThreshold: boolean
  /** Current screen pixel ratio */
  screenPixelRatio: number
  /** Whether zoom should be capped (at threshold but not in precision mode) */
  shouldCapZoom: boolean
  /** Maximum zoom level that keeps screen pixel ratio at threshold */
  maxZoomAtThreshold: number
}

// ============================================================================
// Constants
// ============================================================================

/** Default magnifier width as fraction of container */
const MAGNIFIER_WIDTH_FRACTION = 0.5

// ============================================================================
// Hook Implementation
// ============================================================================

/**
 * Hook for precision mode threshold calculations.
 *
 * This is a pure calculation hook - it receives state as inputs and
 * computes derived values. It does not manage pointer lock state.
 *
 * Use this hook AFTER usePointerLock and useMagnifierZoom in your
 * component to get threshold status and capping decisions.
 *
 * @param options - Configuration options
 * @returns Precision calculation results
 *
 * @example
 * ```tsx
 * // In MapRenderer, after existing hooks:
 * const { pointerLocked } = usePointerLock({ containerRef, canUsePrecisionMode })
 * const { targetZoom, getCurrentZoom } = useMagnifierZoom({ pointerLocked, ... })
 *
 * const precision = usePrecisionCalculations({
 *   containerRef,
 *   svgRef,
 *   viewBox: mapData.viewBox,
 *   currentZoom: getCurrentZoom(),
 *   pointerLocked,
 * })
 *
 * // Use precision.isAtThreshold for UI indicators
 * // Use precision.shouldCapZoom for zoom limiting decisions
 * ```
 */
export function usePrecisionCalculations(
  options: UsePrecisionCalculationsOptions
): UsePrecisionCalculationsReturn {
  const { containerRef, svgRef, viewBox, currentZoom, pointerLocked } = options

  // -------------------------------------------------------------------------
  // Device Capability Detection
  // -------------------------------------------------------------------------
  const canUsePrecisionMode = useCanUsePrecisionMode()

  // -------------------------------------------------------------------------
  // Viewport Calculations
  // -------------------------------------------------------------------------
  const viewBoxComponents = useMemo(() => parseViewBox(viewBox), [viewBox])

  // -------------------------------------------------------------------------
  // Screen Pixel Ratio Calculations
  // -------------------------------------------------------------------------
  const screenPixelRatio = useMemo(() => {
    const container = containerRef.current
    const svg = svgRef.current

    if (!container || !svg) {
      return 0
    }

    const containerRect = container.getBoundingClientRect()
    const svgRect = svg.getBoundingClientRect()
    const magnifierWidth = containerRect.width * MAGNIFIER_WIDTH_FRACTION

    return calculateScreenPixelRatio({
      magnifierWidth,
      viewBoxWidth: viewBoxComponents.width,
      svgWidth: svgRect.width,
      zoom: currentZoom,
    })
  }, [containerRef, svgRef, viewBoxComponents.width, currentZoom])

  // -------------------------------------------------------------------------
  // Threshold Detection
  // -------------------------------------------------------------------------
  const isAtThreshold = useMemo(
    () => isAboveThreshold(screenPixelRatio, PRECISION_MODE_THRESHOLD),
    [screenPixelRatio]
  )

  // -------------------------------------------------------------------------
  // Max Zoom at Threshold
  // -------------------------------------------------------------------------
  const maxZoomAtThreshold = useMemo(() => {
    const container = containerRef.current
    const svg = svgRef.current

    if (!container || !svg) {
      return Infinity
    }

    const containerRect = container.getBoundingClientRect()
    const svgRect = svg.getBoundingClientRect()
    const magnifierWidth = containerRect.width * MAGNIFIER_WIDTH_FRACTION

    return calculateMaxZoomAtThreshold(PRECISION_MODE_THRESHOLD, magnifierWidth, svgRect.width)
  }, [containerRef, svgRef])

  // -------------------------------------------------------------------------
  // Zoom Capping Decision
  // -------------------------------------------------------------------------
  // Cap zoom when:
  // 1. At threshold (would exceed ratio)
  // 2. Precision mode is available (device supports it)
  // 3. Not currently in precision mode (user hasn't activated it)
  const shouldCapZoom = useMemo(
    () => isAtThreshold && canUsePrecisionMode && !pointerLocked,
    [isAtThreshold, canUsePrecisionMode, pointerLocked]
  )

  // -------------------------------------------------------------------------
  // Return
  // -------------------------------------------------------------------------
  return {
    canUsePrecisionMode,
    isAtThreshold,
    screenPixelRatio,
    shouldCapZoom,
    maxZoomAtThreshold,
  }
}