Skip to content

Commit c73f6af

Browse files
leo-stuartclaude
andcommitted
fix(web): select all in a diff file copies every line, not just mounted rows
Cmd/Ctrl+A in the Diff panel selected the whole app, and copying only returned the rows the virtualizer had mounted. Select all now scopes to the diff file the user last clicked in, and copy writes that file's lines from the loaded diff instead of the DOM. Refs #30825 Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 8b44f42 commit c73f6af

4 files changed

Lines changed: 178 additions & 1 deletion

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
2+
import { describe, expect, it, vi } from "vite-plus/test";
3+
4+
import { render } from "../../../test/render";
5+
6+
import { StyledDiffCodeView } from "./StyledDiffCodeView";
7+
8+
const LINE_COUNT = 2_000;
9+
const lines = Array.from({ length: LINE_COUNT }, (_, index) => `line ${index + 1}`);
10+
const fileDiff = parsePatchFiles(
11+
[
12+
"diff --git a/big.sql b/big.sql",
13+
"new file mode 100644",
14+
"--- /dev/null",
15+
"+++ b/big.sql",
16+
`@@ -0,0 +1,${LINE_COUNT} @@`,
17+
...lines.map((line) => `+${line}`),
18+
"",
19+
].join("\n"),
20+
"big.sql",
21+
)[0]!.files[0]!;
22+
23+
function copy(): string {
24+
const clipboardData = new DataTransfer();
25+
document.body.dispatchEvent(
26+
new ClipboardEvent("copy", { clipboardData, bubbles: true, cancelable: true }),
27+
);
28+
return clipboardData.getData("text/plain");
29+
}
30+
31+
describe("StyledDiffCodeView", () => {
32+
it("copies every line of a file after select all, including rows the virtualizer dropped", async () => {
33+
await using screen = await render(
34+
<StyledDiffCodeView
35+
style={{ height: 300, overflow: "auto" }}
36+
items={[{ id: "big", type: "diff", fileDiff }]}
37+
/>,
38+
);
39+
const root = () => screen.container.querySelector("diffs-container")?.shadowRoot;
40+
await vi.waitFor(() => expect(root()?.querySelector("[data-line]")).toBeTruthy());
41+
const rows = root()!.querySelectorAll("[data-line]");
42+
expect(rows.length).toBeLessThan(LINE_COUNT);
43+
44+
rows[1]!.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, composed: true }));
45+
const selectAll = new KeyboardEvent("keydown", {
46+
key: "a",
47+
metaKey: true,
48+
ctrlKey: true,
49+
bubbles: true,
50+
cancelable: true,
51+
});
52+
document.body.dispatchEvent(selectAll);
53+
54+
expect(selectAll.defaultPrevented).toBe(true);
55+
expect(copy()).toBe(lines.join("\n"));
56+
57+
document.body.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));
58+
expect(copy()).toBe("");
59+
});
60+
});

‎apps/web/src/components/diffs/StyledDiffCodeView.tsx‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import type { Ref } from "react";
1111

1212
import { DIFF_SURFACE_THEME_UNSAFE_CSS } from "~/lib/diffRendering";
1313
import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
14+
import { setRef, useDiffSelectAllCopy } from "./useDiffSelectAllCopy";
1415

