Skip to content

Commit

Permalink
feat: update form
Browse files Browse the repository at this point in the history
  • Loading branch information
tangjinzhou committed Jul 14, 2020
1 parent f3a9b7b commit c469853
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 257 deletions.
2 changes: 1 addition & 1 deletion antdv-demo
119 changes: 48 additions & 71 deletions components/form-model/Form.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { inject, provide } from 'vue';
// import scrollIntoView from 'dom-scroll-into-view';
import PropTypes from '../_util/vue-types';
import classNames from 'classnames';
import { ColProps } from '../grid/Col';
Expand All @@ -12,6 +11,8 @@ import { getNamePath, containsNamePath } from './utils/valueUtil';
import { defaultValidateMessages } from './utils/messages';
import { allPromiseFinish } from './utils/asyncUtil';
import { toArray } from './utils/typeUtil';
import isEqual from 'lodash/isEqual';
import scrollIntoView from 'scroll-into-view-if-needed';

export const FormProps = {
layout: PropTypes.oneOf(['horizontal', 'inline', 'vertical']),
Expand Down Expand Up @@ -57,6 +58,10 @@ export const ValidationRule = {
validator: PropTypes.func,
};

function isEqualName(name1, name2) {
return isEqual(toArray(name1), toArray(name2));
}

const Form = {
name: 'AFormModel',
inheritAttrs: false,
Expand All @@ -80,7 +85,7 @@ const Form = {
watch: {
rules() {
if (this.validateOnRuleChange) {
this.validate(() => {});
this.validateFields();
}
},
},
Expand All @@ -96,7 +101,7 @@ const Form = {
}
},
removeField(field) {
if (field.prop) {
if (field.fieldName) {
this.fields.splice(this.fields.indexOf(field), 1);
}
},
Expand All @@ -107,37 +112,34 @@ const Form = {
const res = this.validateFields();
res
.then(values => {
// eslint-disable-next-line no-console
console.log('values', values);
this.$emit('finish', values);
})
.catch(errors => {
// eslint-disable-next-line no-console
console.log('errors', errors);
this.handleFinishFailed(errors);
});
},
resetFields(props = []) {
getFieldsByNameList(nameList) {
const provideNameList = !!nameList;
const namePathList = provideNameList ? toArray(nameList).map(getNamePath) : [];
if (!provideNameList) {
return this.fields;
} else {
return this.fields.filter(
field => namePathList.findIndex(namePath => isEqualName(namePath, field.fieldName)) > -1,
);
}
},
resetFields(name) {
if (!this.model) {
warning(false, 'FormModel', 'model is required for resetFields to work.');
warning(false, 'Form', 'model is required for resetFields to work.');
return;
}
const fields = props.length
? typeof props === 'string'
? this.fields.filter(field => props === field.prop)
: this.fields.filter(field => props.indexOf(field.prop) > -1)
: this.fields;
fields.forEach(field => {
this.getFieldsByNameList(name).forEach(field => {
field.resetField();
});
},
clearValidate(props = []) {
const fields = props.length
? typeof props === 'string'
? this.fields.filter(field => props === field.prop)
: this.fields.filter(field => props.indexOf(field.prop) > -1)
: this.fields;
fields.forEach(field => {
clearValidate(name) {
this.getFieldsByNameList(name).forEach(field => {
field.clearValidate();
});
},
Expand All @@ -150,51 +152,35 @@ const Form = {
},
validate() {
return this.validateField(...arguments);
},
scrollToField(name, options = {}) {
const fields = this.getFieldsByNameList([name]);
if (fields.length) {
const fieldId = fields[0].fieldId;
const node = fieldId ? document.getElementById(fieldId) : null;

// if (!this.model) {
// warning(false, 'FormModel', 'model is required for resetFields to work.');
// return;
// }
// let promise;
// // if no callback, return promise
// if (typeof callback !== 'function' && window.Promise) {
// promise = new window.Promise((resolve, reject) => {
// callback = function(valid) {
// valid ? resolve(valid) : reject(valid);
// };
// });
// }
// let valid = true;
// let count = 0;
// // 如果需要验证的fields为空,调用验证时立刻返回callback
// if (this.fields.length === 0 && callback) {
// callback(true);
// }
// let invalidFields = {};
// this.fields.forEach(field => {
// field.validate('', (message, field) => {
// if (message) {
// valid = false;
// }
// invalidFields = Object.assign({}, invalidFields, field);
// if (typeof callback === 'function' && ++count === this.fields.length) {
// callback(valid, invalidFields);
// }
// });
// });
// if (promise) {
// return promise;
// }
if (node) {
scrollIntoView(node, {
scrollMode: 'if-needed',
block: 'nearest',
...options,
});
}
}
},
scrollToField() {},
// TODO
// eslint-disable-next-line no-unused-vars
getFieldsValue(nameList) {
getFieldsValue(nameList = true) {
const values = {};
this.fields.forEach(({ prop, fieldValue }) => {
values[prop] = fieldValue;
this.fields.forEach(({ fieldName, fieldValue }) => {
values[fieldName] = fieldValue;
});
return values;
if (nameList === true) {
return values;
} else {
const res = {};
toArray(nameList).forEach(namePath => (res[namePath] = values[namePath]));
return res;
}
},
validateFields(nameList, options) {
if (!this.model) {
Expand Down Expand Up @@ -247,15 +233,6 @@ const Form = {
const summaryPromise = allPromiseFinish(promiseList);
this.lastValidatePromise = summaryPromise;

// // Notify fields with rule that validate has finished and need update
// summaryPromise
// .catch(results => results)
// .then(results => {
// const resultNamePathList = results.map(({ name }) => name);
// // eslint-disable-next-line no-console
// console.log(resultNamePathList);
// });

const returnPromise = summaryPromise
.then(() => {
if (this.lastValidatePromise === summaryPromise) {
Expand Down
99 changes: 57 additions & 42 deletions components/form-model/FormItem.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import classNames from 'classnames';
import getTransitionProps from '../_util/getTransitionProps';
import Row from '../grid/Row';
import Col, { ColProps } from '../grid/Col';
import {
import hasProp, {
initDefaultProps,
findDOMNode,
getComponent,
Expand All @@ -24,6 +24,7 @@ import LoadingOutlined from '@ant-design/icons-vue/LoadingOutlined';
import { validateRules } from './utils/validateUtil';
import { getNamePath } from './utils/valueUtil';
import { toArray } from './utils/typeUtil';
import { warning } from '../vc-util/warning';

const iconMap = {
success: CheckCircleFilled,
Expand All @@ -32,29 +33,35 @@ const iconMap = {
validating: LoadingOutlined,
};

function getPropByPath(obj, path, strict) {
function getPropByPath(obj, namePathList, strict) {
let tempObj = obj;
path = path.replace(/\[(\w+)\]/g, '.$1');
path = path.replace(/^\./, '');

let keyArr = path.split('.');
const keyArr = namePathList;
let i = 0;
for (let len = keyArr.length; i < len - 1; ++i) {
if (!tempObj && !strict) break;
let key = keyArr[i];
if (key in tempObj) {
tempObj = tempObj[key];
} else {
if (strict) {
throw new Error('please transfer a valid prop path to form item!');
try {
for (let len = keyArr.length; i < len - 1; ++i) {
if (!tempObj && !strict) break;
let key = keyArr[i];
if (key in tempObj) {
tempObj = tempObj[key];
} else {
if (strict) {
throw Error('please transfer a valid name path to form item!');
}
break;
}
break;
}
if (strict && !tempObj) {
throw Error('please transfer a valid name path to form item!');
}
} catch (error) {
console.error('please transfer a valid name path to form item!');
}

return {
o: tempObj,
k: keyArr[i],
v: tempObj ? tempObj[keyArr[i]] : null,
v: tempObj ? tempObj[keyArr[i]] : undefined,
};
}
export const FormItemProps = {
Expand All @@ -69,7 +76,8 @@ export const FormItemProps = {
hasFeedback: PropTypes.bool,
colon: PropTypes.bool,
labelAlign: PropTypes.oneOf(['left', 'right']),
prop: PropTypes.string,
prop: PropTypes.oneOfType([Array, String, Number]),
name: PropTypes.oneOfType([Array, String, Number]),
rules: PropTypes.oneOfType([Array, Object]),
autoLink: PropTypes.bool,
required: PropTypes.bool,
Expand All @@ -94,6 +102,7 @@ export default {
};
},
data() {
warning(hasProp(this, 'prop'), `\`prop\` is deprecated. Please use \`name\` instead.`);
return {
validateState: this.validateStatus,
validateMessage: '',
Expand All @@ -105,21 +114,29 @@ export default {
},

computed: {
fieldName() {
return this.name || this.prop;
},
namePath() {
return getNamePath(this.fieldName);
},
fieldId() {
return this.id || (this.FormContext.name && this.prop)
? `${this.FormContext.name}_${this.prop}`
: undefined;
if (this.id) {
return this.id;
} else if (!this.namePath.length) {
return undefined;
} else {
const formName = this.FormContext.name;
const mergedId = this.namePath.join('_');
return formName ? `${formName}_${mergedId}` : mergedId;
}
},
fieldValue() {
const model = this.FormContext.model;
if (!model || !this.prop) {
if (!model || !this.fieldName) {
return;
}
let path = this.prop;
if (path.indexOf(':') !== -1) {
path = path.replace(/:/g, '.');
}
return getPropByPath(model, path, true).v;
return getPropByPath(model, this.namePath, true).v;
},
isRequired() {
let rules = this.getRules();
Expand All @@ -145,7 +162,7 @@ export default {
provide('isFormItemChildren', true);
},
mounted() {
if (this.prop) {
if (this.fieldName) {
const { addField } = this.FormContext;
addField && addField(this);
this.initialValue = cloneDeep(this.fieldValue);
Expand All @@ -157,10 +174,10 @@ export default {
},
methods: {
getNamePath() {
const { prop } = this.$props;
const { fieldName } = this;
const { prefixName = [] } = this.FormContext;

return prop !== undefined ? [...prefixName, ...getNamePath(prop)] : [];
return fieldName !== undefined ? [...prefixName, ...this.namePath] : [];
},
validateRules(options) {
const { validateFirst = false, messageVariables } = this.$props;
Expand All @@ -170,15 +187,17 @@ export default {
let filteredRules = this.getRules();
if (triggerName) {
filteredRules = filteredRules.filter(rule => {
const { validateTrigger } = rule;
if (!validateTrigger) {
const { trigger } = rule;
if (!trigger) {
return true;
}
const triggerList = toArray(validateTrigger);
const triggerList = toArray(trigger);
return triggerList.includes(triggerName);
});
}

if (!filteredRules.length) {
return Promise.resolve();
}
const promise = validateRules(
namePath,
this.fieldValue,
Expand Down Expand Up @@ -207,8 +226,8 @@ export default {
const selfRules = this.rules;
const requiredRule =
this.required !== undefined ? { required: !!this.required, trigger: 'change' } : [];
const prop = getPropByPath(formRules, this.prop || '');
formRules = formRules ? prop.o[this.prop || ''] || prop.v : [];
const prop = getPropByPath(formRules, this.namePath);
formRules = formRules ? prop.o[prop.k] || prop.v : [];
return [].concat(selfRules || formRules || []).concat(requiredRule);
},
getFilteredRule(trigger) {
Expand Down Expand Up @@ -242,13 +261,9 @@ export default {
resetField() {
this.validateState = '';
this.validateMessage = '';
let model = this.FormContext.model || {};
let value = this.fieldValue;
let path = this.prop;
if (path.indexOf(':') !== -1) {
path = path.replace(/:/, '.');
}
let prop = getPropByPath(model, path, true);
const model = this.FormContext.model || {};
const value = this.fieldValue;
const prop = getPropByPath(model, this.namePath, true);
this.validateDisabled = true;
if (Array.isArray(value)) {
prop.o[prop.k] = [].concat(this.initialValue);
Expand Down Expand Up @@ -456,7 +471,7 @@ export default {
const { autoLink } = getOptionProps(this);
const children = getSlot(this);
let firstChildren = children[0];
if (this.prop && autoLink && isValidElement(firstChildren)) {
if (this.fieldName && autoLink && isValidElement(firstChildren)) {
const originalEvents = getEvents(firstChildren);
const originalBlur = originalEvents.onBlur;
const originalChange = originalEvents.onChange;
Expand Down
Loading

0 comments on commit c469853

Please sign in to comment.