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

Feature/new context api #198

Merged
merged 18 commits into from
Feb 15, 2020
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
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@
"typescript": "^3.5.3"
},
"peerDependencies": {
"react": "^15.6.1 || ^16.0.0",
"react-dom": "^15.6.1 || ^16.0.0"
"react": "^16.0.0",
"react-dom": "^16.0.0"
Copy link
Member

Choose a reason for hiding this comment

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

It's been 2 years, so this seems like an acceptable change.

}
}
4 changes: 2 additions & 2 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import pkg from './package.json';

const name = 'formsy-react',
input = 'src/index.ts',
extensions = ['.js', '.ts'],
input = 'src/index.tsx',
extensions = ['.js', '.tsx', '.ts'],
babelConfig = {
...babelrc({ addExternalHelpersPlugin: false }),
exclude: 'node_modules/**',
Expand Down
18 changes: 18 additions & 0 deletions src/FormsyContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import React from 'react';
import { FormsyContextInterface } from './interfaces';

const noFormsyErrorMessage = 'No Context Provider defined';

const throwNoFormsyProvider = () => {
throw new Error(noFormsyErrorMessage);
};

const defaultValue = {
attachToForm: throwNoFormsyProvider,
detachFromForm: throwNoFormsyProvider,
isFormDisabled: true,
isValidValue: throwNoFormsyProvider,
validate: throwNoFormsyProvider,
};

export default React.createContext<FormsyContextInterface>(defaultValue);
53 changes: 27 additions & 26 deletions src/Wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import PropTypes from 'prop-types';

import utils from './utils';
import { Validations, WrappedComponentClass, RequiredValidation, Value } from './interfaces';
import FormsyContext from './FormsyContext';

/* eslint-disable react/default-props-match-prop-types */

Expand Down Expand Up @@ -102,19 +103,19 @@ function getDisplayName(component: WrappedComponentClass) {
);
}

