All files / hooks useTechniqueSelection.ts

89.77% Statements 79/88
76.47% Branches 39/51
100% Functions 20/20
95% Lines 76/80

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                                                                                                                                                                                                        92x     92x 54x                 92x     92x         92x     92x 60x   55x       55x     5x 5x 63x 63x 63x 63x 31x       31x       5x 5x 5x 5x 5x           92x   10x 3x             92x   2x 2x   2x           92x   2x               92x     9x 1x               8x 1x               7x 1x               6x                     6x               92x   2x 2x   2x 2x 2x           92x   6x   6x 6x 6x     6x 6x 1x 1x       5x 5x           5x     5x                       92x 92x   49x   1x             1x     1x     1x 1x       1x                         1x 1x 1x 1x       49x 49x     92x                            
/**
 * Custom hook for managing technique selection and execution.
 *
 * **Korean**: 기술 선택 관리 (Technique Selection Management)
 *
 * Handles technique selection state, keyboard shortcuts, cooldown tracking,
 * and validation of technique execution based on player resources and stance.
 *
 * @module hooks/useTechniqueSelection
 * @category Combat Hooks
 * @korean 기술선택훅
 */
 
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { getTechniquesForStanceAndArchetype } from "../data/techniques";
import { PlayerState } from "../systems/player";
import {
  Technique,
  TechniqueCooldown,
  TechniqueKey,
  TechniqueValidation,
} from "../types";
 
/**
 * Configuration for technique selection hook.
 */
export interface UseTechniqueSelectionConfig {
  /** Player state with resources and stance */
  readonly player: PlayerState;
 
  /** Whether technique selection is enabled */
  readonly enabled?: boolean;
 
  /** Callback when technique is selected */
  readonly onTechniqueSelected?: (technique: Technique) => void;
 
  /** Callback when technique execution is attempted */
  readonly onTechniqueExecute?: (technique: Technique) => void;
}
 
/**
 * Technique selection state and actions.
 */
export interface UseTechniqueSelectionResult {
  /** Available techniques for player archetype */
  readonly availableTechniques: readonly Technique[];
 
  /** Currently selected technique index */
  readonly selectedIndex: number;
 
  /** Active cooldowns for techniques */
  readonly activeCooldowns: readonly TechniqueCooldown[];
 
  /** Select technique by index */
  readonly selectTechnique: (index: number) => void;
 
  /** Execute currently selected technique */
  readonly executeTechnique: (indexOverride?: number) => void;
 
  /** Check if technique can be executed */
  readonly validateTechnique: (technique: Technique) => TechniqueValidation;
 
  /** Check if technique is on cooldown */
  readonly isOnCooldown: (techniqueId: string) => boolean;
 
  /** Get remaining cooldown time in ms */
  readonly getRemainingCooldown: (techniqueId: string) => number;
 
  /** Check if player has sufficient resources */
  readonly hasResources: (technique: Technique) => boolean;
}
 
/**
 * Custom hook for managing technique selection and execution.
 *
 * @param config - Configuration options
 * @returns Technique selection state and actions
 *
 * @example
 * ```typescript
 * const techniqueSelection = useTechniqueSelection({
 *   player: playerState,
 *   enabled: !isPaused && combatActive,
 *   onTechniqueExecute: (technique) => {
 *     // Execute technique logic
 *     executeCombatTechnique(playerState, opponent, technique);
 *   }
 * });
 * ```
 *
 * @public
 */
