Skip to content

Instantly share code, notes, and snippets.

@natemoo-re
Last active January 9, 2020 18:23
Show Gist options
  • Save natemoo-re/ef70ae9e8f19b68afa877238a0246b8c to your computer and use it in GitHub Desktop.
Save natemoo-re/ef70ae9e8f19b68afa877238a0246b8c to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const { cancel } = actions;
const TimerMachine = Machine(
{
initial: "idle",
context: {
duration: 5000,
paused: false,
startedAt: null,
remaining: 0
},
states: {
idle: {
on: {
TOGGLE: "active"
}
},
active: {
entry: [
"countdown",
"startCountdown"
],
on: {
TOGGLE: "paused",
FINISH: "complete"
}
},
paused: {
entry: [
"pauseCountdown",
"pause"
],
on: {
TOGGLE: "active"
}
},
complete: {
type: "final",
entry: sendParent('DONE')
}
}
},
{
actions: {
startCountdown: send('FINISH', { id: 'timer', delay: (ctx) => ctx.remaining > 0 ? ctx.remaining : ctx.duration }),
pauseCountdown: cancel('timer'),
countdown: assign((ctx, event) => {
const startedAt = Date.now();
return {
paused: false,
startedAt,
}
}),
pause: assign((ctx, event) => {
const total = ctx.remaining > 0 ? ctx.remaining : ctx.duration;
const elapsed = Date.now() - ctx.startedAt;
const remaining = total - elapsed;
console.log({ total, elapsed, remaining });
return {
paused: true,
startedAt: null,
remaining
}
})
}
}
);
let ids = 0;
const makeId = () => `toast-${ids++}`;
const ADD = {
target: 'active',
actions: assign({
toasts: (context, event) => [
...context.toasts,
{
toast: event.toast,
ref: spawn(ToastMachine, makeId())
}
]
})
}
const ToastMachine = Machine({
initial: 'idle',
context: {
toasts: []
},
states: {
idle: {
on: {
ADD
}
},
active: {
on: {
ADD
}
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment