All files / components/shared/mobile StanceWheelPure.tsx

21.42% Statements 18/84
22.41% Branches 13/58
9.09% Functions 2/22
22.5% Lines 18/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 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484                                                                                                                      2x                           2x                           2x 132x                   132x                                                                         2x                 132x 132x         132x                                                                         132x                                                 132x                                                                               132x                           132x     132x     132x 132x   132x                                                                                                                                                                                                                                                                                         132x                                                                                                                                      
/**
 * StanceWheelPure Component - Pure DOM version (no Three.js/drei dependency)
 *
 * Circular 8-segment stance selector for mobile touch controls
 * Provides visual and tactile stance switching interface
 *
 * This is a pure DOM version that renders OUTSIDE the Three.js Canvas.
 * It does NOT use Html from @react-three/drei, making it compatible with
 * rendering outside Canvas contexts.
 *
 * WCAG 2.1 Level AA Compliance:
 * - ARIA labels for all 8 stance buttons
 * - Keyboard navigation (Tab, Enter, Arrow keys)
 * - Visible focus indicators (2px cyan border)
 * - aria-expanded state for wheel toggle
 * - role="radiogroup" for stance selection
 * - 50x50px touch targets (exceeds 44x44px minimum)
 *
 * @module components/mobile/StanceWheelPure
 * @category Mobile Controls
 * @korean 자세 휠 (순수 DOM)
 */
 
import React, { useCallback, useState } from "react";
import { KOREAN_COLORS } from "@/types/constants";
import { TRIGRAM_STANCES_ORDER } from "../../../systems/trigram/types";
import { TrigramStance } from "../../../types/common";
import { triggerHaptic } from "../../../utils/haptics";
import { getColorRGB } from "../../../utils/colorHelpers";
import {
  handleKeyboardNav,
  getFocusStyle,
  announceToScreenReader,
} from "../../../utils/accessibility";
import { createBilingualLabel } from "../../../types/AccessibilityTypes";
 
/**
 * Props for StanceWheelPure component
 */
export interface StanceWheelPureProps {
  /** Current stance index (0-7) */
  readonly currentStance: number;
  /** Callback when stance changes */
  readonly onStanceChange: (stanceIndex: number) => void;
  /** Whether wheel is expanded */
  readonly expanded: boolean;
  /** Callback to toggle expansion */
  readonly onToggle: () => void;
  /** Whether wheel is disabled */
  readonly disabled?: boolean;
  /** Position from bottom in pixels (default: 34 when collapsed, 100 when expanded for safe area) */
  readonly bottom?: number;
  /** Opacity of wheel (default: 0.8) */
  readonly opacity?: number;
}
 
/**
 * Trigram symbols for each stance
 */
const TRIGRAM_SYMBOLS = [
  "☰",
  "☱",
  "☲",
  "☳",
  "☴",
  "☵",
  "☶",
  "☷",
] as const;
 
/**
 * Korean names for each stance
 */
const STANCE_KOREAN_NAMES = [
  "건", // Geon - Heaven
  "태", // Tae - Lake
  "리", // Li - Fire
  "진", // Jin - Thunder
  "손", // Son - Wind
  "감", // Gam - Water
  "간", // Gan - Mountain
  "곤", // Gon - Earth
] as const;
 
/**
 * Get color for a specific stance
 */
const getStanceColor = (stance: TrigramStance): number => {
  const stanceColors: Record<TrigramStance, number> = {
    geon: 0xffd700, // Gold - Heaven
    tae: 0x00ffff, // Cyan - Lake
    li: 0xff4444, // Red - Fire
    jin: 0xffaa00, // Orange - Thunder
    son: 0x88ff88, // Light Green - Wind
    gam: 0x0088ff, // Blue - Water
    gan: 0x8844ff, // Purple - Mountain
    gon: 0xaa6644, // Brown - Earth
  };
  return stanceColors[stance] ?? KOREAN_COLORS.PRIMARY_CYAN;
};
 
