123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456 |
- /*
- * SonarQube
- * Copyright (C) 2009-2024 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
- import { Highlight, KeyboardHint } from 'design-system';
- import * as React from 'react';
- import { getComponentTree } from '../../../api/components';
- import { getMeasures } from '../../../api/measures';
- import SourceViewer from '../../../components/SourceViewer/SourceViewer';
- import A11ySkipTarget from '../../../components/a11y/A11ySkipTarget';
- import { Router } from '../../../components/hoc/withRouter';
- import FilesCounter from '../../../components/ui/FilesCounter';
- import { getBranchLikeQuery, isSameBranchLike } from '../../../helpers/branch-like';
- import { getComponentMeasureUniqueKey } from '../../../helpers/component';
- import { KeyboardKeys } from '../../../helpers/keycodes';
- import { translate } from '../../../helpers/l10n';
- import { getCCTMeasureValue, isDiffMetric } from '../../../helpers/measures';
- import { RequestData } from '../../../helpers/request';
- import { isDefined } from '../../../helpers/types';
- import { getProjectUrl } from '../../../helpers/urls';
- import { BranchLike } from '../../../types/branch-like';
- import { isApplication, isFile, isView } from '../../../types/component';
- import { MeasurePageView } from '../../../types/measures';
- import { MetricKey } from '../../../types/metrics';
- import {
- ComponentMeasure,
- ComponentMeasureEnhanced,
- ComponentMeasureIntern,
- Dict,
- Measure,
- Metric,
- Paging,
- Period,
- } from '../../../types/types';
- import { complementary } from '../config/complementary';
- import FilesView from '../drilldown/FilesView';
- import TreeMapView from '../drilldown/TreeMapView';
- import { Query, enhanceComponent } from '../utils';
- import MeasureContentHeader from './MeasureContentHeader';
- import MeasureHeader from './MeasureHeader';
- import MeasureViewSelect from './MeasureViewSelect';
- import MeasuresBreadcrumbs from './MeasuresBreadcrumbs';
-
- interface Props {
- branchLike?: BranchLike;
- leakPeriod?: Period;
- requestedMetric: Pick<Metric, 'key' | 'direction'>;
- metrics: Dict<Metric>;
- rootComponent: ComponentMeasure;
- router: Router;
- selected?: string;
- asc?: boolean;
- updateQuery: (query: Partial<Query>) => void;
- view: MeasurePageView;
- }
-
- interface State {
- baseComponent?: ComponentMeasure;
- components: ComponentMeasureEnhanced[];
- loadingMoreComponents: boolean;
- measure?: Measure;
- metric?: Metric;
- paging?: Paging;
- secondaryMeasure?: Measure;
- selectedComponent?: ComponentMeasureIntern;
- }
-
- export default class MeasureContent extends React.PureComponent<Props, State> {
- container?: HTMLElement | null;
- mounted = false;
- state: State = {
- components: [],
- loadingMoreComponents: false,
- };
-
- componentDidMount() {
- this.mounted = true;
- this.fetchComponentTree();
- }
-
- componentDidUpdate(prevProps: Props) {
- const prevComponentKey =
- prevProps.selected !== undefined && prevProps.selected !== ''
- ? prevProps.selected
- : prevProps.rootComponent.key;
- const componentKey =
- this.props.selected !== undefined && this.props.selected !== ''
- ? this.props.selected
- : this.props.rootComponent.key;
- if (
- prevComponentKey !== componentKey ||
- !isSameBranchLike(prevProps.branchLike, this.props.branchLike) ||
- prevProps.requestedMetric !== this.props.requestedMetric ||
- prevProps.view !== this.props.view
- ) {
- this.fetchComponentTree();
- }
- }
-
- componentWillUnmount() {
- this.mounted = false;
- }
-
- fetchComponentTree = () => {
- const { asc, branchLike, metrics, requestedMetric, rootComponent, selected, view } = this.props;
- // if asc is undefined we dont want to pass it inside options
- const { metricKeys, opts, strategy } = this.getComponentRequestParams(view, requestedMetric, {
- ...(asc !== undefined && { asc }),
- });
- const componentKey = selected !== undefined && selected !== '' ? selected : rootComponent.key;
- const baseComponentMetrics = [requestedMetric.key];
- if (requestedMetric.key === MetricKey.ncloc) {
- baseComponentMetrics.push(MetricKey.ncloc_language_distribution);
- }
- Promise.all([
- getComponentTree(strategy, componentKey, metricKeys, opts),
- getMeasures({
- component: componentKey,
- metricKeys: baseComponentMetrics.join(),
- ...getBranchLikeQuery(branchLike),
- }),
- ]).then(
- ([tree, measures]) => {
- if (this.mounted) {
- const metric = tree.metrics.find((m) => m.key === requestedMetric.key);
- if (metric !== undefined) {
- metric.direction = requestedMetric.direction;
- }
-
- const components = tree.components.map((component) =>
- enhanceComponent(component, metric, metrics),
- );
-
- const measure = measures.find((m) => m.metric === requestedMetric.key);
- const secondaryMeasure = measures.find((m) => m.metric !== requestedMetric.key);
-
- this.setState(({ selectedComponent }) => ({
- baseComponent: tree.baseComponent,
- components,
- measure,
- metric,
- paging: tree.paging,
- secondaryMeasure,
- selectedComponent:
- components.length > 0 &&
- components.find(
- (c) =>
- getComponentMeasureUniqueKey(c) ===
- getComponentMeasureUniqueKey(selectedComponent),
- )
- ? selectedComponent
- : undefined,
- }));
- }
- },
- () => {
- /* noop */
- },
- );
- };
-
- fetchMoreComponents = () => {
- const { metrics, view, asc } = this.props;
- const { baseComponent, metric, paging } = this.state;
- if (!baseComponent || !paging || !metric) {
- return;
- }
- // if asc is undefined we dont want to pass it inside options
- const { metricKeys, opts, strategy } = this.getComponentRequestParams(view, metric, {
- p: paging.pageIndex + 1,
- ...(asc !== undefined && { asc }),
- });
- this.setState({ loadingMoreComponents: true });
- getComponentTree(strategy, baseComponent.key, metricKeys, opts).then(
- (r) => {
- if (this.mounted && metric.key === this.props.requestedMetric.key) {
- this.setState((state) => ({
- components: [
- ...state.components,
- ...r.components.map((component) => enhanceComponent(component, metric, metrics)),
- ],
- loadingMoreComponents: false,
- paging: r.paging,
- }));
- }
- },
- () => {
- if (this.mounted) {
- this.setState({ loadingMoreComponents: false });
- }
- },
- );
- };
-
- getComponentRequestParams(
- view: MeasurePageView,
- metric: Pick<Metric, 'key' | 'direction'>,
- options: Object = {},
- ) {
- const strategy = view === MeasurePageView.list ? 'leaves' : 'children';
- const metricKeys = [metric.key];
- const opts: RequestData = {
- ...getBranchLikeQuery(this.props.branchLike),
- additionalFields: 'metrics',
- ps: 500,
- };
-
- const setMetricSort = () => {
- const isDiff = isDiffMetric(metric.key);
- opts.s = isDiff ? 'metricPeriod' : 'metric';
- opts.metricSortFilter = 'withMeasuresOnly';
- if (isDiff) {
- opts.metricPeriodSort = 1;
- }
- };
-
- const isDiff = isDiffMetric(metric.key);
- if (view === MeasurePageView.tree) {
- metricKeys.push(...(complementary[metric.key] || []));
- opts.asc = true;
- opts.s = 'qualifier,name';
- } else if (view === MeasurePageView.list) {
- metricKeys.push(...(complementary[metric.key] || []));
- opts.asc = metric.direction === 1;
- opts.metricSort = metric.key;
- setMetricSort();
- } else if (view === MeasurePageView.treemap) {
- const sizeMetric = isDiff ? MetricKey.new_lines : MetricKey.ncloc;
- metricKeys.push(sizeMetric);
- opts.asc = false;
- opts.metricSort = sizeMetric;
- setMetricSort();
- }
-
- return { metricKeys, opts: { ...opts, ...options }, strategy };
- }
-
- updateSelected = (component: string) => {
- this.props.updateQuery({
- selected: component !== this.props.rootComponent.key ? component : undefined,
- });
- };
-
- updateView = (view: MeasurePageView) => {
- this.props.updateQuery({ view });
- };
-
- onOpenComponent = (component: ComponentMeasureIntern) => {
- if (isView(this.props.rootComponent.qualifier)) {
- const comp = this.state.components.find(
- (c) =>
- c.refKey === component.key ||
- getComponentMeasureUniqueKey(c) === getComponentMeasureUniqueKey(component),
- );
-
- if (comp) {
- this.props.router.push(getProjectUrl(comp.refKey || comp.key, component.branch));
- }
-
- return;
- }
-
- this.setState((state) => ({ selectedComponent: state.baseComponent }));
- this.updateSelected(component.key);
- if (this.container) {
- this.container.focus();
- }
- };
-
- onSelectComponent = (component: ComponentMeasureIntern) => {
- this.setState({ selectedComponent: component });
- };
-
- getSelectedIndex = () => {
- const componentKey = isFile(this.state.baseComponent?.qualifier)
- ? getComponentMeasureUniqueKey(this.state.baseComponent)
- : getComponentMeasureUniqueKey(this.state.selectedComponent);
- const index = this.state.components.findIndex(
- (component) => getComponentMeasureUniqueKey(component) === componentKey,
- );
- return index !== -1 ? index : undefined;
- };
-
- getDefaultShowBestMeasures() {
- const { asc, view } = this.props;
- if ((asc !== undefined && view === MeasurePageView.list) || view === MeasurePageView.tree) {
- return true;
- }
- return false;
- }
-
- renderMeasure() {
- const { view } = this.props;
- const { metric } = this.state;
- if (!metric) {
- return null;
- }
- if (view === MeasurePageView.list || view === MeasurePageView.tree) {
- const selectedIdx = this.getSelectedIndex();
- return (
- <FilesView
- branchLike={this.props.branchLike}
- components={this.state.components}
- defaultShowBestMeasures={this.getDefaultShowBestMeasures()}
- fetchMore={this.fetchMoreComponents}
- handleOpen={this.onOpenComponent}
- handleSelect={this.onSelectComponent}
- loadingMore={this.state.loadingMoreComponents}
- metric={metric}
- metrics={this.props.metrics}
- paging={this.state.paging}
- rootComponent={this.props.rootComponent}
- selectedIdx={selectedIdx}
- selectedComponent={
- selectedIdx !== undefined
- ? (this.state.selectedComponent as ComponentMeasureEnhanced)
- : undefined
- }
- view={view}
- />
- );
- }
-
- return (
- <TreeMapView
- components={this.state.components}
- handleSelect={this.onOpenComponent}
- metric={metric}
- />
- );
- }
-
- render() {
- const { branchLike, rootComponent, view } = this.props;
- const { baseComponent, measure, metric, paging, secondaryMeasure } = this.state;
-
- if (!baseComponent || !metric) {
- return null;
- }
-
- const rawMeasureValue =
- measure && (isDiffMetric(measure.metric) ? measure.period?.value : measure.value);
- const measureValue = getCCTMeasureValue(metric.key, rawMeasureValue);
-
- const isFileComponent = isFile(baseComponent.qualifier);
- const selectedIdx = this.getSelectedIndex();
-
- return (
- <div ref={(container) => (this.container = container)}>
- <A11ySkipTarget anchor="measures_main" />
-
- <MeasureContentHeader
- left={
- <MeasuresBreadcrumbs
- backToFirst={view === MeasurePageView.list}
- branchLike={branchLike}
- className="sw-flex-1"
- component={baseComponent}
- handleSelect={this.onOpenComponent}
- rootComponent={rootComponent}
- />
- }
- right={
- <div className="sw-flex sw-items-center">
- {!isFileComponent && metric && (
- <>
- {!isApplication(baseComponent.qualifier) && (
- <>
- <Highlight
- className="sw-whitespace-nowrap"
- id="measures-view-selection-label"
- >
- {translate('component_measures.view_as')}
- </Highlight>
- <MeasureViewSelect
- className="measure-view-select sw-ml-2 sw-mr-4"
- handleViewChange={this.updateView}
- metric={metric}
- view={view}
- />
- </>
- )}
-
- {view !== MeasurePageView.treemap && (
- <>
- <KeyboardHint
- className="sw-mr-4 sw-ml-6"
- command={`${KeyboardKeys.DownArrow} ${KeyboardKeys.UpArrow}`}
- title={translate('component_measures.select_files')}
- />
-
- <KeyboardHint
- command={`${KeyboardKeys.LeftArrow} ${KeyboardKeys.RightArrow}`}
- title={translate('component_measures.navigate')}
- />
- </>
- )}
-
- {paging && paging.total > 0 && (
- <FilesCounter
- className="sw-min-w-24 sw-text-right"
- current={
- isDefined(selectedIdx) && view !== MeasurePageView.treemap
- ? selectedIdx + 1
- : undefined
- }
- total={paging.total}
- />
- )}
- </>
- )}
- </div>
- }
- />
-
- <div className="sw-p-6">
- <MeasureHeader
- branchLike={branchLike}
- component={baseComponent}
- leakPeriod={this.props.leakPeriod}
- measureValue={measureValue}
- metric={metric}
- secondaryMeasure={secondaryMeasure}
- />
- {isFileComponent ? (
- <div>
- <SourceViewer
- hideHeader
- branchLike={branchLike}
- component={baseComponent.key}
- metricKey={this.state.metric?.key}
- />
- </div>
- ) : (
- this.renderMeasure()
- )}
- </div>
- </div>
- );
- }
- }
|