UNPKG

20.8 kBJavaScriptView Raw
1function _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); }
2
3var _excluded = ["prefixCls", "style", "className"];
4
5function _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); }
6
7function _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; }
8
9function _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; }
10
11function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
12
13function _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); } }
14
15function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
16
17function _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); }
18
19function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
20
21function _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); }; }
22
23function _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); }
24
25function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
26
27function _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; } }
28
29function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
30
31function _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; }
32
33function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
34
35function _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."); }
36
37function _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); }
38
39function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
40
41function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
42
43function _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; }
44
45/* eslint-disable react/no-find-dom-node */
46import * as React from 'react';
47import * as ReactDOM from 'react-dom';
48import classNames from 'classnames'; // import Animate from 'rc-animate';
49
50import omit from "rc-util/es/omit";
51import { Row, Col, Form as V5Form } from 'antd';
52import { CheckCircleFilled, CloseCircleFilled, ExclamationCircleFilled, LoadingOutlined } from '@ant-design/icons';
53import CompatibleConsumer from "../CompatibleConsumer";
54import warning from "../_util/warning";
55import { tuple } from "../_util/types";
56import { FIELD_META_PROP, FIELD_DATA_PROP } from "./constants";
57import FormContext from "./context";
58var V5FormItemInputContext = V5Form.Item.useStatus.Context;
59var ValidateStatuses = tuple('success', 'warning', 'error', 'validating', '');
60var FormLabelAligns = tuple('left', 'right');
61var IconMap = {
62 success: CheckCircleFilled,
63 warning: ExclamationCircleFilled,
64 error: CloseCircleFilled,
65 validating: LoadingOutlined
66};
67
68function intersperseSpace(list) {
69 return list.reduce(function (current, item) {
70 return [].concat(_toConsumableArray(current), [' ', item]);
71 }, []).slice(1);
72}
73
74var FormItem = /*#__PURE__*/function (_React$Component) {
75 _inherits(FormItem, _React$Component);
76
77 var _super = _createSuper(FormItem);
78
79 function FormItem() {
80 var _this;
81
82 _classCallCheck(this, FormItem);
83
84 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
85 args[_key] = arguments[_key];
86 }
87
88 _this = _super.call.apply(_super, [this].concat(args));
89
90 _defineProperty(_assertThisInitialized(_this), "helpShow", false);
91
92 _defineProperty(_assertThisInitialized(_this), "onLabelClick", function () {
93 var id = _this.props.id || _this.getId();
94
95 if (!id) {
96 return;
97 }
98
99 var formItemNode = ReactDOM.findDOMNode(_assertThisInitialized(_this));
100 var control = formItemNode.querySelector("[id=\"".concat(id, "\"]"));
101
102 if (control && control.focus) {
103 control.focus();
104 }
105 });
106
107 _defineProperty(_assertThisInitialized(_this), "renderFormItem", function (_ref) {
108 var _itemClassName;
109
110 var getPrefixCls = _ref.getPrefixCls;
111
112 var _this$props = _this.props,
113 customizePrefixCls = _this$props.prefixCls,
114 style = _this$props.style,
115 className = _this$props.className,
116 restProps = _objectWithoutProperties(_this$props, _excluded);
117
118 var prefixCls = getPrefixCls('legacy-form', customizePrefixCls);
119
120 var children = _this.renderChildren(prefixCls);
121
122 var itemClassName = (_itemClassName = {}, _defineProperty(_itemClassName, "".concat(prefixCls, "-item"), true), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-with-help"), _this.helpShow), _defineProperty(_itemClassName, "".concat(className), !!className), _itemClassName);
123 return /*#__PURE__*/React.createElement(Row, _extends({
124 className: classNames(itemClassName),
125 style: style
126 }, omit(restProps, ['id', // It is deprecated because `htmlFor` is its replacement.
127 'htmlFor', 'label', 'labelAlign', 'labelCol', 'wrapperCol', 'help', 'extra', 'validateStatus', 'hasFeedback', 'required', 'colon']), {
128 key: "row"
129 }), children);
130 });
131
132 return _this;
133 }
134
135 _createClass(FormItem, [{
136 key: "componentDidMount",
137 value: function componentDidMount() {
138 var _this$props2 = this.props,
139 children = _this$props2.children,
140 help = _this$props2.help,
141 validateStatus = _this$props2.validateStatus,
142 id = _this$props2.id;
143 warning(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.');
144 warning(!id, 'Form.Item', '`id` is deprecated for its label `htmlFor`. Please use `htmlFor` directly.');
145 }
146 }, {
147 key: "getHelpMessage",
148 value: function getHelpMessage() {
149 var help = this.props.help;
150
151 if (help === undefined && this.getOnlyControl()) {
152 var _this$getField = this.getField(),
153 errors = _this$getField.errors;
154
155 if (errors) {
156 return intersperseSpace(errors.map(function (e, index) {
157 var node = null;
158
159 if ( /*#__PURE__*/React.isValidElement(e)) {
160 node = e;
161 } else if ( /*#__PURE__*/React.isValidElement(e.message)) {
162 node = e.message;
163 } // eslint-disable-next-line react/no-array-index-key
164
165
166 return node ? /*#__PURE__*/React.cloneElement(node, {
167 key: index
168 }) : e.message;
169 }));
170 }
171
172 return '';
173 }
174
175 return help;
176 }
177 }, {
178 key: "getControls",
179 value: function getControls(children, recursively) {
180 var controls = [];
181 var childrenArray = React.Children.toArray(children);
182
183 for (var i = 0; i < childrenArray.length; i += 1) {
184 if (!recursively && controls.length > 0) {
185 break;
186 }
187
188 var child = childrenArray[i];
189
190 if (child.type && (child.type === FormItem || child.type.displayName === 'FormItem')) {
191 continue;
192 }
193
194 if (!child.props) {
195 continue;
196 }
197
198 if (FIELD_META_PROP in child.props) {
199 // And means FIELD_DATA_PROP in child.props, too.
200 controls.push(child);
201 } else if (child.props.children) {
202 controls = controls.concat(this.getControls(child.props.children, recursively));
203 }
204 }
205
206 return controls;
207 }
208 }, {
209 key: "getOnlyControl",
210 value: function getOnlyControl() {
211 var child = this.getControls(this.props.children, false)[0];
212 return child !== undefined ? child : null;
213 }
214 }, {
215 key: "getChildProp",
216 value: function getChildProp(prop) {
217 var child = this.getOnlyControl();
218 return child && child.props && child.props[prop];
219 }
220 }, {
221 key: "getId",
222 value: function getId() {
223 return this.getChildProp('id');
224 }
225 }, {
226 key: "getMeta",
227 value: function getMeta() {
228 return this.getChildProp(FIELD_META_PROP);
229 }
230 }, {
231 key: "getField",
232 value: function getField() {
233 return this.getChildProp(FIELD_DATA_PROP);
234 }
235 }, {
236 key: "getValidateStatus",
237 value: function getValidateStatus() {
238 var onlyControl = this.getOnlyControl();
239
240 if (!onlyControl) {
241 return '';
242 }
243
244 var field = this.getField();
245
246 if (field.validating) {
247 return 'validating';
248 }
249
250 if (field.errors) {
251 return 'error';
252 }
253
254 var fieldValue = 'value' in field ? field.value : this.getMeta().initialValue;
255
256 if (fieldValue !== undefined && fieldValue !== null && fieldValue !== '') {
257 return 'success';
258 }
259
260 return '';
261 } // Resolve duplicated ids bug between different forms
262 // https://github.com/ant-design/ant-design/issues/7351
263
264 }, {
265 key: "isRequired",
266 value: // onHelpAnimEnd = (_key: string, helpShow: boolean) => {
267 // this.helpShow = helpShow;
268 // if (!helpShow) {
269 // this.setState({});
270 // }
271 // };
272 function isRequired() {
273 var required = this.props.required;
274
275 if (required !== undefined) {
276 return required;
277 }
278
279 if (this.getOnlyControl()) {
280 var meta = this.getMeta() || {};
281 var validate = meta.validate || [];
282 return validate.filter(function (item) {
283 return !!item.rules;
284 }).some(function (item) {
285 return item.rules.some(function (rule) {
286 return rule.required;
287 });
288 });
289 }
290
291 return false;
292 }
293 }, {
294 key: "renderHelp",
295 value: function renderHelp(prefixCls) {
296 var help = this.getHelpMessage();
297 var children = help ? /*#__PURE__*/React.createElement("div", {
298 className: "".concat(prefixCls, "-explain"),
299 key: "help"
300 }, help) : null;
301
302 if (children) {
303 this.helpShow = !!children;
304 }
305
306 return children; // return (
307 // <Animate
308 // transitionName="show-help"
309 // component=""
310 // transitionAppear
311 // key="help"
312 // onEnd={this.onHelpAnimEnd}
313 // >
314 // {children}
315 // </Animate>
316 // );
317 }
318 }, {
319 key: "renderExtra",
320 value: function renderExtra(prefixCls) {
321 var extra = this.props.extra;
322 return extra ? /*#__PURE__*/React.createElement("div", {
323 className: "".concat(prefixCls, "-extra")
324 }, extra) : null;
325 }
326 }, {
327 key: "renderValidateWrapper",
328 value: function renderValidateWrapper(prefixCls, c1, c2, c3) {
329 var _this$props3 = this.props,
330 hasFeedback = _this$props3.hasFeedback,
331 validateStatus = _this$props3.validateStatus;
332 var onlyControl = this.getOnlyControl;
333 var mergedValidateStatus = validateStatus === undefined && onlyControl ? this.getValidateStatus() : validateStatus;
334 var classes = "".concat(prefixCls, "-item-control");
335
336 if (mergedValidateStatus) {
337 classes = classNames("".concat(prefixCls, "-item-control"), {
338 'has-feedback': hasFeedback || mergedValidateStatus === 'validating',
339 'has-success': mergedValidateStatus === 'success',
340 'has-warning': mergedValidateStatus === 'warning',
341 'has-error': mergedValidateStatus === 'error',
342 'is-validating': mergedValidateStatus === 'validating'
343 });
344 } // let iconType: React.ReactNode = null;
345 // switch (validateStatus) {
346 // case 'success':
347 // iconType = <CheckCircleFilled />;
348 // break;
349 // case 'warning':
350 // iconType = <ExclamationCircleFilled />;
351 // break;
352 // case 'error':
353 // iconType = <CloseCircleFilled />;
354 // break;
355 // case 'validating':
356 // iconType = <LoadingOutlined />;
357 // break;
358 // default:
359 // break;
360 // }
361 // const icon =
362 // props.hasFeedback && iconType ? (
363 // <span className={`${prefixCls}-item-children-icon`}>{iconType}</span>
364 // ) : null;
365 // ========================== Feedback ==========================
366
367
368 var IconComponent = mergedValidateStatus && IconMap[mergedValidateStatus];
369 var feedbackIcon = IconComponent ? /*#__PURE__*/React.createElement("span", {
370 className: classNames("".concat(prefixCls, "-item-feedback-icon"), "".concat(prefixCls, "-item-feedback-icon-").concat(mergedValidateStatus))
371 }, /*#__PURE__*/React.createElement(IconComponent, null)) : null;
372 return /*#__PURE__*/React.createElement("div", {
373 className: classes
374 }, /*#__PURE__*/React.createElement("span", {
375 className: "".concat(prefixCls, "-item-children")
376 }, /*#__PURE__*/React.createElement(V5FormItemInputContext.Provider, {
377 value: {
378 status: mergedValidateStatus,
379 feedbackIcon: feedbackIcon,
380 hasFeedback: hasFeedback,
381 isFormItemInput: true
382 }
383 }, c1)), c2, c3);
384 }
385 }, {
386 key: "renderWrapper",
387 value: function renderWrapper(prefixCls, children) {
388 var _this2 = this;
389
390 return /*#__PURE__*/React.createElement(FormContext.Consumer, {
391 key: "wrapper"
392 }, function (_ref2) {
393 var contextWrapperCol = _ref2.wrapperCol,
394 vertical = _ref2.vertical;
395 var wrapperCol = _this2.props.wrapperCol;
396 var mergedWrapperCol = ('wrapperCol' in _this2.props ? wrapperCol : contextWrapperCol) || {};
397 var className = classNames("".concat(prefixCls, "-item-control-wrapper"), mergedWrapperCol.className); // No pass FormContext since it's useless
398
399 return /*#__PURE__*/React.createElement(FormContext.Provider, {
400 value: {
401 vertical: vertical
402 }
403 }, /*#__PURE__*/React.createElement(Col, _extends({}, mergedWrapperCol, {
404 className: className
405 }), children));
406 });
407 }
408 }, {
409 key: "renderLabel",
410 value: function renderLabel(prefixCls) {
411 var _this3 = this;
412
413 return /*#__PURE__*/React.createElement(FormContext.Consumer, {
414 key: "label"
415 }, function (_ref3) {
416 var _classNames;
417
418 var vertical = _ref3.vertical,
419 contextLabelAlign = _ref3.labelAlign,
420 contextLabelCol = _ref3.labelCol,
421 contextColon = _ref3.colon;
422 var _this3$props = _this3.props,
423 label = _this3$props.label,
424 labelCol = _this3$props.labelCol,
425 labelAlign = _this3$props.labelAlign,
426 colon = _this3$props.colon,
427 id = _this3$props.id,
428 htmlFor = _this3$props.htmlFor;
429
430 var required = _this3.isRequired();
431
432 var mergedLabelCol = ('labelCol' in _this3.props ? labelCol : contextLabelCol) || {};
433 var mergedLabelAlign = 'labelAlign' in _this3.props ? labelAlign : contextLabelAlign;
434 var labelClsBasic = "".concat(prefixCls, "-item-label");
435 var labelColClassName = classNames(labelClsBasic, mergedLabelAlign === 'left' && "".concat(labelClsBasic, "-left"), mergedLabelCol.className);
436 var labelChildren = label; // Keep label is original where there should have no colon
437
438 var computedColon = colon === true || contextColon !== false && colon !== false;
439 var haveColon = computedColon && !vertical; // Remove duplicated user input colon
440
441 if (haveColon && typeof label === 'string' && label.trim() !== '') {
442 labelChildren = label.replace(/[::]\s*$/, '');
443 }
444
445 var labelClassName = classNames((_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-item-required"), required), _defineProperty(_classNames, "".concat(prefixCls, "-item-no-colon"), !computedColon), _classNames));
446 return label ? /*#__PURE__*/React.createElement(Col, _extends({}, mergedLabelCol, {
447 className: labelColClassName
448 }), /*#__PURE__*/React.createElement("label", {
449 htmlFor: htmlFor || id || _this3.getId(),
450 className: labelClassName,
451 title: typeof label === 'string' ? label : '',
452 onClick: _this3.onLabelClick
453 }, labelChildren)) : null;
454 });
455 }
456 }, {
457 key: "renderChildren",
458 value: function renderChildren(prefixCls) {
459 var children = this.props.children;
460 return [this.renderLabel(prefixCls), this.renderWrapper(prefixCls, this.renderValidateWrapper(prefixCls, children, this.renderHelp(prefixCls), this.renderExtra(prefixCls)))];
461 }
462 }, {
463 key: "render",
464 value: function render() {
465 return /*#__PURE__*/React.createElement(CompatibleConsumer, null, this.renderFormItem);
466 }
467 }]);
468
469 return FormItem;
470}(React.Component);
471
472_defineProperty(FormItem, "defaultProps", {
473 hasFeedback: false
474});
475
476export { FormItem as default };
\No newline at end of file