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

contextMenuFallback.ts

64 lines2.1 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 btn.className =
45 "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default";
46 btn.addEventListener("click", () => cleanup(item.id));
47 menu.appendChild(btn);
48 }
49​
50 document.body.appendChild(overlay);
51 document.body.appendChild(menu);
52​
53 // Adjust if menu overflows viewport
54 requestAnimationFrame(() => {
55 const rect = menu.getBoundingClientRect();
56 if (rect.right > window.innerWidth) {
57 menu.style.left = `${window.innerWidth - rect.width - 4}px`;
58 }
59 if (rect.bottom > window.innerHeight) {
60 menu.style.top = `${window.innerHeight - rect.height - 4}px`;
61 }
62 });
63 });