Skip to content

Commit

Permalink
fix: incorrect timer on hover (#501)
Browse files Browse the repository at this point in the history
  • Loading branch information
emilkowalski authored Nov 2, 2024
1 parent 5a711d3 commit ff91e0a
Showing 1 changed file with 5 additions and 16 deletions.
21 changes: 5 additions & 16 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ const Toast = (props: ToastProps) => {
const [swipeOut, setSwipeOut] = React.useState(false);
const [offsetBeforeRemove, setOffsetBeforeRemove] = React.useState(0);
const [initialHeight, setInitialHeight] = React.useState(0);
const remainingTime = React.useRef(toast.duration || durationFromToaster || TOAST_LIFETIME);
const dragStartTime = React.useRef<Date | null>(null);
const toastRef = React.useRef<HTMLLIElement>(null);
const isFront = index === 0;
Expand Down Expand Up @@ -172,15 +173,14 @@ const Toast = (props: ToastProps) => {
React.useEffect(() => {
if ((toast.promise && toastType === 'loading') || toast.duration === Infinity || toast.type === 'loading') return;
let timeoutId: NodeJS.Timeout;
let remainingTime = duration;

// Pause the timer on each hover
const pauseTimer = () => {
if (lastCloseTimerStartTimeRef.current < closeTimerStartTimeRef.current) {
// Get the elapsed time since the timer started
const elapsedTime = new Date().getTime() - closeTimerStartTimeRef.current;

remainingTime = remainingTime - elapsedTime;
remainingTime.current = remainingTime.current - elapsedTime;
}

lastCloseTimerStartTimeRef.current = new Date().getTime();
Expand All @@ -190,15 +190,15 @@ const Toast = (props: ToastProps) => {
// setTimeout(, Infinity) behaves as if the delay is 0.
// As a result, the toast would be closed immediately, giving the appearance that it was never rendered.
// See: https://github.com/denysdovhan/wtfjs?tab=readme-ov-file#an-infinite-timeout
if (remainingTime === Infinity) return;
if (remainingTime.current === Infinity) return;

closeTimerStartTimeRef.current = new Date().getTime();

// Let the toast know it has started
timeoutId = setTimeout(() => {
toast.onAutoClose?.(toast);
deleteToast();
}, remainingTime);
}, remainingTime.current);
};

if (expanded || interacting || (pauseWhenPageIsHidden && isDocumentHidden)) {
Expand All @@ -208,18 +208,7 @@ const Toast = (props: ToastProps) => {
}

return () => clearTimeout(timeoutId);
}, [
expanded,
interacting,
expandByDefault,
toast,
duration,
deleteToast,
toast.promise,
toastType,
pauseWhenPageIsHidden,
isDocumentHidden,
]);
}, [expanded, interacting, toast, toastType, pauseWhenPageIsHidden, isDocumentHidden, deleteToast]);

React.useEffect(() => {
if (toast.delete) {
Expand Down

0 comments on commit ff91e0a

Please sign in to comment.