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.

ComponentMeasuresApp.tsx 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 { withTheme } from '@emotion/react';
  21. import styled from '@emotion/styled';
  22. import { Spinner } from '@sonarsource/echoes-react';
  23. import {
  24. FlagMessage,
  25. LargeCenteredLayout,
  26. Note,
  27. PageContentFontWrapper,
  28. themeBorder,
  29. themeColor,
  30. } from 'design-system';
  31. import { keyBy } from 'lodash';
  32. import * as React from 'react';
  33. import { Helmet } from 'react-helmet-async';
  34. import { getMeasuresWithPeriod } from '../../../api/measures';
  35. import { getAllMetrics } from '../../../api/metrics';
  36. import { ComponentContext } from '../../../app/components/componentContext/ComponentContext';
  37. import HelpTooltip from '../../../components/controls/HelpTooltip';
  38. import Suggestions from '../../../components/embed-docs-modal/Suggestions';
  39. import { Location, Router, withRouter } from '../../../components/hoc/withRouter';
  40. import { enhanceMeasure } from '../../../components/measure/utils';
  41. import '../../../components/search-navigator.css';
  42. import AnalysisMissingInfoMessage from '../../../components/shared/AnalysisMissingInfoMessage';
  43. import { getBranchLikeQuery, isPullRequest, isSameBranchLike } from '../../../helpers/branch-like';
  44. import { translate } from '../../../helpers/l10n';
  45. import { areLeakAndOverallCCTMeasuresComputed } from '../../../helpers/measures';
  46. import { WithBranchLikesProps, useBranchesQuery } from '../../../queries/branch';
  47. import { ComponentQualifier, isPortfolioLike } from '../../../types/component';
  48. import { MeasurePageView } from '../../../types/measures';
  49. import { MetricKey } from '../../../types/metrics';
  50. import { ComponentMeasure, Dict, MeasureEnhanced, Metric, Period } from '../../../types/types';
  51. import Sidebar from '../sidebar/Sidebar';
  52. import {
  53. Query,
  54. banQualityGateMeasure,
  55. filterMeasures,
  56. getMeasuresPageMetricKeys,
  57. groupByDomains,
  58. hasBubbleChart,
  59. hasFullMeasures,
  60. hasTree,
  61. hasTreemap,
  62. parseQuery,
  63. serializeQuery,
  64. sortMeasures,
  65. } from '../utils';
  66. import MeasureContent from './MeasureContent';
  67. import MeasureOverviewContainer from './MeasureOverviewContainer';
  68. import MeasuresEmpty from './MeasuresEmpty';
  69. interface Props extends WithBranchLikesProps {
  70. component: ComponentMeasure;
  71. location: Location;
  72. router: Router;
  73. }
  74. interface State {
  75. leakPeriod?: Period;
  76. loading: boolean;
  77. measures: MeasureEnhanced[];
  78. metrics: Dict<Metric>;
  79. }
  80. class ComponentMeasuresApp extends React.PureComponent<Props, State> {
  81. mounted = false;
  82. state: State;
  83. constructor(props: Props) {
  84. super(props);
  85. this.state = {
  86. loading: true,
  87. measures: [],
  88. metrics: {},
  89. };
  90. }
  91. componentDidMount() {
  92. this.mounted = true;
  93. getAllMetrics().then(
  94. (metrics) => {
  95. const byKey = keyBy(metrics, 'key');
  96. this.setState({ metrics: byKey });
  97. },
  98. () => {},
  99. );
  100. }
  101. componentDidUpdate(prevProps: Props, prevState: State) {
  102. const prevQuery = parseQuery(prevProps.location.query);
  103. const query = parseQuery(this.props.location.query);
  104. const hasSelectedQueryChanged = prevQuery.selected !== query.selected;
  105. const hasBranchChanged = !isSameBranchLike(prevProps.branchLike, this.props.branchLike);
  106. const isBranchReady =
  107. isPortfolioLike(this.props.component.qualifier) || this.props.branchLike !== undefined;
  108. const haveMetricsChanged =
  109. Object.keys(this.state.metrics).length !== Object.keys(prevState.metrics).length;
  110. const areMetricsReady = Object.keys(this.state.metrics).length > 0;
  111. if (
  112. areMetricsReady &&
  113. isBranchReady &&
  114. (haveMetricsChanged || hasBranchChanged || hasSelectedQueryChanged)
  115. ) {
  116. this.fetchMeasures(this.state.metrics);
  117. }
  118. }
  119. componentWillUnmount() {
  120. this.mounted = false;
  121. }
  122. fetchMeasures(metrics: State['metrics']) {
  123. const { branchLike } = this.props;
  124. const query = parseQuery(this.props.location.query);
  125. const componentKey =
  126. query.selected !== undefined && query.selected !== ''
  127. ? query.selected
  128. : this.props.component.key;
  129. const filteredKeys = getMeasuresPageMetricKeys(metrics, branchLike);
  130. getMeasuresWithPeriod(componentKey, filteredKeys, getBranchLikeQuery(branchLike)).then(
  131. ({ component, period }) => {
  132. if (this.mounted) {
  133. const measures = filterMeasures(
  134. banQualityGateMeasure(component).map((measure) => enhanceMeasure(measure, metrics)),
  135. );
  136. const leakPeriod =
  137. component.qualifier === ComponentQualifier.Project ? period : undefined;
  138. this.setState({
  139. loading: false,
  140. leakPeriod,
  141. measures: measures.filter(
  142. (measure) => measure.value !== undefined || measure.leak !== undefined,
  143. ),
  144. });
  145. }
  146. },
  147. () => {
  148. if (this.mounted) {
  149. this.setState({ loading: false });
  150. }
  151. },
  152. );
  153. }
  154. getSelectedMetric = (query: Query, displayOverview: boolean) => {
  155. if (displayOverview) {
  156. return undefined;
  157. }
  158. const metric = this.state.metrics[query.metric];
  159. if (!metric) {
  160. const domainMeasures = groupByDomains(this.state.measures);
  161. const firstMeasure =
  162. domainMeasures[0] && sortMeasures(domainMeasures[0].name, domainMeasures[0].measures)[0];
  163. if (firstMeasure && typeof firstMeasure !== 'string') {
  164. return firstMeasure.metric;
  165. }
  166. }
  167. return metric;
  168. };
  169. updateQuery = (newQuery: Partial<Query>) => {
  170. const query: Query = { ...parseQuery(this.props.location.query), ...newQuery };
  171. const metric = this.getSelectedMetric(query, false);
  172. if (metric) {
  173. if (query.view === MeasurePageView.treemap && !hasTreemap(metric.key, metric.type)) {
  174. query.view = MeasurePageView.tree;
  175. } else if (query.view === MeasurePageView.tree && !hasTree(metric.key)) {
  176. query.view = MeasurePageView.list;
  177. }
  178. }
  179. this.props.router.push({
  180. pathname: this.props.location.pathname,
  181. query: {
  182. ...serializeQuery(query),
  183. ...getBranchLikeQuery(this.props.branchLike),
  184. id: this.props.component.key,
  185. },
  186. });
  187. };
  188. renderContent = (displayOverview: boolean, query: Query, metric?: Metric) => {
  189. const { branchLike, component } = this.props;
  190. const { leakPeriod } = this.state;
  191. if (displayOverview) {
  192. return (
  193. <StyledMain className="sw-rounded-1 sw-mb-4">
  194. <MeasureOverviewContainer
  195. branchLike={branchLike}
  196. domain={query.metric}
  197. leakPeriod={leakPeriod}
  198. metrics={this.state.metrics}
  199. rootComponent={component}
  200. router={this.props.router}
  201. selected={query.selected}
  202. updateQuery={this.updateQuery}
  203. />
  204. </StyledMain>
  205. );
  206. }
  207. if (!metric) {
  208. return (
  209. <StyledMain className="sw-rounded-1 sw-p-6 sw-mb-4">
  210. <MeasuresEmpty />
  211. </StyledMain>
  212. );
  213. }
  214. const hideDrilldown =
  215. isPullRequest(branchLike) &&
  216. (metric.key === MetricKey.coverage || metric.key === MetricKey.duplicated_lines_density);
  217. if (hideDrilldown) {
  218. return (
  219. <StyledMain className="sw-rounded-1 sw-p-6 sw-mb-4">
  220. <Note>{translate('component_measures.details_are_not_available')}</Note>
  221. </StyledMain>
  222. );
  223. }
  224. return (
  225. <StyledMain className="sw-rounded-1 sw-mb-4">
  226. <MeasureContent
  227. asc={query.asc}
  228. branchLike={branchLike}
  229. leakPeriod={leakPeriod}
  230. metrics={this.state.metrics}
  231. requestedMetric={metric}
  232. rootComponent={component}
  233. router={this.props.router}
  234. selected={query.selected}
  235. updateQuery={this.updateQuery}
  236. view={query.view}
  237. />
  238. </StyledMain>
  239. );
  240. };
  241. render() {
  242. const { branchLike } = this.props;
  243. const { measures } = this.state;
  244. const { canBrowseAllChildProjects, qualifier } = this.props.component;
  245. const query = parseQuery(this.props.location.query);
  246. const showFullMeasures = hasFullMeasures(branchLike);
  247. const displayOverview = hasBubbleChart(query.metric);
  248. const metric = this.getSelectedMetric(query, displayOverview);
  249. return (
  250. <LargeCenteredLayout id="component-measures" className="sw-pt-8">
  251. <Suggestions suggestions="component_measures" />
  252. <Helmet defer={false} title={translate('layout.measures')} />
  253. <PageContentFontWrapper className="sw-body-sm">
  254. <Spinner isLoading={this.state.loading} />
  255. {measures.length > 0 ? (
  256. <div className="sw-grid sw-grid-cols-12 sw-w-full">
  257. <Sidebar
  258. measures={measures}
  259. selectedMetric={metric ? metric.key : query.metric}
  260. showFullMeasures={showFullMeasures}
  261. updateQuery={this.updateQuery}
  262. />
  263. <div className="sw-col-span-9 sw-ml-12">
  264. {!canBrowseAllChildProjects && isPortfolioLike(qualifier) && (
  265. <FlagMessage className="sw-mb-4 it__portfolio_warning" variant="warning">
  266. {translate('component_measures.not_all_measures_are_shown')}
  267. <HelpTooltip
  268. className="sw-ml-2"
  269. overlay={translate('component_measures.not_all_measures_are_shown.help')}
  270. />
  271. </FlagMessage>
  272. )}
  273. {!areLeakAndOverallCCTMeasuresComputed(measures) && (
  274. <AnalysisMissingInfoMessage className="sw-mb-4" qualifier={qualifier} />
  275. )}
  276. {this.renderContent(displayOverview, query, metric)}
  277. </div>
  278. </div>
  279. ) : (
  280. <StyledMain className="sw-rounded-1 sw-p-6 sw-mb-4">
  281. <MeasuresEmpty />
  282. </StyledMain>
  283. )}
  284. </PageContentFontWrapper>
  285. </LargeCenteredLayout>
  286. );
  287. }
  288. }
  289. /*
  290. * This needs to be refactored: the issue
  291. * is that we can't use the usual withComponentContext HOC, because the type
  292. * of `component` isn't the same. It probably used to work because of the lazy loading
  293. */
  294. const WrappedApp = withRouter(ComponentMeasuresApp);
  295. function AppWithComponentContext() {
  296. const { component } = React.useContext(ComponentContext);
  297. const { data: { branchLike } = {} } = useBranchesQuery(component);
  298. return <WrappedApp branchLike={branchLike} component={component as ComponentMeasure} />;
  299. }
  300. export default AppWithComponentContext;
  301. const StyledMain = withTheme(styled.main`
  302. background-color: ${themeColor('pageBlock')};
  303. border: ${themeBorder('default', 'pageBlockBorder')};
  304. `);