-
Notifications
You must be signed in to change notification settings - Fork 108
/
context.tsx
507 lines (462 loc) · 11.9 KB
/
context.tsx
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
import {
type Constraint,
type Combine,
type FormId,
type FieldName,
type FormContext as BaseFormContext,
type FormValue,
type FormState,
type Intent,
type SubscriptionScope,
type SubscriptionSubject,
type FormOptions as BaseFormOptions,
unstable_createFormContext as createBaseFormContext,
formatPaths,
getPaths,
isPrefix,
STATE,
INTENT,
} from '@conform-to/dom';
import {
type FormEvent,
type ReactElement,
type ReactNode,
type MutableRefObject,
createContext,
useMemo,
useCallback,
useContext,
useSyncExternalStore,
useRef,
} from 'react';
export type Pretty<T> = { [K in keyof T]: T[K] } & {};
export type Primitive =
| string
| number
| bigint
| boolean
| Date
| File
| null
| undefined;
export type Metadata<
Schema,
FormSchema extends Record<string, unknown>,
FormError = string[],
> = {
key: string | undefined;
id: string;
errorId: string;
descriptionId: string;
name: FieldName<Schema, FormSchema, FormError>;
initialValue: FormValue<Schema>;
value: FormValue<Schema>;
errors: FormError | undefined;
allErrors: Record<string, FormError>;
valid: boolean;
dirty: boolean;
};
export type FormMetadata<
Schema extends Record<string, unknown> = Record<string, unknown>,
FormError = string[],
> = Omit<Metadata<Schema, Schema, FormError>, 'id'> &
Pick<FormContext<Schema, FormError>, Intent['type']> & {
id: FormId<Schema, FormError>;
context: Wrapped<FormContext<Schema, FormError>>;
status?: 'success' | 'error';
getFieldset: () => Required<{
[Key in keyof Combine<Schema>]: FieldMetadata<
Combine<Schema>[Key],
Schema,
FormError
>;
}>;
onSubmit: (event: React.FormEvent<HTMLFormElement>) => void;
noValidate: boolean;
};
type SubfieldMetadata<
Schema,
FormSchema extends Record<string, any>,
FormError,
> = [Schema] extends [Primitive]
? {}
: [Schema] extends [Array<infer Item> | null | undefined]
? {
getFieldList: () => Array<FieldMetadata<Item, FormSchema, FormError>>;
}
: [Schema] extends [Record<string, any> | null | undefined]
? {
getFieldset: () => Required<{
[Key in keyof Combine<Schema>]: FieldMetadata<
Combine<Schema>[Key],
FormSchema,
FormError
>;
}>;
}
: {};
export type FieldMetadata<
Schema = unknown,
FormSchema extends Record<string, any> = Record<string, unknown>,
FormError = string[],
> = Metadata<Schema, FormSchema, FormError> &
Constraint & { formId: FormId<FormSchema, FormError> } & SubfieldMetadata<
Schema,
FormSchema,
FormError
>;
export const Form = createContext<FormContext[]>([]);
// To hide the FormContext type from the public API
const wrappedSymbol = Symbol('wrapped');
export type Wrapped<Type> = {
[wrappedSymbol]: Type;
};
export function getWrappedFormContext(
context: Wrapped<FormContext>,
): FormContext {
return context[wrappedSymbol];
}
export function useFormContext<Schema extends Record<string, any>, FormError>(
formId?: FormId<Schema, FormError>,
): FormContext<Schema, FormError, unknown> {
const contexts = useContext(Form);
const form = formId
? contexts.find((context) => formId === context.getFormId())
: contexts[0];
if (!form) {
throw new Error('Form context is not available');
}
return form as unknown as FormContext<Schema, FormError, unknown>;
}
export function useFormState<FormError>(
form: FormContext<any, FormError>,
subjectRef?: MutableRefObject<SubscriptionSubject>,
): FormState<FormError> {
const subscribe = useCallback(
(callback: () => void) =>
form.subscribe(callback, () => subjectRef?.current),
[form, subjectRef],
);
return useSyncExternalStore(subscribe, form.getState, form.getState);
}
export function FormProvider(props: {
context: Wrapped<FormContext<any, any>>;
children: ReactNode;
}): ReactElement {
const forms = useContext(Form);
const context = getWrappedFormContext(props.context);
const value = useMemo(
() => [context].concat(forms), // Put the latest form context first
[forms, context],
);
return <Form.Provider value={value}>{props.children}</Form.Provider>;
}
export function FormStateInput(props: { formId?: string }): React.ReactElement {
const context = useFormContext(props.formId);
return (
<input
type="hidden"
name={STATE}
value={context.getSerializedState()}
form={props.formId}
/>
);
}
export function useSubjectRef(
initialSubject: SubscriptionSubject = {},
): MutableRefObject<SubscriptionSubject> {
const subjectRef = useRef(initialSubject);
// Reset the subject everytime the component is rerendered
// This let us subscribe to data used in the last render only
subjectRef.current = initialSubject;
return subjectRef;
}
export function updateSubjectRef(
ref: MutableRefObject<SubscriptionSubject>,
subject: 'status' | 'formId',
): void;
export function updateSubjectRef(
ref: MutableRefObject<SubscriptionSubject>,
subject: Exclude<keyof SubscriptionSubject, 'status' | 'formId'>,
scope: keyof SubscriptionScope,
name: string,
): void;
export function updateSubjectRef(
ref: MutableRefObject<SubscriptionSubject>,
subject: keyof SubscriptionSubject,
scope?: keyof SubscriptionScope,
name?: string,
): void {
if (subject === 'status' || subject === 'formId') {
ref.current[subject] = true;
} else if (typeof scope !== 'undefined' && typeof name !== 'undefined') {
ref.current[subject] = {
...ref.current[subject],
[scope]: (ref.current[subject]?.[scope] ?? []).concat(name),
};
}
}
export function getMetadata<
Schema,
FormError,
FormSchema extends Record<string, any>,
>(
context: FormContext<FormSchema, FormError, any>,
subjectRef: MutableRefObject<SubscriptionSubject>,
stateSnapshot: FormState<FormError>,
name: FieldName<Schema, FormSchema, FormError> = '',
): Metadata<Schema, FormSchema, FormError> {
const id = name ? `${context.getFormId()}-${name}` : context.getFormId();
const state = context.getState();
return new Proxy(
{
id,
name,
errorId: `${id}-error`,
descriptionId: `${id}-description`,
get initialValue() {
return state.initialValue[name] as FormValue<Schema>;
},
get value() {
return state.value[name] as FormValue<Schema>;
},
get errors() {
return state.error[name];
},
get key() {
return state.key[name];
},
get valid() {
return state.valid[name] as boolean;
},
get dirty() {
return state.dirty[name] as boolean;
},
get allErrors() {
if (name === '') {
return state.error;
}
const result: Record<string, FormError> = {};
for (const [key, error] of Object.entries(state.error)) {
if (isPrefix(key, name)) {
result[key] = error;
}
}
return result;
},
get getFieldset() {
return () =>
new Proxy({} as any, {
get(target, key, receiver) {
if (typeof key === 'string') {
return getFieldMetadata(
context,
subjectRef,
stateSnapshot,
name,
key,
);
}
return Reflect.get(target, key, receiver);
},
});
},
},
{
get(target, key, receiver) {
// We want to minize re-render by identifying whether the field is used in a callback only
// but there is no clear way to know if it is accessed during render or not
// if the stateSnapshot is not the latest, then it must be accessed in a callback
if (state === stateSnapshot) {
switch (key) {
case 'id':
case 'errorId':
case 'descriptionId':
updateSubjectRef(subjectRef, 'formId');
break;
case 'key':
case 'initialValue':
case 'value':
case 'valid':
case 'dirty':
updateSubjectRef(subjectRef, key, 'name', name);
break;
case 'errors':
case 'allErrors':
updateSubjectRef(
subjectRef,
'error',
key === 'errors' ? 'name' : 'prefix',
name,
);
break;
}
}
return Reflect.get(target, key, receiver);
},
},
);
}
export function getFieldMetadata<
Schema,
FormSchema extends Record<string, any>,
FormError,
>(
context: FormContext<FormSchema, FormError, any>,
subjectRef: MutableRefObject<SubscriptionSubject>,
stateSnapshot: FormState<FormError>,
prefix = '',
key?: string | number,
): FieldMetadata<Schema, FormSchema, FormError> {
const name =
typeof key === 'undefined'
? prefix
: formatPaths([...getPaths(prefix), key]);
return new Proxy({} as any, {
get(_, key, receiver) {
const metadata = getMetadata(context, subjectRef, stateSnapshot, name);
const state = context.getState();
switch (key) {
case 'formId':
if (state === stateSnapshot) {
updateSubjectRef(subjectRef, 'formId');
}
return context.getFormId();
case 'required':
case 'minLength':
case 'maxLength':
case 'min':
case 'max':
case 'pattern':
case 'step':
case 'multiple':
return state.constraint[name]?.[key];
case 'getFieldList': {
return () => {
const initialValue = state.initialValue[name] ?? [];
if (state === stateSnapshot) {
updateSubjectRef(subjectRef, 'initialValue', 'name', name);
}
if (!Array.isArray(initialValue)) {
throw new Error(
'The initial value at the given name is not a list',
);
}
return Array(initialValue.length)
.fill(0)
.map((_, index) =>
getFieldMetadata(
context,
subjectRef,
stateSnapshot,
name,
index,
),
);
};
}
}
return Reflect.get(metadata, key, receiver);
},
});
}
export function getFormMetadata<
Schema extends Record<string, any>,
FormError = string[],
FormValue = Schema,
>(
context: FormContext<Schema, FormError, FormValue>,
subjectRef: MutableRefObject<SubscriptionSubject>,
stateSnapshot: FormState<FormError>,
noValidate: boolean,
): FormMetadata<Schema, FormError> {
return new Proxy({} as any, {
get(_, key, receiver) {
const metadata = getMetadata(context, subjectRef, stateSnapshot);
const state = context.getState();
switch (key) {
case 'context':
return {
[wrappedSymbol]: context,
};
case 'status':
if (state === stateSnapshot) {
updateSubjectRef(subjectRef, 'status');
}
return state.submissionStatus;
case 'validate':
case 'update':
case 'reset':
case 'insert':
case 'remove':
case 'reorder':
return context[key];
case 'onSubmit':
return context.submit;
case 'noValidate':
return noValidate;
}
return Reflect.get(metadata, key, receiver);
},
});
}
export type FormOptions<
Schema extends Record<string, any> = any,
FormError = string[],
FormValue = Schema,
> = BaseFormOptions<Schema, FormError, FormValue> & {
/**
* A function to be called before the form is submitted.
*/
onSubmit?: (
event: FormEvent<HTMLFormElement>,
context: ReturnType<
BaseFormContext<Schema, FormError, FormValue>['submit']
>,
) => void;
};
export type FormContext<
Schema extends Record<string, any> = any,
FormError = string[],
FormValue = Schema,
> = Omit<
BaseFormContext<Schema, FormError, FormValue>,
'submit' | 'onUpdate'
> & {
submit: (event: FormEvent<HTMLFormElement>) => void;
onUpdate: (
options: Partial<FormOptions<Schema, FormError, FormValue>>,
) => void;
};
export function createFormContext<
Schema extends Record<string, any> = any,
FormError = string[],
FormValue = Schema,
>(
options: FormOptions<Schema, FormError, FormValue>,
): FormContext<Schema, FormError, FormValue> {
let { onSubmit } = options;
const context = createBaseFormContext(options);
return {
...context,
submit(event) {
const submitEvent = event.nativeEvent as SubmitEvent;
const result = context.submit(submitEvent);
if (
!result.submission ||
result.submission.status === 'success' ||
result.submission.error === null
) {
if (!result.formData.has(INTENT)) {
onSubmit?.(event, result);
}
} else {
event.preventDefault();
}
},
onUpdate(options) {
onSubmit = options.onSubmit;
context.onUpdate(options);
},
};
}