All files / hooks useKeyboardControls.ts

66.32% Statements 130/196
49.62% Branches 66/133
66.66% Functions 10/15
69.27% Lines 124/179

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 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504                            3x             3x                 3x                         3x                                                                                                     3x         3x                                                                       134x 134x 134x 134x     134x         134x 5x 5x 5x 3x     5x 3x   5x                   134x                                                           134x 34x           34x 34x 34x               134x 63x               63x           134x 100x     66x   66x 43x     43x     43x 4x 4x 4x       39x 1x 1x 1x         38x   43x                                                                 38x 38x 13x     13x   1x     1x 1x   1x       12x 12x 4x   8x     8x 8x     8x 8x   8x       25x 25x 25x   25x   2x 2x 2x 2x     1x 1x 1x 1x             17x                                       17x   8x   8x   3x 5x   2x 3x   3x     8x 8x 8x       8x   9x   5x   5x   2x 3x   1x 2x   1x 1x   1x     5x 5x 5x       5x   4x                                               4x 4x   17x       2x 2x 2x 2x       1x 1x 1x 1x       2x 2x 2x 2x         66x         66x 66x   66x 66x 66x   66x                             134x            
/**
 * Custom hook for keyboard controls with visual feedback
 * Manages keyboard input for trigram stance switching and combat actions
 * 
 * @module hooks/useKeyboardControls
 * @category Input System
 * @korean 키보드 컨트롤 훅
 */
 
import { useCallback, useEffect, useRef, useState } from "react";
import { ControlMapper } from "../utils/controlMapping";
import { FOOTWORK_KOREAN_TERMS } from "../systems/animation/types";
 
// Korean terminology constants (module-level to avoid recreation on every keystroke)
const DIAGONAL_KOREAN_TERMS: Record<string, string> = {
  "step_forward_left": "전좌측보법 (Forward-Left)",
  "step_forward_right": "전우측보법 (Forward-Right)",
  "step_back_left": "후좌측보법 (Back-Left)",
  "step_back_right": "후우측보법 (Back-Right)",
};
 
const STEP_KOREAN_TERMS: Record<string, string> = {
  "step_forward": "전진보법 (Forward Step)",
  "step_back": "후퇴보법 (Retreat Step)",
  "step_left": "좌측면보법 (Left Step)",
  "step_right": "우측면보법 (Right Step)",
};
 
// Footwork pattern Korean terminology - maps animation states to display names
// Reuses FOOTWORK_KOREAN_TERMS from types.ts but adds specific animation state labels
const FOOTWORK_DISPLAY_TERMS: Record<string, string> = {
  "footwork_circular_left": `${FOOTWORK_KOREAN_TERMS.circular.korean} 좌 (Circular Left)`,
  "footwork_circular_right": `${FOOTWORK_KOREAN_TERMS.circular.korean} 우 (Circular Right)`,
  "footwork_pivot_left": `${FOOTWORK_KOREAN_TERMS.pivot.korean} 좌 (Pivot Left)`,
  "footwork_pivot_right": `${FOOTWORK_KOREAN_TERMS.pivot.korean} 우 (Pivot Right)`,
  "footwork_slide_forward": `${FOOTWORK_KOREAN_TERMS.slide.korean} 전 (Slide Forward)`,
  "footwork_slide_back": `${FOOTWORK_KOREAN_TERMS.slide.korean} 후 (Slide Back)`,
  "footwork_slide_left": `${FOOTWORK_KOREAN_TERMS.slide.korean} 좌 (Slide Left)`,
  "footwork_slide_right": `${FOOTWORK_KOREAN_TERMS.slide.korean} 우 (Slide Right)`,
  "footwork_shuffle": `${FOOTWORK_KOREAN_TERMS.shuffle.korean} (Shuffle)`,
};
 
// Step direction mapping (all move_* actions covered explicitly)
const STEP_DIRECTION_MAP: Record<string, string> = {
  move_up: "step_forward",
  move_down: "step_back",
  move_left: "step_left",
  move_right: "step_right",
};
 
/**
 * Queued input for input buffer display
 */
export interface QueuedInput {
  readonly action: string;
  readonly key: string;
  readonly timestamp: number;
}
 
/**
 * Props for useKeyboardControls hook
 */
