withField.tsx 24 KB

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