Skip to content

Instantly share code, notes, and snippets.

@georg3103
Last active July 24, 2021 13:30
Show Gist options
  • Save georg3103/a4f0339db5bd28a6f604f46bb2fa93ff to your computer and use it in GitHub Desktop.
Save georg3103/a4f0339db5bd28a6f604f46bb2fa93ff to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const videoRecorderMachine = Machine({
// not a parallel machine
id: 'videoRecorder',
context: {
interval: 1,
elapsed: 0,
elapsed1: 0,
elapsed2: 0,
duration: 3,
duration1: 4,
duration2: 10,
isResolved: false
},
initial: 'idle',
states: {
idle: {
on: { START: 'preparingTimer' }
},
preparingTimer: {
initial: "running",
states: {
running: {
invoke: {
src: context => cb => {
const interval = setInterval(() => {
cb("TICK");
}, 1000 * context.interval);
return () => {
clearInterval(interval);
};
}
},
on: {
"": {
target: "DONE",
cond: context => {
return context.elapsed >= context.duration;
}
},
TICK: {
actions: assign({
elapsed: context => +(context.elapsed + context.interval).toFixed(2)
})
}
}
},
DONE: {
on: {
"": {
target: "#videoRecorder.recording",
cond: context => context.elapsed == context.duration
}
}
}
},
},
// nested parallel machine
recording: {
type: 'parallel',
states: {
userTimer: {
initial: "running1",
states: {
running1: {
invoke: {
src: context => cb => {
const interval = setInterval(() => {
cb("TICK1");
}, 1000 * context.interval);
return () => {
clearInterval(interval);
};
}
},
on: {
"": {
target: "DONE1",
cond: context => {
return context.elapsed1 == context.duration1;
}
},
TICK1: {
actions: assign({
elapsed1: context => context.elapsed1 + context.interval
})
}
}
},
DONE1: {
invoke: {
src: context => cb => {
cb("RESOLVE");
}
},
on: {
RESOLVE: {
// cond: context => context.elapsed1 == context.duration1,
actions: assign({
isResolved: context => true
})
}
}
}
},
},
user: {
initial: 'idle',
states: {
idle: {
on: {
"": {
target: "#videoRecorder.recording.user.stop",
cond: context => context.isResolved
},
}
},
stop: {
on: {
STOP: "#videoRecorder.saving",
}
}
},
},
videoTimer: {
initial: "running2",
states: {
running2: {
invoke: {
src: context => cb => {
const interval = setInterval(() => {
cb("TICK2");
}, 1000 * context.interval);
return () => {
clearInterval(interval);
};
}
},
on: {
"": {
target: "DONE2",
cond: context => {
return context.elapsed2 >= context.duration2;
}
},
TICK2: {
actions: assign({
elapsed2: context => context.elapsed2 + context.interval
})
}
}
},
DONE2: {
on: {
"": {
target: "#videoRecorder.saving",
}
}
}
},
},
}
},
saving: {
},
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment