foundation.ts 37 KB

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