Skip to content

Commit

Permalink
refactor: remove timeout and add transitionend
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielogregorio committed Jan 10, 2024
1 parent 9e97d8b commit 05d5c92
Showing 1 changed file with 26 additions and 15 deletions.
41 changes: 26 additions & 15 deletions packages/preview-astro/src/components/icondetailmodal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -133,16 +133,14 @@ export function IconDetailModal(
);
}

const TIME_IN_MS_TO_FINISH_CLOSE_ANIMATION = 250;

type useModalAnimationProps = {
onClose?(): void;
isOpen?: boolean;
};

const useModalAnimation = ({ onClose, isOpen }: useModalAnimationProps) => {
const [animationIsOpen, setAnimationIsOpen] = useState(isOpen);
const timeoutRef = useRef<NodeJS.Timeout>();
const modalRef = useRef<HTMLDivElement>(null);

useEffect(() => {
const handleInitOpenAnimation = () => {
Expand All @@ -154,24 +152,37 @@ const useModalAnimation = ({ onClose, isOpen }: useModalAnimationProps) => {
handleInitOpenAnimation();
}, [isOpen]);

const handleCloseModal = () => {
setAnimationIsOpen(false);

timeoutRef.current = setTimeout(() => {
onClose?.();
}, TIME_IN_MS_TO_FINISH_CLOSE_ANIMATION);
};

useEffect(() => {
const modalElement = modalRef.current;

const handleTransitionEnd = () => {
if (!animationIsOpen) {
onClose?.();
}
};

if (modalElement) {
modalElement.addEventListener('transitionend', handleTransitionEnd);
}

return () => {
onClose?.();
clearTimeout(timeoutRef.current);
if (modalElement) {
modalElement.removeEventListener('transitionend', handleTransitionEnd);
}
};
}, []);
}, [animationIsOpen, onClose]);

const handleCloseModal = () => {
console.log('close animation modal')

setAnimationIsOpen(false);
};

return {
animationIsOpen,
handleCloseModal,
modalRef
};
};

Expand All @@ -188,7 +199,7 @@ function Modal({
isOpen,
onClose,
}: ModalProps): React.ReactElement {
const { animationIsOpen, handleCloseModal } = useModalAnimation({
const { animationIsOpen, handleCloseModal, modalRef } = useModalAnimation({
onClose,
isOpen,
});
Expand All @@ -199,7 +210,7 @@ function Modal({
className={`overlay ${animationIsOpen ? "" : "appearing"}`}
onClick={() => handleCloseModal()}
></div>
<div className={`modal-body ${animationIsOpen ? "open" : "close"}`}>
<div className={`modal-body ${animationIsOpen ? "open" : "close"}`} ref={modalRef}>
<div className="header">
<h3 className="title">{title}</h3>
<button
Expand Down

0 comments on commit 05d5c92

Please sign in to comment.