@chayns-components/core
Version:
A set of beautiful React components for developing your own applications with chayns.
99 lines • 3.1 kB
JavaScript
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { StyledMotionDelayedDropdownContent } from './DelayedDropdownContent.styles';
const ANIMATION_DELAY_MS = 200;
var AnimationType = /*#__PURE__*/function (AnimationType) {
AnimationType[AnimationType["None"] = 0] = "None";
AnimationType[AnimationType["Hidden"] = 1] = "Hidden";
AnimationType[AnimationType["Visible"] = 2] = "Visible";
AnimationType[AnimationType["FadeIn"] = 3] = "FadeIn";
AnimationType[AnimationType["FadeOut"] = 4] = "FadeOut";
return AnimationType;
}(AnimationType || {});
const DelayedDropdownContent = ({
children,
shouldShowContent,
onMeasure,
coordinates,
transform
}) => {
const [animationState, setAnimationState] = useState(AnimationType.None);
const ref = useRef();
const timeoutRef = useRef();
const measureElement = useCallback(() => {
if (ref.current) {
const {
height,
width,
x,
y
} = ref.current.getBoundingClientRect();
const {
scrollHeight
} = ref.current;
if (typeof onMeasure === 'function') {
onMeasure({
x,
y,
height,
scrollHeight,
width,
element: ref.current
});
}
setAnimationState(AnimationType.FadeIn);
timeoutRef.current = window.setTimeout(() => {
setAnimationState(AnimationType.Visible);
}, ANIMATION_DELAY_MS);
}
}, [onMeasure]);
useEffect(() => {
if (!shouldShowContent) return () => {};
const observer = new ResizeObserver(() => {
measureElement();
});
if (ref.current) {
observer.observe(ref.current);
}
return () => observer.disconnect();
}, [measureElement, shouldShowContent]);
useEffect(() => {
if (shouldShowContent) {
setAnimationState(AnimationType.Hidden);
} else {
clearTimeout(timeoutRef.current);
setAnimationState(prevState => {
if (prevState === AnimationType.None) {
return prevState;
}
return AnimationType.FadeOut;
});
window.setTimeout(() => {
setAnimationState(AnimationType.None);
}, ANIMATION_DELAY_MS);
}
}, [measureElement, shouldShowContent]);
const refCallback = useCallback(reference => {
ref.current = reference ?? undefined;
measureElement();
}, [measureElement]);
if (animationState === AnimationType.None) {
return null;
}
return /*#__PURE__*/React.createElement(StyledMotionDelayedDropdownContent, {
ref: refCallback,
$coordinates: coordinates,
$transform: transform,
$shouldHideContent: animationState === AnimationType.Hidden,
animate: {
opacity: [AnimationType.FadeIn, AnimationType.Visible].includes(animationState) ? 1 : 0
},
transition: {
duration: ANIMATION_DELAY_MS / 1000,
type: 'tween'
},
inert: !shouldShowContent ? 'true' : undefined
}, children);
};
DelayedDropdownContent.displayName = 'DelayedDropdownContent';
export default DelayedDropdownContent;
//# sourceMappingURL=DelayedDropdownContent.js.map