Open History to see the last commit
1import type { ReactNode } from "react";
2import { describe, expect, it, vi } from "vite-plus/test";
3import { cdp, userEvent } from "vite-plus/test/browser";
4import "~/index.css";
5
6import { render } from "../../../test/render";
7
8import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting";
9
10// The pool starts its workers before showing any code, which can outlast a cold CI browser.
11vi.mock(import("~/components/DiffWorkerPoolProvider"), () => ({
12 DiffWorkerPoolProvider: ({ children }: { children?: ReactNode }) => <>{children}</>,
13}));
14
15import ReadOnlySourcePreview from "./ReadOnlySourcePreview";
16
17const LINE_COUNT = 301;
18const 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.
21function 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
29describe("ReadOnlySourcePreview", () => {
30 it("opens a find field on mod+f after a click in the file, as the editable view does", async () => {
31 await getSyntaxHighlighterPromise("typescript");
32 await using screen = await render(
33 <div className="flex h-100 flex-col">
34 <ReadOnlySourcePreview name="other.ts" text={'export const needle = "findme";\n'} />
35 </div>,
36 );
37 const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
38 const firstRow = () => root.querySelector("[data-line]");
39 await vi.waitFor(() => expect(firstRow()?.textContent).toContain("needle"));
40
41 await userEvent.click(firstRow()!);
42 await userEvent.keyboard("{ControlOrMeta>}f{/ControlOrMeta}");
43
44 await vi.waitFor(() => {
45 let active = document.activeElement;
46 while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
47 expect(active).toBeInstanceOf(HTMLInputElement);
48 });
49
50 await userEvent.keyboard("findme");
51 await vi.waitFor(() =>
52 expect(Array.from(CSS.highlights.get("diffs-search-current") ?? [], String)).toEqual([
53 "findme",
54 ]),
55 );
56
57 await userEvent.keyboard("{Escape}");
58 await vi.waitFor(() =>
59 expect(screen.container.querySelector("[data-search-panel]")).toBeNull(),
60 );
61 });
62
63 it("updates rendered text and search matches when text changes without remounting", async () => {
64 await getSyntaxHighlighterPromise("typescript");
65 await using screen = await render(
66 <div className="flex h-100 flex-col">
67 <ReadOnlySourcePreview name="stream.ts" text={"const first = 1;\n"} />
68 </div>,
69 );
70 const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
71 await vi.waitFor(() => expect(root.textContent).toContain("first"));
72
73 await screen.rerender(
74 <div className="flex h-100 flex-col">
75 <ReadOnlySourcePreview name="stream.ts" text={"const first = 1;\nconst second = 2;\n"} />
76 </div>,
77 );
78 await vi.waitFor(() => expect(root.textContent).toContain("second"));
79
80 await userEvent.click(root.querySelector("[data-line]")!);
81 await userEvent.keyboard("{ControlOrMeta>}f{/ControlOrMeta}");
82 await vi.waitFor(() => {
83 let active = document.activeElement;
84 while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
85 expect(active).toBeInstanceOf(HTMLInputElement);
86 });
87 await userEvent.keyboard("second");
88 await vi.waitFor(() =>
89 expect(Array.from(CSS.highlights.get("diffs-search-current") ?? [], String)).toEqual([
90 "second",
91 ]),
92 );
93 });
94
95 it("copies the whole file after Select All, wherever the preview is scrolled", async () => {
96 // File paints nothing until the shared highlighter has loaded; once it has, mount renders synchronously.
97 await getSyntaxHighlighterPromise("text");
98 await using screen = await render(
99 <div className="flex h-100 flex-col">
100 <ReadOnlySourcePreview name="notes.txt" text={text} wordWrap={false} />
101 </div>,
102 );
103 const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
104 const rows = () => root.querySelectorAll("[data-line]");
105 await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
106 // Only rows near the viewport are mounted, so the browser's own copy would stop there.
107 expect(rows().length).toBeLessThan(LINE_COUNT);
108
109 await userEvent.click(rows()[0]!);
110 await userEvent.keyboard("{ControlOrMeta>}a{/ControlOrMeta}");
111 expect(copiedText(rows()[0]!)).toBe(text);
112
113 const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
114 scroller.scrollTop = scroller.scrollHeight;
115 await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"));
116 expect(copiedText(rows()[0]!)).toBe(text);
117
118 document.getSelection()!.removeAllRanges();
119 await userEvent.click(rows()[rows().length - 1]!);
120 await userEvent.keyboard("{ControlOrMeta>}a{/ControlOrMeta}");
121 expect(copiedText(rows()[0]!)).toBe(text);
122
123 // A selection that stops inside the mounted rows at either end stays the browser's to copy.
124 const pre = root.querySelector("pre")!;
125 const firstText = rows()[0]!.querySelector("span")!.firstChild!;
126 const lastText = [...rows()]
127 .findLast((row) => row.querySelector("span") !== null)!
128 .querySelector("span")!.firstChild!;
129 document.getSelection()!.setBaseAndExtent(pre, 0, lastText, 4);
130 expect(copiedText(rows()[0]!)).toBeNull();
131 document.getSelection()!.setBaseAndExtent(firstText, 4, pre, pre.childNodes.length);
132 expect(copiedText(rows()[0]!)).toBeNull();
133 });
134
135 it.each([
136 ["a lone carriage return", "\r"],
137 ["a carriage return and line feed", "\r\n"],
138 ])("copies the whole of a file whose lines end in %s", async (_name, ending) => {
139 const contents = text.replaceAll("\n", ending);
140 await getSyntaxHighlighterPromise("text");
141 await using screen = await render(
142 <div className="flex h-100 flex-col">
143 <ReadOnlySourcePreview name="notes.txt" text={contents} wordWrap={false} />
144 </div>,
145 );
146 const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
147 const rows = () => root.querySelectorAll("[data-line]");
148 await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
149
150 await userEvent.click(rows()[0]!);
151 await userEvent.keyboard("{ControlOrMeta>}a{/ControlOrMeta}");
152 const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
153 scroller.scrollTop = scroller.scrollHeight;
154 await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"));
155 expect(copiedText(rows()[0]!)).toBe(contents);
156 });
157
158 it.each([
159 { contents: text, height: 400 },
160 // Short enough that rows of the selection stay mounted with the preview scrolled to the bottom.
161 { contents: text.split("\n").slice(0, 163).join("\n"), height: 800 },
162 ])(
163 "restores and copies a partial selection after scrolling away and back ($height px)",
164 async ({ contents, height }) => {
165 await getSyntaxHighlighterPromise("text");
166 await using screen = await render(
167 <div className="flex flex-col" style={{ height }}>
168 <ReadOnlySourcePreview name="notes.txt" text={contents} wordWrap={false} />
169 </div>,
170 );
171 const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
172 const rows = () => root.querySelectorAll("[data-line]");
173 await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
174
175 const rowText = (line: number) =>
176 [...rows()].find((row) => row.textContent === `line ${line}`)!.querySelector("span")!
177 .firstChild!;
178 document.getSelection()!.setBaseAndExtent(rowText(5), 0, rowText(20), "line 20".length);
179 const selected = Array.from({ length: 16 }, (_, index) => `line ${index + 5}`).join("\n");
180
181 const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
182 scroller.scrollTop = scroller.scrollHeight;
183 await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"));
184 scroller.scrollTop = 0;
185 await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
186
187 expect(document.getSelection()!.toString()).toBe(selected);
188 expect(copiedText(rows()[0]!) ?? document.getSelection()!.toString()).toBe(selected);
189 },
190 );
191
192 it("drops a selection scrolled out of the mounted window when a click lands on its edge", async () => {
193 await getSyntaxHighlighterPromise("text");
194 await using screen = await render(
195 <div className="flex h-100 flex-col">
196 <ReadOnlySourcePreview name="notes.txt" text={text} wordWrap={false} />
197 </div>,
198 );
199 const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
200 const rows = () => root.querySelectorAll("[data-line]");
201 await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
202
203 const rowText = (index: number) => rows()[index]!.querySelector("span")!.firstChild!;
204 document.getSelection()!.setBaseAndExtent(rowText(4), 0, rowText(19), 4);
205 const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
206 scroller.scrollTop = scroller.scrollHeight;
207 await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"));
208 expect(copiedText(rows()[0]!)).toContain("line 5\n");
209
210 // The first mounted row is where the scrolled-out selection is parked, far above the viewport.
211 rows()[0]!.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, composed: true }));
212 document.getSelection()!.collapse(rowText(0), 0);
213 expect(copiedText(rows()[0]!)).toBeNull();
214 });
215
216 it("copies a drag that autoscrolls past the edge of the preview", async () => {
217 await getSyntaxHighlighterPromise("text");
218 await using screen = await render(
219 <div className="flex h-100 flex-col">
220 <ReadOnlySourcePreview name="notes.txt" text={text} wordWrap={false} />
221 </div>,
222 );
223 const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
224 const rows = () => root.querySelectorAll("[data-line]");
225 await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
226
227 const start = rows()[4]!.querySelector("span")!.getBoundingClientRect();
228 const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
229 const edge = scroller.getBoundingClientRect().bottom;
230 const frame = window.frameElement?.getBoundingClientRect();
231 const mouse = (type: "mousePressed" | "mouseMoved" | "mouseReleased", x: number, y: number) =>
232 cdp().send("Input.dispatchMouseEvent", {
233 type,
234 x: x + (frame?.left ?? 0),
235 y: y + (frame?.top ?? 0),
236 button: "left",
237 buttons: type === "mouseReleased" ? 0 : 1,
238 clickCount: 1,
239 });
240 await mouse("mousePressed", start.left + 1, start.top + 5);
241 await mouse("mouseMoved", start.left + 30, edge - 5);
242 // Held below the preview, the pointer is over no row while the browser scrolls the drag on.
243 await mouse("mouseMoved", start.left + 30, edge + 60);
244 await vi.waitFor(
245 () => expect(Number(rows()[0]?.getAttribute("data-line"))).toBeGreaterThan(5),
246 { timeout: 10_000 },
247 );
248 await mouse("mouseReleased", start.left + 30, edge + 60);
249
250 const copied = copiedText(rows()[0]!)!;
251 const from = text.indexOf("line 5\n");
252 expect(copied).toBe(text.slice(from, from + copied.length));
253 // The drag ends in the rows on screen, short of the last mounted one.
254 const lastLine = 4 + copied.split("\n").length;
255 expect(lastLine).toBeGreaterThan(20);
256 expect(lastLine).toBeLessThan(Number(rows()[rows().length - 1]!.getAttribute("data-line")));
257 });
258
259 it("extends a selection with Shift+click after its anchor scrolls out of the mounted window", async () => {
260 await getSyntaxHighlighterPromise("text");
261 await using screen = await render(
262 <div className="flex h-100 flex-col">
263 <ReadOnlySourcePreview name="notes.txt" text={text} wordWrap={false} />
264 </div>,
265 );
266 const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
267 const rows = () => root.querySelectorAll("[data-line]");
268 await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
269
270 await userEvent.click(rows()[2]!.querySelector("span")!, { position: { x: 1, y: 5 } });
271 const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
272 scroller.scrollTop = scroller.scrollHeight;
273 await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"));
274 const lastSpan = [...rows()]
275 .findLast((row) => row.querySelector("span") !== null)!
276 .querySelector("span")!;
277 await userEvent.click(lastSpan, {
278 position: { x: 1, y: 5 },
279 modifiers: ["Shift"],
280 });
281
282 const clicked = document.getSelection()!.getComposedRanges({ shadowRoots: [root] })[0]!;
283 const lastLine = clicked.endContainer.textContent!;
284 expect(Number(lastLine.replace("line ", ""))).toBeGreaterThan(250);
285 expect(copiedText(rows()[0]!)).toBe(
286 text.slice(text.indexOf("line 3\n"), text.indexOf(`${lastLine}\n`)),
287 );
288 });
289});