summaryrefslogtreecommitdiff
path: root/frontend/src
diff options
context:
space:
mode:
Diffstat (limited to 'frontend/src')
-rw-r--r--frontend/src/components/AddRobotForm.tsx11
-rw-r--r--frontend/src/components/CityMap.tsx6
-rw-r--r--frontend/src/components/RobotList.tsx98
-rw-r--r--frontend/src/components/Sidebar.tsx26
-rw-r--r--frontend/src/components/SimulationActions.tsx35
-rw-r--r--frontend/src/pages/Dashboard.tsx13
-rw-r--r--frontend/src/styles/index.css16
-rw-r--r--frontend/src/types/robot.ts23
8 files changed, 181 insertions, 47 deletions
diff --git a/frontend/src/components/AddRobotForm.tsx b/frontend/src/components/AddRobotForm.tsx
index c178657..0d2a00f 100644
--- a/frontend/src/components/AddRobotForm.tsx
+++ b/frontend/src/components/AddRobotForm.tsx
@@ -5,22 +5,26 @@ import {
type SetStateAction,
} from "react";
import type { ErrorResponse } from "../types/error";
-import type { CreateRobotResponse } from "../types/robot";
+import type { CreateRobotResponse, Robot } from "../types/robot";
type Props = {
apiUrl: string;
errorMessage: string;
+ robots: Robot[];
token: string | null;
setErrorMessage: Dispatch<SetStateAction<string>>;
setIsAddingRobot: Dispatch<SetStateAction<boolean>>;
+ setRobots: Dispatch<SetStateAction<Robot[]>>;
};
function AddRobotForm({
apiUrl,
errorMessage,
+ robots,
token,
setErrorMessage,
setIsAddingRobot,
+ setRobots,
}: Props) {
const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
const [newRobotName, setNewRobotName] = useState<string>("");
@@ -69,7 +73,10 @@ function AddRobotForm({
}
const data: CreateRobotResponse = await response.json();
- console.log("Robot created successfully: ", data);
+ console.log(data.message, data.robot);
+
+ const newRobotList = [...robots, data.robot];
+ setRobots(newRobotList);
// Reset form and close input field
setNewRobotName("");
diff --git a/frontend/src/components/CityMap.tsx b/frontend/src/components/CityMap.tsx
index b61e69a..795598e 100644
--- a/frontend/src/components/CityMap.tsx
+++ b/frontend/src/components/CityMap.tsx
@@ -65,9 +65,11 @@ function CityMap({ robots }: Props) {
source.clear();
- robots.forEach((robot) => {
+ robots?.forEach((robot) => {
const feature = new Feature({
- geometry: new Point(fromLonLat([robot?.lon, robot?.lat])),
+ geometry: new Point(
+ fromLonLat([parseFloat(robot?.lon), parseFloat(robot?.lat)])
+ ),
robotId: robot?.id,
});
diff --git a/frontend/src/components/RobotList.tsx b/frontend/src/components/RobotList.tsx
index d711372..21d8e63 100644
--- a/frontend/src/components/RobotList.tsx
+++ b/frontend/src/components/RobotList.tsx
@@ -1,11 +1,22 @@
-import { useState } from "react";
-import type { Robot } from "../types/robot";
+import {
+ useState,
+ type Dispatch,
+ type MouseEvent,
+ type SetStateAction,
+} from "react";
+import type { ErrorResponse } from "../types/error";
+import type { Robot, SimulationResponse } from "../types/robot";
type ExpandedRobotsState = Record<number, boolean>;
-type Props = { robots: Robot[]; };
+type Props = {
+ apiUrl: string;
+ robots: Robot[];
+ token: string | null;
+ setErrorMessage: Dispatch<SetStateAction<string>>;
+};
-function RobotList({ robots }: Props) {
+function RobotList({ apiUrl, robots, token, setErrorMessage }: Props) {
const [expandedRobots, setExpandedRobots] = useState<ExpandedRobotsState>(
{}
);
@@ -17,15 +28,89 @@ function RobotList({ robots }: Props) {
}));
}
+ // Move or stop individual robot
+ async function controlSingleRobot(
+ event: MouseEvent<HTMLButtonElement>,
+ robotId: number,
+ robotStatus: Robot["status"]
+ ) {
+ const isRobotMoving = robotStatus === "moving";
+ const button = event.currentTarget;
+ button.disabled = true; // prevent spamming
+
+ try {
+ // Make button clickable again after 1 second
+ setTimeout(() => {
+ button.disabled = false;
+ }, 1000);
+
+ const response = await fetch(
+ `${apiUrl}/robots/${robotId}/${
+ isRobotMoving ? "stop" : "move"
+ }`,
+ {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ "Content-Type": "application/json",
+ },
+ }
+ );
+
+ if (!response.ok) {
+ const errorData: ErrorResponse = await response.json();
+ throw new Error(
+ errorData.message ||
+ `Failed to ${
+ isRobotMoving ? "stop" : "start"
+ } robot ID ${robotId}.`
+ );
+ }
+
+ const data: SimulationResponse = await response.json();
+ console.log(data.message);
+ } catch (error) {
+ console.error(
+ `Error ${
+ isRobotMoving ? "stopping" : "starting"
+ } robot ID ${robotId}: `,
+ error
+ );
+
+ if (error instanceof Error) {
+ setErrorMessage(error.message);
+ } else {
+ setErrorMessage("An unexpected error occurred.");
+ }
+ }
+ }
+
return (
<ul className="sidebar-robot-list">
- {robots.map((robot) => {
+ {robots?.map((robot) => {
const isExpanded = expandedRobots[robot?.id];
return (
<li key={robot?.id}>
<p className="robot-name">{robot?.name}</p>
+ {/* Move/stop individual robot */}
+ <button
+ className={`btn btn-single-robot btn-${
+ robot?.status === "idle" ? "start" : "stop"
+ }`}
+ onClick={(event) =>
+ controlSingleRobot(
+ event,
+ robot?.id,
+ robot?.status
+ )
+ }
+ >
+ {robot?.status === "idle" ? "MOVE" : "STOP"}
+ </button>
+
+ {/* Movement status */}
<p>
Status:{" "}
<span className={`robot-status-${robot?.status}`}>
@@ -33,12 +118,14 @@ function RobotList({ robots }: Props) {
</span>
</p>
+ {/* Current position */}
<p className="robot-coordinates-label">Position:</p>
<ul className="robot-coordinates">
<li>Lat: {robot?.lat}</li>
<li>Lon: {robot?.lon}</li>
</ul>
+ {/* Expand position log */}
<button
className="btn btn-robot-history-toggle"
onClick={() => toggleRobotHistory(robot?.id)}
@@ -52,6 +139,7 @@ function RobotList({ robots }: Props) {
</span>
</button>
+ {/* Position log/history */}
<div
className={`robot-history ${
isExpanded ? "expanded" : ""
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index 8bd795b..3760d4e 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -8,13 +8,24 @@ import RobotList from "./RobotList";
import SimulationActions from "./SimulationActions";
type Props = {
+ activeSimulation: boolean;
errorMessage: string;
robots: Robot[];
token: string | null;
+ setActiveSimulation: Dispatch<SetStateAction<boolean>>;
setErrorMessage: Dispatch<SetStateAction<string>>;
+ setRobots: Dispatch<SetStateAction<Robot[]>>;
};
-function Sidebar({ errorMessage, robots, token, setErrorMessage }: Props) {
+function Sidebar({
+ activeSimulation,
+ errorMessage,
+ robots,
+ token,
+ setActiveSimulation,
+ setErrorMessage,
+ setRobots,
+}: Props) {
const [isAddingRobot, setIsAddingRobot] = useState(false);
function handleAddClick() {
@@ -35,13 +46,15 @@ function Sidebar({ errorMessage, robots, token, setErrorMessage }: Props) {
</button>
</div>
- {isAddingRobot && (
+ {isAddingRobot && (
<AddRobotForm
apiUrl={API_URL}
errorMessage={errorMessage}
+ robots={robots}
token={token}
setErrorMessage={setErrorMessage}
setIsAddingRobot={setIsAddingRobot}
+ setRobots={setRobots}
/>
)}
@@ -50,12 +63,19 @@ function Sidebar({ errorMessage, robots, token, setErrorMessage }: Props) {
)}
<SimulationActions
+ activeSimulation={activeSimulation}
apiUrl={API_URL}
token={token}
+ setActiveSimulation={setActiveSimulation}
setErrorMessage={setErrorMessage}
/>
- <RobotList robots={robots} />
+ <RobotList
+ apiUrl={API_URL}
+ robots={robots}
+ token={token}
+ setErrorMessage={setErrorMessage}
+ />
</div>
);
}
diff --git a/frontend/src/components/SimulationActions.tsx b/frontend/src/components/SimulationActions.tsx
index c91b933..0bfca3f 100644
--- a/frontend/src/components/SimulationActions.tsx
+++ b/frontend/src/components/SimulationActions.tsx
@@ -1,19 +1,24 @@
-import { useState, type Dispatch, type SetStateAction } from "react";
+import { type Dispatch, type SetStateAction } from "react";
import type { ErrorResponse } from "../types/error";
+import type { SimulationResponse } from "../types/robot";
type Props = {
+ activeSimulation: boolean;
apiUrl: string;
token: string | null;
+ setActiveSimulation: Dispatch<SetStateAction<boolean>>;
setErrorMessage: Dispatch<SetStateAction<string>>;
};
-function SimulationActions({ apiUrl, token, setErrorMessage }: Props) {
- const [isSimulationActive, setIsSimulationActive] =
- useState<boolean>(false);
-
- // TODO type responses
+function SimulationActions({
+ activeSimulation,
+ apiUrl,
+ token,
+ setActiveSimulation,
+ setErrorMessage,
+}: Props) {
async function handleStartAllRobots() {
- setIsSimulationActive(true);
+ setActiveSimulation(true);
try {
const response = await fetch(`${apiUrl}/robots/move`, {
@@ -31,7 +36,8 @@ function SimulationActions({ apiUrl, token, setErrorMessage }: Props) {
);
}
- console.log("All robots set moving.");
+ const data: SimulationResponse = await response.json();
+ console.log(data.message);
} catch (error) {
console.error("Error starting robots:", error);
@@ -41,12 +47,12 @@ function SimulationActions({ apiUrl, token, setErrorMessage }: Props) {
setErrorMessage("An unexpected error occurred.");
}
- setIsSimulationActive(false);
+ setActiveSimulation(false);
}
}
async function handleStopAllRobots() {
- setIsSimulationActive(false);
+ setActiveSimulation(false);
try {
const response = await fetch(`${apiUrl}/robots/stop`, {
@@ -64,7 +70,8 @@ function SimulationActions({ apiUrl, token, setErrorMessage }: Props) {
);
}
- console.log("All robots set idle.");
+ const data: SimulationResponse = await response.json();
+ console.log(data.message);
} catch (error) {
console.error("Error stopping robots:", error);
@@ -74,7 +81,7 @@ function SimulationActions({ apiUrl, token, setErrorMessage }: Props) {
setErrorMessage("An unexpected error occurred.");
}
- setIsSimulationActive(true);
+ setActiveSimulation(true);
}
}
@@ -83,7 +90,7 @@ function SimulationActions({ apiUrl, token, setErrorMessage }: Props) {
<button
className="btn btn-start"
onClick={handleStartAllRobots}
- disabled={isSimulationActive}
+ disabled={activeSimulation}
>
Start simulation
</button>
@@ -91,7 +98,7 @@ function SimulationActions({ apiUrl, token, setErrorMessage }: Props) {
<button
className="btn btn-stop"
onClick={handleStopAllRobots}
- disabled={!isSimulationActive}
+ disabled={!activeSimulation}
>
Stop simulation
</button>
diff --git a/frontend/src/pages/Dashboard.tsx b/frontend/src/pages/Dashboard.tsx
index 088fee2..b1b38e4 100644
--- a/frontend/src/pages/Dashboard.tsx
+++ b/frontend/src/pages/Dashboard.tsx
@@ -14,6 +14,8 @@ import type { Robot, RobotsResponse } from "../types/robot";
function Dashboard() {
const [errorMessage, setErrorMessage] = useState<string>("");
const [isLoading, setIsLoading] = useState<boolean>(true);
+ const [isSimulationActive, setIsSimulationActive] =
+ useState<boolean>(false);
const [robots, setRobots] = useState<Robot[]>([]);
const navigate = useNavigate();
@@ -25,6 +27,7 @@ function Dashboard() {
async function handleLogout() {
localStorage.removeItem("token-robot-tracker");
localStorage.removeItem("user");
+ // setIsSimulationActive(false);
navigate("/login", { replace: true });
}
@@ -57,7 +60,9 @@ function Dashboard() {
}
const data: RobotsResponse = await response.json();
- setRobots(data.data);
+
+ setRobots(data.robots);
+ setIsSimulationActive(data.simulationRunning);
} catch (error) {
console.error("Failed to load the robots:", error);
@@ -66,7 +71,6 @@ function Dashboard() {
} else {
setErrorMessage("An unexpected error occurred.");
}
-
} finally {
setIsLoading(false);
}
@@ -78,7 +82,7 @@ function Dashboard() {
const socket = io(API_URL);
// Listen for real-time robot updates
- socket.on("robots_update", (updatedRobots) => {
+ socket.on("robots_update", ({ updatedRobots }) => {
setRobots(updatedRobots);
});
@@ -95,10 +99,13 @@ function Dashboard() {
<Header user={user} logout={handleLogout} />
<CityMap robots={robots} />
<Sidebar
+ activeSimulation={isSimulationActive}
errorMessage={errorMessage}
robots={robots}
token={token}
+ setActiveSimulation={setIsSimulationActive}
setErrorMessage={setErrorMessage}
+ setRobots={setRobots}
/>
</div>
);
diff --git a/frontend/src/styles/index.css b/frontend/src/styles/index.css
index dcc2590..bd4eacd 100644
--- a/frontend/src/styles/index.css
+++ b/frontend/src/styles/index.css
@@ -20,25 +20,17 @@
--text-small: 0.9rem;
box-sizing: border-box;
+
+ background-color: #fff;
+ color: #213547;
+
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
-
- color-scheme: light dark;
- color: rgba(255, 255, 255, 0.87);
- background-color: #242424;
-
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-
- @media (prefers-color-scheme: light) {
- :root {
- color: #213547;
- background-color: #fff;
- }
- }
}
body {
diff --git a/frontend/src/types/robot.ts b/frontend/src/types/robot.ts
index 965afea..d9b2e7d 100644
--- a/frontend/src/types/robot.ts
+++ b/frontend/src/types/robot.ts
@@ -1,14 +1,16 @@
export type RobotPosition = {
- lat: number;
- lon: number;
+ lat: string;
+ lon: string;
};
+export type RobotStatus = "idle" | "moving";
+
export type Robot = {
id: number;
name: string;
- status: "idle" | "moving";
- lat: number;
- lon: number;
+ status: RobotStatus;
+ lat: string;
+ lon: string;
robot_positions: RobotPosition[];
created_at: string;
updated_at: string;
@@ -16,7 +18,8 @@ export type Robot = {
export type RobotsResponse = {
source: "cache" | "database";
- data: Robot[];
+ robots: Robot[];
+ simulationRunning: boolean;
};
export type CreateRobotResponse = {
@@ -24,3 +27,11 @@ export type CreateRobotResponse = {
robot: Robot;
};
+export type RobotsUpdateBroadcast = {
+ updatedRobots: Robot[];
+};
+
+export type SimulationResponse = {
+ message: string;
+ status?: RobotStatus;
+};