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