2020-11-05 05:22:05 -05:00
|
|
|
import { useRef, useState, useLayoutEffect } from 'react'
|
|
|
|
import classNames from 'classnames'
|
|
|
|
|
|
|
|
function useExpandCollapse({
|
|
|
|
initiallyExpanded = false,
|
|
|
|
collapsedSize = '0',
|
|
|
|
dimension = 'height',
|
2021-04-27 03:52:58 -04:00
|
|
|
classes = {},
|
2020-11-05 05:22:05 -05:00
|
|
|
} = {}) {
|
|
|
|
const ref = useRef()
|
|
|
|
const [isExpanded, setIsExpanded] = useState(initiallyExpanded)
|
2020-12-02 05:03:03 -05:00
|
|
|
const [sizing, setSizing] = useState({
|
|
|
|
size: null,
|
2021-04-27 03:52:58 -04:00
|
|
|
needsExpandCollapse: null,
|
2020-12-02 05:03:03 -05:00
|
|
|
})
|
2020-11-05 05:22:05 -05:00
|
|
|
|
2020-12-15 05:23:54 -05:00
|
|
|
useLayoutEffect(() => {
|
|
|
|
const expandCollapseEl = ref.current
|
|
|
|
if (expandCollapseEl) {
|
|
|
|
const expandedSize =
|
|
|
|
dimension === 'height'
|
|
|
|
? expandCollapseEl.scrollHeight
|
|
|
|
: expandCollapseEl.scrollWidth
|
2020-12-02 05:03:03 -05:00
|
|
|
|
2020-12-15 05:23:54 -05:00
|
|
|
const needsExpandCollapse = expandedSize > collapsedSize
|
2020-12-02 05:03:03 -05:00
|
|
|
|
2020-12-15 05:23:54 -05:00
|
|
|
if (isExpanded) {
|
|
|
|
setSizing({ size: expandedSize, needsExpandCollapse })
|
|
|
|
} else {
|
|
|
|
setSizing({
|
|
|
|
size: needsExpandCollapse ? collapsedSize : expandedSize,
|
2021-04-27 03:52:58 -04:00
|
|
|
needsExpandCollapse,
|
2020-12-15 05:23:54 -05:00
|
|
|
})
|
2020-11-05 05:22:05 -05:00
|
|
|
}
|
2020-12-15 05:23:54 -05:00
|
|
|
}
|
2021-01-07 09:22:19 -05:00
|
|
|
}, [isExpanded, collapsedSize, dimension])
|
2020-11-05 05:22:05 -05:00
|
|
|
|
|
|
|
const expandableClasses = classNames(
|
|
|
|
'expand-collapse-container',
|
|
|
|
classes.container,
|
|
|
|
!isExpanded ? classes.containerCollapsed : null
|
|
|
|
)
|
|
|
|
|
|
|
|
function handleToggle() {
|
|
|
|
setIsExpanded(!isExpanded)
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
isExpanded,
|
2020-12-02 05:03:03 -05:00
|
|
|
needsExpandCollapse: sizing.needsExpandCollapse,
|
2020-11-05 05:22:05 -05:00
|
|
|
expandableProps: {
|
|
|
|
ref,
|
|
|
|
style: {
|
2021-04-27 03:52:58 -04:00
|
|
|
[dimension === 'height' ? 'height' : 'width']: `${sizing.size}px`,
|
2020-11-05 05:22:05 -05:00
|
|
|
},
|
2021-04-27 03:52:58 -04:00
|
|
|
className: expandableClasses,
|
2020-11-05 05:22:05 -05:00
|
|
|
},
|
|
|
|
toggleProps: {
|
2021-04-27 03:52:58 -04:00
|
|
|
onClick: handleToggle,
|
|
|
|
},
|
2020-11-05 05:22:05 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default useExpandCollapse
|