Skip to content

Instantly share code, notes, and snippets.

@LinusBorg
Created Apr 11, 2020
Embed
What would you like to do?
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const focusMover = Machine({
id: 'focusMover',
initial: 'unknown',
context: {
active: true,
selectedIndex: 0,
max: 5,
},
states: {
unknown: {
on: {
'': [
{
target: 'active',
cond: ctx => ctx.active,
},
{
target: 'inactive',
},
],
},
},
inactive: {
on: {
ACTIVATE: 'active',
UPDATE_MAX: {
actions: 'updateMax'
},
},
},
active: {
entry: 'setActive',
exit: 'setInactive',
on: {
DEACTIVATE: 'inactive',
FORWARD: {
actions: 'forward',
},
BACKWARD: {
actions: 'backward',
},
UPDATE_MAX: {
actions: 'updateMax'
},
},
},
},
},
{
actions: {
setActive: assign({
active: true,
}),
setInactive: assign({
active: false,
}),
backward: assign({
selectedIndex: ctx => Math.max(0, ctx.selectedIndex - 1),
}),
forward: assign({
selectedIndex: ctx => Math.min(ctx.max, ctx.selectedIndex + 1),
}),
updateMax: assign({
max: (ctx, evt) => evt.max,
selectedIndex: (ctx, evt) => Math.min(ctx.selectedIndex, evt.max)
})
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment