All files / Rindu/components/CountDown CountDown.tsx

7.01% Statements 4/57
0% Branches 0/30
0% Functions 0/9
8% Lines 4/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            19x   19x                               19x                                                                                                                                                                                                                                                                                                                       19x  
import React, {
  ReactElement,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
 
export enum CountDownType {
  DOTS = "dots",
  CIRCULAR = "circular",
}
 
export interface CountDownProps {
  duration: number;
  currentProgress: number;
  isPlaying: boolean;
  type?: CountDownType;
  startTime?: number;
  size?: number;
  strokeWidth?: number;
  color?: string;
}
 
export const CountDown = ({
  duration,
  currentProgress,
  isPlaying,
  type = CountDownType.CIRCULAR,
  startTime = 0,
  size = 32,
  strokeWidth = 3,
  color = "#ffffff",
}: CountDownProps): ReactElement | null => {
  const isDotType = type === CountDownType.DOTS;
 
  const { radius, circumference, fontSize } = useMemo(() => {
    const r = size / 2 - strokeWidth / 2;
    return {
      radius: r,
      circumference: 2 * Math.PI * r,
      fontSize: Math.max(size * 0.3, 12),
    } as const;
  }, [size, strokeWidth]);
 
  const circleRef = useRef<SVGCircleElement>(null);
  const animationRef = useRef<number>(null);
  const progressRef = useRef(currentProgress);
  const lastTimeRef = useRef<number | null>(null);
  const [countdownNumber, setCountdownNumber] = useState<number | null>(null);
 
  const paintCircle = () => {
    Iif (!circleRef.current) return false;
    const remainingTime = duration - progressRef.current;
    const progress = Math.max(0, Math.min(1, remainingTime / duration));
    circleRef.current.style.strokeDashoffset = `${
      circumference * (1 - progress)
    }`;
    circleRef.current.style.opacity = progress < 0.1 ? `${progress * 10}` : "1";
 
    const remainingSeconds = Math.ceil(remainingTime / 1000);
    setCountdownNumber(
      remainingSeconds > 0 && remainingSeconds <= 3 ? remainingSeconds : null
    );
 
    return progress > 0;
  };
 
  useEffect(() => {
    progressRef.current = currentProgress;
    Iif (!isDotType) paintCircle();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentProgress, duration, isDotType]);
 
  useEffect(() => {
    Iif (isDotType || !isPlaying) return;
 
    const animate = (time: number) => {
      Iif (lastTimeRef.current !== null) {
        progressRef.current += time - lastTimeRef.current;
      }
      lastTimeRef.current = time;
      Iif (paintCircle()) {
        animationRef.current = requestAnimationFrame(animate);
      }
    };
 
    lastTimeRef.current = performance.now();
    animationRef.current = requestAnimationFrame(animate);
 
    return () => {
      animationRef.current && cancelAnimationFrame(animationRef.current);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isDotType, isPlaying]);
 
  Iif (isDotType) {
    const inWindow =
      currentProgress >= startTime && currentProgress <= startTime + duration;
    const progress = inWindow
      ? Math.min(1, Math.max(0, (currentProgress - startTime) / duration))
      : 0;
 
    const total = progress * 3;
    const activeDot = Math.floor(total);
    const dotProgress = total - activeDot;
 
    const dotOpacity = (i: number) => {
      Iif (i < activeDot) return 1;
      Iif (i > activeDot) return 0.2;
      return 0.2 + dotProgress * 0.8;
    };
 
    const dotSize = Math.max(size * 0.1, 3);
    const gap = size * 0.15;
 
    return (
      <div
        style={{
          width: size,
          display: "flex",
          gap,
          alignItems: "center",
          visibility: inWindow ? "visible" : "hidden",
        }}
      >
        {[0, 1, 2].map((i) => (
          <div
            key={i}
            style={{
              width: dotSize,
              height: dotSize,
              borderRadius: "50%",
              backgroundColor: color,
              opacity: dotOpacity(i),
              transition: "opacity 150ms linear",
            }}
          />
        ))}
      </div>
    );
  }
 
  return (
    <div className="countdown-container" style={{ width: size, height: size }}>
      <svg
        style={{ width: "100%", height: "100%" }}
        viewBox={`0 0 ${size} ${size}`}
      >
        <circle
          ref={circleRef}
          cx={size / 2}
          cy={size / 2}
          r={radius}
          fill="none"
          stroke={color}
          strokeWidth={strokeWidth}
          strokeDasharray={circumference}
          strokeDashoffset={circumference}
          strokeLinecap="round"
          transform={`rotate(-90 ${size / 2} ${size / 2})`}
        />
        {countdownNumber !== null && (
          <text
            x="50%"
            y="50%"
            textAnchor="middle"
            dominantBaseline="central"
            fill={color}
            fontSize={fontSize}
            fontWeight="bold"
          >
            {countdownNumber}
          </text>
        )}
      </svg>
    </div>
  );
};
 
export default CountDown;