Liferay.Loader.define("dynamic-data-mapping-form-field-type@5.0.45/DatePicker/DatePicker.es", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/date-picker', 'dynamic-data-mapping-form-field-type$moment', 'frontend-js-react-web$react', 'dynamic-data-mapping-form-field-type$text-mask-addons', 'dynamic-data-mapping-form-field-type$text-mask-core', '../FieldBase/ReactFieldBase.es', '../hooks/useSyncValue.es'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    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);
    }

    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports["default"] = void 0;

    var _datePicker = _interopRequireDefault(require("@frontend-taglib-clay$clayui/date-picker"));

    var _moment = _interopRequireDefault(require("dynamic-data-mapping-form-field-type$moment"));

    var _react = _interopRequireWildcard(require("frontend-js-react-web$react"));

    var _textMaskAddons = require("dynamic-data-mapping-form-field-type$text-mask-addons");

    var _textMaskCore = require("dynamic-data-mapping-form-field-type$text-mask-core");

    var _ReactFieldBase = require("../FieldBase/ReactFieldBase.es");

    var _useSyncValue3 = require("../hooks/useSyncValue.es");

    function _getRequireWildcardCache() {
      if (typeof WeakMap !== "function") return null;var cache = new WeakMap();_getRequireWildcardCache = function _getRequireWildcardCache() {
        return cache;
      };return cache;
    }

    function _interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      }if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
        return { "default": obj };
      }var cache = _getRequireWildcardCache();if (cache && cache.has(obj)) {
        return cache.get(obj);
      }var newObj = {};var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;if (desc && (desc.get || desc.set)) {
            Object.defineProperty(newObj, key, desc);
          } else {
            newObj[key] = obj[key];
          }
        }
      }newObj["default"] = obj;if (cache) {
        cache.set(obj, newObj);
      }return newObj;
    }

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

    function _extends() {
      _extends = Object.assign || function (target) {
        for (var i = 1; i < arguments.length; i++) {
          var source = arguments[i];for (var key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)) {
              target[key] = source[key];
            }
          }
        }return target;
      };return _extends.apply(this, arguments);
    }

    function _objectWithoutProperties(source, excluded) {
      if (source == null) return {};var target = _objectWithoutPropertiesLoose(source, excluded);var key, i;if (Object.getOwnPropertySymbols) {
        var sourceSymbolKeys = Object.getOwnPropertySymbols(source);for (i = 0; i < sourceSymbolKeys.length; i++) {
          key = sourceSymbolKeys[i];if (excluded.indexOf(key) >= 0) continue;if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;target[key] = source[key];
        }
      }return target;
    }

    function _objectWithoutPropertiesLoose(source, excluded) {
      if (source == null) return {};var target = {};var sourceKeys = Object.keys(source);var key, i;for (i = 0; i < sourceKeys.length; i++) {
        key = sourceKeys[i];if (excluded.indexOf(key) >= 0) continue;target[key] = source[key];
      }return target;
    }

    function _slicedToArray(arr, i) {
      return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
    }

    function _nonIterableRest() {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }

    function _iterableToArrayLimit(arr, i) {
      if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
        return;
      }var _arr = [];var _n = true;var _d = false;var _e = undefined;try {
        for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
          _arr.push(_s.value);if (i && _arr.length === i) break;
        }
      } catch (err) {
        _d = true;_e = err;
      } finally {
        try {
          if (!_n && _i["return"] != null) _i["return"]();
        } finally {
          if (_d) throw _e;
        }
      }return _arr;
    }

    function _arrayWithHoles(arr) {
      if (Array.isArray(arr)) return arr;
    }

    var getInputMask = function getInputMask(dateFormat, dateDelimiter) {
      var inputMaskArray = [];
      dateFormat.split('').forEach(function (item) {
        if (item === dateDelimiter) {
          inputMaskArray.push(dateDelimiter);
        } else if (item === 'Y') {
          inputMaskArray.push(/\d/);
          inputMaskArray.push(/\d/);
          inputMaskArray.push(/\d/);
          inputMaskArray.push(/\d/);
        } else if (item === 'd' || item === 'm') {
          inputMaskArray.push(/\d/);
          inputMaskArray.push(/\d/);
        }
      });
      return inputMaskArray;
    };

    var getDateMask = function getDateMask(dateFormat, dateDelimiter) {
      return dateFormat.split(dateDelimiter).map(function (item) {
        var currentFormat;

        if (item === '%Y') {
          currentFormat = 'yyyy';
        } else if (item === '%m') {
          currentFormat = 'MM';
        } else {
          currentFormat = 'dd';
        }

        return currentFormat;
      }).join(dateDelimiter);
    };

    var getDelimiter = function getDelimiter(dateFormat) {
      var dateDelimiter = '/';

      if (dateFormat.indexOf('.') != -1) {
        dateDelimiter = '.';
      }

      if (dateFormat.indexOf('-') != -1) {
        dateDelimiter = '-';
      }

      return dateDelimiter;
    };

    var getDateFormat = function getDateFormat() {
      var dateFormat = Liferay.AUI.getDateFormat();
      var dateDelimiter = getDelimiter(dateFormat);
      return {
        dateMask: getDateMask(dateFormat, dateDelimiter),
        inputMask: getInputMask(dateFormat, dateDelimiter)
      };
    };

    var transformToDate = function transformToDate(date) {
      if (typeof date === 'string' && date.indexOf('_') === -1 && date !== '') {
        return (0, _moment["default"])(date).toDate();
      }

      return date;
    };

    var getInitialMonth = function getInitialMonth(value) {
      if ((0, _moment["default"])(value).isValid()) {
        return (0, _moment["default"])(value).toDate();
      }

      return (0, _moment["default"])().toDate();
    };

    var getValueForHidden = function getValueForHidden(value) {
      if ((0, _moment["default"])(value).isValid()) {
        return (0, _moment["default"])(value).format('YYYY-MM-DD');
      }

      return null;
    };

    var DatePicker = function DatePicker(_ref) {
      var disabled = _ref.disabled,
          name = _ref.name,
          onChange = _ref.onChange,
          spritemap = _ref.spritemap,
          initialValue = _ref.value;
      var inputRef = (0, _react.useRef)(null);
      var maskInstance = (0, _react.useRef)(null);

      var _useState = (0, _react.useState)(false),
          _useState2 = _slicedToArray(_useState, 2),
          expanded = _useState2[0],
          setExpand = _useState2[1];

      var initialValueMemoized = (0, _react.useMemo)(function () {
        return transformToDate(initialValue);
      }, [initialValue]);

      var _useSyncValue = (0, _useSyncValue3.useSyncValue)(initialValueMemoized),
          _useSyncValue2 = _slicedToArray(_useSyncValue, 2),
          value = _useSyncValue2[0],
          setValue = _useSyncValue2[1];

      var _useState3 = (0, _react.useState)(function () {
        var currentYear = new Date().getFullYear();
        return {
          end: currentYear + 5,
          start: currentYear - 5
        };
      }),
          _useState4 = _slicedToArray(_useState3, 2),
          years = _useState4[0],
          setYears = _useState4[1];

      var _getDateFormat = getDateFormat(),
          dateMask = _getDateFormat.dateMask,
          inputMask = _getDateFormat.inputMask;

      (0, _react.useEffect)(function () {
        if (inputRef.current && inputMask && dateMask) {
          maskInstance.current = (0, _textMaskCore.createTextMaskInputElement)({
            guide: true,
            inputElement: inputRef.current,
            keepCharPositions: true,
            mask: inputMask,
            pipe: (0, _textMaskAddons.createAutoCorrectedDatePipe)(dateMask.toLowerCase()),
            showMask: true
          });
          maskInstance.current.update(inputRef.current.value);
        }
      }, [inputMask, dateMask, inputRef]);

      return _react["default"].createElement(_react["default"].Fragment, null, _react["default"].createElement("input", {
        "aria-hidden": "true",
        name: name,
        type: "hidden",
        value: getValueForHidden(value)
      }), _react["default"].createElement(_datePicker["default"], {
        dateFormat: dateMask,
        disabled: disabled,
        expanded: expanded,
        initialMonth: getInitialMonth(value),
        onExpandedChange: function onExpandedChange(expand) {
          setExpand(expand);
        },
        onInput: function onInput(event) {
          maskInstance.current.update(event.target.value);
        },
        onNavigation: function handleNavigation(date) {
          var currentYear = date.getFullYear();
          setYears({
            end: currentYear + 5,
            start: currentYear - 5
          });
        },
        onValueChange: function onValueChange(value, eventType) {
          setValue(value);

          if (eventType === 'click') {
            setExpand(false);
            inputRef.current.focus();
          }

          if (!value || value === maskInstance.current.state.previousPlaceholder) {
            return onChange('');
          }

          if ((0, _moment["default"])(value).isValid()) {
            onChange((0, _moment["default"])(value).format(dateMask.toUpperCase()));
          }
        },
        ref: inputRef,
        spritemap: spritemap,
        value: value,
        years: years
      }));
    };

    var Main = function Main(_ref2) {
      var name = _ref2.name,
          _onChange = _ref2.onChange,
          placeholder = _ref2.placeholder,
          predefinedValue = _ref2.predefinedValue,
          readOnly = _ref2.readOnly,
          spritemap = _ref2.spritemap,
          value = _ref2.value,
          otherProps = _objectWithoutProperties(_ref2, ["name", "onChange", "placeholder", "predefinedValue", "readOnly", "spritemap", "value"]);

      return _react["default"].createElement(_ReactFieldBase.FieldBase, _extends({}, otherProps, {
        name: name,
        readOnly: readOnly,
        spritemap: spritemap
      }), _react["default"].createElement(DatePicker, {
        disabled: readOnly,
        name: name,
        onChange: function onChange(value) {
          return _onChange({}, value);
        },
        placeholder: placeholder,
        spritemap: spritemap,
        value: value ? value : predefinedValue
      }));
    };

    Main.displayName = 'DatePicker';
    var _default = Main;
    exports["default"] = _default;
    //# sourceMappingURL=DatePicker.es.js.map
  }
});
//# sourceMappingURL=DatePicker.es.js.map