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

contextMenuFallback.ts

142 lines4.9 KB

1import type { ContextMenuItem } from "@t3tools/contracts";
2​
3function clampMenuPosition(menu: HTMLDivElement, preferredLeft: number, preferredTop: number) {
4 const rect = menu.getBoundingClientRect();
5 const left = Math.min(
6 Math.max(4, preferredLeft),
7 Math.max(4, window.innerWidth - rect.width - 4),
8 );
9 const top = Math.min(
10 Math.max(4, preferredTop),
11 Math.max(4, window.innerHeight - rect.height - 4),
12 );
13 menu.style.left = `${left}px`;
14 menu.style.top = `${top}px`;
16​
17/**
18 * Imperative DOM-based context menu for non-Electron environments.
19 * Supports nested submenus and resolves with the clicked leaf item id.
20 */
21export function showContextMenuFallback<T extends string>(
22 items: readonly ContextMenuItem<T>[],
23 position?: { x: number; y: number },
24): Promise<T | null> {
25 return new Promise<T | null>((resolve) => {
26 const overlay = document.createElement("div");
27 overlay.style.cssText = "position:fixed;inset:0;z-index:9999";
28​
29 const menuStack: HTMLDivElement[] = [];
30​
31 const cleanup = (result: T | null) => {
32 document.removeEventListener("keydown", onKeyDown);
33 overlay.remove();
34 for (const menu of menuStack) {
35 menu.remove();
36 }
37 resolve(result);
38 };
39​
40 const onKeyDown = (event: KeyboardEvent) => {
41 if (event.key === "Escape") {
42 event.preventDefault();
43 cleanup(null);
44 }
45 };
46​
47 const closeMenusFromLevel = (level: number) => {
48 while (menuStack.length > level) {
49 menuStack.pop()?.remove();
50 }
51 };
52​
53 const openMenu = (
54 entries: readonly ContextMenuItem<T>[],
55 preferredLeft: number,
56 preferredTop: number,
57 level: number,
58 ) => {
59 closeMenusFromLevel(level);
60​
61 const menu = document.createElement("div");
62 menu.className =
63 "fixed z-[10000] min-w-[160px] rounded-md border border-border bg-popover py-1 shadow-xl animate-in fade-in zoom-in-95";
64 menu.style.left = `${preferredLeft}px`;
65 menu.style.top = `${preferredTop}px`;
66 menu.dataset.level = String(level);
67​
68 for (const item of entries) {
69 const button = document.createElement("button");
70 button.type = "button";
71 const hasChildren = Array.isArray(item.children) && item.children.length > 0;
72 const isLeafDestructive =
73 !hasChildren && (item.destructive === true || item.id === ("delete" as T));
74 const isDisabled = item.disabled === true;
75 button.disabled = isDisabled;
76 button.className = isDisabled
77 ? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-muted-foreground/60 cursor-not-allowed"
78 : isLeafDestructive
79 ? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
80 : "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
81​
82 const label = document.createElement("span");
83 label.className = "min-w-0 flex-1 truncate";
84 label.textContent = item.label;
85 button.appendChild(label);
86​
87 if (hasChildren) {
88 const chevron = document.createElement("span");
89 chevron.className = "shrink-0 text-muted-foreground/70";
90 chevron.textContent = "›";
91 button.appendChild(chevron);
92 }
93​
94 if (!isDisabled) {
95 if (hasChildren) {
96 button.addEventListener("mouseenter", () => {
97 const rect = button.getBoundingClientRect();
98 const nextLeft = rect.right + 4;
99 const nextTop = rect.top;
100 openMenu(item.children!, nextLeft, nextTop, level + 1);
101​
102 const childMenu = menuStack[level + 1];
103 if (!childMenu) {
104 return;
105 }
106 const childRect = childMenu.getBoundingClientRect();
107 if (childRect.right > window.innerWidth) {
108 clampMenuPosition(childMenu, rect.left - childRect.width - 4, rect.top);
109 }
110 });
111 button.addEventListener("click", (event) => {
112 event.preventDefault();
113 });
114 } else {
115 button.addEventListener("mouseenter", () => {
116 closeMenusFromLevel(level + 1);
117 });
118 button.addEventListener("click", () => cleanup(item.id));
119 }
120 }
121​
122 menu.appendChild(button);
123 }
124​
125 menu.addEventListener("mouseenter", () => {
126 closeMenusFromLevel(level + 1);
127 });
128​
129 document.body.appendChild(menu);
130 menuStack[level] = menu;
131​
132 requestAnimationFrame(() => {
133 clampMenuPosition(menu, preferredLeft, preferredTop);
134 });
135 };
136​
137 overlay.addEventListener("mousedown", () => cleanup(null));
138 document.addEventListener("keydown", onKeyDown);
139 document.body.appendChild(overlay);
140 openMenu(items, position?.x ?? 0, position?.y ?? 0, 0);
141 });