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

contextMenuFallback.ts

74 lines2.6 KB

1import type { ContextMenuItem } from "@t3tools/contracts";
2​
3/**
4 * Imperative DOM-based context menu for non-Electron environments.
5 * Shows a positioned dropdown and returns a promise that resolves
6 * with the clicked item id, or null if dismissed.
7 */
8export function showContextMenuFallback<T extends string>(
9 items: readonly ContextMenuItem<T>[],
10 position?: { x: number; y: number },
11): Promise<T | null> {
12 return new Promise<T | null>((resolve) => {
13 const overlay = document.createElement("div");
14 overlay.style.cssText = "position:fixed;inset:0;z-index:9999";
15​
16 const menu = document.createElement("div");
17 menu.className =
18 "fixed z-[10000] min-w-[140px] rounded-md border border-border bg-popover py-1 shadow-xl animate-in fade-in zoom-in-95";
19​
20 const x = position?.x ?? 0;
21 const y = position?.y ?? 0;
22 menu.style.top = `${y}px`;
23 menu.style.left = `${x}px`;
24​
25 function cleanup(result: T | null) {
26 document.removeEventListener("keydown", onKeyDown);
27 overlay.remove();
28 menu.remove();
29 resolve(result);
30 }
31​
32 function onKeyDown(e: KeyboardEvent) {
33 if (e.key === "Escape") {
34 e.preventDefault();
35 cleanup(null);
36 }
37 }
38​
39 overlay.addEventListener("mousedown", () => cleanup(null));
40 document.addEventListener("keydown", onKeyDown);
41​
42 for (const item of items) {
43 const btn = document.createElement("button");
44 btn.type = "button";
45 btn.textContent = item.label;
46 const isDestructiveAction = item.destructive === true || item.id === "delete";
47 const isDisabled = item.disabled === true;
48 btn.disabled = isDisabled;
49 btn.className = isDisabled
50 ? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-muted-foreground/60 cursor-not-allowed"
51 : isDestructiveAction
52 ? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
53 : "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
54 if (!isDisabled) {
55 btn.addEventListener("click", () => cleanup(item.id));
56 }
57 menu.appendChild(btn);
58 }
59​
60 document.body.appendChild(overlay);
61 document.body.appendChild(menu);
62​
63 // Adjust if menu overflows viewport
64 requestAnimationFrame(() => {
65 const rect = menu.getBoundingClientRect();
66 if (rect.right > window.innerWidth) {
67 menu.style.left = `${window.innerWidth - rect.width - 4}px`;
68 }
69 if (rect.bottom > window.innerHeight) {
70 menu.style.top = `${window.innerHeight - rect.height - 4}px`;
71 }
72 });
73 });