-
-
Notifications
You must be signed in to change notification settings - Fork 494
Expand file tree
/
Copy pathuseField.ts
More file actions
387 lines (351 loc) · 12.1 KB
/
useField.ts
File metadata and controls
387 lines (351 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import * as React from "react";
import { useSyncExternalStore } from "use-sync-external-store/shim";
import { fieldSubscriptionItems, getIn } from "final-form";
import type { FieldSubscription, FieldState, FormApi } from "final-form";
import type {
UseFieldConfig,
FieldInputProps,
FieldRenderProps,
} from "./types";
import isReactNative from "./isReactNative";
import getValue from "./getValue";
import useForm from "./useForm";
import useLatest from "./useLatest";
import { addLazyFieldMetaState } from "./getters";
import useConstantCallback from "./useConstantCallback";
const all: FieldSubscription = fieldSubscriptionItems.reduce(
(result: any, key) => {
result[key] = true;
return result;
},
{},
);
const defaultFormat = (value: any, _name: string) =>
value === undefined ? "" : value;
const defaultParse = (value: any, _name: string) =>
value === "" ? undefined : value;
const defaultIsEqual = (a: any, b: any): boolean => a === b;
// Helper to build fallback field state when field is not yet registered
const buildFallbackFieldState = (
name: string,
form: FormApi<any>,
initialValue: any,
defaultValue: any,
component: React.ComponentType<any> | "input" | "select" | "textarea" | undefined,
type: string | undefined,
multiple: boolean | undefined,
allowNull: boolean | undefined,
data: any,
stableBlur: () => void,
stableChange: () => void,
stableFocus: () => void,
isEqual: (a: any, b: any) => boolean = defaultIsEqual,
): FieldState<any> => {
const formState = form.getState();
// Compute initial value (never includes live values from form.change())
// Priority: initialValues > initialValue prop > defaultValue > select multiple default
let initial: any;
const formInitialValue = getIn(formState.initialValues || {}, name);
if (formInitialValue !== undefined) {
initial = formInitialValue;
} else if (initialValue !== undefined) {
initial = initialValue;
} else if (defaultValue !== undefined) {
initial = defaultValue;
} else if ((component === "select" || type === "select") && multiple) {
initial = [];
}
// Compute current value (prefers live values from form.change() calls)
// Priority: live values > initialValues > initialValue prop > defaultValue > select multiple default
let value: any;
const liveValue = getIn(formState.values, name);
if (liveValue !== undefined) {
value = liveValue;
} else {
value = initial;
}
// Handle allowNull for both initial and value
if (initial === null && !allowNull) {
initial = undefined;
}
if (value === null && !allowNull) {
value = undefined;
}
// Compute dirty by comparing value and initial
// Use provided isEqual comparator (respects custom form config)
const dirty = !isEqual(value, initial);
return {
active: false,
blur: stableBlur,
change: stableChange,
data: data ?? {},
dirty,
dirtySinceLastSubmit: false,
error: undefined,
focus: stableFocus,
initial,
invalid: false,
length: undefined,
modified: false,
modifiedSinceLastSubmit: false,
name,
pristine: !dirty,
submitError: undefined,
submitFailed: false,
submitSucceeded: false,
submitting: false,
touched: false,
valid: true,
validating: false,
visited: false,
value,
} as FieldState<any>;
};
function useField<
FieldValue = any,
T extends HTMLElement = HTMLElement,
FormValues = Record<string, any>,
>(name: string, config: UseFieldConfig = {}): FieldRenderProps<FieldValue, T> {
const {
allowNull,
component,
data,
defaultValue,
format = defaultFormat,
formatOnBlur,
initialValue,
multiple,
parse = defaultParse,
type,
value: _value,
} = config;
const form: FormApi<FormValues> = useForm<FormValues>("useField");
const configRef = useLatest(config);
const register = (
callback: (state: FieldState<any>) => void,
silent: boolean,
) =>
// avoid using `state` const in any closures created inside `register`
// because they would refer `state` from current execution context
// whereas actual `state` would defined in the subsequent `useField` hook
// execution
// (that would be caused by `setState` call performed in `register` callback)
form.registerField(name as keyof FormValues, callback, configRef.current.subscription || all, {
afterSubmit: configRef.current.afterSubmit,
beforeSubmit: () => {
const {
beforeSubmit,
formatOnBlur,
format = defaultFormat,
} = configRef.current;
if (formatOnBlur) {
const fieldState = form.getFieldState(name as keyof FormValues);
if (fieldState) {
const { value } = fieldState;
const formatted = format(value, name);
if (formatted !== value) {
form.change(name as keyof FormValues, formatted);
}
}
}
return beforeSubmit && beforeSubmit();
},
data,
defaultValue,
getValidator: () => configRef.current.validate,
initialValue,
isEqual: (a: any, b: any) => (configRef.current.isEqual || defaultIsEqual)(a, b),
silent,
validateFields: configRef.current.validateFields,
});
// FIX #1050: Use useSyncExternalStore to properly integrate with Final Form
// This ensures Form initialValues are available on first render without
// causing side effects during render (React 18+ best practice)
// Stable no-op functions for unregistered field state
const stableBlur = React.useCallback(() => {}, []);
const stableChange = React.useCallback(() => {}, []);
const stableFocus = React.useCallback(() => {}, []);
// Memoized fallback state for when field is not yet registered
const fallbackStateRef = React.useRef<FieldState<any> | null>(null);
// Store the latest field state from subscription callback
// This ensures getSnapshot only returns state when subscribed fields change
const latestStateRef = React.useRef<FieldState<any> | null>(null);
// Reset refs when key dependencies change to avoid stale values
React.useEffect(() => {
fallbackStateRef.current = null;
latestStateRef.current = null;
}, [name, initialValue, defaultValue, data, allowNull, component, multiple]);
const state = useSyncExternalStore(
// subscribe: called when component mounts and when dependencies change
React.useCallback(
(onStoreChange) => {
return register((fieldState) => {
// Save the state from subscription callback
latestStateRef.current = fieldState;
onStoreChange();
}, false);
},
// Note: subscription, afterSubmit, and validateFields are intentionally omitted from deps.
// The register callback reads these from configRef.current to avoid stale closures.
// eslint-disable-next-line react-hooks/exhaustive-deps
[name, data, defaultValue, initialValue],
),
// getSnapshot: return field state from subscription callback
() => {
// If we have state from subscription, return it
if (latestStateRef.current) {
return latestStateRef.current;
}
// Return memoized fallback state if field not registered yet
// Must return same object reference for React 18 stability
if (!fallbackStateRef.current) {
fallbackStateRef.current = buildFallbackFieldState(
name,
form,
initialValue,
defaultValue,
component,
type,
multiple,
allowNull,
data,
stableBlur,
stableChange,
stableFocus,
configRef.current.isEqual || defaultIsEqual,
);
}
return fallbackStateRef.current;
},
// getServerSnapshot: for SSR, return initial state (same as fallback)
() => {
// For SSR, we can return the fallback state which has stable references
if (!fallbackStateRef.current) {
fallbackStateRef.current = buildFallbackFieldState(
name,
form,
initialValue,
defaultValue,
component,
type,
multiple,
allowNull,
data,
stableBlur,
stableChange,
stableFocus,
configRef.current.isEqual || defaultIsEqual,
);
}
return fallbackStateRef.current;
},
);
const meta: any = {};
addLazyFieldMetaState(meta, state);
const getInputValue = () => {
let value = state.value;
// Handle null values first
if (value === null && !allowNull) {
value = "";
}
if (formatOnBlur) {
if (component === "input") {
value = defaultFormat(value, name);
}
} else {
// Only format if value is not null when allowNull is true
if (!(allowNull && value === null)) {
value = format(value, name);
}
}
if ((component === "select" || type === "select") && multiple) {
return Array.isArray(value) ? value : [];
}
// For checkboxes and radios, the `value` prop on the input element itself
// is not the array of selected values or the single selected radio value,
// but rather the specific value this input represents if selected.
// The `checked` prop handles the actual selection state.
// So, for `input.value`, we should return `_value` if provided (for individual inputs in a group)
// or the formatted field value otherwise (for standalone inputs).
if ((type === "checkbox" || type === "radio") && _value !== undefined) {
return _value;
}
return value;
};
const getInputChecked = () => {
let value = state.value;
if (type === "checkbox") {
value = format(value, name);
if (_value === undefined) {
return !!value;
} else {
return !!(Array.isArray(value) && ~value.indexOf(_value));
}
} else if (type === "radio") {
return format(value, name) === _value;
}
return undefined;
};
const input: FieldInputProps<FieldValue, T> = {
name,
onBlur: useConstantCallback((_event?: React.FocusEvent<any>) => {
state.blur();
if (formatOnBlur) {
/**
* Here we must fetch the value directly from Final Form because we cannot
* trust that our `state` closure has the most recent value. This is a problem
* if-and-only-if the library consumer has called `onChange()` immediately
* before calling `onBlur()`, but before the field has had a chance to receive
* the value update from Final Form.
*/
const fieldState = form.getFieldState(state.name as keyof FormValues);
if (fieldState) {
state.change(format(fieldState.value, state.name));
}
}
}),
onChange: useConstantCallback((event: React.ChangeEvent<any> | any) => {
// istanbul ignore next
if (process.env.NODE_ENV !== "production" && event && event.target) {
const targetType = event.target.type;
const unknown =
~["checkbox", "radio", "select-multiple"].indexOf(targetType) &&
!type &&
component !== "select";
const value: any =
targetType === "select-multiple" ? state.value : _value;
if (unknown) {
console.error(
`You must pass \`type="${targetType === "select-multiple" ? "select" : targetType
}"\` prop to your Field(${name}) component.\n` +
`Without it we don't know how to unpack your \`value\` prop - ${Array.isArray(value) ? `[${value}]` : `"${value}"`
}.`,
);
}
}
const value: any =
event && event.target
? getValue(event, state.value, _value, isReactNative)
: event;
state.change(parse(value, name));
}),
onFocus: useConstantCallback((_event?: React.FocusEvent<any>) =>
state.focus(),
),
get value() {
return getInputValue();
},
get checked() {
return getInputChecked();
},
};
if (multiple) {
input.multiple = multiple;
}
if (type !== undefined) {
input.type = type;
}
const renderProps: FieldRenderProps<FieldValue, T> = { input, meta }; // assign to force type check
return renderProps;
}
export default useField;