summaryrefslogtreecommitdiff
path: root/ui/lib/store/messages.js
blob: 931b8fb1c7c4e81dfb701b7597bd8c1d3f5bbc9f (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
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, });
		}
		for (let channel in this.channels) {
			this.channels[channel].sort((a, b) => a.at - b.at);
		}
		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;
	}
}