All files / layout aem-component.directive.ts

87.04% Statements 47/54
88% Branches 22/25
88.24% Functions 15/17
86.79% Lines 46/53

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 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213                                                              1x                           1x                       214x       1x 27x       1x           1x         1x         1x   1x     26x 26x 26x 26x       26x       27x             52x                 26x 25x   25x 25x 25x               52x 26x     26x   26x 83x   83x     38x   38x     83x     26x 26x   26x   26x 2x     26x             26x                                             2x                 2x 1x 1x   1x 1x         26x       26x      
/*
 * Copyright 2020 Adobe. All rights reserved.
 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy
 * of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
 * OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
 
import {
  Directive,
  Input,
  Renderer2,
  ViewContainerRef,
  ComponentFactoryResolver,
  ComponentRef,
  AfterViewInit,
  OnInit,
  OnDestroy, ChangeDetectorRef, OnChanges
} from '@angular/core';
 
import { ComponentMapping } from './component-mapping';
import { Constants } from './constants';
import { Utils } from './utils';
 
/**
 * @private
 */
const PLACEHOLDER_CLASS_NAME = 'cq-placeholder';
 
@Directive({
  selector: '[aemComponent]'
})
 
/**
 * The current directive provides advanced capabilities among which are
 *
 * - The management of the component placeholder in the Page Editor
 * - The dynamic instantiation of components based on a component definition
 * - The conversion from model fields to properties and injection in the component instance
 * - The management of HTMLElement attributes and class names on the native element
 */
export class AEMComponentDirective implements AfterViewInit, OnInit, OnDestroy, OnChanges {
 
  /**
   * Dynamically created component
   */
  private _component: ComponentRef<any>;
  /**
   * Model item that corresponds to the current component
   */
  private _cqItem: any;
 
  get cqItem(): any {
    return this._cqItem;
  }
 
  @Input()
  set cqItem(value: any) {
    this._cqItem = value;
  }
 
  get changeDetectorRef(): ChangeDetectorRef {
    return this._changeDetectorRef;
  }
 
  /**
   * Path to the model structure associated with the current component
   */
  @Input() cqPath: string;
 
  /**
   * Name of the current instance of the component
   */
  @Input() itemName: string;
 
  /**
   * HtmlElement attributes for the current instance of the component
   */
  @Input() itemAttrs: any;
 
  @Input() aemComponent;
 
  constructor(
    private renderer: Renderer2,
    private viewContainer: ViewContainerRef,
    private factoryResolver: ComponentFactoryResolver,
    private _changeDetectorRef: ChangeDetectorRef) {
  }
 
  ngOnInit(): void {
    this.renderComponent(ComponentMapping.get(this.type));
  }
 
  ngOnChanges(): void {
    this.updateComponentData();
  }
 
  /**
   * Returns the type of the cqItem if exists.
   */
  get type(): string | undefined {
    return this.cqItem && this.cqItem[Constants.TYPE_PROP];
  }
 
  /**
   * Renders a component dynamically based on the component definition
   *
   * @param componentDefinition The component definition to render
   */
  private renderComponent(componentDefinition: any) {
    if (componentDefinition) {
      const factory = this.factoryResolver.resolveComponentFactory(componentDefinition);
 
      this.viewContainer.clear();
      this._component = this.viewContainer.createComponent(factory);
      this.updateComponentData();
    }
  }
 
  /**
   * Updates the data of the component based the data of the directive
   */
  private updateComponentData() {
    if (!this._component || !this._component.instance) {
      return;
    }
 
    const keys = Object.getOwnPropertyNames(this.cqItem);
 
    keys.forEach((key) => {
      let propKey = key;
 
      if (propKey.startsWith(':')) {
        // Transformation of internal properties namespaced with [:] to [cq]
        // :myProperty => cqMyProperty
        const tempKey = propKey.substr(1);
 
        propKey = 'cq' + tempKey.substr(0, 1).toUpperCase() + tempKey.substr(1);
      }
 
      this._component.instance[propKey] = this.cqItem[key];
    });
 
    this._component.instance.cqPath = this.cqPath;
    this._component.instance.itemName = this.itemName;
 
    const editConfig = ComponentMapping.getEditConfig(this.type);
 
    if (editConfig && Utils.isInEditor) {
      this.setupPlaceholder(editConfig);
    }
 
    this._changeDetectorRef.detectChanges();
  }
 
  /**
   * Adds the specified item attributes to the element
   */
  private setupItemAttrs() {
    Iif (this.itemAttrs) {
      const keys = Object.getOwnPropertyNames(this.itemAttrs);
 
      keys.forEach((key) => {
        if (key === 'class') {
          const classes = this.itemAttrs[key].split(' ');
 
          classes.forEach((itemClass) => {
            this.renderer.addClass(this._component.location.nativeElement, itemClass);
          });
        } else {
          this.renderer.setAttribute(this._component.location.nativeElement, key, this.itemAttrs[key]);
        }
      });
    }
  }
 
  /**
   * Determines if the placeholder should e displayed.
   *
   * @param editConfig - the edit config of the directive
   */
  private usePlaceholder(editConfig) {
    return editConfig.isEmpty && typeof editConfig.isEmpty === 'function' && editConfig.isEmpty(this.cqItem);
  }
 
  /**
   * Setups the placeholder of needed for the AEM editor
   *
   * @param editConfig - the editConfig, which will dictate the classes to be added on.
   */
  private setupPlaceholder(editConfig) {
    if (this.usePlaceholder(editConfig)) {
      this.renderer.addClass(this._component.location.nativeElement, PLACEHOLDER_CLASS_NAME);
      this.renderer.setAttribute(this._component.location.nativeElement, 'data-emptytext', editConfig.emptyLabel);
    } else {
      this.renderer.removeClass(this._component.location.nativeElement, PLACEHOLDER_CLASS_NAME);
      this.renderer.removeAttribute(this._component.location.nativeElement, 'data-emptytext');
    }
  }
 
  ngAfterViewInit(): void {
    this.setupItemAttrs();
  }
 
  ngOnDestroy(): void {
    this._component && this._component.destroy();
  }
}