"use strict";

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

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

var _propTypes = _interopRequireDefault(require("prop-types"));

var _classnames4 = _interopRequireDefault(require("classnames"));

var _moment = _interopRequireDefault(require("moment"));

var _overlay = _interopRequireDefault(require("../overlay"));

var _input = _interopRequireDefault(require("../input"));

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

var _zhCn = _interopRequireDefault(require("../locale/zh-cn"));

var _util = require("../util");

var _util2 = require("./util");

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

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 _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 _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 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(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(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 _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

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 _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 Popup = _overlay["default"].Popup;
/**
 * DatePicker.YearPicker
 */

var YearPicker =
/*#__PURE__*/
function (_Component) {
  _inherits(YearPicker, _Component);

  function YearPicker(props, context) {
    var _this;

    _classCallCheck(this, YearPicker);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(YearPicker).call(this, props, context));

    _defineProperty(_assertThisInitialized(_this), "getOverlay", function () {
      return _this.popup && _this.popup.getInstance() && _this.popup.getInstance().getOverlay();
    });

    _defineProperty(_assertThisInitialized(_this), "onValueChange", function (newValue) {
      var ret = _this.inputAsString && newValue ? newValue.format(_this.props.format) : newValue;

      _this.props.onChange(ret);
    });

    _defineProperty(_assertThisInitialized(_this), "onSelectCalendarPanel", function (value) {
      // const { format } = this.props;
      var prevSelectedMonth = _this.state.value;
      var selectedMonth = value.clone().month(0).date(1).hour(0).minute(0).second(0);

      _this.handleChange(selectedMonth, prevSelectedMonth, {
        inputing: false
      }, function () {
        _this.onVisibleChange(false, 'calendarSelect');
      });
    });

    _defineProperty(_assertThisInitialized(_this), "clearValue", function () {
      _this.setState({
        dateInputStr: ''
      });

      _this.handleChange(null, _this.state.value);
    });

    _defineProperty(_assertThisInitialized(_this), "onDateInputChange", function (inputStr, e, eventType) {
      if (eventType === 'clear' || !inputStr) {
        e.stopPropagation();

        _this.clearValue();
      } else {
        _this.setState({
          dateInputStr: inputStr,
          inputing: true
        });
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onDateInputBlur", function () {
      var dateInputStr = _this.state.dateInputStr;

      if (dateInputStr) {
        var _this$props = _this.props,
            disabledDate = _this$props.disabledDate,
            format = _this$props.format;
        var parsed = (0, _moment["default"])(dateInputStr, format, true);

        _this.setState({
          dateInputStr: '',
          inputing: false
        });

        if (parsed.isValid() && !disabledDate(parsed, 'year')) {
          _this.handleChange(parsed, _this.state.value);
        }
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onKeyDown", function (e) {
      var format = _this.props.format;
      var _this$state = _this.state,
          dateInputStr = _this$state.dateInputStr,
          value = _this$state.value;
      var dateStr = (0, _util2.onDateKeydown)(e, {
        format: format,
        dateInputStr: dateInputStr,
        value: value
      }, 'year');
      if (!dateStr) return;

      _this.onDateInputChange(dateStr);
    });

    _defineProperty(_assertThisInitialized(_this), "handleChange", function (newValue, prevValue) {
      var others = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
      var callback = arguments.length > 3 ? arguments[3] : undefined;

      if (!('value' in _this.props)) {
        _this.setState(_objectSpread({
          value: newValue
        }, others));
      } else {
        _this.setState(_objectSpread({}, others));
      }

      var format = _this.props.format;
      var newValueOf = newValue ? newValue.format(format) : null;
      var preValueOf = prevValue ? prevValue.format(format) : null;

      if (newValueOf !== preValueOf) {
        _this.onValueChange(newValue);

        if (typeof callback === 'function') {
          return callback();
        }
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onVisibleChange", function (visible, reason) {
      if (!('visible' in _this.props)) {
        _this.setState({
          visible: visible
        });
      }

      _this.props.onVisibleChange(visible, reason);
    });

    var _value = (0, _util2.formatDateValue)(props.value || props.defaultValue, props.format);

    _this.inputAsString = typeof (props.value || props.defaultValue) === 'string'; // 判断用户输入是否是字符串

    _this.state = {
      value: _value,
      dateInputStr: '',
      inputing: false,
      visible: props.visible || props.defaultVisible
    };
    _this.popup = null;
    return _this;
  }

  _createClass(YearPicker, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      if ('value' in nextProps) {
        var value = (0, _util2.formatDateValue)(nextProps.value, nextProps.format || this.props.format);
        this.setState({
          value: value
        });
        this.inputAsString = typeof nextProps.value === 'string';
      }

      if ('visible' in nextProps) {
        this.setState({
          visible: nextProps.visible
        });
      }
    } // 获取底层的overlay实例

  }, {
    key: "render",
    value: function render() {
      var _classnames2,
          _this2 = this;

      var _this$props2 = this.props,
          prefix = _this$props2.prefix,
          rtl = _this$props2.rtl,
          locale = _this$props2.locale,
          label = _this$props2.label,
          state = _this$props2.state,
          format = _this$props2.format,
          disabledDate = _this$props2.disabledDate,
          footerRender = _this$props2.footerRender,
          placeholder = _this$props2.placeholder,
          size = _this$props2.size,
          disabled = _this$props2.disabled,
          hasClear = _this$props2.hasClear,
          popupTriggerType = _this$props2.popupTriggerType,
          popupAlign = _this$props2.popupAlign,
          popupContainer = _this$props2.popupContainer,
          popupStyle = _this$props2.popupStyle,
          popupClassName = _this$props2.popupClassName,
          popupProps = _this$props2.popupProps,
          followTrigger = _this$props2.followTrigger,
          className = _this$props2.className,
          inputProps = _this$props2.inputProps,
          dateInputAriaLabel = _this$props2.dateInputAriaLabel,
          yearCellRender = _this$props2.yearCellRender,
          others = _objectWithoutProperties(_this$props2, ["prefix", "rtl", "locale", "label", "state", "format", "disabledDate", "footerRender", "placeholder", "size", "disabled", "hasClear", "popupTriggerType", "popupAlign", "popupContainer", "popupStyle", "popupClassName", "popupProps", "followTrigger", "className", "inputProps", "dateInputAriaLabel", "yearCellRender"]);

      var _this$state2 = this.state,
          visible = _this$state2.visible,
          value = _this$state2.value,
          dateInputStr = _this$state2.dateInputStr,
          inputing = _this$state2.inputing;
      var yearPickerCls = (0, _classnames4["default"])(_defineProperty({}, "".concat(prefix, "year-picker"), true), className);
      var triggerInputCls = (0, _classnames4["default"])((_classnames2 = {}, _defineProperty(_classnames2, "".concat(prefix, "year-picker-input"), true), _defineProperty(_classnames2, "".concat(prefix, "error"), false), _classnames2));
      var panelBodyClassName = (0, _classnames4["default"])(_defineProperty({}, "".concat(prefix, "year-picker-body"), true));

      if (rtl) {
        others.dir = 'rtl';
      }

      var panelInputCls = "".concat(prefix, "year-picker-panel-input");

      var sharedInputProps = _objectSpread({}, inputProps, {
        size: size,
        disabled: disabled,
        onChange: this.onDateInputChange,
        onBlur: this.onDateInputBlur,
        onPressEnter: this.onDateInputBlur,
        onKeyDown: this.onKeyDown
      });

      var dateInputValue = inputing ? dateInputStr : value && value.format(format) || '';
      var triggerInputValue = dateInputValue;

      var dateInput = _react["default"].createElement(_input["default"], _extends({}, sharedInputProps, {
        hasClear: true,
        size: "xs",
        "aria-label": dateInputAriaLabel,
        value: dateInputValue,
        placeholder: format,
        className: panelInputCls
      }));

      var datePanel = _react["default"].createElement(_calendar["default"], {
        shape: "panel",
        modes: ['year'],
        value: value,
        yearCellRender: yearCellRender,
        onSelect: this.onSelectCalendarPanel,
        disabledDate: disabledDate
      });

      var panelBody = datePanel;
      var panelFooter = footerRender();
      var allowClear = value && hasClear;

      var trigger = _react["default"].createElement("div", {
        className: "".concat(prefix, "year-picker-trigger")
      }, _react["default"].createElement(_input["default"], _extends({}, sharedInputProps, {
        label: label,
        state: state,
        value: triggerInputValue,
        role: "combobox",
        "aria-expanded": visible,
        readOnly: true,
        placeholder: placeholder || locale.yearPlaceholder,
        hint: "calendar",
        hasClear: allowClear,
        className: triggerInputCls
      })));

      return _react["default"].createElement("div", _extends({}, _util.obj.pickOthers(YearPicker.propTypes, others), {
        className: yearPickerCls
      }), _react["default"].createElement(Popup, _extends({
        offset: [0, 4]
      }, popupProps, {
        followTrigger: followTrigger,
        autoFocus: true,
        ref: function ref(popup) {
          _this2.popup = popup;
        },
        disabled: disabled,
        visible: visible,
        onVisibleChange: this.onVisibleChange,
        align: popupAlign,
        triggerType: popupTriggerType,
        container: popupContainer,
        style: popupStyle,
        className: popupClassName,
        trigger: trigger
      }), _react["default"].createElement("div", {
        dir: others.dir,
        className: panelBodyClassName
      }, _react["default"].createElement("div", {
        className: "".concat(prefix, "year-picker-panel-header")
      }, dateInput), panelBody, panelFooter)));
    }
  }]);

  return YearPicker;
}(_react.Component);

_defineProperty(YearPicker, "propTypes", {
  prefix: _propTypes["default"].string,
  rtl: _propTypes["default"].bool,

  /**
   * 输入框内置标签
   */
  label: _propTypes["default"].node,

  /**
   * 输入框状态
   */
  state: _propTypes["default"].oneOf(['success', 'loading', 'error']),

  /**
   * 输入提示
   */
  placeholder: _propTypes["default"].string,

  /**
   * 日期值（受控）moment 对象
   */
  value: _util2.checkDateValue,

  /**
   * 初始日期值，moment 对象
   */
  defaultValue: _util2.checkDateValue,

  /**
   * 日期值的格式（用于限定用户输入和展示）
   */
  format: _propTypes["default"].string,

  /**
   * 禁用日期函数
   * @param {MomentObject} 日期值
   * @param {String} view 当前视图类型，year: 年， month: 月, date: 日
   * @return {Boolean} 是否禁用
   */
  disabledDate: _propTypes["default"].func,

  /**
   * 自定义面板页脚
   * @return {Node} 自定义的面板页脚组件
   */
  footerRender: _propTypes["default"].func,

  /**
   * 日期值改变时的回调
   * @param {MomentObject|String} value 日期值
   */
  onChange: _propTypes["default"].func,

  /**
   * 输入框尺寸
   */
  size: _propTypes["default"].oneOf(['small', 'medium']),

  /**
   * 是否禁用
   */
  disabled: _propTypes["default"].bool,

  /**
   * 是否显示清空按钮
   */
  hasClear: _propTypes["default"].bool,

  /**
   * 弹层显示状态
   */
  visible: _propTypes["default"].bool,

  /**
   * 弹层默认是否显示
   */
  defaultVisible: _propTypes["default"].bool,

  /**
   * 弹层展示状态变化时的回调
   * @param {Boolean} visible 弹层是否显示
   * @param {String} reason 触发弹层显示和隐藏的来源 calendarSelect 表示由日期表盘的选择触发； fromTrigger 表示由trigger的点击触发； docClick 表示由document的点击触发
   */
  onVisibleChange: _propTypes["default"].func,

  /**
   * 弹层触发方式
   */
  popupTriggerType: _propTypes["default"].oneOf(['click', 'hover']),

  /**
   * 弹层对齐方式, 具体含义见 OverLay文档
   */
  popupAlign: _propTypes["default"].string,

  /**
   * 弹层容器
   * @param {Element} target 目标元素
   * @return {Element} 弹层的容器元素
   */
  popupContainer: _propTypes["default"].func,

  /**
   * 弹层自定义样式
   */
  popupStyle: _propTypes["default"].object,

  /**
   * 弹层自定义样式类
   */
  popupClassName: _propTypes["default"].string,

  /**
   * 弹层其他属性
   */
  popupProps: _propTypes["default"].object,

  /**
   * 是否跟随滚动
   */
  followTrigger: _propTypes["default"].bool,

  /**
   * 输入框其他属性
   */
  inputProps: _propTypes["default"].object,
  yearCellRender: _propTypes["default"].func,
  // 兼容 0.x yearCellRender

  /**
   * 日期输入框的 aria-label 属性
   */
  dateInputAriaLabel: _propTypes["default"].string,
  locale: _propTypes["default"].object,
  className: _propTypes["default"].string
});

_defineProperty(YearPicker, "defaultProps", {
  prefix: 'next-',
  rtl: false,
  format: 'YYYY',
  size: 'medium',
  disabledDate: function disabledDate() {
    return false;
  },
  footerRender: function footerRender() {
    return null;
  },
  hasClear: true,
  popupTriggerType: 'click',
  popupAlign: 'tl bl',
  locale: _zhCn["default"].DatePicker,
  onChange: _util.func.noop,
  onVisibleChange: _util.func.noop
});

var _default = YearPicker;
exports["default"] = _default;