react-tooltip 5.10.5-beta.996.1 → 5.10.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,858 @@
1
+ import React, { createContext, useState, useCallback, useMemo, useContext, useRef, useEffect, useLayoutEffect } from 'react';
2
+ import classNames from 'classnames';
3
+ import { arrow, computePosition, offset, flip, shift } from '@floating-ui/dom';
4
+
5
+ /* eslint-disable @typescript-eslint/no-explicit-any */
6
+ /**
7
+ * This function debounce the received function
8
+ * @param { function } func Function to be debounced
9
+ * @param { number } wait Time to wait before execut the function
10
+ * @param { boolean } immediate Param to define if the function will be executed immediately
11
+ */
12
+ const debounce = (func, wait, immediate) => {
13
+ let timeout = null;
14
+ return function debounced(...args) {
15
+ const later = () => {
16
+ timeout = null;
17
+ if (!immediate) {
18
+ func.apply(this, args);
19
+ }
20
+ };
21
+ if (timeout) {
22
+ clearTimeout(timeout);
23
+ }
24
+ timeout = setTimeout(later, wait);
25
+ };
26
+ };
27
+
28
+ const DEFAULT_TOOLTIP_ID = 'DEFAULT_TOOLTIP_ID';
29
+ const DEFAULT_CONTEXT_DATA = {
30
+ anchorRefs: new Set(),
31
+ activeAnchor: { current: null },
32
+ attach: () => {
33
+ /* attach anchor element */
34
+ },
35
+ detach: () => {
36
+ /* detach anchor element */
37
+ },
38
+ setActiveAnchor: () => {
39
+ /* set active anchor */
40
+ },
41
+ };
42
+ const DEFAULT_CONTEXT_DATA_WRAPPER = {
43
+ getTooltipData: () => DEFAULT_CONTEXT_DATA,
44
+ };
45
+ const TooltipContext = createContext(DEFAULT_CONTEXT_DATA_WRAPPER);
46
+ /**
47
+ * @deprecated Use the `data-tooltip-id` attribute, or the `anchorSelect` prop instead.
48
+ * See https://react-tooltip.com/docs/getting-started
49
+ */
50
+ const TooltipProvider = ({ children }) => {
51
+ const [anchorRefMap, setAnchorRefMap] = useState({
52
+ [DEFAULT_TOOLTIP_ID]: new Set(),
53
+ });
54
+ const [activeAnchorMap, setActiveAnchorMap] = useState({
55
+ [DEFAULT_TOOLTIP_ID]: { current: null },
56
+ });
57
+ const attach = (tooltipId, ...refs) => {
58
+ setAnchorRefMap((oldMap) => {
59
+ var _a;
60
+ const tooltipRefs = (_a = oldMap[tooltipId]) !== null && _a !== void 0 ? _a : new Set();
61
+ refs.forEach((ref) => tooltipRefs.add(ref));
62
+ // create new object to trigger re-render
63
+ return { ...oldMap, [tooltipId]: new Set(tooltipRefs) };
64
+ });
65
+ };
66
+ const detach = (tooltipId, ...refs) => {
67
+ setAnchorRefMap((oldMap) => {
68
+ const tooltipRefs = oldMap[tooltipId];
69
+ if (!tooltipRefs) {
70
+ // tooltip not found
71
+ // maybe thow error?
72
+ return oldMap;
73
+ }
74
+ refs.forEach((ref) => tooltipRefs.delete(ref));
75
+ // create new object to trigger re-render
76
+ return { ...oldMap };
77
+ });
78
+ };
79
+ const setActiveAnchor = (tooltipId, ref) => {
80
+ setActiveAnchorMap((oldMap) => {
81
+ var _a;
82
+ if (((_a = oldMap[tooltipId]) === null || _a === void 0 ? void 0 : _a.current) === ref.current) {
83
+ return oldMap;
84
+ }
85
+ // create new object to trigger re-render
86
+ return { ...oldMap, [tooltipId]: ref };
87
+ });
88
+ };
89
+ const getTooltipData = useCallback((tooltipId = DEFAULT_TOOLTIP_ID) => {
90
+ var _a, _b;
91
+ return ({
92
+ anchorRefs: (_a = anchorRefMap[tooltipId]) !== null && _a !== void 0 ? _a : new Set(),
93
+ activeAnchor: (_b = activeAnchorMap[tooltipId]) !== null && _b !== void 0 ? _b : { current: null },
94
+ attach: (...refs) => attach(tooltipId, ...refs),
95
+ detach: (...refs) => detach(tooltipId, ...refs),
96
+ setActiveAnchor: (ref) => setActiveAnchor(tooltipId, ref),
97
+ });
98
+ }, [anchorRefMap, activeAnchorMap, attach, detach]);
99
+ const context = useMemo(() => {
100
+ return {
101
+ getTooltipData,
102
+ };
103
+ }, [getTooltipData]);
104
+ return React.createElement(TooltipContext.Provider, { value: context }, children);
105
+ };
106
+ function useTooltip(tooltipId = DEFAULT_TOOLTIP_ID) {
107
+ return useContext(TooltipContext).getTooltipData(tooltipId);
108
+ }
109
+
110
+ /**
111
+ * @deprecated Use the `data-tooltip-id` attribute, or the `anchorSelect` prop instead.
112
+ * See https://react-tooltip.com/docs/getting-started
113
+ */
114
+ const TooltipWrapper = ({ tooltipId, children, className, place, content, html, variant, offset, wrapper, events, positionStrategy, delayShow, delayHide, }) => {
115
+ const { attach, detach } = useTooltip(tooltipId);
116
+ const anchorRef = useRef(null);
117
+ useEffect(() => {
118
+ attach(anchorRef);
119
+ return () => {
120
+ detach(anchorRef);
121
+ };
122
+ }, []);
123
+ return (React.createElement("span", { ref: anchorRef, className: classNames('react-tooltip-wrapper', className), "data-tooltip-place": place, "data-tooltip-content": content, "data-tooltip-html": html, "data-tooltip-variant": variant, "data-tooltip-offset": offset, "data-tooltip-wrapper": wrapper, "data-tooltip-events": events, "data-tooltip-position-strategy": positionStrategy, "data-tooltip-delay-show": delayShow, "data-tooltip-delay-hide": delayHide }, children));
124
+ };
125
+
126
+ const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;
127
+
128
+ const computeTooltipPosition = async ({ elementReference = null, tooltipReference = null, tooltipArrowReference = null, place = 'top', offset: offsetValue = 10, strategy = 'absolute', middlewares = [offset(Number(offsetValue)), flip(), shift({ padding: 5 })], }) => {
129
+ if (!elementReference) {
130
+ // elementReference can be null or undefined and we will not compute the position
131
+ // eslint-disable-next-line no-console
132
+ // console.error('The reference element for tooltip was not defined: ', elementReference)
133
+ return { tooltipStyles: {}, tooltipArrowStyles: {}, place };
134
+ }
135
+ if (tooltipReference === null) {
136
+ return { tooltipStyles: {}, tooltipArrowStyles: {}, place };
137
+ }
138
+ const middleware = middlewares;
139
+ if (tooltipArrowReference) {
140
+ middleware.push(arrow({ element: tooltipArrowReference, padding: 5 }));
141
+ return computePosition(elementReference, tooltipReference, {
142
+ placement: place,
143
+ strategy,
144
+ middleware,
145
+ }).then(({ x, y, placement, middlewareData }) => {
146
+ var _a, _b;
147
+ const styles = { left: `${x}px`, top: `${y}px` };
148
+ const { x: arrowX, y: arrowY } = (_a = middlewareData.arrow) !== null && _a !== void 0 ? _a : { x: 0, y: 0 };
149
+ const staticSide = (_b = {
150
+ top: 'bottom',
151
+ right: 'left',
152
+ bottom: 'top',
153
+ left: 'right',
154
+ }[placement.split('-')[0]]) !== null && _b !== void 0 ? _b : 'bottom';
155
+ const arrowStyle = {
156
+ left: arrowX != null ? `${arrowX}px` : '',
157
+ top: arrowY != null ? `${arrowY}px` : '',
158
+ right: '',
159
+ bottom: '',
160
+ [staticSide]: '-4px',
161
+ };
162
+ return { tooltipStyles: styles, tooltipArrowStyles: arrowStyle, place: placement };
163
+ });
164
+ }
165
+ return computePosition(elementReference, tooltipReference, {
166
+ placement: 'bottom',
167
+ strategy,
168
+ middleware,
169
+ }).then(({ x, y, placement }) => {
170
+ const styles = { left: `${x}px`, top: `${y}px` };
171
+ return { tooltipStyles: styles, tooltipArrowStyles: {}, place: placement };
172
+ });
173
+ };
174
+
175
+ var styles = {"tooltip":"styles-module_tooltip__mnnfp","fixed":"styles-module_fixed__7ciUi","arrow":"styles-module_arrow__K0L3T","noArrow":"styles-module_noArrow__T8y2L","clickable":"styles-module_clickable__Bv9o7","show":"styles-module_show__2NboJ","dark":"styles-module_dark__xNqje","light":"styles-module_light__Z6W-X","success":"styles-module_success__A2AKt","warning":"styles-module_warning__SCK0X","error":"styles-module_error__JvumD","info":"styles-module_info__BWdHW"};
176
+
177
+ const Tooltip = ({
178
+ // props
179
+ 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, noArrow = false, clickable = false, closeOnEsc = false, style: externalStyles, position, afterShow, afterHide,
180
+ // props handled by controller
181
+ content, contentWrapperRef, isOpen, setIsOpen, activeAnchor, setActiveAnchor, }) => {
182
+ const tooltipRef = useRef(null);
183
+ const tooltipArrowRef = useRef(null);
184
+ const tooltipShowDelayTimerRef = useRef(null);
185
+ const tooltipHideDelayTimerRef = useRef(null);
186
+ const [actualPlacement, setActualPlacement] = useState(place);
187
+ const [inlineStyles, setInlineStyles] = useState({});
188
+ const [inlineArrowStyles, setInlineArrowStyles] = useState({});
189
+ const [show, setShow] = useState(false);
190
+ const [rendered, setRendered] = useState(false);
191
+ const wasShowing = useRef(false);
192
+ const lastFloatPosition = useRef(null);
193
+ /**
194
+ * @todo Remove this in a future version (provider/wrapper method is deprecated)
195
+ */
196
+ const { anchorRefs, setActiveAnchor: setProviderActiveAnchor } = useTooltip(id);
197
+ const hoveringTooltip = useRef(false);
198
+ const [anchorsBySelect, setAnchorsBySelect] = useState([]);
199
+ const mounted = useRef(false);
200
+ const shouldOpenOnClick = openOnClick || events.includes('click');
201
+ /**
202
+ * useLayoutEffect runs before useEffect,
203
+ * but should be used carefully because of caveats
204
+ * https://beta.reactjs.org/reference/react/useLayoutEffect#caveats
205
+ */
206
+ useIsomorphicLayoutEffect(() => {
207
+ mounted.current = true;
208
+ return () => {
209
+ mounted.current = false;
210
+ };
211
+ }, []);
212
+ useEffect(() => {
213
+ if (!show) {
214
+ /**
215
+ * this fixes weird behavior when switching between two anchor elements very quickly
216
+ * remove the timeout and switch quickly between two adjancent anchor elements to see it
217
+ *
218
+ * in practice, this means the tooltip is not immediately removed from the DOM on hide
219
+ */
220
+ const timeout = setTimeout(() => {
221
+ setRendered(false);
222
+ }, 150);
223
+ return () => {
224
+ clearTimeout(timeout);
225
+ };
226
+ }
227
+ return () => null;
228
+ }, [show]);
229
+ const handleShow = (value) => {
230
+ if (!mounted.current) {
231
+ return;
232
+ }
233
+ if (value) {
234
+ setRendered(true);
235
+ }
236
+ /**
237
+ * wait for the component to render and calculate position
238
+ * before actually showing
239
+ */
240
+ setTimeout(() => {
241
+ if (!mounted.current) {
242
+ return;
243
+ }
244
+ setIsOpen === null || setIsOpen === void 0 ? void 0 : setIsOpen(value);
245
+ if (isOpen === undefined) {
246
+ setShow(value);
247
+ }
248
+ }, 10);
249
+ };
250
+ /**
251
+ * this replicates the effect from `handleShow()`
252
+ * when `isOpen` is changed from outside
253
+ */
254
+ useEffect(() => {
255
+ if (isOpen === undefined) {
256
+ return () => null;
257
+ }
258
+ if (isOpen) {
259
+ setRendered(true);
260
+ }
261
+ const timeout = setTimeout(() => {
262
+ setShow(isOpen);
263
+ }, 10);
264
+ return () => {
265
+ clearTimeout(timeout);
266
+ };
267
+ }, [isOpen]);
268
+ useEffect(() => {
269
+ if (show === wasShowing.current) {
270
+ return;
271
+ }
272
+ wasShowing.current = show;
273
+ if (show) {
274
+ afterShow === null || afterShow === void 0 ? void 0 : afterShow();
275
+ }
276
+ else {
277
+ afterHide === null || afterHide === void 0 ? void 0 : afterHide();
278
+ }
279
+ }, [show]);
280
+ const handleShowTooltipDelayed = () => {
281
+ if (tooltipShowDelayTimerRef.current) {
282
+ clearTimeout(tooltipShowDelayTimerRef.current);
283
+ }
284
+ tooltipShowDelayTimerRef.current = setTimeout(() => {
285
+ handleShow(true);
286
+ }, delayShow);
287
+ };
288
+ const handleHideTooltipDelayed = (delay = delayHide) => {
289
+ if (tooltipHideDelayTimerRef.current) {
290
+ clearTimeout(tooltipHideDelayTimerRef.current);
291
+ }
292
+ tooltipHideDelayTimerRef.current = setTimeout(() => {
293
+ if (hoveringTooltip.current) {
294
+ return;
295
+ }
296
+ handleShow(false);
297
+ }, delay);
298
+ };
299
+ const handleShowTooltip = (event) => {
300
+ var _a;
301
+ if (!event) {
302
+ return;
303
+ }
304
+ const target = ((_a = event.currentTarget) !== null && _a !== void 0 ? _a : event.target);
305
+ if (!(target === null || target === void 0 ? void 0 : target.isConnected)) {
306
+ /**
307
+ * this happens when the target is removed from the DOM
308
+ * at the same time the tooltip gets triggered
309
+ */
310
+ setActiveAnchor(null);
311
+ setProviderActiveAnchor({ current: null });
312
+ return;
313
+ }
314
+ if (delayShow) {
315
+ handleShowTooltipDelayed();
316
+ }
317
+ else {
318
+ handleShow(true);
319
+ }
320
+ setActiveAnchor(target);
321
+ setProviderActiveAnchor({ current: target });
322
+ if (tooltipHideDelayTimerRef.current) {
323
+ clearTimeout(tooltipHideDelayTimerRef.current);
324
+ }
325
+ };
326
+ const handleHideTooltip = () => {
327
+ if (clickable) {
328
+ // allow time for the mouse to reach the tooltip, in case there's a gap
329
+ handleHideTooltipDelayed(delayHide || 100);
330
+ }
331
+ else if (delayHide) {
332
+ handleHideTooltipDelayed();
333
+ }
334
+ else {
335
+ handleShow(false);
336
+ }
337
+ if (tooltipShowDelayTimerRef.current) {
338
+ clearTimeout(tooltipShowDelayTimerRef.current);
339
+ }
340
+ };
341
+ const handleTooltipPosition = ({ x, y }) => {
342
+ const virtualElement = {
343
+ getBoundingClientRect() {
344
+ return {
345
+ x,
346
+ y,
347
+ width: 0,
348
+ height: 0,
349
+ top: y,
350
+ left: x,
351
+ right: x,
352
+ bottom: y,
353
+ };
354
+ },
355
+ };
356
+ computeTooltipPosition({
357
+ place,
358
+ offset,
359
+ elementReference: virtualElement,
360
+ tooltipReference: tooltipRef.current,
361
+ tooltipArrowReference: tooltipArrowRef.current,
362
+ strategy: positionStrategy,
363
+ middlewares,
364
+ }).then((computedStylesData) => {
365
+ if (Object.keys(computedStylesData.tooltipStyles).length) {
366
+ setInlineStyles(computedStylesData.tooltipStyles);
367
+ }
368
+ if (Object.keys(computedStylesData.tooltipArrowStyles).length) {
369
+ setInlineArrowStyles(computedStylesData.tooltipArrowStyles);
370
+ }
371
+ setActualPlacement(computedStylesData.place);
372
+ });
373
+ };
374
+ const handleMouseMove = (event) => {
375
+ if (!event) {
376
+ return;
377
+ }
378
+ const mouseEvent = event;
379
+ const mousePosition = {
380
+ x: mouseEvent.clientX,
381
+ y: mouseEvent.clientY,
382
+ };
383
+ handleTooltipPosition(mousePosition);
384
+ lastFloatPosition.current = mousePosition;
385
+ };
386
+ const handleClickTooltipAnchor = (event) => {
387
+ handleShowTooltip(event);
388
+ if (delayHide) {
389
+ handleHideTooltipDelayed();
390
+ }
391
+ };
392
+ const handleClickOutsideAnchors = (event) => {
393
+ var _a;
394
+ const anchorById = document.querySelector(`[id='${anchorId}']`);
395
+ const anchors = [anchorById, ...anchorsBySelect];
396
+ if (anchors.some((anchor) => anchor === null || anchor === void 0 ? void 0 : anchor.contains(event.target))) {
397
+ return;
398
+ }
399
+ if ((_a = tooltipRef.current) === null || _a === void 0 ? void 0 : _a.contains(event.target)) {
400
+ return;
401
+ }
402
+ handleShow(false);
403
+ };
404
+ const handleEsc = (event) => {
405
+ if (event.key !== 'Escape') {
406
+ return;
407
+ }
408
+ handleShow(false);
409
+ };
410
+ // debounce handler to prevent call twice when
411
+ // mouse enter and focus events being triggered toggether
412
+ const debouncedHandleShowTooltip = debounce(handleShowTooltip, 50);
413
+ const debouncedHandleHideTooltip = debounce(handleHideTooltip, 50);
414
+ useEffect(() => {
415
+ var _a, _b;
416
+ const elementRefs = new Set(anchorRefs);
417
+ anchorsBySelect.forEach((anchor) => {
418
+ elementRefs.add({ current: anchor });
419
+ });
420
+ const anchorById = document.querySelector(`[id='${anchorId}']`);
421
+ if (anchorById) {
422
+ elementRefs.add({ current: anchorById });
423
+ }
424
+ if (closeOnEsc) {
425
+ window.addEventListener('keydown', handleEsc);
426
+ }
427
+ const enabledEvents = [];
428
+ if (shouldOpenOnClick) {
429
+ window.addEventListener('click', handleClickOutsideAnchors);
430
+ enabledEvents.push({ event: 'click', listener: handleClickTooltipAnchor });
431
+ }
432
+ else {
433
+ enabledEvents.push({ event: 'mouseenter', listener: debouncedHandleShowTooltip }, { event: 'mouseleave', listener: debouncedHandleHideTooltip }, { event: 'focus', listener: debouncedHandleShowTooltip }, { event: 'blur', listener: debouncedHandleHideTooltip });
434
+ if (float) {
435
+ enabledEvents.push({
436
+ event: 'mousemove',
437
+ listener: handleMouseMove,
438
+ });
439
+ }
440
+ }
441
+ const handleMouseEnterTooltip = () => {
442
+ hoveringTooltip.current = true;
443
+ };
444
+ const handleMouseLeaveTooltip = () => {
445
+ hoveringTooltip.current = false;
446
+ handleHideTooltip();
447
+ };
448
+ if (clickable && !shouldOpenOnClick) {
449
+ (_a = tooltipRef.current) === null || _a === void 0 ? void 0 : _a.addEventListener('mouseenter', handleMouseEnterTooltip);
450
+ (_b = tooltipRef.current) === null || _b === void 0 ? void 0 : _b.addEventListener('mouseleave', handleMouseLeaveTooltip);
451
+ }
452
+ enabledEvents.forEach(({ event, listener }) => {
453
+ elementRefs.forEach((ref) => {
454
+ var _a;
455
+ (_a = ref.current) === null || _a === void 0 ? void 0 : _a.addEventListener(event, listener);
456
+ });
457
+ });
458
+ return () => {
459
+ var _a, _b;
460
+ if (shouldOpenOnClick) {
461
+ window.removeEventListener('click', handleClickOutsideAnchors);
462
+ }
463
+ if (closeOnEsc) {
464
+ window.removeEventListener('keydown', handleEsc);
465
+ }
466
+ if (clickable && !shouldOpenOnClick) {
467
+ (_a = tooltipRef.current) === null || _a === void 0 ? void 0 : _a.removeEventListener('mouseenter', handleMouseEnterTooltip);
468
+ (_b = tooltipRef.current) === null || _b === void 0 ? void 0 : _b.removeEventListener('mouseleave', handleMouseLeaveTooltip);
469
+ }
470
+ enabledEvents.forEach(({ event, listener }) => {
471
+ elementRefs.forEach((ref) => {
472
+ var _a;
473
+ (_a = ref.current) === null || _a === void 0 ? void 0 : _a.removeEventListener(event, listener);
474
+ });
475
+ });
476
+ };
477
+ /**
478
+ * rendered is also a dependency to ensure anchor observers are re-registered
479
+ * since `tooltipRef` becomes stale after removing/adding the tooltip to the DOM
480
+ */
481
+ }, [rendered, anchorRefs, anchorsBySelect, closeOnEsc, events]);
482
+ useEffect(() => {
483
+ let selector = anchorSelect !== null && anchorSelect !== void 0 ? anchorSelect : '';
484
+ if (!selector && id) {
485
+ selector = `[data-tooltip-id='${id}']`;
486
+ }
487
+ const documentObserverCallback = (mutationList) => {
488
+ const newAnchors = [];
489
+ mutationList.forEach((mutation) => {
490
+ if (mutation.type === 'attributes' && mutation.attributeName === 'data-tooltip-id') {
491
+ const newId = mutation.target.getAttribute('data-tooltip-id');
492
+ if (newId === id) {
493
+ newAnchors.push(mutation.target);
494
+ }
495
+ }
496
+ if (mutation.type !== 'childList') {
497
+ return;
498
+ }
499
+ if (activeAnchor) {
500
+ [...mutation.removedNodes].some((node) => {
501
+ var _a;
502
+ if ((_a = node === null || node === void 0 ? void 0 : node.contains) === null || _a === void 0 ? void 0 : _a.call(node, activeAnchor)) {
503
+ setRendered(false);
504
+ handleShow(false);
505
+ setActiveAnchor(null);
506
+ return true;
507
+ }
508
+ return false;
509
+ });
510
+ }
511
+ if (!selector) {
512
+ return;
513
+ }
514
+ try {
515
+ const elements = [...mutation.addedNodes].filter((node) => node.nodeType === 1);
516
+ newAnchors.push(
517
+ // the element itself is an anchor
518
+ ...elements.filter((element) => element.matches(selector)));
519
+ newAnchors.push(
520
+ // the element has children which are anchors
521
+ ...elements.flatMap((element) => [...element.querySelectorAll(selector)]));
522
+ }
523
+ catch (_a) {
524
+ /**
525
+ * invalid CSS selector.
526
+ * already warned on tooltip controller
527
+ */
528
+ }
529
+ });
530
+ if (newAnchors.length) {
531
+ setAnchorsBySelect((anchors) => [...anchors, ...newAnchors]);
532
+ }
533
+ };
534
+ const documentObserver = new MutationObserver(documentObserverCallback);
535
+ // watch for anchor being removed from the DOM
536
+ documentObserver.observe(document.body, {
537
+ childList: true,
538
+ subtree: true,
539
+ attributes: true,
540
+ attributeFilter: ['data-tooltip-id'],
541
+ });
542
+ return () => {
543
+ documentObserver.disconnect();
544
+ };
545
+ }, [id, anchorSelect, activeAnchor]);
546
+ const updateTooltipPosition = () => {
547
+ if (position) {
548
+ // if `position` is set, override regular and `float` positioning
549
+ handleTooltipPosition(position);
550
+ return;
551
+ }
552
+ if (float) {
553
+ if (lastFloatPosition.current) {
554
+ /*
555
+ Without this, changes to `content`, `place`, `offset`, ..., will only
556
+ trigger a position calculation after a `mousemove` event.
557
+
558
+ To see why this matters, comment this line, run `yarn dev` and click the
559
+ "Hover me!" anchor.
560
+ */
561
+ handleTooltipPosition(lastFloatPosition.current);
562
+ }
563
+ // if `float` is set, override regular positioning
564
+ return;
565
+ }
566
+ computeTooltipPosition({
567
+ place,
568
+ offset,
569
+ elementReference: activeAnchor,
570
+ tooltipReference: tooltipRef.current,
571
+ tooltipArrowReference: tooltipArrowRef.current,
572
+ strategy: positionStrategy,
573
+ middlewares,
574
+ }).then((computedStylesData) => {
575
+ if (!mounted.current) {
576
+ // invalidate computed positions after remount
577
+ return;
578
+ }
579
+ if (Object.keys(computedStylesData.tooltipStyles).length) {
580
+ setInlineStyles(computedStylesData.tooltipStyles);
581
+ }
582
+ if (Object.keys(computedStylesData.tooltipArrowStyles).length) {
583
+ setInlineArrowStyles(computedStylesData.tooltipArrowStyles);
584
+ }
585
+ setActualPlacement(computedStylesData.place);
586
+ });
587
+ };
588
+ useEffect(() => {
589
+ updateTooltipPosition();
590
+ }, [show, activeAnchor, content, externalStyles, place, offset, positionStrategy, position]);
591
+ useEffect(() => {
592
+ if (!(contentWrapperRef === null || contentWrapperRef === void 0 ? void 0 : contentWrapperRef.current)) {
593
+ return () => null;
594
+ }
595
+ const contentObserver = new ResizeObserver(() => {
596
+ updateTooltipPosition();
597
+ });
598
+ contentObserver.observe(contentWrapperRef.current);
599
+ return () => {
600
+ contentObserver.disconnect();
601
+ };
602
+ }, [content, contentWrapperRef === null || contentWrapperRef === void 0 ? void 0 : contentWrapperRef.current]);
603
+ useEffect(() => {
604
+ var _a;
605
+ const anchorById = document.querySelector(`[id='${anchorId}']`);
606
+ const anchors = [...anchorsBySelect, anchorById];
607
+ if (!activeAnchor || !anchors.includes(activeAnchor)) {
608
+ /**
609
+ * if there is no active anchor,
610
+ * or if the current active anchor is not amongst the allowed ones,
611
+ * reset it
612
+ */
613
+ setActiveAnchor((_a = anchorsBySelect[0]) !== null && _a !== void 0 ? _a : anchorById);
614
+ }
615
+ }, [anchorId, anchorsBySelect, activeAnchor]);
616
+ useEffect(() => {
617
+ return () => {
618
+ if (tooltipShowDelayTimerRef.current) {
619
+ clearTimeout(tooltipShowDelayTimerRef.current);
620
+ }
621
+ if (tooltipHideDelayTimerRef.current) {
622
+ clearTimeout(tooltipHideDelayTimerRef.current);
623
+ }
624
+ };
625
+ }, []);
626
+ useEffect(() => {
627
+ let selector = anchorSelect;
628
+ if (!selector && id) {
629
+ selector = `[data-tooltip-id='${id}']`;
630
+ }
631
+ if (!selector) {
632
+ return;
633
+ }
634
+ try {
635
+ const anchors = Array.from(document.querySelectorAll(selector));
636
+ setAnchorsBySelect(anchors);
637
+ }
638
+ catch (_a) {
639
+ // warning was already issued in the controller
640
+ setAnchorsBySelect([]);
641
+ }
642
+ }, [id, anchorSelect]);
643
+ const canShow = content && show && Object.keys(inlineStyles).length > 0;
644
+ return rendered ? (React.createElement(WrapperElement, { id: id, role: "tooltip", className: classNames('react-tooltip', styles['tooltip'], styles[variant], className, `react-tooltip__place-${actualPlacement}`, {
645
+ [styles['show']]: canShow,
646
+ [styles['fixed']]: positionStrategy === 'fixed',
647
+ [styles['clickable']]: clickable,
648
+ }), style: { ...externalStyles, ...inlineStyles }, ref: tooltipRef },
649
+ content,
650
+ React.createElement(WrapperElement, { className: classNames('react-tooltip-arrow', styles['arrow'], classNameArrow, {
651
+ /**
652
+ * changed from dash `no-arrow` to camelcase because of:
653
+ * https://github.com/indooorsman/esbuild-css-modules-plugin/issues/42
654
+ */
655
+ [styles['noArrow']]: noArrow,
656
+ }), style: inlineArrowStyles, ref: tooltipArrowRef }))) : null;
657
+ };
658
+
659
+ /* eslint-disable react/no-danger */
660
+ const TooltipContent = ({ content }) => {
661
+ return React.createElement("span", { dangerouslySetInnerHTML: { __html: content } });
662
+ };
663
+
664
+ const TooltipController = ({ id, anchorId, anchorSelect, content, html, render, className, classNameArrow, variant = 'dark', place = 'top', offset = 10, wrapper = 'div', children = null, events = ['hover'], openOnClick = false, positionStrategy = 'absolute', middlewares, delayShow = 0, delayHide = 0, float = false, noArrow = false, clickable = false, closeOnEsc = false, style, position, isOpen, setIsOpen, afterShow, afterHide, }) => {
665
+ const [tooltipContent, setTooltipContent] = useState(content);
666
+ const [tooltipHtml, setTooltipHtml] = useState(html);
667
+ const [tooltipPlace, setTooltipPlace] = useState(place);
668
+ const [tooltipVariant, setTooltipVariant] = useState(variant);
669
+ const [tooltipOffset, setTooltipOffset] = useState(offset);
670
+ const [tooltipDelayShow, setTooltipDelayShow] = useState(delayShow);
671
+ const [tooltipDelayHide, setTooltipDelayHide] = useState(delayHide);
672
+ const [tooltipFloat, setTooltipFloat] = useState(float);
673
+ const [tooltipWrapper, setTooltipWrapper] = useState(wrapper);
674
+ const [tooltipEvents, setTooltipEvents] = useState(events);
675
+ const [tooltipPositionStrategy, setTooltipPositionStrategy] = useState(positionStrategy);
676
+ const [activeAnchor, setActiveAnchor] = useState(null);
677
+ /**
678
+ * @todo Remove this in a future version (provider/wrapper method is deprecated)
679
+ */
680
+ const { anchorRefs, activeAnchor: providerActiveAnchor } = useTooltip(id);
681
+ const getDataAttributesFromAnchorElement = (elementReference) => {
682
+ const dataAttributes = elementReference === null || elementReference === void 0 ? void 0 : elementReference.getAttributeNames().reduce((acc, name) => {
683
+ var _a;
684
+ if (name.startsWith('data-tooltip-')) {
685
+ const parsedAttribute = name.replace(/^data-tooltip-/, '');
686
+ acc[parsedAttribute] = (_a = elementReference === null || elementReference === void 0 ? void 0 : elementReference.getAttribute(name)) !== null && _a !== void 0 ? _a : null;
687
+ }
688
+ return acc;
689
+ }, {});
690
+ return dataAttributes;
691
+ };
692
+ const applyAllDataAttributesFromAnchorElement = (dataAttributes) => {
693
+ const handleDataAttributes = {
694
+ place: (value) => {
695
+ var _a;
696
+ setTooltipPlace((_a = value) !== null && _a !== void 0 ? _a : place);
697
+ },
698
+ content: (value) => {
699
+ setTooltipContent(value !== null && value !== void 0 ? value : content);
700
+ },
701
+ html: (value) => {
702
+ setTooltipHtml(value !== null && value !== void 0 ? value : html);
703
+ },
704
+ variant: (value) => {
705
+ var _a;
706
+ setTooltipVariant((_a = value) !== null && _a !== void 0 ? _a : variant);
707
+ },
708
+ offset: (value) => {
709
+ setTooltipOffset(value === null ? offset : Number(value));
710
+ },
711
+ wrapper: (value) => {
712
+ var _a;
713
+ setTooltipWrapper((_a = value) !== null && _a !== void 0 ? _a : wrapper);
714
+ },
715
+ events: (value) => {
716
+ const parsed = value === null || value === void 0 ? void 0 : value.split(' ');
717
+ setTooltipEvents(parsed !== null && parsed !== void 0 ? parsed : events);
718
+ },
719
+ 'position-strategy': (value) => {
720
+ var _a;
721
+ setTooltipPositionStrategy((_a = value) !== null && _a !== void 0 ? _a : positionStrategy);
722
+ },
723
+ 'delay-show': (value) => {
724
+ setTooltipDelayShow(value === null ? delayShow : Number(value));
725
+ },
726
+ 'delay-hide': (value) => {
727
+ setTooltipDelayHide(value === null ? delayHide : Number(value));
728
+ },
729
+ float: (value) => {
730
+ setTooltipFloat(value === null ? float : value === 'true');
731
+ },
732
+ };
733
+ // reset unset data attributes to default values
734
+ // without this, data attributes from the last active anchor will still be used
735
+ Object.values(handleDataAttributes).forEach((handler) => handler(null));
736
+ Object.entries(dataAttributes).forEach(([key, value]) => {
737
+ var _a;
738
+ (_a = handleDataAttributes[key]) === null || _a === void 0 ? void 0 : _a.call(handleDataAttributes, value);
739
+ });
740
+ };
741
+ useEffect(() => {
742
+ setTooltipContent(content);
743
+ }, [content]);
744
+ useEffect(() => {
745
+ setTooltipHtml(html);
746
+ }, [html]);
747
+ useEffect(() => {
748
+ setTooltipPlace(place);
749
+ }, [place]);
750
+ useEffect(() => {
751
+ var _a;
752
+ const elementRefs = new Set(anchorRefs);
753
+ let selector = anchorSelect;
754
+ if (!selector && id) {
755
+ selector = `[data-tooltip-id='${id}']`;
756
+ }
757
+ if (selector) {
758
+ try {
759
+ const anchorsBySelect = document.querySelectorAll(selector);
760
+ anchorsBySelect.forEach((anchor) => {
761
+ elementRefs.add({ current: anchor });
762
+ });
763
+ }
764
+ catch (_b) {
765
+ {
766
+ // eslint-disable-next-line no-console
767
+ console.warn(`[react-tooltip] "${anchorSelect}" is not a valid CSS selector`);
768
+ }
769
+ }
770
+ }
771
+ const anchorById = document.querySelector(`[id='${anchorId}']`);
772
+ if (anchorById) {
773
+ elementRefs.add({ current: anchorById });
774
+ }
775
+ if (!elementRefs.size) {
776
+ return () => null;
777
+ }
778
+ const anchorElement = (_a = activeAnchor !== null && activeAnchor !== void 0 ? activeAnchor : anchorById) !== null && _a !== void 0 ? _a : providerActiveAnchor.current;
779
+ const observerCallback = (mutationList) => {
780
+ mutationList.forEach((mutation) => {
781
+ var _a;
782
+ if (!anchorElement ||
783
+ mutation.type !== 'attributes' ||
784
+ !((_a = mutation.attributeName) === null || _a === void 0 ? void 0 : _a.startsWith('data-tooltip-'))) {
785
+ return;
786
+ }
787
+ // make sure to get all set attributes, since all unset attributes are reset
788
+ const dataAttributes = getDataAttributesFromAnchorElement(anchorElement);
789
+ applyAllDataAttributesFromAnchorElement(dataAttributes);
790
+ });
791
+ };
792
+ // Create an observer instance linked to the callback function
793
+ const observer = new MutationObserver(observerCallback);
794
+ // do not check for subtree and childrens, we only want to know attribute changes
795
+ // to stay watching `data-attributes-*` from anchor element
796
+ const observerConfig = { attributes: true, childList: false, subtree: false };
797
+ if (anchorElement) {
798
+ const dataAttributes = getDataAttributesFromAnchorElement(anchorElement);
799
+ applyAllDataAttributesFromAnchorElement(dataAttributes);
800
+ // Start observing the target node for configured mutations
801
+ observer.observe(anchorElement, observerConfig);
802
+ }
803
+ return () => {
804
+ // Remove the observer when the tooltip is destroyed
805
+ observer.disconnect();
806
+ };
807
+ }, [anchorRefs, providerActiveAnchor, activeAnchor, anchorId, anchorSelect]);
808
+ /**
809
+ * content priority: children < renderContent or content < html
810
+ * children should be lower priority so that it can be used as the "default" content
811
+ */
812
+ let renderedContent = children;
813
+ const contentWrapperRef = useRef(null);
814
+ if (render) {
815
+ renderedContent = (React.createElement("div", { ref: contentWrapperRef, className: "react-tooltip-content-wrapper" }, render({ content: tooltipContent !== null && tooltipContent !== void 0 ? tooltipContent : null, activeAnchor })));
816
+ }
817
+ else if (tooltipContent) {
818
+ renderedContent = tooltipContent;
819
+ }
820
+ if (tooltipHtml) {
821
+ renderedContent = React.createElement(TooltipContent, { content: tooltipHtml });
822
+ }
823
+ const props = {
824
+ id,
825
+ anchorId,
826
+ anchorSelect,
827
+ className,
828
+ classNameArrow,
829
+ content: renderedContent,
830
+ contentWrapperRef,
831
+ place: tooltipPlace,
832
+ variant: tooltipVariant,
833
+ offset: tooltipOffset,
834
+ wrapper: tooltipWrapper,
835
+ events: tooltipEvents,
836
+ openOnClick,
837
+ positionStrategy: tooltipPositionStrategy,
838
+ middlewares,
839
+ delayShow: tooltipDelayShow,
840
+ delayHide: tooltipDelayHide,
841
+ float: tooltipFloat,
842
+ noArrow,
843
+ clickable,
844
+ closeOnEsc,
845
+ style,
846
+ position,
847
+ isOpen,
848
+ setIsOpen,
849
+ afterShow,
850
+ afterHide,
851
+ activeAnchor,
852
+ setActiveAnchor: (anchor) => setActiveAnchor(anchor),
853
+ };
854
+ return React.createElement(Tooltip, { ...props });
855
+ };
856
+
857
+ export { TooltipController as Tooltip, TooltipProvider, TooltipWrapper };
858
+ //# sourceMappingURL=react-tooltip.mjs.map