withField.tsx 24 KB

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