index.tsx 26 KB

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