From 77853e708cfbe9f0d626fb8aa948eefac96be0ad Mon Sep 17 00:00:00 2001 From: Thibault Duplessis Date: Wed, 30 Oct 2024 15:00:23 +0100 Subject: [PATCH] make common/pubsub a class so that multiple can be made no functional change intended (tm) --- ui/common/src/pubsub.ts | 59 +++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 31 deletions(-) diff --git a/ui/common/src/pubsub.ts b/ui/common/src/pubsub.ts index f257443f85d0..9021532f26e0 100644 --- a/ui/common/src/pubsub.ts +++ b/ui/common/src/pubsub.ts @@ -60,52 +60,49 @@ export type PubsubOneTimeEvent = 'dialog.polyfill' | 'socket.hasConnected'; export type PubsubCallback = (...data: any[]) => void; -export interface Pubsub { - on(msg: PubsubEvent, f: PubsubCallback): void; - off(msg: PubsubEvent, f: PubsubCallback): void; - emit(msg: PubsubEvent, ...args: any[]): void; +export class Pubsub { + private allSubs: Map void>> = new Map(); + private oneTimeEvents: Map = new Map(); - after(event: PubsubOneTimeEvent): Promise; - complete(event: PubsubOneTimeEvent): void; - past(event: PubsubOneTimeEvent): boolean; -} - -export const pubsub: Pubsub = { - on(name: PubsubEvent, cb) { - const subs = allSubs.get(name); + on(name: PubsubEvent, cb: PubsubCallback): void { + const subs = this.allSubs.get(name); if (subs) subs.add(cb); - else allSubs.set(name, new Set([cb])); - }, - off(name: PubsubEvent, cb) { - allSubs.get(name)?.delete(cb); - }, - emit(name: PubsubEvent, ...args: any[]) { - for (const fn of allSubs.get(name) || []) fn.apply(null, args); - }, + else this.allSubs.set(name, new Set([cb])); + } + + off(name: PubsubEvent, cb: PubsubCallback): void { + this.allSubs.get(name)?.delete(cb); + } + + emit(name: PubsubEvent, ...args: any[]): void { + for (const fn of this.allSubs.get(name) || []) fn.apply(null, args); + } + after(event: PubsubOneTimeEvent): Promise { - const found = oneTimeEvents.get(event); + const found = this.oneTimeEvents.get(event); if (found) return found.promise; const handler = {} as OneTimeHandler; handler.promise = new Promise(resolve => (handler!.resolve = resolve)); - oneTimeEvents.set(event, handler); + this.oneTimeEvents.set(event, handler); return handler.promise; - }, + } + complete(event: PubsubOneTimeEvent): void { - const found = oneTimeEvents.get(event); + const found = this.oneTimeEvents.get(event); if (found) { found.resolve?.(); found.resolve = undefined; - } else oneTimeEvents.set(event, { promise: Promise.resolve() }); - }, + } else this.oneTimeEvents.set(event, { promise: Promise.resolve() }); + } + past(event: PubsubOneTimeEvent): boolean { - return oneTimeEvents.has(event) && !oneTimeEvents.get(event)?.resolve; - }, -}; + return this.oneTimeEvents.has(event) && !this.oneTimeEvents.get(event)?.resolve; + } +} -const allSubs: Map void>> = new Map(); -const oneTimeEvents: Map = new Map(); +export const pubsub: Pubsub = new Pubsub(); interface OneTimeHandler { promise: Promise;