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: effect-ts resolver #676

Merged
merged 7 commits into from
May 11, 2024
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/compressedSize.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v2
with:
version: 7
version: 9.0
- uses: preactjs/compressed-size-action@v2
with:
repo-token: '${{ secrets.GITHUB_TOKEN }}'
4 changes: 2 additions & 2 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v2
with:
version: 7
version: 9.0

- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
Expand Down Expand Up @@ -56,7 +56,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v2
with:
version: 7
version: 9.0

- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
Expand Down
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"prettier.configPath": "./prettier.config.cjs",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
"source.fixAll.eslint": "explicit"
},
"typescript.tsdk": "node_modules/typescript/lib"
}
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
- [TypeBox](#typebox)
- [ArkType](#arktype)
- [Valibot](#valibot)
- [effect-ts](#effect-ts)
- [Backers](#backers)
- [Sponsors](#sponsors)
- [Contributors](#contributors)
Expand Down Expand Up @@ -576,6 +577,57 @@ const App = () => {
};
```

### [effect-ts](https://github.com/Effect-TS/effect)

A powerful TypeScript framework that provides a fully-fledged functional effect system with a rich standard library.

[![npm](https://img.shields.io/bundlephobia/minzip/effect?style=for-the-badge)]

```typescript jsx
import React from 'react';
import { useForm } from 'react-hook-form';
import { effectTsResolver } from '@hookform/resolvers/effect-ts';
import { Schema } from '@effect/schema';

const schema = Schema.Struct({
username: Schema.String.pipe(
Schema.nonEmpty({ message: () => 'username required' }),
),
password: Schema.String.pipe(
Schema.nonEmpty({ message: () => 'password required' }),
),
});

type FormData = Schema.Schema.Type<typeof schema>;

interface Props {
onSubmit: (data: FormData) => void;
}

function TestComponent({ onSubmit }: Props) {
const {
register,
handleSubmit,
formState: { errors },
// provide generic if TS has issues inferring types
} = useForm<FormData>({
resolver: effectTsResolver(schema),
});

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}

<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}

<button type="submit">submit</button>
</form>
);
}
```

## Backers

Thanks goes to all our backers! [[Become a backer](https://opencollective.com/react-hook-form#backer)].
Expand Down
1 change: 1 addition & 0 deletions config/node-13-exports.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const subRepositories = [
'typebox',
'arktype',
'valibot',
'effect-ts',
];

const copySrc = () => {
Expand Down
19 changes: 19 additions & 0 deletions effect-ts/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "@hookform/resolvers/effect-ts",
"amdName": "hookformResolversEffectTs",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: effect-ts",
"main": "dist/effect-ts.js",
"module": "dist/effect-ts.module.js",
"umd:main": "dist/effect-ts.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"@hookform/resolvers": "^2.0.0",
"@effect/schema": "^0.66.14",
"effect": "^3.1.2",
"react-hook-form": "^7.0.0"
}
}
88 changes: 88 additions & 0 deletions effect-ts/src/__tests__/Form-native-validation.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { useForm } from 'react-hook-form';
import { effectTsResolver } from '..';
import { Schema } from '@effect/schema';

const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';

const schema = Schema.Struct({
username: Schema.String.pipe(
Schema.nonEmpty({ message: () => USERNAME_REQUIRED_MESSAGE }),
),
password: Schema.String.pipe(
Schema.nonEmpty({ message: () => PASSWORD_REQUIRED_MESSAGE }),
),
});

interface FormData {
username: string;
password: string;
}

interface Props {
onSubmit: (data: FormData) => void;
}

function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: effectTsResolver(schema),
shouldUseNativeValidation: true,
});

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} placeholder="username" />

<input {...register('password')} placeholder="password" />

<button type="submit">submit</button>
</form>
);
}

test("form's native validation with effect-ts", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);

// username
let usernameField = screen.getByPlaceholderText(
/username/i,
) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');

// password
let passwordField = screen.getByPlaceholderText(
/password/i,
) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');

await user.click(screen.getByText(/submit/i));

// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(false);
expect(usernameField.validationMessage).toBe(USERNAME_REQUIRED_MESSAGE);

// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE);

await user.type(screen.getByPlaceholderText(/username/i), 'joe');
await user.type(screen.getByPlaceholderText(/password/i), 'password');

// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');

// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
});
59 changes: 59 additions & 0 deletions effect-ts/src/__tests__/Form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { useForm } from 'react-hook-form';
import { effectTsResolver } from '..';
import { Schema } from '@effect/schema';

const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';

const schema = Schema.Struct({
username: Schema.String.pipe(
Schema.nonEmpty({ message: () => USERNAME_REQUIRED_MESSAGE }),
),
password: Schema.String.pipe(
Schema.nonEmpty({ message: () => PASSWORD_REQUIRED_MESSAGE }),
),
});

type FormData = Schema.Schema.Type<typeof schema>;

interface Props {
onSubmit: (data: FormData) => void;
}

function TestComponent({ onSubmit }: Props) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: effectTsResolver(schema),
});

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}

<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}

<button type="submit">submit</button>
</form>
);
}

test("form's validation with Zod and TypeScript's integration", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);

expect(screen.queryAllByRole('alert')).toHaveLength(0);

await user.click(screen.getByText(/submit/i));

expect(screen.getByText(/username field is required/i)).toBeInTheDocument();
expect(screen.getByText(/password field is required/i)).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});
Loading
Loading