react-tooltip 5.10.2-beta.3 → 5.10.2-beta.4

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,832 @@
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","no-arrow":"styles-module_no-arrow__KcFZN","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, 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
+ if (delayShow) {
305
+ handleShowTooltipDelayed();
306
+ }
307
+ else {
308
+ handleShow(true);
309
+ }
310
+ const target = (_a = event.currentTarget) !== null && _a !== void 0 ? _a : event.target;
311
+ setActiveAnchor(target);
312
+ setProviderActiveAnchor({ current: target });
313
+ if (tooltipHideDelayTimerRef.current) {
314
+ clearTimeout(tooltipHideDelayTimerRef.current);
315
+ }
316
+ };
317
+ const handleHideTooltip = () => {
318
+ if (clickable) {
319
+ // allow time for the mouse to reach the tooltip, in case there's a gap
320
+ handleHideTooltipDelayed(delayHide || 100);
321
+ }
322
+ else if (delayHide) {
323
+ handleHideTooltipDelayed();
324
+ }
325
+ else {
326
+ handleShow(false);
327
+ }
328
+ if (tooltipShowDelayTimerRef.current) {
329
+ clearTimeout(tooltipShowDelayTimerRef.current);
330
+ }
331
+ };
332
+ const handleTooltipPosition = ({ x, y }) => {
333
+ const virtualElement = {
334
+ getBoundingClientRect() {
335
+ return {
336
+ x,
337
+ y,
338
+ width: 0,
339
+ height: 0,
340
+ top: y,
341
+ left: x,
342
+ right: x,
343
+ bottom: y,
344
+ };
345
+ },
346
+ };
347
+ computeTooltipPosition({
348
+ place,
349
+ offset,
350
+ elementReference: virtualElement,
351
+ tooltipReference: tooltipRef.current,
352
+ tooltipArrowReference: tooltipArrowRef.current,
353
+ strategy: positionStrategy,
354
+ middlewares,
355
+ }).then((computedStylesData) => {
356
+ if (Object.keys(computedStylesData.tooltipStyles).length) {
357
+ setInlineStyles(computedStylesData.tooltipStyles);
358
+ }
359
+ if (Object.keys(computedStylesData.tooltipArrowStyles).length) {
360
+ setInlineArrowStyles(computedStylesData.tooltipArrowStyles);
361
+ }
362
+ setActualPlacement(computedStylesData.place);
363
+ });
364
+ };
365
+ const handleMouseMove = (event) => {
366
+ if (!event) {
367
+ return;
368
+ }
369
+ const mouseEvent = event;
370
+ const mousePosition = {
371
+ x: mouseEvent.clientX,
372
+ y: mouseEvent.clientY,
373
+ };
374
+ handleTooltipPosition(mousePosition);
375
+ lastFloatPosition.current = mousePosition;
376
+ };
377
+ const handleClickTooltipAnchor = (event) => {
378
+ handleShowTooltip(event);
379
+ if (delayHide) {
380
+ handleHideTooltipDelayed();
381
+ }
382
+ };
383
+ const handleClickOutsideAnchors = (event) => {
384
+ var _a;
385
+ const anchorById = document.querySelector(`[id='${anchorId}']`);
386
+ const anchors = [anchorById, ...anchorsBySelect];
387
+ if (anchors.some((anchor) => anchor === null || anchor === void 0 ? void 0 : anchor.contains(event.target))) {
388
+ return;
389
+ }
390
+ if ((_a = tooltipRef.current) === null || _a === void 0 ? void 0 : _a.contains(event.target)) {
391
+ return;
392
+ }
393
+ handleShow(false);
394
+ };
395
+ const handleEsc = (event) => {
396
+ if (event.key !== 'Escape') {
397
+ return;
398
+ }
399
+ handleShow(false);
400
+ };
401
+ // debounce handler to prevent call twice when
402
+ // mouse enter and focus events being triggered toggether
403
+ const debouncedHandleShowTooltip = debounce(handleShowTooltip, 50);
404
+ const debouncedHandleHideTooltip = debounce(handleHideTooltip, 50);
405
+ useEffect(() => {
406
+ var _a, _b;
407
+ const elementRefs = new Set(anchorRefs);
408
+ anchorsBySelect.forEach((anchor) => {
409
+ elementRefs.add({ current: anchor });
410
+ });
411
+ const anchorById = document.querySelector(`[id='${anchorId}']`);
412
+ if (anchorById) {
413
+ elementRefs.add({ current: anchorById });
414
+ }
415
+ if (closeOnEsc) {
416
+ window.addEventListener('keydown', handleEsc);
417
+ }
418
+ const enabledEvents = [];
419
+ if (shouldOpenOnClick) {
420
+ window.addEventListener('click', handleClickOutsideAnchors);
421
+ enabledEvents.push({ event: 'click', listener: handleClickTooltipAnchor });
422
+ }
423
+ else {
424
+ enabledEvents.push({ event: 'mouseenter', listener: debouncedHandleShowTooltip }, { event: 'mouseleave', listener: debouncedHandleHideTooltip }, { event: 'focus', listener: debouncedHandleShowTooltip }, { event: 'blur', listener: debouncedHandleHideTooltip });
425
+ if (float) {
426
+ enabledEvents.push({
427
+ event: 'mousemove',
428
+ listener: handleMouseMove,
429
+ });
430
+ }
431
+ }
432
+ const handleMouseEnterTooltip = () => {
433
+ hoveringTooltip.current = true;
434
+ };
435
+ const handleMouseLeaveTooltip = () => {
436
+ hoveringTooltip.current = false;
437
+ handleHideTooltip();
438
+ };
439
+ if (clickable && !shouldOpenOnClick) {
440
+ (_a = tooltipRef.current) === null || _a === void 0 ? void 0 : _a.addEventListener('mouseenter', handleMouseEnterTooltip);
441
+ (_b = tooltipRef.current) === null || _b === void 0 ? void 0 : _b.addEventListener('mouseleave', handleMouseLeaveTooltip);
442
+ }
443
+ enabledEvents.forEach(({ event, listener }) => {
444
+ elementRefs.forEach((ref) => {
445
+ var _a;
446
+ (_a = ref.current) === null || _a === void 0 ? void 0 : _a.addEventListener(event, listener);
447
+ });
448
+ });
449
+ return () => {
450
+ var _a, _b;
451
+ if (shouldOpenOnClick) {
452
+ window.removeEventListener('click', handleClickOutsideAnchors);
453
+ }
454
+ if (closeOnEsc) {
455
+ window.removeEventListener('keydown', handleEsc);
456
+ }
457
+ if (clickable && !shouldOpenOnClick) {
458
+ (_a = tooltipRef.current) === null || _a === void 0 ? void 0 : _a.removeEventListener('mouseenter', handleMouseEnterTooltip);
459
+ (_b = tooltipRef.current) === null || _b === void 0 ? void 0 : _b.removeEventListener('mouseleave', handleMouseLeaveTooltip);
460
+ }
461
+ enabledEvents.forEach(({ event, listener }) => {
462
+ elementRefs.forEach((ref) => {
463
+ var _a;
464
+ (_a = ref.current) === null || _a === void 0 ? void 0 : _a.removeEventListener(event, listener);
465
+ });
466
+ });
467
+ };
468
+ /**
469
+ * rendered is also a dependency to ensure anchor observers are re-registered
470
+ * since `tooltipRef` becomes stale after removing/adding the tooltip to the DOM
471
+ */
472
+ }, [rendered, anchorRefs, anchorsBySelect, closeOnEsc, events]);
473
+ useEffect(() => {
474
+ let selector = anchorSelect !== null && anchorSelect !== void 0 ? anchorSelect : '';
475
+ if (!selector && id) {
476
+ selector = `[data-tooltip-id='${id}']`;
477
+ }
478
+ const documentObserverCallback = (mutationList) => {
479
+ const newAnchors = [];
480
+ mutationList.forEach((mutation) => {
481
+ if (mutation.type === 'attributes' && mutation.attributeName === 'data-tooltip-id') {
482
+ const newId = mutation.target.getAttribute('data-tooltip-id');
483
+ if (newId === id) {
484
+ newAnchors.push(mutation.target);
485
+ }
486
+ }
487
+ if (mutation.type !== 'childList') {
488
+ return;
489
+ }
490
+ if (activeAnchor) {
491
+ [...mutation.removedNodes].some((node) => {
492
+ var _a;
493
+ if ((_a = node === null || node === void 0 ? void 0 : node.contains) === null || _a === void 0 ? void 0 : _a.call(node, activeAnchor)) {
494
+ setRendered(false);
495
+ handleShow(false);
496
+ setActiveAnchor(null);
497
+ return true;
498
+ }
499
+ return false;
500
+ });
501
+ }
502
+ if (!selector) {
503
+ return;
504
+ }
505
+ try {
506
+ const elements = [...mutation.addedNodes].filter((node) => node.nodeType === 1);
507
+ newAnchors.push(
508
+ // the element itself is an anchor
509
+ ...elements.filter((element) => element.matches(selector)));
510
+ newAnchors.push(
511
+ // the element has children which are anchors
512
+ ...elements.flatMap((element) => [...element.querySelectorAll(selector)]));
513
+ }
514
+ catch (_a) {
515
+ /**
516
+ * invalid CSS selector.
517
+ * already warned on tooltip controller
518
+ */
519
+ }
520
+ });
521
+ if (newAnchors.length) {
522
+ setAnchorsBySelect((anchors) => [...anchors, ...newAnchors]);
523
+ }
524
+ };
525
+ const documentObserver = new MutationObserver(documentObserverCallback);
526
+ // watch for anchor being removed from the DOM
527
+ documentObserver.observe(document.body, {
528
+ childList: true,
529
+ subtree: true,
530
+ attributes: true,
531
+ attributeFilter: ['data-tooltip-id'],
532
+ });
533
+ return () => {
534
+ documentObserver.disconnect();
535
+ };
536
+ }, [id, anchorSelect, activeAnchor]);
537
+ useEffect(() => {
538
+ if (position) {
539
+ // if `position` is set, override regular and `float` positioning
540
+ handleTooltipPosition(position);
541
+ return;
542
+ }
543
+ if (float) {
544
+ if (lastFloatPosition.current) {
545
+ /*
546
+ Without this, changes to `content`, `place`, `offset`, ..., will only
547
+ trigger a position calculation after a `mousemove` event.
548
+
549
+ To see why this matters, comment this line, run `yarn dev` and click the
550
+ "Hover me!" anchor.
551
+ */
552
+ handleTooltipPosition(lastFloatPosition.current);
553
+ }
554
+ // if `float` is set, override regular positioning
555
+ return;
556
+ }
557
+ computeTooltipPosition({
558
+ place,
559
+ offset,
560
+ elementReference: activeAnchor,
561
+ tooltipReference: tooltipRef.current,
562
+ tooltipArrowReference: tooltipArrowRef.current,
563
+ strategy: positionStrategy,
564
+ middlewares,
565
+ }).then((computedStylesData) => {
566
+ if (!mounted.current) {
567
+ // invalidate computed positions after remount
568
+ return;
569
+ }
570
+ if (Object.keys(computedStylesData.tooltipStyles).length) {
571
+ setInlineStyles(computedStylesData.tooltipStyles);
572
+ }
573
+ if (Object.keys(computedStylesData.tooltipArrowStyles).length) {
574
+ setInlineArrowStyles(computedStylesData.tooltipArrowStyles);
575
+ }
576
+ setActualPlacement(computedStylesData.place);
577
+ });
578
+ }, [show, activeAnchor, content, place, offset, positionStrategy, position]);
579
+ useEffect(() => {
580
+ var _a;
581
+ const anchorById = document.querySelector(`[id='${anchorId}']`);
582
+ const anchors = [...anchorsBySelect, anchorById];
583
+ if (!activeAnchor || !anchors.includes(activeAnchor)) {
584
+ /**
585
+ * if there is no active anchor,
586
+ * or if the current active anchor is not amongst the allowed ones,
587
+ * reset it
588
+ */
589
+ setActiveAnchor((_a = anchorsBySelect[0]) !== null && _a !== void 0 ? _a : anchorById);
590
+ }
591
+ }, [anchorId, anchorsBySelect, activeAnchor]);
592
+ useEffect(() => {
593
+ return () => {
594
+ if (tooltipShowDelayTimerRef.current) {
595
+ clearTimeout(tooltipShowDelayTimerRef.current);
596
+ }
597
+ if (tooltipHideDelayTimerRef.current) {
598
+ clearTimeout(tooltipHideDelayTimerRef.current);
599
+ }
600
+ };
601
+ }, []);
602
+ useEffect(() => {
603
+ let selector = anchorSelect;
604
+ if (!selector && id) {
605
+ selector = `[data-tooltip-id='${id}']`;
606
+ }
607
+ if (!selector) {
608
+ return;
609
+ }
610
+ try {
611
+ const anchors = Array.from(document.querySelectorAll(selector));
612
+ setAnchorsBySelect(anchors);
613
+ }
614
+ catch (_a) {
615
+ // warning was already issued in the controller
616
+ setAnchorsBySelect([]);
617
+ }
618
+ }, [id, anchorSelect]);
619
+ const canShow = content && show && Object.keys(inlineStyles).length > 0;
620
+ return rendered ? (React.createElement(WrapperElement, { id: id, role: "tooltip", className: classNames('react-tooltip', styles['tooltip'], styles[variant], className, `react-tooltip__place-${actualPlacement}`, {
621
+ [styles['show']]: canShow,
622
+ [styles['fixed']]: positionStrategy === 'fixed',
623
+ [styles['clickable']]: clickable,
624
+ }), style: { ...externalStyles, ...inlineStyles }, ref: tooltipRef },
625
+ content,
626
+ React.createElement(WrapperElement, { className: classNames('react-tooltip-arrow', styles['arrow'], classNameArrow, {
627
+ /**
628
+ * changed from dash `no-arrow` to camelcase because of:
629
+ * https://github.com/indooorsman/esbuild-css-modules-plugin/issues/42
630
+ */
631
+ [styles['noArrow']]: noArrow,
632
+ }), style: inlineArrowStyles, ref: tooltipArrowRef }))) : null;
633
+ };
634
+
635
+ /* eslint-disable react/no-danger */
636
+ const TooltipContent = ({ content }) => {
637
+ return React.createElement("span", { dangerouslySetInnerHTML: { __html: content } });
638
+ };
639
+
640
+ 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, }) => {
641
+ const [tooltipContent, setTooltipContent] = useState(content);
642
+ const [tooltipHtml, setTooltipHtml] = useState(html);
643
+ const [tooltipPlace, setTooltipPlace] = useState(place);
644
+ const [tooltipVariant, setTooltipVariant] = useState(variant);
645
+ const [tooltipOffset, setTooltipOffset] = useState(offset);
646
+ const [tooltipDelayShow, setTooltipDelayShow] = useState(delayShow);
647
+ const [tooltipDelayHide, setTooltipDelayHide] = useState(delayHide);
648
+ const [tooltipFloat, setTooltipFloat] = useState(float);
649
+ const [tooltipWrapper, setTooltipWrapper] = useState(wrapper);
650
+ const [tooltipEvents, setTooltipEvents] = useState(events);
651
+ const [tooltipPositionStrategy, setTooltipPositionStrategy] = useState(positionStrategy);
652
+ const [activeAnchor, setActiveAnchor] = useState(null);
653
+ /**
654
+ * @todo Remove this in a future version (provider/wrapper method is deprecated)
655
+ */
656
+ const { anchorRefs, activeAnchor: providerActiveAnchor } = useTooltip(id);
657
+ const getDataAttributesFromAnchorElement = (elementReference) => {
658
+ const dataAttributes = elementReference === null || elementReference === void 0 ? void 0 : elementReference.getAttributeNames().reduce((acc, name) => {
659
+ var _a;
660
+ if (name.startsWith('data-tooltip-')) {
661
+ const parsedAttribute = name.replace(/^data-tooltip-/, '');
662
+ acc[parsedAttribute] = (_a = elementReference === null || elementReference === void 0 ? void 0 : elementReference.getAttribute(name)) !== null && _a !== void 0 ? _a : null;
663
+ }
664
+ return acc;
665
+ }, {});
666
+ return dataAttributes;
667
+ };
668
+ const applyAllDataAttributesFromAnchorElement = (dataAttributes) => {
669
+ const handleDataAttributes = {
670
+ place: (value) => {
671
+ var _a;
672
+ setTooltipPlace((_a = value) !== null && _a !== void 0 ? _a : place);
673
+ },
674
+ content: (value) => {
675
+ setTooltipContent(value !== null && value !== void 0 ? value : content);
676
+ },
677
+ html: (value) => {
678
+ setTooltipHtml(value !== null && value !== void 0 ? value : html);
679
+ },
680
+ variant: (value) => {
681
+ var _a;
682
+ setTooltipVariant((_a = value) !== null && _a !== void 0 ? _a : variant);
683
+ },
684
+ offset: (value) => {
685
+ setTooltipOffset(value === null ? offset : Number(value));
686
+ },
687
+ wrapper: (value) => {
688
+ var _a;
689
+ setTooltipWrapper((_a = value) !== null && _a !== void 0 ? _a : wrapper);
690
+ },
691
+ events: (value) => {
692
+ const parsed = value === null || value === void 0 ? void 0 : value.split(' ');
693
+ setTooltipEvents(parsed !== null && parsed !== void 0 ? parsed : events);
694
+ },
695
+ 'position-strategy': (value) => {
696
+ var _a;
697
+ setTooltipPositionStrategy((_a = value) !== null && _a !== void 0 ? _a : positionStrategy);
698
+ },
699
+ 'delay-show': (value) => {
700
+ setTooltipDelayShow(value === null ? delayShow : Number(value));
701
+ },
702
+ 'delay-hide': (value) => {
703
+ setTooltipDelayHide(value === null ? delayHide : Number(value));
704
+ },
705
+ float: (value) => {
706
+ setTooltipFloat(value === null ? float : value === 'true');
707
+ },
708
+ };
709
+ // reset unset data attributes to default values
710
+ // without this, data attributes from the last active anchor will still be used
711
+ Object.values(handleDataAttributes).forEach((handler) => handler(null));
712
+ Object.entries(dataAttributes).forEach(([key, value]) => {
713
+ var _a;
714
+ (_a = handleDataAttributes[key]) === null || _a === void 0 ? void 0 : _a.call(handleDataAttributes, value);
715
+ });
716
+ };
717
+ useEffect(() => {
718
+ setTooltipContent(content);
719
+ }, [content]);
720
+ useEffect(() => {
721
+ setTooltipHtml(html);
722
+ }, [html]);
723
+ useEffect(() => {
724
+ setTooltipPlace(place);
725
+ }, [place]);
726
+ useEffect(() => {
727
+ var _a;
728
+ const elementRefs = new Set(anchorRefs);
729
+ let selector = anchorSelect;
730
+ if (!selector && id) {
731
+ selector = `[data-tooltip-id='${id}']`;
732
+ }
733
+ if (selector) {
734
+ try {
735
+ const anchorsBySelect = document.querySelectorAll(selector);
736
+ anchorsBySelect.forEach((anchor) => {
737
+ elementRefs.add({ current: anchor });
738
+ });
739
+ }
740
+ catch (_b) {
741
+ {
742
+ // eslint-disable-next-line no-console
743
+ console.warn(`[react-tooltip] "${anchorSelect}" is not a valid CSS selector`);
744
+ }
745
+ }
746
+ }
747
+ const anchorById = document.querySelector(`[id='${anchorId}']`);
748
+ if (anchorById) {
749
+ elementRefs.add({ current: anchorById });
750
+ }
751
+ if (!elementRefs.size) {
752
+ return () => null;
753
+ }
754
+ const anchorElement = (_a = activeAnchor !== null && activeAnchor !== void 0 ? activeAnchor : anchorById) !== null && _a !== void 0 ? _a : providerActiveAnchor.current;
755
+ const observerCallback = (mutationList) => {
756
+ mutationList.forEach((mutation) => {
757
+ var _a;
758
+ if (!anchorElement ||
759
+ mutation.type !== 'attributes' ||
760
+ !((_a = mutation.attributeName) === null || _a === void 0 ? void 0 : _a.startsWith('data-tooltip-'))) {
761
+ return;
762
+ }
763
+ // make sure to get all set attributes, since all unset attributes are reset
764
+ const dataAttributes = getDataAttributesFromAnchorElement(anchorElement);
765
+ applyAllDataAttributesFromAnchorElement(dataAttributes);
766
+ });
767
+ };
768
+ // Create an observer instance linked to the callback function
769
+ const observer = new MutationObserver(observerCallback);
770
+ // do not check for subtree and childrens, we only want to know attribute changes
771
+ // to stay watching `data-attributes-*` from anchor element
772
+ const observerConfig = { attributes: true, childList: false, subtree: false };
773
+ if (anchorElement) {
774
+ const dataAttributes = getDataAttributesFromAnchorElement(anchorElement);
775
+ applyAllDataAttributesFromAnchorElement(dataAttributes);
776
+ // Start observing the target node for configured mutations
777
+ observer.observe(anchorElement, observerConfig);
778
+ }
779
+ return () => {
780
+ // Remove the observer when the tooltip is destroyed
781
+ observer.disconnect();
782
+ };
783
+ }, [anchorRefs, providerActiveAnchor, activeAnchor, anchorId, anchorSelect]);
784
+ /**
785
+ * content priority: children < renderContent or content < html
786
+ * children should be lower priority so that it can be used as the "default" content
787
+ */
788
+ let renderedContent = children;
789
+ if (render) {
790
+ renderedContent = render({ content: tooltipContent !== null && tooltipContent !== void 0 ? tooltipContent : null, activeAnchor });
791
+ }
792
+ else if (tooltipContent) {
793
+ renderedContent = tooltipContent;
794
+ }
795
+ if (tooltipHtml) {
796
+ renderedContent = React.createElement(TooltipContent, { content: tooltipHtml });
797
+ }
798
+ const props = {
799
+ id,
800
+ anchorId,
801
+ anchorSelect,
802
+ className,
803
+ classNameArrow,
804
+ content: renderedContent,
805
+ place: tooltipPlace,
806
+ variant: tooltipVariant,
807
+ offset: tooltipOffset,
808
+ wrapper: tooltipWrapper,
809
+ events: tooltipEvents,
810
+ openOnClick,
811
+ positionStrategy: tooltipPositionStrategy,
812
+ middlewares,
813
+ delayShow: tooltipDelayShow,
814
+ delayHide: tooltipDelayHide,
815
+ float: tooltipFloat,
816
+ noArrow,
817
+ clickable,
818
+ closeOnEsc,
819
+ style,
820
+ position,
821
+ isOpen,
822
+ setIsOpen,
823
+ afterShow,
824
+ afterHide,
825
+ activeAnchor,
826
+ setActiveAnchor: (anchor) => setActiveAnchor(anchor),
827
+ };
828
+ return React.createElement(Tooltip, { ...props });
829
+ };
830
+
831
+ export { TooltipController as Tooltip, TooltipProvider, TooltipWrapper };
832
+ //# sourceMappingURL=react-tooltip.mjs.map