Last active
April 30, 2021 11:02
-
-
Save oscargm/1f717109e3376f8424788d1303e9b310 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
const initialContext = { | |
selectedValue: -1, | |
availableValues: [ | |
{ id: 1, text: "value 1" }, | |
{ id: 2, text: "value 2" }, | |
{ id: 3, text: "value 3" }, | |
{ id: 4, text: "value 4" }, | |
], | |
}; | |
// Available variables: | |
// - Machine | |
// - interpret | |
// - assign | |
// - send | |
// - sendParent | |
// - spawn | |
// - raise | |
// - actions | |
// - XState (all XState exports) | |
const isArrowDownKeyPressed = (context, event) => { | |
return event.type === "external" && event.keyCode === 40; | |
}; | |
const isTabKeyPressed = (context, event) => { | |
return event.type === "external" && event.keyCode === 9; | |
}; | |
const selectValue = assign({ | |
value: (context, event) => event.value, | |
}); | |
const getLastSelectedValue = assign({ | |
value: (context, event) => context.value, | |
}); | |
const removeValue = assign({ | |
selectedValue: (context, event) => -1, | |
}); | |
const editableDropdownMachine = Machine( | |
{ | |
id: "editableDropdown", | |
initial: "closed", | |
context: initialContext, | |
states: { | |
closed: { | |
on: { | |
FOCUS: "focus", | |
CLICK: "open", | |
CLICK_CROSS: { | |
target: "closed", | |
actions: "removeValue", | |
}, | |
}, | |
}, | |
focus: { | |
on: { | |
CLICK: "open", | |
CLICK_CROSS: { | |
target: "closed", | |
actions: "removeValue", | |
}, | |
KEY_DOWN: [ | |
{ | |
target: `open`, | |
cond: "isArrowDownKeyPressed", | |
}, | |
{ | |
target: `closed`, | |
cond: "isTabKeyPressed", | |
}, | |
{ target: "filtered" }, | |
], | |
}, | |
}, | |
open: { | |
on: { | |
CLICK_OUTSIDE: { | |
target: "focus", | |
actions: "getLastSelectedValue", | |
}, | |
TYPE_TEXT: "filtered", | |
SELECT_OPTION: { | |
target: "closed", | |
actions: "selectValue", | |
}, | |
}, | |
}, | |
filtered: { | |
on: { | |
SELECT_OPTION: { | |
target: "focus", | |
actions: "selectValue", | |
}, | |
CLICK_OUTSIDE: { | |
target: "closed", | |
actions: "getLastSelectedValue", | |
}, | |
}, | |
}, | |
}, | |
}, | |
{ | |
actions: { selectValue, getLastSelectedValue, removeValue }, | |
guards: { | |
isArrowDownKeyPressed, | |
isTabKeyPressed, | |
}, | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment