withField.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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. // field value may change after field component mounted, we use ref value here to get changed value
  347. const refValue = getVal();
  348. updater.register(
  349. field,
  350. {
  351. value: refValue,
  352. error,
  353. touched,
  354. status,
  355. },
  356. {
  357. field,
  358. fieldApi,
  359. keepState,
  360. allowEmpty: allowEmpty || allowEmptyString,
  361. }
  362. );
  363. // return unRegister cb
  364. return () => {
  365. updater.unRegister(field);
  366. // log('unRegister: ' + field);
  367. };
  368. // eslint-disable-next-line react-hooks/exhaustive-deps
  369. }, [field]);
  370. let formProps = updater.getFormProps([
  371. 'labelPosition',
  372. 'labelWidth',
  373. 'labelAlign',
  374. 'labelCol',
  375. 'wrapperCol',
  376. 'disabled',
  377. 'showValidateIcon',
  378. 'extraTextPosition',
  379. ]);
  380. let mergeLabelPos = labelPosition || formProps.labelPosition;
  381. let mergeLabelWidth = labelWidth || formProps.labelWidth;
  382. let mergeLabelAlign = labelAlign || formProps.labelAlign;
  383. let mergeLabelCol = labelCol || formProps.labelCol;
  384. let mergeWrapperCol = wrapperCol || formProps.wrapperCol;
  385. let mergeExtraPos = extraTextPosition || formProps.extraTextPosition || 'bottom';
  386. // id attribute to improve a11y
  387. const a11yId = id ? id : field;
  388. const labelId = `${a11yId}-label`;
  389. const helpTextId = `${a11yId}-helpText`;
  390. const extraTextId = `${a11yId}-extraText`;
  391. const errorMessageId = `${a11yId}-errormessage`;
  392. let FieldComponent = (() => {
  393. // prefer to use validateStatus which pass by user throught props
  394. let blockStatus = validateStatus ? validateStatus : status;
  395. const extraCls = classNames(`${prefix}-field-extra`, {
  396. [`${prefix}-field-extra-string`]: typeof extraText === 'string',
  397. [`${prefix}-field-extra-middle`]: mergeExtraPos === 'middle',
  398. [`${prefix}-field-extra-botttom`]: mergeExtraPos === 'bottom',
  399. });
  400. const extraContent = extraText ? <div className={extraCls} id={extraTextId}>{extraText}</div> : null;
  401. let newProps: Record<string, any> = {
  402. id: a11yId,
  403. disabled: formProps.disabled,
  404. ...rest,
  405. ref,
  406. onBlur: handleBlur,
  407. [options.onKeyChangeFnName]: handleChange,
  408. [options.valueKey]: value,
  409. validateStatus: blockStatus,
  410. 'aria-required': required,
  411. 'aria-labelledby': labelId,
  412. };
  413. if (helpText) {
  414. newProps['aria-describedby'] = extraText ? `${helpTextId} ${extraTextId}` : helpTextId;
  415. }
  416. if (extraText) {
  417. newProps['aria-describedby'] = helpText ? `${helpTextId} ${extraTextId}` : extraTextId;
  418. }
  419. if (status === 'error') {
  420. newProps['aria-errormessage'] = errorMessageId;
  421. newProps['aria-invalid'] = true;
  422. }
  423. const fieldCls = classNames({
  424. [`${prefix}-field`]: true,
  425. [`${prefix}-field-${name}`]: Boolean(name),
  426. [fieldClassName]: Boolean(fieldClassName),
  427. });
  428. const fieldMaincls = classNames({
  429. [`${prefix}-field-main`]: true,
  430. });
  431. if (mergeLabelPos === 'inset' && !noLabel) {
  432. newProps.insetLabel = label || field;
  433. newProps.insetLabelId = labelId;
  434. if (typeof label === 'object' && !isElement(label)) {
  435. newProps.insetLabel = label.text;
  436. newProps.insetLabelId = labelId;
  437. }
  438. }
  439. const com = <Component {...(newProps as any)} />;
  440. // when use in InputGroup, no need to insert <Label>、<ErrorMessage> inside Field, just add it at Group
  441. if (isInInputGroup) {
  442. return com;
  443. }
  444. if (pure) {
  445. let pureCls = classNames(rest.className, {
  446. [`${prefix}-field-pure`]: true,
  447. [`${prefix}-field-${name}`]: Boolean(name),
  448. [fieldClassName]: Boolean(fieldClassName),
  449. });
  450. newProps.className = pureCls;
  451. return <Component {...(newProps as any)} />;
  452. }
  453. let withCol = mergeLabelCol && mergeWrapperCol;
  454. const labelColCls = mergeLabelAlign ? `${prefix}-col-${mergeLabelAlign}` : '';
  455. // get label
  456. let labelContent = null;
  457. if (!noLabel && mergeLabelPos !== 'inset') {
  458. let needSpread = typeof label === 'object' && !isElement(label) ? label : {};
  459. labelContent = (
  460. <Label
  461. text={label || field}
  462. id={labelId}
  463. required={required}
  464. name={a11yId || name || field}
  465. width={mergeLabelWidth}
  466. align={mergeLabelAlign}
  467. {...needSpread}
  468. />
  469. );
  470. }
  471. const fieldMainContent = (
  472. <div className={fieldMaincls}>
  473. {mergeExtraPos === 'middle' ? extraContent : null}
  474. {com}
  475. {!noErrorMessage ? (
  476. <ErrorMessage
  477. error={error}
  478. validateStatus={blockStatus}
  479. helpText={helpText}
  480. helpTextId={helpTextId}
  481. errorMessageId={errorMessageId}
  482. showValidateIcon={formProps.showValidateIcon}
  483. />
  484. ) : null}
  485. {mergeExtraPos === 'bottom' ? extraContent : null}
  486. </div>
  487. );
  488. const withColContent = (
  489. <>
  490. {mergeLabelPos === 'top' ? (
  491. <div style={{ overflow: 'hidden' }}>
  492. <Col {...mergeLabelCol} className={labelColCls}>
  493. {labelContent}
  494. </Col>
  495. </div>
  496. ) : (
  497. <Col {...mergeLabelCol} className={labelColCls}>
  498. {labelContent}
  499. </Col>
  500. )}
  501. <Col {...mergeWrapperCol}>{fieldMainContent}</Col>
  502. </>
  503. );
  504. return (
  505. <div
  506. className={fieldCls}
  507. style={fieldStyle}
  508. x-label-pos={mergeLabelPos}
  509. x-field-id={field}
  510. x-extra-pos={mergeExtraPos}
  511. >
  512. {withCol ? (
  513. withColContent
  514. ) : (
  515. <>
  516. {labelContent}
  517. {fieldMainContent}
  518. </>
  519. )}
  520. </div>
  521. );
  522. })();
  523. // !important optimization
  524. const shouldUpdate = [
  525. ...Object.values(fieldState),
  526. ...Object.values(props),
  527. field,
  528. mergeLabelPos,
  529. mergeLabelAlign,
  530. formProps.disabled,
  531. ];
  532. if (options.shouldMemo) {
  533. // eslint-disable-next-line react-hooks/exhaustive-deps
  534. return useMemo(() => FieldComponent, [...shouldUpdate]);
  535. } else {
  536. // Some Custom Component with inner state shouldn't be memo, otherwise the component will not updated when the internal state is updated
  537. return FieldComponent;
  538. }
  539. };
  540. SemiField = forwardRef(SemiField);
  541. (SemiField as React.FC).displayName = getDisplayName(Component);
  542. return SemiField as any;
  543. }
  544. // eslint-disable-next-line
  545. export default withField;