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:
chengyongru authored and GitHub committed 2026-11-06 16:41:12 +08:00
1 parent f5c359476b
commit 3a37269f3f
44 files changed
+2261 -1072

No files matched your search

@@ -15,6 +15,7 @@ import { useTranslation } from "react-i18next";
import { PromptRail } from "@/components/thread/PromptRail";
import { SubagentThreadMessages, useHasSubagentResults } from "@/components/thread/SubagentTaskResults";
import { DiagramScope } from "@/components/markdown-diagrams/context";
import { DiffViewportContext } from "./activity/DiffViewportContext";
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
import { isAgentActivityMember } from "@/components/thread/AgentActivityCluster";
import { ThreadCameraController } from "@/components/thread/thread-camera";
@@ -306,6 +307,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
const contentRef = useRef<HTMLDivElement>(null);
const messageRegionRef = useRef<HTMLDivElement | null>(null);
const messageContentRef = useRef<HTMLDivElement>(null);
const diffViewport = useMemo(() => ({ scroller: messageRegionRef, content: messageContentRef }), []);
const emptyStateRef = useRef<HTMLDivElement>(null);
const composerDockRef = useRef<HTMLDivElement>(null);
const composerLayoutChangeRef = useRef(onComposerLayoutChange);
@@ -1211,6 +1213,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
)}
>
<div ref={messageContentRef} className="w-full">
<DiffViewportContext.Provider value={diffViewport}>
<DiagramScope identity={conversationKey}>
<SubagentThreadMessages
key={messagesKey}
@@ -1239,6 +1242,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
onActivityToggle={yieldCameraToUser}
/>
</DiagramScope>
</DiffViewportContext.Provider>
</div>
<div aria-hidden className="thread-message-end-gap shrink-0" />
<div ref={bottomRef} aria-hidden className="h-px shrink-0" />
@@ -1,187 +1,66 @@
import { Suspense, lazy, type ReactNode } from "react";
import type { SyntaxHighlighterProps } from "react-syntax-highlighter";
import { useTranslation } from "react-i18next";
import type { RenderableFileDiffLine } from "@/lib/file-diff";
import type { RenderableFileDiff, RenderableFileDiffLine } from "@/lib/file-diff";
import { cn } from "@/lib/utils";
interface DiffSyntaxHighlightProps {
export interface DiffSyntaxHighlightProps {
language: string;
lines: RenderableFileDiffLine[];
text: string;
diff: RenderableFileDiff;
lineLimit: number;
}
type RendererArgs = Parameters<NonNullable<SyntaxHighlighterProps["renderer"]>>[0];
type SyntaxNode = RendererArgs["rows"][number];
const LazyDiffSyntaxHighlight = lazy(async () => {
const [
{ default: SyntaxHighlighter },
{ default: createSyntaxElement },
] = await Promise.all([
import("react-syntax-highlighter/dist/esm/prism-async-light"),
import("react-syntax-highlighter/dist/esm/create-element"),
]);
return {
default: function LoadedDiffSyntaxHighlight({
language,
lines,
}: DiffSyntaxHighlightProps) {
const code = lines.map((line) => line.content || " ").join("\n");
return (
<SyntaxHighlighter
language={language}
useInlineStyles={false}
style={{}}
PreTag="div"
CodeTag="div"
customStyle={{
background: "transparent",
margin: 0,
padding: 0,
overflow: "visible",
fontFamily: "inherit",
fontSize: "inherit",
lineHeight: "inherit",
}}
codeTagProps={{
style: {
background: "transparent",
fontFamily: "inherit",
},
}}
data-language={language}
className="code-content font-mono text-code-dense"
data-testid="syntax-highlighted-diff-hunk"
renderer={({ rows, stylesheet, useInlineStyles }) => (
<DiffLineTable
lines={lines}
renderCode={(line, index) => {
const node = rows[index];
if (!node) return line.content || " ";
return createSyntaxElement({
node: stripConflictingTableClass(trimTrailingLineBreak(node)),
stylesheet,
useInlineStyles,
key: `diff-code-${index}`,
});
}}
/>
)}
>
{code}
</SyntaxHighlighter>
);
},
};
const renderer = await import("./PierreFileDiff");
await renderer.prepareDiffRenderer();
return { default: renderer.PierreFileDiff };
});
export function DiffSyntaxHighlight({ language, lines }: DiffSyntaxHighlightProps) {
export function DiffSyntaxHighlight(props: DiffSyntaxHighlightProps) {
return (
<Suspense fallback={<PlainDiffLines lines={lines} />}>
<LazyDiffSyntaxHighlight language={language} lines={lines} />
<Suspense fallback={<PlainDiffLines diff={props.diff} lineLimit={props.lineLimit} />}>
<LazyDiffSyntaxHighlight {...props} />
</Suspense>
);
}
function PlainDiffLines({ lines }: { lines: RenderableFileDiffLine[] }) {
export function DiffHunkGap({ lineCount }: { lineCount: number }) {
const { t } = useTranslation();
return (
<div data-testid="plain-diff-hunk">
<DiffLineTable lines={lines} renderCode={(line) => line.content || " "} />
<div className="nanobot-diff-gap flex items-center gap-2 bg-muted/35 px-2 text-[11px] text-muted-foreground" data-testid="file-edit-diff-hunk-gap">
<span className="select-none rounded border border-border/45 bg-background/70 px-1 font-mono text-muted-foreground/70" aria-hidden>...</span>
<span>{t("message.fileEditUnchangedLinesHidden", { count: lineCount, defaultValue: "{{count}} unchanged lines hidden" })}</span>
</div>
);
}
function DiffLineTable({
lines,
renderCode,
}: {
lines: RenderableFileDiffLine[];
renderCode: (line: RenderableFileDiffLine, index: number) => ReactNode;
}) {
return (
<table className="w-full border-collapse font-mono text-code-dense">
<tbody>
{lines.map((line, index) => (
<DiffLineRow
key={`${line.old_lineno ?? ""}:${line.new_lineno ?? ""}:${index}`}
line={line}
>
{renderCode(line, index)}
</DiffLineRow>
))}
</tbody>
</table>
);
export function PlainDiffLines({ diff, lineLimit }: { diff: RenderableFileDiff; lineLimit: number }) {
let remaining = lineLimit;
return <div data-testid="plain-diff-hunk">{diff.hunks.map((hunk, index) => {
const lines = hunk.lines.slice(0, Math.max(0, remaining));
remaining -= lines.length;
if (lines.length === 0) return null;
const previous = diff.hunks[index - 1];
const skipped = previous ? Math.max(0, hunk.old_start - previous.old_start - previous.old_lines, hunk.new_start - previous.new_start - previous.new_lines) : 0;
return <div key={index}>
{skipped > 0 ? <DiffHunkGap lineCount={skipped} /> : null}
<table className="w-full border-collapse font-mono text-code-dense"><tbody>
{lines.map((line, lineIndex) => <DiffLineRow key={lineIndex} line={line}>{line.content || " "}</DiffLineRow>)}
</tbody></table>
</div>;
})}</div>;
}
function DiffLineRow({
line,
children,
}: {
line: RenderableFileDiffLine;
children: ReactNode;
}) {
function DiffLineRow({ line, children }: { line: RenderableFileDiffLine; children: ReactNode }) {
const kind = line.kind === "add" || line.kind === "delete" ? line.kind : "context";
const marker = kind === "add" ? "+" : kind === "delete" ? "-" : " ";
return (
<tr
className={cn(
"border-0",
kind === "add" && "bg-diff-added",
kind === "delete" && "bg-diff-deleted",
)}
>
<td className="w-10 select-none border-r border-border/35 px-1.5 text-right text-muted-foreground">
{line.old_lineno ?? ""}
</td>
<td className="w-10 select-none border-r border-border/35 px-1.5 text-right text-muted-foreground">
{line.new_lineno ?? ""}
</td>
<td
className={cn(
"w-5 select-none px-1 text-center",
kind === "add" && "text-diff-added-foreground",
kind === "delete" && "text-diff-deleted-foreground",
kind === "context" && "text-muted-foreground",
)}
>
{marker}
</td>
<td className="min-w-[16rem] px-1.5 text-foreground/86">
<span className="whitespace-pre">{children}</span>
</td>
<tr className={cn("border-0", kind === "add" && "bg-diff-added", kind === "delete" && "bg-diff-deleted")}>
<td className="w-10 select-none border-r border-border/35 px-1.5 text-right text-muted-foreground">{line.old_lineno ?? ""}</td>
<td className="w-10 select-none border-r border-border/35 px-1.5 text-right text-muted-foreground">{line.new_lineno ?? ""}</td>
<td className={cn("w-5 select-none px-1 text-center", kind === "add" && "text-diff-added-foreground", kind === "delete" && "text-diff-deleted-foreground", kind === "context" && "text-muted-foreground")}>{marker}</td>
<td className="min-w-[16rem] px-1.5 text-foreground/86"><span className="whitespace-pre">{children}</span></td>
</tr>
);
}
function trimTrailingLineBreak(node: SyntaxNode): SyntaxNode {
if (node.type === "text" && typeof node.value === "string") {
return { ...node, value: node.value.replace(/\n$/, "") };
}
if (!node.children?.length) return node;
const children = [...node.children];
children[children.length - 1] = trimTrailingLineBreak(children[children.length - 1]!);
return { ...node, children };
}
function stripConflictingTableClass(node: SyntaxNode): SyntaxNode {
const className = node.properties?.className;
const children = node.children?.map(stripConflictingTableClass);
const hasTableClass = Array.isArray(className) && className.includes("table");
if (!hasTableClass && !children) return node;
return {
...node,
...(hasTableClass
? {
properties: {
...node.properties,
// Tailwind's global `.table` utility changes Prism's inline Markdown
// table tokens into CSS tables, splitting a single diff line vertically.
className: className.filter((name) => name !== "table"),
},
}
: {}),
...(children ? { children } : {}),
};
}
@@ -0,0 +1,6 @@
import { createContext, type RefObject } from "react";
export const DiffViewportContext = createContext<{
scroller: RefObject<HTMLElement>;
content: RefObject<HTMLElement>;
} | null>(null);
@@ -14,7 +14,6 @@ import {
hasRenderableFileDiff,
parseRenderableFileDiff,
type RenderableFileDiff,
type RenderableFileDiffHunk,
} from "@/lib/file-diff";
import type { FileEditDisplayMode } from "@/lib/local-preferences";
import type { UIFileDiff, UIFileEdit } from "@/lib/types";
@@ -28,18 +27,6 @@ import { DiffSyntaxHighlight } from "./DiffSyntaxHighlight";
const INITIAL_VISIBLE_DIFF_LINES = 160;
const AUTO_COLLAPSE_DIFF_LINES = INITIAL_VISIBLE_DIFF_LINES;
interface VisibleDiffHunk {
hunk: RenderableFileDiffHunk;
skippedBefore: number;
}
interface VisibleDiff {
hunks: VisibleDiffHunk[];
hiddenLineCount: number;
}
const EMPTY_VISIBLE_DIFF: VisibleDiff = { hunks: [], hiddenLineCount: 0 };
export interface FileEditSummary {
key: string;
path: string;
@@ -192,12 +179,7 @@ function FileUnifiedDiff({
const lineLimit = expandedLines || !shouldLimitLines
? totalLineCount
: INITIAL_VISIBLE_DIFF_LINES;
const visibleDiff = useMemo(
() => shouldRenderBody
? selectVisibleDiffLines(renderableDiff, lineLimit, totalLineCount)
: EMPTY_VISIBLE_DIFF,
[lineLimit, renderableDiff, shouldRenderBody, totalLineCount],
);
const hiddenLineCount = totalLineCount - lineLimit;
const viewDiffLabel = shouldAutoCollapse
? tx("message.fileEditViewLargeDiff", "View large diff")
: tx("message.fileEditViewDiff", "View diff");
@@ -227,18 +209,8 @@ function FileUnifiedDiff({
className="mt-1 overflow-hidden rounded-md border border-border/55 bg-background/80 shadow-[0_1px_0_rgba(15,23,42,0.03)]"
data-testid="file-edit-diff"
>
{visibleDiff.hunks.map(({ hunk, skippedBefore }, index) => (
<div
key={`${hunk.old_start}-${hunk.new_start}-${index}`}
className={cn("min-w-0", index > 0 && "border-t border-border/45")}
>
{skippedBefore > 0 ? <DiffHunkGap lineCount={skippedBefore} /> : null}
<div className="overflow-x-auto">
<DiffSyntaxHighlight language={language} lines={hunk.lines} />
</div>
</div>
))}
{visibleDiff.hiddenLineCount > 0 ? (
<DiffSyntaxHighlight language={language} text={diff.text!} diff={renderableDiff} lineLimit={lineLimit} />
{hiddenLineCount > 0 ? (
<div className="border-t border-border/45 bg-muted/30 px-2 py-1">
<button
type="button"
@@ -251,7 +223,7 @@ function FileUnifiedDiff({
>
<ChevronDown className="h-3 w-3" aria-hidden />
{t("message.fileEditShowMoreLines", {
count: visibleDiff.hiddenLineCount,
count: hiddenLineCount,
defaultValue: "Show {{count}} more lines",
})}
</button>
@@ -330,72 +302,3 @@ function FileUnifiedDiff({
function countDiffLines(diff: RenderableFileDiff): number {
return diff.hunks.reduce((total, hunk) => total + hunk.lines.length, 0);
}
function selectVisibleDiffLines(
diff: RenderableFileDiff,
lineLimit: number,
totalLineCount: number,
): VisibleDiff {
if (lineLimit >= totalLineCount) {
return {
hunks: diff.hunks.map((hunk, index) => ({
hunk,
skippedBefore: index > 0 ? countSkippedUnchangedLines(diff.hunks[index - 1], hunk) : 0,
})),
hiddenLineCount: 0,
};
}
let remaining = Math.max(0, lineLimit);
const hunks: VisibleDiffHunk[] = [];
let previousHunk: RenderableFileDiffHunk | null = null;
for (const hunk of diff.hunks) {
if (remaining <= 0) break;
const skippedBefore = previousHunk ? countSkippedUnchangedLines(previousHunk, hunk) : 0;
if (hunk.lines.length <= remaining) {
hunks.push({ hunk, skippedBefore });
remaining -= hunk.lines.length;
previousHunk = hunk;
continue;
}
hunks.push({ hunk: { ...hunk, lines: hunk.lines.slice(0, remaining) }, skippedBefore });
remaining = 0;
previousHunk = hunk;
}
return {
hunks,
hiddenLineCount: Math.max(0, totalLineCount - lineLimit),
};
}
function countSkippedUnchangedLines(
previous: RenderableFileDiffHunk,
current: RenderableFileDiffHunk,
): number {
const oldGap = current.old_start - (previous.old_start + previous.old_lines);
const newGap = current.new_start - (previous.new_start + previous.new_lines);
return Math.max(0, oldGap, newGap);
}
function DiffHunkGap({ lineCount }: { lineCount: number }) {
const { t } = useTranslation();
return (
<div
className="flex items-center gap-2 bg-muted/35 px-2 py-1 text-[11px] text-muted-foreground"
data-testid="file-edit-diff-hunk-gap"
>
<span
className="select-none rounded border border-border/45 bg-background/70 px-1 font-mono text-muted-foreground/70"
aria-hidden
>
...
</span>
<span>
{t("message.fileEditUnchangedLinesHidden", {
count: lineCount,
defaultValue: "{{count}} unchanged lines hidden",
})}
</span>
</div>
);
}
@@ -0,0 +1,159 @@
import { FileDiff, getSharedHighlighter, getSingularPatch, registerCustomTheme, type FileDiffMetadata, type FileDiffOptions, type RenderRange } from "@pierre/diffs";
import { WorkerPoolManager } from "@pierre/diffs/worker";
import { isSupportedLanguage } from "@pierre/highlights";
import { bundledLanguages } from "shiki/langs";
import { useCallback, useContext, useLayoutEffect, useMemo, useRef } from "react";
import { useTranslation } from "react-i18next";
import { useThemeValue } from "@/hooks/useTheme";
import { CODE_TEXTMATE_THEME, CODE_THEME, CODE_THEME_NAME, codeHighlighterLanguage } from "@/lib/code-theme";
import { DiffViewportContext } from "./DiffViewportContext";
import type { DiffSyntaxHighlightProps } from "./DiffSyntaxHighlight";
import { DIFF_GAP_HEIGHT, diffRenderWindow, diffRowOffsets } from "./diff-render-window";
import { selectedDiffRows } from "./diff-selection";
const THEME = CODE_THEME_NAME;
const CACHE_ENTRIES = 16;
const CACHE_SOURCE_BYTES = 2 * 1024 * 1024;
const metadataCache = new Map<string, FileDiffMetadata>();
let sourceBytes = 0;
let revision = 0;
let pool: WorkerPoolManager | undefined;
let grammarPool: WorkerPoolManager | undefined;
let preparation: Promise<void> | undefined;
registerCustomTheme(THEME, async () => CODE_THEME, "zed");
registerCustomTheme(THEME, async () => CODE_TEXTMATE_THEME, "textmate");
export function prepareDiffRenderer(): Promise<void> {
return preparation ??= (async () => {
await getSharedHighlighter({ themes: [THEME], langs: ["text"], preferredHighlighter: "highlights" });
pool = new WorkerPoolManager({
// The zero-worker pool owns the bounded AST cache; Highlights shares its main-thread engine with code blocks.
workerFactory: () => { throw new Error("The Highlights cache does not create workers"); },
poolSize: 0,
totalASTLRUCacheSize: CACHE_ENTRIES,
mainThreadMaxCharacters: Number.MAX_SAFE_INTEGER,
}, { theme: THEME, preferredHighlighter: "highlights", lineDiffType: "word" });
})();
}
function getGrammarPool(): WorkerPoolManager {
return grammarPool ??= new WorkerPoolManager({
workerFactory: () => new Worker(new URL("@pierre/diffs/worker/worker.js", import.meta.url), { type: "module" }),
poolSize: 1, totalASTLRUCacheSize: CACHE_ENTRIES,
}, { theme: THEME, preferredHighlighter: "shiki-js", lineDiffType: "word" });
}
export function getDiffMetadata(text: string, language: string): FileDiffMetadata {
const alias = codeHighlighterLanguage(language);
const lang = isSupportedLanguage(alias) || Object.hasOwn(bundledLanguages, alias)
? alias as NonNullable<FileDiffMetadata["lang"]> : "text";
const key = `${lang}\0${text}`;
const cached = metadataCache.get(key);
if (cached) {
metadataCache.delete(key);
metadataCache.set(key, cached);
return cached;
}
const metadata = getSingularPatch(text);
metadata.lang = lang;
const bytes = key.length * 2;
if (bytes <= CACHE_SOURCE_BYTES) {
while (metadataCache.size >= CACHE_ENTRIES || sourceBytes + bytes > CACHE_SOURCE_BYTES) {
const [oldKey, oldMetadata] = metadataCache.entries().next().value!;
metadataCache.delete(oldKey);
sourceBytes -= oldKey.length * 2;
pool?.evictDiffFromCache(oldMetadata.cacheKey!);
grammarPool?.evictDiffFromCache(oldMetadata.cacheKey!);
}
metadata.cacheKey = `nanobot-diff-${++revision}`;
metadataCache.set(key, metadata);
sourceBytes += bytes;
}
return metadata;
}
export function PierreFileDiff({ text, language, diff, lineLimit }: DiffSyntaxHighlightProps) {
const theme = useThemeValue();
const { t } = useTranslation();
const viewport = useContext(DiffViewportContext);
const wrapperRef = useRef<HTMLDivElement>(null);
const instanceRef = useRef<FileDiff>();
const metadata = useMemo(() => getDiffMetadata(text, language), [text, language]);
const needsGrammar = !isSupportedLanguage(metadata.lang!);
const gapLabel = useCallback((count: number) => `… ${t("message.fileEditUnchangedLinesHidden", { count, defaultValue: "{{count}} unchanged lines hidden" })}`, [t]);
const options = useMemo<FileDiffOptions<undefined, undefined>>(() => ({
theme: THEME, themeType: theme, preferredHighlighter: "highlights", diffStyle: "unified", diffIndicators: "classic",
disableFileHeader: true, lineDiffType: "word",
// Function separators disable Pierre's incremental row updates and destroy native selections.
hunkSeparators: "line-info",
onPostRender: (node, _instance, phase) => {
if (phase === "unmount") return;
for (const gap of node.shadowRoot!.querySelectorAll<HTMLElement>("[data-separator]")) {
const nextIndex = Number(gap.nextElementSibling?.getAttribute("data-line-index")?.split(",")[0]);
const hunk = metadata.hunks.find(item => item.unifiedLineStart === nextIndex);
const label = gap.querySelector<HTMLElement>("[data-unmodified-lines]");
if (!hunk || !label) continue;
const text = gapLabel(hunk.collapsedBefore);
if (label.textContent !== text) label.textContent = text;
if (gap.closest("[data-gutter]")) label.dataset.testid = "file-edit-diff-hunk-gap";
}
},
unsafeCSS: `:host, pre, code { font: inherit; } pre { padding-block: 0; } [data-line], [data-column-number] { padding-block: 1px; } [data-separator] { height: ${DIFF_GAP_HEIGHT}px; margin: 0; padding: 0; } [data-separator-wrapper], [data-separator-content] { background: transparent; color: hsl(var(--muted-foreground)); } [data-separator-wrapper] { padding-inline: 8px; background: hsl(var(--muted) / .35); font-size: 11px; } [data-separator-first], [data-separator-last] { display: none; }`,
}), [theme, gapLabel, metadata]);
useLayoutEffect(() => {
const wrapper = wrapperRef.current!;
const instance = new FileDiff({ theme: THEME, preferredHighlighter: "highlights" }, needsGrammar ? getGrammarPool() : pool);
instanceRef.current = instance;
return () => { instance.cleanUp(); instanceRef.current = undefined; wrapper.replaceChildren(); };
}, [needsGrammar]);
useLayoutEffect(() => {
const wrapper = wrapperRef.current!;
const instance = instanceRef.current!;
instance.setOptions(options);
const scroller = viewport?.scroller.current;
const eventTarget = scroller ?? window;
let frame = 0;
let previous: RenderRange | undefined;
let forceRender = true;
const render = () => {
frame = 0;
const lineHeight = Math.floor((parseFloat(getComputedStyle(wrapper).lineHeight) + 2) * 64) / 64;
const offsets = diffRowOffsets(diff, lineLimit, lineHeight);
const rootRect = scroller?.getBoundingClientRect();
const wrapperTop = wrapper.getBoundingClientRect().top;
const top = (rootRect?.top ?? 0) - wrapperTop;
const height = rootRect?.height ?? window.innerHeight;
const range = diffRenderWindow(diff, offsets, top - height, top + height * 2, lineHeight, selectedDiffRows(wrapper, metadata));
if (!forceRender && previous && Object.keys(range).every(key => range[key as keyof RenderRange] === previous![key as keyof RenderRange])) return;
previous = range;
instance.render({ fileDiff: metadata, containerWrapper: wrapper, renderRange: range, forceRender });
forceRender = false;
};
const schedule = () => { if (!frame) frame = requestAnimationFrame(render); };
// This observer projects a read-only window; ThreadCameraController remains the sole scroll writer.
const resize = new ResizeObserver(schedule);
resize.observe(wrapper);
if (scroller) resize.observe(scroller);
if (viewport?.content.current) resize.observe(viewport.content.current);
const typography = new MutationObserver(schedule);
typography.observe(document.documentElement, { attributes: true, attributeFilter: ["data-reading-text-size"] });
eventTarget.addEventListener("scroll", schedule, { passive: true });
document.addEventListener("selectionchange", schedule);
window.addEventListener("resize", schedule);
render();
return () => {
cancelAnimationFrame(frame);
resize.disconnect();
typography.disconnect();
eventTarget.removeEventListener("scroll", schedule);
document.removeEventListener("selectionchange", schedule);
window.removeEventListener("resize", schedule);
};
}, [diff, lineLimit, metadata, options, viewport]);
return <div ref={wrapperRef} className="nanobot-file-diff font-mono text-code-dense" data-testid="syntax-highlighted-diff-hunk" data-language={language} />;
}
@@ -0,0 +1,50 @@
import type { RenderableFileDiff } from "@/lib/file-diff";
export const DIFF_GAP_HEIGHT = 26;
const ROW_BATCH = 40;
export function diffRowOffsets(diff: RenderableFileDiff, lineLimit: number, lineHeight: number): number[] {
const offsets: number[] = [];
let top = 0;
for (const [index, hunk] of diff.hunks.entries()) {
if (offsets.length >= lineLimit) break;
const previous = diff.hunks[index - 1];
if (previous && (hunk.old_start > previous.old_start + previous.old_lines || hunk.new_start > previous.new_start + previous.new_lines)) top += DIFF_GAP_HEIGHT;
for (let line = 0; line < hunk.lines.length; line++) {
if (offsets.length >= lineLimit) break;
offsets.push(top);
top += lineHeight;
}
}
offsets.push(top);
return offsets;
}
export function diffRenderWindow(diff: RenderableFileDiff, offsets: number[], top: number, bottom: number, lineHeight: number, selected?: readonly [number, number]) {
const count = offsets.length - 1;
if (count <= 160) return { startingLine: 0, totalLines: count, bufferBefore: 0, bufferAfter: 0 };
let start = offsets.findIndex((offset) => offset >= top);
if (start < 0) start = count - 1;
// Keep both edges together, with one extra batch for the rounded-down start.
const capacity = Math.min(count, (Math.ceil((bottom - top) / lineHeight / ROW_BATCH) + 1) * ROW_BATCH);
start = Math.min(count - capacity, Math.max(0, Math.floor((start - 1) / ROW_BATCH) * ROW_BATCH));
let end = start + capacity;
// Retain only the active selection's rows as the viewport keeps moving. Clearing it
// returns to the ordinary bounded window; do not freeze rendering or accumulate old windows.
if (selected) {
start = Math.min(start, selected[0]);
end = Math.min(count, Math.max(end, selected[1]));
}
let before = offsets[start];
let after = offsets[count] - offsets[end];
// A separator is rendered with its first row, not with the preceding window.
let row = 0;
for (const [index, hunk] of diff.hunks.entries()) {
const previous = diff.hunks[index - 1];
const gap = previous && (hunk.old_start > previous.old_start + previous.old_lines || hunk.new_start > previous.new_start + previous.new_lines);
if (gap && row === start) before -= DIFF_GAP_HEIGHT;
if (gap && row === end) after += DIFF_GAP_HEIGHT;
row += hunk.lines.length;
}
return { startingLine: start, totalLines: end - start, bufferBefore: before, bufferAfter: after };
}
@@ -0,0 +1,40 @@
import type { FileDiffMetadata } from "@pierre/diffs";
// Native ranges must be read inside Pierre's shadow tree, not from retargeted host endpoints.
export function selectedDiffRows(wrapper: HTMLElement, metadata: FileDiffMetadata): readonly [number, number] | undefined {
const host = wrapper.querySelector("diffs-container");
const root = host?.shadowRoot;
const selection = document.getSelection();
if (!root || !selection) return;
const shadowSelection = (root as ShadowRoot & { getSelection?(): Selection | null }).getSelection?.();
const ranges = typeof selection.getComposedRanges === "function"
? selection.getComposedRanges({ shadowRoots: [root] })
: shadowSelection?.rangeCount ? [shadowSelection.getRangeAt(0)] : selection.rangeCount ? [selection.getRangeAt(0)] : [];
const selected = ranges[0];
// Chromium can report document Selection.isCollapsed=true for a nonempty shadow selection.
if (!selected || (selected.startContainer === selected.endContainer && selected.startOffset === selected.endOffset)) return;
const startsInside = selected.startContainer.getRootNode() === root;
const endsInside = selected.endContainer.getRootNode() === root;
if (!startsInside && !endsInside && (!selection.rangeCount || !selection.getRangeAt(0).intersectsNode(host))) return;
const localRange = document.createRange();
localRange.selectNodeContents(root);
if (startsInside) localRange.setStart(selected.startContainer, selected.startOffset);
if (endsInside) localRange.setEnd(selected.endContainer, selected.endOffset);
let first: number | undefined;
let last: number | undefined;
for (const row of root.querySelectorAll<HTMLElement>("[data-code] [data-line][data-line-index]")) {
if (!localRange.intersectsNode(row)) continue;
const index = Number(row.dataset.lineIndex!.split(",")[0]);
let renderedStart = 0;
for (const hunk of metadata.hunks) {
if (index >= hunk.unifiedLineStart && index < hunk.unifiedLineStart + hunk.unifiedLineCount) {
const renderedIndex = renderedStart + index - hunk.unifiedLineStart;
first = first === undefined ? renderedIndex : Math.min(first, renderedIndex);
last = last === undefined ? renderedIndex + 1 : Math.max(last, renderedIndex + 1);
break;
}
renderedStart += hunk.unifiedLineCount;
}
}
return first === undefined || last === undefined ? undefined : [first, last];
}