Skip to content

Instantly share code, notes, and snippets.

@jlengstorf
Created May 17, 2020 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlengstorf/69a3e959dd5e902686470b4a1a0aafb9 to your computer and use it in GitHub Desktop.
Save jlengstorf/69a3e959dd5e902686470b4a1a0aafb9 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const effectsMachine = Machine({
id: 'effects',
initial: 'idle',
context: {
transitionSpeed: 600,
duration: 4000,
},
states: {
idle: {
on: {
COMMAND_RECEIVED: {
actions: assign((context, { command }) => ({
command: command.command,
username: command.author?.username,
image: command.handler?.image,
audio: command.handler?.audio,
duration: command.handler?.duration * 1000 || context.duration,
})),
target: 'loading',
},
},
},
loading: {
invoke: {
src: (_, event) =>
Promise.all([
new Promise((resolve, reject) => {
const { image } = event.command?.handler;
if (!image) resolve(true);
const img = new Image();
img.onload = () => resolve(img);
img.onerror = (err) => {
console.error(err);
reject(err);
};
img.src = image;
}),
new Promise((resolve, reject) => {
const { audio } = event.command?.handler;
if (!audio) resolve(true);
const sfx = new Audio();
sfx.addEventListener('canplaythrough', () => {
resolve(sfx);
});
sfx.onerror = (err) => {
console.error(err);
reject(err);
};
sfx.src = audio;
}),
]),
onDone: 'activating',
onError: 'error',
},
},
activating: {
invoke: {
src: 'startEffectAnimation',
onDone: 'visible',
onError: 'error',
},
},
visible: {
entry: (context) => {
if (!context.audio) return;
const sfx = new Audio(context.audio);
sfx.play();
},
invoke: {
src: (context, event) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
}, context.duration);
}),
onDone: 'deactivating',
},
},
deactivating: {
invoke: {
src: 'endEffectAnimation',
onDone: 'idle',
onError: 'error',
},
},
error: {
on: {
'': 'idle',
},
},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment