hovercard.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
  2. import {createPortal} from 'react-dom';
  3. import {Manager, Popper, PopperProps, Reference} from 'react-popper';
  4. import styled from '@emotion/styled';
  5. import classNames from 'classnames';
  6. import {motion} from 'framer-motion';
  7. import space from 'sentry/styles/space';
  8. import domId from 'sentry/utils/domId';
  9. export const HOVERCARD_PORTAL_ID = 'hovercard-portal';
  10. function findOrCreatePortal(): HTMLElement {
  11. let portal = document.getElementById(HOVERCARD_PORTAL_ID);
  12. if (portal) {
  13. return portal;
  14. }
  15. portal = document.createElement('div');
  16. portal.setAttribute('id', HOVERCARD_PORTAL_ID);
  17. document.body.appendChild(portal);
  18. return portal;
  19. }
  20. interface HovercardProps {
  21. /**
  22. * Classname to apply to the hovercard
  23. */
  24. children: React.ReactNode;
  25. /**
  26. * Element to display in the body
  27. */
  28. body?: React.ReactNode;
  29. /**
  30. * Classname to apply to body container
  31. */
  32. bodyClassName?: string;
  33. className?: string;
  34. /**
  35. * Classname to apply to the hovercard container
  36. */
  37. containerClassName?: string;
  38. /**
  39. * Time in ms until hovercard is hidden
  40. */
  41. displayTimeout?: number;
  42. /**
  43. * Element to display in the header
  44. */
  45. header?: React.ReactNode;
  46. /**
  47. * Popper Modifiers
  48. */
  49. modifiers?: PopperProps['modifiers'];
  50. /**
  51. * Offset for the arrow
  52. */
  53. offset?: string;
  54. /**
  55. * Position tooltip should take relative to the child element
  56. */
  57. position?: PopperProps['placement'];
  58. /**
  59. * If set, is used INSTEAD OF the hover action to determine whether the hovercard is shown
  60. */
  61. show?: boolean;
  62. /**
  63. * Whether to add a dotted underline to the trigger element, to indicate the
  64. * presence of a tooltip.
  65. */
  66. showUnderline?: boolean;
  67. /**
  68. * Color of the arrow tip border
  69. */
  70. tipBorderColor?: string;
  71. /**
  72. * Color of the arrow tip
  73. */
  74. tipColor?: string;
  75. }
  76. function Hovercard(props: HovercardProps): React.ReactElement {
  77. const [visible, setVisible] = useState(false);
  78. const scheduleUpdateRef = useRef<(() => void) | null>(null);
  79. const portalEl = useMemo(() => findOrCreatePortal(), []);
  80. const tooltipId = useMemo(() => domId('hovercard-'), []);
  81. const showHoverCardTimeoutRef = useRef<number | undefined>(undefined);
  82. useEffect(() => {
  83. return () => {
  84. window.clearTimeout(showHoverCardTimeoutRef.current);
  85. };
  86. }, []);
  87. useEffect(() => {
  88. // We had a problem with popper not recalculating position when body/header changed while hovercard still opened.
  89. // This can happen for example when showing a loading spinner in a hovercard and then changing it to the actual content once fetch finishes.
  90. if (scheduleUpdateRef.current) {
  91. scheduleUpdateRef.current();
  92. }
  93. }, [props.body, props.header]);
  94. const toggleHovercard = useCallback(
  95. (value: boolean) => {
  96. window.clearTimeout(showHoverCardTimeoutRef.current);
  97. // Else enqueue a new timeout
  98. showHoverCardTimeoutRef.current = window.setTimeout(
  99. () => setVisible(value),
  100. props.displayTimeout ?? 100
  101. );
  102. },
  103. [props.displayTimeout]
  104. );
  105. const popperModifiers = useMemo(() => {
  106. const modifiers: PopperProps['modifiers'] = {
  107. hide: {
  108. enabled: false,
  109. },
  110. preventOverflow: {
  111. padding: 10,
  112. enabled: true,
  113. boundariesElement: 'viewport',
  114. },
  115. ...(props.modifiers || {}),
  116. };
  117. return modifiers;
  118. }, [props.modifiers]);
  119. // If show is not set, then visibility state is uncontrolled
  120. const isVisible = props.show === undefined ? visible : props.show;
  121. const hoverProps = useMemo((): {
  122. onMouseEnter?: React.MouseEventHandler<HTMLDivElement>;
  123. onMouseLeave?: React.MouseEventHandler<HTMLDivElement>;
  124. } => {
  125. // If show is not set, then visibility state is controlled by mouse events
  126. if (props.show === undefined) {
  127. return {
  128. onMouseEnter: () => toggleHovercard(true),
  129. onMouseLeave: () => toggleHovercard(false),
  130. };
  131. }
  132. return {};
  133. }, [props.show, toggleHovercard]);
  134. return (
  135. <Manager>
  136. <Reference>
  137. {({ref}) => (
  138. <Trigger
  139. ref={ref}
  140. aria-describedby={tooltipId}
  141. className={props.containerClassName}
  142. showUnderline={props.showUnderline}
  143. {...hoverProps}
  144. >
  145. {props.children}
  146. </Trigger>
  147. )}
  148. </Reference>
  149. {createPortal(
  150. <Popper placement={props.position ?? 'top'} modifiers={popperModifiers}>
  151. {({ref, style, placement, arrowProps, scheduleUpdate}) => {
  152. scheduleUpdateRef.current = scheduleUpdate;
  153. // Element is not visible in neither controlled and uncontrolled state (show prop is not passed and card is not hovered)
  154. if (!isVisible) {
  155. return null;
  156. }
  157. // Nothing to render
  158. if (!props.body && !props.header) {
  159. return null;
  160. }
  161. return (
  162. <HovercardContainer style={style}>
  163. <SlideInAnimation visible={isVisible} placement={placement}>
  164. <StyledHovercard
  165. ref={ref}
  166. id={tooltipId}
  167. placement={placement}
  168. offset={props.offset}
  169. // Maintain the hovercard class name for BC with less styles
  170. className={classNames('hovercard', props.className)}
  171. {...hoverProps}
  172. >
  173. {props.header ? <Header>{props.header}</Header> : null}
  174. {props.body ? (
  175. <Body className={props.bodyClassName}>{props.body}</Body>
  176. ) : null}
  177. <HovercardArrow
  178. ref={arrowProps.ref}
  179. style={arrowProps.style}
  180. placement={placement}
  181. tipColor={props.tipColor}
  182. tipBorderColor={props.tipBorderColor}
  183. />
  184. </StyledHovercard>
  185. </SlideInAnimation>
  186. </HovercardContainer>
  187. );
  188. }}
  189. </Popper>,
  190. portalEl
  191. )}
  192. </Manager>
  193. );
  194. }
  195. export {Hovercard};
  196. const SLIDE_DISTANCE = 10;
  197. function SlideInAnimation({
  198. visible,
  199. placement,
  200. children,
  201. }: {
  202. children: React.ReactNode;
  203. placement: PopperProps['placement'];
  204. visible: boolean;
  205. }): React.ReactElement {
  206. const narrowedPlacement = getTipDirection(placement);
  207. const x =
  208. narrowedPlacement === 'left'
  209. ? [-SLIDE_DISTANCE, 0]
  210. : narrowedPlacement === 'right'
  211. ? [SLIDE_DISTANCE, 0]
  212. : [0, 0];
  213. const y =
  214. narrowedPlacement === 'top'
  215. ? [-SLIDE_DISTANCE, 0]
  216. : narrowedPlacement === 'bottom'
  217. ? [SLIDE_DISTANCE, 0]
  218. : [0, 0];
  219. return (
  220. <motion.div
  221. initial="hidden"
  222. variants={{
  223. hidden: {
  224. opacity: 0,
  225. },
  226. visible: {
  227. opacity: [0, 1],
  228. x,
  229. y,
  230. },
  231. }}
  232. animate={visible ? 'visible' : 'hidden'}
  233. transition={{duration: 0.1, ease: 'easeInOut'}}
  234. >
  235. {children}
  236. </motion.div>
  237. );
  238. }
  239. function getTipDirection(
  240. placement: HovercardArrowProps['placement']
  241. ): 'top' | 'bottom' | 'left' | 'right' {
  242. if (!placement) {
  243. return 'top';
  244. }
  245. const prefix = ['top', 'bottom', 'left', 'right'].find(pl => {
  246. return placement.startsWith(pl);
  247. });
  248. return (prefix || 'top') as 'top' | 'bottom' | 'left' | 'right';
  249. }
  250. const Trigger = styled('span')<{showUnderline?: boolean}>`
  251. ${p => p.showUnderline && p.theme.tooltipUnderline};
  252. `;
  253. const HovercardContainer = styled('div')`
  254. /* Some hovercards overlap the toplevel header and sidebar, and we need to appear on top */
  255. z-index: ${p => p.theme.zIndex.hovercard};
  256. `;
  257. type StyledHovercardProps = {
  258. placement: PopperProps['placement'];
  259. offset?: string;
  260. };
  261. const StyledHovercard = styled('div')<StyledHovercardProps>`
  262. position: relative;
  263. border-radius: ${p => p.theme.borderRadius};
  264. text-align: left;
  265. padding: 0;
  266. line-height: 1;
  267. white-space: initial;
  268. color: ${p => p.theme.textColor};
  269. border: 1px solid ${p => p.theme.border};
  270. background: ${p => p.theme.background};
  271. background-clip: padding-box;
  272. box-shadow: 0 0 35px 0 rgba(67, 62, 75, 0.2);
  273. width: 295px;
  274. /* The hovercard may appear in different contexts, don't inherit fonts */
  275. font-family: ${p => p.theme.text.family};
  276. /* Offset for the arrow */
  277. ${p => (p.placement === 'top' ? `margin-bottom: ${p.offset ?? space(2)}` : '')};
  278. ${p => (p.placement === 'bottom' ? `margin-top: ${p.offset ?? space(2)}` : '')};
  279. ${p => (p.placement === 'left' ? `margin-right: ${p.offset ?? space(2)}` : '')};
  280. ${p => (p.placement === 'right' ? `margin-left: ${p.offset ?? space(2)}` : '')};
  281. `;
  282. const Header = styled('div')`
  283. font-size: ${p => p.theme.fontSizeMedium};
  284. background: ${p => p.theme.backgroundSecondary};
  285. border-bottom: 1px solid ${p => p.theme.border};
  286. border-radius: ${p => p.theme.borderRadiusTop};
  287. font-weight: 600;
  288. word-wrap: break-word;
  289. padding: ${space(1.5)};
  290. `;
  291. export {Header};
  292. const Body = styled('div')`
  293. padding: ${space(2)};
  294. min-height: 30px;
  295. `;
  296. export {Body};
  297. type HovercardArrowProps = {
  298. placement: PopperProps['placement'];
  299. tipBorderColor?: string;
  300. tipColor?: string;
  301. };
  302. const HovercardArrow = styled('span')<HovercardArrowProps>`
  303. position: absolute;
  304. width: 20px;
  305. height: 20px;
  306. right: ${p => (p.placement === 'left' ? '-20px' : 'auto')};
  307. left: ${p => (p.placement === 'right' ? '-20px' : 'auto')};
  308. bottom: ${p => (p.placement === 'top' ? '-20px' : 'auto')};
  309. top: ${p => (p.placement === 'bottom' ? '-20px' : 'auto')};
  310. &::before,
  311. &::after {
  312. content: '';
  313. margin: auto;
  314. position: absolute;
  315. display: block;
  316. width: 0;
  317. height: 0;
  318. top: 0;
  319. left: 0;
  320. }
  321. /* before element is the hairline border, it is repositioned for each orientation */
  322. &::before {
  323. top: 1px;
  324. border: 10px solid transparent;
  325. border-${p => getTipDirection(p.placement)}-color:
  326. ${p => p.tipBorderColor || p.tipColor || p.theme.border};
  327. ${p => (p.placement === 'bottom' ? 'top: -1px' : '')};
  328. ${p => (p.placement === 'left' ? 'top: 0; left: 1px;' : '')};
  329. ${p => (p.placement === 'right' ? 'top: 0; left: -1px' : '')};
  330. }
  331. &::after {
  332. border: 10px solid transparent;
  333. border-${p => getTipDirection(p.placement)}-color: ${p =>
  334. p.tipColor ?? p.theme.background};
  335. }
  336. `;