import { useState } from "react"; import { Navigate, useLocation, useNavigate } from "react-router-dom"; import { ApiError } from "../../api/client"; import { useAuth } from "../../auth/AuthContext"; import { Button } from "../../components/ui/Button"; import { Field, Input } from "../../components/ui/Input"; import "./login.css"; interface LocationState { from?: { pathname: string }; } export function LoginPage() { const { user, login } = useAuth(); const navigate = useNavigate(); const location = useLocation(); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(null); const [submitting, setSubmitting] = useState(false); // Already authenticated — bounce to the app. if (user) return ; const from = (location.state as LocationState | null)?.from?.pathname ?? "/machines"; async function handleSubmit(e: React.FormEvent) { e.preventDefault(); setError(null); setSubmitting(true); try { await login(username, password); navigate(from, { replace: true }); } catch (err) { if (err instanceof ApiError) { setError( err.status === 401 ? "Invalid username or password." : err.message, ); } else { setError("Could not sign in. Please try again."); } } finally { setSubmitting(false); } } return (
); }