forked from ReactTooltip/react-tooltip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTooltip.tsx
645 lines (599 loc) · 18.5 KB
/
Tooltip.tsx
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
import React, { useEffect, useState, useRef } from 'react'
import classNames from 'classnames'
import debounce from 'utils/debounce'
import { useTooltip } from 'components/TooltipProvider'
import useIsomorphicLayoutEffect from 'utils/use-isomorphic-layout-effect'
import { autoUpdate } from '@floating-ui/dom'
import { getScrollParent } from 'utils/get-scroll-parent'
import { computeTooltipPosition } from 'utils/compute-positions'
import coreStyles from './core-styles.module.css'
import styles from './styles.module.css'
import type { IPosition, ITooltip, PlacesType } from './TooltipTypes'
const Tooltip = ({
// props
id,
className,
classNameArrow,
variant = 'dark',
anchorId,
anchorSelect,
place = 'top',
offset = 10,
events = ['hover'],
openOnClick = false,
positionStrategy = 'absolute',
middlewares,
wrapper: WrapperElement,
delayShow = 0,
delayHide = 0,
float = false,
hidden = false,
noArrow = false,
clickable = false,
closeOnEsc = false,
closeOnScroll = false,
closeOnResize = false,
style: externalStyles,
position,
afterShow,
afterHide,
// props handled by controller
content,
contentWrapperRef,
isOpen,
setIsOpen,
activeAnchor,
setActiveAnchor,
border,
opacity,
}: ITooltip) => {
const tooltipRef = useRef<HTMLElement>(null)
const tooltipArrowRef = useRef<HTMLElement>(null)
const tooltipShowDelayTimerRef = useRef<NodeJS.Timeout | null>(null)
const tooltipHideDelayTimerRef = useRef<NodeJS.Timeout | null>(null)
const [actualPlacement, setActualPlacement] = useState(place)
const [inlineStyles, setInlineStyles] = useState({})
const [inlineArrowStyles, setInlineArrowStyles] = useState({})
const [show, setShow] = useState(false)
const [rendered, setRendered] = useState(false)
const wasShowing = useRef(false)
const lastFloatPosition = useRef<IPosition | null>(null)
/**
* @todo Remove this in a future version (provider/wrapper method is deprecated)
*/
const { anchorRefs, setActiveAnchor: setProviderActiveAnchor } = useTooltip(id)
const hoveringTooltip = useRef(false)
const [anchorsBySelect, setAnchorsBySelect] = useState<HTMLElement[]>([])
const mounted = useRef(false)
const shouldOpenOnClick = openOnClick || events.includes('click')
/**
* useLayoutEffect runs before useEffect,
* but should be used carefully because of caveats
* https://beta.reactjs.org/reference/react/useLayoutEffect#caveats
*/
useIsomorphicLayoutEffect(() => {
mounted.current = true
return () => {
mounted.current = false
}
}, [])
useEffect(() => {
if (!show) {
/**
* this fixes weird behavior when switching between two anchor elements very quickly
* remove the timeout and switch quickly between two adjancent anchor elements to see it
*
* in practice, this means the tooltip is not immediately removed from the DOM on hide
*/
const timeout = setTimeout(() => {
setRendered(false)
}, 150)
return () => {
clearTimeout(timeout)
}
}
return () => null
}, [show])
const handleShow = (value: boolean) => {
if (!mounted.current) {
return
}
if (value) {
setRendered(true)
}
/**
* wait for the component to render and calculate position
* before actually showing
*/
setTimeout(() => {
if (!mounted.current) {
return
}
setIsOpen?.(value)
if (isOpen === undefined) {
setShow(value)
}
}, 10)
}
/**
* this replicates the effect from `handleShow()`
* when `isOpen` is changed from outside
*/
useEffect(() => {
if (isOpen === undefined) {
return () => null
}
if (isOpen) {
setRendered(true)
}
const timeout = setTimeout(() => {
setShow(isOpen)
}, 10)
return () => {
clearTimeout(timeout)
}
}, [isOpen])
useEffect(() => {
if (show === wasShowing.current) {
return
}
wasShowing.current = show
if (show) {
afterShow?.()
} else {
afterHide?.()
}
}, [show])
const handleShowTooltipDelayed = () => {
if (tooltipShowDelayTimerRef.current) {
clearTimeout(tooltipShowDelayTimerRef.current)
}
tooltipShowDelayTimerRef.current = setTimeout(() => {
handleShow(true)
}, delayShow)
}
const handleHideTooltipDelayed = (delay = delayHide) => {
if (tooltipHideDelayTimerRef.current) {
clearTimeout(tooltipHideDelayTimerRef.current)
}
tooltipHideDelayTimerRef.current = setTimeout(() => {
if (hoveringTooltip.current) {
return
}
handleShow(false)
}, delay)
}
const handleShowTooltip = (event?: Event) => {
if (!event) {
return
}
const target = (event.currentTarget ?? event.target) as HTMLElement | null
if (!target?.isConnected) {
/**
* this happens when the target is removed from the DOM
* at the same time the tooltip gets triggered
*/
setActiveAnchor(null)
setProviderActiveAnchor({ current: null })
return
}
if (delayShow) {
handleShowTooltipDelayed()
} else {
handleShow(true)
}
setActiveAnchor(target)
setProviderActiveAnchor({ current: target })
if (tooltipHideDelayTimerRef.current) {
clearTimeout(tooltipHideDelayTimerRef.current)
}
}
const handleHideTooltip = () => {
if (clickable) {
// allow time for the mouse to reach the tooltip, in case there's a gap
handleHideTooltipDelayed(delayHide || 100)
} else if (delayHide) {
handleHideTooltipDelayed()
} else {
handleShow(false)
}
if (tooltipShowDelayTimerRef.current) {
clearTimeout(tooltipShowDelayTimerRef.current)
}
}
const handleTooltipPosition = ({ x, y }: IPosition) => {
const virtualElement = {
getBoundingClientRect() {
return {
x,
y,
width: 0,
height: 0,
top: y,
left: x,
right: x,
bottom: y,
}
},
} as Element
computeTooltipPosition({
place,
offset,
elementReference: virtualElement,
tooltipReference: tooltipRef.current,
tooltipArrowReference: tooltipArrowRef.current,
strategy: positionStrategy,
middlewares,
border,
}).then((computedStylesData) => {
if (Object.keys(computedStylesData.tooltipStyles).length) {
setInlineStyles(computedStylesData.tooltipStyles)
}
if (Object.keys(computedStylesData.tooltipArrowStyles).length) {
setInlineArrowStyles(computedStylesData.tooltipArrowStyles)
}
setActualPlacement(computedStylesData.place as PlacesType)
})
}
const handleMouseMove = (event?: Event) => {
if (!event) {
return
}
const mouseEvent = event as MouseEvent
const mousePosition = {
x: mouseEvent.clientX,
y: mouseEvent.clientY,
}
handleTooltipPosition(mousePosition)
lastFloatPosition.current = mousePosition
}
const handleClickTooltipAnchor = (event?: Event) => {
handleShowTooltip(event)
if (delayHide) {
handleHideTooltipDelayed()
}
}
const handleClickOutsideAnchors = (event: MouseEvent) => {
const anchorById = document.querySelector<HTMLElement>(`[id='${anchorId}']`)
const anchors = [anchorById, ...anchorsBySelect]
if (anchors.some((anchor) => anchor?.contains(event.target as HTMLElement))) {
return
}
if (tooltipRef.current?.contains(event.target as HTMLElement)) {
return
}
handleShow(false)
if (tooltipShowDelayTimerRef.current) {
clearTimeout(tooltipShowDelayTimerRef.current)
}
}
// debounce handler to prevent call twice when
// mouse enter and focus events being triggered toggether
const debouncedHandleShowTooltip = debounce(handleShowTooltip, 50, true)
const debouncedHandleHideTooltip = debounce(handleHideTooltip, 50, true)
const updateTooltipPosition = () => {
if (position) {
// if `position` is set, override regular and `float` positioning
handleTooltipPosition(position)
return
}
if (float) {
if (lastFloatPosition.current) {
/*
Without this, changes to `content`, `place`, `offset`, ..., will only
trigger a position calculation after a `mousemove` event.
To see why this matters, comment this line, run `yarn dev` and click the
"Hover me!" anchor.
*/
handleTooltipPosition(lastFloatPosition.current)
}
// if `float` is set, override regular positioning
return
}
computeTooltipPosition({
place,
offset,
elementReference: activeAnchor,
tooltipReference: tooltipRef.current,
tooltipArrowReference: tooltipArrowRef.current,
strategy: positionStrategy,
middlewares,
border,
}).then((computedStylesData) => {
if (!mounted.current) {
// invalidate computed positions after remount
return
}
if (Object.keys(computedStylesData.tooltipStyles).length) {
setInlineStyles(computedStylesData.tooltipStyles)
}
if (Object.keys(computedStylesData.tooltipArrowStyles).length) {
setInlineArrowStyles(computedStylesData.tooltipArrowStyles)
}
setActualPlacement(computedStylesData.place as PlacesType)
})
}
useEffect(() => {
const elementRefs = new Set(anchorRefs)
anchorsBySelect.forEach((anchor) => {
elementRefs.add({ current: anchor })
})
const anchorById = document.querySelector<HTMLElement>(`[id='${anchorId}']`)
if (anchorById) {
elementRefs.add({ current: anchorById })
}
const handleScrollResize = () => {
handleShow(false)
}
const anchorScrollParent = getScrollParent(activeAnchor)
const tooltipScrollParent = getScrollParent(tooltipRef.current)
if (closeOnScroll) {
window.addEventListener('scroll', handleScrollResize)
anchorScrollParent?.addEventListener('scroll', handleScrollResize)
tooltipScrollParent?.addEventListener('scroll', handleScrollResize)
}
let updateTooltipCleanup: null | (() => void) = null
if (closeOnResize) {
window.addEventListener('resize', handleScrollResize)
} else if (activeAnchor && tooltipRef.current) {
updateTooltipCleanup = autoUpdate(
activeAnchor as HTMLElement,
tooltipRef.current as HTMLElement,
updateTooltipPosition,
{
ancestorResize: true,
elementResize: true,
layoutShift: true,
},
)
}
const handleEsc = (event: KeyboardEvent) => {
if (event.key !== 'Escape') {
return
}
handleShow(false)
}
if (closeOnEsc) {
window.addEventListener('keydown', handleEsc)
}
const enabledEvents: { event: string; listener: (event?: Event) => void }[] = []
if (shouldOpenOnClick) {
window.addEventListener('click', handleClickOutsideAnchors)
enabledEvents.push({ event: 'click', listener: handleClickTooltipAnchor })
} else {
enabledEvents.push(
{ event: 'mouseenter', listener: debouncedHandleShowTooltip },
{ event: 'mouseleave', listener: debouncedHandleHideTooltip },
{ event: 'focus', listener: debouncedHandleShowTooltip },
{ event: 'blur', listener: debouncedHandleHideTooltip },
)
if (float) {
enabledEvents.push({
event: 'mousemove',
listener: handleMouseMove,
})
}
}
const handleMouseEnterTooltip = () => {
hoveringTooltip.current = true
}
const handleMouseLeaveTooltip = () => {
hoveringTooltip.current = false
handleHideTooltip()
}
if (clickable && !shouldOpenOnClick) {
tooltipRef.current?.addEventListener('mouseenter', handleMouseEnterTooltip)
tooltipRef.current?.addEventListener('mouseleave', handleMouseLeaveTooltip)
}
enabledEvents.forEach(({ event, listener }) => {
elementRefs.forEach((ref) => {
ref.current?.addEventListener(event, listener)
})
})
return () => {
if (closeOnScroll) {
window.removeEventListener('scroll', handleScrollResize)
anchorScrollParent?.removeEventListener('scroll', handleScrollResize)
tooltipScrollParent?.removeEventListener('scroll', handleScrollResize)
}
if (closeOnResize) {
window.removeEventListener('resize', handleScrollResize)
} else {
updateTooltipCleanup?.()
}
if (shouldOpenOnClick) {
window.removeEventListener('click', handleClickOutsideAnchors)
}
if (closeOnEsc) {
window.removeEventListener('keydown', handleEsc)
}
if (clickable && !shouldOpenOnClick) {
tooltipRef.current?.removeEventListener('mouseenter', handleMouseEnterTooltip)
tooltipRef.current?.removeEventListener('mouseleave', handleMouseLeaveTooltip)
}
enabledEvents.forEach(({ event, listener }) => {
elementRefs.forEach((ref) => {
ref.current?.removeEventListener(event, listener)
})
})
}
/**
* rendered is also a dependency to ensure anchor observers are re-registered
* since `tooltipRef` becomes stale after removing/adding the tooltip to the DOM
*/
}, [rendered, anchorRefs, anchorsBySelect, closeOnEsc, events])
useEffect(() => {
let selector = anchorSelect ?? ''
if (!selector && id) {
selector = `[data-tooltip-id='${id}']`
}
const documentObserverCallback: MutationCallback = (mutationList) => {
const newAnchors: HTMLElement[] = []
mutationList.forEach((mutation) => {
if (mutation.type === 'attributes' && mutation.attributeName === 'data-tooltip-id') {
const newId = (mutation.target as HTMLElement).getAttribute('data-tooltip-id')
if (newId === id) {
newAnchors.push(mutation.target as HTMLElement)
}
}
if (mutation.type !== 'childList') {
return
}
if (activeAnchor) {
;[...mutation.removedNodes].some((node) => {
if (node?.contains?.(activeAnchor)) {
setRendered(false)
handleShow(false)
setActiveAnchor(null)
if (tooltipShowDelayTimerRef.current) {
clearTimeout(tooltipShowDelayTimerRef.current)
}
if (tooltipHideDelayTimerRef.current) {
clearTimeout(tooltipHideDelayTimerRef.current)
}
return true
}
return false
})
}
if (!selector) {
return
}
try {
const elements = [...mutation.addedNodes].filter((node) => node.nodeType === 1)
newAnchors.push(
// the element itself is an anchor
...(elements.filter((element) =>
(element as HTMLElement).matches(selector),
) as HTMLElement[]),
)
newAnchors.push(
// the element has children which are anchors
...elements.flatMap(
(element) =>
[...(element as HTMLElement).querySelectorAll(selector)] as HTMLElement[],
),
)
} catch {
/**
* invalid CSS selector.
* already warned on tooltip controller
*/
}
})
if (newAnchors.length) {
setAnchorsBySelect((anchors) => [...anchors, ...newAnchors])
}
}
const documentObserver = new MutationObserver(documentObserverCallback)
// watch for anchor being removed from the DOM
documentObserver.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['data-tooltip-id'],
})
return () => {
documentObserver.disconnect()
}
}, [id, anchorSelect, activeAnchor])
useEffect(() => {
updateTooltipPosition()
}, [show, activeAnchor, content, externalStyles, place, offset, positionStrategy, position])
useEffect(() => {
if (!contentWrapperRef?.current) {
return () => null
}
const contentObserver = new ResizeObserver(() => {
updateTooltipPosition()
})
contentObserver.observe(contentWrapperRef.current)
return () => {
contentObserver.disconnect()
}
}, [content, contentWrapperRef?.current])
useEffect(() => {
const anchorById = document.querySelector<HTMLElement>(`[id='${anchorId}']`)
const anchors = [...anchorsBySelect, anchorById]
if (!activeAnchor || !anchors.includes(activeAnchor)) {
/**
* if there is no active anchor,
* or if the current active anchor is not amongst the allowed ones,
* reset it
*/
setActiveAnchor(anchorsBySelect[0] ?? anchorById)
}
}, [anchorId, anchorsBySelect, activeAnchor])
useEffect(() => {
return () => {
if (tooltipShowDelayTimerRef.current) {
clearTimeout(tooltipShowDelayTimerRef.current)
}
if (tooltipHideDelayTimerRef.current) {
clearTimeout(tooltipHideDelayTimerRef.current)
}
}
}, [])
useEffect(() => {
let selector = anchorSelect
if (!selector && id) {
selector = `[data-tooltip-id='${id}']`
}
if (!selector) {
return
}
try {
const anchors = Array.from(document.querySelectorAll<HTMLElement>(selector))
setAnchorsBySelect(anchors)
} catch {
// warning was already issued in the controller
setAnchorsBySelect([])
}
}, [id, anchorSelect])
const canShow = !hidden && content && show && Object.keys(inlineStyles).length > 0
return rendered ? (
<WrapperElement
id={id}
role="tooltip"
className={classNames(
'react-tooltip',
coreStyles['tooltip'],
styles['tooltip'],
styles[variant],
className,
`react-tooltip__place-${actualPlacement}`,
{
[coreStyles['show']]: canShow,
[coreStyles['fixed']]: positionStrategy === 'fixed',
[coreStyles['clickable']]: clickable,
},
)}
style={{
...externalStyles,
...inlineStyles,
opacity: opacity !== undefined && canShow ? opacity : undefined,
}}
ref={tooltipRef}
>
{content}
<WrapperElement
className={classNames(
'react-tooltip-arrow',
coreStyles['arrow'],
styles['arrow'],
classNameArrow,
{
/**
* changed from dash `no-arrow` to camelcase because of:
* https://github.com/indooorsman/esbuild-css-modules-plugin/issues/42
*/
[coreStyles['noArrow']]: noArrow,
},
)}
style={inlineArrowStyles}
ref={tooltipArrowRef}
/>
</WrapperElement>
) : null
}
export default Tooltip