forked from mantinedev/mantine
/
use-focus-within.ts
57 lines (47 loc) · 1.51 KB
/
use-focus-within.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { useRef, useState, useEffect } from 'react';
export interface UseFocusWithinOptions {
onFocus?(event: FocusEvent): void;
onBlur?(event: FocusEvent): void;
}
function containsRelatedTarget(event: FocusEvent) {
if (event.currentTarget instanceof HTMLElement && event.relatedTarget instanceof HTMLElement) {
return event.currentTarget.contains(event.relatedTarget);
}
return false;
}
export function useFocusWithin<T extends HTMLElement = any>({
onBlur,
onFocus,
}: UseFocusWithinOptions = {}): { ref: React.MutableRefObject<T>; focused: boolean } {
const ref = useRef<T>();
const [focused, _setFocused] = useState(false);
const focusedRef = useRef(false);
const setFocused = (value: boolean) => {
_setFocused(value);
focusedRef.current = value;
};
const handleFocusIn = (event: FocusEvent) => {
if (!focusedRef.current) {
setFocused(true);
onFocus?.(event);
}
};
const handleFocusOut = (event: FocusEvent) => {
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 undefined;
}, [handleFocusIn, handleFocusOut]);
return { ref, focused };
}