Changes
Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com>
This commit is contained in:
co-authored by
renee-png
parent
add07a8450
commit
18545bc093
+80
-83
@@ -2,171 +2,162 @@ import { createContext, useContext, useEffect, useRef, useState, type ReactNode
|
||||
|
||||
const STORAGE_KEY = "counsel.timer.v1";
|
||||
|
||||
export interface TimerTarget {
|
||||
clientId: string;
|
||||
clientName: string;
|
||||
caseId?: string | null;
|
||||
caseNumber?: string | null;
|
||||
caseTitle?: string | null;
|
||||
defaultHourlyRate?: number | null;
|
||||
}
|
||||
|
||||
interface PersistedTimer extends TimerTarget {
|
||||
interface PersistedTimer {
|
||||
clientId: string | null;
|
||||
caseId: string | null;
|
||||
description: string;
|
||||
// Total accumulated milliseconds while running, excluding current segment
|
||||
accumulatedMs: number;
|
||||
// Timestamp (ms) when the current running segment started, or null if paused
|
||||
runningSince: number | null;
|
||||
description: string;
|
||||
startedAt: string; // ISO when first started
|
||||
startedAt: string | null;
|
||||
}
|
||||
|
||||
interface TimerState {
|
||||
active: PersistedTimer | null;
|
||||
timer: PersistedTimer;
|
||||
elapsedMs: number;
|
||||
isRunning: boolean;
|
||||
start: (target: TimerTarget, description?: string) => void;
|
||||
hasStarted: boolean;
|
||||
setClient: (clientId: string | null) => void;
|
||||
setCase: (caseId: string | null) => void;
|
||||
setDescription: (description: string) => void;
|
||||
start: () => void;
|
||||
pause: () => void;
|
||||
resume: () => void;
|
||||
reset: () => void;
|
||||
setDescription: (d: string) => void;
|
||||
// Returns elapsed hours rounded to 2 decimals; clears timer
|
||||
stopAndConsume: () => { hours: number; description: string; target: TimerTarget; startedAt: string } | null;
|
||||
consume: () => { hours: number };
|
||||
}
|
||||
|
||||
const empty: PersistedTimer = {
|
||||
clientId: null,
|
||||
caseId: null,
|
||||
description: "",
|
||||
accumulatedMs: 0,
|
||||
runningSince: null,
|
||||
startedAt: null,
|
||||
};
|
||||
|
||||
const TimerContext = createContext<TimerState | undefined>(undefined);
|
||||
|
||||
function read(): PersistedTimer | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
function read(): PersistedTimer {
|
||||
if (typeof window === "undefined") return empty;
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) return null;
|
||||
return JSON.parse(raw) as PersistedTimer;
|
||||
if (!raw) return empty;
|
||||
return { ...empty, ...(JSON.parse(raw) as PersistedTimer) };
|
||||
} catch {
|
||||
return null;
|
||||
return empty;
|
||||
}
|
||||
}
|
||||
|
||||
function write(t: PersistedTimer | null) {
|
||||
function write(t: PersistedTimer) {
|
||||
if (typeof window === "undefined") return;
|
||||
if (!t) localStorage.removeItem(STORAGE_KEY);
|
||||
else localStorage.setItem(STORAGE_KEY, JSON.stringify(t));
|
||||
if (t.accumulatedMs === 0 && !t.runningSince && !t.clientId && !t.caseId && !t.description) {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
} else {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(t));
|
||||
}
|
||||
}
|
||||
|
||||
function computeElapsed(t: PersistedTimer | null): number {
|
||||
if (!t) return 0;
|
||||
function computeElapsed(t: PersistedTimer): number {
|
||||
return t.accumulatedMs + (t.runningSince ? Date.now() - t.runningSince : 0);
|
||||
}
|
||||
|
||||
export function TimerProvider({ children }: { children: ReactNode }) {
|
||||
const [active, setActive] = useState<PersistedTimer | null>(null);
|
||||
const [timer, setTimer] = useState<PersistedTimer>(empty);
|
||||
const [elapsedMs, setElapsedMs] = useState(0);
|
||||
const intervalRef = useRef<number | null>(null);
|
||||
|
||||
// Hydrate from localStorage on mount
|
||||
useEffect(() => {
|
||||
const t = read();
|
||||
if (t) {
|
||||
setActive(t);
|
||||
setElapsedMs(computeElapsed(t));
|
||||
}
|
||||
setTimer(t);
|
||||
setElapsedMs(computeElapsed(t));
|
||||
}, []);
|
||||
|
||||
// Tick every second when running
|
||||
useEffect(() => {
|
||||
if (intervalRef.current) {
|
||||
clearInterval(intervalRef.current);
|
||||
intervalRef.current = null;
|
||||
}
|
||||
if (active?.runningSince) {
|
||||
if (timer.runningSince) {
|
||||
intervalRef.current = window.setInterval(() => {
|
||||
setElapsedMs(computeElapsed(active));
|
||||
setElapsedMs(computeElapsed(timer));
|
||||
}, 1000);
|
||||
}
|
||||
return () => {
|
||||
if (intervalRef.current) clearInterval(intervalRef.current);
|
||||
};
|
||||
}, [active]);
|
||||
}, [timer]);
|
||||
|
||||
// Cross-tab sync
|
||||
useEffect(() => {
|
||||
const onStorage = (e: StorageEvent) => {
|
||||
if (e.key !== STORAGE_KEY) return;
|
||||
const t = read();
|
||||
setActive(t);
|
||||
setTimer(t);
|
||||
setElapsedMs(computeElapsed(t));
|
||||
};
|
||||
window.addEventListener("storage", onStorage);
|
||||
return () => window.removeEventListener("storage", onStorage);
|
||||
}, []);
|
||||
|
||||
const persist = (t: PersistedTimer | null) => {
|
||||
const persist = (t: PersistedTimer) => {
|
||||
write(t);
|
||||
setActive(t);
|
||||
setTimer(t);
|
||||
setElapsedMs(computeElapsed(t));
|
||||
};
|
||||
|
||||
const start: TimerState["start"] = (target, description = "") => {
|
||||
const t: PersistedTimer = {
|
||||
...target,
|
||||
accumulatedMs: 0,
|
||||
const setClient = (clientId: string | null) =>
|
||||
persist({ ...timer, clientId, caseId: clientId === timer.clientId ? timer.caseId : null });
|
||||
const setCase = (caseId: string | null) => persist({ ...timer, caseId });
|
||||
const setDescription = (description: string) => persist({ ...timer, description });
|
||||
|
||||
const start = () => {
|
||||
if (timer.runningSince) return;
|
||||
persist({
|
||||
...timer,
|
||||
runningSince: Date.now(),
|
||||
description,
|
||||
startedAt: new Date().toISOString(),
|
||||
};
|
||||
persist(t);
|
||||
startedAt: timer.startedAt ?? new Date().toISOString(),
|
||||
});
|
||||
};
|
||||
|
||||
const pause = () => {
|
||||
if (!active?.runningSince) return;
|
||||
const accumulatedMs = active.accumulatedMs + (Date.now() - active.runningSince);
|
||||
persist({ ...active, accumulatedMs, runningSince: null });
|
||||
if (!timer.runningSince) return;
|
||||
const accumulatedMs = timer.accumulatedMs + (Date.now() - timer.runningSince);
|
||||
persist({ ...timer, accumulatedMs, runningSince: null });
|
||||
};
|
||||
|
||||
const resume = () => {
|
||||
if (!active || active.runningSince) return;
|
||||
persist({ ...active, runningSince: Date.now() });
|
||||
if (timer.runningSince) return;
|
||||
persist({ ...timer, runningSince: Date.now() });
|
||||
};
|
||||
|
||||
const reset = () => persist(null);
|
||||
const reset = () => persist(empty);
|
||||
|
||||
const setDescription = (description: string) => {
|
||||
if (!active) return;
|
||||
persist({ ...active, description });
|
||||
};
|
||||
|
||||
const stopAndConsume: TimerState["stopAndConsume"] = () => {
|
||||
if (!active) return null;
|
||||
const ms = computeElapsed(active);
|
||||
const hours = Math.max(0.01, Math.round((ms / 3600000) * 100) / 100);
|
||||
const result = {
|
||||
hours,
|
||||
description: active.description,
|
||||
target: {
|
||||
clientId: active.clientId,
|
||||
clientName: active.clientName,
|
||||
caseId: active.caseId,
|
||||
caseNumber: active.caseNumber,
|
||||
caseTitle: active.caseTitle,
|
||||
defaultHourlyRate: active.defaultHourlyRate,
|
||||
},
|
||||
startedAt: active.startedAt,
|
||||
};
|
||||
persist(null);
|
||||
return result;
|
||||
const consume = () => {
|
||||
const ms = computeElapsed(timer);
|
||||
// Round UP to the nearest 0.1 hour (6 minute / 360,000 ms increments).
|
||||
const increment = 6 * 60 * 1000;
|
||||
const rounded = Math.max(increment, Math.ceil(ms / increment) * increment);
|
||||
const hours = Math.round((rounded / 3600000) * 10) / 10;
|
||||
persist(empty);
|
||||
return { hours };
|
||||
};
|
||||
|
||||
return (
|
||||
<TimerContext.Provider
|
||||
value={{
|
||||
active,
|
||||
timer,
|
||||
elapsedMs,
|
||||
isRunning: !!active?.runningSince,
|
||||
isRunning: !!timer.runningSince,
|
||||
hasStarted: timer.accumulatedMs > 0 || !!timer.runningSince,
|
||||
setClient,
|
||||
setCase,
|
||||
setDescription,
|
||||
start,
|
||||
pause,
|
||||
resume,
|
||||
reset,
|
||||
setDescription,
|
||||
stopAndConsume,
|
||||
consume,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
@@ -187,3 +178,9 @@ export function formatHMS(ms: number): string {
|
||||
const s = total % 60;
|
||||
return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
/** Round hours UP to the nearest 0.1 (6-minute) increment, with 0.1 minimum. */
|
||||
export function roundToTenth(hours: number): number {
|
||||
if (!hours || hours <= 0) return 0;
|
||||
return Math.max(0.1, Math.round(Math.ceil(hours * 10)) / 10);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user