index.tsx 28 KB

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