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

80% Statements 44/55
67.44% Branches 29/43
80% Functions 8/10
80% Lines 40/50

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                                                                                  27x   4x   3x     20x               54x   8x   6x     40x                             3x           27x 27x   27x 27x   27x 27x   27x 27x 27x 27x   27x           27x   27x 27x 27x 27x 27x 23x 20x   27x   27x                                                                                                     3x                                   3x           44x   44x     27x                               3x     30x       30x           30x                     3x      
/**
 * DamageNumbers - Floating damage number display component
 *
 * Displays floating damage numbers that animate upward and fade out.
 * Color-coded based on damage type: normal (cyan), critical (gold), vital (red).
 *
 * Uses Html overlays from @react-three/drei for rendering within 3D scenes.
 * Performance optimized with React.memo to reduce unnecessary re-renders.
 *
 * @module components/shared/three/effects/DamageNumbers
 * @category Shared Effects
 * @korean 피해숫자
 */
 
import { Html } from "@react-three/drei";
import { useFrame } from "@react-three/fiber";
import React, { useMemo, useRef, useState } from "react";
import { DamageNumber, DamageType } 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";
import { withGPUAcceleration } from "../../../../utils/performanceOptimization";
 
/**
 * Props for the DamageNumbers component
 */
export interface DamageNumbersProps {
  /** Array of damage numbers to display */
  readonly damages: readonly DamageNumber[];
  /** 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: 1500) */
  readonly animationDuration?: number;
}
 
/**
 * Get color based on damage type
 */
function getDamageColor(type: DamageType): string {
  switch (type) {
    case "critical":
      return hexColorToCSS(KOREAN_COLORS.ACCENT_GOLD);
    case "vital":
      return hexColorToCSS(KOREAN_COLORS.ACCENT_RED);
    case "normal":
    default:
      return hexColorToCSS(KOREAN_COLORS.PRIMARY_CYAN);
  }
}
 
/**
 * Get glow color based on damage type
 */
function getGlowColor(type: DamageType): string {
  switch (type) {
    case "critical":
      return hexToRgbaString(KOREAN_COLORS.ACCENT_GOLD, 0.8);
    case "vital":
      return hexToRgbaString(KOREAN_COLORS.ACCENT_RED, 0.8);
    case "normal":
    default:
      return hexToRgbaString(KOREAN_COLORS.PRIMARY_CYAN, 0.8);
  }
}
 
/**
 * Individual damage number display
 * Memoized to prevent unnecessary re-renders
 */
interface SingleDamageNumberProps {
  readonly damage: DamageNumber;
  readonly isMobile: boolean;
  readonly arenaBounds: PhysicsArenaBounds;
  readonly animationDuration: number;
}
 
