withField.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  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. console.warn(`[Semi Form]: When FieldComponent (${field}) has an unfinished validation process, you repeatedly trigger a new validation, the old validation will be abandoned, and will neither resolve nor reject. Usually this is an unreasonable practice. Please check your code.`);
  200. return;
  201. }
  202. // validation passed
  203. setStatus('success');
  204. updateError(undefined, callOpts);
  205. resolve({});
  206. })
  207. .catch(err => {
  208. if (isUnmounted.current || validatePromise.current !== rootPromise) {
  209. console.warn(`[Semi Form]: When FieldComponent (${field}) has an unfinished validation process, you repeatedly trigger a new validation, the old validation will be abandoned, and will neither resolve nor reject. Usually this is an unreasonable practice. Please check your code.`);
  210. return;
  211. }
  212. let { errors, fields } = err;
  213. if (errors && fields) {
  214. let messages = errors.map((e: any) => e.message);
  215. if (messages.length === 1) {
  216. messages = messages[0];
  217. }
  218. updateError(messages, callOpts);
  219. if (!isValid(messages)) {
  220. setStatus('error');
  221. resolve(errors);
  222. }
  223. } else {
  224. // Some grammatical errors in rules
  225. setStatus('error');
  226. updateError(err.message, callOpts);
  227. resolve(err.message);
  228. throw err;
  229. }
  230. });
  231. });
  232. validatePromise.current = rootPromise;
  233. return rootPromise;
  234. };
  235. // execute custom validate function
  236. const _validate = (val: any, values: any, callOpts: CallOpts) => {
  237. const rootPromise = new Promise(resolve => {
  238. let maybePromisedErrors;
  239. // let errorThrowSync;
  240. try {
  241. maybePromisedErrors = validateRef.current(val, values);
  242. } catch (err) {
  243. // error throw by syncValidate
  244. maybePromisedErrors = err;
  245. }
  246. if (maybePromisedErrors === undefined) {
  247. resolve({});
  248. updateError(undefined, callOpts);
  249. } else if (isPromise(maybePromisedErrors)) {
  250. maybePromisedErrors.then((result: any) => {
  251. // If the async validate is outdated (a newer validate occurs), the result should be discarded
  252. if (isUnmounted.current || validatePromise.current !== rootPromise) {
  253. console.warn(`[Semi Form]: When Field: (${field}) has an unfinished validation process, you repeatedly trigger a new validation, the old validation will be abandoned, and will neither resolve nor reject. Usually this is an unreasonable practice. Please check your code.`);
  254. return;
  255. }
  256. if (isValid(result)) {
  257. // validate success,no need to do anything with result
  258. updateError(undefined, callOpts);
  259. resolve(null);
  260. } else {
  261. // validate failed
  262. updateError(result, callOpts);
  263. resolve(result);
  264. }
  265. });
  266. } else {
  267. if (isValid(maybePromisedErrors)) {
  268. updateError(undefined, callOpts);
  269. resolve(null);
  270. } else {
  271. updateError(maybePromisedErrors, callOpts);
  272. resolve(maybePromisedErrors);
  273. }
  274. }
  275. });
  276. validatePromise.current = rootPromise;
  277. return rootPromise;
  278. };
  279. const fieldValidate = (val: any, callOpts?: CallOpts) => {
  280. let finalVal = val;
  281. let latestRules = rulesRef.current;
  282. if (transform) {
  283. finalVal = transform(val);
  284. }
  285. if (validateRef.current) {
  286. return _validate(finalVal, updater.getValue(), callOpts);
  287. } else if (latestRules) {
  288. return _validateInternal(finalVal, callOpts);
  289. }
  290. return null;
  291. };
  292. /**
  293. * parse / format
  294. * validate when trigger
  295. *
  296. */
  297. const handleChange = (newValue: any, e: any, ...other: any[]) => {
  298. let fnKey = options.onKeyChangeFnName;
  299. if (fnKey in props && typeof props[options.onKeyChangeFnName] === 'function') {
  300. props[options.onKeyChangeFnName](newValue, e, ...other);
  301. }
  302. // support various type component
  303. let val;
  304. if (!options.valuePath) {
  305. val = newValue;
  306. } else {
  307. val = ObjectUtil.get(newValue, options.valuePath);
  308. }
  309. // User can use convert function to updateValue before Component UI render
  310. if (typeof convert === 'function') {
  311. val = convert(val);
  312. }
  313. // TODO: allowEmptyString split into allowEmpty, emptyValue
  314. // Added abandonment warning
  315. // if (process.env.NODE_ENV !== 'production') {
  316. // warning(allowEmptyString, `'allowEmptyString' will be de deprecated in next version, please replace with 'allowEmpty' & 'emptyValue'
  317. // `)
  318. // }
  319. // set value to undefined if it's an empty string
  320. // allowEmptyString={true} is equivalent to allowEmpty = {true} emptyValue = "
  321. if (allowEmptyString || allowEmpty) {
  322. if (val === '') {
  323. // do nothing
  324. }
  325. } else {
  326. if (val === emptyValue) {
  327. val = undefined;
  328. }
  329. }
  330. // maintain compoent cursor if needed
  331. try {
  332. if (e && e.target && e.target.selectionStart) {
  333. setCursor(e.target.selectionStart);
  334. }
  335. } catch (err) {}
  336. updateTouched(true, { notNotify: true, notUpdate: true });
  337. updateValue(val);
  338. // only validate when trigger includes change
  339. if (mergeTrigger.includes('change')) {
  340. fieldValidate(val);
  341. }
  342. };
  343. const handleBlur = (...e: any[]) => {
  344. if (props.onBlur) {
  345. props.onBlur(...e);
  346. }
  347. if (!touched) {
  348. updateTouched(true);
  349. }
  350. if (mergeTrigger.includes('blur')) {
  351. let val = getVal();
  352. fieldValidate(val);
  353. }
  354. };
  355. /** Field level maintains a separate layer of data, which is convenient for Form to control Field to update the UI */
  356. // The field level maintains a separate layer of data, which is convenient for the Form to control the Field for UI updates.
  357. const fieldApi = {
  358. setValue: updateValue,
  359. setTouched: updateTouched,
  360. setError: updateError,
  361. reset,
  362. validate: fieldValidate,
  363. };
  364. const fieldState = {
  365. value,
  366. error,
  367. touched,
  368. status,
  369. };
  370. // avoid hooks capture value, fixed issue 346
  371. useIsomorphicEffect(() => {
  372. rulesRef.current = rules;
  373. validateRef.current = validate;
  374. }, [rules, validate]);
  375. useIsomorphicEffect(() => {
  376. isUnmounted.current = false;
  377. // exec validate once when trigger include 'mount'
  378. if (validateOnMount) {
  379. fieldValidate(value);
  380. }
  381. return () => {
  382. isUnmounted.current = true;
  383. };
  384. // eslint-disable-next-line react-hooks/exhaustive-deps
  385. }, []);
  386. // register when mounted,unregister when unmounted
  387. // register again when field change
  388. useIsomorphicEffect(() => {
  389. // register
  390. if (typeof field === 'undefined') {
  391. return () => {};
  392. }
  393. // log('register: ' + field);
  394. // field value may change after field component mounted, we use ref value here to get changed value
  395. const refValue = getVal();
  396. updater.register(
  397. field,
  398. {
  399. value: refValue,
  400. error,
  401. touched,
  402. status,
  403. },
  404. {
  405. field,
  406. fieldApi,
  407. keepState,
  408. allowEmpty: allowEmpty || allowEmptyString,
  409. }
  410. );
  411. // return unRegister cb
  412. return () => {
  413. updater.unRegister(field);
  414. // log('unRegister: ' + field);
  415. };
  416. // eslint-disable-next-line react-hooks/exhaustive-deps
  417. }, [field]);
  418. // id attribute to improve a11y
  419. const a11yId = id ? id : field;
  420. const labelId = `${a11yId}-label`;
  421. const helpTextId = `${a11yId}-helpText`;
  422. const extraTextId = `${a11yId}-extraText`;
  423. const errorMessageId = `${a11yId}-errormessage`;
  424. const FieldComponent = () => {
  425. // prefer to use validateStatus which pass by user throught props
  426. let blockStatus = validateStatus ? validateStatus : status;
  427. const extraCls = classNames(`${prefix}-field-extra`, {
  428. [`${prefix}-field-extra-string`]: typeof extraText === 'string',
  429. [`${prefix}-field-extra-middle`]: mergeExtraPos === 'middle',
  430. [`${prefix}-field-extra-bottom`]: mergeExtraPos === 'bottom',
  431. });
  432. const extraContent = extraText ? <div className={extraCls} id={extraTextId} x-semi-prop="extraText">{extraText}</div> : null;
  433. let newProps: Record<string, any> = {
  434. id: a11yId,
  435. disabled: formProps.disabled,
  436. ...rest,
  437. ref,
  438. onBlur: handleBlur,
  439. [options.onKeyChangeFnName]: handleChange,
  440. [options.valueKey]: value,
  441. validateStatus: blockStatus,
  442. 'aria-required': required,
  443. 'aria-labelledby': labelId,
  444. };
  445. if (name) {
  446. newProps['name'] = name;
  447. }
  448. if (helpText) {
  449. newProps['aria-describedby'] = extraText ? `${helpTextId} ${extraTextId}` : helpTextId;
  450. }
  451. if (extraText) {
  452. newProps['aria-describedby'] = helpText ? `${helpTextId} ${extraTextId}` : extraTextId;
  453. }
  454. if (status === 'error') {
  455. newProps['aria-errormessage'] = errorMessageId;
  456. newProps['aria-invalid'] = true;
  457. }
  458. const fieldCls = classNames({
  459. [`${prefix}-field`]: true,
  460. [`${prefix}-field-${name}`]: Boolean(name),
  461. [fieldClassName]: Boolean(fieldClassName),
  462. });
  463. const fieldMaincls = classNames({
  464. [`${prefix}-field-main`]: true,
  465. });
  466. if (mergeLabelPos === 'inset' && !noLabel) {
  467. newProps.insetLabel = label || field;
  468. newProps.insetLabelId = labelId;
  469. if (typeof label === 'object' && !isElement(label)) {
  470. newProps.insetLabel = label.text;
  471. newProps.insetLabelId = labelId;
  472. }
  473. }
  474. const com = <Component {...(newProps as any)} />;
  475. // when use in InputGroup, no need to insert <Label>、<ErrorMessage> inside Field, just add it at Group
  476. if (isInInputGroup) {
  477. return com;
  478. }
  479. if (pure) {
  480. let pureCls = classNames(rest.className, {
  481. [`${prefix}-field-pure`]: true,
  482. [`${prefix}-field-${name}`]: Boolean(name),
  483. [fieldClassName]: Boolean(fieldClassName),
  484. });
  485. newProps.className = pureCls;
  486. return <Component {...(newProps as any)} />;
  487. }
  488. let withCol = mergeLabelCol && mergeWrapperCol;
  489. const labelColCls = mergeLabelAlign ? `${prefix}-col-${mergeLabelAlign}` : '';
  490. // get label
  491. let labelContent = null;
  492. if (!noLabel && mergeLabelPos !== 'inset') {
  493. let needSpread = typeof label === 'object' && !isElement(label) ? label : {};
  494. labelContent = (
  495. <Label
  496. text={label || field}
  497. id={labelId}
  498. required={required}
  499. name={a11yId || name || field}
  500. width={mergeLabelWidth}
  501. align={mergeLabelAlign}
  502. {...needSpread}
  503. />
  504. );
  505. }
  506. const fieldMainContent = (
  507. <div className={fieldMaincls}>
  508. {mergeExtraPos === 'middle' ? extraContent : null}
  509. {com}
  510. {!noErrorMessage ? (
  511. <ErrorMessage
  512. error={error}
  513. validateStatus={blockStatus}
  514. helpText={helpText}
  515. helpTextId={helpTextId}
  516. errorMessageId={errorMessageId}
  517. showValidateIcon={formProps.showValidateIcon}
  518. />
  519. ) : null}
  520. {mergeExtraPos === 'bottom' ? extraContent : null}
  521. </div>
  522. );
  523. const withColContent = (
  524. <>
  525. {mergeLabelPos === 'top' ? (
  526. <div style={{ overflow: 'hidden' }}>
  527. <Col {...mergeLabelCol} className={labelColCls}>
  528. {labelContent}
  529. </Col>
  530. </div>
  531. ) : (
  532. <Col {...mergeLabelCol} className={labelColCls}>
  533. {labelContent}
  534. </Col>
  535. )}
  536. <Col {...mergeWrapperCol}>{fieldMainContent}</Col>
  537. </>
  538. );
  539. return (
  540. <div
  541. className={fieldCls}
  542. style={fieldStyle}
  543. x-label-pos={mergeLabelPos}
  544. x-field-id={field}
  545. x-extra-pos={mergeExtraPos}
  546. >
  547. {withCol ? (
  548. withColContent
  549. ) : (
  550. <>
  551. {labelContent}
  552. {fieldMainContent}
  553. </>
  554. )}
  555. </div>
  556. );
  557. };
  558. // !important optimization
  559. const shouldUpdate = [
  560. ...Object.values(fieldState),
  561. ...Object.values(props),
  562. field,
  563. mergeLabelPos,
  564. mergeLabelAlign,
  565. formProps.disabled,
  566. ];
  567. if (options.shouldMemo) {
  568. // eslint-disable-next-line react-hooks/exhaustive-deps
  569. return useMemo(FieldComponent, [...shouldUpdate]);
  570. } else {
  571. // Some Custom Component with inner state shouldn't be memo, otherwise the component will not updated when the internal state is updated
  572. return FieldComponent();
  573. }
  574. };
  575. SemiField = forwardRef(SemiField);
  576. (SemiField as React.FC).displayName = getDisplayName(Component);
  577. return SemiField as any;
  578. }
  579. // eslint-disable-next-line
  580. export default withField;