Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
// This file is part of Moodle - http://moodle.org/
2
//
3
// Moodle is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// Moodle is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU General Public License for more details.
12
//
13
// You should have received a copy of the GNU General Public License
14
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15
 
16
/**
17
 * Chart output for chart.js.
18
 *
19
 * @copyright  2016 Frédéric Massart - FMCorz.net
20
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
21
 * @module     core/chart_output_chartjs
22
 */
23
define([
24
    'jquery',
25
    'core/chartjs',
26
    'core/chart_axis',
27
    'core/chart_bar',
28
    'core/chart_output_base',
29
    'core/chart_line',
30
    'core/chart_pie',
31
    'core/chart_series'
32
], function($, Chartjs, Axis, Bar, Base, Line, Pie, Series) {
33
 
34
    /**
35
     * Makes an axis ID.
36
     *
37
     * @param {String} xy Accepts 'x' and 'y'.
38
     * @param {Number} index The axis index.
39
     * @return {String}
40
     */
41
    var makeAxisId = function(xy, index) {
42
        return 'axis-' + xy + '-' + index;
43
    };
44
 
45
    /**
46
     * Chart output for Chart.js.
47
     *
48
     * @class
49
     * @extends {module:core/chart_output_base}
50
     */
51
    function Output() {
52
        Base.prototype.constructor.apply(this, arguments);
53
 
54
        // Make sure that we've got a canvas tag.
55
        this._canvas = this._node;
56
        if (this._canvas.prop('tagName') != 'CANVAS') {
57
            this._canvas = $('<canvas>');
58
            this._node.append(this._canvas);
59
        }
60
 
61
        this._build();
62
    }
63
    Output.prototype = Object.create(Base.prototype);
64
 
65
    /**
66
     * Reference to the chart config object.
67
     *
68
     * @type {Object}
69
     * @protected
70
     */
71
    Output.prototype._config = null;
72
 
73
    /**
74
     * Reference to the instance of chart.js.
75
     *
76
     * @type {Object}
77
     * @protected
78
     */
79
    Output.prototype._chartjs = null;
80
 
81
    /**
82
     * Reference to the canvas node.
83
     *
84
     * @type {Jquery}
85
     * @protected
86
     */
87
    Output.prototype._canvas = null;
88
 
89
    /**
90
     * Builds the config and the chart.
91
     *
92
     * @protected
93
     */
94
    Output.prototype._build = function() {
95
        this._config = this._makeConfig();
96
        this._chartjs = new Chartjs(this._canvas[0], this._config);
97
    };
98
 
99
    /**
100
     * Clean data.
101
     *
102
     * @param {(String|String[])} data A single string or an array of strings.
103
     * @returns {(String|String[])}
104
     * @protected
105
     */
106
    Output.prototype._cleanData = function(data) {
107
        if (data instanceof Array) {
108
            return data.map(function(value) {
109
                return $('<span>').html(value).text();
110
            });
111
        } else {
112
            return $('<span>').html(data).text();
113
        }
114
    };
115
 
116
    /**
117
     * Get the chart type and handles the Chart.js specific chart types.
118
     *
119
     * By default returns the current chart TYPE value. Also does the handling of specific chart types, for example
120
     * check if the bar chart should be horizontal and the pie chart should be displayed as a doughnut.
121
     *
122
     * @method getChartType
123
     * @returns {String} the chart type.
124
     * @protected
125
     */
126
    Output.prototype._getChartType = function() {
127
        var type = this._chart.getType();
128
 
129
        // Bars can be displayed vertically and horizontally, defining horizontalBar type.
130
        if (this._chart.getType() === Bar.prototype.TYPE && this._chart.getHorizontal() === true) {
131
            type = 'horizontalBar';
132
        } else if (this._chart.getType() === Pie.prototype.TYPE && this._chart.getDoughnut() === true) {
133
            // Pie chart can be displayed as doughnut.
134
            type = 'doughnut';
135
        }
136
 
137
        return type;
138
    };
139
 
140
    /**
141
     * Make the axis config.
142
     *
143
     * @protected
144
     * @param {module:core/chart_axis} axis The axis.
145
     * @param {String} xy Accepts 'x' or 'y'.
146
     * @param {Number} index The axis index.
147
     * @return {Object} The axis config.
148
     */
149
    Output.prototype._makeAxisConfig = function(axis, xy, index) {
150
        var scaleData = {
151
            id: makeAxisId(xy, index)
152
        };
153
 
154
        if (axis.getPosition() !== Axis.prototype.POS_DEFAULT) {
155
            scaleData.position = axis.getPosition();
156
        }
157
 
158
        if (axis.getLabel() !== null) {
159
            scaleData.title = {
160
                display: true,
161
                text: this._cleanData(axis.getLabel())
162
            };
163
        }
164
 
165
        if (axis.getStepSize() !== null) {
166
            scaleData.ticks = scaleData.ticks || {};
167
            scaleData.ticks.stepSize = axis.getStepSize();
168
        }
169
 
170
        if (axis.getMax() !== null) {
171
            scaleData.ticks = scaleData.ticks || {};
172
            scaleData.ticks.max = axis.getMax();
173
        }
174
 
175
        if (axis.getMin() !== null) {
176
            scaleData.ticks = scaleData.ticks || {};
177
            scaleData.ticks.min = axis.getMin();
178
        }
179
 
180
        return scaleData;
181
    };
182
 
183
    /**
184
     * Make the config config.
185
     *
186
     * @protected
187
     * @return {Object} The axis config.
188
     */
189
    Output.prototype._makeConfig = function() {
190
        var charType = this._getChartType();
1441 ariadna 191
        var labels = this._cleanData(this._chart.getLabels());
1 efrain 192
        var config = {
193
            type: charType,
194
            data: {
1441 ariadna 195
                // If the label is longer than 25 characters, truncate it and add an
196
                // ellipsis to avoid breaking the chart.
197
                labels: labels.map((label) => {
198
                    return label.length > 25 ? `${label.substring(0, 25)}...` : label;
199
                }),
1 efrain 200
                datasets: this._makeDatasetsConfig()
201
            },
202
            options: {
1441 ariadna 203
                locale: document.documentElement.getAttribute('lang'),
1 efrain 204
                responsive: true,
205
                maintainAspectRatio: false,
206
                plugins: {
207
                    title: {
208
                        display: this._chart.getTitle() !== null,
209
                        text: this._cleanData(this._chart.getTitle())
210
                    }
211
                }
212
            }
213
        };
214
 
215
        if (charType === 'horizontalBar') {
216
            config.type = 'bar';
217
            config.options.indexAxis = 'y';
218
        }
219
 
220
        var legendOptions = this._chart.getLegendOptions();
221
        if (legendOptions) {
222
            config.options.plugins.legend = legendOptions;
223
        }
224
 
225
 
226
        this._chart.getXAxes().forEach(function(axis, i) {
227
            var axisLabels = axis.getLabels();
228
 
229
            config.options.scales = config.options.scales || {};
1441 ariadna 230
            config.options.scales.x = this._makeAxisConfig(axis, 'x', i);
1 efrain 231
 
232
            if (axisLabels !== null) {
1441 ariadna 233
                config.options.scales.x.ticks.callback = function(value, index) {
1 efrain 234
                    return axisLabels[index] || '';
235
                };
236
            }
237
            config.options.scales.x.stacked = this._isStacked();
238
        }.bind(this));
239
 
240
        this._chart.getYAxes().forEach(function(axis, i) {
241
            var axisLabels = axis.getLabels();
242
 
243
            config.options.scales = config.options.scales || {};
1441 ariadna 244
            config.options.scales.y = this._makeAxisConfig(axis, 'y', i);
1 efrain 245
 
246
            if (axisLabels !== null) {
1441 ariadna 247
                config.options.scales.y.ticks.callback = function(value) {
1 efrain 248
                    return axisLabels[parseInt(value, 10)] || '';
249
                };
250
            }
251
            config.options.scales.y.stacked = this._isStacked();
252
        }.bind(this));
253
 
254
        config.options.plugins.tooltip = {
255
            callbacks: {
1441 ariadna 256
                title: (ctx) => {
257
                    // Add line breaks to the tooltip title to prevent the tooltip from cutting
258
                    // off if the title has a character count that overlaps the width of the chart.
259
                    var label = labels[ctx[0].dataIndex];
260
                    return label.match(/.{1,80}/g);
261
                },
1 efrain 262
                label: this._makeTooltip.bind(this)
263
            }
264
        };
265
 
266
        return config;
267
    };
268
 
269
    /**
270
     * Get the datasets configurations.
271
     *
272
     * @protected
273
     * @return {Object[]}
274
     */
275
    Output.prototype._makeDatasetsConfig = function() {
276
        var sets = this._chart.getSeries().map(function(series) {
277
            var colors = series.hasColoredValues() ? series.getColors() : series.getColor();
278
            var dataset = {
279
                label: this._cleanData(series.getLabel()),
280
                data: series.getValues(),
281
                type: series.getType(),
282
                fill: series.getFill(),
283
                backgroundColor: colors,
284
                // Pie charts look better without borders.
285
                borderColor: this._chart.getType() == Pie.prototype.TYPE ? '#fff' : colors,
286
                tension: this._isSmooth(series) ? 0.3 : 0
287
            };
288
 
289
            if (series.getXAxis() !== null) {
290
                dataset.xAxisID = makeAxisId('x', series.getXAxis());
291
            }
292
            if (series.getYAxis() !== null) {
293
                dataset.yAxisID = makeAxisId('y', series.getYAxis());
294
            }
295
 
296
            return dataset;
297
        }.bind(this));
298
        return sets;
299
    };
300
 
301
    /**
302
     * Get the chart data, add labels and rebuild the tooltip.
303
     *
304
     * @param {Object[]} tooltipItem The tooltip item object.
305
     * @returns {Array}
306
     * @protected
307
     */
308
    Output.prototype._makeTooltip = function(tooltipItem) {
309
 
310
        // Get series and chart data to rebuild the tooltip and add labels.
1441 ariadna 311
        const formatter = new Intl.NumberFormat(this._config.options.locale);
1 efrain 312
        var series = this._chart.getSeries()[tooltipItem.datasetIndex];
313
        var serieLabel = series.getLabel();
314
        var chartData = tooltipItem.dataset.data;
1441 ariadna 315
        var tooltipData = formatter.format(chartData[tooltipItem.dataIndex]);
1 efrain 316
 
317
        // Build default tooltip.
318
        var tooltip = [];
319
 
320
        // Pie and doughnut charts tooltip are different.
321
        if (this._chart.getType() === Pie.prototype.TYPE) {
322
            var chartLabels = this._cleanData(this._chart.getLabels());
323
            tooltip.push(chartLabels[tooltipItem.dataIndex] + ' - ' + this._cleanData(serieLabel) + ': ' + tooltipData);
324
        } else {
325
            tooltip.push(this._cleanData(serieLabel) + ': ' + tooltipData);
326
        }
327
 
328
        return tooltip;
329
    };
330
 
331
    /**
332
     * Verify if the chart line is smooth or not.
333
     *
334
     * @protected
335
     * @param {module:core/chart_series} series The series.
336
     * @returns {Bool}
337
     */
338
    Output.prototype._isSmooth = function(series) {
339
        var smooth = false;
340
        if (this._chart.getType() === Line.prototype.TYPE) {
341
            smooth = series.getSmooth();
342
            if (smooth === null) {
343
                smooth = this._chart.getSmooth();
344
            }
345
        } else if (series.getType() === Series.prototype.TYPE_LINE) {
346
            smooth = series.getSmooth();
347
        }
348
 
349
        return smooth;
350
    };
351
 
352
    /**
353
     * Verify if the bar chart is stacked or not.
354
     *
355
     * @protected
356
     * @returns {Bool}
357
     */
358
    Output.prototype._isStacked = function() {
359
        var stacked = false;
360
 
361
        // Stacking is (currently) only supported for bar charts.
362
        if (this._chart.getType() === Bar.prototype.TYPE) {
363
            stacked = this._chart.getStacked();
364
        }
365
 
366
        return stacked;
367
    };
368
 
369
    /** @override */
370
    Output.prototype.update = function() {
371
        $.extend(true, this._config, this._makeConfig());
372
        this._chartjs.update();
373
    };
374
 
375
    return Output;
376
 
377
});