All files / src/app/core/directives product-context-access.directive.ts

78.57% Statements 11/14
62.5% Branches 15/24
75% Functions 3/4
78.57% Lines 11/14

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 463x 3x   3x             3x 2x                 2x       2x 2x           2x 2x                   2x      
import { Directive, EmbeddedViewRef, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
 
import { ProductContext, ProductContextFacade } from 'ish-core/facades/product-context.facade';
 
type ProductContextAccessContext = ProductContext & { context: ProductContextFacade };
 
@Directive({
  selector: '[ishProductContextAccess]',
})
export class ProductContextAccessDirective {
  @Input() ishProductContextAccessAlways = false;
 
  private view: EmbeddedViewRef<ProductContextAccessContext>;
 
  constructor(
    context: ProductContextFacade,
    viewContainer: ViewContainerRef,
    template: TemplateRef<ProductContextAccessContext>
  ) {
    context
      .select()
      .pipe(takeUntilDestroyed())
      .subscribe(ctx => {
        if (!this.view && this.check(ctx)) {
          this.view = viewContainer.createEmbeddedView(template, { ...ctx, context });
        } else IEif (this.view && this.check(ctx)) {
          // eslint-disable-next-line ban/ban
          Object.assign(this.view.context, ctx);
        }
 
        if (this.view) {
          this.view.markForCheck();
        }
      });
  }
 
  static ngTemplateContextGuard(_: ProductContextAccessDirective, ctx: unknown): ctx is ProductContextAccessContext {
    return !!ctx || true;
  }
 
  private check(ctx: ProductContext): boolean {
    return this.ishProductContextAccessAlways || !!ctx?.product;
  }
}