Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ReadOnlySourcePreview.browser.test.tsx

326 lines14.9 KB

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