debian-mirror-gitlab/app/assets/javascripts/pages/projects/graphs/charts/index.js

88 lines
2.4 KiB
JavaScript
Raw Normal View History

2018-05-09 12:01:36 +05:30
import $ from 'jquery';
2018-03-27 19:54:05 +05:30
import Chart from 'chart.js';
2017-09-10 17:25:29 +05:30
import _ from 'underscore';
2019-07-07 11:18:12 +05:30
import { barChartOptions, pieChartOptions } from '~/lib/utils/chart_utils';
2017-09-10 17:25:29 +05:30
document.addEventListener('DOMContentLoaded', () => {
const projectChartData = JSON.parse(document.getElementById('projectChartData').innerHTML);
2019-07-07 11:18:12 +05:30
const barChart = (selector, data) => {
2017-09-10 17:25:29 +05:30
// get selector by context
const ctx = selector.get(0).getContext('2d');
// pointing parent container to make chart.js inherit its width
const container = $(selector).parent();
2019-07-07 11:18:12 +05:30
selector.attr('width', $(container).width());
// Scale fonts if window width lower than 768px (iPad portrait)
const shouldAdjustFontSize = window.innerWidth < 768;
return new Chart(ctx, {
type: 'bar',
data,
options: barChartOptions(shouldAdjustFontSize),
});
};
const pieChart = (context, data) => {
const options = pieChartOptions();
return new Chart(context, {
type: 'pie',
data,
options,
});
2017-09-10 17:25:29 +05:30
};
const chartData = data => ({
labels: Object.keys(data),
2018-12-13 13:39:08 +05:30
datasets: [
{
2019-07-07 11:18:12 +05:30
backgroundColor: 'rgba(220,220,220,0.5)',
borderColor: 'rgba(220,220,220,1)',
borderWidth: 1,
2018-12-13 13:39:08 +05:30
data: _.values(data),
},
],
2017-09-10 17:25:29 +05:30
});
2019-03-02 22:35:43 +05:30
const reorderWeekDays = (weekDays, firstDayOfWeek = 0) => {
if (firstDayOfWeek === 0) {
return weekDays;
}
return Object.keys(weekDays).reduce((acc, dayName, idx, arr) => {
const reorderedDayName = arr[(idx + firstDayOfWeek) % arr.length];
return {
...acc,
[reorderedDayName]: weekDays[reorderedDayName],
};
}, {});
};
2017-09-10 17:25:29 +05:30
const hourData = chartData(projectChartData.hour);
2019-07-07 11:18:12 +05:30
barChart($('#hour-chart'), hourData);
2017-09-10 17:25:29 +05:30
2019-03-02 22:35:43 +05:30
const weekDays = reorderWeekDays(projectChartData.weekDays, gon.first_day_of_week);
const dayData = chartData(weekDays);
2019-07-07 11:18:12 +05:30
barChart($('#weekday-chart'), dayData);
2017-09-10 17:25:29 +05:30
const monthData = chartData(projectChartData.month);
2019-07-07 11:18:12 +05:30
barChart($('#month-chart'), monthData);
2017-09-10 17:25:29 +05:30
2019-07-07 11:18:12 +05:30
const data = {
datasets: [
{
data: projectChartData.languages.map(x => x.value),
backgroundColor: projectChartData.languages.map(x => x.color),
hoverBackgroundColor: projectChartData.languages.map(x => x.highlight),
},
],
labels: projectChartData.languages.map(x => x.label),
};
2018-12-13 13:39:08 +05:30
const ctx = $('#languages-chart')
.get(0)
.getContext('2d');
2019-07-07 11:18:12 +05:30
pieChart(ctx, data);
2017-09-10 17:25:29 +05:30
});