All files / hooks usePlayerAnimation.ts

100% Statements 37/37
91.66% Branches 11/12
100% Functions 10/10
100% Lines 34/34

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                                                                                                                                                                                                                                                                                                            177x     177x     177x 92x         177x 92x   92x 1x   92x         177x 177x     177x   50x 50x 50x     50x 50x 50x 50x     50x         177x   16x 16x 15x 15x 15x   16x         177x 1x 1x 1x 1x       177x 111x                    
/**
 * usePlayerAnimation - React hook for player animation state
 * 
 * Provides a React interface to the PlayerAnimationStateMachine
 * with automatic cleanup and event handling.
 * 
 * @module hooks/usePlayerAnimation
 * @category Hooks
 * @korean 플레이어애니메이션훅
 */
 
import { useCallback, useMemo, useRef, useState } from "react";
import {
  AnimationEvents,
  AnimationState,
  DEFAULT_ANIMATION_CONFIGS,
  PlayerAnimationStateMachine,
} from "../systems/animation";
import type { AnimationConfig, AnimationUpdateResult } from "../systems/animation/types";
 
/**
 * Options for usePlayerAnimation hook
 * 
 * @korean 플레이어애니메이션훅옵션
 */
export interface UsePlayerAnimationOptions {
  /**
   * Custom animation configurations
   * If not provided, uses DEFAULT_ANIMATION_CONFIGS
   * 
   * @korean 커스텀애니메이션설정
   */
  readonly customConfigs?: Map<AnimationState, AnimationConfig>;
 
  /**
   * Animation event callbacks
   * 
   * **IMPORTANT**: The events object should be stable (memoized) to prevent
   * unnecessary re-initialization of the animation system. Changes to event
   * callbacks after the hook is initialized will NOT be reflected in the
   * animation system. Use `useMemo` or define events outside the component
   * to ensure stability.
   * 
   * @korean 이벤트콜백
   */
  readonly events?: AnimationEvents;
 
  /**
   * Initial animation state (defaults to "idle")
   * 
   * @korean 초기상태
   */
  readonly initialState?: AnimationState;
}
 
/**
 * Return type for usePlayerAnimation hook
 * 
 * @korean 플레이어애니메이션훅반환타입
 */
export interface UsePlayerAnimationReturn {
  /**
   * Current animation state
   * 
   * @korean 현재상태
   */
  readonly currentState: AnimationState;
 
  /**
   * Current frame index
   * 
   * @korean 현재프레임
   */
  readonly currentFrame: number;
 
  /**
   * Update animation state (call in useFrame)
   * 
   * @param deltaTime - Time elapsed since last update in seconds
   * @returns Animation update result
   * 
   * @korean 업데이트
   */
  readonly update: (deltaTime: number) => AnimationUpdateResult;
 
  /**
   * Transition to a new animation state
   * 
   * @param newState - Target animation state
   * @returns Whether transition was successful
   * 
   * @korean 상태전환
   */
  readonly transitionTo: (newState: AnimationState) => boolean;
 
  /**
   * Reset animation to idle state
   * 
   * @korean 초기화
   */
  readonly reset: () => void;
}
 
/**
 * React hook for player animation state management
 * 
 * Provides frame-accurate animation control with priority system
 * and event callbacks. Integrates seamlessly with useFrame for
 * 60fps updates.
 * 
 * @param options - Animation options
 * @returns Animation control interface
 * 
 * @example
 * ```typescript
 * // Basic usage
 * const { currentState, currentFrame, update, transitionTo } = usePlayerAnimation({
 *   events: {
 *     onAnimationStart: (state) => console.log(`Started ${state}`),
 *     onAnimationComplete: (state) => console.log(`Completed ${state}`),
 *     onFrame: (frame, state) => {
 *       if (state === "attack" && frame === 6) {
 *         // Execute attack at midpoint
 *         executeAttack();
 *       }
 *     }
 *   }
 * });
 * 
 * // In useFrame callback
 * useFrame((state, delta) => {
 *   const result = update(delta);
 *   // Update visuals based on result.state and result.frame
 * });
 * 
 * // Trigger animations
 * const handleAttackInput = () => {
 *   transitionTo("attack");
 * };
 * 
 * const handleMovement = (isMoving: boolean) => {
 *   transitionTo(isMoving ? "walk" : "idle");
 * };
 * ```
 * 
 * @korean 플레이어애니메이션훅
 */
export function usePlayerAnimation(
  options: UsePlayerAnimationOptions = {}
): UsePlayerAnimationReturn {
  const { customConfigs, events, initialState = "idle" } = options;
 
  // Force re-renders when state changes
  const [, forceUpdate] = useState(0);
 
  // Create animation configs (memoized)
  const configs = useMemo(
    () => customConfigs ?? DEFAULT_ANIMATION_CONFIGS,
    [customConfigs]
  );
 
  // Create animation state machine (persistent across renders via useMemo)
  const stateMachine = useMemo(() => {
    const machine = new PlayerAnimationStateMachine(configs, events);
    // Set initial state if not "idle"
    if (initialState !== "idle") {
      machine.transitionTo(initialState);
    }
    return machine;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // Empty deps - only create once
 
  // Track previous state to only update on actual changes
  const prevStateRef = useRef<AnimationState>(stateMachine.getCurrentState());
  const prevFrameRef = useRef<number>(stateMachine.getCurrentFrame());
 
  // Memoized callbacks with selective state updates
  const update = useCallback(
    (deltaTime: number) => {
      const result = stateMachine.update(deltaTime);
      const currentState = stateMachine.getCurrentState();
      const currentFrame = stateMachine.getCurrentFrame();
      
      // Only trigger re-render if state or frame changed
      Eif (currentState !== prevStateRef.current || currentFrame !== prevFrameRef.current) {
        prevStateRef.current = currentState;
        prevFrameRef.current = currentFrame;
        forceUpdate((n) => n + 1);
      }
      
      return result;
    },
    [stateMachine]
  );
 
  const transitionTo = useCallback(
    (newState: AnimationState) => {
      const success = stateMachine.transitionTo(newState);
      if (success) {
        prevStateRef.current = stateMachine.getCurrentState();
        prevFrameRef.current = stateMachine.getCurrentFrame();
        forceUpdate((n) => n + 1);
      }
      return success;
    },
    [stateMachine]
  );
 
  const reset = useCallback(() => {
    stateMachine.reset();
    prevStateRef.current = stateMachine.getCurrentState();
    prevFrameRef.current = stateMachine.getCurrentFrame();
    forceUpdate((n) => n + 1);
  }, [stateMachine]);
 
  // Memoize the return value to ensure stable reference unless state/frame changes
  return useMemo(
    () => ({
      currentState: prevStateRef.current,
      currentFrame: prevFrameRef.current,
      update,
      transitionTo,
      reset,
    }),
    [prevStateRef.current, prevFrameRef.current, update, transitionTo, reset]
  );
}