From 88b52d86aba4be37ebc385a7df9c6455022a9b6e Mon Sep 17 00:00:00 2001 From: shuai Date: Wed, 9 Oct 2024 16:30:42 +0800 Subject: [PATCH] fix: Optimize badge animation effect --- ui/src/components/Modal/BadgeModal.tsx | 43 ++++++++++++++++++++------ ui/src/utils/animateGift.ts | 4 ++- 2 files changed, 37 insertions(+), 10 deletions(-) diff --git a/ui/src/components/Modal/BadgeModal.tsx b/ui/src/components/Modal/BadgeModal.tsx index c0cf4cc3c..9c77e9d4b 100644 --- a/ui/src/components/Modal/BadgeModal.tsx +++ b/ui/src/components/Modal/BadgeModal.tsx @@ -66,19 +66,15 @@ const BadgeModal: FC = ({ badge, visible }) => { navigate(url); }; - useEffect(() => { + const initAnimation = () => { const DURATION = 8000; const LENGTH = 200; const bgNode = document.documentElement || document.body; + const parentNode = document.getElementById('badgeModal')?.parentNode; - if (visible) { - const badgeModalNode = document.getElementById('badgeModal'); - const paranetNode = badgeModalNode?.parentNode; - - badgeModalNode?.setAttribute('style', 'z-index: 1'); - + if (parentNode) { bg1 = new AnimateGift({ - elm: paranetNode, + elm: parentNode, width: bgNode.clientWidth, height: bgNode.clientHeight, length: LENGTH, @@ -88,7 +84,7 @@ const BadgeModal: FC = ({ badge, visible }) => { timeout = setTimeout(() => { bg2 = new AnimateGift({ - elm: paranetNode, + elm: parentNode, width: window.innerWidth, height: window.innerHeight, length: LENGTH, @@ -96,6 +92,35 @@ const BadgeModal: FC = ({ badge, visible }) => { }); }, DURATION / 2); } + }; + + const destroyAnimation = () => { + console.log('destroyAnimation'); + clearTimeout(timeout); + bg1?.destroy(); + bg2?.destroy(); + }; + + useEffect(() => { + if (visible) { + initAnimation(); + } else { + destroyAnimation(); + } + + const handleVisibilityChange = () => { + if (document.visibilityState === 'visible') { + initAnimation(); + } else { + destroyAnimation(); + } + }; + document.addEventListener('visibilitychange', handleVisibilityChange); + + return () => { + document.removeEventListener('visibilitychange', handleVisibilityChange); + destroyAnimation(); + }; }, [visible]); return ( diff --git a/ui/src/utils/animateGift.ts b/ui/src/utils/animateGift.ts index c53b2f76e..70137eca4 100644 --- a/ui/src/utils/animateGift.ts +++ b/ui/src/utils/animateGift.ts @@ -178,6 +178,8 @@ export default class Confetti { } destroy() { - this.parent.removeChild(this.canvas); + if (this.parent.contains(this.canvas)) { + this.parent.removeChild(this.canvas); + } } }