Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 25 additions & 36 deletions src/components/ThemeToggle.tsx
Original file line number Diff line number Diff line change
@@ -1,55 +1,44 @@
import { useEffect, useState } from "react";
import { Moon, Sun } from "lucide-react";
import { Button } from "@/components/ui/button";

/**
* Two modes only: the Blue Aurora dark theme (the default, no class) and Light.
*
* A third "Academia" gold theme existed and has been removed. Because the choice
* is persisted, a browser that still has `academia` stored must resolve to
* something real — otherwise the app loads unthemed and the toggle shows a label
* for a mode that no longer exists.
*/
type Theme = "starry" | "light";
const KEY = "athenaeum-theme";
const ORDER: Theme[] = ["starry", "light"];

const apply = (t: Theme) => {
const root = document.documentElement;
root.classList.remove("theme-light", "theme-academia");
if (t === "light") root.classList.add("theme-light");
};
import {
applyTheme,
initTheme,
THEME_ORDER,
themeFromDocument,
writeStoredTheme,
type Theme,
} from "@/lib/theme";
import { useEffect, useState } from "react";

const labelFor = (t: Theme) => (t === "starry" ? "Aurora" : "Light");

/** Maps any previously stored value onto a theme that still exists. */
const normalise = (stored: string | null): Theme =>
stored === "light" ? "light" : "starry";

/**
* The theme values, storage key and normalisation all live in `@/lib/theme`, which
* `main.tsx` calls at boot. This component only reflects the current theme and
* cycles it — it no longer decides what "light" means or how a stale value resolves.
*/
export function ThemeToggle() {
const [theme, setTheme] = useState<Theme>("starry");
// `initTheme` is idempotent and has already run by the time this mounts, so the
// first render is correct rather than flashing the default before an effect.
const [theme, setTheme] = useState<Theme>(() => themeFromDocument());

useEffect(() => {
const saved = normalise(localStorage.getItem(KEY));
setTheme(saved);
apply(saved);
// Rewrite the stored value so a stale "academia" does not linger.
if (localStorage.getItem(KEY) && localStorage.getItem(KEY) !== saved) {
localStorage.setItem(KEY, saved);
}
// Re-resolve on mount: this also repairs a document whose class was stripped
// by a cached page, and migrates a stale stored value.
setTheme(initTheme());
}, []);

const cycle = () => {
const idx = ORDER.indexOf(theme);
const next = ORDER[(idx + 1) % ORDER.length];
const idx = THEME_ORDER.indexOf(theme);
const next = THEME_ORDER[(idx + 1) % THEME_ORDER.length];
setTheme(next);
apply(next);
localStorage.setItem(KEY, next);
applyTheme(next);
writeStoredTheme(next);
};

// Two modes, two icons. The moon marks the dark Aurora theme, the sun the light one.
const Icon = theme === "light" ? Sun : Moon;
const nextLabel = labelFor(ORDER[(ORDER.indexOf(theme) + 1) % ORDER.length]);
const nextLabel = labelFor(THEME_ORDER[(THEME_ORDER.indexOf(theme) + 1) % THEME_ORDER.length]);

return (
<Button
Expand Down
2 changes: 1 addition & 1 deletion src/lib/landingCopy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export const STACK: StackItem[] = [
export const PROOF = {
backendUnit: 942,
backendIntegration: 101,
frontend: 357,
frontend: 374,
endToEnd: 26,
};

Expand Down
80 changes: 80 additions & 0 deletions src/lib/theme.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* The one place the theme is defined.
*
* This logic used to live entirely inside `ThemeToggle`, which is only mounted by
* `AppLayout` — the authenticated shell. So `/` and `/auth` never applied the
* stored preference and always rendered dark, and someone who had chosen Light
* met a dark page the moment they signed out or followed a shared link.
*
* It lives here now so that `main.tsx` can apply the stored theme at boot, before
* React renders, and the toggle can keep using exactly the same values, key and
* normalisation. There is still one theme system; only its initialisation moved.
*/

export type Theme = "starry" | "light";

export const THEME_KEY = "athenaeum-theme";

/** Cycle order for the toggle. "starry" is the Blue Aurora default and carries no class. */
export const THEME_ORDER: Theme[] = ["starry", "light"];

export const LIGHT_CLASS = "theme-light";

/**
* A third "Academia" gold theme existed and has been removed. Because the choice
* is persisted, a browser that still has `academia` stored must resolve to
* something real — otherwise the app loads unthemed and the toggle shows a label
* for a mode that no longer exists.
*/
export function normaliseTheme(stored: string | null): Theme {
return stored === "light" ? "light" : "starry";
}

/** Maps the DOM to a theme. "starry" is represented by the absence of a class. */
export function applyTheme(theme: Theme): void {
const root = document.documentElement;
// `theme-academia` is removed as well: a cached document can still carry it
// even though nothing writes it any more.
root.classList.remove(LIGHT_CLASS, "theme-academia");
if (theme === "light") root.classList.add(LIGHT_CLASS);
}

/**
* Read the stored preference, apply it, and rewrite the stored value when it was
* stale. Returns the resolved theme so callers can render the right icon.
*
* Called from `main.tsx` at module scope, which is what makes it apply to every
* route — and applies it *before* the first render rather than in an effect after
* mount, so the correct theme is present at first paint.
*/
export function initTheme(): Theme {
const raw = readStoredThemeRaw();
const theme = normaliseTheme(raw);
applyTheme(theme);
// Rewrite so a stale "academia" does not linger in storage.
if (raw !== null && raw !== theme) writeStoredTheme(theme);
return theme;
}

function readStoredThemeRaw(): string | null {
try {
return window.localStorage.getItem(THEME_KEY);
} catch {
// Private browsing or a blocked origin: fall back to the default rather than
// throwing during boot, which would take the whole app down before render.
return null;
}
}

export function writeStoredTheme(theme: Theme): void {
try {
window.localStorage.setItem(THEME_KEY, theme);
} catch {
// Persistence is best-effort; the theme still applies for this page view.
}
}

/** The current theme according to the DOM, not storage. */
export function themeFromDocument(): Theme {
return document.documentElement.classList.contains(LIGHT_CLASS) ? "light" : "starry";
}
11 changes: 11 additions & 0 deletions src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import { initTheme } from "./lib/theme";

// Apply the stored theme before the first render, on every route.
//
// This runs at module scope rather than inside an effect or a mounted component:
// `ThemeToggle` lives in `AppLayout`, so the public landing page and the auth
// screen never had a theme applied at all, and even the authenticated shell only
// got one after mount — which is a visible flash from the default. Running here
// means the first painted frame is already correct, with no inline duplicate of
// this logic in index.html to drift out of sync.
initTheme();

createRoot(document.getElementById("root")!).render(<App />);
208 changes: 208 additions & 0 deletions src/test/themeApplication.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { act } from "react";
import {
applyTheme,
initTheme,
LIGHT_CLASS,
normaliseTheme,
THEME_KEY,
themeFromDocument,
} from "@/lib/theme";

/**
* Step 6 found that a stored Light preference was ignored on `/` and `/auth`.
*
* Those tests could not catch it: `ThemeToggle` is mounted by `AppLayout`, so the
* public routes never had a theme applied at all, and the previous suite only
* grepped component source for className strings. These tests exercise the real
* behaviour — set storage, run boot, assert the DOM.
*/

vi.mock("@/context/AuthContext", () => ({
useAuth: () => ({ isAuthenticated: false, isLoading: false }),
}));

/** Imported lazily because the module runs `initTheme()` at import time. */
async function boot() {
const mod = await import("@/lib/theme");
return mod.initTheme();
}

beforeEach(() => {
localStorage.clear();
document.documentElement.className = "";
});

afterEach(() => {
localStorage.clear();
document.documentElement.className = "";
vi.resetModules();
});

describe("theme values and persistence are unchanged", () => {
it("still recognises exactly the two modes", () => {
expect(normaliseTheme("light")).toBe("light");
expect(normaliseTheme("starry")).toBe("starry");
expect(normaliseTheme(null)).toBe("starry");
});

it("still resolves the retired academia value to a real theme", () => {
expect(normaliseTheme("academia")).toBe("starry");
});

it("still writes back a migrated value so it cannot linger", async () => {
localStorage.setItem(THEME_KEY, "academia");
await boot();

expect(localStorage.getItem(THEME_KEY)).toBe("starry");
});

it("leaves a valid stored value untouched", async () => {
localStorage.setItem(THEME_KEY, "light");
await boot();

expect(localStorage.getItem(THEME_KEY)).toBe("light");
});

it("stores nothing when there was nothing stored", async () => {
await boot();

expect(localStorage.getItem(THEME_KEY)).toBeNull();
});
});

describe("boot applies the stored theme on every route", () => {
it("applies Light on the landing page", async () => {
localStorage.setItem(THEME_KEY, "light");

render(
<MemoryRouter initialEntries={["/"]}>
<Routes>
<Route path="/" element={<div data-testid="landing" />} />
</Routes>
</MemoryRouter>,
);
// Boot runs in main.tsx, so drive the same entry point the app uses.
await act(async () => {
await boot();
});

expect(document.documentElement.classList.contains(LIGHT_CLASS)).toBe(true);
expect(themeFromDocument()).toBe("light");
});

it("applies Light on the auth page", async () => {
localStorage.setItem(THEME_KEY, "light");

render(
<MemoryRouter initialEntries={["/auth"]}>
<Routes>
<Route path="/auth" element={<div data-testid="auth" />} />
</Routes>
</MemoryRouter>,
);
await act(async () => {
await boot();
});

expect(themeFromDocument()).toBe("light");
});

it("applies the Aurora default when nothing is stored", async () => {
await act(async () => {
await boot();
});

expect(document.documentElement.classList.contains(LIGHT_CLASS)).toBe(false);
expect(themeFromDocument()).toBe("starry");
});

it("does not depend on any component being mounted", async () => {
// The whole defect in one assertion: no render, no ThemeToggle, no AppLayout,
// and the class is still applied.
localStorage.setItem(THEME_KEY, "light");
await boot();

expect(document.documentElement.classList.contains(LIGHT_CLASS)).toBe(true);
});

it("clears a stale theme-academia class left on the document", async () => {
document.documentElement.classList.add("theme-academia");
localStorage.setItem(THEME_KEY, "light");

await boot();

expect(document.documentElement.classList.contains("theme-academia")).toBe(false);
expect(document.documentElement.classList.contains(LIGHT_CLASS)).toBe(true);
});

it("survives storage being unavailable instead of throwing during boot", async () => {
const spy = vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => {
throw new Error("blocked");
});

// A throw here would happen before render and take the whole app down.
await expect(boot()).resolves.toBe("starry");

spy.mockRestore();
});
});

describe("applying a theme is idempotent and reversible", () => {
it("re-applying the same theme does not stack classes", async () => {
applyTheme("light");
applyTheme("light");

expect(document.documentElement.classList.contains(LIGHT_CLASS)).toBe(true);
expect(document.documentElement.className.match(new RegExp(LIGHT_CLASS, "g"))).toHaveLength(1);
});

it("switching back to Aurora removes the class", () => {
applyTheme("light");
applyTheme("starry");

expect(document.documentElement.classList.contains(LIGHT_CLASS)).toBe(false);
});
});

describe("reduced-motion support is untouched by the theme move", () => {
it("the motion query is still honoured by the aurora layer, not the theme", async () => {
// The theme and motion preferences are independent: applying a theme must not
// consult or alter matchMedia. AuroraBackground owns that behaviour.
const set = vi.spyOn(window, "matchMedia");

localStorage.setItem(THEME_KEY, "light");
await boot();

expect(set).not.toHaveBeenCalled();
set.mockRestore();
});

it("the stylesheet still gates animation behind prefers-reduced-motion", async () => {
const { readFileSync } = await import("node:fs");
const css = readFileSync("src/index.css", "utf8");

expect(css).toContain("@media (prefers-reduced-motion: reduce)");
});
});

describe("the public routes stay reachable under either theme", () => {
it("renders the auth form with Light applied", async () => {
localStorage.setItem(THEME_KEY, "light");
await act(async () => {
await boot();
});

const Auth = (await import("@/pages/Auth")).default;
render(
<MemoryRouter initialEntries={["/auth"]}>
<Auth />
</MemoryRouter>,
);

expect(screen.getAllByRole("tab", { name: /login/i }).length).toBeGreaterThan(0);
expect(themeFromDocument()).toBe("light");
});
});
Loading
Loading