All files / src/app/core/directives not-role-toggle.directive.ts

100% Statements 21/21
78.94% Branches 15/19
100% Functions 4/4
100% Lines 21/21

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 587x 7x 7x 7x   7x                                   7x   132x   132x     132x 132x 132x 132x   132x 142x 123x   19x   141x           134x   2x   134x     144x      
import { ChangeDetectorRef, DestroyRef, Directive, Input, TemplateRef, ViewContainerRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ReplaySubject, Subscription } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';
 
import { RoleToggleService } from 'ish-core/utils/role-toggle/role-toggle.service';
 
/**
 * Structural directive.
 * Used on an element, this element will only be rendered if the logged in user has NOT the specified role or one of the specified roles.
 *
 * @example
 * <div *ishHasNotRole="'APP_B2B_OCI_USER'">
 *   Only visible when the current user is not an OCI punchout user.
 * </div>
 * or
 * <div *ishHasNotRole="['APP_B2B_CXML_USER', 'APP_B2B_OCI_USER']">
 *   Only visible when the current user is not an OCI punchout user.
 * </div>
 */
@Directive({
  selector: '[ishHasNotRole]',
})
export class NotRoleToggleDirective {
  private subscription: Subscription;
  private enabled$ = new ReplaySubject<boolean>(1);
 
  private destroyRef = inject(DestroyRef);
 
  constructor(
    private templateRef: TemplateRef<unknown>,
    private viewContainer: ViewContainerRef,
    private roleToggleService: RoleToggleService,
    private cdRef: ChangeDetectorRef
  ) {
    this.enabled$.pipe(distinctUntilChanged(), takeUntilDestroyed()).subscribe(enabled => {
      if (enabled) {
        this.viewContainer.createEmbeddedView(this.templateRef);
      } else {
        this.viewContainer.clear();
      }
      this.cdRef.markForCheck();
    });
  }
 
  @Input() set ishHasNotRole(roleId: string | string[]) {
    // end previous subscription and newly subscribe
    if (this.subscription) {
      // eslint-disable-next-line ban/ban
      this.subscription.unsubscribe();
    }
    this.subscription = this.roleToggleService
      .hasRole(roleId)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({ next: val => this.enabled$.next(!val) });
  }
}