Skip to content

Instantly share code, notes, and snippets.

@segunadebayo
Last active November 19, 2019 22:41
Show Gist options
  • Save segunadebayo/5aa214ec8e2e342370da67abab4fe2c6 to your computer and use it in GitHub Desktop.
Save segunadebayo/5aa214ec8e2e342370da67abab4fe2c6 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const menuButtonMachine = new Machine(
{
id: "menu-button",
initial: "idle",
context: {
activeIndex: -1,
items: [1, 2, 3],
focused: ""
},
states: {
idle: {
on: {
FOCUS: "focused"
}
},
focused: {
entry: "focus_button",
meta: {
message: "The button has focus"
},
on: {
CLICK: {
target: "opened",
actions: ["focus_dropdown", "highlight_firstItem"]
},
ARROW_DOWN: {
target: "opened",
actions: ["focus_dropdown", "highlight_firstItem"]
},
ARROW_UP: {
target: "opened",
actions: ["focus_dropdown", "highlight_lastItem"]
}
}
},
opened: {
entry: ["focus_dropdown"],
on: {
ARROW_DOWN: {
actions: "increment"
},
ARROW_UP: {
actions: "decrement"
},
ESCAPE: "closed"
}
},
closed: {
entry : ["clear_index"],
on: { '': 'focused' }
}
}
},
{
actions: {
increment: assign({
activeIndex: context => {
const { length } = context.items;
return (context.activeIndex + 1) % length;
}
}),
decrement: assign({
activeIndex: context => {
const { length } = context.items;
return (context.activeIndex - 1 + length) % length;
}
}),
clear_index: assign({
activeIndex: -1,
focused: ""
}),
focus_button: assign({
focused: "button"
}),
focus_dropdown: assign({
focused: "dropdown"
}),
highlight_firstItem: assign({
activeIndex: 1
})
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment