@navinc/base-react-components
Version:
Nav's Pattern Library
51 lines • 2.47 kB
JavaScript
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { jsx as _jsx } from "react/jsx-runtime";
import { useState, useRef, useMemo, useEffect } from 'react';
import debounce from 'lodash.debounce';
import styled from 'styled-components';
const AnimateHeightContainer = styled.div.withConfig({ displayName: "brc-sc-AnimateHeightContainer", componentId: "brc-sc-uxntoa" }) `
overflow: hidden;
height: ${({ height }) => (height === 'auto' ? 'auto' : `${Math.ceil(height)}px`)};
transition: height 0.4s ease-in-out;
will-change: height;
`;
AnimateHeightContainer.displayName = 'AnimateHeightContainer';
export const AnimateHeight = (_a) => {
var { children } = _a, props = __rest(_a, ["children"]);
const [contentHeight, setContentHeight] = useState('auto');
const contentRef = useRef(null);
const setHeight = useMemo(() => debounce(() => {
window.requestAnimationFrame(() => {
var _a, _b;
setContentHeight((_b = (_a = contentRef === null || contentRef === void 0 ? void 0 : contentRef.current) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect().height) !== null && _b !== void 0 ? _b : 'auto');
});
}, 100), []);
useEffect(() => {
window.addEventListener('resize', setHeight);
// ResizeObserver is not available in older browsers like Safari v12
const observer = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(setHeight) : undefined;
if (observer) {
observer.observe(contentRef.current);
}
return () => {
setHeight.cancel();
window.removeEventListener('resize', setHeight);
if (observer) {
observer.disconnect();
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (_jsx(AnimateHeightContainer, Object.assign({}, props, { height: contentHeight, children: _jsx("div", { ref: contentRef, children: children }) })));
};
//# sourceMappingURL=animate-height.js.map