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

contextMenuFallback.ts

473 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(--contrast-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 =
297 "height:1px;margin:0.25rem 0.5rem;background:var(--contrast-border);";
298 separator.dataset.contextMenuSeparator = "true";
299 separator.setAttribute("role", "separator");
300 inner.appendChild(separator);
301 }
302​
303 if (item.header === true) {
304 const header = document.createElement("div");
305 header.className = "px-2 py-1.5 font-medium text-muted-foreground text-xs";
306 header.textContent = item.label;
307 inner.appendChild(header);
308 continue;
309 }
310​
311 const hasChildren = Array.isArray(item.children) && item.children.length > 0;
312 const isLeafDestructive =
313 !hasChildren && (item.destructive === true || item.id === ("delete" as T));
314​
315 const button = document.createElement("button");
316 button.type = "button";
317 const isDisabled = item.disabled === true;
318 button.disabled = isDisabled;
319 const rowBase =
320 "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";
321 button.className = isDisabled
322 ? `${rowBase} pointer-events-none cursor-not-allowed text-muted-foreground opacity-64`
323 : isLeafDestructive
324 ? `${rowBase} text-destructive-foreground hover:bg-destructive/10 hover:text-destructive-foreground`
325 : `${rowBase} text-foreground hover:bg-accent hover:text-accent-foreground`;
326 button.style.cssText =
327 "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;";
328 if (isLeafDestructive) {
329 button.style.color = "var(--destructive-foreground)";
330 }
331 if (isDisabled) {
332 button.style.color = "var(--contrast-muted-foreground)";
333 button.style.opacity = "0.64";
334 button.style.pointerEvents = "none";
335 }
336​
337 if (typeof item.icon === "string") {
338 const icon = createIconElement(item.icon, isLeafDestructive ? "destructive" : "neutral");
339 if (icon) {
340 button.appendChild(icon);
341 }
342 }
343​
344 const label = document.createElement("span");
345 label.className = "min-w-0 flex-1 truncate";
346 label.textContent = item.label;
347 button.appendChild(label);
348​
349 if (hasChildren) {
350 button.setAttribute("aria-haspopup", "menu");
351 button.setAttribute("aria-expanded", "false");
352 const chevron = createIconElement("chevron-right", "neutral");
353 if (chevron) {
354 chevron.setAttribute(
355 "class",
356 "-me-0.5 ms-auto size-4.5 shrink-0 text-muted-foreground opacity-80 sm:size-4",
357 );
358 chevron.setAttribute("aria-hidden", "true");
359 chevron.dataset.contextMenuChevron = "true";
360 button.appendChild(chevron);
361 }
362 }
363​
364 if (!isDisabled) {
365 let isHovered = false;
366 let isFocused = false;
367 const updateHighlight = () => {
368 const isHighlighted = isHovered || isFocused;
369 button.style.background = isHighlighted
370 ? isLeafDestructive
371 ? "color-mix(in srgb, var(--destructive) 10%, transparent)"
372 : "var(--accent)"
373 : "transparent";
374 button.style.color = isHighlighted
375 ? isLeafDestructive
376 ? "var(--destructive-foreground)"
377 : "var(--contrast-accent-foreground)"
378 : isLeafDestructive
379 ? "var(--destructive-foreground)"
380 : "var(--contrast-foreground)";
381 };
382 button.addEventListener("mouseenter", () => {
383 button.focus({ preventScroll: true });
384 isHovered = true;
385 updateHighlight();
386 });
387 button.addEventListener("mouseleave", () => {
388 isHovered = false;
389 updateHighlight();
390 });
391 button.addEventListener("focus", () => {
392 isFocused = true;
393 updateHighlight();
394 });
395 button.addEventListener("blur", () => {
396 isFocused = false;
397 updateHighlight();
398 });
399​
400 if (hasChildren) {
401 const openSubmenu = (focusFirstItem = false) => {
402 const rect = button.getBoundingClientRect();
403 const nextLeft = rect.right + 4;
404 const nextTop = rect.top;
405 openMenu(item.children!, nextLeft, nextTop, level + 1, button);
406 button.setAttribute("aria-expanded", "true");
407​
408 const childMenu = menuStack[level + 1];
409 if (!childMenu) {
410 return;
411 }
412 const childRect = childMenu.getBoundingClientRect();
413 if (childRect.right > window.innerWidth) {
414 clampMenuPosition(childMenu, rect.left - childRect.width - 4, rect.top);
415 }
416 if (focusFirstItem) {
417 [...childMenu.querySelectorAll<HTMLButtonElement>("button")]
418 .find((childButton) => !childButton.disabled)
419 ?.focus();
420 }
421 };
422 button.addEventListener("mouseenter", () => {
423 openSubmenu();
424 });
425 button.addEventListener("click", (event) => {
426 event.preventDefault();
427 openSubmenu(true);
428 });
429 } else {
430 button.addEventListener("mouseenter", () => {
431 closeMenusFromLevel(level + 1);
432 });
433 button.addEventListener("click", () => {
434 if (canDismissFromPointer) cleanup(item.id);
435 });
436 }
437 }
438​
439 inner.appendChild(button);
440 }
441​
442 menu.appendChild(inner);
443​
444 menu.addEventListener("mouseenter", () => {
445 closeMenusFromLevel(level + 1);
446 });
447​
448 document.body.appendChild(menu);
449 menuStack[level] = menu;
450 submenuTriggerStack[level] = parentTrigger;
451​
452 requestAnimationFrame(() => {
453 clampMenuPosition(menu, preferredLeft, preferredTop);
454 });
455 };
456​
457 document.addEventListener("keydown", onKeyDown);
458 document.addEventListener("pointerdown", onPointerDown, true);
459 document.addEventListener("contextmenu", onContextMenu, true);
460 openMenu(items, position?.x ?? 0, position?.y ?? 0, 0);
461 // Only one fallback menu can be open at a time: a new show must dismiss
462 // any prior one, or its DOM and listeners leak and close() can only ever
463 // reach the newest menu.
464 if (activeContextMenuDismiss) {
465 activeContextMenuDismiss();
466 }
467 activeContextMenuDismiss = dismiss;
468​
469 requestAnimationFrame(() => {
470 canDismissFromPointer = true;
471 });
472 });