All Projects β†’ theKashey β†’ Faste

theKashey / Faste

Licence: mit
Component based πŸ“¦ Finite State Machine Manager πŸ€–

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Faste

use-state-machine
Use Finite State Machines with React Hooks
Stars: ✭ 28 (-73.33%)
Mutual labels:  state-management, finite-state-machine
xstate
State machines and statecharts for the modern web.
Stars: ✭ 21,286 (+20172.38%)
Mutual labels:  state-management, finite-state-machine
Resumablefunctions.jl
C# style generators a.k.a. semi-coroutines for Julia.
Stars: ✭ 82 (-21.9%)
Mutual labels:  finite-state-machine
Homebase React
The React state management library for write-heavy applications
Stars: ✭ 101 (-3.81%)
Mutual labels:  state-management
Reactstatemuseum
A whirlwind tour of React state management systems by example
Stars: ✭ 1,294 (+1132.38%)
Mutual labels:  state-management
Behavior Tree
🌲 Manage React state with Behavior Trees
Stars: ✭ 85 (-19.05%)
Mutual labels:  state-management
Sigi
Well designed effect management framework for complex frontend app
Stars: ✭ 95 (-9.52%)
Mutual labels:  state-management
Compare React State Management
React createContext vs Apollo vs MobX vs Redux in a simple todo app.
Stars: ✭ 81 (-22.86%)
Mutual labels:  state-management
Store
Aurelia single state store based on RxJS
Stars: ✭ 103 (-1.9%)
Mutual labels:  state-management
Finity
A finite state machine library for Node.js and the browser with a friendly configuration DSL.
Stars: ✭ 88 (-16.19%)
Mutual labels:  finite-state-machine
Momentum
MVC pattern for flutter. Works as state management, dependency injection and service locator.
Stars: ✭ 99 (-5.71%)
Mutual labels:  state-management
Stapp
Modular state and side-effects management for microfrontends
Stars: ✭ 88 (-16.19%)
Mutual labels:  state-management
Freezer
A tree data structure that emits events on updates, even if the modification is triggered by one of the leaves, making it easier to think in a reactive way.
Stars: ✭ 1,268 (+1107.62%)
Mutual labels:  state-management
Redux Reset
Give redux the ability to reset the state
Stars: ✭ 95 (-9.52%)
Mutual labels:  state-management
Jstate
Advanced state machines in Java.
Stars: ✭ 84 (-20%)
Mutual labels:  finite-state-machine
Juicr.js
A simple (and tiny <1kb) redux inspired reducer for handling state changes.
Stars: ✭ 102 (-2.86%)
Mutual labels:  state-management
Iflow
Concise & powerful state management framework for Javascript.
Stars: ✭ 81 (-22.86%)
Mutual labels:  state-management
Vuex Pathify
Vue / Vuex plugin providing a unified path syntax to Vuex stores
Stars: ✭ 1,281 (+1120%)
Mutual labels:  state-management
Sismic
Sismic Interactive Statechart Model Interpreter and Checker http://sismic.readthedocs.org/
Stars: ✭ 92 (-12.38%)
Mutual labels:  finite-state-machine
Alexafsm
With alexafsm, developers can model dialog agents with first-class concepts such as states, attributes, transition, and actions. alexafsm also provides visualization and other tools to help understand, test, debug, and maintain complex FSM conversations.
Stars: ✭ 103 (-1.9%)
Mutual labels:  finite-state-machine

πŸ€– Faste πŸ’‘

TypeScript centric finite state block machine
faste

Build status Greenkeeper badge


no dependencies, less than 2kb

This is a Finite State Machine from SDL(Specification and Description Language) prospective. SDL defines state as a set of messages, it should react on, and the actions beneath.

Once state receives a message it executes an action, which could perform calculations and/or change the current state.

The goal is not to change the state, but - execute a bound action. From this prospective faste is closer to RxJX.

Usually "FSM" are more focused on state transitions, often even omitting any operations on message receive. In the Traffic Light example it could be useful, but in more real life examples - probably not.

Faste is more about when you will be able to do what. What you will do, when you receive event, and what you will do next.

Keeping in mind the best practices, like KISS and DRY, it is better to invert state->message->action connection, as long as actions are most complex part of it, and messages are usually reused across different states.

And, make things more common we will call "state" as a "phase", and "state" will be for "internal state".

The key idea is not about transition between states, but transition between behaviors. Keep in mind - if some handler is not defined in some state, and you are sending a message - it will be lost.

Written in TypeScript. To make things less flexible. Flow definitions as incomplete.

State machine

State machine starts in one phase, calls hooks for all messages for the current phase, then awaits for a messages from hooks or external customer, then could trigger a new message, emit signal to the outer world or change the current phase.

Faste is a black box - you can put message inside, and wait for a signal it will sent outside, meanwhile observing a box phase. BlackπŸ“¦ == Component🎁.

πŸ“– Read an article about FASTE, and when to use it.

Example

const light = faste()
    // define possible "phases" of a traffic light  
    .withPhases(['red', 'yellow', 'green'])
    // define possible transitions from one phase to another
    .withTransitions({
      green: ['yellow'],
      yellow: ['red'],
      red: ['green'],
    })
    // define possible events for a machine
    .withMessages(['switch'])
    .on('switch', ['green'], ({transitTo}) => transitTo('yellow'))
    .on('switch', ['yellow'], ({transitTo}) => transitTo('red'))
    .on('switch', ['red'], ({transitTo}) => transitTo('green'))
    // the following line would throw an error at _compile time_
    .on('switch', ['green'], ({transitTo}) => transitTo('red')) // this transition is blocked
    
    // block transition TO green if any pedestrian is on the road
    .guard(['green'], () => noPedestriansOnTheRoad)
    // block transition FROM red if any pedestrian is on the road 
    .trap(['red'], () => !noPedestriansOnTheRoad)  
    // PS: noPedestriansOnTheRoad could be read from attr, passed from a higher state machine. 

API

Machine blueprint

faste(options) - defines a new faste machine every faste instance provide next chainable commands

  • on(eventName, [phases], callback) - set a hook callback for eventName message in states states.

  • hooks(hooks) - set a hook when some message begins, or ends its presence.

  • guard(phases, callback) - add a transition guard, prevention transition to the phase

  • trap(phases, callback) - add a transition guard, prevention transition from the phase

In development mode, and for typed languages you could use next commands

  • withState(state) - set a initial state (use @init hook to derive state from props).

  • withPhases(phases) - limit phases to provided set.

  • withTransitions([phases]:[phases]) - limit phase transitions

  • withMessages(messages) - limit messages to provided set.

  • withAttrs(attributes) - limit attributes to provided set.

  • withSignals(signals) - limit signals to provided set.

  • check() - the final command to check state

  • create() - creates a machine (copies existing, use it instead of new).

All methods returns a faste constructor itself.

Machine instance

Each instance of Faste will have:

  • attrs(attrs) - set attributes.

  • put - put message in

  • connect - connects output to the destination

  • observe - observes phase changes

  • phase - returns the current phase

  • instance - returns the current internal state.

  • destroy - exits the current state, terminates all hooks, and stops machine.

  • namedBy(string) - sets name of the instance (for debug).

For all callbacks the first argument is flow instance, containing.

  • attrs - all the attrs, you cannot change them

  • state - internal state

  • setState - internal state change command

  • phase - current phase

  • transitTo - phase change command.

  • emit - emits a message to the outer world

Magic events

  • @init - on initialization
  • @enter - on phase enter, last phase will be passed as a second arg.
  • @leave - on phase enter, new phase will be passed as a second arg.
  • @change - on state change, old state will be passed as a second arg.
  • @miss - on event without handler.

Magic phases

  • @current - set the same phase as it was on the handler entry
  • @busy - set the busy phase, when no other handler could be called

Hooks

Hooks are not required, but then applied should come in a pair - on/off hook. Both hooks will receive flow as a first arg, and off will receive result of on as a second arg.

Hook took a place when message starts or ends it existance, ie entering or leaving phases if was defined in.

Event bus

  • message handler could change phase, state and trigger a new message
  • hook could change state or trigger a new message, but not change phase
  • external consumer could only trigger a new message

InternalState

Each on or hook handler will receive internalState as a first argument, with following shape

 attrs: { ...AttributesYouSet };  // attributes
 state: { ..CurrentState };       // state

 setState(newState);              // setState (as seen in React)

 transitTo(phase);                // move to a new phase

 emit(message, ...args);          // emit Signal to the outer world (connected) 

 trigger(event, ...args);         // trigger own message handler (dispatch an internal action) 

Debug

Debug mode is integrated into Faste.

import {setFasteDebug} from 'faste'
setFasteDebug(true);
setFasteDebug(true);
setFasteDebug((instance, message, args) => console.log(...));

Examples

Try online : https://codesandbox.io/s/n7kv9081xp

Using different handlers in different states

// common code - invert the flag
onClick = () => this.setState( state => ({ enabled: !state.enabled}));

// faste - use different flags for different states
faste()
 .on('click', 'disabled', ({transitTo}) => transitTo('enabled'))
 .on('click', 'enabled', ({transitTo}) => transitTo('disabled'))

React to state change

// common code - try to reverse engineer the change
componentDidUpdate(oldProps) {
  if (oldProps.enabled !== this.props.enabled) {
    if (this.props.enabled) {
      // I was enabled!
    } else {
      // I was disabled!
    }  
  }
}

// faste - use "magic" methods
faste()
 .on('@enter', 'disabled', () => /* i was disabled */)
 .on('@enter', 'enabled', () => /* i was enabled */)
 // bonus
 .on('@leave', 'disabled', () => /* i am no more disabled */)
 .on('@leave', 'enabled', () => /* i am no more enabled */)

Connected states

https://codesandbox.io/s/5zx8zl91ll

