waffle/frontend/src/stores.js

115 lines
2.8 KiB
JavaScript
Raw Normal View History

import { writable } from "svelte/store";
import gateway, { GatewayEventType } from "./gateway";
class Store {
constructor() {
this._handlers = [];
this._didInit = false;
}
_tryInit() {
if (!this._didInit && this._init) {
this._init();
this._didInit = true;
}
}
subscribe(handler) {
this._tryInit();
const newLength = this._handlers.push(handler);
const handlerIndex = newLength - 1;
handler(this._value);
return () => {
this._handlers.splice(handlerIndex, 1);
};
}
_dispatchUpdate() {
this._handlers.forEach(e => {
e(this._value);
});
}
}
class ChannelsStore extends Store {
constructor() {
super();
this._value = [];
}
_init() {
const channels = gateway.channels;
if (channels) {
this._value = channels;
}
gateway.subscribe(GatewayEventType.Ready, ({ channels }) => {
if (channels) {
this._value = channels;
}
this._dispatchUpdate();
});
gateway.subscribe(GatewayEventType.ChannelCreate, (channel) => {
this._value.push(channel);
this._dispatchUpdate();
});
gateway.subscribe(GatewayEventType.ChannelDelete, ({ id }) => {
const index = this._value.findIndex(e => e.id === id);
if (!index)
return;
this._value.splice(index, 1);
this._dispatchUpdate();
});
gateway.subscribe(GatewayEventType.ChannelUpdate, (data) => {
const index = this._value.findIndex(e => e.id === data.id);
if (!index)
return;
if (!this._value[index])
return;
this._value[index] = data;
this._dispatchUpdate();
});
}
}
class GatewayStatusStore extends Store {
constructor() {
super();
this._value = { open: false, ready: false };
}
_init() {
this._value.open = gateway.open;
this._value.ready = gateway.authenticated;
gateway.subscribe(GatewayEventType.Open, () => {
this._value.open = true;
this._dispatchUpdate();
});
gateway.subscribe(GatewayEventType.Close, () => {
this._value.open = false;
this._value.ready = false;
this._dispatchUpdate();
});
gateway.subscribe(GatewayEventType.Ready, () => {
this._value.ready = true;
this._dispatchUpdate();
});
}
}
export const channels = new ChannelsStore();
export const gatewayStatus = new GatewayStatusStore();
export const selectedChannel = writable({ id: -1, name: "none", creator_id: -1 });