modalManager.tsx 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. import {Component} from 'react';
  2. import isEqual from 'lodash/isEqual';
  3. import omit from 'lodash/omit';
  4. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  5. import type {ModalRenderProps} from 'sentry/actionCreators/modal';
  6. import type {Client} from 'sentry/api';
  7. import {t} from 'sentry/locale';
  8. import type {Organization} from 'sentry/types/organization';
  9. import type {Relay} from 'sentry/types/relay';
  10. import createTrustedRelaysResponseError from './createTrustedRelaysResponseError';
  11. import Form from './form';
  12. import Modal from './modal';
  13. type FormProps = React.ComponentProps<typeof Form>;
  14. type Values = FormProps['values'];
  15. type Props = ModalRenderProps & {
  16. api: Client;
  17. onSubmitSuccess: (organization: Organization) => void;
  18. orgSlug: Organization['slug'];
  19. savedRelays: Array<Relay>;
  20. };
  21. type State = {
  22. disables: FormProps['disables'];
  23. errors: FormProps['errors'];
  24. isFormValid: boolean;
  25. requiredValues: Array<keyof Values>;
  26. title: string;
  27. values: Values;
  28. };
  29. class DialogManager<P extends Props = Props, S extends State = State> extends Component<
  30. P,
  31. S
  32. > {
  33. state = this.getDefaultState();
  34. componentDidMount() {
  35. this.validateForm();
  36. }
  37. componentDidUpdate(_prevProps: Props, prevState: S) {
  38. if (!isEqual(prevState.values, this.state.values)) {
  39. this.validateForm();
  40. }
  41. if (
  42. !isEqual(prevState.errors, this.state.errors) &&
  43. Object.keys(this.state.errors).length > 0
  44. ) {
  45. this.setValidForm(false);
  46. }
  47. }
  48. getDefaultState(): Readonly<S> {
  49. return {
  50. values: {name: '', publicKey: '', description: ''},
  51. requiredValues: ['name', 'publicKey'],
  52. errors: {},
  53. disables: {},
  54. isFormValid: false,
  55. title: this.getTitle(),
  56. } as Readonly<S>;
  57. }
  58. getTitle(): string {
  59. return '';
  60. }
  61. getData(): {trustedRelays: Array<Relay>} {
  62. // Child has to implement this
  63. throw new Error('Not implemented');
  64. }
  65. getBtnSaveLabel(): string | undefined {
  66. return undefined;
  67. }
  68. setValidForm(isFormValid: boolean) {
  69. this.setState({isFormValid});
  70. }
  71. validateForm() {
  72. const {values, requiredValues, errors} = this.state;
  73. const isFormValid = requiredValues.every(
  74. requiredValue =>
  75. !!values[requiredValue].replace(/\s/g, '') && !errors[requiredValue]
  76. );
  77. this.setValidForm(isFormValid);
  78. }
  79. clearError<F extends keyof Values>(field: F) {
  80. this.setState(prevState => ({
  81. errors: omit(prevState.errors, field),
  82. }));
  83. }
  84. handleErrorResponse(error: ReturnType<typeof createTrustedRelaysResponseError>) {
  85. switch (error.type) {
  86. case 'invalid-key':
  87. case 'missing-key':
  88. this.setState(prevState => ({
  89. errors: {...prevState.errors, publicKey: error.message},
  90. }));
  91. break;
  92. case 'empty-name':
  93. case 'missing-name':
  94. this.setState(prevState => ({
  95. errors: {...prevState.errors, name: error.message},
  96. }));
  97. break;
  98. default:
  99. addErrorMessage(error.message);
  100. }
  101. }
  102. handleChange = <F extends keyof Values>(field: F, value: Values[F]) => {
  103. this.setState(prevState => ({
  104. values: {
  105. ...prevState.values,
  106. [field]: value,
  107. },
  108. errors: omit(prevState.errors, field),
  109. }));
  110. };
  111. handleSave = async () => {
  112. const {onSubmitSuccess, closeModal, orgSlug, api} = this.props;
  113. const trustedRelays = this.getData().trustedRelays.map(trustedRelay =>
  114. omit(trustedRelay, ['created', 'lastModified'])
  115. );
  116. try {
  117. const response = await api.requestPromise(`/organizations/${orgSlug}/`, {
  118. method: 'PUT',
  119. data: {trustedRelays},
  120. });
  121. onSubmitSuccess(response);
  122. closeModal();
  123. } catch (error) {
  124. this.handleErrorResponse(createTrustedRelaysResponseError(error));
  125. }
  126. };
  127. handleValidate =
  128. <F extends keyof Values>(field: F) =>
  129. () => {
  130. const isFieldValueEmpty = !this.state.values[field].replace(/\s/g, '');
  131. const fieldErrorAlreadyExist = this.state.errors[field];
  132. if (isFieldValueEmpty && fieldErrorAlreadyExist) {
  133. return;
  134. }
  135. if (isFieldValueEmpty && !fieldErrorAlreadyExist) {
  136. this.setState(prevState => ({
  137. errors: {
  138. ...prevState.errors,
  139. [field]: t('Field Required'),
  140. },
  141. }));
  142. return;
  143. }
  144. if (!isFieldValueEmpty && fieldErrorAlreadyExist) {
  145. this.clearError(field);
  146. }
  147. };
  148. handleValidateKey = () => {
  149. const {savedRelays} = this.props;
  150. const {values, errors} = this.state;
  151. const isKeyAlreadyTaken = savedRelays.find(
  152. savedRelay => savedRelay.publicKey === values.publicKey
  153. );
  154. if (isKeyAlreadyTaken && !errors.publicKey) {
  155. this.setState({
  156. errors: {
  157. ...errors,
  158. publicKey: t('Relay key already taken'),
  159. },
  160. });
  161. return;
  162. }
  163. if (errors.publicKey) {
  164. this.setState({
  165. errors: omit(errors, 'publicKey'),
  166. });
  167. }
  168. this.handleValidate('publicKey')();
  169. };
  170. getForm() {
  171. const {values, errors, disables, isFormValid} = this.state;
  172. return (
  173. <Form
  174. isFormValid={isFormValid}
  175. onSave={this.handleSave}
  176. onChange={this.handleChange}
  177. onValidate={this.handleValidate}
  178. onValidateKey={this.handleValidateKey}
  179. errors={errors}
  180. values={values}
  181. disables={disables}
  182. />
  183. );
  184. }
  185. getContent(): React.ReactElement {
  186. return this.getForm();
  187. }
  188. render() {
  189. const {title, isFormValid} = this.state;
  190. const btnSaveLabel = this.getBtnSaveLabel();
  191. const content = this.getContent();
  192. return (
  193. <Modal
  194. {...this.props}
  195. title={title}
  196. onSave={this.handleSave}
  197. btnSaveLabel={btnSaveLabel}
  198. disabled={!isFormValid}
  199. content={content}
  200. />
  201. );
  202. }
  203. }
  204. export default DialogManager;