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 archive: [
8 { tag: "rect", attrs: { width: "20", height: "5", x: "2", y: "3", rx: "1" } },
9 { tag: "path", attrs: { d: "M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8" } },
10 { tag: "path", attrs: { d: "M10 12h4" } },
11 ],
12 "chevron-right": [{ tag: "path", attrs: { d: "m9 19 7-7-7-7" } }],
13 "circle-check": [
14 { tag: "circle", attrs: { cx: "12", cy: "12", r: "10" } },
15 { tag: "path", attrs: { d: "m9 12 2 2 4-4" } },
16 ],
17 clock: [
18 { tag: "path", attrs: { d: "M12 6v6l4 2" } },
19 { tag: "circle", attrs: { cx: "12", cy: "12", r: "10" } },
20 ],
21 pencil: [
22 {
23 tag: "path",
24 attrs: {
25 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",
26 },
27 },
28 { tag: "path", attrs: { d: "m15 5 4 4" } },
29 ],
30 copy: [
31 { tag: "rect", attrs: { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2" } },
32 { 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" } },
33 ],
34 folder: [
35 {
36 tag: "path",
37 attrs: {
38 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",
39 },
40 },
41 ],
42 "git-branch": [
43 { tag: "line", attrs: { x1: "6", x2: "6", y1: "3", y2: "15" } },
44 { tag: "circle", attrs: { cx: "18", cy: "6", r: "3" } },
45 { tag: "circle", attrs: { cx: "6", cy: "18", r: "3" } },
46 { tag: "path", attrs: { d: "M18 9a9 9 0 0 1-9 9" } },
47 ],
48 hash: [
49 { tag: "line", attrs: { x1: "4", x2: "20", y1: "9", y2: "9" } },
50 { tag: "line", attrs: { x1: "4", x2: "20", y1: "15", y2: "15" } },
51 { tag: "line", attrs: { x1: "10", x2: "8", y1: "3", y2: "21" } },
52 { tag: "line", attrs: { x1: "16", x2: "14", y1: "3", y2: "21" } },
53 ],
54 "mail-open": [
55 {
56 tag: "path",
57 attrs: {
58 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",
59 },
60 },
61 { tag: "path", attrs: { d: "m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10" } },
62 ],
63 "message-square-plus": [
64 {
65 tag: "path",
66 attrs: {
67 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",
68 },
69 },
70 { tag: "path", attrs: { d: "M12 8v6" } },
71 { tag: "path", attrs: { d: "M9 11h6" } },
72 ],
73 pin: [
74 { tag: "path", attrs: { d: "M12 17v5" } },
75 {
76 tag: "path",
77 attrs: {
78 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",
79 },
80 },
81 ],
82 "pin-off": [
83 { tag: "path", attrs: { d: "M12 17v5" } },
84 { tag: "path", attrs: { d: "M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89" } },
85 { tag: "path", attrs: { d: "m2 2 20 20" } },
86 {
87 tag: "path",
88 attrs: {
89 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",
90 },
91 },
92 ],
93 "refresh-cw": [
94 { tag: "path", attrs: { d: "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" } },
95 { tag: "path", attrs: { d: "M21 3v5h-5" } },
96 { tag: "path", attrs: { d: "M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" } },
97 { tag: "path", attrs: { d: "M8 16H3v5" } },
98 ],
99 settings: [
100 {
101 tag: "path",
102 attrs: {
103 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",
104 },
105 },
106 { tag: "circle", attrs: { cx: "12", cy: "12", r: "3" } },
107 ],
108 "folder-tree": [
109 {
110 tag: "path",
111 attrs: {
112 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",
113 },
114 },
115 {
116 tag: "path",
117 attrs: {
118 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",
119 },
120 },
121 { tag: "path", attrs: { d: "M3 5a2 2 0 0 0 2 2h3" } },
122 { tag: "path", attrs: { d: "M3 3v13a2 2 0 0 0 2 2h3" } },
123 ],
124 trash: [
125 { tag: "path", attrs: { d: "M3 6h18" } },
126 { tag: "path", attrs: { d: "M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" } },
127 { tag: "path", attrs: { d: "M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" } },
128 { tag: "line", attrs: { x1: "10", x2: "10", y1: "11", y2: "17" } },
129 { tag: "line", attrs: { x1: "14", x2: "14", y1: "11", y2: "17" } },
130 ],
131};
132
133function createIconElement(name: string, tone: "neutral" | "destructive"): SVGSVGElement | null {
134 const paths = ICON_PATHS[name];
135 if (!paths || typeof document.createElementNS !== "function") {
136 return null;
137 }
138 const svg = document.createElementNS(SVG_NS, "svg");
139 svg.setAttribute("xmlns", SVG_NS);
140 svg.setAttribute("viewBox", "0 0 24 24");
141 svg.setAttribute("fill", "none");
142 svg.setAttribute("stroke", "currentColor");
143 svg.setAttribute("stroke-width", "2");
144 svg.setAttribute("stroke-linecap", "round");
145 svg.setAttribute("stroke-linejoin", "round");
146 svg.setAttribute(
147 "class",
148 tone === "destructive"
149 ? "size-4.5 shrink-0 sm:size-4"
150 : "size-4.5 shrink-0 text-muted-foreground sm:size-4",
151 );
152 for (const node of paths) {
153 const child = document.createElementNS(SVG_NS, node.tag);
154 for (const [key, value] of Object.entries(node.attrs)) {
155 child.setAttribute(key, value);
156 }
157 svg.appendChild(child);
158 }
159 return svg;
160}
161
162function clampMenuPosition(menu: HTMLDivElement, preferredLeft: number, preferredTop: number) {
163 const rect = menu.getBoundingClientRect();
164 const left = Math.min(
165 Math.max(4, preferredLeft),
166 Math.max(4, window.innerWidth - rect.width - 4),
167 );
168 const top = Math.min(
169 Math.max(4, preferredTop),
170 Math.max(4, window.innerHeight - rect.height - 4),
171 );
172 menu.style.left = `${left}px`;
173 menu.style.top = `${top}px`;
174}
175
176function isNodeWithinMenuStack(target: EventTarget | null, menuStack: readonly HTMLDivElement[]) {
177 if (typeof Node !== "undefined" && target instanceof Node) {
178 return menuStack.some((menu) => menu.contains(target));
179 }
180 if (!target || typeof target !== "object") {
181 return false;
182 }
183
184 let current: unknown = target;
185 while (current && typeof current === "object") {
186 if (menuStack.includes(current as HTMLDivElement)) {
187 return true;
188 }
189 current = (current as { parent?: unknown }).parent;
190 }
191 return false;
192}
193
194// Only one fallback menu exists at a time in the renderer; the active one is
195// tracked so a state change (for example a terminal selection clearing) can
196// dismiss it with the same result as an outside click or Escape.
197let activeContextMenuDismiss: (() => void) | null = null;
198
199export function isContextMenuOpen(): boolean {
200 return activeContextMenuDismiss !== null;
201}
202
203/**
204 * Closes the currently open fallback context menu, resolving its show() with
205 * null (the same result as dismissing by outside click or Escape). No-op when
206 * no fallback menu is open.
207 */
208export function dismissContextMenu(): void {
209 activeContextMenuDismiss?.();
210 activeContextMenuDismiss = null;
211}
212
213/**
214 * Imperative DOM-based context menu for non-Electron environments.
215 * Supports nested submenus and resolves with the clicked leaf item id.
216 */
217export function showContextMenuFallback<T extends string>(
218 items: readonly ContextMenuItem<T>[],
219 position?: { x: number; y: number },
220): Promise<T | null> {
221 return new Promise<T | null>((resolve) => {
222 const previouslyFocusedElement =
223 document.activeElement instanceof HTMLElement ? document.activeElement : null;
224 const menuStack: HTMLDivElement[] = [];
225 const submenuTriggerStack: Array<HTMLButtonElement | undefined> = [];
226 let isDisposed = false;
227 let canDismissFromPointer = false;
228
229 const dismiss = () => cleanup(null);
230
231 const cleanup = (result: T | null) => {
232 if (isDisposed) {
233 return;
234 }
235 isDisposed = true;
236 if (activeContextMenuDismiss === dismiss) {
237 activeContextMenuDismiss = null;
238 }
239 document.removeEventListener("keydown", onKeyDown);
240 document.removeEventListener("pointerdown", onPointerDown, true);
241 document.removeEventListener("contextmenu", onContextMenu, true);
242 const shouldRestoreFocus = isNodeWithinMenuStack(document.activeElement, menuStack);
243 for (const menu of menuStack) {
244 menu.remove();
245 }
246 if (shouldRestoreFocus && previouslyFocusedElement?.isConnected) {
247 previouslyFocusedElement.focus({ preventScroll: true });
248 }
249 resolve(result);
250 };
251
252 const onKeyDown = (event: KeyboardEvent) => {
253 if (event.key === "Escape") {
254 event.preventDefault();
255 cleanup(null);
256 }
257 };
258
259 const onPointerDown = (event: PointerEvent) => {
260 if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {
261 return;
262 }
263 cleanup(null);
264 };
265
266 const onContextMenu = (event: MouseEvent) => {
267 if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {
268 return;
269 }
270 event.preventDefault();
271 cleanup(null);
272 };
273
274 const closeMenusFromLevel = (level: number) => {
275 while (menuStack.length > level) {
276 submenuTriggerStack.pop()?.setAttribute("aria-expanded", "false");
277 menuStack.pop()?.remove();
278 }
279 };
280
281 const openMenu = (
282 entries: readonly ContextMenuItem<T>[],
283 preferredLeft: number,
284 preferredTop: number,
285 level: number,
286 parentTrigger?: HTMLButtonElement,
287 ) => {
288 closeMenusFromLevel(level);
289
290 const menu = document.createElement("div");
291 menu.className =
292 "dropdown-glass fixed z-[10000] min-w-32 max-w-sm overflow-hidden rounded-lg bg-clip-padding text-popover-foreground outline-none";
293 menu.style.cssText =
294 "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;";
295 menu.style.left = `${preferredLeft}px`;
296 menu.style.top = `${preferredTop}px`;
297 menu.dataset.level = String(level);
298
299 const inner = document.createElement("div");
300 inner.className =
301 "max-h-[min(24rem,70vh)] min-w-0 max-w-sm overflow-y-auto overflow-x-hidden p-1";
302 inner.style.cssText =
303 "max-height:min(24rem,70vh);min-width:0;max-width:24rem;overflow-x:hidden;overflow-y:auto;padding:0.25rem;";
304
305 for (const item of entries) {
306 if (item.separatorBefore === true && inner.children.length > 0) {
307 const separator = document.createElement("div");
308 separator.className = "mx-2 my-1 h-px bg-border";
309 separator.style.cssText =
310 "height:1px;margin:0.25rem 0.5rem;background:var(--contrast-border);";
311 separator.dataset.contextMenuSeparator = "true";
312 separator.setAttribute("role", "separator");
313 inner.appendChild(separator);
314 }
315
316 if (item.header === true) {
317 const header = document.createElement("div");
318 header.className = "px-2 py-1.5 font-medium text-muted-foreground text-xs";
319 header.textContent = item.label;
320 inner.appendChild(header);
321 continue;
322 }
323
324 const hasChildren = Array.isArray(item.children) && item.children.length > 0;
325 const isLeafDestructive =
326 !hasChildren && (item.destructive === true || item.id === ("delete" as T));
327
328 const button = document.createElement("button");
329 button.type = "button";
330 const isDisabled = item.disabled === true;
331 button.disabled = isDisabled;
332 const rowBase =
333 "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";
334 button.className = isDisabled
335 ? `${rowBase} pointer-events-none cursor-not-allowed text-muted-foreground opacity-64`
336 : isLeafDestructive
337 ? `${rowBase} text-destructive-foreground hover:bg-destructive/10 hover:text-destructive-foreground`
338 : `${rowBase} text-foreground hover:bg-accent hover:text-accent-foreground`;
339 button.style.cssText =
340 "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;";
341 if (isLeafDestructive) {
342 button.style.color = "var(--destructive-foreground)";
343 }
344 if (isDisabled) {
345 button.style.color = "var(--contrast-muted-foreground)";
346 button.style.opacity = "0.64";
347 button.style.pointerEvents = "none";
348 }
349
350 if (typeof item.icon === "string") {
351 const icon = createIconElement(item.icon, isLeafDestructive ? "destructive" : "neutral");
352 if (icon) {
353 button.appendChild(icon);
354 }
355 }
356
357 const label = document.createElement("span");
358 label.className = "min-w-0 flex-1 truncate";
359 label.textContent = item.label;
360 button.appendChild(label);
361
362 if (hasChildren) {
363 button.setAttribute("aria-haspopup", "menu");
364 button.setAttribute("aria-expanded", "false");
365 const chevron = createIconElement("chevron-right", "neutral");
366 if (chevron) {
367 chevron.setAttribute(
368 "class",
369 "-me-0.5 ms-auto size-4.5 shrink-0 text-muted-foreground opacity-80 sm:size-4",
370 );
371 chevron.setAttribute("aria-hidden", "true");
372 chevron.dataset.contextMenuChevron = "true";
373 button.appendChild(chevron);
374 }
375 }
376
377 if (!isDisabled) {
378 let isHovered = false;
379 let isFocused = false;
380 const updateHighlight = () => {
381 const isHighlighted = isHovered || isFocused;
382 button.style.background = isHighlighted
383 ? isLeafDestructive
384 ? "color-mix(in srgb, var(--destructive) 10%, transparent)"
385 : "var(--accent)"
386 : "transparent";
387 button.style.color = isHighlighted
388 ? isLeafDestructive
389 ? "var(--destructive-foreground)"
390 : "var(--contrast-accent-foreground)"
391 : isLeafDestructive
392 ? "var(--destructive-foreground)"
393 : "var(--contrast-foreground)";
394 };
395 button.addEventListener("mouseenter", () => {
396 button.focus({ preventScroll: true });
397 isHovered = true;
398 updateHighlight();
399 });
400 button.addEventListener("mouseleave", () => {
401 isHovered = false;
402 updateHighlight();
403 });
404 button.addEventListener("focus", () => {
405 isFocused = true;
406 updateHighlight();
407 });
408 button.addEventListener("blur", () => {
409 isFocused = false;
410 updateHighlight();
411 });
412
413 if (hasChildren) {
414 const openSubmenu = (focusFirstItem = false) => {
415 const rect = button.getBoundingClientRect();
416 const nextLeft = rect.right + 4;
417 const nextTop = rect.top;
418 openMenu(item.children!, nextLeft, nextTop, level + 1, button);
419 button.setAttribute("aria-expanded", "true");
420
421 const childMenu = menuStack[level + 1];
422 if (!childMenu) {
423 return;
424 }
425 const childRect = childMenu.getBoundingClientRect();
426 if (childRect.right > window.innerWidth) {
427 clampMenuPosition(childMenu, rect.left - childRect.width - 4, rect.top);
428 }
429 if (focusFirstItem) {
430 [...childMenu.querySelectorAll<HTMLButtonElement>("button")]
431 .find((childButton) => !childButton.disabled)
432 ?.focus();
433 }
434 };
435 button.addEventListener("mouseenter", () => {
436 openSubmenu();
437 });
438 button.addEventListener("click", (event) => {
439 event.preventDefault();
440 openSubmenu(true);
441 });
442 } else {
443 button.addEventListener("mouseenter", () => {
444 closeMenusFromLevel(level + 1);
445 });
446 button.addEventListener("click", () => {
447 if (canDismissFromPointer) cleanup(item.id);
448 });
449 }
450 }
451
452 inner.appendChild(button);
453 }
454
455 menu.appendChild(inner);
456
457 menu.addEventListener("mouseenter", () => {
458 closeMenusFromLevel(level + 1);
459 });
460
461 document.body.appendChild(menu);
462 menuStack[level] = menu;
463 submenuTriggerStack[level] = parentTrigger;
464
465 requestAnimationFrame(() => {
466 clampMenuPosition(menu, preferredLeft, preferredTop);
467 });
468 };
469
470 document.addEventListener("keydown", onKeyDown);
471 document.addEventListener("pointerdown", onPointerDown, true);
472 document.addEventListener("contextmenu", onContextMenu, true);
473 openMenu(items, position?.x ?? 0, position?.y ?? 0, 0);
474 // Only one fallback menu can be open at a time: a new show must dismiss
475 // any prior one, or its DOM and listeners leak and close() can only ever
476 // reach the newest menu.
477 if (activeContextMenuDismiss) {
478 activeContextMenuDismiss();
479 }
480 activeContextMenuDismiss = dismiss;
481
482 requestAnimationFrame(() => {
483 canDismissFromPointer = true;
484 });
485 });
486}