index.tsx 29 KB

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