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

+34
View File
@@ -0,0 +1,34 @@
import type { Dispatch, SetStateAction } from "react";
import { useTranslation } from "react-i18next";
import { AppearanceSettingsView } from "@/components/settings/overview/AppearanceSettingsView";
import { useReadingTypography } from "@/hooks/useReadingTypography";
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
import { ThemeProvider, useTheme } from "@/hooks/useTheme";
import { readLocalPreferences, writeLocalPreferences, type LocalPreferences } from "@/lib/local-preferences";
/** Actual appearance controls in a browser-local harness, without a gateway. */
export function AppearanceFixture() {
const { t } = useTranslation();
const { theme, preference, setTheme } = useTheme();
const preferences = useLocalPreferences();
const setPreferences: Dispatch<SetStateAction<LocalPreferences>> = (update) => {
writeLocalPreferences(typeof update === "function" ? update(readLocalPreferences()) : update);
};
useReadingTypography();
return <ThemeProvider theme={theme}>
<main className="h-full overflow-y-auto bg-background" data-appearance-fixture>
<header className="flex items-center gap-2 text-caption text-muted-foreground" style={{ maxWidth: 800, margin: "0 auto", padding: "28px 32px" }}>
<img src="/brand/nanobot_mark.svg" className="h-5 w-5" alt="" />
<span className="font-medium text-foreground">nanobot</span><span aria-hidden>/</span><span>{t("settings.nav.appearance")}</span>
</header>
<div style={{ containerType: "inline-size", maxWidth: 800, margin: "0 auto", padding: "0 16px 64px" }}>
<div className="settings-grid" style={{ margin: 0, width: "100%", maxWidth: "none" }}>
<h1 className="font-semibold tracking-tight" style={{ fontSize: 28, marginBottom: 20, paddingInline: "var(--settings-inset, 16px)" }}>{t("settings.nav.appearance")}</h1>
<AppearanceSettingsView themePreference={preference} onChangeTheme={setTheme}
localPrefs={preferences} onChangeLocalPrefs={setPreferences} />
</div>
</div>
</main>
</ThemeProvider>;
}
+222
View File
@@ -0,0 +1,222 @@
import { expect, test } from "@playwright/test";
test.beforeEach(async ({ page }) => {
await page.route("**/api/**", (route) => route.abort());
});
test("system theme stays live, explicit choices persist, and tabs agree", async ({ page, context }) => {
await page.emulateMedia({ colorScheme: "light" });
await page.goto("/browser/fixture.html?case=appearance");
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();
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 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 expect(page.getByRole("radio", { name: "Light", exact: true })).toBeChecked();
await expect(page.locator("html")).not.toHaveClass(/dark/);
});
test("custom reading size previews, persists and survives preset changes", async ({ page }) => {
await page.addInitScript(() => {
if (!localStorage.getItem("nanobot-webui.settings-preferences")) {
localStorage.setItem("nanobot-webui.settings-preferences", JSON.stringify({
schemaVersion: 1, notificationSound: true, browserNotifications: true, brandLogos: false,
}));
}
});
await page.goto("/browser/fixture.html?case=appearance");
const title = page.getByRole("heading", { name: "Appearance", exact: true });
const titleSize = await title.evaluate((element) => getComputedStyle(element).fontSize);
await page.getByRole("spinbutton", { name: "Custom text size", exact: true }).click();
const input = page.getByRole("spinbutton", { name: "Custom text size" });
await input.fill("23");
const paragraph = page.locator("[data-reading-preview-content] .markdown-content p").first();
await expect(paragraph).toHaveCSS("font-size", "23px");
await expect(page.locator("[data-reading-preview-content] code")).toHaveCSS("font-size", "20.125px");
await input.press("ArrowUp");
await input.press("Enter");
await expect(input).toHaveValue("24");
await page.reload();
await expect(input).toHaveValue("24");
await page.getByRole("radio", { name: "Small reading text", exact: true }).click();
await expect(paragraph).toHaveCSS("font-size", "16px");
await page.getByRole("spinbutton", { name: "Custom text size", exact: true }).click();
await expect(input).toHaveValue("24");
await expect(paragraph).toHaveCSS("font-size", "24px");
await expect(title).toHaveCSS("font-size", titleSize);
expect(await page.evaluate(() => JSON.parse(localStorage.getItem("nanobot-webui.settings-preferences")!))).toMatchObject({
readingTextSize: "custom", customReadingTextSize: 24, notificationSound: true, browserNotifications: true, brandLogos: false,
});
});
for (const narrow of [false, true]) {
test(`appearance remains usable at maximum size: ${narrow ? "narrow dark" : "desktop light"}`, async ({ page }, info) => {
await page.setViewportSize(narrow ? { width: 390, height: 844 } : { width: 1280, height: 1000 });
await page.addInitScript((dark) => {
localStorage.setItem("nanobot.locale", "zh-CN");
localStorage.setItem("nanobot-webui.theme", dark ? "dark" : "light");
}, narrow);
await page.goto("/browser/fixture.html?case=appearance");
await page.getByRole("spinbutton", { name: "自定义字号", exact: true }).click();
await page.getByRole("spinbutton", { name: "自定义字号" }).fill("28");
await expect(page.locator("[data-reading-preview-content] .markdown-content p").first()).toHaveCSS("font-size", "28px");
expect(await page.locator("main").evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true);
const checkbox = page.getByRole("switch", { name: "品牌图标" });
await checkbox.click();
await expect(checkbox).toHaveAttribute("aria-checked", "false");
await page.getByRole("button", { name: "折叠修改", exact: true }).click();
await expect(page.getByText("默认收起代码差异,需要时点开。", { exact: true })).toBeVisible();
await page.locator("main").evaluate((element) => element.scrollTo(0, 0));
await page.screenshot({ path: info.outputPath("appearance.png") });
});
}
test("changing a custom size reflows an existing composer and its mention layer", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.goto("/browser/fixture.html?case=typography");
await page.getByRole("spinbutton", { name: "Custom text size", exact: true }).click();
await page.getByRole("spinbutton", { name: "Custom text size" }).fill("14");
const composer = page.getByRole("textbox", { name: "Message input", exact: true });
await composer.fill("Hello @typography\nKeep reading\nAnother thought");
await expect(composer).toHaveCSS("font-size", "16px");
const before = (await composer.boundingBox())!.height;
await page.getByRole("spinbutton", { name: "Custom text size" }).fill("28");
await expect(composer).toHaveCSS("font-size", "28px");
await expect.poll(async () => (await composer.boundingBox())!.height).toBeGreaterThan(before);
expect(await composer.evaluate((element) => element.scrollHeight <= element.clientHeight + 1)).toBe(true);
await expect(page.locator(".thread-composer-input > div[aria-hidden]")).toHaveCSS("font-size", "28px");
await expect(composer).toHaveValue("Hello @typography\nKeep reading\nAnother thought");
});
test("long localized labels fit a small phone without hiding their meaning", async ({ browser, baseURL }) => {
const context = await browser.newContext({ baseURL, viewport: { width: 320, height: 800 }, hasTouch: true, isMobile: true });
try {
const page = await context.newPage();
await page.route("**/api/**", (route) => route.abort());
await page.goto("/browser/fixture.html?case=appearance&lang=fr");
const custom = page.locator(".appearance-size-options").getByRole("spinbutton");
await page.locator(".appearance-custom-label").tap();
await expect(custom).toBeFocused();
await expect(custom).toHaveCSS("font-size", "16px");
const hint = page.getByRole("tooltip");
await expect(hint).toBeVisible();
const hintSurface = page.locator("[data-radix-popper-content-wrapper]").filter({ has: hint });
const hintBox = (await hintSurface.boundingBox())!;
expect(hintBox.x).toBeGreaterThanOrEqual(0);
expect(hintBox.x + hintBox.width).toBeLessThanOrEqual(320);
expect(await page.locator(".appearance-theme-label, .appearance-size-options, .appearance-custom-label, .appearance-size-options button").evaluateAll(
(elements) => elements.every((element) => element.scrollWidth <= element.clientWidth + 1 && element.scrollHeight <= element.clientHeight + 1),
)).toBe(true);
const labelBox = (await page.locator(".appearance-custom-label").boundingBox())!;
const fieldBox = (await page.locator(".appearance-custom-option").boundingBox())!;
expect(fieldBox.height).toBeGreaterThanOrEqual(44);
expect(labelBox.y).toBeGreaterThan(fieldBox.y);
expect(labelBox.y + labelBox.height).toBeLessThan((await custom.boundingBox())!.y + 1);
} finally {
await context.close();
}
});
test("the inline custom field is keyboard-editable without moving the size control", async ({ page }) => {
await page.goto("/browser/fixture.html?case=appearance");
const preset = page.getByRole("radio", { name: "Large reading text", exact: true });
await preset.click();
const input = page.getByRole("spinbutton", { name: "Custom text size", exact: true });
const before = (await input.boundingBox())!;
await preset.press("Tab");
await expect(input).toBeFocused();
await input.pressSequentially("22");
await expect(input).toHaveValue("22");
await input.press("Enter");
await expect(page.locator("[data-reading-preview-content] .markdown-content p").first()).toHaveCSS("font-size", "22px");
const after = (await input.boundingBox())!;
expect(after.y).toBe(before.y);
expect(after.height).toBe(before.height);
const presetBox = (await preset.boundingBox())!;
const groupBox = (await page.locator(".appearance-size-presets").boundingBox())!;
const customBox = (await page.locator(".appearance-custom-option").boundingBox())!;
expect(Math.abs((customBox.y + customBox.height / 2) - (presetBox.y + presetBox.height / 2))).toBeLessThan(1);
expect(customBox.height).toBe(groupBox.height);
expect(presetBox.width).toBe(presetBox.height);
expect(customBox.x - (groupBox.x + groupBox.width)).toBeGreaterThanOrEqual(8);
await input.fill("");
await input.press("Enter");
await expect(input).toHaveValue("22");
});
test("reading-size guidance opens on hover and focus, and invalid entries explain what stays saved", async ({ page }) => {
await page.goto("/browser/fixture.html?case=appearance");
const input = page.getByRole("spinbutton", { name: "Custom text size", exact: true });
await input.hover();
const hint = page.getByRole("tooltip");
await expect(hint).toContainText("Enter a whole number from 14 to 28 px.");
await expect(page.getByRole("radio", { name: "Standard reading text" })).toBeChecked();
await input.click();
await expect(hint).toContainText("the composer stays at least 16px");
await input.fill("40");
await input.press("Enter");
await expect(input).toHaveValue("40");
await expect(input).toHaveAttribute("aria-invalid", "true");
await expect(hint).toContainText("Your text remains at 18 px.");
await expect(page.locator("[data-reading-preview-content] .markdown-content p").first()).toHaveCSS("font-size", "18px");
await input.fill("22");
await input.press("Enter");
await expect(input).not.toHaveAttribute("aria-invalid", "true");
await expect(page.locator("[data-reading-preview-content] .markdown-content p").first()).toHaveCSS("font-size", "22px");
await expect(hint).toBeHidden();
await page.reload();
await expect(input).toHaveValue("22");
});
test("the visible Custom label activates the same inline editor from a preset", async ({ page }) => {
await page.goto("/browser/fixture.html?case=appearance");
const label = page.locator(".appearance-custom-label");
const input = page.getByRole("spinbutton", { name: "Custom text size", exact: true });
await label.click();
await expect(input).toBeFocused();
await input.pressSequentially("23");
await input.press("Enter");
await expect(page.locator("[data-reading-preview-content] .markdown-content p").first()).toHaveCSS("font-size", "23px");
await page.getByRole("radio", { name: "Small reading text", exact: true }).click();
await label.click();
await expect(input).toBeFocused();
await expect(input).toHaveValue("23");
await expect(page.locator("[data-reading-preview-content] .markdown-content p").first()).toHaveCSS("font-size", "23px");
});
test("unfinished numeric input reports an error instead of acting like a cleared field", async ({ page }) => {
await page.goto("/browser/fixture.html?case=appearance");
const input = page.getByRole("spinbutton", { name: "Custom text size", exact: true });
const paragraph = page.locator("[data-reading-preview-content] .markdown-content p").first();
for (const text of ["-", "1e"]) {
await input.click();
await input.pressSequentially(text);
expect(await input.evaluate((element: HTMLInputElement) => element.validity.badInput)).toBe(true);
await input.press("Enter");
await expect(input).toHaveAttribute("aria-invalid", "true");
await expect(page.getByRole("tooltip", { name: /Your text remains at 18 px\./ })).toBeVisible();
await expect(paragraph).toHaveCSS("font-size", "18px");
await input.click();
await input.press("Escape");
await expect(input).toHaveValue("18");
await expect(input).not.toHaveAttribute("aria-invalid", "true");
await input.press("Tab");
}
await input.fill("22");
await input.press("Enter");
await expect(paragraph).toHaveCSS("font-size", "22px");
await input.fill("");
await input.press("Enter");
await expect(input).toHaveValue("22");
await expect(input).not.toHaveAttribute("aria-invalid", "true");
});
+9 -2
View File
@@ -15,7 +15,8 @@ import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle, Dia
import { TooltipProvider } from "@/components/ui/tooltip";
import { Button } from "@/components/ui/button";
import { SettingsIcon } from "@/components/icons/product-icons";
import { initializeI18n } from "@/i18n";
import { initializeI18n, setAppLanguage } from "@/i18n";
import { normalizeLocale } from "@/i18n/config";
import type { McpPresetInfo, UIMessage } from "@/lib/types";
import { SkeletonFixture } from "./skeleton-fixture";
import { installSkeletonPreviewApi, SkeletonAdditionsFixture } from "./skeleton-additions-fixture";
@@ -42,6 +43,7 @@ import { ThemeToggleFixture } from "./theme-toggle-fixture";
import { DisplayMathFixture } from "./display-math-fixture";
import { AttachmentLayoutFixture } from "./attachment-layout-fixture";
import { LoadedSessionSearchFixture } from "./loaded-session-search-fixture";
import { AppearanceFixture } from "./appearance-fixture";
const history: UIMessage[] = [
{ id: "question", role: "user", content: "Earlier question", createdAt: 1_700_000_000_000 },
@@ -214,8 +216,13 @@ function AppsFixture() {
if (parameters.get("case") === "skeleton-additions") installSkeletonPreviewApi();
if (parameters.get("case") === "idle-compaction") installIdleCompactionApi();
await initializeI18n();
if (parameters.get("case") === "appearance" && parameters.has("lang")) {
await setAppLanguage(normalizeLocale(parameters.get("lang")));
}
createRoot(document.getElementById("root")!).render(<TooltipProvider>
{parameters.get("case") === "loaded-session-search"
{parameters.get("case") === "appearance"
? <AppearanceFixture />
: parameters.get("case") === "loaded-session-search"
? <LoadedSessionSearchFixture />
: parameters.get("case") === "attachments"
? <AttachmentLayoutFixture />
+2 -2
View File
@@ -57,8 +57,8 @@ export function IdleCompactionFixture() {
<button onClick={() => { failNext = true; }}>Fail next save</button>
<output aria-label="Persisted minutes">{String(snapshot.runtime_config?.[path])}</output>
</div>
<SettingsView theme="light" initialSection="runtime" initialSettings={initial}
onSettingsChange={setSnapshot} onToggleTheme={() => {}} onBackToChat={() => {}}
<SettingsView themePreference="light" initialSection="runtime" initialSettings={initial}
onSettingsChange={setSnapshot} onChangeTheme={() => {}} onBackToChat={() => {}}
onModelNameChange={() => {}} onRestart={() => {}} />
</div>
</ClientProvider>;
+1 -1
View File
@@ -129,7 +129,7 @@ function SkeletonSurface() {
automationsError: state === "error" ? "Preview read failed" : null,
},
}}
theme={dark ? "dark" : "light"} showSidebar mainNavigationExpanded={false} onToggleTheme={noop} onBackToChat={noop}
themePreference={dark ? "dark" : "light"} showSidebar mainNavigationExpanded={false} onChangeTheme={noop} onBackToChat={noop}
skills={empty ? [] : [skill]} skillsLoading={loading && empty} skillsError={state === "error"} isRestarting={false} hostChromeInset={false} /></div>
: <main className="settings-grid mx-auto w-full p-4" style={surface === "automations" ? { maxWidth: 960 } : undefined}>
{surface === "chats" ? <div style={{ height: 440, width: 280, maxWidth: "100%" }} className="bg-sidebar"><ChatList sessions={empty ? [] : sessions} activeKey={null} loading={loading} density={density}
+2 -2
View File
@@ -77,7 +77,7 @@ const messages: UIMessage[] = [
export function TypographyFixture() {
useReadingTypography();
const { theme, toggle } = useTheme();
const { theme, preference, setTheme } = useTheme();
const [preferences, setPreferences] = useState(readLocalPreferences);
const [sent, setSent] = useState<UIMessage[]>([]);
const previewMessages = new URLSearchParams(window.location.search).has("stress")
@@ -87,7 +87,7 @@ export function TypographyFixture() {
return <ThemeProvider theme={theme}>
<main className="h-full overflow-y-auto">
<div className="settings-grid mx-auto py-6">
<AppearanceSettingsView theme={theme} onToggleTheme={toggle} localPrefs={preferences}
<AppearanceSettingsView themePreference={preference} onChangeTheme={setTheme} localPrefs={preferences}
onChangeLocalPrefs={setPreferences} />
</div>
<section className="mx-auto max-w-[var(--content-column-width)] space-y-6 px-4 pb-8" aria-label="Reading preview">
+14 -24
View File
@@ -32,18 +32,7 @@ for (const narrow of [false, true]) {
await page.goto("/browser/fixture.html?case=typography");
const group = page.getByRole("radiogroup", { name: "阅读字号", exact: true });
await expect(group.getByRole("radio", { name: "阅读字号:标准", exact: true })).toBeChecked();
const heights = await group.evaluate((control) => {
const row = control.closest(".settings-row")!;
const nextRow = row.nextElementSibling!;
return {
readingRow: row.getBoundingClientRect().height,
otherRow: nextRow.getBoundingClientRect().height,
readingControl: control.getBoundingClientRect().height,
otherControl: nextRow.querySelector(".segmented-control")!.getBoundingClientRect().height,
};
});
expect(heights.readingRow).toBe(heights.otherRow);
expect(heights.readingControl).toBe(heights.otherControl);
await expect(group.getByRole("radio")).toHaveCount(3);
const stable = await metrics(page.locator(".settings-row").first().locator(".text-control-label"));
const observations = [];
for (const [size, label, bodySize] of [
@@ -53,7 +42,7 @@ for (const narrow of [false, true]) {
] as const) {
await group.getByRole("radio", { name: label, exact: true }).click();
await expect(page.locator("html")).toHaveAttribute("data-reading-text-size", size);
const paragraph = page.locator(".markdown-content p").first();
const paragraph = page.locator('section[aria-label="Reading preview"] .markdown-content p').first();
await expect(paragraph).toHaveCSS("font-size", `${bodySize}px`);
const body = await metrics(paragraph);
expect(body.size).toBe(bodySize);
@@ -75,10 +64,17 @@ for (const narrow of [false, true]) {
expect((await metrics(page.locator(".markdown-inline-code"))).size).toBeCloseTo(bodySize * 0.875);
expect((await metrics(page.locator("textarea"))).size).toBe(Math.max(16, bodySize));
expect(await metrics(page.locator(".settings-row").first().locator(".text-control-label"))).toEqual(stable);
const widths = await group.getByRole("radio").evaluateAll((nodes) => nodes.map(node => node.getBoundingClientRect().width));
expect(Math.max(...widths) - Math.min(...widths)).toBeLessThan(1);
const targets = await group.getByRole("radio").evaluateAll((nodes) => nodes.map((node) => {
const { width, height } = node.getBoundingClientRect();
return { width, height };
}));
// Fine-pointer presets are circular; the separate touch test protects 44px hit targets.
for (const target of targets) {
expect(target.width).toBeGreaterThanOrEqual(36);
expect(target.width).toBe(target.height);
}
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
observations.push({ size, body, widths });
observations.push({ size, body, targets });
await page.locator(".markdown-content h1").evaluate(node => node.scrollIntoView({ block: "start" }));
await page.screenshot({ path: info.outputPath(`${size}.png`) });
}
@@ -125,19 +121,13 @@ test("touch composer keeps literal mention metrics and a safe editable minimum",
await page.goto("/browser/fixture.html?case=typography");
const readingGroup = page.getByRole("radiogroup", { name: "Reading text size", exact: true });
await expect(readingGroup.getByRole("radio")).toHaveCount(3);
const heights = await readingGroup.evaluate((control) => {
const row = control.closest(".settings-row")!;
const nextRow = row.nextElementSibling!;
return [row.getBoundingClientRect().height, nextRow.getBoundingClientRect().height];
});
expect(heights[0]).toBe(heights[1]);
const radios = await readingGroup.getByRole("radio").all();
for (const [index, radio] of radios.entries()) {
await radio.scrollIntoViewIfNeeded();
const target = await radio.boundingBox();
expect(target!.width).toBeGreaterThanOrEqual(44);
// The shared switch pattern extends the hit area without growing the pill.
for (const edge of [-21, 21]) {
expect(target!.height).toBeGreaterThanOrEqual(44);
for (const edge of [-20, 20]) {
await radios[(index + 1) % radios.length].tap();
await page.touchscreen.tap(target!.x + target!.width / 2, target!.y + target!.height / 2 + edge);
await expect(radio).toBeChecked();