index.tsx 31 KB

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