Last active
February 1, 2022 17:35
-
-
Save arturcarvalho/3157a8faec8d685120c16f743a5c0f5a 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 ticker = (ctx) => (cb) => { | |
const interval = setInterval(() => { | |
cb("TICK"); | |
}, ctx.interval * 1000); | |
return () => clearInterval(interval); | |
}; | |
const timerFinished = (ctx) => ctx.remaining === 0; | |
const addPomodoro = assign({ | |
pomodorosDone: (ctx) => ctx.pomodorosDone + 1, | |
}) | |
const addBreak = assign({ | |
breaksDone: (ctx) => ctx.breaksDone + 1, | |
}) | |
const pomodoroMachine = Machine({ | |
id: "pomodoroMachine", | |
initial: "workSelected", | |
context: { | |
remaining: 0, | |
interval: 0.5, // seconds | |
workDuration: 0.1 * 60, | |
breakDuration: 0.05 * 60, | |
pomodorosDone: 0, | |
breaksDone: 0 | |
}, | |
states: { | |
workSelected: { | |
entry: assign({ | |
remaining: (ctx) => ctx.workDuration, | |
}), | |
on: { | |
TOGGLE: { | |
target: "breakSelected", | |
}, | |
WORK: { | |
target: "working", | |
}, | |
}, | |
}, | |
working: { | |
invoke: { | |
id: "ticker", // only used for viz | |
src: ticker, | |
}, | |
on: { | |
// null event occurs immediately | |
"": | |
{ | |
target: "breakSelected", | |
cond: timerFinished, | |
actions: addPomodoro | |
}, | |
PAUSE: { | |
target: "workPaused" | |
}, | |
TICK: { | |
actions: assign({ | |
remaining: (ctx) => Math.max(ctx.remaining - ctx.interval, 0), | |
}), | |
}, | |
} | |
}, | |
workPaused: { | |
on:{ | |
UNPAUSE: { | |
target: "working" | |
}, | |
FINISH:{ | |
target:"breakSelected", | |
actions: addPomodoro | |
}, | |
DISCARD:{ | |
target:"breakSelected" | |
} | |
} | |
}, | |
breakSelected: { | |
entry: assign({ | |
remaining: (ctx) => ctx.breakDuration, | |
}), | |
on: { | |
TOGGLE: { | |
target: "workSelected", | |
}, | |
BREAK: { | |
target: "onBreak" | |
} | |
}, | |
}, | |
onBreak: { | |
invoke: { | |
id: "ticker", // only used for viz | |
src: ticker, | |
}, | |
on: { | |
// null event occurs immediately | |
"": { | |
target: "workSelected", | |
cond: timerFinished, | |
actions: addBreak | |
}, | |
PAUSE: { | |
target: "breakPaused" | |
}, | |
TICK: { | |
actions: assign({ | |
remaining: (ctx) => Math.max(ctx.remaining - ctx.interval, 0), | |
}), | |
} | |
} | |
}, | |
breakPaused: { | |
on:{ | |
UNPAUSE: { | |
target: "onBreak" | |
}, | |
FINISH:{ | |
target:"workSelected", | |
actions: addBreak | |
}, | |
DISCARD:{ | |
target:"workSelected", | |
} | |
} | |
} | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment