summaryrefslogtreecommitdiff
path: root/ui/lib/store/messages.js
blob: 62c567a40806baf84e6a6ccc5e9af25e1c598856 (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
export class Messages {
  constructor() {
    this.channels = {};
  }

  inChannel(channel) {
    return (this.channels[channel] = this.channels[channel] || []);
  }

  addMessage(channel, id, at, sender, body) {
    this.updateChannel(channel, (messages) => [...messages, { id, at, sender, body }]);
    return this;
  }

  setMessages(messages) {
    this.channels = {};
    for (let { channel, id, at, sender, body } of messages) {
      this.inChannel(channel).push({ id, at, sender, body });
    }
    return this;
  }

  deleteMessage(message) {
    for (let channel in this.channels) {
      this.updateChannel(channel, (messages) => messages.filter((msg) => msg.id != message));
    }
    return this;
  }

  deleteChannel(id) {
    delete this.channels[id];
    return this;
  }

  updateChannel(channel, callback) {
    let messages = callback(this.inChannel(channel));
    messages.sort((a, b) => a.at - b.at);
    this.channels[channel] = messages;
  }
}