-
Notifications
You must be signed in to change notification settings - Fork 351
refactor(form): migrate Form from Flow to TypeScript #4789
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
Open
bonchevskyi
wants to merge
1
commit into
box:master
Choose a base branch
from
bonchevskyi:refactor/flow-to-ts-form
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
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
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,156 @@ | ||
| import * as React from 'react'; | ||
| // @ts-ignore no types for form-serialize | ||
| import serialize from 'form-serialize'; | ||
|
|
||
| import { FormContext } from './FormContext'; | ||
|
|
||
| export type FormSerializedData = Record<string, unknown>; | ||
|
|
||
| export type FormInputValidityState = ValidityState & { | ||
| customErrorCode?: string; | ||
| }; | ||
|
|
||
| export interface FormFieldValidityState { | ||
| /** Server-side error code */ | ||
| code?: string; | ||
| /** Server-side error message */ | ||
| message?: string; | ||
| /** HTML constraint-validation state from an invalid named input */ | ||
| validityState?: FormInputValidityState; | ||
| } | ||
|
|
||
| export type FormValidityStateMap = Record<string, FormFieldValidityState | null | undefined>; | ||
|
|
||
| export interface FormProps { | ||
| /** Form fields and other child content */ | ||
| children?: React.ReactNode; | ||
| /** An object mapping input names to error messages */ | ||
| formValidityState?: FormValidityStateMap; | ||
| /** Called when an input in the form changes */ | ||
| onChange?: (formData: FormSerializedData) => void; | ||
| /** Called when an invalid submit is made */ | ||
| onInvalidSubmit?: (formValidityState: FormValidityStateMap) => void; | ||
| /** Called when a valid submit is made */ | ||
| onValidSubmit: (formData: FormSerializedData) => void; | ||
| } | ||
|
|
||
| interface FormState { | ||
| registeredInputs: Record<string, (validityState: unknown) => void>; | ||
| } | ||
|
|
||
| function getFormValidityState(form: HTMLFormElement): FormValidityStateMap { | ||
| // Turn the form.elements HTMLCollection into Array before reducing | ||
| return [].slice.call(form.elements).reduce((validityObj: FormValidityStateMap, inputEl: HTMLInputElement) => { | ||
| // Only serialize inputs that have a name defined | ||
| if (inputEl.name && !inputEl.validity.valid) { | ||
| const validityState = inputEl.validity as FormInputValidityState; | ||
|
|
||
| if (inputEl.validity.customError) { | ||
| // If the input is displaying a custom error, | ||
| // we expose the errorCode stored in the validationMessage | ||
| validityState.customErrorCode = inputEl.validationMessage; | ||
| } | ||
|
|
||
| validityObj[inputEl.name] = { | ||
| validityState, | ||
| }; | ||
| return validityObj; | ||
| } | ||
| return validityObj; | ||
| }, {}); | ||
| } | ||
|
|
||
| class Form extends React.Component<FormProps, FormState> { | ||
| constructor(props: FormProps) { | ||
| super(props); | ||
|
|
||
| this.state = { | ||
| registeredInputs: {}, | ||
| }; | ||
| } | ||
|
|
||
| componentDidUpdate({ formValidityState: prevFormValidityState }: FormProps) { | ||
| const { formValidityState } = this.props; | ||
| const { registeredInputs } = this.state; | ||
|
|
||
| if (formValidityState !== prevFormValidityState) { | ||
| Object.keys(formValidityState).forEach(key => { | ||
| if (registeredInputs[key]) { | ||
| registeredInputs[key](formValidityState[key]); | ||
| } | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| onChange = ({ currentTarget }: React.FormEvent<HTMLFormElement>) => { | ||
| if (this.props.onChange) { | ||
| const formData = serialize(currentTarget, { | ||
| hash: true, | ||
| empty: true, | ||
| }); | ||
| this.props.onChange(formData); | ||
| } | ||
| }; | ||
|
|
||
| onSubmit = (event: React.FormEvent<HTMLFormElement>) => { | ||
| const form = event.target as HTMLFormElement; | ||
| event.preventDefault(); | ||
| const isValid = form.checkValidity(); | ||
| const { onInvalidSubmit, onValidSubmit } = this.props; | ||
| const { registeredInputs } = this.state; | ||
|
|
||
| if (isValid) { | ||
| const formData = serialize(form, { hash: true, empty: true }); | ||
| onValidSubmit(formData); | ||
| } else { | ||
| const formValidityState = getFormValidityState(form); | ||
|
|
||
| // Push form validity state to inputs so errors are shown on submit | ||
| Object.keys(formValidityState).forEach( | ||
| key => registeredInputs[key] && registeredInputs[key](formValidityState[key].validityState), | ||
| ); | ||
|
|
||
| if (onInvalidSubmit) { | ||
| onInvalidSubmit(formValidityState); | ||
| } | ||
| } | ||
| }; | ||
|
|
||
| registerInput = (name: string, setValidityStateHandler: (validityState: unknown) => void) => { | ||
| const { registeredInputs } = this.state; | ||
|
|
||
| if (registeredInputs[name]) { | ||
| throw new Error(`Input '${name}' is already registered.`); | ||
| } | ||
|
|
||
| const nextState = this.state; | ||
| nextState.registeredInputs[name] = setValidityStateHandler; | ||
| this.setState(nextState); | ||
| }; | ||
|
|
||
| unregisterInput = (name: string) => { | ||
| const nextState = this.state; | ||
| delete nextState.registeredInputs[name]; | ||
| this.setState(nextState); | ||
| }; | ||
|
|
||
| render() { | ||
| const { children } = this.props; | ||
| return ( | ||
| <FormContext.Provider | ||
| value={{ | ||
| form: { | ||
| registerInput: this.registerInput, | ||
| unregisterInput: this.unregisterInput, | ||
| }, | ||
| }} | ||
| > | ||
| <form noValidate onChange={this.onChange} onSubmit={this.onSubmit}> | ||
| {children} | ||
| </form> | ||
| </FormContext.Provider> | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| export default Form; | ||
This file was deleted.
Oops, something went wrong.
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,6 @@ | ||
| // @flow | ||
| import * as React from 'react'; | ||
|
|
||
| export const FormContext = React.createContext<any>(null); | ||
|
|
||
| FormContext.displayName = 'FormContext'; |
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,14 @@ | ||
| import * as React from 'react'; | ||
|
|
||
| export interface FormContextValue { | ||
| form?: { | ||
| /** Registers a named input so the form can push validity updates */ | ||
| registerInput: (name: string, setValidityStateHandler: (validityState: unknown) => void) => void; | ||
| /** Unregisters a previously registered named input */ | ||
| unregisterInput: (name: string) => void; | ||
| }; | ||
| } | ||
|
|
||
| export const FormContext = React.createContext<FormContextValue | null>(null); | ||
|
|
||
| FormContext.displayName = 'FormContext'; |
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,39 @@ | ||
| import * as React from 'react'; | ||
|
|
||
| import { FormContext } from './FormContext'; | ||
| import type { FormContextValue } from './FormContext'; | ||
|
|
||
| export interface FormInputProps { | ||
| /** Input (or other field) registered with the parent form */ | ||
| children: React.ReactNode; | ||
| /** Input name */ | ||
| name: string; | ||
| /** Called when Form pushes down a new validityState, useful for displaying server validation errors */ | ||
| onValidityStateUpdate: (validityState: unknown) => void; | ||
| } | ||
|
|
||
| class FormInput extends React.Component<FormInputProps> { | ||
| static contextType = FormContext; | ||
|
|
||
| componentDidMount() { | ||
| const { name, onValidityStateUpdate } = this.props; | ||
| const formContext = this.context as FormContextValue | null; | ||
|
|
||
| if (formContext?.form) { | ||
| formContext.form.registerInput(name, onValidityStateUpdate); | ||
| } | ||
| } | ||
|
|
||
| componentWillUnmount() { | ||
| const formContext = this.context as FormContextValue | null; | ||
| if (formContext?.form) { | ||
| formContext.form.unregisterInput(this.props.name); | ||
| } | ||
| } | ||
|
|
||
| render() { | ||
| return <div>{this.props.children}</div>; | ||
| } | ||
| } | ||
|
|
||
| export default FormInput; |
Oops, something went wrong.
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.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Handle an omitted
formValidityState.FormProps.formValidityStateis optional. If a caller changes it from a map toundefined, Line 77 callsObject.keys(undefined)and throws duringcomponentDidUpdate. Guard the enumeration or normalize the value before use.Proposed fix
📝 Committable suggestion
🤖 Prompt for AI Agents