All files / components/ui VolumeControl.tsx

92.98% Statements 53/57
83.78% Branches 62/74
100% Functions 13/13
94.64% Lines 53/56

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                                                        7x           115x     115x 115x 115x 115x     115x 75x 75x 75x 75x       115x 76x   76x           76x   45x   31x                   115x 76x                             115x   1x 1x 1x 1x           115x   1x 1x 1x 1x           115x   1x 1x 1x 1x           115x 2x 2x 2x 2x 1x   1x     2x       115x 76x               115x 76x                   115x 76x                 115x 75x                 115x 74x                                                                             41x                                                                                                                                                                                                                                      
import React, { useCallback, useMemo, useState } from "react";
import { useAudio } from "../../audio/AudioProvider";
import { KOREAN_COLORS } from "../../types/constants";
import { hexToRgbaString, toHex } from "../../utils/colorUtils";
 
export interface VolumeControlProps {
  readonly position?:
    | "top-right"
    | "bottom-right"
    | "top-left"
    | "bottom-left"
    | "custom";
  readonly style?: React.CSSProperties;
  readonly showLabels?: boolean;
  readonly compact?: boolean;
}
 
/**
 * Volume Control Component
 *
 * Provides controls for:
 * - Master volume
 * - Music volume
 * - SFX volume
 * - Mute/unmute toggle
 *
 * Inspired by template game (https://github.com/Hack23/game)
 */
