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

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

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

	addMessages(channel, payloads) {
		this.updateChannel(channel, (messages) => [...messages, ...payloads]);
		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;
	}
}