Skip to content

Instantly share code, notes, and snippets.

@anthonybrown
Forked from ryanflorence/FiniteMachine.js
Created January 8, 2018 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonybrown/d1714b6e9aa99b70cdf50a24835f634b to your computer and use it in GitHub Desktop.
Save anthonybrown/d1714b6e9aa99b70cdf50a24835f634b to your computer and use it in GitHub Desktop.
finite-machine.js
import React, { Component } from "react"
import { Machine } from "xstate"
import * as PropTypes from "prop-types"
class FiniteMachine extends Component {
machine = Machine(this.props.chart)
state = {
data: this.props.reducer(undefined, { type: "@init" }),
machineState: this.machine.getInitialState()
}
transition = (actionType, newData) => {
const { log, chart, reducer } = this.props
const { data, machineState } = this.state
const nextState = this.machine.transition(machineState, actionType).toString()
const action = {
data: newData,
nextState,
type: `${machineState}.${actionType}`
}
if (log) {
console.log(chart.id, action.type, action.data)
}
this.setState(
{
data: reducer(data, action),
machineState: nextState
},
log
? () => {
console.log(chart.id, this.state.machineState, this.state.data)
}
: undefined
)
}
render() {
return this.props.render({
state: this.state.machineState,
data: this.state.data,
transition: this.transition
})
}
}
class Match extends Component {
static propTypes = {
machine: PropTypes.shape({
state: PropTypes.string,
transition: PropTypes.func
}),
state: PropTypes.string,
partial: PropTypes.bool,
conditional: PropTypes.bool
}
static defaultProps = {
partial: false,
conditional: true
}
render() {
const { component: Component, render, partial, conditional, machine, state } = this.props
const match = partial ? machine.state.startsWith(state) : machine.state === state
return conditional ? (
match ? (
render ? (
render(machine)
) : (
<Component {...machine} />
)
) : null
) : render ? (
render(machine)
) : (
<Component {...machine} />
)
}
}
class Switch extends Component {
static propTypes = {
machine: PropTypes.shape({
state: PropTypes.string.isRequired,
transition: PropTypes.func.isRequired
}).isRequired
}
render() {
const { children, machine } = this.props
let match = null
React.Children.forEach(children, child => {
if (match) return
if (child.props.state === machine.state) {
match = child
}
})
return React.cloneElement(match, { machine })
}
}
export { FiniteMachine, Match, Switch }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment