Skip to content

Commit a66d279

Browse files
fix(web): copying a file preview selection returns the selected lines after scrolling
The read-only file preview mounts only the rows near the viewport, so the browser's selection lost an end as soon as that end's row unmounted: a drag that scrolled copied the mounted rows or the whole file, and a click, scroll and Shift+click selected nothing. The preview now keeps the selection as offsets into the file's text. It reads the browser's selection on every change, keeps an end whose row is no longer mounted, and draws the selection back onto the rows after each render. Copy takes the text from those offsets whenever part of it is not mounted. The focus always comes from the browser's own selection, so a drag held past the edge of the preview follows the native autoscroll. Fixes #15927 Co-Authored-By: Claude Fable 5.2 <[email protected]>
1 parent e65a06d commit a66d279

3 files changed

Lines changed: 385 additions & 32 deletions

File tree

‎apps/web/src/components/files/ReadOnlySourcePreview.browser.test.tsx‎

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { ReactNode } from "react";
22
import { describe, expect, it, vi } from "vite-plus/test";
3-
import { userEvent } from "vite-plus/test/browser";
3+
import { cdp, userEvent } from "vite-plus/test/browser";
44
import "~/index.css";
55

66
import { render } from "../../../test/render";
@@ -90,4 +90,72 @@ describe("ReadOnlySourcePreview", () => {
9090

9191
expect(copiedText(rows()[0]!) ?? document.getSelection()!.toString()).toBe(selected);
9292
});
93+
94+
it("copies a drag that autoscrolls past the edge of the preview", async () => {
95+
await getSyntaxHighlighterPromise("text");
96+
await using screen = await render(
97+
<div className="flex h-[400px] flex-col">
98+
<ReadOnlySourcePreview name="notes.txt" text={text} wordWrap={false} />
99+
</div>,
100+
);
101+
const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
102+
const rows = () => root.querySelectorAll("[data-line]");
103+
await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
104+
105+
const start = rows()[4]!.querySelector("span")!.getBoundingClientRect();
106+
const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
107+
const edge = scroller.getBoundingClientRect().bottom;
108+
const frame = window.frameElement?.getBoundingClientRect();
109+
const mouse = (type: "mousePressed" | "mouseMoved" | "mouseReleased", x: number, y: number) =>
110+
cdp().send("Input.dispatchMouseEvent", {
111+
type,
112+
x: x + (frame?.left ?? 0),
113+
y: y + (frame?.top ?? 0),
114+
button: "left",
115+
buttons: type === "mouseReleased" ? 0 : 1,
116+
clickCount: 1,
117+
});
118+
await mouse("mousePressed", start.left + 1, start.top + 5);
119+
await mouse("mouseMoved", start.left + 30, edge - 5);
120+
// Held below the preview, the pointer is over no row while the browser scrolls the drag on.
121+
await mouse("mouseMoved", start.left + 30, edge + 60);
122+
await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"), { timeout: 10_000 });
123+
await mouse("mouseReleased", start.left + 30, edge + 60);
124+
125+
const copied = copiedText(rows()[0]!)!;
126+
const from = text.indexOf("line 5\n");
127+
expect(copied).toBe(text.slice(from, from + copied.length));
128+
// The drag ends in the rows on screen, short of the last mounted one.
129+
const lastLine = 4 + copied.split("\n").length;
130+
expect(lastLine).toBeGreaterThan(50);
131+
expect(lastLine).toBeLessThan(Number(rows()[rows().length - 1]!.getAttribute("data-line")));
132+
});
133+
134+
it("extends a selection with Shift+click after its anchor scrolls out of the mounted window", async () => {
135+
await getSyntaxHighlighterPromise("text");
136+
await using screen = await render(
137+
<div className="flex h-[400px] flex-col">
138+
<ReadOnlySourcePreview name="notes.txt" text={text} wordWrap={false} />
139+
</div>,
140+
);
141+
const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
142+
const rows = () => root.querySelectorAll("[data-line]");
143+
await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
144+
145+
await userEvent.click(rows()[2]!.querySelector("span")!, { position: { x: 1, y: 5 } });
146+
const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
147+
scroller.scrollTop = scroller.scrollHeight;
148+
await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"));
149+
await userEvent.click(rows()[rows().length - 1]!.querySelector("span")!, {
150+
position: { x: 1, y: 5 },
151+
modifiers: ["Shift"],
152+
});
153+
154+
const clicked = document.getSelection()!.getComposedRanges({ shadowRoots: [root] })[0]!;
155+
const lastLine = clicked.endContainer.textContent!;
156+
expect(Number(lastLine.replace("line ", ""))).toBeGreaterThan(250);
157+
expect(copiedText(rows()[0]!)).toBe(
158+
text.slice(text.indexOf("line 3\n"), text.indexOf(`${lastLine}\n`)),
159+
);
160+
});
93161
});

‎apps/web/src/components/files/ReadOnlySourcePreview.tsx‎

Lines changed: 46 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { File, type FileOptions, Virtualizer } from "@pierre/diffs/react";
2-
import type { ClipboardEvent } from "react";
2+
import { type ClipboardEvent, useEffect, useRef, useState } from "react";
33

