"use strict";

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

var React = _interopRequireWildcard(require("react"));

var _index = require("../input/index.js");

var _index2 = require("../popover/index.js");

var _calendar = _interopRequireDefault(require("./calendar.js"));

var _index3 = require("./utils/index.js");

var _overrides = require("../helpers/overrides.js");

var _index4 = require("../locale/index.js");

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

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

function _typeof(obj) { 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 _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 _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) { 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; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

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 _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); }

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

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; }

var Datepicker =
/*#__PURE__*/
function (_React$Component) {
  _inherits(Datepicker, _React$Component);

  function Datepicker() {
    var _getPrototypeOf2;

    var _this;

    _classCallCheck(this, Datepicker);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Datepicker)).call.apply(_getPrototypeOf2, [this].concat(args)));

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "calendar", void 0);

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "state", {
      calendarFocused: false,
      isOpen: false,
      isPseudoFocused: false,
      lastActiveElm: null
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onChange", function (data) {
      var date = data.date;
      var isOpen = false;
      var isPseudoFocused = false;
      var calendarFocused = false;

      if (Array.isArray(date) && _this.props.range && date.length < 2) {
        isOpen = true;
        isPseudoFocused = true;
        calendarFocused = null;
      } else if (_this.state.lastActiveElm) {
        _this.state.lastActiveElm.focus();
      }

      _this.setState(_objectSpread({
        isOpen: isOpen,
        isPseudoFocused: isPseudoFocused
      }, calendarFocused === null ? {} : {
        calendarFocused: calendarFocused
      }));

      _this.props.onChange && _this.props.onChange(data);
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "open", function () {
      _this.setState({
        isOpen: true,
        isPseudoFocused: true
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "close", function () {
      var isPseudoFocused = false;

      _this.setState({
        isOpen: false,
        isPseudoFocused: isPseudoFocused,
        calendarFocused: false
      }, _this.props.onClose);
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleEsc", function () {
      if (_this.state.lastActiveElm) {
        _this.state.lastActiveElm.focus();
      }

      _this.close();
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleInputBlur", function () {
      if (!_this.state.isPseudoFocused) {
        _this.close();
      }
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleKeyDown", function (event) {
      if (!_this.state.isOpen && event.keyCode === 40) {
        _this.open();
      } else if (_this.state.isOpen && event.key === 'ArrowDown') {
        // next line prevents the page jump on the initial arrowDown
        event.preventDefault();

        _this.focusCalendar();
      } else if (_this.state.isOpen && event.keyCode === 9) {
        _this.close();
      }
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "focusCalendar", function () {
      if (typeof document !== 'undefined') {
        var lastActiveElm = document.activeElement;

        _this.setState({
          calendarFocused: true,
          lastActiveElm: lastActiveElm
        });
      }
    });

    return _this;
  }

  _createClass(Datepicker, [{
    key: "formatDate",
    value: function formatDate(date, formatString) {
      if (!date) {
        return '';
      } else if (Array.isArray(date)) {
        return date.map(function (day) {
          return (0, _index3.formatDate)(day, formatString);
        }).join(' - ');
      } else {
        return (0, _index3.formatDate)(date, formatString);
      }
    }
  }, {
    key: "formatDisplayValue",
    value: function formatDisplayValue(date) {
      var formatDisplayValue = this.props.formatDisplayValue || this.formatDate;
      return formatDisplayValue(date, this.props.formatString || 'yyyy/MM/dd');
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props$overrides = this.props.overrides,
          overrides = _this$props$overrides === void 0 ? {} : _this$props$overrides;

      var _getOverrides = (0, _overrides.getOverrides)(overrides.Input, _index.Input),
          _getOverrides2 = _slicedToArray(_getOverrides, 2),
          InputComponent = _getOverrides2[0],
          inputProps = _getOverrides2[1];

      var _getOverrides3 = (0, _overrides.getOverrides)(overrides.Popover, _index2.Popover),
          _getOverrides4 = _slicedToArray(_getOverrides3, 2),
          PopoverComponent = _getOverrides4[0],
          popoverProps = _getOverrides4[1];

      return React.createElement(_index4.LocaleContext.Consumer, null, function (locale) {
        return React.createElement(React.Fragment, null, React.createElement(PopoverComponent, _extends({
          mountNode: _this2.props.mountNode,
          placement: _index2.PLACEMENT.bottom,
          isOpen: _this2.state.isOpen,
          onClickOutside: function onClickOutside(event) {
            // Required to check that items rendered in a sub-popover does not trigger close.
            // For example, upon selecting an option from the month dropdown it would cause
            // this code to run since the two popovers are DOM siblings rather than parent/child.
            // There's likely a more robust way to check this, but ignores clicks from elements
            // that are select options for now.
            function isOption(element) {
              if (!element) return false;
              return element.getAttribute('role') === 'option';
            }

            if (isOption(event.target) || isOption(event.target.parentElement)) {
              return;
            }

            _this2.close();
          },
          onEsc: _this2.handleEsc,
          content: React.createElement(_calendar.default, _extends({
            autoFocusCalendar: _this2.state.calendarFocused,
            trapTabbing: true,
            value: _this2.props.value
          }, _this2.props, {
            onChange: _this2.onChange
          }))
        }, popoverProps), React.createElement("span", null, React.createElement(InputComponent, _extends({
          "aria-disabled": _this2.props.disabled,
          "aria-label": _this2.props['aria-label'] || locale.datepicker.ariaLabel,
          error: _this2.props.error,
          "aria-labelledby": _this2.props['aria-labelledby'],
          "aria-describedby": _this2.props['aria-describedby'],
          "aria-required": _this2.props.required || null,
          disabled: _this2.props.disabled,
          value: _this2.formatDisplayValue(_this2.props.value),
          onFocus: _this2.open,
          onBlur: _this2.handleInputBlur,
          onKeyDown: _this2.handleKeyDown,
          placeholder: _this2.props.placeholder || 'YYYY/MM/DD',
          required: _this2.props.required
        }, inputProps)))), React.createElement("p", {
          id: "datepicker--screenreader--message--input",
          style: {
            position: 'absolute',
            width: '1px',
            height: '1px',
            margin: '-1px',
            border: 0,
            padding: 0,
            overflow: 'hidden',
            clip: 'rect(0, 0, 0, 0)',
            clipPath: 'inset(100%)'
          }
        }, locale.datepicker.screenReaderMessageInput));
      });
    }
  }]);

  return Datepicker;
}(React.Component);

exports.default = Datepicker;

_defineProperty(Datepicker, "defaultProps", {
  'aria-describedby': 'datepicker--screenreader--message--input',
  value: null
});