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

+2
View File
@@ -2889,6 +2889,7 @@ function Shell({
}}
>
<div
data-theme-surface
className={cn(
"absolute inset-y-0 left-0 h-full w-full overflow-hidden",
showHostChrome
@@ -2964,6 +2965,7 @@ function Shell({
</Suspense>
) : null}
<main ref={managementMain}
data-theme-surface
aria-hidden={managingConnections && remoteConnections?.embeddedManagement || undefined}
{...(managingConnections && remoteConnections?.embeddedManagement ? { inert: "" } : {})}
className={cn(
+1 -1
View File
@@ -1829,7 +1829,7 @@ function ProjectGroupHeader({
function ChatsGroupHeader({ label }: { label: string }) {
return (
<div className="px-2 pb-2 pt-2 text-[11px] font-medium leading-4 text-sidebar-muted-foreground">
<div data-theme-ink className="px-2 pb-2 pt-2 text-[11px] font-medium leading-4 text-sidebar-muted-foreground">
{label}
</div>
);
+1
View File
@@ -96,6 +96,7 @@ export function MarkdownText({
const plainFallback = (
<div
data-theme-ink
className={cn(
"whitespace-pre-wrap break-words text-reading text-foreground/92",
streaming && "streaming-text-fallback",
+4 -1
View File
@@ -387,7 +387,7 @@ function IncomingSessionMessage({
<div className="mb-1.5 flex items-center px-4 text-[12px] text-muted-foreground">
<SessionHandleLabel id={handle.id}>{handleName}</SessionHandleLabel>
</div>
<div className="relative min-w-0 rounded-floating bg-secondary/70 px-4 py-2">
<div data-theme-surface className="relative min-w-0 rounded-floating bg-secondary/70 px-4 py-2">
{contextMenu}
<div data-assistant-selectable="true" className="min-w-0">
<MarkdownText
@@ -489,6 +489,7 @@ export function MessageBubble({
<div data-user-text-bubble className="relative ml-auto w-fit max-w-full min-w-0">
{contextMenu}
<p
data-theme-surface
data-temporary-message={temporary ? "true" : undefined}
className={cn(
"ml-auto w-fit max-w-full min-w-0 rounded-floating px-4 py-2",
@@ -561,6 +562,8 @@ export function MessageBubble({
function UserQuotedContext({ text, label }: { text: string; label: string }) {
return (
<blockquote
data-theme-surface
data-theme-ink
className={cn(
"ml-auto flex w-fit max-w-full min-w-0 items-start gap-2 rounded-control",
"border border-border/60 bg-muted/35 px-3 py-2 text-left text-muted-foreground",
+5 -1
View File
@@ -155,6 +155,8 @@ export function Sidebar(props: SidebarProps) {
return (
<nav
data-theme-surface
data-theme-ink
ref={props.containActionMenus ? setMenuPortalContainer : undefined}
aria-label={t("sidebar.navigation")}
className={cn(
@@ -323,8 +325,10 @@ export function Sidebar(props: SidebarProps) {
onRequestUpdate={props.availableUpdate.onRequestUpdate} installationMethod={props.availableUpdate.installationMethod} />
)}
<div
data-theme-surface
className={cn(
"flex items-center justify-between gap-1 bg-sidebar/55 px-2.5 py-3 text-xs",
"flex items-center justify-between gap-1 px-2.5 py-3 text-xs",
props.hostChromeInset && "bg-sidebar/55",
collapsed && "w-14 flex-col px-0",
)}
>
@@ -121,7 +121,7 @@ export function SidebarSelectionHighlight({
data-testid={`${scope}-selection-highlight`}
data-active-id={activeId ?? undefined}
aria-hidden="true"
className={cn("pointer-events-none absolute left-0 top-0 z-0 !mt-0 rounded-control bg-sidebar-foreground/[0.055] opacity-0 transition-[transform,width,height] duration-300 ease-out will-change-transform motion-reduce:transition-none dark:bg-white/[0.07]", highlightClassName)}
className={cn("sidebar-selection-highlight pointer-events-none absolute left-0 top-0 z-0 !mt-0 rounded-control bg-sidebar-foreground/[0.055] opacity-0 will-change-transform dark:bg-white/[0.07]", highlightClassName)}
/>
</div>
);
@@ -126,7 +126,7 @@ export function HostSwitcherView({ picker, status, collapsed = false, portalCont
const current = `${identity}, ${currentLabel}`;
const detail = pendingName ? `${current}. ${t("remote.preparing", { name: pendingName })}` : current;
const button = <Button ref={buttonRef} variant="ghost" size="sm" aria-label={t("remote.switchHost")}
data-host-switcher className={cn("host-no-drag touch-target h-8 min-w-0 gap-2 rounded-xl px-2 text-xs font-normal text-sidebar-content/75 hover:text-sidebar-content",
data-host-switcher data-theme-surface data-theme-ink className={cn("host-no-drag touch-target h-8 min-w-0 gap-2 rounded-xl px-2 text-xs font-normal text-sidebar-content/75 hover:text-sidebar-content",
collapsed ? "w-8 justify-center px-0" : "max-w-full flex-1 justify-start")}
onClick={picker.kind === "embedded" ? () => {
const rect = buttonRef.current?.getBoundingClientRect();
+2 -1
View File
@@ -75,6 +75,7 @@ export function ThreadHeader({
)}
>
<div
data-theme-surface
className={cn(
controlsClassName,
"relative min-w-0",
@@ -111,7 +112,7 @@ export function ThreadHeader({
) : null}
</div>
<div className={cn(controlsClassName, "ml-auto shrink-0")}>
<div data-theme-surface className={cn(controlsClassName, "ml-auto shrink-0")}>
{sessionInfoAction}
{promptNavigatorAction}
{actions}
@@ -335,6 +335,7 @@ function HeroGreeting({ text }: { text: string }) {
<h1
ref={headingRef}
data-testid="hero-greeting"
data-theme-ink
className="select-none whitespace-nowrap text-[34px] font-normal leading-[1.08] tracking-normal text-foreground sm:text-[48px] sm:leading-tight"
>
{text}
@@ -1203,6 +1203,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
<div
ref={composerDockRef}
data-testid="thread-composer-dock"
data-theme-surface
onInputCapture={(event) => {
if (event.target instanceof HTMLTextAreaElement) {
threadMotionRef.current?.handleComposerInput();
@@ -678,6 +678,7 @@ export function PaneWorkbench({
return (
<section
ref={setNavigationFrame}
data-theme-surface
aria-label={t("workbench.aria", { defaultValue: "Conversation workbench" })}
className={cn(
"thread-workspace relative flex h-full min-h-0 flex-col overflow-hidden bg-background",
@@ -693,9 +694,10 @@ export function PaneWorkbench({
/>
</header>
) : null}
<div className="workbench-body relative min-h-0 flex-1 bg-background">
<div className="workbench-body relative min-h-0 flex-1">
<div
ref={gridRef}
data-theme-surface
data-testid="pane-grid"
data-layout={effectiveLayout}
className={cn(
@@ -715,6 +717,7 @@ export function PaneWorkbench({
else paneRefs.current.delete(pane.key);
}}
aria-label={pane.title}
data-theme-surface
data-active={active ? "true" : "false"}
data-dragging={draggingPaneKey === pane.key ? "true" : undefined}
data-testid={`workbench-pane-${pane.key}`}
@@ -830,7 +833,7 @@ export function PaneWorkbench({
</div>
{chrome ? (
<footer className="workbench-composer-footer shrink-0 bg-background px-3 pb-[calc(0.5rem+env(safe-area-inset-bottom))] sm:px-4 sm:pb-[calc(0.75rem+env(safe-area-inset-bottom))]">
<footer className="workbench-composer-footer shrink-0 px-3 pb-[calc(0.5rem+env(safe-area-inset-bottom))] sm:px-4 sm:pb-[calc(0.75rem+env(safe-area-inset-bottom))]">
<div
ref={setComposerPortalTarget}
data-testid="workbench-composer-host"
+46 -3
View File
@@ -30,6 +30,28 @@
}
}
/* Only gradient owners need interpolable colors; palette tokens remain unchanged. */
@property --thread-history-background {
syntax: "<color>";
inherits: false;
initial-value: transparent;
}
@property --host-glass-spot {
syntax: "<color>";
inherits: false;
initial-value: transparent;
}
@property --host-glass-start {
syntax: "<color>";
inherits: false;
initial-value: transparent;
}
@property --host-glass-end {
syntax: "<color>";
inherits: false;
initial-value: transparent;
}
/* Design tokens — HSL form, sourced from shadcn/ui's "neutral" palette. */
@layer base {
:root {
@@ -393,6 +415,12 @@
backdrop-filter: saturate(185%) blur(34px);
}
.host-window-shell {
transition: --host-glass-spot var(--theme-paint-duration, 0s) linear,
--host-glass-start var(--theme-paint-duration, 0s) linear,
--host-glass-end var(--theme-paint-duration, 0s) linear;
}
.host-sidebar-glass {
background: hsl(var(--sidebar) / 0.94);
-webkit-backdrop-filter: saturate(145%) blur(18px);
@@ -444,6 +472,7 @@
--tw-prose-headings: hsl(var(--foreground));
--tw-prose-bold: hsl(var(--foreground));
--tw-prose-lead: hsl(var(--foreground));
transition: var(--theme-ink-transition, color 0s);
@apply text-reading;
}
@@ -631,9 +660,12 @@
}
.thread-history-status {
--thread-history-background: hsl(var(--background));
height: 48px;
background: linear-gradient(hsl(var(--background)) 35%, hsl(var(--background) / 0));
background: linear-gradient(var(--thread-history-background) 35%, transparent);
color: hsl(var(--muted-foreground));
transition: --thread-history-background var(--theme-paint-duration, 0s) linear,
var(--theme-ink-transition, color 0s);
}
.thread-history-reveal {
transform: translateY(calc(var(--history-pull, 0px) - 100%));
@@ -1175,12 +1207,23 @@
}
}
.sidebar-selection-highlight {
transition: transform 300ms ease-out, width 300ms ease-out, height 300ms ease-out,
var(--theme-paint-transition, background-color 0s);
}
@media (prefers-reduced-motion: reduce) {
.sidebar-selection-highlight {
transition: var(--theme-paint-transition, none);
}
}
/* Composer controls adapt to their actual container, not just the viewport. */
.thread-composer-surface {
--composer-shadow-color: 240 10% 16%;
--tw-shadow: inset 0 0 0 1px hsl(var(--border) / 0.75), 0 4px 18px -8px hsl(var(--composer-shadow-color) / 0.12);
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
transition: background-color 160ms ease-out, box-shadow 160ms ease-out, opacity 160ms ease-out;
transition: var(--theme-paint-transition, background-color 160ms ease-out, box-shadow 160ms ease-out), opacity 160ms ease-out;
container-name: thread-composer;
container-type: inline-size;
}
@@ -1190,7 +1233,7 @@
}
@media (prefers-reduced-motion: reduce) {
.thread-composer-surface { transition: none; }
.thread-composer-surface { transition: var(--theme-paint-transition, none); }
}
@media (forced-colors: active) {
+58 -15
View File
@@ -6,25 +6,68 @@
--theme-ink-delay: 100ms;
}
/* Keep text from dissolving into a matching gray while the canvas changes. */
:root[data-theme-transition] :is(
body,
.thread-workspace,
.workbench-body,
.workbench-pane,
main.bg-background,
.bg-sidebar,
.text-sidebar-muted-foreground,
[data-testid="thread-header"] > div,
[data-testid="hero-greeting"]
) {
transition: background-color 280ms linear, border-color 280ms linear, color 0s linear var(--theme-ink-delay);
/* Paint owners opt in; components with local motion compose these lists instead. */
:root[data-theme-transition] {
--theme-paint-duration: 280ms;
--theme-paint-transition: background-color var(--theme-paint-duration) linear, border-color var(--theme-paint-duration) linear, box-shadow var(--theme-paint-duration) linear;
--theme-ink-transition: color 0s linear var(--theme-ink-delay);
}
:root[data-theme-transition] .thread-composer-surface {
transition: background-color 280ms linear, box-shadow 280ms linear, opacity 160ms ease-out;
:root[data-theme-transition] [data-theme-surface] {
transition: var(--theme-paint-transition);
}
/* Delay only explicitly colored ink, not every inheriting layout wrapper. */
:root[data-theme-transition] [data-theme-ink] {
transition: var(--theme-ink-transition);
}
:root[data-theme-transition] :is(body, [data-theme-surface][data-theme-ink]) {
transition: var(--theme-paint-transition), var(--theme-ink-transition);
}
:root[data-theme-transition] .thread-composer-surface textarea::placeholder {
transition: color 0s linear var(--theme-ink-delay);
}
/* Blend complete palettes, without a second layer of per-surface paint interpolation. */
:root[data-theme-snapshot] {
--theme-paint-duration: 0s;
--theme-ink-delay: 0s;
}
:root[data-theme-snapshot]::view-transition {
pointer-events: none;
}
:root[data-theme-snapshot]::view-transition-group(root) {
animation: none;
}
/* Complementary alpha adds to one, rather than exposing an empty frame between themes. */
:root[data-theme-snapshot]::view-transition-image-pair(root) {
isolation: isolate;
}
:root[data-theme-snapshot]::view-transition-old(root),
:root[data-theme-snapshot]::view-transition-new(root) {
mix-blend-mode: plus-lighter;
}
:root[data-theme-snapshot]::view-transition-old(root) {
animation: theme-crossfade-out 200ms ease-in-out both;
}
:root[data-theme-snapshot]::view-transition-new(root) {
animation: theme-crossfade-in 200ms ease-in-out both;
}
@keyframes theme-crossfade-out {
from { opacity: 1; }
to { opacity: 0; }
}
@keyframes theme-crossfade-in {
from { opacity: 0; }
to { opacity: 1; }
}
+57 -16
View File
@@ -8,6 +8,7 @@ import {
useState,
type ReactNode,
} from "react";
import { flushSync } from "react-dom";
import "./theme-transition.css";
import { useMediaQuery } from "@/hooks/useMediaQuery";
@@ -26,6 +27,10 @@ function readStored(): ThemePreference {
}
}
function resolveTheme(preference: ThemePreference, systemDark: boolean): Theme {
return preference === "system" ? (systemDark ? "dark" : "light") : preference;
}
function applyTheme(theme: Theme): void {
const root = document.documentElement;
if (theme === "dark") root.classList.add("dark");
@@ -47,15 +52,19 @@ export function useTheme(): {
} {
const [preference, setPreference] = useState(readStored);
const systemDark = useMediaQuery("(prefers-color-scheme: dark)");
const theme: Theme = preference === "system" ? (systemDark ? "dark" : "light") : preference;
const theme = resolveTheme(preference, systemDark);
const switchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const viewTransition = useRef<ViewTransition | null>(null);
const pendingPreference = useRef<{ value: ThemePreference } | null>(null);
useEffect(() => () => {
if (switchTimer.current !== null) {
clearTimeout(switchTimer.current);
switchTimer.current = null;
delete document.documentElement.dataset.themeTransition;
}
if (switchTimer.current !== null) clearTimeout(switchTimer.current);
switchTimer.current = null;
pendingPreference.current = null;
viewTransition.current?.skipTransition();
viewTransition.current = null;
delete document.documentElement.dataset.themeTransition;
delete document.documentElement.dataset.themeSnapshot;
}, []);
useEffect(() => {
@@ -66,32 +75,64 @@ export function useTheme(): {
const refresh = (event: StorageEvent) => {
if (event.key !== null && event.key !== STORAGE_KEY) return;
if (event.storageArea && event.storageArea !== window.localStorage) return;
setPreference(readStored());
const value = readStored();
if (pendingPreference.current) pendingPreference.current.value = value;
else setPreference(value);
};
window.addEventListener("storage", refresh);
return () => window.removeEventListener("storage", refresh);
}, []);
const setTheme = useCallback((value: ThemePreference) => {
if (value === preference) return;
const next = value === "system" ? (systemDark ? "dark" : "light") : value;
// Changing preference without changing the palette must not start or block a transition.
if (next !== theme) {
if (switchTimer.current !== null) return;
document.documentElement.dataset.themeTransition = next;
const pending = pendingPreference.current;
const selected = pending?.value ?? preference;
if (value === selected) return;
const next = resolveTheme(value, systemDark);
const changesPalette = next !== resolveTheme(selected, systemDark);
const root = document.documentElement;
// Same-palette choices, such as switching to System, must remain selectable.
if (changesPalette) {
if (switchTimer.current !== null || viewTransition.current !== null) return;
root.dataset.themeTransition = next;
switchTimer.current = setTimeout(() => {
delete document.documentElement.dataset.themeTransition;
switchTimer.current = null;
if (viewTransition.current === null) delete root.dataset.themeTransition;
}, 600);
}
setPreference(value);
if (pending) {
// A native capture defers the React commit; retain the latest accepted preference.
pending.value = value;
} else if (changesPalette && document.startViewTransition
&& !window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
const update = { value };
pendingPreference.current = update;
root.dataset.themeSnapshot = "";
const transition = document.startViewTransition(() => {
if (pendingPreference.current !== update) return;
pendingPreference.current = null;
flushSync(() => setPreference(update.value));
});
viewTransition.current = transition;
// Browser-skipped captures still apply their update and must release the owner.
void transition.ready.catch(() => {});
const release = () => {
if (viewTransition.current !== transition) return;
viewTransition.current = null;
delete root.dataset.themeSnapshot;
if (switchTimer.current === null) delete root.dataset.themeTransition;
};
void transition.finished.then(release, release);
} else {
setPreference(value);
}
// Only user choices persist. Resolved system changes and other tabs never write back.
try {
localStorage.setItem(STORAGE_KEY, value);
} catch {
// Browser-only preferences should never block the interface.
}
}, [preference, systemDark, theme]);
}, [preference, systemDark]);
const toggle = useCallback(
() => setTheme(theme === "dark" ? "light" : "dark"),
[setTheme, theme],
+1 -6
View File
@@ -2215,12 +2215,7 @@ describe("App layout", () => {
expect(highlight).not.toHaveClass(
"group-data-[resizing=true]/sidebar:transition-none",
);
expect(highlight).toHaveClass(
"transition-[transform,width,height]",
"duration-300",
"ease-out",
"motion-reduce:transition-none",
);
expect(highlight).toHaveClass("sidebar-selection-highlight");
}
fireEvent.pointerDown(handle, { button: 0, pointerId: 1, clientX: 272 });
fireEvent.pointerMove(handle, { pointerId: 1, clientX: 400 });
+1 -1
View File
@@ -75,7 +75,7 @@ describe("preview tabs", () => {
const highlight = screen.getByTestId("preview-tabs-selection-highlight");
expect(highlight).toHaveAttribute("data-active-id", "file:data.json");
expect(highlight.className).toContain("bg-sidebar-foreground/[0.055]");
expect(highlight.className).toContain("motion-reduce:transition-none");
expect(highlight).toHaveClass("sidebar-selection-highlight");
await waitFor(() => expect(shell.style.getPropertyValue("--file-preview-slot-width")).toBe("544px"));
fireEvent.click(screen.getByRole("tab", { name: "chart.png" }));
expect(screen.getByTestId("preview-pane")).toBe(shell);
+69 -2
View File
@@ -6,6 +6,26 @@ import { useTheme } from "@/hooks/useTheme";
describe("useTheme", () => {
let systemDark = false;
let mediaEvents: EventTarget;
let restoreNativeTransition: (() => void) | undefined;
function deferNativeCapture() {
const previous = Object.getOwnPropertyDescriptor(document, "startViewTransition");
let update!: () => void;
let ready!: () => void;
let finish!: () => void;
const transition = {
ready: new Promise<void>(resolve => { ready = resolve; }),
finished: new Promise<void>(resolve => { finish = resolve; }),
skipTransition: vi.fn(),
};
const start = vi.fn((callback: () => void) => { update = callback; return transition; });
Object.defineProperty(document, "startViewTransition", { configurable: true, value: start });
restoreNativeTransition = () => {
if (previous) Object.defineProperty(document, "startViewTransition", previous);
else Reflect.deleteProperty(document, "startViewTransition");
};
return { start, capture: () => { update(); ready(); }, finish };
}
function changeSystemTheme(dark: boolean) {
act(() => {
@@ -22,8 +42,8 @@ describe("useTheme", () => {
vi.useFakeTimers();
systemDark = false;
mediaEvents = new EventTarget();
vi.stubGlobal("matchMedia", vi.fn(() => ({
get matches() { return systemDark; },
vi.stubGlobal("matchMedia", vi.fn((query: string) => ({
get matches() { return query === "(prefers-color-scheme: dark)" && systemDark; },
addEventListener: mediaEvents.addEventListener.bind(mediaEvents),
removeEventListener: mediaEvents.removeEventListener.bind(mediaEvents),
})));
@@ -40,6 +60,8 @@ describe("useTheme", () => {
afterEach(() => {
cleanup();
restoreNativeTransition?.();
restoreNativeTransition = undefined;
vi.clearAllTimers();
vi.useRealTimers();
vi.restoreAllMocks();
@@ -211,6 +233,51 @@ describe("useTheme", () => {
expect(result.current.theme).toBe("light");
});
it("retains a same-palette System choice before a native capture commits", async () => {
systemDark = true;
localStorage.setItem("nanobot-webui.theme", "light");
const native = deferNativeCapture();
const { result } = renderHook(useTheme);
act(() => result.current.setTheme("dark"));
expect(native.start).toHaveBeenCalledOnce();
expect(localStorage.getItem("nanobot-webui.theme")).toBe("dark");
act(() => result.current.setTheme("light"));
expect(localStorage.getItem("nanobot-webui.theme")).toBe("dark");
act(() => result.current.setTheme("system"));
expect(localStorage.getItem("nanobot-webui.theme")).toBe("system");
act(() => native.capture());
expect(result.current.preference).toBe("system");
expect(result.current.theme).toBe("dark");
changeSystemTheme(false);
expect(result.current.theme).toBe("light");
expect(localStorage.getItem("nanobot-webui.theme")).toBe("system");
await act(async () => native.finish());
act(() => vi.advanceTimersByTime(600));
expect(document.documentElement).not.toHaveAttribute("data-theme-snapshot");
expect(document.documentElement).not.toHaveAttribute("data-theme-transition");
});
it("keeps another tab's newer preference when a native capture is pending", async () => {
localStorage.setItem("nanobot-webui.theme", "light");
const native = deferNativeCapture();
const { result } = renderHook(useTheme);
act(() => result.current.setTheme("dark"));
const write = vi.spyOn(Storage.prototype, "setItem");
localStorage.removeItem("nanobot-webui.theme");
notifyStorageChange();
act(() => native.capture());
expect(result.current.preference).toBe("system");
expect(result.current.theme).toBe("light");
expect(document.documentElement).not.toHaveClass("dark");
expect(write).not.toHaveBeenCalled();
await act(async () => native.finish());
act(() => vi.advanceTimersByTime(600));
expect(document.documentElement).not.toHaveAttribute("data-theme-snapshot");
});
it("ignores rapid reversals for 600ms without replaying them later", () => {
localStorage.setItem("nanobot-webui.theme", "light");
const { result } = renderHook(useTheme);