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

contextMenuFallback.ts

492 lines18.5 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 "folder-tree": [
114 {
115 tag: "path",
116 attrs: {
117 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",
118 },
119 },
120 {
121 tag: "path",
122 attrs: {
123 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",
124 },
125 },
126 { tag: "path", attrs: { d: "M3 5a2 2 0 0 0 2 2h3" } },
127 { tag: "path", attrs: { d: "M3 3v13a2 2 0 0 0 2 2h3" } },
128 ],
129 trash: [
130 { tag: "path", attrs: { d: "M3 6h18" } },
131 { tag: "path", attrs: { d: "M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" } },
132 { tag: "path", attrs: { d: "M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" } },
133 { tag: "line", attrs: { x1: "10", x2: "10", y1: "11", y2: "17" } },
134 { tag: "line", attrs: { x1: "14", x2: "14", y1: "11", y2: "17" } },
135 ],
136};
137​
138function createIconElement(name: string, tone: "neutral" | "destructive"): SVGSVGElement | null {
139 const paths = ICON_PATHS[name];
140 if (!paths || typeof document.createElementNS !== "function") {
141 return null;
142 }
143 const svg = document.createElementNS(SVG_NS, "svg");
144 svg.setAttribute("xmlns", SVG_NS);
145 svg.setAttribute("viewBox", "0 0 24 24");
146 svg.setAttribute("fill", "none");
147 svg.setAttribute("stroke", "currentColor");
148 svg.setAttribute("stroke-width", "2");
149 svg.setAttribute("stroke-linecap", "round");
150 svg.setAttribute("stroke-linejoin", "round");
151 svg.setAttribute(
152 "class",
153 tone === "destructive"
154 ? "size-4.5 shrink-0 sm:size-4"
155 : "size-4.5 shrink-0 text-muted-foreground sm:size-4",
156 );
157 for (const node of paths) {
158 const child = document.createElementNS(SVG_NS, node.tag);
159 for (const [key, value] of Object.entries(node.attrs)) {
160 child.setAttribute(key, value);
161 }
162 svg.appendChild(child);
163 }
164 return svg;
166​
167function clampMenuPosition(menu: HTMLDivElement, preferredLeft: number, preferredTop: number) {
168 const rect = menu.getBoundingClientRect();
169 const left = Math.min(
170 Math.max(4, preferredLeft),
171 Math.max(4, window.innerWidth - rect.width - 4),
172 );
173 const top = Math.min(
174 Math.max(4, preferredTop),
175 Math.max(4, window.innerHeight - rect.height - 4),
176 );
177 menu.style.left = `${left}px`;
178 menu.style.top = `${top}px`;
180​
181function isNodeWithinMenuStack(target: EventTarget | null, menuStack: readonly HTMLDivElement[]) {
182 if (typeof Node !== "undefined" && target instanceof Node) {
183 return menuStack.some((menu) => menu.contains(target));
184 }
185 if (!target || typeof target !== "object") {
186 return false;
187 }
188​
189 let current: unknown = target;
190 while (current && typeof current === "object") {
191 if (menuStack.includes(current as HTMLDivElement)) {
192 return true;
193 }
194 current = (current as { parent?: unknown }).parent;
195 }
196 return false;
198​
199let activeContextMenuDismiss: (() => void) | null = null;
200​
201export function isContextMenuOpen(): boolean {
202 return activeContextMenuDismiss !== null;
204​
205export function dismissContextMenu(): void {
206 activeContextMenuDismiss?.();
207 activeContextMenuDismiss = null;
209​
210export function showContextMenuFallback<T extends string>(
211 items: readonly ContextMenuItem<T>[],
212 position?: { x: number; y: number },
213): Promise<T | null> {
214 return new Promise<T | null>((resolve) => {
215 const previouslyFocusedElement =
216 document.activeElement instanceof HTMLElement ? document.activeElement : null;
217 const menuStack: HTMLDivElement[] = [];
218 const submenuTriggerStack: Array<HTMLButtonElement | undefined> = [];
219 let isDisposed = false;
220 let canDismissFromPointer = false;
221​
222 const dismiss = () => cleanup(null);
223​
224 const cleanup = (result: T | null) => {
225 if (isDisposed) {
226 return;
227 }
228 isDisposed = true;
229 if (activeContextMenuDismiss === dismiss) {
230 activeContextMenuDismiss = null;
231 }
232 document.removeEventListener("keydown", onKeyDown);
233 document.removeEventListener("pointerdown", onPointerDown, true);
234 document.removeEventListener("contextmenu", onContextMenu, true);
235 const shouldRestoreFocus = isNodeWithinMenuStack(document.activeElement, menuStack);
236 for (const menu of menuStack) {
237 menu.remove();
238 }
239 if (shouldRestoreFocus && previouslyFocusedElement?.isConnected) {
240 previouslyFocusedElement.focus({ preventScroll: true });
241 }
242 resolve(result);
243 };
244​
245 const onKeyDown = (event: KeyboardEvent) => {
246 if (event.key === "Escape") {
247 event.preventDefault();
248 cleanup(null);
249 }
250 };
251​
252 const onPointerDown = (event: PointerEvent) => {
253 if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {
254 return;
255 }
256 cleanup(null);
257 };
258​
259 const onContextMenu = (event: MouseEvent) => {
260 if (!canDismissFromPointer || isNodeWithinMenuStack(event.target, menuStack)) {
261 return;
262 }
263 event.preventDefault();
264 cleanup(null);
265 };
266​
267 const closeMenusFromLevel = (level: number) => {
268 while (menuStack.length > level) {
269 submenuTriggerStack.pop()?.setAttribute("aria-expanded", "false");
270 menuStack.pop()?.remove();
271 }
272 };
273​
274 const openMenu = (
275 entries: readonly ContextMenuItem<T>[],
276 preferredLeft: number,
277 preferredTop: number,
278 level: number,
279 parentTrigger?: HTMLButtonElement,
280 ) => {
281 closeMenusFromLevel(level);
282​
283 const menu = document.createElement("div");
284 menu.className =
285 "dropdown-glass fixed z-[10000] min-w-32 max-w-sm overflow-hidden rounded-lg bg-clip-padding text-popover-foreground outline-none";
286 menu.style.cssText =
287 "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;";
288 menu.style.left = `${preferredLeft}px`;
289 menu.style.top = `${preferredTop}px`;
290 menu.dataset.level = String(level);
291​
292 const inner = document.createElement("div");
293 inner.className =
294 "max-h-[calc(100vh-0.5rem)] min-w-0 max-w-sm overflow-y-auto overflow-x-hidden p-1";
295 inner.style.cssText =
296 "max-height:calc(100vh - 0.5rem);min-width:0;max-width:24rem;overflow-x:hidden;overflow-y:auto;padding:0.25rem;";
297​
298 for (const item of entries) {
299 if (item.separatorBefore === true && inner.children.length > 0) {
300 const separator = document.createElement("div");
301 separator.className = "mx-2 my-1 h-px bg-border";
302 separator.style.cssText =
303 "height:1px;margin:0.25rem 0.5rem;background:var(--contrast-border);";
304 separator.dataset.contextMenuSeparator = "true";
305 separator.setAttribute("role", "separator");
306 inner.appendChild(separator);
307 }
308​
309 if (item.header === true) {
310 const header = document.createElement("div");
311 header.className = "px-2 py-1.5 font-medium text-muted-foreground text-xs";
312 header.textContent = item.label;
313 inner.appendChild(header);
314 continue;
315 }
316​
317 const hasChildren = Array.isArray(item.children) && item.children.length > 0;
318 const isLeafDestructive =
319 !hasChildren && (item.destructive === true || item.id === ("delete" as T));
320​
321 const button = document.createElement("button");
322 button.type = "button";
323 const isDisabled = item.disabled === true;
324 button.disabled = isDisabled;
325 const rowBase =
326 "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";
327 button.className = isDisabled
328 ? `${rowBase} pointer-events-none cursor-not-allowed text-muted-foreground opacity-64`
329 : isLeafDestructive
330 ? `${rowBase} text-destructive-foreground hover:bg-destructive/10 hover:text-destructive-foreground`
331 : `${rowBase} text-foreground hover:bg-accent hover:text-accent-foreground`;
332 button.style.cssText =
333 "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;";
334 if (isLeafDestructive) {
335 button.style.color = "var(--destructive-foreground)";
336 }
337 if (isDisabled) {
338 button.style.color = "var(--contrast-muted-foreground)";
339 button.style.opacity = "0.64";
340 button.style.pointerEvents = "none";
341 }
342​
343 if (typeof item.checked === "boolean") {
344 button.setAttribute("role", "menuitemradio");
345 button.setAttribute("aria-checked", item.checked ? "true" : "false");
346 const check = item.checked ? createIconElement("check", "neutral") : null;
347 if (check) {
348 button.appendChild(check);
349 } else {
350 const spacer = document.createElement("span");
351 spacer.className = "size-4.5 shrink-0 sm:size-4";
352 spacer.style.cssText = "display:inline-block;width:1rem;height:1rem;flex-shrink:0;";
353 spacer.setAttribute("aria-hidden", "true");
354 button.appendChild(spacer);
355 }
356 } else if (typeof item.icon === "string") {
357 const icon = createIconElement(item.icon, isLeafDestructive ? "destructive" : "neutral");
358 if (icon) {
359 button.appendChild(icon);
360 }
361 }
362​
363 const label = document.createElement("span");
364 label.className = "min-w-0 flex-1 truncate";
365 label.textContent = item.label;
366 button.appendChild(label);
367​
368 if (hasChildren) {
369 button.setAttribute("aria-haspopup", "menu");
370 button.setAttribute("aria-expanded", "false");
371 const chevron = createIconElement("chevron-right", "neutral");
372 if (chevron) {
373 chevron.setAttribute(
374 "class",
375 "-me-0.5 ms-auto size-4.5 shrink-0 text-muted-foreground opacity-80 sm:size-4",
376 );
377 chevron.setAttribute("aria-hidden", "true");
378 chevron.dataset.contextMenuChevron = "true";
379 button.appendChild(chevron);
380 }
381 }
382​
383 if (!isDisabled) {
384 let isHovered = false;
385 let isFocused = false;
386 const updateHighlight = () => {
387 const isHighlighted = isHovered || isFocused;
388 button.style.background = isHighlighted
389 ? isLeafDestructive
390 ? "color-mix(in srgb, var(--destructive) 10%, transparent)"
391 : "var(--accent)"
392 : "transparent";
393 button.style.color = isHighlighted
394 ? isLeafDestructive
395 ? "var(--destructive-foreground)"
396 : "var(--contrast-accent-foreground)"
397 : isLeafDestructive
398 ? "var(--destructive-foreground)"
399 : "var(--contrast-foreground)";
400 };
401 button.addEventListener("mouseenter", () => {
402 button.focus({ preventScroll: true });
403 isHovered = true;
404 updateHighlight();
405 });
406 button.addEventListener("mouseleave", () => {
407 isHovered = false;
408 updateHighlight();
409 });
410 button.addEventListener("focus", () => {
411 isFocused = true;
412 updateHighlight();
413 });
414 button.addEventListener("blur", () => {
415 isFocused = false;
416 updateHighlight();
417 });
418​
419 if (hasChildren) {
420 const openSubmenu = (focusFirstItem = false) => {
421 const rect = button.getBoundingClientRect();
422 const nextLeft = rect.right + 4;
423 const nextTop = rect.top;
424 openMenu(item.children!, nextLeft, nextTop, level + 1, button);
425 button.setAttribute("aria-expanded", "true");
426​
427 const childMenu = menuStack[level + 1];
428 if (!childMenu) {
429 return;
430 }
431 const childRect = childMenu.getBoundingClientRect();
432 if (childRect.right > window.innerWidth) {
433 clampMenuPosition(childMenu, rect.left - childRect.width - 4, rect.top);
434 }
435 if (focusFirstItem) {
436 [...childMenu.querySelectorAll<HTMLButtonElement>("button")]
437 .find((childButton) => !childButton.disabled)
438 ?.focus();
439 }
440 };
441 button.addEventListener("mouseenter", () => {
442 openSubmenu();
443 });
444 button.addEventListener("click", (event) => {
445 event.preventDefault();
446 openSubmenu(true);
447 });
448 } else {
449 button.addEventListener("mouseenter", () => {
450 closeMenusFromLevel(level + 1);
451 });
452 button.addEventListener("click", () => {
453 if (canDismissFromPointer) cleanup(item.id);
454 });
455 }
456 }
457​
458 inner.appendChild(button);
459 }
460​
461 menu.appendChild(inner);
462​
463 menu.addEventListener("mouseenter", () => {
464 closeMenusFromLevel(level + 1);
465 });
466​
467 document.body.appendChild(menu);
468 menuStack[level] = menu;
469 submenuTriggerStack[level] = parentTrigger;
470​
471 requestAnimationFrame(() => {
472 clampMenuPosition(menu, preferredLeft, preferredTop);
473 });
474 };
475​
476 document.addEventListener("keydown", onKeyDown);
477 document.addEventListener("pointerdown", onPointerDown, true);
478 document.addEventListener("contextmenu", onContextMenu, true);
479 openMenu(items, position?.x ?? 0, position?.y ?? 0, 0);
480 // Only one fallback menu can be open at a time: a new show must dismiss
481 // any prior one, or its DOM and listeners leak and close() can only ever
482 // reach the newest menu.
483 if (activeContextMenuDismiss) {
484 activeContextMenuDismiss();
485 }
486 activeContextMenuDismiss = dismiss;
487​
488 requestAnimationFrame(() => {
489 canDismissFromPointer = true;
490 });
491 });