49 lines
1.3 KiB
TypeScript
49 lines
1.3 KiB
TypeScript
import { useState, useEffect, useRef } from 'react';
|
|
import { useTranslation } from 'react-i18next';
|
|
import { toLocaleDigits } from '@/utils/persianDigit';
|
|
|
|
interface CountdownTimerProps {
|
|
initialSeconds: number;
|
|
onComplete?: () => void;
|
|
}
|
|
|
|
export function CountDownTimer({
|
|
initialSeconds,
|
|
onComplete,
|
|
}: CountdownTimerProps) {
|
|
const { i18n } = useTranslation();
|
|
const [secondsLeft, setSecondsLeft] = useState(initialSeconds);
|
|
|
|
const onCompleteRef = useRef(onComplete);
|
|
useEffect(() => {
|
|
onCompleteRef.current = onComplete;
|
|
}, [onComplete]);
|
|
|
|
useEffect(() => {
|
|
setSecondsLeft(initialSeconds);
|
|
}, [initialSeconds]);
|
|
|
|
useEffect(() => {
|
|
if (secondsLeft <= 0) return;
|
|
const id = setInterval(() => {
|
|
setSecondsLeft((prev) => {
|
|
if (prev <= 1) {
|
|
clearInterval(id);
|
|
onCompleteRef.current?.();
|
|
return 0;
|
|
}
|
|
return prev - 1;
|
|
});
|
|
}, 1000);
|
|
return () => clearInterval(id);
|
|
}, [secondsLeft]);
|
|
|
|
const formatTime = (totalSeconds: number) => {
|
|
const m = String(Math.floor(totalSeconds / 60)).padStart(2, '0');
|
|
const s = String(totalSeconds % 60).padStart(2, '0');
|
|
return toLocaleDigits(`${m}:${s}`, i18n.language);
|
|
};
|
|
|
|
return <span>{formatTime(secondsLeft)}</span>;
|
|
}
|