index.tsx 27 KB

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