All files / components/shared/three/effects ActionFeedback.tsx

72.6% Statements 53/73
67.56% Branches 25/37
80% Functions 8/10
72.85% Lines 51/70

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                                                    3x   3x                                                                       13x   2x   5x   3x   1x   1x   1x                   13x   2x   5x   3x   1x   1x   1x                               3x           13x 13x           13x 13x     13x 13x     13x 13x 13x 13x     13x             13x   13x 13x 13x 13x 13x   13x                                                                                             3x             72x   72x     13x                                                       3x             7x 7x   7x 7x     7x                                                     7x   7x 7x 7x 7x   7x                                                                                                                                
/**
 * ActionFeedback - Combat action feedback display component
 *
 * Displays action indicators like "Perfect!", "Critical!", "Blocked", "Dodged",
 * and technique names with Korean-English bilingual text.
 *
 * Uses Html overlay from @react-three/drei for rendering within 3D scenes.
 *
 * @module components/shared/three/effects/ActionFeedback
 * @category Shared Effects
 * @korean 액션피드백
 */
 
import { Html } from "@react-three/drei";
import { useFrame } from "@react-three/fiber";
import React, { useMemo, useRef, useState } from "react";
import {
  ActionFeedback as ActionFeedbackData,
  ActionFeedbackType,
} from "../../../../hooks/useActionFeedback";
import { FONT_FAMILY, KOREAN_COLORS } from "../../../../types/constants";
import { DEFAULT_PHYSICS_ARENA_BOUNDS, type PhysicsArenaBounds } from "../../../../types/PhysicsTypes";
import { hexColorToCSS, hexToRgbaString } from "../../../../utils/colorUtils";
 
// Animation phase thresholds (as percentage of total duration)
/** Fade in completes at 20% of total duration */
const FADE_IN_THRESHOLD = 0.2;
/** Fade out begins at 80% of total duration */
const FADE_OUT_THRESHOLD = 0.8;
 
/**
 * Props for the ActionFeedback component
 */
export interface ActionFeedbackProps {
  /** Array of action feedbacks to display */
  readonly feedbacks: readonly ActionFeedbackData[];
  /** Whether to use mobile-optimized sizing */
  readonly isMobile?: boolean;
  /** Arena bounds for 3D positioning (physics-first with meter dimensions) */
  readonly arenaBounds?: PhysicsArenaBounds;
  /** Duration of animation in ms (default: 1200) */
  readonly animationDuration?: number;
}
 
/**
 * Props for technique name display
 */
export interface TechniqueNameProps {
  /** Korean technique name */
  readonly korean: string;
  /** English technique name */
  readonly english: string;
  /** Whether to use mobile-optimized sizing */
  readonly isMobile?: boolean;
  /** Animation duration in ms */
  readonly duration?: number;
  /** Callback when animation completes */
  readonly onComplete?: () => void;
}
 
/**
 * Get color based on feedback type
 */
function getFeedbackColor(type: ActionFeedbackType): string {
  switch (type) {
    case "perfect":
      return hexColorToCSS(KOREAN_COLORS.ACCENT_GOLD);
    case "critical":
      return hexColorToCSS(KOREAN_COLORS.ACCENT_RED);
    case "blocked":
      return hexColorToCSS(KOREAN_COLORS.ACCENT_CYAN);
    case "dodged":
      return hexColorToCSS(KOREAN_COLORS.ACCENT_GREEN);
    case "technique":
      return hexColorToCSS(KOREAN_COLORS.SECONDARY_MAGENTA);
    case "combo_milestone":
      return hexColorToCSS(KOREAN_COLORS.ACCENT_GOLD);
    default:
      return hexColorToCSS(KOREAN_COLORS.TEXT_PRIMARY);
  }
}
 
/**
 * Get glow color based on feedback type
 */