44
import { DiffWorkerPoolProvider } from "~/components/DiffWorkerPoolProvider";
55
import { useClientSettings } from "~/hooks/useSettings";
@@ -8,31 +8,7 @@ import { resolveDiffThemeName } from "~/lib/diffRendering";
88
import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
99

1010
import { FILE_LINK_REVEAL_UNSAFE_CSS } from "./fileSurfaceChrome";
11-
12-
/** Select All spans the file's shadow tree, where the virtualizer mounts only rows near the viewport. */
13-
function selectsEveryMountedRow(root: ShadowRoot) {
14-
const rows = root.querySelectorAll("[data-line]");
15-
const first = rows[0];
16-
const last = rows[rows.length - 1];
17-
if (!first || !last) return false;
18-
try {
19-
const selected = document.getSelection()?.getComposedRanges({ shadowRoots: [root] })[0];
20-
if (!selected) return false;
21-
if (!root.contains(selected.startContainer) || !root.contains(selected.endContainer)) {
22-
return false;
23-
}
24-
const range = document.createRange();
25-
range.setStart(selected.startContainer, selected.startOffset);
26-
range.setEnd(selected.endContainer, selected.endOffset);
27-
// A dragged selection ends inside rows, so it never holds a row's own boundaries.
28-
return (
29-
range.comparePoint(first, 0) === 0 && range.comparePoint(last, last.childNodes.length) === 0
30-
);
31-
} catch {
32-
// Engines without composed ranges keep their own copy.
33-
return false;
34-
}
35-
}
11+
import { SourceSelection } from "./sourceSelection";
3612

3713
export default function ReadOnlySourcePreview(props: {
3814
readonly name: string;
@@ -45,15 +21,54 @@ export default function ReadOnlySourcePreview(props: {
4521
const resolvedTheme = useRenderedAppearance();
4622
const defaultWordWrap = useClientSettings((settings) => settings.wordWrap);
4723
const wordWrap = props.wordWrap ?? defaultWordWrap;
48-
const copyWholeFile = (event: ClipboardEvent<HTMLDivElement>) => {
24+
const { text, onPostRender } = props;
25+
const wrapper = useRef<HTMLDivElement>(null);
26+
const [selection] = useState(() => new SourceSelection());
27+
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- follows the document's selection, which only it reports
28+
useEffect(() => {
29+
const root = () => wrapper.current?.querySelector("diffs-container")?.shadowRoot;
30+
const sync = () => {
31+
const shadowRoot = root();
32+
if (shadowRoot) selection.sync(shadowRoot, text);
33+
};
34+
// A drag that autoscrolls is usually released outside the preview.
35+
const release = () => {
36+
const shadowRoot = root();
37+
if (shadowRoot) selection.release(shadowRoot, text);
38+
};
39+
document.addEventListener("selectionchange", sync);
40+
window.addEventListener("pointerup", release, true);
41+
window.addEventListener("pointercancel", release, true);
42+
return () => {
43+
document.removeEventListener("selectionchange", sync);
44+
window.removeEventListener("pointerup", release, true);
45+
window.removeEventListener("pointercancel", release, true);
46+
};
47+
}, [selection, text]);
48+
const copySelection = (event: ClipboardEvent<HTMLDivElement>) => {
4949
const root = event.currentTarget.querySelector("diffs-container")?.shadowRoot;
50-
if (!root || !selectsEveryMountedRow(root)) return;
51-
event.clipboardData.setData("text/plain", props.text);
50+
const copied = root ? selection.copy(root, text) : undefined;
51+
if (copied === undefined) return;
52+
event.clipboardData.setData("text/plain", copied);
5253
event.preventDefault();
5354
};
55+
const drawSelection: NonNullable<typeof onPostRender> = (node, instance, phase) => {
56+
if (phase !== "unmount" && node.shadowRoot) selection.render(node.shadowRoot, text);
57+
return onPostRender?.(node, instance, phase);
58+
};
5459
return (
5560
<DiffWorkerPoolProvider>
56-
<div className="contents" onCopy={copyWholeFile}>
61+
<div
62+
ref={wrapper}
63+
className="contents"
64+
onCopy={copySelection}
65+
onPointerDown={() => selection.press()}
66+
// Scrolling unmounts rows, and a selection made in the same task has not been reported yet.
67+
onScrollCapture={(event) => {
68+
const root = event.currentTarget.querySelector("diffs-container")?.shadowRoot;
69+
if (root) selection.sync(root, text);
70+
}}
71+
>
5772
<Virtualizer
5873
key={`${props.name}:${resolvedTheme}:${props.text.length}`}
5974
className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
@@ -72,7 +87,7 @@ export default function ReadOnlySourcePreview(props: {
7287
preferredHighlighter: PREFERRED_HIGHLIGHTER,
7388
themeType: resolvedTheme,
7489
unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
75-
...(props.onPostRender ? { onPostRender: props.onPostRender } : {}),
90+
onPostRender: drawSelection,
7691
}}
7792
className="min-h-full"
7893
/>

0 commit comments

Comments
 (0)