Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: validator schema to atomWithFormControls #30

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions __tests__/04_schema_generation.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import 'regenerator-runtime/runtime';

import {
act,
cleanup,
fireEvent,
render,
waitFor,
} from '@testing-library/react';
import React from 'react';
import { z } from 'zod';
import * as Yup from 'yup';
import { atomFromZodSchema } from '../src/utils/zod';
import { FormControlPrimitiveValues } from './components/FormControl';
import { atomFromYupSchema } from '../src/utils/yup';

afterEach(() => {
cleanup();
});

describe('atomFromZodSchema', () => {
it('will create a form atom', async () => {
const schema = z.object({
email: z.string().email().default('[email protected]'),
age: z.number(),
agreed: z.boolean(),
});

const formAtom = atomFromZodSchema(schema);

const { getByText, getByLabelText } = render(
<div>
<FormControlPrimitiveValues atomDef={formAtom} />
</div>,
);

await act(async () => {
await waitFor(() => {
const emailInput = getByLabelText('email-input');
getByText('email: [email protected]');

const ageInput = getByLabelText('age-input');
getByText('age: 0');

const agreedInput = getByLabelText('agree-input');
getByText('agreed: No');

fireEvent.change(emailInput, {
target: { value: '[email protected]' },
});
getByText('email: [email protected]');

fireEvent.change(ageInput, {
target: { value: '2' },
});
getByText('age: 2');

fireEvent.click(agreedInput);
getByText('agreed: Yes');
});
});
});
});

describe('atomFromYupSchema', () => {
it('will create a form atom', async () => {
const schema = Yup.object().shape({
email: Yup.string().email().default('[email protected]'),
age: Yup.number(),
agreed: Yup.boolean(),
});

const formAtom = atomFromYupSchema(schema);

const { getByText, getByLabelText } = render(
<div>
<FormControlPrimitiveValues atomDef={formAtom} />
</div>,
);

await act(async () => {
await waitFor(() => {
const emailInput = getByLabelText('email-input');
getByText('email: [email protected]');

const ageInput = getByLabelText('age-input');
getByText('age: 0');

const agreedInput = getByLabelText('agree-input');
getByText('agreed: No');

fireEvent.change(emailInput, {
target: { value: '[email protected]' },
});
getByText('email: [email protected]');

fireEvent.change(ageInput, {
target: { value: '2' },
});
getByText('age: 2');

fireEvent.click(agreedInput);
getByText('agreed: Yes');
});
});
});
});
28 changes: 28 additions & 0 deletions __tests__/components/FormControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,34 @@ type Props = {
atomDef: Atom<any>;
};

export const FormControlPrimitiveValues = ({ atomDef }: Props) => {
const { values, handleOnChange } = useAtomValue(atomDef);

return (
<>
<input
aria-label="email-input"
value={values.email}
onChange={(e) => handleOnChange('email')(e.target.value)}
/>
<p>email: {values.email}</p>
<input
aria-label="age-input"
value={values.age}
onChange={(e) => handleOnChange('age')(e.target.value)}
/>
<p>age: {values.age}</p>
<input
aria-label="agree-input"
type="checkbox"
checked={values.agreed}
onChange={(e) => handleOnChange('agreed')(e.target.checked)}
/>
<p>agreed: {values.agreed ? 'Yes' : 'No'}</p>
</>
);
};

