timolins / react-hot-toast

Smoking Hot React Notifications 🔥
https://react-hot-toast.com
MIT License
9.66k stars 319 forks source link

fix: issue #367 #368

Open Levix0501 opened 1 month ago

vercel[bot] commented 1 month ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
react-hot-toast ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 22, 2024 9:10am
ultrox commented 1 month ago

I've had a look and found out that this fix only works correctly if you remove all toasts, which toast.remove does as it's overloaded (undefined removes all). Actually I would prefer removeById, but that's another discussion.

I found out that what is not happening is that when you click 'remove' the PAUSE_END action is not fired (onMouseLeave is not triggered).

Either fire this action on remove and dismiss, or extract the logic of this PAUSE_END into a separate function and reuse.

You need to do this because the current fix does not count on the pauseDuration being adjusted. This is revealed when you remove by id and then they all disappear at once after the largest pause, which is not the desired behaviour.

Finally, this is a really tricky bug because `dismiss' is also affected, but because dismiss hides the toast, you accidentally trigger END_PAUSE because wrapper is there and onMouseLeave triggers.

All that to say here is "path" towards fix. This one fixes it but, if you have many of them paused, then when you dismiss/remove one, pause ends.

case ActionType.REMOVE_TOAST: {
      const isPaused = state.pausedAt !== undefined
      let toasts = state.toasts;
      if (isPaused) {
          toasts = compensateForPausedTime(state.toasts, state.pausedAt ?? 0)
      }

      if (action.toastId === undefined) {
        return { ...state, toasts: [] };
      }
      return {
        ...state,
        toasts: toasts
        .filter((t) => t.id !== action.toastId)

      };
    }
    case ActionType.START_PAUSE: {
      return {
        ...state,
        pausedAt: action.time,
      };
    }
    case ActionType.END_PAUSE: {
      return {
        ...state,
        pausedAt: undefined,
        toasts: compensateForPausedTime(state.toasts, state.pausedAt ?? 0),
      };
    }
  }
};

function compensateForPausedTime(toasts: Toast[], pausedAt: number ) {
  debugger;
  return toasts.map(t => {
    const newToast = {
      ...t,
      // adding old pauseDuration allows for multiple pause-resume cycles
      pauseDuration: Date.now() - pausedAt + t.pauseDuration
    }
    return newToast
  })
}