From 25ce75aae3a3ec8bbdc2eb463777c20f7a24881f Mon Sep 17 00:00:00 2001
From: yoonieaj <144498960+yoonieaj@users.noreply.github.com>
Date: Sun, 15 Dec 2024 10:01:19 -0500
Subject: [PATCH] Enable left/right arrow keys for webstepper (#108)
---
webstepper/CHANGELOG.md | 1 +
webstepper/src/App.tsx | 27 ++++++++++++++++++++++-----
webstepper/src/__tests__/App.spec.tsx | 12 ++++++++++++
3 files changed, 35 insertions(+), 5 deletions(-)
diff --git a/webstepper/CHANGELOG.md b/webstepper/CHANGELOG.md
index 3a02f1c..9b0a360 100755
--- a/webstepper/CHANGELOG.md
+++ b/webstepper/CHANGELOG.md
@@ -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
diff --git a/webstepper/src/App.tsx b/webstepper/src/App.tsx
index cc16475..0251570 100644
--- a/webstepper/src/App.tsx
+++ b/webstepper/src/App.tsx
@@ -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";
@@ -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 (
<>
@@ -32,13 +49,13 @@ export default function App() {
diff --git a/webstepper/src/__tests__/App.spec.tsx b/webstepper/src/__tests__/App.spec.tsx
index 0aac45c..a9a17b4 100644
--- a/webstepper/src/__tests__/App.spec.tsx
+++ b/webstepper/src/__tests__/App.spec.tsx
@@ -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();
+ });
});