summaryrefslogtreecommitdiff
path: root/ui/lib/store/channels.svelte.js
diff options
context:
space:
mode:
authorKit La Touche <kit@transneptune.net>2024-12-03 13:44:05 -0500
committerKit La Touche <kit@transneptune.net>2024-12-03 13:44:05 -0500
commitc6fbd21c27277dd76c4dbabf5f1bf24f58142a1a (patch)
tree94392c1cafc88e91b14ebbb5a1e39eb86df41bc8 /ui/lib/store/channels.svelte.js
parentd89d64a1bd71bbb0f545818794f574fc80046c0f (diff)
parent4e3ad13aca163e733724b205c250bdb67cc56c29 (diff)
Merge branch 'main' into wip/stylize
Diffstat (limited to 'ui/lib/store/channels.svelte.js')
-rw-r--r--ui/lib/store/channels.svelte.js62
1 files changed, 62 insertions, 0 deletions
diff --git a/ui/lib/store/channels.svelte.js b/ui/lib/store/channels.svelte.js
new file mode 100644
index 0000000..8919be0
--- /dev/null
+++ b/ui/lib/store/channels.svelte.js
@@ -0,0 +1,62 @@
+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;
+ });
+ }
+}