All files / hooks useTouchControls.ts

84.46% Statements 87/103
60% Branches 48/80
100% Functions 9/9
89.47% Lines 85/95

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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420                                                                                                                                                                                                                                                                                    121x 121x 121x 121x               121x 2x                                   121x             4x 4x 4x 4x     4x 4x 2x       2x   4x   4x                       2x   2x                   121x 17x   17x 17x 17x 17x     17x 1x 1x         1x         16x 16x           16x     4x 4x     4x   4x     4x       4x                       121x 9x   9x 9x 9x     9x 9x 9x       9x 9x 9x     9x     9x   5x     5x   3x 2x                 1x                     2x 1x                 1x                   4x   4x   4x               4x   2x 2x                 2x                     9x           121x   2x 2x 2x     2x 2x 2x           121x 104x   71x       71x 71x 71x   71x 71x 71x 71x       121x        
/**
 * Touch Controls Hook
 * 
 * Manages touch event handling and gesture recognition for mobile gameplay
 * Provides swipe detection, multi-touch support, and touch-based movement
 * 
 * @module hooks/useTouchControls
 * @category Mobile Controls
 * @korean 터치 컨트롤 훅
 */
 
import { useCallback, useEffect, useRef, useState } from 'react';
 
/**
 * Gesture types supported by the touch control system
 * 
 * Added tactical step gestures for Korean martial arts footwork:
 * - tap-{direction}: Quick tap for tactical 30cm step
 * - hold-{direction}: Hold for continuous walk
 * 
 * @korean 제스처타입
 */
export type GestureType =
  | 'swipe-right'
  | 'swipe-left'
  | 'swipe-up'
  | 'swipe-down'
  | 'two-finger-tap'
  | 'tap'
  | 'tap-forward'
  | 'tap-back'
  | 'tap-left'
  | 'tap-right'
  | 'tap-forward-left'
  | 'tap-forward-right'
  | 'tap-back-left'
  | 'tap-back-right'
  | 'hold-forward'
  | 'hold-back'
  | 'hold-left'
  | 'hold-right';
 
/**
 * Gesture event data
 */
export interface GestureEvent {
  /** Type of gesture detected */
  readonly type: GestureType;
  /** Distance of swipe in pixels (for swipe gestures) */
  readonly distance?: number;
  /** Coordinates of touch start */
  readonly startX?: number;
  readonly startY?: number;
  /** Coordinates of touch end */
  readonly endX?: number;
  readonly endY?: number;
}
 
/**
 * Props for useTouchControls hook
 */
export interface UseTouchControlsProps {
  /** Callback when gesture is detected */
  readonly onGesture: (gesture: GestureEvent) => void;
  /** Whether touch input is enabled */
  readonly enabled?: boolean;
  /** Minimum swipe distance in pixels (default: 50) */
  readonly minSwipeDistance?: number;
  /** Maximum time for tap in ms (default: 300) */
  readonly maxTapDuration?: number;
  /** Time threshold for hold vs tap in ms (default: 200) */
  readonly holdThreshold?: number;
  /** Enable haptic feedback for steps (default: true) */
  readonly enableHaptics?: boolean;
}
 
/**
 * Return type for useTouchControls hook
 */
export interface UseTouchControlsReturn {
  /** Whether a touch is currently active */
  readonly isTouching: boolean;
}
 
/**
 * Custom hook for handling touch controls and gesture recognition
 * 
 * Features:
 * - Swipe detection (horizontal and vertical)
 * - Two-finger tap detection for vital point mode
 * - Single tap detection
 * - Tactical step gestures (tap) vs continuous walk (hold)
 * - Distance calculation for swipe intensity
 * - Configurable thresholds
 * - Haptic feedback for tactical steps
 * 
 * Gesture Mapping:
 * - Swipe Right: Advance toward opponent
 * - Swipe Left: Retreat from opponent
 * - Swipe Up: High stance mode
 * - Swipe Down: Low stance mode
 * - Two-Finger Tap: Activate vital point targeting mode
 * - Single Tap (directional): Tactical 30cm step (전술적 발걸음)
 * - Hold (directional): Continuous walk movement
 * 
 * @example
 * ```typescript
 * const { isTouching } = useTouchControls({
 *   onGesture: (gesture) => {
 *     switch (gesture.type) {
 *       case 'tap-forward':
 *         handleTacticalStep('forward'); // 전진보법
 *         break;
 *       case 'hold-forward':
 *         handleContinuousWalk('forward');
 *         break;
 *       case 'two-finger-tap':
 *         activateVitalPointMode();
 *         break;
 *     }
 *   },
 *   enabled: !isPaused,
 *   holdThreshold: 200, // 200ms to distinguish tap from hold
 *   enableHaptics: true,
 * });
 * ```
 * 
 * @public
 * @korean 터치컨트롤사용
 */
