All files / skip-links skip-link.service.ts

100% Statements 20/20
100% Branches 5/5
100% Functions 3/3
100% Lines 19/19

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 59 60 61 62                                        1x   14x 14x 14x 14x     28x 14x     28x 28x 28x       28x   28x 14x 14x   14x 14x         14x       14x 14x            
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import {
  ApplicationRef,
  ComponentRef,
  createComponent,
  EnvironmentInjector,
  inject,
  Injectable,
  DOCUMENT
} from '@angular/core';
 
import { SiSkipLinkTargetDirective } from './si-skip-link-target.directive';
import { SiSkipLinksComponent } from './si-skip-links.component';
 
@Injectable({
  providedIn: 'root'
})
export class SkipLinkService {
  private skipLinksComponentRef?: ComponentRef<SiSkipLinksComponent>;
  private appRef = inject(ApplicationRef);
  private environmentInjector = inject(EnvironmentInjector);
  private document = inject(DOCUMENT);
  private registeredTargets: SiSkipLinkTargetDirective[] = [];
 
  registerLink(skipLink: SiSkipLinkTargetDirective): void {
    if (!this.skipLinksComponentRef) {
      this.createSkipLinksComponent();
    }
 
    this.registeredTargets.push(skipLink);
    this.skipLinksComponentRef!.setInput('skipLinks', this.registeredTargets);
    this.skipLinksComponentRef!.changeDetectorRef.markForCheck();
  }
 
  unregisterLink(skipLink: SiSkipLinkTargetDirective): void {
    this.registeredTargets.splice(this.registeredTargets.indexOf(skipLink), 1);
 
    if (this.registeredTargets.length && this.skipLinksComponentRef) {
      this.skipLinksComponentRef.setInput('skipLinks', this.registeredTargets);
      this.skipLinksComponentRef.changeDetectorRef.markForCheck();
    } else {
      this.skipLinksComponentRef?.destroy();
      this.skipLinksComponentRef = undefined;
    }
  }
 
  private createSkipLinksComponent(): void {
    this.skipLinksComponentRef = createComponent(SiSkipLinksComponent, {
      environmentInjector: this.environmentInjector
    });
 
    this.appRef.attachView(this.skipLinksComponentRef.hostView);
    this.document.body.insertBefore(
      this.skipLinksComponentRef.location.nativeElement,
      this.document.body.children.item(0)
    );
  }
}