41 lines
1.1 KiB
TypeScript
41 lines
1.1 KiB
TypeScript
import { useEffect, useState } from "react";
|
|
|
|
function fmt(ms: number): string {
|
|
const total = Math.max(0, Math.floor(ms / 1000));
|
|
return `${Math.floor(total / 60)}m ${total % 60}s`;
|
|
}
|
|
|
|
/**
|
|
* Total process time, anchored on the session's created_at (robust to reload and
|
|
* resume). Ticks every second while running; freezes at stoppedAt once the session
|
|
* is finalized. Renders nothing until a start time is known.
|
|
*/
|
|
export function ElapsedTimer({
|
|
startedAt,
|
|
stoppedAt,
|
|
}: {
|
|
startedAt: string | null;
|
|
stoppedAt?: string | null;
|
|
}) {
|
|
const [now, setNow] = useState(() => Date.now());
|
|
|
|
useEffect(() => {
|
|
if (!startedAt || stoppedAt) return;
|
|
const t = setInterval(() => setNow(Date.now()), 1000);
|
|
return () => clearInterval(t);
|
|
}, [startedAt, stoppedAt]);
|
|
|
|
if (!startedAt) return null;
|
|
const start = new Date(startedAt).getTime();
|
|
const end = stoppedAt ? new Date(stoppedAt).getTime() : now;
|
|
return (
|
|
<span
|
|
className="shrink-0 tabular-nums text-xs text-muted-foreground"
|
|
aria-label="Elapsed time"
|
|
title="Total elapsed time"
|
|
>
|
|
{fmt(end - start)}
|
|
</span>
|
|
);
|
|
}
|