Skip to content

Instantly share code, notes, and snippets.

@tmikeschu
Created December 29, 2019 17:31
Show Gist options
  • Save tmikeschu/ba4f8077d971ce91d72558453cf5131f to your computer and use it in GitHub Desktop.
Save tmikeschu/ba4f8077d971ce91d72558453cf5131f to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const machineConfig = {
initial: "idle",
id: "main",
context: {
initialTime: 0,
currentTime: 0,
notificationTimes: []
},
states: {
idle: {
on: {
START: "running",
RESET: {
actions: ["reset"]
},
SET_TIME: {
actions: ["setTime"]
},
SET_NOTIFICATION_TIMES: {
internal: false,
actions: ["setNotifications"]
}
}
},
running: {
invoke: [
{ src: "timer", id: "timer" },
{ src: "plantNotifications", id: "plantNotifications" }
],
on: {
"": {
target: "idle",
cond: ({ currentTime }) => currentTime <= 0
},
STOP: "idle",
COUNT_DOWN: {
actions: ["countDown"]
}
}
}
}
};
const machineOptions = {
actions: {
setNotifications: assign({
notificationTimes: (context, event) => {
if (event.type === "SET_NOTIFICATION_TIMES") {
return event.payload.notificationTimes;
}
return context.notificationTimes;
}
}),
setTime: assign({
initialTime: (context, event) =>
event.type === "SET_TIME" ? event.payload.time : context.initialTime,
currentTime: (context, event) =>
event.type === "SET_TIME" ? event.payload.time : context.currentTime
}),
countDown: assign({
currentTime: context => context.currentTime - secsToMS(1)
}),
reset: assign({
currentTime: context => context.initialTime
})
},
services: {
timer: () => (cb) => {
const interval = setInterval(() => {
cb("COUNT_DOWN");
}, secsToMS(1));
return () => {
clearInterval(interval);
};
}
}
};
const machine = Machine(machineConfig, machineOptions);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment