forked from gitify-app/gitify
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTooltip.tsx
More file actions
104 lines (88 loc) · 2.83 KB
/
Copy pathTooltip.tsx
File metadata and controls
104 lines (88 loc) · 2.83 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { type FC, type ReactNode, useEffect, useRef, useState } from 'react';
import { QuestionIcon } from '@primer/octicons-react';
import { AnchoredOverlay } from '@primer/react';
import { cn } from '../../utils/cn';
export interface TooltipProps {
name: string;
tooltip: ReactNode | string;
}
export const Tooltip: FC<TooltipProps> = (props: TooltipProps) => {
const [showTooltip, setShowTooltip] = useState(false);
const scrollContainerRef = useRef<HTMLElement | null>(null);
const overlayRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!showTooltip) {
return;
}
// Find the scrollable parent container
const findScrollContainer = (
element: HTMLElement | null,
): HTMLElement | null => {
if (!element) {
return null;
}
const { overflow, overflowY } = window.getComputedStyle(element);
const isScrollable = /(auto|scroll)/.test(overflow + overflowY);
if (isScrollable && element.scrollHeight > element.clientHeight) {
return element;
}
return findScrollContainer(element.parentElement);
};
const tooltipButton = document.getElementById(props.name);
scrollContainerRef.current = findScrollContainer(tooltipButton);
const handleScroll = () => {
setShowTooltip(false);
};
const handleClickOutside = (event: MouseEvent) => {
if (
overlayRef.current &&
!overlayRef.current.contains(event.target as Node) &&
!tooltipButton?.contains(event.target as Node)
) {
setShowTooltip(false);
}
};
if (scrollContainerRef.current) {
scrollContainerRef.current.addEventListener('scroll', handleScroll);
}
document.addEventListener('mousedown', handleClickOutside);
return () => {
if (scrollContainerRef.current) {
scrollContainerRef.current.removeEventListener('scroll', handleScroll);
}
document.removeEventListener('mousedown', handleClickOutside);
};
}, [showTooltip, props.name]);
return (
<AnchoredOverlay
align="center"
open={showTooltip}
renderAnchor={(anchorProps) => (
<button
{...anchorProps}
aria-label={props.name}
data-testid={`tooltip-icon-${props.name}`}
id={props.name}
onClick={() => setShowTooltip(!showTooltip)}
type="button"
>
<QuestionIcon className="text-gitify-tooltip-icon" />
</button>
)}
side="outside-bottom"
>
<div
className={cn(
'z-10 w-60 p-2',
'text-left text-xs text-gitify-font',
'rounded-sm border border-gray-300 shadow-sm bg-gitify-tooltip-popout',
)}
data-testid={`tooltip-content-${props.name}`}
ref={overlayRef}
role="tooltip"
>
{props.tooltip}
</div>
</AnchoredOverlay>
);
};