export const VolumeControl: React.FC<VolumeControlProps> = ({
  position = "top-right",
  style,
  showLabels = true,
  compact = false,
}) => {
  const audio = useAudio();
 
  // Local state to track values for UI (prevents issues if audio not ready)
  const [masterVolume, setMasterVolume] = useState(audio.masterVolume ?? 1.0);
  const [musicVolume, setMusicVolume] = useState(audio.musicVolume ?? 0.7);
  const [sfxVolume, setSfxVolume] = useState(audio.sfxVolume ?? 0.8);
  const [isMuted, setIsMuted] = useState(audio.muted ?? false);
 
  // Sync local state with audio manager state changes
  React.useEffect(() => {
    setMasterVolume(audio.masterVolume ?? 1.0);
    setMusicVolume(audio.musicVolume ?? 0.7);
    setSfxVolume(audio.sfxVolume ?? 0.8);
    setIsMuted(audio.muted ?? false);
  }, [audio.masterVolume, audio.musicVolume, audio.sfxVolume, audio.muted]);
 
  // Get position styles (memoized)
  const getPositionStyle = useMemo((): React.CSSProperties => {
    Iif (position === "custom") return {};
 
    const baseStyle: React.CSSProperties = {
      position: "absolute",
      zIndex: 1000,
      padding: compact ? "8px 12px" : "12px 16px",
    };
 
    switch (position) {
      case "top-right":
        return { ...baseStyle, top: "20px", right: "20px" };
      case "bottom-right":
        return { ...baseStyle, bottom: "20px", right: "20px" };
      case "top-left":
        return { ...baseStyle, top: "20px", left: "20px" };
      case "bottom-left":
        return { ...baseStyle, bottom: "20px", left: "20px" };
      default:
        return baseStyle;
    }
  }, [position, compact]);
 
  const containerStyle = useMemo(
    (): React.CSSProperties => ({
      ...getPositionStyle,
      display: "flex",
      flexDirection: compact ? "row" : "column",
      alignItems: "center",
      gap: compact ? "12px" : "8px",
      background: "rgba(33, 38, 45, 0.95)",
      borderRadius: "12px",
      border: `1px solid ${hexToRgbaString(KOREAN_COLORS.PRIMARY_CYAN, 0.2)}`,
      pointerEvents: "auto", // Enable interaction even when parent has pointerEvents: none
      ...style,
    }),
    [getPositionStyle, compact, style]
  );
 
  const handleMasterVolumeChange = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      const value = parseFloat(event.target.value);
      setMasterVolume(value);
      Eif (audio.isAudioReady) {
        audio.setVolume("master", value);
      }
    },
    [audio]
  );
 
  const handleMusicVolumeChange = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      const value = parseFloat(event.target.value);
      setMusicVolume(value);
      Eif (audio.isAudioReady) {
        audio.setVolume("music", value);
      }
    },
    [audio]
  );
 
  const handleSfxVolumeChange = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      const value = parseFloat(event.target.value);
      setSfxVolume(value);
      Eif (audio.isAudioReady) {
        audio.setVolume("sfx", value);
      }
    },
    [audio]
  );
 
  const handleMuteToggle = useCallback(() => {
    setIsMuted((prevMuted) => {
      const newMuted = !prevMuted;
      Eif (audio.isAudioReady) {
        if (newMuted) {
          audio.mute();
        } else {
          audio.unmute();
        }
      }
      return newMuted;
    });
  }, [audio]);
 
  const sliderStyle = useMemo(
    (): React.CSSProperties => ({
      width: compact ? "60px" : "100px",
      cursor: "pointer",
      accentColor: `#${toHex(KOREAN_COLORS.PRIMARY_CYAN)}`,
    }),
    [compact]
  );
 
  const labelStyle = useMemo(
    (): React.CSSProperties => ({
      color: "#ffffff",
      fontSize: compact ? "11px" : "12px",
      fontWeight: "bold",
      minWidth: compact ? "40px" : "50px",
      textAlign: "left",
    }),
    [compact]
  );
 
  const valueStyle = useMemo(
    (): React.CSSProperties => ({
      color: `#${toHex(KOREAN_COLORS.ACCENT_GOLD)}`,
      fontSize: compact ? "10px" : "11px",
      minWidth: "35px",
      textAlign: "right",
    }),
    [compact]
  );
 
  const controlRowStyle = useMemo(
    (): React.CSSProperties => ({
      display: "flex",
      alignItems: "center",
      gap: "8px",
      width: "100%",
    }),
    []
  );
 
  if (compact) {
    return (
      <div style={containerStyle} data-testid="volume-control">
        <button
          onClick={handleMuteToggle}
          data-testid="mute-toggle-button"
          aria-label={isMuted ? "Unmute audio" : "Mute audio"}
          style={{
            background: isMuted
              ? "#666666"
              : `#${toHex(KOREAN_COLORS.PRIMARY_CYAN)}`,
            color: "white",
            border: "none",
            padding: "6px 12px",
            borderRadius: "6px",
            cursor: "pointer",
            fontWeight: "bold",
            fontSize: "14px",
          }}
          title={isMuted ? "음소거 해제 | Unmute" : "음소거 | Mute"}
        >
          {isMuted ? "🔇" : "🔊"}
        </button>
        <input
          type="range"
          min="0"
          max="1"
          step="0.01"
          value={masterVolume}
          onChange={handleMasterVolumeChange}
          data-testid="master-volume-slider"
          aria-label="마스터 볼륨 | Master Volume"
          style={sliderStyle}
          title="마스터 볼륨 | Master Volume"
        />
        <span style={valueStyle}>{Math.round(masterVolume * 100)}%</span>
      </div>
    );
  }
 
  return (
    <div style={containerStyle} data-testid="volume-control">
      {showLabels && (
        <div
          style={{
            color: `#${toHex(KOREAN_COLORS.PRIMARY_CYAN)}`,
            fontSize: "14px",
            fontWeight: "bold",
            marginBottom: "4px",
            textAlign: "center",
          }}
        >
          🎵 음량 | Volume
        </div>
      )}
 
      {/* Master Volume */}
      <div style={controlRowStyle}>
        <label htmlFor="master-volume" style={labelStyle}>
          전체 | Master
        </label>
        <input
          id="master-volume"
          type="range"
          min="0"
          max="1"
          step="0.01"
          value={masterVolume}
          onChange={handleMasterVolumeChange}
          data-testid="master-volume-slider"
          style={sliderStyle}
        />
        <span style={valueStyle}>{Math.round(masterVolume * 100)}%</span>
      </div>
 
      {/* Music Volume */}
      <div style={controlRowStyle}>
        <label htmlFor="music-volume" style={labelStyle}>
          음악 | Music
        </label>
        <input
          id="music-volume"
          type="range"
          min="0"
          max="1"
          step="0.01"
          value={musicVolume}
          onChange={handleMusicVolumeChange}
          data-testid="music-volume-slider"
          style={sliderStyle}
        />
        <span style={valueStyle}>{Math.round(musicVolume * 100)}%</span>
      </div>
 
      {/* SFX Volume */}
      <div style={controlRowStyle}>
        <label htmlFor="sfx-volume" style={labelStyle}>
          효과음 | SFX
        </label>
        <input
          id="sfx-volume"
          type="range"
          min="0"
          max="1"
          step="0.01"
          value={sfxVolume}
          onChange={handleSfxVolumeChange}
          data-testid="sfx-volume-slider"
          style={sliderStyle}
        />
        <span style={valueStyle}>{Math.round(sfxVolume * 100)}%</span>
      </div>
 
      {/* Mute Toggle */}
      <button
        onClick={handleMuteToggle}
        data-testid="mute-toggle-button"
        aria-label={isMuted ? "Unmute audio" : "Mute audio"}
        style={{
          background: isMuted
            ? "#666666"
            : `#${toHex(KOREAN_COLORS.PRIMARY_CYAN)}`,
          color: "white",
          border: "none",
          padding: "8px 16px",
          borderRadius: "8px",
          cursor: "pointer",
          fontWeight: "bold",
          fontSize: "14px",
          marginTop: "4px",
          width: "100%",
        }}
        title={isMuted ? "음소거 해제 | Unmute" : "음소거 | Mute"}
      >
        {isMuted ? "🔇 음소거 해제 | Unmute" : "🔊 음소거 | Mute"}
      </button>
 
      {/* Audio Status Indicator */}
      <div
        style={{
          color: audio.isAudioReady
            ? `#${toHex(KOREAN_COLORS.ACCENT_GOLD)}`
            : "#999",
          fontSize: "10px",
          marginTop: "4px",
          textAlign: "center",
        }}
      >
        {audio.isAudioReady
          ? "✓ 오디오 준비됨 | Audio Ready"
          : "⏳ 초기화 중... | Initializing..."}
      </div>
    </div>
  );
};