/
useErrorTooltip.ts
45 lines (40 loc) · 1.24 KB
/
useErrorTooltip.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
import type * as React from "react";
import { useRef, useState, useCallback } from "react";
import type { Event } from "../../common/types";
const useErrorTooltip = <T = HTMLInputElement, K = HTMLLabelElement>({
onFocus,
hasTooltip = true,
}: {
onFocus?: Event<React.FocusEvent<T>>;
hasTooltip?: boolean;
}): {
tooltipShown: boolean;
tooltipShownHover: boolean;
setTooltipShown: React.Dispatch<React.SetStateAction<boolean>>;
setTooltipShownHover: React.Dispatch<React.SetStateAction<boolean>>;
labelRef: React.MutableRefObject<K | null>;
iconRef: React.MutableRefObject<HTMLDivElement | null>;
handleFocus: Event<React.FocusEvent<T>>;
} => {
const [tooltipShown, setTooltipShown] = useState(false);
const [tooltipShownHover, setTooltipShownHover] = useState(false);
const labelRef = useRef<K | null>(null);
const iconRef = useRef<HTMLDivElement | null>(null);
const handleFocus = useCallback(
(ev: React.FocusEvent<T>) => {
if (onFocus) onFocus(ev);
if (hasTooltip) setTooltipShown(true);
},
[onFocus, hasTooltip],
);
return {
tooltipShown,
tooltipShownHover,
setTooltipShown,
setTooltipShownHover,
labelRef,
iconRef,
handleFocus,
};
};
export default useErrorTooltip;