import React, { useState, useEffect, useLayoutEffect, useRef, type ComponentType, type CSSProperties } from 'react' import { createPortal } from 'react-dom' import { LucideIcon } from 'lucide-react' import { useLastOpen, usePresence } from './usePresence' interface MenuItem { label?: string /** A lucide icon, or any icon drawn the same way (TREK's own glyphs). */ icon?: LucideIcon | ComponentType<{ size?: number; style?: CSSProperties }> onClick?: () => void disabled?: boolean danger?: boolean divider?: boolean /** A second, quieter line under the label: what an item does, or why it is greyed out. */ hint?: string /** A row that only names what the items below it act on, such as the day picked a step before. */ heading?: boolean } interface MenuState { x: number y: number items: MenuItem[] alignEnd?: boolean /** The top of the button it hangs from: with no room below, the menu opens above it, not over it. */ anchorTop?: number } export function useContextMenu() { const [menu, setMenu] = useState(null) const open = (e: React.MouseEvent, items: MenuItem[], alignEnd = false) => { e.preventDefault() e.stopPropagation() if (!alignEnd) { setMenu({ x: e.clientX, y: e.clientY, items, alignEnd }) return } const anchor = e.currentTarget.getBoundingClientRect() setMenu({ x: anchor.right, y: anchor.bottom + 6, items, alignEnd, anchorTop: anchor.top }) } /** Opens the menu under an element, its end on the element's end: the next step of a menu opened there. */ const openAt = (anchor: Element, items: MenuItem[]) => { const rect = anchor.getBoundingClientRect() setMenu({ x: rect.right, y: rect.bottom + 6, items, alignEnd: true, anchorTop: rect.top }) } const close = () => setMenu(null) return { menu, open, openAt, close } } interface ContextMenuProps { menu: MenuState | null onClose: () => void } export function ContextMenu({ menu, onClose }: ContextMenuProps) { const { mounted, closing } = usePresence(menu != null, 130) // The items stay on screen while the menu fades, after its owner set it to null. const shown = useLastOpen(menu, menu != null) return mounted && shown ? : null } function ContextMenuFrame({ menu, onClose, closing }: { menu: MenuState; onClose: () => void; closing: boolean }) { const ref = useRef(null) useEffect(() => { if (!menu) return const handler = () => onClose() // A fixed menu stays where it opened, so it closes when the page under it // moves or the window changes size. Escape closes it in the capture phase // and goes no further, so a dialog, the assistant column or Studio under // it does not act on the same key. const onKey = (e: KeyboardEvent) => { if (e.key !== 'Escape') return e.stopPropagation() onClose() } document.addEventListener('click', handler) document.addEventListener('contextmenu', handler) document.addEventListener('keydown', onKey, true) window.addEventListener('scroll', handler, true) window.addEventListener('resize', handler) return () => { document.removeEventListener('click', handler) document.removeEventListener('contextmenu', handler) document.removeEventListener('keydown', onKey, true) window.removeEventListener('scroll', handler, true) window.removeEventListener('resize', handler) } }, [menu, onClose]) // Keyboard users land on the first item and move with the arrow keys. useEffect(() => { if (!menu) return ref.current?.querySelector('button:not(:disabled)')?.focus({ preventScroll: true }) }, [menu]) const moveFocus = (e: React.KeyboardEvent) => { if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return e.preventDefault() const items = [...(ref.current?.querySelectorAll('button:not(:disabled)') ?? [])] if (items.length === 0) return const at = items.indexOf(document.activeElement as HTMLButtonElement) const next = e.key === 'ArrowDown' ? (at + 1) % items.length : (at - 1 + items.length) % items.length items[next]?.focus() } useLayoutEffect(() => { if (!menu || !ref.current) return const el = ref.current // The layout size, not getBoundingClientRect: the menu is still mid enter // animation (scaled down) here, and the smaller box let a menu opened near an // edge end up partly off screen. const width = el.offsetWidth const viewW = window.innerWidth const viewH = window.innerHeight // Taller than the screen (a long list on a phone): cap it and let it scroll. if (el.offsetHeight > viewH - 16) { el.style.maxHeight = `${viewH - 16}px` el.style.overflowY = 'auto' } const height = Math.min(el.offsetHeight, viewH - 16) let { x, y } = menu if (menu.alignEnd) x = x - width // A menu hanging from a button near the foot of the screen opens above it. if (menu.anchorTop !== undefined && y + height > viewH - 8 && menu.anchorTop - 6 - height >= 8) y = menu.anchorTop - 6 - height // Kept inside all four edges with 8px to spare. x = Math.min(Math.max(8, x), viewW - width - 8) y = Math.min(Math.max(8, y), viewH - height - 8) if (x !== menu.x || y !== menu.y) { el.style.left = `${Math.max(8, x)}px` el.style.top = `${Math.max(8, y)}px` } }, [menu]) return createPortal(
{menu.items.filter(Boolean).map((item, i) => { if (item.divider) return
if (item.heading) return (
{item.label}
) const Icon = item.icon return ( ) })}
, document.body ) }