arrayField.tsx 6.9 KB

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