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