Skip to content

Instantly share code, notes, and snippets.

@alavkx
Created September 15, 2019 18:57
Show Gist options
  • Save alavkx/f5498ac7cc4c2170a7235c4e0d8070a3 to your computer and use it in GitHub Desktop.
Save alavkx/f5498ac7cc4c2170a7235c4e0d8070a3 to your computer and use it in GitHub Desktop.
Find the bug!
type track = {
name: string,
artist: string,
};
let tracks = [|
{artist: "Kromestar", name: "007"},
{artist: "Kromestar", name: "008"},
{artist: "Kromestar", name: "009"},
{artist: "Kromestar", name: "010"},
{artist: "Kromestar", name: "011"},
{artist: "Kromestar", name: "012"},
{artist: "Kromestar", name: "013"},
|];
type position =
| First
| Middle
| Last;
let getArrayPos = (index: int, xs: array('a)) =>
switch (index) {
| 0 => First
| x when x >= Array.length(xs) - 1 => Last
| _ => Middle
};
type state = {
selectedRowIndex: int,
rowStatus: position,
activeTrack: option(track)
};
type event =
| SelectRow(int)
| Next
| Previous
| DoNothing;
let keyboardEvent = (e: ReactEvent.Keyboard.t) =>
switch (ReactEvent.Keyboard.key(e)) {
| "ArrowUp" => Next
| "ArrowDown" => Previous
| _ => DoNothing
};
[@react.component]
let make = () => {
let (state, dispatch) =
React.useReducer(
(state, event) =>
switch (state.rowStatus, event) {
| (_, SelectRow(index)) => {
selectedRowIndex: index,
rowStatus: getRowStatus(index, tracks),
};
| (Last | Middle, Previous) =>
let nextId = state.selectedRowIndex - 1;
{
selectedRowIndex: nextId,
rowStatus: getRowStatus(nextId, tracks),
};
| (First | Middle, Next) =>
let nextId = state.selectedRowIndex + 1;
{
selectedRowIndex: nextId,
rowStatus: getRowStatus(nextId, tracks),
};
| (First, Previous)
| (Last, Next)
| (_, DoNothing) => state
},
{selectedRowIndex: 0, rowStatus: First, activeTrack: None},
);
<>
<table tabIndex=0 onKeyDown={e => dispatch(keyboardEvent(e))}>
{React.array(
Array.mapi(
(i, {artist, name}) =>
<tr
style={ReactDOMRe.Style.make(
~backgroundColor=state.selectedRowIndex == i ? "blue" : "white",
(),
)}
key={string_of_int(i)}
onClick={_ => dispatch(SelectRow(i))}>
<td> {ReasonReact.string(artist)} </td>
<td> {ReasonReact.string(name)} </td>
</tr>,
tracks,
),
)}
</table>
<nav>
{
switch(state.activeTrack) {
| None => "Pick a song to get started"
| Some({ name }) => "Now playing: " ++ name
}
}<main>Now Playing: {state.activeTrack}</main>
</nav>
</>;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment