Skip to content

Instantly share code, notes, and snippets.

@bwaidelich
Last active April 10, 2021 09:16
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 bwaidelich/b7f6895146d142aaa956f17986a9ee82 to your computer and use it in GitHub Desktop.
Save bwaidelich/b7f6895146d142aaa956f17986a9ee82 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const playheadMachine = Machine({
id: 'playhead',
initial: 'idle',
context: {
fps: 2,
events: [],
lastEmittedEvent: null,
emitted: [],
playhead: 0
},
states: {
idle: {
on: {
PLAY: {
target: 'replaying',
actions: assign({emitted: []}),
cond: (ctx) => ctx.events.length > 0
},
ADD_EVENT: {
actions: assign({
events: (ctx, e) => [...ctx.events, {type: e?.data?.type ?? 'default-' + ctx.events.length, streamId: e?.data?.streamId ?? 'some-stream'}]
}),
target: 'idle'
},
RESET: {
target: 'idle',
actions: assign({events: []}),
cond: (ctx) => ctx.events.length > 0
},
SET_FPS: {
actions: assign({
fps: (_, e) => e?.data?.fps ?? 20
}),
target: 'idle'
}
}
},
replaying: {
entry: send('TICK'),
after: {
REPLAY_DELAY: 'replaying'
},
on: {
TICK: [
{
target: 'replaying',
internal: true,
actions: [
'emit',
assign({
lastEmittedEvent: (ctx, e) => ctx.events[ctx.playhead],
emitted: (ctx, e) => [...ctx.emitted, ctx.events[ctx.playhead]],
playhead: (ctx) => ctx.playhead + 1
})
],
cond: (ctx) => ctx.playhead < ctx.events.length
},
{
target: 'idle',
actions: assign({playhead: 0})
}
],
PAUSE: 'idle',
STOP: {
actions: assign({playhead: 0}),
target: 'idle'
}
}
}
}
}, {
actions: {
emit: (ctx, event) => {
console.log('EMIT', ctx.lastEmittedEvent)
}
},
delays: {
REPLAY_DELAY: (ctx) => 1000 / ctx.fps
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment