foundation.ts 37 KB

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