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

94.54% Statements 52/55
80% Branches 8/10
100% Functions 5/5
94.54% Lines 52/55

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 561x 1x 1x 1x 1x 1x 1x 1x 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,
  inject,
} 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 {
  /** @ignore */
  private readonly _el = inject<ElementRef<HTMLElement>>(ElementRef);
 
  /** @ignore */
  private readonly _ngZone = inject(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);
  }
}