Skip to content

Commit

Permalink
Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
r100-stack committed Jan 21, 2025
1 parent 6942306 commit 76bede6
Showing 1 changed file with 27 additions and 20 deletions.
47 changes: 27 additions & 20 deletions packages/itwinui-react/src/core/Toast/Toast.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,6 @@ const useAnimateToastBasedOnVisibility = (
const motionOk = useMediaQuery('(prefers-reduced-motion: no-preference)');
const animateOutToRef = useLatestRef(animateOutTo);
const onRemoveRef = useLatestRef(onRemove);
const setShouldBeMountedRef = useLatestRef(setShouldBeMounted);

const [prevIsVisible, setPrevIsVisible] = React.useState<
typeof isVisible | undefined
Expand All @@ -300,25 +299,9 @@ const useAnimateToastBasedOnVisibility = (
setPrevIsVisible(isVisible);

if (isVisible) {
setShouldBeMountedRef.current(true);

// Mount *before* handling dialog entry.
queueMicrotask(() => {
animateIn();
});
safeAnimateIn();
} else {
if (!motionOk) {
setShouldBeMountedRef.current(false);
onRemoveRef.current?.();
} else {
const animation = animateOut();

// Unmount *after* handling dialog exit.
animation?.addEventListener('finish', () => {
setShouldBeMountedRef.current(false);
onRemoveRef.current?.();
});
}
safeAnimateOut();
}
}

Expand All @@ -335,6 +318,30 @@ const useAnimateToastBasedOnVisibility = (
return { translateX, translateY };
}

function safeAnimateIn() {
setShouldBeMounted(true);

// Mount *before* handling dialog entry.
queueMicrotask(() => {
animateIn();
});
}

function safeAnimateOut() {
if (!motionOk) {
setShouldBeMounted(false);
onRemoveRef.current?.();
} else {
const animation = animateOut();

// Unmount *after* handling dialog exit.
animation?.addEventListener('finish', () => {
setShouldBeMounted(false);
onRemoveRef.current?.();
});
}
}

function animateIn() {
if (!motionOk) {
return;
Expand Down Expand Up @@ -385,11 +392,11 @@ const useAnimateToastBasedOnVisibility = (
animateOutTo,
motionOk,
thisElement,
setShouldBeMounted,

// Using latest refs to avoid unnecessary effect executions.
animateOutToRef,
onRemoveRef,
setShouldBeMountedRef,
]);

return shouldBeMounted;
Expand Down

0 comments on commit 76bede6

Please sign in to comment.