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// Only one fallback menu exists at a time in the renderer; the active one is
105// tracked so a state change (for example a terminal selection clearing) can
106// dismiss it with the same result as an outside click or Escape.
107let activeContextMenuDismiss: (() => void) | null = null;
108
109/**
110 * Closes the currently open fallback context menu, resolving its show() with
111 * null (the same result as dismissing by outside click or Escape). No-op when
112 * no fallback menu is open.
113 */
114export function dismissContextMenu(): void {
115 activeContextMenuDismiss?.();
116 activeContextMenuDismiss = null;
117}
118
119/**
120 * Imperative DOM-based context menu for non-Electron environments.
121 * Supports nested submenus and resolves with the clicked leaf item id.
122 */
123export function showContextMenuFallback<T extends string>(
124 items: readonly ContextMenuItem<T>[],
125 position?: { x: number; y: number },
126): Promise<T | null> {
127 return new Promise<T | null>((resolve) => {
128 const menuStack: HTMLDivElement[] = [];
129 let isDisposed = false;
130 let canDismissFromPointer = false;
131
132 const dismiss = () => cleanup(null);
133
134 const cleanup = (result: T | null) => {
135 if (isDisposed) {
136 return;
137 }
138 isDisposed = true;
139 if (activeContextMenuDismiss === dismiss) {
140 activeContextMenuDismiss = null;
141 }
142 document.removeEventListener("keydown", onKeyDown);
143 document.removeEventListener("pointerdown", onPointerDown, true);
144 document.removeEventListener("contextmenu", onContextMenu, true);
145 for (const menu of menuStack) {
146 menu.remove();
147 }
148 resolve(result);
149 };
150
151 const onKeyDown = (event: KeyboardEvent) => {
152 if (event.key === "Escape") {
153 event.preventDefault();
154 cleanup(null);
155 }
156 };
157
158 const onPointerDown = (event: PointerEvent) => {
159 if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {
160 return;
161 }
162 cleanup(null);
163 };
164
165 const onContextMenu = (event: MouseEvent) => {
166 if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {
167 return;
168 }
169 event.preventDefault();
170 cleanup(null);
171 };
172
173 const closeMenusFromLevel = (level: number) => {
174 while (menuStack.length > level) {
175 menuStack.pop()?.remove();
176 }
177 };
178
179 const openMenu = (
180 entries: readonly ContextMenuItem<T>[],
181 preferredLeft: number,
182 preferredTop: number,
183 level: number,
184 ) => {
185 closeMenusFromLevel(level);
186
187 const menu = document.createElement("div");
188 menu.className =
189 "dropdown-glass fixed z-[10000] min-w-32 max-w-sm overflow-hidden rounded-lg bg-clip-padding text-popover-foreground outline-none";
190 menu.style.cssText =
191 "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;";
192 menu.style.left = `${preferredLeft}px`;
193 menu.style.top = `${preferredTop}px`;
194 menu.dataset.level = String(level);
195
196 const inner = document.createElement("div");
197 inner.className =
198 "max-h-[min(24rem,70vh)] min-w-0 max-w-sm overflow-y-auto overflow-x-hidden p-1";
199 inner.style.cssText =
200 "max-height:min(24rem,70vh);min-width:0;max-width:24rem;overflow-x:hidden;overflow-y:auto;padding:0.25rem;";
201
202 for (const item of entries) {
203 if (item.header === true) {
204 const header = document.createElement("div");
205 header.className = "px-2 py-1.5 font-medium text-muted-foreground text-xs";
206 header.textContent = item.label;
207 inner.appendChild(header);
208 continue;
209 }
210
211 const hasChildren = Array.isArray(item.children) && item.children.length > 0;
212 const isLeafDestructive =
213 !hasChildren && (item.destructive === true || item.id === ("delete" as T));
214
215 const button = document.createElement("button");
216 button.type = "button";
217 const isDisabled = item.disabled === true;
218 button.disabled = isDisabled;
219 const rowBase =
220 "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";
221 button.className = isDisabled
222 ? `${rowBase} pointer-events-none cursor-not-allowed text-muted-foreground opacity-64`
223 : isLeafDestructive
224 ? `${rowBase} text-destructive-foreground hover:bg-destructive/10 hover:text-destructive-foreground`
225 : `${rowBase} text-foreground hover:bg-accent hover:text-accent-foreground`;
226 button.style.cssText =
227 "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;";
228 if (isLeafDestructive) {
229 button.style.color = "var(--destructive-foreground)";
230 }
231 if (isDisabled) {
232 button.style.color = "var(--muted-foreground)";
233 button.style.opacity = "0.64";
234 button.style.pointerEvents = "none";
235 }
236
237 if (typeof item.icon === "string") {
238 const icon = createIconElement(item.icon, isLeafDestructive ? "destructive" : "neutral");
239 if (icon) {
240 button.appendChild(icon);
241 }
242 }
243
244 const label = document.createElement("span");
245 label.className = "min-w-0 flex-1 truncate";
246 label.textContent = item.label;
247 button.appendChild(label);
248
249 if (hasChildren) {
250 const chevron = document.createElement("span");
251 chevron.className = "ms-auto shrink-0 text-muted-foreground/80 text-sm leading-none";
252 chevron.textContent = ">";
253 button.appendChild(chevron);
254 }
255
256 if (!isDisabled) {
257 button.addEventListener("mouseenter", () => {
258 button.style.background = isLeafDestructive
259 ? "color-mix(in srgb, var(--destructive) 10%, transparent)"
260 : "var(--accent)";
261 button.style.color = isLeafDestructive
262 ? "var(--destructive-foreground)"
263 : "var(--accent-foreground)";
264 });
265 button.addEventListener("mouseleave", () => {
266 button.style.background = "transparent";
267 button.style.color = isLeafDestructive
268 ? "var(--destructive-foreground)"
269 : "var(--foreground)";
270 });
271
272 if (hasChildren) {
273 button.addEventListener("mouseenter", () => {
274 const rect = button.getBoundingClientRect();
275 const nextLeft = rect.right + 4;
276 const nextTop = rect.top;
277 openMenu(item.children!, nextLeft, nextTop, level + 1);
278
279 const childMenu = menuStack[level + 1];
280 if (!childMenu) {
281 return;
282 }
283 const childRect = childMenu.getBoundingClientRect();
284 if (childRect.right > window.innerWidth) {
285 clampMenuPosition(childMenu, rect.left - childRect.width - 4, rect.top);
286 }
287 });
288 button.addEventListener("click", (event) => {
289 event.preventDefault();
290 });
291 } else {
292 button.addEventListener("mouseenter", () => {
293 closeMenusFromLevel(level + 1);
294 });
295 button.addEventListener("click", () => {
296 if (canDismissFromPointer) cleanup(item.id);
297 });
298 }
299 }
300
301 inner.appendChild(button);
302 }
303
304 menu.appendChild(inner);
305
306 menu.addEventListener("mouseenter", () => {
307 closeMenusFromLevel(level + 1);
308 });
309
310 document.body.appendChild(menu);
311 menuStack[level] = menu;
312
313 requestAnimationFrame(() => {
314 clampMenuPosition(menu, preferredLeft, preferredTop);
315 });
316 };
317
318 document.addEventListener("keydown", onKeyDown);
319 document.addEventListener("pointerdown", onPointerDown, true);
320 document.addEventListener("contextmenu", onContextMenu, true);
321 openMenu(items, position?.x ?? 0, position?.y ?? 0, 0);
322 // Only one fallback menu can be open at a time: a new show must dismiss
323 // any prior one, or its DOM and listeners leak and close() can only ever
324 // reach the newest menu.
325 if (activeContextMenuDismiss) {
326 activeContextMenuDismiss();
327 }
328 activeContextMenuDismiss = dismiss;
329
330 requestAnimationFrame(() => {
331 canDismissFromPointer = true;
332 });
333 });
334}