export default function<Props, State, CompState>(
export default function<Props, State>(
WrappedComponent: React.ComponentClass<Props & State>,
): React.ComponentClass<Props & State> {
return class extends React.Component<Props & State & WrapperProps, WrapperState> {
public static contextType = FormsyContext;

public validations?: Validations;

public requiredValidations?: Validations;

public static displayName = `Formsy(${getDisplayName(WrappedComponent)})`;

public static contextTypes = {
formsy: PropTypes.object, // What about required?
};
public context: React.ContextType<typeof FormsyContext>;

public static defaultProps: any = {
innerRef: null,
Expand Down Expand Up @@ -143,7 +144,14 @@ export default function<Props, State, CompState>(

public componentDidMount() {
const { validations, required, name } = this.props;
const { formsy } = this.context;
const { attachToForm } = this.context;

const configure = () => {
this.setValidations(validations, required);

// Pass a function instead?
attachToForm(this);
};

if (!name) {
throw new Error('Form Input requires a name property when used');
Expand All @@ -152,27 +160,23 @@ export default function<Props, State, CompState>(
this.setValidations(validations, required);

// Pass a function instead?
formsy.attachToForm(this);
configure();
}

public shouldComponentUpdate(nextProps, nextState, nextContext) {
const {
props,
state,
context: { formsy: formsyContext },
} = this;
const { props, state, context } = this;
const isPropsChanged = Object.keys(props).some(k => props[k] !== nextProps[k]);

const isStateChanged = Object.keys(state).some(k => state[k] !== nextState[k]);

const isFormsyContextChanged = Object.keys(formsyContext).some(k => formsyContext[k] !== nextContext.formsy[k]);
const isFormsyContextChanged = Object.keys(context).some(k => context[k] !== nextContext[k]);

return isPropsChanged || isStateChanged || isFormsyContextChanged;
}

public componentDidUpdate(prevProps) {
const { value, validations, required } = this.props;
const { formsy } = this.context;
const { validate } = this.context;

// If the value passed has changed, set it. If value is not passed it will
// internally update, and this will never run
Expand All @@ -183,15 +187,14 @@ export default function<Props, State, CompState>(
// If validations or required is changed, run a new validation
if (!utils.isSame(validations, prevProps.validations) || !utils.isSame(required, prevProps.required)) {
this.setValidations(validations, required);
formsy.validate(this);
validate(this);
}
}

// Detach it when component unmounts
// eslint-disable-next-line react/sort-comp
public componentDidUnmount() {
const { formsy } = this.context;
formsy.detachFromForm(this);
public componentWillUnmount() {
const { detachFromForm } = this.context;
detachFromForm(this);
}

public getErrorMessage = () => {
Expand Down Expand Up @@ -220,9 +223,7 @@ export default function<Props, State, CompState>(

// By default, we validate after the value has been set.
// A user can override this and pass a second parameter of `false` to skip validation.
public setValue = (value, validate = true) => {
const { formsy } = this.context;

public setValue = (value: any, validate = true) => {
if (!validate) {
this.setState({
value,
Expand All @@ -234,7 +235,7 @@ export default function<Props, State, CompState>(
isPristine: false,
},
() => {
formsy.validate(this);
this.context.validate(this); //eslint-disable-line
Copy link
Member

Choose a reason for hiding this comment

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

Can we add the rule here? It would be nice to know what eslint is mad about.

},
);
}
Expand All @@ -244,7 +245,7 @@ export default function<Props, State, CompState>(
public hasValue = () => this.state.value !== '';

// eslint-disable-next-line react/destructuring-assignment
public isFormDisabled = () => this.context.formsy.isFormDisabled;
public isFormDisabled = () => this.context.isFormDisabled;

// eslint-disable-next-line react/destructuring-assignment
public isFormSubmitted = () => this.state.formSubmitted;
Expand All @@ -259,19 +260,19 @@ export default function<Props, State, CompState>(
public isValid = () => this.state.isValid;

// eslint-disable-next-line react/destructuring-assignment
public isValidValue = value => this.context.formsy.isValidValue.call(null, this, value);
public isValidValue = value => this.context.isValidValue(this, value);

public resetValue = () => {
const { pristineValue } = this.state;
const { formsy } = this.context;
const { validate } = this.context;

this.setState(
{
value: pristineValue,
isPristine: true,
},
() => {
formsy.validate(this);
validate(this);
},
);
};
Expand Down
66 changes: 34 additions & 32 deletions src/index.ts → src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react';
import PropTypes from 'prop-types';
import formDataToObject from 'form-data-to-object';
import FormsyContext from './FormsyContext';

import utils from './utils';
import validationRules from './validationRules';
Expand All @@ -14,6 +15,7 @@ import {
ISetInputValue,
IUpdateInputsWithError,
ValidationFunction,
FormsyContextInterface,
} from './interfaces';

type FormHTMLAttributesCleaned = Omit<React.FormHTMLAttributes<HTMLFormElement>, 'onChange' | 'onSubmit'>;
Expand Down Expand Up @@ -55,6 +57,7 @@ export interface FormsyState {
isPristine?: boolean;
isSubmitting: boolean;
isValid: boolean;
contextValue: FormsyContextInterface;
}

class Formsy extends React.Component<FormsyProps, FormsyState> {
Expand Down Expand Up @@ -125,38 +128,31 @@ class Formsy extends React.Component<FormsyProps, FormsyState> {
validationErrors: PropTypes.object, // eslint-disable-line
};

public static childContextTypes = {
formsy: PropTypes.object,
};

public constructor(props: FormsyProps) {
super(props);
this.state = {
canChange: false,
isSubmitting: false,
isValid: true,
contextValue: {
attachToForm: this.attachToForm,
detachFromForm: this.detachFromForm,
isFormDisabled: props.disabled,
isValidValue: (component, value) => this.runValidation(component, value).isValid,
validate: this.validate,
},
};
this.inputs = [];
this.emptyArray = [];
}

public getChildContext = () => ({
formsy: {
attachToForm: this.attachToForm,
detachFromForm: this.detachFromForm,
isFormDisabled: this.isFormDisabled(),
isValidValue: this.isValidValue,
validate: this.validate,
},
});

public componentDidMount = () => {
this.prevInputNames = this.inputs.map(component => component.props.name);
this.validateForm();
};

public componentDidUpdate = () => {
const { validationErrors } = this.props;
public componentDidUpdate = (prevProps: FormsyProps) => {
const { validationErrors, disabled } = this.props;

if (validationErrors && typeof validationErrors === 'object' && Object.keys(validationErrors).length > 0) {
this.setInputValidationErrors(validationErrors);
Expand All @@ -167,6 +163,17 @@ class Formsy extends React.Component<FormsyProps, FormsyState> {
this.prevInputNames = newInputNames;
this.validateForm();
}

if (disabled !== prevProps.disabled) {
// eslint-disable-next-line
this.setState(state => ({
...state,
contextValue: {
...state.contextValue,
isFormDisabled: disabled,
},
}));
}
};

public getCurrentValues = () =>
Expand Down Expand Up @@ -237,8 +244,6 @@ class Formsy extends React.Component<FormsyProps, FormsyState> {
}
};

public isValidValue = (component, value) => this.runValidation(component, value).isValid;

// eslint-disable-next-line react/destructuring-assignment
public isFormDisabled = () => this.props.disabled;

Expand Down Expand Up @@ -485,9 +490,7 @@ class Formsy extends React.Component<FormsyProps, FormsyState> {
// If there are no inputs, set state where form is ready to trigger
// change event. New inputs might be added later
if (!this.inputs.length) {
this.setState({
canChange: true,
});
onValidationComplete();
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Oh, and i also fixed a bug, where if you remove all the inputs but the last one was invalid, the form was still invalid. The callback onValidationComplete was never called.

}
};

Expand Down Expand Up @@ -519,20 +522,19 @@ class Formsy extends React.Component<FormsyProps, FormsyState> {
showError,
showRequired,
validationErrors,
children,
/* eslint-enable @typescript-eslint/no-unused-vars */
...nonFormsyProps
} = this.props;

return React.createElement(
'form',
{
onReset: this.resetInternal,
onSubmit: this.submit,
...nonFormsyProps,
disabled: false,
},
// eslint-disable-next-line react/destructuring-assignment
this.props.children,
const { contextValue } = this.state;

return (
// eslint-disable-next-line
<FormsyContext.Provider value={contextValue}>
<form onReset={this.resetInternal} onSubmit={this.submit} {...nonFormsyProps}>
{children}
</form>
</FormsyContext.Provider>
);
};
}
Expand Down
8 changes: 8 additions & 0 deletions src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,11 @@ export interface InputComponent extends React.Component<WrapperProps, WrapperSta
validations?: Validations;
requiredValidations?: Validations;
}

export interface FormsyContextInterface {
attachToForm: (component: InputComponent) => void;
detachFromForm: (component: InputComponent) => void;
isFormDisabled: boolean;
isValidValue: (component: InputComponent, value: any) => boolean;
validate: (component: InputComponent) => void;
}
23 changes: 15 additions & 8 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6011,14 +6011,14 @@ rc@^1.0.1, rc@^1.1.6, rc@^1.2.7, rc@^1.2.8:
strip-json-comments "~2.0.1"

"react-dom@^16.2.0 || ^16.0.0":
version "16.8.6"
resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-16.8.6.tgz#71d6303f631e8b0097f56165ef608f051ff6e10f"
integrity sha512-1nL7PIq9LTL3fthPqwkvr2zY7phIPjYrT0jp4HjyEQrEROnw4dG41VVwi/wfoCneoleqrNX7iAD+pXebJZwrwA==
version "16.10.0"
resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-16.10.0.tgz#319356767b5c044f3c016eef28518ef7726dce84"
integrity sha512-0QJQUFrKG04hB/1lWyUs/FOd1qNseKGRQI+JBRsADIqVAFxYObhZ2zsVQKjt+nVSCmi8KA0sL52RLwwWuXQtOw==
dependencies:
loose-envify "^1.1.0"
object-assign "^4.1.1"
prop-types "^15.6.2"
scheduler "^0.13.6"
scheduler "^0.16.0"

react-is@^16.8.1, react-is@^16.8.4, react-is@^16.8.6:
version "16.8.6"
Expand All @@ -6036,14 +6036,13 @@ react-test-renderer@^16.0.0-0:
scheduler "^0.13.6"

"react@^16.2.0 || ^16.0.0":
version "16.8.6"
resolved "https://registry.yarnpkg.com/react/-/react-16.8.6.tgz#ad6c3a9614fd3a4e9ef51117f54d888da01f2bbe"
integrity sha512-pC0uMkhLaHm11ZSJULfOBqV4tIZkx87ZLvbbQYunNixAAvjnC+snJCg0XQXn9VIsttVsbZP/H/ewzgsd5fxKXw==
version "16.10.0"
resolved "https://registry.yarnpkg.com/react/-/react-16.10.0.tgz#95c41e8fc1c706e174deef54b663b5ab94c8ee32"
integrity sha512-lc37bD3j6ZWJRso/a1rrFu6CO1qOf30ZadUDBi1c5RHA1lBSWA8x2MGABB6Oikk+RfmgC+kAT+XegL0eD1ecKg==
dependencies:
loose-envify "^1.1.0"
object-assign "^4.1.1"
prop-types "^15.6.2"
scheduler "^0.13.6"

read-pkg-up@^2.0.0:
version "2.0.0"
Expand Down Expand Up @@ -6532,6 +6531,14 @@ scheduler@^0.13.6:
loose-envify "^1.1.0"
object-assign "^4.1.1"

scheduler@^0.16.0:
version "0.16.0"
resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.16.0.tgz#cc8914b79c5c1cfa16714cb1ddc4cbd2c7513efa"
integrity sha512-Jq59uCXQzi71B562VEjuDgvsgfTfkLDvdjNhA7hamN/fKBxecXIEFF24Zu4OVrnAz9NJJ8twa9X16Zp4b0P/xQ==
dependencies:
loose-envify "^1.1.0"
object-assign "^4.1.1"

scoped-regex@^2.0.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/scoped-regex/-/scoped-regex-2.1.0.tgz#7b9be845d81fd9d21d1ec97c61a0b7cf86d2015f"
Expand Down