1"use client"
2
3import React, {
4 createContext,
5 ReactNode,
6 useContext,
7 useEffect,
8 useState,
9} from "react"
10import {
11 AnimatePresence,
12 HTMLMotionProps,
13 motion,
14 TargetAndTransition,
15 useMotionValue,
16 useSpring,
17} from "motion/react"
18import useMeasure from "react-use-measure"
19
20import { cn } from "@/lib/utils"
21
22const springConfig = { stiffness: 200, damping: 20, bounce: 0.2 }
23
24interface ExpandableContextType {
25 isExpanded: boolean // Indicates whether the component is expanded
26 toggleExpand: () => void // Function to toggle the expanded state
27 expandDirection: "vertical" | "horizontal" | "both" // Direction of expansion
28 expandBehavior: "replace" | "push" // How the expansion affects surrounding content
29 transitionDuration: number // Duration of the expansion/collapse animation
30 easeType:
31 | "easeInOut"
32 | "easeIn"
33 | "easeOut"
34 | "linear"
35 | [number, number, number, number] // Easing function for the animation
36 initialDelay: number // Delay before the animation starts
37 onExpandEnd?: () => void // Callback function when expansion ends
38 onCollapseEnd?: () => void // Callback function when collapse ends
39}
40
41// Create a context with default values
42const ExpandableContext = createContext<ExpandableContextType>({
43 isExpanded: false,
44 toggleExpand: () => {},
45 expandDirection: "vertical", // 'vertical' | 'horizontal' | 'both' // Direction of expansion
46 expandBehavior: "replace", // How the expansion affects surrounding content
47 transitionDuration: 0.3, // Duration of the expansion/collapse animation
48 easeType: "easeInOut" as const, // Easing function for the animation
49 initialDelay: 0,
50})
51
52// Custom hook to use the ExpandableContext
53const useExpandable = () => useContext(ExpandableContext)
54
55type ExpandablePropsBase = Omit<HTMLMotionProps<"div">, "children">
56
57interface ExpandableProps extends ExpandablePropsBase {
58 children: ReactNode | ((props: { isExpanded: boolean }) => ReactNode)
59 expanded?: boolean
60 onToggle?: () => void
61 transitionDuration?: number
62 easeType?:
63 | "easeInOut"
64 | "easeIn"
65 | "easeOut"
66 | "linear"
67 | [number, number, number, number]
68 expandDirection?: "vertical" | "horizontal" | "both"
69 expandBehavior?: "replace" | "push"
70 initialDelay?: number
71 onExpandStart?: () => void
72 onExpandEnd?: () => void
73 onCollapseStart?: () => void
74 onCollapseEnd?: () => void
75}
76// ROOT Expand component
77const Expandable = React.forwardRef<HTMLDivElement, ExpandableProps>(
78 (
79 {
80 children,
81 expanded,
82 onToggle,
83 transitionDuration = 0.3,
84 easeType = "easeInOut" as const,
85 expandDirection = "vertical",
86 expandBehavior = "replace",
87 initialDelay = 0,
88 onExpandStart,
89 onExpandEnd,
90 onCollapseStart,
91 onCollapseEnd,
92 ...props
93 },
94 ref
95 ) => {
96 // Internal state for expansion when the component is uncontrolled
97 const [isExpandedInternal, setIsExpandedInternal] = useState(false)
98
99 // Use the provided expanded prop if available, otherwise use internal state
100 const isExpanded = expanded !== undefined ? expanded : isExpandedInternal
101
102 // Use the provided onToggle function if available, otherwise use internal toggle function
103 const toggleExpand =
104 onToggle || (() => setIsExpandedInternal((prev) => !prev))
105
106 // Effect to call onExpandStart or onCollapseStart when isExpanded changes
107 useEffect(() => {
108 if (isExpanded) {
109 onExpandStart?.()
110 } else {
111 onCollapseStart?.()
112 }
113 }, [isExpanded, onExpandStart, onCollapseStart])
114
115 // Create the context value to be provided to child components
116 const contextValue: ExpandableContextType = {
117 isExpanded,
118 toggleExpand,
119 expandDirection,
120 expandBehavior,
121 transitionDuration,
122 easeType,
123 initialDelay,
124 onExpandEnd,
125 onCollapseEnd,
126 }
127
128 return (
129 <ExpandableContext.Provider value={contextValue}>
130 <motion.div
131 ref={ref}
132 initial={false}
133 transition={{
134 duration: transitionDuration,
135 ease: easeType,
136 delay: initialDelay,
137 }}
138 {...props}
139 >
140 {/* Render children as a function if provided, otherwise render as is */}
141 {typeof children === "function" ? children({ isExpanded }) : children}
142 </motion.div>
143 </ExpandableContext.Provider>
144 )
145 }
146)
147
148// Simplify animation types
149type AnimationPreset = {
150 initial: { [key: string]: any }
151 animate: { [key: string]: any }
152 exit: { [key: string]: any }
153}
154
155// Update ANIMATION_PRESETS type
156const ANIMATION_PRESETS: Record<string, AnimationPreset> = {
157 fade: {
158 initial: { opacity: 0 },
159 animate: { opacity: 1 },
160 exit: { opacity: 0 },
161 },
162 "slide-up": {
163 initial: { opacity: 0, y: 20 },
164 animate: { opacity: 1, y: 0 },
165 exit: { opacity: 0, y: 20 },
166 },
167 "slide-down": {
168 initial: { opacity: 0, y: -20 },
169 animate: { opacity: 1, y: 0 },
170 exit: { opacity: 0, y: -20 },
171 },
172 "slide-left": {
173 initial: { opacity: 0, x: 20 },
174 animate: { opacity: 1, x: 0 },
175 exit: { opacity: 0, x: 20 },
176 },
177 "slide-right": {
178 initial: { opacity: 0, x: -20 },
179 animate: { opacity: 1, x: 0 },
180 exit: { opacity: 0, x: -20 },
181 },
182 scale: {
183 initial: { opacity: 0, scale: 0.8 },
184 animate: { opacity: 1, scale: 1 },
185 exit: { opacity: 0, scale: 0.8 },
186 },
187 rotate: {
188 initial: { opacity: 0, rotate: -10 },
189 animate: { opacity: 1, rotate: 0 },
190 exit: { opacity: 0, rotate: -10 },
191 },
192 "blur-sm": {
193 initial: { opacity: 0, filter: "blur(4px)" },
194 animate: { opacity: 1, filter: "blur(0px)" },
195 exit: { opacity: 0, filter: "blur(4px)" },
196 },
197 "blur-md": {
198 initial: { opacity: 0, filter: "blur(8px)" },
199 animate: { opacity: 1, filter: "blur(0px)" },
200 exit: { opacity: 0, filter: "blur(8px)" },
201 },
202 "blur-lg": {
203 initial: { opacity: 0, filter: "blur(16px)" },
204 animate: { opacity: 1, filter: "blur(0px)" },
205 exit: { opacity: 0, filter: "blur(16px)" },
206 },
207}
208
209// Update type definitions
210type AnimationConfig = {
211 initial: { [key: string]: number | string }
212 animate: { [key: string]: number | string }
213 exit: { [key: string]: number | string }
214}
215
216// Props for defining custom animations
217interface AnimationProps {
218 initial?: TargetAndTransition
219 animate?: TargetAndTransition
220 exit?: TargetAndTransition
221 transition?: any
222}
223
224// Inside ExpandableContent component
225const getAnimationProps = (
226 preset: keyof typeof ANIMATION_PRESETS | undefined,
227 animateIn?: AnimationProps,
228 animateOut?: AnimationProps
229) => {
230 const defaultAnimation = {
231 initial: {},
232 animate: {},
233 exit: {},
234 }
235
236 const presetAnimation = preset ? ANIMATION_PRESETS[preset] : defaultAnimation
237
238 return {
239 initial: presetAnimation.initial,
240 animate: presetAnimation.animate,
241 exit: animateOut?.exit || presetAnimation.exit,
242 }
243}
244
245// Wrap this around items in the card that you want to be hidden then animated in on expansion
246const ExpandableContent = React.forwardRef<
247 HTMLDivElement,
248 Omit<HTMLMotionProps<"div">, "ref"> & {
249 preset?: keyof typeof ANIMATION_PRESETS
250 animateIn?: AnimationProps
251 animateOut?: AnimationProps
252 stagger?: boolean
253 staggerChildren?: number
254 keepMounted?: boolean
255 }
256>(
257 (
258 {
259 children,
260 preset,
261 animateIn,
262 animateOut,
263 stagger = false,
264 staggerChildren = 0.1,
265 keepMounted = false,
266 ...props
267 },
268 ref
269 ) => {
270 const { isExpanded, transitionDuration, easeType } = useExpandable()
271 // useMeasure is used to measure the height of the content
272 const [measureRef, { height: measuredHeight }] = useMeasure()
273 // useMotionValue creates a value that can be animated smoothly
274 const animatedHeight = useMotionValue(0)
275 // useSpring applies a spring animation to the height value
276 const smoothHeight = useSpring(animatedHeight, springConfig)
277
278 useEffect(() => {
279 // Animate the height based on whether the content is expanded or collapsed
280 if (isExpanded) {
281 animatedHeight.set(measuredHeight)
282 } else {
283 animatedHeight.set(0)
284 }
285 }, [isExpanded, measuredHeight, animatedHeight])
286
287 const animationProps = getAnimationProps(preset, animateIn, animateOut)
288
289 return (
290 // This motion.div animates the height of the content
291 <motion.div
292 ref={ref}
293 style={{
294 height: smoothHeight,
295 overflow: "hidden",
296 }}
297 transition={{ duration: transitionDuration, ease: easeType }}
298 {...props}
299 >
300 {/* AnimatePresence handles the entering and exiting of components */}
301 <AnimatePresence initial={false}>
302 {(isExpanded || keepMounted) && (
303 // This motion.div handles the animation of the content itself
304 <motion.div
305 ref={measureRef}
306 initial={animationProps.initial}
307 animate={animationProps.animate}
308 exit={animationProps.exit}
309 transition={{ duration: transitionDuration, ease: easeType }}
310 >
311 {stagger ? (
312 // If stagger is true, we apply a staggered animation to the children
313 <motion.div
314 variants={{
315 hidden: {},
316 visible: {
317 transition: {
318 staggerChildren: staggerChildren,
319 },
320 },
321 }}
322 initial="hidden"
323 animate="visible"
324 >
325 {React.Children.map(
326 children as React.ReactNode,
327 (child, index) => (
328 <motion.div
329 key={`${child?.toLocaleString}-${index}`}
330 variants={{
331 hidden: { opacity: 0, y: 20 },
332 visible: { opacity: 1, y: 0 },
333 }}
334 >
335 {child}
336 </motion.div>
337 )
338 )}
339 </motion.div>
340 ) : (
341 children
342 )}
343 </motion.div>
344 )}
345 </AnimatePresence>
346 </motion.div>
347 )
348 }
349)
350
351interface ExpandableCardProps {
352 children: ReactNode
353 className?: string
354 collapsedSize?: { width?: number; height?: number } // Size when collapsed
355 expandedSize?: { width?: number; height?: number } // Size when expanded
356 hoverToExpand?: boolean // Whether to expand on hover
357 expandDelay?: number // Delay before expanding
358 collapseDelay?: number // Delay before collapsing
359}
360
361const ExpandableCard = React.forwardRef<HTMLDivElement, ExpandableCardProps>(
362 (
363 {
364 children,
365 className = "",
366 collapsedSize = { width: 320, height: 211 },
367 expandedSize = { width: 480, height: undefined },
368 hoverToExpand = false,
369 expandDelay = 0,
370 collapseDelay = 0,
371 ...props
372 },
373 ref
374 ) => {
375 // Get the expansion state and toggle function from the ExpandableContext
376 const { isExpanded, toggleExpand, expandDirection } = useExpandable()
377
378 // Use useMeasure hook to get the dimensions of the content
379 const [measureRef, { width, height }] = useMeasure()
380
381 // Create motion values for width and height
382 const animatedWidth = useMotionValue(collapsedSize.width || 0)
383 const animatedHeight = useMotionValue(collapsedSize.height || 0)
384
385 // Apply spring animation to the motion values
386 const smoothWidth = useSpring(animatedWidth, springConfig)
387 const smoothHeight = useSpring(animatedHeight, springConfig)
388
389 // Effect to update the animated dimensions when expansion state changes
390 useEffect(() => {
391 if (isExpanded) {
392 animatedWidth.set(expandedSize.width || width)
393 animatedHeight.set(expandedSize.height || height)
394 } else {
395 animatedWidth.set(collapsedSize.width || width)
396 animatedHeight.set(collapsedSize.height || height)
397 }
398 }, [
399 isExpanded,
400 collapsedSize,
401 expandedSize,
402 width,
403 height,
404 animatedWidth,
405 animatedHeight,
406 ])
407
408 // Handler for hover start event
409 const handleHover = () => {
410 if (hoverToExpand && !isExpanded) {
411 setTimeout(toggleExpand, expandDelay)
412 }
413 }
414
415 // Handler for hover end event
416 const handleHoverEnd = () => {
417 if (hoverToExpand && isExpanded) {
418 setTimeout(toggleExpand, collapseDelay)
419 }
420 }
421
422 return (
423 <motion.div
424 ref={ref}
425 className={cn("cursor-pointer", className)}
426 style={{
427 // Set width and height based on expansion direction
428 width:
429 expandDirection === "vertical" ? collapsedSize.width : smoothWidth,
430 height:
431 expandDirection === "horizontal"
432 ? collapsedSize.height
433 : smoothHeight,
434 }}
435 transition={springConfig}
436 onHoverStart={handleHover}
437 onHoverEnd={handleHoverEnd}
438 {...props}
439 >
440 <div
441 className={cn(
442 "grid grid-cols-1 rounded-lg sm:rounded-xl md:rounded-[2rem]",
443 "shadow-[inset_0_0_1px_1px_hsl(var(--border)/0.3)] dark:shadow-[inset_0_0_1px_1px_hsl(var(--border)/0.5)]",
444 "sm:shadow-[inset_0_0_2px_1px_hsl(var(--border)/0.3)] dark:sm:shadow-[inset_0_0_2px_1px_hsl(var(--border)/0.5)]",
445 "ring-1 ring-border/50",
446 "max-w-[calc(100%-1rem)] sm:max-w-[calc(100%-2rem)] md:max-w-[calc(100%-4rem)]",
447 "mx-auto w-full",
448 "transition-all duration-300 ease-in-out"
449 )}
450 >
451 {/* Nested divs purely for styling and layout (the shadow ring around the card) */}
452 <div className="grid grid-cols-1 rounded-lg sm:rounded-xl md:rounded-[2rem] p-1 sm:p-1.5 md:p-2 shadow-md">
453 <div className="rounded-md sm:rounded-lg md:rounded-3xl bg-white dark:bg-muted p-2 sm:p-3 md:p-4 shadow-xl ring-1 ring-border/50">
454 <div className="w-full h-full overflow-hidden">
455 {/* Ref for measuring content dimensions (so we can let framer know to animate into the dimensions) */}
456 <div ref={measureRef} className="flex flex-col h-full">
457 {children}
458 </div>
459 </div>
460 </div>
461 </div>
462 </div>
463 </motion.div>
464 )
465 }
466)
467
468ExpandableCard.displayName = "ExpandableCard"
469
470// I'm telling you we just have to expand 🤌💵
471const ExpandableTrigger = React.forwardRef<
472 HTMLDivElement,
473 React.HTMLAttributes<HTMLDivElement>
474>(({ children, className, ...props }, ref) => {
475 const { toggleExpand } = useExpandable()
476
477 const handleKeyDown = (e: React.KeyboardEvent) => {
478 if (e.key === "Enter" || e.key === " ") {
479 e.preventDefault()
480 toggleExpand()
481 }
482 }
483
484 return (
485 <div
486 ref={ref}
487 onClick={toggleExpand}
488 onKeyDown={handleKeyDown}
489 role="button"
490 tabIndex={0}
491 aria-label="Toggle expand"
492 className={cn("cursor-pointer", className)}
493 {...props}
494 >
495 {children}
496 </div>
497 )
498})
499
500ExpandableTrigger.displayName = "ExpandableTrigger"
501
502const ExpandableCardHeader = React.forwardRef<
503 HTMLDivElement,
504 React.HTMLAttributes<HTMLDivElement>
505>(({ className, children, ...props }, ref) => (
506 <div
507 ref={ref}
508 className={cn("flex flex-col space-y-1.5 p-6", className)}
509 {...props}
510 >
511 <motion.div layout className="flex justify-between items-start">
512 {children}
513 </motion.div>
514 </div>
515))
516
517ExpandableCardHeader.displayName = "ExpandableCardHeader"
518
519const ExpandableCardContent = React.forwardRef<
520 HTMLDivElement,
521 React.HTMLAttributes<HTMLDivElement>
522>(({ className, children, ...props }, ref) => (
523 <div
524 ref={ref}
525 className={cn("p-6 pt-0 px-4 overflow-hidden flex-grow", className)}
526 {...props}
527 >
528 <motion.div layout>{children}</motion.div>
529 </div>
530))
531ExpandableCardContent.displayName = "ExpandableCardContent"
532
533const ExpandableCardFooter = React.forwardRef<
534 HTMLDivElement,
535 React.HTMLAttributes<HTMLDivElement>
536>(({ className, ...props }, ref) => (
537 <div
538 ref={ref}
539 className={cn("flex items-center p-4 pt-0", className)}
540 {...props}
541 />
542))
543ExpandableCardFooter.displayName = "ExpandableCardFooter"
544
545export {
546 Expandable,
547 useExpandable,
548 ExpandableCard,
549 ExpandableContent,
550 ExpandableContext,
551 ExpandableTrigger,
552 ExpandableCardHeader,
553 ExpandableCardContent,
554 ExpandableCardFooter,
555}
556