Files
paperclip/ui/src/pages/Auth.tsx
T
Jannes Stubbemann 8ddd735a7a feat(ui): theme toggle on unauthenticated auth page (supersedes part of #3732) (#5874)
## Thinking Path

> - Paperclip orchestrates AI agents for zero-human companies
> - Operators sign in via the `/auth` page, which renders before any
session exists
> - The signed-in app has a theme toggle inside `SidebarAccountMenu`,
but the signed-out `/auth` page has none — first-time visitors are stuck
in whichever theme was hardcoded at boot
> - Master's existing toggle was inline inside `SidebarAccountMenu.tsx`
as a `MenuAction` row, not exported as a reusable widget; round-1 of
this PR added a standalone `ThemeToggle` but punted on unifying the two
surfaces
> - This pull request makes `ThemeToggle` the canonical theme widget
(one source of truth for label, icon, and toggle behaviour), used both
as a compact icon button on `/auth` and as a full-width menu row in
`SidebarAccountMenu`
> - The benefit is a working pre-auth theme switch and zero risk of the
two call sites drifting out of sync as the theme model evolves

## Linked Issues or Issue Description

No existing issue covers this directly — problem described in-PR
(feature-gap shape):

- The signed-in app has a theme toggle inside `SidebarAccountMenu`, but
the signed-out `/auth` page has none — first-time visitors are stuck in
whichever theme was hardcoded at boot.
- The existing toggle lived inline in `SidebarAccountMenu.tsx` as a
`MenuAction` row, not exported as a reusable widget, so the two surfaces
could drift apart as the theme model evolves.
- This PR supersedes part of PR #3732 (the auth-page toggle slice); no
standalone issue was filed for it.

Duplicate-PR search: related open theme PRs #2769 and #4666 add in-app
three-state system-theme toggles — different surface from this PR
(unauthenticated auth page); sibling PR in this series: #5873.

## What Changed

- **`ui/src/components/ThemeToggle.tsx`** — accepts `variant: "icon" |
"menu-action"` (default `"icon"`) and an `onAfterToggle` callback. Both
variants share `useTheme` and the same label/icon derivation. The
`menu-action` variant matches the existing `MenuAction` row styling.
- **`ui/src/components/SidebarAccountMenu.tsx`** — drops its inline
`useTheme()` + `MenuAction`-for-the-theme-row in favor of `<ThemeToggle
variant="menu-action" onAfterToggle={() => setOpen(false)} />`. Sun/Moon
icon imports and theme state move with it.
- **`ui/src/pages/Auth.tsx`** — unchanged from round 0; renders
`<ThemeToggle />` at top-right of the `/auth` page (already using the
default `icon` variant).
- **`ui/src/components/ThemeToggle.test.tsx`** (new) — covers both
variants, the `onAfterToggle` callback, and the label/icon flip across
themes.
- **`ui/src/components/SidebarAccountMenu.test.tsx`** — unchanged; its
`ThemeContext` mock still works because `ThemeToggle` uses the same
hook.

## Verification

- `pnpm --filter @paperclipai/ui run typecheck` — clean.
- `npx vitest run src/components/ThemeToggle.test.tsx
src/components/SidebarAccountMenu.test.tsx` — 5 passed (4 new + 1
existing).
- Manual: launched `pnpm dev` for the UI, mocked `/api/auth/get-session`
401, navigated to `/auth` — toggle is visible top-right, click flips
light/dark. Screenshots committed.

## Risks

Low. The change is structural — both call sites render the same widget
that already worked on each surface independently.
`SidebarAccountMenu`'s popover behaviour is preserved via
`onAfterToggle`, and `ThemeContext` is untouched.

## Model Used

Claude Opus 4.7 (1M context), extended thinking mode.

## Checklist

- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] Thinking path traces from project context to this change
- [x] Model used specified
- [x] Checked ROADMAP.md — not in conflict with planned core work
- [x] Tests run locally and pass
- [x] Added tests for the new ThemeToggle component (both variants)
- [x] UI change — before/after screenshots in
`docs/pr-screenshots/pr-5874/`
- [x] No documentation updates required (purely internal refactor + new
component)
- [x] Documented risks above
- [x] Will address all Greptile and reviewer comments before merge

Supersedes part of #3732.

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Devin Foley <devin@paperclip.ing>
2026-06-12 12:59:14 -07:00

206 lines
7.7 KiB
TypeScript

import { useEffect, useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useNavigate, useSearchParams } from "@/lib/router";
import { authApi } from "../api/auth";
import { queryKeys } from "../lib/queryKeys";
import { getRememberedInvitePath } from "../lib/invite-memory";
import { Button } from "@/components/ui/button";
import { AsciiArtAnimation } from "@/components/AsciiArtAnimation";
import { ThemeToggle } from "@/components/ThemeToggle";
import { Sparkles } from "lucide-react";
type AuthMode = "sign_in" | "sign_up";
export function AuthPage() {
const queryClient = useQueryClient();
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const [mode, setMode] = useState<AuthMode>("sign_in");
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const errorId = "auth-error";
const nextPath = useMemo(
() => searchParams.get("next") || getRememberedInvitePath() || "/",
[searchParams],
);
const { data: session, isLoading: isSessionLoading } = useQuery({
queryKey: queryKeys.auth.session,
queryFn: () => authApi.getSession(),
retry: false,
});
useEffect(() => {
if (session) {
navigate(nextPath, { replace: true });
}
}, [session, navigate, nextPath]);
const mutation = useMutation({
mutationFn: async () => {
if (mode === "sign_in") {
await authApi.signInEmail({ email: email.trim(), password });
return;
}
await authApi.signUpEmail({
name: name.trim(),
email: email.trim(),
password,
});
},
onSuccess: async () => {
setError(null);
await queryClient.invalidateQueries({ queryKey: queryKeys.auth.session });
await queryClient.invalidateQueries({ queryKey: queryKeys.companies.all });
navigate(nextPath, { replace: true });
},
onError: (err) => {
setError(err instanceof Error ? err.message : "Authentication failed");
},
});
const canSubmit =
email.trim().length > 0 &&
password.trim().length > 0 &&
(mode === "sign_in" || (name.trim().length > 0 && password.trim().length >= 8));
if (isSessionLoading) {
return (
<div className="fixed inset-0 flex items-center justify-center">
<p className="text-sm text-muted-foreground">Loading</p>
</div>
);
}
return (
<div className="fixed inset-0 flex bg-background">
<div className="absolute top-4 right-4 z-10">
<ThemeToggle />
</div>
{/* Left half — form */}
<div className="w-full md:w-1/2 flex flex-col overflow-y-auto">
<div className="w-full max-w-md mx-auto my-auto px-8 py-12">
<div className="flex items-center gap-2 mb-8">
<Sparkles className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium">Paperclip</span>
</div>
<h1 className="text-xl font-semibold">
{mode === "sign_in" ? "Sign in to Paperclip" : "Create your Paperclip account"}
</h1>
<p className="mt-1 text-sm text-muted-foreground">
{mode === "sign_in"
? "Use your email and password to access this instance."
: "Create an account for this instance. Email confirmation is not required in v1."}
</p>
<form
className="mt-6 space-y-4"
method="post"
action={mode === "sign_up" ? "/api/auth/sign-up/email" : "/api/auth/sign-in/email"}
onSubmit={(event) => {
event.preventDefault();
if (mutation.isPending) return;
if (!canSubmit) {
setError("Please fill in all required fields.");
return;
}
mutation.mutate();
}}
>
{mode === "sign_up" && (
<div>
<label htmlFor="name" className="text-xs text-muted-foreground mb-1 block">Name</label>
<input
id="name"
name="name"
className="w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50"
value={name}
onChange={(event) => setName(event.target.value)}
autoComplete="name"
required
aria-required="true"
aria-invalid={error ? true : undefined}
aria-describedby={error ? errorId : undefined}
autoFocus
/>
</div>
)}
<div>
<label htmlFor="email" className="text-xs text-muted-foreground mb-1 block">Email</label>
<input
id="email"
name="email"
className="w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50"
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
autoComplete="username"
required
aria-required="true"
aria-invalid={error ? true : undefined}
aria-describedby={error ? errorId : undefined}
autoFocus={mode === "sign_in"}
/>
</div>
<div>
<label htmlFor="password" className="text-xs text-muted-foreground mb-1 block">Password</label>
<input
id="password"
name="password"
className="w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50"
type="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
autoComplete={mode === "sign_in" ? "current-password" : "new-password"}
required
aria-required="true"
aria-invalid={error ? true : undefined}
aria-describedby={error ? errorId : undefined}
/>
</div>
{error && (
<p id={errorId} role="alert" className="text-xs text-destructive">
{error}
</p>
)}
<Button
type="submit"
disabled={mutation.isPending}
aria-disabled={!canSubmit || mutation.isPending}
className={`w-full ${!canSubmit && !mutation.isPending ? "opacity-50" : ""}`}
>
{mutation.isPending
? "Working…"
: mode === "sign_in"
? "Sign In"
: "Create Account"}
</Button>
</form>
<div className="mt-5 text-sm text-muted-foreground">
{mode === "sign_in" ? "Need an account?" : "Already have an account?"}{" "}
<button
type="button"
className="font-medium text-foreground underline underline-offset-2"
onClick={() => {
setError(null);
setMode(mode === "sign_in" ? "sign_up" : "sign_in");
}}
>
{mode === "sign_in" ? "Create one" : "Sign in"}
</button>
</div>
</div>
</div>
{/* Right half — ASCII art animation (hidden on mobile) */}
<div className="hidden md:block w-1/2 overflow-hidden">
<AsciiArtAnimation />
</div>
</div>
);
}