import type { Fn } from "@thi.ng/api" ; import { setInManyUnsafe } from "@thi.ng/paths/set-in-many" ; import type { ISubscriber } from "@thi.ng/rstream" ; import { pubsub } from "@thi.ng/rstream/pubsub" ; import { stream } from "@thi.ng/rstream/stream" ; import { trace } from "@thi.ng/rstream/trace" ; import type { Transducer } from "@thi.ng/transducers" ; import { filter } from "@thi.ng/transducers/filter" ; import { type , Event , type , EventType , type , EventTypeMap , NEXT , PAGE_READY , PREV } from "./api" ; import { state } from "./state" ; /**
 * Event input stream (not exported)
 * All use code MUST use `dispatch()` function below.
 */ const events = stream < Event > ( ) ; events . subscribe ( trace ( "event:" ) ) ; /**
 * Event handler distribution construct. Attached to event stream and
 * will delegate to event ID based child subscriptions (the actual event
 * handlers).
 */ const eventProc = pubsub < Event , Event > ( { topic : ( x ) => x [ 0 ] } ) ; events . subscribe ( eventProc ) ; param e export const dispatch = ( e ) => events . next ( e ) ; param id param handler param xform export const defHandler = < E extends EventType > ( id , handler , xform ? ) => { const sub = { next : < Fn < Event , void > > handler , error : ( e ) => { console . warn ( e ) ; return false ; } , } ; return eventProc . subscribeTopic ( id , sub , { xform } ) ; } ; param offset const requestPage = ( offset ) => { const curr = state . deref ( ) ! ; curr . timeoutID !== undefined && clearTimeout ( curr . timeoutID ) ; const timeoutID = setTimeout ( ( ) => dispatch ( [ PAGE_READY ] ) , 250 ) ; state . next ( setInManyUnsafe ( curr , "nextPageID" , curr . pageID + offset , "timeoutID" , timeoutID , "isLoading" , true ) ) ; } ; defHandler ( PREV , ( [ _ , step ] ) => requestPage ( - step ! ) , filter ( ( [ _ , x ] ) => state . deref ( ) ! . pageID >= x ! ) ) ; defHandler ( NEXT , ( [ _ , step ] ) => requestPage ( step ! ) , filter ( ( [ _ , x ] ) => state . deref ( ) ! . pageID < 20 - x ! ) ) ; defHandler ( PAGE_READY , ( ) => { const curr = state . deref ( ) ! ; state . next ( setInManyUnsafe ( curr , "pageID" , curr . nextPageID , "isLoading" , false ) ) ; } ) ;