Open History to see the last commit
1import type { ContextMenuItem } from "@t3tools/contracts";
2
3const SVG_NS = "http://www.w3.org/2000/svg";
4
5const ICON_PATHS: Record<string, ReadonlyArray<{ tag: string; attrs: Record<string, string> }>> = {
6 archive: [
7 { tag: "rect", attrs: { width: "20", height: "5", x: "2", y: "3", rx: "1" } },
8 { tag: "path", attrs: { d: "M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8" } },
9 { tag: "path", attrs: { d: "M10 12h4" } },
10 ],
11 check: [{ tag: "path", attrs: { d: "M20 6 9 17l-5-5" } }],
12 timer: [
13 { tag: "line", attrs: { x1: "10", x2: "14", y1: "2", y2: "2" } },
14 { tag: "line", attrs: { x1: "12", x2: "15", y1: "14", y2: "11" } },
15 { tag: "circle", attrs: { cx: "12", cy: "14", r: "8" } },
16 ],
17 "chevron-right": [{ tag: "path", attrs: { d: "m9 19 7-7-7-7" } }],
18 "circle-check": [
19 { tag: "circle", attrs: { cx: "12", cy: "12", r: "10" } },
20 { tag: "path", attrs: { d: "m9 12 2 2 4-4" } },
21 ],
22 clock: [
23 { tag: "path", attrs: { d: "M12 6v6l4 2" } },
24 { tag: "circle", attrs: { cx: "12", cy: "12", r: "10" } },
25 ],
26 pencil: [
27 {
28 tag: "path",
29 attrs: {
30 d: "M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",
31 },
32 },
33 { tag: "path", attrs: { d: "m15 5 4 4" } },
34 ],
35 copy: [
36 { tag: "rect", attrs: { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2" } },
37 { tag: "path", attrs: { d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" } },
38 ],
39 folder: [
40 {
41 tag: "path",
42 attrs: {
43 d: "M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",
44 },
45 },
46 ],
47 "git-branch": [
48 { tag: "line", attrs: { x1: "6", x2: "6", y1: "3", y2: "15" } },
49 { tag: "circle", attrs: { cx: "18", cy: "6", r: "3" } },
50 { tag: "circle", attrs: { cx: "6", cy: "18", r: "3" } },
51 { tag: "path", attrs: { d: "M18 9a9 9 0 0 1-9 9" } },
52 ],
53 hash: [
54 { tag: "line", attrs: { x1: "4", x2: "20", y1: "9", y2: "9" } },
55 { tag: "line", attrs: { x1: "4", x2: "20", y1: "15", y2: "15" } },
56 { tag: "line", attrs: { x1: "10", x2: "8", y1: "3", y2: "21" } },
57 { tag: "line", attrs: { x1: "16", x2: "14", y1: "3", y2: "21" } },
58 ],
59 "mail-open": [
60 {
61 tag: "path",
62 attrs: {
63 d: "M21.2 8.4c.5.38.8.97.8 1.6v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V10a2 2 0 0 1 .8-1.6l8-6a2 2 0 0 1 2.4 0l8 6Z",
64 },
65 },
66 { tag: "path", attrs: { d: "m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10" } },
67 ],
68 "message-square": [
69 {
70 tag: "path",
71 attrs: {
72 d: "M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",
73 },
74 },
75 ],
76 "message-square-plus": [
77 {
78 tag: "path",
79 attrs: {
80 d: "M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",
81 },
82 },
83 { tag: "path", attrs: { d: "M12 8v6" } },
84 { tag: "path", attrs: { d: "M9 11h6" } },
85 ],
86 pin: [
87 { tag: "path", attrs: { d: "M12 17v5" } },
88 {
89 tag: "path",
90 attrs: {
91 d: "M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",
92 },
93 },
94 ],
95 "pin-off": [
96 { tag: "path", attrs: { d: "M12 17v5" } },
97 { tag: "path", attrs: { d: "M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89" } },
98 { tag: "path", attrs: { d: "m2 2 20 20" } },
99 {
100 tag: "path",
101 attrs: {
102 d: "M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",
103 },
104 },
105 ],
106 "refresh-cw": [
107 { tag: "path", attrs: { d: "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" } },
108 { tag: "path", attrs: { d: "M21 3v5h-5" } },
109 { tag: "path", attrs: { d: "M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" } },
110 { tag: "path", attrs: { d: "M8 16H3v5" } },
111 ],
112 settings: [
113 {
114 tag: "path",
115 attrs: {
116 d: "M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.38a2 2 0 0 0-.73-2.73l-.15-.09a2 2 0 0 1-1-1.74v-.51a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",
117 },
118 },
119 { tag: "circle", attrs: { cx: "12", cy: "12", r: "3" } },
120 ],
121 "user-plus": [
122 { tag: "path", attrs: { d: "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" } },
123 { tag: "circle", attrs: { cx: "9", cy: "7", r: "4" } },
124 { tag: "line", attrs: { x1: "19", x2: "19", y1: "8", y2: "14" } },
125 { tag: "line", attrs: { x1: "22", x2: "16", y1: "11", y2: "11" } },
126 ],
127 "folder-tree": [
128 {
129 tag: "path",
130 attrs: {
131 d: "M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",
132 },
133 },
134 {
135 tag: "path",
136 attrs: {
137 d: "M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",
138 },
139 },
140 { tag: "path", attrs: { d: "M3 5a2 2 0 0 0 2 2h3" } },
141 { tag: "path", attrs: { d: "M3 3v13a2 2 0 0 0 2 2h3" } },
142 ],
143 trash: [
144 { tag: "path", attrs: { d: "M3 6h18" } },
145 { tag: "path", attrs: { d: "M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" } },
146 { tag: "path", attrs: { d: "M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" } },
147 { tag: "line", attrs: { x1: "10", x2: "10", y1: "11", y2: "17" } },
148 { tag: "line", attrs: { x1: "14", x2: "14", y1: "11", y2: "17" } },
149 ],
150};
151
152function createIconElement(name: string, tone: "neutral" | "destructive"): SVGSVGElement | null {
153 const paths = ICON_PATHS[name];
154 if (!paths || typeof document.createElementNS !== "function") {
155 return null;
156 }
157 const svg = document.createElementNS(SVG_NS, "svg");
158 svg.setAttribute("aria-hidden", "true");
159 svg.setAttribute("xmlns", SVG_NS);
160 svg.setAttribute("viewBox", "0 0 24 24");
161 svg.setAttribute("fill", "none");
162 svg.setAttribute("stroke", "currentColor");
163 svg.setAttribute("stroke-width", "2");
164 svg.setAttribute("stroke-linecap", "round");
165 svg.setAttribute("stroke-linejoin", "round");
166 svg.setAttribute(
167 "class",
168 tone === "destructive"
169 ? "size-4.5 shrink-0 sm:size-4"
170 : "size-4.5 shrink-0 text-muted-foreground sm:size-4",
171 );
172 for (const node of paths) {
173 const child = document.createElementNS(SVG_NS, node.tag);
174 for (const [key, value] of Object.entries(node.attrs)) {
175 child.setAttribute(key, value);
176 }
177 svg.appendChild(child);
178 }
179 return svg;
180}
181
182function clampMenuPosition(menu: HTMLDivElement, preferredLeft: number, preferredTop: number) {
183 const rect = menu.getBoundingClientRect();
184 const left = Math.min(
185 Math.max(4, preferredLeft),
186 Math.max(4, window.innerWidth - rect.width - 4),
187 );
188 const top = Math.min(
189 Math.max(4, preferredTop),
190 Math.max(4, window.innerHeight - rect.height - 4),
191 );
192 menu.style.left = `${left}px`;
193 menu.style.top = `${top}px`;
194}
195
196function isNodeWithinMenuStack(target: EventTarget | null, menuStack: readonly HTMLDivElement[]) {
197 if (typeof Node !== "undefined" && target instanceof Node) {
198 return menuStack.some((menu) => menu.contains(target));
199 }
200 if (!target || typeof target !== "object") {
201 return false;
202 }
203
204 let current: unknown = target;
205 while (current && typeof current === "object") {
206 if (menuStack.includes(current as HTMLDivElement)) {
207 return true;
208 }
209 current = (current as { parent?: unknown }).parent;
210 }
211 return false;
212}
213
214let activeContextMenuDismiss: ((restoreFocus?: boolean) => void) | null = null;
215
216export function isContextMenuOpen(): boolean {
217 return activeContextMenuDismiss !== null;
218}
219
220export function dismissContextMenu(restoreFocus = true): void {
221 activeContextMenuDismiss?.(restoreFocus);
222 activeContextMenuDismiss = null;
223}
224
225export function showContextMenuFallback<T extends string>(
226 items: readonly ContextMenuItem<T>[],
227 position?: { x: number; y: number },
228): Promise<T | null> {
229 dismissContextMenu();
230 return new Promise<T | null>((resolve) => {
231 const previouslyFocusedElement =
232 document.activeElement instanceof HTMLElement ? document.activeElement : null;
233 const menuStack: HTMLDivElement[] = [];
234 const submenuTriggerStack: Array<HTMLButtonElement | undefined> = [];
235 let isDisposed = false;
236 let canDismissFromPointer = false;
237
238 const dismiss = (restoreFocus = true) => cleanup(null, restoreFocus);
239
240 const cleanup = (result: T | null, restoreFocus = true) => {
241 if (isDisposed) {
242 return;
243 }
244 isDisposed = true;
245 if (activeContextMenuDismiss === dismiss) {
246 activeContextMenuDismiss = null;
247 }
248 document.removeEventListener("keydown", onKeyDown);
249 document.removeEventListener("pointerdown", onPointerDown, true);
250 document.removeEventListener("contextmenu", onContextMenu, true);
251 document.removeEventListener("focusin", onFocusIn);
252 window.removeEventListener("blur", onWindowBlur);
253 const shouldRestoreFocus =
254 restoreFocus && isNodeWithinMenuStack(document.activeElement, menuStack);
255 for (const menu of menuStack) {
256 menu.remove();
257 }
258 if (shouldRestoreFocus && previouslyFocusedElement?.isConnected) {
259 previouslyFocusedElement.focus({ preventScroll: true });
260 }
261 resolve(result);
262 };
263
264 const onKeyDown = (event: KeyboardEvent) => {
265 if (
266 event.defaultPrevented ||
267 event.isComposing ||
268 event.altKey ||
269 event.ctrlKey ||
270 event.metaKey
271 )
272 return;
273 const level = menuStack.findIndex((menu) =>
274 isNodeWithinMenuStack(document.activeElement, [menu]),
275 );
276 if (level < 0) return;
277 const menu = menuStack[level]!;
278 const buttons = [...menu.querySelectorAll<HTMLButtonElement>("button")].filter(
279 (button) => !button.disabled,
280 );
281 const index = buttons.indexOf(document.activeElement as HTMLButtonElement);
282 let target: HTMLButtonElement | undefined;
283 switch (event.key) {
284 case "ArrowDown":
285 target = buttons[(index + 1) % buttons.length];
286 break;
287 case "ArrowUp":
288 target =
289 buttons[(index < 0 ? buttons.length - 1 : index - 1 + buttons.length) % buttons.length];
290 break;
291 case "Home":
292 target = buttons[0];
293 break;
294 case "End":
295 target = buttons.at(-1);
296 break;
297 case "ArrowRight":
298 if (buttons[index]?.getAttribute("aria-haspopup") !== "menu") return;
299 buttons[index]?.click();
300 break;
301 case " ":
302 case "Enter":
303 // Keyboard activation must not depend on the opening pointer gesture's frame.
304 canDismissFromPointer = true;
305 buttons[index]?.click();
306 break;
307 case "ArrowLeft":
308 if (level === 0) return;
309 // Fall through to cancel this submenu only.
310 case "Escape": {
311 const parent = submenuTriggerStack[level];
312 if (parent) {
313 parent.focus({ preventScroll: true });
314 closeMenusFromLevel(level);
315 } else cleanup(null);
316 break;
317 }
318 case "Tab":
319 // Tab closes the menu and continues from the element that opened it.
320 cleanup(null);
321 return;
322 default:
323 return;
324 }
325 event.preventDefault();
326 event.stopPropagation();
327 if (target && target !== submenuTriggerStack[level + 1]) closeMenusFromLevel(level + 1);
328 target?.focus({ preventScroll: true });
329 target?.scrollIntoView({ block: "nearest" });
330 };
331
332 const onFocusIn = (event: FocusEvent) => {
333 if (!isNodeWithinMenuStack(event.target, menuStack)) cleanup(null, false);
334 };
335 const onWindowBlur = () => cleanup(null, false);
336
337 const onPointerDown = (event: PointerEvent) => {
338 if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {
339 return;
340 }
341 cleanup(null);
342 };
343
344 const onContextMenu = (event: MouseEvent) => {
345 if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {
346 return;
347 }
348 event.preventDefault();
349 cleanup(null);
350 };
351
352 const closeMenusFromLevel = (level: number) => {
353 while (menuStack.length > level) {
354 submenuTriggerStack.pop()?.setAttribute("aria-expanded", "false");
355 menuStack.pop()?.remove();
356 }
357 };
358
359 const openMenu = (
360 entries: readonly ContextMenuItem<T>[],
361 preferredLeft: number,
362 preferredTop: number,
363 level: number,
364 parentTrigger?: HTMLButtonElement,
365 ) => {
366 closeMenusFromLevel(level);
367
368 const menu = document.createElement("div");
369 menu.className =
370 "dropdown-glass fixed z-[10000] min-w-32 max-w-sm overflow-hidden rounded-lg bg-clip-padding text-popover-foreground outline-none";
371 menu.style.cssText =
372 "position:fixed;z-index:10000;min-width:8rem;max-width:24rem;overflow:hidden;border-radius:var(--radius-lg);background-clip:padding-box;color:var(--contrast-popover-foreground);outline:none;pointer-events:auto;";
373 menu.style.left = `${preferredLeft}px`;
374 menu.style.top = `${preferredTop}px`;
375 menu.dataset.level = String(level);
376 menu.dataset.contextMenu = "true";
377 menu.setAttribute("role", "menu");
378 menu.setAttribute("aria-label", parentTrigger?.textContent ?? "Context menu");
379 menu.tabIndex = -1;
380
381 const inner = document.createElement("div");
382 inner.className =
383 "max-h-[calc(100vh-0.5rem)] min-w-0 max-w-sm overflow-y-auto overflow-x-hidden p-1";
384 inner.style.cssText =
385 "max-height:calc(100vh - 0.5rem);min-width:0;max-width:24rem;overflow-x:hidden;overflow-y:auto;padding:0.25rem;";
386
387 for (const item of entries) {
388 if (item.separatorBefore === true && inner.children.length > 0) {
389 const separator = document.createElement("div");
390 separator.className = "mx-2 my-1 h-px bg-border";
391 separator.style.cssText =
392 "height:1px;margin:0.25rem 0.5rem;background:var(--contrast-border);";
393 separator.dataset.contextMenuSeparator = "true";
394 separator.setAttribute("role", "separator");
395 inner.appendChild(separator);
396 }
397
398 if (item.header === true) {
399 const header = document.createElement("div");
400 header.className = "px-2 py-1.5 font-medium text-muted-foreground text-xs";
401 header.textContent = item.label;
402 inner.appendChild(header);
403 continue;
404 }
405
406 const hasChildren = Array.isArray(item.children) && item.children.length > 0;
407 const isLeafDestructive =
408 !hasChildren && (item.destructive === true || item.id === ("delete" as T));
409
410 const button = document.createElement("button");
411 button.type = "button";
412 const isDisabled = item.disabled === true;
413 button.disabled = isDisabled;
414 button.tabIndex = -1;
415 button.setAttribute("role", "menuitem");
416 button.setAttribute("aria-disabled", String(isDisabled));
417 const rowBase =
418 "flex w-full cursor-default select-none items-center gap-2 rounded-sm px-2 py-1 text-left outline-none transition-colors sm:min-h-7 sm:text-sm min-h-8 text-base";
419 button.className = isDisabled
420 ? `${rowBase} pointer-events-none cursor-not-allowed text-muted-foreground opacity-64`
421 : isLeafDestructive
422 ? `${rowBase} text-destructive-foreground hover:bg-destructive/10 hover:text-destructive-foreground`
423 : `${rowBase} text-foreground hover:bg-accent hover:text-accent-foreground`;
424 button.style.cssText =
425 "display:flex;width:100%;min-height:1.75rem;align-items:center;gap:0.5rem;border:0;border-radius:var(--radius-sm);background:transparent;padding:0.25rem 0.5rem;color:var(--contrast-foreground);font-family:var(--font-sans,system-ui,sans-serif);font-size:0.875rem;line-height:1.25rem;text-align:left;cursor:default;";
426 if (isLeafDestructive) {
427 button.style.color = "var(--destructive-foreground)";
428 }
429 if (isDisabled) {
430 button.style.color = "var(--contrast-muted-foreground)";
431 button.style.opacity = "0.64";
432 button.style.pointerEvents = "none";
433 }
434
435 if (typeof item.checked === "boolean") {
436 button.setAttribute("role", "menuitemradio");
437 button.setAttribute("aria-checked", item.checked ? "true" : "false");
438 const check = item.checked ? createIconElement("check", "neutral") : null;
439 if (check) {
440 button.appendChild(check);
441 } else {
442 const spacer = document.createElement("span");
443 spacer.className = "size-4.5 shrink-0 sm:size-4";
444 spacer.style.cssText = "display:inline-block;width:1rem;height:1rem;flex-shrink:0;";
445 spacer.setAttribute("aria-hidden", "true");
446 button.appendChild(spacer);
447 }
448 } else if (typeof item.icon === "string") {
449 const icon = createIconElement(item.icon, isLeafDestructive ? "destructive" : "neutral");
450 if (icon) {
451 button.appendChild(icon);
452 }
453 }
454
455 const label = document.createElement("span");
456 label.className = "min-w-0 flex-1 truncate";
457 label.textContent = item.label;
458 button.appendChild(label);
459
460 if (hasChildren) {
461 button.setAttribute("aria-haspopup", "menu");
462 button.setAttribute("aria-expanded", "false");
463 const chevron = createIconElement("chevron-right", "neutral");
464 if (chevron) {
465 chevron.setAttribute(
466 "class",
467 "-me-0.5 ms-auto size-4.5 shrink-0 text-muted-foreground opacity-80 sm:size-4",
468 );
469 chevron.setAttribute("aria-hidden", "true");
470 chevron.dataset.contextMenuChevron = "true";
471 button.appendChild(chevron);
472 }
473 }
474
475 if (!isDisabled) {
476 let isHovered = false;
477 let isFocused = false;
478 const updateHighlight = () => {
479 const isHighlighted = isHovered || isFocused;
480 button.style.background = isHighlighted
481 ? isLeafDestructive
482 ? "color-mix(in srgb, var(--destructive) 10%, transparent)"
483 : "var(--accent)"
484 : "transparent";
485 button.style.color = isHighlighted
486 ? isLeafDestructive
487 ? "var(--destructive-foreground)"
488 : "var(--contrast-accent-foreground)"
489 : isLeafDestructive
490 ? "var(--destructive-foreground)"
491 : "var(--contrast-foreground)";
492 };
493 button.addEventListener("mouseenter", () => {
494 button.focus({ preventScroll: true });
495 isHovered = true;
496 updateHighlight();
497 });
498 button.addEventListener("mouseleave", () => {
499 isHovered = false;
500 updateHighlight();
501 });
502 button.addEventListener("focus", () => {
503 isFocused = true;
504 updateHighlight();
505 });
506 button.addEventListener("blur", () => {
507 isFocused = false;
508 updateHighlight();
509 });
510
511 if (hasChildren) {
512 const openSubmenu = (focusFirstItem = false) => {
513 const rect = button.getBoundingClientRect();
514 const nextLeft = rect.right + 4;
515 const nextTop = rect.top;
516 openMenu(item.children!, nextLeft, nextTop, level + 1, button);
517 button.setAttribute("aria-expanded", "true");
518
519 const childMenu = menuStack[level + 1];
520 if (!childMenu) {
521 return;
522 }
523 const childRect = childMenu.getBoundingClientRect();
524 if (childRect.right > window.innerWidth) {
525 clampMenuPosition(childMenu, rect.left - childRect.width - 4, rect.top);
526 }
527 if (focusFirstItem) {
528 [...childMenu.querySelectorAll<HTMLButtonElement>("button")]
529 .find((childButton) => !childButton.disabled)
530 ?.focus();
531 }
532 };
533 button.addEventListener("mouseenter", () => {
534 openSubmenu();
535 });
536 button.addEventListener("click", (event) => {
537 event.preventDefault();
538 openSubmenu(true);
539 });
540 } else {
541 button.addEventListener("mouseenter", () => {
542 closeMenusFromLevel(level + 1);
543 });
544 button.addEventListener("click", () => {
545 if (canDismissFromPointer) cleanup(item.id);
546 });
547 }
548 }
549
550 inner.appendChild(button);
551 }
552
553 menu.appendChild(inner);
554
555 menu.addEventListener("mouseenter", () => {
556 closeMenusFromLevel(level + 1);
557 });
558
559 document.body.appendChild(menu);
560 menuStack[level] = menu;
561 submenuTriggerStack[level] = parentTrigger;
562
563 requestAnimationFrame(() => {
564 clampMenuPosition(menu, preferredLeft, preferredTop);
565 });
566 };
567
568 document.addEventListener("keydown", onKeyDown);
569 document.addEventListener("pointerdown", onPointerDown, true);
570 document.addEventListener("contextmenu", onContextMenu, true);
571 openMenu(items, position?.x ?? 0, position?.y ?? 0, 0);
572 activeContextMenuDismiss = dismiss;
573 // A keyboard-opened menu starts on its first action, a pointer-opened one on the menu itself.
574 // Text fields always match :focus-visible, so they say nothing about how the menu opened.
575 const firstAction =
576 previouslyFocusedElement?.matches(":focus-visible") &&
577 !previouslyFocusedElement.matches('input, textarea, select, [contenteditable="true"]')
578 ? menuStack[0]?.querySelector<HTMLButtonElement>("button:not(:disabled)")
579 : null;
580 (firstAction ?? menuStack[0])?.focus({ preventScroll: true });
581 document.addEventListener("focusin", onFocusIn);
582 window.addEventListener("blur", onWindowBlur);
583
584 requestAnimationFrame(() => {
585 canDismissFromPointer = true;
586 });
587 });
588}