Skip to content

Instantly share code, notes, and snippets.

@alavkx
Created September 15, 2019 22:51
Show Gist options
  • Save alavkx/dcaf7c716fb854d3e1f6e8229f9b9d78 to your computer and use it in GitHub Desktop.
Save alavkx/dcaf7c716fb854d3e1f6e8229f9b9d78 to your computer and use it in GitHub Desktop.
Audio player state model
type progress =
| Stopped
| Playing
| Rewinding
| FastForwarding
| Paused;
type playerState = {
status: progress,
activeTrackIndex: option(int),
};
type playerEvent =
| PlayTrack(option(int))
| TogglePlaying
| Stop
| FastForward
| Rewind
| DoNothing;
...
let (playerState, playerSend) =
React.useReducer(
(state, event) =>
switch (state.status, event) {
| (_, PlayTrack(None)) => {
activeTrackIndex: Some(0),
status: Playing,
}
| (_, PlayTrack(i)) => {activeTrackIndex: i, status: Playing}
| (Stopped | Paused | Rewinding | FastForwarding, TogglePlaying) => {
...state,
status: Playing,
}
| (Playing, TogglePlaying) => {...state, status: Paused}
| (Paused | Playing | Rewinding | FastForwarding, Rewind) => {
...state,
status: Rewinding,
}
| (Paused | Playing | Rewinding | FastForwarding, FastForward) => {
...state,
status: FastForwarding,
}
| (_, Stop) => {activeTrackIndex: None, status: Stopped}
| (Stopped, FastForward | Rewind)
| (_, DoNothing) => state
},
{activeTrackIndex: None, status: Stopped},
);
@alavkx
Copy link
Author

alavkx commented Sep 15, 2019

Feel free to code review this if you feel so inclined 😅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment