Skip to content

Commit 9f4d9e6

Browse files
feat(studio): a light and dark theme toggle in the header that remembers the choice (#4839)
* feat(studio): a light and dark theme toggle in the header that remembers the choice The sun and moon button flips Studio between Graphite light and dark with a circular reveal, saves the choice, and follows the system until one is made. * fix(studio): studio opens light the first time, then keeps the saved theme * fix(studio): drop the theme field's comment, the theme owner states the rule * fix(studio): the theme toggle shows only in studio's own app and follows the theme on screen A host that embeds StudioApp gets no toggle; the button reads the document's theme, the reveal drops the default crossfade, and reduced motion skips it. * fix(studio): the theme reveal leaves other view transitions alone; one default for the toggle The crossfade rule applies only while the toggle's own transition runs, StudioApp passes the header's single default through, and the reveal's reduced-motion and keyboard paths are tested. * fix(studio): a second theme click mid-reveal keeps the crossfade off Only the latest reveal clears the document marker; tests pin the marker while a reveal runs and the circle's radius. * refactor(studio): the theme toggle shares its icon props and reads as plain functions Simplify pass: one icon props object for the sun and moon, no useCallback around a handler nothing memoises, cannotReveal named for what it answers, the test reuses the theme reader. * fix(studio): studio's own app turns the theme toggle on through context; tests parse index.html App.tsx stays at main's size: main.tsx provides ShowThemeToggle and the header reads it, default off for hosts. The boot-script tests read index.html through DOMParser instead of an HTML regex.
1 parent b6c879c commit 9f4d9e6

9 files changed

Lines changed: 331 additions & 11 deletions

File tree

‎packages/studio/index.html‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,15 @@
55
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
66
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
77
<title>HyperFrames Studio</title>
8+
<script>
9+
// Before the first paint: the theme the toggle saved, else light (owner: src/utils/studioTheme.ts).
10+
try {
11+
if (JSON.parse(localStorage.getItem("hf-studio-ui-preferences") || "{}").theme !== "dark")
12+
document.documentElement.dataset.theme = "paper";
13+
} catch (e) {
14+
document.documentElement.dataset.theme = "paper";
15+
}
16+
</script>
817
</head>
918
<body>
1019
<div data-hf-id="hf-aph5" id="root"></div>

‎packages/studio/src/components/StudioHeader.dom.test.tsx‎

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ vi.mock("../contexts/PanelLayoutContext", () => ({
4242
vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() }));
4343

4444
const { StudioHeader } = await import("./StudioHeader");
45+
const { ShowThemeToggle } = await import("./ThemeToggle");
4546

4647
let mounted: { root: Root; host: HTMLElement } | null = null;
4748

@@ -54,28 +55,38 @@ beforeEach(() => {
5455
});
5556

5657
afterEach(() => {
58+
delete document.documentElement.dataset.theme;
5759
if (!mounted) return;
5860
const { root, host } = mounted;
5961
mounted = null;
6062
act(() => root.unmount());
6163
host.remove();
6264
});
6365

64-
function mount(props: { inspectorButtonActive?: boolean } = {}): HTMLElement {
66+
function mount(
67+
props: { inspectorButtonActive?: boolean; themeToggle?: boolean } = {},
68+
): HTMLElement {
6569
const host = document.createElement("div");
6670
document.body.append(host);
6771
const root = createRoot(host);
6872
mounted = { root, host };
73+
const header = (
74+
<StudioHeader
75+
captureFrameHref="blob:frame"
76+
captureFrameFilename="frame.png"
77+
handleCaptureFrameClick={vi.fn()}
78+
refreshCaptureFrameTime={vi.fn()}
79+
inspectorButtonActive={props.inspectorButtonActive ?? false}
80+
inspectorPanelActive={false}
81+
/>
82+
);
6983
act(() =>
7084
root.render(
71-
<StudioHeader
72-
captureFrameHref="blob:frame"
73-
captureFrameFilename="frame.png"
74-
handleCaptureFrameClick={vi.fn()}
75-
refreshCaptureFrameTime={vi.fn()}
76-
inspectorButtonActive={props.inspectorButtonActive ?? false}
77-
inspectorPanelActive={false}
78-
/>,
85+
props.themeToggle ? (
86+
<ShowThemeToggle.Provider value>{header}</ShowThemeToggle.Provider>
87+
) : (
88+
header
89+
),
7990
),
8091
);
8192
return host;
@@ -179,3 +190,14 @@ it("classifies the new header controls for the hotkey filters as the old ones we
179190
expect(shouldIgnorePlaybackShortcutTarget(el), el.tagName).toBe(true);
180191
}
181192
});
193+
194+
it("shows no theme toggle and leaves the host's data-theme alone when embedded", () => {
195+
document.documentElement.dataset.theme = "host";
196+
const host = mount();
197+
expect(host.querySelector('[aria-label^="Switch to"]')).toBeNull();
198+
expect(document.documentElement.dataset.theme).toBe("host");
199+
});
200+
201+
it("shows the theme toggle in Studio's own app", () => {
202+
expect(mount({ themeToggle: true }).querySelector('[aria-label^="Switch to"]')).not.toBeNull();
203+
});

‎packages/studio/src/components/StudioHeader.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { MouseEvent } from "react";
1+
import { useContext, type MouseEvent } from "react";
22
import { Camera } from "../icons/SystemIcons";
33
import { useStudioShellContext } from "../contexts/StudioContext";
44
import { usePanelLayoutContext } from "../contexts/PanelLayoutContext";
@@ -7,6 +7,7 @@ import { Button, buttonBase, buttonSizes, buttonVariants, cn, Tooltip } from "./
77
import { Dock } from "./dock/Dock";
88
import { InspectorIcon } from "./icons/InspectorIcon";
99
import { HyperframesLogo } from "./ui/HyperframesLogo";
10+
import { ShowThemeToggle, ThemeToggle } from "./ThemeToggle";
1011

1112
export interface StudioHeaderProps {
1213
captureFrameHref: string;
@@ -44,6 +45,7 @@ export function StudioHeader({
4445
inspectorPanelActive,
4546
onExport,
4647
}: StudioHeaderProps) {
48+
const showThemeToggle = useContext(ShowThemeToggle);
4749
const { projectId, renderQueue } = useStudioShellContext();
4850
const { rightCollapsed, setRightCollapsed, setRightPanelTab } = usePanelLayoutContext();
4951
const isRendering = renderQueue.isRendering;
@@ -147,6 +149,7 @@ export function StudioHeader({
147149
</Button>
148150
</Tooltip>
149151
</div>
152+
{showThemeToggle && <ThemeToggle />}
150153
<Dock.WindowMenu />
151154
<Tooltip
152155
label={
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import { createContext } from "react";
2+
import { setStudioTheme, useShownStudioTheme } from "../utils/studioTheme";
3+
import { IconButton, Tooltip } from "./ui";
4+
5+
// hyperframes.dev's theme toggle: the same sun and moon, revealing the new theme in a circle from
6+
// the button. A page that paints no frame aborts the transition; the theme is applied by then.
7+
let latest: ViewTransition | null = null;
8+
9+
function reveal(transition: ViewTransition, at: string, radiusPct: number) {
10+
latest = transition;
11+
const done = () => {
12+
if (latest === transition) delete document.documentElement.dataset.themeReveal;
13+
};
14+
void transition.finished.then(done, done);
15+
void transition.ready.then(
16+
() => {
17+
document.documentElement.animate(
18+
{ clipPath: [`circle(0% ${at})`, `circle(${radiusPct}% ${at})`] },
19+
{ duration: 500, easing: "ease-in-out", pseudoElement: "::view-transition-new(root)" },
20+
);
21+
},
22+
() => {},
23+
);
24+
}
25+
26+
function origin(e: React.MouseEvent<HTMLButtonElement>): [number, number] {
27+
if (e.detail > 0) return [e.clientX, e.clientY];
28+
const box = e.currentTarget.getBoundingClientRect();
29+
return [box.left + box.width / 2, box.top + box.height / 2];
30+
}
31+
32+
/** On only in Studio's own app; a host that embeds Studio owns its theme. */
33+
export const ShowThemeToggle = createContext(false);
34+
35+
function cannotReveal(): boolean {
36+
return (
37+
!document.startViewTransition ||
38+
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true
39+
);
40+
}
41+
42+
const iconProps = {
43+
width: "14",
44+
height: "14",
45+
viewBox: "0 0 24 24",
46+
fill: "none",
47+
stroke: "currentColor",
48+
strokeWidth: "2",
49+
strokeLinecap: "round",
50+
strokeLinejoin: "round",
51+
"aria-hidden": true,
52+
} as const;
53+
54+
export function ThemeToggle() {
55+
const isDark = useShownStudioTheme() === "dark";
56+
const label = `Switch to ${isDark ? "light" : "dark"} theme`;
57+
58+
function toggle(e: React.MouseEvent<HTMLButtonElement>) {
59+
const apply = () => setStudioTheme(isDark ? "light" : "dark");
60+
if (cannotReveal()) return apply();
61+
const [x, y] = origin(e);
62+
const w = window.innerWidth;
63+
const h = window.innerHeight;
64+
const maxRadius = Math.hypot(Math.max(x, w - x), Math.max(y, h - y));
65+
const at = `at ${(x / w) * 100}% ${(y / h) * 100}%`;
66+
const radiusPct = (maxRadius / (Math.hypot(w, h) / Math.SQRT2)) * 100;
67+
// The switch stays synchronous inside the callback: rendering is paused during it.
68+
document.documentElement.dataset.themeReveal = "";
69+
reveal(document.startViewTransition(apply), at, radiusPct);
70+
}
71+
72+
return (
73+
<Tooltip label={label} side="bottom">
74+
<IconButton
75+
onClick={toggle}
76+
aria-label={label}
77+
icon={
78+
isDark ? (
79+
<svg {...iconProps}>
80+
<circle cx="12" cy="12" r="5" />
81+
<line x1="12" y1="1" x2="12" y2="3" />
82+
<line x1="12" y1="21" x2="12" y2="23" />
83+
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />
84+
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
85+
<line x1="1" y1="12" x2="3" y2="12" />
86+
<line x1="21" y1="12" x2="23" y2="12" />
87+
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />
88+
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
89+
</svg>
90+
) : (
91+
<svg {...iconProps}>
92+
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
93+
</svg>
94+
)
95+
}
96+
/>
97+
</Tooltip>
98+
);
99+
}

‎packages/studio/src/main.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { StrictMode } from "react";
22
import { createRoot } from "react-dom/client";
33
import { IconContext } from "@phosphor-icons/react";
44
import { StudioApp } from "./App";
5+
import { ShowThemeToggle } from "./components/ThemeToggle";
56
import { StudioErrorBoundary } from "./components/StudioErrorBoundary";
67
import { readIconTokens } from "./styles/iconTokens";
78
import { trackStudioEvent } from "./utils/studioTelemetry";
@@ -128,7 +129,9 @@ createRoot(document.getElementById("root")!).render(
128129
Icons that pass their own size or weight still win. */}
129130
<IconContext.Provider value={readIconTokens()}>
130131
<StudioErrorBoundary>
131-
<StudioApp />
132+
<ShowThemeToggle.Provider value>
133+
<StudioApp />
134+
</ShowThemeToggle.Provider>
132135
</StudioErrorBoundary>
133136
</IconContext.Provider>
134137
</StrictMode>,

‎packages/studio/src/styles/studio.css‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@
1616
}
1717
}
1818

19+
[data-theme-reveal]::view-transition-old(root),
20+
[data-theme-reveal]::view-transition-new(root) {
21+
animation: none;
22+
mix-blend-mode: normal;
23+
}
24+
1925
body {
2026
margin: 0;
2127
padding: 0;
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
// @vitest-environment happy-dom
2+
import { readFileSync } from "node:fs";
3+
import path from "node:path";
4+
import { act } from "react";
5+
import { afterEach, describe, expect, it, vi } from "vitest";
6+
import { ThemeToggle } from "../components/ThemeToggle";
7+
import { cleanupMounted, mountHost } from "../components/ui/mountHost.testHelpers";
8+
import { savedStudioTheme, shownStudioTheme } from "./studioTheme";
9+
10+
const KEY = "hf-studio-ui-preferences";
11+
const page = new DOMParser().parseFromString(
12+
readFileSync(path.join(__dirname, "../../index.html"), "utf8"),
13+
"text/html",
14+
);
15+
const scripts = [...page.querySelectorAll("script")];
16+
const boot = scripts.find((script) => !script.type)?.textContent ?? "";
17+
18+
function store(theme: unknown) {
19+
localStorage.setItem(KEY, JSON.stringify({ theme }));
20+
}
21+
22+
function boots(): "light" | "dark" {
23+
new Function(boot)();
24+
return shownStudioTheme();
25+
}
26+
27+
afterEach(() => {
28+
cleanupMounted();
29+
localStorage.clear();
30+
delete document.documentElement.dataset.theme;
31+
});
32+
33+
describe("Studio's theme", () => {
34+
it.each([["light"], ["dark"], [undefined], ["neon"]])(
35+
"boots to the theme the owner picks (saved %s)",
36+
(saved) => {
37+
store(saved);
38+
expect(boots()).toBe(savedStudioTheme());
39+
},
40+
);
41+
42+
it.each([["null"], ["{not json"], ['"dark"']])("boots to the owner's pick from %s", (raw) => {
43+
localStorage.setItem(KEY, raw);
44+
expect(boots()).toBe(savedStudioTheme());
45+
});
46+
47+
it("opens light the first time", () => {
48+
expect(boots()).toBe("light");
49+
expect(savedStudioTheme()).toBe("light");
50+
});
51+
52+
it("runs the boot script before the app's module", () => {
53+
expect(boot).toContain(`"${KEY}"`);
54+
expect(scripts.findIndex((script) => !script.type)).toBeLessThan(
55+
scripts.findIndex((script) => script.type === "module"),
56+
);
57+
});
58+
59+
it("flips the document between light and dark and keeps the choice", async () => {
60+
store("dark");
61+
const host = mountHost(<ThemeToggle />);
62+
const button = () => host.querySelector("button")!;
63+
expect(button().getAttribute("aria-label")).toBe("Switch to light theme");
64+
65+
await act(async () => button().click());
66+
expect(document.documentElement.dataset.theme).toBe("paper");
67+
expect(JSON.parse(localStorage.getItem(KEY)!).theme).toBe("light");
68+
expect(button().getAttribute("aria-label")).toBe("Switch to dark theme");
69+
70+
await act(async () => button().click());
71+
expect(document.documentElement.dataset.theme).toBeUndefined();
72+
expect(JSON.parse(localStorage.getItem(KEY)!).theme).toBe("dark");
73+
});
74+
75+
it("follows the theme on screen, not only its own clicks", async () => {
76+
store("light");
77+
const host = mountHost(<ThemeToggle />);
78+
expect(host.querySelector("button")!.getAttribute("aria-label")).toBe("Switch to light theme");
79+
await act(async () => {
80+
document.documentElement.dataset.theme = "paper";
81+
});
82+
expect(host.querySelector("button")!.getAttribute("aria-label")).toBe("Switch to dark theme");
83+
});
84+
});
85+
86+
describe("the reveal", () => {
87+
function stubTransition() {
88+
const animate = vi.fn();
89+
Object.assign(document.documentElement, { animate });
90+
const markers: (string | undefined)[] = [];
91+
const finish: (() => void)[] = [];
92+
const start = vi.fn((update: () => void) => {
93+
markers.push(document.documentElement.dataset.themeReveal);
94+
update();
95+
return { ready: Promise.resolve(), finished: new Promise<void>((done) => finish.push(done)) };
96+
});
97+
Object.assign(document, { startViewTransition: start });
98+
return { animate, start, markers, finish };
99+
}
100+
101+
afterEach(() => {
102+
Reflect.deleteProperty(document, "startViewTransition");
103+
Reflect.deleteProperty(document.documentElement, "animate");
104+
vi.unstubAllGlobals();
105+
});
106+
107+
it("grows from the button's centre when the keyboard presses it, marked while it runs", async () => {
108+
const { animate, markers, finish } = stubTransition();
109+
vi.stubGlobal("innerWidth", 1000);
110+
vi.stubGlobal("innerHeight", 500);
111+
const button = mountHost(<ThemeToggle />).querySelector("button")!;
112+
button.getBoundingClientRect = () => ({ left: 890, top: 10, width: 20, height: 20 }) as DOMRect;
113+
await act(async () => {
114+
button.dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 0 }));
115+
});
116+
expect(markers).toEqual([""]);
117+
expect(animate.mock.calls[0]![0].clipPath[1]).toMatch(/^circle\(129\.0\d*% at 90% 4%\)$/);
118+
await act(async () => finish[0]!());
119+
expect(document.documentElement.dataset.themeReveal).toBeUndefined();
120+
});
121+
122+
it("keeps the marker for a second reveal that starts before the first ends", async () => {
123+
const { finish } = stubTransition();
124+
const button = mountHost(<ThemeToggle />).querySelector("button")!;
125+
await act(async () => button.click());
126+
await act(async () => button.click());
127+
await act(async () => finish[0]!());
128+
expect(document.documentElement.dataset.themeReveal).toBe("");
129+
await act(async () => finish[1]!());
130+
expect(document.documentElement.dataset.themeReveal).toBeUndefined();
131+
});
132+
133+
it("switches without the reveal under reduced motion", async () => {
134+
const { start } = stubTransition();
135+
vi.stubGlobal("matchMedia", (query: string) => ({ matches: query.includes("reduce") }));
136+
const button = mountHost(<ThemeToggle />).querySelector("button")!;
137+
await act(async () => button.click());
138+
expect(start).not.toHaveBeenCalled();
139+
expect(document.documentElement.dataset.theme).toBe("paper");
140+
});
141+
});

0 commit comments

Comments
 (0)