1
0

withField.tsx 23 KB

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