function getGlowColor(type: ActionFeedbackType): string {
  switch (type) {
    case "perfect":
      return hexToRgbaString(KOREAN_COLORS.ACCENT_GOLD, 0.8);
    case "critical":
      return hexToRgbaString(KOREAN_COLORS.ACCENT_RED, 0.8);
    case "blocked":
      return hexToRgbaString(KOREAN_COLORS.ACCENT_CYAN, 0.6);
    case "dodged":
      return hexToRgbaString(KOREAN_COLORS.ACCENT_GREEN, 0.6);
    case "technique":
      return hexToRgbaString(KOREAN_COLORS.SECONDARY_MAGENTA, 0.8);
    case "combo_milestone":
      return hexToRgbaString(KOREAN_COLORS.ACCENT_GOLD, 0.8);
    default:
      return hexToRgbaString(KOREAN_COLORS.TEXT_PRIMARY, 0.4);
  }
}
 
/**
 * Individual action feedback display
 */
interface SingleFeedbackProps {
  readonly feedback: ActionFeedbackData;
  readonly isMobile: boolean;
  readonly arenaBounds: PhysicsArenaBounds;
  readonly animationDuration: number;
}
 
const SingleFeedback: React.FC<SingleFeedbackProps> = ({
  feedback,
  isMobile,
  arenaBounds,
  animationDuration,
}) => {
  const [progress, setProgress] = useState(0);
  const startTimeRef = useRef(feedback.timestamp);
 
  // Calculate 3D position from meter-based coordinates (physics-first architecture)
  // Position is in meters relative to arena center (0, 0)
  // Player models use meter coordinates directly: position={[playerPos.x, 0, playerPos.y]}
  // So we use meter coordinates directly too for alignment
  const halfWidth = arenaBounds.worldWidthMeters / 2;
  const halfDepth = arenaBounds.worldDepthMeters / 2;
  
  // Clamp position to arena boundaries in meters
  const clampedX = Math.min(halfWidth, Math.max(-halfWidth, feedback.position.x));
  const clampedZ = Math.min(halfDepth, Math.max(-halfDepth, feedback.position.y));
  
  // Use clamped meter coordinates directly in 3D space (no remapping)
  const x = clampedX; // Meter position X
  const y = 2.5 + progress * 1.5; // Float upward
  const z = clampedZ; // Meter position Z (depth)
  const position3D: [number, number, number] = [x, y, z];
 
  // Update progress using useFrame
  useFrame(() => {
    const elapsed = Date.now() - startTimeRef.current;
    const newProgress = Math.min(elapsed / animationDuration, 1);
    setProgress(newProgress);
  });
 
  // Don't render if expired
  Iif (progress >= 1) return null;
 
  const opacity = 1 - progress;
  const scale = 1 + (progress < 0.2 ? progress * 2 : (1 - progress) * 0.5);
  const fontSize = isMobile ? 18 : 24;
  const color = getFeedbackColor(feedback.type);
  const glowColor = getGlowColor(feedback.type);
 
  return (
    <Html
      position={position3D}
      center
      distanceFactor={10}
      style={{ pointerEvents: "none" }}
    >
      <div
        data-testid={`action-feedback-${feedback.id}`}
        style={{
          fontSize: `${fontSize}px`,
          fontWeight: "bold",
          fontFamily: FONT_FAMILY.KOREAN,
          color,
          opacity,
          transform: `scale(${scale})`,
          textShadow: `
            0 0 10px ${glowColor},
            0 0 20px ${glowColor},
            2px 2px 4px rgba(0, 0, 0, 0.9)
          `,
          whiteSpace: "nowrap",
          userSelect: "none",
          textAlign: "center",
        }}
      >
        {feedback.textKorean} | {feedback.text}
      </div>
    </Html>
  );
};
 
/**
 * ActionFeedback Component
 *
 * Renders multiple action feedback indicators in the 3D scene.
 * Each indicator floats upward and fades out over time.
 *
 * @example
 * ```tsx
 * <ActionFeedback
 *   feedbacks={actionFeedbacks}
 *   isMobile={isMobile}
 *   arenaBounds={arenaBounds}
 * />
 * ```
 */
export const ActionFeedback: React.FC<ActionFeedbackProps> = ({
  feedbacks,
  isMobile = false,
  arenaBounds = DEFAULT_PHYSICS_ARENA_BOUNDS,
  animationDuration = 1200,
}) => {
  // Derive visible feedbacks from props - no need for state sync
  const visibleFeedbacks = useMemo(() => [...feedbacks], [feedbacks]);
 
  return (
    <group data-testid="action-feedback-container">
      {visibleFeedbacks.map((feedback) => (
        <SingleFeedback
          key={feedback.id}
          feedback={feedback}
          isMobile={isMobile}
          arenaBounds={arenaBounds}
          animationDuration={animationDuration}
        />
      ))}
    </group>
  );
};
 
