baseForm.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import React from 'react';
  2. import classNames from 'classnames';
  3. import PropTypes from 'prop-types';
  4. import FormFoundation, { BaseFormAdapter } from '@douyinfe/semi-foundation/form/foundation';
  5. import { strings, cssClasses } from '@douyinfe/semi-foundation/form/constants';
  6. import { getUuidv4 } from '@douyinfe/semi-foundation/utils/uuid';
  7. import warning from '@douyinfe/semi-foundation/utils/warning';
  8. import BaseComponent from '../_base/baseComponent';
  9. import { FormStateContext, FormApiContext, FormUpdaterContext } from './context';
  10. import { isEmptyChildren } from '../_base/reactUtils';
  11. import Row from '../grid/row';
  12. import { cloneDeep } from '../_utils/index';
  13. import Slot from './slot';
  14. import Section from './section';
  15. import Label from './label';
  16. import ErrorMessage from './errorMessage';
  17. import FormInputGroup from './group';
  18. import { noop } from 'lodash';
  19. import '@douyinfe/semi-foundation/form/form.scss';
  20. import {
  21. FormInput,
  22. FormInputNumber,
  23. FormTextArea,
  24. FormSelect,
  25. FormCheckboxGroup,
  26. FormCheckbox,
  27. FormRadioGroup,
  28. FormRadio,
  29. FormDatePicker,
  30. FormSwitch,
  31. FormSlider,
  32. FormTimePicker,
  33. FormTreeSelect,
  34. FormCascader,
  35. FormRating,
  36. FormAutoComplete,
  37. FormUpload,
  38. FormTagInput } from './field';
  39. import {
  40. BaseFormProps,
  41. FormState,
  42. FormApi,
  43. ErrorMsg
  44. } from './interface';
  45. const prefix = cssClasses.PREFIX;
  46. interface BaseFormState {
  47. formId: string
  48. }
  49. class Form<Values extends Record<string, any> = any> extends BaseComponent<BaseFormProps<Values>, BaseFormState> {
  50. static propTypes = {
  51. 'aria-label': PropTypes.string,
  52. onSubmit: PropTypes.func,
  53. onSubmitFail: PropTypes.func,
  54. /* Triggered from update, including field mount/unmount/value change/blur/verification status change/error prompt change, input parameter is formState, currentField */
  55. onChange: PropTypes.func,
  56. onReset: PropTypes.func,
  57. // Triggered when the value of the form is updated, only when the value of the subfield changes. The entry parameter is formState.values
  58. onValueChange: PropTypes.func,
  59. initValues: PropTypes.object,
  60. getFormApi: PropTypes.func,
  61. component: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
  62. render: PropTypes.func,
  63. validateFields: PropTypes.func,
  64. style: PropTypes.object,
  65. className: PropTypes.string,
  66. layout: PropTypes.oneOf(strings.LAYOUT),
  67. labelPosition: PropTypes.oneOf(strings.LABEL_POS),
  68. labelWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  69. labelAlign: PropTypes.oneOf(strings.LABEL_ALIGN),
  70. labelCol: PropTypes.object, // Control labelCol {span: number, offset: number} for all field child nodes
  71. wrapperCol: PropTypes.object, // Control wrapperCol {span: number, offset: number} for all field child nodes
  72. allowEmpty: PropTypes.bool,
  73. autoScrollToError: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
  74. disabled: PropTypes.bool,
  75. showValidateIcon: PropTypes.bool,
  76. extraTextPosition: PropTypes.oneOf(strings.EXTRA_POS),
  77. id: PropTypes.string,
  78. };
  79. static defaultProps = {
  80. onChange: noop,
  81. onSubmitFail: noop,
  82. onSubmit: noop,
  83. onReset: noop,
  84. onValueChange: noop,
  85. layout: 'vertical',
  86. labelPosition: 'top',
  87. allowEmpty: false,
  88. autoScrollToError: false,
  89. showValidateIcon: true,
  90. };
  91. static Input = FormInput;
  92. static TextArea = FormTextArea;
  93. static InputNumber = FormInputNumber;
  94. static Select = FormSelect;
  95. static Checkbox = FormCheckbox;
  96. static CheckboxGroup = FormCheckboxGroup;
  97. static Radio = FormRadio;
  98. static RadioGroup = FormRadioGroup;
  99. static DatePicker = FormDatePicker;
  100. static TimePicker = FormTimePicker;
  101. static Switch = FormSwitch;
  102. static Slider = FormSlider;
  103. static TreeSelect = FormTreeSelect;
  104. static Cascader = FormCascader;
  105. static Rating = FormRating;
  106. static AutoComplete = FormAutoComplete;
  107. static Upload = FormUpload;
  108. static TagInput = FormTagInput;
  109. static Slot = Slot;
  110. static ErrorMessage = ErrorMessage;
  111. static InputGroup = FormInputGroup;
  112. static Label = Label;
  113. static Section = Section;
  114. formApi: FormApi<Values>;
  115. constructor(props: BaseFormProps<Values>) {
  116. super(props);
  117. this.state = {
  118. formId: '',
  119. };
  120. warning(
  121. Boolean(props.component && props.render),
  122. '[Semi Form] You should not use <Form component> and <Form render> in ths same time; <Form render> will be ignored'
  123. );
  124. warning(
  125. props.component && props.children && !isEmptyChildren(props.children),
  126. '[Semi Form] You should not use <Form component> and <Form>{children}</Form> in ths same time; <Form>{children}</Form> will be ignored'
  127. );
  128. warning(
  129. props.render && props.children && !isEmptyChildren(props.children),
  130. '[Semi Form] You should not use <Form render> and <Form>{children}</Form> in ths same time; <Form>{children}</Form> will be ignored'
  131. );
  132. this.submit = this.submit.bind(this);
  133. this.reset = this.reset.bind(this);
  134. this.foundation = new FormFoundation(this.adapter);
  135. this.formApi = this.foundation.getFormApi();
  136. if (this.props.getFormApi) {
  137. this.props.getFormApi(this.formApi);
  138. }
  139. }
  140. componentDidMount() {
  141. this.foundation.init();
  142. }
  143. componentWillUnmount() {
  144. this.foundation.destroy();
  145. }
  146. get adapter(): BaseFormAdapter<BaseFormProps<Values>, BaseFormState, Values> {
  147. return {
  148. ...super.adapter,
  149. cloneDeep,
  150. notifySubmit: (values: Values, e: any) => {
  151. this.props.onSubmit(values, e);
  152. },
  153. notifySubmitFail: (errors, values, e: any) => {
  154. this.props.onSubmitFail(errors, values, e);
  155. },
  156. forceUpdate: (callback?: () => void) => {
  157. this.forceUpdate(callback);
  158. },
  159. notifyChange: (formState: FormState) => {
  160. this.props.onChange(formState);
  161. },
  162. notifyValueChange: (values: Values, changedValues: Partial<Values>) => {
  163. this.props.onValueChange(values, changedValues);
  164. },
  165. notifyReset: () => {
  166. this.props.onReset();
  167. },
  168. initFormId: () => {
  169. this.setState({
  170. formId: getUuidv4()
  171. });
  172. },
  173. getInitValues: () => this.props.initValues,
  174. getFormProps: (keys: undefined | string | Array<string>) => {
  175. if (typeof keys === 'undefined') {
  176. return this.props;
  177. } else if (typeof keys === 'string') {
  178. return this.props[keys];
  179. } else {
  180. const props = {};
  181. keys.forEach(key => {
  182. props[key] = this.props[key];
  183. });
  184. return props;
  185. }
  186. },
  187. getAllErrorDOM: () => {
  188. const { formId } = this.state;
  189. const { id } = this.props;
  190. const xId = id ? id : formId;
  191. return document.querySelectorAll(
  192. `form[x-form-id="${xId}"] .${cssClasses.PREFIX}-field-error-message`
  193. );
  194. },
  195. getFieldDOM: (field: string) =>
  196. document.querySelector(`.${cssClasses.PREFIX}-field[x-field-id="${field}"]`),
  197. };
  198. }
  199. get content() {
  200. const { children, component, render } = this.props;
  201. const formState = this.foundation.getFormState();
  202. const props = {
  203. formState,
  204. formApi: this.foundation.getFormApi(),
  205. values: formState.values,
  206. };
  207. if (component) {
  208. return React.createElement(component, props);
  209. }
  210. if (render) {
  211. return render(props);
  212. }
  213. if (typeof children === 'function') {
  214. return children(props);
  215. }
  216. return children;
  217. }
  218. submit(e: React.FormEvent<HTMLFormElement>) {
  219. e.preventDefault();
  220. this.foundation.submit(e);
  221. }
  222. reset(e: React.FormEvent<HTMLFormElement>) {
  223. e.preventDefault();
  224. this.foundation.reset();
  225. }
  226. render() {
  227. const needClone = false;
  228. const formState = this.foundation.getFormState(needClone);
  229. const updaterApi = this.foundation.getModifyFormStateApi();
  230. const { formId } = this.state;
  231. const {
  232. children,
  233. getFormApi,
  234. onChange,
  235. onSubmit,
  236. onSubmitFail,
  237. onValueChange,
  238. component,
  239. render,
  240. validateFields,
  241. initValues,
  242. layout,
  243. style,
  244. className,
  245. labelPosition,
  246. labelWidth,
  247. labelAlign,
  248. labelCol,
  249. wrapperCol,
  250. allowEmpty,
  251. autoScrollToError,
  252. showValidateIcon,
  253. extraTextPosition,
  254. id,
  255. ...rest
  256. } = this.props;
  257. const formCls = classNames(prefix, className, {
  258. [prefix + '-vertical']: layout === 'vertical',
  259. [prefix + '-horizontal']: layout === 'horizontal',
  260. });
  261. const showldAppendRow = wrapperCol && labelCol;
  262. const formContent = (
  263. <form
  264. style={style}
  265. {...rest}
  266. onReset={this.reset}
  267. onSubmit={this.submit}
  268. className={formCls}
  269. x-form-id={id ? id : formId}
  270. >
  271. {this.content}
  272. </form>
  273. );
  274. const withRowForm = <Row>{formContent}</Row>;
  275. return (
  276. <FormUpdaterContext.Provider value={updaterApi}>
  277. <FormApiContext.Provider value={this.formApi}>
  278. <FormStateContext.Provider value={formState}>
  279. {showldAppendRow ? withRowForm : formContent}
  280. </FormStateContext.Provider>
  281. </FormApiContext.Provider>
  282. </FormUpdaterContext.Provider>
  283. );
  284. }
  285. }
  286. export default Form;