Last active
March 5, 2020 18:22
-
-
Save avanslaars/c252a19d438cc55f5bf26dc3b652cd59 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains hidden or 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
// Available variables: | |
// - Machine | |
// - interpret | |
// - assign | |
// - send | |
// - sendParent | |
// - spawn | |
// - raise | |
// - actions | |
// - XState (all XState exports) | |
const undoMachine = Machine({ | |
id: 'undo', | |
initial: 'idle', | |
context: { | |
value: "", | |
prevSteps: [] | |
}, | |
states: { | |
idle: { | |
on: { | |
EDIT: {target: 'editing', actions: 'captureStep'}, | |
UNDO: {actions: 'undo', cond: 'hasUndoSteps'} | |
} | |
}, | |
editing: { | |
on: { | |
CHANGE: {actions: 'setValue'}, | |
SAVE: [{target: 'idle', cond: 'hasNewValue'}, {actions: send('CANCEL')}], | |
CANCEL: {target: 'idle', actions: 'undo'} | |
} | |
}, | |
} | |
}, { | |
actions: { | |
setValue: assign({value: (_, event) => event.data || ""}), | |
captureStep: assign({prevSteps: (context) => [context.value, ...context.prevSteps]}), | |
undo: assign(context => { | |
const [head, ...tail] = context.prevSteps | |
return {value: head, prevSteps: tail} | |
}) | |
}, | |
guards: { | |
hasUndoSteps: context => Boolean(context.prevSteps.length), | |
hasNewValue: (context, event) => context.prevSteps[0] !== context.value | |
}, | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment