All files / lib/dynamic-form-action dynamic-form-action.service.ts

100% Statements 16/16
100% Branches 4/4
100% Functions 5/5
100% Lines 15/15

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                  1x       74x   74x   74x       6x       4x 1x 1x 1x   3x 3x 2x 2x 2x         2x          
import { Inject, Injectable, Optional } from '@angular/core';
import { DynamicFormElement } from '../dynamic-form-element/dynamic-form-element';
import { DynamicFormField } from '../dynamic-form-field/dynamic-form-field';
import { DynamicFormLibraryService } from '../dynamic-form-library/dynamic-form-library.service';
import { DynamicFormAction } from './dynamic-form-action';
import { DynamicFormActionHandler } from './dynamic-form-action-handler';
import { DynamicFormActionHandlerConfig, DYNAMIC_FORM_ACTION_HANDLER_CONFIG } from './dynamic-form-action-handler-config';
 
@Injectable()
export class DynamicFormActionService {
  readonly handlers: DynamicFormActionHandler[];
 
  constructor(
    private readonly libraryService: DynamicFormLibraryService,
    @Optional() @Inject(DYNAMIC_FORM_ACTION_HANDLER_CONFIG)
    private handlerConfig: DynamicFormActionHandlerConfig,
  ) {
    this.handlers = this.libraryService.filterTypes(this.handlerConfig);
  }
 
  getHandler(type: string): DynamicFormActionHandler {
    return this.handlers.find(f => f.type === type);
  }
 
  handle(action: DynamicFormAction, $event: Event): void {
    if (typeof action.template.action === 'function') {
      action.template.action();
      $event.stopPropagation();
      return;
    }
    const handler = this.getHandler(action.template.action);
    if (handler) {
      const element = this.getElement(handler, action);
      handler.func(element, action);
      $event.stopPropagation();
    }
  }
 
  private getElement(handler: DynamicFormActionHandler, action: DynamicFormAction): DynamicFormElement | DynamicFormField {
    return handler.elementFunc
      ? handler.elementFunc(action)
      : action.parent;
  }
}