summaryrefslogtreecommitdiffhomepage
path: root/frontend/src/modules/task/index.ts
blob: 7e2687c5758756f356f5bbfeecaeabaf1ac7760e (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
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
import { LOG } from "@/utilities/console";
import {
  hideNotification,
  showNotification,
  updateNotification,
} from "@mantine/notifications";
import { uniqueId } from "lodash";
import { notification } from "./notification";

class TaskDispatcher {
  private running: boolean;
  private tasks: Record<string, Task.Callable[]> = {};
  private progress: Record<string, Site.Progress> = {};

  constructor() {
    this.running = false;
    this.tasks = {};
    this.progress = {};

    window.addEventListener("beforeunload", this.onBeforeUnload.bind(this));
  }

  private onBeforeUnload(e: BeforeUnloadEvent) {
    const message = "Background tasks are still running";

    if (Object.keys(this.tasks).length > 0) {
      e.preventDefault();
      e.returnValue = message;
      return;
    }
    delete e["returnValue"];
  }

  private update() {
    if (this.running) {
      return;
    }

    LOG("info", "Starting background task queue");

    this.running = true;

    const queue = window.queueMicrotask?.bind(window) ?? setTimeout;

    queue(async () => {
      while (Object.keys(this.tasks).length > 0) {
        const groups = Object.keys(this.tasks);

        for await (const group of groups) {
          const tasks = this.tasks[group];

          const taskId = group;

          for (let index = 0; index < tasks.length; index++) {
            const task = tasks[index];

            const notifyInProgress = notification.progress.update(
              taskId,
              group,
              task.description,
              index,
              tasks.length
            );
            updateNotification(notifyInProgress);

            try {
              await task(...task.parameters);
            } catch (error) {
              // TODO
            }
          }

          const notifyEnd = notification.progress.end(taskId, group);
          updateNotification(notifyEnd);

          delete this.tasks[group];
        }
      }
      this.running = false;
    });
  }

  public create<T extends Task.AnyCallable>(
    name: string,
    group: string,
    callable: T,
    ...parameters: Parameters<T>
  ): Task.Ref {
    // Clone this function
    const task = callable.bind({}) as Task.Callable<T>;
    task.parameters = parameters;
    task.description = name;
    task.id = uniqueId("task");

    if (this.tasks[group] === undefined) {
      this.tasks[group] = [];
      const notifyStart = notification.progress.pending(group, group);
      showNotification(notifyStart);
    }

    this.tasks[group].push(task);

    this.update();

    return task.id;
  }

  public updateProgress(items: Site.Progress[]) {
    items.forEach((item) => {
      // TODO: FIX ME!
      item.value += 1;

      if (item.value >= item.count && this.progress[item.id] !== undefined) {
        updateNotification(notification.progress.end(item.id, item.header));
        delete this.progress[item.id];
      } else if (item.value > 1 && this.progress[item.id] !== undefined) {
        updateNotification(
          notification.progress.update(
            item.id,
            item.header,
            item.name,
            item.value,
            item.count
          )
        );
      } else {
        showNotification(notification.progress.pending(item.id, item.header));
        this.progress[item.id] = item;
      }
    });
  }

  public removeProgress(ids: string[]) {
    setTimeout(
      () => ids.forEach(hideNotification),
      notification.PROGRESS_TIMEOUT
    );
  }
}

export const task = new TaskDispatcher();
export * from "./group";
export * from "./notification";