1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
import { useState, useEffect, useRef, useCallback } from "react";
import { commands, type TimerState, type TickResult } from "../lib/commands";
import { playWorkDoneSound, playBreakDoneSound } from "../lib/sounds";
export function useTimer() {
const [timer, setTimer] = useState<TimerState | null>(null);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
// Load initial state
useEffect(() => {
commands.getState().then((snap) => setTimer(snap.timer));
}, []);
// 1-second tick interval when running
useEffect(() => {
if (timer?.is_running) {
intervalRef.current = setInterval(async () => {
const result: TickResult = await commands.tick();
if (result.event) {
if (result.timer.mode === "work") {
playBreakDoneSound(); // Break finished, wake up for work
} else {
playWorkDoneSound(); // Work finished, relax for break
}
}
setTimer(result.timer);
}, 1000);
} else {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
}
return () => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
};
}, [timer?.is_running]);
const refreshTimer = useCallback(async () => {
const snap = await commands.getState();
setTimer(snap.timer);
}, []);
const toggleRunning = useCallback(async () => {
await commands.toggleTimer();
await refreshTimer();
}, [refreshTimer]);
const reset = useCallback(async () => {
await commands.resetTimer();
await refreshTimer();
}, [refreshTimer]);
const skip = useCallback(async () => {
await commands.skipSession();
await refreshTimer();
}, [refreshTimer]);
const cycleMode = useCallback(async () => {
await commands.cycleMode();
await refreshTimer();
}, [refreshTimer]);
const toggleAutoSwitch = useCallback(async () => {
await commands.toggleAutoSwitch();
await refreshTimer();
}, [refreshTimer]);
const setDuration = useCallback(async (mins: number) => {
await commands.setDuration(mins);
await refreshTimer();
}, [refreshTimer]);
return {
timer,
toggleRunning,
reset,
skip,
cycleMode,
toggleAutoSwitch,
setDuration,
};
}
|