All files / lib/internal/tooltip tooltip.component.ts

95.33% Statements 592/621
91.42% Branches 96/105
90.32% Functions 28/31
95.33% Lines 592/621

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 6221x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4929x 4929x 1x 1x 4929x 4929x 4929x 863x 4066x 4066x 4929x 4929x 13x 13x 13x 13x 4929x 4929x 4929x 1x 1x 4318x 4318x 4318x 4318x 1x 1x 22x 22x 1x 1x 1x 1x 1x 4628x 4628x 4628x 2180x 2448x 4628x 4628x 4628x 4628x 4628x 4628x 4628x 1x 1x 18249x 18249x 1x 1x 1x 1x 1x 4929x 4929x 1x 1x 957x 957x 957x 957x 957x 957x 957x 957x 957x 640x 640x 640x 640x 640x 640x 640x 640x 640x 640x 640x 640x 640x 640x 640x 640x 640x 640x 640x 957x 957x 957x 957x 957x 317x 957x 957x 957x 957x 197x 957x 957x 957x 317x 957x 957x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4604x 4604x 4604x 4604x 4604x 4604x 4604x 1x 1x 1x 1x 1x 1116x 129x 129x 1116x 1116x 22x 22x 1116x 1116x 1116x 1116x 1116x 1116x 1x 1x 1x 1x 1x 4604x 4604x 4604x 4604x 1x 1x 1x 1x 1x 1058x 1058x 1x 1x 1x 4x 4x 4x 4x 4x 1x 1x 1x 317x 317x 317x 317x 317x 317x 163x 163x 317x 317x 317x 317x 317x 317x 317x 317x 317x 317x 317x 317x 317x 317x 317x 317x 317x 1x 1x 1x 317x 29x 317x 317x 317x 317x 317x 317x 46x 46x 317x 317x 1x 1x 1x 7744x 7744x 7744x 1x 1x 1x 2073x 2073x 2073x 2073x 632x 2073x 2073x 1x 1x 1x 144x 144x 144x 144x 138x 141x 141x 141x 141x 141x 144x 1x 1x 1x       1x 1x 1x 72x 72x 72x 72x 70x 66x 66x 66x 66x 66x 66x 66x 72x 72x 1x 1x 1x           1x 1x 1x 335x 335x 335x 1x 1x 1x 234x 234x 234x 1x 1x 1x 117x   117x 117x 117x 1x 1x 1x       1x 1x 1x 897x 897x 893x 893x 681x 897x 1x 1x 1x 8606x 6248x 6248x 6248x 21x     6248x 6248x 6248x 1x     6248x 6248x 6248x 1076x 6248x 6248x 8606x 1x 1x 1x 741x 741x 741x 741x 741x 741x 741x 741x 741x 741x 741x 741x 741x 741x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 120x 120x 120x 120x 120x 120x 120x 731x 731x 731x 731x 731x 731x 731x                 10x 10x 10x 10x 10x 10x 10x 10x       10x 10x 741x 741x 741x 741x 741x 1x 1x 1x 741x 741x 741x 741x 741x 10x 731x 731x 741x 741x 741x 741x 741x 741x 741x 741x 741x 741x   741x 741x   741x 741x 1x 1x 1x 6628x 6628x 6628x 6628x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 4288x 57x 31x 4288x 4288x 4288x 4288x 4288x 6628x 1x  
import {
  AfterViewInit,
  Component,
  ElementRef,
  Input,
  NgZone,
  OnDestroy,
  Optional,
  ViewChild,
} from '@angular/core';
 
import {
  computePureTextLength,
  observeElementOutsideAngular,
  simpleMD,
  subscribe,
  subscribeDocument,
  subscribeWindow,
  textToLine,
} from '../../utils/internal-utils';
import { Callback } from '../../utils/util.types';
 
import { ElementInsertionContextService } from '../element-insertion-context.service';
 
let UNIQUE_ID = 1;
 
let CURRENT_TOOLTIP: TooltipComponent | undefined;
 
export type ConnectType = 'aria-describedby' | 'aria-labelledby' | 'none';
 
