| 132 | } |
| 133 | |
| 134 | export function createFieldArrayApi<T extends Record<string, unknown>>(options: { |
| 135 | state: FormState<T>; |
| 136 | validateOnChange: boolean | undefined; |
| 137 | initialValuesRef: { current: T }; |
| 138 | fieldArrayKeysRef: FieldArrayKeysRef<T>; |
| 139 | fieldArrayKeyCounterRef: CounterRef; |
| 140 | pendingAsyncValuesRef: { current: T | null }; |
| 141 | asyncValidatorRef: AsyncValidatorRef<T>; |
| 142 | updateFormState: UpdateFormState<T>; |
| 143 | isFieldEditableInternal: ( |
| 144 | field: keyof T, |
| 145 | source?: Pick<FormState<T>, "disabled" | "fieldDisabled" | "readOnly" | "fieldReadOnly">, |
| 146 | ) => boolean; |
| 147 | runSyncValidationFiltered: ( |
| 148 | values: T, |
| 149 | source?: Pick<FormState<T>, "disabled" | "fieldDisabled">, |
| 150 | ) => ValidationResult<T>; |
| 151 | }): Readonly<{ |
| 152 | useFieldArray: <K extends ArrayFieldName<T>>(field: K) => UseFieldArrayReturn<T, K>; |
| 153 | }> { |
| 154 | const useFieldArray = <K extends ArrayFieldName<T>>(field: K): UseFieldArrayReturn<T, K> => { |
| 155 | const fieldKey = field as keyof T; |
| 156 | const values = getArrayFieldValues(options.state.values, field); |
| 157 | const keys = ensureFieldArrayKeys( |
| 158 | fieldKey, |
| 159 | values.length, |
| 160 | options.fieldArrayKeysRef, |
| 161 | options.fieldArrayKeyCounterRef, |
| 162 | ); |
| 163 | |
| 164 | const append = (item: ArrayFieldItem<T, K>): void => { |
| 165 | options.pendingAsyncValuesRef.current = null; |
| 166 | |
| 167 | options.updateFormState((prev) => { |
| 168 | if (prev.isSubmitting || !options.isFieldEditableInternal(fieldKey, prev)) { |
| 169 | return prev; |
| 170 | } |
| 171 | |
| 172 | const currentValues = getArrayFieldValues(prev.values, field); |
| 173 | const nextValuesArray = [...currentValues, item]; |
| 174 | const nextValues = { |
| 175 | ...prev.values, |
| 176 | [field]: nextValuesArray as unknown as T[K], |
| 177 | }; |
| 178 | options.pendingAsyncValuesRef.current = nextValues; |
| 179 | |
| 180 | const nextTouched = [ |
| 181 | ...normalizeBooleanArray(prev.touched[fieldKey], currentValues.length, false), |
| 182 | false, |
| 183 | ]; |
| 184 | const nextDirty = computeFieldDirty( |
| 185 | fieldKey, |
| 186 | nextValuesArray as T[keyof T], |
| 187 | options.initialValuesRef.current, |
| 188 | ); |
| 189 | |
| 190 | let nextErrors = prev.errors; |
| 191 | if (options.validateOnChange) { |