Skip to content

Instantly share code, notes, and snippets.

@danielkcz
Last active November 16, 2019 22:32
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 danielkcz/577d8ba60bae726aa4d1105c461fb80a to your computer and use it in GitHub Desktop.
Save danielkcz/577d8ba60bae726aa4d1105c461fb80a to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const reset = assign({
value: ({ initialValue }) => initialValue
})
const updateValue = assign({
value: (_, ev) => ev.value
})
const isEnterOrTab = (_, ev) => ['Enter', 'Tab'].includes(ev.key)
const isEscape = (ctx, ev) => ['Escape'].includes(ev.key)
const isValueDirty = ({ initialValue, value }) => initialValue !== value
const smartTextMachine = Machine(
{
id: 'smartText',
initial: 'reading',
context: {
initialValue: '',
value: ''
},
states: {
reading: {
initial: 'hideIndicator',
states: {
hideIndicator: {},
showIndicator: {}
},
onEntry: 'reset',
on: {
START_EDIT: 'editing',
MOUSE_LEAVE: '.hideIndicator',
MOUSE_ENTER: '.showIndicator'
}
},
editing: {
initial: 'unknown',
states: {
unknown: {
on: {
'': [
{ target: '#smartText.editing.dirty', cond: 'isValueDirty' },
{ target: '#smartText.editing.pristine' }
]
}
},
pristine: {},
dirty: {}
},
onEntry: 'setFocus',
on: {
KEYPRESS: [
{ target: '#smartText.confirm', cond: 'isEnterOrTab' },
{ target: '#smartText.cancel', cond: 'isEscape' }
],
CHANGE: {
actions: 'updateValue',
target: '.unknown'
},
CANCEL_EDIT: 'cancel'
}
},
confirm: {
entry: 'submit',
on: {
'': 'reading'
}
},
cancel: {
entry: 'reset',
on: {
'': 'reading'
}
}
}
},
{
guards: {
isValueDirty,
isEnterOrTab,
isEscape
},
actions: {
reset,
updateValue,
setFocus: () => {},
submit: () => {}
}
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment