feat(webui): add reading text size preferences (#6325)

* feat(webui): add reading text size preferences

* fix(webui): align loading skeletons with reading typography
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-20 16:33:05 +08:00
1 parent 816c9221a0
commit 282839cc65
48 files changed
+662 -120

No files matched your search

+4 -1
View File
@@ -22,6 +22,7 @@ import { installSkeletonPreviewApi, SkeletonAdditionsFixture } from "./skeleton-
import { NewChatSkeletonFixture } from "./new-chat-skeleton-fixture";
import "../src/globals.css";
import { DiagramFixture } from "./diagram-fixture";
import { TypographyFixture } from "./typography-fixture";
import { HistoryBoundaryFixture } from "./history-boundary-fixture";
const history: UIMessage[] = [
@@ -144,7 +145,9 @@ function AppsFixture() {
if (parameters.get("case") === "skeleton-additions") installSkeletonPreviewApi();
await initializeI18n();
createRoot(document.getElementById("root")!).render(<TooltipProvider>
{parameters.get("case") === "history-boundary"
{parameters.get("case") === "typography"
? <ClientProvider client={railClient} token="fixture"><TypographyFixture /></ClientProvider>
: parameters.get("case") === "history-boundary"
? <ClientProvider client={railClient} token="fixture" webuiCapabilities={["webui.prompt-navigation.v1"]}><HistoryBoundaryFixture local={parameters.has("local")} navigate={parameters.has("navigate")} /></ClientProvider>
: parameters.get("case") === "diagrams"
? <DiagramFixture parameters={parameters} />
+2
View File
@@ -76,11 +76,13 @@ for (const width of [390, 1440]) for (const locale of ["en", "zh-CN"]) {
const notificationDetails = section === "notifications" ? ", .settings-list-inset > .border-t, section > p" : "";
const loaded = await boxes(target.locator(selector + notificationDetails));
const loadedControls = section === "notifications" ? await boxes(target.getByRole("switch")) : null;
const readingControl = section === "appearance" ? await boxes(target.getByRole("radiogroup")) : null;
await page.goto(fixture("settings", "loading", extra));
await settle(page);
const skeletonSelector = section === "overview" ? "[data-overview-skeleton-row]" : section === "models" ? "[data-model-preset-skeleton], .settings-footer" : section === "about" ? ".settings-list-row" : "[data-settings-skeleton-row]";
const skeleton = await boxes(target.locator(skeletonSelector + notificationDetails));
sameBoxes(skeleton, loaded);
if (readingControl) sameBoxes(await boxes(target.locator("[data-skeleton-reading-size]")), readingControl);
if (loadedControls) {
const skeletonControls = await boxes(target.locator("[data-skeleton-switch]"));
sameBoxes(skeletonControls, loadedControls);
+2
View File
@@ -9,6 +9,7 @@ import { ChannelsSettings } from "@/components/settings/system/ChannelsSettings"
import { McpManagementDialog } from "@/components/settings/system/McpManagementDialog";
import { WorkspaceProjectPicker } from "@/components/thread/WorkspaceControls";
import { settings } from "@/dev/gallery/settings";
import { useReadingTypography } from "@/hooks/useReadingTypography";
import { fetchWorkspaceDirectories } from "@/lib/api";
import type { McpPresetInfo, NanobotFeatureInfo } from "@/lib/types";
@@ -22,6 +23,7 @@ const preset: McpPresetInfo = {
};
export function SkeletonFixture({ surface, loading }: { surface: string; loading: boolean }) {
useReadingTypography();
const [model, setModel] = useState("");
const [previewLoading, setPreviewLoading] = useState(loading);
const feature: NanobotFeatureInfo = {
+7 -2
View File
@@ -187,8 +187,12 @@ for (const width of [390, 1440]) {
} finally { release(); }
});
test("file preview skeletons follow code gutters and Markdown controls", async ({ page }) => {
for (const readingTextSize of ["small", "standard", "large"] as const) test(`file preview skeletons follow code gutters and Markdown controls: ${readingTextSize}`, async ({ page }) => {
await page.addInitScript((size) => {
localStorage.setItem("nanobot-webui.settings-preferences", JSON.stringify({ schemaVersion: 1, readingTextSize: size }));
}, readingTextSize);
await page.goto(fixture("file"));
await expect(page.locator("html")).toHaveAttribute("data-reading-text-size", readingTextSize);
await expect(page.getByTestId("viewport-code-rows")).toBeVisible();
const source = await box(page.locator("pre"));
const code = await box(page.locator("[data-highlighted]"));
@@ -202,7 +206,8 @@ for (const width of [390, 1440]) {
const controls = await box(page.getByTestId("file-preview-panel").locator(":scope > div").first());
await page.goto(fixture("markdown", true));
sameBox(await box(status(page).locator("[aria-hidden] > .flex").first()), controls);
const title = await box(status(page).locator(".h-7 > div"));
const title = await box(status(page).locator("[data-file-preview-heading-skeleton]"));
sameBox(title, heading);
expect(title.x).toBe(heading.x);
expect(title.y + title.height / 2).toBe(heading.y + heading.height / 2);
await noOverflow(page);
+105
View File
@@ -0,0 +1,105 @@
import { useEffect, useState } from "react";
import { MessageBubble } from "@/components/MessageBubble";
import { AppearanceSettingsView } from "@/components/settings/overview/AppearanceSettingsView";
import { ThreadComposer } from "@/components/thread/ThreadComposer";
import { DiffSyntaxHighlight } from "@/components/thread/activity/DiffSyntaxHighlight";
import { ThemeProvider, useTheme } from "@/hooks/useTheme";
import { useReadingTypography } from "@/hooks/useReadingTypography";
import { readLocalPreferences, writeLocalPreferences } from "@/lib/local-preferences";
import type { ChatSummary, UIMessage } from "@/lib/types";
const session: ChatSummary = {
key: "websocket:typography", channel: "websocket", chatId: "typography",
createdAt: null, updatedAt: null, title: "排版讨论 Typography", preview: "",
handle: { id: "handle_12345678901234567890123456789012", name: "typography" },
};
const content = `# 阅读,让思路自然延续
排版应当帮助理解,而不是抢走注意力。中文与 English、API identifiers 混排时,也需要清楚的层级与自然的节奏。字号、行高和列宽一起决定阅读体验。
## 保留层级,减少干扰
普通正文使用稳定的字重,**重点内容保持清晰**。Inline code 如 \`readingTextSize\` 仍应与句子协调。A comfortable reading rhythm leaves enough room for the next thought, without making every line feel disconnected.
> 好的工具让人专注于内容。Reading is a conversation between the reader and the page.
### 可执行的检查清单
1. 即时切换字号,保留其他界面偏好。
2. 长段落和 long-unbroken-identifiers-without-spaces-abcdefghijklmnopqrstuvwxyz0123456789 可以换行。
3. 操作仍然可达,导航尺寸保持稳定。
- 嵌套列表保留清楚的缩进。
- 中文、English 与数字 12345 的组合。
- [x] 已完成的任务与正文一致
- [ ] 接下来确认视觉舒适度
| 内容角色 | 示例 | 设计意图 |
| --- | --- | --- |
| 正文 Body | 中文 English 混排 | 舒适、连续的阅读节奏 |
| 标题 Heading | 清楚的内容层级 | 保留结构,而非所有文字同大 |
| Code | configuration.readingTextSize | 完整显示,必要时在局部滚动 |
\`\`\`typescript
// 中文注释与 English code
const preference = { readingTextSize: "standard" };
function welcome(name: string) {
return \`你好,\${name} — keep exploring.\`;
}
\`\`\`
#### 进一步阅读
The quick brown fox jumps over the lazy dog. 继续探索,保持好奇。
<details><summary>展开查看补充说明</summary>
这里的正文与折叠标题也应保持协调,不因字号变化发生裁切。
</details>
`;
const stressContent = `
## 长内容阅读 Long content
${Array.from({ length: 30 }, (_, index) => `${index + 1}. 第 ${index + 1} 项:中文与 English 混排的长列表内容,保持自然换行和清楚的编号。`).join("\n")}
\`\`\`typescript
const longIdentifier = "${"long-path-segment/".repeat(20)}";
${Array.from({ length: 80 }, (_, index) => `const item${index} = "第 ${index + 1} 行 — readable code";`).join("\n")}
\`\`\`
`;
const messages: UIMessage[] = [
{ id: "typography-user", role: "user", content: "请用中文与 English 解释这套排版,保持标题、引用和代码清楚。", createdAt: 1 },
{ id: "typography-answer", role: "assistant", content, createdAt: 2 },
];
export function TypographyFixture() {
useReadingTypography();
const { theme, toggle } = useTheme();
const [preferences, setPreferences] = useState(readLocalPreferences);
const [sent, setSent] = useState<UIMessage[]>([]);
const previewMessages = new URLSearchParams(window.location.search).has("stress")
? messages.map((message) => message.role === "assistant" ? { ...message, content: content + stressContent } : message)
: messages;
useEffect(() => writeLocalPreferences(preferences), [preferences]);
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}
onChangeLocalPrefs={setPreferences} />
</div>
<section className="mx-auto max-w-[var(--content-column-width)] space-y-6 px-4 pb-8" aria-label="Reading preview">
{[...previewMessages, ...sent].map((message) => <MessageBubble key={message.id} message={message} />)}
<div className="overflow-x-auto"><DiffSyntaxHighlight language="typescript" lines={[
{ kind: "delete", content: "const size = 16;", old_lineno: 1, new_lineno: null },
{ kind: "add", content: "const size = preferences.readingTextSize;", old_lineno: null, new_lineno: 1 },
]} /></div>
<ThreadComposer compactWhenIdle sessions={[session]} modelLabel="Fixture" persistDraft={false} onSend={(text) => {
setSent((current) => [...current, { id: `sent-${current.length}`, role: "user", content: text, createdAt: 3 + current.length }]);
}} />
</section>
</main>
</ThemeProvider>;
}
+207
View File
@@ -0,0 +1,207 @@
import { expect, test, type Locator } from "@playwright/test";
async function readMetrics(element: Locator) {
return element.evaluate((node) => {
if (!node.isConnected) return null;
const style = getComputedStyle(node);
return {
size: parseFloat(style.fontSize), line: parseFloat(style.lineHeight), weight: style.fontWeight,
family: style.fontFamily, letterSpacing: style.letterSpacing,
padding: style.padding, autospace: style.getPropertyValue("text-autospace"),
};
});
}
async function metrics(element: Locator): Promise<NonNullable<Awaited<ReturnType<typeof readMetrics>>>> {
let value: Awaited<ReturnType<typeof readMetrics>> = null;
// Streamdown may replace a paragraph while settling its first render.
await expect.poll(async () => {
value = await readMetrics(element);
return value !== null && Number.isFinite(value.size) && Number.isFinite(value.line);
}).toBe(true);
return value!;
}
for (const narrow of [false, true]) {
for (const dark of [false, true]) {
test(`reading hierarchy and stable controls: ${narrow ? "narrow" : "desktop"}, ${dark ? "dark" : "light"}`, async ({ page }, info) => {
await page.setViewportSize(narrow ? { width: 390, height: 844 } : { width: 1440, height: 1000 });
await page.addInitScript((theme) => {
localStorage.setItem("nanobot.locale", "zh-CN");
localStorage.setItem("nanobot-webui.theme", theme);
}, dark ? "dark" : "light");
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);
const stable = await metrics(page.locator(".settings-row").first().locator(".text-control-label"));
const observations = [];
for (const [size, label, bodySize] of [
["small", "阅读字号:小", narrow ? 15 : 16],
["standard", "阅读字号:标准", narrow ? 16 : 18],
["large", "阅读字号:大", narrow ? 18 : 20],
] 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();
await expect(paragraph).toHaveCSS("font-size", `${bodySize}px`);
const body = await metrics(paragraph);
expect(body.size).toBe(bodySize);
expect(body.line).toBeCloseTo(bodySize * 1.8);
expect(body.weight).toBe("400");
expect((await metrics(page.locator("[data-user-text-bubble] p"))).size).toBe(bodySize);
for (const selector of ["blockquote", "ol > li", ".task-list-item"]) {
expect((await metrics(page.locator(`.markdown-content ${selector}`).first())).size).toBe(bodySize);
}
for (const [selector, ratio] of [["h1", 1.5], ["h2", 1.25], ["h3", 1.125], ["h4", 1]] as const) {
const heading = await metrics(page.locator(`.markdown-content ${selector}`));
expect(heading.size).toBeCloseTo(bodySize * ratio);
expect(heading.weight).toBe("600");
}
for (const selector of ["table", "th", "td"]) {
expect((await metrics(page.locator(`.markdown-content ${selector}`).first())).size).toBeCloseTo(bodySize * 0.875);
}
expect((await metrics(page.locator(".code-content pre"))).size).toBeCloseTo(bodySize * 0.875);
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);
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
observations.push({ size, body, widths });
await page.locator(".markdown-content h1").evaluate(node => node.scrollIntoView({ block: "start" }));
await page.screenshot({ path: info.outputPath(`${size}.png`) });
}
await info.attach("text-metrics", { body: JSON.stringify(observations, null, 2), contentType: "application/json" });
await page.getByRole("button", { name: "复制代码", exact: true }).click();
await expect(page.getByRole("button", { name: "已复制", exact: true })).toBeVisible();
await page.locator("summary").click();
await expect(page.getByText("这里的正文与折叠标题也应保持协调,不因字号变化发生裁切。")).toBeVisible();
});
}
}
test("keyboard, tooltip, persistence and unchanged preferences", async ({ page }) => {
await page.addInitScript(() => {
localStorage.setItem("nanobot.locale", "en");
if (!localStorage.getItem("nanobot-webui.settings-preferences")) {
localStorage.setItem("nanobot-webui.settings-preferences", JSON.stringify({
schemaVersion: 1, codeWrap: false, brandLogos: false, activityMode: "expanded", notificationSound: true,
}));
}
});
await page.goto("/browser/fixture.html?case=typography");
const standard = page.getByRole("radio", { name: "Standard reading text", exact: true });
await standard.focus();
await expect(page.getByRole("tooltip")).toHaveText("Standard reading text");
expect(await standard.evaluate(node => node.matches(":focus-visible"))).toBe(true);
await page.keyboard.press("ArrowRight");
const large = page.getByRole("radio", { name: "Large reading text", exact: true });
await expect(large).toBeFocused();
await expect(large).toBeChecked();
await expect(page.locator(".markdown-content p").first()).toHaveCSS("line-height", `${20 * 1.625}px`);
await page.reload();
await expect(page.getByRole("radio", { name: "Large reading text", exact: true })).toBeChecked();
expect(await page.evaluate(() => JSON.parse(localStorage.getItem("nanobot-webui.settings-preferences")!))).toMatchObject({
readingTextSize: "large", codeWrap: false, brandLogos: false, activityMode: "expanded", notificationSound: true,
});
});
test("touch composer keeps literal mention metrics and a safe editable minimum", async ({ browser, baseURL }, info) => {
const context = await browser.newContext({ baseURL, viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true });
try {
const page = await context.newPage();
await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en"));
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]) {
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();
}
}
const input = page.getByRole("textbox", { name: "Message input", exact: true });
await input.fill("中文 English @typography 混排\n多行内容与光标保持一致,继续输入 more text.\n最后一行。");
for (const label of ["Small reading text", "Standard reading text", "Large reading text"]) {
await page.getByRole("radio", { name: label, exact: true }).click();
await input.focus();
const overlay = page.locator(".thread-composer-input > div[aria-hidden]");
await expect(overlay).toContainText("@typography");
const text = await metrics(input);
expect(text.size).toBeGreaterThanOrEqual(16);
expect(await metrics(overlay)).toEqual(text);
expect(text.autospace).toBe("no-autospace");
expect(await input.evaluate(node => node.scrollHeight <= node.clientHeight + 1)).toBe(true);
expect(await page.evaluate(() => visualViewport?.scale)).toBe(1);
}
await input.fill([...Array.from({ length: 18 }, (_, i) => `第 ${i + 1} 行 中文 English @typography 光标与装饰层。`), "最后一行。"].join("\n"));
for (const label of ["Small reading text", "Standard reading text", "Large reading text"]) {
await page.getByRole("radio", { name: label, exact: true }).click();
await input.focus();
await input.press("Control+End");
const overlay = page.locator(".thread-composer-input > div[aria-hidden]");
expect(await input.evaluate(node => node.scrollHeight > node.clientHeight)).toBe(true);
await expect.poll(async () => Math.abs(await input.evaluate(node => node.scrollTop) - await overlay.evaluate(node => node.scrollTop))).toBeLessThanOrEqual(1);
expect(await metrics(overlay)).toEqual(await metrics(input));
}
await page.keyboard.press("End");
await page.keyboard.type("追加文字");
await expect(input).toHaveValue(/最后一行。追加文字$/);
await page.screenshot({ path: info.outputPath("touch-mention-caret.png") });
await page.getByRole("button", { name: "Send message", exact: true }).click();
await expect(page.locator("[data-user-text-bubble]").last()).toContainText("最后一行。追加文字");
} finally {
await context.close();
}
});
test("large narrow reading keeps long lists and code reachable", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.addInitScript(() => {
localStorage.setItem("nanobot.locale", "en");
localStorage.setItem("nanobot-webui.settings-preferences", JSON.stringify({ schemaVersion: 1, readingTextSize: "large" }));
});
await page.goto("/browser/fixture.html?case=typography&stress");
const lastItem = page.getByText("第 30 项:中文与 English 混排的长列表内容,保持自然换行和清楚的编号。", { exact: true });
await lastItem.click();
await expect(lastItem).toBeVisible();
await expect(lastItem).toHaveCSS("font-size", "18px");
const pre = page.locator(".code-content pre").last();
await expect(pre).toContainText('const item79 = "第 80 行 — readable code";');
await expect(pre).toHaveCSS("font-size", "15.75px");
const finalLine = pre.getByText('"第 80 行 — readable code"', { exact: true });
await finalLine.click();
await expect(finalLine).toBeVisible();
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
await page.getByRole("button", { name: "Copy code", exact: true }).last().click();
await expect(page.getByRole("button", { name: "Copied", exact: true })).toBeVisible();
const input = page.getByRole("textbox", { name: "Message input", exact: true });
await input.fill("读完长内容后仍然可以发送。Still usable.");
await page.getByRole("button", { name: "Send message", exact: true }).click();
await expect(page.locator("[data-user-text-bubble]").last()).toContainText("Still usable.");
});