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

PickPreload.test.ts

225 lines9.0 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("keeps the tool while typing a tool key in the comment", () => {
97 const shadowRoot = startAnnotation();
98 const comment = shadowRoot.querySelector("textarea");
99 if (!comment) throw new Error("comment textarea not found");
100​
101 comment.focus();
102 comment.dispatchEvent(new KeyboardEvent("keydown", { key: "r", bubbles: true, composed: true }));
103​
104 expect(document.documentElement.getAttribute("data-t3code-annotation-tool")).toBe("select");
105});
106​
107it("keeps comment keystrokes away from the page's capture-phase shortcuts", () => {
108 const pageShortcut = vi.fn((event: KeyboardEvent) => event.preventDefault());
109 window.addEventListener("keydown", pageShortcut, { capture: true });
110 const shadowRoot = startAnnotation();
111 const comment = shadowRoot.querySelector("textarea");
112 if (!comment) throw new Error("comment textarea not found");
113​
114 comment.focus();
115 const space = new KeyboardEvent("keydown", {
116 key: " ",
117 code: "Space",
118 bubbles: true,
119 cancelable: true,
120 composed: true,
121 });
122 comment.dispatchEvent(space);
123 window.removeEventListener("keydown", pageShortcut, { capture: true });
124​
125 expect(pageShortcut).not.toHaveBeenCalled();
126 expect(space.defaultPrevented).toBe(false);
127});
128​
129it("keeps the annotation when Escape dismisses an IME candidate in the comment", () => {
130 const shadowRoot = startAnnotation();
131 const comment = shadowRoot.querySelector("textarea");
132 if (!comment) throw new Error("comment textarea not found");
133​
134 comment.value = "draft";
135 comment.focus();
136 comment.dispatchEvent(
137 new KeyboardEvent("keydown", {
138 key: "Escape",
139 isComposing: true,
140 bubbles: true,
141 cancelable: true,
142 composed: true,
143 }),
144 );
145​
146 expect(shadowRoot.host.isConnected).toBe(true);
147 expect(comment.value).toBe("draft");
148});
149​
150it.each([
151 { scrolled: false, rect: { x: 40, y: 60, width: 200, height: 120 } },
152 // The last rect would point at whatever now sits there, so no crop beats a wrong one.
153 { scrolled: true, rect: { x: 0, y: 0, width: 0, height: 0 } },
154])(
155 "submits a replaced element's last rect unless the page scrolled ($scrolled)",
156 async ({ scrolled, rect }) => {
157 ipcSend.calls.length = 0;
158 const card = document.body.appendChild(document.createElement("div"));
159 const pickedRect = new DOMRect(40, 60, 200, 120);
160 // Browsers report a detached element at 0x0 in the corner.
161 using _rect = vi
162 .spyOn(card, "getBoundingClientRect")
163 .mockImplementation(() => (card.isConnected ? pickedRect : new DOMRect()));
164 document.elementsFromPoint = () => [card];
165 using listeners = vi.spyOn(HTMLButtonElement.prototype, "addEventListener");
166 const shadowRoot = startAnnotation();
167​
168 card.dispatchEvent(
169 new PointerEvent("pointerdown", { button: 0, clientX: 100, clientY: 100, bubbles: true }),
170 );
171 // A polling page re-renders while the comment is written and replaces the picked node.
172 card.replaceWith(document.createElement("div"));
173 if (scrolled) window.dispatchEvent(new Event("scroll"));
174 const attach = Array.from(shadowRoot.querySelectorAll("button")).find(
175 (button) => button.textContent === "Attach",
176 );
177 if (!attach) throw new Error("Attach button not found");
178 attach.click();
179 expect(attach.disabled).toBe(false);
180 expect(ipcSend.calls.some(([channel]) => channel === ELEMENT_PICKED_CHANNEL)).toBe(false);
181 const listenerIndex = listeners.mock.contexts.findIndex(
182 (target, index) => target === attach && listeners.mock.calls[index]?.[0] === "click",
183 );
184 const listener = listeners.mock.calls[listenerIndex]?.[1];
185 if (typeof listener !== "function") throw new Error("Attach click listener not found");
186 // The DOM test environment has no native input source.
187 listener.call(attach, { isTrusted: true } as MouseEvent);
188​
189 await vi.waitFor(() =>
190 expect(ipcSend.calls.some(([channel]) => channel === ELEMENT_PICKED_CHANNEL)).toBe(true),
191 );
192 const [, annotation] =
193 ipcSend.calls.find(([channel]) => channel === ELEMENT_PICKED_CHANNEL) ?? [];
194 expect((annotation as { elements: Array<{ rect: unknown }> }).elements[0]?.rect).toEqual(rect);
195 },
196);
197​
198it("keeps only the well-typed fields of what the page reports about an element", async () => {
199 pageElementContext.mockResolvedValueOnce({
200 selector: { toString: () => "#object" },
201 htmlPreview: "<button>Pay</button>",
202 componentName: 7,
203 styles: null,
204 stack: [{ functionName: "Checkout", fileName: ["x"], lineNumber: "12", columnNumber: 4 }, 3],
205 });
206 const card = document.body.appendChild(document.createElement("div"));
207 const element = await pickAndAttach(card);
208 const frame = { functionName: "Checkout", fileName: null, lineNumber: null, columnNumber: 4 };
209 expect(element).toMatchObject({
210 selector: null,
211 htmlPreview: "<button>Pay</button>",
212 componentName: null,
213 styles: "",
214 source: frame,
215 stack: [frame, { functionName: null, fileName: null, lineNumber: null, columnNumber: null }],
216 });
217});
218​
219it("drops a straddling surrogate pair when falling back to outerHTML preview", async () => {
220 pageElementContext.mockRejectedValueOnce(new Error("page lookup failed"));
221 const card = document.body.appendChild(document.createElement("div"));
222 card.textContent = `${"a".repeat(494)}🚀tail`;
223 expect(card.outerHTML.charCodeAt(499)).toBe(0xd83d);
224 expect((await pickAndAttach(card))?.htmlPreview).toBe(card.outerHTML.slice(0, 499));
225});