1
0

withField.tsx 24 KB

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