arrayField.tsx 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. /* eslint-disable react/destructuring-assignment */
  2. import React, { Component } from 'react';
  3. import { getUuidv4 } from '@douyinfe/semi-foundation/utils/uuid';
  4. import { cloneDeep, isUndefined } from 'lodash';
  5. import { FormUpdaterContext, ArrayFieldContext } from './context';
  6. import warning from '@douyinfe/semi-foundation/utils/warning';
  7. import { ArrayFieldStaff, FormUpdaterContextType } from '@douyinfe/semi-foundation/form/interface';
  8. export interface ArrayFieldProps {
  9. initValue?: any[];
  10. field?: string;
  11. children?: (props: ArrayFieldChildrenProps) => React.ReactNode;
  12. }
  13. export interface ArrayFieldChildrenProps {
  14. arrayFields: {
  15. key: string;
  16. field: string;
  17. remove: () => void;
  18. }[];
  19. add: () => void;
  20. addWithInitValue: (lineObject: Record<string, any>) => void;
  21. }
  22. export interface ArrayFieldState {
  23. keys: string[];
  24. }
  25. const filterArrayByIndex = (array: any[], index: number) => array.filter((item, i) => i !== index);
  26. const getUuidByArray = (array: any[]) => array.map(() => getUuidv4());
  27. const getUpdateKey = (arrayField: ArrayFieldStaff): string | undefined => {
  28. if (!arrayField) {
  29. return undefined;
  30. }
  31. if (arrayField && arrayField.updateKey) {
  32. return arrayField.updateKey;
  33. }
  34. return undefined;
  35. };
  36. const initValueAdapter = (initValue: any) => {
  37. const iv: any[] = [];
  38. if (Array.isArray(initValue)) {
  39. return initValue;
  40. } else {
  41. warning(
  42. !isUndefined(initValue),
  43. '[Semi Form ArrayField] initValue of ArrayField must be an array. Please check the type of your props'
  44. );
  45. return iv;
  46. }
  47. };
  48. /**
  49. *
  50. * @param {any[]} value
  51. * @param {string[]} oldKeys
  52. * @returns string[]
  53. */
  54. const generateKeys = (value: any[], oldKeys?: string[]) => {
  55. const val = initValueAdapter(value);
  56. const newKeys = getUuidByArray(val);
  57. // return newKeys;
  58. const keys = newKeys.map((key, i) => (oldKeys && oldKeys[i] ? oldKeys[i] : key));
  59. return keys;
  60. };
  61. class ArrayFieldComponent extends Component<ArrayFieldProps, ArrayFieldState> {
  62. static contextType = FormUpdaterContext;
  63. cacheFieldValues: any[];
  64. shouldUseInitValue: boolean;
  65. cacheUpdateKey: string;
  66. constructor(props: ArrayFieldProps, context: FormUpdaterContextType) {
  67. super(props, context);
  68. const initValueInProps = this.props.initValue;
  69. const { field } = this.props;
  70. const initValueInForm = context.getValue(field);
  71. const initValue = initValueInProps || initValueInForm;
  72. this.state = {
  73. keys: generateKeys(initValue),
  74. };
  75. this.add = this.add.bind(this);
  76. this.addWithInitValue = this.addWithInitValue.bind(this);
  77. this.remove = this.remove.bind(this);
  78. this.cacheFieldValues = null;
  79. this.cacheUpdateKey = null;
  80. /*
  81. If updateKey exists, it means that the arrayField (usually a nested ArrayField not at the first level) is only re-mounted due to setValues,
  82. and the fields it contains do not need to consume initValue
  83. */
  84. // whether the fields inside arrayField should use props.initValue in current render process
  85. this.shouldUseInitValue = !context.getArrayField(field);
  86. // Separate the arrays that reset and the usual add and remove modify, otherwise they will affect each other
  87. const initValueCopyForFormState = cloneDeep(initValue);
  88. const initValueCopyForReset = cloneDeep(initValue);
  89. context.registerArrayField(field, initValueCopyForReset);
  90. // register ArrayField will update state.updateKey to render, So there is no need to execute forceUpdate here
  91. context.updateStateValue(field, initValueCopyForFormState, { notNotify: true, notUpdate: true });
  92. }
  93. componentWillUnmount() {
  94. const updater = this.context;
  95. const { field } = this.props;
  96. updater.unRegisterArrayField(field);
  97. }
  98. componentDidUpdate() {
  99. const updater = this.context;
  100. const { field } = this.props;
  101. const { keys } = this.state;
  102. const fieldValues = updater.getValue(field);
  103. const updateKey = getUpdateKey(updater.getArrayField(field));
  104. // when update form outside, like use formApi.setValue('field', [{newItem1, newItem2}]), formApi.setValues
  105. // re generate keys to update arrayField;
  106. if (updateKey !== this.cacheUpdateKey) {
  107. const newKeys = generateKeys(fieldValues, keys);
  108. // eslint-disable-next-line
  109. this.setState({ keys: newKeys });
  110. this.cacheUpdateKey = updateKey;
  111. if (this.cacheUpdateKey !== null) {
  112. this.shouldUseInitValue = false;
  113. }
  114. }
  115. }
  116. add() {
  117. const { keys } = this.state;
  118. keys.push(getUuidv4());
  119. this.shouldUseInitValue = true;
  120. this.setState({ keys });
  121. }
  122. addWithInitValue(lineObject: Record<string, any>) {
  123. const updater = this.context;
  124. const { field } = this.props;
  125. const newArrayFieldVal = updater.getValue(field) ? updater.getValue(field).slice() : [];
  126. newArrayFieldVal.push(lineObject);
  127. updater.updateStateValue(field, newArrayFieldVal, {});
  128. updater.updateArrayField(field, { updateKey: new Date().valueOf() });
  129. }
  130. remove(i: number) {
  131. const updater = this.context;
  132. const { keys } = this.state;
  133. const { field } = this.props;
  134. const newKeys = filterArrayByIndex(keys, i);
  135. // Make sure that all the keys in the line are removed, because some keys are not taken over by the field, only set in the initValue
  136. let newArrayFieldError = updater.getError(field);
  137. const opts = { notNotify: true, notUpdate: true };
  138. if (Array.isArray(newArrayFieldError)) {
  139. newArrayFieldError = newArrayFieldError.slice();
  140. newArrayFieldError.splice(i, 1);
  141. updater.updateStateError(field, newArrayFieldError, opts);
  142. }
  143. // if (Array.isArray(newArrayFieldTouched)) {
  144. // newArrayFieldTouched = newArrayFieldTouched.slice();
  145. // newArrayFieldTouched.splice(i, 1);
  146. // updater.updateStateTouched(field, newArrayFieldTouched, opts);
  147. // }
  148. let newArrayFieldValue = updater.getValue(field);
  149. if (Array.isArray(newArrayFieldValue)) {
  150. newArrayFieldValue = newArrayFieldValue.slice();
  151. newArrayFieldValue.splice(i, 1);
  152. updater.updateStateValue(field, newArrayFieldValue);
  153. }
  154. this.setState({ keys: newKeys });
  155. }
  156. render() {
  157. const { children, field } = this.props;
  158. const { keys } = this.state;
  159. const arrayFields = keys.map((key, i) => ({
  160. // key: i,
  161. key,
  162. field: `${field}[${i}]`,
  163. remove: () => this.remove(i),
  164. }));
  165. const { add } = this;
  166. const { addWithInitValue } = this;
  167. const contextVal = {
  168. shouldUseInitValue: this.shouldUseInitValue,
  169. };
  170. return (
  171. <ArrayFieldContext.Provider value={contextVal}>
  172. {children({ arrayFields, add, addWithInitValue })}
  173. </ArrayFieldContext.Provider>
  174. );
  175. }
  176. }
  177. export default ArrayFieldComponent;