/**
 * TechniqueName Component
 *
 * Displays the current technique name in Korean and English.
 * Appears at the center of the screen with a dramatic animation.
 *
 * @example
 * ```tsx
 * <TechniqueName
 *   korean="천둥벽력"
 *   english="Thunder Strike"
 *   isMobile={isMobile}
 *   duration={2000}
 * />
 * ```
 */
export const TechniqueName: React.FC<TechniqueNameProps> = ({
  korean,
  english,
  isMobile = false,
  duration = 2000,
  onComplete,
}) => {
  const [opacity, setOpacity] = useState(0);
  const [scale, setScale] = useState(0.5);
  // Use useState lazy initializer for Date.now() to avoid impure function during render
  const [startTime] = useState(() => Date.now());
  const startTimeRef = useRef(startTime);
 
  // Animation phases: fade in (0-FADE_IN_THRESHOLD), hold (FADE_IN_THRESHOLD-FADE_OUT_THRESHOLD), fade out (FADE_OUT_THRESHOLD-1)
  useFrame(() => {
    const elapsed = Date.now() - startTimeRef.current;
    const progress = Math.min(elapsed / duration, 1);
 
    if (progress < FADE_IN_THRESHOLD) {
      // Fade in phase
      const fadeInProgress = progress / FADE_IN_THRESHOLD;
      setOpacity(fadeInProgress);
      setScale(0.5 + fadeInProgress * 0.5);
    } else if (progress < FADE_OUT_THRESHOLD) {
      // Hold phase
      setOpacity(1);
      setScale(1);
    } else {
      // Fade out phase
      const fadeOutProgress =
        (progress - FADE_OUT_THRESHOLD) / (1 - FADE_OUT_THRESHOLD);
      setOpacity(1 - fadeOutProgress);
      setScale(1 + fadeOutProgress * 0.2);
    }
 
    if (progress >= 1 && onComplete) {
      onComplete();
    }
  });
 
  // Position at center of scene, slightly below top
  const position3D: [number, number, number] = [0, 3.5, 0];
 
  const mainFontSize = isMobile ? 28 : 42;
  const subFontSize = isMobile ? 16 : 24;
  const color = hexColorToCSS(KOREAN_COLORS.SECONDARY_MAGENTA);
  const glowColor = hexToRgbaString(KOREAN_COLORS.SECONDARY_MAGENTA, 0.8);
 
  return (
    <Html
      position={position3D}
      center
      distanceFactor={10}
      style={{ pointerEvents: "none" }}
    >
      <div
        data-testid="technique-name"
        style={{
          textAlign: "center",
          opacity,
          transform: `scale(${scale})`,
          transition: "transform 0.1s ease-out",
        }}
      >
        {/* Korean name */}
        <div
          style={{
            fontSize: `${mainFontSize}px`,
            fontWeight: "bold",
            fontFamily: FONT_FAMILY.KOREAN,
            color,
            textShadow: `
              0 0 15px ${glowColor},
              0 0 30px ${glowColor},
              3px 3px 6px rgba(0, 0, 0, 0.9)
            `,
            letterSpacing: "4px",
          }}
        >
          {korean}
        </div>
 
        {/* Divider */}
        <div
          style={{
            width: "60px",
            height: "2px",
            background: `linear-gradient(90deg, transparent, ${color}, transparent)`,
            margin: "8px auto",
          }}
        />
 
        {/* English name */}
        <div
          style={{
            fontSize: `${subFontSize}px`,
            fontWeight: "bold",
            fontFamily: FONT_FAMILY.KOREAN,
            color: hexColorToCSS(KOREAN_COLORS.TEXT_SECONDARY),
            textShadow: "2px 2px 4px rgba(0, 0, 0, 0.8)",
            letterSpacing: "2px",
            textTransform: "uppercase",
          }}
        >
          {english}
        </div>
      </div>
    </Html>
  );
};
 
export default ActionFeedback;