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 3 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
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@
"np": "^5.0.2",
"prettier": "^1.18.2",
"pretty-quick": "^1.11.1",
"react": "^16.2.0 || ^16.0.0",
"react-dom": "^16.2.0 || ^16.0.0",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"rollup": "^1.16.7",
"rollup-plugin-babel": "^4.3.3",
"rollup-plugin-commonjs": "^10.0.1",
Expand All @@ -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);
31 changes: 12 additions & 19 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,7 +103,7 @@ 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> {
Expand All @@ -112,9 +113,8 @@ export default function<Props, State, CompState>(

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

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

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

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

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

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

if (!name) {
Expand All @@ -176,7 +174,6 @@ export default function<Props, State, CompState>(

public componentDidUpdate(prevProps) {
const { value, validations, required } = this.props;
const { formsy } = 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 @@ -186,14 +183,13 @@ 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)) {
formsy.validate(this);
this.context.validate(this);
}
}

// Detach it when component unmounts
public componentWillUnmount() {
const { formsy } = this.context;
formsy.detachFromForm(this);
this.context.detachFromForm(this);
}

public getErrorMessage = () => {
Expand Down Expand Up @@ -222,9 +218,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 @@ -236,7 +230,7 @@ export default function<Props, State, CompState>(
isPristine: false,
},
() => {
formsy.validate(this);
this.context.validate(this);
},
);
}
Expand All @@ -246,7 +240,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 @@ -261,19 +255,18 @@ 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;

this.setState(
{
value: pristineValue,
isPristine: true,
},
() => {
formsy.validate(this);
this.context.validate(this);
},
);
};
Expand Down
50 changes: 29 additions & 21 deletions src/index.ts → src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
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';
import Wrapper, { propTypes } from './Wrapper';

import { IData, IModel, InputComponent, IResetModel, IUpdateInputsWithError, ValidationFunction } from './interfaces';
import {
IData,
IModel,
InputComponent,
IResetModel,
IUpdateInputsWithError,
ValidationFunction,
FormsyContextInterface,
} from './interfaces';

type FormHTMLAttributesCleaned = Omit<React.FormHTMLAttributes<HTMLFormElement>, 'onChange' | 'onSubmit'>;

Expand Down Expand Up @@ -54,6 +63,8 @@ class Formsy extends React.Component<FormsyProps, FormsyState> {

public emptyArray: any[];

public contextValue: FormsyContextInterface;

public prevInputNames: any[] | null = null;

public static displayName = 'Formsy';
Expand Down Expand Up @@ -117,10 +128,6 @@ 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 = {
Expand All @@ -130,17 +137,14 @@ class Formsy extends React.Component<FormsyProps, FormsyState> {
};
this.inputs = [];
this.emptyArray = [];
}

public getChildContext = () => ({
formsy: {
this.contextValue = {
attachToForm: this.attachToForm,
detachFromForm: this.detachFromForm,
isFormDisabled: this.isFormDisabled,
isValidValue: (component, value) => this.runValidation(component, value).isValid,
validate: this.validate,
},
});
};
}

public componentDidMount = () => {
this.validateForm();
Expand Down Expand Up @@ -509,16 +513,20 @@ class Formsy extends React.Component<FormsyProps, FormsyState> {
...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,
return (
<FormsyContext.Provider value={this.contextValue}>
{React.createElement(
Copy link
Contributor

Choose a reason for hiding this comment

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

Any reason to not convert this to jsx? Mixing jsx and React.createElement seems messy

'form',
{
onReset: this.resetInternal,
onSubmit: this.submit,
...nonFormsyProps,
disabled: false,
},
// eslint-disable-next-line react/destructuring-assignment
this.props.children,
)}
</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 @@ -31,3 +31,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;
}
Loading