Skip to content

Commit c469853

Browse files
committed
feat: update form
1 parent f3a9b7b commit c469853

File tree

5 files changed

+107
-257
lines changed

5 files changed

+107
-257
lines changed

antdv-demo

components/form-model/Form.jsx

+48-71
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { inject, provide } from 'vue';
2-
// import scrollIntoView from 'dom-scroll-into-view';
32
import PropTypes from '../_util/vue-types';
43
import classNames from 'classnames';
54
import { ColProps } from '../grid/Col';
@@ -12,6 +11,8 @@ import { getNamePath, containsNamePath } from './utils/valueUtil';
1211
import { defaultValidateMessages } from './utils/messages';
1312
import { allPromiseFinish } from './utils/asyncUtil';
1413
import { toArray } from './utils/typeUtil';
14+
import isEqual from 'lodash/isEqual';
15+
import scrollIntoView from 'scroll-into-view-if-needed';
1516

1617
export const FormProps = {
1718
layout: PropTypes.oneOf(['horizontal', 'inline', 'vertical']),
@@ -57,6 +58,10 @@ export const ValidationRule = {
5758
validator: PropTypes.func,
5859
};
5960

61+
function isEqualName(name1, name2) {
62+
return isEqual(toArray(name1), toArray(name2));
63+
}
64+
6065
const Form = {
6166
name: 'AFormModel',
6267
inheritAttrs: false,
@@ -80,7 +85,7 @@ const Form = {
8085
watch: {
8186
rules() {
8287
if (this.validateOnRuleChange) {
83-
this.validate(() => {});
88+
this.validateFields();
8489
}
8590
},
8691
},
@@ -96,7 +101,7 @@ const Form = {
96101
}
97102
},
98103
removeField(field) {
99-
if (field.prop) {
104+
if (field.fieldName) {
100105
this.fields.splice(this.fields.indexOf(field), 1);
101106
}
102107
},
@@ -107,37 +112,34 @@ const Form = {
107112
const res = this.validateFields();
108113
res
109114
.then(values => {
110-
// eslint-disable-next-line no-console
111-
console.log('values', values);
112115
this.$emit('finish', values);
113116
})
114117
.catch(errors => {
115-
// eslint-disable-next-line no-console
116-
console.log('errors', errors);
117118
this.handleFinishFailed(errors);
118119
});
119120
},
120-
resetFields(props = []) {
121+
getFieldsByNameList(nameList) {
122+
const provideNameList = !!nameList;
123+
const namePathList = provideNameList ? toArray(nameList).map(getNamePath) : [];
124+
if (!provideNameList) {
125+
return this.fields;
126+
} else {
127+
return this.fields.filter(
128+
field => namePathList.findIndex(namePath => isEqualName(namePath, field.fieldName)) > -1,
129+
);
130+
}
131+
},
132+
resetFields(name) {
121133
if (!this.model) {
122-
warning(false, 'FormModel', 'model is required for resetFields to work.');
134+
warning(false, 'Form', 'model is required for resetFields to work.');
123135
return;
124136
}
125-
const fields = props.length
126-
? typeof props === 'string'
127-
? this.fields.filter(field => props === field.prop)
128-
: this.fields.filter(field => props.indexOf(field.prop) > -1)
129-
: this.fields;
130-
fields.forEach(field => {
137+
this.getFieldsByNameList(name).forEach(field => {
131138
field.resetField();
132139
});
133140
},
134-
clearValidate(props = []) {
135-
const fields = props.length
136-
? typeof props === 'string'
137-
? this.fields.filter(field => props === field.prop)
138-
: this.fields.filter(field => props.indexOf(field.prop) > -1)
139-
: this.fields;
140-
fields.forEach(field => {
141+
clearValidate(name) {
142+
this.getFieldsByNameList(name).forEach(field => {
141143
field.clearValidate();
142144
});
143145
},
@@ -150,51 +152,35 @@ const Form = {
150152
},
151153
validate() {
152154
return this.validateField(...arguments);
155+
},
156+
scrollToField(name, options = {}) {
157+
const fields = this.getFieldsByNameList([name]);
158+
if (fields.length) {
159+
const fieldId = fields[0].fieldId;
160+
const node = fieldId ? document.getElementById(fieldId) : null;
153161

154-
// if (!this.model) {
155-
// warning(false, 'FormModel', 'model is required for resetFields to work.');
156-
// return;
157-
// }
158-
// let promise;
159-
// // if no callback, return promise
160-
// if (typeof callback !== 'function' && window.Promise) {
161-
// promise = new window.Promise((resolve, reject) => {
162-
// callback = function(valid) {
163-
// valid ? resolve(valid) : reject(valid);
164-
// };
165-
// });
166-
// }
167-
// let valid = true;
168-
// let count = 0;
169-
// // 如果需要验证的fields为空,调用验证时立刻返回callback
170-
// if (this.fields.length === 0 && callback) {
171-
// callback(true);
172-
// }
173-
// let invalidFields = {};
174-
// this.fields.forEach(field => {
175-
// field.validate('', (message, field) => {
176-
// if (message) {
177-
// valid = false;
178-
// }
179-
// invalidFields = Object.assign({}, invalidFields, field);
180-
// if (typeof callback === 'function' && ++count === this.fields.length) {
181-
// callback(valid, invalidFields);
182-
// }
183-
// });
184-
// });
185-
// if (promise) {
186-
// return promise;
187-
// }
162+
if (node) {
163+
scrollIntoView(node, {
164+
scrollMode: 'if-needed',
165+
block: 'nearest',
166+
...options,
167+
});
168+
}
169+
}
188170
},
189-
scrollToField() {},
190-
// TODO
191171
// eslint-disable-next-line no-unused-vars
192-
getFieldsValue(nameList) {
172+
getFieldsValue(nameList = true) {
193173
const values = {};
194-
this.fields.forEach(({ prop, fieldValue }) => {
195-
values[prop] = fieldValue;
174+
this.fields.forEach(({ fieldName, fieldValue }) => {
175+
values[fieldName] = fieldValue;
196176
});
197-
return values;
177+
if (nameList === true) {
178+
return values;
179+
} else {
180+
const res = {};
181+
toArray(nameList).forEach(namePath => (res[namePath] = values[namePath]));
182+
return res;
183+
}
198184
},
199185
validateFields(nameList, options) {
200186
if (!this.model) {
@@ -247,15 +233,6 @@ const Form = {
247233
const summaryPromise = allPromiseFinish(promiseList);
248234
this.lastValidatePromise = summaryPromise;
249235

250-
// // Notify fields with rule that validate has finished and need update
251-
// summaryPromise
252-
// .catch(results => results)
253-
// .then(results => {
254-
// const resultNamePathList = results.map(({ name }) => name);
255-
// // eslint-disable-next-line no-console
256-
// console.log(resultNamePathList);
257-
// });
258-
259236
const returnPromise = summaryPromise
260237
.then(() => {
261238
if (this.lastValidatePromise === summaryPromise) {

components/form-model/FormItem.jsx

+57-42
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import classNames from 'classnames';
55
import getTransitionProps from '../_util/getTransitionProps';
66
import Row from '../grid/Row';
77
import Col, { ColProps } from '../grid/Col';
8-
import {
8+
import hasProp, {
99
initDefaultProps,
1010
findDOMNode,
1111
getComponent,
@@ -24,6 +24,7 @@ import LoadingOutlined from '@ant-design/icons-vue/LoadingOutlined';
2424
import { validateRules } from './utils/validateUtil';
2525
import { getNamePath } from './utils/valueUtil';
2626
import { toArray } from './utils/typeUtil';
27+
import { warning } from '../vc-util/warning';
2728

2829
const iconMap = {
2930
success: CheckCircleFilled,
@@ -32,29 +33,35 @@ const iconMap = {
3233
validating: LoadingOutlined,
3334
};
3435

35-
function getPropByPath(obj, path, strict) {
36+
function getPropByPath(obj, namePathList, strict) {
3637
let tempObj = obj;
37-
path = path.replace(/\[(\w+)\]/g, '.$1');
38-
path = path.replace(/^\./, '');
3938

40-
let keyArr = path.split('.');
39+
const keyArr = namePathList;
4140
let i = 0;
42-
for (let len = keyArr.length; i < len - 1; ++i) {
43-
if (!tempObj && !strict) break;
44-
let key = keyArr[i];
45-
if (key in tempObj) {
46-
tempObj = tempObj[key];
47-
} else {
48-
if (strict) {
49-
throw new Error('please transfer a valid prop path to form item!');
41+
try {
42+
for (let len = keyArr.length; i < len - 1; ++i) {
43+
if (!tempObj && !strict) break;
44+
let key = keyArr[i];
45+
if (key in tempObj) {
46+
tempObj = tempObj[key];
47+
} else {
48+
if (strict) {
49+
throw Error('please transfer a valid name path to form item!');
50+
}
51+
break;
5052
}
51-
break;
5253
}
54+
if (strict && !tempObj) {
55+
throw Error('please transfer a valid name path to form item!');
56+
}
57+
} catch (error) {
58+
console.error('please transfer a valid name path to form item!');
5359
}
60+
5461
return {
5562
o: tempObj,
5663
k: keyArr[i],
57-
v: tempObj ? tempObj[keyArr[i]] : null,
64+
v: tempObj ? tempObj[keyArr[i]] : undefined,
5865
};
5966
}
6067
export const FormItemProps = {
@@ -69,7 +76,8 @@ export const FormItemProps = {
6976
hasFeedback: PropTypes.bool,
7077
colon: PropTypes.bool,
7178
labelAlign: PropTypes.oneOf(['left', 'right']),
72-
prop: PropTypes.string,
79+
prop: PropTypes.oneOfType([Array, String, Number]),
80+
name: PropTypes.oneOfType([Array, String, Number]),
7381
rules: PropTypes.oneOfType([Array, Object]),
7482
autoLink: PropTypes.bool,
7583
required: PropTypes.bool,
@@ -94,6 +102,7 @@ export default {
94102
};
95103
},
96104
data() {
105+
warning(hasProp(this, 'prop'), `\`prop\` is deprecated. Please use \`name\` instead.`);
97106
return {
98107
validateState: this.validateStatus,
99108
validateMessage: '',
@@ -105,21 +114,29 @@ export default {
105114
},
106115

107116
computed: {
117+
fieldName() {
118+
return this.name || this.prop;
119+
},
120+
namePath() {
121+
return getNamePath(this.fieldName);
122+
},
108123
fieldId() {
109-
return this.id || (this.FormContext.name && this.prop)
110-
? `${this.FormContext.name}_${this.prop}`
111-
: undefined;
124+
if (this.id) {
125+
return this.id;
126+
} else if (!this.namePath.length) {
127+
return undefined;
128+
} else {
129+
const formName = this.FormContext.name;
130+
const mergedId = this.namePath.join('_');
131+
return formName ? `${formName}_${mergedId}` : mergedId;
132+
}
112133
},
113134
fieldValue() {
114135
const model = this.FormContext.model;
115-
if (!model || !this.prop) {
136+
if (!model || !this.fieldName) {
116137
return;
117138
}
118-
let path = this.prop;
119-
if (path.indexOf(':') !== -1) {
120-
path = path.replace(/:/g, '.');
121-
}
122-
return getPropByPath(model, path, true).v;
139+
return getPropByPath(model, this.namePath, true).v;
123140
},
124141
isRequired() {
125142
let rules = this.getRules();
@@ -145,7 +162,7 @@ export default {
145162
provide('isFormItemChildren', true);
146163
},
147164
mounted() {
148-
if (this.prop) {
165+
if (this.fieldName) {
149166
const { addField } = this.FormContext;
150167
addField && addField(this);
151168
this.initialValue = cloneDeep(this.fieldValue);
@@ -157,10 +174,10 @@ export default {
157174
},
158175
methods: {
159176
getNamePath() {
160-
const { prop } = this.$props;
177+
const { fieldName } = this;
161178
const { prefixName = [] } = this.FormContext;
162179

163-
return prop !== undefined ? [...prefixName, ...getNamePath(prop)] : [];
180+
return fieldName !== undefined ? [...prefixName, ...this.namePath] : [];
164181
},
165182
validateRules(options) {
166183
const { validateFirst = false, messageVariables } = this.$props;
@@ -170,15 +187,17 @@ export default {
170187
let filteredRules = this.getRules();
171188
if (triggerName) {
172189
filteredRules = filteredRules.filter(rule => {
173-
const { validateTrigger } = rule;
174-
if (!validateTrigger) {
190+
const { trigger } = rule;
191+
if (!trigger) {
175192
return true;
176193
}
177-
const triggerList = toArray(validateTrigger);
194+
const triggerList = toArray(trigger);
178195
return triggerList.includes(triggerName);
179196
});
180197
}
181-
198+
if (!filteredRules.length) {
199+
return Promise.resolve();
200+
}
182201
const promise = validateRules(
183202
namePath,
184203
this.fieldValue,
@@ -207,8 +226,8 @@ export default {
207226
const selfRules = this.rules;
208227
const requiredRule =
209228
this.required !== undefined ? { required: !!this.required, trigger: 'change' } : [];
210-
const prop = getPropByPath(formRules, this.prop || '');
211-
formRules = formRules ? prop.o[this.prop || ''] || prop.v : [];
229+
const prop = getPropByPath(formRules, this.namePath);
230+
formRules = formRules ? prop.o[prop.k] || prop.v : [];
212231
return [].concat(selfRules || formRules || []).concat(requiredRule);
213232
},
214233
getFilteredRule(trigger) {
@@ -242,13 +261,9 @@ export default {
242261
resetField() {
243262
this.validateState = '';
244263
this.validateMessage = '';
245-
let model = this.FormContext.model || {};
246-
let value = this.fieldValue;
247-
let path = this.prop;
248-
if (path.indexOf(':') !== -1) {
249-
path = path.replace(/:/, '.');
250-
}
251-
let prop = getPropByPath(model, path, true);
264+
const model = this.FormContext.model || {};
265+
const value = this.fieldValue;
266+
const prop = getPropByPath(model, this.namePath, true);
252267
this.validateDisabled = true;
253268
if (Array.isArray(value)) {
254269
prop.o[prop.k] = [].concat(this.initialValue);
@@ -456,7 +471,7 @@ export default {
456471
const { autoLink } = getOptionProps(this);
457472
const children = getSlot(this);
458473
let firstChildren = children[0];
459-
if (this.prop && autoLink && isValidElement(firstChildren)) {
474+
if (this.fieldName && autoLink && isValidElement(firstChildren)) {
460475
const originalEvents = getEvents(firstChildren);
461476
const originalBlur = originalEvents.onBlur;
462477
const originalChange = originalEvents.onChange;

0 commit comments

Comments
 (0)