const ARIA_DESCRIBEDBY = 'aria-describedby';
const ARIA_LABELLEDBY = 'aria-labelledby';
 
@Component({
  selector: 'gc-tooltip',
  templateUrl: './tooltip.component.html',
  styleUrls: ['./tooltip.component.css'],
})
export class TooltipComponent implements OnDestroy, AfterViewInit {
  @Input()
  public offset = 0;
 
  @Input()
  public orientation: 'vertical' | 'horizontal' = 'vertical';
 
  /** @ignore */
  @ViewChild('tooltip')
  public tooltipNode?: ElementRef<HTMLDivElement>;
 
  /**
   * Optional callback to permit showing of the tooltip.
   * By default the tooltip is always permitted to be visible.
   */
  @Input()
  public permitTooltip?: () => boolean;
 
  /**
   * Text displayed as the tooltip
   */
  get text(): string {
    return this._text;
  }
 
  @Input()
  set text(text: string) {
    this._text = text;
    if (computePureTextLength(this.text) > 32) {
      this._tooltipText = simpleMD(textToLine(text, 32, '<br>'));
    } else {
      this._tooltipText = simpleMD(text);
    }
    if (this.visible) {
      this.zone.runOutsideAngular(() => {
        setTimeout(() => {
          this.updatePosition();
        });
      });
    }
  }
 
  @Input()
  set connectAs(value: ConnectType) {
    this._connectAs = value;
    this.updateConnection();
  }
 
  get connectAs(): ConnectType {
    return this._connectAs;
  }
 
  /**
   * Set the owner of the tooltip
   */
  @Input()
  set tooltipOwner(value: ElementRef<HTMLElement> | HTMLElement | undefined) {
    this._tooltipOwner =
      value === undefined || 'nativeElement' in value
        ? value
        : new ElementRef(value);
 
    this.zone.runOutsideAngular(() => {
      if (this.tooltipNode) {
        this.initTooltipOwner();
      }
    });
  }
 
  get tooltipOwner(): ElementRef | undefined {
    return this._tooltipOwner;
  }
 
  /**
   * @ignore
   */
  get visible(): boolean {
    return this._visible;
  }
 
  set visible(value: boolean) {
    NgZone.assertNotInAngularZone();
 
    if (this.tooltipNode === undefined) {
      return;
    }
    this.deattachWhilstVisibleHandlers();
    const tooltipNode = this.tooltipNode.nativeElement;
 
    if (value) {
      this.whilstVisibleSubscriptions.push(
        subscribeDocument('keydown', this.onKeyDown.bind(this), true),
        subscribeWindow('resize', this.updatePosition.bind(this), true),
      );
 
      if (this._tooltipOwner) {
        this.tooltipOwnerResizeObserver = new ResizeObserver(
          this.updatePosition.bind(this),
        );
        this.tooltipOwnerResizeObserver.observe(
          this._tooltipOwner.nativeElement,
        );
      }
 
      // delay until next tick because if we scrolled the focus element
      // into view we'd hide it
      setTimeout(() => {
        this.whilstVisibleSubscriptions.push(
          subscribeDocument('scroll', this.onscroll.bind(this), true),
        );
      });
    }
 
    if (!this._visible && value) {
      this.handleShowTooltip(tooltipNode);
    }
 
    this._visible = value;
    if (CURRENT_TOOLTIP === this && !value) {
      CURRENT_TOOLTIP = undefined;
    }
 
    if (!value) {
      this.handleHideTooltip(tooltipNode);
    }
  }
 
  /**
   * @ignore
   */
  protected readonly _tooltipId = 'gc-tooltip' + (UNIQUE_ID++).toString();
 
  /**
   * @ignore
   */
  protected readonly _tooltipContentId = this._tooltipId + '-content';
 
  /**
   * @ignore
   */
  protected _tooltipText = '';
 
  /**
   * @ignore
   */
  private _visible = false;
 
  /**
   * @ignore
   */
  private _flipped = false;
 
  /**
   * @ignore
   */
  private _top = 0;
 
  /**
   * @ignore
   */
  private _left = 0;
 
  /**
   * @ignore
   */
  private _shiftX = 0;
 
