form.tsx 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import * as React from 'react';
  2. import styled from '@emotion/styled';
  3. import {Observer} from 'mobx-react';
  4. import {APIRequestMethod} from 'sentry/api';
  5. import Button from 'sentry/components/button';
  6. import Panel from 'sentry/components/panels/panel';
  7. import {t} from 'sentry/locale';
  8. import space from 'sentry/styles/space';
  9. import {isRenderFunc} from 'sentry/utils/isRenderFunc';
  10. import FormContext, {
  11. FormContextData,
  12. } from 'sentry/views/settings/components/forms/formContext';
  13. import FormModel, {FormOptions} from 'sentry/views/settings/components/forms/model';
  14. import {Data, OnSubmitCallback} from 'sentry/views/settings/components/forms/type';
  15. type RenderProps = {
  16. model: FormModel;
  17. };
  18. type RenderFunc = (props: RenderProps) => React.ReactNode;
  19. type Props = {
  20. /**
  21. * The HTTP method to use.
  22. */
  23. apiMethod?: APIRequestMethod;
  24. /**
  25. * The URL to the API endpoint this form submits to.
  26. */
  27. apiEndpoint?: string;
  28. children?: React.ReactNode | RenderFunc;
  29. className?: string;
  30. cancelLabel?: string;
  31. /**
  32. * Should the submit button be disabled.
  33. */
  34. submitDisabled?: boolean;
  35. submitLabel?: string;
  36. submitPriority?: React.ComponentProps<typeof Button>['priority'];
  37. footerClass?: string;
  38. footerStyle?: React.CSSProperties;
  39. extraButton?: React.ReactNode;
  40. initialData?: Data;
  41. /**
  42. * Are changed required before the form can be submitted.
  43. */
  44. requireChanges?: boolean;
  45. /**
  46. * Should the form reset its state when there are errors after submission.
  47. */
  48. resetOnError?: boolean;
  49. hideFooter?: boolean;
  50. allowUndo?: boolean;
  51. /**
  52. * Should fields save individually as they are blurred.
  53. */
  54. saveOnBlur?: boolean;
  55. /**
  56. * A FormModel instance. If undefined a FormModel will be created for you.
  57. */
  58. model?: FormModel;
  59. /**
  60. * If set to true, preventDefault is not called
  61. */
  62. skipPreventDefault?: boolean;
  63. additionalFieldProps?: {[key: string]: any};
  64. 'data-test-id'?: string;
  65. /**
  66. * Callback fired when the form is cancelled via the cancel button.
  67. */
  68. onCancel?: (e: React.MouseEvent) => void;
  69. /**
  70. * Callback to handle form submission.
  71. *
  72. * Defining this prop will replace the normal API submission behavior
  73. * and instead only call the provided callback.
  74. *
  75. * Your callback is expected to call `onSubmitSuccess` when the action succeeds and
  76. * `onSubmitError` when the action fails.
  77. */
  78. onSubmit?: OnSubmitCallback;
  79. onPreSubmit?: () => void;
  80. /**
  81. * Ensure the form model isn't reset when the form unmounts
  82. */
  83. preventFormResetOnUnmount?: boolean;
  84. } & Pick<FormOptions, 'onSubmitSuccess' | 'onSubmitError' | 'onFieldChange'>;
  85. export default class Form extends React.Component<Props> {
  86. constructor(props: Props, context: FormContextData) {
  87. super(props, context);
  88. const {
  89. saveOnBlur,
  90. apiEndpoint,
  91. apiMethod,
  92. resetOnError,
  93. onSubmitSuccess,
  94. onSubmitError,
  95. onFieldChange,
  96. initialData,
  97. allowUndo,
  98. } = props;
  99. this.model.setInitialData(initialData);
  100. this.model.setFormOptions({
  101. resetOnError,
  102. allowUndo,
  103. onFieldChange,
  104. onSubmitSuccess,
  105. onSubmitError,
  106. saveOnBlur,
  107. apiEndpoint,
  108. apiMethod,
  109. });
  110. }
  111. componentWillUnmount() {
  112. !this.props.preventFormResetOnUnmount && this.model.reset();
  113. }
  114. model: FormModel = this.props.model || new FormModel();
  115. contextData() {
  116. return {
  117. saveOnBlur: this.props.saveOnBlur,
  118. form: this.model,
  119. };
  120. }
  121. onSubmit = e => {
  122. !this.props.skipPreventDefault && e.preventDefault();
  123. if (this.model.isSaving) {
  124. return;
  125. }
  126. this.props.onPreSubmit?.();
  127. if (this.props.onSubmit) {
  128. this.props.onSubmit(
  129. this.model.getData(),
  130. this.onSubmitSuccess,
  131. this.onSubmitError,
  132. e,
  133. this.model
  134. );
  135. } else {
  136. this.model.saveForm();
  137. }
  138. };
  139. onSubmitSuccess = data => {
  140. const {onSubmitSuccess} = this.props;
  141. this.model.submitSuccess(data);
  142. if (onSubmitSuccess) {
  143. onSubmitSuccess(data, this.model);
  144. }
  145. };
  146. onSubmitError = error => {
  147. const {onSubmitError} = this.props;
  148. this.model.submitError(error);
  149. if (onSubmitError) {
  150. onSubmitError(error, this.model);
  151. }
  152. };
  153. render() {
  154. const {
  155. className,
  156. children,
  157. footerClass,
  158. footerStyle,
  159. submitDisabled,
  160. submitLabel,
  161. submitPriority,
  162. cancelLabel,
  163. onCancel,
  164. extraButton,
  165. requireChanges,
  166. saveOnBlur,
  167. hideFooter,
  168. } = this.props;
  169. const shouldShowFooter =
  170. typeof hideFooter !== 'undefined' ? !hideFooter : !saveOnBlur;
  171. return (
  172. <FormContext.Provider value={this.contextData()}>
  173. <form
  174. onSubmit={this.onSubmit}
  175. className={className ?? 'form-stacked'}
  176. data-test-id={this.props['data-test-id']}
  177. >
  178. <div>
  179. {isRenderFunc<RenderFunc>(children)
  180. ? children({model: this.model})
  181. : children}
  182. </div>
  183. {shouldShowFooter && (
  184. <StyledFooter
  185. className={footerClass}
  186. style={footerStyle}
  187. saveOnBlur={saveOnBlur}
  188. >
  189. {extraButton}
  190. <DefaultButtons>
  191. {onCancel && (
  192. <Observer>
  193. {() => (
  194. <Button
  195. type="button"
  196. disabled={this.model.isSaving}
  197. onClick={onCancel}
  198. style={{marginLeft: 5}}
  199. >
  200. {cancelLabel ?? t('Cancel')}
  201. </Button>
  202. )}
  203. </Observer>
  204. )}
  205. <Observer>
  206. {() => (
  207. <Button
  208. data-test-id="form-submit"
  209. priority={submitPriority ?? 'primary'}
  210. disabled={
  211. this.model.isError ||
  212. this.model.isSaving ||
  213. submitDisabled ||
  214. (requireChanges ? !this.model.formChanged : false)
  215. }
  216. type="submit"
  217. >
  218. {submitLabel ?? t('Save Changes')}
  219. </Button>
  220. )}
  221. </Observer>
  222. </DefaultButtons>
  223. </StyledFooter>
  224. )}
  225. </form>
  226. </FormContext.Provider>
  227. );
  228. }
  229. }
  230. const StyledFooter = styled('div')<{saveOnBlur?: boolean}>`
  231. display: flex;
  232. justify-content: flex-end;
  233. margin-top: 25px;
  234. border-top: 1px solid ${p => p.theme.innerBorder};
  235. background: none;
  236. padding: 16px 0 0;
  237. margin-bottom: 16px;
  238. ${p =>
  239. !p.saveOnBlur &&
  240. `
  241. ${Panel} & {
  242. margin-top: 0;
  243. padding-right: 36px;
  244. }
  245. /* Better padding with form inside of a modal */
  246. [role='document'] & {
  247. padding-right: 30px;
  248. margin-left: -30px;
  249. margin-right: -30px;
  250. margin-bottom: -30px;
  251. margin-top: 16px;
  252. padding-bottom: 16px;
  253. }
  254. `};
  255. `;
  256. const DefaultButtons = styled('div')`
  257. display: grid;
  258. grid-gap: ${space(1)};
  259. grid-auto-flow: column;
  260. justify-content: flex-end;
  261. flex: 1;
  262. `;