index.tsx 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. /* eslint-disable prefer-destructuring, max-lines-per-function, react/no-find-dom-node, max-len, @typescript-eslint/no-empty-function */
  2. import React, { isValidElement, cloneElement } from 'react';
  3. import ReactDOM from 'react-dom';
  4. import classNames from 'classnames';
  5. import PropTypes from 'prop-types';
  6. import { throttle, noop, get, omit, each, isEmpty, isFunction } from 'lodash';
  7. import { BASE_CLASS_PREFIX } from '@douyinfe/semi-foundation/base/constants';
  8. import warning from '@douyinfe/semi-foundation/utils/warning';
  9. import Event from '@douyinfe/semi-foundation/utils/Event';
  10. import { ArrayElement } from '@douyinfe/semi-foundation/utils/type';
  11. import { convertDOMRectToObject, DOMRectLikeType } from '@douyinfe/semi-foundation/utils/dom';
  12. import TooltipFoundation, { TooltipAdapter, Position, PopupContainerDOMRect } from '@douyinfe/semi-foundation/tooltip/foundation';
  13. import { strings, cssClasses, numbers } from '@douyinfe/semi-foundation/tooltip/constants';
  14. import { getUuidShort } from '@douyinfe/semi-foundation/utils/uuid';
  15. import '@douyinfe/semi-foundation/tooltip/tooltip.scss';
  16. import BaseComponent, { BaseProps } from '../_base/baseComponent';
  17. import { isHTMLElement } from '../_base/reactUtils';
  18. import { getActiveElement, getFocusableElements, stopPropagation } from '../_utils';
  19. import Portal from '../_portal/index';
  20. import ConfigContext, { ContextValue } from '../configProvider/context';
  21. import TriangleArrow from './TriangleArrow';
  22. import TriangleArrowVertical from './TriangleArrowVertical';
  23. import TooltipTransition from './TooltipStyledTransition';
  24. import ArrowBoundingShape from './ArrowBoundingShape';
  25. import { Motion } from '../_base/base';
  26. export { TooltipTransitionProps } from './TooltipStyledTransition';
  27. export type Trigger = ArrayElement<typeof strings.TRIGGER_SET>;
  28. export interface ArrowBounding {
  29. offsetX?: number;
  30. offsetY?: number;
  31. width?: number;
  32. height?: number;
  33. }
  34. export interface RenderContentProps {
  35. initialFocusRef?: React.RefObject<HTMLElement>;
  36. }
  37. export type RenderContent = (props: RenderContentProps) => React.ReactNode;
  38. export interface TooltipProps extends BaseProps {
  39. children?: React.ReactNode;
  40. motion?: Motion;
  41. autoAdjustOverflow?: boolean;
  42. position?: Position;
  43. getPopupContainer?: () => HTMLElement;
  44. mouseEnterDelay?: number;
  45. mouseLeaveDelay?: number;
  46. trigger?: Trigger;
  47. className?: string;
  48. clickToHide?: boolean;
  49. visible?: boolean;
  50. style?: React.CSSProperties;
  51. content?: React.ReactNode | RenderContent;
  52. prefixCls?: string;
  53. onVisibleChange?: (visible: boolean) => void;
  54. onClickOutSide?: (e: React.MouseEvent) => void;
  55. spacing?: number;
  56. showArrow?: boolean | React.ReactNode;
  57. zIndex?: number;
  58. rePosKey?: string | number;
  59. role?: string;
  60. arrowBounding?: ArrowBounding;
  61. transformFromCenter?: boolean;
  62. arrowPointAtCenter?: boolean;
  63. wrapWhenSpecial?: boolean;
  64. stopPropagation?: boolean;
  65. clickTriggerToHide?: boolean;
  66. wrapperClassName?: string;
  67. closeOnEsc?: boolean;
  68. guardFocus?: boolean;
  69. returnFocusOnClose?: boolean;
  70. onEscKeyDown?: (e: React.KeyboardEvent) => void;
  71. wrapperId?: string;
  72. }
  73. interface TooltipState {
  74. visible: boolean;
  75. transitionState: string;
  76. triggerEventSet: {
  77. [key: string]: any;
  78. };
  79. portalEventSet: {
  80. [key: string]: any;
  81. };
  82. containerStyle: React.CSSProperties;
  83. isInsert: boolean;
  84. placement: Position;
  85. transitionStyle: Record<string, any>;
  86. isPositionUpdated: boolean;
  87. id: string;
  88. }
  89. const prefix = cssClasses.PREFIX;
  90. const positionSet = strings.POSITION_SET;
  91. const triggerSet = strings.TRIGGER_SET;
  92. const blockDisplays = ['flex', 'block', 'table', 'flow-root', 'grid'];
  93. const defaultGetContainer = () => document.body;
  94. export default class Tooltip extends BaseComponent<TooltipProps, TooltipState> {
  95. static contextType = ConfigContext;
  96. static propTypes = {
  97. children: PropTypes.node,
  98. motion: PropTypes.oneOfType([PropTypes.bool, PropTypes.object, PropTypes.func]),
  99. autoAdjustOverflow: PropTypes.bool,
  100. position: PropTypes.oneOf(positionSet),
  101. getPopupContainer: PropTypes.func,
  102. mouseEnterDelay: PropTypes.number,
  103. mouseLeaveDelay: PropTypes.number,
  104. trigger: PropTypes.oneOf(triggerSet).isRequired,
  105. className: PropTypes.string,
  106. wrapperClassName: PropTypes.string,
  107. clickToHide: PropTypes.bool,
  108. // used with trigger === hover, private
  109. clickTriggerToHide: PropTypes.bool,
  110. visible: PropTypes.bool,
  111. style: PropTypes.object,
  112. content: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
  113. prefixCls: PropTypes.string,
  114. onVisibleChange: PropTypes.func,
  115. onClickOutSide: PropTypes.func,
  116. spacing: PropTypes.number,
  117. showArrow: PropTypes.oneOfType([PropTypes.bool, PropTypes.node]),
  118. zIndex: PropTypes.number,
  119. rePosKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  120. arrowBounding: ArrowBoundingShape,
  121. transformFromCenter: PropTypes.bool, // Whether to change from the center of the trigger (for dynamic effects)
  122. arrowPointAtCenter: PropTypes.bool,
  123. stopPropagation: PropTypes.bool,
  124. // private
  125. role: PropTypes.string,
  126. wrapWhenSpecial: PropTypes.bool, // when trigger has special status such as "disabled" or "loading", wrap span
  127. guardFocus: PropTypes.bool,
  128. returnFocusOnClose: PropTypes.bool,
  129. };
  130. static defaultProps = {
  131. arrowBounding: numbers.ARROW_BOUNDING,
  132. autoAdjustOverflow: true,
  133. arrowPointAtCenter: true,
  134. trigger: 'hover',
  135. transformFromCenter: true,
  136. position: 'top',
  137. prefixCls: prefix,
  138. role: 'tooltip',
  139. mouseEnterDelay: numbers.MOUSE_ENTER_DELAY,
  140. mouseLeaveDelay: numbers.MOUSE_LEAVE_DELAY,
  141. motion: true,
  142. onVisibleChange: noop,
  143. onClickOutSide: noop,
  144. spacing: numbers.SPACING,
  145. showArrow: true,
  146. wrapWhenSpecial: true,
  147. zIndex: numbers.DEFAULT_Z_INDEX,
  148. closeOnEsc: false,
  149. guardFocus: false,
  150. returnFocusOnClose: false,
  151. onEscKeyDown: noop,
  152. };
  153. eventManager: Event;
  154. triggerEl: React.RefObject<unknown>;
  155. containerEl: React.RefObject<HTMLDivElement>;
  156. initialFocusRef: React.RefObject<HTMLElement>;
  157. clickOutsideHandler: any;
  158. resizeHandler: any;
  159. isWrapped: boolean;
  160. mounted: any;
  161. scrollHandler: any;
  162. getPopupContainer: () => HTMLElement;
  163. containerPosition: string;
  164. foundation: TooltipFoundation;
  165. context: ContextValue;
  166. constructor(props: TooltipProps) {
  167. super(props);
  168. this.state = {
  169. visible: false,
  170. /**
  171. *
  172. * Note: The transitionState parameter is equivalent to isInsert
  173. */
  174. transitionState: '',
  175. triggerEventSet: {},
  176. portalEventSet: {},
  177. containerStyle: {
  178. // zIndex: props.zIndex,
  179. },
  180. isInsert: false,
  181. placement: props.position || 'top',
  182. transitionStyle: {},
  183. isPositionUpdated: false,
  184. id: props.wrapperId, // auto generate id, will be used by children.aria-describedby & content.id, improve a11y
  185. };
  186. this.foundation = new TooltipFoundation(this.adapter);
  187. this.eventManager = new Event();
  188. this.triggerEl = React.createRef();
  189. this.containerEl = React.createRef();
  190. this.initialFocusRef = React.createRef();
  191. this.clickOutsideHandler = null;
  192. this.resizeHandler = null;
  193. this.isWrapped = false; // Identifies whether a span element is wrapped
  194. this.containerPosition = undefined;
  195. }
  196. setContainerEl = (node: HTMLDivElement) => (this.containerEl = { current: node });
  197. get adapter(): TooltipAdapter<TooltipProps, TooltipState> {
  198. return {
  199. ...super.adapter,
  200. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  201. // @ts-ignore
  202. on: (...args: any[]) => this.eventManager.on(...args),
  203. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  204. // @ts-ignore
  205. off: (...args: any[]) => this.eventManager.off(...args),
  206. insertPortal: (content: TooltipProps['content'], { position, ...containerStyle }: { position: Position }) => {
  207. this.setState(
  208. {
  209. isInsert: true,
  210. transitionState: 'enter',
  211. containerStyle: { ...this.state.containerStyle, ...containerStyle },
  212. },
  213. () => {
  214. setTimeout(() => {
  215. // waiting child component mounted
  216. this.eventManager.emit('portalInserted');
  217. }, 0);
  218. }
  219. );
  220. },
  221. removePortal: () => {
  222. this.setState({ isInsert: false, isPositionUpdated: false });
  223. },
  224. getEventName: () => ({
  225. mouseEnter: 'onMouseEnter',
  226. mouseLeave: 'onMouseLeave',
  227. mouseOut: 'onMouseOut',
  228. mouseOver: 'onMouseOver',
  229. click: 'onClick',
  230. focus: 'onFocus',
  231. blur: 'onBlur',
  232. keydown: 'onKeyDown'
  233. }),
  234. registerTriggerEvent: (triggerEventSet: Record<string, any>) => {
  235. this.setState({ triggerEventSet });
  236. },
  237. unregisterTriggerEvent: () => {},
  238. registerPortalEvent: (portalEventSet: Record<string, any>) => {
  239. this.setState({ portalEventSet });
  240. },
  241. unregisterPortalEvent: () => {},
  242. getTriggerBounding: () => {
  243. // eslint-disable-next-line
  244. // It may be a React component or an html element
  245. // There is no guarantee that triggerE l.current can get the real dom, so call findDOMNode to ensure that you can get the real dom
  246. const triggerDOM = this.adapter.getTriggerNode();
  247. (this.triggerEl as any).current = triggerDOM;
  248. return triggerDOM && (triggerDOM as Element).getBoundingClientRect();
  249. },
  250. // Gets the outer size of the specified container
  251. getPopupContainerRect: () => {
  252. const container = this.getPopupContainer();
  253. let rect: PopupContainerDOMRect = null;
  254. if (container && isHTMLElement(container)) {
  255. const boundingRect: DOMRectLikeType = convertDOMRectToObject(container.getBoundingClientRect());
  256. rect = {
  257. ...boundingRect,
  258. scrollLeft: container.scrollLeft,
  259. scrollTop: container.scrollTop,
  260. };
  261. }
  262. return rect;
  263. },
  264. containerIsBody: () => {
  265. const container = this.getPopupContainer();
  266. return container === document.body;
  267. },
  268. containerIsRelative: () => {
  269. const container = this.getPopupContainer();
  270. const computedStyle = window.getComputedStyle(container);
  271. return computedStyle.getPropertyValue('position') === 'relative';
  272. },
  273. containerIsRelativeOrAbsolute: () => ['relative', 'absolute'].includes(this.containerPosition),
  274. // Get the size of the pop-up layer
  275. getWrapperBounding: () => {
  276. const el = this.containerEl && this.containerEl.current;
  277. return el && (el as Element).getBoundingClientRect();
  278. },
  279. getDocumentElementBounding: () => document.documentElement.getBoundingClientRect(),
  280. setPosition: ({ position, ...style }: { position: Position }) => {
  281. this.setState(
  282. {
  283. containerStyle: { ...this.state.containerStyle, ...style },
  284. placement: position,
  285. isPositionUpdated: true
  286. },
  287. () => {
  288. this.eventManager.emit('positionUpdated');
  289. }
  290. );
  291. },
  292. updatePlacementAttr: (placement: Position) => {
  293. this.setState({ placement });
  294. },
  295. togglePortalVisible: (visible: boolean, cb: () => void) => {
  296. const willUpdateStates: Partial<TooltipState> = {};
  297. if (this.adapter.canMotion()) {
  298. willUpdateStates.transitionState = visible ? 'enter' : 'leave';
  299. willUpdateStates.visible = visible;
  300. } else {
  301. willUpdateStates.visible = visible;
  302. }
  303. this.mounted && this.setState(willUpdateStates as TooltipState, () => {
  304. cb();
  305. });
  306. },
  307. registerClickOutsideHandler: (cb: () => void) => {
  308. if (this.clickOutsideHandler) {
  309. this.adapter.unregisterClickOutsideHandler();
  310. }
  311. this.clickOutsideHandler = (e: React.MouseEvent): any => {
  312. if (!this.mounted) {
  313. return false;
  314. }
  315. let el = this.triggerEl && this.triggerEl.current;
  316. let popupEl = this.containerEl && this.containerEl.current;
  317. el = ReactDOM.findDOMNode(el as React.ReactInstance);
  318. popupEl = ReactDOM.findDOMNode(popupEl as React.ReactInstance) as HTMLDivElement;
  319. if (
  320. (el && !(el as any).contains(e.target) && popupEl && !(popupEl as any).contains(e.target)) ||
  321. this.props.clickTriggerToHide
  322. ) {
  323. this.props.onClickOutSide(e);
  324. cb();
  325. }
  326. };
  327. window.addEventListener('mousedown', this.clickOutsideHandler);
  328. },
  329. unregisterClickOutsideHandler: () => {
  330. if (this.clickOutsideHandler) {
  331. window.removeEventListener('mousedown', this.clickOutsideHandler);
  332. this.clickOutsideHandler = null;
  333. }
  334. },
  335. registerResizeHandler: (cb: (e: any) => void) => {
  336. if (this.resizeHandler) {
  337. this.adapter.unregisterResizeHandler();
  338. }
  339. this.resizeHandler = throttle((e): any => {
  340. if (!this.mounted) {
  341. return false;
  342. }
  343. cb(e);
  344. }, 10);
  345. window.addEventListener('resize', this.resizeHandler, false);
  346. },
  347. unregisterResizeHandler: () => {
  348. if (this.resizeHandler) {
  349. window.removeEventListener('resize', this.resizeHandler, false);
  350. this.resizeHandler = null;
  351. }
  352. },
  353. notifyVisibleChange: (visible: boolean) => {
  354. this.props.onVisibleChange(visible);
  355. },
  356. registerScrollHandler: (rePositionCb: (arg: { x: number; y: number }) => void) => {
  357. if (this.scrollHandler) {
  358. this.adapter.unregisterScrollHandler();
  359. }
  360. this.scrollHandler = throttle((e): any => {
  361. if (!this.mounted) {
  362. return false;
  363. }
  364. const triggerDOM = this.adapter.getTriggerNode();
  365. const isRelativeScroll = e.target.contains(triggerDOM);
  366. if (isRelativeScroll) {
  367. const scrollPos = { x: e.target.scrollLeft, y: e.target.scrollTop };
  368. rePositionCb(scrollPos);
  369. }
  370. }, 10); // When it is greater than 16ms, it will be very obvious
  371. window.addEventListener('scroll', this.scrollHandler, true);
  372. },
  373. unregisterScrollHandler: () => {
  374. if (this.scrollHandler) {
  375. window.removeEventListener('scroll', this.scrollHandler, true);
  376. this.scrollHandler = null;
  377. }
  378. },
  379. canMotion: () => Boolean(this.props.motion),
  380. updateContainerPosition: () => {
  381. const container = this.getPopupContainer();
  382. if (container && isHTMLElement(container)) {
  383. // getComputedStyle need first parameter is Element type
  384. const computedStyle = window.getComputedStyle(container);
  385. const position = computedStyle.getPropertyValue('position');
  386. this.containerPosition = position;
  387. }
  388. },
  389. getContainerPosition: () => this.containerPosition,
  390. getContainer: () => this.containerEl && this.containerEl.current,
  391. getTriggerNode: () => {
  392. let triggerDOM = this.triggerEl.current;
  393. if (!isHTMLElement(this.triggerEl.current)) {
  394. triggerDOM = ReactDOM.findDOMNode(this.triggerEl.current as React.ReactInstance);
  395. }
  396. return triggerDOM as Element;
  397. },
  398. getFocusableElements: (node: HTMLDivElement) => {
  399. return getFocusableElements(node);
  400. },
  401. getActiveElement: () => {
  402. return getActiveElement();
  403. },
  404. setInitialFocus: () => {
  405. const focusRefNode = get(this, 'initialFocusRef.current');
  406. if (focusRefNode && 'focus' in focusRefNode) {
  407. focusRefNode.focus();
  408. }
  409. },
  410. notifyEscKeydown: (event: React.KeyboardEvent) => {
  411. this.props.onEscKeyDown(event);
  412. },
  413. setId: () => {
  414. this.setState({ id: getUuidShort() });
  415. }
  416. };
  417. }
  418. componentDidMount() {
  419. this.mounted = true;
  420. this.getPopupContainer = this.props.getPopupContainer || this.context.getPopupContainer || defaultGetContainer;
  421. this.foundation.init();
  422. }
  423. componentWillUnmount() {
  424. this.mounted = false;
  425. this.foundation.destroy();
  426. }
  427. isSpecial = (elem: React.ReactNode | HTMLElement | any) => {
  428. if (isHTMLElement(elem)) {
  429. return Boolean(elem.disabled);
  430. } else if (isValidElement(elem)) {
  431. const disabled = get(elem, 'props.disabled');
  432. if (disabled) {
  433. return strings.STATUS_DISABLED;
  434. }
  435. const loading = get(elem, 'props.loading');
  436. /* Only judge the loading state of the Button, and no longer judge other components */
  437. const isButton = !isEmpty(elem)
  438. && !isEmpty(elem.type)
  439. && (elem.type as any).name === 'Button'
  440. || (elem.type as any).name === 'IconButton';
  441. if (loading && isButton) {
  442. return strings.STATUS_LOADING;
  443. }
  444. }
  445. return false;
  446. };
  447. // willEnter = () => {
  448. // this.foundation.calcPosition();
  449. // this.setState({ visible: true });
  450. // };
  451. didLeave = () => {
  452. this.adapter.unregisterClickOutsideHandler();
  453. this.adapter.unregisterScrollHandler();
  454. this.adapter.unregisterResizeHandler();
  455. this.adapter.removePortal();
  456. };
  457. /** for transition - end */
  458. rePosition() {
  459. return this.foundation.calcPosition();
  460. }
  461. componentDidUpdate(prevProps: TooltipProps, prevState: TooltipState) {
  462. warning(
  463. this.props.mouseLeaveDelay < this.props.mouseEnterDelay,
  464. "[Semi Tooltip] 'mouseLeaveDelay' cannot be less than 'mouseEnterDelay', which may cause the dropdown layer to not be hidden."
  465. );
  466. if (prevProps.visible !== this.props.visible) {
  467. this.props.visible ? this.foundation.delayShow() : this.foundation.delayHide();
  468. }
  469. if (prevProps.rePosKey !== this.props.rePosKey) {
  470. this.rePosition();
  471. }
  472. }
  473. renderIcon = () => {
  474. const { placement } = this.state;
  475. const { showArrow, prefixCls, style } = this.props;
  476. let icon = null;
  477. const triangleCls = classNames([`${prefixCls}-icon-arrow`]);
  478. const bgColor = get(style, 'backgroundColor');
  479. const iconComponent = placement.includes('left') || placement.includes('right') ?
  480. <TriangleArrowVertical /> :
  481. <TriangleArrow />;
  482. if (showArrow) {
  483. if (isValidElement(showArrow)) {
  484. icon = showArrow;
  485. } else {
  486. icon = React.cloneElement(iconComponent, { className: triangleCls, style: { color: bgColor, fill: 'currentColor' } });
  487. }
  488. }
  489. return icon;
  490. };
  491. handlePortalInnerClick = (e: React.MouseEvent) => {
  492. if (this.props.clickToHide) {
  493. this.foundation.hide();
  494. }
  495. if (this.props.stopPropagation) {
  496. stopPropagation(e);
  497. }
  498. };
  499. handlePortalMouseDown = (e: React.MouseEvent) => {
  500. if (this.props.stopPropagation) {
  501. stopPropagation(e);
  502. }
  503. }
  504. handlePortalInnerKeyDown = (e: React.KeyboardEvent) => {
  505. this.foundation.handleContainerKeydown(e);
  506. }
  507. renderContentNode = (content: TooltipProps['content']) => {
  508. const contentProps = {
  509. initialFocusRef: this.initialFocusRef
  510. };
  511. return !isFunction(content) ? content : content(contentProps);
  512. };
  513. renderPortal = () => {
  514. const { containerStyle = {}, visible, portalEventSet, placement, transitionState, id, isPositionUpdated } = this.state;
  515. const { prefixCls, content, showArrow, style, motion, role, zIndex } = this.props;
  516. const contentNode = this.renderContentNode(content);
  517. const { className: propClassName } = this.props;
  518. const direction = this.context.direction;
  519. const className = classNames(propClassName, {
  520. [`${prefixCls}-wrapper`]: true,
  521. [`${prefixCls}-wrapper-show`]: visible,
  522. [`${prefixCls}-with-arrow`]: Boolean(showArrow),
  523. [`${prefixCls}-rtl`]: direction === 'rtl',
  524. });
  525. const icon = this.renderIcon();
  526. const portalInnerStyle = omit(containerStyle, motion ? ['transformOrigin'] : undefined);
  527. const transformOrigin = get(containerStyle, 'transformOrigin');
  528. const inner = motion && isPositionUpdated ? (
  529. <TooltipTransition position={placement} didLeave={this.didLeave} motion={motion}>
  530. {
  531. transitionState === 'enter' ?
  532. ({ animateCls, animateStyle, animateEvents }) => (
  533. <div
  534. className={classNames(className, animateCls)}
  535. style={{
  536. visibility: 'visible',
  537. ...animateStyle,
  538. transformOrigin,
  539. ...style,
  540. }}
  541. {...portalEventSet}
  542. {...animateEvents}
  543. role={role}
  544. x-placement={placement}
  545. id={id}
  546. >
  547. {contentNode}
  548. {icon}
  549. </div>
  550. ) :
  551. null
  552. }
  553. </TooltipTransition>
  554. ) : (
  555. <div className={className} {...portalEventSet} x-placement={placement} style={{ visibility: motion ? 'hidden' : 'visible', ...style }}>
  556. {contentNode}
  557. {icon}
  558. </div>
  559. );
  560. return (
  561. <Portal getPopupContainer={this.props.getPopupContainer} style={{ zIndex }}>
  562. {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
  563. <div
  564. className={`${BASE_CLASS_PREFIX}-portal-inner`}
  565. style={portalInnerStyle}
  566. ref={this.setContainerEl}
  567. onClick={this.handlePortalInnerClick}
  568. onMouseDown={this.handlePortalMouseDown}
  569. onKeyDown={this.handlePortalInnerKeyDown}
  570. >
  571. {inner}
  572. </div>
  573. </Portal>
  574. );
  575. };
  576. wrapSpan = (elem: React.ReactNode | React.ReactElement) => {
  577. const { wrapperClassName } = this.props;
  578. const display = get(elem, 'props.style.display');
  579. const block = get(elem, 'props.block');
  580. const style: React.CSSProperties = {
  581. display: 'inline-block',
  582. };
  583. if (block || blockDisplays.includes(display)) {
  584. style.width = '100%';
  585. }
  586. return <span className={wrapperClassName} style={style}>{elem}</span>;
  587. };
  588. mergeEvents = (rawEvents: Record<string, any>, events: Record<string, any>) => {
  589. const mergedEvents = {};
  590. each(events, (handler: any, key) => {
  591. if (typeof handler === 'function') {
  592. mergedEvents[key] = (...args: any[]) => {
  593. handler(...args);
  594. if (rawEvents && typeof rawEvents[key] === 'function') {
  595. rawEvents[key](...args);
  596. }
  597. };
  598. }
  599. });
  600. return mergedEvents;
  601. };
  602. render() {
  603. const { isInsert, triggerEventSet, visible, id } = this.state;
  604. const { wrapWhenSpecial, role, trigger } = this.props;
  605. let { children } = this.props;
  606. const childrenStyle = { ...get(children, 'props.style') };
  607. const extraStyle: React.CSSProperties = {};
  608. if (wrapWhenSpecial) {
  609. const isSpecial = this.isSpecial(children);
  610. if (isSpecial) {
  611. childrenStyle.pointerEvents = 'none';
  612. if (isSpecial === strings.STATUS_DISABLED) {
  613. extraStyle.cursor = 'not-allowed';
  614. }
  615. children = cloneElement(children as React.ReactElement, { style: childrenStyle });
  616. children = this.wrapSpan(children);
  617. this.isWrapped = true;
  618. } else if (!isValidElement(children)) {
  619. children = this.wrapSpan(children);
  620. this.isWrapped = true;
  621. }
  622. }
  623. // eslint-disable-next-line prefer-const
  624. let ariaAttribute = {};
  625. // Take effect when used by Popover component
  626. if (role === 'dialog') {
  627. ariaAttribute['aria-expanded'] = visible ? 'true' : 'false';
  628. ariaAttribute['aria-haspopup'] = 'dialog';
  629. ariaAttribute['aria-controls'] = id;
  630. } else {
  631. ariaAttribute['aria-describedby'] = id;
  632. }
  633. // The incoming children is a single valid element, otherwise wrap a layer with span
  634. const newChild = React.cloneElement(children as React.ReactElement, {
  635. ...ariaAttribute,
  636. ...(children as React.ReactElement).props,
  637. ...this.mergeEvents((children as React.ReactElement).props, triggerEventSet),
  638. style: {
  639. ...get(children, 'props.style'),
  640. ...extraStyle,
  641. },
  642. className: classNames(
  643. get(children, 'props.className')
  644. ),
  645. // to maintain refs with callback
  646. ref: (node: React.ReactNode) => {
  647. // Keep your own reference
  648. (this.triggerEl as any).current = node;
  649. // Call the original ref, if any
  650. const { ref } = children as any;
  651. // this.log('tooltip render() - get ref', ref);
  652. if (typeof ref === 'function') {
  653. ref(node);
  654. } else if (ref && typeof ref === 'object') {
  655. ref.current = node;
  656. }
  657. },
  658. tabIndex: trigger === 'hover' ? 0 : undefined, // a11y keyboard
  659. });
  660. // If you do not add a layer of div, in order to bind the events and className in the tooltip, you need to cloneElement children, but this time it may overwrite the children's original ref reference
  661. // So if the user adds ref to the content, you need to use callback ref: https://github.com/facebook/react/issues/8873
  662. return (
  663. <React.Fragment>
  664. {isInsert ? this.renderPortal() : null}
  665. {newChild}
  666. </React.Fragment>
  667. );
  668. }
  669. }
  670. export { Position };