  /** @ignore */
  private _hoverOwner = false;
 
  /** @ignore */
  private _hoverTooltip = false;
 
  /** @ignore */
  private _focused = false;
 
  /** @ignore */
  private _escClosed = false;
 
  /** @ignore */
  private _text = '';
 
  /** @ignore */
  private parentSubscriptions: Callback[] = [];
 
  /** @ignore */
  private whilstVisibleSubscriptions: Callback[] = [];
 
  /** @ignore */
  private _suppress = false;
 
  /** @ignore */
  private _tooltipTimer?: ReturnType<typeof setTimeout>;
 
  /**
   * @ignore
   */
  private _tooltipOwner: ElementRef<HTMLElement> | undefined;
 
  /** @ignore */
  private _connectAs: ConnectType = ARIA_DESCRIBEDBY;
 
  /** @ignore */
  private tooltipOwnerResizeObserver?: ResizeObserver;
 
  private parentElement: HTMLElement;
 
  constructor(
    private elementRef: ElementRef<HTMLElement>,
    private zone: NgZone,
    @Optional() eic: ElementInsertionContextService | null,
  ) {
    this.parentElement = eic?.parent ?? document.body;
    this.parentElement.appendChild(elementRef.nativeElement);
  }
 
  /**
   * @ignore
   */
  ngOnDestroy(): void {
    if (this._tooltipOwner?.nativeElement && this._connectAs !== 'none') {
      const el = this._tooltipOwner.nativeElement;
      el.removeAttribute(this._connectAs);
    }
    if (this._tooltipTimer) {
      clearTimeout(this._tooltipTimer);
      this._tooltipTimer = undefined;
    }
 
    this.parentElement.removeChild(this.elementRef.nativeElement);
    this.deattachWhilstVisibleHandlers();
    this.deattachParentHandlers();
  }
 
  /**
   * @ignore
   */
  ngAfterViewInit(): void {
    this.zone.runOutsideAngular(() => {
      this.initTooltipOwner();
    });
  }
 
  /**
   * @ignore
   */
  _leftVal(): string {
    return Math.ceil(this._left).toFixed(0) + 'px';
  }
 
  /** @ignore */
  hide(): void {
    this._suppress = true;
    this.zone.runOutsideAngular(() => {
      this.updateVisibility();
    });
  }
 
  /** @ignore */
  private handleHideTooltip(tooltipNode: HTMLDivElement) {
    // Reset states to make sure we always start with a clean one
    this._hoverOwner = false;
    this._focused = false;
    this._hoverTooltip = false;
    this._escClosed = false;
    if (this._tooltipTimer) {
      clearTimeout(this._tooltipTimer);
      this._tooltipTimer = undefined;
    }
 
    tooltipNode.classList.remove('gc-visible');
 
    // Reposition to 0/0 because if a resize happens in between we are
    // we might get shrinked and multiple lines height hence our bounds
    // are not valid anymore
    this._left = 0;
    this._top = 0;
    this._shiftX = 0;
    tooltipNode.setAttribute(
      'style',
      `left: ${this._leftVal()}; top: ${this._top.toFixed(0)}px; --gc-arrow-shift: ${this._shiftX.toFixed(
        0,
      )}px`,
    );
  }
 
  /** @ignore */
  private handleShowTooltip(tooltipNode: HTMLDivElement) {
    if (CURRENT_TOOLTIP !== undefined && CURRENT_TOOLTIP !== this) {
      CURRENT_TOOLTIP.visible = false;
    }
    // TODO check and rework this to potentially work without the `this` assignment (e.g. store a callback instead)
    // eslint-disable-next-line @typescript-eslint/no-this-alias
    CURRENT_TOOLTIP = this;
    this.updatePosition();
    this._tooltipTimer = setTimeout(() => {
      this._tooltipTimer = undefined;
      tooltipNode.classList.add('gc-visible');
    }, 2000);
  }
 
  /** @ignore */
  private deattachParentHandlers() {
    this.parentSubscriptions.forEach(s => s());
    this.parentSubscriptions = [];
  }
 
