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

contextMenuFallback.ts

646 lines24.9 KB

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