Skip to content

Feature/controlled errors #29

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

Merged
merged 2 commits into from
Feb 6, 2021
Merged
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
3 changes: 2 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"import/no-dynamic-require": "off",
"global-require": "off",
"quotes": ["error", "single", { "allowTemplateLiterals": true }],
"@typescript-eslint/indent": ["error", 4]
"@typescript-eslint/indent": ["error", 4],
"@typescript-eslint/no-non-null-assertion": ["off"]
}
}
23 changes: 23 additions & 0 deletions __tests__/suits/Area.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -425,4 +425,27 @@ describe('test ValidatorProvider', () => {
await tick();
expect(area.find('div').text()).toBe('yes')
});

it('should set errors in areas from props and change over time', () => {
const area = mount<ValidatorArea, ValidatorAreaProps>(
<ValidatorArea name="test" errors={['test error']}>
<input value="" />
</ValidatorArea>
);

expect(area.state().errors.length).toBe(1);
area.setProps({ errors: ['test error 2']});
expect(area.state().errors.length).toBe(2);
});

it('should set errors from props', () => {
const area = mount<ValidatorArea, ValidatorAreaProps>(
<ValidatorArea name="test">
<input value="" />
</ValidatorArea>
);

area.setProps({ errors: ['test error'] });
expect(area.state().errors.length).toBe(1);
});
})
40 changes: 40 additions & 0 deletions __tests__/suits/Provider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,44 @@ describe('test ValidatorProvider', () => {
await tick();
expect(mockFn).toHaveBeenCalled()
});

it('should set errors in areas from props and change over time', () => {
const provider = mount<ValidatorProvider, ValidatorProviderProps>(
<ValidatorProvider errors={{ test: ['test error']}}>
<ValidatorArea name="test">
<input value="" />
</ValidatorArea>
</ValidatorProvider>
);

expect(provider.find(ValidatorArea).state().errors.length).toBe(1);
provider.setProps({ errors: { test: ['test error 2'] } });
expect(provider.find(ValidatorArea).state().errors.length).toBe(2);
});

it('should set errors in areas from props', () => {
const provider = mount<ValidatorProvider, ValidatorProviderProps>(
<ValidatorProvider>
<ValidatorArea name="test">
<input value="" />
</ValidatorArea>
</ValidatorProvider>
);

provider.setProps({ errors: { test: ['test error 2'] } });
expect(provider.find(ValidatorArea).state().errors.length).toBe(1);
});

it('should ignore errors where no area is for', () => {
const provider = mount<ValidatorProvider, ValidatorProviderProps>(
<ValidatorProvider>
<ValidatorArea name="test">
<input value="" />
</ValidatorArea>
</ValidatorProvider>
);

provider.setProps({ errors: { not_existing: ['test error 2'] } });
expect(provider.find(ValidatorArea).state().errors.length).toBe(0);
});
})
14 changes: 14 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"lodash": "^4.17.20",
"react": "^16.14.0",
"react-dom": "^16.14.0",
"react-is": "^16.13.1"
Expand Down Expand Up @@ -46,6 +47,7 @@
"@types/enzyme": "^3.10.8",
"@types/enzyme-adapter-react-16": "^1.0.6",
"@types/jest": "^26.0.20",
"@types/lodash": "^4.14.168",
"@types/react": "^16.14.2",
"@types/react-is": "^16.7.2",
"@typescript-eslint/eslint-plugin": "^3.10.1",
Expand Down
46 changes: 46 additions & 0 deletions src/components/ValidatorArea.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from 'react';
import { isFragment } from 'react-is';
import { isEqual } from 'lodash';
import { RuleOptions } from '@/RuleOptions';
import { AreaScope } from '@/AreaScope';
import { ValidatorContext } from '@/ValidatorContext';
Expand All @@ -8,6 +9,7 @@ import { Validator } from '@/Validator';
export interface ValidatorAreaProps {
rules?: RuleOptions;
name?: string;
errors?: string[];
children: React.ReactNode | ((scope: AreaScope) => React.ReactNode);
validationName?: string;
}
Expand Down Expand Up @@ -63,6 +65,15 @@ export class ValidatorArea extends React.Component<ValidatorAreaProps, Validator
rules: []
}

