fix(webui): keep file preview tab switching responsive

This commit is contained in:
Xubin Ren committed 2026-09-24 15:17:05 +08:00
1 parent ebb29759c0
commit 8b02d56e6c
6 files changed
+308 -12

No files matched your search

+62 -7
View File
@@ -1,4 +1,4 @@
import { Suspense, lazy, useCallback, useMemo, useState, type ReactNode } from "react";
import { Suspense, lazy, memo, startTransition, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { Check, Copy } from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -16,6 +16,7 @@ interface CodeBlockProps {
highlight?: boolean;
showLineNumbers?: boolean;
wrapLongLines?: boolean;
viewportHighlight?: boolean;
}
interface HighlightedCodeProps {
@@ -25,6 +26,7 @@ interface HighlightedCodeProps {
chrome: "default" | "none";
showLineNumbers: boolean;
wrapLongLines: boolean;
viewportHighlight: boolean;
}
const CODE_FONT_STACK = [
@@ -46,10 +48,12 @@ const LazyHighlightedCode = lazy(async () => {
{ default: SyntaxHighlighter },
{ default: oneDark },
{ default: oneLight },
{ ViewportCodeRows },
] = await Promise.all([
import("react-syntax-highlighter/dist/esm/prism-async-light"),
import("react-syntax-highlighter/dist/esm/styles/prism/one-dark"),
import("react-syntax-highlighter/dist/esm/styles/prism/one-light"),
import("@/components/ViewportCodeRows"),
]);
return {
@@ -60,6 +64,7 @@ const LazyHighlightedCode = lazy(async () => {
chrome,
showLineNumbers,
wrapLongLines,
viewportHighlight,
}: HighlightedCodeProps) {
const theme = isDark ? oneDark : oneLight;
const transparentTheme = chrome === "none" ? {
@@ -91,6 +96,7 @@ const LazyHighlightedCode = lazy(async () => {
style: {
background: "transparent",
fontFamily: CODE_FONT_STACK,
...(viewportHighlight ? { lineHeight: "inherit" } : {}),
},
}}
lineNumberStyle={{
@@ -101,8 +107,9 @@ const LazyHighlightedCode = lazy(async () => {
userSelect: "none",
}}
PreTag="pre"
showLineNumbers={showLineNumbers}
showLineNumbers={showLineNumbers && !viewportHighlight}
wrapLongLines={wrapLongLines}
renderer={viewportHighlight ? props => <ViewportCodeRows {...props} /> : undefined}
>
{code}
</SyntaxHighlighter>
@@ -130,6 +137,7 @@ function CodeTextBlock({
testId,
className,
renderText = renderPlainText,
compact = false,
}: {
code: string;
chrome: "default" | "none";
@@ -137,6 +145,7 @@ function CodeTextBlock({
testId: string;
className?: string;
renderText?: (value: string) => ReactNode;
compact?: boolean;
}) {
const lines = showLineNumbers ? code.split("\n") : [];
return (
@@ -146,13 +155,20 @@ function CodeTextBlock({
showLineNumbers ? "whitespace-pre" : "whitespace-pre-wrap",
chrome === "default"
? "py-4 pl-5 pr-14 leading-[1.6]"
: "p-3 leading-[1.55]",
: compact ? "px-4 py-3 leading-[1.55]" : "p-3 leading-[1.55]",
className,
)}
data-testid={testId}
style={compact ? { fontFamily: CODE_FONT_STACK } : undefined}
>
<code className="text-inherit">
{showLineNumbers ? (
{showLineNumbers && compact ? (
<span className="flex min-w-max">
<span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground/60"
style={{ minWidth: "4.25em" }}>{lines.map((_, index) => index + 1).join("\n")}</span>
<span>{renderText(code)}</span>
</span>
) : showLineNumbers ? (
lines.map((line, index) => (
<span key={index} className="flex min-w-max">
<span className="w-10 shrink-0 select-none pr-4 text-right text-muted-foreground/60">
@@ -173,7 +189,7 @@ function shouldRenderAnsi(language: string | undefined, code: string): boolean {
return Boolean((normalized && ANSI_LANGUAGES.has(normalized)) || hasAnsi(code));
}
export function CodeBlock({
export const CodeBlock = memo(function CodeBlock({
language,
code,
className,
@@ -181,14 +197,48 @@ export function CodeBlock({
highlight = true,
showLineNumbers = false,
wrapLongLines = true,
viewportHighlight = false,
}: CodeBlockProps) {
const { t } = useTranslation();
const rootRef = useRef<HTMLDivElement>(null);
const [copied, setCopied] = useState(false);
const [highlightedSource, setHighlightedSource] = useState<string | null>(null);
const renderAnsi = useMemo(() => shouldRenderAnsi(language, code), [language, code]);
const plainCode = useMemo(() => renderAnsi ? stripAnsi(code) : code, [renderAnsi, code]);
const isDark = useThemeValue() === "dark";
const hasChrome = chrome === "default";
const syntaxLanguage = normalizeCodeLanguage(language);
const useViewportHighlight = viewportHighlight && showLineNumbers && !wrapLongLines;
// Minified/very large previews must not monopolize the main thread in Prism.
// Plain text still contains the entire preview, with normal selection and find.
const withinHighlightBudget = useMemo(() => {
if (!useViewportHighlight) return true;
if (code.length > 100_000) return false;
const lines = code.split("\n");
return lines.length <= 2_000 && !lines.some(line => line.length > 2_000);
}, [code, useViewportHighlight]);
const deferHighlight = highlight && !renderAnsi && useViewportHighlight
&& withinHighlightBudget && code.length > 8_000;
useEffect(() => {
if (!deferHighlight) return;
// Paint the tab and full plain source first. Color is a progressive enhancement,
// not a reason to hold up switching tabs (including an already cached file).
let frame = requestAnimationFrame(() => {
frame = requestAnimationFrame(enhance);
});
function enhance() {
const selection = document.getSelection();
if (rootRef.current && selection && !selection.isCollapsed && selection.rangeCount
&& selection.getRangeAt(0).intersectsNode(rootRef.current)) return;
document.removeEventListener("selectionchange", enhance);
startTransition(() => setHighlightedSource(code));
}
document.addEventListener("selectionchange", enhance);
return () => {
cancelAnimationFrame(frame);
document.removeEventListener("selectionchange", enhance);
};
}, [code, deferHighlight]);
const copyLabel = copied ? t("code.copied") : t("code.copyAria");
const onCopy = useCallback(() => {
@@ -201,6 +251,7 @@ export function CodeBlock({
return (
<div
ref={rootRef}
className={cn(
"not-prose relative overflow-hidden",
hasChrome && "rounded-floating bg-secondary/70",
@@ -215,8 +266,9 @@ export function CodeBlock({
showLineNumbers={showLineNumbers}
testId="ansi-code"
renderText={renderAnsiText}
compact={useViewportHighlight}
/>
) : highlight ? (
) : highlight && withinHighlightBudget && (!deferHighlight || highlightedSource === code) ? (
<Suspense
fallback={
<CodeTextBlock
@@ -224,6 +276,7 @@ export function CodeBlock({
chrome={chrome}
showLineNumbers={showLineNumbers}
testId="plain-code-fallback"
compact={useViewportHighlight}
/>
}
>
@@ -234,6 +287,7 @@ export function CodeBlock({
chrome={chrome}
showLineNumbers={showLineNumbers}
wrapLongLines={wrapLongLines}
viewportHighlight={useViewportHighlight}
/>
</Suspense>
) : (
@@ -242,6 +296,7 @@ export function CodeBlock({
chrome={chrome}
showLineNumbers={showLineNumbers}
testId="plain-code-fallback"
compact={useViewportHighlight}
/>
)}
{hasChrome ? (
@@ -265,4 +320,4 @@ export function CodeBlock({
) : null}
</div>
);
}
});
+8 -3
View File
@@ -44,10 +44,13 @@ export function FilePreviewPanel({
let cancelled = false;
setImageOpen(false);
const cached = initialPreviewRef.current;
setState(cached ? { status: "ready", payload: cached } : { status: "loading" });
setState(previous => cached
? (previous.status === "ready" && previous.payload === cached ? previous : { status: "ready", payload: cached })
: (previous.status === "loading" ? previous : { status: "loading" }));
(loadPreview?.(path) ?? fetchFilePreview(tokenRef.current, sessionKey, path))
.then((payload) => {
if (!cancelled) setState({ status: "ready", payload });
if (!cancelled) setState(previous => previous.status === "ready" && previous.payload === payload
? previous : { status: "ready", payload });
})
.catch((error: unknown) => {
if (!cancelled) setState({ status: "error", error });
@@ -72,7 +75,8 @@ export function FilePreviewPanel({
return (
<section aria-label={t("filePreview.aria")} data-testid="file-preview-panel" className="flex min-h-0 flex-1 flex-col">
<div className="min-h-0 flex-1 overflow-auto">
<div data-file-preview-scroll tabIndex={0}
className="min-h-0 flex-1 overflow-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/60">
{state.status === "loading" ? (
<div role="status" aria-label={t("filePreview.loading", { defaultValue: "Loading preview..." })}
className="flex h-full flex-col justify-center gap-3 p-6" aria-busy="true">
@@ -123,6 +127,7 @@ export function FilePreviewPanel({
highlight
showLineNumbers
wrapLongLines={false}
viewportHighlight
className="min-h-full"
/>
</div>
+84
View File
@@ -0,0 +1,84 @@
import { memo, useEffect, useMemo, useRef, useState } from "react";
import type { SyntaxHighlighterProps } from "react-syntax-highlighter";
import createElement from "react-syntax-highlighter/dist/esm/create-element";
type RowsProps = Parameters<NonNullable<SyntaxHighlighterProps["renderer"]>>[0];
type Row = RowsProps["rows"][number];
const CHUNK_LINES = 40;
function textOf(node: Row): string {
return node.type === "text" ? String(node.value ?? "") : (node.children ?? []).map(textOf).join("");
}
const CodeChunk = memo(function CodeChunk({ rows, text, start, stylesheet, useInlineStyles, highlighted }: RowsProps & {
text: string;
start: number;
highlighted: boolean;
}) {
return (
<span data-code-chunk={start / CHUNK_LINES} className="flex min-w-max">
<span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground/60"
style={{ minWidth: "4.25em" }}>
{rows.map((_, index) => start + index + 1).join("\n")}
</span>
<span data-highlighted={highlighted}>
{highlighted ? rows.map((node, index) => createElement({
node, stylesheet, useInlineStyles, key: start + index,
})) : text}
</span>
</span>
);
});
/** Keep the complete source searchable/selectable; only offscreen token spans are omitted. */
export function ViewportCodeRows({ rows, stylesheet, useInlineStyles }: RowsProps) {
const rootRef = useRef<HTMLSpanElement>(null);
const [visible, setVisible] = useState(() => new Set([0]));
// The inline renderer only matches token class combinations. Passing Prism's
// unrelated toolbar/pseudo selectors makes it scan those again for every token.
const tokenStyles = useMemo(() => Object.fromEntries(Object.entries(stylesheet)
.filter(([selector]) => /^[\w-]+(?:\.[\w-]+)*$/.test(selector))), [stylesheet]);
const chunks = useMemo(() => {
const result = [];
for (let start = 0; start < rows.length; start += CHUNK_LINES) {
const chunk = rows.slice(start, start + CHUNK_LINES);
result.push({ start, rows: chunk, text: chunk.map(textOf).join("") });
}
return result;
}, [rows]);
useEffect(() => {
const root = rootRef.current;
if (!root || typeof IntersectionObserver === "undefined") return;
const intersecting = new Set<number>();
const update = () => {
// Replacing spans during a drag/keyboard selection would destroy its Range.
const selection = document.getSelection();
if (selection && !selection.isCollapsed && selection.rangeCount
&& selection.getRangeAt(0).intersectsNode(root)) return;
setVisible((previous) => previous.size === intersecting.size
&& [...previous].every(index => intersecting.has(index)) ? previous : new Set(intersecting));
};
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
const index = Number((entry.target as HTMLElement).dataset.codeChunk);
if (entry.isIntersecting) intersecting.add(index);
else intersecting.delete(index);
}
update();
}, { root: root.closest("[data-file-preview-scroll]"), rootMargin: "80px 0px" });
root.querySelectorAll("[data-code-chunk]").forEach(chunk => observer.observe(chunk));
document.addEventListener("selectionchange", update);
return () => {
observer.disconnect();
document.removeEventListener("selectionchange", update);
};
}, [chunks]);
return (
<span ref={rootRef} className="block min-w-max" data-testid="viewport-code-rows">
{chunks.map((chunk, index) => <CodeChunk key={chunk.start} {...chunk}
stylesheet={tokenStyles} useInlineStyles={useInlineStyles} highlighted={visible.has(index)} />)}
</span>
);
}
+49
View File
@@ -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">
+14 -2
View File
@@ -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);
});
});