summaryrefslogtreecommitdiff
path: root/src/hooks/useTimerEvents.ts
blob: 21422738e4957de7273bd7212b6b2c6e55443aa0 (plain)
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
import { useEffect, useRef } from 'react';
import { listen } from '@tauri-apps/api/event';
import { useTimerStore, TimerTickPayload } from '../store/timerStore';
import { useTaskStore } from '../store/taskStore';

interface PhaseChangedPayload {
  phase: TimerTickPayload['phase'];
  session_count: number;
}

interface CompletedPayload {
  task_id: string | null;
}

export function useTimerEvents(
  onCompleted: (taskId: string | null) => void,
) {
  const syncFromBackend = useTimerStore((s) => s.syncFromBackend);
  const setRunning = useTimerStore((s) => s.setRunning);
  const fetchTasks = useTaskStore((s) => s.fetchTasks);

  const onCompletedRef = useRef(onCompleted);
  useEffect(() => {
    onCompletedRef.current = onCompleted;
  }, [onCompleted]);

  useEffect(() => {
    let cancelled = false;
    let unlisteners: Array<() => void> = [];

    async function setup() {
      // Register all listeners atomically
      try {
        const [unlistenTick, unlistenCompleted, unlistenPhaseChanged] = await Promise.all([
          listen<TimerTickPayload>('timer-tick', (event) => {
            useTimerStore.setState({
              phase: event.payload.phase,
              remainingSecs: event.payload.remaining_secs,
              totalSecs: event.payload.total_secs,
              running: true,
              sessionCount: event.payload.session_count,
              currentTaskId: event.payload.current_task_id,
            });
          }),
          listen<CompletedPayload>('timer-completed', async (event) => {
            setRunning(false);
            onCompletedRef.current(event.payload.task_id ?? null);
            await fetchTasks();
            await syncFromBackend();
          }),
          listen<PhaseChangedPayload>('timer-phase-changed', async (_event) => {
            try {
              await syncFromBackend();
            } catch (e) {
              console.error('Failed to re-sync timer status:', e);
            }
          }),
        ]);

        if (cancelled) {
          unlistenTick();
          unlistenCompleted();
          unlistenPhaseChanged();
          return;
        }

        unlisteners = [unlistenTick, unlistenCompleted, unlistenPhaseChanged];

        try {
          await syncFromBackend();
        } catch (e) {
          console.error('Failed to get timer status:', e);
        }
      } catch (e) {
        console.error('Failed to register timer listeners:', e);
      }
    }

    setup();

    return () => {
      cancelled = true;
      unlisteners.forEach((fn) => fn());
    };
  }, [syncFromBackend, setRunning, fetchTasks]); // onCompleted excluded — updated via ref
}