38 lines
912 B
TypeScript
38 lines
912 B
TypeScript
"use client";
|
|
|
|
import { useState, useEffect, useMemo } from "react";
|
|
import { calculateCountdown } from "@timetoleave/core";
|
|
|
|
interface ClockResult {
|
|
countdown: ReturnType<typeof calculateCountdown>;
|
|
status: "upcoming" | "now" | "past";
|
|
}
|
|
|
|
export function useClock(targetDate: Date): ClockResult {
|
|
const [now, setNow] = useState<Date>(new Date());
|
|
|
|
useEffect(() => {
|
|
const interval = setInterval(() => {
|
|
setNow(new Date());
|
|
}, 10_000);
|
|
|
|
return () => clearInterval(interval);
|
|
}, []);
|
|
|
|
return useMemo(() => {
|
|
const countdown = calculateCountdown(targetDate);
|
|
const diffMs = targetDate.getTime() - now.getTime();
|
|
|
|
let status: "upcoming" | "now" | "past";
|
|
if (diffMs <= 0) {
|
|
status = "now";
|
|
} else if (diffMs <= 10 * 60 * 1000) {
|
|
status = "now";
|
|
} else {
|
|
status = "upcoming";
|
|
}
|
|
|
|
return { countdown, status };
|
|
}, [targetDate, now]);
|
|
}
|