UNPKG

@zedux/machines

Version:

Simple native state machine implementation for Zedux atoms

42 lines (41 loc) 1.75 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MachineStore = void 0; const atoms_1 = require("@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()` */ class MachineStore extends atoms_1.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); } } exports.MachineStore = MachineStore;