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

contextMenuFallback.ts

496 lines18.7 KB

1import type { ContextMenuItem } from "@t3tools/contracts";
2​
3const SVG_NS = "http://www.w3.org/2000/svg";
4​
5const ICON_PATHS: Record<string, ReadonlyArray<{ tag: string; attrs: Record<string, string> }>> = {
6 archive: [
7 { tag: "rect", attrs: { width: "20", height: "5", x: "2", y: "3", rx: "1" } },
8 { tag: "path", attrs: { d: "M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8" } },
9 { tag: "path", attrs: { d: "M10 12h4" } },
10 ],
11 check: [{ tag: "path", attrs: { d: "M20 6 9 17l-5-5" } }],
12 timer: [
13 { tag: "line", attrs: { x1: "10", x2: "14", y1: "2", y2: "2" } },
14 { tag: "line", attrs: { x1: "12", x2: "15", y1: "14", y2: "11" } },
15 { tag: "circle", attrs: { cx: "12", cy: "14", r: "8" } },
16 ],
17 "chevron-right": [{ tag: "path", attrs: { d: "m9 19 7-7-7-7" } }],
18 "circle-check": [
19 { tag: "circle", attrs: { cx: "12", cy: "12", r: "10" } },
20 { tag: "path", attrs: { d: "m9 12 2 2 4-4" } },
21 ],
22 clock: [
23 { tag: "path", attrs: { d: "M12 6v6l4 2" } },
24 { tag: "circle", attrs: { cx: "12", cy: "12", r: "10" } },
25 ],
26 pencil: [
27 {
28 tag: "path",
29 attrs: {
30 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",
31 },
32 },
33 { tag: "path", attrs: { d: "m15 5 4 4" } },
34 ],
35 copy: [
36 { tag: "rect", attrs: { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2" } },
37 { 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" } },
38 ],
39 folder: [
40 {
41 tag: "path",
42 attrs: {
43 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",
44 },
45 },
46 ],
47 "git-branch": [
48 { tag: "line", attrs: { x1: "6", x2: "6", y1: "3", y2: "15" } },
49 { tag: "circle", attrs: { cx: "18", cy: "6", r: "3" } },
50 { tag: "circle", attrs: { cx: "6", cy: "18", r: "3" } },
51 { tag: "path", attrs: { d: "M18 9a9 9 0 0 1-9 9" } },
52 ],
53 hash: [
54 { tag: "line", attrs: { x1: "4", x2: "20", y1: "9", y2: "9" } },
55 { tag: "line", attrs: { x1: "4", x2: "20", y1: "15", y2: "15" } },
56 { tag: "line", attrs: { x1: "10", x2: "8", y1: "3", y2: "21" } },
57 { tag: "line", attrs: { x1: "16", x2: "14", y1: "3", y2: "21" } },
58 ],
59 "mail-open": [
60 {
61 tag: "path",
62 attrs: {
63 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",
64 },
65 },
66 { tag: "path", attrs: { d: "m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10" } },
67 ],
68 "message-square-plus": [
69 {
70 tag: "path",
71 attrs: {
72 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",
73 },
74 },
75 { tag: "path", attrs: { d: "M12 8v6" } },
76 { tag: "path", attrs: { d: "M9 11h6" } },
77 ],
78 pin: [
79 { tag: "path", attrs: { d: "M12 17v5" } },
80 {
81 tag: "path",
82 attrs: {
83 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",
84 },
85 },
86 ],
87 "pin-off": [
88 { tag: "path", attrs: { d: "M12 17v5" } },
89 { tag: "path", attrs: { d: "M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89" } },
90 { tag: "path", attrs: { d: "m2 2 20 20" } },
91 {
92 tag: "path",
93 attrs: {
94 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",
95 },
96 },
97 ],
98 "refresh-cw": [
99 { tag: "path", attrs: { d: "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" } },
100 { tag: "path", attrs: { d: "M21 3v5h-5" } },
101 { tag: "path", attrs: { d: "M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" } },
102 { tag: "path", attrs: { d: "M8 16H3v5" } },
103 ],
104 settings: [
105 {
106 tag: "path",
107 attrs: {
108 d: "M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.38a2 2 0 0 0-.73-2.73l-.15-.09a2 2 0 0 1-1-1.74v-.51a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",
109 },
110 },
111 { tag: "circle", attrs: { cx: "12", cy: "12", r: "3" } },
112 ],
113 "user-plus": [
114 { tag: "path", attrs: { d: "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" } },
115 { tag: "circle", attrs: { cx: "9", cy: "7", r: "4" } },
116 { tag: "line", attrs: { x1: "19", x2: "19", y1: "8", y2: "14" } },
117 { tag: "line", attrs: { x1: "22", x2: "16", y1: "11", y2: "11" } },
118 ],
119 "folder-tree": [
120 {
121 tag: "path",
122 attrs: {
123 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",
124 },
125 },
126 {
127 tag: "path",
128 attrs: {
129 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",
130 },
131 },
132 { tag: "path", attrs: { d: "M3 5a2 2 0 0 0 2 2h3" } },
133 { tag: "path", attrs: { d: "M3 3v13a2 2 0 0 0 2 2h3" } },
134 ],
135 trash: [
136 { tag: "path", attrs: { d: "M3 6h18" } },
137 { tag: "path", attrs: { d: "M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" } },
138 { tag: "path", attrs: { d: "M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" } },
139 { tag: "line", attrs: { x1: "10", x2: "10", y1: "11", y2: "17" } },
140 { tag: "line", attrs: { x1: "14", x2: "14", y1: "11", y2: "17" } },
141 ],
142};
143​
144function createIconElement(name: string, tone: "neutral" | "destructive"): SVGSVGElement | null {
145 const paths = ICON_PATHS[name];
146 if (!paths || typeof document.createElementNS !== "function") {
147 return null;
148 }
149 const svg = document.createElementNS(SVG_NS, "svg");
150 svg.setAttribute("xmlns", SVG_NS);
151 svg.setAttribute("viewBox", "0 0 24 24");
152 svg.setAttribute("fill", "none");
153 svg.setAttribute("stroke", "currentColor");
154 svg.setAttribute("stroke-width", "2");
155 svg.setAttribute("stroke-linecap", "round");
156 svg.setAttribute("stroke-linejoin", "round");
157 svg.setAttribute(
158 "class",
159 tone === "destructive"
160 ? "size-4.5 shrink-0 sm:size-4"
161 : "size-4.5 shrink-0 text-muted-foreground sm:size-4",
162 );
163 for (const node of paths) {
164 const child = document.createElementNS(SVG_NS, node.tag);
165 for (const [key, value] of Object.entries(node.attrs)) {
166 child.setAttribute(key, value);
167 }
168 svg.appendChild(child);
169 }
170 return svg;
172​
173function clampMenuPosition(menu: HTMLDivElement, preferredLeft: number, preferredTop: number) {
174 const rect = menu.getBoundingClientRect();
175 const left = Math.min(
176 Math.max(4, preferredLeft),
177 Math.max(4, window.innerWidth - rect.width - 4),
178 );
179 const top = Math.min(
180 Math.max(4, preferredTop),
181 Math.max(4, window.innerHeight - rect.height - 4),
182 );
183 menu.style.left = `${left}px`;
184 menu.style.top = `${top}px`;
186​
187function isNodeWithinMenuStack(target: EventTarget | null, menuStack: readonly HTMLDivElement[]) {
188 if (typeof Node !== "undefined" && target instanceof Node) {
189 return menuStack.some((menu) => menu.contains(target));
190 }
191 if (!target || typeof target !== "object") {
192 return false;
193 }
194​
195 let current: unknown = target;
196 while (current && typeof current === "object") {
197 if (menuStack.includes(current as HTMLDivElement)) {
198 return true;
199 }
200 current = (current as { parent?: unknown }).parent;
201 }
202 return false;
204​
205let activeContextMenuDismiss: (() => void) | null = null;
206​
207export function isContextMenuOpen(): boolean {
208 return activeContextMenuDismiss !== null;
210​
211export function dismissContextMenu(): void {
212 activeContextMenuDismiss?.();
213 activeContextMenuDismiss = null;
215​
216export function showContextMenuFallback<T extends string>(
217 items: readonly ContextMenuItem<T>[],
218 position?: { x: number; y: number },
219): Promise<T | null> {
220 return new Promise<T | null>((resolve) => {
221 const previouslyFocusedElement =
222 document.activeElement instanceof HTMLElement ? document.activeElement : null;
223 const menuStack: HTMLDivElement[] = [];
224 const submenuTriggerStack: Array<HTMLButtonElement | undefined> = [];
225 let isDisposed = false;
226 let canDismissFromPointer = false;
227​
228 const dismiss = () => cleanup(null);
229​
230 const cleanup = (result: T | null) => {
231 if (isDisposed) {
232 return;
233 }
234 isDisposed = true;
235 if (activeContextMenuDismiss === dismiss) {
236 activeContextMenuDismiss = null;
237 }
238 document.removeEventListener("keydown", onKeyDown);
239 document.removeEventListener("pointerdown", onPointerDown, true);
240 document.removeEventListener("contextmenu", onContextMenu, true);
241 const shouldRestoreFocus = isNodeWithinMenuStack(document.activeElement, menuStack);
242 for (const menu of menuStack) {
243 menu.remove();
244 }
245 if (shouldRestoreFocus && previouslyFocusedElement?.isConnected) {
246 previouslyFocusedElement.focus({ preventScroll: true });
247 }
248 resolve(result);
249 };
250​
251 const onKeyDown = (event: KeyboardEvent) => {
252 if (event.key === "Escape") {
253 event.preventDefault();
254 cleanup(null);
255 }
256 };
257​
258 const onPointerDown = (event: PointerEvent) => {
259 if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {
260 return;
261 }
262 cleanup(null);
263 };
264​
265 const onContextMenu = (event: MouseEvent) => {
266 if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {
267 return;
268 }
269 event.preventDefault();
270 cleanup(null);
271 };
272​
273 const closeMenusFromLevel = (level: number) => {
274 while (menuStack.length > level) {
275 submenuTriggerStack.pop()?.setAttribute("aria-expanded", "false");
276 menuStack.pop()?.remove();
277 }
278 };
279​
280 const openMenu = (
281 entries: readonly ContextMenuItem<T>[],
282 preferredLeft: number,
283 preferredTop: number,
284 level: number,
285 parentTrigger?: HTMLButtonElement,
286 ) => {
287 closeMenusFromLevel(level);
288​
289 const menu = document.createElement("div");
290 menu.className =
291 "dropdown-glass fixed z-[10000] min-w-32 max-w-sm overflow-hidden rounded-lg bg-clip-padding text-popover-foreground outline-none";
292 menu.style.cssText =
293 "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;";
294 menu.style.left = `${preferredLeft}px`;
295 menu.style.top = `${preferredTop}px`;
296 menu.dataset.level = String(level);
297​
298 const inner = document.createElement("div");
299 inner.className =
300 "max-h-[calc(100vh-0.5rem)] min-w-0 max-w-sm overflow-y-auto overflow-x-hidden p-1";
301 inner.style.cssText =
302 "max-height:calc(100vh - 0.5rem);min-width:0;max-width:24rem;overflow-x:hidden;overflow-y:auto;padding:0.25rem;";
303​
304 for (const item of entries) {
305 if (item.separatorBefore === true && inner.children.length > 0) {
306 const separator = document.createElement("div");
307 separator.className = "mx-2 my-1 h-px bg-border";
308 separator.style.cssText =
309 "height:1px;margin:0.25rem 0.5rem;background:var(--contrast-border);";
310 separator.dataset.contextMenuSeparator = "true";
311 separator.setAttribute("role", "separator");
312 inner.appendChild(separator);
313 }
314​
315 if (item.header === true) {
316 const header = document.createElement("div");
317 header.className = "px-2 py-1.5 font-medium text-muted-foreground text-xs";
318 header.textContent = item.label;
319 inner.appendChild(header);
320 continue;
321 }
322​
323 const hasChildren = Array.isArray(item.children) && item.children.length > 0;
324 const isLeafDestructive =
325 !hasChildren && (item.destructive === true || item.id === ("delete" as T));
326​
327 const button = document.createElement("button");
328 button.type = "button";
329 const isDisabled = item.disabled === true;
330 button.disabled = isDisabled;
331 const rowBase =
332 "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";
333 button.className = isDisabled
334 ? `${rowBase} pointer-events-none cursor-not-allowed text-muted-foreground opacity-64`
335 : isLeafDestructive
336 ? `${rowBase} text-destructive-foreground hover:bg-destructive/10 hover:text-destructive-foreground`
337 : `${rowBase} text-foreground hover:bg-accent hover:text-accent-foreground`;
338 button.style.cssText =
339 "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;";
340 if (isLeafDestructive) {
341 button.style.color = "var(--destructive-foreground)";
342 }
343 if (isDisabled) {
344 button.style.color = "var(--contrast-muted-foreground)";
345 button.style.opacity = "0.64";
346 button.style.pointerEvents = "none";
347 }
348​
349 if (typeof item.checked === "boolean") {
350 button.setAttribute("role", "menuitemradio");
351 button.setAttribute("aria-checked", item.checked ? "true" : "false");
352 const check = item.checked ? createIconElement("check", "neutral") : null;
353 if (check) {
354 button.appendChild(check);
355 } else {
356 const spacer = document.createElement("span");
357 spacer.className = "size-4.5 shrink-0 sm:size-4";
358 spacer.style.cssText = "display:inline-block;width:1rem;height:1rem;flex-shrink:0;";
359 spacer.setAttribute("aria-hidden", "true");
360 button.appendChild(spacer);
361 }
362 } else if (typeof item.icon === "string") {
363 const icon = createIconElement(item.icon, isLeafDestructive ? "destructive" : "neutral");
364 if (icon) {
365 button.appendChild(icon);
366 }
367 }
368​
369 const label = document.createElement("span");
370 label.className = "min-w-0 flex-1 truncate";
371 label.textContent = item.label;
372 button.appendChild(label);
373​
374 if (hasChildren) {
375 button.setAttribute("aria-haspopup", "menu");
376 button.setAttribute("aria-expanded", "false");
377 const chevron = createIconElement("chevron-right", "neutral");
378 if (chevron) {
379 chevron.setAttribute(
380 "class",
381 "-me-0.5 ms-auto size-4.5 shrink-0 text-muted-foreground opacity-80 sm:size-4",
382 );
383 chevron.setAttribute("aria-hidden", "true");
384 chevron.dataset.contextMenuChevron = "true";
385 button.appendChild(chevron);
386 }
387 }
388​
389 if (!isDisabled) {
390 let isHovered = false;
391 let isFocused = false;
392 const updateHighlight = () => {
393 const isHighlighted = isHovered || isFocused;
394 button.style.background = isHighlighted
395 ? isLeafDestructive
396 ? "color-mix(in srgb, var(--destructive) 10%, transparent)"
397 : "var(--accent)"
398 : "transparent";
399 button.style.color = isHighlighted
400 ? isLeafDestructive
401 ? "var(--destructive-foreground)"
402 : "var(--contrast-accent-foreground)"
403 : isLeafDestructive
404 ? "var(--destructive-foreground)"
405 : "var(--contrast-foreground)";
406 };
407 button.addEventListener("mouseenter", () => {
408 button.focus({ preventScroll: true });
409 isHovered = true;
410 updateHighlight();
411 });
412 button.addEventListener("mouseleave", () => {
413 isHovered = false;
414 updateHighlight();
415 });
416 button.addEventListener("focus", () => {
417 isFocused = true;
418 updateHighlight();
419 });
420 button.addEventListener("blur", () => {
421 isFocused = false;
422 updateHighlight();
423 });
424​
425 if (hasChildren) {
426 const openSubmenu = (focusFirstItem = false) => {
427 const rect = button.getBoundingClientRect();
428 const nextLeft = rect.right + 4;
429 const nextTop = rect.top;
430 openMenu(item.children!, nextLeft, nextTop, level + 1, button);
431 button.setAttribute("aria-expanded", "true");
432​
433 const childMenu = menuStack[level + 1];
434 if (!childMenu) {
435 return;
436 }
437 const childRect = childMenu.getBoundingClientRect();
438 if (childRect.right > window.innerWidth) {
439 clampMenuPosition(childMenu, rect.left - childRect.width - 4, rect.top);
440 }
441 if (focusFirstItem) {
442 [...childMenu.querySelectorAll<HTMLButtonElement>("button")]
443 .find((childButton) => !childButton.disabled)
444 ?.focus();
445 }
446 };
447 button.addEventListener("mouseenter", () => {
448 openSubmenu();
449 });
450 button.addEventListener("click", (event) => {
451 event.preventDefault();
452 openSubmenu(true);
453 });
454 } else {
455 button.addEventListener("mouseenter", () => {
456 closeMenusFromLevel(level + 1);
457 });
458 button.addEventListener("click", () => {
459 if (canDismissFromPointer) cleanup(item.id);
460 });
461 }
462 }
463​
464 inner.appendChild(button);
465 }
466​
467 menu.appendChild(inner);
468​
469 menu.addEventListener("mouseenter", () => {
470 closeMenusFromLevel(level + 1);
471 });
472​
473 document.body.appendChild(menu);
474 menuStack[level] = menu;
475 submenuTriggerStack[level] = parentTrigger;
476​
477 requestAnimationFrame(() => {
478 clampMenuPosition(menu, preferredLeft, preferredTop);
479 });
480 };
481​
482 document.addEventListener("keydown", onKeyDown);
483 document.addEventListener("pointerdown", onPointerDown, true);
484 document.addEventListener("contextmenu", onContextMenu, true);
485 openMenu(items, position?.x ?? 0, position?.y ?? 0, 0);
486 // Dismiss the prior menu before replacing its only cleanup handle, or its DOM and listeners leak.
487 if (activeContextMenuDismiss) {
488 activeContextMenuDismiss();
489 }
490 activeContextMenuDismiss = dismiss;
491​
492 requestAnimationFrame(() => {
493 canDismissFromPointer = true;
494 });
495 });