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

contextMenuFallback.ts

605 lines22.8 KB

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-plus": [
128 { tag: "path", attrs: { d: "M12 10v6" } },
129 { tag: "path", attrs: { d: "M9 13h6" } },
130 {
131 tag: "path",
132 attrs: {
133 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",
134 },
135 },
136 ],
137 "folder-tree": [
138 {
139 tag: "path",
140 attrs: {
141 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",
142 },
143 },
144 {
145 tag: "path",
146 attrs: {
147 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",
148 },
149 },
150 { tag: "path", attrs: { d: "M3 5a2 2 0 0 0 2 2h3" } },
151 { tag: "path", attrs: { d: "M3 3v13a2 2 0 0 0 2 2h3" } },
152 ],
153 "text-search": [
154 { tag: "path", attrs: { d: "M21 5H3" } },
155 { tag: "path", attrs: { d: "M10 12H3" } },
156 { tag: "path", attrs: { d: "M10 19H3" } },
157 { tag: "circle", attrs: { cx: "17", cy: "15", r: "3" } },
158 { tag: "path", attrs: { d: "m21 19-1.9-1.9" } },
159 ],
160 trash: [
161 { tag: "path", attrs: { d: "M3 6h18" } },
162 { tag: "path", attrs: { d: "M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" } },
163 { tag: "path", attrs: { d: "M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" } },
164 { tag: "line", attrs: { x1: "10", x2: "10", y1: "11", y2: "17" } },
165 { tag: "line", attrs: { x1: "14", x2: "14", y1: "11", y2: "17" } },
166 ],
167};
168​
169function createIconElement(name: string, tone: "neutral" | "destructive"): SVGSVGElement | null {
170 const paths = ICON_PATHS[name];
171 if (!paths || typeof document.createElementNS !== "function") {
172 return null;
173 }
174 const svg = document.createElementNS(SVG_NS, "svg");
175 svg.setAttribute("aria-hidden", "true");
176 svg.setAttribute("xmlns", SVG_NS);
177 svg.setAttribute("viewBox", "0 0 24 24");
178 svg.setAttribute("fill", "none");
179 svg.setAttribute("stroke", "currentColor");
180 svg.setAttribute("stroke-width", "2");
181 svg.setAttribute("stroke-linecap", "round");
182 svg.setAttribute("stroke-linejoin", "round");
183 svg.setAttribute(
184 "class",
185 tone === "destructive"
186 ? "size-4.5 shrink-0 sm:size-4"
187 : "size-4.5 shrink-0 text-muted-foreground sm:size-4",
188 );
189 for (const node of paths) {
190 const child = document.createElementNS(SVG_NS, node.tag);
191 for (const [key, value] of Object.entries(node.attrs)) {
192 child.setAttribute(key, value);
193 }
194 svg.appendChild(child);
195 }
196 return svg;
198​
199function clampMenuPosition(menu: HTMLDivElement, preferredLeft: number, preferredTop: number) {
200 const rect = menu.getBoundingClientRect();
201 const left = Math.min(
202 Math.max(4, preferredLeft),
203 Math.max(4, window.innerWidth - rect.width - 4),
204 );
205 const top = Math.min(
206 Math.max(4, preferredTop),
207 Math.max(4, window.innerHeight - rect.height - 4),
208 );
209 menu.style.left = `${left}px`;
210 menu.style.top = `${top}px`;
212​
213function isNodeWithinMenuStack(target: EventTarget | null, menuStack: readonly HTMLDivElement[]) {
214 if (typeof Node !== "undefined" && target instanceof Node) {
215 return menuStack.some((menu) => menu.contains(target));
216 }
217 if (!target || typeof target !== "object") {
218 return false;
219 }
220​
221 let current: unknown = target;
222 while (current && typeof current === "object") {
223 if (menuStack.includes(current as HTMLDivElement)) {
224 return true;
225 }
226 current = (current as { parent?: unknown }).parent;
227 }
228 return false;
230​
231let activeContextMenuDismiss: ((restoreFocus?: boolean) => void) | null = null;
232​
233export function isContextMenuOpen(): boolean {
234 return activeContextMenuDismiss !== null;
236​
237export function dismissContextMenu(restoreFocus = true): void {
238 activeContextMenuDismiss?.(restoreFocus);
239 activeContextMenuDismiss = null;
241​
242export function showContextMenuFallback<T extends string>(
243 items: readonly ContextMenuItem<T>[],
244 position?: { x: number; y: number },
245): Promise<T | null> {
246 dismissContextMenu();
247 return new Promise<T | null>((resolve) => {
248 const previouslyFocusedElement =
249 document.activeElement instanceof HTMLElement ? document.activeElement : null;
250 const menuStack: HTMLDivElement[] = [];
251 const submenuTriggerStack: Array<HTMLButtonElement | undefined> = [];
252 let isDisposed = false;
253 let canDismissFromPointer = false;
254​
255 const dismiss = (restoreFocus = true) => cleanup(null, restoreFocus);
256​
257 const cleanup = (result: T | null, restoreFocus = true) => {
258 if (isDisposed) {
259 return;
260 }
261 isDisposed = true;
262 if (activeContextMenuDismiss === dismiss) {
263 activeContextMenuDismiss = null;
264 }
265 document.removeEventListener("keydown", onKeyDown);
266 document.removeEventListener("pointerdown", onPointerDown, true);
267 document.removeEventListener("contextmenu", onContextMenu, true);
268 document.removeEventListener("focusin", onFocusIn);
269 window.removeEventListener("blur", onWindowBlur);
270 const shouldRestoreFocus =
271 restoreFocus && isNodeWithinMenuStack(document.activeElement, menuStack);
272 for (const menu of menuStack) {
273 menu.remove();
274 }
275 if (shouldRestoreFocus && previouslyFocusedElement?.isConnected) {
276 previouslyFocusedElement.focus({ preventScroll: true });
277 }
278 resolve(result);
279 };
280​
281 const onKeyDown = (event: KeyboardEvent) => {
282 if (
283 event.defaultPrevented ||
284 event.isComposing ||
285 event.altKey ||
286 event.ctrlKey ||
287 event.metaKey
288 )
289 return;
290 const level = menuStack.findIndex((menu) =>
291 isNodeWithinMenuStack(document.activeElement, [menu]),
292 );
293 if (level < 0) return;
294 const menu = menuStack[level]!;
295 const buttons = [...menu.querySelectorAll<HTMLButtonElement>("button")].filter(
296 (button) => !button.disabled,
297 );
298 const index = buttons.indexOf(document.activeElement as HTMLButtonElement);
299 let target: HTMLButtonElement | undefined;
300 switch (event.key) {
301 case "ArrowDown":
302 target = buttons[(index + 1) % buttons.length];
303 break;
304 case "ArrowUp":
305 target =
306 buttons[(index < 0 ? buttons.length - 1 : index - 1 + buttons.length) % buttons.length];
307 break;
308 case "Home":
309 target = buttons[0];
310 break;
311 case "End":
312 target = buttons.at(-1);
313 break;
314 case "ArrowRight":
315 if (buttons[index]?.getAttribute("aria-haspopup") !== "menu") return;
316 buttons[index]?.click();
317 break;
318 case " ":
319 case "Enter":
320 // Keyboard activation must not depend on the opening pointer gesture's frame.
321 canDismissFromPointer = true;
322 buttons[index]?.click();
323 break;
324 case "ArrowLeft":
325 if (level === 0) return;
326 // Fall through to cancel this submenu only.
327 case "Escape": {
328 const parent = submenuTriggerStack[level];
329 if (parent) {
330 parent.focus({ preventScroll: true });
331 closeMenusFromLevel(level);
332 } else cleanup(null);
333 break;
334 }
335 case "Tab":
336 // Tab closes the menu and continues from the element that opened it.
337 cleanup(null);
338 return;
339 default:
340 return;
341 }
342 event.preventDefault();
343 event.stopPropagation();
344 if (target && target !== submenuTriggerStack[level + 1]) closeMenusFromLevel(level + 1);
345 target?.focus({ preventScroll: true });
346 target?.scrollIntoView({ block: "nearest" });
347 };
348​
349 const onFocusIn = (event: FocusEvent) => {
350 if (!isNodeWithinMenuStack(event.target, menuStack)) cleanup(null, false);
351 };
352 const onWindowBlur = () => cleanup(null, false);
353​
354 const onPointerDown = (event: PointerEvent) => {
355 if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {
356 return;
357 }
358 cleanup(null);
359 };
360​
361 const onContextMenu = (event: MouseEvent) => {
362 if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {
363 return;
364 }
365 event.preventDefault();
366 cleanup(null);
367 };
368​
369 const closeMenusFromLevel = (level: number) => {
370 while (menuStack.length > level) {
371 submenuTriggerStack.pop()?.setAttribute("aria-expanded", "false");
372 menuStack.pop()?.remove();
373 }
374 };
375​
376 const openMenu = (
377 entries: readonly ContextMenuItem<T>[],
378 preferredLeft: number,
379 preferredTop: number,
380 level: number,
381 parentTrigger?: HTMLButtonElement,
382 ) => {
383 closeMenusFromLevel(level);
384​
385 const menu = document.createElement("div");
386 menu.className =
387 "dropdown-glass fixed z-[10000] min-w-32 max-w-sm overflow-hidden rounded-lg bg-clip-padding text-popover-foreground outline-none";
388 menu.style.cssText =
389 "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;";
390 menu.style.left = `${preferredLeft}px`;
391 menu.style.top = `${preferredTop}px`;
392 menu.dataset.level = String(level);
393 menu.dataset.contextMenu = "true";
394 menu.setAttribute("role", "menu");
395 menu.setAttribute("aria-label", parentTrigger?.textContent ?? "Context menu");
396 menu.tabIndex = -1;
397​
398 const inner = document.createElement("div");
399 inner.className =
400 "max-h-[calc(100vh-0.5rem)] min-w-0 max-w-sm overflow-y-auto overflow-x-hidden p-1";
401 inner.style.cssText =
402 "max-height:calc(100vh - 0.5rem);min-width:0;max-width:24rem;overflow-x:hidden;overflow-y:auto;padding:0.25rem;";
403​
404 for (const item of entries) {
405 if (item.separatorBefore === true && inner.children.length > 0) {
406 const separator = document.createElement("div");
407 separator.className = "mx-2 my-1 h-px bg-border";
408 separator.style.cssText =
409 "height:1px;margin:0.25rem 0.5rem;background:var(--contrast-border);";
410 separator.dataset.contextMenuSeparator = "true";
411 separator.setAttribute("role", "separator");
412 inner.appendChild(separator);
413 }
414​
415 if (item.header === true) {
416 const header = document.createElement("div");
417 header.className = "px-2 py-1.5 font-medium text-muted-foreground text-xs";
418 header.textContent = item.label;
419 inner.appendChild(header);
420 continue;
421 }
422​
423 const hasChildren = Array.isArray(item.children) && item.children.length > 0;
424 const isLeafDestructive =
425 !hasChildren && (item.destructive === true || item.id === ("delete" as T));
426​
427 const button = document.createElement("button");
428 button.type = "button";
429 const isDisabled = item.disabled === true;
430 button.disabled = isDisabled;
431 button.tabIndex = -1;
432 button.setAttribute("role", "menuitem");
433 button.setAttribute("aria-disabled", String(isDisabled));
434 const rowBase =
435 "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";
436 button.className = isDisabled
437 ? `${rowBase} pointer-events-none cursor-not-allowed text-muted-foreground opacity-64`
438 : isLeafDestructive
439 ? `${rowBase} text-destructive-foreground hover:bg-destructive/10 hover:text-destructive-foreground`
440 : `${rowBase} text-foreground hover:bg-accent hover:text-accent-foreground`;
441 button.style.cssText =
442 "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;";
443 if (isLeafDestructive) {
444 button.style.color = "var(--destructive-foreground)";
445 }
446 if (isDisabled) {
447 button.style.color = "var(--contrast-muted-foreground)";
448 button.style.opacity = "0.64";
449 button.style.pointerEvents = "none";
450 }
451​
452 if (typeof item.checked === "boolean") {
453 button.setAttribute("role", "menuitemradio");
454 button.setAttribute("aria-checked", item.checked ? "true" : "false");
455 const check = item.checked ? createIconElement("check", "neutral") : null;
456 if (check) {
457 button.appendChild(check);
458 } else {
459 const spacer = document.createElement("span");
460 spacer.className = "size-4.5 shrink-0 sm:size-4";
461 spacer.style.cssText = "display:inline-block;width:1rem;height:1rem;flex-shrink:0;";
462 spacer.setAttribute("aria-hidden", "true");
463 button.appendChild(spacer);
464 }
465 } else if (typeof item.icon === "string") {
466 const icon = createIconElement(item.icon, isLeafDestructive ? "destructive" : "neutral");
467 if (icon) {
468 button.appendChild(icon);
469 }
470 }
471​
472 const label = document.createElement("span");
473 label.className = "min-w-0 flex-1 truncate";
474 label.textContent = item.label;
475 button.appendChild(label);
476​
477 if (hasChildren) {
478 button.setAttribute("aria-haspopup", "menu");
479 button.setAttribute("aria-expanded", "false");
480 const chevron = createIconElement("chevron-right", "neutral");
481 if (chevron) {
482 chevron.setAttribute(
483 "class",
484 "-me-0.5 ms-auto size-4.5 shrink-0 text-muted-foreground opacity-80 sm:size-4",
485 );
486 chevron.setAttribute("aria-hidden", "true");
487 chevron.dataset.contextMenuChevron = "true";
488 button.appendChild(chevron);
489 }
490 }
491​
492 if (!isDisabled) {
493 let isHovered = false;
494 let isFocused = false;
495 const updateHighlight = () => {
496 const isHighlighted = isHovered || isFocused;
497 button.style.background = isHighlighted
498 ? isLeafDestructive
499 ? "color-mix(in srgb, var(--destructive) 10%, transparent)"
500 : "var(--accent)"
501 : "transparent";
502 button.style.color = isHighlighted
503 ? isLeafDestructive
504 ? "var(--destructive-foreground)"
505 : "var(--contrast-accent-foreground)"
506 : isLeafDestructive
507 ? "var(--destructive-foreground)"
508 : "var(--contrast-foreground)";
509 };
510 button.addEventListener("mouseenter", () => {
511 button.focus({ preventScroll: true });
512 isHovered = true;
513 updateHighlight();
514 });
515 button.addEventListener("mouseleave", () => {
516 isHovered = false;
517 updateHighlight();
518 });
519 button.addEventListener("focus", () => {
520 isFocused = true;
521 updateHighlight();
522 });
523 button.addEventListener("blur", () => {
524 isFocused = false;
525 updateHighlight();
526 });
527​
528 if (hasChildren) {
529 const openSubmenu = (focusFirstItem = false) => {
530 const rect = button.getBoundingClientRect();
531 const nextLeft = rect.right + 4;
532 const nextTop = rect.top;
533 openMenu(item.children!, nextLeft, nextTop, level + 1, button);
534 button.setAttribute("aria-expanded", "true");
535​
536 const childMenu = menuStack[level + 1];
537 if (!childMenu) {
538 return;
539 }
540 const childRect = childMenu.getBoundingClientRect();
541 if (childRect.right > window.innerWidth) {
542 clampMenuPosition(childMenu, rect.left - childRect.width - 4, rect.top);
543 }
544 if (focusFirstItem) {
545 [...childMenu.querySelectorAll<HTMLButtonElement>("button")]
546 .find((childButton) => !childButton.disabled)
547 ?.focus();
548 }
549 };
550 button.addEventListener("mouseenter", () => {
551 openSubmenu();
552 });
553 button.addEventListener("click", (event) => {
554 event.preventDefault();
555 openSubmenu(true);
556 });
557 } else {
558 button.addEventListener("mouseenter", () => {
559 closeMenusFromLevel(level + 1);
560 });
561 button.addEventListener("click", () => {
562 if (canDismissFromPointer) cleanup(item.id);
563 });
564 }
565 }
566​
567 inner.appendChild(button);
568 }
569​
570 menu.appendChild(inner);
571​
572 menu.addEventListener("mouseenter", () => {
573 closeMenusFromLevel(level + 1);
574 });
575​
576 document.body.appendChild(menu);
577 menuStack[level] = menu;
578 submenuTriggerStack[level] = parentTrigger;
579​
580 requestAnimationFrame(() => {
581 clampMenuPosition(menu, preferredLeft, preferredTop);
582 });
583 };
584​
585 document.addEventListener("keydown", onKeyDown);
586 document.addEventListener("pointerdown", onPointerDown, true);
587 document.addEventListener("contextmenu", onContextMenu, true);
588 openMenu(items, position?.x ?? 0, position?.y ?? 0, 0);
589 activeContextMenuDismiss = dismiss;
590 // A keyboard-opened menu starts on its first action, a pointer-opened one on the menu itself.
591 // Text fields always match :focus-visible, so they say nothing about how the menu opened.
592 const firstAction =
593 previouslyFocusedElement?.matches(":focus-visible") &&
594 !previouslyFocusedElement.matches('input, textarea, select, [contenteditable="true"]')
595 ? menuStack[0]?.querySelector<HTMLButtonElement>("button:not(:disabled)")
596 : null;
597 (firstAction ?? menuStack[0])?.focus({ preventScroll: true });
598 document.addEventListener("focusin", onFocusIn);
599 window.addEventListener("blur", onWindowBlur);
600​
601 requestAnimationFrame(() => {
602 canDismissFromPointer = true;
603 });
604 });