export interface UseKeyboardControlsProps {
  /** Callback when stance changes (receives stance index 0-7) */
  readonly onStanceChange: (stance: number) => void;
  /** Callback for combat actions (attack, block, etc.) */
  readonly onAction: (action: string) => void;
  /** Whether keyboard input is enabled */
  readonly enabled?: boolean;
  /** Current stance index (0-7) for validation */
  readonly currentStance?: number;
  /** Callback when hints toggle is requested */
  readonly onToggleHints?: () => void;
  /** Play sound effect function */
  readonly playSFX?: (soundId: string) => void;
  /** Current animation state for grounded detection */
  readonly currentAnimationState?: string;
}
 
/**
 * Return type for useKeyboardControls hook
 */
export interface UseKeyboardControlsReturn {
  /** Queued inputs for display */
  readonly queuedInputs: readonly QueuedInput[];
  /** Whether hints are visible */
  readonly showHints: boolean;
  /** Toggle hints visibility */
  readonly toggleHints: () => void;
}
 
/**
 * Maximum number of inputs to keep in queue
 */
const MAX_QUEUE_SIZE = 3;
 
/**
 * Time to keep inputs in queue (milliseconds)
 */
const QUEUE_RETENTION_TIME = 2000;
 
/**
 * Custom hook for handling keyboard controls with visual feedback
 * 
 * Features:
 * - Trigram stance switching (1-8 keys or custom bindings)
 * - Combat action handling (attack, block, movement)
 * - Input queue visualization
 * - Keyboard hints toggle (F1)
 * - Invalid input prevention
 * - Audio feedback integration
 * 
 * @example
 * ```typescript
 * const { queuedInputs, showHints, toggleHints } = useKeyboardControls({
 *   onStanceChange: (stance) => handleStanceChange(stance),
 *   onAction: (action) => handleAction(action),
 *   enabled: !isPaused,
 *   currentStance: player.stance,
 *   playSFX: audio.playSFX,
 * });
 * ```
 * 
 * @public
 * @korean 키보드컨트롤사용
 */
