summaryrefslogtreecommitdiff
path: root/ui/lib/state/remote/state.svelte.js
blob: 6cbe1248e4299008a1ffe168c0d6fa12a292c8db (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { Users } from './users.svelte.js';
import { Channels } from './channels.svelte.js';
import { Messages } from './messages.svelte.js';

export class State {
  currentUser = $state();
  users = $state();
  channels = $state();
  messages = $state();

  static boot({ currentUser, users, channels, messages, resumePoint }) {
    return new State({
      currentUser,
      users: Users.boot(users),
      channels: Channels.boot(channels),
      messages: Messages.boot(messages),
      resumePoint
    });
  }

  constructor({ currentUser, users, channels, messages, resumePoint }) {
    this.currentUser = currentUser;
    this.users = users;
    this.channels = channels;
    this.messages = messages;
    this.resumePoint = resumePoint;
  }

  onEvent(event) {
    switch (event.type) {
      case 'channel':
        return this.onChannelEvent(event);
      case 'user':
        return this.onUserEvent(event);
      case 'message':
        return this.onMessageEvent(event);
    }
  }

  onChannelEvent(event) {
    switch (event.event) {
      case 'created':
        return this.onChannelCreated(event);
      case 'deleted':
        return this.onChannelDeleted(event);
    }
  }

  onChannelCreated(event) {
    const { id, name } = event;
    this.channels.add({ id, name });
  }

  onChannelDeleted(event) {
    const { id } = event;
    this.channels.remove(id);
  }

  onUserEvent(event) {
    switch (event.event) {
      case 'created':
        return this.onUserCreated(event);
    }
  }

  onUserCreated(event) {
    const { id, name } = event;
    this.users.add({ id, name });
  }

  onMessageEvent(event) {
    switch (event.event) {
      case 'sent':
        return this.onMessageSent(event);
      case 'deleted':
        return this.onMessageDeleted(event);
    }
  }

  onMessageSent(event) {
    const { id, at, channel, sender, body } = event;
    this.messages.add({ id, at, channel, sender, body });
  }

  onMessageDeleted(event) {
    const { id } = event;
    this.messages.remove(id);
  }
}