1
0

index.tsx 29 KB

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