tooltip.tsx 10 KB

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