import { call } from 'redux-saga/effects' ; import { PlayerInstant } from "./index" ; import { ReplayContext } from "./sagas" ; import { Bundle } from "../linker" ; export interface ReplayApi { on : ( keys : string [ ] | string , saga : any ) => void ; applyEvent : any ; onReset : ( saga : ( instant : PlayerInstant , quick ? : boolean ) => void ) => void ; reset : any ; } export default function ( bundle ) { const eventHandlers = new Map ( ) ; const resetSagas = [ ] ; const replayApi = { on : function ( keys , saga ) { if ( typeof keys === 'string' ) { keys = [ keys ] ; } for ( let key of keys ) { let sagas ; if ( eventHandlers . has ( key ) ) { sagas = eventHandlers . get ( key ) ; } else { sagas = [ ] ; eventHandlers . set ( key , sagas ) ; } sagas . push ( saga ) ; } } , applyEvent : function * ( key , replayContext , event ) { if ( eventHandlers . has ( key ) ) { const funcs = eventHandlers . get ( key ) ; for ( let func of funcs ) { yield call ( func , replayContext , event ) ; } } else { console . log ( `event ${ key } ignored (no replay handler)` ) ; } } , onReset : function ( saga ) : void { resetSagas . push ( saga ) ; } , reset : function * ( instant , quick ? ) { console . log ( 'RESET INSTANT' , instant . state ) ; for ( let saga of resetSagas ) { yield call ( saga , instant , quick ) ; } } } ; bundle . defineValue ( 'replayApi' , replayApi ) ; }