diff --git a/README.md b/README.md index 605172b3..ce8e2dc5 100644 --- a/README.md +++ b/README.md @@ -14,103 +14,61 @@ ### 🏠 [Homepage](https://useform.org) ### ✨ [Demo](https://codesandbox.io/s/useform-2u2ju) +# UseForm - - Example in CodeSandbox - +> Create hooks to manage your forms. -## Motivation - -There are many ways to create forms in React, and there are many form libraries available, with different features. I must admit that there a lot of good form libraries, -so, why one more? - -UseForm was born because I found great difficulty when I wanted to build complex forms with different steps or levels and with many fields. -When we need to build complex forms we can encounter issues like: - -- A lot of rendering - Every change is made in the form state is reflected and the form component tree is rendered again and again. -- A lot of properties - When you use some libraries it is necessary to put many properties in one input, creating a lot of unnecessary code. -- Just one approach - You can use controlled forms or uncontrolled forms never both together in the same library. - -UseForm is a library that solves all these problems. -## Description +UseForm is an open source project that allow you to create form easily, different from the others options, this package guide you to create custom hooks to manage your forms, you can use the same form in different components without context API. -Forms are an important part of web applications, and with react it's possible to create greats forms, -react hooks are a game-changer when we think about forms, with hooks it is very simple to create forms, and you can go on without libraries. -But when we wanna complex forms with many validations and nested objects with several layer and properties is appropriate to use a library form to manager the state of inputs and its validations. -For this reason, there is useForm, with useForm we can make greats forms and complex validations with less line code. + - As other packages, you can also use yup validation to validate your form. + - You can also use different approach to handle your form, like `onSubmit | onChange | debounce`. + - Less code, than other options. -```jsx -// FORMIk EXAMPLE - - -//USEFORM EXAMPLE - -``` - -UseForm provides a way to create complex forms easily, this hook returns an object of values ​​in the same shape that it receives, this is possible using dot notation. Therefore, -it does not matter if there is a nested object or has many properties or array, -the result is the same. This process turns very easily to create forms from nested objects, -the same layers and properties are replicated in the final object, -this approach prevents you to type more code to convert an object from form to backend object type. The same process is realized with errors object and touched objects. - -## What to expect with useForm +## Motivation -- Performer forms - useForm provides a way to complete a form and submit it without any rerender, by default useForm creates uncontrolled forms. -- Easy to write - useForm has an easy way to write forms with less code. - register function return necessary input's properties and it is all we need to manage all events in a native HTML `input`. Also, you can write forms without form tag. -- Easy validation - By default useform uses yup validation, we can write complex validation without effort. -- Easy to use - useForm is very easy to use, you can register a field with a single line of code. -- No dependencies - useForm does not depend on any library to work. +Today we have a lot of form packages, and this project don't pretend to be the number one, this is just a new way to create hooks to manage your forms. But if you guys like this project, we can publish it, and maintain it. -## Installation +## First step +The first step is to create your form with the `createForm` function, this function returns a hook that you can use to manage your form, wherever you want to use. -``` - npm i @use-form/use-form -``` +``` javascript +export const useLoginForm = createForm({ + initialValues: { + email: 'juciano@juciano.com', + password: 'yourpassword', + } +}) ``` - yarn add @use-form/use-form -``` - -## Usage - -`useForm` provides a `register` function, this function return all necessary properties to manage the input's events and validation. - -
+## Second step +The second step is to create a component to render your form, you can use the `useLoginForm` hook to get the form state and manage it. -```javascript -import { useForm } from '@use-form/use-form' - -/* - * initial Values optional - */ -const initialValues = { - name: 'Jesse', - email: 'jesse@jesse.com', - score: 25 -} - -const { - register, - state: { values } -} = useForm({ initialValues, mode: 'onChange' }) +```jsx + import { useLoginForm } from 'react-create-form' + + const LoginForm = () => { + const { handleSubmit, register } = useLoginForm() + + function onSubmit(values) { + console.log(values) + } + + return ( +
+ + + +
+ ) + } ``` -Use dot notation to create nested objects or to map object values. Type an entry name and type or an entry property object. -```jsx - - - -``` +# It's All. +## Read the full documentation [here](https://useform.org/docs/). ### [Post](https://dev.to/jucian0/building-forms-with-useform-1cna) ## 🤝 Contributing diff --git a/__tests__/debounce.test.ts b/__tests__/debounce.test.ts deleted file mode 100644 index fd9c01b3..00000000 --- a/__tests__/debounce.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { debounce } from '../src/utils' - -describe('Test debounce function', () => { - jest.useFakeTimers() - - it('should call immediately function callback', () => { - const callback = jest.fn() - - const debounced = debounce(callback, 100, true) - - debounced() - jest.advanceTimersByTime(0) - - expect(callback).toBeCalled() - }) - - it('should call function callback when the time is up', () => { - const callback = jest.fn() - - const debounced = debounce(callback, 300) - - debounced() - jest.advanceTimersByTime(300) - - expect(callback).toBeCalled() - }) -}) diff --git a/__tests__/useForm.test.ts b/__tests__/useForm.test.ts deleted file mode 100644 index bbf6b459..00000000 --- a/__tests__/useForm.test.ts +++ /dev/null @@ -1,639 +0,0 @@ -import { - makeHandleChangeSut, - makeRadioSut, - makeSelectSut, - makeSut, - makeUseFormParamsMock -} from './utils/makeSut' -import * as faker from 'faker' -import { waitFor } from '@testing-library/dom' -import '@testing-library/jest-dom/extend-expect' -import { act, fireEvent } from '@testing-library/react' - -describe('Test initial state', () => { - test('Should set initial values', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word() - }) - const { hookState } = makeSut(mock) - await waitFor(() => { - expect(hookState.state.values).toEqual(mock.hookParams.initialValues) - }) - }) - - test('Should set initial errors', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word(), - error: faker.random.words() - }) - const { hookState } = makeSut(mock) - await waitFor(() => { - expect(hookState.state.errors).toEqual(mock.hookParams.initialErrors) - }) - }) - - test('Should set initial touched', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word(), - touched: faker.datatype.boolean() - }) - const { hookState } = makeSut(mock) - await waitFor(() => { - expect(hookState.state.touched).toEqual(mock.hookParams.initialTouched) - }) - }) -}) - -describe('Test handle functions to setField/value/error/touched and resetField/value/error/touched', () => { - test('Should change input state when run setFieldValue', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word() - }) - const { hookState } = makeSut(mock) - const newValue = faker.random.word() - - act(() => { - hookState.setFieldValue(mock.inputParams.name, newValue) - }) - - await waitFor(() => { - expect(hookState.state.values.inputName).toEqual(newValue) - }) - }) - - test('Should change input state when run setFieldError', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word(), - error: faker.random.words() - }) - const { hookState } = makeSut(mock) - const newError = faker.random.words() - - act(() => { - hookState.setFieldError(mock.inputParams.name, newError) - }) - - await waitFor(() => { - expect(hookState.state.errors.inputName).toEqual(newError) - }) - }) - - test('Should change input state when run setFieldTouched', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word(), - touched: false - }) - const { hookState } = makeSut(mock) - const newTouched = true - - act(() => { - hookState.setFieldTouched(mock.inputParams.name, newTouched) - }) - - await waitFor(() => { - expect(hookState.state.touched.inputName).toEqual(newTouched) - }) - }) - - test('Should reset input state when run resetFieldError', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word(), - error: faker.random.words() - }) - const { hookState } = makeSut(mock) - const newError = faker.random.words() - - act(() => { - hookState.setFieldError(mock.inputParams.name, newError) - }) - - await waitFor(() => { - expect(hookState.state.errors.inputName).toEqual(newError) - }) - - act(() => { - hookState.resetFieldError(mock.inputParams.name) - }) - - await waitFor(() => { - expect(hookState.state.errors.inputName).toEqual( - mock.hookParams.initialErrors.inputName - ) - }) - }) - - test('Should reset input state when run resetFieldTouched', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word(), - touched: false - }) - const { hookState } = makeSut(mock) - const newTouched = true - - act(() => { - hookState.setFieldTouched(mock.inputParams.name, newTouched) - }) - - await waitFor(() => { - expect(hookState.state.touched.inputName).toEqual(newTouched) - }) - - act(() => { - hookState.resetFieldTouched(mock.inputParams.name) - }) - - await waitFor(() => { - expect(hookState.state.touched.inputName).toEqual( - mock.hookParams.initialTouched.inputName - ) - }) - }) - - test('Should reset input state when run resetFieldValue', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word() - }) - const { hookState } = makeSut(mock) - const newValue = faker.random.word() - - act(() => { - hookState.setFieldValue(mock.inputParams.name, newValue) - }) - - await waitFor(() => { - expect(hookState.state.values.inputName).toEqual(newValue) - }) - - act(() => { - hookState.resetFieldValue(mock.inputParams.name) - }) - - await waitFor(() => { - expect(hookState.state.values.inputName).toEqual( - mock.hookParams.initialValues.inputName - ) - }) - }) -}) - -describe('Test handle functions to setFields/value/error/touched and resetFields/values/errors/touched', () => { - test('Should change input state when run setFieldsValue', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word() - }) - const { hookState } = makeSut(mock) - const newValues = { - inputName: faker.random.word(), - inputEmail: faker.random.word() - } - - act(() => { - hookState.setFieldsValue(newValues) - }) - - await waitFor(() => { - expect(hookState.state.values).toEqual(newValues) - }) - }) - - test('Should change input state when run setFieldsError', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word(), - error: faker.random.words() - }) - const { hookState } = makeSut(mock) - const newErrors = { - inputName: faker.random.words(), - inputEmail: faker.random.words() - } - - act(() => { - hookState.setFieldsError(newErrors) - }) - - await waitFor(() => { - expect(hookState.state.errors).toEqual(newErrors) - }) - }) - - test('Should change input state when run setFieldsTouched', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word(), - touched: faker.datatype.boolean() - }) - const { hookState } = makeSut(mock) - const newTouched = { - inputName: faker.datatype.boolean(), - inputEmail: faker.datatype.boolean() - } - - act(() => { - hookState.setFieldsTouched(newTouched) - }) - }) - - test('Should reset input state when run resetFieldsValue', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word() - }) - const { hookState } = makeSut(mock) - const newValues = { - inputName: faker.random.word(), - inputEmail: faker.random.word() - } - - act(() => { - hookState.setFieldsValue(newValues) - }) - - await waitFor(() => { - expect(hookState.state.values).toEqual(newValues) - }) - - act(() => { - hookState.resetFieldsValue() - }) - - await waitFor(() => { - expect(hookState.state.values).toEqual(mock.hookParams.initialValues) - }) - }) - - test('Should reset input state when run resetFieldsError', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word(), - error: faker.random.words() - }) - const { hookState } = makeSut(mock) - const newErrors = { - inputName: faker.random.words(), - inputEmail: faker.random.words() - } - - act(() => { - hookState.setFieldsError(newErrors) - }) - - await waitFor(() => { - expect(hookState.state.errors).toEqual(newErrors) - }) - - act(() => { - hookState.resetFieldsError() - }) - - await waitFor(() => { - expect(hookState.state.errors).toEqual(mock.hookParams.initialErrors) - }) - }) - - test('Should reset input state when run resetFieldsTouched', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word(), - touched: faker.datatype.boolean() - }) - const { hookState } = makeSut(mock) - const newTouched = { - inputName: faker.datatype.boolean(), - inputEmail: faker.datatype.boolean() - } - - act(() => { - hookState.setFieldsTouched(newTouched) - }) - - await waitFor(() => { - expect(hookState.state.touched).toEqual(newTouched) - }) - - act(() => { - hookState.resetFieldsTouched() - }) - - await waitFor(() => { - expect(hookState.state.touched).toEqual(mock.hookParams.initialTouched) - }) - }) -}) - -describe('Test form handle functions', () => { - test('Should change form state when run setForm', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word(), - error: faker.random.words() - }) - const { hookState } = makeSut(mock) - const newState = { - values: { - inputName: faker.random.word() - }, - errors: {}, - touched: {} - } - - act(() => { - hookState.setForm(newState) - }) - - await waitFor(() => { - expect(hookState.state).toEqual(newState) - }) - }) - - test('Should change form state when run resetForm', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word() - }) - const { hookState } = makeSut(mock) - const newState = { - values: { - inputName: faker.random.word() - }, - errors: {}, - touched: {} - } - - act(() => { - hookState.setForm(newState) - }) - - await waitFor(() => { - expect(hookState.state).toEqual(newState) - }) - - act(() => { - hookState.resetForm() - }) - - await waitFor(() => { - expect(hookState.state).toEqual({ - values: { - inputName: mock.hookParams.initialValues.inputName - }, - errors: { inputName: '' }, - touched: { inputName: false } - }) - }) - }) -}) - -describe('Tests input event and state manipulation', () => { - test('Should update input value when dispatch input event', async () => { - const mock = makeUseFormParamsMock({ - value: faker.random.word() - }) - const { hookState, sut } = makeSut(mock) - const input = sut.getByTestId(mock.inputParams.name) - const nextValue = faker.name.firstName() - fireEvent.input(input, { target: { value: nextValue } }) - - await waitFor(() => { - expect(hookState.state.values.inputName).toEqual(nextValue) - }) - }) - - test('Should update input number value when dispatch input event', () => { - const mock = makeUseFormParamsMock({ - value: faker.datatype.number(), - type: 'number' - }) - const { hookState, sut } = makeSut(mock) - const input = sut.getByTestId(mock.inputParams.name) - const nextValue = faker.datatype.number() - fireEvent.input(input, { target: { value: nextValue } }) - - expect(hookState.state.values.inputName).toEqual(nextValue) - }) - - test('Should update input checkbox value when dispatch input event', () => { - const mock = makeUseFormParamsMock({ - value: faker.datatype.boolean(), - type: 'checkbox' - }) - const { hookState, sut } = makeSut(mock) - const input = sut.getByTestId(mock.inputParams.name) - const nextValue = faker.datatype.number() - fireEvent.input(input, { target: { value: nextValue } }) - - expect(hookState.state.values.inputName).toEqual(nextValue) - }) - - test('Should update input range value when dispatch input event', () => { - const mock = makeUseFormParamsMock({ - value: faker.datatype.number({ min: 0, max: 100 }), - type: 'range' - }) - const { hookState, sut } = makeSut(mock) - const input = sut.getByTestId(mock.inputParams.name) - const nextValue = faker.datatype.number() - fireEvent.input(input, { target: { value: nextValue } }) - - expect(hookState.state.values.inputName).toEqual(nextValue) - }) - - test('Should update input date value when dispatch input event', () => { - const mock = makeUseFormParamsMock({ - value: faker.date.past(), - type: 'date' - }) - const { hookState, sut } = makeSut(mock) - const input = sut.getByTestId(mock.inputParams.name) - const nextValue = new Date(faker.date.past()).toTimeString() - fireEvent.input(input, { target: { value: nextValue } }) - - expect(hookState.state.values.inputName).toEqual(nextValue) - }) - - test('Should update input time value when dispatch input event', () => { - const mock = makeUseFormParamsMock({ - value: faker.date.past(), - type: 'time' - }) - const { hookState, sut } = makeSut(mock) - const input = sut.getByTestId(mock.inputParams.name) - const nextValue = new Date(faker.date.past()).toTimeString() - fireEvent.input(input, { target: { value: nextValue } }) - - expect(hookState.state.values.inputName).toEqual(nextValue) - }) - - test('Should update input datetime-local value when dispatch input event', () => { - const mock = makeUseFormParamsMock({ - value: faker.date.past(), - type: 'datetime-local' - }) - const { hookState, sut } = makeSut(mock) - const input = sut.getByTestId(mock.inputParams.name) - const nextValue = new Date(faker.date.past()).toTimeString() - fireEvent.input(input, { target: { value: nextValue } }) - - expect(hookState.state.values.inputName).toEqual(nextValue) - }) - - test('Should update input month value when dispatch input event', () => { - const mock = makeUseFormParamsMock({ - value: faker.date.past(), - type: 'month' - }) - const { hookState, sut } = makeSut(mock) - const input = sut.getByTestId(mock.inputParams.name) - const nextValue = new Date(faker.date.past()).toTimeString() - fireEvent.input(input, { target: { value: nextValue } }) - - expect(hookState.state.values.inputName).toEqual(nextValue) - }) - - test('Should update input week value when dispatch input event', () => { - const mock = makeUseFormParamsMock({ - value: faker.date.past(), - type: 'week' - }) - const { hookState, sut } = makeSut(mock) - const input = sut.getByTestId(mock.inputParams.name) - const nextValue = new Date(faker.date.past()).toTimeString() - fireEvent.input(input, { target: { value: nextValue } }) - - expect(hookState.state.values.inputName).toEqual(nextValue) - }) - - test('Should update input color value when dispatch input event', () => { - const mock = makeUseFormParamsMock({ - value: faker.internet.color(), - type: 'color' - }) - const { hookState, sut } = makeSut(mock) - const input = sut.getByTestId(mock.inputParams.name) - const nextValue = faker.internet.color() - fireEvent.input(input, { target: { value: nextValue } }) - - expect(hookState.state.values.inputName).toEqual(nextValue) - }) - - test('Should update input radio value when dispatch input event', async () => { - const mock = makeUseFormParamsMock({ - value: 'option-1' - }) - const { hookState, sut } = makeRadioSut(mock) - const input = sut.getByTestId('radio-2') - const nextValue = 'option-2' - fireEvent.click(input) - - expect(hookState.state.values.inputName).toEqual(nextValue) - }) - - test('Should update input select value when dispatch input event', () => { - const mock = makeUseFormParamsMock({ - value: 'option-1' - }) - const { hookState, sut } = makeSelectSut(mock) - const input = sut.getByTestId(mock.inputParams.name) - const nextValue = 'option-2' - fireEvent.input(input, { target: { value: nextValue } }) - - expect(hookState.state.values.inputName).toEqual(nextValue) - }) -}) - -describe('Tests useForm mode', () => { - test('Should update input text value just when dispatch blur event', () => { - const mock = makeUseFormParamsMock({ - value: faker.lorem.words(), - type: 'text', - mode: 'onBlur' - }) - - const { hookState, sut } = makeSut(mock) - const input = sut.getByTestId(mock.inputParams.name) - const nextValue = faker.lorem.words() - fireEvent.input(input, { target: { value: nextValue } }) - expect(hookState.state.values.inputName).toEqual( - mock.hookParams.initialValues.inputName - ) - - fireEvent.blur(input) - expect(hookState.state.values.inputName).toEqual(nextValue) - }) - - test('Should update input text value just when dispatch input event', () => { - const mock = makeUseFormParamsMock({ - value: faker.lorem.words(), - type: 'text' - }) - - const { hookState, sut } = makeSut(mock) - const input = sut.getByTestId(mock.inputParams.name) - const nextValue = faker.lorem.words() - - fireEvent.blur(input, { target: { value: nextValue } }) - expect(hookState.state.values.inputName).toEqual( - mock.hookParams.initialValues.inputName - ) - - fireEvent.input(input, { target: { value: nextValue } }) - expect(hookState.state.values.inputName).toEqual(nextValue) - }) - - test('Should update input text value just 500ms after dispatch input event', async () => { - const mock = makeUseFormParamsMock({ - value: faker.lorem.words(), - type: 'text', - mode: 'debounced' - }) - - const { hookState, sut } = makeSut(mock) - const input = sut.getByTestId(mock.inputParams.name) - const nextValue = faker.lorem.words() - - fireEvent.input(input, { target: { value: nextValue } }) - expect(hookState.state.values.inputName).toEqual( - mock.hookParams.initialValues.inputName - ) - - await waitFor(() => { - expect(hookState.state.values.inputName).toEqual(nextValue) - }) - }) - - test('Should receive form value when submit form', async () => { - const mock = makeUseFormParamsMock({ - value: faker.lorem.words(), - type: 'text', - mode: 'onSubmit' - }) - - const { hookState, sut } = makeSut(mock) - const input = sut.getByTestId(mock.inputParams.name) - const nextValue = faker.lorem.words() - const onSubmitParams = [ - { - inputName: nextValue - }, - true - ] - - fireEvent.input(input, { target: { value: nextValue } }) - expect(hookState.state.values.inputName).toEqual( - mock.hookParams.initialValues.inputName - ) - - fireEvent.submit(sut.getByTestId('form')) - - await waitFor(() => { - expect(mock.onSubmit).toHaveBeenCalledWith(...onSubmitParams) - }) - }) - - test('Should change input value when run handleChange function', () => { - const mock = makeUseFormParamsMock({ - value: faker.lorem.words(), - type: 'text' - }) - - const { hookState, sut } = makeHandleChangeSut(mock) - const input = sut.getByTestId(mock.inputParams.name) - const nextValue = faker.lorem.words() - fireEvent.change(input, { target: { value: nextValue } }) - - expect(hookState.state.values.inputName).toEqual(nextValue) - }) -}) diff --git a/__tests__/utils/makeSut.tsx b/__tests__/utils/makeSut.tsx deleted file mode 100644 index 7aa2d21d..00000000 --- a/__tests__/utils/makeSut.tsx +++ /dev/null @@ -1,170 +0,0 @@ -import React from 'react' -import { render } from '@testing-library/react' -import { useForm } from '../../src/index' -import { UseFormReturnType } from '../../src/types' - -export function makeSut({ hookParams, inputParams, onSubmit }: any) { - const hookState: UseFormReturnType = Object.assign({}) - - function InputComponent() { - const { state, register, ...rest } = useForm(hookParams) - Object.assign(hookState, { state, ...rest }) - - return ( -
- - - -
- ) - } - - const sut = render() - - return { sut, hookState } -} - -export function makeHandleChangeSut({ - hookParams, - inputParams, - onSubmit -}: any) { - const hookState: UseFormReturnType = Object.assign({}) - - function InputComponent() { - const { state, register, ...rest } = useForm(hookParams) - Object.assign(hookState, { state, ...rest }) - - return ( -
- -
- ) - } - - const sut = render() - - return { sut, hookState } -} - -export function makeRadioSut({ hookParams, inputParams, onSubmit }: any) { - const hookState: UseFormReturnType = Object.assign({}) - - function InputComponent() { - const { state, register, ...rest } = useForm(hookParams) - Object.assign(hookState, { state, ...rest }) - - return ( -
-
- - - -
- - -
- ) - } - - const sut = render() - - return { sut, hookState } -} - -export function makeSelectSut({ hookParams, inputParams, onSubmit }: any) { - const hookState: UseFormReturnType = Object.assign({}) - - function InputComponent() { - const { state, register, ...rest } = useForm(hookParams) - Object.assign(hookState, { state, ...rest }) - - return ( -
- - - -
- ) - } - - const sut = render() - - return { sut, hookState } -} - -export function makeUseFormParamsMock({ - value = '', - name = 'inputName', - type = 'text', - touched = false, - error = '', - mode = 'onChange' -}: { - value?: any - name?: string - type?: string - touched?: boolean - error?: string - mode?: 'onChange' | 'onBlur' | 'debounced' | 'onSubmit' -}) { - return { - hookParams: { - initialValues: { - inputName: value - }, - initialTouched: { - inputName: touched - }, - initialErrors: { - inputName: error - }, - mode - }, - onSubmit: jest.fn(), - inputParams: { - name, - type - } - } -} diff --git a/__tests__/utils/tes-input-file.json b/__tests__/utils/tes-input-file.json deleted file mode 100644 index 6bd2dd80..00000000 --- a/__tests__/utils/tes-input-file.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "test": "file.json" -} \ No newline at end of file diff --git a/example/.gitignore b/example/.gitignore index 587e4ec7..d451ff16 100644 --- a/example/.gitignore +++ b/example/.gitignore @@ -1,3 +1,5 @@ node_modules -.cache -dist \ No newline at end of file +.DS_Store +dist +dist-ssr +*.local diff --git a/example/babel.config.js b/example/babel.config.js deleted file mode 100644 index 2dc03f52..00000000 --- a/example/babel.config.js +++ /dev/null @@ -1,16 +0,0 @@ - module.exports = { - "presets": [ - "@babel/preset-env", - "@babel/preset-react", - "@babel/typescript", - ], - "plugins": [ - "@babel/proposal-class-properties", - "@babel/proposal-object-rest-spread", - "@babel/plugin-syntax-optional-chaining", - "@babel/plugin-proposal-optional-chaining", - "react-hot-loader/babel", - "@babel/plugin-transform-runtime", - "@babel/plugin-transform-classes" - ] -} \ No newline at end of file diff --git a/example/index.html b/example/index.html new file mode 100644 index 00000000..38f38611 --- /dev/null +++ b/example/index.html @@ -0,0 +1,13 @@ + + + + + + + Vite App + + +
+ + + diff --git a/example/package.json b/example/package.json index 027ba7a5..f20ff80a 100644 --- a/example/package.json +++ b/example/package.json @@ -1,43 +1,25 @@ { - "name": "playground", - "version": "1.0.0", - "main": "index.js", - "license": "MIT", + "name": "react-create-form", + "version": "0.0.0", "scripts": { - "start": "webpack-dev-server --mode development" + "dev": "vite", + "build": "tsc && vite build", + "preview": "vite preview" }, "dependencies": { - "@material-ui/core": "*", - "bootstrap": "^4.6.0", - "react-app-polyfill": "^1.0.0", - "react-select": "^5.1.0", - "yup": "^0.32.11" - }, - "alias": { - "react": "../node_modules/react", - "react-dom": "../node_modules/react-dom/profiling", - "scheduler/tracing": "../node_modules/scheduler/tracing-profiling" + "@types/react-datepicker": "^4.3.4", + "react": "^17.0.2", + "react-datepicker": "^4.6.0", + "react-dom": "^17.0.2", + "react-select": "^5.2.1", + "yup": "^0.27.0" }, "devDependencies": { - "@babel/core": "^7.10.5", - "@babel/plugin-transform-classes": "^7.13.0", - "@babel/plugin-transform-runtime": "^7.13.10", - "@babel/preset-env": "^7.10.4", - "@babel/preset-react": "^7.10.4", - "@babel/preset-typescript": "^7.10.4", - "@pmmmwh/react-refresh-webpack-plugin": "^0.3.3", - "@types/react": "^16.9.11", - "@types/react-dom": "^16.8.4", - "babel-loader": "^8.2.2", - "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2", - "css-loader": "^5.2.6", - "html-webpack-plugin": "^4.3.0", - "react-hot-loader": "^4.13.0", - "react-refresh": "^0.9.0", - "style-loader": "^2.0.0", - "typescript": "^4.2.2", - "webpack": "^4.43.0", - "webpack-cli": "^3.3.12", - "webpack-dev-server": "^3.11.0" + "@types/react": "^17.0.33", + "@types/react-dom": "^17.0.10", + "@types/yup": "^0.29.13", + "@vitejs/plugin-react": "^1.0.7", + "typescript": "^4.4.4", + "vite": "^2.7.2" } } diff --git a/example/public/index.html b/example/public/index.html deleted file mode 100644 index 03a65e87..00000000 --- a/example/public/index.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - Playground - - - -
- - - \ No newline at end of file diff --git a/example/src/App.css b/example/src/App.css new file mode 100644 index 00000000..8da3fde6 --- /dev/null +++ b/example/src/App.css @@ -0,0 +1,42 @@ +.App { + text-align: center; +} + +.App-logo { + height: 40vmin; + pointer-events: none; +} + +@media (prefers-reduced-motion: no-preference) { + .App-logo { + animation: App-logo-spin infinite 20s linear; + } +} + +.App-header { + background-color: #282c34; + min-height: 100vh; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + font-size: calc(10px + 2vmin); + color: white; +} + +.App-link { + color: #61dafb; +} + +@keyframes App-logo-spin { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +} + +button { + font-size: calc(10px + 2vmin); +} diff --git a/example/src/App.tsx b/example/src/App.tsx new file mode 100644 index 00000000..de705611 --- /dev/null +++ b/example/src/App.tsx @@ -0,0 +1,218 @@ +import { useState } from 'react' +import * as yup from 'yup' +import './App.css' +import { createForm, Wrapper } from '../../src' +import Select from 'react-select' +import DatePicker from 'react-datepicker' + +import 'react-datepicker/dist/react-datepicker.css' + +const validationSchema = yup.object().shape({ + email: yup.string().email().required(), + password: yup.string().required(), + agree: yup.boolean().required(), + gender: yup.string().required() +}) + +function App() { + const [count, setCount] = useState(0) + + return ( +
+ + {/* */} +
+ ) +} + +export default App + +const useLoginForm = createForm({ + initialValues: { + email: 'juciano@juciano.com', + password: '1234567', + agree: true, + gender: 'masculine', + distance: 10, + location: { + city: '', + state: '', + zip: '' + }, + select: { + label: 'Outro', + value: 'other' + }, + date: null + }, + validationSchema + // initialErrors: { + // email: 'E-mail ja esta sendo usado' + // } +}) + +const options = [ + { value: 'masculine', label: 'Masculino' }, + { value: 'feminine', label: 'Feminino' }, + { value: 'other', label: 'Outro' } +] + +function FormComponent() { + const { + state, + register, + form, + setFieldValue, + setFieldsValue, + reset, + resetValues, + resetTouched, + resetErrors, + setFieldsError, + setFieldsTouched, + handleSubmit + } = useLoginForm({ + mode: 'onChange', + onChange: values => { + // console.log('onChange', values) + // return values + } + }) + + function handleEmail() { + setFieldValue('email', 'jose@jose.com') + } + + function handleReset() { + reset() + } + + function handleResetValues() { + resetValues() + } + + function handleResetTouched() { + resetTouched() + } + + function handleResetErrors() { + resetErrors() + } + + function handleAllValues() { + setFieldsValue({ + email: 'jose@jose.com', + password: '1234567891011121314151618', + gender: 'female', + agree: false, + distance: 10, + location: { + city: 'São Paulo', + state: 'SP', + zip: '01001-000' + }, + select: { + value: 'masculine', + label: 'Masculino' + }, + date: null + }) + + setFieldsTouched(state => ({ + ...state, + email: true + })) + } + + function handleSetErrors() { + setFieldsError(state => ({ + ...state, + password: 'Senha deve conter no mínimo 8 caracteres' + })) + } + + console.log('state', state) + + return ( +
+

Form

+
{ + // console.log(e, isValid) + })} + > + + + + +
+ + Masculine + + Female +
+ + + + + + + + + + + + + + + + + +
+ ) +} + +function FormComponent2() { + const { register, form } = useLoginForm() + return ( +
+

Form2

+
+ + + + + + +
+
+ ) +} diff --git a/example/src/Controlled/index.tsx b/example/src/Controlled/index.tsx deleted file mode 100644 index d1765fb7..00000000 --- a/example/src/Controlled/index.tsx +++ /dev/null @@ -1,120 +0,0 @@ -import React, { useEffect } from 'react' -import { useForm } from '../../../src/hooks/useForm' -import { useFormContext } from '../../../src/hooks/useContextForm' -import { FormContextProvider } from '../../../src/core/contextForm' -import Select from 'react-select' - -const options = [ - { value: 'chocolate', label: 'Chocolate' }, - { value: 'strawberry', label: 'Strawberry' }, - { value: 'vanilla', label: 'Vanilla' } -] - -const Controlled: React.FC = () => { - const { state, register, setFieldsValue, onSubmit, ...form } = useForm({ - initialValues: { - name: 'juciano', - email: 'juciano@juciano.com' - // password: '123456', - } - }) - - console.log(state) - - return ( - -
{ - console.log(e) - })} - > -
-
-
- - -
-
-
-
- - -
-
- -
-
- - -
-
- -
-
-
- ) -} - -function InnerForm() { - const { register, setFieldValue, state, setFieldTouched } = useFormContext() - - // console.log(form.state.values) - - return ( -
-
-
- - -
-
-
-
- - + + + + + ) + } + + const element = render() + + return { + element, + spy, + sut + } +} + +function makeMockedValues() { + return { + name: faker.name.firstName(), + email: faker.internet.email(), + password: faker.internet.password() + } +} + +describe('CreateForm', () => { + each(['onChange', 'debounce']).it( + 'Should init the hook with the initial properties - [%s] mode', + mode => { + const initialValues = makeMockedValues() + const form = makeSut({ initialValues }, mode) + expect(form.sut.current.state.values).toEqual(initialValues) + } + ) + + each(['onChange', 'debounce']).it( + 'Should update the hook when run setFieldValue - [%s] mode', + async mode => { + const initialValues = makeMockedValues() + const form = makeSut({ initialValues }, mode) + const newValue = faker.name.findName() + form.sut.current.setFieldValue('name', newValue) + + await waitFor(() => { + expect(form.sut.current.state.values.name).toEqual(newValue) + }) + } + ) + + each(['onChange', 'debounce']).it( + 'Should update the hook when run setFieldError - [%s] mode', + async mode => { + const initialValues = makeMockedValues() + const form = makeSut({ initialValues }, mode) + const newError = faker.name.findName() + form.sut.current.setFieldError('name', newError) + + await waitFor(() => { + expect(form.sut.current.state.errors.name).toEqual(newError) + }) + } + ) + + each(['onChange', 'debounce']).it( + 'Should update the hook when run setFieldTouched - [%s] mode', + async mode => { + const initialValues = makeMockedValues() + const form = makeSut({ initialValues }, mode) + form.sut.current.setFieldTouched('name', true) + + await waitFor(() => { + expect(form.sut.current.state.touched.name).toEqual(true) + }) + } + ) + + each(['onChange', 'debounce']).it( + 'Should update the hook when run setFieldsValue - [%s] mode', + async mode => { + const initialValues = makeMockedValues() + const newValues = makeMockedValues() + const form = makeSut({ initialValues }, mode) + form.sut.current.setFieldsValue(newValues) + + await waitFor(() => { + expect(form.sut.current.state.values).toEqual(newValues) + }) + } + ) + + each(['onChange', 'debounce']).it( + 'Should update the hook when run setFieldsError - [%s] mode', + async mode => { + const initialValues = makeMockedValues() + const form = makeSut({ initialValues }, mode) + const newErrors = makeMockedValues() + form.sut.current.setFieldsError(newErrors) + + await waitFor(() => { + expect(form.sut.current.state.errors).toEqual(newErrors) + }) + } + ) + + each(['onChange', 'debounce']).it( + 'Should update the hook when run setFieldsTouched - [%s] mode', + async mode => { + const initialValues = makeMockedValues() + const form = makeSut({ initialValues }, mode) + const newTouched = { + name: true, + email: true, + password: true + } + form.sut.current.setFieldsTouched(newTouched) + + await waitFor(() => { + expect(form.sut.current.state.touched).toEqual(newTouched) + }) + } + ) + + each(['onChange', 'debounce']).it( + 'Should update the hook when run resetErrors - [%s] mode', + async mode => { + const initialValues = makeMockedValues() + const form = makeSut({ initialValues }, mode) + const newErrors = makeMockedValues() + form.sut.current.setFieldsError(newErrors) + + await waitFor(() => { + expect(form.sut.current.state.errors).toEqual(newErrors) + }) + form.sut.current.resetErrors() + await waitFor(() => { + expect(form.sut.current.state.errors).toEqual({}) + }) + } + ) + + each(['onChange', 'debounce']).it( + 'Should update the hook when run resetValues - [%s] mode', + async mode => { + const initialValues = makeMockedValues() + const form = makeSut({ initialValues }, mode) + const newValues = makeMockedValues() + form.sut.current.setFieldsValue(newValues) + + await waitFor(() => { + expect(form.sut.current.state.values).toEqual(newValues) + }) + form.sut.current.resetValues() + await waitFor(() => { + expect(form.sut.current.state.values).toEqual(initialValues) + }) + } + ) + + each(['onChange', 'debounce']).it( + 'Should update the hook when run resetTouched - [%s] mode', + async mode => { + const initialValues = makeMockedValues() + const form = makeSut({ initialValues }, mode) + const newTouched = { + name: true, + email: true, + password: true + } + form.sut.current.setFieldsTouched(newTouched) + await waitFor(() => { + expect(form.sut.current.state.touched).toEqual(newTouched) + }) + + form.sut.current.resetTouched() + + await waitFor(() => { + expect(form.sut.current.state.touched).toEqual({}) + }) + } + ) + + each(['onChange', 'debounce']).it( + 'Should update the hook when run reset - [%s] mode', + async mode => { + const initialValues = makeMockedValues() + const form = makeSut({ initialValues }, mode) + const newValues = makeMockedValues() + await waitFor(() => { + form.sut.current.setFieldsValue(newValues) + }) + form.sut.current.reset() + + await waitFor(() => { + expect(form.sut.current.state.values).toEqual(initialValues) + expect(form.sut.current.state.touched).toEqual({}) + expect(form.sut.current.state.errors).toEqual({}) + }) + } + ) + + each(['onChange', 'debounce']).it( + 'SHould call handleSubmit function when run onSubmit - [%s] mode', + async mode => { + const initialValues = makeMockedValues() + const form = makeSut({ initialValues }, mode) + const submitButton = form.element.getByTestId('submit') + + fireEvent.click(submitButton) + // since we aren't passing any validation we assume the form is valid + const submittedValues = [initialValues, true] + + await waitFor(() => { + expect(form.spy).toHaveBeenCalledWith(...submittedValues) + }) + } + ) + + each(['onChange', 'debounce']).it( + 'Should call handleSubmit function when run onSubmit with errors - [%s] mode', + async mode => { + const initialValues = makeMockedValues() + const initialErrors = { + name: faker.name.findName() + } + + const form = makeSut({ initialValues, initialErrors }, mode) + const submitButton = form.element.getByTestId('submit') + + fireEvent.click(submitButton) + // since we are passing an error validation we assume the form is invalid + const submittedValues = [initialValues, false] + + await waitFor(() => { + expect(form.spy).toHaveBeenCalledWith(...submittedValues) + }) + } + ) + + each(['onChange', 'debounce']).it( + 'Should call onChange function when any change event happens - [%s] mode', + async mode => { + const initialValues = makeMockedValues() + const form = makeSut({ initialValues }, mode) + const input = form.element.getByTestId('name') + const nextValue = faker.name.findName() + const nextValues = { + ...initialValues, + name: nextValue + } + + fireEvent.input(input, { target: { value: nextValue } }) + + await waitFor(() => { + expect(form.spy).toHaveBeenCalledWith(nextValues) + }) + } + ) + + each(['onChange', 'debounce']).it( + 'Should call onBlur function when any blur event happens - [%s] mode', + async mode => { + const initialValues = makeMockedValues() + const form = makeSut({ initialValues }, mode) + const input = form.element.getByTestId('name') + fireEvent.blur(input) + + await waitFor(() => { + expect(form.spy).toHaveBeenCalledWith(initialValues) + }) + } + ) + + each(['onChange', 'debounce']).it( + 'Should update hook state when a change event happens - [%s] mode', + async mode => { + const initialValues = makeMockedValues() + const form = makeSut({ initialValues }, mode) + const input = form.element.getByTestId('name') + const nextValue = faker.name.findName() + const nextValues = { + ...initialValues, + name: nextValue + } + + fireEvent.input(input, { target: { value: nextValue } }) + + await waitFor(() => { + expect(form.sut.current.state.values).toEqual(nextValues) + }) + } + ) + + each(['onChange', 'debounce']).it( + 'Should update hook state when a blur event happens - [%s] mode', + async mode => { + const initialValues = makeMockedValues() + const form = makeSut({ initialValues }, mode) + const input = form.element.getByTestId('name') + fireEvent.blur(input) + + await waitFor(() => { + expect(form.sut.current.state.touched).toEqual({ name: true }) + }) + } + ) +}) diff --git a/test/ObjectUtils.test.ts b/test/ObjectUtils.test.ts new file mode 100644 index 00000000..ee1efbb4 --- /dev/null +++ b/test/ObjectUtils.test.ts @@ -0,0 +1,61 @@ +import * as Dot from './../src/ObjectUtils' + +describe('Dot set', () => { + it('Should set a value', () => { + const obj = (value: string) => ({ foo: value }) + const newValue = 'baz' + const newObj = Dot.set(obj('bar'), 'foo', newValue) + expect(newObj).toEqual(obj(newValue)) + }) + + it('Should set a value in an array', () => { + const obj = (value: string) => ({ foo: [value] }) + const newValue = 'bar' + const newObj = Dot.set(obj('bar'), 'foo[0]', newValue) + expect(newObj).toEqual(obj(newValue)) + }) + + it('Should set a value in an array with a number', () => { + const newValue = 'baz' + const newObj = Dot.set({ foo: [] }, 'foo.1', newValue) + expect(newObj).toEqual({ foo: [undefined, newValue] }) + }) + + it('Should set a value in a nested object', () => { + const newValue = 'baz' + const newObj = Dot.set({ foo: { bar: 'bar' } }, 'foo.bar', newValue) + expect(newObj).toEqual({ foo: { bar: newValue } }) + }) +}) + +describe('Dot get', () => { + it('Should get a value', () => { + const obj = { foo: 'bar' } + expect(Dot.get(obj, 'foo')).toEqual('bar') + }) + + it('Should get a value in an array', () => { + const obj = { foo: ['bar'] } + expect(Dot.get(obj, 'foo[0]')).toEqual('bar') + }) + + it('Should get a value in an array with a number', () => { + const obj = { foo: [undefined, 'bar'] } + expect(Dot.get(obj, 'foo.1')).toEqual('bar') + }) + + it('Should get a value in a nested object', () => { + const obj = { foo: { bar: 'bar' } } + expect(Dot.get(obj, 'foo.bar')).toEqual('bar') + }) + + it('Should return undefined when property does not exist', () => { + const obj = { foo: 'bar' } + expect(Dot.get(obj, 'bar')).toEqual(undefined) + }) + + it('Should return undefined when property does not exist in an array', () => { + const obj = { foo: ['bar'] } + expect(Dot.get(obj, 'foo[1]')).toEqual(undefined) + }) +}) diff --git a/test/Store.test.ts b/test/Store.test.ts new file mode 100644 index 00000000..4268a03d --- /dev/null +++ b/test/Store.test.ts @@ -0,0 +1,66 @@ +import { createStore } from '../src/Store' + +function makeSut(state = {}) { + const spy = jest.fn() + const sut = createStore(state) + + return { + sut, + spy + } +} + +describe('Store', () => { + it('Should set initial state when createStore is called', () => { + const initialState = { + foo: 'bar' + } + const { sut } = makeSut(initialState) + expect(sut.get()).toEqual(initialState) + }) + + it('Should set a new state when set is called', () => { + const { sut } = makeSut() + const newState = { + foo: 'bar' + } + sut.set(newState) + expect(sut.get()).toEqual(newState) + }) + + it('Should call subscribers when set is called', () => { + const { sut, spy } = makeSut() + sut.subscribe(spy) + sut.set({ foo: 'bar' }) + expect(spy).toHaveBeenCalledWith({ foo: 'bar' }) + }) + + it('Should patch a state when patch is called', () => { + const { sut } = makeSut() + sut.patch('foo', 'bar') + expect(sut.get()).toEqual({ foo: 'bar' }) + }) + + it('Should call subscribers when patch is called', () => { + const { sut, spy } = makeSut() + sut.subscribe(spy) + sut.patch('foo', 'bar') + expect(spy).toHaveBeenCalledWith({ foo: 'bar' }) + }) + + it('Should get a property value when getPropertyValue is called', () => { + const { sut } = makeSut() + sut.patch('foo', 'bar') + expect(sut.getPropertyValue('foo')).toEqual('bar') + }) + + it('Should get an initial property value when getInitialPropertyValue is called', () => { + const { sut } = makeSut() + expect(sut.getInitialPropertyValue('foo')).toEqual(undefined) + }) + + it('Should get an initial state when getInitialState is called', () => { + const { sut } = makeSut() + expect(sut.getInitialState()).toEqual({}) + }) +}) diff --git a/test/Wrapper.test.tsx b/test/Wrapper.test.tsx new file mode 100644 index 00000000..9ecd4327 --- /dev/null +++ b/test/Wrapper.test.tsx @@ -0,0 +1,63 @@ +import React from 'react' +import { render, fireEvent, waitFor } from '@testing-library/react' +import faker from 'faker' +import { Wrapper } from '../src/Wrapper' +import { createForm } from '../src' +import { renderHook } from '@testing-library/react-hooks' + +function makeSut() { + const sut = render() + return { + sut + } +} + +function Component(props: any) { + function handleOnChange(e: React.ChangeEvent) { + props.onChange(e.target.value) + } + + return ( +
+ +
+ ) +} + +const value = faker.random.word() +const useForm = createForm({ + initialValues: { + name: value + } +}) + +function Setup() { + const form = useForm() + + return +} + +describe('Wrapper', () => { + it('Should render children with the value', () => { + const { sut } = makeSut() + const input = sut.getByTestId('name') as HTMLInputElement + expect(input.value).toBe(value) + }) + + it('Should set the custom input value', async () => { + const form = renderHook(() => useForm({ mode: 'onChange' })) + const { sut } = makeSut() + const input = sut.getByTestId('name') as HTMLInputElement + const nextValue = faker.random.word() + fireEvent.change(input, { target: { value: nextValue } }) + + await waitFor(() => { + expect(form.result.current.state.values.name).toBe(nextValue) + }) + }) +})