fix(webui): keep file preview tab switching responsive
This commit is contained in:
1 parent
ebb29759c0
commit
8b02d56e6c
6 files changed
+308
-12
No files matched your search
@@ -66,6 +66,55 @@ describe("CodeBlock", () => {
|
||||
expect(screen.getAllByRole("button")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["many lines", "x\n".repeat(60_000)],
|
||||
["many short lines", "\n".repeat(2_000)],
|
||||
["a minified line", "x".repeat(2_001) + "😀tail"],
|
||||
])("keeps an oversized file preview (%s) complete without a huge token/line DOM", (_name, code) => {
|
||||
const { container } = render(<CodeBlock code={code} language="html" chrome="none"
|
||||
showLineNumbers wrapLongLines={false} viewportHighlight />);
|
||||
expect(screen.queryByTestId("highlighted-code")).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId("plain-code-fallback").querySelector("code > span > span:last-child")?.textContent).toBe(code);
|
||||
expect(container.querySelectorAll("*").length).toBeLessThan(10);
|
||||
});
|
||||
|
||||
it("paints large preview text before enhancing it, and cancels enhancement on unmount", async () => {
|
||||
const callbacks = new Map<number, FrameRequestCallback>();
|
||||
let next = 0;
|
||||
const raf = vi.spyOn(window, "requestAnimationFrame").mockImplementation(callback => {
|
||||
callbacks.set(++next, callback);
|
||||
return next;
|
||||
});
|
||||
const cancel = vi.spyOn(window, "cancelAnimationFrame").mockImplementation(id => { callbacks.delete(id); });
|
||||
const code = "const value = 1;\n".repeat(600);
|
||||
try {
|
||||
const { unmount } = render(<CodeBlock code={code} language="ts" chrome="none"
|
||||
showLineNumbers wrapLongLines={false} viewportHighlight />);
|
||||
expect(screen.getByTestId("plain-code-fallback")).toBeInTheDocument();
|
||||
expect(screen.queryByTestId("highlighted-code")).not.toBeInTheDocument();
|
||||
await act(async () => { callbacks.get(1)?.(0); });
|
||||
expect(screen.getByTestId("plain-code-fallback")).toBeInTheDocument();
|
||||
const selection = document.getSelection()!;
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(screen.getByTestId("plain-code-fallback"));
|
||||
act(() => selection.addRange(range));
|
||||
await act(async () => { callbacks.get(2)?.(16); });
|
||||
expect(screen.getByTestId("plain-code-fallback")).toBeInTheDocument();
|
||||
await act(async () => { selection.removeAllRanges(); document.dispatchEvent(new Event("selectionchange")); });
|
||||
expect(await screen.findByTestId("highlighted-code")).toBeInTheDocument();
|
||||
unmount();
|
||||
expect(cancel).toHaveBeenCalledWith(2);
|
||||
const second = render(<CodeBlock code={code} language="ts" chrome="none"
|
||||
showLineNumbers wrapLongLines={false} viewportHighlight />);
|
||||
const pending = next;
|
||||
second.unmount();
|
||||
expect(callbacks.has(pending)).toBe(false);
|
||||
} finally {
|
||||
raf.mockRestore();
|
||||
cancel.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("renders plain code without mounting the highlighter when highlighting is disabled", () => {
|
||||
render(
|
||||
<ThemeProvider theme="dark">
|
||||
|
||||
@@ -2,11 +2,12 @@ import { act, fireEvent, render, screen, waitFor, within } from "@testing-librar
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
|
||||
import { CodeBlock } from "@/components/CodeBlock";
|
||||
import { setAppLanguage } from "@/i18n";
|
||||
import { fetchFilePreview } from "@/lib/api";
|
||||
|
||||
vi.mock("@/components/CodeBlock", () => ({
|
||||
CodeBlock: ({
|
||||
CodeBlock: vi.fn(({
|
||||
code,
|
||||
language,
|
||||
highlight,
|
||||
@@ -22,7 +23,7 @@ vi.mock("@/components/CodeBlock", () => ({
|
||||
>
|
||||
{code}
|
||||
</pre>
|
||||
),
|
||||
)),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api", async (importOriginal) => {
|
||||
@@ -37,6 +38,7 @@ describe("FilePreviewPanel", () => {
|
||||
beforeEach(async () => {
|
||||
await setAppLanguage("en");
|
||||
vi.mocked(fetchFilePreview).mockReset();
|
||||
vi.mocked(CodeBlock).mockClear();
|
||||
});
|
||||
|
||||
it("renders a raster instead of source and reports failed image decoding", async () => {
|
||||
@@ -139,6 +141,16 @@ describe("FilePreviewPanel", () => {
|
||||
expect(screen.queryByText("Cached")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not repaint a cache hit twice after its initial synchronous paint", async () => {
|
||||
const cached = { path: "notes.txt", display_path: "notes.txt", language: "text", content: "Cached", truncated: false };
|
||||
const loadPreview = vi.fn().mockResolvedValue(cached);
|
||||
render(<FilePreviewPanel sessionKey="a" path="notes.txt" token="test"
|
||||
initialPreview={cached} loadPreview={loadPreview} />);
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(loadPreview).toHaveBeenCalledOnce();
|
||||
expect(CodeBlock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("updates translated chrome without refetching the open file", async () => {
|
||||
vi.mocked(fetchFilePreview).mockResolvedValue({
|
||||
path: "/workspace/notes.md",
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
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 { ViewportCodeRows } from "@/components/ViewportCodeRows";
|
||||
|
||||
SyntaxHighlighter.registerLanguage("markup", markup);
|
||||
|
||||
let notify: IntersectionObserverCallback;
|
||||
const disconnect = vi.fn();
|
||||
const observe = vi.fn();
|
||||
function showChunks(indices: number[]) {
|
||||
const entries = [...document.querySelectorAll<HTMLElement>("[data-code-chunk]")]
|
||||
.map(target => ({ target, isIntersecting: indices.includes(Number(target.dataset.codeChunk)) }));
|
||||
act(() => notify(entries as IntersectionObserverEntry[], {} as IntersectionObserver));
|
||||
}
|
||||
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>;
|
||||
}
|
||||
|
||||
describe("viewport code highlighting", () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("IntersectionObserver", class {
|
||||
constructor(callback: IntersectionObserverCallback) { notify = callback; }
|
||||
observe = observe;
|
||||
disconnect = disconnect;
|
||||
});
|
||||
observe.mockClear();
|
||||
disconnect.mockClear();
|
||||
});
|
||||
afterEach(() => {
|
||||
act(() => document.getSelection()?.removeAllRanges());
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("keeps all text in the DOM while limiting highlighted rows, including a jump to the end", () => {
|
||||
const code = Array.from({ length: 602 }, (_, index) => `<p>Line ${index} 😀</p>`).join("\n");
|
||||
const { container, unmount } = render(preview(code));
|
||||
expect(sourceText()).toBe(code);
|
||||
expect(observe).toHaveBeenCalledTimes(16);
|
||||
expect(container.querySelectorAll("*").length).toBeLessThan(1000);
|
||||
showChunks([15]);
|
||||
expect(container.querySelector('[data-code-chunk="0"] [data-highlighted]')).toHaveAttribute("data-highlighted", "false");
|
||||
expect(container.querySelector('[data-code-chunk="15"] [data-highlighted]')).toHaveAttribute("data-highlighted", "true");
|
||||
expect(sourceText()).toBe(code);
|
||||
expect(container.querySelectorAll("*").length).toBeLessThan(1000);
|
||||
unmount();
|
||||
expect(disconnect).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("retains multiline syntax context across offscreen chunk boundaries and escapes source", () => {
|
||||
const code = "<!--\n" + "comment\n".repeat(79) + "-->\n<script>alert('not executed')</script>\n<img onerror='bad()'>";
|
||||
const { container } = render(preview(code));
|
||||
showChunks([1]);
|
||||
const middle = container.querySelector('[data-code-chunk="1"] [data-highlighted]');
|
||||
expect(middle?.querySelector("span[style]" )?.getAttribute("style")).toContain("italic");
|
||||
expect(sourceText()).toBe(code);
|
||||
showChunks([2]);
|
||||
expect(container.querySelector("script, img")).toBeNull();
|
||||
expect(sourceText()).toBe(code);
|
||||
});
|
||||
|
||||
it("does not replace token nodes underneath an active text selection", () => {
|
||||
render(preview("<p>Sample</p>\n".repeat(120)));
|
||||
const root = screen.getByTestId("viewport-code-rows");
|
||||
const first = root.querySelector('[data-highlighted="true"]')!;
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(first);
|
||||
const selection = document.getSelection()!;
|
||||
act(() => selection.addRange(range));
|
||||
showChunks([2]);
|
||||
expect(first).toHaveAttribute("data-highlighted", "true");
|
||||
expect(selection.toString()).toContain("Sample");
|
||||
act(() => { selection.removeAllRanges(); document.dispatchEvent(new Event("selectionchange")); });
|
||||
expect(first).toHaveAttribute("data-highlighted", "false");
|
||||
expect(root.querySelector('[data-code-chunk="2"] [data-highlighted]')).toHaveAttribute("data-highlighted", "true");
|
||||
});
|
||||
|
||||
it("falls back to full readable text when IntersectionObserver is unavailable", () => {
|
||||
vi.stubGlobal("IntersectionObserver", undefined);
|
||||
const code = "<p>Sample</p>\n".repeat(120);
|
||||
render(preview(code));
|
||||
expect(sourceText()).toBe(code);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user