tooltip.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import * as React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import {Manager, Popper, PopperArrowProps, PopperProps, Reference} from 'react-popper';
  4. import {SerializedStyles} from '@emotion/react';
  5. import styled from '@emotion/styled';
  6. import {AnimatePresence, motion, MotionStyle} from 'framer-motion';
  7. import memoize from 'lodash/memoize';
  8. import * as PopperJS from 'popper.js';
  9. import {IS_ACCEPTANCE_TEST} from 'sentry/constants';
  10. import space from 'sentry/styles/space';
  11. import {domId} from 'sentry/utils/domId';
  12. import testableTransition from 'sentry/utils/testableTransition';
  13. import {isOverflown} from 'sentry/utils/tooltip';
  14. export const OPEN_DELAY = 50;
  15. /**
  16. * How long to wait before closing the tooltip when isHoverable is set
  17. */
  18. const CLOSE_DELAY = 50;
  19. type DefaultProps = {
  20. /**
  21. * Display mode for the container element
  22. */
  23. containerDisplayMode?: React.CSSProperties['display'];
  24. /**
  25. * Position for the tooltip.
  26. */
  27. position?: PopperJS.Placement;
  28. };
  29. type Props = DefaultProps & {
  30. /**
  31. * The node to attach the Tooltip to
  32. */
  33. children: React.ReactNode;
  34. /**
  35. * The content to show in the tooltip popover
  36. */
  37. title: React.ReactNode;
  38. className?: string;
  39. /**
  40. * Time to wait (in milliseconds) before showing the tooltip
  41. */
  42. delay?: number;
  43. /**
  44. * Stops tooltip from being opened during tooltip visual acceptance.
  45. * Should be set to true if tooltip contains unisolated data (eg. dates)
  46. */
  47. disableForVisualTest?: boolean;
  48. /**
  49. * Disable the tooltip display entirely
  50. */
  51. disabled?: boolean;
  52. /**
  53. * Force the tooltip to be visible without hovering
  54. */
  55. forceShow?: boolean;
  56. /**
  57. * If true, user is able to hover tooltip without it disappearing.
  58. * (nice if you want to be able to copy tooltip contents to clipboard)
  59. */
  60. isHoverable?: boolean;
  61. /**
  62. * Additional style rules for the tooltip content.
  63. */
  64. popperStyle?: React.CSSProperties | SerializedStyles;
  65. /**
  66. * Only display the tooltip only if the content overflows
  67. */
  68. showOnlyOnOverflow?: boolean;
  69. /**
  70. * If child node supports ref forwarding, you can skip apply a wrapper
  71. */
  72. skipWrapper?: boolean;
  73. };
  74. type State = {
  75. isOpen: boolean;
  76. usesGlobalPortal: boolean;
  77. };
  78. /**
  79. * Used to compute the transform origin to give the scale-down micro-animation
  80. * a pleasant feeling. Without this the animation can feel somewhat 'wrong'.
  81. */
  82. function computeOriginFromArrow(
  83. placement: PopperProps['placement'],
  84. arrowProps: PopperArrowProps
  85. ): MotionStyle {
  86. // XXX: Bottom means the arrow will be pointing up
  87. switch (placement) {
  88. case 'top':
  89. return {originX: `${arrowProps.style.left}px`, originY: '100%'};
  90. case 'bottom':
  91. return {originX: `${arrowProps.style.left}px`, originY: 0};
  92. case 'left':
  93. return {originX: '100%', originY: `${arrowProps.style.top}px`};
  94. case 'right':
  95. return {originX: 0, originY: `${arrowProps.style.top}px`};
  96. default:
  97. return {originX: `50%`, originY: '100%'};
  98. }
  99. }
  100. class Tooltip extends React.Component<Props, State> {
  101. static defaultProps: DefaultProps = {
  102. position: 'top',
  103. containerDisplayMode: 'inline-block',
  104. };
  105. state: State = {
  106. isOpen: false,
  107. usesGlobalPortal: true,
  108. };
  109. async componentDidMount() {
  110. if (IS_ACCEPTANCE_TEST) {
  111. const TooltipStore = (await import('sentry/stores/tooltipStore')).default;
  112. TooltipStore.addTooltip(this);
  113. }
  114. }
  115. async componentWillUnmount() {
  116. const {usesGlobalPortal} = this.state;
  117. if (IS_ACCEPTANCE_TEST) {
  118. const TooltipStore = (await import('sentry/stores/tooltipStore')).default;
  119. TooltipStore.removeTooltip(this);
  120. }
  121. if (!usesGlobalPortal) {
  122. document.body.removeChild(this.getPortal(usesGlobalPortal));
  123. }
  124. }
  125. tooltipId: string = domId('tooltip-');
  126. delayTimeout: number | null = null;
  127. delayHideTimeout: number | null = null;
  128. triggerEl: Element | null = null;
  129. getPortal = memoize((usesGlobalPortal): HTMLElement => {
  130. if (usesGlobalPortal) {
  131. let portal = document.getElementById('tooltip-portal');
  132. if (!portal) {
  133. portal = document.createElement('div');
  134. portal.setAttribute('id', 'tooltip-portal');
  135. document.body.appendChild(portal);
  136. }
  137. return portal;
  138. }
  139. const portal = document.createElement('div');
  140. document.body.appendChild(portal);
  141. return portal;
  142. });
  143. setOpen = () => {
  144. this.setState({isOpen: true});
  145. };
  146. setClose = () => {
  147. this.setState({isOpen: false});
  148. };
  149. handleOpen = () => {
  150. const {delay, showOnlyOnOverflow} = this.props;
  151. if (this.triggerEl && showOnlyOnOverflow && !isOverflown(this.triggerEl)) {
  152. return;
  153. }
  154. if (this.delayHideTimeout) {
  155. window.clearTimeout(this.delayHideTimeout);
  156. this.delayHideTimeout = null;
  157. }
  158. if (delay === 0) {
  159. this.setOpen();
  160. return;
  161. }
  162. this.delayTimeout = window.setTimeout(this.setOpen, delay ?? OPEN_DELAY);
  163. };
  164. handleClose = () => {
  165. const {isHoverable} = this.props;
  166. if (this.delayTimeout) {
  167. window.clearTimeout(this.delayTimeout);
  168. this.delayTimeout = null;
  169. }
  170. if (isHoverable) {
  171. this.delayHideTimeout = window.setTimeout(this.setClose, CLOSE_DELAY);
  172. } else {
  173. this.setClose();
  174. }
  175. };
  176. renderTrigger(children: React.ReactNode, ref: React.Ref<HTMLElement>) {
  177. const propList: {[key: string]: any} = {
  178. 'aria-describedby': this.tooltipId,
  179. onFocus: this.handleOpen,
  180. onBlur: this.handleClose,
  181. onPointerEnter: this.handleOpen,
  182. onPointerLeave: this.handleClose,
  183. };
  184. const setRef = el => {
  185. if (typeof ref === 'function') {
  186. ref(el);
  187. }
  188. this.triggerEl = el;
  189. };
  190. // Use the `type` property of the react instance to detect whether we
  191. // have a basic element (type=string) or a class/function component (type=function or object)
  192. // Because we can't rely on the child element implementing forwardRefs we wrap
  193. // it with a span tag so that popper has ref
  194. if (
  195. React.isValidElement(children) &&
  196. (this.props.skipWrapper || typeof children.type === 'string')
  197. ) {
  198. // Basic DOM nodes can be cloned and have more props applied.
  199. return React.cloneElement(children, {
  200. ...propList,
  201. ref: setRef,
  202. });
  203. }
  204. propList.containerDisplayMode = this.props.containerDisplayMode;
  205. return (
  206. <Container {...propList} className={this.props.className} ref={setRef}>
  207. {children}
  208. </Container>
  209. );
  210. }
  211. render() {
  212. const {disabled, forceShow, children, title, position, popperStyle, isHoverable} =
  213. this.props;
  214. const {isOpen, usesGlobalPortal} = this.state;
  215. if (disabled || !title) {
  216. return children;
  217. }
  218. const modifiers: PopperJS.Modifiers = {
  219. hide: {enabled: false},
  220. preventOverflow: {
  221. padding: 10,
  222. enabled: true,
  223. boundariesElement: 'viewport',
  224. },
  225. applyStyle: {
  226. gpuAcceleration: true,
  227. },
  228. };
  229. const visible = forceShow || isOpen;
  230. const tip = visible ? (
  231. <Popper placement={position} modifiers={modifiers}>
  232. {({ref, style, placement, arrowProps}) => (
  233. <PositionWrapper style={style}>
  234. <TooltipContent
  235. id={this.tooltipId}
  236. initial={{opacity: 0}}
  237. animate={{
  238. opacity: 1,
  239. scale: 1,
  240. transition: testableTransition({
  241. type: 'linear',
  242. ease: [0.5, 1, 0.89, 1],
  243. duration: 0.2,
  244. }),
  245. }}
  246. exit={{
  247. opacity: 0,
  248. scale: 0.95,
  249. transition: testableTransition({type: 'spring', delay: 0.1}),
  250. }}
  251. style={computeOriginFromArrow(position, arrowProps)}
  252. transition={{duration: 0.2}}
  253. className="tooltip-content"
  254. aria-hidden={!visible}
  255. ref={ref}
  256. data-placement={placement}
  257. popperStyle={popperStyle}
  258. onMouseEnter={() => isHoverable && this.handleOpen()}
  259. onMouseLeave={() => isHoverable && this.handleClose()}
  260. >
  261. {title}
  262. <TooltipArrow
  263. ref={arrowProps.ref}
  264. data-placement={placement}
  265. style={arrowProps.style}
  266. />
  267. </TooltipContent>
  268. </PositionWrapper>
  269. )}
  270. </Popper>
  271. ) : null;
  272. return (
  273. <Manager>
  274. <Reference>{({ref}) => this.renderTrigger(children, ref)}</Reference>
  275. {ReactDOM.createPortal(
  276. <AnimatePresence>{tip}</AnimatePresence>,
  277. this.getPortal(usesGlobalPortal)
  278. )}
  279. </Manager>
  280. );
  281. }
  282. }
  283. // Using an inline-block solves the container being smaller
  284. // than the elements it is wrapping
  285. const Container = styled('span')<{
  286. containerDisplayMode?: React.CSSProperties['display'];
  287. }>`
  288. ${p => p.containerDisplayMode && `display: ${p.containerDisplayMode}`};
  289. max-width: 100%;
  290. `;
  291. const PositionWrapper = styled('div')`
  292. z-index: ${p => p.theme.zIndex.tooltip};
  293. `;
  294. const TooltipContent = styled(motion.div)<Pick<Props, 'popperStyle'>>`
  295. will-change: transform, opacity;
  296. position: relative;
  297. background: ${p => p.theme.backgroundElevated};
  298. padding: ${space(1)} ${space(1.5)};
  299. border-radius: ${p => p.theme.borderRadius};
  300. box-shadow: 0 0 0 1px ${p => p.theme.translucentBorder}, ${p => p.theme.dropShadowHeavy};
  301. overflow-wrap: break-word;
  302. max-width: 225px;
  303. color: ${p => p.theme.textColor};
  304. font-size: ${p => p.theme.fontSizeSmall};
  305. line-height: 1.2;
  306. margin: 6px;
  307. text-align: center;
  308. ${p => p.popperStyle as any};
  309. `;
  310. const TooltipArrow = styled('span')`
  311. position: absolute;
  312. width: 6px;
  313. height: 6px;
  314. border: solid 6px transparent;
  315. pointer-events: none;
  316. &::before {
  317. content: '';
  318. display: block;
  319. position: absolute;
  320. width: 0;
  321. height: 0;
  322. border: solid 6px transparent;
  323. z-index: -1;
  324. }
  325. &[data-placement*='bottom'] {
  326. top: 0;
  327. margin-top: -12px;
  328. border-bottom-color: ${p => p.theme.backgroundElevated};
  329. &::before {
  330. bottom: -5px;
  331. left: -6px;
  332. border-bottom-color: ${p => p.theme.translucentBorder};
  333. }
  334. }
  335. &[data-placement*='top'] {
  336. bottom: 0;
  337. margin-bottom: -12px;
  338. border-top-color: ${p => p.theme.backgroundElevated};
  339. &::before {
  340. top: -5px;
  341. left: -6px;
  342. border-top-color: ${p => p.theme.translucentBorder};
  343. }
  344. }
  345. &[data-placement*='right'] {
  346. left: 0;
  347. margin-left: -12px;
  348. border-right-color: ${p => p.theme.backgroundElevated};
  349. &::before {
  350. top: -6px;
  351. right: -5px;
  352. border-right-color: ${p => p.theme.translucentBorder};
  353. }
  354. }
  355. &[data-placement*='left'] {
  356. right: 0;
  357. margin-right: -12px;
  358. border-left-color: ${p => p.theme.backgroundElevated};
  359. &::before {
  360. top: -6px;
  361. left: -5px;
  362. border-left-color: ${p => p.theme.translucentBorder};
  363. }
  364. }
  365. `;
  366. export default Tooltip;