Skip to content

Instantly share code, notes, and snippets.

@LevelbossMike
Created September 17, 2020 08:00
Show Gist options
  • Select an option

  • Save LevelbossMike/b20afd5b1d2b47e759d0e3f7e395040d to your computer and use it in GitHub Desktop.

Select an option

Save LevelbossMike/b20afd5b1d2b47e759d0e3f7e395040d 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 selectMachine = Machine(
{
initial: 'closed',
context: {
filter: '',
selectedIndex: 0,
},
states: {
closed: {
id: 'closed',
on: {
TOGGLE: 'open',
OPEN: 'open',
// open the dropdown when closed and user starts typing
FILTER: {
target: 'open',
actions: [send('FILTER')],
},
},
},
open: {
initial: 'filtered',
on: {
TOGGLE: 'closed',
CLOSE: 'closed',
FILTER: {
target: 'open.filtering',
actions: [
actions.cancel('debounce-filter'),
send(
'APPLY_FILTER',
{
delay: 300,
id: 'debounce-filter',
}
),
],
},
},
states: {
filtering: {
on: {
APPLY_FILTER: [
{
target: 'filtered',
actions: [
actions.assign({ filter: (_context, { filter }) => filter }),
],
},
],
},
},
filtered: {
entry: assign({
selectedIndex: 0,
}),
on: {
UP: {
actions: [
actions.assign({
selectedIndex: (context) => context.selectedIndex - 1,
}),
],
cond: 'upIsPossible',
},
DOWN: {
actions: [
assign({
selectedIndex: (context) => context.selectedIndex + 1,
}),
],
cond: 'downIsPossible',
},
ENTER: {
target: '#closed',
actions: [
actions.assign({
filter: '',
}),
],
cond: 'enterIsPossible',
},
},
},
},
},
},
},
{
guards: {
upIsPossible() {},
downIsPossible() {},
enterIsPossible() {},
},
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment