Giter Site home page Giter Site logo

nanostate's Introduction

nanostate

npm version build status downloads js-standard-style

Small Finite State Machines. Great data structure to make code more readable, maintainable and easier to debug.

Usage

var nanostate = require('nanostate')

var machine = nanostate('green', {
  green: { timer: 'yellow' },
  yellow: { timer: 'red' },
  red: { timer: 'green' }
})

machine.emit('timer')
console.log(machine.state)
// => 'yellow'

machine.emit('timer')
console.log(machine.state)
// => 'red'

machine.emit('timer')
console.log(machine.state)
// => 'green'

Hierarchical

Let's implement a traffic light that flashes red whenever there's a power outage. Instead of adding a powerOutage event to each normal state, we introduce a hierarchy which allows any normal state to emit the powerOutage event to change the state to flashingRed.

var nanostate = require('nanostate')

var machine = nanostate('green', {
  green: { timer: 'yellow' },
  yellow: { timer: 'red' },
  red: { timer: 'green' }
})

machine.event('powerOutage', nanostate('flashingRed', {
  flashingRed: { powerRestored: 'green' }
}))

machine.emit('timer')
console.log(machine.state)
// => 'yellow'

machine.emit('powerOutage')
console.log(machine.state)
// => 'flashingRed'

machine.emit('powerRestored')
console.log(machine.state)
// => 'green'

History (to be implemented)

Implementers note: keep track of the last state a machine was in before exiting to the next machine. That way if '$history' is called, it can be merged into the previous machine.

TODO: figure out how it works if machines are combined in a non-linear fashion.

var nanostate = require('nanostate')

var machine = nanostate('cash', {
  cash: { check: 'check' },
  check: { cash: 'cash' }
})

machine.join('next', nanostate('review', {
  review: { previous: '$history' }
}))

Parallel

Sometimes there's multiple parallel states that need expressing; nanostate.parallel helps with that. For example when editing text, a particular piece of text might be bold, italic and underlined at the same time. The trick is that all of these states operate in parallel

var nanostate = require('nanostate')

var machine = nanostate.parallel({
  bold: nanostate('off', {
    on: { 'toggle': 'off' },
    off: { 'toggle': 'on' },
  }),
  underline: nanostate('off', {
    on: { 'toggle': 'off' },
    off: { 'toggle': 'on' },
  }),
  italics: nanostate('off', {
    on: { 'toggle': 'off' },
    off: { 'toggle': 'on' },
  }),
  list: nanostate('none', {
    none: { bullets: 'bullets', numbers: 'numbers' },
    bullets: { none: 'none', numbers: 'numbers' },
    numbers: { bullets: 'bullets', none: 'none' }
  })
})

machine.emit('bold:toggle')
console.log(machine.state)
// => {
//   bold: 'on',
//   italics: 'off',
//   underline: 'off',
//   list: 'none'
// }

Nanocomponent

Usage in combination with nanocomponent to create stateful UI components.

var Nanocomponent = require('nanocomponent')
var nanostate = require('nanostate')

module.exports = class Component extends Nanocomponent {
  constructor (name, state, emit) {
    super(name, state, emit)

    this.state = {
      data: {},
      input: ''
    }

    this.machine = nanostate('idle', {
      idle: { click: 'loading' },
      loading: { resolve: 'data', reject: 'error' },
      data: { click: 'loading' },
      error: { click: 'loading' }
    })

    this.machine.on('loading', () => this.searchRepositories())
  }

  createElement () {
    var buttonText = {
      idle: 'Fetch Github',
      loading: 'Loading…',
      error: 'Github fail. Retry?',
      data: 'Fetch Again?'
    }[this.machine.state]

    return html`
      <div>
        <input
          type="text"
          value=${this.state.input}
          onChange=${e => (this.state.input = e.target.value) && this.rerender()}
        >
        <button
          onClick=${() => this.machine.emit('click')}
          disabled=${this.machine.state === 'loading'}
        >
          ${buttonText}
        </button>
        ${data && html`<div>${JSON.stringify(data, null, 2)}</div>`}
        ${this.machine.state === 'error' && html`<h1>Error</h1>`}
      </div>
    `
  }

  searchRepositories () {
    fetch(`${ROOT_URL}/${this.state.input}`)
      .then(res => res.json())
      .then(res => {
         this.state.data = res.data
         this.machine.emit('resolve')
       })
      .catch(err => this.machine.emit('reject'))
  }
}

API

machine = nanostate(initialState, transitions)

Create a new instance of Nanostate. Takes the name of the initial state, and a mapping of states and their corresponding transitions. A state mapping is defined as { 1: { 2: 3 }}, where 1 is the state's name, 2 is an event name it accepts, and 3 is the new state after the event has been emitted.

machine.emit(event)

Move from the current state to a new state. Will throw if an invalid command is passed.

machine.on(state, cb)

Trigger a callback when a certain state is entered. Useful to trigger side effects upon state change.

state = machine.state

Return the current state.

machine.event(eventName, machine) (to be implemented)

Add another machine to the transition graph. The first argument is an event name, which can be transitioned to from all other states in the graph.

machine = nanostate.parallel(machines) (to be implemented)

Combine several state machines into a single machine. Takes an object of state machines, where the key is used to prefix the events for the state machine.

Say we have two state machine: 'foo' and 'bar'. 'foo' has an event called 'beep'. When combined through .parallel(), the event on the combined machine would be 'foo:beep'.

Installation

$ npm install nanostate

See Also

License

Apache-2.0

nanostate's People

Contributors

bates64 avatar brunoskonrad avatar dawidgorny avatar downeyfe avatar goto-bus-stop avatar kareniel avatar yoshuawuyts avatar zhouhanseng avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nanostate's Issues

Implementation of History API

I was wondering what is the join function used in History code sample:

var nanostate = require('nanostate')

var machine = nanostate('cash', {
  cash: { check: 'check' },
  check: { cash: 'cash' }
})

machine.join('next', nanostate('review', {
  review: { previous: '$history' }
}))

What exactly is next and what it changes in machine object?

Are the .on's not emitting?

it seems like the machine.on('x', cb) things aren't happening for me

var nanostate = require('nanostate')

var machine = nanostate('idle', {
  idle: { click: 'loading' },
  loading: { resolve: 'data', reject: 'error' },
  data: { click: 'loading' },
  error: { click: 'loading' }
})

console.log(machine.state)
machine.emit('click')
console.log(machine.state)

machine.on('idle', () => console.log('on idle'))
machine.on('loading', () => console.log('on loading'))

Error handling

Currently emitting invalid state transition emits error nanostate.emit: invalid transition ${this.state} -> ${eventName}.

Do you have any ideas on how to handle those errors? E.g.

var machine = nanostate('cash', {
  cash: { check: 'check' },
  check: { cash: 'cash' }
})

machine.onError((e) => {
  console.log(error)
  throw e
})

machine.emit('robbery')

Support transition from 'Any'

Hi,

I wanted to propose a feature which I found very handy.

Inspired by a state machine in Unity where you can define transitions from 'Any'. This way you can avoid repetition if there is some set of transitions always available no matter in which state we are.

const machine = nanostate('idle', {
  '_any': { 
    'reset': 'idle'
  },
  'idle': { go: 'state1' }
  'state1': {  }

  // ...

}

I created a draft PR: #13

IE11 Support

There's one line in index.js that is not compatible with IE11 due to the backticks.

Could this be re-written without them? I'd be happy to fork and raise a PR myself.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.