withField.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. /* eslint-disable max-lines-per-function, react-hooks/rules-of-hooks, prefer-const, max-len */
  2. import React, { useState, useLayoutEffect, useMemo, useRef, forwardRef } from 'react';
  3. import classNames from 'classnames';
  4. import { cssClasses } from '@douyinfe/semi-foundation/form/constants';
  5. import { isValid, generateValidatesFromRules, mergeOptions, mergeProps, getDisplayName } from '@douyinfe/semi-foundation/form/utils';
  6. import * as ObjectUtil from '@douyinfe/semi-foundation/utils/object';
  7. import isPromise from '@douyinfe/semi-foundation/utils/isPromise';
  8. import warning from '@douyinfe/semi-foundation/utils/warning';
  9. import { useFormState, useStateWithGetter, useFormUpdater, useArrayFieldState } from '../hooks/index';
  10. import ErrorMessage from '../errorMessage';
  11. import { isElement } from '../../_base/reactUtils';
  12. import Label from '../label';
  13. import { Col } from '../../grid';
  14. import { CallOpts, WithFieldOption } from '@douyinfe/semi-foundation/form/interface';
  15. import { CommonFieldProps, CommonexcludeType } from '../interface';
  16. import { Subtract } from 'utility-types';
  17. import { noop } from "lodash";
  18. const prefix = cssClasses.PREFIX;
  19. /**
  20. * withFiled is used to inject components
  21. * 1. Takes over the value and onChange of the component and synchronizes them to Form Foundation
  22. * 2. Insert <Label>
  23. * 3. Insert <ErrorMessage>
  24. */
  25. function withField<
  26. C extends React.ElementType,
  27. T extends Subtract<React.ComponentProps<C>, CommonexcludeType> & CommonFieldProps,
  28. R extends React.ComponentType<T>
  29. >(Component: C, opts?: WithFieldOption): R {
  30. let SemiField = (props: any, ref: React.MutableRefObject<any> | ((instance: any) => void)) => {
  31. let {
  32. // condition,
  33. field,
  34. label,
  35. labelPosition,
  36. labelWidth,
  37. labelAlign,
  38. labelCol,
  39. wrapperCol,
  40. noLabel,
  41. noErrorMessage,
  42. isInInputGroup,
  43. initValue,
  44. validate,
  45. validateStatus,
  46. trigger,
  47. allowEmptyString,
  48. allowEmpty,
  49. emptyValue,
  50. rules,
  51. required,
  52. keepState,
  53. transform,
  54. name,
  55. fieldClassName,
  56. fieldStyle,
  57. convert,
  58. stopValidateWithError,
  59. helpText,
  60. extraText,
  61. extraTextPosition,
  62. pure,
  63. id,
  64. rest,
  65. } = mergeProps(props);
  66. let { options, shouldInject } = mergeOptions(opts, props);
  67. warning(
  68. typeof field === 'undefined' && options.shouldInject,
  69. "[Semi Form]: 'field' is required, please check your props of Field Component"
  70. );
  71. // 无需注入的直接返回,eg:Group内的checkbox、radio
  72. // Return without injection, eg: <Checkbox> / <Radio> inside CheckboxGroup/RadioGroup
  73. if (!shouldInject) {
  74. return <Component {...rest} ref={ref} />;
  75. }
  76. // grab formState from context
  77. const formState = useFormState();
  78. // grab formUpdater (the api for field to read/modify FormState) from context
  79. const updater = useFormUpdater();
  80. if (!updater.getFormProps) {
  81. warning(
  82. true,
  83. '[Semi Form]: Field Component must be use inside the Form, please check your dom declaration'
  84. );
  85. return null;
  86. }
  87. // To prevent user forgetting to pass the field, use undefined as the key, and updater.getValue will get the wrong value.
  88. let initValueInFormOpts = typeof field !== 'undefined' ? updater.getValue(field) : undefined; // Get the init value of form from formP rops.init Values Get the initial value set in the initValues of Form
  89. let initVal = typeof initValue !== 'undefined' ? initValue : initValueInFormOpts;
  90. // use arrayFieldState to fix issue 615
  91. let arrayFieldState;
  92. try {
  93. arrayFieldState = useArrayFieldState();
  94. if (arrayFieldState) {
  95. initVal =
  96. arrayFieldState.shouldUseInitValue && typeof initValue !== 'undefined'
  97. ? initValue
  98. : initValueInFormOpts;
  99. }
  100. } catch (err) {}
  101. const [value, setValue, getVal] = useStateWithGetter(typeof initVal !== undefined ? initVal : null);
  102. const validateOnMount = trigger.includes('mount');
  103. allowEmpty = allowEmpty || updater.getFormProps().allowEmpty;
  104. // Error information: Array, String, undefined
  105. const [error, setError, getError] = useStateWithGetter();
  106. const [touched, setTouched] = useState<boolean | undefined>();
  107. const [cursor, setCursor, getCursor] = useStateWithGetter(0);
  108. const [status, setStatus] = useState(validateStatus); // use props.validateStatus to init
  109. const rulesRef = useRef(rules);
  110. const validateRef = useRef(validate);
  111. // notNotify is true means that the onChange of the Form does not need to be triggered
  112. // notUpdate is true means that this operation does not need to trigger the forceUpdate
  113. const updateTouched = (isTouched: boolean, callOpts?: CallOpts) => {
  114. setTouched(isTouched);
  115. updater.updateStateTouched(field, isTouched, callOpts);
  116. };
  117. const updateError = (errors: any, callOpts?: CallOpts) => {
  118. if (errors === getError()) {
  119. // When the inspection result is unchanged, no need to update, saving a forceUpdate overhead
  120. // When errors is an array, deepEqual is not used, and it is always treated as a need to update
  121. // 检验结果不变时,无需更新,节省一次forceUpdate开销
  122. // errors为数组时,不做deepEqual,始终当做需要更新处理
  123. return;
  124. }
  125. setError(errors);
  126. updater.updateStateError(field, errors, callOpts);
  127. if (!isValid(errors)) {
  128. setStatus('error');
  129. } else {
  130. setStatus('success');
  131. }
  132. };
  133. const updateValue = (val: any, callOpts?: CallOpts) => {
  134. setValue(val);
  135. let newOpts = {
  136. ...callOpts,
  137. allowEmpty,
  138. };
  139. updater.updateStateValue(field, val, newOpts);
  140. };
  141. const reset = () => {
  142. let callOpts = {
  143. notNotify: true,
  144. notUpdate: true,
  145. };
  146. // reset is called by the FormFoundaion uniformly. The field level does not need to trigger notify and update.
  147. updateValue(initVal !== null ? initVal : undefined, callOpts);
  148. updateError(undefined, callOpts);
  149. updateTouched(undefined, callOpts);
  150. setStatus('default');
  151. };
  152. // Execute the validation rules specified by rules
  153. const _validateInternal = (val: any, callOpts: CallOpts) => {
  154. let latestRules = rulesRef.current || [];
  155. const validator = generateValidatesFromRules(field, latestRules);
  156. const model = {
  157. [field]: val,
  158. };
  159. return new Promise((resolve, reject) => {
  160. validator
  161. .validate(
  162. model,
  163. {
  164. first: stopValidateWithError,
  165. },
  166. // eslint-disable-next-line @typescript-eslint/no-empty-function
  167. (errors, fields) => {}
  168. )
  169. .then(res => {
  170. // validation passed
  171. setStatus('success');
  172. updateError(undefined, callOpts);
  173. resolve({});
  174. })
  175. .catch(err => {
  176. let { errors, fields } = err;
  177. if (errors && fields) {
  178. let messages = errors.map((e: any) => e.message);
  179. if (messages.length === 1) {
  180. // eslint-disable-next-line prefer-destructuring
  181. messages = messages[0];
  182. }
  183. updateError(messages, callOpts);
  184. if (!isValid(messages)) {
  185. setStatus('error');
  186. resolve(errors);
  187. }
  188. } else {
  189. // Some grammatical errors in rules
  190. setStatus('error');
  191. updateError(err.message, callOpts);
  192. resolve(err.message);
  193. throw err;
  194. }
  195. });
  196. });
  197. };
  198. // execute custom validate function
  199. const _validate = (val: any, values: any, callOpts: CallOpts) =>
  200. new Promise(resolve => {
  201. let maybePromisedErrors;
  202. // let errorThrowSync;
  203. try {
  204. maybePromisedErrors = validateRef.current(val, values);
  205. } catch (err) {
  206. // error throw by syncValidate
  207. maybePromisedErrors = err;
  208. }
  209. if (maybePromisedErrors === undefined) {
  210. resolve({});
  211. updateError(undefined, callOpts);
  212. } else if (isPromise(maybePromisedErrors)) {
  213. maybePromisedErrors.then((result: any) => {
  214. if (isValid(result)) {
  215. // validate success,no need to do anything with result
  216. updateError(undefined, callOpts);
  217. resolve(null);
  218. } else {
  219. // validate failed
  220. updateError(result, callOpts);
  221. resolve(result);
  222. }
  223. });
  224. } else {
  225. if (isValid(maybePromisedErrors)) {
  226. updateError(undefined, callOpts);
  227. resolve(null);
  228. } else {
  229. updateError(maybePromisedErrors, callOpts);
  230. resolve(maybePromisedErrors);
  231. }
  232. }
  233. });
  234. const fieldValidate = (val: any, callOpts?: CallOpts) => {
  235. let finalVal = val;
  236. let latestRules = rulesRef.current;
  237. if (transform) {
  238. finalVal = transform(val);
  239. }
  240. if (validateRef.current) {
  241. return _validate(finalVal, updater.getValue(), callOpts);
  242. } else if (latestRules) {
  243. return _validateInternal(finalVal, callOpts);
  244. }
  245. return null;
  246. };
  247. /**
  248. * parse / format
  249. * validate when trigger
  250. *
  251. */
  252. const handleChange = (newValue: any, e: any, ...other: any[]) => {
  253. let fnKey = options.onKeyChangeFnName;
  254. if (fnKey in props && typeof props[options.onKeyChangeFnName] === 'function') {
  255. props[options.onKeyChangeFnName](newValue, e, ...other);
  256. }
  257. // support various type component
  258. let val;
  259. if (!options.valuePath) {
  260. val = newValue;
  261. } else {
  262. val = ObjectUtil.get(newValue, options.valuePath);
  263. }
  264. // User can use convert function to updateValue before Component UI render
  265. if (typeof convert === 'function') {
  266. val = convert(val);
  267. }
  268. // TODO: allowEmptyString split into allowEmpty, emptyValue
  269. // Added abandonment warning
  270. // if (process.env.NODE_ENV !== 'production') {
  271. // warning(allowEmptyString, `'allowEmptyString' will be de deprecated in next version, please replace with 'allowEmpty' & 'emptyValue'
  272. // `)
  273. // }
  274. // set value to undefined if it's an empty string
  275. // allowEmptyString={true} is equivalent to allowEmpty = {true} emptyValue = "
  276. if (allowEmptyString || allowEmpty) {
  277. if (val === '') {
  278. // do nothing
  279. }
  280. } else {
  281. if (val === emptyValue) {
  282. val = undefined;
  283. }
  284. }
  285. // maintain compoent cursor if needed
  286. try {
  287. if (e && e.target && e.target.selectionStart) {
  288. setCursor(e.target.selectionStart);
  289. }
  290. } catch (err) {}
  291. updateTouched(true, { notNotify: true, notUpdate: true });
  292. updateValue(val);
  293. // only validate when trigger includes change
  294. if (trigger.includes('change')) {
  295. fieldValidate(val);
  296. }
  297. };
  298. const handleBlur = (...e: any[]) => {
  299. if (props.onBlur) {
  300. props.onBlur(...e);
  301. }
  302. if (!touched) {
  303. updateTouched(true);
  304. }
  305. if (trigger.includes('blur')) {
  306. let val = getVal();
  307. fieldValidate(val);
  308. }
  309. };
  310. /** Field level maintains a separate layer of data, which is convenient for Form to control Field to update the UI */
  311. // The field level maintains a separate layer of data, which is convenient for the Form to control the Field for UI updates.
  312. const fieldApi = {
  313. setValue: updateValue,
  314. setTouched: updateTouched,
  315. setError: updateError,
  316. reset,
  317. validate: fieldValidate,
  318. };
  319. const fieldState = {
  320. value,
  321. error,
  322. touched,
  323. status,
  324. };
  325. // avoid hooks capture value, fixed issue 346
  326. useLayoutEffect(() => {
  327. rulesRef.current = rules;
  328. validateRef.current = validate;
  329. }, [rules, validate]);
  330. // exec validate once when trigger inlcude 'mount'
  331. useLayoutEffect(() => {
  332. if (validateOnMount) {
  333. fieldValidate(value);
  334. }
  335. // eslint-disable-next-line react-hooks/exhaustive-deps
  336. }, []);
  337. // register when mounted,unregister when unmounted
  338. // register again when field change
  339. useLayoutEffect(() => {
  340. // register
  341. if (typeof field === 'undefined') {
  342. // eslint-disable-next-line @typescript-eslint/no-empty-function
  343. return () => {};
  344. }
  345. // log('register: ' + field);
  346. updater.register(field, fieldState, {
  347. field,
  348. fieldApi,
  349. keepState,
  350. allowEmpty: allowEmpty || allowEmptyString,
  351. });
  352. // return unRegister cb
  353. return () => {
  354. updater.unRegister(field);
  355. // log('unRegister: ' + field);
  356. };
  357. // eslint-disable-next-line react-hooks/exhaustive-deps
  358. }, [field]);
  359. let formProps = updater.getFormProps([
  360. 'labelPosition',
  361. 'labelWidth',
  362. 'labelAlign',
  363. 'labelCol',
  364. 'wrapperCol',
  365. 'disabled',
  366. 'showValidateIcon',
  367. 'extraTextPosition',
  368. ]);
  369. let mergeLabelPos = labelPosition || formProps.labelPosition;
  370. let mergeLabelWidth = labelWidth || formProps.labelWidth;
  371. let mergeLabelAlign = labelAlign || formProps.labelAlign;
  372. let mergeLabelCol = labelCol || formProps.labelCol;
  373. let mergeWrapperCol = wrapperCol || formProps.wrapperCol;
  374. let mergeExtraPos = extraTextPosition || formProps.extraTextPosition || 'bottom';
  375. // id attribute to improve a11y
  376. const a11yId = id ? id : field;
  377. const labelId = `${a11yId}-label`;
  378. const helpTextId = `${a11yId}-helpText`;
  379. const extraTextId = `${a11yId}-extraText`;
  380. const errorMessageId = `${a11yId}-errormessage`;
  381. let FieldComponent = (() => {
  382. // prefer to use validateStatus which pass by user throught props
  383. let blockStatus = validateStatus ? validateStatus : status;
  384. const extraCls = classNames(`${prefix}-field-extra`, {
  385. [`${prefix}-field-extra-string`]: typeof extraText === 'string',
  386. [`${prefix}-field-extra-middle`]: mergeExtraPos === 'middle',
  387. [`${prefix}-field-extra-botttom`]: mergeExtraPos === 'bottom',
  388. });
  389. const extraContent = extraText ? <div className={extraCls} id={extraTextId}>{extraText}</div> : null;
  390. let newProps: Record<string, any> = {
  391. id: a11yId,
  392. disabled: formProps.disabled,
  393. ...rest,
  394. ref,
  395. onBlur: handleBlur,
  396. [options.onKeyChangeFnName]: handleChange,
  397. [options.valueKey]: value,
  398. validateStatus: blockStatus,
  399. 'aria-required': required,
  400. 'aria-labelledby': labelId,
  401. };
  402. if (helpText) {
  403. newProps['aria-describedby'] = extraText ? `${helpTextId} ${extraTextId}` : helpTextId;
  404. }
  405. if (extraText) {
  406. newProps['aria-describedby'] = helpText ? `${helpTextId} ${extraTextId}` : extraTextId;
  407. }
  408. if (status === 'error') {
  409. newProps['aria-errormessage'] = errorMessageId;
  410. newProps['aria-invalid'] = true;
  411. }
  412. const fieldCls = classNames({
  413. [`${prefix}-field`]: true,
  414. [`${prefix}-field-${name}`]: Boolean(name),
  415. [fieldClassName]: Boolean(fieldClassName),
  416. });
  417. const fieldMaincls = classNames({
  418. [`${prefix}-field-main`]: true,
  419. });
  420. if (mergeLabelPos === 'inset' && !noLabel) {
  421. newProps.insetLabel = label || field;
  422. newProps.insetLabelId = labelId;
  423. if (typeof label === 'object' && !isElement(label)) {
  424. newProps.insetLabel = label.text;
  425. newProps.insetLabelId = labelId;
  426. }
  427. }
  428. const com = <Component {...(newProps as any)} />;
  429. // when use in InputGroup, no need to insert <Label>、<ErrorMessage> inside Field, just add it at Group
  430. if (isInInputGroup) {
  431. return com;
  432. }
  433. if (pure) {
  434. let pureCls = classNames(rest.className, {
  435. [`${prefix}-field-pure`]: true,
  436. [`${prefix}-field-${name}`]: Boolean(name),
  437. [fieldClassName]: Boolean(fieldClassName),
  438. });
  439. newProps.className = pureCls;
  440. return <Component {...(newProps as any)} />;
  441. }
  442. let withCol = mergeLabelCol && mergeWrapperCol;
  443. const labelColCls = mergeLabelAlign ? `${prefix}-col-${mergeLabelAlign}` : '';
  444. // get label
  445. let labelContent = null;
  446. if (!noLabel && mergeLabelPos !== 'inset') {
  447. let needSpread = typeof label === 'object' && !isElement(label) ? label : {};
  448. labelContent = (
  449. <Label
  450. text={label || field}
  451. id={labelId}
  452. required={required}
  453. name={a11yId || name || field}
  454. width={mergeLabelWidth}
  455. align={mergeLabelAlign}
  456. {...needSpread}
  457. />
  458. );
  459. }
  460. const fieldMainContent = (
  461. <div className={fieldMaincls}>
  462. {mergeExtraPos === 'middle' ? extraContent : null}
  463. {com}
  464. {!noErrorMessage ? (
  465. <ErrorMessage
  466. error={error}
  467. validateStatus={blockStatus}
  468. helpText={helpText}
  469. helpTextId={helpTextId}
  470. errorMessageId={errorMessageId}
  471. showValidateIcon={formProps.showValidateIcon}
  472. />
  473. ) : null}
  474. {mergeExtraPos === 'bottom' ? extraContent : null}
  475. </div>
  476. );
  477. const withColContent = (
  478. <>
  479. {mergeLabelPos === 'top' ? (
  480. <div style={{ overflow: 'hidden' }}>
  481. <Col {...mergeLabelCol} className={labelColCls}>
  482. {labelContent}
  483. </Col>
  484. </div>
  485. ) : (
  486. <Col {...mergeLabelCol} className={labelColCls}>
  487. {labelContent}
  488. </Col>
  489. )}
  490. <Col {...mergeWrapperCol}>{fieldMainContent}</Col>
  491. </>
  492. );
  493. return (
  494. <div
  495. className={fieldCls}
  496. style={fieldStyle}
  497. x-label-pos={mergeLabelPos}
  498. x-field-id={field}
  499. x-extra-pos={mergeExtraPos}
  500. >
  501. {withCol ? (
  502. withColContent
  503. ) : (
  504. <>
  505. {labelContent}
  506. {fieldMainContent}
  507. </>
  508. )}
  509. </div>
  510. );
  511. })();
  512. // !important optimization
  513. const shouldUpdate = [
  514. ...Object.values(fieldState),
  515. ...Object.values(props),
  516. field,
  517. mergeLabelPos,
  518. mergeLabelAlign,
  519. formProps.disabled,
  520. ];
  521. if (options.shouldMemo) {
  522. // eslint-disable-next-line react-hooks/exhaustive-deps
  523. return useMemo(() => FieldComponent, [...shouldUpdate]);
  524. } else {
  525. // Some Custom Component with inner state shouldn't be memo, otherwise the component will not updated when the internal state is updated
  526. return FieldComponent;
  527. }
  528. };
  529. SemiField = forwardRef(SemiField);
  530. (SemiField as React.FC).displayName = getDisplayName(Component);
  531. return SemiField as any;
  532. }
  533. // eslint-disable-next-line
  534. export default withField;