export function useTouchControls({
  onGesture,
  enabled = true,
  minSwipeDistance = 50,
  maxTapDuration = 300,
  holdThreshold = 200,
  enableHaptics = true,
}: UseTouchControlsProps): UseTouchControlsReturn {
  const touchStartRef = useRef<Touch | null>(null);
  const touchStartTimeRef = useRef<number>(0);
  const [isTouching, setIsTouching] = useState<boolean>(false);
  const holdTimerRef = useRef<number | null>(null);
  
  /**
   * Trigger haptic feedback for tactical step
   * Light vibration (10ms) to confirm step input
   * 
   * @korean 햅틱피드백
   */
  const triggerStepHaptic = useCallback(() => {
    Eif (!enableHaptics || !navigator.vibrate) return;
    
    try {
      // Short, light vibration for step (10ms)
      navigator.vibrate(10);
    } catch (error) {
      // Haptic feedback not supported or failed
      console.debug('Haptic feedback not available:', error);
    }
  }, [enableHaptics]);
  
  /**
   * Determine directional gesture from touch position
   * Used for D-pad style controls
   * Returns null for ambiguous/stationary taps
   * 
   * @korean 방향제스처감지
   */
  const getDirectionalGesture = useCallback((
    startX: number,
    startY: number,
    endX: number,
    endY: number,
    isTap: boolean
  ): GestureType | null => {
    const deltaX = endX - startX;
    const deltaY = endY - startY;
    const absX = Math.abs(deltaX);
    const absY = Math.abs(deltaY);
    
    // If movement is too small, it's not a directional gesture
    const minDirectionalMovement = 15; // pixels
    if (absX < minDirectionalMovement && absY < minDirectionalMovement) {
      return null; // Ambiguous tap, not directional
    }
    
    // Check for diagonal gestures (45-degree threshold)
    const isDiagonal = absX > 20 && absY > 20 && Math.abs(absX - absY) < 30;
    
    const prefix = isTap ? 'tap' : 'hold';
    
    Iif (isDiagonal) {
      // Diagonal gestures (only for taps/steps)
      if (isTap) {
        if (deltaY < 0 && deltaX < 0) return 'tap-forward-left';
        if (deltaY < 0 && deltaX > 0) return 'tap-forward-right';
        if (deltaY > 0 && deltaX < 0) return 'tap-back-left';
        if (deltaY > 0 && deltaX > 0) return 'tap-back-right';
      }
      return null;
    }
    
    // Cardinal directions
    if (absX > absY) {
      // Horizontal
      return deltaX > 0 ? `${prefix}-right` as GestureType : `${prefix}-left` as GestureType;
    } else E{
      // Vertical
      return deltaY < 0 ? `${prefix}-forward` as GestureType : `${prefix}-back` as GestureType;
    }
  }, []);
 
  /**
   * Handle touch start event
   */
  const handleTouchStart = useCallback((e: TouchEvent) => {
    Iif (!enabled) return;
 
    const touch = e.touches[0];
    touchStartRef.current = touch;
    touchStartTimeRef.current = Date.now();
    setIsTouching(true);
 
    // Check for two-finger tap immediately
    if (e.touches.length === 2) {
      e.preventDefault();
      onGesture({
        type: 'two-finger-tap',
        startX: touch.clientX,
        startY: touch.clientY,
      });
      return;
    }
    
    // Capture screen dimensions at touch start time to prevent incorrect
    // direction calculation if window is resized during hold
    const screenCenterX = window.innerWidth / 2;
    const screenCenterY = window.innerHeight / 2;
    
    // Set up hold detection timer
    // Note: Hold gesture direction is determined from the initial touch position
    // relative to screen center. This supports D-pad style layouts where each
    // region of the screen (or an overlaid control) corresponds to a cardinal direction.
    holdTimerRef.current = window.setTimeout(() => {
      // Touch held for longer than threshold - trigger hold gesture
      // Check touchStartRef to ensure touch hasn't ended before timer fired
      Eif (touchStartRef.current) {
        const { clientX, clientY } = touchStartRef.current;
 
        // Use captured screen center coordinates (from touch start time)
        const deltaX = clientX - screenCenterX;
        // Invert Y so that a touch higher on the screen is considered "forward"
        const deltaY = screenCenterY - clientY;
 
        const holdGesture: GestureType =
          Math.abs(deltaX) >= Math.abs(deltaY)
            ? (deltaX > 0 ? 'hold-right' : 'hold-left')
            : (deltaY > 0 ? 'hold-forward' : 'hold-back');
 
        onGesture({
          type: holdGesture,
          startX: clientX,
          startY: clientY,
        });
      }
    }, holdThreshold);
  }, [enabled, onGesture, holdThreshold]);
 
  /**
   * Handle touch end event
   */
  const handleTouchEnd = useCallback((e: TouchEvent) => {
    Iif (!enabled || !touchStartRef.current) return;
 
    const touchEnd = e.changedTouches[0];
    const touchStart = touchStartRef.current;
    const touchDuration = Date.now() - touchStartTimeRef.current;
 
    // Clear hold timer
    Eif (holdTimerRef.current) {
      clearTimeout(holdTimerRef.current);
      holdTimerRef.current = null;
    }
 
    // Calculate deltas
    const deltaX = touchEnd.clientX - touchStart.clientX;
    const deltaY = touchEnd.clientY - touchStart.clientY;
    const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
 
    // Reset touch state
    setIsTouching(false);
 
    // Detect gesture type
    if (distance >= minSwipeDistance) {
      // Swipe gesture (for quick directional inputs)
      e.preventDefault();
 
      // Determine primary direction
      if (Math.abs(deltaX) > Math.abs(deltaY)) {
        // Horizontal swipe
        if (deltaX > 0) {
          onGesture({
            type: 'swipe-right',
            distance,
            startX: touchStart.clientX,
            startY: touchStart.clientY,
            endX: touchEnd.clientX,
            endY: touchEnd.clientY,
          });
        } else {
          onGesture({
            type: 'swipe-left',
            distance,
            startX: touchStart.clientX,
            startY: touchStart.clientY,
            endX: touchEnd.clientX,
            endY: touchEnd.clientY,
          });
        }
      } else {
        // Vertical swipe
        if (deltaY > 0) {
          onGesture({
            type: 'swipe-down',
            distance,
            startX: touchStart.clientX,
            startY: touchStart.clientY,
            endX: touchEnd.clientX,
            endY: touchEnd.clientY,
          });
        } else {
          onGesture({
            type: 'swipe-up',
            distance,
            startX: touchStart.clientX,
            startY: touchStart.clientY,
            endX: touchEnd.clientX,
            endY: touchEnd.clientY,
          });
        }
      }
    E} else if (touchDuration <= maxTapDuration && touchDuration < holdThreshold) {
      // Quick tap - tactical step gesture
      e.preventDefault();
      
      const tapGesture = getDirectionalGesture(
        touchStart.clientX,
        touchStart.clientY,
        touchEnd.clientX,
        touchEnd.clientY,
        true // Is a tap
      );
      
      if (tapGesture) {
        // Directional step tap
        triggerStepHaptic();
        onGesture({
          type: tapGesture,
          startX: touchStart.clientX,
          startY: touchStart.clientY,
          endX: touchEnd.clientX,
          endY: touchEnd.clientY,
        });
      } else {
        // Generic tap (fallback)
        onGesture({
          type: 'tap',
          startX: touchStart.clientX,
          startY: touchStart.clientY,
          endX: touchEnd.clientX,
          endY: touchEnd.clientY,
        });
      }
    }
 
    // Clear touch start reference
    touchStartRef.current = null;
  }, [enabled, minSwipeDistance, maxTapDuration, holdThreshold, onGesture, getDirectionalGesture, triggerStepHaptic]);
 
  /**
   * Handle touch cancel event
   */
  const handleTouchCancel = useCallback(() => {
    // Clear hold timer
    Eif (holdTimerRef.current) {
      clearTimeout(holdTimerRef.current);
      holdTimerRef.current = null;
    }
    
    touchStartRef.current = null;
    touchStartTimeRef.current = 0;
    setIsTouching(false);
  }, []);
 
  /**
   * Setup touch event listeners
   */
  useEffect(() => {
    if (!enabled) return;
 
    const options: AddEventListenerOptions = {
      passive: false, // Allow preventDefault for gesture handling
    };
 
    document.addEventListener('touchstart', handleTouchStart, options);
    document.addEventListener('touchend', handleTouchEnd, options);
    document.addEventListener('touchcancel', handleTouchCancel, options);
 
    return () => {
      document.removeEventListener('touchstart', handleTouchStart);
      document.removeEventListener('touchend', handleTouchEnd);
      document.removeEventListener('touchcancel', handleTouchCancel);
    };
  }, [enabled, handleTouchStart, handleTouchEnd, handleTouchCancel]);
 
  return {
    isTouching,
  };
}