All files / components/three StanceTransitionEffect.tsx

2.43% Statements 1/41
0% Branches 0/16
0% Functions 0/8
2.7% Lines 1/37

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                                                                                                                            3x                                                                                                                                                                                                                                                                                                                                                  
/**
 * StanceTransitionEffect - Smooth visual transition between trigram stances
 *
 * Manages the visual transition when a player changes stance, providing:
 * - 0.5s smooth color fade between old and new stance colors
 * - Expanding energy ring effect
 * - Bilingual stance name display (Korean + English) for 1s
 * - Audio synchronization for stance change SFX
 *
 * @module components/three/StanceTransitionEffect
 * @category 3D Components
 * @korean 자세전환효과
 */
 
import { Html } from "@react-three/drei";
import { useFrame } from "@react-three/fiber";
import React, { useEffect, useMemo, useRef, useState } from "react";
import * as THREE from "three";
import { TrigramStance } from "../../types/common";
import { FONT_FAMILY } from "../../types/constants";
import { colorUtils } from "../../types/constants/colors";
import { getStanceColor, getStanceNames } from "../../utils/stanceHelpers";
 
/**
 * Props for StanceTransitionEffect component
 */
export interface StanceTransitionEffectProps {
  /** Previous stance (for color interpolation) */
  readonly fromStance: TrigramStance | null;
  /** New stance being transitioned to */
  readonly toStance: TrigramStance;
  /** Callback when transition completes */
  readonly onTransitionComplete?: () => void;
  /** Transition duration in seconds (default: 0.5) */
  readonly duration?: number;
  /** Show stance name overlay (default: true) */
  readonly showNameOverlay?: boolean;
}
 
/**
 * StanceTransitionEffect Component
 *
 * Provides smooth visual feedback during stance changes:
 * 1. Expanding energy ring effect from player center
 * 2. Color interpolation from old to new stance
 * 3. Bilingual stance name overlay (1 second display)
 *
 * Performance optimized:
 * - Single animation frame callback
 * - Auto-cleanup after transition completes
 * - Reuses Three.js materials and geometries
 *
 * @example
 * ```tsx
 * <StanceTransitionEffect
 *   fromStance={TrigramStance.GEON}
 *   toStance={TrigramStance.TAE}
 *   onTransitionComplete={() => console.log('Transition done')}
 *   duration={0.5}
 * />
 * ```
 */
export const StanceTransitionEffect: React.FC<StanceTransitionEffectProps> = ({
  fromStance,
  toStance,
  onTransitionComplete,
  duration = 0.5,
  showNameOverlay = true,
}) => {
  const ringRef = useRef<THREE.Mesh>(null);
  const startTimeRef = useRef<number>(0);
  const isInitializedRef = useRef(false);
  const [isTransitioning, setIsTransitioning] = useState(true);
  const [showName, setShowName] = useState(showNameOverlay);
 
  // Get colors and names
  const fromColor = useMemo(
    () => (fromStance ? getStanceColor(fromStance) : getStanceColor(toStance)),
    [fromStance, toStance]
  );
  const toColor = useMemo(() => getStanceColor(toStance), [toStance]);
  const stanceNames = useMemo(() => getStanceNames(toStance), [toStance]);
 
  // Handle transitions - external timer effect justifies useEffect
   
  useEffect(() => {
    // Reset for new transition
    isInitializedRef.current = false;
    startTimeRef.current = 0;
    // These setState calls are intentional - triggered by prop change, not creating infinite loops
    setIsTransitioning(true);
    setShowName(showNameOverlay);
 
    // External system: timer for name overlay
    if (showNameOverlay) {
      const nameTimer = setTimeout(() => {
        setShowName(false);
      }, 1000);
 
      return () => clearTimeout(nameTimer);
    }
  }, [toStance, showNameOverlay]);
 
  // Animation loop
  useFrame((state) => {
    if (!isTransitioning || !ringRef.current) return;
 
    // Initialize start time on first frame for consistency with clock
    if (!isInitializedRef.current) {
      startTimeRef.current = state.clock.elapsedTime;
      isInitializedRef.current = true;
    }
 
    const elapsed = state.clock.elapsedTime - startTimeRef.current;
    const progress = Math.min(elapsed / duration, 1.0);
 
    // Interpolate color
    const currentColor = colorUtils.blend(fromColor, toColor, progress);
    (ringRef.current.material as THREE.MeshBasicMaterial).color.setHex(
      currentColor
    );
 
    // Expand ring outward
    const scale = 0.5 + progress * 2.5; // From 0.5 to 3.0
    ringRef.current.scale.setScalar(scale);
 
    // Fade out as it expands
    const opacity = 1.0 - progress * 0.7; // From 1.0 to 0.3
    (ringRef.current.material as THREE.MeshBasicMaterial).opacity = opacity;
 
    // Complete transition
    if (progress >= 1.0) {
      setIsTransitioning(false);
      onTransitionComplete?.();
    }
  });
 
  // Convert color to hex string for CSS
  const toColorHex = `#${toColor.toString(16).padStart(6, "0")}`;
 
  return (
    <group data-testid="stance-transition-effect">
      {/* Expanding energy ring */}
      <mesh
        ref={ringRef}
        position={[0, 0.05, 0]}
        rotation={[-Math.PI / 2, 0, 0]}
        data-testid="transition-ring"
      >
        <ringGeometry args={[0.8, 1.0, 32]} />
        <meshBasicMaterial
          color={fromColor}
          transparent
          opacity={1.0}
          side={THREE.DoubleSide}
          depthWrite={false}
          blending={THREE.AdditiveBlending}
        />
      </mesh>
 
      {/* Stance name overlay (Korean + English) */}
      {showName && (
        <Html
          position={[0, 2.0, 0]}
          center
          distanceFactor={10}
          style={{
            pointerEvents: "none",
            userSelect: "none",
          }}
          data-testid="stance-name-overlay"
        >
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              gap: "4px",
              padding: "8px 16px",
              backgroundColor: "rgba(0, 0, 0, 0.7)",
              borderRadius: "8px",
              border: `2px solid ${toColorHex}`,
              boxShadow: `0 0 20px ${toColorHex}`,
              animation: "fadeInOut 1s ease-in-out",
            }}
          >
            {/* Korean name */}
            <div
              style={{
                fontSize: "24px",
                fontFamily: FONT_FAMILY.KOREAN,
                color: toColorHex,
                fontWeight: "bold",
                textShadow: `0 0 10px ${toColorHex}`,
              }}
            >
              {stanceNames.korean}
            </div>
 
            {/* English name */}
            <div
              style={{
                fontSize: "14px",
                fontFamily: FONT_FAMILY.KOREAN,
                color: toColorHex,
                fontWeight: "normal",
                opacity: 0.8,
              }}
            >
              {stanceNames.english}
            </div>
          </div>
 
          {/* CSS animation */}
          <style>
            {`
              @keyframes fadeInOut {
                0% { opacity: 0; transform: translateY(10px); }
                20% { opacity: 1; transform: translateY(0); }
                80% { opacity: 1; transform: translateY(0); }
                100% { opacity: 0; transform: translateY(-10px); }
              }
            `}
          </style>
        </Html>
      )}
    </group>
  );
};
 
export default StanceTransitionEffect;