Skip to content
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
5 changes: 3 additions & 2 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
{
"version": "0.2.0",

"configurations": [
{
"name": "Debug Core Tests",
"type": "node",
"request": "launch",
"runtimeArgs": ["--inspect-brk", "${workspaceFolder}/node_modules/aqu/dist/aqu.js", "test", "--runInBand"],
"runtimeArgs": ["--inspect-brk", ".\\node_modules\\jest\\bin\\jest.js", "--watch", "useForm.test"],
"cwd": "${workspaceFolder}/packages/core",
"console": "integratedTerminal",
"console": "externalTerminal",
"internalConsoleOptions": "neverOpen",
"port": 9229
}
Expand Down
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,6 @@
"gitlens.codeLens.scopes": ["document"],
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
},
"terminal.integrated.defaultProfile.windows": "Command Prompt"
}
3 changes: 1 addition & 2 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@
"rimraf": "3.0.2",
"ts-jest": "29.0.3",
"tslib": "2.3.1",
"typescript": "4.8.4",
"yup": "0.32.9"
"typescript": "4.8.4"
},
"peerDependencies": {
"react": ">=16"
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/hooks/useField.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ export type FieldConfig<V> = {
name: Pxth<V>;
} & FieldValidationProps<V>;

export const useField = <V>({ name, validator, schema }: FieldConfig<V>): FieldContext<V> => {
export const useField = <V>({ name, validator }: FieldConfig<V>): FieldContext<V> => {
const [value, setValue] = useFieldValue<V>(name);
const [touched, setTouched] = useFieldTouched<V>(name);
const [error, setError] = useFieldError<V>(name);

useFieldValidator({ name, validator, schema });
useFieldValidator({ name, validator });

return {
value,
Expand Down
35 changes: 10 additions & 25 deletions packages/core/src/hooks/useFieldValidator.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,26 @@
import { useEffect, useRef } from 'react';
import merge from 'lodash/merge';
import { useEffect } from 'react';
import { Pxth } from 'pxth';
import type { BaseSchema } from 'yup';

import { useFormContext } from './useFormContext';
import { FieldValidator } from '../typings/FieldValidator';
import { runYupSchema } from '../utils/runYupSchema';
import { validatorResultToError } from '../utils/validatorResultToError';

export type UseFieldValidatorConfig<V> = FieldValidationProps<V> & { name: Pxth<V> };

export type FieldValidationProps<V> = {
validator?: FieldValidator<V>;
schema?: BaseSchema<Partial<V> | V | undefined>;
};

export const useFieldValidator = <V>({ name, validator: validatorFn, schema }: UseFieldValidatorConfig<V>) => {
export const useFieldValidator = <V>({ name, validator }: UseFieldValidatorConfig<V>) => {
const { registerValidator } = useFormContext();

const validate = async (value: V) => {
if (!validatorFn && !schema) return undefined;
useEffect(
() =>
registerValidator(name, async (value: V) => {
if (!validator) return undefined;

const validatorErrors = validatorResultToError(await validatorFn?.(value));
const schemaErrors = schema ? await runYupSchema(schema, value) : undefined;

if (!schemaErrors) return validatorErrors;

return merge(schemaErrors, validatorErrors);
};

const validateRef = useRef(validate);

validateRef.current = validate;

useEffect(() => {
const validator = (value: V) => validateRef.current(value);

return registerValidator(name, validator);
}, [name, registerValidator]);
return validatorResultToError(await validator?.(value));
}),
[name, registerValidator, validator],
);
};
24 changes: 7 additions & 17 deletions packages/core/src/hooks/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import mergeWith from 'lodash/mergeWith';
import { createPxth, deepGet, deepSet, Pxth } from 'pxth';
import { BatchUpdate } from 'stocked';
import invariant from 'tiny-invariant';
import type { BaseSchema } from 'yup';

import { useFormControl } from './useFormControl';
import { usePluginBagDecorators, usePluginConfigDecorators } from './usePlugins';
Expand All @@ -21,7 +20,6 @@ import { SubmitAction } from '../typings/SubmitAction';
import { deepRemoveEmpty } from '../utils/deepRemoveEmpty';
import { excludeOverlaps } from '../utils/excludeOverlaps';
import { overrideMerge } from '../utils/overrideMerge';
import { runYupSchema } from '../utils/runYupSchema';
import { setNestedValues } from '../utils/setNestedValues';
import { useRefCallback } from '../utils/useRefCallback';
import { validatorResultToError } from '../utils/validatorResultToError';
Expand All @@ -33,7 +31,6 @@ export type InitialFormStateConfig<Values extends object> = {
};

export interface ExtendableFormConfig<Values extends object> {
schema?: BaseSchema<Partial<Values> | undefined>;
onSubmit?: SubmitAction<Values>;
validateForm?: FieldValidator<Values>;
onValidationFailed?: (errors: FieldError<Values>) => void;
Expand Down Expand Up @@ -80,7 +77,7 @@ const formMetaPaths = createPxth<FormMeta>([]);
export const useForm = <Values extends object>(initialConfig: FormConfig<Values>): FormShared<Values> => {
const config = usePluginConfigDecorators(initialConfig);

const { schema, disablePureFieldsValidation } = config;
const { disablePureFieldsValidation } = config;

const onSubmit = useRefCallback(config.onSubmit);
const validateFormFn = useRefCallback(config.validateForm);
Expand All @@ -98,7 +95,10 @@ export const useForm = <Values extends object>(initialConfig: FormConfig<Values>
} = config;

const control = useFormControl({ initialValues, initialErrors, initialTouched });
const { validateAllFields, hasValidator, validateBranch, registerValidator } = useValidationRegistry();
const { validateAllFields, hasValidator, validateBranch, registerValidator } = useValidationRegistry({
getFieldValue: control.getFieldValue,
setFieldError: control.setFieldError,
});

const initialValuesRef = useRef(initialValues);
const initialErrorsRef = useRef(initialErrors);
Expand Down Expand Up @@ -157,30 +157,20 @@ export const useForm = <Values extends object>(initialConfig: FormConfig<Values>
[getFieldValue, hasValidator, normalizeErrors, validateBranch, values],
);

const runFormValidationSchema = useCallback(
(values: Values): Promise<FieldError<Values> | undefined> => {
if (!schema) return Promise.resolve(undefined);

return runYupSchema(schema, values);
},
[schema],
);

const validateForm = useCallback(
async (values: Values): Promise<FieldError<Values>> => {
const registryErrors = await validateAllFields(values);
const validateFormFnErrors: FieldError<Values> = validatorResultToError(await validateFormFn?.(values));
const schemaErrors = await runFormValidationSchema(values);

const allErrors = deepRemoveEmpty(merge({}, registryErrors, validateFormFnErrors, schemaErrors)) ?? {};
const allErrors = deepRemoveEmpty(merge({}, registryErrors, validateFormFnErrors)) ?? {};

if (!disablePureFieldsValidation) {
return allErrors as FieldError<Values>;
} else {
return excludeOverlaps(values, initialValuesRef.current, allErrors) as FieldError<Values>;
}
},
[runFormValidationSchema, validateAllFields, validateFormFn, disablePureFieldsValidation],
[validateAllFields, validateFormFn, disablePureFieldsValidation],
);

const updateFormDirtiness = useCallback(
Expand Down
54 changes: 38 additions & 16 deletions packages/core/src/hooks/useValidationRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { createPxth, deepGet, deepSet, getPxthSegments, isInnerPxth, Pxth, sameP
import { PxthMap } from 'stocked';
import invariant from 'tiny-invariant';

import { ControlHandlers } from './useControlHandlers';
import { FieldError } from '../typings/FieldError';
import { FieldValidator } from '../typings/FieldValidator';
import { Empty, FieldValidator } from '../typings/FieldValidator';
import { FunctionArray } from '../utils/FunctionArray';
import { UnwrapPromise, validatorResultToError } from '../utils/validatorResultToError';

Expand All @@ -23,28 +24,49 @@ export type ValidationRegistryControl = {

type ValidateBranchOutput<V, T> = { attachPath: Pxth<V>; errors: FieldError<T> };

export const useValidationRegistry = (): ValidationRegistryControl => {
const registry = useRef<ValidationRegistry>(new PxthMap());
export type ValidationRegistryConfig = Pick<ControlHandlers<object>, 'getFieldValue' | 'setFieldError'>;

const registerValidator = useCallback(<V>(name: Pxth<V>, validator: FieldValidator<V>) => {
if (!registry.current.has(name)) {
registry.current.set(name, new FunctionArray());
}
export const useValidationRegistry = ({
getFieldValue,
setFieldError,
}: ValidationRegistryConfig): ValidationRegistryControl => {
const registry = useRef<ValidationRegistry>(new PxthMap());

registry.current.get(name).push(validator as FieldValidator<unknown>);
const registerValidator = useCallback(
<V>(name: Pxth<V>, validator: FieldValidator<V>) => {
if (!registry.current.has(name)) {
registry.current.set(name, new FunctionArray());
}

return () => {
const currentValidators: FunctionArray<FieldValidator<unknown>> | undefined = registry.current.get(name);
registry.current.get(name).push(validator as FieldValidator<unknown>);

invariant(currentValidators, 'Cannot unregister field validator on field, which was not registered');
const result = validator(getFieldValue(name));

currentValidators.remove(validator as FieldValidator<unknown>);
const setError = (validatorResult: FieldError<V> | string | Empty) => {
setFieldError(name, validatorResultToError(validatorResult));
};

if (currentValidators.isEmpty()) {
registry.current.remove(name);
if (result instanceof Promise) {
result.then(setError);
} else {
setError(result);
}
};
}, []);

return () => {
const currentValidators: FunctionArray<FieldValidator<unknown>> | undefined =
registry.current.get(name);

invariant(currentValidators, 'Cannot unregister field validator on field, which was not registered');

currentValidators.remove(validator as FieldValidator<unknown>);

if (currentValidators.isEmpty()) {
registry.current.remove(name);
}
};
},
[getFieldValue, setFieldError],
);

const validateField = useCallback(async <V>(name: Pxth<V>, value: V): Promise<FieldError<V> | undefined> => {
if (registry.current.has(name)) {
Expand Down
5 changes: 0 additions & 5 deletions packages/core/src/utils/isYupError.ts

This file was deleted.

23 changes: 0 additions & 23 deletions packages/core/src/utils/runYupSchema.ts

This file was deleted.

26 changes: 0 additions & 26 deletions packages/core/src/utils/yupToFormErrors.ts

This file was deleted.

13 changes: 8 additions & 5 deletions packages/core/tests/hooks/useField.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { PropsWithChildren } from 'react';
import { act, renderHook, RenderHookResult } from '@testing-library/react';
import { act, renderHook, RenderHookResult, waitFor } from '@testing-library/react';
import { createPxth, Pxth } from 'pxth';

import { FieldContext, FormConfig, FormShared, ReactiveFormProvider, useField, useForm } from '../../src';
Expand All @@ -23,6 +23,7 @@ const config = {
initialValues: {
test: 'hello',
},
// TODO: initial errors doesn't make sense because it is derived state from values
initialErrors: {
test: {
$error: 'error',
Expand Down Expand Up @@ -71,13 +72,15 @@ describe('useField', () => {
expect(result.current.meta.touched?.$touched).toBe(false);
});

it('should setError', async () => {
it.only('should setError', async () => {
const { result } = renderField<string, { test: string }>(createPxth(['test']), config);

await act(async () => {
await result.current.control.setError({ $error: 'modified error' });
act(() => {
result.current.control.setError({ $error: 'modified error' });
});

expect(result.current.meta.error?.$error).toBe('modified error');
await waitFor(() => {
expect(result.current.meta.error?.$error).toBe('modified error');
});
});
});
Loading