import { useEffect, useMemo, useRef, useState } from 'react' import { createPortal } from 'react-dom' import { ChevronDown } from 'lucide-react' import { useTranslation } from '../../i18n' import { useOpenTargetStore } from '../../stores/openTargetStore' import { TargetIcon } from '../common/TargetIcon' type Props = { path: string | null | undefined } export function OpenProjectMenu({ path }: Props) { const t = useTranslation() const targets = useOpenTargetStore((state) => state.targets) const primaryTargetId = useOpenTargetStore((state) => state.primaryTargetId) const ensureTargets = useOpenTargetStore((state) => state.ensureTargets) const openTarget = useOpenTargetStore((state) => state.openTarget) const [open, setOpen] = useState(false) const buttonRef = useRef(null) const menuRef = useRef(null) useEffect(() => { if (!path) { setOpen(false) return } void ensureTargets() }, [ensureTargets, path]) useEffect(() => { if (!open) return const handleDocumentMouseDown = (event: MouseEvent) => { const target = event.target as Node if (buttonRef.current?.contains(target) || menuRef.current?.contains(target)) return setOpen(false) } const handleKeyDown = (event: KeyboardEvent) => { if (event.key === 'Escape') setOpen(false) } document.addEventListener('mousedown', handleDocumentMouseDown) document.addEventListener('keydown', handleKeyDown) return () => { document.removeEventListener('mousedown', handleDocumentMouseDown) document.removeEventListener('keydown', handleKeyDown) } }, [open]) const primaryTarget = useMemo( () => targets.find((target) => target.id === primaryTargetId) ?? targets[0] ?? null, [primaryTargetId, targets], ) const hasMenu = targets.length > 1 const handleOpenTarget = async (targetId: string) => { if (!path) return try { await openTarget(targetId, path) } catch { // Store state already records the failure; keep the control responsive. } finally { setOpen(false) } } if (!path || !primaryTarget) return null const buttonLabel = hasMenu ? t('openProject.openProject') : t('openProject.openIn', { target: primaryTarget.label }) const rect = buttonRef.current?.getBoundingClientRect() return (
{open && hasMenu && rect ? createPortal(
{targets.map((target) => ( ))}
, document.body, ) : null}
) }