Skip to content

Instantly share code, notes, and snippets.

@musikele
Last active August 13, 2020 15:45
Show Gist options
  • Save musikele/8181c5f5b6bd1700248cebfd844583ee to your computer and use it in GitHub Desktop.
Save musikele/8181c5f5b6bd1700248cebfd844583ee to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const unloaded = {
on: {
LOAD: {
target: 'stopped'
}
}
}
const stopped = {
entry: ['stopAction'],
on: {
PLAY: {
target: 'playing',
}
}
}
const playing = {
entry: ['playAction'],
exit: undefined,
on: {
STOP: {
target: 'stopped',
},
PAUSE: {
target: 'paused'
},
SEEK: {
actions: ['seekAction']
}
}
}
const paused = {
entry: ['pausedAction'],
on: {
STOP: {
target: 'stopped',
},
PLAY: {
target: 'playing',
}
}
}
const states = {unloaded, stopped, playing, paused}
const initial = 'unloaded'
const config = {
id: 'soundManager',
initial,
context: {
time: 0,
interval: null,
startTime: 0,
pausedTime: 0,
seekTime: 0
},
states
}
const soundManagerMachine = Machine(config, {
actions: {
playAction: (context, event) => {
if (context.interval) {
clearInterval(context.interval);
}
context.startTime = new Date().getTime() - (context.pausedTime * 1000);
context.interval = setInterval(() => {
if (typeof context.seekTime !== 'undefined') {
context.startTime = new Date().getTime() - context.seekTime * 1000;
}
context.time = new Date().getTime() - context.startTime;
context.seekTime = undefined;
}, 50);
context.pausedTime = 0;
console.log(context)
},
stopAction: (context, event) => {
context.time = 0;
context.pausedTime = 0;
clearInterval(context.interval);
console.log(context)
},
pausedAction: (context, event) => {
context.pausedTime = context.time / 1000;
clearInterval(context.interval);
console.log(context)
},
seekAction: (context, event) => {
context.seekTime = event.seconds
if (context.seekTime < 0) context.seekTime = 0
context.time = console.seekTime * 1000
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment