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.

MeasureContent.tsx 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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 { Highlight, KeyboardHint } from 'design-system';
  21. import * as React from 'react';
  22. import { getComponentTree } from '../../../api/components';
  23. import { getMeasures } from '../../../api/measures';
  24. import SourceViewer from '../../../components/SourceViewer/SourceViewer';
  25. import A11ySkipTarget from '../../../components/a11y/A11ySkipTarget';
  26. import { Router } from '../../../components/hoc/withRouter';
  27. import FilesCounter from '../../../components/ui/FilesCounter';
  28. import { getBranchLikeQuery, isSameBranchLike } from '../../../helpers/branch-like';
  29. import { getComponentMeasureUniqueKey } from '../../../helpers/component';
  30. import { KeyboardKeys } from '../../../helpers/keycodes';
  31. import { translate } from '../../../helpers/l10n';
  32. import { getCCTMeasureValue, isDiffMetric } from '../../../helpers/measures';
  33. import { RequestData } from '../../../helpers/request';
  34. import { isDefined } from '../../../helpers/types';
  35. import { getProjectUrl } from '../../../helpers/urls';
  36. import { BranchLike } from '../../../types/branch-like';
  37. import { isApplication, isFile, isView } from '../../../types/component';
  38. import { MeasurePageView } from '../../../types/measures';
  39. import { MetricKey } from '../../../types/metrics';
  40. import {
  41. ComponentMeasure,
  42. ComponentMeasureEnhanced,
  43. ComponentMeasureIntern,
  44. Dict,
  45. Measure,
  46. Metric,
  47. Paging,
  48. Period,
  49. } from '../../../types/types';
  50. import { complementary } from '../config/complementary';
  51. import FilesView from '../drilldown/FilesView';
  52. import TreeMapView from '../drilldown/TreeMapView';
  53. import { Query, enhanceComponent } from '../utils';
  54. import MeasureContentHeader from './MeasureContentHeader';
  55. import MeasureHeader from './MeasureHeader';
  56. import MeasureViewSelect from './MeasureViewSelect';
  57. import MeasuresBreadcrumbs from './MeasuresBreadcrumbs';
  58. interface Props {
  59. branchLike?: BranchLike;
  60. leakPeriod?: Period;
  61. requestedMetric: Pick<Metric, 'key' | 'direction'>;
  62. metrics: Dict<Metric>;
  63. rootComponent: ComponentMeasure;
  64. router: Router;
  65. selected?: string;
  66. asc?: boolean;
  67. updateQuery: (query: Partial<Query>) => void;
  68. view: MeasurePageView;
  69. }
  70. interface State {
  71. baseComponent?: ComponentMeasure;
  72. components: ComponentMeasureEnhanced[];
  73. loadingMoreComponents: boolean;
  74. measure?: Measure;
  75. metric?: Metric;
  76. paging?: Paging;
  77. secondaryMeasure?: Measure;
  78. selectedComponent?: ComponentMeasureIntern;
  79. }
  80. export default class MeasureContent extends React.PureComponent<Props, State> {
  81. container?: HTMLElement | null;
  82. mounted = false;
  83. state: State = {
  84. components: [],
  85. loadingMoreComponents: false,
  86. };
  87. componentDidMount() {
  88. this.mounted = true;
  89. this.fetchComponentTree();
  90. }
  91. componentDidUpdate(prevProps: Props) {
  92. const prevComponentKey =
  93. prevProps.selected !== undefined && prevProps.selected !== ''
  94. ? prevProps.selected
  95. : prevProps.rootComponent.key;
  96. const componentKey =
  97. this.props.selected !== undefined && this.props.selected !== ''
  98. ? this.props.selected
  99. : this.props.rootComponent.key;
  100. if (
  101. prevComponentKey !== componentKey ||
  102. !isSameBranchLike(prevProps.branchLike, this.props.branchLike) ||
  103. prevProps.requestedMetric !== this.props.requestedMetric ||
  104. prevProps.view !== this.props.view
  105. ) {
  106. this.fetchComponentTree();
  107. }
  108. }
  109. componentWillUnmount() {
  110. this.mounted = false;
  111. }
  112. fetchComponentTree = () => {
  113. const { asc, branchLike, metrics, requestedMetric, rootComponent, selected, view } = this.props;
  114. // if asc is undefined we dont want to pass it inside options
  115. const { metricKeys, opts, strategy } = this.getComponentRequestParams(view, requestedMetric, {
  116. ...(asc !== undefined && { asc }),
  117. });
  118. const componentKey = selected !== undefined && selected !== '' ? selected : rootComponent.key;
  119. const baseComponentMetrics = [requestedMetric.key];
  120. if (requestedMetric.key === MetricKey.ncloc) {
  121. baseComponentMetrics.push(MetricKey.ncloc_language_distribution);
  122. }
  123. Promise.all([
  124. getComponentTree(strategy, componentKey, metricKeys, opts),
  125. getMeasures({
  126. component: componentKey,
  127. metricKeys: baseComponentMetrics.join(),
  128. ...getBranchLikeQuery(branchLike),
  129. }),
  130. ]).then(
  131. ([tree, measures]) => {
  132. if (this.mounted) {
  133. const metric = tree.metrics.find((m) => m.key === requestedMetric.key);
  134. if (metric !== undefined) {
  135. metric.direction = requestedMetric.direction;
  136. }
  137. const components = tree.components.map((component) =>
  138. enhanceComponent(component, metric, metrics),
  139. );
  140. const measure = measures.find((m) => m.metric === requestedMetric.key);
  141. const secondaryMeasure = measures.find((m) => m.metric !== requestedMetric.key);
  142. this.setState(({ selectedComponent }) => ({
  143. baseComponent: tree.baseComponent,
  144. components,
  145. measure,
  146. metric,
  147. paging: tree.paging,
  148. secondaryMeasure,
  149. selectedComponent:
  150. components.length > 0 &&
  151. components.find(
  152. (c) =>
  153. getComponentMeasureUniqueKey(c) ===
  154. getComponentMeasureUniqueKey(selectedComponent),
  155. )
  156. ? selectedComponent
  157. : undefined,
  158. }));
  159. }
  160. },
  161. () => {
  162. /* noop */
  163. },
  164. );
  165. };
  166. fetchMoreComponents = () => {
  167. const { metrics, view, asc } = this.props;
  168. const { baseComponent, metric, paging } = this.state;
  169. if (!baseComponent || !paging || !metric) {
  170. return;
  171. }
  172. // if asc is undefined we dont want to pass it inside options
  173. const { metricKeys, opts, strategy } = this.getComponentRequestParams(view, metric, {
  174. p: paging.pageIndex + 1,
  175. ...(asc !== undefined && { asc }),
  176. });
  177. this.setState({ loadingMoreComponents: true });
  178. getComponentTree(strategy, baseComponent.key, metricKeys, opts).then(
  179. (r) => {
  180. if (this.mounted && metric.key === this.props.requestedMetric.key) {
  181. this.setState((state) => ({
  182. components: [
  183. ...state.components,
  184. ...r.components.map((component) => enhanceComponent(component, metric, metrics)),
  185. ],
  186. loadingMoreComponents: false,
  187. paging: r.paging,
  188. }));
  189. }
  190. },
  191. () => {
  192. if (this.mounted) {
  193. this.setState({ loadingMoreComponents: false });
  194. }
  195. },
  196. );
  197. };
  198. getComponentRequestParams(
  199. view: MeasurePageView,
  200. metric: Pick<Metric, 'key' | 'direction'>,
  201. options: Object = {},
  202. ) {
  203. const strategy = view === MeasurePageView.list ? 'leaves' : 'children';
  204. const metricKeys = [metric.key];
  205. const opts: RequestData = {
  206. ...getBranchLikeQuery(this.props.branchLike),
  207. additionalFields: 'metrics',
  208. ps: 500,
  209. };
  210. const setMetricSort = () => {
  211. const isDiff = isDiffMetric(metric.key);
  212. opts.s = isDiff ? 'metricPeriod' : 'metric';
  213. opts.metricSortFilter = 'withMeasuresOnly';
  214. if (isDiff) {
  215. opts.metricPeriodSort = 1;
  216. }
  217. };
  218. const isDiff = isDiffMetric(metric.key);
  219. if (view === MeasurePageView.tree) {
  220. metricKeys.push(...(complementary[metric.key] || []));
  221. opts.asc = true;
  222. opts.s = 'qualifier,name';
  223. } else if (view === MeasurePageView.list) {
  224. metricKeys.push(...(complementary[metric.key] || []));
  225. opts.asc = metric.direction === 1;
  226. opts.metricSort = metric.key;
  227. setMetricSort();
  228. } else if (view === MeasurePageView.treemap) {
  229. const sizeMetric = isDiff ? MetricKey.new_lines : MetricKey.ncloc;
  230. metricKeys.push(sizeMetric);
  231. opts.asc = false;
  232. opts.metricSort = sizeMetric;
  233. setMetricSort();
  234. }
  235. return { metricKeys, opts: { ...opts, ...options }, strategy };
  236. }
  237. updateSelected = (component: string) => {
  238. this.props.updateQuery({
  239. selected: component !== this.props.rootComponent.key ? component : undefined,
  240. });
  241. };
  242. updateView = (view: MeasurePageView) => {
  243. this.props.updateQuery({ view });
  244. };
  245. onOpenComponent = (component: ComponentMeasureIntern) => {
  246. if (isView(this.props.rootComponent.qualifier)) {
  247. const comp = this.state.components.find(
  248. (c) =>
  249. c.refKey === component.key ||
  250. getComponentMeasureUniqueKey(c) === getComponentMeasureUniqueKey(component),
  251. );
  252. if (comp) {
  253. this.props.router.push(getProjectUrl(comp.refKey || comp.key, component.branch));
  254. }
  255. return;
  256. }
  257. this.setState((state) => ({ selectedComponent: state.baseComponent }));
  258. this.updateSelected(component.key);
  259. if (this.container) {
  260. this.container.focus();
  261. }
  262. };
  263. onSelectComponent = (component: ComponentMeasureIntern) => {
  264. this.setState({ selectedComponent: component });
  265. };
  266. getSelectedIndex = () => {
  267. const componentKey = isFile(this.state.baseComponent?.qualifier)
  268. ? getComponentMeasureUniqueKey(this.state.baseComponent)
  269. : getComponentMeasureUniqueKey(this.state.selectedComponent);
  270. const index = this.state.components.findIndex(
  271. (component) => getComponentMeasureUniqueKey(component) === componentKey,
  272. );
  273. return index !== -1 ? index : undefined;
  274. };
  275. getDefaultShowBestMeasures() {
  276. const { asc, view } = this.props;
  277. if ((asc !== undefined && view === MeasurePageView.list) || view === MeasurePageView.tree) {
  278. return true;
  279. }
  280. return false;
  281. }
  282. renderMeasure() {
  283. const { view } = this.props;
  284. const { metric } = this.state;
  285. if (!metric) {
  286. return null;
  287. }
  288. if (view === MeasurePageView.list || view === MeasurePageView.tree) {
  289. const selectedIdx = this.getSelectedIndex();
  290. return (
  291. <FilesView
  292. branchLike={this.props.branchLike}
  293. components={this.state.components}
  294. defaultShowBestMeasures={this.getDefaultShowBestMeasures()}
  295. fetchMore={this.fetchMoreComponents}
  296. handleOpen={this.onOpenComponent}
  297. handleSelect={this.onSelectComponent}
  298. loadingMore={this.state.loadingMoreComponents}
  299. metric={metric}
  300. metrics={this.props.metrics}
  301. paging={this.state.paging}
  302. rootComponent={this.props.rootComponent}
  303. selectedIdx={selectedIdx}
  304. selectedComponent={
  305. selectedIdx !== undefined
  306. ? (this.state.selectedComponent as ComponentMeasureEnhanced)
  307. : undefined
  308. }
  309. view={view}
  310. />
  311. );
  312. }
  313. return (
  314. <TreeMapView
  315. components={this.state.components}
  316. handleSelect={this.onOpenComponent}
  317. metric={metric}
  318. />
  319. );
  320. }
  321. render() {
  322. const { branchLike, rootComponent, view } = this.props;
  323. const { baseComponent, measure, metric, paging, secondaryMeasure } = this.state;
  324. if (!baseComponent || !metric) {
  325. return null;
  326. }
  327. const rawMeasureValue =
  328. measure && (isDiffMetric(measure.metric) ? measure.period?.value : measure.value);
  329. const measureValue = getCCTMeasureValue(metric.key, rawMeasureValue);
  330. const isFileComponent = isFile(baseComponent.qualifier);
  331. const selectedIdx = this.getSelectedIndex();
  332. return (
  333. <div ref={(container) => (this.container = container)}>
  334. <A11ySkipTarget anchor="measures_main" />
  335. <MeasureContentHeader
  336. left={
  337. <MeasuresBreadcrumbs
  338. backToFirst={view === MeasurePageView.list}
  339. branchLike={branchLike}
  340. className="sw-flex-1"
  341. component={baseComponent}
  342. handleSelect={this.onOpenComponent}
  343. rootComponent={rootComponent}
  344. />
  345. }
  346. right={
  347. <div className="sw-flex sw-items-center">
  348. {!isFileComponent && metric && (
  349. <>
  350. {!isApplication(baseComponent.qualifier) && (
  351. <>
  352. <Highlight
  353. className="sw-whitespace-nowrap"
  354. id="measures-view-selection-label"
  355. >
  356. {translate('component_measures.view_as')}
  357. </Highlight>
  358. <MeasureViewSelect
  359. className="measure-view-select sw-ml-2 sw-mr-4"
  360. handleViewChange={this.updateView}
  361. metric={metric}
  362. view={view}
  363. />
  364. </>
  365. )}
  366. {view !== MeasurePageView.treemap && (
  367. <>
  368. <KeyboardHint
  369. className="sw-mr-4 sw-ml-6"
  370. command={`${KeyboardKeys.DownArrow} ${KeyboardKeys.UpArrow}`}
  371. title={translate('component_measures.select_files')}
  372. />
  373. <KeyboardHint
  374. command={`${KeyboardKeys.LeftArrow} ${KeyboardKeys.RightArrow}`}
  375. title={translate('component_measures.navigate')}
  376. />
  377. </>
  378. )}
  379. {paging && paging.total > 0 && (
  380. <FilesCounter
  381. className="sw-min-w-24 sw-text-right"
  382. current={
  383. isDefined(selectedIdx) && view !== MeasurePageView.treemap
  384. ? selectedIdx + 1
  385. : undefined
  386. }
  387. total={paging.total}
  388. />
  389. )}
  390. </>
  391. )}
  392. </div>
  393. }
  394. />
  395. <div className="sw-p-6">
  396. <MeasureHeader
  397. branchLike={branchLike}
  398. component={baseComponent}
  399. leakPeriod={this.props.leakPeriod}
  400. measureValue={measureValue}
  401. metric={metric}
  402. secondaryMeasure={secondaryMeasure}
  403. />
  404. {isFileComponent ? (
  405. <div>
  406. <SourceViewer
  407. hideHeader
  408. branchLike={branchLike}
  409. component={baseComponent.key}
  410. metricKey={this.state.metric?.key}
  411. />
  412. </div>
  413. ) : (
  414. this.renderMeasure()
  415. )}
  416. </div>
  417. </div>
  418. );
  419. }
  420. }