Skip to content

Commit

Permalink
[Form lib] Add useFormData() hook to listen to fields value changes (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
sebelga authored Sep 1, 2020
1 parent 27bdc88 commit ef7246f
Show file tree
Hide file tree
Showing 18 changed files with 482 additions and 117 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export const ComboBoxField = ({ field, euiFieldProps = {}, ...rest }: Props) =>
};

const onSearchComboChange = (value: string) => {
if (value) {
if (value !== undefined) {
field.clearErrors(VALIDATION_TYPES.ARRAY_ITEM);
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import React, { ReactNode } from 'react';
import { EuiForm } from '@elastic/eui';

import { FormProvider } from '../form_context';
import { FormDataContextProvider } from '../form_data_context';
import { FormHook } from '../types';

interface Props {
Expand All @@ -30,8 +31,14 @@ interface Props {
[key: string]: any;
}

export const Form = ({ form, FormWrapper = EuiForm, ...rest }: Props) => (
<FormProvider form={form}>
<FormWrapper {...rest} />
</FormProvider>
);
export const Form = ({ form, FormWrapper = EuiForm, ...rest }: Props) => {
const { getFormData, __getFormData$ } = form;

return (
<FormDataContextProvider getFormData={getFormData} getFormData$={__getFormData$}>
<FormProvider form={form}>
<FormWrapper {...rest} />
</FormProvider>
</FormDataContextProvider>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -75,16 +75,7 @@ describe('<FormDataProvider />', () => {
setInputValue('lastNameField', 'updated value');
});

/**
* The children will be rendered three times:
* - Twice for each input value that has changed
* - once because after updating both fields, the **form** isValid state changes (from "undefined" to "true")
* causing a new "form" object to be returned and thus a re-render.
*
* When the form object will be memoized (in a future PR), te bellow call count should only be 2 as listening
* to form data changes should not receive updates when the "isValid" state of the form changes.
*/
expect(onFormData.mock.calls.length).toBe(3);
expect(onFormData).toBeCalledTimes(2);

const [formDataUpdated] = onFormData.mock.calls[onFormData.mock.calls.length - 1] as Parameters<
OnUpdateHandler
Expand Down Expand Up @@ -130,7 +121,7 @@ describe('<FormDataProvider />', () => {
find,
} = setup() as TestBed;

expect(onFormData.mock.calls.length).toBe(0); // Not present in the DOM yet
expect(onFormData).toBeCalledTimes(0); // Not present in the DOM yet

// Make some changes to the form fields
await act(async () => {
Expand Down Expand Up @@ -188,7 +179,7 @@ describe('<FormDataProvider />', () => {
setInputValue('lastNameField', 'updated value');
});

expect(onFormData.mock.calls.length).toBe(0);
expect(onFormData).toBeCalledTimes(0);
});

test('props.pathsToWatch (Array<string>): should not re-render the children when the field that changed is not in the watch list', async () => {
Expand Down Expand Up @@ -228,14 +219,14 @@ describe('<FormDataProvider />', () => {
});

// No re-render
expect(onFormData.mock.calls.length).toBe(0);
expect(onFormData).toBeCalledTimes(0);

// Make some changes to fields in the watch list
await act(async () => {
setInputValue('nameField', 'updated value');
});

expect(onFormData.mock.calls.length).toBe(1);
expect(onFormData).toBeCalledTimes(1);

onFormData.mockReset();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,57 +17,20 @@
* under the License.
*/

import React, { useState, useEffect, useRef, useCallback } from 'react';
import React from 'react';

import { FormData } from '../types';
import { useFormContext } from '../form_context';
import { useFormData } from '../hooks';

interface Props {
children: (formData: FormData) => JSX.Element | null;
pathsToWatch?: string | string[];
}

export const FormDataProvider = React.memo(({ children, pathsToWatch }: Props) => {
const form = useFormContext();
const { subscribe } = form;
const previousRawData = useRef<FormData>(form.__getFormData$().value);
const isMounted = useRef(false);
const [formData, setFormData] = useState<FormData>(previousRawData.current);
const { 0: formData, 2: isReady } = useFormData({ watch: pathsToWatch });

const onFormData = useCallback(
({ data: { raw } }) => {
// To avoid re-rendering the children for updates on the form data
// that we are **not** interested in, we can specify one or multiple path(s)
// to watch.
if (pathsToWatch) {
const valuesToWatchArray = Array.isArray(pathsToWatch)
? (pathsToWatch as string[])
: ([pathsToWatch] as string[]);

if (valuesToWatchArray.some((value) => previousRawData.current[value] !== raw[value])) {
previousRawData.current = raw;
setFormData(raw);
}
} else {
setFormData(raw);
}
},
[pathsToWatch]
);

useEffect(() => {
const subscription = subscribe(onFormData);
return subscription.unsubscribe;
}, [subscribe, onFormData]);

useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);

if (!isMounted.current && Object.keys(formData).length === 0) {
if (!isReady) {
// No field has mounted yet, don't render anything
return null;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import React, { createContext, useContext, useMemo } from 'react';

import { FormData, FormHook } from './types';
import { Subject } from './lib';

export interface Context<T extends FormData = FormData> {
getFormData$: () => Subject<FormData>;
getFormData: FormHook<T>['getFormData'];
}

const FormDataContext = createContext<Context<any> | undefined>(undefined);

interface Props extends Context {
children: React.ReactNode;
}

export const FormDataContextProvider = ({ children, getFormData$, getFormData }: Props) => {
const value = useMemo<Context>(
() => ({
getFormData,
getFormData$,
}),
[getFormData, getFormData$]
);

return <FormDataContext.Provider value={value}>{children}</FormDataContext.Provider>;
};

export function useFormDataContext<T extends FormData = FormData>() {
return useContext<Context<T> | undefined>(FormDataContext);
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@

export { useField } from './use_field';
export { useForm } from './use_form';
export { useFormData } from './use_form_data';
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,8 @@ export const useField = <T>(

validationErrors.push({
...validationResult,
// See comment below that explains why we add "__isBlocking__".
__isBlocking__: validationResult.__isBlocking__ ?? validation.isBlocking,
validationType: validationType || VALIDATION_TYPES.FIELD,
});

Expand Down Expand Up @@ -306,6 +308,11 @@ export const useField = <T>(

validationErrors.push({
...(validationResult as ValidationError),
// We add an "__isBlocking__" property to know if this error is a blocker or no.
// Most validation errors are blockers but in some cases a validation is more a warning than an error
// like with the ComboBox items when they are added.
__isBlocking__:
(validationResult as ValidationError).__isBlocking__ ?? validation.isBlocking,
validationType: validationType || VALIDATION_TYPES.FIELD,
});

Expand Down Expand Up @@ -394,7 +401,13 @@ export const useField = <T>(
);

const _setErrors: FieldHook<T>['setErrors'] = useCallback((_errors) => {
setErrors(_errors.map((error) => ({ validationType: VALIDATION_TYPES.FIELD, ...error })));
setErrors(
_errors.map((error) => ({
validationType: VALIDATION_TYPES.FIELD,
__isBlocking__: true,
...error,
}))
);
}, []);

/**
Expand Down Expand Up @@ -463,7 +476,8 @@ export const useField = <T>(
[setValue, deserializeValue, defaultValue]
);

const isValid = errors.length === 0;
// Don't take into account non blocker validation. Some are just warning (like trying to add a wrong ComboBox item)
const isValid = errors.filter((e) => e.__isBlocking__ !== false).length === 0;

const field = useMemo<FieldHook<T>>(() => {
return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const onFormHook = (_form: FormHook<any>) => {
formHook = _form;
};

describe('use_form() hook', () => {
describe('useForm() hook', () => {
beforeEach(() => {
formHook = null;
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,12 @@ export function useForm<T extends FormData = FormData>(

if (!field.isValidated) {
setIsValid(undefined);

// When we submit the form (and set "isSubmitted" to "true"), we validate **all fields**.
// If a field is added and it is not validated it means that we have swapped fields and added new ones:
// --> we have basically have a new form in front of us.
// For that reason we make sure that the "isSubmitted" state is false.
setIsSubmitted(false);
}
},
[updateFormDataAt]
Expand Down Expand Up @@ -389,6 +395,7 @@ export function useForm<T extends FormData = FormData>(
isValid,
id,
submit: submitForm,
validate: validateAllFields,
subscribe,
setFieldValue,
setFieldErrors,
Expand Down Expand Up @@ -428,6 +435,7 @@ export function useForm<T extends FormData = FormData>(
addField,
removeField,
validateFields,
validateAllFields,
]);

useEffect(() => {
Expand Down
Loading

0 comments on commit ef7246f

Please sign in to comment.