withField.tsx 22 KB

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