cognee/cognee-frontend/src/utils/useOutsideClick.ts
Boris aaa1776293
feat: implement new local UI (#1279)
<!-- .github/pull_request_template.md -->

## Description
<!-- Provide a clear description of the changes in this PR -->

## DCO Affirmation
I affirm that all code in every commit of this pull request conforms to
the terms of the Topoteretes Developer Certificate of Origin.

---------

Co-authored-by: Daulet Amirkhanov <damirkhanov01@gmail.com>
2025-09-05 15:39:04 +02:00

25 lines
729 B
TypeScript

import { useEffect, useRef } from "react";
export default function useOutsideClick<ElementType extends HTMLElement>(callbackFn: () => void, isEnabled = true) {
const rootElementRef = useRef<ElementType>(null);
useEffect(() => {
function handleClickOutside(event: MouseEvent) {
const clickedElement = event.target;
if (clickedElement && rootElementRef.current && !rootElementRef.current?.contains(clickedElement as Node)) {
callbackFn();
}
}
if (isEnabled) {
document.addEventListener("click", handleClickOutside);
return () => {
document.removeEventListener("click", handleClickOutside);
};
}
}, [callbackFn, isEnabled]);
return rootElementRef;
}