"use strict";

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

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

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

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

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

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

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

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

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

var _panel = _interopRequireDefault(require("./panel"));

var _utils = require("./utils");

var _util2 = require("../date-picker/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 _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;
var noop = _util.func.noop;
var timePickerLocale = _zhCn["default"].TimePicker;
/**
 * TimePicker
 */

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

  function TimePicker(props, context) {
    var _this;

    _classCallCheck(this, TimePicker);

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

    _defineProperty(_assertThisInitialized(_this), "onClearValue", function () {
      _this.setState({
        value: null
      });

      if (_this.state.value) {
        _this.onValueChange(null);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onInputChange", function (inputValue, e, eventType) {
      if (!('value' in _this.props)) {
        if (eventType === 'clear' || !inputValue) {
          e.stopPropagation();

          _this.onClearValue();
        }

        _this.setState({
          inputStr: inputValue,
          inputing: true
        });
      } else if (eventType === 'clear') {
        // 受控状态下用户点击 clear
        e.stopPropagation();

        _this.onValueChange(null);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onInputBlur", function () {
      var _this$state = _this.state,
          value = _this$state.value,
          inputStr = _this$state.inputStr;

      if (!value && inputStr) {
        var format = _this.props.format;
        var parsed = (0, _moment["default"])(inputStr, format, true);

        if (parsed.isValid()) {
          _this.setState({
            value: parsed,
            inputStr: ''
          });

          _this.onValueChange(parsed);
        }

        _this.setState({
          inputing: false
        });
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onKeyown", function (e) {
      var _this$state2 = _this.state,
          value = _this$state2.value,
          inputStr = _this$state2.inputStr;
      var _this$props = _this.props,
          format = _this$props.format,
          _this$props$hourStep = _this$props.hourStep,
          hourStep = _this$props$hourStep === void 0 ? 1 : _this$props$hourStep,
          _this$props$minuteSte = _this$props.minuteStep,
          minuteStep = _this$props$minuteSte === void 0 ? 1 : _this$props$minuteSte,
          _this$props$secondSte = _this$props.secondStep,
          secondStep = _this$props$secondSte === void 0 ? 1 : _this$props$secondSte,
          disabledMinutes = _this$props.disabledMinutes,
          disabledSeconds = _this$props.disabledSeconds;
      var unit = 'second';

      if (disabledSeconds) {
        unit = disabledMinutes ? 'hour' : 'minute';
      }

      var timeStr = (0, _util2.onTimeKeydown)(e, {
        format: format,
        timeInputStr: inputStr,
        steps: {
          hour: hourStep,
          minute: minuteStep,
          second: secondStep
        },
        value: value
      }, unit);
      if (!timeStr) return;

      _this.onInputChange(timeStr);
    });

    _defineProperty(_assertThisInitialized(_this), "onTimePanelSelect", function (value) {
      if (!('value' in _this.props)) {
        _this.setState({
          value: value,
          inputing: false
        });
      }

      if (!_this.state.value || value.valueOf() !== _this.state.value.valueOf()) {
        _this.onValueChange(value);
      }
    });

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

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

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

    _this.inputAsString = typeof (props.value || props.defaultValue) === 'string';
    _this.state = {
      value: _value,
      inputStr: '',
      inputing: false,
      visible: props.visible || props.defaultVisible
    };
    return _this;
  }

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

      if ('visible' in nextProps) {
        this.setState({
          visible: nextProps.visible
        });
      }
    }
  }, {
    key: "onValueChange",
    value: function onValueChange(newValue) {
      var ret = this.inputAsString && newValue ? newValue.format(this.props.format) : newValue;
      this.props.onChange(ret);
    }
  }, {
    key: "render",
    value: function render() {
      var _classnames2;

      var _this$props2 = this.props,
          prefix = _this$props2.prefix,
          label = _this$props2.label,
          state = _this$props2.state,
          placeholder = _this$props2.placeholder,
          size = _this$props2.size,
          format = _this$props2.format,
          hasClear = _this$props2.hasClear,
          hourStep = _this$props2.hourStep,
          minuteStep = _this$props2.minuteStep,
          secondStep = _this$props2.secondStep,
          disabledHours = _this$props2.disabledHours,
          disabledMinutes = _this$props2.disabledMinutes,
          disabledSeconds = _this$props2.disabledSeconds,
          popupAlign = _this$props2.popupAlign,
          popupTriggerType = _this$props2.popupTriggerType,
          popupContainer = _this$props2.popupContainer,
          popupStyle = _this$props2.popupStyle,
          popupClassName = _this$props2.popupClassName,
          popupProps = _this$props2.popupProps,
          followTrigger = _this$props2.followTrigger,
          disabled = _this$props2.disabled,
          className = _this$props2.className,
          style = _this$props2.style,
          locale = _this$props2.locale,
          rtl = _this$props2.rtl,
          others = _objectWithoutProperties(_this$props2, ["prefix", "label", "state", "placeholder", "size", "format", "hasClear", "hourStep", "minuteStep", "secondStep", "disabledHours", "disabledMinutes", "disabledSeconds", "popupAlign", "popupTriggerType", "popupContainer", "popupStyle", "popupClassName", "popupProps", "followTrigger", "disabled", "className", "style", "locale", "rtl"]);

      var _this$state3 = this.state,
          value = _this$state3.value,
          inputStr = _this$state3.inputStr,
          inputing = _this$state3.inputing,
          visible = _this$state3.visible;
      var triggerCls = (0, _classnames3["default"])(_defineProperty({}, "".concat(prefix, "time-picker-trigger"), true));

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

      var inputValue = inputing ? inputStr : value && value.format(format) || '';
      var sharedInputProps = {
        disabled: disabled,
        value: inputValue,
        onChange: this.onInputChange,
        onBlur: this.onInputBlur,
        onPressEnter: this.onInputBlur,
        onKeyDown: this.onKeyown
      };

      var triggerInput = _react["default"].createElement("div", {
        className: triggerCls
      }, _react["default"].createElement(_input["default"], _extends({}, sharedInputProps, {
        size: size,
        hint: "clock",
        hasClear: hasClear,
        label: label,
        state: state,
        placeholder: placeholder || locale.placeholder,
        className: "".concat(prefix, "time-picker-input")
      })));

      var panelProps = {
        prefix: prefix,
        locale: locale,
        value: value,
        disabled: disabled,
        showHour: format.indexOf('H') > -1,
        showSecond: format.indexOf('s') > -1,
        hourStep: hourStep,
        minuteStep: minuteStep,
        secondStep: secondStep,
        disabledHours: disabledHours,
        disabledMinutes: disabledMinutes,
        disabledSeconds: disabledSeconds,
        onSelect: this.onTimePanelSelect
      };
      var classNames = (0, _classnames3["default"])((_classnames2 = {}, _defineProperty(_classnames2, "".concat(prefix, "time-picker"), true), _defineProperty(_classnames2, "".concat(prefix, "time-picker-").concat(size), size), _defineProperty(_classnames2, "".concat(prefix, "disabled"), disabled), _classnames2), className);
      return _react["default"].createElement("div", _extends({}, _util.obj.pickOthers(TimePicker.propTypes, others), {
        className: classNames,
        tabIndex: disabled ? null : 0,
        style: style
      }), _react["default"].createElement(Popup, _extends({}, popupProps, {
        offset: [0, 4],
        followTrigger: followTrigger,
        autoFocus: true,
        visible: visible,
        onVisibleChange: this.onVisibleChange,
        trigger: triggerInput,
        container: popupContainer,
        disabled: disabled,
        align: popupAlign,
        triggerType: popupTriggerType,
        style: popupStyle,
        className: popupClassName
      }), _react["default"].createElement("div", {
        dir: others.dir,
        className: "".concat(prefix, "time-picker-body")
      }, _react["default"].createElement("div", {
        className: "".concat(prefix, "time-picker-panel-header")
      }, _react["default"].createElement(_input["default"], _extends({}, sharedInputProps, {
        size: "xs",
        placeholder: format,
        className: "".concat(prefix, "time-picker-panel-input")
      }))), _react["default"].createElement(_panel["default"], panelProps))));
    }
  }]);

  return TimePicker;
}(_react.Component);

