Skip to content

Instantly share code, notes, and snippets.

@jamestharpe
Last active April 2, 2021 22:24
Show Gist options
  • Save jamestharpe/88911ffba684f39e1a1e17fc3810ffcc to your computer and use it in GitHub Desktop.
Save jamestharpe/88911ffba684f39e1a1e17fc3810ffcc 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)
const pomodoroMachine = Machine({
id: 'pomodoro',
initial: 'idle',
context: {
iterations: 0,
elapsed: 0,
started: Date.now(),
paused: Date.now(),
target: {
working: 10000,
resting: 5000
}
},
states: {
idle: {
on: {
NEXT: 'running'
}
},
running: {
initial: "iterating",
on: {
END: "idle"
},
states: {
iterating: {
exit: ["start", "iterate"],
on: {
"": "working"
}
},
working: {
entry: ["tick"],
on: {
PAUSE: "#pomodoro.paused",
SKIP: "worked",
"": { target: "worked", cond: "complete" }
},
after: {
1000: [
{ target: "working", cond: "incomplete"},
]
}
},
worked: {
on: {
NEXT: "resting",
REPEAT: "iterating",
},
exit: "start"
},
resting: {
entry: "tick",
on: {
PAUSE: "#pomodoro.paused",
SKIP: "rested",
"": { target: "rested", cond: "complete"}
},
after: {
1000: [
{ target: "resting", cond: "incomplete"},
]
}
},
rested: {
on: {
NEXT: "iterating",
REPEAT: "resting",
},
exit: "start"
},
last: {
type: 'history',
},
},
},
paused: {
entry: "pause",
on: {
RESUME: "running.last",
END: "idle"
},
exit: "resume"
}
}
},
{
guards: {
complete: (context, event, { state }) => {
const target = state?.matches("running.working") ? context.target.working : context.target.resting;
return context.elapsed >= target;
},
incomplete: (context, event, {state}) => {
const target = state?.matches("running.working") ? context.target.working : context.target.resting;
return context.elapsed < target;
},
firstIteration: (context) => context.iterations === 0
},
actions: {
tick: assign({
elapsed: (context) => Date.now() - context.started}),
start: assign({ started: () => Date.now() }),
pause: assign({ paused: () => Date.now() }),
resume: assign({ started: (context) => context.started + (Date.now() - context.paused) }),
iterate: assign({
iterations: (context) => {
return context.iterations + 1
}
})
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment