Skip to content

Instantly share code, notes, and snippets.

@jonathanj
Last active March 6, 2020 06:30
Show Gist options
  • Save jonathanj/5caaa153af803cde8c1c7d110e4ff07c to your computer and use it in GitHub Desktop.
Save jonathanj/5caaa153af803cde8c1c7d110e4ff07c to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
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