import type { IObjectOf } from "@thi.ng/api" ; import { start } from "@thi.ng/hdom/start" ; import { EventBus , FX_DISPATCH_ASYNC , FX_DISPATCH_NOW , valueSetter , type , EffectDef , type , EventDef } from "@thi.ng/interceptors" ; const EV_SET_STATUS = "set-status" ; const EV_LOAD_JSON = "load-json" ; const EV_RECEIVE_JSON = "receive-json" ; const EV_ERROR = "error" ; const FX_JSON = "load-json" ; const FX_DELAY = "delay" ; const events = { [ EV_SET_STATUS ] : valueSetter ( "status" ) , [ EV_LOAD_JSON ] : ( _ , [ __ , url ] ) => ( { [ FX_DISPATCH_NOW ] : [ EV_SET_STATUS , [ "idle" , `loading: ${ url }...` ] ] , [ FX_DISPATCH_ASYNC ] : [ FX_JSON , url , EV_RECEIVE_JSON , EV_ERROR ] , } ) , [ EV_RECEIVE_JSON ] : [ valueSetter ( "json" , ( json ) => JSON . stringify ( json , null , 2 ) ) , ( ) => ( { [ FX_DISPATCH_NOW ] : [ EV_SET_STATUS , [ "success" , "JSON successfully loaded" ] , ] , [ FX_DISPATCH_ASYNC ] : [ FX_DELAY , [ 1000 , [ "idle" , "done." ] ] , EV_SET_STATUS , EV_ERROR , ] , } ) , ] , [ EV_ERROR ] : ( _ , [ __ , err ] ) => ( { [ FX_DISPATCH_NOW ] : [ EV_SET_STATUS , [ "error" , err . message ] ] , } ) , } ; const effects = { [ FX_JSON ] : ( url ) => fetch ( url ) . then ( ( res ) => res . json ( ) ) , [ FX_DELAY ] : ( [ x , msg ] ) => new Promise ( ( res ) => setTimeout ( ( ) => res ( msg ) , x ) ) , } ; const app = ( ) => { const bus = new EventBus ( null , events , effects ) ; bus . dispatch ( [ EV_LOAD_JSON , "data/foo.json" ] ) ; return ( ) => { if ( bus . processQueue ( ) ) { const { json , status } = bus . deref ( ) ; return [ "div" , [ "p#status" , { class : status [ 0 ] } , `status: ${ status [ 1 ] }` ] , [ "pre" , json ] , ] ; } } ; } ; start ( app ( ) ) ;