public constructor(props: ValidatorAreaProps) {
super(props);

if (props.errors) {
this.state.errors = props.errors;
this.state.valid = false;
}
}

/**
* @inheritDoc
*/
Expand All @@ -72,6 +83,26 @@ export class ValidatorArea extends React.Component<ValidatorAreaProps, Validator
addArea(this.getName(), this);
}

public componentDidUpdate(prevProps: Readonly<ValidatorAreaProps>): void {
if (this.props.errors && this.props.errors.length) {
if (!prevProps.errors) {
this.setErrorsFromProps(this.props.errors);
} else if (prevProps.errors.length && !isEqual(prevProps.errors, this.props.errors)) {
this.setErrorsFromProps(this.props.errors);
}
}
}

/**
* Sets the errors given via props in the indicated area
*/
private setErrorsFromProps(errors: string[]): void {
this.setState((prevState: ValidatorAreaState) => ({
errors: [...prevState.errors, ...errors],
valid: false
}));
}

/**
* Validate the area, or a given element when provided
*/
Expand Down Expand Up @@ -125,6 +156,21 @@ export class ValidatorArea extends React.Component<ValidatorAreaProps, Validator
})
}

/**
* Adds errors to the currently existing errors in state
*/
public addErrors(errors: string[]): void {
this.setState((prevState: ValidatorAreaState) => ({
...prevState,
errors: [...prevState.errors, ...errors],
valid: false,

}));
}

/**
* Gets the name of the area
*/
private getName(): string {
if (this.inputRefs.length === 1 && this.inputRefs[0].getAttribute('name')) {
return this.inputRefs[0].getAttribute('name') as string;
Expand Down
51 changes: 51 additions & 0 deletions src/components/ValidatorProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as React from 'react';
import { isEqual } from 'lodash';
import { Messages } from '@/Messages';
import { RuleOptions } from '@/RuleOptions';
import { ProviderScope } from '@/ProviderScope';
Expand All @@ -7,6 +8,7 @@ import { ValidatorArea } from '@/components/ValidatorArea';

export interface ValidatorProviderProps {
rules?: RuleOptions;
errors?: Messages;
children?: React.ReactNode | ((scope: ProviderScope) => React.ReactNode);
}

Expand All @@ -23,6 +25,51 @@ export class ValidatorProvider extends React.Component<ValidatorProviderProps, V
valid: false
}

public constructor(props: ValidatorProviderProps) {
super(props);

if (props.errors) {
this.state.errors = props.errors;
}
}

public componentDidUpdate(
prevProps: Readonly<ValidatorProviderProps>
) {
if (this.props.errors && Object.keys(this.props.errors).length) {
if (!prevProps.errors || !Object.keys(prevProps.errors).length) {
this.setErrorsFromProps(this.props.errors);
} else if (Object.keys(prevProps.errors).length
&& Object.keys(this.props.errors).length
&& !isEqual(prevProps.errors, this.props.errors)
) {
this.setErrorsFromProps(this.props.errors);
}
}
}

/**
* Indicates whether an area exists with the given name
*/
private hasArea(name: string): boolean {
return !!Object.prototype.hasOwnProperty.call(this.state.areas, name);
}

/**
* Sets the errors given via props in the indicated area
*/
private setErrorsFromProps(errors: Messages): void {
Object.keys(errors).forEach((key: string) => {
if (this.hasArea(key)) {
this.state.areas[key].addErrors(errors[key]);
}
})
}

private hasErrorsForArea(name: string): boolean {
return !!Object.prototype.hasOwnProperty.call(this.state.errors, name);
}

/**
* Add a new area to the provider
*/
Expand All @@ -32,6 +79,10 @@ export class ValidatorProvider extends React.Component<ValidatorProviderProps, V
throw new Error('Validation area names should be unique');
}

if (this.hasErrorsForArea(name)) {
ref.addErrors(this.state.errors[name]);
}

return {
areas: {
...prevState.areas,
Expand Down