"use client"; import { useEffect, useRef, useState } from "react"; import { usePhone } from "@/components/shell/phone"; import { Sheet } from "@/components/shell/Sheet"; import { useHydrated } from "@/components/ui/use-hydrated"; import { cn } from "@/lib/utils"; // A small menu under a trigger in a piece's head: the lifecycle chip's and the // ⋯ menu's. A panel below the trigger, right-aligned; Escape, a click away, or // a lifecycle change (the `umtool:lifecycle` event a LifecycleButton sends) // closes it. The trigger is disabled until hydration, the house rule: a press // before React is listening opens nothing. // // On a phone the panel is a BOTTOM SHEET (components/shell/Sheet.tsx), where // the thumb is, its items full-width targets. `flatOnPhone`: a menu that is // already inside a sheet (a piece's ⋯ items, in the page's ⋯ sheet) lays its // items out there, with no trigger -- a menu inside a sheet is one tap too many. export default function Menu({ trigger, label, className, triggerClassName, flatOnPhone = false, children, ...props }: { trigger: React.ReactNode; /** The trigger's accessible name when its text is not one ("More" for ⋯). */ label?: string; className?: string; triggerClassName?: string; /** On a phone: the items in place, no trigger (the menu is already in a sheet). */ flatOnPhone?: boolean; children: React.ReactNode; } & Omit, "children">) { const hydrated = useHydrated(); const phone = usePhone(); const [open, setOpen] = useState(false); const ref = useRef(null); useEffect(() => { if (!open) return; const away = (e: MouseEvent) => { if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false); }; const key = (e: KeyboardEvent) => { if (e.key === "Escape") setOpen(false); }; const changed = () => setOpen(false); document.addEventListener("mousedown", away); document.addEventListener("keydown", key); window.addEventListener("umtool:lifecycle", changed); return () => { document.removeEventListener("mousedown", away); document.removeEventListener("keydown", key); window.removeEventListener("umtool:lifecycle", changed); }; }, [open]); if (phone && flatOnPhone) { return (
{children}
); } return (
{open && phone && ( setOpen(false)} data-menu-panel=""> {children} )} {open && !phone && (
{children}
)}
); }