tooltip.tsx 10 KB

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