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

97.87% Statements 46/47
90% Branches 9/10
100% Functions 6/6
97.87% Lines 46/47

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 481x 1x 1x 1x 1x 1x 1x 1x 1x 1x 155x 155x 155x 1x 1x 188x 188x 188x 188x 188x 18x 188x 170x 170x 170x 170x 170x 188x 188x 188x 188x 188x 1x 1x 155x   155x 155x 155x 155x 155x 155x 1x 1x 179x 179x 1x  
import { AfterContentInit, Directive, ElementRef, NgZone } from '@angular/core';
import { take } from 'rxjs/operators';
 
import { getKeyboardFocusableElements } from '../utils/internal-utils';
 
@Directive({
  selector: '[data-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>(
      '[data-gc-initial-focus="true"]',
    );
    if (focusTarget !== null) {
      focusTarget.focus();
      return true;
    } else {
      const elements = getKeyboardFocusableElements(nativeElement);
      if (elements.length > 0) {
        const el = elements[0];
        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);
  }
}