withField.tsx 24 KB

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