Skip to content

Commit c00a373

Browse files
fix(web): Select All then Copy in a read-only file preview copies the whole file (#33903)
Co-authored-by: Julius Marminge <[email protected]>
1 parent 7eca0ed commit c00a373

2 files changed

Lines changed: 124 additions & 23 deletions

File tree

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import type { ReactNode } from "react";
2+
import { describe, expect, it, vi } from "vite-plus/test";
3+
import { userEvent } from "vite-plus/test/browser";
4+
import "~/index.css";
5+
6+
import { render } from "../../../test/render";
7+
8+
import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting";
9+
10+
// The pool starts its workers before showing any code, which can outlast a cold CI browser.
11+
vi.mock(import("~/components/DiffWorkerPoolProvider"), () => ({
12+
DiffWorkerPoolProvider: ({ children }: { children?: ReactNode }) => <>{children}</>,
13+
}));
14+
15+
import ReadOnlySourcePreview from "./ReadOnlySourcePreview";
16+
17+
const LINE_COUNT = 301;
18+
const text = `${Array.from({ length: LINE_COUNT }, (_, index) => `line ${index + 1}`).join("\n")}\n`;
19+
20+
// The browser ignores a copy event's data unless the event is cancelled, and copies the selection itself.
21+
function copiedText(target: Element) {
22+
const clipboardData = new DataTransfer();
23+
const handled = !target.dispatchEvent(
24+
new ClipboardEvent("copy", { clipboardData, bubbles: true, cancelable: true, composed: true }),
25+
);
26+
return handled ? clipboardData.getData("text/plain") : null;
27+
}
28+
29+
describe("ReadOnlySourcePreview", () => {
30+
it("copies the whole file after Select All, wherever the preview is scrolled", async () => {
31+
// File paints nothing until the shared highlighter has loaded; once it has, mount renders synchronously.
32+
await getSyntaxHighlighterPromise("text");
33+
await using screen = await render(
34+
<div className="flex h-[400px] flex-col">
35+
<ReadOnlySourcePreview name="notes.txt" text={text} wordWrap={false} />
36+
</div>,
37+
);
38+
const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
39+
const rows = () => root.querySelectorAll("[data-line]");
40+
await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
41+
// Only rows near the viewport are mounted, so the browser's own copy would stop there.
42+
expect(rows().length).toBeLessThan(LINE_COUNT);
43+
44+
await userEvent.click(rows()[0]!);
45+
await userEvent.keyboard("{ControlOrMeta>}a{/ControlOrMeta}");
46+
expect(copiedText(rows()[0]!)).toBe(text);
47+
48+
const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
49+
scroller.scrollTop = scroller.scrollHeight;
50+
await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"));
51+
expect(copiedText(rows()[0]!)).toBe(text);
52+
53+
document.getSelection()!.removeAllRanges();
54+
await userEvent.click(rows()[rows().length - 1]!);
55+
await userEvent.keyboard("{ControlOrMeta>}a{/ControlOrMeta}");
56+
expect(copiedText(rows()[0]!)).toBe(text);
57+
58+
// A selection that stops inside the mounted rows at either end stays the browser's to copy.
59+
const pre = root.querySelector("pre")!;
60+
const firstText = rows()[0]!.querySelector("span")!.firstChild!;
61+
const lastText = rows()[rows().length - 1]!.querySelector("span")!.firstChild!;
62+
document.getSelection()!.setBaseAndExtent(pre, 0, lastText, 4);
63+
expect(copiedText(rows()[0]!)).toBeNull();
64+
document.getSelection()!.setBaseAndExtent(firstText, 4, pre, pre.childNodes.length);
65+
expect(copiedText(rows()[0]!)).toBeNull();
66+
});
67+
});
Lines changed: 57 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { File, type FileOptions, Virtualizer } from "@pierre/diffs/react";
2+
import type { ClipboardEvent } from "react";
23

34
import { DiffWorkerPoolProvider } from "~/components/DiffWorkerPoolProvider";
45
import { useClientSettings } from "~/hooks/useSettings";
@@ -8,6 +9,31 @@ import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
89

910
import { FILE_LINK_REVEAL_UNSAFE_CSS } from "./fileSurfaceChrome";
1011

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+
}
36+
1137
export default function ReadOnlySourcePreview(props: {
1238
readonly name: string;
1339
readonly text: string;
@@ -19,31 +45,39 @@ export default function ReadOnlySourcePreview(props: {
1945
const resolvedTheme = useRenderedAppearance();
2046
const defaultWordWrap = useClientSettings((settings) => settings.wordWrap);
2147
const wordWrap = props.wordWrap ?? defaultWordWrap;
48+
const copyWholeFile = (event: ClipboardEvent<HTMLDivElement>) => {
49+
const root = event.currentTarget.querySelector("diffs-container")?.shadowRoot;
50+
if (!root || !selectsEveryMountedRow(root)) return;
51+
event.clipboardData.setData("text/plain", props.text);
52+
event.preventDefault();
53+
};
2254
return (
2355
<DiffWorkerPoolProvider>
24-
<Virtualizer
25-
key={`${props.name}:${resolvedTheme}:${props.text.length}`}
26-
className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
27-
config={{ overscrollSize: 600, intersectionObserverMargin: 1200 }}
28-
>
29-
<File
30-
file={{
31-
name: props.name,
32-
contents: props.text,
33-
...(props.cacheKey ? { cacheKey: props.cacheKey } : {}),
34-
}}
35-
options={{
36-
disableFileHeader: true,
37-
overflow: wordWrap ? "wrap" : "scroll",
38-
theme: resolveDiffThemeName(resolvedTheme),
39-
preferredHighlighter: PREFERRED_HIGHLIGHTER,
40-
themeType: resolvedTheme,
41-
unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
42-
...(props.onPostRender ? { onPostRender: props.onPostRender } : {}),
43-
}}
44-
className="min-h-full"
45-
/>
46-
</Virtualizer>
56+
<div className="contents" onCopy={copyWholeFile}>
57+
<Virtualizer
58+
key={`${props.name}:${resolvedTheme}:${props.text.length}`}
59+
className="file-preview-virtualizer min-h-0 flex-1 overflow-auto"
60+
config={{ overscrollSize: 600, intersectionObserverMargin: 1200 }}
61+
>
62+
<File
63+
file={{
64+
name: props.name,
65+
contents: props.text,
66+
...(props.cacheKey ? { cacheKey: props.cacheKey } : {}),
67+
}}
68+
options={{
69+
disableFileHeader: true,
70+
overflow: wordWrap ? "wrap" : "scroll",
71+
theme: resolveDiffThemeName(resolvedTheme),
72+
preferredHighlighter: PREFERRED_HIGHLIGHTER,
73+
themeType: resolvedTheme,
74+
unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
75+
...(props.onPostRender ? { onPostRender: props.onPostRender } : {}),
76+
}}
77+
className="min-h-full"
78+
/>
79+
</Virtualizer>
80+
</div>
4781
</DiffWorkerPoolProvider>
4882
);
4983
}

0 commit comments

Comments
 (0)