/**
 * StanceWheelPure Component
 *
 * Pure DOM circular stance selector with 8 segments for trigram stances
 * Features:
 * - Expandable/collapsible interface
 * - Visual stance indicator when collapsed (60x60px)
 * - 8 touch-optimized stance buttons when expanded (50x50px each)
 * - 200px wheel diameter with safe positioning
 * - Korean trigram symbols and names
 * - Color-coded by stance element
 * - Haptic feedback on selection
 * - 50x50px minimum touch targets
 *
 * Usage in Combat:
 * - Tap collapsed indicator to expand wheel
 * - Select from 8 trigram stances
 * - Current stance highlighted with gold accent
 * - Tap current stance to collapse wheel
 *
 * @example
 * ```tsx
 * <StanceWheelPure
 *   currentStance={player.stance}
 *   onStanceChange={(index) => handleStanceChange(index)}
 *   expanded={wheelExpanded}
 *   onToggle={() => setWheelExpanded(!wheelExpanded)}
 *   disabled={isPaused}
 * />
 * ```
 *
 * @public
 * @korean 자세휠순수
 */
export const StanceWheelPure: React.FC<StanceWheelPureProps> = ({
  currentStance,
  onStanceChange,
  expanded,
  onToggle,
  disabled = false,
  bottom,
  opacity = 0.8,
}) => {
  const [hoveredStance, setHoveredStance] = useState<number | null>(null);
  const [focusedStance, setFocusedStance] = useState<number | null>(null);
 
  /**
   * Handle stance selection (touch or mouse)
   */
  const handleStanceSelect = useCallback(
    (e: React.TouchEvent | React.MouseEvent, stanceIndex: number) => {
      if (disabled) return;
      e.preventDefault();
      e.stopPropagation();
 
      // Don't allow selecting the same stance
      if (stanceIndex === currentStance) {
        // Collapse wheel if tapping current stance
        onToggle();
        triggerHaptic("light");
        return;
      }
 
      onStanceChange(stanceIndex);
      triggerHaptic("medium");
 
      // Announce stance change to screen readers
      const stanceName = STANCE_KOREAN_NAMES[stanceIndex];
      const stanceSymbol = TRIGRAM_SYMBOLS[stanceIndex];
      announceToScreenReader({
        message: createBilingualLabel(
          `자세 변경: ${stanceName} ${stanceSymbol}`,
          `Stance changed to ${TRIGRAM_STANCES_ORDER[stanceIndex]}`,
        ).label,
        politeness: "polite",
      });
 
      // Auto-collapse after selection (optional)
      // onToggle();
    },
    [disabled, currentStance, onStanceChange, onToggle],
  );
 
  /**
   * Handle wheel toggle (touch or mouse)
   */
  const handleToggle = useCallback(
    (e: React.TouchEvent | React.MouseEvent) => {
      if (disabled) return;
      e.preventDefault();
      e.stopPropagation();
 
      onToggle();
      triggerHaptic("light");
 
      // Announce state change to screen readers using the toggled value
      const nextExpanded = !expanded;
      announceToScreenReader({
        message: createBilingualLabel(
          nextExpanded ? "자세 휠 열림" : "자세 휠 닫힘",
          nextExpanded ? "Stance wheel opened" : "Stance wheel closed",
        ).label,
        politeness: "polite",
      });
    },
    [disabled, onToggle, expanded],
  );
 
  /**
   * Handle keyboard navigation for stance buttons
   */
  const handleStanceKeyDown = useCallback(
    (stanceIndex: number) => (e: React.KeyboardEvent) => {
      if (disabled) return;
      handleKeyboardNav(e.nativeEvent, {
        onActivate: () => {
          if (stanceIndex === currentStance) {
            onToggle();
          } else {
            onStanceChange(stanceIndex);
          }
          triggerHaptic("medium");
        },
        onCancel: () => {
          onToggle();
        },
        onNavigate: (direction) => {
          // Navigate between stances with arrow keys
          let newIndex = stanceIndex;
          if (direction === "left" || direction === "up") {
            newIndex = (stanceIndex - 1 + 8) % 8;
          } else if (direction === "right" || direction === "down") {
            newIndex = (stanceIndex + 1) % 8;
          }
          setFocusedStance(newIndex);
          // Focus the new stance button on the next animation frame
          requestAnimationFrame(() => {
            const button = document.querySelector(
              `[data-testid="stance-button-pure-${newIndex}"]`,
            ) as HTMLElement | null;
            button?.focus();
          });
        },
      });
    },
    [disabled, currentStance, onStanceChange, onToggle],
  );
 
  /**
   * Handle keyboard navigation for toggle button
   */
  const handleToggleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (disabled) return;
      handleKeyboardNav(e.nativeEvent, {
        onActivate: () => {
          onToggle();
          triggerHaptic("light");
        },
      });
    },
    [disabled, onToggle],
  );
 
  // Dynamic bottom position with safe area consideration
  const dynamicBottom = bottom ?? (expanded ? 100 : 34);
 
  // Get RGB values for colors using shared utility
  const currentStanceColor = getColorRGB(
    getStanceColor(TRIGRAM_STANCES_ORDER[currentStance]),
  );
  const goldColor = getColorRGB(KOREAN_COLORS.ACCENT_GOLD);
  const primaryColor = getColorRGB(KOREAN_COLORS.PRIMARY_CYAN);
 
  Iif (expanded) {
    // Expanded: Show full 8-segment wheel
    const wheelSize = 200;
    const segmentAngle = 360 / 8;
 
    return (
      <div
        style={{
          position: "absolute", // Changed from fixed to position relative to container
          bottom: `${dynamicBottom}px`,
          left: "50%",
          transform: "translateX(-50%)",
          opacity: disabled ? 0.3 : opacity,
          pointerEvents: disabled ? "none" : "auto",
          transition: "all 0.3s ease",
          zIndex: 1000,
        }}
        data-testid="stance-wheel-pure-expanded"
        role="radiogroup"
        aria-label={
          createBilingualLabel(
            "팔괘 자세 선택",
            "Eight Trigram Stance Selection",
          ).label
        }
        aria-activedescendant={`stance-button-pure-${currentStance}`}
      >
        <div
          style={{
            width: `${wheelSize}px`,
            height: `${wheelSize}px`,
            position: "relative",
          }}
        >
          {/* Stance buttons arranged in circle */}
          {TRIGRAM_STANCES_ORDER.map((stance, index) => {
            const angle = index * segmentAngle;
            const radian = (angle - 90) * (Math.PI / 180); // -90 to start from top
            const x = Math.cos(radian) * 80 + 100;
            const y = Math.sin(radian) * 80 + 100;
            const isActive = index === currentStance;
            const isHovered = index === hoveredStance;
            const stanceColor = getColorRGB(getStanceColor(stance));
 
            return (
              <button
                key={stance}
                onTouchStart={(e) => handleStanceSelect(e, index)}
                onTouchEnd={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  setHoveredStance(null);
                }}
                onMouseDown={(e) => handleStanceSelect(e, index)}
                onMouseEnter={() => setHoveredStance(index)}
                onMouseLeave={() => setHoveredStance(null)}
                onKeyDown={handleStanceKeyDown(index)}
                onFocus={() => setFocusedStance(index)}
                onBlur={() => setFocusedStance(null)}
                style={{
                  position: "absolute",
                  left: `${x - 25}px`,
                  top: `${y - 25}px`,
                  width: "50px",
                  height: "50px",
                  borderRadius: "50%",
                  background: isActive
                    ? `rgba(${goldColor.r}, ${goldColor.g}, ${goldColor.b}, 0.95)`
                    : `rgba(${stanceColor.r}, ${stanceColor.g}, ${stanceColor.b}, 0.8)`,
                  border: `3px solid ${isActive ? "#fff" : `rgba(${stanceColor.r}, ${stanceColor.g}, ${stanceColor.b}, 1)`}`,
                  fontSize: "24px",
                  color: isActive ? "#000" : "#fff",
                  fontWeight: "bold",
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  justifyContent: "center",
                  cursor: "pointer",
                  userSelect: "none",
                  touchAction: "none",
                  transition: "all 0.2s ease",
                  transform: isActive || isHovered ? "scale(1.15)" : "scale(1)",
                  boxShadow: isActive
                    ? `0 0 25px rgba(${goldColor.r}, ${goldColor.g}, ${goldColor.b}, 0.9)`
                    : isHovered
                      ? `0 0 15px rgba(${stanceColor.r}, ${stanceColor.g}, ${stanceColor.b}, 0.8)`
                      : `0 4px 10px rgba(0, 0, 0, 0.5)`,
                  ...getFocusStyle(focusedStance === index, {
                    boxShadow: `0 0 0 4px rgba(${primaryColor.r}, ${primaryColor.g}, ${primaryColor.b}, 0.5), 0 0 25px rgba(${goldColor.r}, ${goldColor.g}, ${goldColor.b}, 0.9)`,
                    outlineColor: KOREAN_COLORS.PRIMARY_CYAN,
                    outlineWidth: 3,
                  }),
                }}
                aria-label={
                  createBilingualLabel(
                    `${STANCE_KOREAN_NAMES[index]} ${TRIGRAM_SYMBOLS[index]}`,
                    `${stance} stance`,
                  ).label
                }
                aria-checked={isActive}
                role="radio"
                tabIndex={0}
                disabled={disabled}
                id={`stance-button-pure-${index}`}
                data-testid={`stance-button-pure-${index}`}
              >
                <div style={{ fontSize: "20px", lineHeight: 1 }}>
                  {TRIGRAM_SYMBOLS[index]}
                </div>
                <div style={{ fontSize: "8px", marginTop: "2px" }}>
                  {STANCE_KOREAN_NAMES[index]}
                </div>
              </button>
            );
          })}
 
          {/* Center label */}
          <div
            style={{
              position: "absolute",
              top: "50%",
              left: "50%",
              transform: "translate(-50%, -50%)",
              fontSize: "12px",
              color: `rgba(${primaryColor.r}, ${primaryColor.g}, ${primaryColor.b}, 0.9)`,
              textShadow: "0 1px 3px rgba(0, 0, 0, 0.8)",
              fontWeight: "bold",
              textAlign: "center",
              pointerEvents: "none",
            }}
          >
            자세 선택
            <br />
            <span style={{ fontSize: "10px" }}>Stance</span>
          </div>
        </div>
      </div>
    );
  }
 
  // Collapsed: Show current stance indicator
  return (
    <div
      style={{
        position: "absolute", // Changed from fixed to position relative to container
        bottom: `${dynamicBottom}px`,
        left: "50%",
        transform: "translateX(-50%)",
        opacity: disabled ? 0.3 : opacity,
        pointerEvents: disabled ? "none" : "auto",
        transition: "all 0.3s ease",
        zIndex: 1000,
      }}
      data-testid="stance-wheel-pure-collapsed"
    >
      <button
        onTouchStart={handleToggle}
        onMouseDown={handleToggle}
        onKeyDown={handleToggleKeyDown}
        onFocus={() => setFocusedStance(currentStance)}
        onBlur={() => setFocusedStance(null)}
        style={{
          width: "60px",
          height: "60px",
          borderRadius: "50%",
          background: `rgba(${currentStanceColor.r}, ${currentStanceColor.g}, ${currentStanceColor.b}, 0.9)`,
          border: `3px solid rgba(${goldColor.r}, ${goldColor.g}, ${goldColor.b}, 0.9)`,
          fontSize: "28px",
          color: "#fff",
          fontWeight: "bold",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          cursor: "pointer",
          userSelect: "none",
          touchAction: "none",
          transition: "all 0.2s ease",
          boxShadow: `0 4px 15px rgba(0, 0, 0, 0.6), 0 0 20px rgba(${currentStanceColor.r}, ${currentStanceColor.g}, ${currentStanceColor.b}, 0.6)`,
          ...getFocusStyle(focusedStance === currentStance, {
            boxShadow: `0 0 0 4px rgba(${primaryColor.r}, ${primaryColor.g}, ${primaryColor.b}, 0.5), 0 4px 15px rgba(0, 0, 0, 0.6), 0 0 20px rgba(${currentStanceColor.r}, ${currentStanceColor.g}, ${currentStanceColor.b}, 0.6)`,
            outlineColor: KOREAN_COLORS.PRIMARY_CYAN,
            outlineWidth: 3,
          }),
        }}
        disabled={disabled}
        aria-label={
          createBilingualLabel(
            `현재 자세: ${STANCE_KOREAN_NAMES[currentStance]} ${TRIGRAM_SYMBOLS[currentStance]}. 자세 휠 열기`,
            `Current stance: ${TRIGRAM_STANCES_ORDER[currentStance]}. Open stance wheel`,
          ).label
        }
        aria-expanded={expanded}
        aria-haspopup="menu"
        role="button"
        tabIndex={disabled ? -1 : 0}
        data-testid="stance-wheel-pure-toggle"
      >
        <div style={{ fontSize: "24px", lineHeight: 1 }}>
          {TRIGRAM_SYMBOLS[currentStance]}
        </div>
        <div style={{ fontSize: "10px", marginTop: "2px" }}>
          {STANCE_KOREAN_NAMES[currentStance]}
        </div>
      </button>
    </div>
  );
};