UNPKG

19.9 kBJavaScriptView Raw
1function _typeof(obj) { "@babel/helpers - typeof"; 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); }
2
3var _excluded = ["prefixCls", "style", "className"];
4
5function 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; }
6
7function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
8
9function _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; }
10
11function _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; }
12
13function _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; }
14
15function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
16
17function _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); } }
18
19function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
20
21function _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); }
22
23function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
24
25function _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); }; }
26
27function _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); }
28
29function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
30
31function _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; } }
32
33function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
34
35function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
36
37function _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."); }
38
39function _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); }
40
41function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
42
43function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
44
45function _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; }
46
47import * as React from 'react';
48import * as ReactDOM from 'react-dom';
49import classNames from 'classnames';
50import Animate from 'rc-animate';
51import omit from 'omit.js';
52import { Row, Col } from 'antd';
53import { CheckCircleFilled, CloseCircleFilled, ExclamationCircleFilled, LoadingOutlined } from '@ant-design/icons';
54import CompatibleConsumer from '../CompatibleConsumer';
55import warning from '../_util/warning';
56import { tuple } from '../_util/types';
57import { FIELD_META_PROP, FIELD_DATA_PROP } from './constants';
58import FormContext from './context';
59var ValidateStatuses = tuple('success', 'warning', 'error', 'validating', '');
60var FormLabelAligns = tuple('left', 'right');
61
62function intersperseSpace(list) {
63 return list.reduce(function (current, item) {
64 return [].concat(_toConsumableArray(current), [' ', item]);
65 }, []).slice(1);
66}
67
68var FormItem = /*#__PURE__*/function (_React$Component) {
69 _inherits(FormItem, _React$Component);
70
71 var _super = _createSuper(FormItem);
72
73 function FormItem() {
74 var _this;
75
76 _classCallCheck(this, FormItem);
77
78 for (var _len = arguments.length, args = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
79 args[_key2] = arguments[_key2];
80 }
81
82 _this = _super.call.apply(_super, [this].concat(args));
83 _this.helpShow = false;
84
85 _this.onLabelClick = function () {
86 var id = _this.props.id || _this.getId();
87
88 if (!id) {
89 return;
90 }
91
92 var formItemNode = ReactDOM.findDOMNode(_assertThisInitialized(_this));
93 var control = formItemNode.querySelector("[id=\"".concat(id, "\"]"));
94
95 if (control && control.focus) {
96 control.focus();
97 }
98 };
99
100 _this.onHelpAnimEnd = function (_key, helpShow) {
101 _this.helpShow = helpShow;
102
103 if (!helpShow) {
104 _this.setState({});
105 }
106 };
107
108 _this.renderFormItem = function (_ref) {
109 var _itemClassName;
110
111 var getPrefixCls = _ref.getPrefixCls;
112
113 var _this$props = _this.props,
114 customizePrefixCls = _this$props.prefixCls,
115 style = _this$props.style,
116 className = _this$props.className,
117 restProps = _objectWithoutProperties(_this$props, _excluded);
118
119 var prefixCls = getPrefixCls('legacy-form', customizePrefixCls);
120
121 var children = _this.renderChildren(prefixCls);
122
123 var itemClassName = (_itemClassName = {}, _defineProperty(_itemClassName, "".concat(prefixCls, "-item"), true), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-with-help"), _this.helpShow), _defineProperty(_itemClassName, "".concat(className), !!className), _itemClassName);
124 return /*#__PURE__*/React.createElement(Row, _objectSpread(_objectSpread({
125 className: classNames(itemClassName),
126 style: style
127 }, omit(restProps, ['id', '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: function isRequired() {
267 var required = this.props.required;
268
269 if (required !== undefined) {
270 return required;
271 }
272
273 if (this.getOnlyControl()) {
274 var meta = this.getMeta() || {};
275 var validate = meta.validate || [];
276 return validate.filter(function (item) {
277 return !!item.rules;
278 }).some(function (item) {
279 return item.rules.some(function (rule) {
280 return rule.required;
281 });
282 });
283 }
284
285 return false;
286 }
287 }, {
288 key: "renderHelp",
289 value: function renderHelp(prefixCls) {
290 var help = this.getHelpMessage();
291 var children = help ? /*#__PURE__*/React.createElement("div", {
292 className: "".concat(prefixCls, "-explain"),
293 key: "help"
294 }, help) : null;
295
296 if (children) {
297 this.helpShow = !!children;
298 }
299
300 return /*#__PURE__*/React.createElement(Animate, {
301 transitionName: "show-help",
302 component: "",
303 transitionAppear: true,
304 key: "help",
305 onEnd: this.onHelpAnimEnd
306 }, children);
307 }
308 }, {
309 key: "renderExtra",
310 value: function renderExtra(prefixCls) {
311 var extra = this.props.extra;
312 return extra ? /*#__PURE__*/React.createElement("div", {
313 className: "".concat(prefixCls, "-extra")
314 }, extra) : null;
315 }
316 }, {
317 key: "renderValidateWrapper",
318 value: function renderValidateWrapper(prefixCls, c1, c2, c3) {
319 var props = this.props;
320 var onlyControl = this.getOnlyControl;
321 var validateStatus = props.validateStatus === undefined && onlyControl ? this.getValidateStatus() : props.validateStatus;
322 var classes = "".concat(prefixCls, "-item-control");
323
324 if (validateStatus) {
325 classes = classNames("".concat(prefixCls, "-item-control"), {
326 'has-feedback': props.hasFeedback || validateStatus === 'validating',
327 'has-success': validateStatus === 'success',
328 'has-warning': validateStatus === 'warning',
329 'has-error': validateStatus === 'error',
330 'is-validating': validateStatus === 'validating'
331 });
332 }
333
334 var iconType = null;
335
336 switch (validateStatus) {
337 case 'success':
338 iconType = /*#__PURE__*/React.createElement(CheckCircleFilled, null);
339 break;
340
341 case 'warning':
342 iconType = /*#__PURE__*/React.createElement(ExclamationCircleFilled, null);
343 break;
344
345 case 'error':
346 iconType = /*#__PURE__*/React.createElement(CloseCircleFilled, null);
347 break;
348
349 case 'validating':
350 iconType = /*#__PURE__*/React.createElement(LoadingOutlined, null);
351 break;
352
353 default:
354 break;
355 }
356
357 var icon = props.hasFeedback && iconType ? /*#__PURE__*/React.createElement("span", {
358 className: "".concat(prefixCls, "-item-children-icon")
359 }, iconType) : null;
360 return /*#__PURE__*/React.createElement("div", {
361 className: classes
362 }, /*#__PURE__*/React.createElement("span", {
363 className: "".concat(prefixCls, "-item-children")
364 }, c1, icon), c2, c3);
365 }
366 }, {
367 key: "renderWrapper",
368 value: function renderWrapper(prefixCls, children) {
369 var _this2 = this;
370
371 return /*#__PURE__*/React.createElement(FormContext.Consumer, {
372 key: "wrapper"
373 }, function (_ref2) {
374 var contextWrapperCol = _ref2.wrapperCol,
375 vertical = _ref2.vertical;
376 var wrapperCol = _this2.props.wrapperCol;
377 var mergedWrapperCol = ('wrapperCol' in _this2.props ? wrapperCol : contextWrapperCol) || {};
378 var className = classNames("".concat(prefixCls, "-item-control-wrapper"), mergedWrapperCol.className); // No pass FormContext since it's useless
379
380 return /*#__PURE__*/React.createElement(FormContext.Provider, {
381 value: {
382 vertical: vertical
383 }
384 }, /*#__PURE__*/React.createElement(Col, _objectSpread(_objectSpread({}, mergedWrapperCol), {}, {
385 className: className
386 }), children));
387 });
388 }
389 }, {
390 key: "renderLabel",
391 value: function renderLabel(prefixCls) {
392 var _this3 = this;
393
394 return /*#__PURE__*/React.createElement(FormContext.Consumer, {
395 key: "label"
396 }, function (_ref3) {
397 var _classNames;
398
399 var vertical = _ref3.vertical,
400 contextLabelAlign = _ref3.labelAlign,
401 contextLabelCol = _ref3.labelCol,
402 contextColon = _ref3.colon;
403 var _this3$props = _this3.props,
404 label = _this3$props.label,
405 labelCol = _this3$props.labelCol,
406 labelAlign = _this3$props.labelAlign,
407 colon = _this3$props.colon,
408 id = _this3$props.id,
409 htmlFor = _this3$props.htmlFor;
410
411 var required = _this3.isRequired();
412
413 var mergedLabelCol = ('labelCol' in _this3.props ? labelCol : contextLabelCol) || {};
414 var mergedLabelAlign = 'labelAlign' in _this3.props ? labelAlign : contextLabelAlign;
415 var labelClsBasic = "".concat(prefixCls, "-item-label");
416 var labelColClassName = classNames(labelClsBasic, mergedLabelAlign === 'left' && "".concat(labelClsBasic, "-left"), mergedLabelCol.className);
417 var labelChildren = label; // Keep label is original where there should have no colon
418
419 var computedColon = colon === true || contextColon !== false && colon !== false;
420 var haveColon = computedColon && !vertical; // Remove duplicated user input colon
421
422 if (haveColon && typeof label === 'string' && label.trim() !== '') {
423 labelChildren = label.replace(/[::]\s*$/, '');
424 }
425
426 var labelClassName = classNames((_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-item-required"), required), _defineProperty(_classNames, "".concat(prefixCls, "-item-no-colon"), !computedColon), _classNames));
427 return label ? /*#__PURE__*/React.createElement(Col, _objectSpread(_objectSpread({}, mergedLabelCol), {}, {
428 className: labelColClassName
429 }), /*#__PURE__*/React.createElement("label", {
430 htmlFor: htmlFor || id || _this3.getId(),
431 className: labelClassName,
432 title: typeof label === 'string' ? label : '',
433 onClick: _this3.onLabelClick
434 }, labelChildren)) : null;
435 });
436 }
437 }, {
438 key: "renderChildren",
439 value: function renderChildren(prefixCls) {
440 var children = this.props.children;
441 return [this.renderLabel(prefixCls), this.renderWrapper(prefixCls, this.renderValidateWrapper(prefixCls, children, this.renderHelp(prefixCls), this.renderExtra(prefixCls)))];
442 }
443 }, {
444 key: "render",
445 value: function render() {
446 return /*#__PURE__*/React.createElement(CompatibleConsumer, null, this.renderFormItem);
447 }
448 }]);
449
450 return FormItem;
451}(React.Component);
452
453FormItem.defaultProps = {
454 hasFeedback: false
455};
456export { FormItem as default };
\No newline at end of file