@mantine/hooks
Version:
A collection of 50+ hooks for state and UI management
49 lines (46 loc) • 1.34 kB
JavaScript
'use client';
import { useRef, useState, useEffect } from 'react';
function containsRelatedTarget(event) {
if (event.currentTarget instanceof HTMLElement && event.relatedTarget instanceof HTMLElement) {
return event.currentTarget.contains(event.relatedTarget);
}
return false;
}
function useFocusWithin({
onBlur,
onFocus
} = {}) {
const ref = useRef();
const [focused, setFocused] = useState(false);
const focusedRef = useRef(false);
const _setFocused = (value) => {
setFocused(value);
focusedRef.current = value;
};
const handleFocusIn = (event) => {
if (!focusedRef.current) {
_setFocused(true);
onFocus?.(event);
}
};
const handleFocusOut = (event) => {
if (focusedRef.current && !containsRelatedTarget(event)) {
_setFocused(false);
onBlur?.(event);
}
};
useEffect(() => {
if (ref.current) {
ref.current.addEventListener("focusin", handleFocusIn);
ref.current.addEventListener("focusout", handleFocusOut);
return () => {
ref.current?.removeEventListener("focusin", handleFocusIn);
ref.current?.removeEventListener("focusout", handleFocusOut);
};
}
return void 0;
}, [handleFocusIn, handleFocusOut]);
return { ref, focused };
}
export { useFocusWithin };
//# sourceMappingURL=use-focus-within.mjs.map