Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@skava/ui / dist / forms / form / FormState.js
Size: Mime:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

const tslib_1 = require("tslib");

const exotic_1 = require("exotic");

const mobx_1 = require("xmobx/mobx");

const deps_1 = require("../deps");

const isValidCreditCard_1 = require("../deps/isValidCreditCard");

const isValidExpiryDate_1 = require("../deps/isValidExpiryDate");

const deps_2 = require("./deps");

class FormState {
  constructor(stateData = {}) {
    this.hasAllValidInputs = false;
    this.inputsList = [];
    /**
     * @note added identifier check too
     * @param name name of the input for this form
     */

    this.get = name => {
      /**
       * @todo convert this to a .find
       */
      let result;

      const isSameName = inputState => {
        console.info('[forms] input state get - recursing: ', inputState);
        /**
         * @todo @james - this actually helps to loop through the elementsList inside groupElements,
         * will calling it recursively "result" variable has the element state, though it doesn't return anything.
         */

        if (inputState.type === 'groupElements') {
          // console.error('[form state] MISSING serialized')
          inputState.elementList.forEach(isSameName);
        } else if (inputState.name === name || inputState.identifier === name) {
          result = inputState;
        }
      };

      this.inputsList.forEach(isSameName);
      return result;
    }; // ========= @todo - remove this duplication =========


    this.formValidation = () => {
      const isValidInput = (item, index) => {
        console.log('itemDetails', item);
        const {
          type,
          isHidden,
          isEnabled,
          validationType
        } = item;

        if (isEnabled && type !== 'label' && validationType !== 'none') {
          if (type === 'groupElements' && exotic_1.isArray(item.elementList)) {
            return item.elementList.every(isValidInput);
          } else {
            return this.isValidElement(item);
          }
        } else {
          return true;
        }
      };

      console.log('current input list', this.inputsList);
      const hasAllValidInputs = this.inputsList.every(isValidInput);
      console.log('hasAllValidInputs', hasAllValidInputs);
      return hasAllValidInputs;
    };
    /**
     * @todo @gnanaprabhu why is this duplicated
     */


    this.isValidElement = item => {
      const {
        validationType,
        value
      } = item;

      if (validationType === 'creditCard' || validationType === 'securityCode') {
        return this.validateCreditCard(item);
      }

      if (validationType === 'month' || validationType === 'year') {
        return this.validateExpiryDate(item);
      }

      if (validationType === 'confirmPassword') {
        if (this.validateConfirmPassword(item) === false) {
          return false;
        }
      }

      if (validationType === 'newPassword') {
        if (this.validateNewPassword(item) === false) {
          return false;
        }
      } else {
        const validationResult = deps_1.isValid(value, validationType);

        if (!validationResult) {
          return false;
        }
      }

      return true;
    };

    this.validateCreditCard = item => {
      const validationType = item.validationType;
      const creditCard = this.get('cardNumber');
      const securityCode = this.get('SecurityCode');
      const securityCodeValue = securityCode.getValue();

      if (creditCard && creditCard.getValue()) {
        if (securityCode && securityCodeValue) {
          const isamexCard = isValidCreditCard_1.isAmexCard(creditCard.getValue());

          if (isamexCard && securityCodeValue.length !== 4) {
            return false;
          } else if (!isamexCard && securityCodeValue.length !== 3) {
            return false;
          }
        } else if (validationType === 'securityCode') {
          return false;
        }

        return isValidCreditCard_1.isValidCreditCard(creditCard.getValue());
      }

      return false;
    };

    this.validateExpiryDate = item => {
      const expiryMonth = this.get('expirationMonth');
      const expiryYear = this.get('expirationYear');
      const objValid = {
        validationType: item.validationType,
        expiryYear,
        expiryMonth,
        expiryMonthParsed: expiryMonth.getValue(),
        expiryYearParsed: expiryYear.getValue()
      };
      return isValidExpiryDate_1.isValidExpiryDate(objValid);
    };
    /**
     * @todo when setting inputs list, copy...
     * ORIGINAL_INPUTS_LIST
     */


    this.inputsList = mobx_1.observable([]); // no need to add another method, is an alias for specific usage

    this.toSerialized = this.toJSON.bind(this);
  }

  static init(state) {
    return new FormState(state);
  }

  setInputsList(list) {
    this.inputsList = list;
    return this;
  }

  setFormReference(dom) {
    this.form = dom;
  }

  setProps(props) {
    this.props = props;
  } // ========= protected read =========


  toJSON() {
    const formData = {};

    const assignInputValue = (input, index) => {
      // ignore labels
      if (input.type === 'label') {
        return undefined;
      } // title says it all


      const {
        key,
        value
      } = deps_2.fromInputToSerializedKeyValue(input, assignInputValue); // special place for radios

      if (input.type === 'radio') {
        if (value) {
          formData['selectedItem'] = key;
        }
      } else {
        // otherwise, default
        formData[key] = value;
        /**
         * @todo @fixme bad serialization - fixed in ui-component-library
         */

        if (formData['0'] === value) {
          delete formData['0'];
        }
      }
    }; // this is using `assignInputValue` as a longhand `.reduce`


    this.inputsList.forEach(assignInputValue);
    return formData;
  }

  validateForSamePassword(item, name, shouldBeSamePassword) {
    // if (isObj(item) === false) {
    //   console.error('@ganesh - it is being passed a string')
    //   return false
    // }
    const {
      value
    } = item;

    if (!deps_1.isValidPassword(value)) {
      item.setIsValidInput(false);
      item.errorMessage = deps_1.errorMessage('password');
      return false;
    }

    const password = this.get(name);
    const passwordValue = password.getValue();
    item.setIsValidInput(true);
    let isValid = passwordValue === '';
    isValid = shouldBeSamePassword ? passwordValue !== item.value : passwordValue === item.value;

    if (isValid) {
      item.setIsValidInput(false);
      item.errorMessage = deps_1.errorMessage(item.errorMessageFor);
      return false;
    }

    return true;
  }

  validateConfirmPassword(item) {
    return this.validateForSamePassword(item, 'password', true);
  }

  validateNewPassword(item) {
    return this.validateForSamePassword(item, 'oldPassword', false);
  }

}

tslib_1.__decorate([mobx_1.observable], FormState.prototype, "hasAllValidInputs", void 0);

tslib_1.__decorate([mobx_1.observable], FormState.prototype, "inputsList", void 0);

tslib_1.__decorate([mobx_1.action], FormState.prototype, "setInputsList", null);

tslib_1.__decorate([mobx_1.action.bound], FormState.prototype, "setFormReference", null);

tslib_1.__decorate([mobx_1.action.bound], FormState.prototype, "setProps", null);

tslib_1.__decorate([mobx_1.action.bound], FormState.prototype, "validateForSamePassword", null);

tslib_1.__decorate([mobx_1.action.bound], FormState.prototype, "validateConfirmPassword", null);

tslib_1.__decorate([mobx_1.action.bound], FormState.prototype, "validateNewPassword", null);

exports.FormState = FormState;
exports.default = FormState; //# sourceMappingURL=FormState.js.map