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

PickPreload.test.ts

236 lines9.4 KB

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