exports["default"] = TimePicker;

_defineProperty(TimePicker, "displayName", 'TimePicker');

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

  /**
   * 按钮的文案
   */
  label: _propTypes["default"].node,

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

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

  /**
   * 时间值（moment 对象或时间字符串，受控状态使用）
   */
  value: _utils.checkDateValue,

  /**
   * 时间初值（moment 对象或时间字符串，非受控状态使用）
   */
  defaultValue: _utils.checkDateValue,

  /**
   * 时间选择框的尺寸
   */
  size: _propTypes["default"].oneOf(['small', 'medium']),

  /**
   * 是否允许清空时间
   */
  hasClear: _propTypes["default"].bool,

  /**
   * 时间的格式
   * https://momentjs.com/docs/#/parsing/string-format/
   */
  format: _propTypes["default"].string,

  /**
   * 小时选项步长
   */
  hourStep: _propTypes["default"].number,

  /**
   * 分钟选项步长
   */
  minuteStep: _propTypes["default"].number,

  /**
   * 秒钟选项步长
   */
  secondStep: _propTypes["default"].number,

  /**
   * 禁用小时函数
   * @param {Number} index 时 0 - 23
   * @return {Boolean} 是否禁用
   */
  disabledHours: _propTypes["default"].func,

  /**
   * 禁用分钟函数
   * @param {Number} index 分 0 - 59
   * @return {Boolean} 是否禁用
   */
  disabledMinutes: _propTypes["default"].func,

  /**
   * 禁用秒钟函数
   * @param {Number} index 秒 0 - 59
   * @return {Boolean} 是否禁用
   */
  disabledSeconds: _propTypes["default"].func,

  /**
   * 弹层是否显示（受控）
   */
  visible: _propTypes["default"].bool,

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

  /**
   * 弹层容器
   * @param {Object} target 目标节点
   * @return {ReactNode} 容器节点
   */
  popupContainer: _propTypes["default"].func,

  /**
   * 弹层对齐方式, 详情见Overlay 文档
   */
  popupAlign: _propTypes["default"].string,

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

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

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

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

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

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

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

  /**
   * 时间值改变时的回调
   * @param {Object|String} value 时间对象或时间字符串
   */
  onChange: _propTypes["default"].func,
  className: _propTypes["default"].string,
  style: _propTypes["default"].object
});

_defineProperty(TimePicker, "defaultProps", {
  prefix: 'next-',
  rtl: false,
  locale: timePickerLocale,
  size: 'medium',
  format: 'HH:mm:ss',
  hasClear: true,
  disabled: false,
  popupAlign: 'tl bl',
  popupTriggerType: 'click',
  onChange: noop,
  onVisibleChange: noop
});