Liferay.Loader.define("dynamic-data-mapping-form-builder@3.0.66/js/components/RuleList/RuleList.es", ['module', 'exports', 'require', 'frontend-taglib-clay$clay-button', 'frontend-taglib-clay$clay-label', 'frontend-taglib-clay$clay-dropdown', 'frontend-taglib-clay$clay-tooltip', 'dynamic-data-mapping-form-renderer', 'frontend-js-metal-web$metal-component', 'frontend-js-metal-web$metal-dom', 'frontend-js-metal-web$metal-events', 'frontend-js-metal-web$metal-soy', 'frontend-js-metal-web$metal-state', '../../util/pageSupport.es', '../LayoutProvider/util/fields.es', '../RuleBuilder/RulesSupport.es', './RuleList.soy'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;

    require("frontend-taglib-clay$clay-button");

    require("frontend-taglib-clay$clay-label");

    require("frontend-taglib-clay$clay-dropdown");

    var _clayTooltip = _interopRequireDefault(require("frontend-taglib-clay$clay-tooltip"));

    var _dynamicDataMappingFormRenderer = require("dynamic-data-mapping-form-renderer");

    var _metalComponent = _interopRequireDefault(require("frontend-js-metal-web$metal-component"));

    var _metalDom = _interopRequireDefault(require("frontend-js-metal-web$metal-dom"));

    var _metalEvents = require("frontend-js-metal-web$metal-events");

    var _metalSoy = _interopRequireDefault(require("frontend-js-metal-web$metal-soy"));

    var _metalState = require("frontend-js-metal-web$metal-state");

    var _pageSupport = require("../../util/pageSupport.es");

    var _fields = require("../LayoutProvider/util/fields.es");

    var _RulesSupport = _interopRequireDefault(require("../RuleBuilder/RulesSupport.es"));

    var _RuleList = _interopRequireDefault(require("./RuleList.soy"));

    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { default: obj };
    }

    function _typeof(obj) {
      "@babel/helpers - typeof";
      if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
        _typeof = function _typeof(obj) {
          return typeof obj;
        };
      } else {
        _typeof = function _typeof(obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
      }return _typeof(obj);
    }

    function ownKeys(object, enumerableOnly) {
      var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);if (enumerableOnly) symbols = symbols.filter(function (sym) {
          return Object.getOwnPropertyDescriptor(object, sym).enumerable;
        });keys.push.apply(keys, symbols);
      }return keys;
    }

    function _objectSpread(target) {
      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i] != null ? arguments[i] : {};if (i % 2) {
          ownKeys(Object(source), true).forEach(function (key) {
            _defineProperty(target, key, source[key]);
          });
        } else if (Object.getOwnPropertyDescriptors) {
          Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
        } else {
          ownKeys(Object(source)).forEach(function (key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
          });
        }
      }return target;
    }

    function _defineProperty(obj, key, value) {
      if (key in obj) {
        Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });
      } else {
        obj[key] = value;
      }return obj;
    }

    function _classCallCheck(instance, Constructor) {
      if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
      }
    }

    function _defineProperties(target, props) {
      for (var i = 0; i < props.length; i++) {
        var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
      }
    }

    function _createClass(Constructor, protoProps, staticProps) {
      if (protoProps) _defineProperties(Constructor.prototype, protoProps);if (staticProps) _defineProperties(Constructor, staticProps);return Constructor;
    }

    function _possibleConstructorReturn(self, call) {
      if (call && (_typeof(call) === "object" || typeof call === "function")) {
        return call;
      }return _assertThisInitialized(self);
    }

    function _assertThisInitialized(self) {
      if (self === void 0) {
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
      }return self;
    }

    function _get(target, property, receiver) {
      if (typeof Reflect !== "undefined" && Reflect.get) {
        _get = Reflect.get;
      } else {
        _get = function _get(target, property, receiver) {
          var base = _superPropBase(target, property);if (!base) return;var desc = Object.getOwnPropertyDescriptor(base, property);if (desc.get) {
            return desc.get.call(receiver);
          }return desc.value;
        };
      }return _get(target, property, receiver || target);
    }

    function _superPropBase(object, property) {
      while (!Object.prototype.hasOwnProperty.call(object, property)) {
        object = _getPrototypeOf(object);if (object === null) break;
      }return object;
    }

    function _getPrototypeOf(o) {
      _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
        return o.__proto__ || Object.getPrototypeOf(o);
      };return _getPrototypeOf(o);
    }

    function _inherits(subClass, superClass) {
      if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function");
      }subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });if (superClass) _setPrototypeOf(subClass, superClass);
    }

    function _setPrototypeOf(o, p) {
      _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
        o.__proto__ = p;return o;
      };return _setPrototypeOf(o, p);
    }

    /**
     * RuleList.
     * @extends Component
     */
    var RuleList = /*#__PURE__*/function (_Component) {
      _inherits(RuleList, _Component);

      function RuleList() {
        _classCallCheck(this, RuleList);

        return _possibleConstructorReturn(this, _getPrototypeOf(RuleList).apply(this, arguments));
      }

      _createClass(RuleList, [{
        key: "attached",
        value: function attached() {
          this._eventHandler = new _metalEvents.EventHandler();

          this._eventHandler.add(_metalDom.default.on(document, 'mouseup', this._handleDocumentMouseUp.bind(this), true));

          _clayTooltip.default.init();
        }
      }, {
        key: "disposeInternal",
        value: function disposeInternal() {
          _get(_getPrototypeOf(RuleList.prototype), "disposeInternal", this).call(this);

          this._eventHandler.removeAllListeners();
        }
      }, {
        key: "prepareStateForRender",
        value: function prepareStateForRender(states) {
          var _this = this;

          var rules = _RulesSupport.default.formatRules(this.pages, this._setDataProviderNames(states));

          return _objectSpread(_objectSpread({}, states), {}, {
            rules: rules.map(function (rule) {
              var logicalOperator;
              var invalidRule = false;

              if (rule['logical-operator']) {
                logicalOperator = rule['logical-operator'].toLowerCase();
              } else if (rule.logicalOperator) {
                logicalOperator = rule.logicalOperator.toLowerCase();
              }

              invalidRule = _RulesSupport.default.findInvalidRule(_this.pages, rule);
              return _objectSpread(_objectSpread({}, rule), {}, {
                actions: rule.actions.map(function (action) {
                  var newAction;

                  if (action.action === 'auto-fill') {
                    var inputs = action.inputs,
                        outputs = action.outputs;
                    var inputLabel = Object.values(inputs).map(function (input) {
                      return _this._getFieldLabel(input);
                    });
                    var outputLabel = Object.values(outputs).map(function (output) {
                      return _this._getFieldLabel(output);
                    });
                    newAction = _objectSpread(_objectSpread({}, action), {}, {
                      inputLabel: inputLabel,
                      outputLabel: outputLabel
                    });
                  } else if (action.action == 'jump-to-page') {
                    newAction = _objectSpread(_objectSpread({}, action), {}, {
                      label: _this._getJumpToPageLabel(rule, action)
                    });
                  } else {
                    newAction = _objectSpread(_objectSpread({}, action), {}, {
                      label: _this._getFieldLabel(action.target)
                    });
                  }

                  return newAction;
                }),
                conditions: rule.conditions.map(function (condition) {
                  return _objectSpread(_objectSpread({}, condition), {}, {
                    operands: condition.operands.map(function (operand, index) {
                      var label = _this._getOperandLabel(condition.operands, index);

                      return _objectSpread(_objectSpread({}, operand), {}, {
                        label: label,
                        value: label
                      });
                    })
                  });
                }),
                invalidRule: invalidRule,
                logicalOperator: logicalOperator,
                rulesCardOptions: _this._getRulesCardOptions(rule)
              });
            })
          });
        }
      }, {
        key: "_getDataProviderName",
        value: function _getDataProviderName(id) {
          var dataProvider = this.dataProvider;
          return dataProvider.find(function (data) {
            return data.uuid == id;
          }).label;
        }
      }, {
        key: "_getFieldLabel",
        value: function _getFieldLabel(fieldName) {
          var pages = this.pages;
          return (0, _fields.getFieldProperty)(pages, fieldName, 'label') || fieldName;
        }
      }, {
        key: "_getJumpToPageLabel",
        value: function _getJumpToPageLabel(rule, action) {
          var pages = this.pages;
          var pageLabel = '';
          var fieldTarget = (parseInt(action.target, 10) + 1).toString();
          var maxPageIndexRes = (0, _pageSupport.maxPageIndex)(rule.conditions, pages);
          var pageOptionsList = (0, _pageSupport.pageOptions)(pages, maxPageIndexRes);
          var selectedPage = pageOptionsList.find(function (option) {
            return option.value == fieldTarget;
          });

          if (selectedPage) {
            pageLabel = selectedPage.label;
          }

          return pageLabel;
        }
      }, {
        key: "_getOperandLabel",
        value: function _getOperandLabel(operands, index) {
          var label = '';
          var operand = operands[index];

          if (operand.type === 'field') {
            label = this._getFieldLabel(operand.value);
          } else if (operand.type === 'user') {
            label = Liferay.Language.get('user');
          } else if (operand.type !== 'field') {
            var fieldType = _RulesSupport.default.getFieldType(operands[0].value, this.pages);

            if (fieldType === 'checkbox_multiple' || fieldType === 'radio' || fieldType === 'select') {
              label = this._getOptionLabel(operands[0].value, operand.value);
            } else if (operand.type === 'json') {
              label = '';
              var operandValueJSON = JSON.parse(operand.value);

              for (var key in operandValueJSON) {
                var keyLabel = this._getPropertyLabel(operands[0].value, 'rows', key);

                var valueLabel = this._getPropertyLabel(operands[0].value, 'columns', operandValueJSON[key]);

                label += keyLabel + ':' + valueLabel + ', ';
              }

              var lastCommaPosition = label.lastIndexOf(', ');

              if (lastCommaPosition != -1) {
                label = label.substr(0, lastCommaPosition);
              }
            } else {
              label = operand.value;
            }
          } else {
            label = operand.value;
          }

          return label;
        }
      }, {
        key: "_getOptionLabel",
        value: function _getOptionLabel(fieldName, optionValue) {
          return this._getPropertyLabel(fieldName, 'options', optionValue);
        }
      }, {
        key: "_getPropertyLabel",
        value: function _getPropertyLabel(fieldName, propertyName, propertyValue) {
          var pages = this.pages;
          var fieldLabel = null;

          if (pages && propertyValue) {
            var visitor = new _dynamicDataMappingFormRenderer.PagesVisitor(pages);
            visitor.findField(function (field) {
              var found = false;

              if (field.fieldName === fieldName && field.options) {
                field[propertyName].some(function (property) {
                  if (property.value == propertyValue) {
                    fieldLabel = property.label;
                    found = true;
                  }

                  return found;
                });
              }

              return found;
            });
          }

          return fieldLabel ? fieldLabel : propertyValue;
        }
      }, {
        key: "_getRulesCardOptions",
        value: function _getRulesCardOptions(rule) {
          var hasNestedCondition = this._hasNestedCondition(rule);

          var rulesCardOptions = [{
            disabled: hasNestedCondition,
            label: Liferay.Language.get('edit'),
            settingsItem: 'edit'
          }, {
            confirm: hasNestedCondition,
            label: Liferay.Language.get('delete'),
            settingsItem: 'delete'
          }];
          return rulesCardOptions;
        }
      }, {
        key: "_handleDocumentMouseUp",
        value: function _handleDocumentMouseUp(_ref) {
          var target = _ref.target;

          var dropdownSettings = _metalDom.default.closest(target, '.ddm-rule-list-settings');

          if (dropdownSettings) {
            return;
          }

          this.setState({
            dropdownExpandedIndex: -1
          });
        }
      }, {
        key: "_handleDropdownClicked",
        value: function _handleDropdownClicked(event) {
          event.preventDefault();
          var dropdownExpandedIndex = this.dropdownExpandedIndex;

          var ruleNode = _metalDom.default.closest(event.delegateTarget, '.component-action');

          var ruleIndex = parseInt(ruleNode.dataset.ruleIndex, 10);

          if (ruleIndex === dropdownExpandedIndex) {
            ruleIndex = -1;
          }

          this.setState({
            dropdownExpandedIndex: ruleIndex
          });
        }
      }, {
        key: "_handleRuleCardClicked",
        value: function _handleRuleCardClicked(_ref2) {
          var data = _ref2.data,
              target = _ref2.target;

          var cardElement = _metalDom.default.closest(target.element, '[data-card-id]');

          var cardId = parseInt(cardElement.getAttribute('data-card-id'), 10);

          if (data.item.settingsItem == 'edit') {
            this.emit('ruleEdited', {
              ruleId: cardId
            });
          } else if (data.item.settingsItem == 'delete') {
            if (!data.item.confirm || confirm(Liferay.Language.get('you-cannot-create-rules-with-nested-functions.-are-you-sure-you-want-to-delete-this-rule'))) {
              this.emit('ruleDeleted', {
                ruleId: cardId
              });
            }
          }
        }
      }, {
        key: "_hasNestedCondition",
        value: function _hasNestedCondition(rule) {
          return rule.conditions.find(function (condition) {
            return condition.operands.find(function (operand) {
              return operand.value.match(/[aA-zZ]+[(].*[,]+.*[)]/);
            });
          }) !== undefined;
        }
      }, {
        key: "_setDataProviderNames",
        value: function _setDataProviderNames(states) {
          var _this2 = this;

          var rules = states.rules;

          if (this.dataProvider) {
            for (var rule = 0; rule < rules.length; rule++) {
              var actions = rules[rule].actions;
              actions.forEach(function (action) {
                if (action.action === 'auto-fill') {
                  var dataProviderName = _this2._getDataProviderName(action.ddmDataProviderInstanceUUID);

                  action.dataProviderName = dataProviderName;
                }
              });
            }
          }

          return rules;
        }
      }]);

      return RuleList;
    }(_metalComponent.default);

    RuleList.STATE = {
      dataProvider: _metalState.Config.arrayOf(_metalState.Config.shapeOf({
        id: _metalState.Config.string(),
        name: _metalState.Config.string(),
        uuid: _metalState.Config.string()
      })),
      dropdownExpandedIndex: _metalState.Config.number().internal(),
      pages: _metalState.Config.array().required(),
      roles: _metalState.Config.arrayOf(_metalState.Config.shapeOf({
        id: _metalState.Config.string(),
        name: _metalState.Config.string()
      })).value([]),

      /**
       * @default 0
       * @instance
       * @memberof RuleList
       * @type {?array}
       */
      rules: _metalState.Config.arrayOf(_metalState.Config.shapeOf(_defineProperty({
        actions: _metalState.Config.arrayOf(_metalState.Config.shapeOf({
          action: _metalState.Config.string(),
          ddmDataProviderInstanceUUID: _metalState.Config.string(),
          expression: _metalState.Config.string(),
          inputs: _metalState.Config.object(),
          label: _metalState.Config.string(),
          outputs: _metalState.Config.object(),
          target: _metalState.Config.string()
        })),
        conditions: _metalState.Config.arrayOf(_metalState.Config.shapeOf({
          operands: _metalState.Config.arrayOf(_metalState.Config.shapeOf({
            label: _metalState.Config.string(),
            repeatable: _metalState.Config.bool(),
            type: _metalState.Config.string(),
            value: _metalState.Config.string()
          })),
          operator: _metalState.Config.string()
        }))
      }, 'logical-operator', _metalState.Config.string()))).value([]),

      /**
       * @default undefined
       * @instance
       * @memberof RuleList
       * @type {!string}
       */
      spritemap: _metalState.Config.string().required(),

      /**
       * @default strings
       * @instance
       * @memberof RuleList
       * @type {!object}
       */
      strings: _metalState.Config.object().value({
        'belongs-to': Liferay.Language.get('belongs-to'),
        'calculate-field': Liferay.Language.get('calculate-field-x-as-x'),
        contains: Liferay.Language.get('contains'),
        'due-to-missing-fields': Liferay.Language.get('due-to-missing-fields'),
        'equals-to': Liferay.Language.get('is-equal-to'),
        'greater-than': Liferay.Language.get('is-greater-than'),
        'greater-than-equals': Liferay.Language.get('is-greater-than-or-equal-to'),
        'is-empty': Liferay.Language.get('is-empty'),
        'less-than': Liferay.Language.get('is-less-than'),
        'less-than-equals': Liferay.Language.get('is-less-than-or-equal-to'),
        'not-contains': Liferay.Language.get('does-not-contain'),
        'not-equals-to': Liferay.Language.get('is-not-equal-to'),
        'not-is-empty': Liferay.Language.get('is-not-empty')
      })
    };

    _metalSoy.default.register(RuleList, _RuleList.default);

    var _default = RuleList;
    exports.default = _default;
    //# sourceMappingURL=RuleList.es.js.map
  }
});
//# sourceMappingURL=RuleList.es.js.map