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

[SECURITY_SOLUTION][ENDPOINT] Trusted App Create Form show inline validations errors #78305

Merged
Show file tree
Hide file tree
Changes from 7 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

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import {
AppContextTestRender,
createAppRootMockRenderer,
} from '../../../../../common/mock/endpoint';
import * as reactTestingLibrary from '@testing-library/react';
import React from 'react';
import { CreateTrustedAppForm, CreateTrustedAppFormProps } from './create_trusted_app_form';

describe('When showing the Trusted App Create Form', () => {
let render: () => ReturnType<AppContextTestRender['render']>;
let onChangeCallback: jest.MockedFunction<CreateTrustedAppFormProps['onChange']>;

beforeEach(() => {
const mockedContext = createAppRootMockRenderer();

onChangeCallback = jest.fn();
render = () => mockedContext.render(<CreateTrustedAppForm onChange={onChangeCallback} />);
});

it.todo('should show Name as required');

it.todo('should default OS to Windows');

it.todo('should allow user to select between 3 OSs');

it.todo('should show Description as optional');

it.todo('should NOT initially show any inline validation errors');

it.todo('should show top-level Errors');

describe('the condition builder component', () => {
it.todo('should show an initial condition entry');

it.todo('should not allow the entry to be removed if its the only one displayed');

it.todo('should display 2 options for Field');

it.todo('should show the value field as required');

it.todo('should display the `AND` button');

it.todo('should add a new condition entry when `AND` is clicked');

it.todo('should have remove icons enabled when multiple conditions are present');
});

describe('and the user visits required fields but does not fill them out', () => {
it.todo('should show Name validation error');

it.todo('should show Condition validation error');

it.todo('should NOT display any other errors');

it.todo('should call change callback with isValid set to false and contain the new item');
});

describe('and invalid data is entered', () => {
it.todo('should validate that Name has a non empty space value');

it.todo('should validate that a condition value has a non empty space value');

it.todo(
'should validate all condition values (when multiples exist) have non empty space value'
);
});

describe('and all required data passes validation', () => {
it.todo('should call change callback with isValid set to true and contain the new item');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -40,43 +40,114 @@ const generateNewEntry = (): NewTrustedApp['entries'][0] => {
};
};

interface FieldValidationState {
/** If this fields state is invalid. Drives display of errors on the UI */
isInvalid: boolean;
errors: string[];
warnings: string[];
}
interface ValidationResult {
/** Overall indicator if form is valid */
isValid: boolean;
errors: Partial<{ [k in keyof NewTrustedApp]: string }>;

/** Individual form field validations */
result: Partial<
{
[key in keyof NewTrustedApp]: FieldValidationState;
}
>;
}

const addResultToValidation = (
validation: ValidationResult,
field: keyof NewTrustedApp,
type: 'warnings' | 'errors',
resultValue: string
) => {
if (!validation.result[field]) {
validation.result[field] = {
isInvalid: false,
errors: [],
warnings: [],
};
}
validation.result[field]![type].push(resultValue);
validation.result[field]!.isInvalid = true;
};

const validateFormValues = (values: NewTrustedApp): ValidationResult => {
const errors: ValidationResult['errors'] = {};
let isValid: ValidationResult['isValid'] = true;
const validation: ValidationResult = {
isValid,
result: {},
};

// Name field
if (!values.name.trim()) {
errors.name = 'Name is required';
isValid = false;
addResultToValidation(
validation,
'name',
'errors',
i18n.translate('xpack.securitySolution.trustedapps.create.nameRequiredMsg', {
defaultMessage: 'Name is required',
})
);
}

if (!values.os) {
errors.os = 'OS is required';
isValid = false;
addResultToValidation(
validation,
'os',
'errors',
i18n.translate('xpack.securitySolution.trustedapps.create.osRequiredMsg', {
defaultMessage: 'Operating System is required',
})
);
}

if (!values.entries.length) {
errors.entries = 'At least one Field definition is required';
isValid = false;
addResultToValidation(
validation,
'entries',
'errors',
i18n.translate('xpack.securitySolution.trustedapps.create.conditionRequiredMsg', {
defaultMessage: 'At least one Field definition is required',
})
);
} else {
values.entries.some((entry, index) => {
if (!entry.field || !entry.value.trim()) {
errors.entries = `Field entry ${index + 1} must have a value`;
isValid = false;
addResultToValidation(
validation,
'entries',
'errors',
i18n.translate(
'xpack.securitySolution.trustedapps.create.conditionFieldValueRequiredMsg',
{
defaultMessage: '[{row}] Field entry must have a value',
values: { row: index + 1 },
}
)
);
return true;
}
return false;
});
}

return {
isValid: Object.keys(errors).length === 0,
errors,
};
validation.isValid = isValid;
return validation;
};

export interface TrustedAppFormState {
isValid: boolean;
item: NewTrustedApp;
}

export type CreateTrustedAppFormProps = Pick<
EuiFormProps,
'className' | 'data-test-subj' | 'isInvalid' | 'error' | 'invalidCallout'
Expand All @@ -88,6 +159,7 @@ export type CreateTrustedAppFormProps = Pick<
export const CreateTrustedAppForm = memo<CreateTrustedAppFormProps>(
({ fullWidth, onChange, ...formProps }) => {
const dataTestSubj = formProps['data-test-subj'];

const osOptions: Array<EuiSuperSelectOption<string>> = useMemo(() => {
return TRUSTED_APPS_SUPPORTED_OS_TYPES.map((os) => {
return {
Expand All @@ -96,12 +168,26 @@ export const CreateTrustedAppForm = memo<CreateTrustedAppFormProps>(
};
});
}, []);

const [formValues, setFormValues] = useState<NewTrustedApp>({
name: '',
os: 'windows',
entries: [generateNewEntry()],
description: '',
});

const [validationResult, setValidationResult] = useState<ValidationResult>(() =>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

when are we using react's state vs redux state?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😝 answer here 👉 https://www.elastic.co/about/our-source-code#it-depends


😄 to expand on my reasoning:

For this one - the entire thing - it was developed as a "pure" component and it is not tied to the Store. I did not see the benefit of storing this in Redux while the data is being collected from the user. Another reason, but one that really would probably not have convinced me to change the approach, was that at the time I started it, the trusted apps store setup was not yet available (pending PR).

validateFormValues(formValues)
);

const [wasVisited, setWasVisited] = useState<
Partial<
{
[key in keyof NewTrustedApp]: boolean;
}
>
>({});

const getTestId = useCallback(
(suffix: string): string | undefined => {
if (dataTestSubj) {
Expand All @@ -110,6 +196,7 @@ export const CreateTrustedAppForm = memo<CreateTrustedAppFormProps>(
},
[dataTestSubj]
);

const handleAndClick = useCallback(() => {
setFormValues(
(prevState): NewTrustedApp => {
Expand All @@ -132,6 +219,7 @@ export const CreateTrustedAppForm = memo<CreateTrustedAppFormProps>(
}
);
}, [setFormValues]);

const handleDomChangeEvents = useCallback<
ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement>
>(({ target: { name, value } }) => {
Expand All @@ -144,6 +232,19 @@ export const CreateTrustedAppForm = memo<CreateTrustedAppFormProps>(
}
);
}, []);

const handleDomBlurEvents = useCallback<ChangeEventHandler<HTMLInputElement>>(
({ target: { name } }) => {
setWasVisited((prevState) => {
return {
...prevState,
[name]: true,
};
});
},
[]
);

const handleOsChange = useCallback<(v: string) => void>((newOsValue) => {
setFormValues(
(prevState): NewTrustedApp => {
Expand All @@ -170,7 +271,14 @@ export const CreateTrustedAppForm = memo<CreateTrustedAppFormProps>(
return prevState;
}
);
setWasVisited((prevState) => {
return {
...prevState,
os: true,
};
});
}, []);

const handleEntryRemove = useCallback((entry: NewTrustedApp['entries'][0]) => {
setFormValues(
(prevState): NewTrustedApp => {
Expand All @@ -181,6 +289,7 @@ export const CreateTrustedAppForm = memo<CreateTrustedAppFormProps>(
}
);
}, []);

const handleEntryChange = useCallback<LogicalConditionBuilderProps['onEntryChange']>(
(newEntry, oldEntry) => {
setFormValues(
Expand Down Expand Up @@ -212,13 +321,27 @@ export const CreateTrustedAppForm = memo<CreateTrustedAppFormProps>(
[]
);

const handleConditionBuilderOnVisited: LogicalConditionBuilderProps['onVisited'] = useCallback(() => {
setWasVisited((prevState) => {
return {
...prevState,
entries: true,
};
});
}, []);

// Anytime the form values change, re-validate
useEffect(() => {
setValidationResult(validateFormValues(formValues));
}, [formValues]);

// Anytime the form values change - validate and notify
useEffect(() => {
onChange({
isValid: validateFormValues(formValues).isValid,
isValid: validationResult.isValid,
item: formValues,
});
}, [formValues, onChange]);
}, [formValues, onChange, validationResult.isValid]);

return (
<EuiForm {...formProps} component="div">
Expand All @@ -228,12 +351,16 @@ export const CreateTrustedAppForm = memo<CreateTrustedAppFormProps>(
})}
fullWidth={fullWidth}
data-test-subj={getTestId('nameRow')}
isInvalid={wasVisited?.name && validationResult.result.name?.isInvalid}
error={validationResult.result.name?.errors}
>
<EuiFieldText
name="name"
value={formValues.name}
onChange={handleDomChangeEvents}
onBlur={handleDomBlurEvents}
fullWidth
required
data-test-subj={getTestId('nameTextField')}
/>
</EuiFormRow>
Expand All @@ -243,6 +370,8 @@ export const CreateTrustedAppForm = memo<CreateTrustedAppFormProps>(
})}
fullWidth={fullWidth}
data-test-subj={getTestId('OsRow')}
isInvalid={wasVisited?.os && validationResult.result.os?.isInvalid}
error={validationResult.result.os?.errors}
>
<EuiSuperSelect
name="os"
Expand All @@ -253,13 +382,19 @@ export const CreateTrustedAppForm = memo<CreateTrustedAppFormProps>(
data-test-subj={getTestId('osSelectField')}
/>
</EuiFormRow>
<EuiFormRow fullWidth={fullWidth} data-test-subj={getTestId('conditionsRow')}>
<EuiFormRow
fullWidth={fullWidth}
data-test-subj={getTestId('conditionsRow')}
isInvalid={wasVisited?.entries && validationResult.result.entries?.isInvalid}
error={validationResult.result.entries?.errors}
>
<LogicalConditionBuilder
entries={formValues.entries}
os={formValues.os}
onAndClicked={handleAndClick}
onEntryRemove={handleEntryRemove}
onEntryChange={handleEntryChange}
onVisited={handleConditionBuilderOnVisited}
data-test-subj={getTestId('conditionsBuilder')}
/>
</EuiFormRow>
Expand Down
Loading