aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/packages/ui/src/stores/download-store.ts
blob: ccaf75acccb1ea5c99ff2f033919b434c048f709 (plain) (blame)
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { create } from "zustand";
import type { ProgressEvent } from "@/types";

export type DownloadPhase =
  | "idle"
  | "preparing"
  | "downloading"
  | "finalizing"
  | "installing-mod-loader"
  | "completed"
  | "error";

export interface DownloadState {
  /** Whether a download session is active */
  phase: DownloadPhase;

  /** Total number of files to download */
  totalFiles: number;
  /** Number of files completed */
  completedFiles: number;

  /** Current file being downloaded */
  currentFile: string;
  /** Current file status */
  currentFileStatus: string;

  /** Bytes downloaded for current file */
  currentFileDownloaded: number;
  /** Total bytes for current file */
  currentFileTotal: number;

  /** Total bytes downloaded across all files */
  totalDownloadedBytes: number;

  /** Error message if any */
  errorMessage: string | null;

  /** Phase label for display (e.g. "Installing Fabric...") */
  phaseLabel: string;

  // Actions
  init: () => Promise<void>;
  cleanup: () => void;
  reset: () => void;
  setPhase: (phase: DownloadPhase, label?: string) => void;
  setError: (message: string) => void;
}

let unlisteners: UnlistenFn[] = [];
let initialized = false;

// Throttle progress updates to avoid excessive re-renders.
// We buffer the latest event and flush on a timer.
let progressTimer: ReturnType<typeof setTimeout> | null = null;
let pendingProgress: ProgressEvent | null = null;
const PROGRESS_INTERVAL_MS = 50; // ~20 fps

export const useDownloadStore = create<DownloadState>((set, get) => ({
  phase: "idle",
  totalFiles: 0,
  completedFiles: 0,
  currentFile: "",
  currentFileStatus: "",
  currentFileDownloaded: 0,
  currentFileTotal: 0,
  totalDownloadedBytes: 0,
  errorMessage: null,
  phaseLabel: "",

  init: async () => {
    if (initialized) return;
    initialized = true;

    const flushProgress = () => {
      const p = pendingProgress;
      if (!p) return;
      pendingProgress = null;
      set({
        currentFile: p.file,
        currentFileStatus: p.status,
        currentFileDownloaded: Number(p.downloaded),
        currentFileTotal: Number(p.total),
        completedFiles: p.completedFiles,
        totalFiles: p.totalFiles,
        totalDownloadedBytes: Number(p.totalDownloadedBytes),
      });
    };

    const unlistenStart = await listen<number>("download-start", (e) => {
      set({
        phase: "downloading",
        totalFiles: e.payload,
        completedFiles: 0,
        currentFile: "",
        currentFileStatus: "",
        currentFileDownloaded: 0,
        currentFileTotal: 0,
        totalDownloadedBytes: 0,
        errorMessage: null,
        phaseLabel: "Downloading files...",
      });
    });

    const unlistenProgress = await listen<ProgressEvent>(
      "download-progress",
      (e) => {
        pendingProgress = e.payload;
        if (!progressTimer) {
          progressTimer = setTimeout(() => {
            progressTimer = null;
            flushProgress();
          }, PROGRESS_INTERVAL_MS);
        }
      },
    );

    const unlistenComplete = await listen("download-complete", () => {
      // Flush any pending progress before transitioning
      if (progressTimer) {
        clearTimeout(progressTimer);
        progressTimer = null;
      }
      if (pendingProgress) {
        const p = pendingProgress;
        pendingProgress = null;
        set({
          currentFile: p.file,
          currentFileStatus: p.status,
          currentFileDownloaded: Number(p.downloaded),
          currentFileTotal: Number(p.total),
          completedFiles: p.completedFiles,
          totalFiles: p.totalFiles,
          totalDownloadedBytes: Number(p.totalDownloadedBytes),
        });
      }

      const { phase } = get();
      // Downloads finished; move to finalizing while we wait for the
      // install command to return and the caller to set the next phase.
      if (phase === "downloading") {
        set({
          phase: "finalizing",
          phaseLabel: "Finalizing installation...",
        });
      }
    });

    unlisteners = [unlistenStart, unlistenProgress, unlistenComplete];
  },

  cleanup: () => {
    if (progressTimer) {
      clearTimeout(progressTimer);
      progressTimer = null;
    }
    pendingProgress = null;
    for (const unlisten of unlisteners) {
      unlisten();
    }
    unlisteners = [];
    initialized = false;
    // Reset state on cleanup to avoid residual state
    set({
      phase: "idle",
      totalFiles: 0,
      completedFiles: 0,
      currentFile: "",
      currentFileStatus: "",
      currentFileDownloaded: 0,
      currentFileTotal: 0,
      totalDownloadedBytes: 0,
      errorMessage: null,
      phaseLabel: "",
    });
  },

  reset: () => {
    set({
      phase: "idle",
      totalFiles: 0,
      completedFiles: 0,
      currentFile: "",
      currentFileStatus: "",
      currentFileDownloaded: 0,
      currentFileTotal: 0,
      totalDownloadedBytes: 0,
      errorMessage: null,
      phaseLabel: "",
    });
  },

  setPhase: (phase, label) => {
    set({
      phase,
      phaseLabel: label ?? "",
    });
  },

  setError: (message) => {
    set({
      phase: "error",
      errorMessage: message,
      phaseLabel: "Error",
    });
  },
}));