- {showLineNumbers ? (
+ {showLineNumbers && compact ? (
+
+ {lines.map((_, index) => index + 1).join("\n")}
+ {renderText(code)}
+
+ ) : showLineNumbers ? (
lines.map((line, index) => (
@@ -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(null);
const [copied, setCopied] = useState(false);
+ const [highlightedSource, setHighlightedSource] = useState(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 (
- ) : highlight ? (
+ ) : highlight && withinHighlightBudget && (!deferHighlight || highlightedSource === code) ? (
}
>
@@ -234,6 +287,7 @@ export function CodeBlock({
chrome={chrome}
showLineNumbers={showLineNumbers}
wrapLongLines={wrapLongLines}
+ viewportHighlight={useViewportHighlight}
/>
) : (
@@ -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}
);
-}
+});
diff --git a/webui/src/components/FilePreviewPanel.tsx b/webui/src/components/FilePreviewPanel.tsx
index d963b583f..b9541aee7 100644
--- a/webui/src/components/FilePreviewPanel.tsx
+++ b/webui/src/components/FilePreviewPanel.tsx
@@ -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 (
-
+
{state.status === "loading" ? (
@@ -123,6 +127,7 @@ export function FilePreviewPanel({
highlight
showLineNumbers
wrapLongLines={false}
+ viewportHighlight
className="min-h-full"
/>
diff --git a/webui/src/components/ViewportCodeRows.tsx b/webui/src/components/ViewportCodeRows.tsx
new file mode 100644
index 000000000..3c888d15a
--- /dev/null
+++ b/webui/src/components/ViewportCodeRows.tsx
@@ -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>[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 (
+
+
+ {rows.map((_, index) => start + index + 1).join("\n")}
+
+
+ {highlighted ? rows.map((node, index) => createElement({
+ node, stylesheet, useInlineStyles, key: start + index,
+ })) : text}
+
+
+ );
+});
+
+/** Keep the complete source searchable/selectable; only offscreen token spans are omitted. */
+export function ViewportCodeRows({ rows, stylesheet, useInlineStyles }: RowsProps) {
+ const rootRef = useRef(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();
+ 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 (
+
+ {chunks.map((chunk, index) => )}
+
+ );
+}
diff --git a/webui/src/tests/code-block.test.tsx b/webui/src/tests/code-block.test.tsx
index fc9109a19..ee45071c8 100644
--- a/webui/src/tests/code-block.test.tsx
+++ b/webui/src/tests/code-block.test.tsx
@@ -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( );
+ 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();
+ 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( );
+ 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( );
+ 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(
diff --git a/webui/src/tests/file-preview-panel.test.tsx b/webui/src/tests/file-preview-panel.test.tsx
index 00974edc5..eb9aeaa2d 100644
--- a/webui/src/tests/file-preview-panel.test.tsx
+++ b/webui/src/tests/file-preview-panel.test.tsx
@@ -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}
- ),
+ )),
}));
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( );
+ 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",
diff --git a/webui/src/tests/viewport-code-rows.test.tsx b/webui/src/tests/viewport-code-rows.test.tsx
new file mode 100644
index 000000000..67f60d57a
--- /dev/null
+++ b/webui/src/tests/viewport-code-rows.test.tsx
@@ -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("[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 }>{code} ;
+}
+
+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) => `Line ${index} 😀
`).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\n
";
+ 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("Sample
\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 = "Sample
\n".repeat(120);
+ render(preview(code));
+ expect(sourceText()).toBe(code);
+ });
+});