summaryrefslogtreecommitdiff
path: root/ui/lib/state/remote/messages.svelte.js
blob: 576a74eef6753c26487cb7703244fcbcd4cd9dcf (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
import { DateTime } from 'luxon';
import { render } from '$lib/markdown.js';

class Message {
  static boot({ id, at, channel, sender, body }) {
    return new Message({
      id,
      at: DateTime.fromISO(at),
      channel,
      sender,
      body,
      renderedBody: render(body)
    });
  }

  constructor({ id, at, channel, sender, body, renderedBody }) {
    this.id = id;
    this.at = at;
    this.channel = channel;
    this.sender = sender;
    this.body = body;
    this.renderedBody = renderedBody;
  }

  resolve(get) {
    const { sender, ...rest } = this;
    return new Message({ sender: get.sender(sender), ...rest });
  }
}

export class Messages {
  all = $state([]);

  static boot(messages) {
    const all = messages.map(Message.boot);
    return new Messages({ all });
  }

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

  add({ id, at, channel, sender, body }) {
    const message = Message.boot({ id, at, channel, sender, body });
    this.all.push(message);
  }

  remove(id) {
    const index = this.all.findIndex((message) => message.id === id);
    this.all.splice(index, 1);
  }
}