Raw
1 "use client"
2
3 import React, { useState } from "react"
4 // @ts-expect-error can't install the types package because it doesn't support React v19
5 import { CSSTransition } from "react-transition-group"
6
7 export type CollapsibleProps = {
8 initialValue?: boolean
9 heightAnimation?: boolean
10 translateEnabled?: boolean
11 onClose?: () => void
12 unmountOnExit?: boolean
13 childrenRef?: React.RefObject<HTMLElement | null>
14 useChild?: boolean
15 }
16
17 export type CollapsibleReturn = {
18 getCollapsibleElms: (children: React.ReactNode) => React.JSX.Element
19 collapsed: boolean
20 setCollapsed: React.Dispatch<React.SetStateAction<boolean>>
21 }
22
23 export const useCollapsible = ({
24 initialValue = true,
25 heightAnimation = false,
26 translateEnabled = true,
27 onClose,
28 unmountOnExit = true,
29 childrenRef,
30 useChild = true,
31 }: CollapsibleProps): CollapsibleReturn => {
32 const [collapsed, setCollapsed] = useState(initialValue)
33
34 const getNodeFromChildrenRef = () => {
35 if (!useChild) {
36 return childrenRef?.current
37 }
38
39 return (
40 (childrenRef?.current?.firstElementChild as HTMLElement) ||
41 childrenRef?.current
42 )
43 }
44
45 const getCollapsibleElms = (children: React.ReactNode) => {
46 return (
47 <CSSTransition
48 unmountOnExit={unmountOnExit}
49 in={!collapsed}
50 timeout={150}
51 nodeRef={childrenRef}
52 onEnter={() => {
53 const node = getNodeFromChildrenRef()
54 if (!node) {
55 return
56 }
57
58 if (heightAnimation) {
59 node.classList.add("transition-[height]")
60 node.style.height = `0px`
61 } else {
62 node.classList.add("!mb-docs_2", "!mt-0")
63 if (translateEnabled) {
64 node.classList.add("translate-y-docs_1", "transition-transform")
65 }
66 }
67 }}
68 onEntering={() => {
69 const node = getNodeFromChildrenRef()
70 if (!node) {
71 return
72 }
73
74 if (heightAnimation) {
75 node.style.height = `${node.scrollHeight}px`
76 }
77 }}
78 onEntered={() => {
79 const node = getNodeFromChildrenRef()
80 if (!node) {
81 return
82 }
83
84 if (heightAnimation) {
85 node.style.height = `auto`
86 }
87 }}
88 onExit={() => {
89 const node = getNodeFromChildrenRef()
90 if (!node) {
91 return
92 }
93
94 if (heightAnimation) {
95 node.style.height = `${node.scrollHeight}px`
96 } else {
97 if (translateEnabled) {
98 node.classList.add("transition-transform", "!-translate-y-docs_1")
99 }
100 setTimeout(() => {
101 onClose?.()
102 }, 100)
103 }
104 }}
105 onExiting={() => {
106 const node = getNodeFromChildrenRef()
107 if (!node) {
108 return
109 }
110
111 if (heightAnimation) {
112 node.style.height = `0px`
113 setTimeout(() => {
114 onClose?.()
115 }, 100)
116 }
117 }}
118 >
119 {children}
120 </CSSTransition>
121 )
122 }
123
124 return {
125 getCollapsibleElms,
126 collapsed,
127 setCollapsed,
128 }
129 }