-
-
Notifications
You must be signed in to change notification settings - Fork 278
feat: Support FormProvider #4
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
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
/* eslint-disable react/prop-types */ | ||
|
||
import React from 'react'; | ||
import StateForm, { FormProvider } from '../src'; | ||
import Input from './components/Input'; | ||
import LabelField from './components/LabelField'; | ||
import { ValidateMessages } from '../src/interface'; | ||
|
||
const myMessages: ValidateMessages = { | ||
required: '${name} 是必需品', | ||
}; | ||
|
||
const formStyle: React.CSSProperties = { | ||
padding: '10px 15px', | ||
flex: 'auto', | ||
}; | ||
|
||
const Form1 = () => { | ||
const [form] = StateForm.useForm(); | ||
|
||
return ( | ||
<StateForm form={form} style={{ ...formStyle, border: '1px solid #000' }} name="first"> | ||
<h4>Form 1</h4> | ||
<p>Change me!</p> | ||
<LabelField name="username" rules={[{ required: true }]}> | ||
<Input placeholder="username" /> | ||
</LabelField> | ||
<LabelField name="password" rules={[{ required: true }]}> | ||
<Input placeholder="password" /> | ||
</LabelField> | ||
|
||
<button type="submit">Submit</button> | ||
</StateForm> | ||
); | ||
}; | ||
|
||
const Form2 = () => { | ||
const [form] = StateForm.useForm(); | ||
|
||
return ( | ||
<StateForm form={form} style={{ ...formStyle, border: '1px solid #F00' }} name="second"> | ||
<h4>Form 2</h4> | ||
<p>Will follow Form 1 but not sync back</p> | ||
<LabelField name="username" rules={[{ required: true }]}> | ||
<Input placeholder="username" /> | ||
</LabelField> | ||
<LabelField name="password" rules={[{ required: true }]}> | ||
<Input placeholder="password" /> | ||
</LabelField> | ||
|
||
<button type="submit">Submit</button> | ||
</StateForm> | ||
); | ||
}; | ||
|
||
const Demo = () => { | ||
return ( | ||
<div> | ||
<h3>Form Context</h3> | ||
<p>Support global `validateMessages` config and communication between forms.</p> | ||
<FormProvider | ||
validateMessages={myMessages} | ||
onFormChange={(name, { changedFields, forms }) => { | ||
console.log('change from:', name, changedFields, forms); | ||
if (name === 'first') { | ||
forms.second.setFields(changedFields); | ||
} | ||
}} | ||
> | ||
<div style={{ display: 'flex', width: '100%' }}> | ||
<Form1 /> | ||
<Form2 /> | ||
</div> | ||
</FormProvider> | ||
</div> | ||
); | ||
}; | ||
|
||
export default Demo; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,129 @@ | ||
import * as React from 'react'; | ||
import { | ||
Store, | ||
FormInstance, | ||
FieldData, | ||
ValidateMessages, | ||
Callbacks, | ||
InternalFormInstance, | ||
} from './interface'; | ||
import useForm from './useForm'; | ||
import FieldContext, { HOOK_MARK } from './FieldContext'; | ||
import FormContext, { FormContextProps } from './FormContext'; | ||
|
||
type BaseFormProps = Omit<React.FormHTMLAttributes<HTMLFormElement>, 'onSubmit'>; | ||
|
||
export interface StateFormProps extends BaseFormProps { | ||
initialValues?: Store; | ||
form?: FormInstance; | ||
children?: (() => JSX.Element | React.ReactNode) | React.ReactNode; | ||
fields?: FieldData[]; | ||
name?: string; | ||
validateMessages?: ValidateMessages; | ||
onValuesChange?: Callbacks['onValuesChange']; | ||
onFieldsChange?: Callbacks['onFieldsChange']; | ||
onFinish?: (values: Store) => void; | ||
} | ||
|
||
const StateForm: React.FunctionComponent<StateFormProps> = ( | ||
{ | ||
name, | ||
initialValues, | ||
fields, | ||
form, | ||
children, | ||
validateMessages, | ||
onValuesChange, | ||
onFieldsChange, | ||
onFinish, | ||
...restProps | ||
}: StateFormProps, | ||
ref, | ||
) => { | ||
const formContext: FormContextProps = React.useContext(FormContext); | ||
|
||
// We customize handle event since Context will makes all the consumer re-render: | ||
// https://reactjs.org/docs/context.html#contextprovider | ||
const [formInstance] = useForm(form); | ||
const { | ||
useSubscribe, | ||
setInitialValues, | ||
setCallbacks, | ||
setValidateMessages, | ||
} = (formInstance as InternalFormInstance).getInternalHooks(HOOK_MARK); | ||
|
||
// Pass ref with form instance | ||
React.useImperativeHandle(ref, () => formInstance); | ||
|
||
// Register form into Context | ||
React.useEffect(() => { | ||
return formContext.registerForm(name, formInstance); | ||
}, [name]); | ||
|
||
// Pass props to store | ||
setValidateMessages({ | ||
...formContext.validateMessages, | ||
...validateMessages, | ||
}); | ||
setCallbacks({ | ||
onValuesChange, | ||
onFieldsChange: (changedFields: FieldData[], ...rest) => { | ||
formContext.triggerFormChange(name, changedFields); | ||
|
||
if (onFieldsChange) { | ||
onFieldsChange(changedFields, ...rest); | ||
} | ||
}, | ||
}); | ||
|
||
// Initial store value when first mount | ||
const mountRef = React.useRef(null); | ||
if (!mountRef.current) { | ||
mountRef.current = true; | ||
setInitialValues(initialValues); | ||
} | ||
|
||
// Prepare children by `children` type | ||
let childrenNode = children; | ||
const childrenRenderProps = typeof children === 'function'; | ||
if (childrenRenderProps) { | ||
const values = formInstance.getFieldsValue(); | ||
childrenNode = (children as any)(values, formInstance); | ||
} | ||
|
||
// Not use subscribe when using render props | ||
useSubscribe(!childrenRenderProps); | ||
|
||
// Listen if fields provided. We use ref to save prev data here to avoid additional render | ||
const prevFieldsRef = React.useRef<FieldData[] | undefined>(); | ||
if (prevFieldsRef.current !== fields) { | ||
formInstance.setFields(fields || []); | ||
} | ||
prevFieldsRef.current = fields; | ||
|
||
return ( | ||
<form | ||
{...restProps} | ||
onSubmit={event => { | ||
event.preventDefault(); | ||
event.stopPropagation(); | ||
|
||
formInstance | ||
.validateFields() | ||
.then(values => { | ||
if (onFinish) { | ||
onFinish(values); | ||
} | ||
}) | ||
// Do nothing about submit catch | ||
.catch(e => e); | ||
}} | ||
> | ||
<FieldContext.Provider value={formInstance as InternalFormInstance}> | ||
{childrenNode} | ||
</FieldContext.Provider> | ||
</form> | ||
); | ||
}; | ||
|
||
export default StateForm; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
import * as React from 'react'; | ||
import { ValidateMessages, FormInstance, FieldData } from './interface'; | ||
|
||
interface Forms { | ||
[name: string]: FormInstance; | ||
} | ||
|
||
interface FormChangeInfo { | ||
changedFields: FieldData[]; | ||
forms: Forms; | ||
} | ||
|
||
export interface FormProviderProps { | ||
validateMessages?: ValidateMessages; | ||
onFormChange?: (name: string, info: FormChangeInfo) => void; | ||
} | ||
|
||
export interface FormContextProps extends FormProviderProps { | ||
triggerFormChange: (name: string, changedFields: FieldData[]) => void; | ||
registerForm: (name: string, form: FormInstance) => () => void; | ||
} | ||
|
||
const FormContext = React.createContext<FormContextProps>({ | ||
triggerFormChange: () => {}, | ||
registerForm: () => () => {}, | ||
}); | ||
|
||
const FormProvider: React.FunctionComponent<FormProviderProps> = ({ | ||
validateMessages, | ||
onFormChange, | ||
children, | ||
}) => { | ||
const formContext = React.useContext(FormContext); | ||
|
||
const formsRef = React.useRef<Forms>({}); | ||
|
||
return ( | ||
<FormContext.Provider | ||
value={{ | ||
...formContext, | ||
validateMessages, | ||
|
||
// ========================================================= | ||
// = Global Form Control = | ||
// ========================================================= | ||
triggerFormChange: (name, changedFields) => { | ||
if (onFormChange) { | ||
onFormChange(name, { | ||
changedFields, | ||
forms: formsRef.current, | ||
}); | ||
} | ||
}, | ||
registerForm: (name, form) => { | ||
if (name) { | ||
formsRef.current = { | ||
...formsRef.current, | ||
[name]: form, | ||
}; | ||
} | ||
|
||
return () => { | ||
const newForms = { ...formsRef.current }; | ||
delete newForms[name]; | ||
formsRef.current = newForms; | ||
}; | ||
}, | ||
}} | ||
> | ||
{children} | ||
</FormContext.Provider> | ||
); | ||
}; | ||
|
||
export { FormProvider }; | ||
|
||
export default FormContext; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
rules 是不是也可以支持一下。
https://redd.gitbook.io/react-advanced-form/components/form-provider
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Rule 我们现在是 Field level 的,不太好支持。