Skip to content

Commit

Permalink
Enable left/right arrow keys for webstepper (#108)
Browse files Browse the repository at this point in the history
  • Loading branch information
yoonieaj authored Dec 15, 2024
1 parent 229a46e commit 25ce75a
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 5 deletions.
1 change: 1 addition & 0 deletions webstepper/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- Launchd an initial prototype!
- Improved UI to indicate when the end of the program is reached.
- Expanded code and svg displays in UI.
- Added the ability to step back and forth using the arrow keys.

### 🐛 Bug fixes

Expand Down
27 changes: 22 additions & 5 deletions webstepper/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from "react";
import React, { useEffect, useState } from "react";
import Header from "./Header";
import { Button, Box, Typography, Stack } from "@mui/material";
import SvgDisplay from "./SvgDisplay";
Expand All @@ -15,10 +15,27 @@ export default function App() {
const codeText = window.codeText;
const limit = window.svgArray.length;

const handleStep = (newStep: number) => {
setStep(Math.min(Math.max(newStep, 0), limit - 1));
const handleStep = (offset: number) => {
setStep((step) => Math.min(Math.max(step + offset, 0), limit - 1));
};

useEffect(() => {
const handleKeyDown = (event) => {
if (event.key == "ArrowLeft") {
handleStep(-1);
}
if (event.key == "ArrowRight") {
handleStep(1);
}
};

document.addEventListener("keydown", handleKeyDown);

return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}, []);

return (
<>
<Header />
Expand All @@ -32,13 +49,13 @@ export default function App() {
</Typography>
<Button
disabled={step === 0}
onClick={() => handleStep(step - 1)}
onClick={() => handleStep(-1)}
>
Back
</Button>
<Button
disabled={step === limit - 1}
onClick={() => handleStep(step + 1)}
onClick={() => handleStep(1)}
>
Next
</Button>
Expand Down
12 changes: 12 additions & 0 deletions webstepper/src/__tests__/App.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,16 @@ describe("App", () => {
expect(firstLineElement).not.toHaveClass("code-box__line--highlighted");
expect(secondLineElement).toHaveClass("code-box__line--highlighted");
});

it("updates step when arrow keys are pressed", () => {
const maxStep = getMaxStep();
fireEvent.keyDown(document, { key: "ArrowRight" });

expect(screen.getByText(`Step 2/${maxStep}`)).toBeInTheDocument();

// Then go back
fireEvent.keyDown(document, { key: "ArrowLeft" });

expect(screen.getByText(`Step 1/${maxStep}`)).toBeInTheDocument();
});
});

0 comments on commit 25ce75a

Please sign in to comment.