hovercard.tsx 9.9 KB

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