Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/site/app/webroot/js/stats/plots.js
blob: 48f792e6afce8eaff56bb47ada42ef67674c6e6d (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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
var Plots = {
    timeplot_id: '',
    timeplotCount: 0,
    timeplot: null,
    availableFields: [],
    currentCSV: '',
    
    determinePlot: function() {
        var selected = plotSelection.dropdowns['plot-selector'].selectedItem.value;
        var group_by = plotSelection.getGroupByValue();

        // Remove current plot selections
        plotSelection.removeAll();
        
        // Make sure summary-specific options are shown or hidden as approp.
        this.summary.updateOptionsVisibility();
        
        if (selected == 'summary')
            this.summary.initialize();
        else if (selected == 'custom')
            Plots.customPlot();
        else
            Plots.defined.initialize();
    },
    
    newTimeplot: function() {
        if (this.timeplot_id != '') {
            $('#' + this.timeplot_id).remove();
            this.timeplot = null;
        }
        this.timeplotCount++;
        
        $('#not-enough-data').hide();
        
        this.timeplot_id = 'timeplot' + this.timeplotCount;
        $('#timeplot-container').append('<div id="' + this.timeplot_id + '" class="timeplot"></div>');
    },
    
    summary: {
        dataSources: {},
        timeGeometry: {},
        valueGeometry: {},
        plotInfo: {},
        zoomLevel: 0,
        
        initialize: function() {       
            this.dataSources = {
                'downloads': new Timeplot.DefaultEventSource(),
                'updatepings': new Timeplot.DefaultEventSource()
            };

            PlotsTables.addListeners('summary', this.dataSources);
            
            this.valueGeometry = {
                'downloads': {
                    'gridColor': '#000000',
                    'axisLabelsPlacement': 'left'
                },
                'updatepings': {
                    'gridColor': '#9966CC',
                    'axisLabelsPlacement': 'right'
                }
            };
            
            this.timeGeometry = {
                'gridColor': '#000000',
                'axisLabelsPlacement': 'bottom',
                'min': this.getInitialMinDate()
            };
            
            this.plotInfo = {
                'downloads': {
                    'id': 'downloads',
                    'dataSource': new Timeplot.ColumnSource(this.dataSources['downloads'], 1),
                    'valueGeometry': new Timeplot.DefaultValueGeometry(this.valueGeometry['downloads']),
                    'showValues': true,
                    'dotColor': '#33AAFF',
                    'dotRadius': 3.0,
                    'lineColor': '#33AAFF',
                    'lineWidth': 3.0
                },
                'updatepings': {
                    'id': 'updatepings',
                    'dataSource': new Timeplot.ColumnSource(this.dataSources['updatepings'], 1),
                    'valueGeometry': new Timeplot.DefaultValueGeometry(this.valueGeometry['updatepings']),
                    'showValues': true,
                    'dotColor': '#EE3322',
                    'dotRadius': 3.0,
                    'lineColor': '#EE3322',
                    'lineWidth': 3.0
                }
            };
            
            this.plot();
            this.zoomLevel = 0;
            this.updateButtonVisibility();
        },
        
        plot: function() {
            var timeGeometry = new Timeplot.DefaultTimeGeometry(this.timeGeometry);
            
            this.plotInfo['downloads'].timeGeometry = timeGeometry;
            this.plotInfo['updatepings'].timeGeometry = timeGeometry;
            
            var plotInfo = [
                Timeplot.createPlotInfo(this.plotInfo['downloads']),
                Timeplot.createPlotInfo(this.plotInfo['updatepings'])
            ];
            
            Plots.newTimeplot();
            Plots.timeplot = Timeplot.create(document.getElementById(Plots.timeplot_id), plotInfo);
            Plots.timeplot.loadText(statsURL + 'csv/' + addonID + '/downloads', ",", this.dataSources['downloads']);
            Plots.timeplot.loadText(statsURL + 'csv/' + addonID + '/updatepings', ",", this.dataSources['updatepings']);
        },
        
        zoomIn: function() {
            this.zoomLevel++;
            this.updateButtonVisibility();
            
            var date = this.timeGeometry.min;
            var matches = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);
            
            if (matches[2] != 12)
                var newDate = matches[1] + '-' + this.leadingZero(parseInt(matches[2]) + 1) + '-01';
            else
                var newDate = (parseInt(matches[1]) + 1) + '-01-01'
            
            this.timeGeometry.min = newDate;
            
            this.plot();
        },
        
        zoomOut: function() {
            this.zoomLevel--;
            this.updateButtonVisibility();
            
            var date = this.timeGeometry.min;
            var matches = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);
            
            if (matches[2] != 1)
                var newDate = matches[1] + '-' + this.leadingZero(parseInt(matches[2]) - 1) + '-01';
            else
                var newDate = (parseInt(matches[1]) - 1) + '-12-01'
            
            this.timeGeometry.min = newDate;
            this.updateDotRadius();
            
            this.plot();
        },
        
        updateOptionsVisibility: function() {
            var plotType = plotSelection.dropdowns['plot-selector'].selectedItem.value;
            
            if (plotType == 'summary') {
                $('#weeks-legend').hide();
                $('#summary-legend').show();
                $('#summary-options').show();
                $('#group-by-selector').hide();
            }
            else {
                $('#weeks-legend').hide();
                $('#summary-legend').hide();
                $('#summary-options').hide();
                $('#group-by-selector').show();
            }
        },
        
        updateButtonVisibility: function() {
            if (this.zoomLevel >= 0)
                $('#zoom-in').addClass('disabled');
            else
                $('#zoom-in').removeClass('disabled');
        },
        
        updateDotRadius: function() {
            if (this.zoomLevel >= -1 && this.zoomLevel <= 1) {
                this.plotInfo['downloads'].dotRadius = 3.0;
                this.plotInfo['updatepings'].dotRadius = 3.0;
            }
            else if (this.zoomLevel >= -3 && this.zoomLevel <= 3) {
                this.plotInfo['downloads'].dotRadius = 2.0;
                this.plotInfo['updatepings'].dotRadius = 2.0;
            }
            else {
                this.plotInfo['downloads'].dotRadius = 1.0;
                this.plotInfo['updatepings'].dotRadius = 1.0;
            }
        },
        
        getInitialMinDate: function() {
            var currentTime = new Date();
            var year = currentTime.getFullYear();
            var month = currentTime.getMonth() + 1;
            var day = currentTime.getDate();
            
            if (day < 15) {
                if (month == 1) {
                    month = 12;
                    year--;
                }
                else
                    month--;
                day = 15;
            }
            else if (day >= 15) {
                day = 1;
            }
            
            var date = year + '-' + this.leadingZero(month) + '-' + this.leadingZero(day);
            
            return date;
            
        },
        
        leadingZero: function(number) {
            return (number < 10 ? '0' + number : number);
        }
    },
    
    defined: {
        dataSources: {},
        timeGeometry: {},
        valueGeometry: {},
        plotInfo: {},
        
        initialize: function() {
            var type = plotSelection.dropdowns['plot-selector'].selectedItem.value;
            Plots.currentCSV = statsURL + 'csv/' + addonID + '/' + type;

            // If there's a value for the group-by selector, add it as a
            // parameter to the CSV URL to invoke it server-side.
            var group_by = plotSelection.getGroupByValue();

            if ('week_over_week' == group_by) {
                if ('updatepings' == type || 'downloads' == type) {
                    $('#weeks-legend').show();
                    return this.plotWeekOverWeek();
                } else {
                    // HACK: Until I can figure out how to disable the Compare
                    // by: Week option for views not supported for it
                    group_by = 'week';
                }
            } 

            $('#weeks-legend').hide();
            if (group_by) Plots.currentCSV += '?group_by=' + group_by;

            this.dataSources = {
                'count': new Timeplot.DefaultEventSource(),
                'events-firefox': new Timeplot.DefaultEventSource(),
                'events-addon': new Timeplot.DefaultEventSource()
            };

            PlotsTables.addListeners('defined', this.dataSources);
            
            this.valueGeometry = {
                'gridColor': '#000000',
                'axisLabelsPlacement': 'left',
                'min': 0
            };
            
            var min = '2007-07-01';
            if (type == 'downloads' && plotSelection.summary.downloads.availableDates)
                min = plotSelection.summary.downloads.availableDates[0];
            else if (plotSelection.summary.updatepings.availableDates)
                min = plotSelection.summary.updatepings.availableDates[0];
            
            this.timeGeometry = {
                'gridColor': '#000000',
                'axisLabelsPlacement': 'top',
                'min': min
            };
            
            this.plotInfo = {
                'count': {
                    'id': 'count',
                    'dataSource': new Timeplot.ColumnSource(this.dataSources['count'], 1),
                    'showValues': true,
                    'dotColor': '#000000',
                    'lineColor': '#000000',
                    'fillColor': '#000000'
                },
                'events-firefox': {
                    'id': 'events-firefox',
                    'eventSource': this.dataSources['events-firefox'],
                    'lineColor': '#000000'
                },
                'events-addon': {
                    'id': 'events-addon',
                    'eventSource': this.dataSources['events-addon'],
                    'lineColor': '#000000'
                },
                'default': {
                    'showValues': true
                }
            };

            if (type == 'downloads' || type == 'updatepings') {
                if (type == 'downloads') {
                    var dark = '#3366CC';
                    var light = '#3399CC';
                }
                else if (type == 'updatepings') {
                    var dark = '#9966CC';
                    var light = '#CC99CC';
                }
                
                this.plotInfo['count'].fillColor = dark;
                this.plotInfo['count'].dotColor = null;
                this.plotInfo['count'].fillGradient = false;
                
                this.plotInfo['events-firefox'].lineColor = light;
                this.plotInfo['events-addon'].lineColor = light;
            }
            
            this.plot();
        },

        plot: function() {
            var timeGeometry = new Timeplot.DefaultTimeGeometry(this.timeGeometry);
            var valueGeometry = new Timeplot.DefaultValueGeometry(this.valueGeometry);
            
            this.plotInfo['count'].timeGeometry = timeGeometry;
            this.plotInfo['count'].valueGeometry = valueGeometry;
            this.plotInfo['events-firefox'].timeGeometry = timeGeometry;
            this.plotInfo['events-addon'].timeGeometry = timeGeometry;
            this.plotInfo['default'].timeGeometry = timeGeometry;
            this.plotInfo['default'].valueGeometry = valueGeometry;
            
            var plotInfo = [
                Timeplot.createPlotInfo(this.plotInfo['count']),
                Timeplot.createPlotInfo(this.plotInfo['events-firefox']),
                Timeplot.createPlotInfo(this.plotInfo['events-addon'])
            ];
            
            Plots.newTimeplot();
            Plots.timeplot = Timeplot.create(document.getElementById(Plots.timeplot_id), plotInfo);
            Plots.timeplot.loadText(Plots.currentCSV, ",", this.dataSources['count'], parseFields);
            Plots.timeplot.loadXML(statsURL + 'xml/events/firefox', this.dataSources['events-firefox']);
            Plots.timeplot.loadXML(statsURL + 'xml/events/addon/' + addonID, this.dataSources['events-addon']);
        },

        /**
         * Construct a plot consisting of 2 different weeks' data overlaid on
         * the same graph.
         */
        plotWeekOverWeek: function() {

            var type = plotSelection.dropdowns['plot-selector'].selectedItem.value;
            Plots.currentCSV = statsURL + 'csv/' + addonID + '/' + type;

            this.dataSources = {
                'count': new Timeplot.DefaultEventSource(),
            };

            PlotsTables.addListeners('week_over_week', this.dataSources);
            
            var date_parser = Timeline.NativeDateUnit.getParser('iso8601');

            // Collect Mondays from the set of available dates.
            var available_dates = plotSelection
                .summary[ (type=='downloads') ? 'downloads' : 'updatepings' ]
                .availableDates;
            var dates = [];
            var DAY_MONDAY = 1;
            for (idx in available_dates) {
                // The available dates data is a little weird - it's an object
                // with numerical properties, instead of an array.
                if (available_dates.hasOwnProperty(idx)) {
                    var date = date_parser(available_dates[idx]);
                    if (date.getDay() == DAY_MONDAY)
                        dates.push(available_dates[idx]);
                }
            }

            // Set up empty ranges set.
            var ranges = {
                week1: { min: '', max: '' },
                week2: { min: '', max: '' }
            };

            var WEEK = ( 1000 * 60 * 60 * 24 * 7 );

            if ( $('#weeks-legend .template').length ) {

                // The date selection dropdowns still contain unpopulated
                // templates, so set up the defaults and populate the dropdowns
                
                ranges['week2']['min'] = date_parser(dates[dates.length - 1]);
                ranges['week2']['max'] = new Date(ranges['week2']['min'].getTime() + WEEK);
                ranges['week1']['min'] = date_parser(dates[dates.length - 2]);
                ranges['week1']['max'] = new Date(ranges['week1']['min'].getTime() + WEEK);

                var weeks = ['week1', 'week2'];
                for (var i=0, week; week=weeks[i]; i++) {

                    // Convert the selection template into a concrete element
                    var tmpl = $('#'+week+'-selection select.template');
                    if (!tmpl.length) continue;
                    tmpl.remove().removeClass('template');

                    // Convert the current min date to string for comparison.
                    var min_str = ranges[week]['min'].strftime('%Y-%m-%d');

                    // Now populate the selection element with options cloned
                    // and populated from available dates.
                    var t_opt = tmpl.find('option').remove();
                    for (var j=0,date; date=dates[j]; j++) {
                        var opt = t_opt.clone();

                        var dp = date.split('-');
                        opt.text([dp[1], dp[2], dp[0]].join('/'))
                            .attr('value', date)
                            .appendTo(tmpl);

                        if (date == min_str)
                            opt.attr('selected', 'selected');
                    }

                    // Finally inject the populated selector into the DOM and
                    // wire up an onChange handler to reload the plot.
                    tmpl.appendTo('#'+week+'-selection')
                        .change(function() { Plots.determinePlot() });
                }

            } else {

                // The date selection dropdowns are populated, so set ranges
                // from the selected values.
                
                var weeks = ['week1', 'week2'];
                for (var i=0, week; week=weeks[i]; i++) {
                    var opt = $('#'+week+'-selection select')[0];
                    var date = opt.options[opt.selectedIndex].value;
                    ranges[week]['min'] = date_parser(date);
                    ranges[week]['max'] = new Date(ranges[week]['min'].getTime() + WEEK);
                }

            }

            // Assemble the time geometries from the selected time ranges.
            this.timeGeometries = {
                'week1': {
                    'min': ranges['week1']['min'],
                    'max': ranges['week1']['max'],
                    'gridColor': '#CC6666',
                    'axisLabelsPlacement': 'bottom'
                },
                'week2': {
                    'min': ranges['week2']['min'],
                    'max': ranges['week2']['max'],
                    'gridColor': '#6666CC',
                    'axisLabelsPlacement': 'top'
                }
            };

            // Both time ranges share the same value geometry
            this.valueGeometry = {
                'gridColor': '#000000',
                'axisLabelsPlacement': 'left',
                'min': 0
            };

            // Construct the plot info structures for each of the overlaid sets.
            Plots.newTimeplot();
            Plots.timeplot = Timeplot.create(document.getElementById(Plots.timeplot_id), [
                Timeplot.createPlotInfo({
                    'id': 'week1-plot',
                    'dataSource':    
                        new Timeplot.ColumnSource(this.dataSources['count'], 1),
                    'timeGeometry':  
                        new Timeplot.DefaultTimeGeometry(this.timeGeometries['week1']),
                    'valueGeometry': 
                        new Timeplot.DefaultValueGeometry(this.valueGeometry),
                    'showValues': true,
                    'dotColor':   '#CC6666',
                    'dotRadius':  3.0,
                    'lineColor':  '#CC6666',
                    'lineWidth':  3.0,
                    'fillColor':  false
                }),
                Timeplot.createPlotInfo({
                    'id': 'week2-plot',
                    'dataSource':    
                        new Timeplot.ColumnSource(this.dataSources['count'], 1),
                    'timeGeometry':  
                        new Timeplot.DefaultTimeGeometry(this.timeGeometries['week2']),
                    'valueGeometry': 
                        new Timeplot.DefaultValueGeometry(this.valueGeometry),
                    'showValues': true,
                    'dotColor':   '#6666CC',
                    'dotRadius':  3.0,
                    'lineColor':  '#6666CC',
                    'lineWidth':  3.0,
                    'fillColor':  false
                })
            ]);

            // Finally, queue up a load for the plot data.
            Plots.timeplot.loadText(
                Plots.currentCSV, 
                ",", 
                this.dataSources['count'], 
                parseFields
            );

        },
        
        addPlot: function(plotName, column, color) {
            if (plotName in this.plotInfo)
                var plotInfo = this.plotInfo[plotName];
            else {
                var plotInfo = this.plotInfo['default'];
                plotInfo.id = plotName;
                plotInfo.dataSource = new Timeplot.ColumnSource(this.dataSources['count'], column);
                plotInfo.dotColor = color;
                plotInfo.lineColor = color;
                plotInfo.fillColor = color;
            }
            
            return Plots.timeplot.addPlot(Timeplot.createPlotInfo(plotInfo), true);
        },
        
        addEventPlot: function(plotName) {
            return Plots.timeplot.addPlot(Timeplot.createPlotInfo(this.plotInfo[plotName]), true);
        },
        
        removePlot: function(plotName) {
            return Plots.timeplot.removePlot(plotName);
        }
    },
    
    customPlot: function() {
        plotSelection.addCustomDropdown();
    },
    
    resizePlot: function(newHeight) {
        $('#' + Plots.timeplot_id).height(newHeight);
        Plots.timeplot.repaint();
    }
};
    
function parseFields(data) {
    if (data != '') {
        var lineCount = (data.split("\n").length - 9);
        
        if (lineCount > 1) {
            // Enough data
            $('#not-enough-data').hide();
            
            var start = data.indexOf('Fields: [');
            var end = data.indexOf(']', start);
            var fields = data.substring(start + 9, end);
            
            var fieldArray = fields.split(';');
            
            Plots.availableFields = [];
            
            for (var i = 0; i < fieldArray.length; i++) {
                Plots.availableFields[i] = fieldArray[i];
            }
            
            plotSelection.addDefinedDropdowns();
        }
        else {
            // Not enough data
            $('#not-enough-data').show();
            
            if (Plots.timeplot_id != '') {
                $('#' + Plots.timeplot_id).remove();
                Plots.timeplot = null;
            }
        }
    }
    
    return data;
}