index.tsx 31 KB

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