UNPKG

@zedux/machines

Version:

Simple native state machine implementation for Zedux atoms

38 lines (37 loc) 1.61 kB
import { Store } from '@zedux/atoms'; /** * An extremely low-level Store class that represents a state machine. Don't * create this class yourself, use a helper such as @zedux/machine's * `injectMachineStore()` */ export class MachineStore extends Store { constructor(initialState, states, initialContext, guard) { super(null, { context: initialContext, value: initialState, }); this.states = states; this.guard = guard; this.getContext = () => this.getState().context; this.getValue = () => this.getState().value; this.is = (stateName) => this.getState().value === stateName; this.send = (eventName, meta) => this.setState(currentState => { const nextValue = this.states[currentState.value][eventName]; if (!nextValue || (nextValue.guard && !nextValue.guard(currentState.context)) || (this.guard && !this.guard(currentState, nextValue.name))) { return currentState; } return { context: currentState.context, value: nextValue.name }; }, meta); this.setContext = (context, meta) => this.setState(state => ({ context: typeof context === 'function' ? context(state.context) : context, value: state.value, }), meta); this.setContextDeep = (partialContext, meta) => this.setStateDeep(state => ({ context: typeof partialContext === 'function' ? partialContext(state.context) : partialContext, }), meta); } }