All files / components/crud crud-form.ts

6.45% Statements 2/31
0% Branches 0/10
0% Functions 0/9
6.66% Lines 2/30

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 1001x             1x                                                                                                                                                                                        
import { Form, Component } from '@zeedhi/common';
import { IDictionary } from '@zeedhi/core';
import { ICrudForm } from './interfaces';
 
/**
 * Form to be used on Crud operations
 */
export class CrudForm extends Form implements ICrudForm {
  /**
   * Form edit state
   */
  public editing: boolean = false;
 
  /**
   * Stores value before editing
   */
  private beforeEditValue?: IDictionary<any>;
 
  /**
   * Stores unsaved Value
   */
  private unSavedValue?: IDictionary<any>;
 
  /**
   * Create new Crud Form
   * @param props component properties
   */
  public constructor(props: ICrudForm) {
    super(props);
    Iif (Object.keys(this.value).length > 0) {
      this.setValue(this.value);
    }
  }
 
  public setValue(value: IDictionary, autoSave: boolean = true) {
    this.value = value;
    this.unSavedValue = value;
    Iif (autoSave) this.saveEdit();
  }
 
  /**
   * Cancel edit and return value to original
   */
  public cancelEdit() {
    this.editing = false;
    Iif (this.beforeEditValue) {
      this.value = this.beforeEditValue;
    }
  }
 
  /**
   * SaveEdit
   */
  public saveEdit() {
    this.editing = false;
    this.beforeEditValue = { ...this.unSavedValue };
  }
 
  /**
   * Update value using child input value
   * @param child child input
   * @param value input value
   */
  public updateChild(child: Component, value: any) {
    const valueKeys = Object.keys(this.value);
    const formChanged = valueKeys.some((key) => {
      const currValue = this.value[key];
      const prevValue = this.beforeEditValue ? this.beforeEditValue[key] : null;
      return this.nullCast(currValue) !== this.nullCast(prevValue);
    });
 
    Iif (!formChanged) {
      this.editing = false;
      return;
    }
 
    this.value[child.name] = value;
    this.editing = true;
  }
 
  private nullCast(value: any) {
    return ['', null, undefined].includes(value) ? null : value;
  }
 
  public onMounted(element: HTMLElement) {
    this.cancelEdit();
    super.onMounted(element);
    element.addEventListener('focus', this.focus.bind(this), true);
  }
 
  /**
   * Form is focused
   */
  public focus() {
    Iif (!this.beforeEditValue) {
      this.beforeEditValue = { ...this.value };
    }
  }
}