Skip to content

Commit

Permalink
fix: Better Popper Timeout Tracking
Browse files Browse the repository at this point in the history
We noticed that Popper was sometimes closing the dorpdown inaccurately.
This was pinned down to timeouts being incorrectly cleared, and thefore
sometimes running when they ought not to. Careful examination of the
code revealed that they weren't being tracked very well, and thus stomped on
or lost.

This approach leverages a ref to track the value to avoid loss during
re-renders, and to also avoid unnecessary re-renders.
  • Loading branch information
jherdman committed May 28, 2024
1 parent 56079b7 commit 2a28fb0
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions src/Popper/Popper.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// @ts-nocheck
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, useRef } from "react";
import { Manager, Reference, Popper as ReactPopperPopUp } from "react-popper";
import { useTranslation } from "react-i18next";
import { PopperArrow } from "../utils";
Expand Down Expand Up @@ -49,20 +49,28 @@ const Popper: React.FC<PopperProps> = React.forwardRef(
},
popperRef
) => {
let timeoutID;
// We're going to manage the ID of the timeout in a ref so that we can examine
// it without causing a re-render. Note that "0" will denote "no jobs running",
// whereas positive values are the ID of the running job.
const timeoutId = useRef(0);

const resetTimeoutId = () => {
clearTimeout(timeoutId.current);
timeoutId.current = 0;
};

const [isOpen, setIsOpen] = useState(defaultOpen);

const conditionallyApplyDelay = (fnc: () => void, delay: number, skipDelay = true) => {
if (!skipDelay) {
timeoutID = setTimeout(fnc, delay);
timeoutId.current = setTimeout(fnc, delay);
} else {
fnc();
}
};

const setPopUpState = (nextIsOpenState: boolean, skipDelay: boolean) => {
clearTimeout(timeoutID);
resetTimeoutId();
conditionallyApplyDelay(() => setIsOpen(nextIsOpenState), nextIsOpenState ? showDelay : hideDelay, skipDelay);
};

Expand All @@ -85,7 +93,7 @@ const Popper: React.FC<PopperProps> = React.forwardRef(

const cleanup = () => {
document.removeEventListener("keydown", handleKeyDown);
clearTimeout(timeoutID);
resetTimeoutId();
};
return cleanup;
}, []);
Expand Down

0 comments on commit 2a28fb0

Please sign in to comment.