react-tooltip 5.10.1 → 5.10.2-beta.1

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,840 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var jsxRuntime = require('react/jsx-runtime');
6
+ var react = require('react');
7
+ var classNames = require('classnames');
8
+ var dom = require('@floating-ui/dom');
9
+
10
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
11
+
12
+ var classNames__default = /*#__PURE__*/_interopDefaultLegacy(classNames);
13
+
14
+ /* eslint-disable @typescript-eslint/no-explicit-any */
15
+ /**
16
+ * This function debounce the received function
17
+ * @param { function } func Function to be debounced
18
+ * @param { number } wait Time to wait before execut the function
19
+ * @param { boolean } immediate Param to define if the function will be executed immediately
20
+ */
21
+ const debounce = (func, wait, immediate) => {
22
+ let timeout = null;
23
+ return function debounced(...args) {
24
+ const later = () => {
25
+ timeout = null;
26
+ if (!immediate) {
27
+ func.apply(this, args);
28
+ }
29
+ };
30
+ if (timeout) {
31
+ clearTimeout(timeout);
32
+ }
33
+ timeout = setTimeout(later, wait);
34
+ };
35
+ };
36
+
37
+ const DEFAULT_TOOLTIP_ID = 'DEFAULT_TOOLTIP_ID';
38
+ const DEFAULT_CONTEXT_DATA = {
39
+ anchorRefs: new Set(),
40
+ activeAnchor: { current: null },
41
+ attach: () => {
42
+ /* attach anchor element */
43
+ },
44
+ detach: () => {
45
+ /* detach anchor element */
46
+ },
47
+ setActiveAnchor: () => {
48
+ /* set active anchor */
49
+ },
50
+ };
51
+ const DEFAULT_CONTEXT_DATA_WRAPPER = {
52
+ getTooltipData: () => DEFAULT_CONTEXT_DATA,
53
+ };
54
+ const TooltipContext = react.createContext(DEFAULT_CONTEXT_DATA_WRAPPER);
55
+ /**
56
+ * @deprecated Use the `data-tooltip-id` attribute, or the `anchorSelect` prop instead.
57
+ * See https://react-tooltip.com/docs/getting-started
58
+ */
59
+ const TooltipProvider = ({ children }) => {
60
+ const [anchorRefMap, setAnchorRefMap] = react.useState({
61
+ [DEFAULT_TOOLTIP_ID]: new Set(),
62
+ });
63
+ const [activeAnchorMap, setActiveAnchorMap] = react.useState({
64
+ [DEFAULT_TOOLTIP_ID]: { current: null },
65
+ });
66
+ const attach = (tooltipId, ...refs) => {
67
+ setAnchorRefMap((oldMap) => {
68
+ var _a;
69
+ const tooltipRefs = (_a = oldMap[tooltipId]) !== null && _a !== void 0 ? _a : new Set();
70
+ refs.forEach((ref) => tooltipRefs.add(ref));
71
+ // create new object to trigger re-render
72
+ return { ...oldMap, [tooltipId]: new Set(tooltipRefs) };
73
+ });
74
+ };
75
+ const detach = (tooltipId, ...refs) => {
76
+ setAnchorRefMap((oldMap) => {
77
+ const tooltipRefs = oldMap[tooltipId];
78
+ if (!tooltipRefs) {
79
+ // tooltip not found
80
+ // maybe thow error?
81
+ return oldMap;
82
+ }
83
+ refs.forEach((ref) => tooltipRefs.delete(ref));
84
+ // create new object to trigger re-render
85
+ return { ...oldMap };
86
+ });
87
+ };
88
+ const setActiveAnchor = (tooltipId, ref) => {
89
+ setActiveAnchorMap((oldMap) => {
90
+ var _a;
91
+ if (((_a = oldMap[tooltipId]) === null || _a === void 0 ? void 0 : _a.current) === ref.current) {
92
+ return oldMap;
93
+ }
94
+ // create new object to trigger re-render
95
+ return { ...oldMap, [tooltipId]: ref };
96
+ });
97
+ };
98
+ const getTooltipData = react.useCallback((tooltipId = DEFAULT_TOOLTIP_ID) => {
99
+ var _a, _b;
100
+ return ({
101
+ anchorRefs: (_a = anchorRefMap[tooltipId]) !== null && _a !== void 0 ? _a : new Set(),
102
+ activeAnchor: (_b = activeAnchorMap[tooltipId]) !== null && _b !== void 0 ? _b : { current: null },
103
+ attach: (...refs) => attach(tooltipId, ...refs),
104
+ detach: (...refs) => detach(tooltipId, ...refs),
105
+ setActiveAnchor: (ref) => setActiveAnchor(tooltipId, ref),
106
+ });
107
+ }, [anchorRefMap, activeAnchorMap, attach, detach]);
108
+ const context = react.useMemo(() => {
109
+ return {
110
+ getTooltipData,
111
+ };
112
+ }, [getTooltipData]);
113
+ return jsxRuntime.jsx(TooltipContext.Provider, { value: context, children: children });
114
+ };
115
+ function useTooltip(tooltipId = DEFAULT_TOOLTIP_ID) {
116
+ return react.useContext(TooltipContext).getTooltipData(tooltipId);
117
+ }
118
+
119
+ /**
120
+ * @deprecated Use the `data-tooltip-id` attribute, or the `anchorSelect` prop instead.
121
+ * See https://react-tooltip.com/docs/getting-started
122
+ */
123
+ const TooltipWrapper = ({ tooltipId, children, className, place, content, html, variant, offset, wrapper, events, positionStrategy, delayShow, delayHide, }) => {
124
+ const { attach, detach } = useTooltip(tooltipId);
125
+ const anchorRef = react.useRef(null);
126
+ react.useEffect(() => {
127
+ attach(anchorRef);
128
+ return () => {
129
+ detach(anchorRef);
130
+ };
131
+ }, []);
132
+ return (jsxRuntime.jsx("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: children }));
133
+ };
134
+
135
+ const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? react.useLayoutEffect : react.useEffect;
136
+
137
+ 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 })], }) => {
138
+ if (!elementReference) {
139
+ // elementReference can be null or undefined and we will not compute the position
140
+ // eslint-disable-next-line no-console
141
+ // console.error('The reference element for tooltip was not defined: ', elementReference)
142
+ return { tooltipStyles: {}, tooltipArrowStyles: {}, place };
143
+ }
144
+ if (tooltipReference === null) {
145
+ return { tooltipStyles: {}, tooltipArrowStyles: {}, place };
146
+ }
147
+ const middleware = middlewares;
148
+ if (tooltipArrowReference) {
149
+ middleware.push(dom.arrow({ element: tooltipArrowReference, padding: 5 }));
150
+ return dom.computePosition(elementReference, tooltipReference, {
151
+ placement: place,
152
+ strategy,
153
+ middleware,
154
+ }).then(({ x, y, placement, middlewareData }) => {
155
+ var _a, _b;
156
+ const styles = { left: `${x}px`, top: `${y}px` };
157
+ const { x: arrowX, y: arrowY } = (_a = middlewareData.arrow) !== null && _a !== void 0 ? _a : { x: 0, y: 0 };
158
+ const staticSide = (_b = {
159
+ top: 'bottom',
160
+ right: 'left',
161
+ bottom: 'top',
162
+ left: 'right',
163
+ }[placement.split('-')[0]]) !== null && _b !== void 0 ? _b : 'bottom';
164
+ const arrowStyle = {
165
+ left: arrowX != null ? `${arrowX}px` : '',
166
+ top: arrowY != null ? `${arrowY}px` : '',
167
+ right: '',
168
+ bottom: '',
169
+ [staticSide]: '-4px',
170
+ };
171
+ return { tooltipStyles: styles, tooltipArrowStyles: arrowStyle, place: placement };
172
+ });
173
+ }
174
+ return dom.computePosition(elementReference, tooltipReference, {
175
+ placement: 'bottom',
176
+ strategy,
177
+ middleware,
178
+ }).then(({ x, y, placement }) => {
179
+ const styles = { left: `${x}px`, top: `${y}px` };
180
+ return { tooltipStyles: styles, tooltipArrowStyles: {}, place: placement };
181
+ });
182
+ };
183
+
184
+ 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"};
185
+
186
+ const Tooltip = ({
187
+ // props
188
+ 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,
189
+ // props handled by controller
190
+ content, isOpen, setIsOpen, activeAnchor, setActiveAnchor, }) => {
191
+ const tooltipRef = react.useRef(null);
192
+ const tooltipArrowRef = react.useRef(null);
193
+ const tooltipShowDelayTimerRef = react.useRef(null);
194
+ const tooltipHideDelayTimerRef = react.useRef(null);
195
+ const [actualPlacement, setActualPlacement] = react.useState(place);
196
+ const [inlineStyles, setInlineStyles] = react.useState({});
197
+ const [inlineArrowStyles, setInlineArrowStyles] = react.useState({});
198
+ const [show, setShow] = react.useState(false);
199
+ const [rendered, setRendered] = react.useState(false);
200
+ const wasShowing = react.useRef(false);
201
+ const lastFloatPosition = react.useRef(null);
202
+ /**
203
+ * @todo Remove this in a future version (provider/wrapper method is deprecated)
204
+ */
205
+ const { anchorRefs, setActiveAnchor: setProviderActiveAnchor } = useTooltip(id);
206
+ const hoveringTooltip = react.useRef(false);
207
+ const [anchorsBySelect, setAnchorsBySelect] = react.useState([]);
208
+ const mounted = react.useRef(false);
209
+ const shouldOpenOnClick = openOnClick || events.includes('click');
210
+ /**
211
+ * useLayoutEffect runs before useEffect,
212
+ * but should be used carefully because of caveats
213
+ * https://beta.reactjs.org/reference/react/useLayoutEffect#caveats
214
+ */
215
+ useIsomorphicLayoutEffect(() => {
216
+ mounted.current = true;
217
+ return () => {
218
+ mounted.current = false;
219
+ };
220
+ }, []);
221
+ react.useEffect(() => {
222
+ if (!show) {
223
+ /**
224
+ * this fixes weird behavior when switching between two anchor elements very quickly
225
+ * remove the timeout and switch quickly between two adjancent anchor elements to see it
226
+ *
227
+ * in practice, this means the tooltip is not immediately removed from the DOM on hide
228
+ */
229
+ const timeout = setTimeout(() => {
230
+ setRendered(false);
231
+ }, 150);
232
+ return () => {
233
+ clearTimeout(timeout);
234
+ };
235
+ }
236
+ return () => null;
237
+ }, [show]);
238
+ const handleShow = (value) => {
239
+ if (!mounted.current) {
240
+ return;
241
+ }
242
+ if (value) {
243
+ setRendered(true);
244
+ }
245
+ /**
246
+ * wait for the component to render and calculate position
247
+ * before actually showing
248
+ */
249
+ setTimeout(() => {
250
+ if (!mounted.current) {
251
+ return;
252
+ }
253
+ setIsOpen === null || setIsOpen === void 0 ? void 0 : setIsOpen(value);
254
+ if (isOpen === undefined) {
255
+ setShow(value);
256
+ }
257
+ }, 10);
258
+ };
259
+ /**
260
+ * this replicates the effect from `handleShow()`
261
+ * when `isOpen` is changed from outside
262
+ */
263
+ react.useEffect(() => {
264
+ if (isOpen === undefined) {
265
+ return () => null;
266
+ }
267
+ if (isOpen) {
268
+ setRendered(true);
269
+ }
270
+ const timeout = setTimeout(() => {
271
+ setShow(isOpen);
272
+ }, 10);
273
+ return () => {
274
+ clearTimeout(timeout);
275
+ };
276
+ }, [isOpen]);
277
+ react.useEffect(() => {
278
+ if (show === wasShowing.current) {
279
+ return;
280
+ }
281
+ wasShowing.current = show;
282
+ if (show) {
283
+ afterShow === null || afterShow === void 0 ? void 0 : afterShow();
284
+ }
285
+ else {
286
+ afterHide === null || afterHide === void 0 ? void 0 : afterHide();
287
+ }
288
+ }, [show]);
289
+ const handleShowTooltipDelayed = () => {
290
+ if (tooltipShowDelayTimerRef.current) {
291
+ clearTimeout(tooltipShowDelayTimerRef.current);
292
+ }
293
+ tooltipShowDelayTimerRef.current = setTimeout(() => {
294
+ handleShow(true);
295
+ }, delayShow);
296
+ };
297
+ const handleHideTooltipDelayed = (delay = delayHide) => {
298
+ if (tooltipHideDelayTimerRef.current) {
299
+ clearTimeout(tooltipHideDelayTimerRef.current);
300
+ }
301
+ tooltipHideDelayTimerRef.current = setTimeout(() => {
302
+ if (hoveringTooltip.current) {
303
+ return;
304
+ }
305
+ handleShow(false);
306
+ }, delay);
307
+ };
308
+ const handleShowTooltip = (event) => {
309
+ var _a;
310
+ if (!event) {
311
+ return;
312
+ }
313
+ if (delayShow) {
314
+ handleShowTooltipDelayed();
315
+ }
316
+ else {
317
+ handleShow(true);
318
+ }
319
+ const target = (_a = event.currentTarget) !== null && _a !== void 0 ? _a : event.target;
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
+ react.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
+ react.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
+ react.useEffect(() => {
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
+ }, [show, activeAnchor, content, place, offset, positionStrategy, position]);
588
+ react.useEffect(() => {
589
+ var _a;
590
+ const anchorById = document.querySelector(`[id='${anchorId}']`);
591
+ const anchors = [...anchorsBySelect, anchorById];
592
+ if (!activeAnchor || !anchors.includes(activeAnchor)) {
593
+ /**
594
+ * if there is no active anchor,
595
+ * or if the current active anchor is not amongst the allowed ones,
596
+ * reset it
597
+ */
598
+ setActiveAnchor((_a = anchorsBySelect[0]) !== null && _a !== void 0 ? _a : anchorById);
599
+ }
600
+ }, [anchorId, anchorsBySelect, activeAnchor]);
601
+ react.useEffect(() => {
602
+ return () => {
603
+ if (tooltipShowDelayTimerRef.current) {
604
+ clearTimeout(tooltipShowDelayTimerRef.current);
605
+ }
606
+ if (tooltipHideDelayTimerRef.current) {
607
+ clearTimeout(tooltipHideDelayTimerRef.current);
608
+ }
609
+ };
610
+ }, []);
611
+ react.useEffect(() => {
612
+ let selector = anchorSelect;
613
+ if (!selector && id) {
614
+ selector = `[data-tooltip-id='${id}']`;
615
+ }
616
+ if (!selector) {
617
+ return;
618
+ }
619
+ try {
620
+ const anchors = Array.from(document.querySelectorAll(selector));
621
+ setAnchorsBySelect(anchors);
622
+ }
623
+ catch (_a) {
624
+ // warning was already issued in the controller
625
+ setAnchorsBySelect([]);
626
+ }
627
+ }, [id, anchorSelect]);
628
+ const canShow = content && show && Object.keys(inlineStyles).length > 0;
629
+ return rendered ? (jsxRuntime.jsxs(WrapperElement, { id: id, role: "tooltip", className: classNames__default["default"]('react-tooltip', styles['tooltip'], styles[variant], className, `react-tooltip__place-${actualPlacement}`, {
630
+ [styles['show']]: canShow,
631
+ [styles['fixed']]: positionStrategy === 'fixed',
632
+ [styles['clickable']]: clickable,
633
+ }), style: { ...externalStyles, ...inlineStyles }, ref: tooltipRef, children: [content, jsxRuntime.jsx(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
+ const TooltipContent = ({ content }) => {
643
+ return jsxRuntime.jsx("span", { dangerouslySetInnerHTML: { __html: content } });
644
+ };
645
+
646
+ 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, }) => {
647
+ const [tooltipContent, setTooltipContent] = react.useState(content);
648
+ const [tooltipHtml, setTooltipHtml] = react.useState(html);
649
+ const [tooltipPlace, setTooltipPlace] = react.useState(place);
650
+ const [tooltipVariant, setTooltipVariant] = react.useState(variant);
651
+ const [tooltipOffset, setTooltipOffset] = react.useState(offset);
652
+ const [tooltipDelayShow, setTooltipDelayShow] = react.useState(delayShow);
653
+ const [tooltipDelayHide, setTooltipDelayHide] = react.useState(delayHide);
654
+ const [tooltipFloat, setTooltipFloat] = react.useState(float);
655
+ const [tooltipWrapper, setTooltipWrapper] = react.useState(wrapper);
656
+ const [tooltipEvents, setTooltipEvents] = react.useState(events);
657
+ const [tooltipPositionStrategy, setTooltipPositionStrategy] = react.useState(positionStrategy);
658
+ const [activeAnchor, setActiveAnchor] = react.useState(null);
659
+ /**
660
+ * @todo Remove this in a future version (provider/wrapper method is deprecated)
661
+ */
662
+ const { anchorRefs, activeAnchor: providerActiveAnchor } = useTooltip(id);
663
+ const getDataAttributesFromAnchorElement = (elementReference) => {
664
+ const dataAttributes = elementReference === null || elementReference === void 0 ? void 0 : elementReference.getAttributeNames().reduce((acc, name) => {
665
+ var _a;
666
+ if (name.startsWith('data-tooltip-')) {
667
+ const parsedAttribute = name.replace(/^data-tooltip-/, '');
668
+ acc[parsedAttribute] = (_a = elementReference === null || elementReference === void 0 ? void 0 : elementReference.getAttribute(name)) !== null && _a !== void 0 ? _a : null;
669
+ }
670
+ return acc;
671
+ }, {});
672
+ return dataAttributes;
673
+ };
674
+ const applyAllDataAttributesFromAnchorElement = (dataAttributes) => {
675
+ const handleDataAttributes = {
676
+ place: (value) => {
677
+ var _a;
678
+ setTooltipPlace((_a = value) !== null && _a !== void 0 ? _a : place);
679
+ },
680
+ content: (value) => {
681
+ setTooltipContent(value !== null && value !== void 0 ? value : content);
682
+ },
683
+ html: (value) => {
684
+ setTooltipHtml(value !== null && value !== void 0 ? value : html);
685
+ },
686
+ variant: (value) => {
687
+ var _a;
688
+ setTooltipVariant((_a = value) !== null && _a !== void 0 ? _a : variant);
689
+ },
690
+ offset: (value) => {
691
+ setTooltipOffset(value === null ? offset : Number(value));
692
+ },
693
+ wrapper: (value) => {
694
+ var _a;
695
+ setTooltipWrapper((_a = value) !== null && _a !== void 0 ? _a : wrapper);
696
+ },
697
+ events: (value) => {
698
+ const parsed = value === null || value === void 0 ? void 0 : value.split(' ');
699
+ setTooltipEvents(parsed !== null && parsed !== void 0 ? parsed : events);
700
+ },
701
+ 'position-strategy': (value) => {
702
+ var _a;
703
+ setTooltipPositionStrategy((_a = value) !== null && _a !== void 0 ? _a : positionStrategy);
704
+ },
705
+ 'delay-show': (value) => {
706
+ setTooltipDelayShow(value === null ? delayShow : Number(value));
707
+ },
708
+ 'delay-hide': (value) => {
709
+ setTooltipDelayHide(value === null ? delayHide : Number(value));
710
+ },
711
+ float: (value) => {
712
+ setTooltipFloat(value === null ? float : value === 'true');
713
+ },
714
+ };
715
+ // reset unset data attributes to default values
716
+ // without this, data attributes from the last active anchor will still be used
717
+ Object.values(handleDataAttributes).forEach((handler) => handler(null));
718
+ Object.entries(dataAttributes).forEach(([key, value]) => {
719
+ var _a;
720
+ (_a = handleDataAttributes[key]) === null || _a === void 0 ? void 0 : _a.call(handleDataAttributes, value);
721
+ });
722
+ };
723
+ react.useEffect(() => {
724
+ setTooltipContent(content);
725
+ }, [content]);
726
+ react.useEffect(() => {
727
+ setTooltipHtml(html);
728
+ }, [html]);
729
+ react.useEffect(() => {
730
+ setTooltipPlace(place);
731
+ }, [place]);
732
+ react.useEffect(() => {
733
+ var _a;
734
+ const elementRefs = new Set(anchorRefs);
735
+ let selector = anchorSelect;
736
+ if (!selector && id) {
737
+ selector = `[data-tooltip-id='${id}']`;
738
+ }
739
+ if (selector) {
740
+ try {
741
+ const anchorsBySelect = document.querySelectorAll(selector);
742
+ anchorsBySelect.forEach((anchor) => {
743
+ elementRefs.add({ current: anchor });
744
+ });
745
+ }
746
+ catch (_b) {
747
+ {
748
+ // eslint-disable-next-line no-console
749
+ console.warn(`[react-tooltip] "${anchorSelect}" is not a valid CSS selector`);
750
+ }
751
+ }
752
+ }
753
+ const anchorById = document.querySelector(`[id='${anchorId}']`);
754
+ if (anchorById) {
755
+ elementRefs.add({ current: anchorById });
756
+ }
757
+ if (!elementRefs.size) {
758
+ return () => null;
759
+ }
760
+ const anchorElement = (_a = activeAnchor !== null && activeAnchor !== void 0 ? activeAnchor : anchorById) !== null && _a !== void 0 ? _a : providerActiveAnchor.current;
761
+ const observerCallback = (mutationList) => {
762
+ mutationList.forEach((mutation) => {
763
+ var _a;
764
+ if (!anchorElement ||
765
+ mutation.type !== 'attributes' ||
766
+ !((_a = mutation.attributeName) === null || _a === void 0 ? void 0 : _a.startsWith('data-tooltip-'))) {
767
+ return;
768
+ }
769
+ // make sure to get all set attributes, since all unset attributes are reset
770
+ const dataAttributes = getDataAttributesFromAnchorElement(anchorElement);
771
+ applyAllDataAttributesFromAnchorElement(dataAttributes);
772
+ });
773
+ };
774
+ // Create an observer instance linked to the callback function
775
+ const observer = new MutationObserver(observerCallback);
776
+ // do not check for subtree and childrens, we only want to know attribute changes
777
+ // to stay watching `data-attributes-*` from anchor element
778
+ const observerConfig = { attributes: true, childList: false, subtree: false };
779
+ if (anchorElement) {
780
+ const dataAttributes = getDataAttributesFromAnchorElement(anchorElement);
781
+ applyAllDataAttributesFromAnchorElement(dataAttributes);
782
+ // Start observing the target node for configured mutations
783
+ observer.observe(anchorElement, observerConfig);
784
+ }
785
+ return () => {
786
+ // Remove the observer when the tooltip is destroyed
787
+ observer.disconnect();
788
+ };
789
+ }, [anchorRefs, providerActiveAnchor, activeAnchor, anchorId, anchorSelect]);
790
+ /**
791
+ * content priority: children < renderContent or content < html
792
+ * children should be lower priority so that it can be used as the "default" content
793
+ */
794
+ let renderedContent = children;
795
+ if (render) {
796
+ renderedContent = render({ content: tooltipContent !== null && tooltipContent !== void 0 ? tooltipContent : null, activeAnchor });
797
+ }
798
+ else if (tooltipContent) {
799
+ renderedContent = tooltipContent;
800
+ }
801
+ if (tooltipHtml) {
802
+ renderedContent = jsxRuntime.jsx(TooltipContent, { content: tooltipHtml });
803
+ }
804
+ const props = {
805
+ id,
806
+ anchorId,
807
+ anchorSelect,
808
+ className,
809
+ classNameArrow,
810
+ content: renderedContent,
811
+ place: tooltipPlace,
812
+ variant: tooltipVariant,
813
+ offset: tooltipOffset,
814
+ wrapper: tooltipWrapper,
815
+ events: tooltipEvents,
816
+ openOnClick,
817
+ positionStrategy: tooltipPositionStrategy,
818
+ middlewares,
819
+ delayShow: tooltipDelayShow,
820
+ delayHide: tooltipDelayHide,
821
+ float: tooltipFloat,
822
+ noArrow,
823
+ clickable,
824
+ closeOnEsc,
825
+ style,
826
+ position,
827
+ isOpen,
828
+ setIsOpen,
829
+ afterShow,
830
+ afterHide,
831
+ activeAnchor,
832
+ setActiveAnchor: (anchor) => setActiveAnchor(anchor),
833
+ };
834
+ return jsxRuntime.jsx(Tooltip, { ...props });
835
+ };
836
+
837
+ exports.Tooltip = TooltipController;
838
+ exports.TooltipProvider = TooltipProvider;
839
+ exports.TooltipWrapper = TooltipWrapper;
840
+ //# sourceMappingURL=react-tooltip.cjs.map