Skip to content

Instantly share code, notes, and snippets.

@avanslaars
Created March 5, 2020 19:48
Show Gist options
  • Save avanslaars/6815bdf02b7c8b6ebce23cf34c676365 to your computer and use it in GitHub Desktop.
Save avanslaars/6815bdf02b7c8b6ebce23cf34c676365 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const undoMachine = Machine({
id: 'input_w_undo',
initial: 'idle',
context: {
value: "",
prevSteps: []
},
states: {
idle: {
on: {
FOCUS: {target: 'editing', actions: 'captureStep'},
UNDO: {actions: 'undo', cond: 'hasUndoSteps'}
}
},
editing: {
on: {
CHANGE: {actions: 'setValue'},
BLUR: [{target: 'idle', cond: 'hasNewValue'}, {actions: send('RESET')}],
RESET: {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