refactor(webui): unify code and diff highlighting (#6412)
* refactor(webui): unify code and diff highlighting Replace Prism with shared Highlights tokens and Pierre read-only diffs, retaining rare grammars through lazy Shiki and preserving source, copy, preview and diff controls. Restore single-session Composer ownership inside the conversation column while retaining the shared multi-pane footer. Keep the measured large-diff scroll regression explicit during review. * fix(webui): contain highlighting errors and retain diff selections Refs NAN-343 * test(webui): align pane fixtures after main rebase * chore(webui): update highlighting dependencies Keep grammar fallback coverage on a language that still requires Shiki, and align reading-size assertions with main.
This commit is contained in:
1 parent
f5c359476b
commit
3a37269f3f
44 files changed
+2261
-1072
No files matched your search
@@ -7,6 +7,12 @@ import { setAppLanguage } from "@/i18n";
|
||||
import { DEFAULT_LOCAL_PREFS, LOCAL_PREFS_STORAGE_KEY, writeLocalPreferences } from "@/lib/local-preferences";
|
||||
import type { CliAppInfo, McpPresetInfo, UIMessage } from "@/lib/types";
|
||||
|
||||
// These DOM tests exercise disclosure/source contracts; the real shadow renderer runs in browser tests.
|
||||
vi.mock("@/components/thread/activity/DiffSyntaxHighlight", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/components/thread/activity/DiffSyntaxHighlight")>();
|
||||
return { ...actual, DiffSyntaxHighlight: actual.PlainDiffLines };
|
||||
});
|
||||
|
||||
const BLENDER_CLI_APP: CliAppInfo = {
|
||||
name: "blender",
|
||||
display_name: "Blender",
|
||||
|
||||
@@ -4088,6 +4088,13 @@ describe("App layout", () => {
|
||||
.toEqual(["Alpha"]);
|
||||
expect(screen.queryByRole("button", { name: "Layout" }))
|
||||
.not.toBeInTheDocument();
|
||||
const alphaInput = screen.getByRole("textbox", { name: "Message Alpha" });
|
||||
expect(screen.getByTestId("workbench-pane-websocket:chat-alpha")).toContainElement(alphaInput);
|
||||
fireEvent.change(alphaInput, { target: { value: "keep this Alpha draft" } });
|
||||
fireEvent.change(alphaInput.closest(".thread-composer-surface")!.querySelector('input[type="file"]')!, {
|
||||
target: { files: [new File(["notes"], "alpha-notes.txt", { type: "text/plain" })] },
|
||||
});
|
||||
expect(within(await screen.findByTestId("composer-chip")).getByRole("button", { name: "alpha-notes.txt" })).toBeVisible();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Add pane" }));
|
||||
expect(screen.queryByRole("dialog", { name: "Search" })).not.toBeInTheDocument();
|
||||
@@ -4163,6 +4170,11 @@ describe("App layout", () => {
|
||||
name: "Remove",
|
||||
}));
|
||||
await waitFor(() => expect(screen.getByTestId("pane-grid").children).toHaveLength(1));
|
||||
fireEvent.click(within(sidebar).getByRole("button", { name: "Alpha" }));
|
||||
const restoredInput = await screen.findByRole("textbox", { name: "Message Alpha" });
|
||||
expect(screen.getByTestId("workbench-pane-websocket:chat-alpha")).toContainElement(restoredInput);
|
||||
expect(restoredInput).toHaveValue("keep this Alpha draft");
|
||||
expect(within(await screen.findByTestId("composer-chip")).getByRole("button", { name: "alpha-notes.txt" })).toBeVisible();
|
||||
const researchGroup = within(sidebar).getByRole("button", {
|
||||
name: "Group: Research",
|
||||
}).closest("[data-sidebar-tab-group]") as HTMLElement;
|
||||
|
||||
@@ -1,31 +1,49 @@
|
||||
import { act, render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { HighlightedCodeProps } from "@/components/HighlightedCode";
|
||||
|
||||
import { CodeBlock } from "@/components/CodeBlock";
|
||||
import { ThemeProvider } from "@/hooks/useTheme";
|
||||
|
||||
vi.mock("react-syntax-highlighter/dist/esm/prism-async-light", () => ({
|
||||
default: ({
|
||||
children,
|
||||
language,
|
||||
customStyle,
|
||||
}: {
|
||||
children: string;
|
||||
language?: string;
|
||||
customStyle?: React.CSSProperties;
|
||||
}) => (
|
||||
<pre
|
||||
data-testid="highlighted-code"
|
||||
data-language={language}
|
||||
style={customStyle}
|
||||
>
|
||||
<code>{children}</code>
|
||||
</pre>
|
||||
),
|
||||
const failures = vi.hoisted(() => new Set<string>());
|
||||
|
||||
// Test CodeBlock's controls and enhancement boundary here; token/DOM rendering has dedicated real-engine and browser coverage.
|
||||
vi.mock("@/components/HighlightedCode", () => ({
|
||||
HighlightedCode: ({ code, language, viewportHighlight }: HighlightedCodeProps) => {
|
||||
if (failures.has(code)) throw new Error("Grammar download failed");
|
||||
return <pre data-testid="highlighted-code" data-language={language || "text"}
|
||||
style={{ overflow: viewportHighlight ? "visible" : "auto" }}><code data-code-text="">{code}</code></pre>;
|
||||
},
|
||||
}));
|
||||
|
||||
describe("CodeBlock", () => {
|
||||
it("contains a failed grammar, preserves source and copy, and enhances changed source", async () => {
|
||||
const source = "; 中文 😀\r\n[server]\r\nhost=localhost\r\n";
|
||||
failures.add(source);
|
||||
const user = userEvent.setup();
|
||||
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
|
||||
const errors = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const warnings = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
try {
|
||||
const { rerender } = render(<><textarea defaultValue="keep draft" /><CodeBlock code={source} language="ini" /></>);
|
||||
await waitFor(() => expect(warnings).toHaveBeenCalledWith("Code highlighting failed.", expect.any(Error)));
|
||||
expect(screen.getByTestId("plain-code-fallback").textContent).toBe(source);
|
||||
expect(screen.getByRole("textbox")).toHaveValue("keep draft");
|
||||
await user.click(screen.getByRole("button", { name: "Copy code" }));
|
||||
expect(writeText).toHaveBeenCalledWith(source);
|
||||
rerender(<><textarea defaultValue="keep draft" /><CodeBlock code={source + "; updated"} language="ini" /></>);
|
||||
expect((await screen.findByTestId("highlighted-code")).textContent).toBe(source + "; updated");
|
||||
expect(screen.getByRole("textbox")).toHaveValue("keep draft");
|
||||
} finally {
|
||||
failures.clear();
|
||||
errors.mockRestore();
|
||||
warnings.mockRestore();
|
||||
Reflect.deleteProperty(navigator, "clipboard");
|
||||
}
|
||||
});
|
||||
|
||||
it("renders and copies a large code block in full without pagination", async () => {
|
||||
const user = userEvent.setup();
|
||||
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||
@@ -37,7 +55,8 @@ describe("CodeBlock", () => {
|
||||
|
||||
try {
|
||||
render(<CodeBlock code={source} language="typescript" showLineNumbers />);
|
||||
expect((await screen.findByTestId("highlighted-code")).textContent).toBe(source);
|
||||
const code = await screen.findByTestId("highlighted-code");
|
||||
expect([...code.querySelectorAll("[data-code-text]")].map(node => node.textContent).join("")).toBe(source);
|
||||
expect(screen.getAllByRole("button")).toHaveLength(1);
|
||||
await user.click(screen.getByRole("button", { name: "Copy code" }));
|
||||
expect(writeText).toHaveBeenCalledWith(source);
|
||||
@@ -179,7 +198,7 @@ describe("CodeBlock", () => {
|
||||
expect(screen.getByText("const value = 1;")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("normalizes file language aliases before loading Prism", async () => {
|
||||
it("normalizes file language aliases before highlighting", async () => {
|
||||
render(
|
||||
<ThemeProvider theme="light">
|
||||
<CodeBlock language="html" code="<main />" />
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CodeTokens } from "@/components/CodeTokens";
|
||||
import { codeHighlight } from "@/lib/code-highlighter";
|
||||
|
||||
async function lines(source: string, language: string) {
|
||||
const resource = codeHighlight(source, language);
|
||||
try { return resource.read(); } catch (pending) {
|
||||
if (!(pending instanceof Promise)) throw pending;
|
||||
await pending;
|
||||
return resource.read();
|
||||
}
|
||||
}
|
||||
|
||||
describe("shared code highlighting", () => {
|
||||
it.each(["", "中文 😀\tconst x = 1;\n", "const a = 1;\r\n\tconst b = '中文';\r\n", "unterminated\r"])("preserves the complete source %j", async (source) => {
|
||||
const value = await lines(source, "typescript");
|
||||
expect(value.map(line => line.text).join("")).toBe(source);
|
||||
expect(value.flatMap(line => line.tokens).map(token => token.content).join("")).toBe(source);
|
||||
});
|
||||
|
||||
it("tokenizes the complete large code block without pagination or dropping rows", async () => {
|
||||
const source = Array.from({ length: 1200 }, (_, index) => `const value${index} = ${index};`).join("\n");
|
||||
const value = await lines(source, "typescript");
|
||||
expect(value).toHaveLength(1200);
|
||||
expect(value.flatMap(line => line.tokens).map(token => token.content).join("")).toBe(source);
|
||||
});
|
||||
|
||||
it("keeps multiline lexical context and produces the existing keyword/string palette", async () => {
|
||||
const value = await lines("/* start\ncomment\n*/\nexport const value = 'yes';", "typescript");
|
||||
expect(value[1].tokens.some(token => token.color === "var(--code-comment)" && token.fontStyle === 1)).toBe(true);
|
||||
expect(value[3].tokens.some(token => token.color === "var(--code-keyword)" && token.content.trim() === "export")).toBe(true);
|
||||
expect(value[3].tokens.some(token => token.color === "var(--code-string)" && token.content === "'yes'")).toBe(true);
|
||||
});
|
||||
|
||||
it("retains INI configuration-file colors", async () => {
|
||||
const source = "; comment\n[server]\nhost=localhost\n";
|
||||
const value = await lines(source, "ini");
|
||||
expect(value.flatMap(line => line.tokens).map(token => token.content).join("")).toBe(source);
|
||||
expect(value[0].tokens.some(token => token.color === "var(--code-comment)")).toBe(true);
|
||||
expect(value[1].tokens.some(token => token.color === "var(--code-property)")).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps an unknown language readable and never turns source into active HTML", async () => {
|
||||
const source = "<script>alert('x')</script><img onerror='bad()'>";
|
||||
render(<pre data-testid="source"><CodeTokens lines={await lines(source, "unknown-file-format")} /></pre>);
|
||||
expect(screen.getByTestId("source").textContent).toBe(source);
|
||||
expect(document.querySelector("script, img")).toBeNull();
|
||||
});
|
||||
|
||||
it("reuses source revisions but does not return stale text after an edit", async () => {
|
||||
const source = "export const value = 1;";
|
||||
expect(codeHighlight(source, "typescript")).toBe(codeHighlight(source, "typescript"));
|
||||
const changed = await lines(source.replace("1", "2"), "typescript");
|
||||
expect(changed.flatMap(line => line.tokens).map(token => token.content).join("")).toBe("export const value = 2;");
|
||||
});
|
||||
});
|
||||
@@ -1,161 +0,0 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import { parse } from "postcss";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { DiffSyntaxHighlight } from "@/components/thread/activity/DiffSyntaxHighlight";
|
||||
import { ThemeProvider } from "@/hooks/useTheme";
|
||||
|
||||
const globalStyles = parse(readFileSync(resolve(process.cwd(), "src/globals.css"), "utf8"));
|
||||
// happy-dom does not apply cascade layers; retain the real rules and their order.
|
||||
globalStyles.walkAtRules("layer", (layer) => {
|
||||
layer.replaceWith(...(layer.nodes ?? []));
|
||||
});
|
||||
|
||||
describe("DiffSyntaxHighlight with Prism", () => {
|
||||
it("loads the TSX grammar and renders styled syntax tokens", async () => {
|
||||
render(
|
||||
<ThemeProvider theme="light">
|
||||
<DiffSyntaxHighlight
|
||||
language="tsx"
|
||||
lines={[
|
||||
{
|
||||
kind: "context",
|
||||
old_lineno: 1,
|
||||
new_lineno: 1,
|
||||
content: 'import { useMemo } from "react";',
|
||||
},
|
||||
{
|
||||
kind: "delete",
|
||||
old_lineno: 2,
|
||||
new_lineno: null,
|
||||
content: "export function StatusBadge() {",
|
||||
},
|
||||
{
|
||||
kind: "add",
|
||||
old_lineno: null,
|
||||
new_lineno: 2,
|
||||
content: "export function StatusBadge(): JSX.Element {",
|
||||
},
|
||||
{
|
||||
kind: "context",
|
||||
old_lineno: 3,
|
||||
new_lineno: 3,
|
||||
content: ' return <span className="badge">ready</span>;',
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
|
||||
// Full-suite workers can keep the first Prism grammar import busy for more
|
||||
// than Testing Library's one-second default, especially on Windows.
|
||||
const highlighted = await screen.findByTestId(
|
||||
"syntax-highlighted-diff-hunk",
|
||||
{},
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
await waitFor(
|
||||
() => {
|
||||
const tokens = highlighted.querySelectorAll<HTMLElement>(
|
||||
"td:last-child .token",
|
||||
);
|
||||
expect(tokens).not.toHaveLength(0);
|
||||
expect(highlighted.querySelector(".token.keyword")).not.toBeNull();
|
||||
expect(highlighted.querySelector(".token.string")).not.toBeNull();
|
||||
},
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
|
||||
expect(highlighted).toHaveAttribute("data-language", "tsx");
|
||||
expect(highlighted.querySelectorAll("tbody tr")).toHaveLength(4);
|
||||
});
|
||||
|
||||
it.each(["light", "dark"] as const)(
|
||||
"preserves nested JSX token colors in the %s appearance",
|
||||
async (appearance) => {
|
||||
const { container } = render(
|
||||
<div className={appearance === "dark" ? "dark" : ""}>
|
||||
<style>{globalStyles.toString()}</style>
|
||||
<DiffSyntaxHighlight
|
||||
language="tsx"
|
||||
lines={[{
|
||||
kind: "add",
|
||||
old_lineno: null,
|
||||
new_lineno: 1,
|
||||
content: '<span className={enabled ? "yes" : "no"} onClick={() => save(new Event("ok"))}>ready</span>',
|
||||
}]}
|
||||
/>
|
||||
</div>,
|
||||
);
|
||||
|
||||
const highlighted = await screen.findByTestId(
|
||||
"syntax-highlighted-diff-hunk",
|
||||
{},
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(highlighted.querySelector(".token.function")).not.toBeNull();
|
||||
}, { timeout: 10_000 });
|
||||
|
||||
const colors = getComputedStyle(
|
||||
appearance === "dark" ? container.firstElementChild! : document.documentElement,
|
||||
);
|
||||
const tokens = [...highlighted.querySelectorAll<HTMLElement>(".token")];
|
||||
for (const [text, category, variable] of [
|
||||
['"yes"', "string", "--code-string"],
|
||||
["new", "keyword", "--code-keyword"],
|
||||
["save", "function", "--code-function"],
|
||||
["=>", "operator", "--code-function"],
|
||||
["className", "attr-name", "--code-property"],
|
||||
["span", "tag", "--code-property"],
|
||||
]) {
|
||||
const token = tokens.find(
|
||||
(node) => node.textContent === text && node.classList.contains(category),
|
||||
);
|
||||
const expectedColor = colors.getPropertyValue(variable).trim();
|
||||
expect(token, `${category}: ${text}`).toBeDefined();
|
||||
expect(expectedColor).not.toBe("");
|
||||
expect.soft(getComputedStyle(token!).color, `${category}: ${text}`).toBe(expectedColor);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves markdown table line boundaries", async () => {
|
||||
const lines = [
|
||||
"## 发布安排",
|
||||
"",
|
||||
"| 日期 | 角色 | 方向 | 是否进实验 |",
|
||||
"| --- | --- | --- | --- |",
|
||||
"| 7/22 | trust / core | data-driven | yes |",
|
||||
];
|
||||
|
||||
render(
|
||||
<ThemeProvider theme="light">
|
||||
<DiffSyntaxHighlight
|
||||
language="markdown"
|
||||
lines={lines.map((content, index) => ({
|
||||
kind: "add" as const,
|
||||
old_lineno: null,
|
||||
new_lineno: 20 + index,
|
||||
content,
|
||||
}))}
|
||||
/>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
|
||||
const highlighted = await screen.findByTestId(
|
||||
"syntax-highlighted-diff-hunk",
|
||||
{},
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
const rows = [...highlighted.querySelectorAll("tbody tr")];
|
||||
|
||||
expect(rows).toHaveLength(lines.length);
|
||||
expect(rows.map((row) => row.querySelector("td:last-child")?.textContent)).toEqual(
|
||||
lines.map((line) => line || " "),
|
||||
);
|
||||
expect(highlighted.querySelector(".token.table")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,84 +1,85 @@
|
||||
import { act, render, screen } from "@testing-library/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { DiffSyntaxHighlight } from "@/components/thread/activity/DiffSyntaxHighlight";
|
||||
import { ThemeProvider } from "@/hooks/useTheme";
|
||||
import { getDiffMetadata } from "@/components/thread/activity/PierreFileDiff";
|
||||
import { DIFF_GAP_HEIGHT, diffRenderWindow, diffRowOffsets } from "@/components/thread/activity/diff-render-window";
|
||||
import { parseRenderableFileDiff } from "@/lib/file-diff";
|
||||
|
||||
vi.mock("react-syntax-highlighter/dist/esm/prism-async-light", () => {
|
||||
const MockSyntaxHighlighter = ({
|
||||
children,
|
||||
language,
|
||||
renderer,
|
||||
...props
|
||||
}: {
|
||||
children: string;
|
||||
language: string;
|
||||
renderer: (args: {
|
||||
rows: Array<{
|
||||
type: "element";
|
||||
tagName: "span";
|
||||
properties: { className: string[] };
|
||||
children: Array<{ type: "text"; value: string }>;
|
||||
}>;
|
||||
stylesheet: Record<string, React.CSSProperties>;
|
||||
useInlineStyles: boolean;
|
||||
}) => ReactNode;
|
||||
[key: string]: unknown;
|
||||
}) => (
|
||||
<div data-testid={String(props["data-testid"])} data-language={language}>
|
||||
{renderer({
|
||||
rows: children.split("\n").map((line) => ({
|
||||
type: "element" as const,
|
||||
tagName: "span" as const,
|
||||
properties: { className: ["token", "keyword"] },
|
||||
children: [{ type: "text" as const, value: `${line}\n` }],
|
||||
})),
|
||||
stylesheet: {},
|
||||
useInlineStyles: true,
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
return { default: MockSyntaxHighlighter };
|
||||
});
|
||||
const patch = (name: string, content: string, start = 20) => `--- a/${name}\n+++ b/${name}\n@@ -0,0 +${start},1 @@\n+${content}\n`;
|
||||
|
||||
vi.mock("react-syntax-highlighter/dist/esm/create-element", () => ({
|
||||
default: ({ node }: { node: { children?: Array<{ value?: string }> } }) => (
|
||||
<span data-testid="syntax-token">{node.children?.[0]?.value}</span>
|
||||
),
|
||||
}));
|
||||
describe("file diff render metadata", () => {
|
||||
it("preserves complete source and coordinates and reuses a revision across remounts", () => {
|
||||
const text = "--- a/fixture.ts\n+++ b/fixture.ts\n@@ -4,3 +4,3 @@\n export function run() {\n- return oldValue;\n+ return newValue;\n \n";
|
||||
const file = getDiffMetadata(text, "typescript");
|
||||
expect(file.hunks).toHaveLength(1);
|
||||
expect(file.hunks[0]).toMatchObject({ deletionStart: 4, additionStart: 4, deletionCount: 3, additionCount: 3, unifiedLineCount: 4 });
|
||||
expect(file.deletionLines).toEqual(["export function run() {\n", " return oldValue;\n", "\n"]);
|
||||
expect(file.additionLines).toEqual(["export function run() {\n", " return newValue;\n", "\n"]);
|
||||
expect(getDiffMetadata(text, "typescript")).toBe(file);
|
||||
expect(getDiffMetadata(text.replace("newValue", "changedValue"), "typescript").cacheKey).not.toBe(file.cacheKey);
|
||||
expect(getDiffMetadata(text, "javascript").cacheKey).not.toBe(file.cacheKey);
|
||||
});
|
||||
|
||||
describe("DiffSyntaxHighlight", () => {
|
||||
it("highlights a complete hunk while preserving diff rows and line numbers", async () => {
|
||||
render(
|
||||
<ThemeProvider theme="light">
|
||||
<DiffSyntaxHighlight
|
||||
language="typescript"
|
||||
lines={[
|
||||
{ kind: "context", old_lineno: 4, new_lineno: 4, content: "export function run() {" },
|
||||
{ kind: "delete", old_lineno: 5, new_lineno: null, content: " return oldValue;" },
|
||||
{ kind: "add", old_lineno: null, new_lineno: 5, content: " return newValue;" },
|
||||
]}
|
||||
/>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
it.each([["markup", "html"], ["docker", "dockerfile"], ["ini", "ini"], ["lock", "text"]])("maps %s to %s without losing source", (language, expected) => {
|
||||
const file = getDiffMetadata(patch("fixture", "<span>中文 & text</span>"), language);
|
||||
expect(file.lang).toBe(expected);
|
||||
expect(file.additionLines).toEqual(["<span>中文 & text</span>\n"]);
|
||||
expect(file.hunks[0]).toMatchObject({ deletionCount: 0, additionStart: 20, additionCount: 1 });
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
});
|
||||
it("evicts older revisions under the entry budget without reusing their identity", () => {
|
||||
const text = patch("old.ts", "old revision");
|
||||
const old = getDiffMetadata(text, "typescript");
|
||||
for (let i = 0; i < 16; i++) getDiffMetadata(patch(`revision-${i}.ts`, `const item = ${i};`), "typescript");
|
||||
const reloaded = getDiffMetadata(text, "typescript");
|
||||
expect(reloaded.cacheKey).not.toBe(old.cacheKey);
|
||||
expect(reloaded.additionLines).toEqual(old.additionLines);
|
||||
});
|
||||
});
|
||||
|
||||
const highlighted = await screen.findByTestId("syntax-highlighted-diff-hunk");
|
||||
expect(highlighted).toHaveAttribute("data-language", "typescript");
|
||||
expect(screen.getAllByTestId("syntax-token")).toHaveLength(3);
|
||||
expect(screen.getByText("return oldValue;", { exact: false }).closest("tr")).toHaveClass(
|
||||
"bg-diff-deleted",
|
||||
);
|
||||
expect(screen.getByText("return newValue;", { exact: false }).closest("tr")).toHaveClass(
|
||||
"bg-diff-added",
|
||||
);
|
||||
expect(screen.getAllByText("5")).toHaveLength(2);
|
||||
expect(screen.getAllByTestId("syntax-token").some((node) => node.textContent?.endsWith("\n"))).toBe(false);
|
||||
describe("file diff render windows", () => {
|
||||
const lines = Array.from({ length: 200 }, (_, i) => `+export const item${i} = ${i};`);
|
||||
const text = `--- a/fixture.ts\n+++ b/fixture.ts\n@@ -0,0 +1,200 @@\n${lines.join("\n")}\n@@ -500,0 +501,200 @@\n${lines.join("\n")}\n`;
|
||||
const diff = parseRenderableFileDiff({ format: "unified", text });
|
||||
|
||||
it("keeps the initial 160-line disclosure bounded and reserves no space for hidden content", () => {
|
||||
const offsets = diffRowOffsets(diff, 160, 24);
|
||||
expect(offsets).toHaveLength(161);
|
||||
expect(offsets.at(-1)).toBe(160 * 24);
|
||||
expect(diffRenderWindow(diff, offsets, 0, 900, 24)).toEqual({ startingLine: 0, totalLines: 160, bufferBefore: 0, bufferAfter: 0 });
|
||||
});
|
||||
|
||||
it("retains a fixed row budget while an overlapping viewport remains in the same start chunk", () => {
|
||||
const offsets = diffRowOffsets(diff, 400, 24);
|
||||
expect(diffRenderWindow(diff, offsets, -900, 1800, 24)).toEqual(diffRenderWindow(diff, offsets, -300, 2400, 24));
|
||||
});
|
||||
|
||||
it("covers the requested overscan in short and tall reading viewports", () => {
|
||||
for (const lineHeight of [21.1875, 23.59375, 26]) {
|
||||
const offsets = diffRowOffsets(diff, 400, lineHeight);
|
||||
const height = offsets.at(-1)!;
|
||||
for (const viewportHeight of [240, 390, 844, 1050]) {
|
||||
for (let y = 0; y < height; y += lineHeight * 10) {
|
||||
const top = y - viewportHeight;
|
||||
const bottom = y + viewportHeight * 2;
|
||||
const window = diffRenderWindow(diff, offsets, top, bottom, lineHeight);
|
||||
expect(window.bufferBefore).toBeLessThanOrEqual(Math.max(0, top));
|
||||
expect(height - window.bufferAfter).toBeGreaterThanOrEqual(Math.min(height, bottom));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves total geometry and gap ownership across adjacent virtual windows", () => {
|
||||
const offsets = diffRowOffsets(diff, 400, 24);
|
||||
expect(offsets.at(-1)).toBe(400 * 24 + DIFF_GAP_HEIGHT);
|
||||
const first = diffRenderWindow(diff, offsets, 0, 3840, 24);
|
||||
expect(first).toEqual({ startingLine: 0, totalLines: 200, bufferBefore: 0, bufferAfter: 200 * 24 + DIFF_GAP_HEIGHT });
|
||||
const second = diffRenderWindow(diff, offsets, 4827, 6000, 24);
|
||||
expect(second.startingLine).toBe(200);
|
||||
expect(second.bufferBefore).toBe(200 * 24);
|
||||
expect(second.totalLines * 24 + DIFF_GAP_HEIGHT + second.bufferBefore + second.bufferAfter).toBe(offsets.at(-1));
|
||||
const tail = diffRenderWindow(diff, offsets, 30000, 32000, 24);
|
||||
expect(tail.startingLine + tail.totalLines).toBe(400);
|
||||
expect(tail.bufferAfter).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -108,17 +108,24 @@ function BspWorkbenchHarness() {
|
||||
}
|
||||
|
||||
describe("PaneWorkbench", () => {
|
||||
it("keeps a single conversation's header inside that pane instead of above its previews", () => {
|
||||
it("keeps a single conversation's header and composer inside its preview layout", () => {
|
||||
const composer = <textarea aria-label="Composer Alpha" />;
|
||||
render(<PaneWorkbench panes={[{ key: "alpha", title: "Alpha" }]} activePaneKey="alpha"
|
||||
layout="columns" chrome showLayoutControl={false} onActivatePane={vi.fn()} onAddPane={vi.fn()}
|
||||
onLayoutChange={vi.fn()} onPaneOrderChange={vi.fn()}
|
||||
renderPane={(_pane, context) => {
|
||||
expect(context.headerPortalTarget).toBeUndefined();
|
||||
expect(context.multiplePanes).toBe(false);
|
||||
return <div data-testid="local-toolbar">{context.headerActions}</div>;
|
||||
return <div data-testid="local-toolbar">
|
||||
{context.headerActions}
|
||||
{context.composerPortalTarget === undefined ? composer : context.composerPortalTarget
|
||||
? createPortal(composer, context.composerPortalTarget) : null}
|
||||
</div>;
|
||||
}} />);
|
||||
expect(screen.getByTestId("workbench-header-host")).toBeEmptyDOMElement();
|
||||
expect(within(screen.getByTestId("local-toolbar")).getByRole("button", { name: "Add pane" })).toBeVisible();
|
||||
const conversation = screen.getByTestId("local-toolbar");
|
||||
expect(within(conversation).getByRole("button", { name: "Add pane" })).toBeVisible();
|
||||
expect(within(conversation).getByRole("textbox", { name: "Composer Alpha" })).toBeVisible();
|
||||
});
|
||||
|
||||
const originalGetBoundingClientRect = HTMLElement.prototype.getBoundingClientRect;
|
||||
@@ -168,7 +175,7 @@ describe("PaneWorkbench", () => {
|
||||
.toEqual(["Alpha", "Beta"]);
|
||||
expect(screen.getByRole("button", { name: "Focus Alpha" })).toHaveAttribute("data-multiple-panes", "true");
|
||||
expect(screen.getByRole("button", { name: "Focus Beta" })).toHaveAttribute("data-multiple-panes", "true");
|
||||
expect(screen.getByLabelText("Composer Beta")).toBeVisible();
|
||||
expect(within(screen.getByTestId("workbench-composer-host")).getByLabelText("Composer Beta")).toBeVisible();
|
||||
expect(screen.getByLabelText("Composer Alpha")).not.toBeVisible();
|
||||
|
||||
fireEvent.pointerDown(
|
||||
@@ -400,7 +407,12 @@ describe("PaneWorkbench", () => {
|
||||
renderPane: (pane: { key: string; title: string }, context: {
|
||||
headerActions: ReactNode;
|
||||
multiplePanes: boolean;
|
||||
}) => <>{context.headerActions}<span data-multiple-panes={context.multiplePanes}>{pane.title}</span></>,
|
||||
composerPortalTarget: HTMLElement | null | undefined;
|
||||
}) => <>{context.headerActions}<span data-multiple-panes={context.multiplePanes}>{pane.title}</span>
|
||||
{context.composerPortalTarget ? createPortal(
|
||||
<textarea aria-label={`Composer ${pane.title}`} />, context.composerPortalTarget,
|
||||
) : null}
|
||||
</>,
|
||||
};
|
||||
|
||||
const { rerender } = render(<PaneWorkbench {...props} activePaneKey="gamma" />);
|
||||
@@ -408,6 +420,7 @@ describe("PaneWorkbench", () => {
|
||||
expect(screen.getByTestId("pane-grid").children).toHaveLength(1);
|
||||
expect(screen.getByTestId("workbench-pane-gamma")).toBeInTheDocument();
|
||||
expect(screen.getByText("gamma", { selector: "span" })).toHaveAttribute("data-multiple-panes", "false");
|
||||
expect(within(screen.getByTestId("workbench-composer-host")).getByRole("textbox", { name: "Composer gamma" })).toBeVisible();
|
||||
expect(screen.queryByRole("button", { name: "Layout" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Add pane" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("separator")).not.toBeInTheDocument();
|
||||
@@ -415,6 +428,7 @@ describe("PaneWorkbench", () => {
|
||||
rerender(<PaneWorkbench {...props} activePaneKey="delta" />);
|
||||
expect(screen.getByTestId("pane-grid").children).toHaveLength(1);
|
||||
expect(screen.getByTestId("workbench-pane-delta")).toBeInTheDocument();
|
||||
expect(within(screen.getByTestId("workbench-composer-host")).getByRole("textbox", { name: "Composer delta" })).toBeVisible();
|
||||
expect(screen.queryByTestId("workbench-pane-gamma")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -11,6 +11,12 @@ import {
|
||||
import { preloadMarkdownText } from "@/components/MarkdownText";
|
||||
import type { UIMessage } from "@/lib/types";
|
||||
|
||||
// These DOM tests exercise disclosure/source contracts; the real shadow renderer runs in browser tests.
|
||||
vi.mock("@/components/thread/activity/DiffSyntaxHighlight", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/components/thread/activity/DiffSyntaxHighlight")>();
|
||||
return { ...actual, DiffSyntaxHighlight: actual.PlainDiffLines };
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import { act, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import SyntaxHighlighter from "react-syntax-highlighter/dist/esm/prism-light";
|
||||
import markup from "react-syntax-highlighter/dist/esm/languages/prism/markup";
|
||||
import oneLight from "react-syntax-highlighter/dist/esm/styles/prism/one-light";
|
||||
import { codeHighlight } from "@/lib/code-highlighter";
|
||||
|
||||
import { ViewportCodeRows } from "@/components/ViewportCodeRows";
|
||||
|
||||
SyntaxHighlighter.registerLanguage("markup", markup);
|
||||
|
||||
let notify: (entries: IntersectionObserverEntry[]) => void;
|
||||
const disconnect = vi.fn();
|
||||
const observe = vi.fn();
|
||||
@@ -25,8 +21,7 @@ function sourceText() {
|
||||
return [...document.querySelectorAll("[data-highlighted]")].map(node => node.textContent).join("");
|
||||
}
|
||||
function preview(code: string) {
|
||||
return <div data-file-preview-scroll><SyntaxHighlighter language="markup" style={oneLight}
|
||||
renderer={props => <ViewportCodeRows {...props} />}>{code}</SyntaxHighlighter></div>;
|
||||
return <div data-file-preview-scroll><ViewportCodeRows lines={codeHighlight(code, "markup").read()} /></div>;
|
||||
}
|
||||
|
||||
describe("viewport code highlighting", () => {
|
||||
|
||||
@@ -70,14 +70,18 @@ describe("entryLazyFeatureImports", () => {
|
||||
expect(entryLazyFeatureImports(["assets/react-vendor-abc.js"])).toEqual([]);
|
||||
expect(entryLazyFeatureImports([
|
||||
"assets/markdown-vendor-abc.js",
|
||||
"assets/syntax-highlight-def.js",
|
||||
"assets/katex-ghi.js",
|
||||
"assets/MermaidBlock-jkl.js",
|
||||
"assets/HighlightedCode-def.js",
|
||||
"assets/code-highlighter-ghi.js",
|
||||
"assets/PierreFileDiff-jkl.js",
|
||||
"assets/katex-mno.js",
|
||||
"assets/MermaidBlock-pqr.js",
|
||||
])).toEqual([
|
||||
"assets/markdown-vendor-abc.js",
|
||||
"assets/syntax-highlight-def.js",
|
||||
"assets/katex-ghi.js",
|
||||
"assets/MermaidBlock-jkl.js",
|
||||
"assets/HighlightedCode-def.js",
|
||||
"assets/code-highlighter-ghi.js",
|
||||
"assets/PierreFileDiff-jkl.js",
|
||||
"assets/katex-mno.js",
|
||||
"assets/MermaidBlock-pqr.js",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -100,12 +104,6 @@ describe("webuiManualChunk", () => {
|
||||
expect(webuiManualChunk("\0vite/preload-helper.js")).toBe("react-vendor");
|
||||
});
|
||||
|
||||
it("keeps Refractor's selector parser in the syntax highlighting chunk", () => {
|
||||
expect(
|
||||
webuiManualChunk("/repo/node_modules/hast-util-parse-selector/index.js"),
|
||||
).toBe("syntax-highlight");
|
||||
});
|
||||
|
||||
it("keeps markdown-only hast utilities in the markdown chunk", () => {
|
||||
expect(
|
||||
webuiManualChunk("/repo/node_modules/hast-util-to-jsx-runtime/lib/index.js"),
|
||||
@@ -132,6 +130,6 @@ describe("webuiManualChunk", () => {
|
||||
});
|
||||
|
||||
it("leaves language grammars as independently loaded chunks", () => {
|
||||
expect(webuiManualChunk("/repo/node_modules/refractor/lang/python.js")).toBeUndefined();
|
||||
expect(webuiManualChunk("/repo/node_modules/@shikijs/langs/dist/ini.mjs")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user