Picker.js 14.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";

/**
 * Removed:
 *  - getCalendarContainer: use `getPopupContainer` instead
 *  - onOk
 *
 * New Feature:
 *  - picker
 *  - allowEmpty
 *  - selectable
 *
 * Tips: Should add faq about `datetime` mode with `defaultValue`
 */
import * as React from 'react';
import classNames from 'classnames';
import warning from "rc-util/es/warning";
import useMergedState from "rc-util/es/hooks/useMergedState";
import PickerPanel from './PickerPanel';
import PickerTrigger from './PickerTrigger';
import { formatValue, isEqual, parseValue } from './utils/dateUtil';
import getDataOrAriaProps, { toArray } from './utils/miscUtil';
import PanelContext from './PanelContext';
import { getDefaultFormat, getInputSize, elementsContains } from './utils/uiUtil';
import usePickerInput from './hooks/usePickerInput';
import useTextValueMapping from './hooks/useTextValueMapping';
import useValueTexts from './hooks/useValueTexts';
import useHoverValue from './hooks/useHoverValue';

function InnerPicker(props) {
  var _classNames2;

  var _props$prefixCls = props.prefixCls,
      prefixCls = _props$prefixCls === void 0 ? 'rc-picker' : _props$prefixCls,
      id = props.id,
      tabIndex = props.tabIndex,
      style = props.style,
      className = props.className,
      dropdownClassName = props.dropdownClassName,
      dropdownAlign = props.dropdownAlign,
      popupStyle = props.popupStyle,
      transitionName = props.transitionName,
      generateConfig = props.generateConfig,
      locale = props.locale,
      inputReadOnly = props.inputReadOnly,
      allowClear = props.allowClear,
      autoFocus = props.autoFocus,
      showTime = props.showTime,
      _props$picker = props.picker,
      picker = _props$picker === void 0 ? 'date' : _props$picker,
      format = props.format,
      use12Hours = props.use12Hours,
      value = props.value,
      defaultValue = props.defaultValue,
      open = props.open,
      defaultOpen = props.defaultOpen,
      defaultOpenValue = props.defaultOpenValue,
      suffixIcon = props.suffixIcon,
      clearIcon = props.clearIcon,
      disabled = props.disabled,
      disabledDate = props.disabledDate,
      placeholder = props.placeholder,
      getPopupContainer = props.getPopupContainer,
      pickerRef = props.pickerRef,
      panelRender = props.panelRender,
      onChange = props.onChange,
      onOpenChange = props.onOpenChange,
      onFocus = props.onFocus,
      onBlur = props.onBlur,
      onMouseDown = props.onMouseDown,
      onMouseUp = props.onMouseUp,
      onMouseEnter = props.onMouseEnter,
      onMouseLeave = props.onMouseLeave,
      onContextMenu = props.onContextMenu,
      onClick = props.onClick,
      _onSelect = props.onSelect,
      direction = props.direction,
      _props$autoComplete = props.autoComplete,
      autoComplete = _props$autoComplete === void 0 ? 'off' : _props$autoComplete;
  var inputRef = React.useRef(null);
  var needConfirmButton = picker === 'date' && !!showTime || picker === 'time'; // ============================= State =============================

  var formatList = toArray(getDefaultFormat(format, picker, showTime, use12Hours)); // Panel ref

  var panelDivRef = React.useRef(null);
  var inputDivRef = React.useRef(null); // Real value

  var _useMergedState = useMergedState(null, {
    value: value,
    defaultValue: defaultValue
  }),
      _useMergedState2 = _slicedToArray(_useMergedState, 2),
      mergedValue = _useMergedState2[0],
      setInnerValue = _useMergedState2[1]; // Selected value


  var _React$useState = React.useState(mergedValue),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      selectedValue = _React$useState2[0],
      setSelectedValue = _React$useState2[1]; // Operation ref


  var operationRef = React.useRef(null); // Open

  var _useMergedState3 = useMergedState(false, {
    value: open,
    defaultValue: defaultOpen,
    postState: function postState(postOpen) {
      return disabled ? false : postOpen;
    },
    onChange: function onChange(newOpen) {
      if (onOpenChange) {
        onOpenChange(newOpen);
      }

      if (!newOpen && operationRef.current && operationRef.current.onClose) {
        operationRef.current.onClose();
      }
    }
  }),
      _useMergedState4 = _slicedToArray(_useMergedState3, 2),
      mergedOpen = _useMergedState4[0],
      triggerInnerOpen = _useMergedState4[1]; // ============================= Text ==============================


  var _useValueTexts = useValueTexts(selectedValue, {
    formatList: formatList,
    generateConfig: generateConfig,
    locale: locale
  }),
      _useValueTexts2 = _slicedToArray(_useValueTexts, 2),
      valueTexts = _useValueTexts2[0],
      firstValueText = _useValueTexts2[1];

  var _useTextValueMapping = useTextValueMapping({
    valueTexts: valueTexts,
    onTextChange: function onTextChange(newText) {
      var inputDate = parseValue(newText, {
        locale: locale,
        formatList: formatList,
        generateConfig: generateConfig
      });

      if (inputDate && (!disabledDate || !disabledDate(inputDate))) {
        setSelectedValue(inputDate);
      }
    }
  }),
      _useTextValueMapping2 = _slicedToArray(_useTextValueMapping, 3),
      text = _useTextValueMapping2[0],
      triggerTextChange = _useTextValueMapping2[1],
      resetText = _useTextValueMapping2[2]; // ============================ Trigger ============================


  var triggerChange = function triggerChange(newValue) {
    setSelectedValue(newValue);
    setInnerValue(newValue);

    if (onChange && !isEqual(generateConfig, mergedValue, newValue)) {
      onChange(newValue, newValue ? formatValue(newValue, {
        generateConfig: generateConfig,
        locale: locale,
        format: formatList[0]
      }) : '');
    }
  };

  var triggerOpen = function triggerOpen(newOpen) {
    if (disabled && newOpen) {
      return;
    }

    triggerInnerOpen(newOpen);
  };

  var forwardKeyDown = function forwardKeyDown(e) {
    if (mergedOpen && operationRef.current && operationRef.current.onKeyDown) {
      // Let popup panel handle keyboard
      return operationRef.current.onKeyDown(e);
    }
    /* istanbul ignore next */

    /* eslint-disable no-lone-blocks */


    {
      warning(false, 'Picker not correct forward KeyDown operation. Please help to fire issue about this.');
      return false;
    }
  };

  var onInternalMouseUp = function onInternalMouseUp() {
    if (onMouseUp) {
      onMouseUp.apply(void 0, arguments);
    }

    if (inputRef.current) {
      inputRef.current.focus();
      triggerOpen(true);
    }
  }; // ============================= Input =============================


  var _usePickerInput = usePickerInput({
    blurToCancel: needConfirmButton,
    open: mergedOpen,
    value: text,
    triggerOpen: triggerOpen,
    forwardKeyDown: forwardKeyDown,
    isClickOutside: function isClickOutside(target) {
      return !elementsContains([panelDivRef.current, inputDivRef.current], target);
    },
    onSubmit: function onSubmit() {
      if (disabledDate && disabledDate(selectedValue)) {
        return false;
      }

      triggerChange(selectedValue);
      triggerOpen(false);
      resetText();
      return true;
    },
    onCancel: function onCancel() {
      triggerOpen(false);
      setSelectedValue(mergedValue);
      resetText();
    },
    onFocus: onFocus,
    onBlur: onBlur
  }),
      _usePickerInput2 = _slicedToArray(_usePickerInput, 2),
      inputProps = _usePickerInput2[0],
      _usePickerInput2$ = _usePickerInput2[1],
      focused = _usePickerInput2$.focused,
      typing = _usePickerInput2$.typing; // ============================= Sync ==============================
  // Close should sync back with text value


  React.useEffect(function () {
    if (!mergedOpen) {
      setSelectedValue(mergedValue);

      if (!valueTexts.length || valueTexts[0] === '') {
        triggerTextChange('');
      } else if (firstValueText !== text) {
        resetText();
      }
    }
  }, [mergedOpen, valueTexts]); // Change picker should sync back with text value

  React.useEffect(function () {
    if (!mergedOpen) {
      resetText();
    }
  }, [picker]); // Sync innerValue with control mode

  React.useEffect(function () {
    // Sync select value
    setSelectedValue(mergedValue);
  }, [mergedValue]); // ============================ Private ============================

  if (pickerRef) {
    pickerRef.current = {
      focus: function focus() {
        if (inputRef.current) {
          inputRef.current.focus();
        }
      },
      blur: function blur() {
        if (inputRef.current) {
          inputRef.current.blur();
        }
      }
    };
  } // ============================= Panel =============================


  var panelProps = _objectSpread(_objectSpread({}, props), {}, {
    className: undefined,
    style: undefined,
    pickerValue: undefined,
    onPickerValueChange: undefined,
    onChange: null
  });

  var panelNode = /*#__PURE__*/React.createElement(PickerPanel, Object.assign({}, panelProps, {
    generateConfig: generateConfig,
    className: classNames(_defineProperty({}, "".concat(prefixCls, "-panel-focused"), !typing)),
    value: selectedValue,
    locale: locale,
    tabIndex: -1,
    onSelect: function onSelect(date) {
      _onSelect === null || _onSelect === void 0 ? void 0 : _onSelect(date);
      setSelectedValue(date);
    },
    direction: direction
  }));

  if (panelRender) {
    panelNode = panelRender(panelNode);
  }

  var panel = /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-panel-container"),
    onMouseDown: function onMouseDown(e) {
      e.preventDefault();
    }
  }, panelNode);
  var suffixNode;

  if (suffixIcon) {
    suffixNode = /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-suffix")
    }, suffixIcon);
  }

  var clearNode;

  if (allowClear && mergedValue && !disabled) {
    clearNode = /*#__PURE__*/React.createElement("span", {
      onMouseDown: function onMouseDown(e) {
        e.preventDefault();
        e.stopPropagation();
      },
      onMouseUp: function onMouseUp(e) {
        e.preventDefault();
        e.stopPropagation();
        triggerChange(null);
        triggerOpen(false);
      },
      className: "".concat(prefixCls, "-clear")
    }, clearIcon || /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-clear-btn")
    }));
  } // ============================ Warning ============================


  if (process.env.NODE_ENV !== 'production') {
    warning(!defaultOpenValue, '`defaultOpenValue` may confuse user for the current value status. Please use `defaultValue` instead.');
  } // ============================ Return =============================


  var onContextSelect = function onContextSelect(date, type) {
    if (type === 'submit' || type !== 'key' && !needConfirmButton) {
      // triggerChange will also update selected values
      triggerChange(date);
      triggerOpen(false);
    }
  };

  var popupPlacement = direction === 'rtl' ? 'bottomRight' : 'bottomLeft';

  var _useHoverValue = useHoverValue(text, {
    formatList: formatList,
    generateConfig: generateConfig,
    locale: locale
  }),
      _useHoverValue2 = _slicedToArray(_useHoverValue, 3),
      hoverValue = _useHoverValue2[0],
      onEnter = _useHoverValue2[1],
      onLeave = _useHoverValue2[2];

  return /*#__PURE__*/React.createElement(PanelContext.Provider, {
    value: {
      operationRef: operationRef,
      hideHeader: picker === 'time',
      panelRef: panelDivRef,
      onSelect: onContextSelect,
      open: mergedOpen,
      defaultOpenValue: defaultOpenValue,
      onDateMouseEnter: onEnter,
      onDateMouseLeave: onLeave
    }
  }, /*#__PURE__*/React.createElement(PickerTrigger, {
    visible: mergedOpen,
    popupElement: panel,
    popupStyle: popupStyle,
    prefixCls: prefixCls,
    dropdownClassName: dropdownClassName,
    dropdownAlign: dropdownAlign,
    getPopupContainer: getPopupContainer,
    transitionName: transitionName,
    popupPlacement: popupPlacement,
    direction: direction
  }, /*#__PURE__*/React.createElement("div", {
    className: classNames(prefixCls, className, (_classNames2 = {}, _defineProperty(_classNames2, "".concat(prefixCls, "-disabled"), disabled), _defineProperty(_classNames2, "".concat(prefixCls, "-focused"), focused), _defineProperty(_classNames2, "".concat(prefixCls, "-rtl"), direction === 'rtl'), _classNames2)),
    style: style,
    onMouseDown: onMouseDown,
    onMouseUp: onInternalMouseUp,
    onMouseEnter: onMouseEnter,
    onMouseLeave: onMouseLeave,
    onContextMenu: onContextMenu,
    onClick: onClick
  }, /*#__PURE__*/React.createElement("div", {
    className: classNames("".concat(prefixCls, "-input"), _defineProperty({}, "".concat(prefixCls, "-input-placeholder"), !!hoverValue)),
    ref: inputDivRef
  }, /*#__PURE__*/React.createElement("input", Object.assign({
    id: id,
    tabIndex: tabIndex,
    disabled: disabled,
    readOnly: inputReadOnly || typeof formatList[0] === 'function' || !typing,
    value: hoverValue || text,
    onChange: function onChange(e) {
      triggerTextChange(e.target.value);
    },
    autoFocus: autoFocus,
    placeholder: placeholder,
    ref: inputRef,
    title: text
  }, inputProps, {
    size: getInputSize(picker, formatList[0], generateConfig)
  }, getDataOrAriaProps(props), {
    autoComplete: autoComplete
  })), suffixNode, clearNode))));
} // Wrap with class component to enable pass generic with instance method


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

  var _super = _createSuper(Picker);

  function Picker() {
    var _this;

    _classCallCheck(this, Picker);

    _this = _super.apply(this, arguments);
    _this.pickerRef = /*#__PURE__*/React.createRef();

    _this.focus = function () {
      if (_this.pickerRef.current) {
        _this.pickerRef.current.focus();
      }
    };

    _this.blur = function () {
      if (_this.pickerRef.current) {
        _this.pickerRef.current.blur();
      }
    };

    return _this;
  }

  _createClass(Picker, [{
    key: "render",
    value: function render() {
      return /*#__PURE__*/React.createElement(InnerPicker, Object.assign({}, this.props, {
        pickerRef: this.pickerRef
      }));
    }
  }]);

  return Picker;
}(React.Component);

export default Picker;