Skip to content

akhil0001/simple-state-machine

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🚧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.

Packages

Quick glance

  • A simplest state machine can be a "Light<>Dark" Mode toggling. On click of button is toggle from light to dark or vice versa.
  • State diagram looks something like this for it: toggle-sm
  • 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: Edit toggle-theme-machine

Examples

API

  • For core library API, please look into core API

Why, How and What ?

  • For anyone curious to understand these points
    • Why ?
    • How and Whats of implementation => coming soon!

LICENSE

MIT