export function useTechniqueSelection(
  config: UseTechniqueSelectionConfig
): UseTechniqueSelectionResult {
  const {
    player,
    enabled = true,
    onTechniqueSelected,
    onTechniqueExecute,
  } = config;
 
  // Get available techniques based on player's current stance and archetype
  const availableTechniques = useMemo(
    () =>
      getTechniquesForStanceAndArchetype(
        player.currentStance,
        player.archetype
      ),
    [player.currentStance, player.archetype]
  );
 
  // Selected technique state
  const [selectedIndex, setSelectedIndex] = useState(0);
 
  // Cooldown tracking
  const [activeCooldowns, setActiveCooldowns] = useState<TechniqueCooldown[]>(
    []
  );
 
  // Ref for cleanup
  const cooldownUpdateIntervalRef = useRef<NodeJS.Timeout | null>(null);
 
  // Update cooldowns every 100ms
  useEffect(() => {
    if (activeCooldowns.length === 0) {
      // Clear any existing interval when no cooldowns
      Iif (cooldownUpdateIntervalRef.current) {
        clearInterval(cooldownUpdateIntervalRef.current);
        cooldownUpdateIntervalRef.current = null;
      }
      return;
    }
 
    let isMounted = true;
    cooldownUpdateIntervalRef.current = setInterval(() => {
      Iif (!isMounted) return;
      const now = Date.now();
      setActiveCooldowns((prev) => {
        return prev
          .map((cd) => ({
            ...cd,
            remaining: Math.max(0, cd.startTime + cd.duration - now),
          }))
          .filter((cd) => cd.remaining > 0);
      });
    }, 100);
 
    return () => {
      isMounted = false;
      Eif (cooldownUpdateIntervalRef.current) {
        clearInterval(cooldownUpdateIntervalRef.current);
        cooldownUpdateIntervalRef.current = null;
      }
    };
  }, [activeCooldowns.length]);
 
  // Check if technique is on cooldown
  const isOnCooldown = useCallback(
    (techniqueId: string): boolean => {
      return activeCooldowns.some(
        (cd) => cd.techniqueId === techniqueId && cd.remaining > 0
      );
    },
    [activeCooldowns]
  );
 
  // Get remaining cooldown time
  const getRemainingCooldown = useCallback(
    (techniqueId: string): number => {
      const cooldown = activeCooldowns.find(
        (cd) => cd.techniqueId === techniqueId
      );
      return cooldown?.remaining ?? 0;
    },
    [activeCooldowns]
  );
 
  // Check if player has sufficient resources
  const hasResources = useCallback(
    (technique: Technique): boolean => {
      return (
        player.stamina >= technique.staminaCost && player.ki >= technique.kiCost
      );
    },
    [player.stamina, player.ki]
  );
 
  // Validate technique execution
  const validateTechnique = useCallback(
    (technique: Technique): TechniqueValidation => {
      // Check stamina
      if (player.stamina < technique.staminaCost) {
        return {
          canExecute: false,
          reason: "Insufficient stamina",
          insufficientStamina: true,
        };
      }
 
      // Check Ki
      if (player.ki < technique.kiCost) {
        return {
          canExecute: false,
          reason: "Insufficient Ki",
          insufficientKi: true,
        };
      }
 
      // Check cooldown
      if (isOnCooldown(technique.id)) {
        return {
          canExecute: false,
          reason: "Technique on cooldown",
          onCooldown: true,
        };
      }
 
      // Check required stance
      Iif (
        technique.requiredStance &&
        player.currentStance !== technique.requiredStance
      ) {
        return {
          canExecute: false,
          reason: `Requires ${technique.requiredStance} stance`,
          wrongStance: true,
        };
      }
 
      return {
        canExecute: true,
      };
    },
    [player.stamina, player.ki, player.currentStance, isOnCooldown]
  );
 
  // Select technique by index
  const selectTechnique = useCallback(
    (index: number) => {
      Iif (index < 0 || index >= availableTechniques.length) return;
      Iif (!enabled) return;
 
      setSelectedIndex(index);
      const technique = availableTechniques[index];
      onTechniqueSelected?.(technique);
    },
    [availableTechniques, enabled, onTechniqueSelected]
  );
 
  // Execute currently selected technique
  const executeTechnique = useCallback(
    (indexOverride?: number) => {
      Iif (!enabled) return;
 
      const index = indexOverride ?? selectedIndex;
      const technique = availableTechniques[index];
      Iif (!technique) return;
 
      // Validate technique execution
      const validation = validateTechnique(technique);
      if (!validation.canExecute) {
        console.warn(`Cannot execute technique: ${validation.reason}`);
        return;
      }
 
      // Start cooldown
      const now = Date.now();
      const cooldown: TechniqueCooldown = {
        techniqueId: technique.id,
        startTime: now,
        duration: technique.cooldown,
        remaining: technique.cooldown,
      };
      setActiveCooldowns((prev) => [...prev, cooldown]);
 
      // Execute technique
      onTechniqueExecute?.(technique);
    },
    [
      enabled,
      availableTechniques,
      selectedIndex,
      validateTechnique,
      onTechniqueExecute,
    ]
  );
 
  // Keyboard shortcut handler
  useEffect(() => {
    if (!enabled) return;
 
    const handleKeyPress = (event: KeyboardEvent) => {
      // Don't capture if user is typing in an input field
      Iif (
        event.target instanceof HTMLInputElement ||
        event.target instanceof HTMLTextAreaElement
      ) {
        return;
      }
 
      const key = event.key.toUpperCase() as TechniqueKey;
 
      // Technique keys - top row Q through P (10 keys)
      const techniqueKeys = ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"];
 
      // Prevent default for all technique keys during combat
      Eif (techniqueKeys.includes(key)) {
        event.preventDefault();
      }
 
      // Map keys to technique indices
      const keyMap: Record<TechniqueKey, number> = {
        Q: 0,
        W: 1,
        E: 2,
        R: 3,
        T: 4,
        Y: 5,
        U: 6,
        I: 7,
        O: 8,
        P: 9,
      };
 
      const index = keyMap[key];
      Eif (index !== undefined && index < availableTechniques.length) {
        selectTechnique(index);
        executeTechnique(index);
      }
    };
 
    window.addEventListener("keydown", handleKeyPress);
    return () => window.removeEventListener("keydown", handleKeyPress);
  }, [enabled, availableTechniques, selectTechnique, executeTechnique]);
 
  return {
    availableTechniques,
    selectedIndex,
    activeCooldowns,
    selectTechnique,
    executeTechnique,
    validateTechnique,
    isOnCooldown,
    getRemainingCooldown,
    hasResources,
  };
}
 
export default useTechniqueSelection;