The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 216 lines 10.4 KB
Raw
1 import type { ReactNode } from "react";
2 import { describe, expect, it, vi } from "vite-plus/test";
3 import { cdp, 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
68 it.each([
69 ["a lone carriage return", "\r"],
70 ["a carriage return and line feed", "\r\n"],
71 ])("copies the whole of a file whose lines end in %s", async (_name, ending) => {
72 const contents = text.replaceAll("\n", ending);
73 await getSyntaxHighlighterPromise("text");
74 await using screen = await render(
75 <div className="flex h-[400px] flex-col">
76 <ReadOnlySourcePreview name="notes.txt" text={contents} wordWrap={false} />
77 </div>,
78 );
79 const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
80 const rows = () => root.querySelectorAll("[data-line]");
81 await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
82
83 await userEvent.click(rows()[0]!);
84 await userEvent.keyboard("{ControlOrMeta>}a{/ControlOrMeta}");
85 const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
86 scroller.scrollTop = scroller.scrollHeight;
87 await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"));
88 expect(copiedText(rows()[0]!)).toBe(contents);
89 });
90
91 it.each([
92 { contents: text, height: 400 },
93 // Short enough that rows of the selection stay mounted with the preview scrolled to the bottom.
94 { contents: text.split("\n").slice(0, 163).join("\n"), height: 800 },
95 ])(
96 "restores and copies a partial selection after scrolling away and back ($height px)",
97 async ({ contents, height }) => {
98 await getSyntaxHighlighterPromise("text");
99 await using screen = await render(
100 <div className="flex flex-col" style={{ height }}>
101 <ReadOnlySourcePreview name="notes.txt" text={contents} wordWrap={false} />
102 </div>,
103 );
104 const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
105 const rows = () => root.querySelectorAll("[data-line]");
106 await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
107
108 const rowText = (line: number) =>
109 [...rows()].find((row) => row.textContent === `line ${line}`)!.querySelector("span")!
110 .firstChild!;
111 document.getSelection()!.setBaseAndExtent(rowText(5), 0, rowText(20), "line 20".length);
112 const selected = Array.from({ length: 16 }, (_, index) => `line ${index + 5}`).join("\n");
113
114 const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
115 scroller.scrollTop = scroller.scrollHeight;
116 await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"));
117 scroller.scrollTop = 0;
118 await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
119
120 expect(document.getSelection()!.toString()).toBe(selected);
121 expect(copiedText(rows()[0]!) ?? document.getSelection()!.toString()).toBe(selected);
122 },
123 );
124
125 it("drops a selection scrolled out of the mounted window when a click lands on its edge", async () => {
126 await getSyntaxHighlighterPromise("text");
127 await using screen = await render(
128 <div className="flex h-[400px] flex-col">
129 <ReadOnlySourcePreview name="notes.txt" text={text} wordWrap={false} />
130 </div>,
131 );
132 const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
133 const rows = () => root.querySelectorAll("[data-line]");
134 await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
135
136 const rowText = (index: number) => rows()[index]!.querySelector("span")!.firstChild!;
137 document.getSelection()!.setBaseAndExtent(rowText(4), 0, rowText(19), 4);
138 const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
139 scroller.scrollTop = scroller.scrollHeight;
140 await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"));
141 expect(copiedText(rows()[0]!)).toContain("line 5\n");
142
143 // The first mounted row is where the scrolled-out selection is parked, far above the viewport.
144 rows()[0]!.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, composed: true }));
145 document.getSelection()!.collapse(rowText(0), 0);
146 expect(copiedText(rows()[0]!)).toBeNull();
147 });
148
149 it("copies a drag that autoscrolls past the edge of the preview", async () => {
150 await getSyntaxHighlighterPromise("text");
151 await using screen = await render(
152 <div className="flex h-[400px] flex-col">
153 <ReadOnlySourcePreview name="notes.txt" text={text} wordWrap={false} />
154 </div>,
155 );
156 const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
157 const rows = () => root.querySelectorAll("[data-line]");
158 await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
159
160 const start = rows()[4]!.querySelector("span")!.getBoundingClientRect();
161 const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
162 const edge = scroller.getBoundingClientRect().bottom;
163 const frame = window.frameElement?.getBoundingClientRect();
164 const mouse = (type: "mousePressed" | "mouseMoved" | "mouseReleased", x: number, y: number) =>
165 cdp().send("Input.dispatchMouseEvent", {
166 type,
167 x: x + (frame?.left ?? 0),
168 y: y + (frame?.top ?? 0),
169 button: "left",
170 buttons: type === "mouseReleased" ? 0 : 1,
171 clickCount: 1,
172 });
173 await mouse("mousePressed", start.left + 1, start.top + 5);
174 await mouse("mouseMoved", start.left + 30, edge - 5);
175 // Held below the preview, the pointer is over no row while the browser scrolls the drag on.
176 await mouse("mouseMoved", start.left + 30, edge + 60);
177 await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"), { timeout: 10_000 });
178 await mouse("mouseReleased", start.left + 30, edge + 60);
179
180 const copied = copiedText(rows()[0]!)!;
181 const from = text.indexOf("line 5\n");
182 expect(copied).toBe(text.slice(from, from + copied.length));
183 // The drag ends in the rows on screen, short of the last mounted one.
184 const lastLine = 4 + copied.split("\n").length;
185 expect(lastLine).toBeGreaterThan(50);
186 expect(lastLine).toBeLessThan(Number(rows()[rows().length - 1]!.getAttribute("data-line")));
187 });
188
189 it("extends a selection with Shift+click after its anchor scrolls out of the mounted window", async () => {
190 await getSyntaxHighlighterPromise("text");
191 await using screen = await render(
192 <div className="flex h-[400px] flex-col">
193 <ReadOnlySourcePreview name="notes.txt" text={text} wordWrap={false} />
194 </div>,
195 );
196 const root = screen.container.querySelector("diffs-container")!.shadowRoot!;
197 const rows = () => root.querySelectorAll("[data-line]");
198 await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1"));
199
200 await userEvent.click(rows()[2]!.querySelector("span")!, { position: { x: 1, y: 5 } });
201 const scroller = screen.container.querySelector(".file-preview-virtualizer")!;
202 scroller.scrollTop = scroller.scrollHeight;
203 await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1"));
204 await userEvent.click(rows()[rows().length - 1]!.querySelector("span")!, {
205 position: { x: 1, y: 5 },
206 modifiers: ["Shift"],
207 });
208
209 const clicked = document.getSelection()!.getComposedRanges({ shadowRoots: [root] })[0]!;
210 const lastLine = clicked.endContainer.textContent!;
211 expect(Number(lastLine.replace("line ", ""))).toBeGreaterThan(250);
212 expect(copiedText(rows()[0]!)).toBe(
213 text.slice(text.indexOf("line 3\n"), text.indexOf(`${lastLine}\n`)),
214 );
215 });
216 });