form.tsx 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. import {Component} from 'react';
  2. import styled from '@emotion/styled';
  3. import isEqual from 'lodash/isEqual';
  4. import Button from 'sentry/components/button';
  5. import FormContext, {
  6. FormContextData,
  7. } from 'sentry/components/deprecatedforms/formContext';
  8. import FormState from 'sentry/components/forms/state';
  9. import {t} from 'sentry/locale';
  10. type FormProps = {
  11. cancelLabel?: string;
  12. className?: string;
  13. errorMessage?: React.ReactNode;
  14. extraButton?: React.ReactNode;
  15. footerClass?: string;
  16. hideErrors?: boolean;
  17. initialData?: object;
  18. onCancel?: () => void;
  19. onSubmit?: (
  20. data: object,
  21. onSubmitSuccess: (data: object) => void,
  22. onSubmitError: (error: object) => void
  23. ) => void;
  24. onSubmitError?: (error: object) => void;
  25. onSubmitSuccess?: (data: object) => void;
  26. requireChanges?: boolean;
  27. resetOnError?: boolean;
  28. submitDisabled?: boolean;
  29. submitLabel?: string;
  30. };
  31. type FormClassState = {
  32. data: any;
  33. errors: {non_field_errors?: object[]} & object;
  34. initialData: object;
  35. state: FormState;
  36. };
  37. // Re-export for compatibility alias.
  38. export type Context = FormContextData;
  39. class Form<
  40. Props extends FormProps = FormProps,
  41. State extends FormClassState = FormClassState
  42. > extends Component<Props, State> {
  43. static defaultProps = {
  44. cancelLabel: t('Cancel'),
  45. submitLabel: t('Save Changes'),
  46. submitDisabled: false,
  47. footerClass: 'form-actions align-right',
  48. className: 'form-stacked',
  49. requireChanges: false,
  50. hideErrors: false,
  51. resetOnError: false,
  52. errorMessage: t(
  53. 'Unable to save your changes. Please ensure all fields are valid and try again.'
  54. ),
  55. };
  56. constructor(props: Props, context: Context) {
  57. super(props, context);
  58. this.state = {
  59. data: {...this.props.initialData},
  60. errors: {},
  61. initialData: {...this.props.initialData},
  62. state: FormState.READY,
  63. } as State;
  64. }
  65. getContext() {
  66. const {data, errors} = this.state;
  67. return {
  68. form: {
  69. data,
  70. errors,
  71. onFieldChange: this.onFieldChange,
  72. },
  73. };
  74. }
  75. onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
  76. e.preventDefault();
  77. if (!this.props.onSubmit) {
  78. throw new Error('onSubmit is a required prop');
  79. }
  80. this.props.onSubmit(this.state.data, this.onSubmitSuccess, this.onSubmitError);
  81. };
  82. onSubmitSuccess = (data: object) => {
  83. this.setState({
  84. state: FormState.READY,
  85. errors: {},
  86. initialData: {...this.state.data, ...(data || {})},
  87. });
  88. this.props.onSubmitSuccess && this.props.onSubmitSuccess(data);
  89. };
  90. onSubmitError = error => {
  91. this.setState({
  92. state: FormState.ERROR,
  93. errors: error.responseJSON,
  94. });
  95. if (this.props.resetOnError) {
  96. this.setState({
  97. initialData: {},
  98. });
  99. }
  100. this.props.onSubmitError && this.props.onSubmitError(error);
  101. };
  102. onFieldChange = (name: string, value: string | number) => {
  103. this.setState(state => ({
  104. data: {
  105. ...state.data,
  106. [name]: value,
  107. },
  108. }));
  109. };
  110. render() {
  111. const isSaving = this.state.state === FormState.SAVING;
  112. const {initialData, data} = this.state;
  113. const {errorMessage, hideErrors, requireChanges} = this.props;
  114. const hasChanges = requireChanges
  115. ? Object.keys(data).length && !isEqual(data, initialData)
  116. : true;
  117. const isError = this.state.state === FormState.ERROR;
  118. const nonFieldErrors = this.state.errors && this.state.errors.non_field_errors;
  119. return (
  120. <FormContext.Provider value={this.getContext()}>
  121. <StyledForm
  122. onSubmit={this.onSubmit}
  123. className={this.props.className}
  124. aria-label={this.props['aria-label']}
  125. >
  126. {isError && !hideErrors && (
  127. <div className="alert alert-error alert-block">
  128. {nonFieldErrors ? (
  129. <div>
  130. <p>
  131. {t(
  132. 'Unable to save your changes. Please correct the following errors try again.'
  133. )}
  134. </p>
  135. <ul>
  136. {nonFieldErrors.map((e, i) => (
  137. <li key={i}>{e}</li>
  138. ))}
  139. </ul>
  140. </div>
  141. ) : (
  142. errorMessage
  143. )}
  144. </div>
  145. )}
  146. {this.props.children}
  147. <div className={this.props.footerClass} style={{marginTop: 25}}>
  148. <Button
  149. priority="primary"
  150. disabled={isSaving || this.props.submitDisabled || !hasChanges}
  151. type="submit"
  152. aria-label={this.props.submitLabel ?? t('Submit')}
  153. >
  154. {this.props.submitLabel}
  155. </Button>
  156. {this.props.onCancel && (
  157. <Button
  158. type="button"
  159. disabled={isSaving}
  160. onClick={this.props.onCancel}
  161. style={{marginLeft: 5}}
  162. aria-label={this.props.cancelLabel ?? t('Cancel')}
  163. >
  164. {this.props.cancelLabel}
  165. </Button>
  166. )}
  167. {this.props.extraButton}
  168. </div>
  169. </StyledForm>
  170. </FormContext.Provider>
  171. );
  172. }
  173. }
  174. // Note: this is so we can use this as a selector for SelectField
  175. // We need to keep `Form` as a React Component because ApiForm extends it :/
  176. export const StyledForm = styled('form')``;
  177. export default Form;