components/linyi/collapsible.tsx
motionlucide-react
"use client"; import * as React from "react";import { AnimatePresence, motion } from "motion/react";import { ChevronRight } from "lucide-react";import { cn } from "@/lib/cn";import { SPRING_SMOOTH, SPRING_SNAPPY } from "@/lib/motion"; export interface CollapsibleProps { title: string; badge?: string; defaultOpen?: boolean; open?: boolean; onOpenChange?: (open: boolean) => void; children: React.ReactNode; className?: string;} export function Collapsible({ title, badge, defaultOpen = false, open, onOpenChange, children, className,}: CollapsibleProps) { const [internalOpen, setInternalOpen] = React.useState(defaultOpen); const uid = React.useId(); const triggerId = `collapsible-trigger-${uid}`; const contentId = `collapsible-content-${uid}`; const isControlled = open !== undefined; const isOpen = isControlled ? open : internalOpen; const toggle = () => { const next = !isOpen; if (!isControlled) { setInternalOpen(next); } onOpenChange?.(next); }; return ( <div className={cn( "w-full rounded-well border border-line bg-surface overflow-hidden transition-colors hover:border-line-strong", className )} > <button id={triggerId} type="button" onClick={toggle} aria-expanded={isOpen} aria-controls={contentId} className="w-full min-h-[42px] px-3.5 flex items-center justify-between gap-2 text-xs font-medium text-fg cursor-pointer select-none outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent" > <span className="truncate">{title}</span> <span className="flex items-center gap-2 flex-shrink-0"> {badge && ( <span className="font-mono-num text-[10px] px-1.5 py-0.5 rounded-badge bg-well text-fg-secondary border border-line"> {badge} </span> )} <motion.span animate={{ rotate: isOpen ? 90 : 0 }} transition={SPRING_SNAPPY} className="text-fg-muted flex items-center" > <ChevronRight className="w-4 h-4" /> </motion.span> </span> </button> <AnimatePresence initial={false}> {isOpen && ( <motion.div id={contentId} role="region" aria-labelledby={triggerId} initial={{ height: 0, opacity: 0 }} animate={{ height: "auto", opacity: 1 }} exit={{ height: 0, opacity: 0 }} transition={SPRING_SMOOTH} className="overflow-hidden" > <div className="px-3.5 pb-3 pt-2.5 border-t border-line text-xs text-fg-secondary"> {children} </div> </motion.div> )} </AnimatePresence> </div> );}