Skip to content

Instantly share code, notes, and snippets.

@mfeckie
Last active October 10, 2020 14:02
Show Gist options
  • Save mfeckie/e3689fe367f539e0111de97fb7d92b1b to your computer and use it in GitHub Desktop.
Save mfeckie/e3689fe367f539e0111de97fb7d92b1b 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)
/**
* Wraps a value to be in the range 0-24
*/
function modHours(value) {
if (value % 12 === 0) {
return 12;
} else {
return value % 12
}
}
function modMinutes(value) {
return value % 60;
}
const fetchMachine = Machine({
id: "time-machine",
initial: "idle",
context: {
hours: null,
minutes: null,
meridiem: null
},
states: {
idle: {
on: {
FOCUS: "focussed"
},
},
focussed: {
entry: [
assign((context) => {
return {
hours: context.hours || 1,
minutes: context.minutes || 0,
meridiem: context.meridiem || 'AM'
}
})
],
on: {
BLUR: "visited",
TAB: "visited",
HOURS: "hours",
MINUTES: "minutes",
MERIDIEM: "meridiem"
},
},
visited: {
on: {
always: [
{
target: 'valid',
cond: 'allFieldsValid'
},
{
target: 'invalid'
}
]
}
},
valid: {},
invalid: {},
hours: {
initial: 'focussed',
on: {
MINUTES: 'minutes',
VISITED: 'visited'
},
states: {
focussed: {
on: {
INCREMENT: {
actions: assign({
hours: ({hours}) => {
const newHours = modHours(hours + 1);
console.log(newHours)
return newHours;
},
}),
},
DECREMENT: {
actions: 'decrement'
},
USER_INPUT: {
actions: 'userInput'
},
TAB: {
actions: send('MINUTES')
},
BLUR: {
actions: send('VISITED')
}
}
}
}
},
minutes: {
initial: 'focussed',
on: {
MERIDIEM: 'meridiem',
BLUR: 'visited'
},
states: {
focussed: {
on: {
INCREMENT: {
actions: assign({
minutes: ({minutes}) => {
const newMinutes = modMinutes(minutes + 1);
console.log(newMinutes);
return newMinutes
}
})
},
DECREMENT: {
actions: 'decrement'
},
USER_INPUT: {
actions: 'userInput'
},
TAB: {
actions: send('MERIDIEM')
},
BLUR: {
actions: send('BLUR')
}
}
}
}
},
meridiem: {
initial: 'focussed',
on: {
BLUR: 'visited',
},
states: {
focussed: {
on: {
TOGGLE: {
actions: assign({
meridiem: (({meridiem}) => {
if (meridiem == 'AM') {
return 'PM'
}
return 'AM'
})
})
},
BLUR: {
actions: send('BLUR')
}
}
}
}
}
},
}, {
guards: {
allFieldsValid: ({hours, minutes, meridiem}, _event) => {
return hours !== undefined && minutes !== undefined && meridiem
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment