All files / src/lib/core component-registry.service.ts

93.33% Statements 14/15
75% Branches 3/4
100% Functions 4/4
92.86% Lines 13/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 46 47 48 49 50 51 52 53 54                1x     97x     97x     1x         240x   240x         233x         19x           17x 17x   17x       17x   17x        
import { Injectable } from '@angular/core';
 
/**
 * A registry for each WvrBaseComponent currently present on the page.
 */
@Injectable({
  providedIn: 'root'
})
export class ComponentRegistryService<T> {
 
  /** Incrementing index of all registered components. */
  private index = -1;
 
  /** Registry for all WvrBaseComponent. */
  private readonly registry: Map<number | string, T> = new Map<number, T>();
 
  /** A statically accessible reference to the prefix used in deriving the HTML identifier. */
  static readonly HTML_ID_BASE = 'wvr-component';
 
  /** Adds a WvrBaseComponent to the registry. */
  register(component: T): number {
    // tslint:disable-next-line:increment-decrement
    this.registry.set(++this.index, component);
 
    return this.index;
  }
 
  /** Removes a WvrBaseComponent from the registry. */
  unRegisterComponent(id: number | string): void {
    this.registry.delete(id);
  }
 
  /** Retrieves a WvrBaseComponent from the registry. */
  getComponent(id: number | string): T {
    return this.registry.get(id);
  }
 
  /** Retrieves a WvrBaseComponent from the registry by HTMLElement. */
  getComponentByElement(element: HTMLElement): T {
 
    const hasNativeId = element.hasAttribute('wvr-id');
    const htmlID = hasNativeId ? element.getAttribute('wvr-id') : element.getAttribute('id');
 
    Iif (!htmlID) {
      return undefined;
    }
 
    const id = parseInt(htmlID.replace(`${ComponentRegistryService.HTML_ID_BASE}-`, ''), 10);
 
    return this.getComponent(id);
  }
 
}