/
createSchemaForm.tsx
390 lines (372 loc) · 12.2 KB
/
createSchemaForm.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
import React, {
ForwardRefExoticComponent,
Fragment,
ReactNode,
RefAttributes,
useRef,
} from "react";
import { ComponentProps } from "react";
import { DeepPartial, useForm, UseFormReturn } from "react-hook-form";
import { AnyZodObject, z, ZodEffects } from "zod";
import { getComponentForZodType } from "./getComponentForZodType";
import { zodResolver } from "@hookform/resolvers/zod";
import { IndexOf, RequireKeysWithRequiredChildren } from "./typeUtilities";
import { getMetaInformationForZodType } from "./getMetaInformationForZodType";
import { unwrapEffects, UnwrapZodType } from "./unwrap";
import { RTFBaseZodType, RTFSupportedZodTypes } from "./supportedZodTypes";
import { FieldContextProvider } from "./FieldContext";
import { isZodTypeEqual } from "./isZodTypeEqual";
import { printWarningsForSchema } from "./logging";
/**
* @internal
*/
export type ReactProps = Record<string, any>;
/**
* @internal
*/
export type ReactComponentWithRequiredProps<
Props extends ReactProps
// ExtraProps extends Record<string, any> = {}
> =
| ((props: Props) => JSX.Element)
| (ForwardRefExoticComponent<Props> & RefAttributes<unknown>);
export type MappingItem<PropType extends ReactProps> = readonly [
RTFBaseZodType,
ReactComponentWithRequiredProps<PropType>
];
export type FormComponentMapping = readonly MappingItem<any>[];
export type MappableProp =
| "control"
| "name"
| "enumValues"
| "descriptionLabel"
| "descriptionPlaceholder";
export type PropsMapping = readonly (readonly [MappableProp, string])[];
export function noMatchingSchemaErrorMessage(
propertyName: string,
propertyType: string
) {
return `No matching zod schema for type \`${propertyType}\` found in mapping for property \`${propertyName}\`. Make sure there's a matching zod schema for every property in your schema.`;
}
export function useFormResultValueChangedErrorMesssage() {
return `useFormResult prop changed - its value shouldn't changed during the lifetime of the component.`;
}
/**
* @internal
*/
type FormComponent = "form" | ((props: any) => JSX.Element);
export type ExtraProps = {
/**
* An element to render before the field.
*/
beforeElement?: ReactNode;
/**
* An element to render after the field.
*/
afterElement?: ReactNode;
};
/**
* @internal
*/
type UnwrapEffects<T extends AnyZodObject | ZodEffects<any, any>> =
T extends AnyZodObject
? T
: T extends ZodEffects<any, any>
? T["_def"]["schema"]
: never;
export function duplicateTypeError() {
return "Found duplicate zod schema in zod-component mapping. Each zod type in the mapping must be unique, if you need to map multiple of the same types to different schemas use createUniqueFieldSchema.";
}
function checkForDuplicateTypes(array: RTFSupportedZodTypes[]) {
var combinations = array.flatMap((v, i) =>
array.slice(i + 1).map((w) => [v, w] as const)
);
for (const [a, b] of combinations) {
printWarningsForSchema(a);
printWarningsForSchema(b);
if (isZodTypeEqual(a!, b)) {
throw new Error(duplicateTypeError());
}
}
}
const defaultPropsMap = [
["name", "name"] as const,
["control", "control"] as const,
["enumValues", "enumValues"] as const,
] as const;
function propsMapToObect(propsMap: PropsMapping) {
const r: { [key in MappableProp]+?: string } = {};
for (const [mappable, toProp] of propsMap) {
r[mappable] = toProp;
}
return r;
}
/**
* Creates a reusable, typesafe form component based on a zod-component mapping.
* @example
* ```tsx
* const mapping = [
* [z.string, TextField] as const
* ] as const
* const MyForm = createTsForm(mapping)
* ```
* @param componentMap A zod-component mapping. An array of 2-tuples where the first element is a zod schema and the second element is a React Functional Component.
* @param options Optional - A custom form component to use as the container for the input fields.
*/
export function createTsForm<
Mapping extends FormComponentMapping,
PropsMapType extends PropsMapping = typeof defaultPropsMap,
FormType extends FormComponent = "form"
>(
/**
* An array mapping zod schemas to components.
* @example
* ```tsx
* const mapping = [
* [z.string(), TextField] as const
* [z.boolean(), CheckBoxField] as const
* ] as const
*
* const MyForm = createTsForm(mapping);
* ```
*/
componentMap: Mapping,
/**
* Options to customize your form.
*/
options?: {
/**
* The component to wrap your fields in. By default, it is a `<form/>`.
* @example
* ```tsx
* function MyCustomFormContainer({children, onSubmit}:{children: ReactNode, onSubmit: ()=>void}) {
* return (
* <form onSubmit={onSubmit}>
* {children}
* <button>Submit</button>
* </form>
* )
* }
* const MyForm = createTsForm(mapping, {
* FormComponent: MyCustomFormContainer
* })
* ```
*/
FormComponent?: FormType;
/**
* Modify which props the form control and such get passed to when rendering components. This can make it easier to integrate existing
* components with `@ts-react/form` or modify its behavior. The values of the object are the names of the props to forward the corresponding
* data to.
* @default {
* name: "name",
* control: "control",
* enumValues: "enumValues",
* }
* @example
* ```tsx
* function MyTextField({someControlProp}:{someControlProp: Control<any>}) {
* //...
* }
*
* const createTsForm(mapping, {
* propsMap: {
* control: "someControlProp"
* }
* })
* ```
*/
propsMap?: PropsMapType;
}
) {
const ActualFormComponent = options?.FormComponent
? options.FormComponent
: "form";
checkForDuplicateTypes(componentMap.map((e) => e[0]));
const propsMap = propsMapToObect(
options?.propsMap ? options.propsMap : defaultPropsMap
);
return function Component<
SchemaType extends z.AnyZodObject | ZodEffects<any, any>
>({
schema,
onSubmit,
props,
formProps,
defaultValues,
renderAfter,
renderBefore,
form,
}: {
/**
* A Zod Schema - An input field will be rendered for each property in the schema, based on the mapping passed to `createTsForm`
*/
schema: SchemaType;
/**
* A callback function that will be called with the data once the form has been submitted and validated successfully.
*/
onSubmit: (values: z.infer<UnwrapEffects<SchemaType>>) => void;
/**
* Initializes your form with default values. Is a deep partial, so all properties and nested properties are optional.
*/
defaultValues?: DeepPartial<z.infer<UnwrapEffects<SchemaType>>>;
/**
* A function that renders components after the form, the function is passed a `submit` function that can be used to trigger
* form submission.
* @example
* ```tsx
* <Form
* // ...
* renderAfter={({submit})=><button onClick={submit}>Submit</button>}
* />
* ```
*/
renderAfter?: (vars: { submit: () => void }) => ReactNode;
/**
* A function that renders components before the form, the function is passed a `submit` function that can be used to trigger
* form submission.
* @example
* ```tsx
* <Form
* // ...
* renderBefore={({submit})=><button onClick={submit}>Submit</button>}
* />
* ```
*/
renderBefore?: (vars: { submit: () => void }) => ReactNode;
/**
* Use this if you need access to the `react-hook-form` useForm() in the component containing the form component (if you need access to any of its other properties.)
* This will give you full control over you form state (in case you need check if it's dirty or reset it or anything.)
* @example
* ```tsx
* function Component() {
* const form = useForm();
* return <MyForm useFormResult={form}/>
* }
* ```
*/
form?: UseFormReturn<z.infer<SchemaType>>;
} & RequireKeysWithRequiredChildren<{
/**
* Props to pass to the individual form components. The keys of `props` will be the names of your form properties in the form schema, and they will
* be typesafe to the form components in the mapping passed to `createTsForm`. If any of the rendered form components have required props, this is required.
* @example
* ```tsx
* <MyForm
* schema={z.object({field: z.string()})}
* props={{
* field: {
* // TextField props
* }
* }}
* />
* ```
*/
props?: RequireKeysWithRequiredChildren<
Partial<{
[key in keyof z.infer<SchemaType>]: Mapping[IndexOf<
Mapping,
readonly [
UnwrapZodType<
ReturnType<UnwrapEffects<SchemaType>["_def"]["shape"]>[key]
>,
any
]
>] extends readonly [any, any] // I guess this tells typescript it has a second element? errors without this check.
? Omit<
ComponentProps<
Mapping[IndexOf<
Mapping,
readonly [
UnwrapZodType<
ReturnType<
UnwrapEffects<SchemaType>["_def"]["shape"]
>[key]
>,
any
]
>][1]
>,
PropsMapType[number][1]
> &
ExtraProps
: never;
}>
>;
}> &
RequireKeysWithRequiredChildren<{
/**
* Props to pass to the form container component (by default the props that "form" tags accept)
*/
formProps?: Omit<ComponentProps<FormType>, "children" | "onSubmit">;
}>) {
const useFormResultInitialValue = useRef<
undefined | ReturnType<typeof useForm>
>(form);
if (!!useFormResultInitialValue.current !== !!form) {
throw new Error(useFormResultValueChangedErrorMesssage());
}
const { control, handleSubmit } = (() => {
if (form) return form;
const uf = useForm({
resolver: zodResolver(schema),
defaultValues,
});
return uf;
})();
const _schema = unwrapEffects(schema);
const shape: Record<string, RTFSupportedZodTypes> = _schema._def.shape();
function _submit(data: z.infer<SchemaType>) {
onSubmit(data);
}
const submitFn = handleSubmit(_submit);
return (
<ActualFormComponent {...formProps} onSubmit={submitFn}>
{renderBefore && renderBefore({ submit: submitFn })}
{Object.keys(shape).map((key) => {
const type = shape[key] as RTFSupportedZodTypes;
const Component = getComponentForZodType(type, componentMap);
if (!Component) {
throw new Error(
noMatchingSchemaErrorMessage(key, type._def.typeName)
);
}
const meta = getMetaInformationForZodType(type);
const fieldProps = props && props[key] ? (props[key] as any) : {};
const { beforeElement, afterElement } = fieldProps;
const mergedProps = {
...(propsMap.name && { [propsMap.name]: key }),
...(propsMap.control && { [propsMap.control]: control }),
...(propsMap.enumValues && {
[propsMap.enumValues]: meta.enumValues,
}),
...(propsMap.descriptionLabel && {
[propsMap.descriptionLabel]: meta.description?.label,
}),
...(propsMap.descriptionPlaceholder && {
[propsMap.descriptionPlaceholder]: meta.description?.placeholder,
}),
...fieldProps,
};
const ctxLabel = meta.description?.label;
const ctxPlaceholder = meta.description?.placeholder;
return (
<Fragment key={key}>
{beforeElement}
<FieldContextProvider
control={control}
name={key}
label={ctxLabel}
placeholder={ctxPlaceholder}
enumValues={meta.enumValues as string[] | undefined}
>
<Component key={key} {...mergedProps} />
</FieldContextProvider>
{afterElement}
</Fragment>
);
})}
{renderAfter && renderAfter({ submit: submitFn })}
</ActualFormComponent>
);
};
}