UNPKG

lexer-state

Version:

Lightweight state machine library to define and manage state transition declaratively

60 lines 2.31 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useLexerStates = exports.LexerStateProviders = exports.useLexerStateBase = void 0; const jsx_runtime_1 = require("react/jsx-runtime"); const react_1 = require("react"); 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); }, }; }; 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 LexerStateProviders = ({ children, machines, }) => { const factory = (0, react_1.useMemo)(() => { return contextFactory.create(machines); }, [machines]); const providers = machines.map((machine) => { const machineContext = factory.get(machine); return ((0, jsx_runtime_1.jsx)(SingleMahineProvider, { LexerStateContext: machineContext, machine: machine })); }, null); const ContextProvider = (0, util_1.compose)(providers); return (0, jsx_runtime_1.jsx)(ContextProvider, { children: children }); }; exports.LexerStateProviders = LexerStateProviders; const useLexerStates = (machine) => { const [currentState, dispatchEvent] = (0, react_1.useContext)(contextFactory.get(machine)); return { currentState: currentState, dispatchEvent: dispatchEvent, }; }; exports.useLexerStates = useLexerStates; //# sourceMappingURL=useLexerStates.js.map