UNPKG

lexer-state

Version:

Lightweight state machine library to define and manage state transition declaratively

68 lines 2.67 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useLexerState = exports.LexerStateProvider = exports.useLexerStateBase = void 0; const jsx_runtime_1 = require("react/jsx-runtime"); const react_1 = require("react"); const errors_1 = require("../errors"); const util_1 = require("../util"); const useLexerStateBase = (machine) => { const [currentState, setCurrentState] = (0, react_1.useState)(machine.currentState); return { currentState, dispatchEvent(e) { setCurrentState(machine.next(e)); }, }; }; exports.useLexerStateBase = useLexerStateBase; const createLexerStateContext = () => (0, react_1.createContext)([ { currentState: null }, () => null, ]); const createContextFactory = () => { const map = new Map(); return { create(machines) { for (const machine of machines) { map.set(machine, createLexerStateContext()); } return this; }, get(mahine) { return map.get(mahine); }, size() { return map.size; }, }; }; const contextFactory = createContextFactory(); const SingleMahineProvider = ({ LexerStateContext, machine, children, }) => { const { currentState, dispatchEvent } = (0, exports.useLexerStateBase)(machine); return ((0, jsx_runtime_1.jsx)(LexerStateContext.Provider, { value: [currentState, dispatchEvent], children: children })); }; const LexerStateProvider = ({ children, machines = [], machine, }) => { if (!machine && !Array.isArray(machines)) throw new errors_1.MachineNotFoundError(); const allMachines = (0, react_1.useMemo)(() => (machine ? [...machines, machine] : machines), [machine, machines]); const factory = (0, react_1.useMemo)(() => { return contextFactory.create(allMachines); }, [allMachines]); const providers = allMachines.map((machine) => { const machineContext = factory.get(machine); return ((0, jsx_runtime_1.jsx)(SingleMahineProvider, { LexerStateContext: machineContext, machine: machine })); }); return ((0, jsx_runtime_1.jsx)(util_1.ComposedProviders, { providers: providers, children: children })); }; exports.LexerStateProvider = LexerStateProvider; const useLexerState = (machine) => { if (!machine) throw new errors_1.LexerStateHookError(); const [currentState, dispatchEvent] = (0, react_1.useContext)(contextFactory.get(machine)); return { currentState: currentState, dispatchEvent: dispatchEvent, }; }; exports.useLexerState = useLexerState; //# sourceMappingURL=useLexerState.js.map