// starts a timer when active
const SignalSource = faste()
  .on("@enter", ["active"], ({ setState, attrs, emit }) =>
    setState({ interval: setInterval(() => emit("message"), attrs.duration) })
  )
  .on("@leave", ["active"], ({ state }) => clearInterval(state.interval));

// responds to "message" by moving from tick to tock
// emiting the current state outside
const TickState = faste()
  // autoinit to "tick" mode
  .on("@init", ({ transitTo }) => transitTo("tick"))
  // message handlers
  .on("message", ["tick"], ({ transitTo }) => transitTo("tock"))
  .on("message", ["tock"], ({ transitTo }) => transitTo("tick"))
  .on("@leave", ({ emit }, newPhase) => emit("currentState", newPhase));

// just transfer message to attached node
const DisplayState = faste().on(
  "currentState",
  ({ attrs }, message) => (attrs.node.innerHTML = message)
);

// create machines
const signalSource = SignalSource.create().attrs({
  duration: 1000
});
const tickState = TickState.create();
const displayState = DisplayState.create().attrs({
  node: document.querySelector(".display")
});

// direct connect signal source and ticker
signalSource.connect(tickState);

// "functionaly" connect tickes and display
tickState.connect((message, payload) => displayState.put(message, payload));

// RUN! start signal in active mode
signalSource.start("active");

Traffic light

const state = faste() 
 .withPhases(['red', 'yellow', 'green'])
 .withMessages(['tick','next'])
 
 .on('tick',['green'], ({transit}) => transit('yellow'))
 .on('tick',['yellow'], ({transit}) => transit('red'))
 .on('tick',['red'], ({transit}) => transit('green'))

  // on 'next' trigger 'tick' for a better debugging.
  // just rethrow event
 .on('next',[], ({trigger}) => trigger('tick'))
  
  // on "green" - start timer
 .on('@enter',['green'], ({setState, attrs, trigger}) => setState({ 
    interval: setInterval(() => trigger('next'), attrs.duration)
 }))
 // on "red" - stop timer
 .on('@leave',['red'], ({state}) => clearInterval(state.interval))
 
 
 .check();

state
  .create()
  .attrs({duration: 1000})
  .start('green');

Try online : https://codesandbox.io/s/n7kv9081xp

Draggable

const domHook = eventName => ({
  'on': ({attrs, trigger}) => {
    const callback = event => trigger(eventName, event);    
    attrs.node.addEventListener(eventName, callback);
    // "hook" could return anything, callback for example
    return callback;
  },
  'off': ({attrs}, hook /* result from 'on' callback */) => {          
      attrs.node.removeEventListener(eventName, hook);
    }
});

const state = faste({}) 
 .on('@enter', ['active'], ({emit}) => emit('start'))
 .on('@leave', ['active'], ({emit}) => emit('end'))
 
 .on('mousedown',['idle'], ({transitTo}) => transitTo('active'))
 .on('mousemove',['active'], (_, event) => emit('move',event))
 .on('mouseup', ['active'], ({transitTo}) => transitTo('idle'))
 
 hooks({
   'mousedown': domHook('mousedown'),
   'mousemove': domHook('mousemove'),
   'mouseup': domHook('mouseup'),
 })
 .check()

 .attr({node: document.body})
 .start('idle');

Async

Message handler doesn't have to be sync. But managing async commands could be hard. But will not

  1. Accept command only in initial state, then transit to temporal state to prevent other commands to be executes.
const Login = faste()
 .on('login', ['idle'], ({transitTo}, {userName, password}) => {
   transitTo('logging-in'); // just transit to "other" state  
   login(userName, password)
       .then( () => transitTo('logged'))
       .catch( () => transitTo('error'))
 });  
  1. Accept command only in initial state, then transit to execution state, and do the job on state enter
const Login = faste()
 .on('login', ['idle'], ({transitTo}, data) => transitTo('logging', data)
 .on('@enter', ['logging'], ({transitTo}, {userName, password}) => {                                 
  login(userName, password)
      .then( () => transitTo('logged'))
      .catch( () => transitTo('error'))
});  
  1. Always accept command, but be "busy" while doing stuff
const Login = faste()
 .on('login', ({transitTo}, {userName, password}) => {
   transitTo('@busy'); // we are "busy" 
   return login(userName, password)
       .then( () => transitTo('logged'))
       .catch( () => transitTo('error'))
 });  

handler returns Promise( could be async ) to indicate that ending in @busy state is not a mistake, and will not lead to deadlock.

By default @busy will queue messages, executing them after leaving busy phase. If want to ignore them - instead of @busy, you might use @locked phase, which will ignore them.

PS: You probably will never need those states.

SDL and Block

Faste was born from this. From Q.931(EDSS) state definition.

How it starts. What signals it accepts. What it does next.

U17

That is quite simple diagram.

Prior art

This library combines ideas from xstate and redux-saga. The original idea is based on xflow state machine, developed for CT Company's VoIP solutions back in 2005.

Licence

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].