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