Skip to content

Instantly share code, notes, and snippets.

@dsadhanala
Last active April 17, 2020 06:48
Show Gist options
  • Save dsadhanala/52e7dcae04d3351181ce5e5a593f5d60 to your computer and use it in GitHub Desktop.
Save dsadhanala/52e7dcae04d3351181ce5e5a593f5d60 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const updateMessage = (message) => assign({ message: (_, _e) => message });
const projectnameStates = {
initial: 'editing',
states: {
editing: {
entry: ['logState'],
on: {
PROJECT_NAME_SAVING: {
target: '#headerMachine.saving',
cond: 'validProjectName',
actions: 'updateLabel'
},
PROJECT_NAME_CANCEL: 'cancelled'
}
},
cancelled: { entry: ['logState'] }
}
};
const headerMachine = Machine(
{
id: 'headerMachine',
strict: true,
initial: 'ready',
context: {
projectName: '',
message: undefined,
},
on: {
PROJECT_NAME_EDIT: 'projectname',
UNDO_CLICK: 'undo',
REDO_CLICK: 'redo',
INVITE_CLICK: 'invite',
DOWNLOAD_ITEM_CLICK: 'download',
SHARE_ITEM_CLICK: 'share'
},
states: {
ready: {},
projectname: { ...projectnameStates },
redo: {
entry: ['logState'],
after: { AUTO_SAVE_DELAY: 'saving'}
},
undo: {
entry: ['logState'],
after: { AUTO_SAVE_DELAY: 'saving'}
},
invite: {
entry: ['logState']
},
download: {
entry: ['logState']
},
share: {
entry: ['logState']
},
saving: {
entry: ['updateLabel', updateMessage('Saving...')],
invoke: {
id: 'saveProject',
src: 'saveService',
onDone: {
target: 'saved',
actions: updateMessage('Saved'),
},
onError: {
target: 'failed',
actions: updateMessage('Failed to save!'),
},
},
},
saved: {
entry: ['logState'],
// on: { '': 'idle'}
},
failed: {
entry: ['logState'],
// on: { '': 'idle'}
},
},
},
{
delays: {
AUTO_SAVE_DELAY: 2000
},
actions: {
updateLabel: assign({
projectName: (_, { projectName }) => projectName,
}),
logState: (_, event) => console.info(event),
},
services: {
saveService: (_ctx, event) => {
// this is a fetch request which saves project
return new Promise((resolve, _reject) => {
console.info(event.type);
setTimeout(resolve, 2000);
});
},
},
guards: {
validProjectName: (_, { projectName }) => !!projectName,
},
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment