summaryrefslogtreecommitdiff
path: root/ui/lib/outbox.svelte.js
blob: 0681f29dd87e6bd4aa1955a4f1f8759288695d07 (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
import * as api from './apiServer.js';
import * as md from './markdown.js';

class Message {
  constructor(channel, body) {
    this.channel = channel;
    this.body = body;
    this.renderedBody = md.render(body);
  }
}

export class Outbox {
  pending = $state([]);

  static empty() {
    return new Outbox([]);
  }

  constructor(pending) {
    this.pending = pending;
  }

  send(channel, body) {
    this.pending.push(new Message(channel, body));
    this.start();
  }

  start() {
    if (this.sending) {
      return;
    }
    // This is a promise transform primarily to keep the management of `this.sending` in one place,
    // rather than spreading it across multiple methods.
    this.sending = this.drain().finally(() => {
      this.sending = null;
    });
  }

  async drain() {
    while (this.pending.length > 0) {
      const { channel, body } = this.pending[0];

      await api.retry(() => api.postToChannel(channel, body));
      this.pending.shift();
    }
  }
}