summaryrefslogtreecommitdiff
path: root/ui/lib/store/channels.svelte.js
blob: c82f9aae8cefbf6a47f15e338ede2e09ffa5090a (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
import { DateTime } from 'luxon';
const EPOCH_STRING = '1970-01-01T00:00:00Z';

// For reasons unclear to me, a straight up class definition with a constructor
// doesn't seem to work, reactively. So we resort to this.
// Owen suggests that this sentence in the Svelte docs should make the reason
// clear:
// > If $state is used with an array or a simple object, the result is a deeply
// > reactive state proxy.
// Emphasis on "simple object".
// --Kit
function makeChannelObject({ id, name, draft = '', lastReadAt = null, scrollPosition = null }) {
  return {
    id,
    name,
    lastReadAt: lastReadAt || DateTime.fromISO(EPOCH_STRING),
    draft,
    scrollPosition
  };
}

export class Channels {
  channels = $state([]);

  getChannel(channelId) {
    return this.channels.filter((ch) => ch.id === channelId)[0] || null;
  }

  setChannels(channels) {
    this.channels = channels.map(makeChannelObject);
    this.sort();
    return this;
  }

  addChannel(id, name) {
    this.channels = [...this.channels, makeChannelObject({ id, name })];
    this.sort();
    return this;
  }

  deleteChannel(id) {
    const channelIndex = this.channels.map((e) => e.id).indexOf(id);
    if (channelIndex !== -1) {
      this.channels.splice(channelIndex, 1);
    }
    return this;
  }

  sort() {
    this.channels.sort((a, b) => {
      if (a.name < b.name) {
        return -1;
      } else if (a.name > b.name) {
        return 1;
      }
      return 0;
    });
  }
}