All files / app/directive limit-width.directive.ts

79.31% Statements 23/29
81.25% Branches 26/32
60% Functions 6/10
76.19% Lines 16/21

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 5969x         69x   13x     13x         13x 13x                 13x 13x       12x       12x                       13x 12x 12x 12x   12x 12x            
import { AfterViewInit, Directive, ElementRef, HostListener, Input, OnDestroy } from '@angular/core';
import { throttle } from 'lodash-es';
import { ConfigService } from '../service/config.service';
 
@Directive({ selector: '[appLimitWidth]' })
export class LimitWidthDirective implements OnDestroy, AfterViewInit {
 
  resizeObserver = window.ResizeObserver && new ResizeObserver(() => this.fill()) || undefined;
 
  @Input()
  limitSibling = false;
 
  private _linked?: HTMLElement;
 
  constructor(
    private config: ConfigService,
    private el: ElementRef,
  ) { }
 
  get linked() {
    return this._linked;
  }
 
  @Input('appLimitWidth')
  set linked(value: HTMLElement | undefined | null) {
    this._linked = value!;
    if (value) this.resizeObserver?.observe(value);
  }
 
  ngAfterViewInit() {
    this.fill();
  }
 
  ngOnDestroy() {
    this.resizeObserver?.disconnect();
  }
 
  @HostListener('window:resize', ['$event'])
  onWindowResize(event: UIEvent) {
    this.fill();
  }
 
  get max() {
    return window.innerWidth;
  }
 
  private fill = throttle(() => {
    let linkedWidth = this._linked?.clientWidth || 0;
    Eif (this.limitSibling) linkedWidth += this._linked?.nextElementSibling?.clientWidth || 0;
    Iif (this.config.mobile) {
      this.el.nativeElement.style.maxWidth = '100vw';
    } else if (!linkedWidth) {
      this.el.nativeElement.style.maxWidth = '';
    } else E{
      this.el.nativeElement.style.maxWidth = Math.min(this.max, linkedWidth) + 'px';
    }
  }, 16, { leading: true, trailing: true});
}