summaryrefslogtreecommitdiff
path: root/src/hooks/useTimerEvents.ts
blob: aebc7800c0375a5fd7e2c24083549f0851aac309 (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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import { useEffect, useRef } from 'react';
import { listen } from '@tauri-apps/api/event';
import { invoke } from '@tauri-apps/api/core';
import { useTimerStore, TimerTickPayload } from '../store/timerStore';
import { useTaskStore } from '../store/taskStore';

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

interface TimerStatus {
  phase: 'work' | 'short_break' | 'long_break';
  remaining_secs: number;
  total_secs: number;
  running: boolean;
  session_count: number;
  current_task_id: string | null;
}

interface CompletedPayload {
  task_id: string | null;
}

export function useTimerEvents(
  onCompleted: (taskId: string | null) => void,
) {
  const setTimerTick = useTimerStore((s) => s.setTimerTick);
  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() {
      // Bootstrap initial state from backend
      try {
        const status = await invoke<TimerStatus>('get_timer_status');
        if (cancelled) return;
        setTimerTick({
          phase: status.phase,
          remaining_secs: status.remaining_secs,
          total_secs: status.total_secs,
          session_count: status.session_count,
          current_task_id: status.current_task_id,
        });
        setRunning(status.running);
      } catch (e) {
        console.error('Failed to get timer status:', e);
      }

      if (cancelled) return;

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

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

        unlisteners = [unlistenTick, unlistenCompleted, unlistenPhaseChanged];
      } catch (e) {
        console.error('Failed to register timer listeners:', e);
      }
    }

    setup();

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