perf(web): defer diff workers until a code view opens (#9692)
This commit is contained in:
1 parent
c163d502dd
commit
b3e1d88590
11 files changed
+802
-274
No files matched your search
@@ -179,7 +179,6 @@ import {
|
||||
deriveAgentPanelModel,
|
||||
foldSubagentActivities,
|
||||
} from "@t3tools/client-runtime/state/subagentRuntime";
|
||||
import { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
|
||||
import { BranchToolbar } from "./BranchToolbar";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
|
||||
@@ -1351,7 +1350,7 @@ function releaseChatTimelineAnchor<T extends { readonly messageId: MessageId | n
|
||||
return current.messageId === null ? current : { ...current, messageId: null };
|
||||
}
|
||||
|
||||
function ChatViewContent(props: ChatViewProps) {
|
||||
export default function ChatView(props: ChatViewProps) {
|
||||
const {
|
||||
environmentId,
|
||||
threadId,
|
||||
@@ -8226,11 +8225,3 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ChatView(props: ChatViewProps) {
|
||||
return (
|
||||
<DiffWorkerPoolProvider>
|
||||
<ChatViewContent {...props} />
|
||||
</DiffWorkerPoolProvider>
|
||||
);
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal";
|
||||
import { useOpenInPreferredEditor } from "../editorPreferences";
|
||||
import { type DraftId } from "../composerDraftStore";
|
||||
import { openDiffFilePrimaryAction } from "../diffFileActions";
|
||||
@@ -129,7 +130,7 @@ export default function DiffPanel({
|
||||
fileKeys: EMPTY_COLLAPSED_DIFF_FILE_KEYS,
|
||||
}));
|
||||
const [codeViewRevision, setCodeViewRevision] = useState(0);
|
||||
const codeViewRef = useRef<AnnotatableCodeViewHandle>(null);
|
||||
const [codeView, setCodeView] = useState<AnnotatableCodeViewHandle | null>(null);
|
||||
|
||||
const routeThreadRef = useParams({
|
||||
strict: false,
|
||||
@@ -448,17 +449,15 @@ export default function DiffPanel({
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedDiffFileKey) return;
|
||||
codeViewRef.current?.scrollTo({ type: "item", id: selectedDiffFileKey, align: "start" });
|
||||
}, [codeViewMountKey, selectedDiffFileKey, selectedFileRevealRequestId]);
|
||||
if (!selectedDiffFileKey || !codeView?.getInstance()) return;
|
||||
codeView.scrollTo({ type: "item", id: selectedDiffFileKey, align: "start" });
|
||||
}, [codeView, codeViewMountKey, selectedDiffFileKey, selectedFileRevealRequestId]);
|
||||
|
||||
// Held as state so the scroll runs after a collapsed file has been drawn open again; scrolling
|
||||
// in the same tick would land on the folded header's position.
|
||||
const [treeReveal, setTreeReveal] = useState<{ fileKey: string; id: number } | null>(null);
|
||||
useEffect(() => {
|
||||
if (treeReveal === null) return;
|
||||
codeViewRef.current?.scrollTo({ type: "item", id: treeReveal.fileKey, align: "start" });
|
||||
}, [treeReveal]);
|
||||
const treeRevealScope = useMemo(
|
||||
() => ({ collapseScopeKey, diffSelection }),
|
||||
[collapseScopeKey, diffSelection],
|
||||
);
|
||||
const requestTreeReveal = useCodeViewFileReveal(codeView, treeRevealScope);
|
||||
const revealDiffFile = useCallback(
|
||||
(filePath: string) => {
|
||||
const file = codeViewFiles.find((candidate) => candidate.filePath === filePath);
|
||||
@@ -470,9 +469,9 @@ export default function DiffPanel({
|
||||
return { scopeKey: collapseScopeKey, fileKeys: next };
|
||||
});
|
||||
}
|
||||
setTreeReveal((current) => ({ fileKey: file.fileKey, id: (current?.id ?? 0) + 1 }));
|
||||
requestTreeReveal(file.fileKey);
|
||||
},
|
||||
[codeViewFiles, collapseScopeKey],
|
||||
[codeViewFiles, collapseScopeKey, requestTreeReveal],
|
||||
);
|
||||
|
||||
const openDiffFile = useCallback(
|
||||
@@ -972,7 +971,7 @@ export default function DiffPanel({
|
||||
>
|
||||
<AnnotatableCodeView
|
||||
key={collapseScopeKey ?? reviewSectionId}
|
||||
viewerRef={codeViewRef}
|
||||
viewerRef={setCodeView}
|
||||
codeViewKey={codeViewMountKey}
|
||||
className="h-full min-h-0 overflow-auto"
|
||||
files={codeViewFiles}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
|
||||
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { useEffect, useMemo, type ReactNode } from "react";
|
||||
import { useEffect, useMemo, useState, type ReactNode } from "react";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { PREFERRED_HIGHLIGHTER } from "../lib/syntaxHighlighting";
|
||||
@@ -46,6 +46,39 @@ function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Plain-text views do not queue a highlight task that could retry a blank first render.
|
||||
function DiffWorkerReady({ children }: { children?: ReactNode }) {
|
||||
const workerPool = useWorkerPool();
|
||||
const [ready, setReady] = useState(
|
||||
() => !workerPool || workerPool.isInitialized() || !workerPool.isWorkingPool(),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (ready || !workerPool) return;
|
||||
|
||||
let mounted = true;
|
||||
const finish = () => {
|
||||
if (mounted) setReady(true);
|
||||
};
|
||||
// Failed pools use Pierre's existing main-thread highlighter.
|
||||
void workerPool.initialize().then(finish, finish);
|
||||
return () => {
|
||||
mounted = false;
|
||||
};
|
||||
}, [ready, workerPool]);
|
||||
|
||||
return ready ? (
|
||||
children
|
||||
) : (
|
||||
<div
|
||||
role="status"
|
||||
className="flex min-h-0 flex-1 items-center justify-center p-4 text-xs text-muted-foreground"
|
||||
>
|
||||
Loading code...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
@@ -80,7 +113,7 @@ export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
||||
}}
|
||||
>
|
||||
<DiffWorkerThemeSync themeName={diffThemeName} />
|
||||
{children}
|
||||
<DiffWorkerReady>{children}</DiffWorkerReady>
|
||||
</WorkerPoolContextProvider>
|
||||
);
|
||||
}
|
||||
@@ -122,6 +122,10 @@ vi.mock("@pierre/diffs/react", () => {
|
||||
return { FileDiff: MockFileDiff };
|
||||
});
|
||||
|
||||
vi.mock("../DiffWorkerPoolProvider", () => ({
|
||||
DiffWorkerPoolProvider: ({ children }: { children?: ReactNode }) => children,
|
||||
}));
|
||||
|
||||
function matchMedia() {
|
||||
return {
|
||||
matches: false,
|
||||
|
||||
@@ -50,6 +50,7 @@ import {
|
||||
type MaintainScrollAtEndOptions,
|
||||
} from "@legendapp/list/react";
|
||||
import { FileDiff } from "@pierre/diffs/react";
|
||||
import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
|
||||
import {
|
||||
deriveTimelineEntries,
|
||||
workEntryDisplayIndicatesToolFailure,
|
||||
@@ -2530,19 +2531,22 @@ function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentConte
|
||||
className="text-message-foreground"
|
||||
/>
|
||||
)}
|
||||
{renderablePatch?.kind === "files" &&
|
||||
renderablePatch.files.map((fileDiff) => (
|
||||
<FileDiff
|
||||
key={resolveFileDiffPath(fileDiff)}
|
||||
fileDiff={fileDiff}
|
||||
options={{
|
||||
collapsed: false,
|
||||
diffStyle: "unified",
|
||||
theme: resolveDiffThemeName(ctx.resolvedTheme),
|
||||
preferredHighlighter: PREFERRED_HIGHLIGHTER,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
{renderablePatch?.kind === "files" && (
|
||||
<DiffWorkerPoolProvider>
|
||||
{renderablePatch.files.map((fileDiff) => (
|
||||
<FileDiff
|
||||
key={resolveFileDiffPath(fileDiff)}
|
||||
fileDiff={fileDiff}
|
||||
options={{
|
||||
collapsed: false,
|
||||
diffStyle: "unified",
|
||||
theme: resolveDiffThemeName(ctx.resolvedTheme),
|
||||
preferredHighlighter: PREFERRED_HIGHLIGHTER,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</DiffWorkerPoolProvider>
|
||||
)}
|
||||
{renderablePatch?.kind === "raw" && (
|
||||
<pre className="overflow-x-auto rounded-md bg-muted/40 p-2 text-xs">
|
||||
{renderablePatch.text}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
@@ -12,6 +13,10 @@ vi.mock("@pierre/diffs/react", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../DiffWorkerPoolProvider", () => ({
|
||||
DiffWorkerPoolProvider: ({ children }: { children?: ReactNode }) => children,
|
||||
}));
|
||||
|
||||
vi.mock("~/composerDraftStore", () => ({
|
||||
useComposerDraftStore: (selector: (store: Record<string, unknown>) => unknown) =>
|
||||
selector({
|
||||
|
||||
@@ -1,20 +1,153 @@
|
||||
import type * as NodeWorkerThreads from "node:worker_threads";
|
||||
import {
|
||||
FileRenderer,
|
||||
getSharedHighlighter,
|
||||
type CodeViewScrollTarget,
|
||||
type FileContents,
|
||||
} from "@pierre/diffs";
|
||||
import { useWorkerPool, type CodeViewProps } from "@pierre/diffs/react";
|
||||
import { WorkerPoolManager, type WorkerRequest, type WorkerResponse } from "@pierre/diffs/worker";
|
||||
import {
|
||||
act,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type Ref,
|
||||
} from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { create, type ReactTestRenderer } from "react-test-renderer";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const testState = vi.hoisted(() => ({
|
||||
codeViewClassName: null as string | null,
|
||||
codeViewOptions: null as Record<string, unknown> | null,
|
||||
workers: [] as NodeWorkerThreads.Worker[],
|
||||
terminations: [] as Promise<number>[],
|
||||
requests: [] as WorkerRequest[],
|
||||
pools: new Map<WorkerPoolManager, Promise<void>>(),
|
||||
renderPools: [] as (WorkerPoolManager | undefined)[],
|
||||
failWorkers: false,
|
||||
holdInitialization: false,
|
||||
heldResponses: [] as (() => void)[],
|
||||
onInitializationHeld: undefined as (() => void) | undefined,
|
||||
}));
|
||||
|
||||
vi.mock("@pierre/diffs/react", () => ({
|
||||
CodeView: (props: { className: string; options: Record<string, unknown> }) => {
|
||||
testState.codeViewClassName = props.className;
|
||||
testState.codeViewOptions = props.options;
|
||||
return null;
|
||||
vi.mock("../../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
|
||||
|
||||
vi.mock("@pierre/diffs/worker/worker.js?worker", async () => {
|
||||
const { Worker } = await import("node:worker_threads");
|
||||
const moduleUrl = import.meta.resolve("@pierre/diffs/worker/worker.js");
|
||||
|
||||
// Adapt only the transport. Pierre's real worker loads its WASM and produces every response.
|
||||
return {
|
||||
default: class {
|
||||
worker: NodeWorkerThreads.Worker;
|
||||
|
||||
constructor() {
|
||||
if (testState.failWorkers) throw new Error("Worker creation failed");
|
||||
this.worker = new Worker(
|
||||
`const { parentPort, workerData } = require("node:worker_threads");
|
||||
globalThis.self = {
|
||||
addEventListener(type, listener) {
|
||||
if (type === "message") parentPort.on("message", data => listener({ data }));
|
||||
if (type === "error") process.on("uncaughtException", listener);
|
||||
}
|
||||
};
|
||||
globalThis.postMessage = data => parentPort.postMessage(data);
|
||||
import(workerData.moduleUrl);`,
|
||||
{ eval: true, workerData: { moduleUrl }, execArgv: [] },
|
||||
);
|
||||
testState.workers.push(this.worker);
|
||||
}
|
||||
|
||||
addEventListener(
|
||||
type: "message" | "error",
|
||||
listener: (event: { data: WorkerResponse } | Error) => void,
|
||||
) {
|
||||
if (type === "error") {
|
||||
this.worker.on("error", listener);
|
||||
return;
|
||||
}
|
||||
this.worker.on("message", (data: WorkerResponse) => {
|
||||
const deliver = () => listener({ data });
|
||||
if (
|
||||
testState.holdInitialization &&
|
||||
data.type === "success" &&
|
||||
data.requestType === "initialize"
|
||||
) {
|
||||
testState.heldResponses.push(deliver);
|
||||
if (testState.heldResponses.length === 2) testState.onInitializationHeld?.();
|
||||
} else {
|
||||
deliver();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
postMessage(message: WorkerRequest) {
|
||||
testState.requests.push(message);
|
||||
this.worker.postMessage(message, []);
|
||||
}
|
||||
|
||||
terminate() {
|
||||
testState.terminations.push(this.worker.terminate());
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@pierre/diffs/react", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@pierre/diffs/react")>()),
|
||||
CodeView: (props: CodeViewProps) => {
|
||||
testState.codeViewClassName = props.className ?? null;
|
||||
testState.codeViewOptions = props.options ? { ...props.options } : null;
|
||||
return props.items?.map((item) =>
|
||||
item.type === "file" ? <FileOutput key={item.id} file={item.file} /> : null,
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
import { StyledDiffCodeView } from "./StyledDiffCodeView";
|
||||
import { useCodeViewFileReveal } from "./useCodeViewFileReveal";
|
||||
|
||||
function FileOutput({ file }: { file: FileContents }) {
|
||||
const pool = useWorkerPool();
|
||||
const [html, setHtml] = useState("");
|
||||
useEffect(() => {
|
||||
testState.renderPools.push(pool);
|
||||
const renderer = new FileRenderer(
|
||||
{ theme: "pierre-dark", preferredHighlighter: "shiki-wasm" },
|
||||
render,
|
||||
pool,
|
||||
);
|
||||
function render() {
|
||||
const result = renderer.renderFile(file);
|
||||
if (result) setHtml(renderer.renderFullHTML(result));
|
||||
}
|
||||
render();
|
||||
return () => renderer.cleanUp();
|
||||
}, [file, pool]);
|
||||
return <pre data-code-file={file.name}>{html}</pre>;
|
||||
}
|
||||
|
||||
const files = [
|
||||
{ name: "notes.txt", contents: "Plain text is ready.\n", cacheKey: "plain-text" },
|
||||
{ name: "answer.ts", contents: "const answer = 42;\n", cacheKey: "typescript" },
|
||||
] satisfies FileContents[];
|
||||
|
||||
function Views({ count }: { count: number }) {
|
||||
const [draft, setDraft] = useState("Draft");
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => setDraft("Edited draft")}>{draft}</button>
|
||||
{files.slice(0, count).map((file) => (
|
||||
<StyledDiffCodeView key={file.name} items={[{ type: "file", id: file.name, file }]} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
describe("StyledDiffCodeView", () => {
|
||||
beforeEach(() => {
|
||||
@@ -58,3 +191,338 @@ describe("StyledDiffCodeView", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("code-view worker lifecycle", () => {
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
testState.workers = [];
|
||||
testState.terminations = [];
|
||||
testState.requests = [];
|
||||
testState.pools.clear();
|
||||
testState.renderPools = [];
|
||||
testState.failWorkers = false;
|
||||
testState.holdInitialization = false;
|
||||
testState.heldResponses = [];
|
||||
testState.onInitializationHeld = undefined;
|
||||
vi.stubGlobal("window", {});
|
||||
vi.stubGlobal("navigator", { hardwareConcurrency: 2 });
|
||||
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) =>
|
||||
setImmediate(() => callback(0)),
|
||||
);
|
||||
vi.stubGlobal("cancelAnimationFrame", clearImmediate);
|
||||
const initialize = WorkerPoolManager.prototype.initialize;
|
||||
vi.spyOn(WorkerPoolManager.prototype, "initialize").mockImplementation(function (
|
||||
this: WorkerPoolManager,
|
||||
...args
|
||||
) {
|
||||
const pending = initialize.apply(this, args);
|
||||
testState.pools.set(this, pending);
|
||||
return pending;
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => renderer?.unmount());
|
||||
renderer = undefined;
|
||||
await Promise.all(testState.terminations);
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("starts on demand, shares one pool, disposes the last view, and reopens without resetting siblings", async () => {
|
||||
await act(async () => {
|
||||
renderer = create(<Views count={0} />);
|
||||
});
|
||||
const mounted = renderer!;
|
||||
const button = mounted.root.findByType("button");
|
||||
expect(testState.workers).toHaveLength(0);
|
||||
expect(testState.pools.size).toBe(0);
|
||||
await act(async () => {
|
||||
(button.props as { onClick(): void }).onClick();
|
||||
mounted.update(<Views count={1} />);
|
||||
});
|
||||
const pool = [...testState.pools.keys()][0]!;
|
||||
await act(async () => testState.pools.get(pool));
|
||||
expect(pool.isInitialized()).toBe(true);
|
||||
expect(testState.workers).toHaveLength(2);
|
||||
expect(mounted.root.findByProps({ "data-code-file": "notes.txt" }).children.join("")).toContain(
|
||||
"Plain text is ready.",
|
||||
);
|
||||
expect(testState.requests.filter((request) => request.type === "file")).toHaveLength(0);
|
||||
|
||||
await act(async () => mounted.update(<Views count={2} />));
|
||||
await act(async () => pool.primeFileHighlightCache(files[1]!));
|
||||
expect(testState.pools.size).toBe(1);
|
||||
expect(testState.workers).toHaveLength(2);
|
||||
expect(testState.renderPools).toEqual([pool, pool]);
|
||||
expect(pool.getFileResultCache(files[1]!)).toBeDefined();
|
||||
expect(mounted.root.findByProps({ "data-code-file": "answer.ts" }).children.join("")).toContain(
|
||||
"answer",
|
||||
);
|
||||
|
||||
await act(async () => mounted.update(<Views count={1} />));
|
||||
expect(pool.getStats().totalWorkers).toBe(2);
|
||||
expect(testState.terminations).toHaveLength(0);
|
||||
await act(async () => mounted.update(<Views count={0} />));
|
||||
await Promise.all(testState.terminations);
|
||||
expect(pool.getStats().totalWorkers).toBe(0);
|
||||
expect(testState.terminations).toHaveLength(2);
|
||||
|
||||
await act(async () => mounted.update(<Views count={1} />));
|
||||
const reopenedPool = [...testState.pools.keys()][1]!;
|
||||
await act(async () => testState.pools.get(reopenedPool));
|
||||
expect(reopenedPool.isInitialized()).toBe(true);
|
||||
expect(testState.workers).toHaveLength(4);
|
||||
expect(mounted.root.findByType("button")).toBe(button);
|
||||
expect(button.children).toEqual(["Edited draft"]);
|
||||
expect(mounted.root.findByProps({ "data-code-file": "notes.txt" }).children.join("")).toContain(
|
||||
"Plain text is ready.",
|
||||
);
|
||||
});
|
||||
|
||||
it("renders through Pierre's main-thread fallback when worker creation fails", async () => {
|
||||
testState.failWorkers = true;
|
||||
await act(async () => {
|
||||
renderer = create(<Views count={1} />);
|
||||
});
|
||||
const pool = [...testState.pools.keys()][0]!;
|
||||
await act(async () => {
|
||||
await expect(testState.pools.get(pool)).rejects.toMatchObject({ _tag: "DiffWorkerError" });
|
||||
await getSharedHighlighter({
|
||||
themes: ["pierre-dark"],
|
||||
langs: ["text"],
|
||||
preferredHighlighter: "shiki-wasm",
|
||||
});
|
||||
});
|
||||
expect(pool.isWorkingPool()).toBe(false);
|
||||
expect(testState.workers).toHaveLength(0);
|
||||
expect(
|
||||
renderer!.root.findByProps({ "data-code-file": "notes.txt" }).children.join(""),
|
||||
).toContain("Plain text is ready.");
|
||||
});
|
||||
|
||||
it("keeps an initializing pool until its last view closes and ignores late responses", async () => {
|
||||
testState.holdInitialization = true;
|
||||
const held = new Promise<void>((resolve) => {
|
||||
testState.onInitializationHeld = resolve;
|
||||
});
|
||||
await act(async () => {
|
||||
renderer = create(<Views count={2} />);
|
||||
});
|
||||
const pool = [...testState.pools.keys()][0]!;
|
||||
const pending = testState.pools.get(pool)!;
|
||||
await held;
|
||||
expect(pool.isInitialized()).toBe(false);
|
||||
expect(testState.pools.size).toBe(1);
|
||||
expect(renderer!.root.findAllByProps({ role: "status" })).toHaveLength(2);
|
||||
expect(testState.renderPools).toHaveLength(0);
|
||||
|
||||
await act(async () => renderer!.update(<Views count={1} />));
|
||||
expect(pool.getStats().totalWorkers).toBe(2);
|
||||
expect(testState.terminations).toHaveLength(0);
|
||||
await act(async () => renderer!.update(<Views count={0} />));
|
||||
await pending;
|
||||
await Promise.all(testState.terminations);
|
||||
await act(async () => {
|
||||
for (const deliver of testState.heldResponses) deliver();
|
||||
});
|
||||
expect(pool.getStats().totalWorkers).toBe(0);
|
||||
expect(testState.workers).toHaveLength(2);
|
||||
expect(testState.terminations).toHaveLength(2);
|
||||
expect(testState.renderPools).toHaveLength(0);
|
||||
expect(renderer!.root.findAllByType("pre")).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
type RevealHandle = NonNullable<Parameters<typeof useCodeViewFileReveal>[0]>;
|
||||
const revealCalls: {
|
||||
scope: string;
|
||||
fileKey: string;
|
||||
mounted: boolean;
|
||||
collapsed: boolean | undefined;
|
||||
}[] = [];
|
||||
|
||||
function RevealViewer({
|
||||
viewerRef,
|
||||
scope,
|
||||
collapsed,
|
||||
}: {
|
||||
viewerRef: Ref<RevealHandle>;
|
||||
scope: string;
|
||||
collapsed: boolean;
|
||||
}) {
|
||||
const instance = useRef<{ collapsed: boolean } | undefined>(undefined);
|
||||
useLayoutEffect(() => {
|
||||
instance.current = { collapsed };
|
||||
return () => {
|
||||
instance.current = undefined;
|
||||
};
|
||||
}, [collapsed]);
|
||||
const handle = useMemo(
|
||||
() => ({
|
||||
getInstance: () => instance.current,
|
||||
scrollTo: (target: CodeViewScrollTarget) => {
|
||||
if (target.type !== "item") return;
|
||||
revealCalls.push({
|
||||
scope,
|
||||
fileKey: target.id,
|
||||
mounted: instance.current !== undefined,
|
||||
collapsed: instance.current?.collapsed,
|
||||
});
|
||||
},
|
||||
}),
|
||||
[scope],
|
||||
);
|
||||
useImperativeHandle(viewerRef, () => handle, [handle]);
|
||||
return null;
|
||||
}
|
||||
|
||||
function RevealViews({
|
||||
scope,
|
||||
visible,
|
||||
selectedFile = null,
|
||||
requestId = 0,
|
||||
}: {
|
||||
scope: string;
|
||||
visible: boolean;
|
||||
selectedFile?: string | null;
|
||||
requestId?: number;
|
||||
}) {
|
||||
const [viewer, setViewer] = useState<RevealHandle | null>(null);
|
||||
const [collapsed, setCollapsed] = useState(true);
|
||||
const selectedRequest = useMemo(() => ({ selectedFile, requestId }), [requestId, selectedFile]);
|
||||
useEffect(() => {
|
||||
if (!selectedRequest.selectedFile || !viewer?.getInstance()) return;
|
||||
viewer.scrollTo({ type: "item", id: selectedRequest.selectedFile, align: "start" });
|
||||
}, [selectedRequest, viewer]);
|
||||
const revealScope = useMemo(() => ({ scope, selectedRequest }), [scope, selectedRequest]);
|
||||
const requestReveal = useCodeViewFileReveal(viewer, revealScope);
|
||||
return (
|
||||
<>
|
||||
{visible && (
|
||||
<RevealViewer key={scope} viewerRef={setViewer} scope={scope} collapsed={collapsed} />
|
||||
)}
|
||||
<button
|
||||
onClick={() => {
|
||||
setCollapsed(false);
|
||||
requestReveal("tree-file");
|
||||
}}
|
||||
>
|
||||
Reveal file
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
describe("code-view file reveals", () => {
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
revealCalls.length = 0;
|
||||
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => renderer?.unmount());
|
||||
renderer = undefined;
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("does not replay a handled tree click or scroll an old handle when a selected file remounts the view", async () => {
|
||||
await act(async () => {
|
||||
renderer = create(<RevealViews scope="first" visible selectedFile="external-a" />);
|
||||
});
|
||||
await act(async () => {
|
||||
(renderer!.root.findByType("button").props as { onClick(): void }).onClick();
|
||||
});
|
||||
expect(revealCalls.at(-1)?.fileKey).toBe("tree-file");
|
||||
revealCalls.length = 0;
|
||||
|
||||
await act(async () => {
|
||||
renderer!.update(
|
||||
<RevealViews scope="second" visible selectedFile="external-b" requestId={1} />,
|
||||
);
|
||||
});
|
||||
expect(revealCalls).toEqual([
|
||||
{ scope: "second", fileKey: "external-b", mounted: true, collapsed: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it("waits for a live viewer and applies each pending tree click only once", async () => {
|
||||
await act(async () => {
|
||||
renderer = create(<RevealViews scope="diff" visible={false} selectedFile="external" />);
|
||||
});
|
||||
await act(async () => {
|
||||
(renderer!.root.findByType("button").props as { onClick(): void }).onClick();
|
||||
});
|
||||
expect(revealCalls).toEqual([]);
|
||||
|
||||
await act(async () => {
|
||||
renderer!.update(<RevealViews scope="diff" visible selectedFile="external" />);
|
||||
});
|
||||
expect(revealCalls.map((call) => call.fileKey)).toEqual(["external", "tree-file"]);
|
||||
revealCalls.length = 0;
|
||||
await act(async () => {
|
||||
renderer!.update(<RevealViews scope="diff" visible={false} selectedFile="external" />);
|
||||
});
|
||||
await act(async () => {
|
||||
renderer!.update(<RevealViews scope="diff" visible selectedFile="external" />);
|
||||
});
|
||||
expect(revealCalls).toEqual([
|
||||
{ scope: "diff", fileKey: "external", mounted: true, collapsed: false },
|
||||
]);
|
||||
|
||||
revealCalls.length = 0;
|
||||
await act(async () => {
|
||||
(renderer!.root.findByType("button").props as { onClick(): void }).onClick();
|
||||
renderer!.update(<RevealViews scope="diff" visible={false} selectedFile="external" />);
|
||||
});
|
||||
expect(revealCalls).toEqual([]);
|
||||
await act(async () => {
|
||||
renderer!.update(<RevealViews scope="diff" visible selectedFile="external" />);
|
||||
});
|
||||
expect(revealCalls).toEqual([
|
||||
{ scope: "diff", fileKey: "external", mounted: true, collapsed: false },
|
||||
{ scope: "diff", fileKey: "tree-file", mounted: true, collapsed: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it("cancels pending tree clicks when an external selection or diff scope changes", async () => {
|
||||
await act(async () => {
|
||||
renderer = create(<RevealViews scope="first" visible={false} selectedFile="external-a" />);
|
||||
});
|
||||
await act(async () => {
|
||||
(renderer!.root.findByType("button").props as { onClick(): void }).onClick();
|
||||
});
|
||||
await act(async () => {
|
||||
renderer!.update(
|
||||
<RevealViews scope="first" visible selectedFile="external-b" requestId={1} />,
|
||||
);
|
||||
});
|
||||
expect(revealCalls.map((call) => call.fileKey)).toEqual(["external-b"]);
|
||||
revealCalls.length = 0;
|
||||
|
||||
await act(async () => renderer!.update(<RevealViews scope="first" visible={false} />));
|
||||
await act(async () => {
|
||||
(renderer!.root.findByType("button").props as { onClick(): void }).onClick();
|
||||
});
|
||||
await act(async () => renderer!.update(<RevealViews scope="second" visible={false} />));
|
||||
await act(async () => renderer!.update(<RevealViews scope="first" visible />));
|
||||
expect(revealCalls).toEqual([]);
|
||||
});
|
||||
|
||||
it("reveals after a collapsed file expands and honors another click on the same file", async () => {
|
||||
await act(async () => {
|
||||
renderer = create(<RevealViews scope="diff" visible />);
|
||||
});
|
||||
const reveal = renderer!.root.findByType("button").props as { onClick(): void };
|
||||
await act(async () => reveal.onClick());
|
||||
await act(async () => reveal.onClick());
|
||||
expect(revealCalls).toEqual([
|
||||
{ scope: "diff", fileKey: "tree-file", mounted: true, collapsed: false },
|
||||
{ scope: "diff", fileKey: "tree-file", mounted: true, collapsed: false },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import type { Ref } from "react";
|
||||
|
||||
import { DIFF_SURFACE_THEME_UNSAFE_CSS } from "~/lib/diffRendering";
|
||||
import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
|
||||
|
||||
const DIFF_VIEW_UNSAFE_CSS = `${DIFF_SURFACE_THEME_UNSAFE_CSS}
|
||||
:is(
|
||||
@@ -285,38 +286,40 @@ export function StyledDiffCodeView<LAnnotation = undefined>({
|
||||
...props
|
||||
}: StyledDiffCodeViewProps<LAnnotation>) {
|
||||
return (
|
||||
<CodeView<LAnnotation>
|
||||
{...props}
|
||||
{...(viewerRef ? { ref: viewerRef } : {})}
|
||||
// The custom element itself is focusable for keyboard scrolling. Its native outline sits
|
||||
// outside the panel clipping boundary; actual controls inside retain their own indicators.
|
||||
className={
|
||||
className
|
||||
? `diff-render-surface [--code-background:var(--background)] outline-none ${className}`
|
||||
: "diff-render-surface [--code-background:var(--background)] outline-none"
|
||||
}
|
||||
options={{
|
||||
...options,
|
||||
unsafeCSS: unsafeCSSExtra
|
||||
? `${DIFF_VIEW_UNSAFE_CSS}\n${unsafeCSSExtra}`
|
||||
: DIFF_VIEW_UNSAFE_CSS,
|
||||
itemMetrics: {
|
||||
diffHeaderHeight: 32,
|
||||
hunkSeparatorHeight: 24,
|
||||
// Pierre uses its general file spacing as a fallback in expanded-file layout paths.
|
||||
// Keep it zero alongside the explicit paddingTop or expanding the first file can
|
||||
// reintroduce the library's default 8px gap above its header.
|
||||
spacing: 0,
|
||||
paddingTop: 0,
|
||||
// Unlike the gap above, the 8px under a file's last line is painted
|
||||
// unconditionally by Pierre's stylesheet (`--diffs-gap-fallback`), so the metric has
|
||||
// to count it: at zero every expanded file's virtual height ran 8px short of its
|
||||
// rendered height, and the end of the list sat past the reachable scroll range —
|
||||
// one clipped file row per expanded file above it.
|
||||
paddingBottom: 8,
|
||||
},
|
||||
layout: { paddingTop: 0, paddingBottom: 0, gap: 0 },
|
||||
}}
|
||||
/>
|
||||
<DiffWorkerPoolProvider>
|
||||
<CodeView<LAnnotation>
|
||||
{...props}
|
||||
{...(viewerRef ? { ref: viewerRef } : {})}
|
||||
// The custom element itself is focusable for keyboard scrolling. Its native outline sits
|
||||
// outside the panel clipping boundary; actual controls inside retain their own indicators.
|
||||
className={
|
||||
className
|
||||
? `diff-render-surface [--code-background:var(--background)] outline-none ${className}`
|
||||
: "diff-render-surface [--code-background:var(--background)] outline-none"
|
||||
}
|
||||
options={{
|
||||
...options,
|
||||
unsafeCSS: unsafeCSSExtra
|
||||
? `${DIFF_VIEW_UNSAFE_CSS}\n${unsafeCSSExtra}`
|
||||
: DIFF_VIEW_UNSAFE_CSS,
|
||||
itemMetrics: {
|
||||
diffHeaderHeight: 32,
|
||||
hunkSeparatorHeight: 24,
|
||||
// Pierre uses its general file spacing as a fallback in expanded-file layout paths.
|
||||
// Keep it zero alongside the explicit paddingTop or expanding the first file can
|
||||
// reintroduce the library's default 8px gap above its header.
|
||||
spacing: 0,
|
||||
paddingTop: 0,
|
||||
// Unlike the gap above, the 8px under a file's last line is painted
|
||||
// unconditionally by Pierre's stylesheet (`--diffs-gap-fallback`), so the metric has
|
||||
// to count it: at zero every expanded file's virtual height ran 8px short of its
|
||||
// rendered height, and the end of the list sat past the reachable scroll range —
|
||||
// one clipped file row per expanded file above it.
|
||||
paddingBottom: 8,
|
||||
},
|
||||
layout: { paddingTop: 0, paddingBottom: 0, gap: 0 },
|
||||
}}
|
||||
/>
|
||||
</DiffWorkerPoolProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { CodeViewScrollTarget } from "@pierre/diffs";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
interface FileRevealHandle {
|
||||
getInstance(): object | undefined;
|
||||
scrollTo(target: CodeViewScrollTarget): void;
|
||||
}
|
||||
|
||||
// Wait for a mounted viewer and expanded rows, then apply each tree click once.
|
||||
// Keep scope stable until the diff or external file selection changes.
|
||||
export function useCodeViewFileReveal<TScope>(viewer: FileRevealHandle | null, scope: TScope) {
|
||||
const [request, setRequest] = useState<{ fileKey: string; scope: TScope } | null>(null);
|
||||
const handledRequest = useRef<typeof request>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (request === null || handledRequest.current === request) return;
|
||||
if (request.scope !== scope) {
|
||||
handledRequest.current = request;
|
||||
return;
|
||||
}
|
||||
if (!viewer?.getInstance()) return;
|
||||
|
||||
viewer.scrollTo({ type: "item", id: request.fileKey, align: "start" });
|
||||
handledRequest.current = request;
|
||||
}, [request, scope, viewer]);
|
||||
|
||||
return useCallback((fileKey: string) => setRequest({ fileKey, scope }), [scope]);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
import { VirtualizedFile, type SelectedLineRange } from "@pierre/diffs";
|
||||
import { Editor } from "@pierre/diffs/editor";
|
||||
import { EditProvider, File, type FileOptions, Virtualizer } from "@pierre/diffs/react";
|
||||
import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
@@ -1304,46 +1305,50 @@ export default function FilePreviewPanel({
|
||||
onPendingChange={onPendingChange}
|
||||
/>
|
||||
) : file.data.truncated || isHostFile ? (
|
||||
<Virtualizer
|
||||
key={`${relativePath}:${resolvedTheme}:${file.data.byteLength}`}
|
||||
className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
|
||||
config={{
|
||||
overscrollSize: 600,
|
||||
intersectionObserverMargin: 1200,
|
||||
}}
|
||||
>
|
||||
<File
|
||||
file={{
|
||||
name: relativePath,
|
||||
contents: file.data.contents,
|
||||
cacheKey: projectFileCacheKey(cwd, relativePath, file.data.contents),
|
||||
<DiffWorkerPoolProvider>
|
||||
<Virtualizer
|
||||
key={`${relativePath}:${resolvedTheme}:${file.data.byteLength}`}
|
||||
className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
|
||||
config={{
|
||||
overscrollSize: 600,
|
||||
intersectionObserverMargin: 1200,
|
||||
}}
|
||||
options={{
|
||||
disableFileHeader: true,
|
||||
overflow: wordWrap ? "wrap" : "scroll",
|
||||
theme: resolveDiffThemeName(resolvedTheme),
|
||||
preferredHighlighter: PREFERRED_HIGHLIGHTER,
|
||||
themeType: resolvedTheme,
|
||||
unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
|
||||
onPostRender: onFilePostRender,
|
||||
}}
|
||||
className="min-h-full"
|
||||
/>
|
||||
</Virtualizer>
|
||||
>
|
||||
<File
|
||||
file={{
|
||||
name: relativePath,
|
||||
contents: file.data.contents,
|
||||
cacheKey: projectFileCacheKey(cwd, relativePath, file.data.contents),
|
||||
}}
|
||||
options={{
|
||||
disableFileHeader: true,
|
||||
overflow: wordWrap ? "wrap" : "scroll",
|
||||
theme: resolveDiffThemeName(resolvedTheme),
|
||||
preferredHighlighter: PREFERRED_HIGHLIGHTER,
|
||||
themeType: resolvedTheme,
|
||||
unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
|
||||
onPostRender: onFilePostRender,
|
||||
}}
|
||||
className="min-h-full"
|
||||
/>
|
||||
</Virtualizer>
|
||||
</DiffWorkerPoolProvider>
|
||||
) : (
|
||||
<EditableFileSurface
|
||||
key={`${relativePath}:${resolvedTheme}`}
|
||||
environmentId={environmentId}
|
||||
cwd={cwd}
|
||||
relativePath={relativePath}
|
||||
composerDraftTarget={composerDraftTarget}
|
||||
contents={file.data.contents}
|
||||
resolvedTheme={resolvedTheme}
|
||||
revealRequestId={revealRequestId}
|
||||
wordWrap={wordWrap}
|
||||
onPostRender={onFilePostRender}
|
||||
onPendingChange={onPendingChange}
|
||||
/>
|
||||
<DiffWorkerPoolProvider>
|
||||
<EditableFileSurface
|
||||
key={`${relativePath}:${resolvedTheme}`}
|
||||
environmentId={environmentId}
|
||||
cwd={cwd}
|
||||
relativePath={relativePath}
|
||||
composerDraftTarget={composerDraftTarget}
|
||||
contents={file.data.contents}
|
||||
resolvedTheme={resolvedTheme}
|
||||
revealRequestId={revealRequestId}
|
||||
wordWrap={wordWrap}
|
||||
onPostRender={onFilePostRender}
|
||||
onPendingChange={onPendingChange}
|
||||
/>
|
||||
</DiffWorkerPoolProvider>
|
||||
)
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@@ -58,9 +58,9 @@ import { useEnvironmentQuery } from "~/state/query";
|
||||
import { useAtomCommand } from "~/state/use-atom-command";
|
||||
|
||||
import { DiffPanelLoadingState } from "../DiffPanelShell";
|
||||
import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
|
||||
import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";
|
||||
import { DiffFileTree } from "../diffs/DiffFileTree";
|
||||
import { useCodeViewFileReveal } from "../diffs/useCodeViewFileReveal";
|
||||
import { diffFileTreeEntries } from "../diffs/diffFileTree.logic";
|
||||
import { StyledDiffCodeView } from "../diffs/StyledDiffCodeView";
|
||||
import { Button } from "../ui/button";
|
||||
@@ -250,7 +250,7 @@ export function PullRequestCodeTab({
|
||||
readonly slices: ReadonlyArray<DiffSlice>;
|
||||
}>({ key: "", cursor: null, slices: NO_SLICES });
|
||||
const parseCache = useRef(new Map<string, RenderablePatch>());
|
||||
const viewerRef = useRef<CodeViewHandle<ReviewAnnotationGroup> | null>(null);
|
||||
const [viewer, setViewer] = useState<CodeViewHandle<ReviewAnnotationGroup> | null>(null);
|
||||
|
||||
const referenceKey = pullRequestReviewKey(reference);
|
||||
const commit = selectedCommitOid;
|
||||
@@ -603,21 +603,15 @@ export function PullRequestCodeTab({
|
||||
[],
|
||||
);
|
||||
|
||||
// Held as state so the scroll runs after a folded file has been drawn open; scrolling in the
|
||||
// same tick would land on the folded header's position.
|
||||
const [treeReveal, setTreeReveal] = useState<{ fileKey: string; id: number } | null>(null);
|
||||
useEffect(() => {
|
||||
if (treeReveal === null) return;
|
||||
viewerRef.current?.scrollTo({ type: "item", id: treeReveal.fileKey, align: "start" });
|
||||
}, [treeReveal]);
|
||||
const requestTreeReveal = useCodeViewFileReveal(viewer, scopeKey);
|
||||
const revealFile = useCallback(
|
||||
(path: string) => {
|
||||
const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path);
|
||||
if (item === undefined) return;
|
||||
if (item.collapsed === true) toggleFile(item.id);
|
||||
setTreeReveal((current) => ({ fileKey: item.id, id: (current?.id ?? 0) + 1 }));
|
||||
requestTreeReveal(item.id);
|
||||
},
|
||||
[items, toggleFile],
|
||||
[items, requestTreeReveal, toggleFile],
|
||||
);
|
||||
|
||||
const toggleAllFiles = () => {
|
||||
@@ -1290,164 +1284,158 @@ export function PullRequestCodeTab({
|
||||
);
|
||||
|
||||
return (
|
||||
<DiffWorkerPoolProvider>
|
||||
<div className="flex h-full min-h-0 flex-col">
|
||||
{toolbar}
|
||||
{/* Above the code, closed, and counted: these belong to the change rather than to any
|
||||
<div className="flex h-full min-h-0 flex-col">
|
||||
{toolbar}
|
||||
{/* Above the code, closed, and counted: these belong to the change rather than to any
|
||||
line of it, and in the stream they read as cards dropped into the patch. */}
|
||||
{orphanFiles.size > 0 ? (
|
||||
<Collapsible
|
||||
className="shrink-0 border-b border-border/60"
|
||||
open={orphansOpen}
|
||||
onOpenChange={setOrphansOpen}
|
||||
>
|
||||
{/* Still a heading, so the section keeps its place in a screen reader's outline;
|
||||
{orphanFiles.size > 0 ? (
|
||||
<Collapsible
|
||||
className="shrink-0 border-b border-border/60"
|
||||
open={orphansOpen}
|
||||
onOpenChange={setOrphansOpen}
|
||||
>
|
||||
{/* Still a heading, so the section keeps its place in a screen reader's outline;
|
||||
the count is spelled out there rather than left as a bare number. */}
|
||||
<h2>
|
||||
<CollapsibleTrigger className="flex w-full items-center gap-1.5 px-4 py-2 text-left text-xs text-muted-foreground">
|
||||
{/* While slices are still arriving a conversation may simply belong to a file
|
||||
<h2>
|
||||
<CollapsibleTrigger className="flex w-full items-center gap-1.5 px-4 py-2 text-left text-xs text-muted-foreground">
|
||||
{/* While slices are still arriving a conversation may simply belong to a file
|
||||
that has not landed yet, which is not the same as being off the diff. */}
|
||||
<span>
|
||||
{nextCursor === null
|
||||
? "Conversations not on the current diff"
|
||||
: "Conversations not on the diff loaded so far"}
|
||||
</span>
|
||||
<ChevronRightIcon
|
||||
aria-hidden
|
||||
className={cn("size-3.5 transition-transform", orphansOpen && "rotate-90")}
|
||||
/>
|
||||
<span aria-hidden className="tabular-nums">
|
||||
{orphanThreads.length}
|
||||
</span>
|
||||
<span className="sr-only">
|
||||
{orphanThreads.length === 1
|
||||
? "1 conversation"
|
||||
: `${orphanThreads.length} conversations`}
|
||||
</span>
|
||||
</CollapsibleTrigger>
|
||||
</h2>
|
||||
<CollapsiblePanel>
|
||||
{/* Capped: opened on a change with dozens of them, this would otherwise leave no
|
||||
<span>
|
||||
{nextCursor === null
|
||||
? "Conversations not on the current diff"
|
||||
: "Conversations not on the diff loaded so far"}
|
||||
</span>
|
||||
<ChevronRightIcon
|
||||
aria-hidden
|
||||
className={cn("size-3.5 transition-transform", orphansOpen && "rotate-90")}
|
||||
/>
|
||||
<span aria-hidden className="tabular-nums">
|
||||
{orphanThreads.length}
|
||||
</span>
|
||||
<span className="sr-only">
|
||||
{orphanThreads.length === 1
|
||||
? "1 conversation"
|
||||
: `${orphanThreads.length} conversations`}
|
||||
</span>
|
||||
</CollapsibleTrigger>
|
||||
</h2>
|
||||
<CollapsiblePanel>
|
||||
{/* Capped: opened on a change with dozens of them, this would otherwise leave no
|
||||
room for the diff it sits above. */}
|
||||
<div className="max-h-64 space-y-3 overflow-auto px-4 pb-3">
|
||||
{[...orphanFiles].map(([path, threads]) => (
|
||||
<div key={path}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<p className="truncate px-3 text-xs text-muted-foreground">{path}</p>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">{path}</TooltipPopup>
|
||||
</Tooltip>
|
||||
<div className="mt-1 space-y-2">
|
||||
{threads.map((thread) => (
|
||||
<div key={thread.id}>
|
||||
{thread.line === null ? null : (
|
||||
<p className="px-3 text-xs text-muted-foreground">Line {thread.line}</p>
|
||||
)}
|
||||
{renderThreadCard(thread)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="max-h-64 space-y-3 overflow-auto px-4 pb-3">
|
||||
{[...orphanFiles].map(([path, threads]) => (
|
||||
<div key={path}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={<p className="truncate px-3 text-xs text-muted-foreground">{path}</p>}
|
||||
/>
|
||||
<TooltipPopup side="top">{path}</TooltipPopup>
|
||||
</Tooltip>
|
||||
<div className="mt-1 space-y-2">
|
||||
{threads.map((thread) => (
|
||||
<div key={thread.id}>
|
||||
{thread.line === null ? null : (
|
||||
<p className="px-3 text-xs text-muted-foreground">Line {thread.line}</p>
|
||||
)}
|
||||
{renderThreadCard(thread)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CollapsiblePanel>
|
||||
</Collapsible>
|
||||
) : null}
|
||||
<div className="flex min-h-0 flex-1 overflow-hidden">
|
||||
{/* Relative wrapper so the review overlay floats over the diff rather than pushing it
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CollapsiblePanel>
|
||||
</Collapsible>
|
||||
) : null}
|
||||
<div className="flex min-h-0 flex-1 overflow-hidden">
|
||||
{/* Relative wrapper so the review overlay floats over the diff rather than pushing it
|
||||
up; the viewer inside still owns its own scrolling. */}
|
||||
<div
|
||||
className="relative min-h-0 min-w-0 flex-1"
|
||||
// The chevron answers this too, but the whole header row is the target a reader
|
||||
// actually aims for. The header lives in the viewer's shadow tree, so the capture
|
||||
// listener walks `composedPath` — the only way to see through the shadow boundary.
|
||||
onClickCapture={(event) => {
|
||||
const composedPath = event.nativeEvent.composedPath?.() ?? [];
|
||||
for (const node of composedPath) {
|
||||
if (!(node instanceof HTMLElement)) continue;
|
||||
// A control inside the header — the collapse chevron — handles itself, and
|
||||
// this capture listener fires before its own click does. Leave it alone or
|
||||
// the two toggles cancel out.
|
||||
if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {
|
||||
return;
|
||||
}
|
||||
if (node.hasAttribute("data-diffs-header")) {
|
||||
const filePath = node.querySelector("[data-title]")?.textContent?.trim();
|
||||
if (filePath === undefined || filePath === "") return;
|
||||
const item = items.find(
|
||||
(candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,
|
||||
);
|
||||
if (item !== undefined) toggleFile(item.id);
|
||||
return;
|
||||
}
|
||||
<div
|
||||
className="relative min-h-0 min-w-0 flex-1"
|
||||
// The chevron answers this too, but the whole header row is the target a reader
|
||||
// actually aims for. The header lives in the viewer's shadow tree, so the capture
|
||||
// listener walks `composedPath` — the only way to see through the shadow boundary.
|
||||
onClickCapture={(event) => {
|
||||
const composedPath = event.nativeEvent.composedPath?.() ?? [];
|
||||
for (const node of composedPath) {
|
||||
if (!(node instanceof HTMLElement)) continue;
|
||||
// A control inside the header — the collapse chevron — handles itself, and
|
||||
// this capture listener fires before its own click does. Leave it alone or
|
||||
// the two toggles cancel out.
|
||||
if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {
|
||||
return;
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/* The viewer virtualizes against the element it is told is scrolling and places its
|
||||
if (node.hasAttribute("data-diffs-header")) {
|
||||
const filePath = node.querySelector("[data-title]")?.textContent?.trim();
|
||||
if (filePath === undefined || filePath === "") return;
|
||||
const item = items.find(
|
||||
(candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,
|
||||
);
|
||||
if (item !== undefined) toggleFile(item.id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/* The viewer virtualizes against the element it is told is scrolling and places its
|
||||
rows absolutely, so it has to own that element — the thread diff panel hands it the
|
||||
same one. Scrolling from a parent instead leaves it painting over its neighbours. */}
|
||||
<StyledDiffCodeView<ReviewAnnotationGroup>
|
||||
// Keep scrollbar space stable so file metadata and line numbers do not shift as a
|
||||
// diff crosses the overflow boundary. The viewer is itself focusable for keyboard
|
||||
// interaction, but its native host outline clips and competes with the focus
|
||||
// indicators on its actual controls.
|
||||
className="h-full overflow-auto [scrollbar-gutter:stable]"
|
||||
viewerRef={viewerRef}
|
||||
items={items}
|
||||
selectedLines={selectedLines}
|
||||
onSelectedLinesChange={setSelectedLines}
|
||||
options={diffViewOptions}
|
||||
// The viewer owns the scroll container, so the sentinel that asks for the next slice
|
||||
// has to live inside it — at the end of the files, where reaching it means the reader
|
||||
// is running out of diff.
|
||||
renderCodeViewFooter={renderCodeViewFooter}
|
||||
renderHeaderPrefix={renderHeaderPrefix}
|
||||
renderHeaderMetadata={renderHeaderMetadata}
|
||||
renderAnnotation={renderAnnotation}
|
||||
unsafeCSSExtra={REPLACE_FILE_COUNTS_CSS}
|
||||
/>
|
||||
{reviewOverlay}
|
||||
</div>
|
||||
{fileTreeOpen ? (
|
||||
<aside className="flex w-[min(20rem,40%)] min-w-48 shrink-0 border-l border-border/60">
|
||||
<DiffFileTree
|
||||
ariaLabel={`Pull request #${detail.number} files`}
|
||||
entries={fileTreeEntries}
|
||||
onSelectFile={revealFile}
|
||||
// The tree lists only what has arrived; a footer says so while the diff is still
|
||||
// paging, and lets the reader pull the rest in without scrolling for it.
|
||||
footer={
|
||||
nextCursor === null ? null : (
|
||||
<div className="shrink-0 border-t border-border/60 p-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
disabled={diffQuery.isPending}
|
||||
onClick={
|
||||
diffQuery.error !== null ? () => diffQuery.refresh() : loadNextSlice
|
||||
}
|
||||
>
|
||||
{diffQuery.error !== null
|
||||
? "Retry"
|
||||
: diffQuery.isPending
|
||||
? "Loading more files..."
|
||||
: "Load more files"}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</aside>
|
||||
) : null}
|
||||
<StyledDiffCodeView<ReviewAnnotationGroup>
|
||||
// Keep scrollbar space stable so file metadata and line numbers do not shift as a
|
||||
// diff crosses the overflow boundary. The viewer is itself focusable for keyboard
|
||||
// interaction, but its native host outline clips and competes with the focus
|
||||
// indicators on its actual controls.
|
||||
className="h-full overflow-auto [scrollbar-gutter:stable]"
|
||||
viewerRef={setViewer}
|
||||
items={items}
|
||||
selectedLines={selectedLines}
|
||||
onSelectedLinesChange={setSelectedLines}
|
||||
options={diffViewOptions}
|
||||
// The viewer owns the scroll container, so the sentinel that asks for the next slice
|
||||
// has to live inside it — at the end of the files, where reaching it means the reader
|
||||
// is running out of diff.
|
||||
renderCodeViewFooter={renderCodeViewFooter}
|
||||
renderHeaderPrefix={renderHeaderPrefix}
|
||||
renderHeaderMetadata={renderHeaderMetadata}
|
||||
renderAnnotation={renderAnnotation}
|
||||
unsafeCSSExtra={REPLACE_FILE_COUNTS_CSS}
|
||||
/>
|
||||
{reviewOverlay}
|
||||
</div>
|
||||
{unstructured}
|
||||
{fileTreeOpen ? (
|
||||
<aside className="flex w-[min(20rem,40%)] min-w-48 shrink-0 border-l border-border/60">
|
||||
<DiffFileTree
|
||||
ariaLabel={`Pull request #${detail.number} files`}
|
||||
entries={fileTreeEntries}
|
||||
onSelectFile={revealFile}
|
||||
// The tree lists only what has arrived; a footer says so while the diff is still
|
||||
// paging, and lets the reader pull the rest in without scrolling for it.
|
||||
footer={
|
||||
nextCursor === null ? null : (
|
||||
<div className="shrink-0 border-t border-border/60 p-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
disabled={diffQuery.isPending}
|
||||
onClick={diffQuery.error !== null ? () => diffQuery.refresh() : loadNextSlice}
|
||||
>
|
||||
{diffQuery.error !== null
|
||||
? "Retry"
|
||||
: diffQuery.isPending
|
||||
? "Loading more files..."
|
||||
: "Load more files"}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</aside>
|
||||
) : null}
|
||||
</div>
|
||||
</DiffWorkerPoolProvider>
|
||||
{unstructured}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user