fix(webui): crossfade theme changes as one page (#6459)

* fix(webui): crossfade theme changes as one page

* test(webui): align selection highlight motion checks

Follow the shared CSS transition contract instead of obsolete Tailwind utilities. Verify normal geometry easing and reduced-motion theme paint in the browser without changing accepted theme behavior or relaxing CI gates.
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-25 23:54:06 +08:00
1 parent 4701218719
commit 83b6112843
20 files changed
+538 -67

No files matched your search

+7 -3
View File
@@ -10,17 +10,21 @@ test("system theme stays live, explicit choices persist, and tabs agree", async
await expect(page.getByRole("radio", { name: "System", exact: true })).toBeChecked();
await page.emulateMedia({ colorScheme: "dark" });
await expect(page.locator("html")).toHaveClass(/dark/);
await page.getByRole("radio", { name: "Light", exact: true }).check();
// Native theme snapshots commit the selected preference after capture.
await page.getByRole("radio", { name: "Light", exact: true }).click();
await expect(page.getByRole("radio", { name: "Light", exact: true })).toBeChecked();
await expect(page.locator("html")).not.toHaveClass(/dark/);
await page.reload();
await expect(page.getByRole("radio", { name: "Light", exact: true })).toBeChecked();
await expect(page.locator("html")).not.toHaveClass(/dark/);
await page.getByRole("radio", { name: "System", exact: true }).check();
await page.getByRole("radio", { name: "System", exact: true }).click();
await expect(page.getByRole("radio", { name: "System", exact: true })).toBeChecked();
await expect(page.locator("html")).toHaveClass(/dark/);
const other = await context.newPage();
await other.goto("/browser/fixture.html?case=appearance");
await expect(other.getByRole("radio", { name: "System", exact: true })).toBeChecked();
await other.getByRole("radio", { name: "Light", exact: true }).check();
await other.getByRole("radio", { name: "Light", exact: true }).click();
await expect(other.getByRole("radio", { name: "Light", exact: true })).toBeChecked();
await expect(page.getByRole("radio", { name: "Light", exact: true })).toBeChecked();
await expect(page.locator("html")).not.toHaveClass(/dark/);
});
+58 -9
View File
@@ -1,3 +1,11 @@
import { useState } from "react";
import { createPortal } from "react-dom";
import { Sidebar } from "@/components/Sidebar";
import { PaneWorkbench } from "@/components/workbench/PaneWorkbench";
import { ThreadViewport } from "@/components/thread/ThreadViewport";
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
import { formatQuotedUserMessage } from "@/lib/user-message-quote";
import type { ChatSummary, UIMessage } from "@/lib/types";
import { ThreadComposer } from "@/components/thread/ThreadComposer";
import { ThreadHeader } from "@/components/thread/ThreadHeader";
import { ThemeProvider, useTheme } from "@/hooks/useTheme";
@@ -6,15 +14,56 @@ export function ThemeToggleFixture() {
const { theme, toggle } = useTheme();
return (
<ThemeProvider theme={theme}>
<main className="thread-workspace relative flex h-screen flex-col justify-center gap-8 bg-background px-6">
<ThreadHeader title="Theme preview" hideTitle theme={theme} onToggleTheme={toggle} onToggleSidebar={() => {}} />
<div className="workbench-body bg-background">
<section className="workbench-pane flex flex-col gap-8 bg-background">
<h1 data-testid="hero-greeting" className="text-center text-4xl text-foreground">Where should we start?</h1>
<ThreadComposer variant="hero" onSend={() => {}} />
</section>
</div>
</main>
{new URLSearchParams(location.search).has("chat") ? <ThemeChatFixture theme={theme} toggle={toggle} /> : (
<main data-theme-surface className="thread-workspace relative flex flex-col justify-center gap-8 bg-background px-6" style={{ height: "100vh" }}>
<div className="absolute inset-x-0 top-0">
<ThreadHeader title="Theme preview" hideTitle theme={theme} onToggleTheme={toggle} onToggleSidebar={() => {}} />
</div>
<div className="workbench-body">
<section data-theme-surface className="workbench-pane flex flex-col gap-8 bg-background">
<h1 data-testid="hero-greeting" data-theme-ink className="text-center text-4xl text-foreground">Where should we start?</h1>
<ThreadComposer variant="hero" onSend={() => {}} />
</section>
</div>
</main>
)}
</ThemeProvider>
);
}
const sessions: ChatSummary[] = ["Theme chat", "Another chat"].map((title, index) => ({
key: `websocket:theme-${index}`, channel: "websocket", chatId: `theme-${index}`,
title, preview: "", createdAt: null, updatedAt: null,
}));
const messages: UIMessage[] = [
{ id: "user", role: "user", content: formatQuotedUserMessage("Keep the surface layers in sync.", "Quoted context has its own translucent fill."), createdAt: 1 },
{ id: "answer", role: "assistant", content: "An existing conversation with a portaled composer.", createdAt: 2 },
{ id: "session", role: "user", content: "An incoming session message.", createdAt: 3,
sessionMessage: { message_id: "incoming", session: { id: "handle_0123456789abcdef0123456789abcdef", name: "nori" } } },
];
const noop = () => {};
function ThemeChatFixture({ theme, toggle }: { theme: "light" | "dark"; toggle: () => void }) {
const [activeKey, setActiveKey] = useState(sessions[0].key);
const composer = <ThreadComposer onSend={noop} />;
return <main data-theme-surface className="flex bg-background" style={{ height: "100vh" }}>
<aside className="hidden w-64 shrink-0 sm:block">
<Sidebar sessions={sessions} activeKey={activeKey} onSelect={setActiveKey} loading={false} newChatActive={false}
onNewChat={noop} onRequestDelete={noop} onTogglePin={noop} onRequestRename={async () => {}}
onToggleArchive={noop} onToggleGroup={noop} onRequestRenameProject={noop} onNewChatInProject={noop}
onOpenSettings={noop} onOpenApps={noop} onOpenSkills={noop} onOpenAutomations={noop}
onOpenChannels={noop} onOpenSearch={noop} onToggleArchived={noop} />
</aside>
<div className="min-w-0 flex-1">
<PaneWorkbench panes={[{ key: "theme", title: "Theme chat" }]} activePaneKey="theme" layout="columns"
showLayoutControl={false} onActivatePane={noop} onAddPane={noop} onLayoutChange={noop} onPaneOrderChange={noop}
renderPane={(_pane, context) => <div className="relative flex min-h-0 flex-1 flex-col">
<ThreadHeader title="Theme chat" hideTitle theme={theme} onToggleTheme={toggle} onToggleSidebar={noop} />
<ThreadViewport messages={messages} isStreaming={false} conversationKey={activeKey}
navigationFrame={context.navigationFrame} composer={null} />
<ThreadHistoryStatus loading={false} error={null} exhausted onRetry={noop} />
{context.composerPortalTarget && createPortal(composer, context.composerPortalTarget)}
</div>} />
</div>
</main>;
}
+217 -4
View File
@@ -16,10 +16,18 @@ for (const width of [1440, 390]) {
expect(await icon.evaluate(node => node.getAnimations({ subtree: true }).length)).toBe(0);
const initialBox = await toggle.boundingBox();
await toggle.click();
await expect(page.locator("html")).toHaveClass(/dark/);
const intermediate = await icon.evaluate(async node => {
await new Promise(requestAnimationFrame);
const changed = new Promise<void>(resolve => {
const observer = new MutationObserver(() => {
if (node.getAttribute("data-theme") !== "dark") return;
observer.disconnect();
resolve();
});
observer.observe(node, { attributes: true, attributeFilter: ["data-theme"] });
});
node.closest<HTMLButtonElement>("button")!.click();
await changed;
// Sample in the commit microtask, before a protocol round-trip can outlive the morph.
const transitions = node.getAnimations({ subtree: true });
for (const transition of transitions) {
transition.pause();
@@ -31,6 +39,7 @@ for (const width of [1440, 390]) {
for (const transition of transitions) transition.play();
return result;
});
await expect(page.locator("html")).toHaveClass(/dark/);
expect(intermediate.count).toBeGreaterThan(0);
expect(intermediate.radius).toBeGreaterThan(5);
expect(intermediate.radius).toBeLessThan(8);
@@ -38,7 +47,8 @@ for (const width of [1440, 390]) {
expect(intermediate.opacity).toBeLessThan(1);
expect(await toggle.boundingBox()).toEqual(initialBox);
await toggle.click();
const toggleBox = (await toggle.boundingBox())!;
await page.mouse.click(toggleBox.x + toggleBox.width / 2, toggleBox.y + toggleBox.height / 2);
await expect(icon).toHaveAttribute("data-theme", "dark");
const input = page.getByRole("textbox");
await input.fill("Typing stays available during the theme change");
@@ -93,3 +103,206 @@ test("reduced motion keeps the canvas fade but switches the icon directly", asyn
await expect(core).toHaveCSS("r", "5px");
expect(await icon.evaluate(node => node.getAnimations({ subtree: true }).length)).toBe(0);
});
for (const width of [1440, 390]) {
for (const initial of ["light", "dark"] as const) {
test(`reduced motion fades existing chat surfaces together from ${initial} at ${width}px`, async ({ page }) => {
await page.emulateMedia({ reducedMotion: "reduce" });
await page.setViewportSize({ width, height: 844 });
await page.addInitScript((theme) => {
localStorage.setItem("nanobot.locale", "en");
localStorage.setItem("nanobot-webui.theme", theme);
}, initial);
await page.goto("/browser/fixture.html?case=theme-toggle&chat");
const input = page.getByRole("textbox");
await input.fill("Keep this draft while changing theme");
const inputBox = await input.boundingBox();
await expect(page.locator("[data-user-text-bubble]").first()).toBeInViewport();
const selectors = [
".thread-workspace", ".workbench-pane", ".thread-composer-surface",
"[data-testid='thread-header'] > div:last-child", "[data-user-text-bubble] p",
"blockquote", "[data-session-message] > div:last-child",
];
const readPaint = () => page.evaluate((targets) => targets.map(selector =>
getComputedStyle(document.querySelector(selector)!).backgroundColor), selectors);
const before = await readPaint();
await page.getByRole("button", { name: "Toggle theme from header", exact: true }).click();
const middle = await page.evaluate(async (targets) => {
await new Promise(requestAnimationFrame);
const transitions = document.getAnimations().filter(animation => animation instanceof CSSTransition);
for (const transition of transitions) {
transition.pause();
transition.currentTime = 140;
}
const style = (selector: string) => getComputedStyle(document.querySelector(selector)!);
const result = {
paint: targets.map(selector => style(selector).backgroundColor),
footer: style(".workbench-composer-footer").backgroundColor,
sidebarFooter: style("nav > div:last-child").backgroundColor,
gradient: style(".thread-history-status").getPropertyValue("--thread-history-background"),
highlight: style("[data-testid='chats-selection-highlight']").transitionProperty,
rowAction: style(".sidebar-action-trigger").transitionProperty,
};
for (const transition of transitions) transition.finish();
return result;
}, selectors);
await expect.poll(() => page.locator("html").getAttribute("data-theme-transition")).toBeNull();
const after = await readPaint();
for (const [index, selector] of selectors.entries()) {
expect(middle.paint[index], `${selector} must not snap to the target palette`).not.toBe(after[index]);
expect(middle.paint[index], `${selector} must leave the old palette`).not.toBe(before[index]);
}
// These in-flow wrappers now reveal their painted parent instead of adding a second canvas.
expect(middle.footer).toBe("rgba(0, 0, 0, 0)");
expect(middle.sidebarFooter).toBe("rgba(0, 0, 0, 0)");
expect(middle.gradient).toBe(middle.paint[0]);
expect(middle.highlight).toContain("background-color");
expect(middle.rowAction).toBe("opacity");
await expect(input).toHaveValue("Keep this draft while changing theme");
expect(await input.boundingBox()).toEqual(inputBox);
});
}
}
for (const width of [1440, 390]) {
for (const initial of ["light", "dark"] as const) {
test(`crossfades the whole ${initial === "light" ? "dark" : "light"} palette without a blank stage at ${width}px`, async ({ page }) => {
await page.setViewportSize({ width, height: 844 });
await page.addInitScript((theme) => {
localStorage.setItem("nanobot.locale", "en");
if (!localStorage.getItem("nanobot-webui.theme")) localStorage.setItem("nanobot-webui.theme", theme);
}, initial);
await page.goto("/browser/fixture.html?case=theme-toggle&chat");
const toggle = page.getByRole("button", { name: "Toggle theme from header", exact: true });
const input = page.getByRole("textbox");
await input.fill("Crossfade keeps the draft and layout");
const box = await input.boundingBox();
await expect(page.locator("[data-user-text-bubble]").first()).toBeInViewport();
await toggle.focus();
await page.keyboard.press("Space");
await expect.poll(() => page.evaluate(() => document.getAnimations().filter(animation => animation instanceof CSSAnimation
&& animation.animationName.startsWith("theme-crossfade-")).length)).toBe(2);
const middle = await page.evaluate(() => {
const root = document.documentElement;
const fades = document.getAnimations().filter(animation => animation instanceof CSSAnimation
&& animation.animationName.startsWith("theme-crossfade-"));
for (const fade of fades) {
fade.pause();
fade.currentTime = 100;
}
const oldTheme = getComputedStyle(root, "::view-transition-old(root)");
const newTheme = getComputedStyle(root, "::view-transition-new(root)");
return {
durations: fades.map(fade => fade.effect!.getTiming().duration),
canvas: getComputedStyle(document.querySelector(".workbench-pane")!).backgroundColor,
bubble: getComputedStyle(document.querySelector("[data-user-text-bubble] p")!).backgroundColor,
oldOpacity: Number(oldTheme.opacity), newOpacity: Number(newTheme.opacity),
oldBlend: oldTheme.mixBlendMode, newBlend: newTheme.mixBlendMode,
isolation: getComputedStyle(root, "::view-transition-image-pair(root)").isolation,
mask: newTheme.maskImage, clip: newTheme.clipPath,
};
});
expect(middle.durations).toEqual([200, 200]);
expect(middle.canvas).toBe(initial === "light" ? "rgb(48, 48, 48)" : "rgb(255, 255, 255)");
expect(middle.bubble).toBe(initial === "light" ? "rgba(56, 56, 56, 0.7)" : "rgba(245, 245, 245, 0.7)");
expect(middle.oldOpacity).toBeCloseTo(0.5);
expect(middle.newOpacity).toBeCloseTo(0.5);
expect(middle.oldOpacity + middle.newOpacity).toBeCloseTo(1);
expect(middle.oldBlend).toBe("plus-lighter");
expect(middle.newBlend).toBe("plus-lighter");
expect(middle.isolation).toBe("isolate");
expect(middle.mask).toBe("none");
expect(middle.clip).toBe("none");
await expect(toggle).toBeFocused();
expect(await input.boundingBox()).toEqual(box);
await page.screenshot({ path: test.info().outputPath(`crossfade-${width}-${initial}-mid.png`), animations: "allow" });
// Keyboard input still reaches the live DOM while the native snapshots are paused.
await page.keyboard.press("Space");
for (let step = 0; step < 20 && !await input.evaluate(node => node === document.activeElement); step++) {
await page.keyboard.press("Tab");
}
await expect(input).toBeFocused();
await page.keyboard.type(" — typed during the crossfade");
await expect(input).toHaveValue("Crossfade keeps the draft and layout — typed during the crossfade");
await page.evaluate(() => document.getAnimations().filter(animation => animation instanceof CSSAnimation
&& animation.animationName.startsWith("theme-crossfade-")).forEach(animation => animation.finish()));
await expect.poll(() => page.locator("html").getAttribute("data-theme-snapshot")).toBeNull();
await expect.poll(() => page.locator("html").getAttribute("data-theme-transition")).toBeNull();
await expect(toggle.locator("svg")).toHaveAttribute("data-theme", initial === "light" ? "dark" : "light");
await page.reload();
await expect(toggle.locator("svg")).toHaveAttribute("data-theme", initial === "light" ? "dark" : "light");
expect(await page.evaluate(() => document.getAnimations().some(animation => animation instanceof CSSAnimation
&& animation.animationName.startsWith("theme-crossfade-")))).toBe(false);
});
}
}
test("browsers without View Transitions keep a working palette fade", async ({ page }) => {
await page.addInitScript(() => {
localStorage.setItem("nanobot-webui.theme", "light");
Object.defineProperty(document, "startViewTransition", { value: undefined });
});
await page.goto("/browser/fixture.html?case=theme-toggle&chat");
await page.getByRole("button", { name: "Toggle theme from header", exact: true }).click();
await expect(page.locator("html")).toHaveClass(/dark/);
const midpoint = await page.locator(".workbench-pane").evaluate(async node => {
await new Promise(requestAnimationFrame);
const paint = node.getAnimations().filter(animation => animation instanceof CSSTransition);
paint.forEach(animation => { animation.pause(); animation.currentTime = 140; });
const color = getComputedStyle(node).backgroundColor;
paint.forEach(animation => animation.finish());
return color;
});
expect(midpoint).not.toBe("rgb(48, 48, 48)");
expect(midpoint).not.toBe("rgb(255, 255, 255)");
await expect.poll(() => page.locator("html").getAttribute("data-theme-transition")).toBeNull();
await expect(page.getByRole("textbox")).toBeEditable();
});
test("a browser-skipped transition still applies the theme and releases the toggle", async ({ page }) => {
await page.addInitScript(() => {
localStorage.setItem("nanobot-webui.theme", "light");
const start = document.startViewTransition.bind(document);
document.startViewTransition = (...args) => {
const transition = start(...args);
transition.skipTransition();
return transition;
};
});
await page.goto("/browser/fixture.html?case=theme-toggle&chat");
const toggle = page.getByRole("button", { name: "Toggle theme from header", exact: true });
await toggle.click();
await expect(page.locator("html")).toHaveClass(/dark/);
await expect.poll(() => page.locator("html").getAttribute("data-theme-snapshot")).toBeNull();
await expect.poll(() => page.locator("html").getAttribute("data-theme-transition")).toBeNull();
await toggle.click();
await expect(page.locator("html")).not.toHaveClass(/dark/);
});
test("selection highlights keep geometry easing and only fade paint with reduced motion", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 844 });
await page.addInitScript(() => {
localStorage.setItem("nanobot.locale", "en");
localStorage.setItem("nanobot-webui.theme", "light");
});
await page.goto("/browser/fixture.html?case=theme-toggle&chat");
const highlight = page.getByTestId("chats-selection-highlight");
await expect(highlight).toHaveCSS("transition-property", "transform, width, height, background-color");
await expect(highlight).toHaveCSS("transition-duration", "0.3s, 0.3s, 0.3s, 0s");
await expect(highlight).toHaveCSS("transition-timing-function", "ease-out, ease-out, ease-out, ease");
await page.emulateMedia({ reducedMotion: "reduce" });
await expect(highlight).toHaveCSS("transition-property", "none");
const paint = await highlight.evaluate(node => {
document.querySelector<HTMLButtonElement>("button[aria-label='Toggle theme from header']")!.click();
const style = getComputedStyle(node);
return { property: style.transitionProperty, duration: style.transitionDuration };
});
expect(paint).toEqual({
property: "background-color, border-color, box-shadow",
duration: "0.28s, 0.28s, 0.28s",
});
await expect(page.locator("html")).toHaveClass(/dark/);
await expect.poll(() => page.locator("html").getAttribute("data-theme-transition")).toBeNull();
await expect(highlight).toHaveCSS("transition-property", "none");
});