Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2
3import { showContextMenuFallback } from "./contextMenuFallback";
4
5type FakeListener = (event: FakeDomEvent) => void;
6
7class FakeDomEvent {
8 defaultPrevented = false;
9
10 constructor(
11 readonly type: string,
12 init: Record<string, unknown> = {},
13 ) {
14 Object.assign(this, init);
15 }
16
17 preventDefault() {
18 this.defaultPrevented = true;
19 }
20}
21
22let activeElement: FakeElement | null = null;
23
24class FakeElement {
25 children: FakeElement[] = [];
26 parent: FakeElement | null = null;
27 style: Record<string, string> & { cssText?: string } = {};
28 dataset: Record<string, string> = {};
29 className = "";
30 disabled = false;
31 type = "";
32 tabIndex = 0;
33 private textValue = "";
34 private readonly attributes = new Map<string, string>();
35 private readonly listeners = new Map<string, FakeListener[]>();
36
37 constructor(readonly tagName: string) {}
38
39 appendChild(child: FakeElement) {
40 child.parent = this;
41 this.children.push(child);
42 return child;
43 }
44
45 remove() {
46 if (!this.parent) {
47 return;
48 }
49 const index = this.parent.children.indexOf(this);
50 if (index >= 0) {
51 this.parent.children.splice(index, 1);
52 }
53 this.parent = null;
54 if (activeElement === this) {
55 activeElement = null;
56 }
57 }
58
59 addEventListener(type: string, listener: FakeListener) {
60 const existing = this.listeners.get(type) ?? [];
61 existing.push(listener);
62 this.listeners.set(type, existing);
63 }
64
65 dispatchEvent(event: FakeDomEvent) {
66 if (!("target" in event)) {
67 Object.assign(event, { target: this });
68 }
69 for (const listener of this.listeners.get(event.type) ?? []) {
70 listener(event);
71 }
72 return true;
73 }
74
75 focus() {
76 activeElement = this;
77 }
78
79 scrollIntoView() {}
80
81 setAttribute(name: string, value: string) {
82 this.attributes.set(name, value);
83 }
84
85 getAttribute(name: string) {
86 return this.attributes.get(name) ?? null;
87 }
88
89 set textContent(value: string) {
90 this.textValue = value;
91 }
92
93 get textContent() {
94 return `${this.textValue}${this.children.map((child) => child.textContent).join("")}`;
95 }
96
97 querySelectorAll(tagName: string): FakeElement[] {
98 const matches: FakeElement[] = [];
99 if (this.tagName === tagName) {
100 matches.push(this);
101 }
102 for (const child of this.children) {
103 matches.push(...child.querySelectorAll(tagName));
104 }
105 return matches;
106 }
107
108 getBoundingClientRect() {
109 const left = Number.parseInt(this.style.left ?? "0", 10) || 0;
110 const top = Number.parseInt(this.style.top ?? "0", 10) || 0;
111 const width = this.tagName === "div" ? 180 : 140;
112 const height = this.tagName === "div" ? 120 : 28;
113 return {
114 left,
115 top,
116 width,
117 height,
118 right: left + width,
119 bottom: top + height,
120 };
121 }
122}
123
124class FakeBody extends FakeElement {
125 private html = "";
126
127 constructor() {
128 super("body");
129 }
130
131 set innerHTML(value: string) {
132 this.html = value;
133 this.children = [];
134 }
135
136 get innerHTML() {
137 return this.html;
138 }
139}
140
141class FakeDocument {
142 body = new FakeBody();
143 private readonly listeners = new Map<string, FakeListener[]>();
144
145 get activeElement() {
146 return activeElement;
147 }
148
149 createElement(tagName: string) {
150 return new FakeElement(tagName);
151 }
152
153 addEventListener(type: string, listener: FakeListener) {
154 const existing = this.listeners.get(type) ?? [];
155 existing.push(listener);
156 this.listeners.set(type, existing);
157 }
158
159 removeEventListener(type: string, listener: FakeListener) {
160 const existing = this.listeners.get(type);
161 if (!existing) {
162 return;
163 }
164 const index = existing.indexOf(listener);
165 if (index >= 0) {
166 existing.splice(index, 1);
167 }
168 }
169
170 dispatchEvent(event: FakeDomEvent) {
171 for (const listener of this.listeners.get(event.type) ?? []) {
172 listener(event);
173 }
174 return true;
175 }
176
177 querySelectorAll(tagName: string) {
178 return this.body.querySelectorAll(tagName);
179 }
180}
181
182function findButton(label: string): FakeElement | undefined {
183 return (document as unknown as FakeDocument)
184 .querySelectorAll("button")
185 .find((button) => button.textContent.includes(label));
186}
187
188function keyboardEvent(key: string, target: FakeElement | undefined) {
189 const event = new KeyboardEvent("keydown", { key });
190 Object.assign(event, { target });
191 return event;
192}
193
194beforeEach(() => {
195 activeElement = null;
196 vi.stubGlobal("document", new FakeDocument());
197 vi.stubGlobal("window", {
198 innerWidth: 1280,
199 innerHeight: 800,
200 });
201 vi.stubGlobal("requestAnimationFrame", (callback: (time: number) => void) => {
202 callback(0);
203 return 0;
204 });
205 vi.stubGlobal(
206 "MouseEvent",
207 class extends FakeDomEvent {
208 constructor(type: string, init: Record<string, unknown> = {}) {
209 super(type, init);
210 }
211 },
212 );
213 vi.stubGlobal(
214 "KeyboardEvent",
215 class extends FakeDomEvent {
216 constructor(type: string, init: Record<string, unknown> = {}) {
217 super(type, init);
218 }
219 },
220 );
221});
222
223afterEach(() => {
224 vi.unstubAllGlobals();
225});
226
227describe("showContextMenuFallback", () => {
228 it("uses themed surface and action tokens for app menus", async () => {
229 const selectionPromise = showContextMenuFallback([
230 { id: "rename", label: "Rename" },
231 { id: "delete", label: "Delete", destructive: true },
232 ]);
233
234 const menu = (document as unknown as FakeDocument).body.children[0];
235 expect(menu?.className).toContain("dropdown-glass");
236 expect(menu?.style.cssText).toContain("var(--popover-foreground)");
237
238 const renameButton = findButton("Rename");
239 const deleteButton = findButton("Delete");
240 expect(renameButton?.className).toContain("text-foreground");
241 expect(deleteButton?.className).toContain("text-destructive-foreground");
242 expect(menu?.getAttribute("data-slot")).toBe("menu-popup");
243
244 renameButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
245 await expect(selectionPromise).resolves.toBe("rename");
246 });
247
248 it("resolves a clicked flat menu item", async () => {
249 const selectionPromise = showContextMenuFallback([
250 { id: "rename", label: "Rename" },
251 { id: "delete", label: "Delete", destructive: true },
252 ]);
253
254 const renameButton = findButton("Rename");
255 expect(renameButton).toBeTruthy();
256 renameButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
257
258 await expect(selectionPromise).resolves.toBe("rename");
259 });
260
261 it("supports keyboard navigation and activation", async () => {
262 const selectionPromise = showContextMenuFallback([
263 { id: "rename", label: "Rename" },
264 { id: "delete", label: "Delete", destructive: true },
265 ]);
266 const document = globalThis.document as unknown as FakeDocument;
267 const renameButton = findButton("Rename");
268 const deleteButton = findButton("Delete");
269
270 expect(document.activeElement).toBe(renameButton);
271 const moveDown = keyboardEvent("ArrowDown", renameButton);
272 document.dispatchEvent(moveDown);
273 expect(moveDown.defaultPrevented).toBe(true);
274 expect(document.activeElement).toBe(deleteButton);
275
276 const activate = keyboardEvent("Enter", deleteButton);
277 document.dispatchEvent(activate);
278 await expect(selectionPromise).resolves.toBe("delete");
279 });
280
281 it("opens and closes nested menus with the keyboard", async () => {
282 const selectionPromise = showContextMenuFallback([
283 {
284 id: "rename:submenu",
285 label: "Rename project",
286 children: [
287 { id: "rename:project-a", label: "/tmp/project-a" },
288 { id: "rename:project-b", label: "/tmp/project-b" },
289 ],
290 },
291 ]);
292 const document = globalThis.document as unknown as FakeDocument;
293 const parentButton = findButton("Rename project");
294
295 document.dispatchEvent(keyboardEvent("ArrowRight", parentButton));
296 const childButton = findButton("/tmp/project-a");
297 expect(document.activeElement).toBe(childButton);
298 expect(parentButton?.getAttribute("aria-expanded")).toBe("true");
299
300 document.dispatchEvent(keyboardEvent("ArrowLeft", childButton));
301 expect(document.activeElement).toBe(parentButton);
302 expect(parentButton?.getAttribute("aria-expanded")).toBe("false");
303
304 document.dispatchEvent(keyboardEvent("ArrowRight", parentButton));
305 const secondChildButton = findButton("/tmp/project-b");
306 expect(parentButton?.getAttribute("aria-expanded")).toBe("true");
307 document.dispatchEvent(keyboardEvent("ArrowDown", findButton("/tmp/project-a")));
308 document.dispatchEvent(keyboardEvent("Enter", secondChildButton));
309
310 await expect(selectionPromise).resolves.toBe("rename:project-b");
311 });
312
313 it("restores focus when pointer navigation closes a submenu", () => {
314 showContextMenuFallback([
315 {
316 id: "rename:submenu",
317 label: "Rename project",
318 children: [{ id: "rename:project-a", label: "/tmp/project-a" }],
319 },
320 { id: "mark-unread", label: "Mark unread" },
321 ]);
322
323 const parentButton = findButton("Rename project");
324 parentButton?.dispatchEvent(new MouseEvent("mouseenter", { bubbles: true }));
325 const childButton = findButton("/tmp/project-a");
326 childButton?.focus();
327 const rootMenu = (document as unknown as FakeDocument).body.children[0];
328 rootMenu?.dispatchEvent(new MouseEvent("mouseenter", { bubbles: true }));
329
330 expect(document.activeElement).toBe(parentButton);
331 });
332
333 it("restores focus to the opener after cleanup", async () => {
334 const opener = document.createElement("button");
335 document.body.appendChild(opener);
336 opener.focus();
337
338 const selectionPromise = showContextMenuFallback([{ id: "rename", label: "Rename" }]);
339 const renameButton = findButton("Rename");
340 renameButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
341
342 await expect(selectionPromise).resolves.toBe("rename");
343 expect(document.activeElement).toBe(opener);
344 });
345
346 it("keeps keyboard focus aligned with hovered menu items", () => {
347 showContextMenuFallback([
348 {
349 id: "project-a",
350 label: "Project A",
351 children: [{ id: "project-a:branch", label: "Project A branch" }],
352 },
353 {
354 id: "project-b",
355 label: "Project B",
356 children: [{ id: "project-b:branch", label: "Project B branch" }],
357 },
358 { id: "mark-unread", label: "Mark unread" },
359 ]);
360
361 const projectA = findButton("Project A");
362 const projectB = findButton("Project B");
363 const markUnread = findButton("Mark unread");
364 projectA?.dispatchEvent(new MouseEvent("mouseenter", { bubbles: true }));
365 projectB?.dispatchEvent(new MouseEvent("mouseenter", { bubbles: true }));
366
367 expect(document.activeElement).toBe(projectB);
368 document.dispatchEvent(keyboardEvent("ArrowDown", projectB));
369 expect(document.activeElement).toBe(markUnread);
370 });
371
372 it("ignores a click from the gesture that opened the menu", async () => {
373 let enablePointerSelection: ((time: number) => void) | undefined;
374 vi.stubGlobal("requestAnimationFrame", (callback: (time: number) => void) => {
375 enablePointerSelection = callback;
376 return 0;
377 });
378
379 const selectionPromise = showContextMenuFallback([{ id: "rename", label: "Rename" }]);
380 const renameButton = findButton("Rename");
381
382 renameButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
383 enablePointerSelection?.(0);
384 renameButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
385
386 await expect(selectionPromise).resolves.toBe("rename");
387 });
388
389 it("opens nested submenus and resolves the clicked leaf id", async () => {
390 const selectionPromise = showContextMenuFallback([
391 {
392 id: "rename:submenu",
393 label: "Rename project",
394 children: [
395 { id: "rename:project-a", label: "/tmp/project-a" },
396 { id: "rename:project-b", label: "/tmp/project-b" },
397 ],
398 },
399 ]);
400
401 const parentButton = findButton("Rename project");
402 expect(parentButton).toBeTruthy();
403 parentButton?.dispatchEvent(new MouseEvent("mouseenter", { bubbles: true }));
404
405 const childButton = findButton("/tmp/project-b");
406 expect(childButton).toBeTruthy();
407 childButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
408
409 await expect(selectionPromise).resolves.toBe("rename:project-b");
410 });
411});