Skip to content

Commit

Permalink
prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
iway1 committed Mar 7, 2023
1 parent 534acc1 commit a2f3962
Show file tree
Hide file tree
Showing 6 changed files with 127 additions and 105 deletions.
4 changes: 4 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"printWidth": 80,
"tabWidth": 2
}
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
"test:cov": "jest --coverage",
"test": "jest",
"build": "npx rollup -c rollup.config.js",
"build-test:dryrun": "act -j build-test -P ubuntu-latest=ghcr.io/catthehacker/ubuntu:js-latest"
"build-test:dryrun": "act -j build-test -P ubuntu-latest=ghcr.io/catthehacker/ubuntu:js-latest",
"pretty": "prettier --write \"./**/*.{js,jsx,ts,tsx,json}\""
},
"repository": {
"type": "git",
Expand All @@ -35,6 +36,7 @@
"expect-type": "^0.15.0",
"jest": "^29.3.1",
"jest-environment-jsdom": "^29.3.1",
"prettier": "^2.8.4",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-hook-form": "^7.41.3",
Expand Down
38 changes: 19 additions & 19 deletions src/__tests__/createSchemaForm.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ describe("createSchemaForm", () => {
});

const extraTestIds = {
extra1 : 'extra-form-fun',
extra2 : 'extra-form-fun2'
}
extra1: "extra-form-fun",
extra2: "extra-form-fun2",
};
render(
<TestForm
onSubmit={() => {}}
Expand All @@ -102,25 +102,23 @@ describe("createSchemaForm", () => {
},
}}
>
{({renderedFields : {textField, booleanField, ...restFields}}) => {
return <>
<div data-testid={extraTestIds.extra1}>
{textField}
</div>
<div data-testid={extraTestIds.extra2}>
{booleanField}
</div>
{Object.values(restFields)}
</>
{({ renderedFields: { textField, booleanField, ...restFields } }) => {
return (
<>
<div data-testid={extraTestIds.extra1}>{textField}</div>
<div data-testid={extraTestIds.extra2}>{booleanField}</div>
{Object.values(restFields)}
</>
);
}}
</TestForm>
);

expect(screen.queryByTestId(testIds.textField)).toBeTruthy();
expect(screen.queryByTestId(testIds.textFieldTwo)).toBeTruthy();
expect(screen.queryByTestId(testIds.booleanField)).toBeTruthy();
expect(screen.queryByTestId(extraTestIds.extra1)).toBeTruthy();
expect(screen.queryByTestId(extraTestIds.extra2 )).toBeTruthy();
expect(screen.queryByTestId(extraTestIds.extra2)).toBeTruthy();
});
it("should render a text field and a boolean field based on the mapping and schema, unwrapping refine calls", () => {
const testSchema = z.object({
Expand Down Expand Up @@ -595,11 +593,11 @@ describe("createSchemaForm", () => {
it("should track submitting properly", async () => {
const testId = "id";
const val = "true";
let submitPromiseResolve : () => void = () => {};
let submitPromiseResolve: () => void = () => {};
const submitPromise = new Promise<void>((resolve) => {
submitPromiseResolve = resolve;
})
let submitting =false;
});
let submitting = false;
function Component() {
const form = useForm({
defaultValues: {
Expand All @@ -613,7 +611,9 @@ describe("createSchemaForm", () => {
schema={z.object({
v: z.string(),
})}
onSubmit={() => {return submitPromise}}
onSubmit={() => {
return submitPromise;
}}
props={{
v: {
testId: testId,
Expand Down
14 changes: 12 additions & 2 deletions src/__tests__/utils/testForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,18 @@ export const TestForm = createTsForm(mapping, {
propsMap: propsMap,
});

const FormWithSubmit = ({children,...props} : {children : JSX.Element[], onSubmit: () => void;}) => <form {...props}>{children} <button type="submit">submit</button></form>;
const FormWithSubmit = ({
children,
...props
}: {
children: JSX.Element[];
onSubmit: () => void;
}) => (
<form {...props}>
{children} <button type="submit">submit</button>
</form>
);
export const TestFormWithSubmit = createTsForm(mapping, {
propsMap: propsMap,
FormComponent: FormWithSubmit
FormComponent: FormWithSubmit,
});
145 changes: 79 additions & 66 deletions src/createSchemaForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ export function createTsForm<
renderAfter,
renderBefore,
form,
children : CustomChildrenComponent,
children: CustomChildrenComponent,
}: {
/**
* A Zod Schema - An input field will be rendered for each property in the schema, based on the mapping passed to `createTsForm`
Expand Down Expand Up @@ -288,9 +288,11 @@ export function createTsForm<
* ```
*/
form?: UseFormReturn<z.infer<SchemaType>>;
children? : FunctionComponent<{renderedFields : {
[key in keyof z.infer<UnwrapEffects<SchemaType>>] : ReactNode
}}>
children?: FunctionComponent<{
renderedFields: {
[key in keyof z.infer<UnwrapEffects<SchemaType>>]: ReactNode;
};
}>;
} & 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
Expand Down Expand Up @@ -382,79 +384,90 @@ export function createTsForm<
}

function _submit(data: z.infer<SchemaType>) {
return resolver(removeUndefined(data), {} as any, {} as any).then(async (e) => {
const errorKeys = Object.keys(e.errors);
if (!errorKeys.length) {
await onSubmit(data);
return;
}
for (const key of errorKeys) {
setError(
key as any,
(e.errors as any)[key] as unknown as ErrorOption
);
return resolver(removeUndefined(data), {} as any, {} as any).then(
async (e) => {
const errorKeys = Object.keys(e.errors);
if (!errorKeys.length) {
await onSubmit(data);
return;
}
for (const key of errorKeys) {
setError(
key as any,
(e.errors as any)[key] as unknown as ErrorOption
);
}
}
});
);
}
const submitFn = handleSubmit(_submit);
type SchemaKey = keyof z.infer<UnwrapEffects<SchemaType>>;
const renderedFields = Object.keys(shape).reduce((accum, key : SchemaKey) => {
// we know this is a string but TS thinks it can be number and symbol so just in case stringify
const stringKey = key.toString();
const type = shape[key] as RTFSupportedZodTypes;
const Component = getComponentForZodType(type, componentMap);
if (!Component) {
throw new Error(
noMatchingSchemaErrorMessage(stringKey, type._def.typeName)
);
}
const meta = getMetaInformationForZodType(type);
const renderedFields = Object.keys(shape).reduce(
(accum, key: SchemaKey) => {
// we know this is a string but TS thinks it can be number and symbol so just in case stringify
const stringKey = key.toString();
const type = shape[key] as RTFSupportedZodTypes;
const Component = getComponentForZodType(type, componentMap);
if (!Component) {
throw new Error(
noMatchingSchemaErrorMessage(stringKey, type._def.typeName)
);
}
const meta = getMetaInformationForZodType(type);

const fieldProps = props && props[key] ? (props[key] as any) : {};
const fieldProps = props && props[key] ? (props[key] as any) : {};

const { beforeElement, afterElement } = fieldProps;
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;
accum[key] = (
<Fragment key={stringKey}>
{beforeElement}
<FieldContextProvider
control={control}
name={stringKey}
label={ctxLabel}
placeholder={ctxPlaceholder}
enumValues={meta.enumValues as string[] | undefined}
addToCoerceUndefined={addToCoerceUndefined}
removeFromCoerceUndefined={removeFromCoerceUndefined}
>
<Component key={key} {...mergedProps} />
</FieldContextProvider>
{afterElement}
</Fragment>
);
return accum;
}, {} as Record<SchemaKey, React.ReactNode>);
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;
accum[key] = (
<Fragment key={stringKey}>
{beforeElement}
<FieldContextProvider
control={control}
name={stringKey}
label={ctxLabel}
placeholder={ctxPlaceholder}
enumValues={meta.enumValues as string[] | undefined}
addToCoerceUndefined={addToCoerceUndefined}
removeFromCoerceUndefined={removeFromCoerceUndefined}
>
<Component key={key} {...mergedProps} />
</FieldContextProvider>
{afterElement}
</Fragment>
);
return accum;
},
{} as Record<SchemaKey, React.ReactNode>
);
const renderedFieldNodes = Object.values(renderedFields);
return (
<FormProvider {..._form}>
<ActualFormComponent {...formProps} onSubmit={submitFn} >
<ActualFormComponent {...formProps} onSubmit={submitFn}>
{renderBefore && renderBefore({ submit: submitFn })}
{CustomChildrenComponent ? <CustomChildrenComponent renderedFields={renderedFields}></CustomChildrenComponent> : renderedFieldNodes}
{CustomChildrenComponent ? (
<CustomChildrenComponent
renderedFields={renderedFields}
></CustomChildrenComponent>
) : (
renderedFieldNodes
)}
{renderAfter && renderAfter({ submit: submitFn })}
</ActualFormComponent>
</FormProvider>
Expand Down
27 changes: 10 additions & 17 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,35 +1,28 @@
{
"compilerOptions": {
"lib": [
"ESNext",
"dom",
"ES2022"
],
"outDir": "lib",
"removeComments": true,
"target": "ES6",
"lib": ["ESNext", "dom", "ES2022"],
"outDir": "lib",
"removeComments": true,
"target": "ES6",
"declaration": true,
"module": "ES2022",
"rootDir": "./",
"esModuleInterop": true,
"moduleResolution": "node",
"esModuleInterop": true,
"moduleResolution": "node",
"sourceMap": true,
"sourceRoot": "/",
"alwaysStrict": true,
"allowUnreachableCode": false,
"noImplicitAny": true,
"noImplicitAny": true,
"strict": true,

"noImplicitReturns": true,
"noUncheckedIndexedAccess": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noUnusedParameters": true,
"resolveJsonModule": true,
"jsx": "react",
"jsx": "react"
},
"include": ["./src/**/*"],
"exclude": [
"node_modules/**/*",
"lib/**/*",
],
"exclude": ["node_modules/**/*", "lib/**/*"]
}

0 comments on commit a2f3962

Please sign in to comment.