import { DATASTAR } from '~/engine/consts' export const DATASTAR_SSE_EVENT = `${DATASTAR}-sse` export const SETTLING_CLASS = `${DATASTAR}-settling` export const SWAPPING_CLASS = `${DATASTAR}-swapping` export const STARTED = 'started' export const FINISHED = 'finished' export const ERROR = 'error' export interface DatastarSSEEvent { type: string argsRaw: Record } export interface CustomEventMap { 'datastar-sse': CustomEvent } export type WatcherFn = ( this: Document, ev: CustomEventMap[K], ) => void declare global { interface Document { //adds definition to Document, but you can do the same with HTMLElement addEventListener( type: K, listener: WatcherFn, ): void removeEventListener( type: K, listener: WatcherFn, ): void dispatchEvent(ev: CustomEventMap[K]): void } } export function datastarSSEEventWatcher( // ctx: InitContext, eventType: string, fn: (argsRaw: Record) => void, ) { document.addEventListener( DATASTAR_SSE_EVENT, (event: CustomEvent) => { if (event.detail.type !== eventType) return const { argsRaw } = event.detail fn(argsRaw) }, ) }