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

PickPreload.test.ts

213 lines8.4 KB

1import { expect, it, vi } from "vite-plus/test";
2​
3import { ELEMENT_PICKED_CHANNEL, START_PICK_CHANNEL } from "./GuestProtocol.ts";
4import "./PickPreload.ts";
5​
6const ipcListeners = vi.hoisted(() => new Map<string, Array<(...args: unknown[]) => void>>());
7const ipcSend = vi.hoisted(() => ({ calls: [] as unknown[][] }));
8const pageElementContext = vi.hoisted(() => vi.fn(async (): Promise<unknown> => null));
9​
10vi.mock("electron", () => ({
11 ipcRenderer: {
12 on: (channel: string, listener: (...args: unknown[]) => void) => {
13 ipcListeners.set(channel, [...(ipcListeners.get(channel) ?? []), listener]);
14 },
15 off: () => {},
16 send: (...args: unknown[]) => {
17 ipcSend.calls.push(args);
18 },
19 invoke: async () => undefined,
20 },
21}));
22​
23vi.mock("./PageWorldBridge.ts", () => ({ pageWorld: { elementContext: pageElementContext } }));
24​
25const startAnnotation = (): ShadowRoot => {
26 vi.stubGlobal(
27 "ResizeObserver",
28 class {
29 observe() {}
30 disconnect() {}
31 },
32 );
33 // jsdom has no popover API.
34 HTMLElement.prototype.showPopover ??= () => {};
35 HTMLElement.prototype.hidePopover ??= () => {};
36 // jsdom has no adoptedStyleSheets.
37 for (const target of [Document.prototype, ShadowRoot.prototype]) {
38 if (!("adoptedStyleSheets" in target)) {
39 Object.defineProperty(target, "adoptedStyleSheets", { value: [], writable: true });
40 }
41 }
42 using attachShadow = vi.spyOn(Element.prototype, "attachShadow");
43 for (const listener of ipcListeners.get(START_PICK_CHANNEL) ?? []) listener({}, undefined, false);
44 const shadowRoot = attachShadow.mock.results[0]?.value;
45 if (!(shadowRoot instanceof ShadowRoot)) throw new Error("annotation overlay did not start");
46 return shadowRoot;
47};
48​
49it("switches tools from the keyboard after a toolbar button is clicked", () => {
50 const shadowRoot = startAnnotation();
51 const region = Array.from(shadowRoot.querySelectorAll("button")).find(
52 (button) => button.textContent === "Region",
53 );
54 if (!region) throw new Error("Region toolbar button not found");
55​
56 region.focus();
57 region.click();
58 expect(document.documentElement.getAttribute("data-t3code-annotation-tool")).toBe("marquee");
59​
60 region.dispatchEvent(new KeyboardEvent("keydown", { key: "v", bubbles: true, composed: true }));
61​
62 expect(
63 document.documentElement.getAttribute("data-t3code-annotation-tool"),
64 "V should switch to Select while focus is on a toolbar button",
65 ).toBe("select");
66});
67​
68it("keeps the tool while typing a tool key in the comment", () => {
69 const shadowRoot = startAnnotation();
70 const comment = shadowRoot.querySelector("textarea");
71 if (!comment) throw new Error("comment textarea not found");
72​
73 comment.focus();
74 comment.dispatchEvent(new KeyboardEvent("keydown", { key: "r", bubbles: true, composed: true }));
75​
76 expect(document.documentElement.getAttribute("data-t3code-annotation-tool")).toBe("select");
77});
78​
79it("keeps comment keystrokes away from the page's capture-phase shortcuts", () => {
80 const pageShortcut = vi.fn((event: KeyboardEvent) => event.preventDefault());
81 window.addEventListener("keydown", pageShortcut, { capture: true });
82 const shadowRoot = startAnnotation();
83 const comment = shadowRoot.querySelector("textarea");
84 if (!comment) throw new Error("comment textarea not found");
85​
86 comment.focus();
87 const space = new KeyboardEvent("keydown", {
88 key: " ",
89 code: "Space",
90 bubbles: true,
91 cancelable: true,
92 composed: true,
93 });
94 comment.dispatchEvent(space);
95 window.removeEventListener("keydown", pageShortcut, { capture: true });
96​
97 expect(pageShortcut).not.toHaveBeenCalled();
98 expect(space.defaultPrevented).toBe(false);
99});
100​
101it("keeps the annotation when Escape dismisses an IME candidate in the comment", () => {
102 const shadowRoot = startAnnotation();
103 const comment = shadowRoot.querySelector("textarea");
104 if (!comment) throw new Error("comment textarea not found");
105​
106 comment.value = "draft";
107 comment.focus();
108 comment.dispatchEvent(
109 new KeyboardEvent("keydown", {
110 key: "Escape",
111 isComposing: true,
112 bubbles: true,
113 cancelable: true,
114 composed: true,
115 }),
116 );
117​
118 expect(shadowRoot.host.isConnected).toBe(true);
119 expect(comment.value).toBe("draft");
120});
121​
122it.each([
123 { scrolled: false, rect: { x: 40, y: 60, width: 200, height: 120 } },
124 // The last rect would point at whatever now sits there, so no crop beats a wrong one.
125 { scrolled: true, rect: { x: 0, y: 0, width: 0, height: 0 } },
126])(
127 "submits a replaced element's last rect unless the page scrolled ($scrolled)",
128 async ({ scrolled, rect }) => {
129 ipcSend.calls.length = 0;
130 const card = document.body.appendChild(document.createElement("div"));
131 const pickedRect = new DOMRect(40, 60, 200, 120);
132 // Browsers report a detached element at 0x0 in the corner.
133 using _rect = vi
134 .spyOn(card, "getBoundingClientRect")
135 .mockImplementation(() => (card.isConnected ? pickedRect : new DOMRect()));
136 document.elementsFromPoint = () => [card];
137 using listeners = vi.spyOn(HTMLButtonElement.prototype, "addEventListener");
138 const shadowRoot = startAnnotation();
139​
140 card.dispatchEvent(
141 new PointerEvent("pointerdown", { button: 0, clientX: 100, clientY: 100, bubbles: true }),
142 );
143 // A polling page re-renders while the comment is written and replaces the picked node.
144 card.replaceWith(document.createElement("div"));
145 if (scrolled) window.dispatchEvent(new Event("scroll"));
146 const attach = Array.from(shadowRoot.querySelectorAll("button")).find(
147 (button) => button.textContent === "Attach",
148 );
149 if (!attach) throw new Error("Attach button not found");
150 attach.click();
151 expect(attach.disabled).toBe(false);
152 expect(ipcSend.calls.some(([channel]) => channel === ELEMENT_PICKED_CHANNEL)).toBe(false);
153 const listenerIndex = listeners.mock.contexts.findIndex(
154 (target, index) => target === attach && listeners.mock.calls[index]?.[0] === "click",
155 );
156 const listener = listeners.mock.calls[listenerIndex]?.[1];
157 if (typeof listener !== "function") throw new Error("Attach click listener not found");
158 // The DOM test environment has no native input source.
159 listener.call(attach, { isTrusted: true } as MouseEvent);
160​
161 await vi.waitFor(() =>
162 expect(ipcSend.calls.some(([channel]) => channel === ELEMENT_PICKED_CHANNEL)).toBe(true),
163 );
164 const [, annotation] =
165 ipcSend.calls.find(([channel]) => channel === ELEMENT_PICKED_CHANNEL) ?? [];
166 expect((annotation as { elements: Array<{ rect: unknown }> }).elements[0]?.rect).toEqual(rect);
167 },
168);
169​
170it("keeps only the well-typed fields of what the page reports about an element", async () => {
171 ipcSend.calls.length = 0;
172 pageElementContext.mockResolvedValueOnce({
173 selector: { toString: () => "#object" },
174 htmlPreview: "<button>Pay</button>",
175 componentName: 7,
176 styles: null,
177 stack: [{ functionName: "Checkout", fileName: ["x"], lineNumber: "12", columnNumber: 4 }, 3],
178 });
179 const card = document.body.appendChild(document.createElement("div"));
180 document.elementsFromPoint = () => [card];
181 using listeners = vi.spyOn(HTMLButtonElement.prototype, "addEventListener");
182 const shadowRoot = startAnnotation();
183 card.dispatchEvent(
184 new PointerEvent("pointerdown", { button: 0, clientX: 100, clientY: 100, bubbles: true }),
185 );
186 const attach = Array.from(shadowRoot.querySelectorAll("button")).find(
187 (button) => button.textContent === "Attach",
188 );
189 const listenerIndex = listeners.mock.contexts.findIndex(
190 (target, index) => target === attach && listeners.mock.calls[index]?.[0] === "click",
191 );
192 const listener = listeners.mock.calls[listenerIndex]?.[1];
193 if (!attach || typeof listener !== "function") throw new Error("Attach listener not found");
194 // The DOM test environment has no native input source.
195 listener.call(attach, { isTrusted: true } as MouseEvent);
196​
197 await vi.waitFor(() =>
198 expect(ipcSend.calls.some(([channel]) => channel === ELEMENT_PICKED_CHANNEL)).toBe(true),
199 );
200 const [, annotation] =
201 ipcSend.calls.find(([channel]) => channel === ELEMENT_PICKED_CHANNEL) ?? [];
202 const frame = { functionName: "Checkout", fileName: null, lineNumber: null, columnNumber: 4 };
203 expect(
204 (annotation as { elements: Array<{ element: unknown }> }).elements[0]?.element,
205 ).toMatchObject({
206 selector: null,
207 htmlPreview: "<button>Pay</button>",
208 componentName: null,
209 styles: "",
210 source: frame,
211 stack: [frame, { functionName: null, fileName: null, lineNumber: null, columnNumber: null }],
212 });
213});