File size: 1,337 Bytes
794cf6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { writable } from "svelte/store";

interface LoadingState {
  isLoading: boolean;
  progress: number;
}

function createLoadingStore() {
  const { subscribe, set, update } = writable<LoadingState>({
    isLoading: true,
    progress: 0,
  });

  let progressInterval: number | null = null;

  return {
    subscribe,
    setProgress: (progress: number) => {
      update((state) => ({
        ...state,
        progress: Math.min(100, Math.max(0, progress)),
      }));
    },
    startLoading: () => {
      set({ isLoading: true, progress: 0 });

      let currentProgress = 0;
      progressInterval = window.setInterval(() => {
        currentProgress += Math.random() * 15;
        if (currentProgress >= 90) {
          if (progressInterval) {
            clearInterval(progressInterval);
            progressInterval = null;
          }
          currentProgress = 90;
        }
        update((state) => ({ ...state, progress: currentProgress }));
      }, 200);
    },
    finishLoading: () => {
      if (progressInterval) {
        clearInterval(progressInterval);
        progressInterval = null;
      }

      update((state) => ({ ...state, progress: 100 }));

      setTimeout(() => {
        set({ isLoading: false, progress: 100 });
      }, 300);
    },
  };
}

export const loadingStore = createLoadingStore();