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

[NCL-8162] Implement useForm async validations #314

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
64 changes: 64 additions & 0 deletions src/components/DemoPage/DemoPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,11 @@ import { MutableRefObject, useCallback, useEffect, useRef, useState } from 'reac

import { Build, GroupBuild } from 'pnc-api-types-ts';

import { productMilestoneEntityAttributes } from 'common/productMilestoneEntityAttributes';

import { useDataBuffer } from 'hooks/useDataBuffer';
import { IFieldConfigs, IFieldValues, useForm } from 'hooks/useForm';
import { useServiceContainer } from 'hooks/useServiceContainer';
import { useTitle } from 'hooks/useTitle';

import { ActionButton } from 'components/ActionButton/ActionButton';
Expand All @@ -41,8 +44,10 @@ import { ProductMilestoneReleaseLabel } from 'components/ProductMilestoneRelease
import { ScmRepositoryLink } from 'components/ScmRepositoryLink/ScmRepositoryLink';
import { ScmRepositoryUrl } from 'components/ScmRepositoryUrl/ScmRepositoryUrl';
import { SearchSelect } from 'components/SearchSelect/SearchSelect';
import { TextInputAsyncValidated } from 'components/TextInputAsyncValidated/TextInputAsyncValidated';
import { TooltipWrapper } from 'components/TooltipWrapper/TooltipWrapper';

import * as productMilestoneApi from 'services/productMilestoneApi';
import * as projectApi from 'services/projectApi';

import { maxLength, minLength } from 'utils/formValidationHelpers';
Expand All @@ -53,10 +58,15 @@ import mockBuildData from './data/mock-build-data.json';

const buildRes: Build[] = mockBuildData;

const validateMultipleFields = (fieldValues: IFieldValues): boolean => {
return !!fieldValues.inputFieldA && !!fieldValues.version;
};