export function useKeyboardControls({
  onStanceChange,
  onAction,
  enabled = true,
  currentStance = 0,
  onToggleHints,
  playSFX,
  currentAnimationState,
}: UseKeyboardControlsProps): UseKeyboardControlsReturn {
  const [queuedInputs, setQueuedInputs] = useState<readonly QueuedInput[]>([]);
  const [showHints, setShowHints] = useState(false);
  const controlMapperRef = useRef<ControlMapper>(new ControlMapper());
  const lastStanceChangeRef = useRef<number>(0);
  
  // Track currently pressed keys for diagonal step detection
  const pressedKeysRef = useRef<Set<string>>(new Set());
 
  /**
   * Toggle hints visibility
   */
  const toggleHints = useCallback(() => {
    setShowHints((prev) => {
      const newState = !prev;
      if (onToggleHints) {
        onToggleHints();
      }
      // Play UI sound
      if (playSFX) {
        playSFX("menu_select");
      }
      return newState;
    });
  }, [onToggleHints, playSFX]);
  
  /**
   * Detect diagonal step direction from pressed keys
   * Returns step action for diagonal or null if not diagonal
   * 
   * @korean 대각선발걸음감지
   */
  const getDiagonalStepAction = useCallback((): string | null => {
    const keys = pressedKeysRef.current;
    const mapper = controlMapperRef.current;
    
    // Check for forward diagonals
    if (keys.has(mapper.getBindings().movement.up.toLowerCase())) {
      if (keys.has(mapper.getBindings().movement.left.toLowerCase())) {
        return "step_forward_left"; // 전좌측보법
      }
      if (keys.has(mapper.getBindings().movement.right.toLowerCase())) {
        return "step_forward_right"; // 전우측보법
      }
    }
    
    // Check for backward diagonals
    if (keys.has(mapper.getBindings().movement.down.toLowerCase())) {
      if (keys.has(mapper.getBindings().movement.left.toLowerCase())) {
        return "step_back_left"; // 후좌측보법
      }
      if (keys.has(mapper.getBindings().movement.right.toLowerCase())) {
        return "step_back_right"; // 후우측보법
      }
    }
    
    return null;
  }, []);
 
  /**
   * Add input to queue
   */
  const addToQueue = useCallback((action: string, key: string) => {
    const newInput: QueuedInput = {
      action,
      key,
      timestamp: Date.now(),
    };
 
    setQueuedInputs((prev) => {
      const updated = [newInput, ...prev].slice(0, MAX_QUEUE_SIZE);
      return updated;
    });
  }, []);
 
  /**
   * Clean up old queued inputs
   * Single interval for component lifetime to avoid recreating on every input
   */
  useEffect(() => {
    const interval = setInterval(() => {
      const now = Date.now();
      setQueuedInputs((prev) => {
        if (prev.length === 0) return prev;
        return prev.filter((input) => now - input.timestamp < QUEUE_RETENTION_TIME);
      });
    }, 500);
 
    return () => clearInterval(interval);
  }, []); // Empty deps - single interval for component lifetime
 
  /**
   * Handle keyboard input
   */
  useEffect(() => {
    if (!enabled) return;
 
    // Copy ref value for cleanup
    const pressedKeys = pressedKeysRef.current;
 
    const handleKeyDown = (e: KeyboardEvent) => {
      const mapper = controlMapperRef.current;
      
      // Track pressed keys for diagonal detection
      pressedKeysRef.current.add(e.key.toLowerCase());
 
      // F1: Toggle hints (prevent default browser help)
      if (e.key === "F1") {
        e.preventDefault();
        toggleHints();
        return;
      }
 
      // Escape: Close hints if open
      if (e.key === "Escape" && showHints) {
        e.preventDefault();
        setShowHints(false);
        return;
      }
 
      // Recovery input detection (기상 입력 감지)
      // When player is in ground state, any button triggers recovery options
      const isGrounded = currentAnimationState?.startsWith("ground_");
      
      Iif (isGrounded) {
        // Space: Quick/default recovery
        if (e.key === " ") {
          e.preventDefault();
          onAction("recovery_quick");
          addToQueue("기상 (Quick Recovery)", "Space");
          if (playSFX) playSFX("stance_change");
          return;
        }
        
        // R or Enter: Roll recovery (회전기상) - fast but costs stamina
        if (e.key.toLowerCase() === "r" || e.key === "Enter") {
          e.preventDefault();
          onAction("recovery_roll");
          addToQueue("회전기상 (Roll Recovery)", e.key);
          if (playSFX) playSFX("stance_change");
          return;
        }
        
        // Shift: Defensive getup (방어기상) - slow but protected
        if (e.shiftKey) {
          e.preventDefault();
          onAction("recovery_defensive");
          addToQueue("방어기상 (Defensive Getup)", "Shift");
          if (playSFX) playSFX("stance_change");
          return;
        }
        
        // If grounded, don't process other inputs (can't attack/move while down)
        return;
      }
 
      // Check for stance change (1-8 or custom bindings)
      const stanceIndex = mapper.getStanceForKey(e.key);
      if (stanceIndex !== null) {
        e.preventDefault();
 
        // Prevent switching to the same stance
        if (stanceIndex === currentStance) {
          // Invalid input feedback (shake animation trigger)
          addToQueue(`Stance ${stanceIndex + 1} (already active)`, e.key);
 
          // Play error sound
          Eif (playSFX) {
            playSFX("menu_error");
          }
          return;
        }
 
        // Throttle stance changes (minimum 8 frames at 60fps = 133ms)
        const now = Date.now();
        if (now - lastStanceChangeRef.current < 133) {
          return;
        }
        lastStanceChangeRef.current = now;
 
        // Execute stance change
        onStanceChange(stanceIndex);
        addToQueue(`Stance ${stanceIndex + 1}`, e.key);
 
        // Play stance change sound
        Eif (playSFX) {
          playSFX("stance_change");
        }
        return;
      }
 
      // Handle other actions
      const action = mapper.getActionForKey(e.key);
      Eif (action) {
        e.preventDefault();
 
        switch (action) {
          case "attack":
            onAction("attack");
            addToQueue("Attack", e.key);
            Eif (playSFX) playSFX("attack_light");
            break;
 
          case "block":
            onAction("block");
            addToQueue("Block", e.key);
            Eif (playSFX) playSFX("block");
            break;
 
          case "move_up":
          case "move_down":
          case "move_left":
          case "move_right":
            // Check for Alt+A/D modifier for slide left/right (MUST be checked first)
            Iif (e.altKey) {
              // Alt modifier for slide left/right footwork patterns
              let slideFootwork: string | null = null;
              
              if (action === "move_left") {
                // Alt+A: Slide left (미끄럼보 좌)
                slideFootwork = "footwork_slide_left";
              } else if (action === "move_right") {
                // Alt+D: Slide right (미끄럼보 우)
                slideFootwork = "footwork_slide_right";
              }
              
              if (slideFootwork) {
                onAction(slideFootwork);
                addToQueue(
                  FOOTWORK_DISPLAY_TERMS[slideFootwork] ?? "Slide Footwork",
                  `Alt+${e.key}`
                );
                if (playSFX) playSFX("footstep");
              }
            } else if (e.shiftKey && e.ctrlKey) {
              // Shift+Ctrl modifier for advanced footwork patterns
              let advancedFootwork: string | null = null;
              
              if (action === "move_left") {
                // Shift+Ctrl+A: Pivot left (축족회전 좌)
                advancedFootwork = "footwork_pivot_left";
              } else if (action === "move_right") {
                // Shift+Ctrl+D: Pivot right (축족회전 우)
                advancedFootwork = "footwork_pivot_right";
              E} else if (action === "move_up" || action === "move_down") {
                // Shift+Ctrl+W or Shift+Ctrl+S: Shuffle step (섞음보)
                advancedFootwork = "footwork_shuffle";
              }
              
              Eif (advancedFootwork) {
                onAction(advancedFootwork);
                addToQueue(
                  FOOTWORK_DISPLAY_TERMS[advancedFootwork] ?? "Advanced Footwork",
                  `Shift+Ctrl+${e.key}`
                );
                Iif (playSFX) playSFX("footstep");
              }
            } else if (e.ctrlKey) {
              // Footwork patterns with Ctrl+WASD
              let footworkAction: string | null = null;
              
              if (action === "move_left") {
                // Ctrl+A: Circular step left (원형보)
                footworkAction = "footwork_circular_left";
              } else if (action === "move_right") {
                // Ctrl+D: Circular step right (원형보)
                footworkAction = "footwork_circular_right";
              } else if (action === "move_up") {
                // Ctrl+W: Slide forward (미끄럼보)
                footworkAction = "footwork_slide_forward";
              E} else if (action === "move_down") {
                // Ctrl+S: Slide back (미끄럼보)
                footworkAction = "footwork_slide_back";
              }
              
              Eif (footworkAction) {
                onAction(footworkAction);
                addToQueue(
                  FOOTWORK_DISPLAY_TERMS[footworkAction] ?? "Footwork",
                  `Ctrl+${e.key}`
                );
                Iif (playSFX) playSFX("footstep");
              }
            I} else if (e.shiftKey) {
              // Check if Shift is held for tactical step instead of walk
              // Check for diagonal step first
              const diagonalStep = getDiagonalStepAction();
              
              if (diagonalStep) {
                // Diagonal tactical step
                onAction(diagonalStep);
                
                addToQueue(DIAGONAL_KOREAN_TERMS[diagonalStep] ?? "Diagonal Step", `Shift+${e.key}`);
                
                if (playSFX) playSFX("footstep");
              } else {
                // Cardinal direction tactical step
                // Map move_up/move_down to step_forward/step_back to match AnimationState
                const stepDirection = STEP_DIRECTION_MAP[action];
                onAction(stepDirection);
                
                addToQueue(STEP_KOREAN_TERMS[stepDirection] ?? "Step", `Shift+${e.key}`);
                
                if (playSFX) playSFX("footstep");
              }
            } else {
              // Regular movement
              onAction(action);
              addToQueue(action, e.key);
            }
            break;
 
          case "stance_side_switch":
            // H key: Switch front foot (stance side switch)
            onAction("stance_side_switch");
            addToQueue("발 바꿈 (Switch Stance Side)", e.key);
            Iif (playSFX) playSFX("stance_change");
            break;
 
          case "vital_points_overlay":
            // Vital points overlay toggle
            onAction("vital_points_overlay");
            addToQueue("Vital Points", e.key);
            Eif (playSFX) playSFX("menu_select");
            break;
 
          case "pause":
            // Pause menu toggle
            onAction("pause");
            addToQueue("Pause", e.key);
            Eif (playSFX) playSFX("menu_select");
            break;
        }
      }
    };
    
    const handleKeyUp = (e: KeyboardEvent) => {
      // Remove key from pressed keys set
      pressedKeysRef.current.delete(e.key.toLowerCase());
    };
 
    window.addEventListener("keydown", handleKeyDown);
    window.addEventListener("keyup", handleKeyUp);
    
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
      window.removeEventListener("keyup", handleKeyUp);
      // Clear pressed keys on cleanup using copied ref value
      pressedKeys.clear();
    };
  }, [
    enabled,
    currentStance,
    onStanceChange,
    onAction,
    addToQueue,
    toggleHints,
    getDiagonalStepAction,
    showHints,
    playSFX,
    currentAnimationState,
  ]);
 
  return {
    queuedInputs,
    showHints,
    toggleHints,
  };
}