Proyectos de Subversion Moodle

Rev

| 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();
191
        var config = {
192
            type: charType,
193
            data: {
194
                labels: this._cleanData(this._chart.getLabels()),
195
                datasets: this._makeDatasetsConfig()
196
            },
197
            options: {
198
                responsive: true,
199
                maintainAspectRatio: false,
200
                plugins: {
201
                    title: {
202
                        display: this._chart.getTitle() !== null,
203
                        text: this._cleanData(this._chart.getTitle())
204
                    }
205
                }
206
            }
207
        };
208
 
209
        if (charType === 'horizontalBar') {
210
            config.type = 'bar';
211
            config.options.indexAxis = 'y';
212
        }
213
 
214
        var legendOptions = this._chart.getLegendOptions();
215
        if (legendOptions) {
216
            config.options.plugins.legend = legendOptions;
217
        }
218
 
219
 
220
        this._chart.getXAxes().forEach(function(axis, i) {
221
            var axisLabels = axis.getLabels();
222
 
223
            config.options.scales = config.options.scales || {};
224
            config.options.scales.x = config.options.scales.x || {};
225
            config.options.scales.x[i] = this._makeAxisConfig(axis, 'x', i);
226
 
227
            if (axisLabels !== null) {
228
                config.options.scales.x[i].ticks.callback = function(value, index) {
229
                    return axisLabels[index] || '';
230
                };
231
            }
232
            config.options.scales.x.stacked = this._isStacked();
233
        }.bind(this));
234
 
235
        this._chart.getYAxes().forEach(function(axis, i) {
236
            var axisLabels = axis.getLabels();
237
 
238
            config.options.scales = config.options.scales || {};
239
            config.options.scales.y = config.options.scales.yAxes || {};
240
            config.options.scales.y[i] = this._makeAxisConfig(axis, 'y', i);
241
 
242
            if (axisLabels !== null) {
243
                config.options.scales.y[i].ticks.callback = function(value) {
244
                    return axisLabels[parseInt(value, 10)] || '';
245
                };
246
            }
247
            config.options.scales.y.stacked = this._isStacked();
248
        }.bind(this));
249
 
250
        config.options.plugins.tooltip = {
251
            callbacks: {
252
                label: this._makeTooltip.bind(this)
253
            }
254
        };
255
 
256
        return config;
257
    };
258
 
259
    /**
260
     * Get the datasets configurations.
261
     *
262
     * @protected
263
     * @return {Object[]}
264
     */
265
    Output.prototype._makeDatasetsConfig = function() {
266
        var sets = this._chart.getSeries().map(function(series) {
267
            var colors = series.hasColoredValues() ? series.getColors() : series.getColor();
268
            var dataset = {
269
                label: this._cleanData(series.getLabel()),
270
                data: series.getValues(),
271
                type: series.getType(),
272
                fill: series.getFill(),
273
                backgroundColor: colors,
274
                // Pie charts look better without borders.
275
                borderColor: this._chart.getType() == Pie.prototype.TYPE ? '#fff' : colors,
276
                tension: this._isSmooth(series) ? 0.3 : 0
277
            };
278
 
279
            if (series.getXAxis() !== null) {
280
                dataset.xAxisID = makeAxisId('x', series.getXAxis());
281
            }
282
            if (series.getYAxis() !== null) {
283
                dataset.yAxisID = makeAxisId('y', series.getYAxis());
284
            }
285
 
286
            return dataset;
287
        }.bind(this));
288
        return sets;
289
    };
290
 
291
    /**
292
     * Get the chart data, add labels and rebuild the tooltip.
293
     *
294
     * @param {Object[]} tooltipItem The tooltip item object.
295
     * @returns {Array}
296
     * @protected
297
     */
298
    Output.prototype._makeTooltip = function(tooltipItem) {
299
 
300
        // Get series and chart data to rebuild the tooltip and add labels.
301
        var series = this._chart.getSeries()[tooltipItem.datasetIndex];
302
        var serieLabel = series.getLabel();
303
        var chartData = tooltipItem.dataset.data;
304
        var tooltipData = chartData[tooltipItem.dataIndex];
305
 
306
        // Build default tooltip.
307
        var tooltip = [];
308
 
309
        // Pie and doughnut charts tooltip are different.
310
        if (this._chart.getType() === Pie.prototype.TYPE) {
311
            var chartLabels = this._cleanData(this._chart.getLabels());
312
            tooltip.push(chartLabels[tooltipItem.dataIndex] + ' - ' + this._cleanData(serieLabel) + ': ' + tooltipData);
313
        } else {
314
            tooltip.push(this._cleanData(serieLabel) + ': ' + tooltipData);
315
        }
316
 
317
        return tooltip;
318
    };
319
 
320
    /**
321
     * Verify if the chart line is smooth or not.
322
     *
323
     * @protected
324
     * @param {module:core/chart_series} series The series.
325
     * @returns {Bool}
326
     */
327
    Output.prototype._isSmooth = function(series) {
328
        var smooth = false;
329
        if (this._chart.getType() === Line.prototype.TYPE) {
330
            smooth = series.getSmooth();
331
            if (smooth === null) {
332
                smooth = this._chart.getSmooth();
333
            }
334
        } else if (series.getType() === Series.prototype.TYPE_LINE) {
335
            smooth = series.getSmooth();
336
        }
337
 
338
        return smooth;
339
    };
340
 
341
    /**
342
     * Verify if the bar chart is stacked or not.
343
     *
344
     * @protected
345
     * @returns {Bool}
346
     */
347
    Output.prototype._isStacked = function() {
348
        var stacked = false;
349
 
350
        // Stacking is (currently) only supported for bar charts.
351
        if (this._chart.getType() === Bar.prototype.TYPE) {
352
            stacked = this._chart.getStacked();
353
        }
354
 
355
        return stacked;
356
    };
357
 
358
    /** @override */
359
    Output.prototype.update = function() {
360
        $.extend(true, this._config, this._makeConfig());
361
        this._chartjs.update();
362
    };
363
 
364
    return Output;
365
 
366
});