Skip to content

Instantly share code, notes, and snippets.

@christianhg
Last active June 18, 2021 18:12
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 christianhg/260f966ea9b61221588a84c46b4eecda to your computer and use it in GitHub Desktop.
Save christianhg/260f966ea9b61221588a84c46b4eecda 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 searchListMachine = Machine({
id: 'search-list',
initial: 'closed',
context: {
pointer: 0,
results: []
},
states: {
closed: {
on: {
OPEN: {
target: 'opened'
}
}
},
opened: {
initial: 'idle',
on: {
CLOSE: {
target: 'closed'
},
RESULTS_CHANGED: {
target: '.idle',
actions: ['updateResults']
},
HOVER_FOOTER: {
target: '.focusingFooter'
},
HOVER_RESULT: {
target: '.browsingList',
actions: ['setPointer']
}
},
states: {
idle: {
entry: ['resetPointer'],
on: {
DOWN: [
{
cond: 'noResults',
target: 'focusingFooter'
},
{
target: 'browsingList'
}
]
}
},
browsingList: {
on: {
DOWN: [
{
cond: 'lastResult',
target: 'focusingFooter'
},
{
actions: ['movePointerDown']
}
],
UP: [
{
cond: 'firstResult',
target: 'idle'
},
{
actions: ['movePointerUp']
}
],
ENTER: {
target: '#search-list.closed',
actions: ['selectPointedItem']
}
}
},
focusingFooter: {
on: {
UP: [
{
cond: 'hasResults',
target: 'browsingList',
actions: ['pointAtTheBottom']
},
{
target: 'idle'
}
],
ENTER: {
target: '#search-list.closed',
actions: ['selectFooter']
}
}
}
}
}
}
},
{
actions: {
updateResults: assign({
results: (context, event) => event.results
}),
resetPointer: assign({
pointer: 0
}),
pointAtTheTop: assign({
pointer: 0
}),
pointAtTheBottom: assign({
pointer: (context) => context.results.length - 1
}),
setPointer: assign({
pointer: (context, event) => event.pointer
}),
movePointerDown: assign({
pointer: (context) => context.pointer + 1
}),
movePointerUp: assign({
pointer: (context) => context.pointer - - 1
}),
selectPointedItem: (context) => {
console.log(`Select ${context.results[context.pointer]}`)
},
selectFooter: () => {
console.log('Select footer')
}
},
guards: {
noResults: (context) => context.results && context.results.length === 0,
hasResults: (context) => context.results && context.results.length > 0,
lastResult: (context) =>context.results && context.results.length - 1 === context.pointer
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment