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

93.75% Statements 45/48
85.71% Branches 12/14
100% Functions 8/8
93.75% Lines 45/48

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 491x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 231x 231x 231x 1x 1x 257x 257x 257x 257x 257x 24x 257x 233x 233x 233x 233x 233x     257x 257x 257x 1x 1x 231x   231x 231x 231x 231x 231x 231x 1x 1x 248x 248x 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]',
  standalone: false,
})
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);
  }
}