Open History to see the last commit
1import type { ContextMenuItem } from "@t3tools/contracts";
2
3const SVG_NS = "http://www.w3.org/2000/svg";
4
5// Inline Lucide-style icon paths (stroke-based, viewBox 0 0 24 24, strokeWidth 2).
6const ICON_PATHS: Record<string, ReadonlyArray<{ tag: string; attrs: Record<string, string> }>> = {
7 pencil: [
8 {
9 tag: "path",
10 attrs: {
11 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",
12 },
13 },
14 { tag: "path", attrs: { d: "m15 5 4 4" } },
15 ],
16 copy: [
17 { tag: "rect", attrs: { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2" } },
18 { 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" } },
19 ],
20 "folder-tree": [
21 {
22 tag: "path",
23 attrs: {
24 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",
25 },
26 },
27 {
28 tag: "path",
29 attrs: {
30 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",
31 },
32 },
33 { tag: "path", attrs: { d: "M3 5a2 2 0 0 0 2 2h3" } },
34 { tag: "path", attrs: { d: "M3 3v13a2 2 0 0 0 2 2h3" } },
35 ],
36 trash: [
37 { tag: "path", attrs: { d: "M3 6h18" } },
38 { tag: "path", attrs: { d: "M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" } },
39 { tag: "path", attrs: { d: "M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" } },
40 { tag: "line", attrs: { x1: "10", x2: "10", y1: "11", y2: "17" } },
41 { tag: "line", attrs: { x1: "14", x2: "14", y1: "11", y2: "17" } },
42 ],
43};
44
45function createIconElement(name: string, tone: "neutral" | "destructive"): SVGSVGElement | null {
46 const paths = ICON_PATHS[name];
47 if (!paths) {
48 return null;
49 }
50 const svg = document.createElementNS(SVG_NS, "svg");
51 svg.setAttribute("xmlns", SVG_NS);
52 svg.setAttribute("viewBox", "0 0 24 24");
53 svg.setAttribute("fill", "none");
54 svg.setAttribute("stroke", "currentColor");
55 svg.setAttribute("stroke-width", "2");
56 svg.setAttribute("stroke-linecap", "round");
57 svg.setAttribute("stroke-linejoin", "round");
58 svg.setAttribute(
59 "class",
60 tone === "destructive" ? "size-3.5 shrink-0" : "size-3.5 shrink-0 text-muted-foreground",
61 );
62 for (const node of paths) {
63 const child = document.createElementNS(SVG_NS, node.tag);
64 for (const [key, value] of Object.entries(node.attrs)) {
65 child.setAttribute(key, value);
66 }
67 svg.appendChild(child);
68 }
69 return svg;
70}
71
72function clampMenuPosition(menu: HTMLDivElement, preferredLeft: number, preferredTop: number) {
73 const rect = menu.getBoundingClientRect();
74 const left = Math.min(
75 Math.max(4, preferredLeft),
76 Math.max(4, window.innerWidth - rect.width - 4),
77 );
78 const top = Math.min(
79 Math.max(4, preferredTop),
80 Math.max(4, window.innerHeight - rect.height - 4),
81 );
82 menu.style.left = `${left}px`;
83 menu.style.top = `${top}px`;
84}
85
86function isNodeWithinMenuStack(target: EventTarget | null, menuStack: readonly HTMLDivElement[]) {
87 if (typeof Node !== "undefined" && target instanceof Node) {
88 return menuStack.some((menu) => menu.contains(target));
89 }
90 if (!target || typeof target !== "object") {
91 return false;
92 }
93
94 let current: unknown = target;
95 while (current && typeof current === "object") {
96 if (menuStack.includes(current as HTMLDivElement)) {
97 return true;
98 }
99 current = (current as { parent?: unknown }).parent;
100 }
101 return false;
102}
103
104/**
105 * Imperative DOM-based context menu for non-Electron environments.
106 * Supports keyboard and pointer navigation through nested submenus and resolves
107 * with the selected leaf item id.
108 */
109export function showContextMenuFallback<T extends string>(
110 items: readonly ContextMenuItem<T>[],
111 position?: { x: number; y: number },
112): Promise<T | null> {
113 return new Promise<T | null>((resolve) => {
114 const previousActiveElement = document.activeElement as HTMLElement | null;
115 const menuStack: HTMLDivElement[] = [];
116 const menuParentButtons: Array<HTMLButtonElement | null> = [];
117 const buttonMetadata = new WeakMap<
118 HTMLButtonElement,
119 {
120 readonly item: ContextMenuItem<T>;
121 readonly openSubmenu: (focusFirstItem: boolean) => void;
122 }
123 >();
124 let isDisposed = false;
125 let canDismissFromPointer = false;
126
127 const cleanup = (result: T | null) => {
128 if (isDisposed) {
129 return;
130 }
131 isDisposed = true;
132 document.removeEventListener("keydown", onKeyDown);
133 document.removeEventListener("pointerdown", onPointerDown, true);
134 document.removeEventListener("contextmenu", onContextMenu, true);
135 for (const menu of menuStack) {
136 menu.remove();
137 }
138 previousActiveElement?.focus();
139 resolve(result);
140 };
141
142 const closeMenusFromLevel = (level: number) => {
143 while (menuStack.length > level) {
144 const childLevel = menuStack.length - 1;
145 const childMenu = menuStack[childLevel];
146 const parentButton = menuParentButtons[childLevel];
147 if (
148 childMenu &&
149 parentButton &&
150 isNodeWithinMenuStack(document.activeElement, [childMenu])
151 ) {
152 parentButton.focus();
153 }
154 parentButton?.setAttribute("aria-expanded", "false");
155 menuParentButtons.pop();
156 menuStack.pop();
157 childMenu?.remove();
158 }
159 };
160
161 const getEnabledMenuButtons = (menu: HTMLDivElement): HTMLButtonElement[] =>
162 Array.from(menu.querySelectorAll<HTMLButtonElement>("button")).filter(
163 (button) => !button.disabled,
164 );
165
166 const focusMenuItem = (menu: HTMLDivElement, index: number) => {
167 const buttons = getEnabledMenuButtons(menu);
168 if (buttons.length === 0) {
169 return;
170 }
171 const normalizedIndex = (index + buttons.length) % buttons.length;
172 const button = buttons[normalizedIndex];
173 if (!button) {
174 return;
175 }
176 button.focus();
177 button.scrollIntoView?.({ block: "nearest" });
178 };
179
180 const onKeyDown = (event: KeyboardEvent) => {
181 if (event.key === "Escape") {
182 event.preventDefault();
183 cleanup(null);
184 return;
185 }
186
187 const eventTarget = event.target ?? document.activeElement;
188 const menuIndex = menuStack.findIndex((menu) => isNodeWithinMenuStack(eventTarget, [menu]));
189 const menu = menuStack[menuIndex];
190 if (!menu) {
191 return;
192 }
193
194 const buttons = getEnabledMenuButtons(menu);
195 const button = buttons.find((candidate) => candidate === eventTarget);
196 const metadata = button ? buttonMetadata.get(button) : undefined;
197 if (!button || !metadata) {
198 return;
199 }
200
201 const currentIndex = buttons.indexOf(button);
202 switch (event.key) {
203 case "ArrowDown":
204 event.preventDefault();
205 closeMenusFromLevel(menuIndex + 1);
206 focusMenuItem(menu, currentIndex + 1);
207 break;
208 case "ArrowUp":
209 event.preventDefault();
210 closeMenusFromLevel(menuIndex + 1);
211 focusMenuItem(menu, currentIndex - 1);
212 break;
213 case "Home":
214 event.preventDefault();
215 closeMenusFromLevel(menuIndex + 1);
216 focusMenuItem(menu, 0);
217 break;
218 case "End":
219 event.preventDefault();
220 closeMenusFromLevel(menuIndex + 1);
221 focusMenuItem(menu, buttons.length - 1);
222 break;
223 case "ArrowRight":
224 if (metadata.item.children && metadata.item.children.length > 0) {
225 event.preventDefault();
226 metadata.openSubmenu(true);
227 }
228 break;
229 case "ArrowLeft": {
230 const parentButton = menuParentButtons[menuIndex];
231 if (!parentButton) {
232 return;
233 }
234 event.preventDefault();
235 closeMenusFromLevel(menuIndex);
236 parentButton.focus();
237 break;
238 }
239 case "Enter":
240 case " ":
241 event.preventDefault();
242 if (metadata.item.children && metadata.item.children.length > 0) {
243 metadata.openSubmenu(true);
244 } else {
245 cleanup(metadata.item.id);
246 }
247 break;
248 }
249 };
250
251 const onPointerDown = (event: PointerEvent) => {
252 if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {
253 return;
254 }
255 cleanup(null);
256 };
257
258 const onContextMenu = (event: MouseEvent) => {
259 if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {
260 return;
261 }
262 event.preventDefault();
263 cleanup(null);
264 };
265
266 const openMenu = (
267 entries: readonly ContextMenuItem<T>[],
268 preferredLeft: number,
269 preferredTop: number,
270 level: number,
271 focusFirstItem = false,
272 parentButton?: HTMLButtonElement,
273 ) => {
274 closeMenusFromLevel(level);
275
276 const menu = document.createElement("div");
277 menu.className =
278 "dropdown-glass fixed z-[10000] min-w-32 max-w-sm overflow-hidden rounded-lg bg-clip-padding text-popover-foreground outline-none";
279 menu.style.cssText =
280 "position:fixed;z-index:10000;min-width:8rem;max-width:24rem;overflow:hidden;border-radius:var(--radius-lg);background-clip:padding-box;color:var(--popover-foreground);outline:none;pointer-events:auto;";
281 menu.style.left = `${preferredLeft}px`;
282 menu.style.top = `${preferredTop}px`;
283 menu.dataset.level = String(level);
284 menu.setAttribute("role", "menu");
285 menu.setAttribute("aria-orientation", "vertical");
286 menu.setAttribute("data-slot", "menu-popup");
287 menuParentButtons[level] = parentButton ?? null;
288
289 const inner = document.createElement("div");
290 inner.className =
291 "max-h-[min(24rem,70vh)] min-w-0 max-w-sm overflow-y-auto overflow-x-hidden p-1";
292 inner.style.cssText =
293 "max-height:min(24rem,70vh);min-width:0;max-width:24rem;overflow-x:hidden;overflow-y:auto;padding:0.25rem;";
294
295 for (const item of entries) {
296 if (item.header === true) {
297 const header = document.createElement("div");
298 header.className = "px-2 py-1.5 font-medium text-muted-foreground text-xs";
299 header.textContent = item.label;
300 inner.appendChild(header);
301 continue;
302 }
303
304 const hasChildren = Array.isArray(item.children) && item.children.length > 0;
305 const isLeafDestructive =
306 !hasChildren && (item.destructive === true || item.id === ("delete" as T));
307
308 const button = document.createElement("button");
309 button.type = "button";
310 button.tabIndex = -1;
311 button.setAttribute("role", "menuitem");
312 const isDisabled = item.disabled === true;
313 button.disabled = isDisabled;
314 const rowBase =
315 "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";
316 button.className = isDisabled
317 ? `${rowBase} pointer-events-none cursor-not-allowed text-muted-foreground opacity-64`
318 : isLeafDestructive
319 ? `${rowBase} text-destructive-foreground hover:bg-destructive/10 hover:text-destructive-foreground`
320 : `${rowBase} text-foreground hover:bg-accent hover:text-accent-foreground`;
321 button.style.cssText =
322 "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(--foreground);font-family:var(--font-sans,system-ui,sans-serif);font-size:0.875rem;line-height:1.25rem;text-align:left;cursor:default;";
323 if (isLeafDestructive) {
324 button.style.color = "var(--destructive-foreground)";
325 }
326 if (isDisabled) {
327 button.style.color = "var(--muted-foreground)";
328 button.style.opacity = "0.64";
329 button.style.pointerEvents = "none";
330 }
331
332 if (typeof item.icon === "string") {
333 const icon = createIconElement(item.icon, isLeafDestructive ? "destructive" : "neutral");
334 if (icon) {
335 button.appendChild(icon);
336 }
337 }
338
339 const label = document.createElement("span");
340 label.className = "min-w-0 flex-1 truncate";
341 label.textContent = item.label;
342 button.appendChild(label);
343
344 if (hasChildren) {
345 const chevron = document.createElement("span");
346 chevron.className = "ms-auto shrink-0 text-muted-foreground/80 text-sm leading-none";
347 chevron.textContent = ">";
348 button.appendChild(chevron);
349 button.setAttribute("aria-haspopup", "menu");
350 button.setAttribute("aria-expanded", "false");
351 }
352
353 if (!isDisabled) {
354 let isHovered = false;
355 let isFocused = false;
356 const applyInteractionStyles = () => {
357 const isActive = isHovered || isFocused;
358 button.style.background = isActive
359 ? isLeafDestructive
360 ? "color-mix(in srgb, var(--destructive) 10%, transparent)"
361 : "var(--accent)"
362 : "transparent";
363 button.style.color = isActive
364 ? isLeafDestructive
365 ? "var(--destructive-foreground)"
366 : "var(--accent-foreground)"
367 : isLeafDestructive
368 ? "var(--destructive-foreground)"
369 : "var(--foreground)";
370 };
371 button.addEventListener("focus", () => {
372 isFocused = true;
373 applyInteractionStyles();
374 });
375 button.addEventListener("blur", () => {
376 isFocused = false;
377 applyInteractionStyles();
378 });
379 button.addEventListener("mouseenter", () => {
380 isHovered = true;
381 applyInteractionStyles();
382 });
383 button.addEventListener("mouseleave", () => {
384 isHovered = false;
385 applyInteractionStyles();
386 });
387
388 const openSubmenu = (shouldFocusFirst: boolean) => {
389 const rect = button.getBoundingClientRect();
390 openMenu(item.children!, rect.right + 4, rect.top, level + 1, shouldFocusFirst, button);
391
392 const childMenu = menuStack[level + 1];
393 if (!childMenu) {
394 button.setAttribute("aria-expanded", "false");
395 return;
396 }
397 button.setAttribute("aria-expanded", "true");
398 const childRect = childMenu.getBoundingClientRect();
399 if (childRect.right > window.innerWidth) {
400 clampMenuPosition(childMenu, rect.left - childRect.width - 4, rect.top);
401 }
402 };
403 buttonMetadata.set(button, { item, openSubmenu });
404
405 if (hasChildren) {
406 button.addEventListener("mouseenter", () => {
407 button.focus();
408 openSubmenu(false);
409 });
410 button.addEventListener("click", (event) => {
411 event.preventDefault();
412 openSubmenu(true);
413 });
414 } else {
415 button.addEventListener("mouseenter", () => {
416 button.focus();
417 closeMenusFromLevel(level + 1);
418 });
419 button.addEventListener("click", () => {
420 if (canDismissFromPointer) cleanup(item.id);
421 });
422 }
423 }
424
425 inner.appendChild(button);
426 }
427
428 menu.appendChild(inner);
429
430 menu.addEventListener("mouseenter", () => {
431 closeMenusFromLevel(level + 1);
432 });
433
434 document.body.appendChild(menu);
435 menuStack[level] = menu;
436
437 requestAnimationFrame(() => {
438 clampMenuPosition(menu, preferredLeft, preferredTop);
439 if (focusFirstItem) {
440 focusMenuItem(menu, 0);
441 }
442 });
443 };
444
445 document.addEventListener("keydown", onKeyDown);
446 document.addEventListener("pointerdown", onPointerDown, true);
447 document.addEventListener("contextmenu", onContextMenu, true);
448 openMenu(items, position?.x ?? 0, position?.y ?? 0, 0, true);
449
450 requestAnimationFrame(() => {
451 canDismissFromPointer = true;
452 });
453 });
454}