export const FormControlValues = ({ atomDef }: Props) => {
const { values, handleOnChange } = useAtomValue(atomDef);

Expand Down
51 changes: 22 additions & 29 deletions examples/05_zod/src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,35 @@
import { atomFromZodSchema } from 'jotai-form/zod';
import { useAtomValue } from 'jotai/react';
import React from 'react';
import { createRoot } from 'react-dom/client';
import { useAtom } from 'jotai/react';
import { atomWithValidate } from 'jotai-form';
import { z } from 'zod';
import { ZodIssue, z } from 'zod';

const emailSchema = z.string().email();

const emailAtom = atomWithValidate('[email protected]', {
validate: (email) => {
try {
emailSchema.parse(email);
return email;
} catch (err: any) {
// We catch the original and pull out the array of issues
// to render
// you can also just pick the first one and throw that again
throw err.issues;
}
},
});
const formAtom = atomFromZodSchema(
z.object({
email: z.string().email().default('[email protected]'),
}),
);

const App = () => {
const [state, setValue] = useAtom(emailAtom);
const formValue = useAtomValue(formAtom);
const { fieldErrors, isDirty, isValid, values, handleOnChange } = formValue;

return (
<>
<span>{state.isDirty && '*'}</span>
<span>{isDirty && '*'}</span>
<input
value={state.value}
onChange={(e) => setValue(e.target.value as any)}
value={values.email}
onChange={(e) => handleOnChange('email')(e.target.value as any)}
/>
<span>{state.isValid && 'Valid'}</span>
{!state.isValid &&
// Since there's no way for error to inherit itself, this becomes necessary
((state.error as any[]) || []).map((issue: any, errIndex: number) => (
// eslint-disable-next-line react/no-array-index-key
<span key={`error-${errIndex}`}>{`${issue.message}`}</span>
))}
<span>{isValid && 'Valid'}</span>
{!isValid && (
<span key="error">
{[]
.concat(fieldErrors.email?.issues)
.filter((x) => x)
.map((d: ZodIssue) => d.message)}
</span>
)}
</>
);
};
Expand Down
31 changes: 28 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,18 @@
"module": "./dist/react/index.modern.js",
"import": "./dist/react/index.modern.mjs",
"default": "./dist/react/index.umd.js"
},
"./zod": {
"types": "./dist/utils/src/utils/zod.d.ts",
"module": "./dist/utils/zod.modern.js",
"import": "./dist/utils/zod.modern.mjs",
"default": "./dist/utils/zod.umd.js"
},
"./yup": {
"types": "./dist/utils/src/utils/yup.d.ts",
"module": "./dist/utils/yup.modern.js",
"import": "./dist/utils/yup.modern.mjs",
"default": "./dist/utils/yup.umd.js"
}
},
"sideEffects": false,
Expand Down Expand Up @@ -54,7 +66,10 @@
"preset": "ts-jest/presets/js-with-ts",
"testPathIgnorePatterns": [
"__tests__/components"
]
],
"moduleNameMapper": {
"jotai-form": "<rootDir>/src"
}
},
"keywords": [
"jotai",
Expand Down Expand Up @@ -104,10 +119,20 @@
"webpack": "^5.89.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.15.1",
"yup": "^0.32.11",
"yup": "^1.4.0",
"zod": "^3.22.4"
},
"peerDependencies": {
"jotai": ">=2"
"jotai": ">=2",
"yup": ">=1",
"zod": ">=3"
},
"peerDependenciesMeta": {
"zod": {
"optional": true
},
"yup": {
"optional": true
}
}
}
32 changes: 28 additions & 4 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,22 @@ module.exports = function config() {
// react
builder.buildUMD('./src/react/index.ts', 'jotai-form-react', 'dist/react'),
builder.buildESM('./src/react/index.ts', 'dist/react'),

// utils - zod
builder.buildUMD('./src/utils/zod.ts', 'jotai-form-zod', 'dist/utils/zod', {
external: [/^jotai\//, 'jotai-form', 'zod'],
}),
builder.buildESM('./src/utils/zod.ts', 'dist/utils/zod', {
external: [/^jotai\//, 'jotai-form', 'zod'],
}),

// utils - yup
builder.buildUMD('./src/utils/zod.ts', 'jotai-form-zod', 'dist/utils/zod', {
external: [/^jotai\//, 'jotai-form', 'zod'],
}),
builder.buildESM('./src/utils/yup.ts', 'dist/utils/yup', {
external: [/^jotai\//, 'jotai-form', 'yup'],
}),
);
};

Expand Down Expand Up @@ -57,8 +73,10 @@ function configBuilder({ env } = {}) {
merge(...configs) {
return [].concat(configs).flat(1);
},
/** @returns {import("rollup").RollupOptions[]} */
buildESM(input, output) {
/**
* @param {import("rollup").RollupOptions} options
* @returns {import("rollup").RollupOptions[]} */
buildESM(input, output, options = {}) {
const plugins = getCommonPlugins(input, output);

return [
Expand All @@ -73,6 +91,7 @@ function configBuilder({ env } = {}) {
entryFileNames: '[name].modern.js',
},
plugins: [...plugins],
...options,
},
{
input,
Expand All @@ -85,11 +104,15 @@ function configBuilder({ env } = {}) {
entryFileNames: '[name].modern.mjs',
},
plugins: [...plugins],
...options,
},
];
},
/** @returns {import("rollup").RollupOptions[]} */
buildUMD(input, name, output) {

/**
* @param {import("rollup").RollupOptions} options
* @returns {import("rollup").RollupOptions[]} */
buildUMD(input, name, output, options = {}) {
const plugins = getCommonPlugins(input, output);
return [
{
Expand All @@ -104,6 +127,7 @@ function configBuilder({ env } = {}) {
entryFileNames: '[name].umd.js',
},
plugins: [...plugins],
...options,
},
];
},
Expand Down
10 changes: 10 additions & 0 deletions src/atomWithFormControls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export type FormControls<Keys extends string, Vals> = {
fieldErrors: {
[k: string]: any;
};
isDirty: boolean;
touched: Record<Keys, boolean>;
focused: Record<Keys, boolean>;
setValue(key: Keys, value: Vals): void;
Expand Down Expand Up @@ -53,6 +54,13 @@ export function atomWithFormControls<
Object.entries(labeledAtoms).map(([k]) => [k, false]),
);

const isDirtyAtom = atom((get) => {
return Object.values(labeledAtoms)
.map((atomRef) => {
return get(atomRef).isDirty;
})
.some((d) => d);
});
const touchedState = atom(initBooleanState);
const focusedState = atom(initBooleanState);
const validating = validateAtoms(labeledAtoms, validate);
Expand Down Expand Up @@ -109,12 +117,14 @@ export function atomWithFormControls<
const errLen = Object.keys(errorVals).filter((x) => errorVals[x]).length;
const validateAtomResult = get(formGroupAtomValues);
const isValid = Boolean(validateAtomResult.isValid && errLen === 0);
const isDirty = get(isDirtyAtom);

// INTERNAL USECASE, AVOID USING IN YOUR OWN LIBS
const setter = atomOptions.setSelf;

return {
...validateAtomResult,
isDirty,
isValid,
fieldErrors: <Record<Keys, any>>errorVals,
touched: <Record<Keys, boolean>>get(touchedState),
Expand Down
2 changes: 2 additions & 0 deletions src/atomWithValidate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export function atomWithValidate<Value>(
let initialPromise: Promise<Value> | undefined;
try {
const initialValidatedValue = validate(initialValue);

if (initialValidatedValue instanceof Promise) {
initialPromise = initialValidatedValue;
initialState = {
Expand All @@ -69,6 +70,7 @@ export function atomWithValidate<Value>(
error,
};
}

const baseAtom = atom(initialState);
if (process.env.NODE_ENV !== 'production') {
baseAtom.debugPrivate = true;
Expand Down
Loading
Loading