xonecas.io
8058
Ir

irvc / files

irvc / web / src / ui / Menu.tsx

3.2 KB
1import {
2  useEffect,
3  useLayoutEffect,
4  useRef,
5  useState,
6  type ReactNode,
7} from "react";
8import { createPortal } from "react-dom";
9import { cn } from "cn";
10
11// Menu is the single way to reveal secondary actions. It opens on a click or
12// tap (never on hover, so it works everywhere), renders into a portal so it is
13// never clipped by a scrolling parent, and closes on outside click or Escape.
14export function Menu({
15  trigger,
16  children,
17  align = "end",
18  className,
19}: {
20  trigger: ReactNode;
21  children: (close: () => void) => ReactNode;
22  align?: "start" | "end";
23  className?: string;
24}) {
25  const [open, setOpen] = useState(false);
26  const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
27  const wrap = useRef<HTMLDivElement>(null);
28  const panel = useRef<HTMLDivElement>(null);
29
30  useLayoutEffect(() => {
31    if (!open) {
32      setPos(null);
33      return;
34    }
35    const r = wrap.current!.getBoundingClientRect();
36    const p = panel.current!.getBoundingClientRect();
37    let top = r.bottom + 4;
38    if (top + p.height > innerHeight - 8) top = Math.max(8, r.top - p.height - 4);
39    let left = align === "end" ? r.right - p.width : r.left;
40    left = Math.max(8, Math.min(left, innerWidth - p.width - 8));
41    setPos({ top, left });
42  }, [open, align]);
43
44  useEffect(() => {
45    if (!open) return;
46    // The panel is portalled, so it is outside the wrapper: without this check
47    // a press on an item would close the menu before the click landed.
48    const down = (e: PointerEvent) => {
49      const target = e.target as Node;
50      if (!wrap.current?.contains(target) && !panel.current?.contains(target)) setOpen(false);
51    };
52    const key = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false);
53    document.addEventListener("pointerdown", down);
54    document.addEventListener("keydown", key);
55    return () => {
56      document.removeEventListener("pointerdown", down);
57      document.removeEventListener("keydown", key);
58    };
59  }, [open]);
60
61  return (
62    <div ref={wrap} className={cn("shrink-0", className)}>
63      {/* The trigger is itself a button, so this wrapper only forwards the
64          click; the child keeps the semantics (label, keyboard, focus). */}
65      <div className="contents" onClick={() => setOpen((v) => !v)}>
66        {trigger}
67      </div>
68      {open &&
69        createPortal(
70          <div
71            ref={panel}
72            role="menu"
73            style={{ top: pos?.top ?? 0, left: pos?.left ?? 0, visibility: pos ? "visible" : "hidden" }}
74            className="menu fixed z-50"
75          >
76            {children(() => setOpen(false))}
77          </div>,
78          document.body,
79        )}
80    </div>
81  );
82}
83
84export function MenuItem({
85  onClick,
86  danger,
87  children,
88  className,
89}: {
90  onClick?: () => void;
91  danger?: boolean;
92  children: ReactNode;
93  className?: string;
94}) {
95  return (
96    <button
97      type="button"
98      role="menuitem"
99      onClick={onClick}
100      className={cn("menu-item", danger && "menu-item-danger", className)}
101    >
102      {children}
103    </button>
104  );
105}
106
107export function MenuLabel({ children }: { children: ReactNode }) {
108  return <div className="px-2.5 py-1.5 text-[0.7rem] tracking-widest text-faint uppercase">{children}</div>;
109}