🚧Note: Work is in progress to improve test coverage and documentation🚧
- Simple State Machine is a typescript library that aims to make coding state machines simple, type-safe and fun.
- If you are new to state machines, I would recommend to go through statecharts.dev. Its an amazing design pattern that helps developer to think about UI State problems with a new mental model.
- Core -
@simple-state-machine/core
- React -
@simple-state-machine/react
- A simplest state machine can be a "Light<>Dark" Mode toggling. On click of button is toggle from
light
todark
or vice versa. - State diagram looks something like this for it:
- Code for the above machine using the library looks like
import {createState, createEvents, createContext, MachineConfig, interpret} from 'simple-state-machine' const states = createStates('light', 'dark'); const events = createEvents('TOGGLE'); const context = createContext({}); const ThemeMachine = new MachineConfig(states, context, events); const {whenIn} = ThemeMachine whenIn('light').on('TOGGLE').moveTo('dark'); whenIn('dark').on('TOGGLE').moveTo('light'); const {send, subscribe, start} = interpret(ThemeMachine) // toggle on button click document.querySelector('.toggle-btn').addEventListener('click', () => send('TOGGLE')); // subscribe to updates machine.subscribe((state) => { document.body.className = state.value === 'light' ? 'light-mode' : 'dark-mode' }) // start the machine start()
- Enough talk, show me code:
- Toggle Theme Machine
- Throttling Machine in typescript
- Debounce Machine in React
- For
core
library API, please look into core API
- For anyone curious to understand these points
- Why ?
- How and Whats of implementation => coming soon!
MIT