/
Tooltip.js
754 lines (691 loc) · 20.9 KB
/
Tooltip.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { deepmerge, elementAcceptingRef } from '@material-ui/utils';
import { alpha } from '../styles/colorManipulator';
import withStyles from '../styles/withStyles';
import capitalize from '../utils/capitalize';
import Grow from '../Grow';
import Popper from '../Popper';
import useEventCallback from '../utils/useEventCallback';
import useForkRef from '../utils/useForkRef';
import useId from '../utils/useId';
import useIsFocusVisible from '../utils/useIsFocusVisible';
import useControlled from '../utils/useControlled';
import useTheme from '../styles/useTheme';
function round(value) {
return Math.round(value * 1e5) / 1e5;
}
function arrowGenerator() {
return {
'&[x-placement*="bottom"] $arrow': {
top: 0,
left: 0,
marginTop: '-0.71em',
marginLeft: 4,
marginRight: 4,
'&::before': {
transformOrigin: '0 100%',
},
},
'&[x-placement*="top"] $arrow': {
bottom: 0,
left: 0,
marginBottom: '-0.71em',
marginLeft: 4,
marginRight: 4,
'&::before': {
transformOrigin: '100% 0',
},
},
'&[x-placement*="right"] $arrow': {
left: 0,
marginLeft: '-0.71em',
height: '1em',
width: '0.71em',
marginTop: 4,
marginBottom: 4,
'&::before': {
transformOrigin: '100% 100%',
},
},
'&[x-placement*="left"] $arrow': {
right: 0,
marginRight: '-0.71em',
height: '1em',
width: '0.71em',
marginTop: 4,
marginBottom: 4,
'&::before': {
transformOrigin: '0 0',
},
},
};
}
export const styles = (theme) => ({
/* Styles applied to the Popper component. */
popper: {
zIndex: theme.zIndex.tooltip,
pointerEvents: 'none', // disable jss-rtl plugin
},
/* Styles applied to the Popper component unless `disableInteractive={true}`. */
popperInteractive: {
pointerEvents: 'auto',
},
/* Styles applied to the Popper component if `arrow={true}`. */
popperArrow: arrowGenerator(),
/* Styles applied to the tooltip (label wrapper) element. */
tooltip: {
backgroundColor: alpha(theme.palette.grey[700], 0.92),
borderRadius: theme.shape.borderRadius,
color: theme.palette.common.white,
fontFamily: theme.typography.fontFamily,
padding: '4px 8px',
fontSize: theme.typography.pxToRem(11),
maxWidth: 300,
wordWrap: 'break-word',
fontWeight: theme.typography.fontWeightMedium,
},
/* Styles applied to the tooltip (label wrapper) element if `arrow={true}`. */
tooltipArrow: {
position: 'relative',
margin: '0',
},
/* Styles applied to the arrow element. */
arrow: {
overflow: 'hidden',
position: 'absolute',
width: '1em',
height: '0.71em' /* = width / sqrt(2) = (length of the hypotenuse) */,
boxSizing: 'border-box',
color: alpha(theme.palette.grey[700], 0.9),
'&::before': {
content: '""',
margin: 'auto',
display: 'block',
width: '100%',
height: '100%',
backgroundColor: 'currentColor',
transform: 'rotate(45deg)',
},
},
/* Styles applied to the tooltip (label wrapper) element if the tooltip is opened by touch. */
touch: {
padding: '8px 16px',
fontSize: theme.typography.pxToRem(14),
lineHeight: `${round(16 / 14)}em`,
fontWeight: theme.typography.fontWeightRegular,
},
/* Styles applied to the tooltip (label wrapper) element if `placement` contains "left". */
tooltipPlacementLeft: {
transformOrigin: 'right center',
margin: '0 24px ',
[theme.breakpoints.up('sm')]: {
margin: '0 14px',
},
},
/* Styles applied to the tooltip (label wrapper) element if `placement` contains "right". */
tooltipPlacementRight: {
transformOrigin: 'left center',
margin: '0 24px',
[theme.breakpoints.up('sm')]: {
margin: '0 14px',
},
},
/* Styles applied to the tooltip (label wrapper) element if `placement` contains "top". */
tooltipPlacementTop: {
transformOrigin: 'center bottom',
margin: '24px 0',
[theme.breakpoints.up('sm')]: {
margin: '14px 0',
},
},
/* Styles applied to the tooltip (label wrapper) element if `placement` contains "bottom". */
tooltipPlacementBottom: {
transformOrigin: 'center top',
margin: '24px 0',
[theme.breakpoints.up('sm')]: {
margin: '14px 0',
},
},
});
let hystersisOpen = false;
let hystersisTimer = null;
export function testReset() {
hystersisOpen = false;
clearTimeout(hystersisTimer);
}
const Tooltip = React.forwardRef(function Tooltip(props, ref) {
const {
arrow = false,
children,
classes,
describeChild = false,
disableFocusListener = false,
disableHoverListener = false,
disableTouchListener = false,
enterDelay = 100,
enterNextDelay = 0,
enterTouchDelay = 700,
followCursor = false,
id: idProp,
disableInteractive = false,
leaveDelay = 0,
leaveTouchDelay = 1500,
onClose,
onOpen,
open: openProp,
placement = 'bottom',
PopperComponent = Popper,
PopperProps,
title,
TransitionComponent = Grow,
TransitionProps,
...other
} = props;
const theme = useTheme();
const [childNode, setChildNode] = React.useState();
const [arrowRef, setArrowRef] = React.useState(null);
const ignoreNonTouchEvents = React.useRef(false);
const closeTimer = React.useRef();
const enterTimer = React.useRef();
const leaveTimer = React.useRef();
const touchTimer = React.useRef();
const [openState, setOpenState] = useControlled({
controlled: openProp,
default: false,
name: 'Tooltip',
state: 'open',
});
let open = openState;
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
const { current: isControlled } = React.useRef(openProp !== undefined);
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
if (
childNode &&
childNode.disabled &&
!isControlled &&
title !== '' &&
childNode.tagName.toLowerCase() === 'button'
) {
console.error(
[
'Material-UI: You are providing a disabled `button` child to the Tooltip component.',
'A disabled element does not fire events.',
"Tooltip needs to listen to the child element's events to display the title.",
'',
'Add a simple wrapper element, such as a `span`.',
].join('\n'),
);
}
}, [title, childNode, isControlled]);
}
const id = useId(idProp);
React.useEffect(() => {
return () => {
clearTimeout(closeTimer.current);
clearTimeout(enterTimer.current);
clearTimeout(leaveTimer.current);
clearTimeout(touchTimer.current);
};
}, []);
const handleOpen = (event) => {
clearTimeout(hystersisTimer);
hystersisOpen = true;
// The mouseover event will trigger for every nested element in the tooltip.
// We can skip rerendering when the tooltip is already open.
// We are using the mouseover event instead of the mouseenter event to fix a hide/show issue.
setOpenState(true);
if (onOpen) {
onOpen(event);
}
};
const handleEnter = (forward = true) => (event) => {
const childrenProps = children.props;
if (event.type === 'mouseover' && childrenProps.onMouseOver && forward) {
childrenProps.onMouseOver(event);
}
if (ignoreNonTouchEvents.current && event.type !== 'touchstart') {
return;
}
// Remove the title ahead of time.
// We don't want to wait for the next render commit.
// We would risk displaying two tooltips at the same time (native + this one).
if (childNode) {
childNode.removeAttribute('title');
}
clearTimeout(enterTimer.current);
clearTimeout(leaveTimer.current);
if (enterDelay || (hystersisOpen && enterNextDelay)) {
event.persist();
enterTimer.current = setTimeout(
() => {
handleOpen(event);
},
hystersisOpen ? enterNextDelay : enterDelay,
);
} else {
handleOpen(event);
}
};
const {
isFocusVisibleRef,
onBlur: handleBlurVisible,
onFocus: handleFocusVisible,
ref: focusVisibleRef,
} = useIsFocusVisible();
// We don't necessarily care about the focusVisible state (which is safe to access via ref anyway).
// We just need to re-render the Tooltip if the focus-visible state changes.
const [, setChildIsFocusVisible] = React.useState(false);
const handleBlur = (event) => {
handleBlurVisible(event);
if (isFocusVisibleRef.current === false) {
setChildIsFocusVisible(false);
}
};
const handleFocus = (forward = true) => (event) => {
// Workaround for https://github.com/facebook/react/issues/7769
// The autoFocus of React might trigger the event before the componentDidMount.
// We need to account for this eventuality.
if (!childNode) {
setChildNode(event.currentTarget);
}
handleFocusVisible(event);
if (isFocusVisibleRef.current === true) {
setChildIsFocusVisible(true);
handleEnter()(event);
}
const childrenProps = children.props;
if (childrenProps.onFocus && forward) {
childrenProps.onFocus(event);
}
};
const handleClose = useEventCallback(
/**
* @param {React.SyntheticEvent | Event} event
*/
(event) => {
clearTimeout(hystersisTimer);
hystersisTimer = setTimeout(() => {
hystersisOpen = false;
}, 800 + leaveDelay);
setOpenState(false);
if (onClose) {
onClose(event);
}
clearTimeout(closeTimer.current);
closeTimer.current = setTimeout(() => {
ignoreNonTouchEvents.current = false;
}, theme.transitions.duration.shortest);
},
);
const handleLeave = (forward = true) => (event) => {
const childrenProps = children.props;
if (event.type === 'blur') {
if (childrenProps.onBlur && forward) {
childrenProps.onBlur(event);
}
handleBlur(event);
}
if (
event.type === 'mouseleave' &&
childrenProps.onMouseLeave &&
event.currentTarget === childNode
) {
childrenProps.onMouseLeave(event);
}
clearTimeout(enterTimer.current);
clearTimeout(leaveTimer.current);
event.persist();
leaveTimer.current = setTimeout(() => {
handleClose(event);
}, leaveDelay);
};
const detectTouchStart = (event) => {
ignoreNonTouchEvents.current = true;
const childrenProps = children.props;
if (childrenProps.onTouchStart) {
childrenProps.onTouchStart(event);
}
};
const handleTouchStart = (event) => {
detectTouchStart(event);
clearTimeout(leaveTimer.current);
clearTimeout(closeTimer.current);
clearTimeout(touchTimer.current);
event.persist();
touchTimer.current = setTimeout(() => {
handleEnter()(event);
}, enterTouchDelay);
};
const handleTouchEnd = (event) => {
if (children.props.onTouchEnd) {
children.props.onTouchEnd(event);
}
clearTimeout(touchTimer.current);
clearTimeout(leaveTimer.current);
event.persist();
leaveTimer.current = setTimeout(() => {
handleClose(event);
}, leaveTouchDelay);
};
React.useEffect(() => {
if (!open) {
return undefined;
}
/**
* @param {KeyboardEvent} nativeEvent
*/
function handleKeyDown(nativeEvent) {
// IE11, Edge (prior to using Bink?) use 'Esc'
if (nativeEvent.key === 'Escape' || nativeEvent.key === 'Esc') {
handleClose(nativeEvent);
}
}
document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [handleClose, open]);
const handleUseRef = useForkRef(setChildNode, ref);
const handleFocusRef = useForkRef(focusVisibleRef, handleUseRef);
const handleRef = useForkRef(children.ref, handleFocusRef);
// There is no point in displaying an empty tooltip.
if (title === '') {
open = false;
}
const positionRef = React.useRef({ x: 0, y: 0 });
const popperRef = React.useRef();
const handleMouseMove = (event) => {
const childrenProps = children.props;
if (childrenProps.onMouseMove) {
childrenProps.onMouseMove(event);
}
positionRef.current = { x: event.clientX, y: event.clientY };
if (popperRef.current) {
popperRef.current.scheduleUpdate();
}
};
const nameOrDescProps = {};
const titleIsString = typeof title === 'string';
if (describeChild) {
nameOrDescProps['title'] = !open && titleIsString && !disableHoverListener ? title : null;
nameOrDescProps['aria-describedby'] = open ? id : null;
} else {
nameOrDescProps['aria-label'] = titleIsString ? title : null;
nameOrDescProps['aria-labelledby'] = open && !titleIsString ? id : null;
}
const childrenProps = {
...nameOrDescProps,
...other,
...children.props,
className: clsx(other.className, children.props.className),
onTouchStart: detectTouchStart,
ref: handleRef,
...(followCursor ? { onMouseMove: handleMouseMove } : {}),
};
if (process.env.NODE_ENV !== 'production') {
childrenProps['data-mui-internal-clone-element'] = true;
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
if (childNode && !childNode.getAttribute('data-mui-internal-clone-element')) {
console.error(
[
'Material-UI: The `children` component of the Tooltip is not forwarding its props correctly.',
'Please make sure that props are spread on the same element that the ref is applied to.',
].join('\n'),
);
}
}, [childNode]);
}
const interactiveWrapperListeners = {};
if (!disableTouchListener) {
childrenProps.onTouchStart = handleTouchStart;
childrenProps.onTouchEnd = handleTouchEnd;
}
if (!disableHoverListener) {
childrenProps.onMouseOver = handleEnter();
childrenProps.onMouseLeave = handleLeave();
if (!disableInteractive) {
interactiveWrapperListeners.onMouseOver = handleEnter(false);
interactiveWrapperListeners.onMouseLeave = handleLeave(false);
}
}
if (!disableFocusListener) {
childrenProps.onFocus = handleFocus();
childrenProps.onBlur = handleLeave();
if (!disableInteractive) {
interactiveWrapperListeners.onFocus = handleFocus(false);
interactiveWrapperListeners.onBlur = handleLeave(false);
}
}
if (process.env.NODE_ENV !== 'production') {
if (children.props.title) {
console.error(
[
'Material-UI: You have provided a `title` prop to the child of <Tooltip />.',
`Remove this title prop \`${children.props.title}\` or the Tooltip component.`,
].join('\n'),
);
}
}
const mergedPopperProps = React.useMemo(() => {
return deepmerge(
{
popperOptions: {
modifiers: {
arrow: {
enabled: Boolean(arrowRef),
element: arrowRef,
},
},
},
},
PopperProps,
);
}, [arrowRef, PopperProps]);
return (
<React.Fragment>
{React.cloneElement(children, childrenProps)}
<PopperComponent
className={clsx(classes.popper, {
[classes.popperInteractive]: !disableInteractive,
[classes.popperArrow]: arrow,
})}
placement={placement}
anchorEl={
followCursor
? {
clientHeight: 0,
clientWidth: 0,
getBoundingClientRect: () => ({
top: positionRef.current.y,
left: positionRef.current.x,
right: positionRef.current.x,
bottom: positionRef.current.y,
width: 0,
height: 0,
}),
}
: childNode
}
popperRef={popperRef}
open={childNode ? open : false}
id={id}
transition
{...interactiveWrapperListeners}
{...mergedPopperProps}
>
{({ placement: placementInner, TransitionProps: TransitionPropsInner }) => (
<TransitionComponent
timeout={theme.transitions.duration.shorter}
{...TransitionPropsInner}
{...TransitionProps}
>
<div
className={clsx(
classes.tooltip,
{
[classes.touch]: ignoreNonTouchEvents.current,
[classes.tooltipArrow]: arrow,
},
classes[`tooltipPlacement${capitalize(placementInner.split('-')[0])}`],
)}
>
{title}
{arrow ? <span className={classes.arrow} ref={setArrowRef} /> : null}
</div>
</TransitionComponent>
)}
</PopperComponent>
</React.Fragment>
);
});
Tooltip.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* If `true`, adds an arrow to the tooltip.
* @default false
*/
arrow: PropTypes.bool,
/**
* Tooltip reference element.
*/
children: elementAcceptingRef.isRequired,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* Set to `true` if the `title` acts as an accessible description.
* By default the `title` acts as an accessible label for the child.
* @default false
*/
describeChild: PropTypes.bool,
/**
* Do not respond to focus events.
* @default false
*/
disableFocusListener: PropTypes.bool,
/**
* Do not respond to hover events.
* @default false
*/
disableHoverListener: PropTypes.bool,
/**
* Makes a tooltip not interactive, i.e. it will close when the user
* hovers over the tooltip before the `leaveDelay` is expired.
* @default false
*/
disableInteractive: PropTypes.bool,
/**
* Do not respond to long press touch events.
* @default false
*/
disableTouchListener: PropTypes.bool,
/**
* The number of milliseconds to wait before showing the tooltip.
* This prop won't impact the enter touch delay (`enterTouchDelay`).
* @default 100
*/
enterDelay: PropTypes.number,
/**
* The number of milliseconds to wait before showing the tooltip when one was already recently opened.
* @default 0
*/
enterNextDelay: PropTypes.number,
/**
* The number of milliseconds a user must touch the element before showing the tooltip.
* @default 700
*/
enterTouchDelay: PropTypes.number,
/**
* If `true`, the tooltip follow the cursor over the wrapped element.
* @default false
*/
followCursor: PropTypes.bool,
/**
* This prop is used to help implement the accessibility logic.
* If you don't provide this prop. It falls back to a randomly generated id.
*/
id: PropTypes.string,
/**
* The number of milliseconds to wait before hiding the tooltip.
* This prop won't impact the leave touch delay (`leaveTouchDelay`).
* @default 0
*/
leaveDelay: PropTypes.number,
/**
* The number of milliseconds after the user stops touching an element before hiding the tooltip.
* @default 1500
*/
leaveTouchDelay: PropTypes.number,
/**
* Callback fired when the component requests to be closed.
*
* @param {object} event The event source of the callback.
*/
onClose: PropTypes.func,
/**
* Callback fired when the component requests to be open.
*
* @param {object} event The event source of the callback.
*/
onOpen: PropTypes.func,
/**
* If `true`, the tooltip is shown.
*/
open: PropTypes.bool,
/**
* Tooltip placement.
* @default 'bottom'
*/
placement: PropTypes.oneOf([
'bottom-end',
'bottom-start',
'bottom',
'left-end',
'left-start',
'left',
'right-end',
'right-start',
'right',
'top-end',
'top-start',
'top',
]),
/**
* The component used for the popper.
* @default Popper
*/
PopperComponent: PropTypes.elementType,
/**
* Props applied to the [`Popper`](/api/popper/) element.
*/
PopperProps: PropTypes.object,
/**
* Tooltip title. Zero-length titles string are never displayed.
*/
title: PropTypes /* @typescript-to-proptypes-ignore */.node.isRequired,
/**
* The component used for the transition.
* [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
* @default Grow
*/
TransitionComponent: PropTypes.elementType,
/**
* Props applied to the transition element.
* By default, the element is based on this [`Transition`](http://reactcommunity.org/react-transition-group/transition) component.
*/
TransitionProps: PropTypes.object,
};
export default withStyles(styles, { name: 'MuiTooltip', flip: false })(Tooltip);