  /** @ignore */
  private deattachWhilstVisibleHandlers() {
    this.whilstVisibleSubscriptions.forEach(cleanup => cleanup());
    this.whilstVisibleSubscriptions = [];
 
    if (this.tooltipOwnerResizeObserver) {
      this.tooltipOwnerResizeObserver.disconnect();
    }
  }
 
  /** @ignore */
  private onOwnerMouseEnter() {
    // Firefox delivers a mouse enter/leave on disabled buttons
    if (
      this._tooltipOwner &&
      this._tooltipOwner.nativeElement instanceof HTMLButtonElement &&
      this._tooltipOwner.nativeElement.disabled
    ) {
      return;
    }
    this._hoverOwner = true;
    this.updateVisibility();
  }
 
  /** @ignore */
  private onTooltipMouseEnter() {
    this._hoverTooltip = true;
    this.updateVisibility();
  }
 
  /** @ignore */
  private onOwnerMouseLeave() {
    // Firefox delivers a mouse enter/leave on disabled buttons
    if (
      this._tooltipOwner &&
      this._tooltipOwner.nativeElement instanceof HTMLButtonElement &&
      this._tooltipOwner.nativeElement.disabled
    ) {
      return;
    }
 
    this._hoverOwner = false;
    setTimeout(() => {
      this.updateVisibility();
    });
  }
 
  /** @ignore */
  private onTooltipMouseLeave() {
    this._hoverTooltip = false;
    setTimeout(() => {
      this.updateVisibility();
    });
  }
 
  /** @ignore */
  private onFocus() {
    this._focused = true;
    this.updateVisibility();
  }
 
  /** @ignore */
  private onBlur() {
    this._focused = false;
    this.updateVisibility();
  }
 
  /** @ignore */
  private onKeyDown(evt: KeyboardEvent) {
    if (evt.key === 'Escape' || evt.key == 'Esc') {
      this._escClosed = true;
    }
    this.updateVisibility();
  }
 
  /** @ignore */
  private onscroll() {
    this._escClosed = true;
    this.updateVisibility();
  }
 
  /** @ignore */
  private updateVisibility() {
    this.visible =
      !this._suppress &&
      !this._escClosed &&
      (this._hoverOwner || this._hoverTooltip || this._focused) &&
      (this.permitTooltip === undefined || this.permitTooltip());
  }
 
  /** @ignore */
  private updateConnection() {
    if (this._tooltipOwner?.nativeElement) {
      const el = this._tooltipOwner.nativeElement;
      if (
        el.getAttribute(ARIA_DESCRIBEDBY) === this._tooltipContentId &&
        this.connectAs !== ARIA_DESCRIBEDBY
      ) {
        el.removeAttribute(ARIA_DESCRIBEDBY);
      }
      if (
        el.getAttribute(ARIA_LABELLEDBY) === this._tooltipContentId &&
        this.connectAs !== ARIA_LABELLEDBY
      ) {
        el.removeAttribute(ARIA_LABELLEDBY);
      }
 
      if (this._connectAs !== 'none') {
        el.setAttribute(this._connectAs, this._tooltipContentId);
      }
    }
  }
 
