Files
time_to_leave/apps/web/src/hooks/useClock.ts
T
fegger 1851d2ed47 Add TimeToLeave feature checklist and plan (50)
Add TimeToLeave feature checklist and plan
2026-05-12 13:17:17 +02:00

40 lines
1012 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, departureTime?: Date | null): ClockResult {
const [now, setNow] = useState<Date>(new Date());
useEffect(() => {
const interval = setInterval(() => {
setNow(new Date());
}, 10_000);
return () => clearInterval(interval);
}, []);
const effectiveTarget = departureTime ?? targetDate;
return useMemo(() => {
const countdown = calculateCountdown(effectiveTarget);
const diffMs = effectiveTarget.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 };
}, [effectiveTarget, now]);
}