All files / lib/internal auto-focus-area.directive.ts

97.5% Statements 39/40
88.89% Branches 8/9
100% Functions 4/4
97.5% Lines 39/40

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 411x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 111x 111x 111x 111x 111x 30x 104x 81x 81x 81x 81x 1x 1x 1x 1x 1x 1x 1x 86x   86x 86x 1x 1x 1x 1x 102x 1x 1x  
import { AfterContentInit, Directive, ElementRef, NgZone } from '@angular/core';
import { take } from 'rxjs/operators';
 
import { getKeyboardFocusableElements } from '../utils/internal-utils';
 
@Directive({
  selector: '[gc-auto-focus-area]'
})
export class AutoFocusAreaDirective implements AfterContentInit {
 
  constructor(private _el: ElementRef<HTMLElement>, private _ngZone: NgZone) {}
 
  public static focusInitialElement(nativeElement: HTMLElement): boolean {
    const focusTarget = nativeElement.querySelector<HTMLElement>('[gc-initial-focus="true"]');
    if( focusTarget !== null ) {
      focusTarget.focus();
      return true;
    } else {
      const el = getKeyboardFocusableElements(nativeElement)[0] as HTMLElement;
      if( el ) {
        el.focus();
        return true;
      } else {
        return false;
      }
    }
  }
 
  ngAfterContentInit() {
    if( this._ngZone.isStable ) {
      this.focusInitialElement();
    } else {
      this._ngZone.onStable.pipe(take(1)).subscribe(this.focusInitialElement.bind(this));
    }
  }
  
  focusInitialElement(): boolean {
    return AutoFocusAreaDirective.focusInitialElement(this._el.nativeElement);
  }
}