UNPKG

@ant-design/compatible

Version:

Ant Design v3 to v4 compatible package

498 lines (399 loc) 22.4 kB
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var React = _interopRequireWildcard(require("react")); var ReactDOM = _interopRequireWildcard(require("react-dom")); var _classnames = _interopRequireDefault(require("classnames")); var _omit = _interopRequireDefault(require("rc-util/lib/omit")); var _antd = require("antd"); var _icons = require("@ant-design/icons"); var _CompatibleConsumer = _interopRequireDefault(require("../CompatibleConsumer")); var _warning = _interopRequireDefault(require("../_util/warning")); var _types = require("../_util/types"); var _constants = require("./constants"); var _context = _interopRequireDefault(require("./context")); var _excluded = ["prefixCls", "style", "className"]; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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 _extends() { _extends = Object.assign ? Object.assign.bind() : 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); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } 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 } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var V5FormItemInputContext = _antd.Form.Item.useStatus.Context; var ValidateStatuses = (0, _types.tuple)('success', 'warning', 'error', 'validating', ''); var FormLabelAligns = (0, _types.tuple)('left', 'right'); var IconMap = { success: _icons.CheckCircleFilled, warning: _icons.ExclamationCircleFilled, error: _icons.CloseCircleFilled, validating: _icons.LoadingOutlined }; function intersperseSpace(list) { return list.reduce(function (current, item) { return [].concat(_toConsumableArray(current), [' ', item]); }, []).slice(1); } var FormItem = /*#__PURE__*/function (_React$Component) { _inherits(FormItem, _React$Component); var _super = _createSuper(FormItem); function FormItem() { var _this; _classCallCheck(this, FormItem); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _super.call.apply(_super, [this].concat(args)); _defineProperty(_assertThisInitialized(_this), "helpShow", false); _defineProperty(_assertThisInitialized(_this), "onLabelClick", function () { var id = _this.props.id || _this.getId(); if (!id) { return; } var formItemNode = ReactDOM.findDOMNode(_assertThisInitialized(_this)); var control = formItemNode.querySelector("[id=\"".concat(id, "\"]")); if (control && control.focus) { control.focus(); } }); _defineProperty(_assertThisInitialized(_this), "renderFormItem", function (_ref) { var _itemClassName; var getPrefixCls = _ref.getPrefixCls; var _this$props = _this.props, customizePrefixCls = _this$props.prefixCls, style = _this$props.style, className = _this$props.className, restProps = _objectWithoutProperties(_this$props, _excluded); var prefixCls = getPrefixCls('legacy-form', customizePrefixCls); var children = _this.renderChildren(prefixCls); var itemClassName = (_itemClassName = {}, _defineProperty(_itemClassName, "".concat(prefixCls, "-item"), true), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-with-help"), _this.helpShow), _defineProperty(_itemClassName, "".concat(className), !!className), _itemClassName); return /*#__PURE__*/React.createElement(_antd.Row, _extends({ className: (0, _classnames.default)(itemClassName), style: style }, (0, _omit.default)(restProps, ['id', // It is deprecated because `htmlFor` is its replacement. 'htmlFor', 'label', 'labelAlign', 'labelCol', 'wrapperCol', 'help', 'extra', 'validateStatus', 'hasFeedback', 'required', 'colon']), { key: "row" }), children); }); return _this; } _createClass(FormItem, [{ key: "componentDidMount", value: function componentDidMount() { var _this$props2 = this.props, children = _this$props2.children, help = _this$props2.help, validateStatus = _this$props2.validateStatus, id = _this$props2.id; (0, _warning.default)(this.getControls(children, true).length <= 1 || help !== undefined || validateStatus !== undefined, 'Form.Item', 'Cannot generate `validateStatus` and `help` automatically, ' + 'while there are more than one `getFieldDecorator` in it.'); (0, _warning.default)(!id, 'Form.Item', '`id` is deprecated for its label `htmlFor`. Please use `htmlFor` directly.'); } }, { key: "getHelpMessage", value: function getHelpMessage() { var help = this.props.help; if (help === undefined && this.getOnlyControl()) { var _this$getField = this.getField(), errors = _this$getField.errors; if (errors) { return intersperseSpace(errors.map(function (e, index) { var node = null; if ( /*#__PURE__*/React.isValidElement(e)) { node = e; } else if ( /*#__PURE__*/React.isValidElement(e.message)) { node = e.message; } // eslint-disable-next-line react/no-array-index-key return node ? /*#__PURE__*/React.cloneElement(node, { key: index }) : e.message; })); } return ''; } return help; } }, { key: "getControls", value: function getControls(children, recursively) { var controls = []; var childrenArray = React.Children.toArray(children); for (var i = 0; i < childrenArray.length; i += 1) { if (!recursively && controls.length > 0) { break; } var child = childrenArray[i]; if (child.type && (child.type === FormItem || child.type.displayName === 'FormItem')) { continue; } if (!child.props) { continue; } if (_constants.FIELD_META_PROP in child.props) { // And means FIELD_DATA_PROP in child.props, too. controls.push(child); } else if (child.props.children) { controls = controls.concat(this.getControls(child.props.children, recursively)); } } return controls; } }, { key: "getOnlyControl", value: function getOnlyControl() { var child = this.getControls(this.props.children, false)[0]; return child !== undefined ? child : null; } }, { key: "getChildProp", value: function getChildProp(prop) { var child = this.getOnlyControl(); return child && child.props && child.props[prop]; } }, { key: "getId", value: function getId() { return this.getChildProp('id'); } }, { key: "getMeta", value: function getMeta() { return this.getChildProp(_constants.FIELD_META_PROP); } }, { key: "getField", value: function getField() { return this.getChildProp(_constants.FIELD_DATA_PROP); } }, { key: "getValidateStatus", value: function getValidateStatus() { var onlyControl = this.getOnlyControl(); if (!onlyControl) { return ''; } var field = this.getField(); if (field.validating) { return 'validating'; } if (field.errors) { return 'error'; } var fieldValue = 'value' in field ? field.value : this.getMeta().initialValue; if (fieldValue !== undefined && fieldValue !== null && fieldValue !== '') { return 'success'; } return ''; } // Resolve duplicated ids bug between different forms // https://github.com/ant-design/ant-design/issues/7351 }, { key: "isRequired", value: // onHelpAnimEnd = (_key: string, helpShow: boolean) => { // this.helpShow = helpShow; // if (!helpShow) { // this.setState({}); // } // }; function isRequired() { var required = this.props.required; if (required !== undefined) { return required; } if (this.getOnlyControl()) { var meta = this.getMeta() || {}; var validate = meta.validate || []; return validate.filter(function (item) { return !!item.rules; }).some(function (item) { return item.rules.some(function (rule) { return rule.required; }); }); } return false; } }, { key: "renderHelp", value: function renderHelp(prefixCls) { var help = this.getHelpMessage(); var children = help ? /*#__PURE__*/React.createElement("div", { className: "".concat(prefixCls, "-explain"), key: "help" }, help) : null; if (children) { this.helpShow = !!children; } return children; // return ( // <Animate // transitionName="show-help" // component="" // transitionAppear // key="help" // onEnd={this.onHelpAnimEnd} // > // {children} // </Animate> // ); } }, { key: "renderExtra", value: function renderExtra(prefixCls) { var extra = this.props.extra; return extra ? /*#__PURE__*/React.createElement("div", { className: "".concat(prefixCls, "-extra") }, extra) : null; } }, { key: "renderValidateWrapper", value: function renderValidateWrapper(prefixCls, c1, c2, c3) { var _this$props3 = this.props, hasFeedback = _this$props3.hasFeedback, validateStatus = _this$props3.validateStatus; var onlyControl = this.getOnlyControl; var mergedValidateStatus = validateStatus === undefined && onlyControl ? this.getValidateStatus() : validateStatus; var classes = "".concat(prefixCls, "-item-control"); if (mergedValidateStatus) { classes = (0, _classnames.default)("".concat(prefixCls, "-item-control"), { 'has-feedback': hasFeedback || mergedValidateStatus === 'validating', 'has-success': mergedValidateStatus === 'success', 'has-warning': mergedValidateStatus === 'warning', 'has-error': mergedValidateStatus === 'error', 'is-validating': mergedValidateStatus === 'validating' }); } // let iconType: React.ReactNode = null; // switch (validateStatus) { // case 'success': // iconType = <CheckCircleFilled />; // break; // case 'warning': // iconType = <ExclamationCircleFilled />; // break; // case 'error': // iconType = <CloseCircleFilled />; // break; // case 'validating': // iconType = <LoadingOutlined />; // break; // default: // break; // } // const icon = // props.hasFeedback && iconType ? ( // <span className={`${prefixCls}-item-children-icon`}>{iconType}</span> // ) : null; // ========================== Feedback ========================== var IconComponent = mergedValidateStatus && IconMap[mergedValidateStatus]; var feedbackIcon = IconComponent ? /*#__PURE__*/React.createElement("span", { className: (0, _classnames.default)("".concat(prefixCls, "-item-feedback-icon"), "".concat(prefixCls, "-item-feedback-icon-").concat(mergedValidateStatus)) }, /*#__PURE__*/React.createElement(IconComponent, null)) : null; return /*#__PURE__*/React.createElement("div", { className: classes }, /*#__PURE__*/React.createElement("span", { className: "".concat(prefixCls, "-item-children") }, /*#__PURE__*/React.createElement(V5FormItemInputContext.Provider, { value: { status: mergedValidateStatus, feedbackIcon: feedbackIcon, hasFeedback: hasFeedback, isFormItemInput: true } }, c1)), c2, c3); } }, { key: "renderWrapper", value: function renderWrapper(prefixCls, children) { var _this2 = this; return /*#__PURE__*/React.createElement(_context.default.Consumer, { key: "wrapper" }, function (_ref2) { var contextWrapperCol = _ref2.wrapperCol, vertical = _ref2.vertical; var wrapperCol = _this2.props.wrapperCol; var mergedWrapperCol = ('wrapperCol' in _this2.props ? wrapperCol : contextWrapperCol) || {}; var className = (0, _classnames.default)("".concat(prefixCls, "-item-control-wrapper"), mergedWrapperCol.className); // No pass FormContext since it's useless return /*#__PURE__*/React.createElement(_context.default.Provider, { value: { vertical: vertical } }, /*#__PURE__*/React.createElement(_antd.Col, _extends({}, mergedWrapperCol, { className: className }), children)); }); } }, { key: "renderLabel", value: function renderLabel(prefixCls) { var _this3 = this; return /*#__PURE__*/React.createElement(_context.default.Consumer, { key: "label" }, function (_ref3) { var _classNames; var vertical = _ref3.vertical, contextLabelAlign = _ref3.labelAlign, contextLabelCol = _ref3.labelCol, contextColon = _ref3.colon; var _this3$props = _this3.props, label = _this3$props.label, labelCol = _this3$props.labelCol, labelAlign = _this3$props.labelAlign, colon = _this3$props.colon, id = _this3$props.id, htmlFor = _this3$props.htmlFor; var required = _this3.isRequired(); var mergedLabelCol = ('labelCol' in _this3.props ? labelCol : contextLabelCol) || {}; var mergedLabelAlign = 'labelAlign' in _this3.props ? labelAlign : contextLabelAlign; var labelClsBasic = "".concat(prefixCls, "-item-label"); var labelColClassName = (0, _classnames.default)(labelClsBasic, mergedLabelAlign === 'left' && "".concat(labelClsBasic, "-left"), mergedLabelCol.className); var labelChildren = label; // Keep label is original where there should have no colon var computedColon = colon === true || contextColon !== false && colon !== false; var haveColon = computedColon && !vertical; // Remove duplicated user input colon if (haveColon && typeof label === 'string' && label.trim() !== '') { labelChildren = label.replace(/[::]\s*$/, ''); } var labelClassName = (0, _classnames.default)((_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-item-required"), required), _defineProperty(_classNames, "".concat(prefixCls, "-item-no-colon"), !computedColon), _classNames)); return label ? /*#__PURE__*/React.createElement(_antd.Col, _extends({}, mergedLabelCol, { className: labelColClassName }), /*#__PURE__*/React.createElement("label", { htmlFor: htmlFor || id || _this3.getId(), className: labelClassName, title: typeof label === 'string' ? label : '', onClick: _this3.onLabelClick }, labelChildren)) : null; }); } }, { key: "renderChildren", value: function renderChildren(prefixCls) { var children = this.props.children; return [this.renderLabel(prefixCls), this.renderWrapper(prefixCls, this.renderValidateWrapper(prefixCls, children, this.renderHelp(prefixCls), this.renderExtra(prefixCls)))]; } }, { key: "render", value: function render() { return /*#__PURE__*/React.createElement(_CompatibleConsumer.default, null, this.renderFormItem); } }]); return FormItem; }(React.Component); exports.default = FormItem; _defineProperty(FormItem, "defaultProps", { hasFeedback: false });