import {Directive, ElementRef, HostListener, Inject} from '@angular/core'; import {DOCUMENT} from '@angular/common'; @Directive({ selector: '[tooltip-interaction]' }) export class TooltipDirective { constructor( @Inject(DOCUMENT) private doc: any, private elRef: ElementRef ) {} @HostListener('focusin') @HostListener('mouseenter') onMouseEnter(): void { this.setPosition(); } setPosition(): void { const xPos = this.elRef.nativeElement.offsetLeft - this.elRef.nativeElement.scrollLeft + this.elRef.nativeElement.clientLeft; const docW = this.doc.documentElement.clientWidth; const winW = (typeof window !== 'undefined') ? window.innerWidth : 0; const docMaxW = Math.max(docW, winW || 0); const docRightW = docMaxW - xPos; const tooltipContent = this.elRef.nativeElement.querySelector('.hdca-tooltip'); const tooltipContentWidth = this.getOffSetWidth(tooltipContent); const tooltipButton = this.elRef.nativeElement.querySelector('.hdca-form-field__help-button'); const tooltipButtonW = tooltipButton.clientWidth; // reset style / classes tooltipContent.classList.remove('hdca-tooltip--is-right'); tooltipContent.classList.remove('hdca-tooltip--is-right--mobile'); tooltipContent.classList.remove('hdca-tooltip--is-centered'); tooltipContent.setAttribute('style', ''); if (xPos > tooltipContentWidth) { if ((docRightW - (tooltipContentWidth || tooltipContent.clientWidth)) < 0) { tooltipContent.classList.add('hdca-tooltip--is-right'); tooltipContent.classList.add('hdca-tooltip--is-right--mobile'); } } else if (tooltipContentWidth > (docMaxW - xPos)) { const toolTipCenteredPos = (Number(tooltipContentWidth) / 2) - (Number(tooltipButtonW) / 2); tooltipContent.setAttribute('style', 'left:-' + toolTipCenteredPos + 'px'); tooltipContent.classList.add('hdca-tooltip--is-centered'); } } getOffSetWidth(el: HTMLElement) { el.setAttribute('style', 'display:block'); const elW = el.offsetWidth; el.setAttribute('style', 'display:none'); return elW; } }