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

contextMenuFallback.ts

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