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

contextMenuFallback.ts

66 lines2.3 KB

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