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>
);
}