const fieldConfigs = {
inputFieldA: {
isRequired: true,
validators: [
{ validator: validateMultipleFields, errorMessage: 'inputFieldA and version must be defined.', relatedFields: ['version'] },
{ validator: minLength(2), errorMessage: 'Text must be at least two characters long.' },
{
validator: maxLength(10),
Expand All @@ -67,6 +77,16 @@ const fieldConfigs = {
selectA: {
isRequired: true,
},
version: {
isRequired: true,
validators: [
{
validator: validateMultipleFields,
errorMessage: 'version and inputFieldA must be defined.',
relatedFields: ['inputFieldA'],
},
],
},
} satisfies IFieldConfigs;

const initLogData = [
Expand Down Expand Up @@ -230,6 +250,9 @@ export const DemoPage = () => {
});
};

const serviceContainerValidateProductMilestone = useServiceContainer(productMilestoneApi.validateProductMilestoneVersion, 0);
const serviceContainerValidateProductMilestone2 = useServiceContainer(productMilestoneApi.validateProductMilestoneVersion, 0);

const selectOptions = [{ value: 'Build' }, { value: 'Option' }, { value: 'Project' }, { value: 'Version' }];

const [isSelectOpen, setIsSelectOpen] = useState<boolean>(false);
Expand Down Expand Up @@ -345,6 +368,47 @@ export const DemoPage = () => {
)}
/>
</FormGroup>
<FormGroup
isRequired
label={productMilestoneEntityAttributes.version.title}
fieldId={productMilestoneEntityAttributes.version.id}
helperText={
<FormHelperText isHidden={getFieldState(productMilestoneEntityAttributes.version.id) !== 'error'} isError>
{getFieldErrors(productMilestoneEntityAttributes.version.id)}
</FormHelperText>
}
>
<TextInputAsyncValidated
isRequired
type="text"
id={productMilestoneEntityAttributes.version.id}
name={productMilestoneEntityAttributes.version.id}
autoComplete="off"
{...register<string>(productMilestoneEntityAttributes.version.id, {
...fieldConfigs.version,
validators: [
...fieldConfigs.version.validators,
{
asyncValidator: (value) =>
serviceContainerValidateProductMilestone.run({
serviceData: {
data: { productVersionId: '101', version: '2.0.' + value },
},
}),
},
{
asyncValidator: (value) =>
serviceContainerValidateProductMilestone2.run({
serviceData: {
data: { productVersionId: '101', version: '2.0.' + value },
},
}),
},
],
})}
prefixComponent={<>2.0</>}
/>
</FormGroup>
<ActionGroup>
<Button variant="primary" isDisabled={isSubmitDisabled} onClick={handleSubmit(submitForm)}>
Submit
Expand Down
12 changes: 10 additions & 2 deletions src/components/FormInput/FormInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,17 @@ interface IFormInputProps<T extends TValue> extends IRegisterData<T> {
* @param onChange - On-change callback of the input
* @param onBlur - On-blur callback of the input
* @param validated - Input state
* @param validationState - State of the input validation
* @param render - Function to render the form input component
* @returns
*/
export const FormInput = <T extends TValue>({ value, onChange, onBlur, validated, render }: IFormInputProps<T>) => {
return render({ value, onChange, onBlur, validated });
export const FormInput = <T extends TValue>({
value,
onChange,
onBlur,
validated,
validationState,
render,
}: IFormInputProps<T>) => {
return render({ value, onChange, onBlur, validated, validationState });
};
Original file line number Diff line number Diff line change
@@ -1,14 +1,4 @@
import {
ActionGroup,
Button,
Form,
FormGroup,
FormHelperText,
InputGroup,
InputGroupText,
Switch,
TextInput,
} from '@patternfly/react-core';
import { ActionGroup, Button, Form, FormGroup, FormHelperText, Switch } from '@patternfly/react-core';
import { useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';

Expand All @@ -28,6 +18,7 @@ import { FormInput } from 'components/FormInput/FormInput';
import { PageLayout } from 'components/PageLayout/PageLayout';
import { ServiceContainerCreatingUpdating } from 'components/ServiceContainers/ServiceContainerCreatingUpdating';
import { ServiceContainerLoading } from 'components/ServiceContainers/ServiceContainerLoading';
import { TextInputAsyncValidated } from 'components/TextInputAsyncValidated/TextInputAsyncValidated';
import { TooltipWrapper } from 'components/TooltipWrapper/TooltipWrapper';

import * as productMilestoneApi from 'services/productMilestoneApi';
Expand All @@ -52,6 +43,7 @@ const fieldConfigs = {
version: {
// TODO: NCL-8162 implementing async validation
isRequired: true,
validators: [],
},
startingDate: {
isRequired: true,
Expand Down Expand Up @@ -101,6 +93,8 @@ export const ProductMilestoneCreateEditPage = ({ isEditPage = false }: IProductM

const serviceContainerProductVersionPatch = useServiceContainer(productVersionApi.patchProductVersion);

const serviceContainerValidateProductMilestone = useServiceContainer(productMilestoneApi.validateProductMilestoneVersion, 0);

const { register, setFieldValues, getFieldState, getFieldErrors, handleSubmit, isSubmitDisabled } = useForm();

const isProductMilestoneCurrent = serviceContainerProductVersion.data?.currentProductMilestone?.id === productMilestoneId;
Expand Down Expand Up @@ -224,21 +218,35 @@ export const ProductMilestoneCreateEditPage = ({ isEditPage = false }: IProductM
</FormHelperText>
}
>
<InputGroup>
<InputGroupText>
<TextInputAsyncValidated
isRequired
patrikk0123 marked this conversation as resolved.
Show resolved Hide resolved
type="text"
id={productMilestoneEntityAttributes.version.id}
name={productMilestoneEntityAttributes.version.id}
isDisabled={!serviceContainerProductVersion.data}
autoComplete="off"
{...register<string>(productMilestoneEntityAttributes.version.id, {
...fieldConfigs.version,
validators: [
patrikk0123 marked this conversation as resolved.
Show resolved Hide resolved
patrikk0123 marked this conversation as resolved.
Show resolved Hide resolved
...fieldConfigs.version.validators,
{
asyncValidator: (value) =>
serviceContainerProductVersion.data?.version
? serviceContainerValidateProductMilestone.run({
serviceData: {
data: { productVersionId, version: serviceContainerProductVersion.data.version + '.' + value },
},
})
: Promise.reject(new Error('"version" property of Product Version is undefined')),
},
],
})}
prefixComponent={
<ServiceContainerLoading {...serviceContainerProductVersion} variant="icon" title="Product Version">
{serviceContainerProductVersion.data?.version}.
</ServiceContainerLoading>
</InputGroupText>
<TextInput
isRequired
type="text"
id={productMilestoneEntityAttributes.version.id}
name={productMilestoneEntityAttributes.version.id}
autoComplete="off"
{...register<string>(productMilestoneEntityAttributes.version.id, fieldConfigs.version)}
/>
</InputGroup>
}
/>
</FormGroup>
<FormGroup
isRequired
Expand Down Expand Up @@ -300,7 +308,7 @@ export const ProductMilestoneCreateEditPage = ({ isEditPage = false }: IProductM
<ActionGroup>
<Button
variant="primary"
isDisabled={isSubmitDisabled || !!serviceContainerProductVersion.error}
isDisabled={isSubmitDisabled || !!serviceContainerProductVersion.loading || !!serviceContainerProductVersion.error}
onClick={handleSubmit(isEditPage ? submitUpdate : submitCreate)}
>
{isEditPage ? 'Update' : 'Create'} Milestone
Expand Down
4 changes: 2 additions & 2 deletions src/components/SearchSelect/SearchSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';

import { FILTERING_PLACEHOLDER_DEFAULT } from 'common/constants';

import { useServiceContainer } from 'hooks/useServiceContainer';
import { isServiceError, useServiceContainer } from 'hooks/useServiceContainer';

import '../../index.css';
import styles from './SearchSelect.module.css';
Expand Down Expand Up @@ -110,7 +110,7 @@ export const SearchSelect = ({
}
})
.catch((error: Error) => {
if (error.name !== 'CanceledError') {
if (isServiceError(error)) {
setPageIndex(pageIndexDefault);
setFetchedData([]);
}
Expand Down
4 changes: 1 addition & 3 deletions src/components/StateCard/ErrorStateCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,7 @@ export const ErrorStateCard = ({ title, error, variant = 'block' }: IErrorStateC
return (
<span>
<TooltipWrapper tooltip={errorTitle}>
<Icon status="danger">
<ExclamationCircleIcon />
</Icon>
<ExclamationCircleIcon color="#c9190b" />
</TooltipWrapper>
</span>
);
Expand Down
42 changes: 42 additions & 0 deletions src/components/TextInputAsyncValidated/TextInputAsyncValidated.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { InputGroup, InputGroupText, TextInput, TextInputProps } from '@patternfly/react-core';
import { ReactNode } from 'react';

import { IRegisterData } from 'hooks/useForm';

import { LoadingSpinner } from 'components/LoadingSpinner/LoadingSpinner';
import { ErrorStateCard } from 'components/StateCard/ErrorStateCard';
import { TooltipWrapper } from 'components/TooltipWrapper/TooltipWrapper';

interface ITextInputAsyncValidatedProps extends TextInputProps {
validationState?: IRegisterData<string>['validationState'];
prefixComponent: ReactNode;
}

/**
* Text input with state of async validation.
* When async validation is being fetched, spinner is displayed.
* When async validation request failed, error icon is displayed.
*
* props: same as TextInputProps + IRegisterData, and:
* @param prefixComponent - Prefix of the text input
*/
export const TextInputAsyncValidated = (props: ITextInputAsyncValidatedProps) => (
<InputGroup>
{props.prefixComponent && <InputGroupText>{props.prefixComponent}</InputGroupText>}
<TextInput {...props} />

{props.validationState === 'validating' && (
<InputGroupText>
<TooltipWrapper tooltip="Validating input..">
<LoadingSpinner isInline />
</TooltipWrapper>
</InputGroupText>
)}

{props.validationState === 'error' && (
<InputGroupText>
<ErrorStateCard title="validation" variant="icon" />
</InputGroupText>
)}
</InputGroup>
);
Loading