arrayField.tsx 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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, isEqual, get } from 'lodash';
  5. import { FormUpdaterContext, ArrayFieldContext } from './context';
  6. import warning from '@douyinfe/semi-foundation/utils/warning';
  7. import type { 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. // // TODO
  32. // if (arrayField && arrayField.updateKey) {
  33. // return arrayField.updateKey;
  34. // }
  35. // return undefined;
  36. // };
  37. const initValueAdapter = (initValue: any) => {
  38. const iv: any[] = [];
  39. if (Array.isArray(initValue)) {
  40. return initValue;
  41. } else {
  42. warning(
  43. !isUndefined(initValue),
  44. '[Semi Form ArrayField] initValue of ArrayField must be an array. Please check the type of your props'
  45. );
  46. return iv;
  47. }
  48. };
  49. /**
  50. *
  51. * @param {any[]} value
  52. * @param {string[]} oldKeys
  53. * @param {any[]} cacheValue
  54. * @returns string[]
  55. */
  56. const generateKeys = (value: any[] = [], oldKeys?: string[], cacheValues: any[] = []) => {
  57. const val = initValueAdapter(value);
  58. const newKeys = getUuidByArray(val);
  59. const keys = [];
  60. // todo cacheValue 与 oldKeys 是对不上的
  61. value.forEach((newRow, i) => {
  62. const cacheRow = get(cacheValues, i);
  63. if (!isEqual(newRow, cacheRow)) {
  64. keys[i] = newKeys[i];
  65. } else {
  66. keys[i] = oldKeys && oldKeys[i] ? oldKeys[i] : newKeys[i];
  67. }
  68. });
  69. return keys;
  70. };
  71. class ArrayFieldComponent extends Component<ArrayFieldProps, ArrayFieldState> {
  72. static contextType = FormUpdaterContext;
  73. cacheFieldValues: any[] | null;
  74. shouldUseInitValue: boolean;
  75. // cacheUpdateKey: string;
  76. context: FormUpdaterContextType;
  77. constructor(props: ArrayFieldProps, context: FormUpdaterContextType) {
  78. super(props, context);
  79. const initValueInProps = this.props.initValue;
  80. const { field } = this.props;
  81. const initValueInForm = context.getValue(field);
  82. const initValue = initValueInProps || initValueInForm;
  83. this.state = {
  84. keys: generateKeys(initValue),
  85. };
  86. this.add = this.add.bind(this);
  87. this.addWithInitValue = this.addWithInitValue.bind(this);
  88. this.remove = this.remove.bind(this);
  89. this.cacheFieldValues = initValue;
  90. // /*
  91. // If updateKey exists, it means that the arrayField (usually a nested ArrayField not at the first level) is only re-mounted due to setValues,
  92. // and the fields it contains do not need to consume initValue
  93. // */
  94. // // whether the fields inside arrayField should use props.initValue in current render process
  95. // this.shouldUseInitValue = !context.getArrayField(field);
  96. // Separate the arrays that reset and the usual add and remove modify, otherwise they will affect each other
  97. const initValueCopyForFormState = cloneDeep(initValue);
  98. const initValueCopyForReset = cloneDeep(initValue);
  99. context.registerArrayField(field, { initValue: initValueCopyForReset, forceUpdate: this.forceUpdate });
  100. context.updateStateValue(field, initValueCopyForFormState, { notNotify: true, notUpdate: true });
  101. }
  102. componentDidMount() {
  103. // const { field } = this.props;
  104. // const updater = this.context;
  105. // updater.updateArrayField(field, { forceUpdate: this.forceUpdate });
  106. }
  107. componentWillUnmount() {
  108. const updater = this.context;
  109. const { field } = this.props;
  110. updater.unRegisterArrayField(field);
  111. }
  112. // componentDidUpdate() {
  113. // const updater = this.context;
  114. // // const { field } = this.props;
  115. // // const { keys } = this.state;
  116. // // const fieldValues = updater.getValue(field);
  117. // // const updateKey = getUpdateKey(updater.getArrayField(field));
  118. // // // when update form outside, like use formApi.setValue('field', [{newItem1, newItem2}]), formApi.setValues
  119. // // // re generate keys to update arrayField;
  120. // // if (updateKey !== this.cacheUpdateKey) {
  121. // // const newKeys = generateKeys(fieldValues, keys);
  122. // // // eslint-disable-next-line
  123. // // this.setState({ keys: newKeys });
  124. // // this.cacheUpdateKey = updateKey;
  125. // // if (this.cacheUpdateKey !== null) {
  126. // // this.shouldUseInitValue = false;
  127. // // }
  128. // // } else {
  129. // // console.log('not update');
  130. // // }
  131. // }
  132. forceUpdate = (value?: any): void => {
  133. const updater = this.context;
  134. const { field } = this.props;
  135. const { keys } = this.state;
  136. console.log(this.cacheFieldValues);
  137. const fieldValues = value ? value : updater.getValue(field);
  138. // TODO fieldValues 如果长度相同,keys目前仍会相同,需要为新的
  139. const newKeys = generateKeys(fieldValues, keys, this.cacheFieldValues);
  140. // eslint-disable-next-line
  141. this.setState({ keys: newKeys });
  142. this.cacheFieldValues = [...value];
  143. }
  144. add() {
  145. const { keys } = this.state;
  146. keys.push(getUuidv4());
  147. // this.shouldUseInitValue = true;
  148. // TODO allowEmpty 为 false 的情况下
  149. this.setState({ keys });
  150. }
  151. addWithInitValue(lineObject: Record<string, any>) {
  152. const updater = this.context;
  153. const { field } = this.props;
  154. const newArrayFieldVal = updater.getValue(field) ? updater.getValue(field).slice() : [];
  155. newArrayFieldVal.push(lineObject);
  156. updater.updateStateValue(field, newArrayFieldVal, {});
  157. updater.updateArrayField(field, { updateValue: newArrayFieldVal });
  158. }
  159. remove(i: number) {
  160. const updater = this.context;
  161. const { keys } = this.state;
  162. const { field } = this.props;
  163. const newKeys = filterArrayByIndex(keys, i);
  164. // 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
  165. let newArrayFieldError = updater.getError(field);
  166. const opts = { notNotify: true, notUpdate: true };
  167. if (Array.isArray(newArrayFieldError)) {
  168. newArrayFieldError = newArrayFieldError.slice();
  169. newArrayFieldError.splice(i, 1);
  170. updater.updateStateError(field, newArrayFieldError, opts);
  171. }
  172. // if (Array.isArray(newArrayFieldTouched)) {
  173. // newArrayFieldTouched = newArrayFieldTouched.slice();
  174. // newArrayFieldTouched.splice(i, 1);
  175. // updater.updateStateTouched(field, newArrayFieldTouched, opts);
  176. // }
  177. let newArrayFieldValue = updater.getValue(field);
  178. if (Array.isArray(newArrayFieldValue)) {
  179. newArrayFieldValue = newArrayFieldValue.slice();
  180. newArrayFieldValue.splice(i, 1);
  181. updater.updateStateValue(field, newArrayFieldValue);
  182. }
  183. this.setState({ keys: newKeys });
  184. this.cacheFieldValues = [...newArrayFieldValue];
  185. }
  186. render() {
  187. const { children, field } = this.props;
  188. const { keys } = this.state;
  189. const arrayFields = keys.map((key, i) => ({
  190. key,
  191. field: `${field}[${i}]`,
  192. remove: () => this.remove(i),
  193. }));
  194. const { add } = this;
  195. const { addWithInitValue } = this;
  196. const contextVal = {
  197. // shouldUseInitValue: this.shouldUseInitValue,
  198. };
  199. return (
  200. <ArrayFieldContext.Provider value={contextVal}>
  201. {children({ arrayFields, add, addWithInitValue })}
  202. </ArrayFieldContext.Provider>
  203. );
  204. }
  205. }
  206. export default ArrayFieldComponent;