diff --git a/src/utils.ts b/src/utils.ts index 3bc5288..37a677b 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -16,3 +16,57 @@ export const rotateArray = (arr: T[], reverse = false): T[] => { else arr.push(arr.shift()!); return arr; }; + +type resolveCallback = (value: T) => void; +type rejectCallback = (reason?: unknown) => void; +export const newPromise = (): [ + Promise, + resolveCallback, + rejectCallback +] => { + let resolve: resolveCallback; + let reject: rejectCallback; + const promise = new Promise( + (res: resolveCallback, rej: rejectCallback) => { + resolve = res; + reject = rej; + } + ); + return [promise, resolve!, reject!]; +}; + +declare global { + interface Window { + alarmsMap?: Map, rejectCallback]>; + } +} + +//Clone of the https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/alarms +export namespace Alarms { + const getMap = () => { + window.alarmsMap ??= new Map(); + return window.alarmsMap; + }; + + export const create = (delay: number, name?: any) => { + const map = getMap(); + const alrm = map.get(name); + if (alrm) alrm[1](); + + const [promise, resolve, reject] = newPromise(); + const timeout = setTimeout(resolve, delay); + promise.catch(() => window.clearTimeout(timeout)); + + if (name != undefined) map.set(name, [promise, reject]); + return promise; + }; + + export const get = (name: any) => (getMap().get(name) ?? [])[0]; + export const getAll = () => Array.from(getMap().entries()).map((a) => a[0]); + + export const clear = (name: any) => { + const alrm = getMap().get(name); + if (alrm) alrm[1](); + }; + export const clearAll = () => getMap().forEach((a) => a[1]()); +}