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