1516
export const DIFF_VIEW_UNSAFE_CSS = `${DIFF_SURFACE_THEME_UNSAFE_CSS}
1617
/* A 1fr track's automatic minimum grows with the currently mounted lines. In split
@@ -224,11 +225,15 @@ export function StyledDiffCodeView<LAnnotation = undefined>({
224225
unsafeCSSExtra,
225226
...props
226227
}: StyledDiffCodeViewProps<LAnnotation>) {
228+
const setSelectAllHandle = useDiffSelectAllCopy<LAnnotation>();
227229
return (
228230
<DiffWorkerPoolProvider>
229231
<CodeView<LAnnotation>
230232
{...props}
231-
{...(viewerRef ? { ref: viewerRef } : {})}
233+
ref={(handle: CodeViewHandle<LAnnotation, undefined> | null) => {
234+
setSelectAllHandle(handle);
235+
setRef(viewerRef, handle);
236+
}}
232237
className={
233238
className
234239
? `diff-render-surface [--code-background:var(--background)] outline-none ${className}`
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
import type { CodeViewHandle } from "@pierre/diffs/react";
2+
import { type Ref, useEffect, useState } from "react";
3+
4+
import { isEditableFocused } from "~/lib/editableFocus";
5+
import { buildDiffFileText } from "~/reviewCommentContext";
6+
7+
function isSelectAll(event: KeyboardEvent): boolean {
8+
return (
9+
event.key.toLowerCase() === "a" &&
10+
(event.metaKey || event.ctrlKey) &&
11+
!event.altKey &&
12+
!event.shiftKey
13+
);
14+
}
15+
16+
function isCopy(event: KeyboardEvent): boolean {
17+
return event.key.toLowerCase() === "c" && (event.metaKey || event.ctrlKey);
18+
}
19+
20+
const MODIFIER_KEYS = new Set(["Meta", "Control", "Shift", "Alt"]);
21+
22+
class DiffSelectAll<LAnnotation> {
23+
handle: CodeViewHandle<LAnnotation, undefined> | null = null;
24+
// The file the last pointer interaction landed in.
25+
engagedItemId: string | null = null;
26+
// The file select all chose. The virtualizer drops its offscreen rows, so
27+
// copy writes the file's text instead of the drawn selection.
28+
selectedItemId: string | null = null;
29+
30+
setHandle = (handle: CodeViewHandle<LAnnotation, undefined> | null) => {
31+
this.handle = handle;
32+
};
33+
34+
itemText(itemId: string): string | null {
35+
const item = this.handle?.getItem(itemId);
36+
if (!item) return null;
37+
return item.type === "diff" ? buildDiffFileText(item.fileDiff) : item.file.contents;
38+
}
39+
40+
drawSelection(itemId: string) {
41+
const element = this.handle
42+
?.getInstance()
43+
?.getRenderedItems()
44+
.find((item) => item.id === itemId)?.element;
45+
const rows = element?.shadowRoot?.querySelectorAll("[data-line]");
46+
const first = rows?.[0];
47+
const last = rows?.[rows.length - 1];
48+
if (!first || !last) return;
49+
document.getSelection()?.setBaseAndExtent(first, 0, last, last.childNodes.length);
50+
}
51+
52+
listen(): () => void {
53+
const onPointerDown = (event: PointerEvent) => {
54+
this.selectedItemId = null;
55+
const path = event.composedPath();
56+
this.engagedItemId =
57+
this.handle
58+
?.getInstance()
59+
?.getRenderedItems()
60+
.find((item) => path.includes(item.element))?.id ?? null;
61+
};
62+
const onKeyDown = (event: KeyboardEvent) => {
63+
if (MODIFIER_KEYS.has(event.key) || isCopy(event)) return;
64+
this.selectedItemId = null;
65+
const itemId = this.engagedItemId;
66+
if (!isSelectAll(event) || itemId === null || isEditableFocused(event.target)) return;
67+
if (this.itemText(itemId) === null) return;
68+
event.preventDefault();
69+
this.selectedItemId = itemId;
70+
this.drawSelection(itemId);
71+
};
72+
const onCopy = (event: ClipboardEvent) => {
73+
const itemId = this.selectedItemId;
74+
if (itemId === null || !event.clipboardData || isEditableFocused()) return;
75+
const text = this.itemText(itemId);
76+
if (text === null) return;
77+
event.clipboardData.setData("text/plain", text);
78+
event.preventDefault();
79+
};
80+
document.addEventListener("pointerdown", onPointerDown, true);
81+
document.addEventListener("keydown", onKeyDown, true);
82+
document.addEventListener("copy", onCopy, true);
83+
return () => {
84+
document.removeEventListener("pointerdown", onPointerDown, true);
85+
document.removeEventListener("keydown", onKeyDown, true);
86+
document.removeEventListener("copy", onCopy, true);
87+
};
88+
}
89+
}
90+
91+
/**
92+
* Scopes select all to the diff file the user is working in and copies all of
93+
* its lines, since the virtualizer only keeps the rows near the viewport.
94+
*/
95+
export function useDiffSelectAllCopy<LAnnotation>() {
96+
const [selectAll] = useState(() => new DiffSelectAll<LAnnotation>());
97+
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- document listeners live while the viewer is mounted
98+
useEffect(() => selectAll.listen(), [selectAll]);
99+
return selectAll.setHandle;
100+
}
101+
102+
export function setRef<T>(ref: Ref<T> | undefined, value: T | null) {
103+
if (typeof ref === "function") ref(value);
104+
else if (ref) ref.current = value;
105+
}

‎apps/web/src/reviewCommentContext.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,13 @@ export function resolveDiffReviewAnchor(
415415
: { position: last };
416416
}
417417

418+
/** The file's diff lines in unified order, without markers or collapsed context. */
419+
export function buildDiffFileText(fileDiff: FileDiffMetadata): string {
420+
return buildDiffReviewLines(fileDiff, false)
421+
.map((line) => line.content)
422+
.join("\n");
423+
}
424+
418425
function getDiffRange(
419426
lines: ReadonlyArray<DiffReviewLine>,
420427
key: "oldLineNumber" | "newLineNumber",

0 commit comments

Comments
 (0)