foundation.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. /* eslint-disable no-param-reassign */
  2. /* eslint-disable prefer-destructuring, max-lines-per-function, one-var, max-len, @typescript-eslint/restrict-plus-operands */
  3. /* argus-disable unPkgSensitiveInfo */
  4. import { get, isEmpty } from 'lodash';
  5. import { DOMRectLikeType } from '../utils/dom';
  6. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  7. import { ArrayElement } from '../utils/type';
  8. import { strings } from './constants';
  9. const REGS = {
  10. TOP: /top/i,
  11. RIGHT: /right/i,
  12. BOTTOM: /bottom/i,
  13. LEFT: /left/i,
  14. };
  15. const defaultRect = {
  16. left: 0,
  17. top: 0,
  18. height: 0,
  19. width: 0,
  20. scrollLeft: 0,
  21. scrollTop: 0,
  22. };
  23. export interface TooltipAdapter<P = Record<string, any>, S = Record<string, any>> extends DefaultAdapter<P, S> {
  24. registerPortalEvent(portalEventSet: any): void;
  25. unregisterPortalEvent(): void;
  26. registerResizeHandler(onResize: () => void): void;
  27. unregisterResizeHandler(onResize?: () => void): void;
  28. on(arg0: string, arg1: () => void): void;
  29. notifyVisibleChange(isVisible: any): void;
  30. getPopupContainerRect(): PopupContainerDOMRect;
  31. containerIsBody(): boolean;
  32. off(arg0: string): void;
  33. canMotion(): boolean;
  34. registerScrollHandler(arg: () => Record<string, any>): void;
  35. unregisterScrollHandler(): void;
  36. insertPortal(...args: any[]): void;
  37. removePortal(...args: any[]): void;
  38. getEventName(): {
  39. mouseEnter: string;
  40. mouseLeave: string;
  41. mouseOut: string;
  42. mouseOver: string;
  43. click: string;
  44. focus: string;
  45. blur: string;
  46. keydown: string;
  47. };
  48. registerTriggerEvent(...args: any[]): void;
  49. getTriggerBounding(...args: any[]): DOMRect;
  50. getWrapperBounding(...args: any[]): DOMRect;
  51. setPosition(...args: any[]): void;
  52. togglePortalVisible(...args: any[]): void;
  53. registerClickOutsideHandler(...args: any[]): void;
  54. unregisterClickOutsideHandler(...args: any[]): void;
  55. unregisterTriggerEvent(): void;
  56. containerIsRelative(): boolean;
  57. containerIsRelativeOrAbsolute(): boolean;
  58. getDocumentElementBounding(): DOMRect;
  59. updateContainerPosition(): void;
  60. updatePlacementAttr(placement: Position): void;
  61. getContainerPosition(): string;
  62. getFocusableElements(node: any): any[];
  63. getActiveElement(): any;
  64. getContainer(): any;
  65. setInitialFocus(): void;
  66. notifyEscKeydown(event: any): void;
  67. getTriggerNode(): any;
  68. }
  69. export type Position = ArrayElement<typeof strings.POSITION_SET>;
  70. export interface PopupContainerDOMRect extends DOMRectLikeType {
  71. scrollLeft?: number;
  72. scrollTop?: number;
  73. }
  74. export default class Tooltip<P = Record<string, any>, S = Record<string, any>> extends BaseFoundation<TooltipAdapter<P, S>, P, S> {
  75. _timer: ReturnType<typeof setTimeout>;
  76. _mounted: boolean;
  77. constructor(adapter: TooltipAdapter<P, S>) {
  78. super({ ...adapter });
  79. this._timer = null;
  80. }
  81. init() {
  82. this._mounted = true;
  83. this._bindEvent();
  84. this._shouldShow();
  85. this._initContainerPosition();
  86. }
  87. destroy() {
  88. this._mounted = false;
  89. this._unBindEvent();
  90. }
  91. _bindEvent() {
  92. const trigger = this.getProp('trigger'); // get trigger type
  93. const { triggerEventSet, portalEventSet } = this._generateEvent(trigger);
  94. this._bindTriggerEvent(triggerEventSet);
  95. this._bindPortalEvent(portalEventSet);
  96. this._bindResizeEvent();
  97. }
  98. _unBindEvent() {
  99. this._unBindTriggerEvent();
  100. this._unBindPortalEvent();
  101. this._unBindResizeEvent();
  102. this._unBindScrollEvent();
  103. }
  104. _bindTriggerEvent(triggerEventSet: Record<string, any>) {
  105. this._adapter.registerTriggerEvent(triggerEventSet);
  106. }
  107. _unBindTriggerEvent() {
  108. this._adapter.unregisterTriggerEvent();
  109. }
  110. _bindPortalEvent(portalEventSet: Record<string, any>) {
  111. this._adapter.registerPortalEvent(portalEventSet);
  112. }
  113. _unBindPortalEvent() {
  114. this._adapter.unregisterPortalEvent();
  115. }
  116. _bindResizeEvent() {
  117. this._adapter.registerResizeHandler(this.onResize);
  118. }
  119. _unBindResizeEvent() {
  120. this._adapter.unregisterResizeHandler(this.onResize);
  121. }
  122. _reversePos(position = '', isVertical = false) {
  123. if (isVertical) {
  124. if (REGS.TOP.test(position)) {
  125. return position.replace('top', 'bottom').replace('Top', 'Bottom');
  126. } else if (REGS.BOTTOM.test(position)) {
  127. return position.replace('bottom', 'top').replace('Bottom', 'Top');
  128. }
  129. } else if (REGS.LEFT.test(position)) {
  130. return position.replace('left', 'right').replace('Left', 'Right');
  131. } else if (REGS.RIGHT.test(position)) {
  132. return position.replace('right', 'left').replace('Right', 'Left');
  133. }
  134. return position;
  135. }
  136. clearDelayTimer() {
  137. if (this._timer) {
  138. clearTimeout(this._timer);
  139. this._timer = null;
  140. }
  141. }
  142. _generateEvent(types: ArrayElement<typeof strings.TRIGGER_SET>) {
  143. const eventNames = this._adapter.getEventName();
  144. const triggerEventSet = {
  145. // bind esc keydown on trigger for a11y
  146. [eventNames.keydown]: (event) => {
  147. this._handleTriggerKeydown(event);
  148. },
  149. };
  150. let portalEventSet = {};
  151. switch (types) {
  152. case 'focus':
  153. triggerEventSet[eventNames.focus] = () => {
  154. this.delayShow();
  155. };
  156. triggerEventSet[eventNames.blur] = () => {
  157. this.delayHide();
  158. };
  159. portalEventSet = triggerEventSet;
  160. break;
  161. case 'click':
  162. triggerEventSet[eventNames.click] = () => {
  163. // this.delayShow();
  164. this.show();
  165. };
  166. portalEventSet = {};
  167. // Click outside needs special treatment, can not be directly tied to the trigger Element, need to be bound to the document
  168. break;
  169. case 'hover':
  170. triggerEventSet[eventNames.mouseEnter] = () => {
  171. // console.log(e);
  172. this.setCache('isClickToHide', false);
  173. this.delayShow();
  174. // this.show('trigger');
  175. };
  176. triggerEventSet[eventNames.mouseLeave] = () => {
  177. // console.log(e);
  178. this.delayHide();
  179. // this.hide('trigger');
  180. };
  181. // bind focus to hover trigger for a11y
  182. triggerEventSet[eventNames.focus] = () => {
  183. this.delayShow();
  184. };
  185. triggerEventSet[eventNames.blur] = () => {
  186. this.delayHide();
  187. };
  188. portalEventSet = { ...triggerEventSet };
  189. if (this.getProp('clickToHide')) {
  190. portalEventSet[eventNames.click] = () => {
  191. this.setCache('isClickToHide', true);
  192. this.hide();
  193. };
  194. portalEventSet[eventNames.mouseEnter] = () => {
  195. if (this.getCache('isClickToHide')) {
  196. return;
  197. }
  198. this.delayShow();
  199. };
  200. }
  201. break;
  202. case 'custom':
  203. // when trigger type is 'custom', no need to bind eventHandler
  204. // show/hide completely depend on props.visible which change by user
  205. break;
  206. default:
  207. break;
  208. }
  209. return { triggerEventSet, portalEventSet };
  210. }
  211. onResize = () => {
  212. // this.log('resize');
  213. // rePosition when window resize
  214. this.calcPosition();
  215. };
  216. _shouldShow() {
  217. const visible = this.getProp('visible');
  218. if (visible) {
  219. this.show();
  220. } else {
  221. // this.hide();
  222. }
  223. }
  224. delayShow = () => {
  225. const mouseEnterDelay: number = this.getProp('mouseEnterDelay');
  226. this.clearDelayTimer();
  227. if (mouseEnterDelay > 0) {
  228. this._timer = setTimeout(() => {
  229. this.show();
  230. this.clearDelayTimer();
  231. }, mouseEnterDelay);
  232. } else {
  233. this.show();
  234. }
  235. };
  236. show = () => {
  237. const content = this.getProp('content');
  238. const trigger = this.getProp('trigger');
  239. const clickTriggerToHide = this.getProp('clickTriggerToHide');
  240. this.clearDelayTimer();
  241. /**
  242. * If you emit an event in setState callback, you need to place the event listener function before setState to execute.
  243. * This is to avoid event registration being executed later than setState callback when setState is executed in setTimeout.
  244. * internal-issues:1402#note_38969412
  245. */
  246. this._adapter.on('portalInserted', () => {
  247. this.calcPosition();
  248. });
  249. this._adapter.on('positionUpdated', () => {
  250. this._togglePortalVisible(true);
  251. });
  252. const position = this.calcPosition(null, null, null, false);
  253. this._adapter.insertPortal(content, position);
  254. if (trigger === 'custom') {
  255. // eslint-disable-next-line
  256. this._adapter.registerClickOutsideHandler(() => {});
  257. }
  258. /**
  259. * trigger类型是click时,仅当portal被插入显示后,才绑定clickOutsideHandler
  260. * 因为handler需要绑定在document上。如果在constructor阶段绑定
  261. * 当一个页面中有多个容器实例时,一次click会触发多个容器的handler
  262. *
  263. * When the trigger type is click, clickOutsideHandler is bound only after the portal is inserted and displayed
  264. * Because the handler needs to be bound to the document. If you bind during the constructor phase
  265. * When there are multiple container instances in a page, one click triggers the handler of multiple containers
  266. */
  267. if (trigger === 'click' || clickTriggerToHide) {
  268. this._adapter.registerClickOutsideHandler(this.hide);
  269. }
  270. this._bindScrollEvent();
  271. this._bindResizeEvent();
  272. };
  273. _togglePortalVisible(isVisible: boolean) {
  274. const nowVisible = this.getState('visible');
  275. if (nowVisible !== isVisible) {
  276. this._adapter.togglePortalVisible(isVisible, () => {
  277. if (isVisible) {
  278. this._adapter.setInitialFocus();
  279. }
  280. this._adapter.notifyVisibleChange(isVisible);
  281. });
  282. }
  283. }
  284. _roundPixel(pixel: number) {
  285. if (typeof pixel === 'number') {
  286. return Math.round(pixel);
  287. }
  288. return pixel;
  289. }
  290. calcTransformOrigin(position: Position, triggerRect: DOMRect, translateX: number, translateY: number) {
  291. // eslint-disable-next-line
  292. if (position && triggerRect && translateX != null && translateY != null) {
  293. if (this.getProp('transformFromCenter')) {
  294. if (['topLeft', 'bottomLeft'].includes(position)) {
  295. return `${this._roundPixel(triggerRect.width / 2)}px ${-translateY * 100}%`;
  296. }
  297. if (['topRight', 'bottomRight'].includes(position)) {
  298. return `calc(100% - ${this._roundPixel(triggerRect.width / 2)}px) ${-translateY * 100}%`;
  299. }
  300. if (['leftTop', 'rightTop'].includes(position)) {
  301. return `${-translateX * 100}% ${this._roundPixel(triggerRect.height / 2)}px`;
  302. }
  303. if (['leftBottom', 'rightBottom'].includes(position)) {
  304. return `${-translateX * 100}% calc(100% - ${this._roundPixel(triggerRect.height / 2)}px)`;
  305. }
  306. }
  307. return `${-translateX * 100}% ${-translateY * 100}%`;
  308. }
  309. return null;
  310. }
  311. calcPosStyle(triggerRect: DOMRect, wrapperRect: DOMRect, containerRect: PopupContainerDOMRect, position?: Position, spacing?: number) {
  312. triggerRect = (isEmpty(triggerRect) ? triggerRect : this._adapter.getTriggerBounding()) || { ...defaultRect as any };
  313. containerRect = (isEmpty(containerRect) ? containerRect : this._adapter.getPopupContainerRect()) || {
  314. ...defaultRect,
  315. };
  316. wrapperRect = (isEmpty(wrapperRect) ? wrapperRect : this._adapter.getWrapperBounding()) || { ...defaultRect as any };
  317. // eslint-disable-next-line
  318. position = position != null ? position : this.getProp('position');
  319. // eslint-disable-next-line
  320. const SPACING = spacing != null ? spacing : this.getProp('spacing');
  321. const { arrowPointAtCenter, showArrow, arrowBounding } = this.getProps();
  322. const pointAtCenter = showArrow && arrowPointAtCenter;
  323. const horizontalArrowWidth = get(arrowBounding, 'width', 24);
  324. const verticalArrowHeight = get(arrowBounding, 'width', 24);
  325. const arrowOffsetY = get(arrowBounding, 'offsetY', 0);
  326. const positionOffsetX = 6;
  327. const positionOffsetY = 6;
  328. // You must use left/top when rendering, using right/bottom does not render the element position correctly
  329. // Use left/top + translate to achieve tooltip positioning perfectly without knowing the size of the tooltip expansion layer
  330. let left;
  331. let top;
  332. let translateX = 0; // Container x-direction translation distance
  333. let translateY = 0; // Container y-direction translation distance
  334. const middleX = triggerRect.left + triggerRect.width / 2;
  335. const middleY = triggerRect.top + triggerRect.height / 2;
  336. const offsetXWithArrow = positionOffsetX + horizontalArrowWidth / 2;
  337. const offsetYWithArrow = positionOffsetY + verticalArrowHeight / 2;
  338. switch (position) {
  339. case 'top':
  340. left = middleX;
  341. top = triggerRect.top - SPACING;
  342. translateX = -0.5;
  343. translateY = -1;
  344. break;
  345. case 'topLeft':
  346. left = pointAtCenter ? middleX - offsetXWithArrow : triggerRect.left;
  347. top = triggerRect.top - SPACING;
  348. translateY = -1;
  349. break;
  350. case 'topRight':
  351. left = pointAtCenter ? middleX + offsetXWithArrow : triggerRect.right;
  352. top = triggerRect.top - SPACING;
  353. translateY = -1;
  354. translateX = -1;
  355. break;
  356. case 'left':
  357. left = triggerRect.left - SPACING;
  358. top = middleY;
  359. translateX = -1;
  360. translateY = -0.5;
  361. break;
  362. case 'leftTop':
  363. left = triggerRect.left - SPACING;
  364. top = pointAtCenter ? middleY - offsetYWithArrow : triggerRect.top;
  365. translateX = -1;
  366. break;
  367. case 'leftBottom':
  368. left = triggerRect.left - SPACING;
  369. top = pointAtCenter ? middleY + offsetYWithArrow : triggerRect.bottom;
  370. translateX = -1;
  371. translateY = -1;
  372. break;
  373. case 'bottom':
  374. left = middleX;
  375. top = triggerRect.top + triggerRect.height + SPACING;
  376. translateX = -0.5;
  377. break;
  378. case 'bottomLeft':
  379. left = pointAtCenter ? middleX - offsetXWithArrow : triggerRect.left;
  380. top = triggerRect.bottom + SPACING;
  381. break;
  382. case 'bottomRight':
  383. left = pointAtCenter ? middleX + offsetXWithArrow : triggerRect.right;
  384. top = triggerRect.bottom + SPACING;
  385. translateX = -1;
  386. break;
  387. case 'right':
  388. left = triggerRect.right + SPACING;
  389. top = middleY;
  390. translateY = -0.5;
  391. break;
  392. case 'rightTop':
  393. left = triggerRect.right + SPACING;
  394. top = pointAtCenter ? middleY - offsetYWithArrow : triggerRect.top;
  395. break;
  396. case 'rightBottom':
  397. left = triggerRect.right + SPACING;
  398. top = pointAtCenter ? middleY + offsetYWithArrow : triggerRect.bottom;
  399. translateY = -1;
  400. break;
  401. case 'leftTopOver':
  402. left = triggerRect.left - SPACING;
  403. top = triggerRect.top - SPACING;
  404. break;
  405. case 'rightTopOver':
  406. left = triggerRect.right + SPACING;
  407. top = triggerRect.top - SPACING;
  408. translateX = -1;
  409. break;
  410. case 'leftBottomOver':
  411. left = triggerRect.left - SPACING;
  412. top = triggerRect.bottom + SPACING;
  413. translateY = -1;
  414. break;
  415. case 'rightBottomOver':
  416. left = triggerRect.right + SPACING;
  417. top = triggerRect.bottom + SPACING;
  418. translateX = -1;
  419. translateY = -1;
  420. break;
  421. default:
  422. break;
  423. }
  424. const transformOrigin = this.calcTransformOrigin(position, triggerRect, translateX, translateY); // Transform origin
  425. const _containerIsBody = this._adapter.containerIsBody();
  426. // Calculate container positioning relative to window
  427. left = left - containerRect.left;
  428. top = top - containerRect.top;
  429. /**
  430. * container为body时,如果position不为relative或absolute,这时trigger计算出的top/left会根据html定位(initial containing block)
  431. * 此时如果body有margin,则计算出的位置相对于body会有问题 fix issue #1368
  432. *
  433. * When container is body, if position is not relative or absolute, then the top/left calculated by trigger will be positioned according to html
  434. * At this time, if the body has a margin, the calculated position will have a problem relative to the body fix issue #1368
  435. */
  436. if (_containerIsBody && !this._adapter.containerIsRelativeOrAbsolute()) {
  437. const documentEleRect = this._adapter.getDocumentElementBounding();
  438. // Represents the left of the body relative to html
  439. left += containerRect.left - documentEleRect.left;
  440. // Represents the top of the body relative to html
  441. top += containerRect.top - documentEleRect.top;
  442. }
  443. // ContainerRect.scrollLeft to solve the inner scrolling of the container
  444. left = _containerIsBody ? left : left + containerRect.scrollLeft;
  445. top = _containerIsBody ? top : top + containerRect.scrollTop;
  446. const triggerHeight = triggerRect.height;
  447. if (
  448. this.getProp('showArrow') &&
  449. !arrowPointAtCenter &&
  450. triggerHeight <= (verticalArrowHeight / 2 + arrowOffsetY) * 2
  451. ) {
  452. const offsetY = triggerHeight / 2 - (arrowOffsetY + verticalArrowHeight / 2);
  453. if ((position.includes('Top') || position.includes('Bottom')) && !position.includes('Over')) {
  454. top = position.includes('Top') ? top + offsetY : top - offsetY;
  455. }
  456. }
  457. // The left/top value here must be rounded, otherwise it will cause the small triangle to shake
  458. const style: Record<string, string | number> = {
  459. left: this._roundPixel(left),
  460. top: this._roundPixel(top),
  461. };
  462. let transform = '';
  463. // eslint-disable-next-line
  464. if (translateX != null) {
  465. transform += `translateX(${translateX * 100}%) `;
  466. Object.defineProperty(style, 'translateX', {
  467. enumerable: false,
  468. value: translateX,
  469. });
  470. }
  471. // eslint-disable-next-line
  472. if (translateY != null) {
  473. transform += `translateY(${translateY * 100}%) `;
  474. Object.defineProperty(style, 'translateY', {
  475. enumerable: false,
  476. value: translateY,
  477. });
  478. }
  479. // eslint-disable-next-line
  480. if (transformOrigin != null) {
  481. style.transformOrigin = transformOrigin;
  482. }
  483. if (transform) {
  484. style.transform = transform;
  485. }
  486. return style;
  487. }
  488. /**
  489. * 耦合的东西比较多,稍微罗列一下:
  490. *
  491. * - 根据 trigger 和 wrapper 的 boundingClient 计算当前的 left、top、transform-origin
  492. * - 根据当前的 position 和 wrapper 的 boundingClient 决定是否需要自动调整位置
  493. * - 根据当前的 position、trigger 的 boundingClient 以及 motion.handleStyle 调整当前的 style
  494. *
  495. * There are many coupling things, a little list:
  496. *
  497. * - calculate the current left, top, and transfer-origin according to the boundingClient of trigger and wrapper
  498. * - decide whether to automatically adjust the position according to the current position and the boundingClient of wrapper
  499. * - adjust the current style according to the current position, the boundingClient of trigger and motion.handle Style
  500. */
  501. calcPosition = (triggerRect?: DOMRect, wrapperRect?: DOMRect, containerRect?: PopupContainerDOMRect, shouldUpdatePos = true) => {
  502. triggerRect = (isEmpty(triggerRect) ? this._adapter.getTriggerBounding() : triggerRect) || { ...defaultRect as any };
  503. containerRect = (isEmpty(containerRect) ? this._adapter.getPopupContainerRect() : containerRect) || {
  504. ...defaultRect,
  505. };
  506. wrapperRect = (isEmpty(wrapperRect) ? this._adapter.getWrapperBounding() : wrapperRect) || { ...defaultRect as any };
  507. // console.log('containerRect: ', containerRect, 'triggerRect: ', triggerRect, 'wrapperRect: ', wrapperRect);
  508. let style = this.calcPosStyle(triggerRect, wrapperRect, containerRect);
  509. let position = this.getProp('position');
  510. if (this.getProp('autoAdjustOverflow')) {
  511. // console.log('style: ', style, '\ntriggerRect: ', triggerRect, '\nwrapperRect: ', wrapperRect);
  512. const adjustedPos = this.adjustPosIfNeed(position, style, triggerRect, wrapperRect, containerRect);
  513. if (position !== adjustedPos) {
  514. position = adjustedPos;
  515. style = this.calcPosStyle(triggerRect, wrapperRect, containerRect, position);
  516. }
  517. }
  518. if (shouldUpdatePos && this._mounted) {
  519. // this._adapter.updatePlacementAttr(style.position);
  520. this._adapter.setPosition({ ...style, position });
  521. }
  522. return style;
  523. };
  524. isLR(position = '') {
  525. return position.indexOf('left') === 0 || position.indexOf('right') === 0;
  526. }
  527. isTB(position = '') {
  528. return position.indexOf('top') === 0 || position.indexOf('bottom') === 0;
  529. }
  530. // place the dom correctly
  531. adjustPosIfNeed(position: Position | string, style: Record<string, any>, triggerRect: DOMRect, wrapperRect: DOMRect, containerRect: PopupContainerDOMRect) {
  532. const { innerWidth, innerHeight } = window;
  533. const { spacing } = this.getProps();
  534. if (wrapperRect.width > 0 && wrapperRect.height > 0) {
  535. // let clientLeft = left + translateX * wrapperRect.width - containerRect.scrollLeft;
  536. // let clientTop = top + translateY * wrapperRect.height - containerRect.scrollTop;
  537. // if (this._adapter.containerIsBody() || this._adapter.containerIsRelative()) {
  538. // clientLeft += containerRect.left;
  539. // clientTop += containerRect.top;
  540. // }
  541. // const clientRight = clientLeft + wrapperRect.width;
  542. // const clientBottom = clientTop + wrapperRect.height;
  543. // The relative position of the elements on the screen
  544. // https://lf3-static.bytednsdoc.com/obj/eden-cn/ptlz_zlp/ljhwZthlaukjlkulzlp/tooltip-pic.svg
  545. const clientLeft = triggerRect.left;
  546. const clientRight = triggerRect.right;
  547. const clientTop = triggerRect.top;
  548. const clientBottom = triggerRect.bottom;
  549. const restClientLeft = innerWidth - clientLeft;
  550. const restClientTop = innerHeight - clientTop;
  551. const restClientRight = innerWidth - clientRight;
  552. const restClientBottom = innerHeight - clientBottom;
  553. const widthIsBigger = wrapperRect.width > triggerRect.width;
  554. const heightIsBigger = wrapperRect.height > triggerRect.height;
  555. // The wrapperR ect.top|bottom equivalent cannot be directly used here for comparison, which is easy to cause jitter
  556. const shouldReverseTop = clientTop < wrapperRect.height + spacing && restClientBottom > wrapperRect.height + spacing;
  557. const shouldReverseLeft = clientLeft < wrapperRect.width + spacing && restClientRight > wrapperRect.width + spacing;
  558. const shouldReverseBottom = restClientBottom < wrapperRect.height + spacing && clientTop > wrapperRect.height + spacing;
  559. const shouldReverseRight = restClientRight < wrapperRect.width + spacing && clientLeft > wrapperRect.width + spacing;
  560. const shouldReverseTopOver = restClientTop < wrapperRect.height + spacing && clientBottom > wrapperRect.height + spacing;
  561. const shouldReverseBottomOver = clientBottom < wrapperRect.height + spacing && restClientTop > wrapperRect.height + spacing;
  562. const shouldReverseTopSide = restClientTop < wrapperRect.height && clientBottom > wrapperRect.height;
  563. const shouldReverseBottomSide = clientBottom < wrapperRect.height && restClientTop > wrapperRect.height;
  564. const shouldReverseLeftSide = restClientLeft < wrapperRect.width && clientRight > wrapperRect.width;
  565. const shouldReverseRightSide = clientRight < wrapperRect.width && restClientLeft > wrapperRect.width;
  566. const shouldReverseLeftOver = restClientLeft < wrapperRect.width && clientRight > wrapperRect.width;
  567. const shouldReverseRightOver = clientRight < wrapperRect.width && restClientLeft > wrapperRect.width;
  568. switch (position) {
  569. case 'top':
  570. if (shouldReverseTop) {
  571. position = this._reversePos(position, true);
  572. }
  573. break;
  574. case 'topLeft':
  575. if (shouldReverseTop) {
  576. position = this._reversePos(position, true);
  577. }
  578. if (shouldReverseLeftSide && widthIsBigger) {
  579. position = this._reversePos(position);
  580. }
  581. break;
  582. case 'topRight':
  583. if (shouldReverseTop) {
  584. position = this._reversePos(position, true);
  585. }
  586. if (shouldReverseRightSide && widthIsBigger) {
  587. position = this._reversePos(position);
  588. }
  589. break;
  590. case 'left':
  591. if (shouldReverseLeft) {
  592. position = this._reversePos(position);
  593. }
  594. break;
  595. case 'leftTop':
  596. if (shouldReverseLeft) {
  597. position = this._reversePos(position);
  598. }
  599. if (shouldReverseTopSide && heightIsBigger) {
  600. position = this._reversePos(position, true);
  601. }
  602. break;
  603. case 'leftBottom':
  604. if (shouldReverseLeft) {
  605. position = this._reversePos(position);
  606. }
  607. if (shouldReverseBottomSide && heightIsBigger) {
  608. position = this._reversePos(position, true);
  609. }
  610. break;
  611. case 'bottom':
  612. if (shouldReverseBottom) {
  613. position = this._reversePos(position, true);
  614. }
  615. break;
  616. case 'bottomLeft':
  617. if (shouldReverseBottom) {
  618. position = this._reversePos(position, true);
  619. }
  620. if (shouldReverseLeftSide && widthIsBigger) {
  621. position = this._reversePos(position);
  622. }
  623. break;
  624. case 'bottomRight':
  625. if (shouldReverseBottom) {
  626. position = this._reversePos(position, true);
  627. }
  628. if (shouldReverseRightSide && widthIsBigger) {
  629. position = this._reversePos(position);
  630. }
  631. break;
  632. case 'right':
  633. if (shouldReverseRight) {
  634. position = this._reversePos(position);
  635. }
  636. break;
  637. case 'rightTop':
  638. if (shouldReverseRight) {
  639. position = this._reversePos(position);
  640. }
  641. if (shouldReverseTopSide && heightIsBigger) {
  642. position = this._reversePos(position, true);
  643. }
  644. break;
  645. case 'rightBottom':
  646. if (shouldReverseRight) {
  647. position = this._reversePos(position);
  648. }
  649. if (shouldReverseBottomSide && heightIsBigger) {
  650. position = this._reversePos(position, true);
  651. }
  652. break;
  653. case 'leftTopOver':
  654. if (shouldReverseTopOver) {
  655. position = this._reversePos(position, true);
  656. }
  657. if (shouldReverseLeftOver) {
  658. position = this._reversePos(position);
  659. }
  660. break;
  661. case 'leftBottomOver':
  662. if (shouldReverseBottomOver) {
  663. position = this._reversePos(position, true);
  664. }
  665. if (shouldReverseLeftOver) {
  666. position = this._reversePos(position);
  667. }
  668. break;
  669. case 'rightTopOver':
  670. if (shouldReverseTopOver) {
  671. position = this._reversePos(position, true);
  672. }
  673. if (shouldReverseRightOver) {
  674. position = this._reversePos(position);
  675. }
  676. break;
  677. case 'rightBottomOver':
  678. if (shouldReverseBottomOver) {
  679. position = this._reversePos(position, true);
  680. }
  681. if (shouldReverseRightOver) {
  682. position = this._reversePos(position);
  683. }
  684. break;
  685. default:
  686. break;
  687. }
  688. }
  689. return position;
  690. }
  691. delayHide = () => {
  692. const mouseLeaveDelay = this.getProp('mouseLeaveDelay');
  693. this.clearDelayTimer();
  694. if (mouseLeaveDelay > 0) {
  695. this._timer = setTimeout(() => {
  696. // console.log('delayHide for ', mouseLeaveDelay, ' ms, ', ...args);
  697. this.hide();
  698. this.clearDelayTimer();
  699. }, mouseLeaveDelay);
  700. } else {
  701. this.hide();
  702. }
  703. };
  704. hide = () => {
  705. this.clearDelayTimer();
  706. this._togglePortalVisible(false);
  707. this._adapter.off('portalInserted');
  708. this._adapter.off('positionUpdated');
  709. if (!this._adapter.canMotion()) {
  710. this._adapter.removePortal();
  711. // When the portal is removed, the global click outside event binding is also removed
  712. this._adapter.unregisterClickOutsideHandler();
  713. this._unBindScrollEvent();
  714. this._unBindResizeEvent();
  715. }
  716. };
  717. _bindScrollEvent() {
  718. this._adapter.registerScrollHandler(() => this.calcPosition());
  719. // Capture scroll events on the window to determine whether the current scrolling area (e.target) will affect the positioning of the pop-up layer relative to the viewport when scrolling
  720. // (By determining whether the e.target contains the triggerDom of the current tooltip) If so, the pop-up layer will also be affected and needs to be repositioned
  721. }
  722. _unBindScrollEvent() {
  723. this._adapter.unregisterScrollHandler();
  724. }
  725. _initContainerPosition() {
  726. this._adapter.updateContainerPosition();
  727. }
  728. handleContainerKeydown = (event: any) => {
  729. const { guardFocus, closeOnEsc } = this.getProps();
  730. switch (event && event.key) {
  731. case "Escape":
  732. closeOnEsc && this._handleEscKeyDown(event);
  733. break;
  734. case "Tab":
  735. if (guardFocus) {
  736. const container = this._adapter.getContainer();
  737. const focusableElements = this._adapter.getFocusableElements(container);
  738. const focusableNum = focusableElements.length;
  739. if (focusableNum) {
  740. // Shift + Tab will move focus backward
  741. if (event.shiftKey) {
  742. this._handleContainerShiftTabKeyDown(focusableElements, event);
  743. } else {
  744. this._handleContainerTabKeyDown(focusableElements, event);
  745. }
  746. }
  747. }
  748. break;
  749. default:
  750. break;
  751. }
  752. }
  753. _handleTriggerKeydown(event: any) {
  754. const { closeOnEsc } = this.getProps();
  755. const container = this._adapter.getContainer();
  756. const focusableElements = this._adapter.getFocusableElements(container);
  757. const focusableNum = focusableElements.length;
  758. switch (event && event.key) {
  759. case "Escape":
  760. closeOnEsc && this._handleEscKeyDown(event);
  761. break;
  762. case "ArrowUp":
  763. focusableNum && this._handleTriggerArrowUpKeydown(focusableElements, event);
  764. break;
  765. case "ArrowDown":
  766. focusableNum && this._handleTriggerArrowDownKeydown(focusableElements, event);
  767. break;
  768. default:
  769. break;
  770. }
  771. }
  772. /**
  773. * focus trigger
  774. *
  775. * when trigger is 'focus' or 'hover', onFocus is bind to show popup
  776. * if we focus trigger, popup will show again
  777. *
  778. * 如果 trigger 是 focus 或者 hover,则它绑定了 onFocus,这里我们如果重新 focus 的话,popup 会再次打开
  779. * 因此 returnFocusOnClose 只支持 click trigger
  780. */
  781. _focusTrigger() {
  782. const { trigger, returnFocusOnClose } = this.getProps();
  783. if (returnFocusOnClose && trigger === 'click') {
  784. const triggerNode = this._adapter.getTriggerNode();
  785. if (triggerNode && 'focus' in triggerNode) {
  786. triggerNode.focus();
  787. }
  788. }
  789. }
  790. _handleEscKeyDown(event: any) {
  791. const { trigger } = this.getProps();
  792. if (trigger !== 'custom') {
  793. this.hide();
  794. this._focusTrigger();
  795. }
  796. this._adapter.notifyEscKeydown(event);
  797. }
  798. _handleContainerTabKeyDown(focusableElements: any[], event: any) {
  799. const activeElement = this._adapter.getActiveElement();
  800. const isLastCurrentFocus = focusableElements[focusableElements.length - 1] === activeElement;
  801. if (isLastCurrentFocus) {
  802. focusableElements[0].focus();
  803. event.preventDefault(); // prevent browser default tab move behavior
  804. }
  805. }
  806. _handleContainerShiftTabKeyDown(focusableElements: any[], event: any) {
  807. const activeElement = this._adapter.getActiveElement();
  808. const isFirstCurrentFocus = focusableElements[0] === activeElement;
  809. if (isFirstCurrentFocus) {
  810. focusableElements[focusableElements.length - 1].focus();
  811. event.preventDefault(); // prevent browser default tab move behavior
  812. }
  813. }
  814. _handleTriggerArrowDownKeydown(focusableElements: any[], event: any) {
  815. focusableElements[0].focus();
  816. event.preventDefault(); // prevent browser default scroll behavior
  817. }
  818. _handleTriggerArrowUpKeydown(focusableElements: any[], event: any) {
  819. focusableElements[focusableElements.length - 1].focus();
  820. event.preventDefault(); // prevent browser default scroll behavior
  821. }
  822. }