ant-design/components/form/Form.tsx

268 lines
9.2 KiB
TypeScript
Raw Normal View History

import * as React from 'react';
2018-08-07 21:07:52 +08:00
import * as PropTypes from 'prop-types';
import classNames from 'classnames';
2016-11-08 16:13:07 +08:00
import createDOMForm from 'rc-form/lib/createDOMForm';
2017-11-17 21:19:10 +08:00
import createFormField from 'rc-form/lib/createFormField';
import omit from 'omit.js';
import FormItem from './FormItem';
import { FIELD_META_PROP, FIELD_DATA_PROP } from './constants';
import { ConfigConsumer, ConfigConsumerProps } from '../config-provider';
import { Omit, tuple } from '../_util/type';
import warning from '../_util/warning';
2015-10-09 13:53:04 +08:00
type FormCreateOptionMessagesCallback = (...args: any[]) => string;
interface FormCreateOptionMessages {
2018-12-07 20:02:01 +08:00
[messageId: string]: string | FormCreateOptionMessagesCallback | FormCreateOptionMessages;
}
export interface FormCreateOption<T> {
onFieldsChange?: (props: T, fields: object, allFields: any, add: string) => void;
onValuesChange?: (props: T, changedValues: any, allValues: any) => void;
mapPropsToFields?: (props: T) => void;
validateMessages?: FormCreateOptionMessages;
withRef?: boolean;
name?: string;
}
const FormLayouts = tuple('horizontal', 'inline', 'vertical');
export type FormLayout = (typeof FormLayouts)[number];
export interface FormProps extends React.FormHTMLAttributes<HTMLFormElement> {
layout?: FormLayout;
form?: WrappedFormUtils;
2016-10-19 17:51:33 +08:00
onSubmit?: React.FormEventHandler<any>;
style?: React.CSSProperties;
className?: string;
2016-08-24 16:09:55 +08:00
prefixCls?: string;
hideRequiredMark?: boolean;
}
export type ValidationRule = {
/** validation error message */
2018-07-31 12:38:19 +08:00
message?: React.ReactNode;
/** built-in validation type, available options: https://github.com/yiminghe/async-validator#type */
type?: string;
/** indicates whether field is required */
required?: boolean;
/** treat required fields that only contain whitespace as errors */
whitespace?: boolean;
/** validate the exact length of a field */
len?: number;
/** validate the min length of a field */
min?: number;
/** validate the max length of a field */
max?: number;
/** validate the value from a list of possible values */
enum?: string | string[];
/** validate from a regular expression */
pattern?: RegExp;
/** transform a value before validation */
transform?: (value: any) => any;
/** custom validate function (Note: callback must be called) */
validator?: (rule: any, value: any, callback: any, source?: any, options?: any) => any;
};
2017-10-18 23:52:54 +08:00
export type ValidateCallback = (errors: any, values: any) => void;
export type GetFieldDecoratorOptions = {
/** 子节点的值的属性,如 Checkbox 的是 'checked' */
valuePropName?: string;
/** 子节点的初始值,类型、可选值均由子节点决定 */
initialValue?: any;
/** 收集子节点的值的时机 */
trigger?: string;
/** 可以把 onChange 的参数转化为控件的值,例如 DatePicker 可设为:(date, dateString) => dateString */
getValueFromEvent?: (...args: any[]) => any;
2018-08-29 11:20:33 +08:00
/** Get the component props according to field value. */
getValueProps?: (value: any) => any;
/** 校验子节点值的时机 */
validateTrigger?: string | string[];
/** 校验规则,参见 [async-validator](https://github.com/yiminghe/async-validator) */
rules?: ValidationRule[];
/** 是否和其他控件互斥,特别用于 Radio 单选控件 */
exclusive?: boolean;
/** Normalize value to form component */
normalize?: (value: any, prevValue: any, allValues: any) => any;
/** Whether stop validate on first rule of error for this field. */
validateFirst?: boolean;
/** 是否一直保留子节点的信息 */
2018-12-21 23:58:31 +08:00
preserve?: boolean;
2017-07-22 15:25:08 +08:00
};
/** dom-scroll-into-view 组件配置参数 */
export type DomScrollIntoViewConfig = {
/** 是否和左边界对齐 */
alignWithLeft?: boolean;
/** 是否和上边界对齐 */
alignWithTop?: boolean;
/** 顶部偏移量 */
offsetTop?: number;
/** 左侧偏移量 */
offsetLeft?: number;
/** 底部偏移量 */
offsetBottom?: number;
/** 右侧偏移量 */
offsetRight?: number;
/** 是否允许容器水平滚动 */
allowHorizontalScroll?: boolean;
/** 当内容可见时是否允许滚动容器 */
onlyScrollIfNeeded?: boolean;
};
export type ValidateFieldsOptions = {
/** 所有表单域是否在第一个校验规则失败后停止继续校验 */
first?: boolean;
/** 指定哪些表单域在第一个校验规则失败后停止继续校验 */
firstFields?: string[];
/** 已经校验过的表单域,在 validateTrigger 再次被触发时是否再次校验 */
force?: boolean;
/** 定义 validateFieldsAndScroll 的滚动行为 */
scroll?: DomScrollIntoViewConfig;
};
2016-08-24 16:09:55 +08:00
// function create
2016-08-22 17:26:14 +08:00
export type WrappedFormUtils = {
2016-08-24 16:09:55 +08:00
/** 获取一组输入控件的值,如不传入参数,则获取全部组件的值 */
2019-01-25 15:45:26 +08:00
getFieldsValue(fieldNames?: Array<string>): { [field: string]: any };
/** 获取一个输入控件的值 */
2016-08-22 17:26:14 +08:00
getFieldValue(fieldName: string): any;
/** 设置一组输入控件的值 */
2016-08-22 17:26:14 +08:00
setFieldsValue(obj: Object): void;
/** 设置一组输入控件的值 */
2016-08-22 17:26:14 +08:00
setFields(obj: Object): void;
2016-08-24 16:09:55 +08:00
/** 校验并获取一组输入域的值与 Error */
validateFields(
fieldNames: Array<string>,
options: ValidateFieldsOptions,
callback: ValidateCallback,
): void;
validateFields(options: ValidateFieldsOptions, callback: ValidateCallback): void;
validateFields(fieldNames: Array<string>, callback: ValidateCallback): void;
validateFields(fieldNames: Array<string>, options: ValidateFieldsOptions): void;
validateFields(fieldNames: Array<string>): void;
2018-01-11 21:29:34 +08:00
validateFields(callback: ValidateCallback): void;
validateFields(options: ValidateFieldsOptions): void;
2018-01-11 21:29:34 +08:00
validateFields(): void;
/** 与 `validateFields` 相似,但校验完后,如果校验不通过的菜单域不在可见范围内,则自动滚动进可见范围 */
2018-12-07 20:02:01 +08:00
validateFieldsAndScroll(
fieldNames: Array<string>,
options: ValidateFieldsOptions,
2018-12-07 20:02:01 +08:00
callback: ValidateCallback,
): void;
validateFieldsAndScroll(options: ValidateFieldsOptions, callback: ValidateCallback): void;
validateFieldsAndScroll(fieldNames: Array<string>, callback: ValidateCallback): void;
validateFieldsAndScroll(fieldNames: Array<string>, options: ValidateFieldsOptions): void;
validateFieldsAndScroll(fieldNames: Array<string>): void;
validateFieldsAndScroll(callback: ValidateCallback): void;
validateFieldsAndScroll(options: ValidateFieldsOptions): void;
2018-01-11 21:29:34 +08:00
validateFieldsAndScroll(): void;
/** 获取某个输入控件的 Error */
2016-08-22 17:26:14 +08:00
getFieldError(name: string): Object[];
getFieldsError(names?: Array<string>): Object;
/** 判断一个输入控件是否在校验状态 */
2016-08-22 17:26:14 +08:00
isFieldValidating(name: string): boolean;
isFieldTouched(name: string): boolean;
isFieldsTouched(names?: Array<string>): boolean;
2016-08-24 16:09:55 +08:00
/** 重置一组输入控件的值与状态,如不传入参数,则重置所有组件 */
2016-08-22 17:26:14 +08:00
resetFields(names?: Array<string>): void;
2018-08-20 19:26:29 +08:00
// tslint:disable-next-line:max-line-length
2018-12-07 20:02:01 +08:00
getFieldDecorator<T extends Object = {}>(
id: keyof T,
options?: GetFieldDecoratorOptions,
): (node: React.ReactNode) => React.ReactNode;
};
2016-08-19 16:53:27 +08:00
export interface FormComponentProps {
form: WrappedFormUtils;
}
export interface RcBaseFormProps {
2018-12-07 20:02:01 +08:00
wrappedComponentRef?: any;
}
export interface ComponentDecorator {
2017-08-18 17:21:18 +08:00
<P extends FormComponentProps>(
component: React.ComponentClass<P> | React.SFC<P>,
): React.ComponentClass<RcBaseFormProps & Omit<P, keyof FormComponentProps>>;
}
export default class Form extends React.Component<FormProps, any> {
static defaultProps = {
layout: 'horizontal' as FormLayout,
hideRequiredMark: false,
2017-11-21 20:45:24 +08:00
onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
},
2016-07-13 11:14:24 +08:00
};
static propTypes = {
prefixCls: PropTypes.string,
layout: PropTypes.oneOf(FormLayouts),
children: PropTypes.any,
onSubmit: PropTypes.func,
hideRequiredMark: PropTypes.bool,
2016-07-13 11:14:24 +08:00
};
static childContextTypes = {
vertical: PropTypes.bool,
};
2016-08-24 16:09:55 +08:00
static Item = FormItem;
2017-11-17 21:19:10 +08:00
static createFormField = createFormField;
2018-12-07 20:02:01 +08:00
static create = function<TOwnProps>(
options: FormCreateOption<TOwnProps> = {},
): ComponentDecorator {
return createDOMForm({
2016-08-24 16:09:55 +08:00
fieldNameProp: 'id',
...options,
2016-08-24 16:09:55 +08:00
fieldMetaProp: FIELD_META_PROP,
fieldDataProp: FIELD_DATA_PROP,
});
2017-03-24 11:56:18 +08:00
};
2016-08-24 16:09:55 +08:00
2017-11-21 20:45:24 +08:00
constructor(props: FormProps) {
2016-07-29 13:59:37 +08:00
super(props);
warning(!props.form, 'It is unnecessary to pass `form` to `Form` after antd@1.7.0.');
2016-07-29 13:59:37 +08:00
}
getChildContext() {
2017-11-30 09:53:32 +08:00
const { layout } = this.props;
return {
2017-11-30 09:53:32 +08:00
vertical: layout === 'vertical',
};
}
renderForm = ({ getPrefixCls }: ConfigConsumerProps) => {
2018-12-07 20:02:01 +08:00
const { prefixCls: customizePrefixCls, hideRequiredMark, className = '', layout } = this.props;
const prefixCls = getPrefixCls('form', customizePrefixCls);
2018-12-07 20:02:01 +08:00
const formClassName = classNames(
prefixCls,
{
[`${prefixCls}-horizontal`]: layout === 'horizontal',
[`${prefixCls}-vertical`]: layout === 'vertical',
[`${prefixCls}-inline`]: layout === 'inline',
[`${prefixCls}-hide-required-mark`]: hideRequiredMark,
},
className,
);
2015-10-09 13:53:04 +08:00
2016-07-07 12:06:05 +08:00
const formProps = omit(this.props, [
'prefixCls',
'className',
'layout',
2016-07-07 12:06:05 +08:00
'form',
'hideRequiredMark',
2016-07-07 12:06:05 +08:00
]);
return <form {...formProps} className={formClassName} />;
2018-12-07 20:02:01 +08:00
};
render() {
2018-12-07 20:02:01 +08:00
return <ConfigConsumer>{this.renderForm}</ConfigConsumer>;
}
2015-10-09 13:53:04 +08:00
}