2022-12-19 20:13:43 +05:30
|
|
|
import React, { useEffect } from "react";
|
|
|
|
|
|
2024-08-05 20:42:14 +05:30
|
|
|
// TODO: move it to helpers package
|
2022-12-19 20:13:43 +05:30
|
|
|
const useOutsideClickDetector = (ref: React.RefObject<HTMLElement>, callback: () => void) => {
|
|
|
|
|
const handleClick = (event: MouseEvent) => {
|
|
|
|
|
if (ref.current && !ref.current.contains(event.target as Node)) {
|
2024-08-05 20:42:14 +05:30
|
|
|
// get all the element with attribute name data-prevent-outside-click
|
|
|
|
|
const preventOutsideClickElements = document.querySelectorAll("[data-prevent-outside-click]");
|
|
|
|
|
// check if the click target is any of the elements with attribute name data-prevent-outside-click
|
|
|
|
|
for (let i = 0; i < preventOutsideClickElements.length; i++) {
|
|
|
|
|
if (preventOutsideClickElements[i].contains(event.target as Node)) {
|
|
|
|
|
// if the click target is any of the elements with attribute name data-prevent-outside-click, return
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
// get all the element with attribute name data-delay-outside-click
|
|
|
|
|
const delayOutsideClickElements = document.querySelectorAll("[data-delay-outside-click]");
|
|
|
|
|
// check if the click target is any of the elements with attribute name data-delay-outside-click
|
|
|
|
|
for (let i = 0; i < delayOutsideClickElements.length; i++) {
|
|
|
|
|
if (delayOutsideClickElements[i].contains(event.target as Node)) {
|
|
|
|
|
// if the click target is any of the elements with attribute name data-delay-outside-click, delay the callback
|
|
|
|
|
setTimeout(() => {
|
|
|
|
|
callback();
|
|
|
|
|
}, 1);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
// else, call the callback immediately
|
2022-12-19 20:13:43 +05:30
|
|
|
callback();
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
2023-08-19 18:50:12 +05:30
|
|
|
document.addEventListener("mousedown", handleClick);
|
2022-12-19 20:13:43 +05:30
|
|
|
|
|
|
|
|
return () => {
|
2023-08-19 18:50:12 +05:30
|
|
|
document.removeEventListener("mousedown", handleClick);
|
2022-12-19 20:13:43 +05:30
|
|
|
};
|
|
|
|
|
});
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export default useOutsideClickDetector;
|