waffle/frontend/src/stores.js

70 lines
1.7 KiB
JavaScript
Raw Normal View History

import gateway, { GatewayEventType } from "./gateway";
export const channels = {
_handlers: [],
_value: [],
_didInit: false,
subscribe(handler) {
this._init();
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);
});
},
_init() {
window.__WAFFLE_CHANNELS_STORE = this;
if (this._didInit)
return;
this._didInit = true;
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);
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();
});
}
};