All files / src/app/core/directives server-html.directive.ts

89.36% Statements 42/47
77.5% Branches 31/40
100% Functions 10/10
89.13% Lines 41/46

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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 13438x 38x                         38x   38x 38x         38x         19x     19x 19x 19x 19x       19x 19x     19x       19x           19x         19x 8x   8x           19x 3x         4x 4x 1x 1x 1x 3x 2x   1x         19x             2x   2x 2x 2x     2x       2x                       2x     2x           2x       2x 2x          
import { APP_BASE_HREF } from '@angular/common';
import {
  AfterContentInit,
  AfterViewInit,
  Directive,
  ElementRef,
  HostListener,
  Inject,
  Input,
  OnChanges,
  Renderer2,
  SimpleChanges,
  inject,
} from '@angular/core';
import { Router } from '@angular/router';
 
import { AppFacade } from 'ish-core/facades/app.facade';
import { LinkParser } from 'ish-core/utils/link-parser';
 
@Directive({
  selector: '[ishServerHtml]',
})
export class ServerHtmlDirective implements AfterContentInit, AfterViewInit, OnChanges {
  @Input() callbacks: {
    [key: string]: (event?: MouseEvent) => void;
  };
 
  private renderer = inject(Renderer2);
 
  constructor(
    private router: Router,
    private elementRef: ElementRef,
    private appFacade: AppFacade,
    @Inject(APP_BASE_HREF) private baseHref: string
  ) {}
 
  @Input() set ishServerHtml(val: string) {
    const element = this.elementRef.nativeElement;
    while (element.firstChild) {
      element.removeChild(element.firstChild);
    }
    element.insertAdjacentHTML('afterbegin', val);
  }
 
  ngOnChanges(changes: SimpleChanges): void {
    Iif (changes.ishServerHtml && !changes.ishServerHtml.firstChange) {
      this.patchElements();
    }
  }
 
  ngAfterContentInit() {
    this.patchElements();
  }
 
  private patchElements() {
    // use setAttribute here to bypass security check
    Array.from(this.elementRef.nativeElement.querySelectorAll('[href]')).forEach((element: HTMLElement) => {
      const href = element.getAttribute('href');
 
      this.renderer.setAttribute(
        element,
        'href',
        href.startsWith('/INTERSHOP/') ? this.transformMediaObjectSrc(href) : LinkParser.parseLink(href, this.baseHref)
      );
    });
    Array.from(this.elementRef.nativeElement.querySelectorAll('[src]')).forEach((element: HTMLElement) => {
      this.renderer.setAttribute(element, 'src', this.transformMediaObjectSrc(element.getAttribute('src')));
    });
  }
 
  private transformMediaObjectSrc(src: string) {
    const regex = /.*\[ismediaobject\](.*?)\[\/ismediaobject\].*/;
    if (regex.test(src)) {
      const [, ismediaobjectContent] = regex.exec(src);
      const mediaObjectSrc = ismediaobjectContent.split('|')[1];
      return this.appFacade.icmBaseUrl + mediaObjectSrc;
    } else if (src.startsWith('/INTERSHOP/')) {
      return this.appFacade.icmBaseUrl + src;
    } else {
      return src;
    }
  }
 
  ngAfterViewInit() {
    this.elementRef.nativeElement.removeAttribute('ng-reflect-ish-server-html');
  }
 
  @HostListener('click', ['$event'])
  // eslint-disable-next-line complexity
  onClick(event: MouseEvent) {
    // go along path of click but not further up than self
    for (let el = event.target as HTMLElement; el && el !== this.elementRef.nativeElement; el = el.parentElement) {
      // anchors only
      if (el.tagName === 'A') {
        const href = el.getAttribute('href');
        const cb = el.getAttribute('callback');
 
        // handle links with callback functions, e.g. <a callback="availableCallbackFunction">
        Iif (cb && this.callbacks && typeof this.callbacks[cb] === 'function') {
          this.callbacks[cb](event);
        }
 
        Iif (
          !href ||
          href.startsWith('http') ||
          href.startsWith('javascript:') ||
          el.getAttribute('target') === '_blank' ||
          el.getAttribute('target') === '_self'
        ) {
          // apply default link handling
          return;
        }
 
        const routeHref =
          this.baseHref !== '/' && href.startsWith(this.baseHref) ? href.substring(this.baseHref.length) : href;
 
        // handle fragment links / anchor navigation
        Iif (routeHref.startsWith('#')) {
          this.elementRef.nativeElement
            .querySelector(routeHref)
            ?.scrollIntoView({ block: 'start', behavior: 'smooth' });
        } else {
          // otherwise handle as routerLink
          this.router.navigateByUrl(routeHref);
        }
 
        // prevent default link handling
        event.preventDefault();
        return false;
      }
    }
  }
}