Open History to see the last commit
1import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";
2import { createElement } from "react";
3import { expect, it } from "vite-plus/test";
4import { page, userEvent } from "vite-plus/test/browser";
5import { render } from "../test/render";
6import {
7 dismissContextMenu,
8 isContextMenuOpen,
9 showContextMenuFallback,
10} from "./contextMenuFallback";
11import { createLocalApi } from "./localApi";
12
13const items = [
14 { id: "heading", label: "Thread actions", header: true },
15 { id: "disabled", label: "Unavailable", disabled: true },
16 { id: "rename", label: "Rename" },
17 { id: "pin", label: "Pinned", checked: true, separatorBefore: true },
18 {
19 id: "copy",
20 label: "Copy",
21 children: [
22 { id: "copy-unavailable", label: "Unavailable copy", disabled: true },
23 { id: "path", label: "Path" },
24 { id: "branch", label: "Branch" },
25 ],
26 },
27];
28
29function setup() {
30 const origin = document.createElement("button");
31 origin.textContent = "Selected thread";
32 document.body.append(origin);
33 origin.focus();
34 return {
35 origin,
36 [Symbol.dispose]() {
37 dismissContextMenu();
38 origin.remove();
39 },
40 };
41}
42
43function press(key: string, shiftKey = false) {
44 const event = new KeyboardEvent("keydown", { key, shiftKey, bubbles: true, cancelable: true });
45 document.activeElement!.dispatchEvent(event);
46 return event;
47}
48
49const label = () => document.activeElement?.textContent;
50
51it("starts a keyboard-opened menu on its first action and wraps through enabled actions", () => {
52 using _fixture = setup();
53 void showContextMenuFallback(items);
54 expect(label()).toBe("Rename");
55 press("ArrowUp");
56 expect(label()).toBe("Copy");
57 press("ArrowDown");
58 expect(label()).toBe("Rename");
59 press("End");
60 expect(label()).toBe("Copy");
61 press("Home");
62 expect(label()).toBe("Rename");
63});
64
65it("opens and cancels one submenu level at a time, then returns to the thread", async () => {
66 using fixture = setup();
67 const result = showContextMenuFallback(items);
68 press("End");
69 const parent = document.activeElement;
70 press("ArrowRight");
71 expect(label()).toBe("Path");
72 press("ArrowLeft");
73 expect(document.activeElement).toBe(parent);
74 press("Enter");
75 expect(label()).toBe("Path");
76 press("Escape");
77 expect(document.activeElement).toBe(parent);
78 expect(isContextMenuOpen()).toBe(true);
79 press("Escape");
80 expect(document.activeElement).toBe(fixture.origin);
81 await expect(result).resolves.toBeNull();
82});
83
84it("activates the focused action with Space or Enter", async () => {
85 using _fixture = setup();
86 const first = showContextMenuFallback(items);
87 press(" ");
88 await expect(first).resolves.toBe("rename");
89 const second = showContextMenuFallback(items);
90 press("Enter");
91 await expect(second).resolves.toBe("rename");
92});
93
94it("closes on Tab and returns focus to the opener so Tab continues from there", async () => {
95 using fixture = setup();
96 const result = showContextMenuFallback(items);
97 expect(press("Tab").defaultPrevented).toBe(false);
98 await expect(result).resolves.toBeNull();
99 expect(document.activeElement).toBe(fixture.origin);
100});
101
102it("closes without taking focus back when focus moves elsewhere", async () => {
103 using _fixture = setup();
104 const result = showContextMenuFallback(items);
105 const destination = document.createElement("button");
106 document.body.append(destination);
107 using _destination = { [Symbol.dispose]: () => destination.remove() };
108 destination.focus();
109 await expect(result).resolves.toBeNull();
110 expect(document.activeElement).toBe(destination);
111});
112
113it("takes thumb Back and Forward presses so the app router stays put", () => {
114 using _fixture = setup();
115 void showContextMenuFallback(items);
116 for (const button of [3, 4]) {
117 const event = new MouseEvent("mouseup", { button, bubbles: true, cancelable: true });
118 document.activeElement!.dispatchEvent(event);
119 // Chromium runs history back/forward on a thumb-button mouseup nobody cancelled.
120 expect(event.defaultPrevented).toBe(true);
121 }
122 expect(isContextMenuOpen()).toBe(true);
123});
124
125// NVDA browse mode sends Shift+F10 without keyboard focus on the opener, so the opener does
126// not match :focus-visible; the caller's keyboard source must still start on the first action.
127it("starts a keyboard-sourced menu on its first action when the opener was focused by pointer", async () => {
128 using fixture = setup();
129 fixture.origin.blur();
130 await userEvent.click(fixture.origin);
131 expect(fixture.origin.matches(":focus-visible")).toBe(false);
132 void createLocalApi().contextMenu.show(items, { x: 0, y: 0 }, "keyboard");
133 expect(label()).toBe("Rename");
134});
135
136it("keeps focus on the parent menu when leaving a submenu onto a non-action area", async () => {
137 using fixture = setup();
138 const result = showContextMenuFallback(items);
139 const parentMenu = document.querySelector<HTMLElement>(
140 '[data-context-menu="true"][data-level="0"]',
141 )!;
142 const copyTrigger = [...parentMenu.querySelectorAll("button")].find(
143 (button) => button.textContent === "Copy",
144 )!;
145 await userEvent.hover(copyTrigger);
146
147 const submenu = document.querySelector<HTMLElement>(
148 '[data-context-menu="true"][data-level="1"]',
149 )!;
150 const pathButton = [...submenu.querySelectorAll("button")].find(
151 (button) => button.textContent === "Path",
152 )!;
153 await userEvent.hover(pathButton);
154 expect(label()).toBe("Path");
155
156 const separator = parentMenu.querySelector<HTMLElement>('[data-context-menu-separator="true"]')!;
157 await userEvent.hover(separator);
158
159 expect(document.querySelector('[data-context-menu="true"][data-level="1"]')).toBeNull();
160 expect(isContextMenuOpen()).toBe(true);
161 expect(document.activeElement).toBe(parentMenu);
162
163 press("ArrowDown");
164 expect(label()).toBe("Rename");
165 press("Escape");
166 expect(document.activeElement).toBe(fixture.origin);
167 await expect(result).resolves.toBeNull();
168});
169
170it("closes an open menu and submenu on Escape before a Base UI dialog beneath it", async () => {
171 await using _screen = await render(
172 createElement(
173 DialogPrimitive.Root,
174 { defaultOpen: true },
175 createElement(
176 DialogPrimitive.Portal,
177 null,
178 createElement(
179 DialogPrimitive.Popup,
180 null,
181 createElement("button", { type: "button" }, "Dialog action"),
182 ),
183 ),
184 ),
185 );
186 using _menuCleanup = { [Symbol.dispose]: () => dismissContextMenu() };
187
188 const dialog = page.getByRole("dialog");
189 await expect.element(dialog).toBeVisible();
190 // The dialog moves focus to its first action a frame after it opens. Opening the menu
191 // before that frame lets that late focus close the menu.
192 const openerLocator = page.getByRole("button", { name: "Dialog action" });
193 await expect.element(openerLocator).toHaveFocus();
194 const opener = openerLocator.element() as HTMLButtonElement;
195
196 const result = showContextMenuFallback(items, undefined, "keyboard");
197 press("End");
198 const parent = document.activeElement;
199 press("ArrowRight");
200 expect(label()).toBe("Path");
201
202 await userEvent.keyboard("{Escape}");
203 expect(document.activeElement).toBe(parent);
204 expect(isContextMenuOpen()).toBe(true);
205 await expect.element(dialog).toBeVisible();
206
207 await userEvent.keyboard("{Escape}");
208 await expect(result).resolves.toBeNull();
209 expect(isContextMenuOpen()).toBe(false);
210 expect(document.activeElement).toBe(opener);
211 await expect.element(dialog).toBeVisible();
212
213 await userEvent.keyboard("{Escape}");
214 await expect.element(dialog).not.toBeInTheDocument();
215});