Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Last active August 23, 2019 15:01
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 JamieMason/874b497397b399c35ca917bca1499064 to your computer and use it in GitHub Desktop.
Save JamieMason/874b497397b399c35ca917bca1499064 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Generally Expected Flow (actions and implementation are missing)
//
// 1 renderNode runs logic which inspects this hard-coded rootNode
// 2 transtions to renderBranch because it has children
// 3 there are two children so the UI would display them
// 4 user chooses the first child
// 5 fetchNode finds no children property, so there is nothing more to load
// 6 fetchNode resolves success with the node
// 7 renderNode runs logic which inspects the node
// 8 transtions to renderLeaf because it has no children
// 9 user either:
// * confirms this is the accepted choice
// * goes back to the parent node
// * returns to the root node
const rootNode = {
label: 'This is the Root Node',
children: [
{ label: 'This is a leaf, finalising the machine if rendered' },
{
label: 'This is a branch, whose children are loaded async',
children: () =>
Promise.resolve({ label: 'This is a leaf, finalising the machine if rendered' })
}
]
};
const treeWalkerMachine = Machine(
{
id: 'tree-walker',
initial: 'renderNode',
context: {
currentNode: rootNode,
parentNode: null,
retries: 0,
rootNode
},
states: {
fetchNode: {
initial: 'loading',
states: {
loading: {
on: {
RESOLVE: 'success',
REJECT: 'failure'
}
},
success: {
on: {
'': {
target: '#tree-walker.renderNode',
actions: ['resetRetries']
}
}
},
failure: {
on: {
RETRY: {
target: 'loading',
actions: ['incrementRetries']
}
}
}
}
},
renderNode: {
on: {
IS_BRANCH: '#tree-walker.renderBranch',
IS_LEAF: '#tree-walker.renderLeaf'
}
},
renderBranch: {
on: {
SELECT_CHILD: 'fetchNode',
SELECT_PARENT: 'renderNode',
SELECT_ROOT: 'fetchNode'
}
},
renderLeaf: {
on: {
SELECT_LEAF: 'confirmChoice',
SELECT_PARENT: 'renderNode',
SELECT_ROOT: 'fetchNode'
}
},
confirmChoice: {
type: 'final'
}
}
},
{
actions: {
incrementRetries: assign({ retries: context => context.retries + 1 }),
resetRetries: assign({ retries: () => 0 })
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment