Skip to content

Instantly share code, notes, and snippets.

@the-main-thing
Last active February 26, 2020 10:47
Show Gist options
  • Save the-main-thing/658013f7f6a0b33ac22549bed6cc1da6 to your computer and use it in GitHub Desktop.
Save the-main-thing/658013f7f6a0b33ac22549bed6cc1da6 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const id = 'uid'
const initialEvents = {
ADD: {
target: `#${id}.edit.new`,
actions: ['onAdd']
},
EDIT: {
target: `#${id}.edit.change`,
actions: ['onEdit']
},
DELETE: {
target: 'deleting',
actions: ['onDelete']
}
};
const deletingState = (errorStateName, initialStateName) => {
return {
initial: 'confirm',
states: {
confirm: {
on: {
CONFIRM: 'deleting',
CANCEL: initialStateName
}
},
deleting: {
invoke: {
src: 'remove',
onDone: {
target: initialStateName,
actions: ['resetDeleteKey']
},
onError: {
target: errorStateName
}
}
}
}
};
};
const editingEvents = {
SAVE: {
target: 'saving'
},
CHANGE: {
target: 'idle',
actions: ['onChange']
},
DELETE: {
target: 'deleting',
actions: ['onDelete']
},
CANCEL: {
target: `#${id}.idle`,
actions: ['onCancel', 'clearContext']
}
};
const getEditingState = (invokeFnName, rootStateName) => {
return {
initial: 'idle',
states: {
idle: {
on: {
...editingEvents
}
},
saving: {
invoke: {
src: invokeFnName,
onDone: {
target: `#${id}.idle`,
actions: ['clearContext']
},
onError: {
target: 'savingError'
}
}
},
savingError: {
on: {
...editingEvents
}
},
deleting: deletingState(`${rootStateName}.deletingError`, `#${rootStateName}.idle`),
deletingError: {
on: {
...editingEvents
}
}
}
};
};
const tableEditingMachine = Machine({
id,
initial: 'idle',
context: {},
states: {
idle: {
initial: 'idle',
states: {
idle: {
on: {
...initialEvents
}
},
deletingError: {
on: {
...initialEvents
}
},
deleting: deletingState(`#${id}.idle.deletingError`, `#${id}.idle.idle`)
}
},
edit: {
states: {
new: getEditingState('saveNew', `#${id}.edit.new`),
change: getEditingState('saveChange', `#${id}.edit.change`)
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment