index.tsx 31 KB

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