forked from vueComponent/ant-design-vue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFormItem.jsx
485 lines (458 loc) · 14.3 KB
/
FormItem.jsx
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
import intersperse from 'intersperse';
import PropTypes from '../_util/vue-types';
import classNames from 'classnames';
import find from 'lodash/find';
import Row from '../grid/Row';
import Col, { ColProps } from '../grid/Col';
import warning from '../_util/warning';
import { FIELD_META_PROP, FIELD_DATA_PROP } from './constants';
import {
initDefaultProps,
getComponentFromProp,
filterEmpty,
getSlotOptions,
isValidElement,
getAllChildren,
} from '../_util/props-util';
import getTransitionProps from '../_util/getTransitionProps';
import BaseMixin from '../_util/BaseMixin';
import { cloneElement, cloneVNodes } from '../_util/vnode';
import Icon from '../icon';
function noop() {}
export const FormItemProps = {
id: PropTypes.string,
prefixCls: PropTypes.string,
label: PropTypes.any,
labelCol: PropTypes.shape(ColProps).loose,
wrapperCol: PropTypes.shape(ColProps).loose,
help: PropTypes.any,
extra: PropTypes.any,
validateStatus: PropTypes.oneOf(['', 'success', 'warning', 'error', 'validating']),
hasFeedback: PropTypes.bool,
required: PropTypes.bool,
colon: PropTypes.bool,
fieldDecoratorId: PropTypes.string,
fieldDecoratorOptions: PropTypes.object,
};
function comeFromSlot(vnodes = [], itemVnode) {
let isSlot = false;
for (let i = 0, len = vnodes.length; i < len; i++) {
const vnode = vnodes[i];
if (vnode && (vnode === itemVnode || vnode.$vnode === itemVnode)) {
isSlot = true;
} else {
const children = vnode.componentOptions ? vnode.componentOptions.children : vnode.children;
isSlot = comeFromSlot(children, itemVnode);
}
if (isSlot) {
break;
}
}
return isSlot;
}
export default {
name: 'AFormItem',
__ANT_FORM_ITEM: true,
mixins: [BaseMixin],
props: initDefaultProps(FormItemProps, {
hasFeedback: false,
prefixCls: 'ant-form',
colon: true,
}),
inject: {
FormProps: { default: () => ({}) },
decoratorFormProps: { default: () => ({}) },
collectFormItemContext: { default: () => noop },
},
data() {
return { helpShow: false };
},
created() {
this.collectContext();
},
beforeUpdate() {
if (process.env.NODE_ENV !== 'production') {
this.collectContext();
}
},
beforeDestroy() {
this.collectFormItemContext(this.$vnode.context, 'delete');
},
mounted() {
warning(
this.getControls(this.slotDefault, true).length <= 1,
'`Form.Item` cannot generate `validateStatus` and `help` automatically, ' +
'while there are more than one `getFieldDecorator` in it.',
);
warning(
!this.fieldDecoratorId,
'`fieldDecoratorId` is deprecated. please use `v-decorator={id, options}` instead.',
);
},
methods: {
collectContext() {
if (this.FormProps.form && this.FormProps.form.templateContext) {
const { templateContext } = this.FormProps.form;
const vnodes = Object.values(templateContext.$slots || {}).reduce((a, b) => {
return [...a, ...b];
}, []);
const isSlot = comeFromSlot(vnodes, this.$vnode);
warning(!isSlot, 'You can not set FormItem from slot, please use slot-scope instead slot');
let isSlotScope = false;
// 进一步判断是否是通过slot-scope传递
if (!isSlot && this.$vnode.context !== templateContext) {
isSlotScope = comeFromSlot(this.$vnode.context.$children, templateContext.$vnode);
}
if (!isSlotScope && !isSlot) {
this.collectFormItemContext(this.$vnode.context);
}
}
},
getHelpMessage() {
const help = getComponentFromProp(this, 'help');
const onlyControl = this.getOnlyControl();
if (help === undefined && onlyControl) {
const errors = this.getField().errors;
if (errors) {
return intersperse(
errors.map((e, index) => {
return isValidElement(e.message)
? cloneElement(e.message, { key: index })
: e.message;
}),
' ',
);
} else {
return '';
}
}
return help;
},
getControls(childrenArray = [], recursively) {
let controls = [];
for (let i = 0; i < childrenArray.length; i++) {
if (!recursively && controls.length > 0) {
break;
}
const child = childrenArray[i];
if (!child.tag && child.text.trim() === '') {
continue;
}
if (getSlotOptions(child).__ANT_FORM_ITEM) {
continue;
}
const children = getAllChildren(child);
const attrs = (child.data && child.data.attrs) || {};
if (FIELD_META_PROP in attrs) {
// And means FIELD_DATA_PROP in child.props, too.
controls.push(child);
} else if (children) {
controls = controls.concat(this.getControls(children, recursively));
}
}
return controls;
},
getOnlyControl() {
const child = this.getControls(this.slotDefault, false)[0];
return child !== undefined ? child : null;
},
getChildAttr(prop) {
const child = this.getOnlyControl();
let data = {};
if (!child) {
return undefined;
}
if (child.data) {
data = child.data;
} else if (child.$vnode && child.$vnode.data) {
data = child.$vnode.data;
}
return data[prop] || data.attrs[prop];
},
getId() {
return this.getChildAttr('id');
},
getMeta() {
return this.getChildAttr(FIELD_META_PROP);
},
getField() {
return this.getChildAttr(FIELD_DATA_PROP);
},
onHelpAnimEnd(_key, helpShow) {
this.helpShow = helpShow;
if (!helpShow) {
this.$forceUpdate();
}
},
renderHelp() {
const prefixCls = this.prefixCls;
const help = this.getHelpMessage();
const children = help ? (
<div class={`${prefixCls}-explain`} key="help">
{help}
</div>
) : null;
if (children) {
this.helpShow = !!children;
}
const transitionProps = getTransitionProps('show-help', {
afterEnter: () => this.onHelpAnimEnd('help', true),
afterLeave: () => this.onHelpAnimEnd('help', false),
});
return (
<transition {...transitionProps} key="help">
{children}
</transition>
);
},
renderExtra() {
const { prefixCls } = this;
const extra = getComponentFromProp(this, 'extra');
return extra ? <div class={`${prefixCls}-extra`}>{extra}</div> : null;
},
getValidateStatus() {
const onlyControl = this.getOnlyControl();
if (!onlyControl) {
return '';
}
const field = this.getField();
if (field.validating) {
return 'validating';
}
if (field.errors) {
return 'error';
}
const fieldValue = 'value' in field ? field.value : this.getMeta().initialValue;
if (fieldValue !== undefined && fieldValue !== null && fieldValue !== '') {
return 'success';
}
return '';
},
renderValidateWrapper(c1, c2, c3) {
const props = this.$props;
const onlyControl = this.getOnlyControl;
const validateStatus =
props.validateStatus === undefined && onlyControl
? this.getValidateStatus()
: props.validateStatus;
let classes = `${props.prefixCls}-item-control`;
if (validateStatus) {
classes = classNames(`${props.prefixCls}-item-control`, {
'has-feedback': props.hasFeedback || validateStatus === 'validating',
'has-success': validateStatus === 'success',
'has-warning': validateStatus === 'warning',
'has-error': validateStatus === 'error',
'is-validating': validateStatus === 'validating',
});
}
let iconType = '';
switch (validateStatus) {
case 'success':
iconType = 'check-circle';
break;
case 'warning':
iconType = 'exclamation-circle';
break;
case 'error':
iconType = 'close-circle';
break;
case 'validating':
iconType = 'loading';
break;
default:
iconType = '';
break;
}
const icon =
props.hasFeedback && iconType ? (
<span class={`${props.prefixCls}-item-children-icon`}>
<Icon type={iconType} theme={iconType === 'loading' ? 'outlined' : 'filled'} />
</span>
) : null;
return (
<div class={classes}>
<span class={`${props.prefixCls}-item-children`}>
{c1}
{icon}
</span>
{c2}
{c3}
</div>
);
},
renderWrapper(children) {
const { prefixCls, wrapperCol = {} } = this;
const { class: cls, style, id, on, ...restProps } = wrapperCol;
const className = classNames(`${prefixCls}-item-control-wrapper`, cls);
const colProps = {
props: restProps,
class: className,
key: 'wrapper',
style,
id,
on,
};
return <Col {...colProps}>{children}</Col>;
},
isRequired() {
const { required } = this;
if (required !== undefined) {
return required;
}
if (this.getOnlyControl()) {
const meta = this.getMeta() || {};
const validate = meta.validate || [];
return validate
.filter(item => !!item.rules)
.some(item => {
return item.rules.some(rule => rule.required);
});
}
return false;
},
// Resolve duplicated ids bug between different forms
// https://github.com/ant-design/ant-design/issues/7351
onLabelClick(e) {
const label = getComponentFromProp(this, 'label');
const id = this.id || this.getId();
if (!id) {
return;
}
const controls = document.querySelectorAll(`[id="${id}"]`);
if (controls.length !== 1) {
// Only prevent in default situation
// Avoid preventing event in `label={<a href="xx">link</a>}``
if (typeof label === 'string') {
e.preventDefault();
}
const control = this.$el.querySelector(`[id="${id}"]`);
if (control && control.focus) {
control.focus();
}
}
},
renderLabel() {
const { prefixCls, labelCol = {}, colon, id } = this;
const label = getComponentFromProp(this, 'label');
const required = this.isRequired();
const {
class: labelColClass,
style: labelColStyle,
id: labelColId,
on,
...restProps
} = labelCol;
const labelColClassName = classNames(`${prefixCls}-item-label`, labelColClass);
const labelClassName = classNames({
[`${prefixCls}-item-required`]: required,
});
let labelChildren = label;
// Keep label is original where there should have no colon
const haveColon = colon && this.FormProps.layout !== 'vertical';
// Remove duplicated user input colon
if (haveColon && typeof label === 'string' && label.trim() !== '') {
labelChildren = label.replace(/[:|:]\s*$/, '');
}
const colProps = {
props: restProps,
class: labelColClassName,
key: 'label',
style: labelColStyle,
id: labelColId,
on,
};
return label ? (
<Col {...colProps}>
<label
for={id || this.getId()}
class={labelClassName}
title={typeof label === 'string' ? label : ''}
onClick={this.onLabelClick}
>
{labelChildren}
</label>
</Col>
) : null;
},
renderChildren() {
return [
this.renderLabel(),
this.renderWrapper(
this.renderValidateWrapper(this.slotDefault, this.renderHelp(), this.renderExtra()),
),
];
},
renderFormItem(children) {
const props = this.$props;
const prefixCls = props.prefixCls;
const itemClassName = {
[`${prefixCls}-item`]: true,
[`${prefixCls}-item-with-help`]: this.helpShow,
[`${prefixCls}-item-no-colon`]: !props.colon,
};
return <Row class={classNames(itemClassName)}>{children}</Row>;
},
decoratorOption(vnode) {
if (vnode.data && vnode.data.directives) {
const directive = find(vnode.data.directives, ['name', 'decorator']);
warning(
!directive || (directive && Array.isArray(directive.value)),
`Invalid directive: type check failed for directive "decorator". Expected Array, got ${typeof (directive ? directive.value : directive)}. At ${
vnode.tag
}.`,
);
return directive ? directive.value : null;
} else {
return null;
}
},
decoratorChildren(vnodes) {
const { FormProps } = this;
const getFieldDecorator = FormProps.form.getFieldDecorator;
for (let i = 0, len = vnodes.length; i < len; i++) {
const vnode = vnodes[i];
if (getSlotOptions(vnode).__ANT_FORM_ITEM) {
break;
}
if (vnode.children) {
vnode.children = this.decoratorChildren(cloneVNodes(vnode.children));
} else if (vnode.componentOptions && vnode.componentOptions.children) {
vnode.componentOptions.children = this.decoratorChildren(
cloneVNodes(vnode.componentOptions.children),
);
}
const option = this.decoratorOption(vnode);
if (option && option[0]) {
vnodes[i] = getFieldDecorator(option[0], option[1])(vnode);
}
}
return vnodes;
},
},
render() {
const {
$slots,
decoratorFormProps,
fieldDecoratorId,
fieldDecoratorOptions = {},
FormProps,
} = this;
let child = filterEmpty($slots.default || []);
if (decoratorFormProps.form && fieldDecoratorId && child.length) {
const getFieldDecorator = decoratorFormProps.form.getFieldDecorator;
child[0] = getFieldDecorator(fieldDecoratorId, fieldDecoratorOptions)(child[0]);
warning(
!(child.length > 1),
'`autoFormCreate` just `decorator` then first children. but you can use JSX to support multiple children',
);
this.slotDefault = child;
} else if (FormProps.form) {
child = cloneVNodes(child);
this.slotDefault = this.decoratorChildren(child);
} else {
this.slotDefault = child;
}
const children = this.renderChildren();
return this.renderFormItem(children);
},
};