const SingleDamageNumber = React.memo<SingleDamageNumberProps>(({
  damage,
  isMobile,
  arenaBounds,
  animationDuration,
}) => {
  const [progress, setProgress] = useState(0);
  const startTimeRef = useRef(damage.timestamp);
 
  const halfWidth = arenaBounds.worldWidthMeters / 2;
  const halfDepth = arenaBounds.worldDepthMeters / 2;
  
  const clampedX = Math.min(halfWidth, Math.max(-halfWidth, damage.position.x));
  const clampedZ = Math.min(halfDepth, Math.max(-halfDepth, damage.position.y));
  
  const x = clampedX; // Meter position X
  const y = 2 + progress * 2; // Float upward
  const z = clampedZ; // Meter position Z (depth)
  const position3D: [number, number, number] = [x, y, z];
 
  useFrame(() => {
    const elapsed = Date.now() - startTimeRef.current;
    const newProgress = Math.min(elapsed / animationDuration, 1);
    setProgress(newProgress);
  });
 
  Iif (progress >= 1) return null;
 
  const opacity = 1 - progress;
  const scale = 1 + progress * 0.3; // Slight scale up during animation
  const fontSize = isMobile ? 20 : 28;
  const getCriticalBonus = (): number => {
    if (damage.type === "critical") return 8;
    if (damage.type === "vital") return 4;
    return 0;
  };
  const criticalBonus = getCriticalBonus();
 
  return (
    <Html
      position={position3D}
      center
      distanceFactor={10}
      style={{ pointerEvents: "none" }}
    >
      <div
        data-testid={`damage-${damage.id}`}
        style={withGPUAcceleration({
          fontSize: `${fontSize + criticalBonus}px`,
          fontWeight: "bold",
          fontFamily: FONT_FAMILY.KOREAN,
          color: getDamageColor(damage.type),
          opacity,
          transform: `scale(${scale})`,
          textShadow: `
            0 0 10px ${getGlowColor(damage.type)},
            0 0 20px ${getGlowColor(damage.type)},
            2px 2px 4px rgba(0, 0, 0, 0.8)
          `,
          whiteSpace: "nowrap",
          userSelect: "none",
        })}
      >
        {damage.damage}
        {damage.type === "critical" && "!"}
        {damage.type === "vital" && "!!"}
      </div>
    </Html>
  );
}, (prevProps, nextProps) => {
  const prevArena = prevProps.arenaBounds;
  const nextArena = nextProps.arenaBounds;
 
  const sameArenaBounds =
    prevArena?.x === nextArena?.x &&
    prevArena?.y === nextArena?.y &&
    prevArena?.width === nextArena?.width &&
    prevArena?.height === nextArena?.height &&
    prevArena?.worldWidthMeters === nextArena?.worldWidthMeters &&
    prevArena?.worldDepthMeters === nextArena?.worldDepthMeters;
 
  return (
    prevProps.damage.id === nextProps.damage.id &&
    prevProps.isMobile === nextProps.isMobile &&
    prevProps.animationDuration === nextProps.animationDuration &&
    sameArenaBounds
  );
});
 
SingleDamageNumber.displayName = "SingleDamageNumber";
 
/**
 * DamageNumbers Component
 *
 * Renders multiple floating damage numbers in the 3D scene.
 * Each number floats upward and fades out over time.
 * Performance optimized with React.memo.
 *
 * @example
 * ```tsx
 * <DamageNumbers
 *   damages={damageNumbers}
 *   isMobile={isMobile}
 *   arenaBounds={arenaBounds}
 * />
 * ```
 */
const DamageNumbersComponent: React.FC<DamageNumbersProps> = ({
  damages,
  isMobile = false,
  arenaBounds = DEFAULT_PHYSICS_ARENA_BOUNDS,
  animationDuration = 1500,
}) => {
  const visibleDamages = useMemo(() => [...damages], [damages]);
 
  return (
    <group data-testid="damage-numbers-container">
      {visibleDamages.map((damage) => (
        <SingleDamageNumber
          key={damage.id}
          damage={damage}
          isMobile={isMobile}
          arenaBounds={arenaBounds}
          animationDuration={animationDuration}
        />
      ))}
    </group>
  );
};
 
/**
 * Memoized DamageNumbers with custom comparison
 * Only re-renders when damage array changes
 */
export const DamageNumbers = React.memo(
  DamageNumbersComponent,
  (prevProps, nextProps) => {
    Iif (prevProps.damages.length !== nextProps.damages.length) {
      return false;
    }
    
    for (let i = 0; i < prevProps.damages.length; i++) {
      if (prevProps.damages[i].id !== nextProps.damages[i].id) {
        return false;
      }
    }
    
    return (
      prevProps.isMobile === nextProps.isMobile &&
      prevProps.animationDuration === nextProps.animationDuration &&
      prevProps.arenaBounds?.x === nextProps.arenaBounds?.x &&
      prevProps.arenaBounds?.y === nextProps.arenaBounds?.y &&
      prevProps.arenaBounds?.width === nextProps.arenaBounds?.width &&
      prevProps.arenaBounds?.height === nextProps.arenaBounds?.height
    );
  }
);
 
DamageNumbers.displayName = "DamageNumbers";
 
export default DamageNumbers;