summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/monitoring/components/charts/time_series.vue
blob: 170c5ff76956da1a3d3501347532b33e41706cca (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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
<script>
import { isEmpty, omit, throttle } from 'lodash';
import { GlLink, GlTooltip, GlResizeObserverDirective, GlIcon } from '@gitlab/ui';
import { GlAreaChart, GlLineChart, GlChartSeriesLabel } from '@gitlab/ui/dist/charts';
import { s__ } from '~/locale';
import { getSvgIconPathContent } from '~/lib/utils/icon_utils';
import { panelTypes, chartHeight, lineTypes, lineWidths, legendLayoutTypes } from '../../constants';
import { getYAxisOptions, getTimeAxisOptions, getChartGrid, getTooltipFormatter } from './options';
import { annotationsYAxis, generateAnnotationsSeries } from './annotations';
import { makeDataSeries } from '~/helpers/monitor_helper';
import { graphDataValidatorForValues } from '../../utils';
import { formatDate, timezones } from '../../format_date';

export const timestampToISODate = timestamp => new Date(timestamp).toISOString();

const THROTTLED_DATAZOOM_WAIT = 1000; // milliseconds

const events = {
  datazoom: 'datazoom',
};

export default {
  components: {
    GlAreaChart,
    GlLineChart,
    GlTooltip,
    GlChartSeriesLabel,
    GlLink,
    GlIcon,
  },
  directives: {
    GlResizeObserverDirective,
  },
  inheritAttrs: false,
  props: {
    graphData: {
      type: Object,
      required: true,
      validator: graphDataValidatorForValues.bind(null, false),
    },
    option: {
      type: Object,
      required: false,
      default: () => ({}),
    },
    timeRange: {
      type: Object,
      required: false,
      default: () => ({}),
    },
    seriesConfig: {
      type: Object,
      required: false,
      default: () => ({}),
    },
    deploymentData: {
      type: Array,
      required: false,
      default: () => [],
    },
    annotations: {
      type: Array,
      required: false,
      default: () => [],
    },
    projectPath: {
      type: String,
      required: false,
      default: '',
    },
    height: {
      type: Number,
      required: false,
      default: chartHeight,
    },
    thresholds: {
      type: Array,
      required: false,
      default: () => [],
    },
    legendLayout: {
      type: String,
      required: false,
      default: legendLayoutTypes.table,
    },
    legendAverageText: {
      type: String,
      required: false,
      default: s__('Metrics|Avg'),
    },
    legendCurrentText: {
      type: String,
      required: false,
      default: s__('Metrics|Current'),
    },
    legendMaxText: {
      type: String,
      required: false,
      default: s__('Metrics|Max'),
    },
    legendMinText: {
      type: String,
      required: false,
      default: s__('Metrics|Min'),
    },
    groupId: {
      type: String,
      required: false,
      default: '',
    },
    timezone: {
      type: String,
      required: false,
      default: timezones.LOCAL,
    },
  },
  data() {
    return {
      tooltip: {
        type: '',
        title: '',
        content: [],
        commitUrl: '',
        sha: '',
      },
      width: 0,
      svgs: {},
      primaryColor: null,
      throttledDatazoom: null,
    };
  },
  computed: {
    chartData() {
      // Transforms & supplements query data to render appropriate labels & styles
      // Input: [{ queryAttributes1 }, { queryAttributes2 }]
      // Output: [{ seriesAttributes1 }, { seriesAttributes2 }]
      return this.graphData.metrics.reduce((acc, query) => {
        const { appearance } = query;
        const lineType =
          appearance && appearance.line && appearance.line.type
            ? appearance.line.type
            : lineTypes.default;
        const lineWidth =
          appearance && appearance.line && appearance.line.width
            ? appearance.line.width
            : lineWidths.default;
        const areaStyle = {
          opacity:
            appearance && appearance.area && typeof appearance.area.opacity === 'number'
              ? appearance.area.opacity
              : undefined,
        };
        const series = makeDataSeries(query.result || [], {
          name: this.formatLegendLabel(query),
          lineStyle: {
            type: lineType,
            width: lineWidth,
          },
          showSymbol: false,
          areaStyle: this.graphData.type === 'area-chart' ? areaStyle : undefined,
          ...this.seriesConfig,
        });

        return acc.concat(series);
      }, []);
    },
    chartOptionSeries() {
      // After https://gitlab.com/gitlab-org/gitlab/-/issues/211330 is implemented,
      // this method will have access to annotations data
      return (this.option.series || []).concat(
        generateAnnotationsSeries({
          deployments: this.recentDeployments,
          annotations: this.annotations,
        }),
      );
    },
    chartOptions() {
      const { yAxis, xAxis } = this.option;
      const option = omit(this.option, ['series', 'yAxis', 'xAxis']);
      const xAxisBounds = isEmpty(this.timeRange)
        ? {}
        : {
            min: this.timeRange.start,
            max: this.timeRange.end,
          };

      const timeXAxis = {
        ...getTimeAxisOptions({ timezone: this.timezone }),
        ...xAxis,
        ...xAxisBounds,
      };

      const dataYAxis = {
        ...getYAxisOptions(this.graphData.yAxis),
        ...yAxis,
      };

      return {
        series: this.chartOptionSeries,
        xAxis: timeXAxis,
        yAxis: [dataYAxis, annotationsYAxis],
        grid: getChartGrid(),
        dataZoom: [this.dataZoomConfig],
        ...option,
      };
    },
    dataZoomConfig() {
      const handleIcon = this.svgs['scroll-handle'];

      return handleIcon ? { handleIcon } : {};
    },
    /**
     * This method returns the earliest time value in all series of a chart.
     * Takes a chart data with data to populate a timeseries.
     * data should be an array of data points [t, y] where t is a ISO formatted date,
     * and is sorted by t (time).
     * @returns {(String|null)} earliest x value from all series, or null when the
     * chart series data is empty.
     */
    earliestDatapoint() {
      return this.chartData.reduce((acc, series) => {
        const { data } = series;
        const { length } = data;
        if (!length) {
          return acc;
        }

        const [first] = data[0];
        const [last] = data[length - 1];
        const seriesEarliest = first < last ? first : last;

        return seriesEarliest < acc || acc === null ? seriesEarliest : acc;
      }, null);
    },
    glChartComponent() {
      const chartTypes = {
        [panelTypes.AREA_CHART]: GlAreaChart,
        [panelTypes.LINE_CHART]: GlLineChart,
      };
      return chartTypes[this.graphData.type] || GlAreaChart;
    },
    isMultiSeries() {
      return this.tooltip.content.length > 1;
    },
    recentDeployments() {
      return this.deploymentData.reduce((acc, deployment) => {
        if (deployment.created_at >= this.earliestDatapoint) {
          const { id, created_at, sha, ref, tag } = deployment;
          acc.push({
            id,
            createdAt: created_at,
            sha,
            commitUrl: `${this.projectPath}/-/commit/${sha}`,
            tag,
            tagUrl: tag ? `${this.tagsPath}/${ref.name}` : null,
            ref: ref.name,
            showDeploymentFlag: false,
            icon: this.svgs.rocket,
            color: this.primaryColor,
          });
        }

        return acc;
      }, []);
    },
    tooltipYFormatter() {
      // Use same format as y-axis
      return getTooltipFormatter({ format: this.graphData.yAxis?.format });
    },
  },
  created() {
    this.setSvg('rocket');
    this.setSvg('scroll-handle');
  },
  destroyed() {
    if (this.throttledDatazoom) {
      this.throttledDatazoom.cancel();
    }
  },
  methods: {
    formatLegendLabel(query) {
      return query.label;
    },
    isTooltipOfType(tooltipType, defaultType) {
      return tooltipType === defaultType;
    },
    /**
     * This method is triggered when hovered over a single markPoint.
     *
     * The annotations title timestamp should match the data tooltip
     * title.
     *
     * @params {Object} params markPoint object
     * @returns {Object}
     */
    formatAnnotationsTooltipText(params) {
      return {
        title: formatDate(params.data?.tooltipData?.title, { timezone: this.timezone }),
        content: params.data?.tooltipData?.content,
      };
    },
    formatTooltipText(params) {
      this.tooltip.title = formatDate(params.value, { timezone: this.timezone });

      this.tooltip.content = [];

      params.seriesData.forEach(dataPoint => {
        if (dataPoint.value) {
          const [, yVal] = dataPoint.value;
          this.tooltip.type = dataPoint.name;
          if (this.tooltip.type === 'deployments') {
            const { data = {} } = dataPoint;
            this.tooltip.sha = data?.tooltipData?.sha;
            this.tooltip.commitUrl = data?.tooltipData?.commitUrl;
          } else {
            const { seriesName, color, dataIndex } = dataPoint;

            this.tooltip.content.push({
              name: seriesName,
              dataIndex,
              value: this.tooltipYFormatter(yVal),
              color,
            });
          }
        }
      });
    },
    setSvg(name) {
      getSvgIconPathContent(name)
        .then(path => {
          if (path) {
            this.$set(this.svgs, name, `path://${path}`);
          }
        })
        .catch(e => {
          // eslint-disable-next-line no-console, @gitlab/require-i18n-strings
          console.error('SVG could not be rendered correctly: ', e);
        });
    },
    onChartUpdated(eChart) {
      [this.primaryColor] = eChart.getOption().color;
    },
    onChartCreated(eChart) {
      // Emit a datazoom event that corresponds to the eChart
      // `datazoom` event.

      if (this.throttledDatazoom) {
        // Chart can be created multiple times in this component's
        // lifetime, remove previous handlers every time
        // chart is created.
        this.throttledDatazoom.cancel();
      }

      // Emitting is throttled to avoid flurries of calls when
      // the user changes or scrolls the zoom bar.
      this.throttledDatazoom = throttle(
        () => {
          const { startValue, endValue } = eChart.getOption().dataZoom[0];
          this.$emit(events.datazoom, {
            start: timestampToISODate(startValue),
            end: timestampToISODate(endValue),
          });
        },
        THROTTLED_DATAZOOM_WAIT,
        {
          leading: false,
        },
      );

      // eslint-disable-next-line @gitlab/no-global-event-off
      eChart.off('datazoom');
      eChart.on('datazoom', this.throttledDatazoom);
    },
    onResize() {
      if (!this.$refs.chart) return;
      const { width } = this.$refs.chart.$el.getBoundingClientRect();
      this.width = width;
    },
  },
};
</script>

<template>
  <div v-gl-resize-observer-directive="onResize">
    <component
      :is="glChartComponent"
      ref="chart"
      v-bind="$attrs"
      :group-id="groupId"
      :data="chartData"
      :option="chartOptions"
      :format-tooltip-text="formatTooltipText"
      :format-annotations-tooltip-text="formatAnnotationsTooltipText"
      :thresholds="thresholds"
      :width="width"
      :height="height"
      :legend-layout="legendLayout"
      :legend-average-text="legendAverageText"
      :legend-current-text="legendCurrentText"
      :legend-max-text="legendMaxText"
      :legend-min-text="legendMinText"
      @created="onChartCreated"
      @updated="onChartUpdated"
    >
      <template v-if="tooltip.type === 'deployments'">
        <template slot="tooltip-title">
          {{ __('Deployed') }}
        </template>
        <div slot="tooltip-content" class="d-flex align-items-center">
          <gl-icon name="commit" class="mr-2" />
          <gl-link :href="tooltip.commitUrl">{{ tooltip.sha }}</gl-link>
        </div>
      </template>
      <template v-else>
        <template slot="tooltip-title">
          <div class="text-nowrap">
            {{ tooltip.title }}
          </div>
        </template>
        <template slot="tooltip-content" :tooltip="tooltip">
          <div
            v-for="(content, key) in tooltip.content"
            :key="key"
            class="d-flex justify-content-between"
          >
            <gl-chart-series-label :color="isMultiSeries ? content.color : ''">
              {{ content.name }}
            </gl-chart-series-label>
            <div class="gl-ml-7">
              {{ content.value }}
            </div>
          </div>
        </template>
      </template>
    </component>
  </div>
</template>