Last active
February 13, 2020 21:34
-
-
Save adamscott/a11db8f49a443b3ad56a42f68bbc25a2 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains 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 forms = [ | |
'name', | |
'email', | |
'phone', | |
'website', | |
'contacts', | |
'employees', | |
'longevity', | |
'objective', | |
'password', | |
'confirm', | |
]; | |
const getNextForm = (context, forms, currentForm) => { | |
let currentIndex = -1; | |
if (currentForm) { | |
currentIndex = forms.indexOf(currentForm); | |
} | |
return forms | |
.filter((_, index) => index > currentIndex) | |
.find((form) => { | |
return !context.data.hasOwnProperty(form); | |
}) || null; | |
}; | |
const getBackForm = (context, forms, currentForm) => { | |
let currentIndex = forms.length; | |
if (currentForm) { | |
currentIndex = forms.indexOf(currentForm); | |
} | |
return forms | |
.filter((_, index) => index < currentIndex) | |
.reverse() | |
.find((form) => { | |
return !context.data.hasOwnProperty(form); | |
}) || null; | |
}; | |
const context = { | |
currentForm: null, | |
data: { | |
email: '[email protected]', | |
employees: 10 | |
} | |
}; | |
const freeTrialMachine = Machine({ | |
id: 'freeTrial', | |
initial: 'idle', | |
context, | |
states: { | |
idle: { | |
on: { | |
'': [{ | |
target: 'form', | |
actions: ['init'] | |
}] | |
} | |
}, | |
form: { | |
on: { | |
BACK: [{ | |
target: 'form', | |
cond: 'hasBack', | |
actions: [assign({ | |
currentForm: (context) => getBackForm(context, forms, context.currentForm) | |
})] | |
}], | |
NEXT: [ | |
{ | |
target: 'form', | |
cond: 'hasNext', | |
actions: [assign({ | |
currentForm: (context) => getNextForm(context, forms, context.currentForm) | |
})] | |
}, | |
{ | |
target: 'confirm', | |
actions: [assign({ | |
currentForm: (context) => getBackForm(context, forms) | |
})] | |
} | |
] | |
} | |
}, | |
confirm: { | |
on: { | |
BACK: [{ | |
target: 'form', | |
actions: [assign({ | |
currentForm: (context) => getBackForm(context, forms) | |
})] | |
}] | |
} | |
} | |
} | |
}, { | |
actions: { | |
init: assign({ | |
currentForm: (context) => { | |
return getNextForm(context, forms); | |
} | |
}) | |
}, | |
guards: { | |
hasBack: (context) => !!getBackForm(context, forms, context.currentForm), | |
hasNext: (context) => !!getNextForm(context, forms, context.currentForm) | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment