-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathtooltip.tsx
More file actions
301 lines (272 loc) · 7.91 KB
/
tooltip.tsx
File metadata and controls
301 lines (272 loc) · 7.91 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import {
autoUpdate,
computePosition,
flip,
type MiddlewareState,
offset,
shift,
} from '@floating-ui/dom';
import { Slot } from '@radix-ui/react-slot';
import cl from 'clsx/lite';
import type { HTMLAttributes, ReactElement, RefAttributes } from 'react';
import {
Fragment,
forwardRef,
useEffect,
useId,
useRef,
useState,
version,
} from 'react';
import type { DefaultProps } from '../../types';
import type { MergeRight } from '../../utilities';
import { useMergeRefs } from '../../utilities/hooks';
export type TooltipProps = MergeRight<
Omit<DefaultProps, 'data-color'> & HTMLAttributes<HTMLDivElement>,
{
/**
* The element or string that triggers the tooltip.
*
* @note If it is a string, it will be wrapped in a span.
* @note If it is an element, it needs to be able to receive a ref.
*/
children: (ReactElement & RefAttributes<HTMLElement>) | string;
/**
* Content of the tooltip
**/
content: string;
/**
* Placement of the tooltip on the trigger.
* @default 'top'
*/
placement?: 'top' | 'right' | 'bottom' | 'left';
/**
* Whether to enable auto placement.
* @default true
*/
autoPlacement?: boolean;
/**
* Whether the tooltip is open or not.
* This overrides the internal state of the tooltip.
*/
open?: boolean;
/**
* Override if `aria-describedby` or `aria-labelledby` is used.
* By default, if the trigger element has no inner text, `aria-labelledby` is used.
*/
type?: 'describedby' | 'labelledby';
}
>;
/**
* Tooltip component that displays a small piece of information when hovering or focusing on an element.
*
* @example
* <Tooltip content='This is a tooltip'>
* <button>Hover me</button>
* </Tooltip>
*
* @example
* <Tooltip content='This is a tooltip'>
* Hover me
* </Tooltip>
*/
export const Tooltip = forwardRef<HTMLDivElement, TooltipProps>(
function Tooltip(
{
id,
children,
content,
placement = 'top',
autoPlacement = true,
open,
className,
type,
...rest
},
ref,
) {
const randomTooltipId = useId();
const [internalOpen, setInternalOpen] = useState(false);
const triggerRef = useRef<HTMLElement>(null);
const tooltipRef = useRef<HTMLDivElement>(null);
const mergedRefs = useMergeRefs([tooltipRef, ref]);
const controlledOpen = open ?? internalOpen;
const tooltipId = id ?? randomTooltipId;
const setOpen = () => {
setInternalOpen(true);
};
const setClose = () => {
setInternalOpen(false);
};
// Position with floating-ui
useEffect(() => {
const tooltip = tooltipRef.current;
const trigger = triggerRef.current;
tooltip?.togglePopover?.(controlledOpen);
if (tooltip) tooltip.style.opacity = controlledOpen ? '1' : '0';
if (tooltip && trigger && controlledOpen) {
return autoUpdate(trigger, tooltip, () => {
computePosition(trigger, tooltip, {
placement,
strategy: 'fixed',
middleware: [
offset((data) => {
// get pseudo element arrow size
const styles = getComputedStyle(
data.elements.floating,
'::before',
);
return parseFloat(styles.height);
}),
...(autoPlacement
? [flip({ fallbackAxisSideDirection: 'start' }), shift()]
: []),
shift(),
arrowPseudoElement,
safeAreaElement,
],
}).then(({ x, y }) => {
tooltip.style.translate = `${Math.round(x)}px ${Math.round(y)}px`;
});
});
}
}, [controlledOpen, placement]);
/* Add listeners for ESC to dismiss and click outside on mobile */
useEffect(() => {
const tooltip = tooltipRef.current;
const trigger = triggerRef.current;
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
setInternalOpen(false);
}
};
const handleClick = (event: MouseEvent) => {
const el = event.target as Element | null;
const isTooltip = tooltip?.contains(el as Node);
const isTrigger = trigger?.contains(el as Node);
const isOutside = !isTrigger && !isTooltip;
if (isOutside && controlledOpen) {
setInternalOpen(false);
}
};
if (controlledOpen) {
window.addEventListener('keydown', handleKeyDown);
/* Add click listener to handle mobile tap-to-close */
document.addEventListener('click', handleClick);
}
return () => {
window.removeEventListener('keydown', handleKeyDown);
document.removeEventListener('click', handleClick);
};
}, [controlledOpen]);
/* If children is only a string, make a span */
const ChildContainer = typeof children === 'string' ? 'span' : Slot;
/* Make sure it is valid */
if (typeof children !== 'string' && children.type === Fragment) {
console.error(
'<Tooltip> children needs to be a single ReactElement that can receive a ref and not: <Fragment/> | <></>',
);
return null;
}
const popoverProps = {
[version.startsWith('19') ? 'popoverTarget' : 'popovertarget']: tooltipId,
[version.startsWith('19')
? 'popoverTargetAction'
: 'popovertargetaction']: 'show',
};
const autoType = `aria-${triggerRef.current?.innerText.trim() ? 'describedby' : 'labelledby'}`;
return (
<>
<ChildContainer
ref={triggerRef}
{...popoverProps}
onMouseEnter={setOpen}
onMouseLeave={setClose}
onFocus={setOpen}
onBlur={setClose}
{...{ [type ? 'aria-' + type : autoType]: tooltipId }}
>
{children}
</ChildContainer>
<span
onMouseEnter={setOpen}
onMouseLeave={setClose}
ref={mergedRefs}
role='tooltip'
className={cl('ds-tooltip', className)}
id={tooltipId}
popover='manual'
{...rest}
>
{content}
</span>
</>
);
},
);
const arrowPseudoElement = {
name: 'ArrowPseudoElement',
fn(data: MiddlewareState) {
const { elements, rects, placement } = data;
let arrowX = `${Math.round(
rects.reference.width / 2 + rects.reference.x - data.x,
)}px`;
let arrowY = `${Math.round(
rects.reference.height / 2 + rects.reference.y - data.y,
)}px`;
switch (placement) {
case 'top':
arrowY = '100%';
break;
case 'right':
arrowX = '0';
break;
case 'bottom':
arrowY = '0';
break;
case 'left':
arrowX = '100%';
break;
}
elements.floating.style.setProperty('--dsc-tooltip-arrow-x', arrowX);
elements.floating.style.setProperty('--dsc-tooltip-arrow-y', arrowY);
return data;
},
};
const safeAreaElement = {
name: 'SafeAreaElement',
fn(data: MiddlewareState) {
const { elements, placement } = data;
let width = '100%';
let height = 'var(--dsc-tooltip-arrow-size)';
let translate = '0px';
switch (placement) {
case 'top':
translate = `-50% 0%`;
break;
case 'right':
height = '100%';
width = 'var(--dsc-tooltip-arrow-size)';
translate = '-100% -50%';
break;
case 'bottom':
translate = '-50% -100%';
break;
case 'left':
height = '100%';
width = 'var(--dsc-tooltip-arrow-size)';
translate = '0 -50%';
break;
}
elements.floating.style.setProperty(
'--_dsc-tooltip-safearea-height',
height,
);
elements.floating.style.setProperty('--_dsc-tooltip-safearea-width', width);
elements.floating.style.setProperty(
'--_dsc-tooltip-safearea-translate',
translate,
);
return data;
},
};