Skip to content

Instantly share code, notes, and snippets.

@happylinks
Created December 14, 2019 14:19
Show Gist options
  • Save happylinks/9d2b496591e6fb202e8fff4ebaa30830 to your computer and use it in GitHub Desktop.
Save happylinks/9d2b496591e6fb202e8fff4ebaa30830 to your computer and use it in GitHub Desktop.
/* Hooks.re */
let useMachine = (initialState, initialContext, decisionTree) => {
let (state, setState) = React.useState(_ => initialState);
let (context, setContext) = React.useState(_ => initialContext);
let transition = event =>
setState(state => decisionTree(event, state, setContext));
(state, context, transition);
};
/* PlayerState.re */
type context = {
startTime: float,
currentTime: float,
};
type state =
| Idle
| Playing
| Paused;
type event =
| PLAY
| PAUSE
| STOP
| TICK;
let decisionTree = (event, state, setContext) =>
switch (event) {
| PLAY =>
switch (state) {
| Idle =>
setContext(_ => {startTime: Js.Date.now(), currentTime: 0.});
Playing;
| Paused =>
setContext(context =>
{...context, startTime: Js.Date.now() -. context.currentTime}
);
Playing;
| state => state
}
| PAUSE => Paused
| STOP => Idle
| TICK =>
switch (state) {
| Playing =>
setContext(context =>
{...context, currentTime: Js.Date.now() -. context.startTime}
);
Playing;
| state => state
}
};
/* In your component */
let (playerState, playerContext, playerTransition) =
Hooks.useMachine(
PlayerState.Idle,
PlayerState.{startTime: 0.0, currentTime: 0.0},
PlayerState.decisionTree,
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment