You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BulkChangeModal.tsx 8.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2024 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. import { ButtonPrimary, FlagMessage, FormField, Modal, Spinner } from 'design-system';
  21. import * as React from 'react';
  22. import { Profile, bulkActivateRules, bulkDeactivateRules } from '../../../api/quality-profiles';
  23. import withLanguagesContext from '../../../app/components/languages/withLanguagesContext';
  24. import { translate, translateWithParameters } from '../../../helpers/l10n';
  25. import { formatMeasure } from '../../../helpers/measures';
  26. import { Languages } from '../../../types/languages';
  27. import { MetricType } from '../../../types/metrics';
  28. import { Dict } from '../../../types/types';
  29. import { Query, serializeQuery } from '../query';
  30. import { QualityProfileSelector } from './QualityProfileSelector';
  31. interface Props {
  32. action: string;
  33. languages: Languages;
  34. onClose: () => void;
  35. onSubmit?: () => void;
  36. profile?: Profile;
  37. query: Query;
  38. referencedProfiles: Dict<Profile>;
  39. total: number;
  40. }
  41. interface ActivationResult {
  42. failed: number;
  43. profile: string;
  44. succeeded: number;
  45. }
  46. interface State {
  47. finished: boolean;
  48. results: ActivationResult[];
  49. selectedProfiles: Profile[];
  50. submitting: boolean;
  51. }
  52. export class BulkChangeModal extends React.PureComponent<Props, State> {
  53. mounted = false;
  54. constructor(props: Props) {
  55. super(props);
  56. // if there is only one possible option for profile, select it immediately
  57. const selectedProfiles = [];
  58. const availableProfiles = this.getAvailableQualityProfiles(props);
  59. if (availableProfiles.length === 1) {
  60. selectedProfiles.push(availableProfiles[0]);
  61. }
  62. this.state = {
  63. finished: false,
  64. results: [],
  65. selectedProfiles,
  66. submitting: false,
  67. };
  68. }
  69. componentDidMount() {
  70. this.mounted = true;
  71. }
  72. componentWillUnmount() {
  73. this.mounted = false;
  74. }
  75. handleProfileSelect = (selectedProfiles: Profile[]) => {
  76. this.setState({ selectedProfiles });
  77. };
  78. getProfiles = () => {
  79. // if a profile is selected in the facet, pick it
  80. // otherwise take all profiles selected in the dropdown
  81. return this.props.profile
  82. ? [this.props.profile.key]
  83. : this.state.selectedProfiles.map((p) => p.key);
  84. };
  85. getAvailableQualityProfiles = ({ query, referencedProfiles } = this.props) => {
  86. let profiles = Object.values(referencedProfiles);
  87. if (query.languages.length > 0) {
  88. profiles = profiles.filter((profile) => query.languages.includes(profile.language));
  89. }
  90. return profiles
  91. .filter((profile) => profile.actions?.edit)
  92. .filter((profile) => !profile.isBuiltIn);
  93. };
  94. processResponse = (profile: string, response: any) => {
  95. if (this.mounted) {
  96. const result: ActivationResult = {
  97. failed: response.failed || 0,
  98. profile,
  99. succeeded: response.succeeded || 0,
  100. };
  101. this.setState((state) => ({ results: [...state.results, result] }));
  102. }
  103. };
  104. sendRequests = () => {
  105. let looper = Promise.resolve();
  106. // serialize the query, but delete the `profile`
  107. const data = serializeQuery(this.props.query);
  108. delete data.profile;
  109. const method = this.props.action === 'activate' ? bulkActivateRules : bulkDeactivateRules;
  110. const profiles = this.getProfiles();
  111. for (const profile of profiles) {
  112. looper = looper
  113. .then(() =>
  114. method({
  115. ...data,
  116. targetKey: profile,
  117. }),
  118. )
  119. .then((response) => this.processResponse(profile, response));
  120. }
  121. return looper;
  122. };
  123. handleFormSubmit = (event: React.SyntheticEvent<HTMLFormElement>) => {
  124. event.preventDefault();
  125. this.setState({ submitting: true });
  126. this.sendRequests().then(
  127. () => {
  128. if (this.mounted) {
  129. this.setState({ finished: true, submitting: false });
  130. }
  131. },
  132. () => {
  133. if (this.mounted) {
  134. this.setState({ submitting: false });
  135. }
  136. },
  137. );
  138. };
  139. handleClose = () => {
  140. if (this.props.onSubmit && this.state.finished) {
  141. this.props.onSubmit();
  142. }
  143. this.props.onClose();
  144. };
  145. renderResult = (result: ActivationResult) => {
  146. const { profile: profileKey } = result;
  147. const profile = this.props.referencedProfiles[profileKey];
  148. const { languages } = this.props;
  149. const language = languages[profile.language]
  150. ? languages[profile.language].name
  151. : profile.language;
  152. return (
  153. <FlagMessage
  154. className="sw-mb-4"
  155. key={result.profile}
  156. variant={result.failed === 0 ? 'success' : 'warning'}
  157. >
  158. {result.failed
  159. ? translateWithParameters(
  160. 'coding_rules.bulk_change.warning',
  161. profile.name,
  162. language,
  163. result.succeeded,
  164. result.failed,
  165. )
  166. : translateWithParameters(
  167. 'coding_rules.bulk_change.success',
  168. profile.name,
  169. language,
  170. result.succeeded,
  171. )}
  172. </FlagMessage>
  173. );
  174. };
  175. renderProfileSelect = () => {
  176. const profiles = this.getAvailableQualityProfiles();
  177. const { selectedProfiles } = this.state;
  178. return (
  179. <QualityProfileSelector
  180. inputId="coding-rules-bulk-change-profile-select"
  181. profiles={profiles}
  182. selectedProfiles={selectedProfiles}
  183. onChange={this.handleProfileSelect}
  184. />
  185. );
  186. };
  187. render() {
  188. const { action, profile, total } = this.props;
  189. const header =
  190. action === 'activate'
  191. ? `${translate('coding_rules.activate_in_quality_profile')} (${formatMeasure(
  192. total,
  193. MetricType.Integer,
  194. )} ${translate('coding_rules._rules')})`
  195. : `${translate('coding_rules.deactivate_in_quality_profile')} (${formatMeasure(
  196. total,
  197. MetricType.Integer,
  198. )} ${translate('coding_rules._rules')})`;
  199. const FORM_ID = `coding-rules-bulk-change-form-${action}`;
  200. const formBody = (
  201. <form id={FORM_ID} onSubmit={this.handleFormSubmit}>
  202. <div>
  203. {this.state.results.map(this.renderResult)}
  204. {!this.state.finished && !this.state.submitting && (
  205. <FormField
  206. id="coding-rules-bulk-change-profile-header"
  207. htmlFor="coding-rules-bulk-change-profile-select"
  208. label={
  209. action === 'activate'
  210. ? translate('coding_rules.activate_in')
  211. : translate('coding_rules.deactivate_in')
  212. }
  213. >
  214. {profile ? (
  215. <span>
  216. {profile.name}
  217. {' — '}
  218. {translate('are_you_sure')}
  219. </span>
  220. ) : (
  221. this.renderProfileSelect()
  222. )}
  223. </FormField>
  224. )}
  225. </div>
  226. </form>
  227. );
  228. return (
  229. <Modal
  230. headerTitle={header}
  231. isScrollable
  232. onClose={this.handleClose}
  233. body={<Spinner loading={this.state.submitting}>{formBody}</Spinner>}
  234. primaryButton={
  235. !this.state.finished && (
  236. <ButtonPrimary
  237. autoFocus
  238. type="submit"
  239. disabled={
  240. this.state.submitting ||
  241. (this.state.selectedProfiles.length === 0 && profile === undefined)
  242. }
  243. form={FORM_ID}
  244. >
  245. {translate('apply')}
  246. </ButtonPrimary>
  247. )
  248. }
  249. secondaryButtonLabel={this.state.finished ? translate('close') : translate('cancel')}
  250. />
  251. );
  252. }
  253. }
  254. export default withLanguagesContext(BulkChangeModal);