form.tsx 7.1 KB

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