withField.tsx 23 KB

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