fix(webui): keep numbered code tokens in one wrapping flow
This commit is contained in:
1 parent
219c8bb2bc
commit
e981e97f10
5 files changed
+100
-1
No files matched your search
@@ -0,0 +1,25 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import { MessageBubble } from "@/components/MessageBubble";
|
||||
|
||||
const source = [
|
||||
"# Environment",
|
||||
"",
|
||||
"- `ncode` 启动器在 `C:\\Users\\reader\\.config\\powershell\\profile.ps1`,使用 `uv run --project D:\\projects\\nanobot`;默认配置在 `C:\\Users\\reader\\.nanobot\\config.json`。",
|
||||
"- 缓存与工具链:npm cache `D:\\cache\\npm`,uv cache `D:\\cache\\uv`,Node/npm 在 `D:\\program\\nodejs`;WezTerm 桌面启动用 `wezterm-gui`。",
|
||||
"- 末行:中文与 English 仍保持连续排版。",
|
||||
].join("\n");
|
||||
|
||||
export function CodeWrappingFixture() {
|
||||
const [code, setCode] = useState(source);
|
||||
const [streaming, setStreaming] = useState(true);
|
||||
return <main className="mx-auto max-w-3xl space-y-4 p-4">
|
||||
<textarea aria-label="Code source" className="h-24 w-full font-mono text-code" value={code}
|
||||
onChange={event => setCode(event.target.value)} />
|
||||
<button onClick={() => setStreaming(false)}>Complete message</button>
|
||||
<MessageBubble message={{
|
||||
id: "wrapped-code", role: "assistant", createdAt: 1, isStreaming: streaming,
|
||||
content: `\`\`\`markdown\n${code}\n\`\`\``,
|
||||
}} />
|
||||
</main>;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
test("numbered Markdown code keeps mixed text flowing after stream completion", async ({ page, context }) => {
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en"));
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
await page.goto("/browser/fixture.html?case=code-wrapping");
|
||||
const source = await page.getByRole("textbox", { name: "Code source" }).inputValue();
|
||||
const block = page.locator('[data-language="markdown"]');
|
||||
await expect(block.getByTestId("plain-code-fallback")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Complete message" }).click();
|
||||
const pre = block.locator("pre");
|
||||
await expect(pre.locator(".token").first()).toBeVisible();
|
||||
await expect(pre.locator(".linenumber")).toHaveText(source.split("\n").map((_, index) => String(index + 1)));
|
||||
|
||||
for (const width of [1280, 390]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
await expect.poll(() => pre.evaluate(element => {
|
||||
const phrase = "启动器在";
|
||||
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
|
||||
let node: Node | null;
|
||||
while ((node = walker.nextNode())) {
|
||||
const start = node.textContent!.indexOf(phrase);
|
||||
if (start < 0) continue;
|
||||
const range = document.createRange();
|
||||
range.setStart(node, start);
|
||||
range.setEnd(node, start + 1);
|
||||
const first = range.getBoundingClientRect();
|
||||
range.setStart(node, start + phrase.length - 1);
|
||||
range.setEnd(node, start + phrase.length);
|
||||
const last = range.getBoundingClientRect();
|
||||
return {
|
||||
horizontal: Math.abs(first.y - last.y) < 1 && last.x > first.x,
|
||||
contained: element.scrollWidth <= element.clientWidth + 1,
|
||||
};
|
||||
}
|
||||
throw new Error("The Chinese phrase is missing from the rendered source");
|
||||
})).toEqual({ horizontal: true, contained: true });
|
||||
}
|
||||
|
||||
await block.getByRole("button", { name: "Copy code", exact: true }).click();
|
||||
await expect.poll(async () => (await page.evaluate(() => navigator.clipboard.readText())).replaceAll("\r\n", "\n")).toBe(source);
|
||||
});
|
||||
@@ -24,6 +24,7 @@ import { NewChatSkeletonFixture } from "./new-chat-skeleton-fixture";
|
||||
import "../src/globals.css";
|
||||
import { DiagramFixture } from "./diagram-fixture";
|
||||
import { TypographyFixture } from "./typography-fixture";
|
||||
import { CodeWrappingFixture } from "./code-wrapping-fixture";
|
||||
import { InlineReferencesFixture } from "./inline-references-fixture";
|
||||
import { HistoryBoundaryFixture } from "./history-boundary-fixture";
|
||||
import { ChatFailureFixture } from "./chat-failure-fixture";
|
||||
@@ -251,6 +252,8 @@ createRoot(document.getElementById("root")!).render(<TooltipProvider>
|
||||
? <ChatFailureFixture parameters={parameters} />
|
||||
: parameters.get("case") === "display-math"
|
||||
? <DisplayMathFixture />
|
||||
: parameters.get("case") === "code-wrapping"
|
||||
? <CodeWrappingFixture />
|
||||
: parameters.get("case") === "typography"
|
||||
? <ClientProvider client={railClient} token="fixture"><TypographyFixture /></ClientProvider>
|
||||
: parameters.get("case") === "inline-references"
|
||||
|
||||
@@ -35,9 +35,11 @@ const LazyHighlightedCode = lazy(async () => {
|
||||
const [
|
||||
{ default: SyntaxHighlighter },
|
||||
{ ViewportCodeRows },
|
||||
{ WrappedCodeRows },
|
||||
] = await Promise.all([
|
||||
import("react-syntax-highlighter/dist/esm/prism-async-light"),
|
||||
import("@/components/ViewportCodeRows"),
|
||||
import("@/components/WrappedCodeRows"),
|
||||
]);
|
||||
|
||||
return {
|
||||
@@ -84,7 +86,8 @@ const LazyHighlightedCode = lazy(async () => {
|
||||
PreTag="pre"
|
||||
showLineNumbers={showLineNumbers && !viewportHighlight}
|
||||
wrapLongLines={wrapLongLines}
|
||||
renderer={viewportHighlight ? props => <ViewportCodeRows {...props} /> : undefined}
|
||||
renderer={viewportHighlight ? props => <ViewportCodeRows {...props} />
|
||||
: showLineNumbers && wrapLongLines ? props => <WrappedCodeRows {...props} /> : undefined}
|
||||
>
|
||||
{code}
|
||||
</SyntaxHighlighter>
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { SyntaxHighlighterProps } from "react-syntax-highlighter";
|
||||
import createElement from "react-syntax-highlighter/dist/esm/create-element";
|
||||
|
||||
type RowsProps = Parameters<NonNullable<SyntaxHighlighterProps["renderer"]>>[0];
|
||||
|
||||
/** Keep inline tokens in one wrapping flow beside the line-number gutter. */
|
||||
export function WrappedCodeRows({ rows, ...props }: RowsProps) {
|
||||
return rows.map((row, index) => {
|
||||
const [lineNumber, ...content] = row.children!;
|
||||
return createElement({
|
||||
...props,
|
||||
key: index,
|
||||
node: {
|
||||
...row,
|
||||
children: [lineNumber, {
|
||||
type: "element",
|
||||
tagName: "span",
|
||||
properties: { className: ["min-w-0", "flex-1"] },
|
||||
children: content,
|
||||
}],
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user