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

contextMenuFallback.ts

472 lines17.3 KB

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