overleaf/services/web/frontend/js/shared/hooks/use-expand-collapse.js
Jakob Ackermann c6a853c7ed Merge pull request #3332 from overleaf/pr-new-log-entries-ui
New log entries ui

GitOrigin-RevId: a13ccac04197e7c8f3777750b956d550c95c8f0d
2020-11-06 03:04:59 +00:00

55 lines
1.2 KiB
JavaScript

import { useRef, useState, useLayoutEffect } from 'react'
import classNames from 'classnames'
function useExpandCollapse({
initiallyExpanded = false,
collapsedSize = '0',
dimension = 'height',
classes = {}
} = {}) {
const ref = useRef()
const [isExpanded, setIsExpanded] = useState(initiallyExpanded)
const [size, setSize] = useState()
useLayoutEffect(
() => {
const expandCollapseEl = ref.current
if (isExpanded) {
const expandedSize =
dimension === 'height'
? expandCollapseEl.scrollHeight
: expandCollapseEl.scrollWidth
setSize(expandedSize)
} else {
setSize(collapsedSize)
}
},
[isExpanded]
)
const expandableClasses = classNames(
'expand-collapse-container',
classes.container,
!isExpanded ? classes.containerCollapsed : null
)
function handleToggle() {
setIsExpanded(!isExpanded)
}
return {
isExpanded,
expandableProps: {
ref,
style: {
[dimension === 'height' ? 'height' : 'width']: `${size}px`
},
className: expandableClasses
},
toggleProps: {
onClick: handleToggle
}
}
}
export default useExpandCollapse