components/linyi/motion-dropdown-menu.tsx
motionlucide-react
"use client"; import * as React from "react";import { AnimatePresence, motion } from "motion/react";import { Check, ChevronDown } from "lucide-react";import { cn } from "@/lib/cn";import { SPRING_SNAPPY } from "@/lib/motion"; export interface MotionDropdownOption { value: string; label: string; shortcut?: string; group?: string; danger?: boolean; disabled?: boolean;} export interface MotionDropdownMenuProps { options: MotionDropdownOption[]; value?: string; defaultValue?: string; onSelect?: (value: string) => void; placeholder?: string; open?: boolean; defaultOpen?: boolean; onOpenChange?: (open: boolean) => void; inline?: boolean; ariaLabel?: string; className?: string;} export function MotionDropdownMenu({ options, value, defaultValue, onSelect, placeholder = "选择操作", open, defaultOpen = false, onOpenChange, inline = false, ariaLabel = "操作菜单", className,}: MotionDropdownMenuProps) { const containerRef = React.useRef<HTMLDivElement>(null); const triggerRef = React.useRef<HTMLButtonElement>(null); const itemRefs = React.useRef<(HTMLButtonElement | null)[]>([]); const uid = React.useId(); const [internalOpen, setInternalOpen] = React.useState(defaultOpen); const [internalValue, setInternalValue] = React.useState( defaultValue ?? options.find((o) => !o.disabled)?.value ?? "" ); const [activeIndex, setActiveIndex] = React.useState<number | null>(null); const isOpenControlled = open !== undefined; const isOpen = isOpenControlled ? open : internalOpen; const isValueControlled = value !== undefined; const selectedValue = isValueControlled ? value : internalValue; const selectedOption = options.find((o) => o.value === selectedValue); const setOpenState = React.useCallback( (next: boolean) => { if (!isOpenControlled) { setInternalOpen(next); } onOpenChange?.(next); if (!next) { setActiveIndex(null); } }, [isOpenControlled, onOpenChange] ); // Close on click outside (skipped when inline preview is explicitly pinned open) React.useEffect(() => { if (!isOpen || inline) return; const handlePointerDown = (e: PointerEvent) => { if (!containerRef.current?.contains(e.target as Node)) { setOpenState(false); } }; document.addEventListener("pointerdown", handlePointerDown); return () => document.removeEventListener("pointerdown", handlePointerDown); }, [isOpen, inline, setOpenState]); const findNextEnabled = (start: number, delta: 1 | -1): number => { const len = options.length; for (let step = 0; step < len; step++) { const idx = (start + step * delta + len) % len; if (!options[idx]?.disabled) return idx; } return -1; }; const focusItem = (idx: number) => { if (idx < 0) return; setActiveIndex(idx); requestAnimationFrame(() => { itemRefs.current[idx]?.focus(); }); }; const openAndFocus = (direction: "first" | "last") => { setOpenState(true); const target = direction === "first" ? findNextEnabled(0, 1) : findNextEnabled(options.length - 1, -1); focusItem(target); }; const handleTriggerKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => { if (e.key === "ArrowDown") { e.preventDefault(); openAndFocus("first"); } else if (e.key === "ArrowUp") { e.preventDefault(); openAndFocus("last"); } else if (e.key === "Escape" && isOpen) { e.preventDefault(); setOpenState(false); } }; const handleSelectOption = (opt: MotionDropdownOption) => { if (opt.disabled) return; if (!isValueControlled) { setInternalValue(opt.value); } onSelect?.(opt.value); if (!inline) { setOpenState(false); triggerRef.current?.focus(); } }; const handleMenuKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => { if (e.key === "Escape") { e.preventDefault(); setOpenState(false); triggerRef.current?.focus(); return; } if (e.key === "ArrowDown") { e.preventDefault(); const start = activeIndex === null ? 0 : (activeIndex + 1) % options.length; focusItem(findNextEnabled(start, 1)); } else if (e.key === "ArrowUp") { e.preventDefault(); const start = activeIndex === null ? options.length - 1 : (activeIndex - 1 + options.length) % options.length; focusItem(findNextEnabled(start, -1)); } else if (e.key === "Home") { e.preventDefault(); focusItem(findNextEnabled(0, 1)); } else if (e.key === "End") { e.preventDefault(); focusItem(findNextEnabled(options.length - 1, -1)); } }; return ( <div ref={containerRef} className={cn("relative w-52", className)}> <button ref={triggerRef} type="button" aria-haspopup="menu" aria-expanded={isOpen} aria-controls={`menu-${uid}`} onClick={() => setOpenState(!isOpen)} onKeyDown={handleTriggerKeyDown} className="ui-btn ui-btn-default px-3.5 min-h-[36px] text-xs w-full justify-between" > <span className="truncate">{selectedOption?.label ?? placeholder}</span> <motion.span animate={{ rotate: isOpen ? 180 : 0 }} transition={SPRING_SNAPPY} className="flex-shrink-0" > <ChevronDown className="w-3.5 h-3.5" /> </motion.span> </button> <AnimatePresence> {isOpen && ( <motion.div id={`menu-${uid}`} role="menu" aria-label={ariaLabel} initial={{ opacity: 0, y: -6, scale: 0.96 }} animate={{ opacity: 1, y: 0, scale: 1 }} exit={{ opacity: 0, y: -6, scale: 0.96 }} transition={SPRING_SNAPPY} onMouseLeave={() => setActiveIndex(null)} onKeyDown={handleMenuKeyDown} className={cn( "mt-2 w-full rounded-well border border-line-strong bg-surface p-1 shadow-popover", inline ? "relative" : "absolute left-0 top-full z-40" )} > {options.map((opt, idx) => { const prevGroup = idx > 0 ? options[idx - 1]?.group : undefined; const showDivider = idx > 0 && opt.group !== prevGroup; const isHighlighted = activeIndex === idx && !opt.disabled; const isSelected = selectedValue === opt.value; return ( <React.Fragment key={opt.value}> {showDivider && <div className="my-1 h-px bg-line" role="separator" />} <button ref={(el) => { itemRefs.current[idx] = el; }} type="button" role="menuitemradio" aria-checked={isSelected} disabled={opt.disabled} onMouseEnter={() => { if (!opt.disabled) setActiveIndex(idx); }} onFocus={() => { if (!opt.disabled) setActiveIndex(idx); }} onClick={() => handleSelectOption(opt)} className={cn( "relative w-full text-left px-2.5 min-h-[32px] rounded-[8px] text-xs flex items-center justify-between gap-2 outline-none transition-colors", opt.disabled ? "opacity-45 cursor-not-allowed" : "cursor-pointer", opt.danger ? "text-danger" : "text-fg" )} > {isHighlighted && ( <motion.span layoutId={`dd-hover-${uid}`} transition={SPRING_SNAPPY} className={cn( "absolute inset-0 rounded-[8px] pointer-events-none", opt.danger ? "bg-danger-soft" : "bg-well" )} /> )} <span className="relative z-10 flex items-center gap-2 min-w-0"> <span className="w-3.5 h-3.5 flex items-center justify-center flex-shrink-0"> {isSelected && <Check className="w-3 h-3 text-accent" />} </span> <span className="truncate">{opt.label}</span> </span> {opt.shortcut && ( <span className="relative z-10 font-mono-num text-[10px] text-fg-muted flex-shrink-0"> {opt.shortcut} </span> )} </button> </React.Fragment> ); })} </motion.div> )} </AnimatePresence> </div> );}