import {InputState, derive, input, State, IfThen} from 'reactivestates'; import {debugLog} from "../../helpers/debug_output"; export class SwitchState { private readonly contextSwitch$: InputState = input(); public transition(context: StateName) { if (this.validTransition(context)) { debugLog(`Switching table context to ${context}`); this.contextSwitch$.putValue(context); } } public validTransition(to: StateName) { return (this.contextSwitch$.value !== to); } public reset(reason?: string) { debugLog('Resetting table context.'); this.contextSwitch$.clear(reason); } public doAndTransition(context: StateName, callback:() => PromiseLike) { this.reset('Clearing before transitioning to ' + context); const promise = callback(); promise.then(() => this.transition(context)); } public fireOnTransition(cb: State, ...context: StateName[]): State { return IfThen(this.contextSwitch$, s => context.indexOf(s) > -1, cb); } public fireOnStateChange(state: State, ...context: StateName[]): State { return derive(state, $ => $ .filter(() => this.contextSwitch$.hasValue() && context.indexOf(this.contextSwitch$.value!) > -1)) } }