2025-10-14 16:45:07 +05:30
|
|
|
import type React from "react";
|
2025-11-25 18:52:20 +05:30
|
|
|
import { useEffect, useCallback } from "react";
|
2025-02-17 23:46:55 +05:30
|
|
|
|
|
|
|
|
const useExtendedSidebarOutsideClickDetector = (
|
|
|
|
|
ref: React.RefObject<HTMLElement>,
|
|
|
|
|
callback: () => void,
|
|
|
|
|
targetId: string
|
|
|
|
|
) => {
|
2025-11-25 18:52:20 +05:30
|
|
|
const handleClick = useCallback(
|
|
|
|
|
(event: MouseEvent) => {
|
|
|
|
|
if (!(event.target instanceof HTMLElement)) return;
|
|
|
|
|
if (ref.current && !ref.current.contains(event.target)) {
|
|
|
|
|
// check for the closest element with attribute name data-prevent-outside-click
|
|
|
|
|
const preventOutsideClickElement = event.target.closest("[data-prevent-outside-click]");
|
|
|
|
|
// if the closest element with attribute name data-prevent-outside-click is found, return
|
|
|
|
|
if (preventOutsideClickElement) {
|
2025-02-17 23:46:55 +05:30
|
|
|
return;
|
|
|
|
|
}
|
2025-11-25 18:52:20 +05:30
|
|
|
// check if the click target is the current issue element or its children
|
|
|
|
|
let targetElement: HTMLElement | null = event.target;
|
|
|
|
|
while (targetElement) {
|
|
|
|
|
if (targetElement.id === targetId) {
|
|
|
|
|
// if the click target is the current issue element, return
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
targetElement = targetElement.parentElement;
|
|
|
|
|
}
|
|
|
|
|
const delayOutsideClickElement = event.target.closest("[data-delay-outside-click]");
|
|
|
|
|
if (delayOutsideClickElement) {
|
|
|
|
|
// if the click target is the closest element with attribute name data-delay-outside-click, delay the callback
|
|
|
|
|
setTimeout(() => {
|
|
|
|
|
callback();
|
|
|
|
|
}, 0);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
// else, call the callback immediately
|
|
|
|
|
callback();
|
2025-02-17 23:46:55 +05:30
|
|
|
}
|
2025-11-25 18:52:20 +05:30
|
|
|
},
|
|
|
|
|
[ref, callback, targetId]
|
|
|
|
|
);
|
2025-02-17 23:46:55 +05:30
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
document.addEventListener("mousedown", handleClick);
|
|
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
|
document.removeEventListener("mousedown", handleClick);
|
|
|
|
|
};
|
2025-11-25 18:52:20 +05:30
|
|
|
}, [handleClick]);
|
2025-02-17 23:46:55 +05:30
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export default useExtendedSidebarOutsideClickDetector;
|