feat(webui): refine appearance and add custom reading sizes

This commit is contained in:
Xubin Ren committed 2026-10-25 22:14:58 +08:00
1 parent b048cf44f7
commit ef8271b2c0
38 files changed
+1148 -213

No files matched your search

+2
View File
@@ -224,6 +224,8 @@ vi.mock("@/hooks/useTheme", async () => {
React.createElement(React.Fragment, null, children),
useTheme: () => ({
theme: "light" as const,
preference: "light" as const,
setTheme: vi.fn(),
toggle: toggleThemeSpy,
}),
useThemeValue: () => "light" as const,
+16
View File
@@ -47,6 +47,22 @@ describe("local preferences", () => {
});
});
it("round-trips a custom reading size without resetting other preferences", () => {
const preferences = { ...DEFAULT_LOCAL_PREFS, readingTextSize: "custom" as const,
customReadingTextSize: 24, notificationSound: true, codeWrap: false };
writeLocalPreferences(preferences);
expect(readLocalPreferences()).toEqual(preferences);
});
it.each([[40, 28], [8, 14], [19.6, 20], ["22", 18], [null, 18]])(
"normalizes persisted custom size %j to %s", (stored, expected) => {
localStorage.setItem(LOCAL_PREFS_STORAGE_KEY, JSON.stringify({
schemaVersion: 1, readingTextSize: "custom", customReadingTextSize: stored, codeWrap: false,
}));
expect(readLocalPreferences()).toMatchObject({ readingTextSize: "custom", customReadingTextSize: expected, codeWrap: false });
},
);
it("keeps browser notifications opt-in", () => {
expect(DEFAULT_LOCAL_PREFS.browserNotifications).toBe(false);
expect(readLocalPreferences().browserNotifications).toBe(false);
@@ -531,9 +531,9 @@ describe("Settings capabilities", () => {
return <ClientProvider client={{ requestMutation: requestMutationMock, status: "open",
onStatus: (handler: (status: "open") => void) => { handler("open"); return () => {}; },
} as never} token="tok">
<SettingsView theme="light" initialSection="voice" initialSettings={snapshot}
<SettingsView themePreference="light" initialSection="voice" initialSettings={snapshot}
onSettingsChange={setSnapshot} onNativeEngineRestart={restart}
onToggleTheme={() => {}} onBackToChat={() => {}} onModelNameChange={() => {}} />
onChangeTheme={() => {}} onBackToChat={() => {}} onModelNameChange={() => {}} />
</ClientProvider>;
}
render(<Parent />);
@@ -182,6 +182,47 @@ describe("Settings overview and appearance", () => {
expect(screen.getByRole("radio", { name: "Large reading text" })).toBeChecked();
});
it("edits and remembers a custom reading size without committing an empty input", async () => {
writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, notificationSound: true, codeWrap: false });
renderSettingsView({ initialSection: "appearance", initialSettings: settingsPayload() });
fireEvent.focus(screen.getByRole("spinbutton", { name: "Custom text size" }));
const input = screen.getByRole("spinbutton", { name: "Custom text size" });
fireEvent.change(input, { target: { value: "" } });
expect(readLocalPreferences().customReadingTextSize).toBe(18);
fireEvent.change(input, { target: { value: "24" } });
await waitFor(() => expect(readLocalPreferences()).toMatchObject({
readingTextSize: "custom", customReadingTextSize: 24, notificationSound: true, codeWrap: false,
}));
fireEvent.click(screen.getByRole("radio", { name: "Standard reading text" }));
fireEvent.focus(screen.getByRole("spinbutton", { name: "Custom text size" }));
expect(screen.getByRole("spinbutton", { name: "Custom text size" })).toHaveValue(24);
const currentInput = screen.getByRole("spinbutton", { name: "Custom text size" });
fireEvent.change(currentInput, { target: { value: "21" } });
expect(readLocalPreferences().customReadingTextSize).toBe(21);
fireEvent.change(currentInput, { target: { value: "40" } });
fireEvent.blur(currentInput);
expect(currentInput).toHaveValue(40);
expect(currentInput).toHaveAttribute("aria-invalid", "true");
expect(readLocalPreferences().customReadingTextSize).toBe(21);
expect(await screen.findByRole("tooltip")).toHaveTextContent("Your text remains at 21 px.");
fireEvent.change(currentInput, { target: { value: "22" } });
expect(currentInput).not.toHaveAttribute("aria-invalid", "true");
expect(readLocalPreferences().customReadingTextSize).toBe(22);
});
it.each(["", "40"])("restores the saved custom size after another tab interrupts draft %j", async (draft) => {
writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, readingTextSize: "custom", customReadingTextSize: 24 });
renderSettingsView({ initialSection: "appearance", initialSettings: settingsPayload() });
fireEvent.change(screen.getByRole("spinbutton", { name: "Custom text size" }), { target: { value: draft } });
act(() => {
localStorage.setItem(LOCAL_PREFS_STORAGE_KEY, JSON.stringify({ ...readLocalPreferences(), schemaVersion: 1, readingTextSize: "small" }));
window.dispatchEvent(new StorageEvent("storage", { key: LOCAL_PREFS_STORAGE_KEY }));
});
await waitFor(() => expect(screen.getByRole("radio", { name: "Small reading text" })).toBeChecked());
fireEvent.focus(screen.getByRole("spinbutton", { name: "Custom text size" }));
expect(screen.getByRole("spinbutton", { name: "Custom text size" })).toHaveValue(24);
});
it("persists the file edit display local preference", async () => {
renderSettingsView({
initialSection: "appearance",
+4 -2
View File
@@ -129,6 +129,8 @@ type SettingsViewTestOptions = Partial<Pick<
React.ComponentProps<typeof SettingsView>,
| "initialSection"
| "initialSettings"
| "themePreference"
| "onChangeTheme"
| "skills"
| "skillsLoading"
| "showSidebar"
@@ -151,14 +153,14 @@ export function renderSettingsView(options: SettingsViewTestOptions = {}) {
},
} as never} token="tok">
<SettingsView
theme="light"
themePreference={options.themePreference ?? "light"}
initialSection={options.initialSection ?? "apps"}
initialSettings={options.initialSettings}
skills={options.skills}
skillsLoading={options.skillsLoading}
showSidebar={options.showSidebar}
mainNavigationExpanded={options.mainNavigationExpanded}
onToggleTheme={() => {}}
onChangeTheme={options.onChangeTheme ?? (() => {})}
onBackToChat={options.onBackToChat ?? (() => {})}
onModelNameChange={() => {}}
onSettingsChange={options.onSettingsChange}
+171 -1
View File
@@ -1,11 +1,32 @@
import { act, renderHook } from "@testing-library/react";
import { act, cleanup, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useTheme } from "@/hooks/useTheme";
describe("useTheme", () => {
let systemDark = false;
let mediaEvents: EventTarget;
function changeSystemTheme(dark: boolean) {
act(() => {
systemDark = dark;
mediaEvents.dispatchEvent(new Event("change"));
});
}
function notifyStorageChange(key: string | null = "nanobot-webui.theme") {
act(() => window.dispatchEvent(new StorageEvent("storage", { key })));
}
beforeEach(() => {
vi.useFakeTimers();
systemDark = false;
mediaEvents = new EventTarget();
vi.stubGlobal("matchMedia", vi.fn(() => ({
get matches() { return systemDark; },
addEventListener: mediaEvents.addEventListener.bind(mediaEvents),
removeEventListener: mediaEvents.removeEventListener.bind(mediaEvents),
})));
localStorage.removeItem("nanobot-webui.theme");
document.documentElement.classList.remove("dark");
@@ -18,8 +39,11 @@ describe("useTheme", () => {
});
afterEach(() => {
cleanup();
vi.clearAllTimers();
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
delete document.documentElement.dataset.themeTransition;
document.querySelector('meta[name="theme-color"]')?.remove();
document.documentElement.classList.remove("dark");
@@ -39,6 +63,152 @@ describe("useTheme", () => {
expect(document.documentElement).not.toHaveClass("dark");
expect(themeColor?.content).toBe("#ffffff");
expect(localStorage.getItem("nanobot-webui.theme")).toBe("light");
expect(result.current.preference).toBe("light");
});
it.each(["light", "dark"] as const)("preserves a previously saved %s choice", (saved) => {
systemDark = saved === "light";
localStorage.setItem("nanobot-webui.theme", saved);
const { result } = renderHook(useTheme);
expect(result.current.preference).toBe(saved);
expect(result.current.theme).toBe(saved);
expect(localStorage.getItem("nanobot-webui.theme")).toBe(saved);
});
it("defaults to system and follows live changes without persisting the resolved theme", () => {
const { result } = renderHook(useTheme);
const themeColor = document.querySelector<HTMLMetaElement>('meta[name="theme-color"]');
expect(result.current.preference).toBe("system");
expect(result.current.theme).toBe("light");
changeSystemTheme(true);
expect(result.current.preference).toBe("system");
expect(result.current.theme).toBe("dark");
expect(document.documentElement).toHaveClass("dark");
expect(themeColor?.content).toBe("#303030");
changeSystemTheme(false);
expect(result.current.theme).toBe("light");
expect(document.documentElement).not.toHaveClass("dark");
expect(themeColor?.content).toBe("#ffffff");
expect(localStorage.getItem("nanobot-webui.theme")).toBeNull();
});
it("restores system preference against the current system theme", () => {
localStorage.setItem("nanobot-webui.theme", "system");
systemDark = true;
const { result } = renderHook(useTheme);
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");
});
it("ignores system changes in explicit mode and resumes the latest system theme", () => {
const { result } = renderHook(useTheme);
act(() => result.current.setTheme("light"));
changeSystemTheme(true);
expect(result.current.preference).toBe("light");
expect(result.current.theme).toBe("light");
expect(document.documentElement).not.toHaveClass("dark");
act(() => result.current.setTheme("system"));
expect(result.current.preference).toBe("system");
expect(result.current.theme).toBe("dark");
expect(document.documentElement).toHaveClass("dark");
expect(localStorage.getItem("nanobot-webui.theme")).toBe("system");
});
it.each([false, true])("toggles the resolved system theme into an explicit choice: dark=%s", (dark) => {
systemDark = dark;
const { result } = renderHook(useTheme);
const selected = dark ? "light" : "dark";
act(() => result.current.toggle());
expect(result.current.preference).toBe(selected);
expect(result.current.theme).toBe(selected);
expect(localStorage.getItem("nanobot-webui.theme")).toBe(selected);
changeSystemTheme(!dark);
changeSystemTheme(dark);
expect(result.current.theme).toBe(selected);
act(() => vi.advanceTimersByTime(600));
act(() => result.current.toggle());
expect(result.current.preference).toBe(dark ? "dark" : "light");
expect(result.current.theme).toBe(dark ? "dark" : "light");
});
it("synchronizes other tabs and storage removal without writing back", () => {
const { result } = renderHook(useTheme);
const write = vi.spyOn(Storage.prototype, "setItem");
localStorage.setItem("nanobot-webui.theme", "dark");
write.mockClear();
notifyStorageChange("nanobot.locale");
expect(result.current.preference).toBe("system");
notifyStorageChange();
expect(result.current.preference).toBe("dark");
expect(result.current.theme).toBe("dark");
expect(document.documentElement).toHaveClass("dark");
expect(write).not.toHaveBeenCalled();
localStorage.removeItem("nanobot-webui.theme");
notifyStorageChange();
expect(result.current.preference).toBe("system");
expect(result.current.theme).toBe("light");
localStorage.setItem("nanobot-webui.theme", "dark");
notifyStorageChange();
localStorage.clear();
write.mockClear();
notifyStorageChange(null);
expect(result.current.preference).toBe("system");
expect(result.current.theme).toBe("light");
expect(write).not.toHaveBeenCalled();
});
it("uses system for unrecognized stored preferences", () => {
systemDark = true;
localStorage.setItem("nanobot-webui.theme", "invalid");
const { result } = renderHook(useTheme);
expect(result.current.preference).toBe("system");
expect(result.current.theme).toBe("dark");
});
it("keeps theme controls usable when browser storage is unavailable", () => {
vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => { throw new Error("Storage blocked"); });
vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { throw new Error("Storage blocked"); });
const { result } = renderHook(useTheme);
expect(result.current.preference).toBe("system");
act(() => result.current.setTheme("dark"));
expect(result.current.preference).toBe("dark");
expect(result.current.theme).toBe("dark");
expect(document.documentElement).toHaveClass("dark");
});
it("can select system during a same-palette transition and still follows OS changes", () => {
systemDark = true;
localStorage.setItem("nanobot-webui.theme", "light");
const { result } = renderHook(useTheme);
act(() => result.current.setTheme("dark"));
expect(document.documentElement).toHaveAttribute("data-theme-transition", "dark");
act(() => result.current.setTheme("system"));
expect(result.current.preference).toBe("system");
expect(result.current.theme).toBe("dark");
expect(localStorage.getItem("nanobot-webui.theme")).toBe("system");
changeSystemTheme(false);
expect(result.current.theme).toBe("light");
expect(localStorage.getItem("nanobot-webui.theme")).toBe("system");
act(() => vi.advanceTimersByTime(600));
expect(document.documentElement).not.toHaveAttribute("data-theme-transition");
expect(result.current.theme).toBe("light");
});
it("ignores rapid reversals for 600ms without replaying them later", () => {