Last active
March 6, 2020 06:30
-
-
Save jonathanj/5caaa153af803cde8c1c7d110e4ff07c to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const machine = Machine({ | |
id: 'shape', | |
initial: 'idle', | |
devTools: true, | |
context: { | |
mode: 'poly', | |
points: [], | |
shapes: [], | |
}, | |
states: { | |
idle: { | |
on: { | |
'': { | |
target: 'done', | |
cond: 'shapeComplete', | |
}, | |
CLICK: { | |
target: 'idle', | |
actions: ['addPoint'], | |
}, | |
DONE: { | |
target: 'done', | |
cond: 'polyComplete', | |
}, | |
}, | |
}, | |
done: { | |
type: 'final', | |
on: { | |
'': { | |
actions: ['addShape'], | |
target: 'idle', | |
}, | |
}, | |
}, | |
}, | |
on: { | |
RECT: { | |
actions: assign({ | |
points: [], | |
mode: 'rect', | |
}), | |
}, | |
POINT: { | |
actions: assign({ | |
points: [], | |
mode: 'point', | |
}), | |
}, | |
POLY: { | |
actions: assign({ | |
points: [], | |
mode: 'poly', | |
}), | |
}, | |
} | |
}, | |
{ | |
actions: { | |
addPoint: assign({ | |
points: ctx => ctx.points.concat([true]), | |
}), | |
addShape: assign({ | |
shapes: ctx => ctx.shapes.concat({ | |
type: ctx.mode, | |
points: [...ctx.points], | |
}), | |
points: [], | |
}), | |
}, | |
guards: { | |
shapeComplete(context, event) { | |
const {points, mode} = context; | |
switch (mode) { | |
case 'point': | |
return points.length === 1; | |
case 'rect': | |
return points.length === 2; | |
default: | |
return false; | |
} | |
}, | |
polyComplete(context) { | |
const {points, mode} = context; | |
return mode === 'poly' && points.length > 2; | |
}, | |
}, | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment