aboutsummaryrefslogtreecommitdiffstats
path: root/server/sonar-web/src/main/js/apps/overview/events/PreviewGraph.js
blob: 0c52daceb1ad4e72577d61b241773c990e90ccd1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
/*
 * SonarQube
 * Copyright (C) 2009-2017 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.
 */
// @flow
import React from 'react';
import { minBy } from 'lodash';
import { AutoSizer } from 'react-virtualized';
import AdvancedTimeline from '../../../components/charts/AdvancedTimeline';
import PreviewGraphTooltips from './PreviewGraphTooltips';
import {
  DEFAULT_GRAPH,
  getDisplayedHistoryMetrics,
  generateSeries,
  getSeriesMetricType,
  hasHistoryDataValue,
  splitSeriesInGraphs
} from '../../projectActivity/utils';
import { getBranchName } from '../../../helpers/branches';
import { getCustomGraph, getGraph } from '../../../helpers/storage';
import { formatMeasure, getShortType } from '../../../helpers/measures';
import { translate } from '../../../helpers/l10n';
/*:: import type { Serie } from '../../../components/charts/AdvancedTimeline'; */
/*:: import type { History, Metric } from '../types'; */

/*::
type Props = {
  branch: {},
  history: ?History,
  metrics: Array<Metric>,
  project: string,
  router: { push: ({ pathname: string, query?: {} }) => void }
};
*/

/*::
type State = {
  customMetrics: Array<string>,
  graph: string,
  selectedDate: ?Date,
  series: Array<Serie>,
  tooltipIdx: ?number,
  tooltipXPos: ?number
};
*/

const GRAPH_PADDING = [4, 0, 4, 0];
const MAX_GRAPH_NB = 1;
const MAX_SERIES_PER_GRAPH = 3;

export default class PreviewGraph extends React.PureComponent {
  /*:: props: Props; */
  /*:: state: State; */

  constructor(props /*: Props */) {
    super(props);
    const graph = getGraph();
    const customMetrics = getCustomGraph();
    const series = splitSeriesInGraphs(
      this.getSeries(props.history, graph, customMetrics, props.metrics),
      MAX_GRAPH_NB,
      MAX_SERIES_PER_GRAPH
    );
    this.state = {
      customMetrics,
      graph,
      selectedDate: null,
      series: series.length > 0 ? series[0] : [],
      tooltipIdx: null,
      tooltipXPos: null
    };
  }

  componentWillReceiveProps(nextProps /*: Props */) {
    if (nextProps.history !== this.props.history || nextProps.metrics !== this.props.metrics) {
      const graph = getGraph();
      const customMetrics = getCustomGraph();
      const series = splitSeriesInGraphs(
        this.getSeries(nextProps.history, graph, customMetrics, nextProps.metrics),
        MAX_GRAPH_NB,
        MAX_SERIES_PER_GRAPH
      );
      this.setState({
        customMetrics,
        graph,
        series: series.length > 0 ? series[0] : []
      });
    }
  }

  formatValue = (tick /*: number | string */) =>
    formatMeasure(tick, getShortType(getSeriesMetricType(this.state.series)));

  getDisplayedMetrics = (graph /*: string */, customMetrics /*: Array<string> */) => {
    const metrics /*: Array<string> */ = getDisplayedHistoryMetrics(graph, customMetrics);
    if (!metrics || metrics.length <= 0) {
      return getDisplayedHistoryMetrics(DEFAULT_GRAPH, customMetrics);
    }
    return metrics;
  };

  getSeries = (
    history /*: ?History */,
    graph /*: string */,
    customMetrics /*: Array<string> */,
    metrics /*: Array<Metric> */
  ) => {
    const myHistory = history;
    if (!myHistory) {
      return [];
    }
    const displayedMetrics = this.getDisplayedMetrics(graph, customMetrics);
    const firstValid = minBy(
      displayedMetrics.map(metric => myHistory[metric].find(p => p.value || p.value === 0)),
      'date'
    );
    const measureHistory = displayedMetrics.map(metric => ({
      metric,
      history: firstValid
        ? myHistory[metric].filter(p => p.date >= firstValid.date)
        : myHistory[metric]
    }));
    return generateSeries(measureHistory, graph, metrics, displayedMetrics);
  };

  handleClick = () => {
    this.props.router.push({
      pathname: '/project/activity',
      query: { id: this.props.project, branch: getBranchName(this.props.branch) }
    });
  };

  updateTooltip = (
    selectedDate /*: ?Date */,
    tooltipXPos /*: ?number */,
    tooltipIdx /*: ?number */
  ) => this.setState({ selectedDate, tooltipXPos, tooltipIdx });

  renderTimeline() {
    const { graph, selectedDate, series, tooltipIdx, tooltipXPos } = this.state;
    return (
      <AutoSizer disableHeight={true}>
        {({ width }) =>
          <div>
            <AdvancedTimeline
              endDate={null}
              startDate={null}
              height={80}
              width={width}
              hideGrid={true}
              hideXAxis={true}
              interpolate="linear"
              metricType={getSeriesMetricType(series)}
              padding={GRAPH_PADDING}
              series={series}
              showAreas={['coverage', 'duplications'].includes(graph)}
              updateTooltip={this.updateTooltip}
            />
            {selectedDate != null &&
              tooltipXPos != null &&
              tooltipIdx != null &&
              <PreviewGraphTooltips
                formatValue={this.formatValue}
                graph={graph}
                graphWidth={width}
                metrics={this.props.metrics}
                selectedDate={selectedDate}
                series={series}
                tooltipIdx={tooltipIdx}
                tooltipPos={tooltipXPos}
              />}
          </div>}
      </AutoSizer>
    );
  }

  render() {
    const { series } = this.state;
    return (
      <div
        className="overview-analysis-graph big-spacer-bottom spacer-top"
        onClick={this.handleClick}
        tabIndex={0}
        role="link">
        {hasHistoryDataValue(series)
          ? this.renderTimeline()
          : <div className="note text-center spacer-top big-spacer-bottom">
              {translate('component_measures.no_history')}
            </div>}
      </div>
    );
  }
}