  /** @ignore */
  private updatePosition() {
    NgZone.assertNotInAngularZone();
 
    const ankerNode = this._tooltipOwner?.nativeElement;
    const tooltipNode = this.tooltipNode?.nativeElement;
 
    if (ankerNode === undefined || !tooltipNode) {
      return;
    }
 
    const offset = this.offset + 7;
    let paddingTop = offset;
    let paddingBottom = 0;
 
    const pageInset = 8;
    const ankerBounds = ankerNode.getBoundingClientRect();
    const tooltipBounds = tooltipNode.getBoundingClientRect();
    if (this.orientation === 'vertical') {
      this._top = ankerBounds.top + ankerBounds.height;
      this._left =
        ankerBounds.left + ankerBounds.width / 2 - tooltipBounds.width / 2;
      this._shiftX = 0;
 
      if (this._left < pageInset) {
        this._shiftX = -(pageInset - this._left);
        this._left = pageInset;
      } else if (
        this._left + tooltipBounds.width + pageInset >=
        document.documentElement.clientWidth
      ) {
        this._shiftX =
          this._left +
          tooltipBounds.width +
          pageInset -
          document.documentElement.clientWidth;
        this._left -= this._shiftX;
      }
 
      this._flipped = false;
      if (
        document.documentElement.clientHeight <
        this._top + tooltipBounds.height + offset + 1
      ) {
        const top = ankerBounds.top - tooltipBounds.height + offset;
        if (top >= 0) {
          this._top = top - offset;
          this._flipped = true;
          paddingTop = 0;
          paddingBottom = offset;
        }
      }
    } else {
      this._top =
        ankerBounds.bottom - tooltipBounds.height / 2 - ankerBounds.height / 2;
      this._left = ankerBounds.right + (offset - 1);
 
      if (
        ankerBounds.right + tooltipBounds.width + 7 >
        document.documentElement.clientWidth
      ) {
        this._left = ankerBounds.left - tooltipBounds.width - (offset + 1);
        this._flipped = true;
      } else {
        this._flipped = false;
      }
    }
 
    this.updateTooltipCssProperties(tooltipNode, paddingBottom, paddingTop);
  }
 
  /** @ignore */
  private updateTooltipCssProperties(
    tooltipNode: HTMLElement,
    paddingBottom: number,
    paddingTop: number,
  ): void {
    if (this.orientation === 'horizontal') {
      tooltipNode.classList.remove('gc-tooltip-vertical');
    } else {
      tooltipNode.classList.remove('gc-tooltip-horizontal');
    }
 
    tooltipNode.setAttribute(
      'style',
      `--gc-tooltip-top-shift: ${paddingTop.toFixed(0)}px; --gc-tooltip-bottom-shift: ${paddingBottom.toFixed(0)}px; left: ${this._leftVal()}; top: ${this._top.toFixed(
        0,
      )}px; --gc-arrow-shift: ${this._shiftX.toFixed(0)}px`,
    );
    tooltipNode.classList.add('gc-tooltip-' + this.orientation);
    this._flipped && this.orientation === 'vertical'
      ? tooltipNode.classList.add('gc-bottom')
      : tooltipNode.classList.remove('gc-bottom');
    this._flipped && this.orientation === 'horizontal'
      ? tooltipNode.classList.add('gc-left')
      : tooltipNode.classList.remove('gc-left');
  }
 
  /** @ignore */
  private initTooltipOwner() {
    NgZone.assertNotInAngularZone();
    this.deattachParentHandlers();
 
    if (this._tooltipOwner && this.tooltipNode) {
      const ownerElement = this._tooltipOwner.nativeElement;
      const tooltipElement = this.tooltipNode.nativeElement;
      this.updateConnection();
      this.parentSubscriptions.push(
        subscribe(
          ownerElement,
          'mouseenter',
          this.onOwnerMouseEnter.bind(this),
        ),
      );
      this.parentSubscriptions.push(
        subscribe(
          ownerElement,
          'mouseleave',
          this.onOwnerMouseLeave.bind(this),
        ),
      );
 
      this.parentSubscriptions.push(
        subscribe(ownerElement, 'focus', this.onFocus.bind(this)),
      );
      this.parentSubscriptions.push(
        subscribe(ownerElement, 'blur', this.onBlur.bind(this)),
      );
 
      this.parentSubscriptions.push(
        subscribe(
          tooltipElement,
          'mouseenter',
          this.onTooltipMouseEnter.bind(this),
        ),
      );
      this.parentSubscriptions.push(
        subscribe(
          tooltipElement,
          'mouseleave',
          this.onTooltipMouseLeave.bind(this),
        ),
      );
 
      /*
       * hide the tooltip, if the owner element gets disabled, even when no blur or mouse-left event is delivered
       */
      const targetElement = this._tooltipOwner.nativeElement;
      this.parentSubscriptions.push(
        observeElementOutsideAngular(
          targetElement,
          { attributeFilter: ['disabled'] },
          this.zone,
          () => {
            if (targetElement.getAttribute('disabled') !== null) {
              this.visible = false;
            }
          },
        ),
      );
    }
  }
}