Relationship between A/B testing results are unclear
[WebKit-https.git] / Websites / perf.webkit.org / public / v2 / app.js
1 window.App = Ember.Application.create();
2
3 App.Router.map(function () {
4     this.resource('customDashboard', {path: 'dashboard/custom'});
5     this.resource('dashboard', {path: 'dashboard/:name'});
6     this.resource('charts', {path: 'charts'});
7     this.resource('analysis', {path: 'analysis'});
8     this.resource('analysisTask', {path: 'analysis/task/:taskId'});
9 });
10
11 App.DashboardRow = Ember.Object.extend({
12     header: null,
13     cells: [],
14
15     init: function ()
16     {
17         this._super();
18
19         var cellsInfo = this.get('cellsInfo') || [];
20         var columnCount = this.get('columnCount');
21         while (cellsInfo.length < columnCount)
22             cellsInfo.push([]);
23
24         this.set('cells', cellsInfo.map(this._createPane.bind(this)));
25     },
26     addPane: function (paneInfo)
27     {
28         var pane = this._createPane(paneInfo);
29         this.get('cells').pushObject(pane);
30         this.set('columnCount', this.get('columnCount') + 1);
31     },
32     _createPane: function (paneInfo)
33     {
34         if (!paneInfo || !paneInfo.length || (!paneInfo[0] && !paneInfo[1]))
35             paneInfo = null;
36
37         var pane = App.Pane.create({
38             store: this.get('store'),
39             platformId: paneInfo ? paneInfo[0] : null,
40             metricId: paneInfo ? paneInfo[1] : null,
41         });
42
43         return App.DashboardPaneProxyForPicker.create({content: pane});
44     },
45 });
46
47 App.DashboardPaneProxyForPicker = Ember.ObjectProxy.extend({
48     _platformOrMetricIdChanged: function ()
49     {
50         var self = this;
51         App.buildPopup(this.get('store'), 'choosePane', this)
52             .then(function (platforms) { self.set('pickerData', platforms); });
53     }.observes('platformId', 'metricId').on('init'),
54     paneList: function () {
55         return App.encodePrettifiedJSON([[this.get('platformId'), this.get('metricId'), null, null, false]]);
56     }.property('platformId', 'metricId'),
57 });
58
59 App.IndexRoute = Ember.Route.extend({
60     beforeModel: function ()
61     {
62         var self = this;
63         App.Manifest.fetch(this.store).then(function () {
64             self.transitionTo('dashboard', App.Manifest.defaultDashboardName());
65         });
66     },
67 });
68
69 App.DashboardRoute = Ember.Route.extend({
70     model: function (param)
71     {
72         return App.Manifest.fetch(this.store).then(function () {
73             return App.Manifest.dashboardByName(param.name);
74         });
75     },
76 });
77
78 App.CustomDashboardRoute = Ember.Route.extend({
79     controllerName: 'dashboard',
80     model: function (param)
81     {
82         return this.store.createRecord('dashboard', {serialized: param.grid});
83     },
84     renderTemplate: function()
85     {
86         this.render('dashboard');
87     }
88 });
89
90 App.DashboardController = Ember.Controller.extend({
91     queryParams: ['grid', 'numberOfDays'],
92     headerColumns: [],
93     rows: [],
94     numberOfDays: 7,
95     editMode: false,
96
97     modelChanged: function ()
98     {
99         var dashboard = this.get('model');
100         if (!dashboard)
101             return;
102
103         var headerColumns = dashboard.get('headerColumns');
104         this.set('headerColumns', headerColumns);
105         var columnCount = headerColumns.length;
106         this.set('columnCount', columnCount);
107
108         var store = this.store;
109         this.set('rows', dashboard.get('rows').map(function (rowParam) {
110             return App.DashboardRow.create({
111                 store: store,
112                 header: rowParam[0],
113                 cellsInfo: rowParam.slice(1),
114                 columnCount: columnCount,
115             })
116         }));
117
118         this.set('emptyRow', new Array(columnCount));
119     }.observes('model').on('init'),
120
121     computeGrid: function()
122     {
123         var headers = this.get('headerColumns').map(function (header) { return header.label; });
124         var table = [headers].concat(this.get('rows').map(function (row) {
125             return [row.get('header')].concat(row.get('cells').map(function (pane) {
126                 var platformAndMetric = [pane.get('platformId'), pane.get('metricId')];
127                 return platformAndMetric[0] || platformAndMetric[1] ? platformAndMetric : [];
128             }));
129         }));
130         return JSON.stringify(table);
131     },
132
133     _sharedDomainChanged: function ()
134     {
135         var numberOfDays = this.get('numberOfDays');
136         if (!numberOfDays)
137             return;
138
139         numberOfDays = parseInt(numberOfDays);
140         var present = Date.now();
141         var past = present - numberOfDays * 24 * 3600 * 1000;
142         this.set('since', past);
143         this.set('sharedDomain', [past, present]);
144     }.observes('numberOfDays').on('init'),
145
146     actions: {
147         setNumberOfDays: function (numberOfDays)
148         {
149             this.set('numberOfDays', numberOfDays);
150         },
151         choosePane: function (param)
152         {
153             var pane = param.position;
154             pane.set('platformId', param.platform.get('id'));
155             pane.set('metricId', param.metric.get('id'));
156         },
157         addColumn: function ()
158         {
159             this.get('headerColumns').pushObject({
160                 label: this.get('newColumnHeader'),
161                 index: this.get('headerColumns').length,
162             });
163             this.get('rows').forEach(function (row) {
164                 row.addPane();
165             });
166             this.set('newColumnHeader', null);
167         },
168         removeColumn: function (index)
169         {
170             this.get('headerColumns').removeAt(index);
171             this.get('rows').forEach(function (row) {
172                 row.get('cells').removeAt(index);
173             });
174         },
175         addRow: function ()
176         {
177             this.get('rows').pushObject(App.DashboardRow.create({
178                 store: this.store,
179                 header: this.get('newRowHeader'),
180                 columnCount: this.get('columnCount'),
181             }));
182             this.set('newRowHeader', null);
183         },
184         removeRow: function (row)
185         {
186             this.get('rows').removeObject(row);
187         },
188         resetPane: function (pane)
189         {
190             pane.set('platformId', null);
191             pane.set('metricId', null);
192         },
193         toggleEditMode: function ()
194         {
195             this.toggleProperty('editMode');
196             if (this.get('editMode'))
197                 this.transitionToRoute('dashboard', 'custom', {name: null, queryParams: {grid: this.computeGrid()}});
198             else
199                 this.set('grid', this.computeGrid());
200         },
201     },
202
203     init: function ()
204     {
205         this._super();
206         App.Manifest.fetch(this.get('store'));
207     }
208 });
209
210 App.NumberOfDaysControlView = Ember.View.extend({
211     classNames: ['controls'],
212     templateName: 'number-of-days-controls',
213     didInsertElement: function ()
214     {
215         this._matchingElements(this._previousNumberOfDaysClass).addClass('active');
216     },
217     _numberOfDaysChanged: function ()
218     {
219         this._matchingElements(this._previousNumberOfDaysClass).removeClass('active');
220
221         var newNumberOfDaysClass = 'numberOfDaysIs' + this.get('numberOfDays');
222         this._matchingElements(this._previousNumberOfDaysClass).addClass('active');
223         this._previousNumberOfDaysClass = newNumberOfDaysClass;
224     }.observes('numberOfDays').on('init'),
225     _matchingElements: function (className)
226     {
227         var element = this.get('element');
228         if (!element)
229             return $([]);
230         return $(element.getElementsByClassName(className));
231     }
232 });
233
234 App.StartTimeSliderView = Ember.View.extend({
235     templateName: 'start-time-slider',
236     classNames: ['start-time-slider'],
237     startTime: Date.now() - 7 * 24 * 3600 * 1000,
238     oldestStartTime: null,
239     _numberOfDaysView: null,
240     _slider: null,
241     _startTimeInSlider: null,
242     _currentNumberOfDays: null,
243     _MILLISECONDS_PER_DAY: 24 * 3600 * 1000,
244
245     didInsertElement: function ()
246     {
247         this.oldestStartTime = Date.now() - 365 * 24 * 3600 * 1000;
248         this._slider = $(this.get('element')).find('input');
249         this._numberOfDaysView = $(this.get('element')).find('.numberOfDays');
250         this._sliderRangeChanged();
251         this._slider.change(this._sliderMoved.bind(this));
252     },
253     _sliderRangeChanged: function ()
254     {
255         var minimumNumberOfDays = 1;
256         var maximumNumberOfDays = this._timeInPastToNumberOfDays(this.get('oldestStartTime'));
257         var precision = 1000; // FIXME: Compute this from maximumNumberOfDays.
258         var slider = this._slider;
259         slider.attr('min', Math.floor(Math.log(Math.max(1, minimumNumberOfDays)) * precision) / precision);
260         slider.attr('max', Math.ceil(Math.log(maximumNumberOfDays) * precision) / precision);
261         slider.attr('step', 1 / precision);
262         this._startTimeChanged();
263     }.observes('oldestStartTime'),
264     _sliderMoved: function ()
265     {
266         this._currentNumberOfDays = Math.round(Math.exp(this._slider.val()));
267         this._numberOfDaysView.text(this._currentNumberOfDays);
268         this._startTimeInSlider = this._numberOfDaysToTimeInPast(this._currentNumberOfDays);
269         this.set('startTime', this._startTimeInSlider);
270     },
271     _startTimeChanged: function ()
272     {
273         var startTime = this.get('startTime');
274         if (startTime == this._startTimeSetBySlider)
275             return;
276         this._currentNumberOfDays = this._timeInPastToNumberOfDays(startTime);
277
278         if (this._slider) {
279             this._numberOfDaysView.text(this._currentNumberOfDays);
280             this._slider.val(Math.log(this._currentNumberOfDays));
281             this._startTimeInSlider = startTime;
282         }
283     }.observes('startTime').on('init'),
284     _timeInPastToNumberOfDays: function (timeInPast)
285     {
286         return Math.max(1, Math.round((Date.now() - timeInPast) / this._MILLISECONDS_PER_DAY));
287     },
288     _numberOfDaysToTimeInPast: function (numberOfDays)
289     {
290         return Date.now() - numberOfDays * this._MILLISECONDS_PER_DAY;
291     },
292 });
293
294 App.Pane = Ember.Object.extend({
295     platformId: null,
296     platform: null,
297     metricId: null,
298     metric: null,
299     selectedItem: null,
300     selectedPoints: null,
301     hoveredOrSelectedItem: null,
302     showFullYAxis: false,
303     searchCommit: function (repository, keyword) {
304         var self = this;
305         var repositoryId = repository.get('id');
306         CommitLogs.fetchForTimeRange(repositoryId, null, null, keyword).then(function (commits) {
307             if (self.isDestroyed || !self.get('chartData') || !commits.length)
308                 return;
309             var currentRuns = self.get('chartData').current.series();
310             if (!currentRuns.length)
311                 return;
312
313             var highlightedItems = {};
314             var commitIndex = 0;
315             for (var runIndex = 0; runIndex < currentRuns.length && commitIndex < commits.length; runIndex++) {
316                 var measurement = currentRuns[runIndex].measurement;
317                 var commitTime = measurement.commitTimeForRepository(repositoryId);
318                 if (!commitTime)
319                     continue;
320                 if (commits[commitIndex].time <= commitTime) {
321                     highlightedItems[measurement.id()] = true;
322                     do {
323                         commitIndex++;
324                     } while (commitIndex < commits.length && commits[commitIndex].time <= commitTime);
325                 }
326             }
327
328             self.set('highlightedItems', highlightedItems);
329         }, function () {
330             // FIXME: Report errors
331             this.set('highlightedItems', {});
332         });
333     },
334     _fetch: function () {
335         var platformId = this.get('platformId');
336         var metricId = this.get('metricId');
337         if (!platformId && !metricId) {
338             this.set('empty', true);
339             return;
340         }
341         this.set('empty', false);
342         this.set('platform', null);
343         this.set('chartData', null);
344         this.set('metric', null);
345         this.set('failure', null);
346
347         if (!this._isValidId(platformId))
348             this.set('failure', platformId ? 'Invalid platform id:' + platformId : 'Platform id was not specified');
349         else if (!this._isValidId(metricId))
350             this.set('failure', metricId ? 'Invalid metric id:' + metricId : 'Metric id was not specified');
351         else {
352             var self = this;
353
354             App.Manifest.fetchRunsWithPlatformAndMetric(this.get('store'), platformId, metricId).then(function (result) {
355                 self.set('platform', result.platform);
356                 self.set('metric', result.metric);
357                 self.set('chartData', result.data);
358                 self._updateMovingAverageAndEnvelope();
359             }, function (result) {
360                 if (!result || typeof(result) === "string")
361                     self.set('failure', 'Failed to fetch the JSON with an error: ' + result);
362                 else if (!result.platform)
363                     self.set('failure', 'Could not find the platform "' + platformId + '"');
364                 else if (!result.metric)
365                     self.set('failure', 'Could not find the metric "' + metricId + '"');
366                 else
367                     self.set('failure', 'An internal error');
368             });
369
370             this.fetchAnalyticRanges();
371         }
372     }.observes('platformId', 'metricId').on('init'),
373     fetchAnalyticRanges: function ()
374     {
375         var platformId = this.get('platformId');
376         var metricId = this.get('metricId');
377         var self = this;
378         this.get('store')
379             .find('analysisTask', {platform: platformId, metric: metricId})
380             .then(function (tasks) {
381                 self.set('analyticRanges', tasks.filter(function (task) { return task.get('startRun') && task.get('endRun'); }));
382             });
383     },
384     _isValidId: function (id)
385     {
386         if (typeof(id) == "number")
387             return true;
388         if (typeof(id) == "string")
389             return !!id.match(/^[A-Za-z0-9_]+$/);
390         return false;
391     },
392     computeStatus: function (currentPoint, previousPoint)
393     {
394         var chartData = this.get('chartData');
395         var diffFromBaseline = this._relativeDifferentToLaterPointInTimeSeries(currentPoint, chartData.baseline);
396         var diffFromTarget = this._relativeDifferentToLaterPointInTimeSeries(currentPoint, chartData.target);
397
398         var label = '';
399         var className = '';
400         var formatter = d3.format('.3p');
401
402         var smallerIsBetter = chartData.smallerIsBetter;
403         if (diffFromBaseline !== undefined && diffFromBaseline > 0 == smallerIsBetter) {
404             label = formatter(Math.abs(diffFromBaseline)) + ' ' + (smallerIsBetter ? 'above' : 'below') + ' baseline';
405             className = 'worse';
406         } else if (diffFromTarget !== undefined && diffFromTarget < 0 == smallerIsBetter) {
407             label = formatter(Math.abs(diffFromTarget)) + ' ' + (smallerIsBetter ? 'below' : 'above') + ' target';
408             className = 'better';
409         } else if (diffFromTarget !== undefined)
410             label = formatter(Math.abs(diffFromTarget)) + ' until target';
411
412         var valueDelta = previousPoint ? chartData.deltaFormatter(currentPoint.value - previousPoint.value) : null;
413         return {className: className, label: label, currentValue: chartData.formatter(currentPoint.value), valueDelta: valueDelta};
414     },
415     _relativeDifferentToLaterPointInTimeSeries: function (currentPoint, timeSeries)
416     {
417         if (!currentPoint || !timeSeries)
418             return undefined;
419
420         var referencePoint = timeSeries.findPointAfterTime(currentPoint.time);
421         if (!referencePoint)
422             return undefined;
423
424         return (currentPoint.value - referencePoint.value) / referencePoint.value;
425     },
426     latestStatus: function ()
427     {
428         var chartData = this.get('chartData');
429         if (!chartData || !chartData.current)
430             return null;
431
432         var lastPoint = chartData.current.lastPoint();
433         if (!lastPoint)
434             return null;
435
436         return this.computeStatus(lastPoint, chartData.current.previousPoint(lastPoint));
437     }.property('chartData'),
438     updateStatisticsTools: function ()
439     {
440         var movingAverageStrategies = Statistics.MovingAverageStrategies.map(this._cloneStrategy.bind(this));
441         this.set('movingAverageStrategies', [{label: 'None'}].concat(movingAverageStrategies));
442         this.set('chosenMovingAverageStrategy', this._configureStrategy(movingAverageStrategies, this.get('movingAverageConfig')));
443
444         var envelopingStrategies = Statistics.EnvelopingStrategies.map(this._cloneStrategy.bind(this));
445         this.set('envelopingStrategies', [{label: 'None'}].concat(envelopingStrategies));
446         this.set('chosenEnvelopingStrategy', this._configureStrategy(envelopingStrategies, this.get('envelopingConfig')));
447     }.on('init'),
448     _cloneStrategy: function (strategy)
449     {
450         var parameterList = (strategy.parameterList || []).map(function (param) { return Ember.Object.create(param); });
451         return Ember.Object.create({
452             id: strategy.id,
453             label: strategy.label,
454             description: strategy.description,
455             parameterList: parameterList,
456             execute: strategy.execute,
457         });
458     },
459     _configureStrategy: function (strategies, config)
460     {
461         if (!config || !config[0])
462             return null;
463
464         var id = config[0];
465         var chosenStrategy = strategies.find(function (strategy) { return strategy.id == id });
466         if (!chosenStrategy)
467             return null;
468
469         if (chosenStrategy.parameterList) {
470             for (var i = 0; i < chosenStrategy.parameterList.length; i++)
471                 chosenStrategy.parameterList[i].value = parseFloat(config[i + 1]);
472         }
473
474         return chosenStrategy;
475     },
476     _updateMovingAverageAndEnvelope: function ()
477     {
478         var chartData = this.get('chartData');
479         if (!chartData)
480             return;
481
482         var movingAverageStrategy = this.get('chosenMovingAverageStrategy');
483         this._updateStrategyConfigIfNeeded(movingAverageStrategy, 'movingAverageConfig');
484
485         var envelopingStrategy = this.get('chosenEnvelopingStrategy');
486         this._updateStrategyConfigIfNeeded(envelopingStrategy, 'envelopingConfig');
487
488         chartData.movingAverage = this._computeMovingAverageAndOutliers(chartData, movingAverageStrategy, envelopingStrategy);
489     }.observes('chosenMovingAverageStrategy', 'chosenMovingAverageStrategy.parameterList.@each.value',
490         'chosenEnvelopingStrategy', 'chosenEnvelopingStrategy.parameterList.@each.value'),
491     _computeMovingAverageAndOutliers: function (chartData, movingAverageStrategy, envelopingStrategy)
492     {
493         var currentTimeSeriesData = chartData.current.series();
494         var movingAverageIsSetByUser = movingAverageStrategy && movingAverageStrategy.execute;
495         var movingAverageValues = this._executeStrategy(
496             movingAverageIsSetByUser ? movingAverageStrategy : Statistics.MovingAverageStrategies[0], currentTimeSeriesData);
497         if (!movingAverageValues)
498             return null;
499
500         var envelopeIsSetByUser = envelopingStrategy && envelopingStrategy.execute;
501         var envelopeDelta = this._executeStrategy(envelopeIsSetByUser ? envelopingStrategy : Statistics.EnvelopingStrategies[0],
502             currentTimeSeriesData, [movingAverageValues]);
503
504         for (var i = 0; i < currentTimeSeriesData.length; i++) {
505             var currentValue = currentTimeSeriesData[i].value;
506             var movingAverageValue = movingAverageValues[i];
507             if (currentValue < movingAverageValue - envelopeDelta || movingAverageValue + envelopeDelta < currentValue)
508                 currentTimeSeriesData[i].isOutlier = true;
509         }
510         if (!envelopeIsSetByUser)
511             envelopeDelta = null;
512
513         if (movingAverageIsSetByUser) {
514             return new TimeSeries(currentTimeSeriesData.map(function (point, index) {
515                 var value = movingAverageValues[index];
516                 return {
517                     measurement: point.measurement,
518                     time: point.time,
519                     value: value,
520                     interval: envelopeDelta !== null ? [value - envelopeDelta, value + envelopeDelta] : null,
521                 }
522             }));            
523         }
524     },
525     _executeStrategy: function (strategy, currentTimeSeriesData, additionalArguments)
526     {
527         var parameters = (strategy.parameterList || []).map(function (param) {
528             var parsed = parseFloat(param.value);
529             return Math.min(param.max || Infinity, Math.max(param.min || -Infinity, isNaN(parsed) ? 0 : parsed));
530         });
531         parameters.push(currentTimeSeriesData.map(function (point) { return point.value }));
532         return strategy.execute.apply(window, parameters.concat(additionalArguments));
533     },
534     _updateStrategyConfigIfNeeded: function (strategy, configName)
535     {
536         var config = null;
537         if (strategy && strategy.execute)
538             config = [strategy.id].concat((strategy.parameterList || []).map(function (param) { return param.value; }));
539
540         if (JSON.stringify(config) != JSON.stringify(this.get(configName)))
541             this.set(configName, config);
542     },
543     _updateDetails: function ()
544     {
545         var selectedPoints = this.get('selectedPoints');
546         var currentPoint = this.get('hoveredOrSelectedItem');
547         if (!selectedPoints && !currentPoint) {
548             this.set('details', null);
549             return;
550         }
551
552         var currentMeasurement;
553         var previousPoint;
554         if (!selectedPoints)
555             previousPoint = currentPoint.series.previousPoint(currentPoint);
556         else {
557             currentPoint = selectedPoints[selectedPoints.length - 1];
558             previousPoint = selectedPoints[0];
559         }
560         var currentMeasurement = currentPoint.measurement;
561         var oldMeasurement = previousPoint ? previousPoint.measurement : null;
562
563         var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
564         var revisions = App.Manifest.get('repositories')
565             .filter(function (repository) { return formattedRevisions[repository.get('id')]; })
566             .map(function (repository) {
567             var revision = Ember.Object.create(formattedRevisions[repository.get('id')]);
568             revision['url'] = revision.previousRevision
569                 ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
570                 : repository.urlForRevision(revision.currentRevision);
571             revision['name'] = repository.get('name');
572             revision['repository'] = repository;
573             return revision; 
574         });
575
576         var buildNumber = null;
577         var buildURL = null;
578         if (!selectedPoints) {
579             buildNumber = currentMeasurement.buildNumber();
580             var builder = App.Manifest.builder(currentMeasurement.builderId());
581             if (builder)
582                 buildURL = builder.urlFromBuildNumber(buildNumber);
583         }
584
585         this.set('details', Ember.Object.create({
586             status: this.computeStatus(currentPoint, previousPoint),
587             buildNumber: buildNumber,
588             buildURL: buildURL,
589             buildTime: currentMeasurement.formattedBuildTime(),
590             revisions: revisions,
591         }));
592     }.observes('hoveredOrSelectedItem', 'selectedPoints'),
593 });
594
595 App.encodePrettifiedJSON = function (plain)
596 {
597     function numberIfPossible(string) {
598         return string == parseInt(string) ? parseInt(string) : string;
599     }
600
601     function recursivelyConvertNumberIfPossible(input) {
602         if (input instanceof Array) {
603             return input.map(recursivelyConvertNumberIfPossible);
604         }
605         return numberIfPossible(input);
606     }
607
608     return JSON.stringify(recursivelyConvertNumberIfPossible(plain))
609         .replace(/\[/g, '(').replace(/\]/g, ')').replace(/\,/g, '-');
610 }
611
612 App.decodePrettifiedJSON = function (encoded)
613 {
614     var parsed = encoded.replace(/\(/g, '[').replace(/\)/g, ']').replace(/\-/g, ',');
615     try {
616         return JSON.parse(parsed);
617     } catch (exception) {
618         return null;
619     }
620 }
621
622 App.ChartsController = Ember.Controller.extend({
623     queryParams: ['paneList', 'zoom', 'since'],
624     needs: ['pane'],
625     _currentEncodedPaneList: null,
626     panes: [],
627     platforms: null,
628     sharedZoom: null,
629     startTime: null,
630     present: Date.now(),
631     defaultSince: Date.now() - 7 * 24 * 3600 * 1000,
632
633     addPane: function (pane)
634     {
635         this.panes.unshiftObject(pane);
636     },
637
638     removePane: function (pane)
639     {
640         this.panes.removeObject(pane);
641     },
642
643     refreshPanes: function()
644     {
645         var paneList = this.get('paneList');
646         if (paneList === this._currentEncodedPaneList)
647             return;
648
649         var panes = this._parsePaneList(paneList || '[]');
650         if (!panes) {
651             console.log('Failed to parse', jsonPaneList, exception);
652             return;
653         }
654         this.set('panes', panes);
655         this._currentEncodedPaneList = paneList;
656     }.observes('paneList').on('init'),
657
658     refreshZoom: function()
659     {
660         var zoom = this.get('zoom');
661         if (!zoom) {
662             this.set('sharedZoom', null);
663             return;
664         }
665
666         zoom = zoom.split('-');
667         var selection = new Array(2);
668         try {
669             selection[0] = new Date(parseFloat(zoom[0]));
670             selection[1] = new Date(parseFloat(zoom[1]));
671         } catch (error) {
672             console.log('Failed to parse the zoom', zoom);
673         }
674         this.set('sharedZoom', selection);
675
676         var startTime = this.get('startTime');
677         if (startTime && startTime > selection[0])
678             this.set('startTime', selection[0]);
679
680     }.observes('zoom').on('init'),
681
682     _startTimeChanged: function () {
683         this.set('sharedDomain', [this.get('startTime'), this.get('present')]);
684         this._scheduleQueryStringUpdate();
685     }.observes('startTime'),
686
687     _sinceChanged: function () {
688         var since = parseInt(this.get('since'));
689         if (isNaN(since))
690             since = this.defaultSince;
691         this.set('startTime', new Date(since));
692     }.observes('since').on('init'),
693
694     _parsePaneList: function (encodedPaneList)
695     {
696         var parsedPaneList = App.decodePrettifiedJSON(encodedPaneList);
697         if (!parsedPaneList)
698             return null;
699
700         // FIXME: Don't re-create all panes.
701         var self = this;
702         return parsedPaneList.map(function (paneInfo) {
703             var timeRange = null;
704             var selectedItem = null;
705             if (paneInfo[2] instanceof Array) {
706                 var timeRange = paneInfo[2];
707                 try {
708                     timeRange = [new Date(timeRange[0]), new Date(timeRange[1])];
709                 } catch (error) {
710                     console.log("Failed to parse the time range:", timeRange, error);
711                 }
712             } else
713                 selectedItem = paneInfo[2];
714
715             return App.Pane.create({
716                 store: self.store,
717                 info: paneInfo,
718                 platformId: paneInfo[0],
719                 metricId: paneInfo[1],
720                 selectedItem: selectedItem,
721                 timeRange: timeRange,
722                 showFullYAxis: paneInfo[3],
723                 movingAverageConfig: paneInfo[4],
724                 envelopingConfig: paneInfo[5],
725             });
726         });
727     },
728
729     _serializePaneList: function (panes)
730     {
731         if (!panes.length)
732             return undefined;
733         var self = this;
734         return App.encodePrettifiedJSON(panes.map(function (pane) {
735             return [
736                 pane.get('platformId'),
737                 pane.get('metricId'),
738                 pane.get('timeRange') ? pane.get('timeRange').map(function (date) { return date.getTime() }) : pane.get('selectedItem'),
739                 pane.get('showFullYAxis'),
740                 pane.get('movingAverageConfig'),
741                 pane.get('envelopingConfig'),
742             ];
743         }));
744     },
745
746     _scheduleQueryStringUpdate: function ()
747     {
748         Ember.run.debounce(this, '_updateQueryString', 1000);
749     }.observes('sharedZoom', 'panes.@each.platform', 'panes.@each.metric', 'panes.@each.selectedItem', 'panes.@each.timeRange',
750         'panes.@each.showFullYAxis', 'panes.@each.movingAverageConfig', 'panes.@each.envelopingConfig'),
751
752     _updateQueryString: function ()
753     {
754         this._currentEncodedPaneList = this._serializePaneList(this.get('panes'));
755         this.set('paneList', this._currentEncodedPaneList);
756
757         var zoom = undefined;
758         var sharedZoom = this.get('sharedZoom');
759         if (sharedZoom && !App.domainsAreEqual(sharedZoom, this.get('sharedDomain')))
760             zoom = +sharedZoom[0] + '-' + +sharedZoom[1];
761         this.set('zoom', zoom);
762
763         if (this.get('startTime') - this.defaultSince)
764             this.set('since', this.get('startTime') - 0);
765     },
766
767     actions: {
768         addPaneByMetricAndPlatform: function (param)
769         {
770             this.addPane(App.Pane.create({
771                 store: this.store,
772                 platformId: param.platform.get('id'),
773                 metricId: param.metric.get('id'),
774                 showingDetails: false
775             }));
776         },
777     },
778
779     init: function ()
780     {
781         this._super();
782         var self = this;
783         App.buildPopup(this.store, 'addPaneByMetricAndPlatform').then(function (platforms) {
784             self.set('platforms', platforms);
785         });
786     },
787 });
788
789 App.buildPopup = function(store, action, position)
790 {
791     return App.Manifest.fetch(store).then(function () {
792         return App.Manifest.get('platforms').map(function (platform) {
793             return App.PlatformProxyForPopup.create({content: platform,
794                 action: action, position: position});
795         });
796     });
797 }
798
799 App.PlatformProxyForPopup = Ember.ObjectProxy.extend({
800     children: function ()
801     {
802         var platform = this.content;
803         var containsTest = this.content.containsTest.bind(this.content);
804         var action = this.get('action');
805         var position = this.get('position');
806         return App.Manifest.get('topLevelTests')
807             .filter(containsTest)
808             .map(function (test) {
809                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
810             });
811     }.property('App.Manifest.topLevelTests'),
812 });
813
814 App.TestProxyForPopup = Ember.ObjectProxy.extend({
815     platform: null,
816     children: function ()
817     {
818         var platform = this.get('platform');
819         var action = this.get('action');
820         var position = this.get('position');
821
822         var childTests = this.get('childTests')
823             .filter(function (test) { return platform.containsTest(test); })
824             .map(function (test) {
825                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
826             });
827
828         var metrics = this.get('metrics')
829             .filter(function (metric) { return platform.containsMetric(metric); })
830             .map(function (metric) {
831                 var aggregator = metric.get('aggregator');
832                 return {
833                     actionName: action,
834                     actionArgument: {platform: platform, metric: metric, position:position},
835                     label: metric.get('label')
836                 };
837             });
838
839         if (childTests.length && metrics.length)
840             metrics.push({isSeparator: true});
841
842         return metrics.concat(childTests);
843     }.property('childTests', 'metrics'),
844 });
845
846 App.domainsAreEqual = function (domain1, domain2) {
847     return (!domain1 && !domain2) || (domain1 && domain2 && !(domain1[0] - domain2[0]) && !(domain1[1] - domain2[1]));
848 }
849
850 App.PaneController = Ember.ObjectController.extend({
851     needs: ['charts'],
852     sharedTime: Ember.computed.alias('parentController.sharedTime'),
853     sharedSelection: Ember.computed.alias('parentController.sharedSelection'),
854     selection: null,
855     actions: {
856         toggleDetails: function()
857         {
858             this.toggleProperty('showingDetails');
859         },
860         close: function ()
861         {
862             this.parentController.removePane(this.get('model'));
863         },
864         toggleBugsPane: function ()
865         {
866             if (this.toggleProperty('showingAnalysisPane')) {
867                 this.set('showingSearchPane', false);
868                 this.set('showingStatPane', false);
869             }
870         },
871         createAnalysisTask: function ()
872         {
873             var name = this.get('newAnalysisTaskName');
874             var points = this.get('selectedPoints');
875             Ember.assert('The analysis name should not be empty', name);
876             Ember.assert('There should be at least two points in the range', points && points.length >= 2);
877
878             var newWindow = window.open();
879             var self = this;
880             App.AnalysisTask.create(name, points[0].measurement, points[points.length - 1].measurement).then(function (data) {
881                 // FIXME: Update the UI to show the new analysis task.
882                 var url = App.Router.router.generate('analysisTask', data['taskId']);
883                 newWindow.location.href = '#' + url;
884                 self.get('model').fetchAnalyticRanges();
885             }, function (error) {
886                 newWindow.close();
887                 if (error === 'DuplicateAnalysisTask') {
888                     // FIXME: Duplicate this error more gracefully.
889                 }
890                 alert(error);
891             });
892         },
893         toggleSearchPane: function ()
894         {
895             if (!App.Manifest.repositoriesWithReportedCommits)
896                 return;
897             var model = this.get('model');
898             if (!model.get('commitSearchRepository'))
899                 model.set('commitSearchRepository', App.Manifest.repositoriesWithReportedCommits[0]);
900             if (this.toggleProperty('showingSearchPane')) {
901                 this.set('showingAnalysisPane', false);
902                 this.set('showingStatPane', false);
903             }
904         },
905         searchCommit: function () {
906             var model = this.get('model');
907             model.searchCommit(model.get('commitSearchRepository'), model.get('commitSearchKeyword'));                
908         },
909         toggleStatPane: function ()
910         {
911             if (this.toggleProperty('showingStatPane')) {
912                 this.set('showingSearchPane', false);
913                 this.set('showingAnalysisPane', false);
914             }
915         },
916         zoomed: function (selection)
917         {
918             this.set('mainPlotDomain', selection ? selection : this.get('overviewDomain'));
919             Ember.run.debounce(this, 'propagateZoom', 100);
920         },
921     },
922     _detailsChanged: function ()
923     {
924         this.set('showingAnalysisPane', false);
925     }.observes('details'),
926     _overviewSelectionChanged: function ()
927     {
928         var overviewSelection = this.get('overviewSelection');
929         if (App.domainsAreEqual(overviewSelection, this.get('mainPlotDomain')))
930             return;
931         this.set('mainPlotDomain', overviewSelection || this.get('overviewDomain'));
932         Ember.run.debounce(this, 'propagateZoom', 100);
933     }.observes('overviewSelection'),
934     _sharedDomainChanged: function ()
935     {
936         var newDomain = this.get('parentController').get('sharedDomain');
937         if (App.domainsAreEqual(newDomain, this.get('overviewDomain')))
938             return;
939         this.set('overviewDomain', newDomain);
940         if (!this.get('overviewSelection'))
941             this.set('mainPlotDomain', newDomain);
942     }.observes('parentController.sharedDomain').on('init'),
943     propagateZoom: function ()
944     {
945         this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
946     },
947     _sharedZoomChanged: function ()
948     {
949         var newSelection = this.get('parentController').get('sharedZoom');
950         if (App.domainsAreEqual(newSelection, this.get('mainPlotDomain')))
951             return;
952         this.set('mainPlotDomain', newSelection || this.get('overviewDomain'));
953         this.set('overviewSelection', newSelection);
954     }.observes('parentController.sharedZoom').on('init'),
955     _updateCanAnalyze: function ()
956     {
957         var points = this.get('model').get('selectedPoints');
958         this.set('cannotAnalyze', !this.get('newAnalysisTaskName') || !points || points.length < 2);
959     }.observes('newAnalysisTaskName', 'model.selectedPoints'),
960 });
961
962 App.AnalysisRoute = Ember.Route.extend({
963     model: function () {
964         return this.store.findAll('analysisTask').then(function (tasks) {
965             return Ember.Object.create({'tasks': tasks});
966         });
967     },
968 });
969
970 App.AnalysisTaskRoute = Ember.Route.extend({
971     model: function (param)
972     {
973         return this.store.find('analysisTask', param.taskId);
974     },
975 });
976
977 App.AnalysisTaskController = Ember.Controller.extend({
978     label: Ember.computed.alias('model.name'),
979     platform: Ember.computed.alias('model.platform'),
980     metric: Ember.computed.alias('model.metric'),
981     details: Ember.computed.alias('pane.details'),
982     testSets: [],
983     roots: [],
984     bugTrackers: [],
985     possibleRepetitionCounts: [1, 2, 3, 4, 5, 6],
986     _taskUpdated: function ()
987     {
988         var model = this.get('model');
989         if (!model)
990             return;
991
992         App.Manifest.fetch(this.store).then(this._fetchedManifest.bind(this));
993         this.set('pane', App.Pane.create({
994             store: this.store,
995             platformId: model.get('platform').get('id'),
996             metricId: model.get('metric').get('id'),
997         }));
998     }.observes('model').on('init'),
999     _fetchedManifest: function ()
1000     {
1001         var trackerIdToBugNumber = {};
1002         this.get('model').get('bugs').forEach(function (bug) {
1003             trackerIdToBugNumber[bug.get('bugTracker').get('id')] = bug.get('number');
1004         });
1005
1006         this.set('bugTrackers', App.Manifest.get('bugTrackers').map(function (bugTracker) {
1007             var bugNumber = trackerIdToBugNumber[bugTracker.get('id')];
1008             return Ember.ObjectProxy.create({
1009                 content: bugTracker,
1010                 bugNumber: bugNumber,
1011                 editedBugNumber: bugNumber,
1012             });
1013         }));
1014     },
1015     paneDomain: function ()
1016     {
1017         var pane = this.get('pane');
1018         if (!pane)
1019             return;
1020
1021         var chartData = pane.get('chartData');
1022         if (!chartData)
1023             return null;
1024
1025         var currentTimeSeries = chartData.current;
1026         if (!currentTimeSeries)
1027             return null; // FIXME: Report an error.
1028
1029         var start = currentTimeSeries.findPointByMeasurementId(this.get('model').get('startRun'));
1030         var end = currentTimeSeries.findPointByMeasurementId(this.get('model').get('endRun'));
1031         if (!start || !end)
1032             return null; // FIXME: Report an error.
1033
1034         var highlightedItems = {};
1035         highlightedItems[start.measurement.id()] = true;
1036         highlightedItems[end.measurement.id()] = true;
1037
1038         var formatedPoints = currentTimeSeries.seriesBetweenPoints(start, end).map(function (point, index) {
1039             return {
1040                 id: point.measurement.id(),
1041                 measurement: point.measurement,
1042                 label: 'Point ' + (index + 1),
1043                 value: chartData.formatWithUnit(point.value),
1044             };
1045         });
1046
1047         var margin = (end.time - start.time) * 0.1;
1048         this.set('highlightedItems', highlightedItems);
1049         this.set('analysisPoints', formatedPoints);
1050
1051         var paneDomain = [start.time - margin, +end.time + margin];
1052
1053         var testGroupPanes = this.get('testGroupPanes');
1054         if (testGroupPanes) {
1055             testGroupPanes.setEach('overviewPane', pane);
1056             testGroupPanes.setEach('overviewDomain', paneDomain);
1057         }
1058
1059         return paneDomain;
1060     }.property('pane.chartData'),
1061     testSets: function ()
1062     {
1063         var analysisPoints = this.get('analysisPoints');
1064         if (!analysisPoints)
1065             return;
1066         var pointOptions = [{value: ' ', label: 'None'}]
1067             .concat(analysisPoints.map(function (point) { return {value: point.id, label: point.label}; }));
1068         return [
1069             Ember.Object.create({name: "A", options: pointOptions, selection: pointOptions[1]}),
1070             Ember.Object.create({name: "B", options: pointOptions, selection: pointOptions[pointOptions.length - 1]}),
1071         ];
1072     }.property('analysisPoints'),
1073     _rootChangedForTestSet: function ()
1074     {
1075         var sets = this.get('testSets');
1076         var roots = this.get('roots');
1077         if (!sets || !roots)
1078             return;
1079
1080         sets.forEach(function (testSet, setIndex) {
1081             var currentSelection = testSet.get('selection');
1082             if (currentSelection == testSet.get('previousSelection'))
1083                 return;
1084             testSet.set('previousSelection', currentSelection);
1085             var pointIndex = testSet.get('options').indexOf(currentSelection);
1086
1087             roots.forEach(function (root) {
1088                 var set = root.sets[setIndex];
1089                 set.set('selection', set.revisions[pointIndex]);
1090             });
1091         });
1092
1093     }.observes('testSets.@each.selection'),
1094     updateRoots: function ()
1095     {
1096         var analysisPoints = this.get('analysisPoints');
1097         if (!analysisPoints)
1098             return;
1099         var repositoryToRevisions = {};
1100         analysisPoints.forEach(function (point, pointIndex) {
1101             var revisions = point.measurement.formattedRevisions();
1102             for (var repositoryId in revisions) {
1103                 if (!repositoryToRevisions[repositoryId])
1104                     repositoryToRevisions[repositoryId] = new Array(analysisPoints.length);
1105                 var revision = revisions[repositoryId];
1106                 repositoryToRevisions[repositoryId][pointIndex] = {
1107                     label: point.label + ': ' + revision.label,
1108                     value: revision.currentRevision,
1109                 };
1110             }
1111         });
1112
1113         var self = this;
1114         this.get('model').get('triggerable').then(function (triggerable) {
1115             if (!triggerable)
1116                 return;
1117
1118             self.set('roots', triggerable.get('acceptedRepositories').map(function (repository) {
1119                 var repositoryId = repository.get('id');
1120                 var revisions = [{value: ' ', label: 'None'}].concat(repositoryToRevisions[repositoryId]);
1121                 return Ember.Object.create({
1122                     name: repository.get('name'),
1123                     sets: [
1124                         Ember.Object.create({name: 'A[' + repositoryId + ']',
1125                             revisions: revisions,
1126                             selection: revisions[1]}),
1127                         Ember.Object.create({name: 'B[' + repositoryId + ']',
1128                             revisions: revisions,
1129                             selection: revisions[revisions.length - 1]}),
1130                     ],
1131                 });
1132             }));
1133         });
1134     }.observes('analysisPoints'),
1135     updateTestGroupPanes: function ()
1136     {
1137         var model = this.get('model');
1138         if (!model)
1139             return;
1140         var self = this;
1141         model.get('testGroups').then(function (groups) {
1142             self.set('testGroupPanes', groups.map(function (group) { return App.TestGroupPane.create({content: group}); }));
1143         });
1144     }.observes('model'),
1145     actions: {
1146         associateBug: function (bugTracker, bugNumber)
1147         {
1148             var model = this.get('model');
1149             this.store.createRecord('bug',
1150                 {task: this.get('model'), bugTracker: bugTracker.get('content'), number: bugNumber}).save().then(function () {
1151                     // FIXME: Should we notify the user?
1152                 }, function (error) {
1153                     alert('Failed to associate the bug: ' + error);
1154                 });
1155         },
1156         createTestGroup: function (name, repetitionCount)
1157         {
1158             var roots = {};
1159             this.get('roots').map(function (root) {
1160                 roots[root.get('name')] = root.get('sets').map(function (item) { return item.get('selection').value; });
1161             });
1162             App.TestGroup.create(this.get('model'), name, roots, repetitionCount).then(function () {
1163                 
1164             });
1165         },
1166         toggleShowRequestList: function (configuration)
1167         {
1168             configuration.toggleProperty('showRequestList');
1169         }
1170     },
1171 });
1172
1173 App.TestGroupPane = Ember.ObjectProxy.extend({
1174     _populate: function ()
1175     {
1176         var buildRequests = this.get('buildRequests');
1177         var testResults = this.get('testResults');
1178         if (!buildRequests || !testResults)
1179             return [];
1180
1181         var repositories = this._computeRepositoryList();
1182         this.set('repositories', repositories);
1183
1184         var requestsByRooSet = this._groupRequestsByConfigurations(buildRequests);
1185
1186         var configurations = [];
1187         var index = 0;
1188         var range = {min: Infinity, max: -Infinity};
1189         for (var rootSetId in requestsByRooSet) {
1190             var configLetter = String.fromCharCode('A'.charCodeAt(0) + index++);
1191             configurations.push(this._createConfigurationSummary(requestsByRooSet[rootSetId], configLetter, range));
1192         }
1193
1194         var margin = 0.1 * (range.max - range.min);
1195         range.max += margin;
1196         range.min -= margin;
1197
1198         this.set('configurations', configurations);
1199     }.observes('testResults', 'buildRequests'),
1200     _updateReferenceChart: function ()
1201     {
1202         var configurations = this.get('configurations');
1203         var chartData = this.get('overviewPane') ? this.get('overviewPane').get('chartData') : null;
1204         if (!configurations || !chartData || this.get('referenceChart'))
1205             return;
1206
1207         var currentTimeSeries = chartData.current;
1208         if (!currentTimeSeries)
1209             return;
1210
1211         var repositories = this.get('repositories');
1212         var highlightedItems = {};
1213         var failedToFindPoint = false;
1214         configurations.forEach(function (config) {
1215             var revisions = {};
1216             config.get('rootSet').get('roots').forEach(function (root) {
1217                 revisions[root.get('repository').get('id')] = root.get('revision');
1218             });
1219             var point = currentTimeSeries.findPointByRevisions(revisions);
1220             if (!point) {
1221                 failedToFindPoint = true;
1222                 return;
1223             }
1224             highlightedItems[point.measurement.id()] = true;
1225         });
1226         if (failedToFindPoint)
1227             return;
1228
1229         this.set('referenceChart', {
1230             data: chartData,
1231             highlightedItems: highlightedItems,
1232         });
1233     }.observes('configurations', 'overviewPane.chartData'),
1234     _computeRepositoryList: function ()
1235     {
1236         var specifiedRepositories = new Ember.Set();
1237         (this.get('rootSets') || []).forEach(function (rootSet) {
1238             (rootSet.get('roots') || []).forEach(function (root) {
1239                 specifiedRepositories.add(root.get('repository'));
1240             });
1241         });
1242         var reportedRepositories = new Ember.Set();
1243         var testResults = this.get('testResults');
1244         (this.get('buildRequests') || []).forEach(function (request) {
1245             var point = testResults.current.findPointByBuild(request.get('build'));
1246             if (!point)
1247                 return;
1248
1249             var revisionByRepositoryId = point.measurement.formattedRevisions();
1250             for (var repositoryId in revisionByRepositoryId) {
1251                 var repository = App.Manifest.repository(repositoryId);
1252                 if (!specifiedRepositories.contains(repository))
1253                     reportedRepositories.add(repository);
1254             }
1255         });
1256         return specifiedRepositories.sortBy('name').concat(reportedRepositories.sortBy('name'));
1257     },
1258     _groupRequestsByConfigurations: function (requests, repositoryList)
1259     {
1260         var rootSetIdToRequests = {};
1261         var testGroup = this;
1262         requests.forEach(function (request) {
1263             var rootSetId = request.get('rootSet').get('id');
1264             if (!rootSetIdToRequests[rootSetId])
1265                 rootSetIdToRequests[rootSetId] = [];
1266             rootSetIdToRequests[rootSetId].push(request);
1267         });
1268         return rootSetIdToRequests;
1269     },
1270     _createConfigurationSummary: function (buildRequests, configLetter, range)
1271     {
1272         var repositories = this.get('repositories');
1273         var testResults = this.get('testResults');
1274         var requests = buildRequests.map(function (originalRequest) {
1275             var point = testResults.current.findPointByBuild(originalRequest.get('build'));
1276             var revisionByRepositoryId = point ? point.measurement.formattedRevisions() : {};
1277             return Ember.ObjectProxy.create({
1278                 content: originalRequest,
1279                 revisionList: repositories.map(function (repository, index) {
1280                     return (revisionByRepositoryId[repository.get('id')] || {label:null}).label;
1281                 }),
1282                 value: point ? point.value : null,
1283                 valueRange: range,
1284                 formattedValue: point ? testResults.formatWithUnit(point.value) : null,
1285                 buildLabel: point ? 'Build ' + point.measurement.buildNumber() : null,
1286             });
1287         });
1288
1289         var rootSet = requests ? requests[0].get('rootSet') : null;
1290         var summaryRevisions = repositories.map(function (repository, index) {
1291             var revision = rootSet ? rootSet.revisionForRepository(repository) : null;
1292             if (!revision)
1293                 return requests[0].get('revisionList')[index];
1294             return Measurement.formatRevisionRange(revision).label;
1295         });
1296
1297         requests.forEach(function (request) {
1298             var revisionList = request.get('revisionList');
1299             repositories.forEach(function (repository, index) {
1300                 if (revisionList[index] == summaryRevisions[index])
1301                     revisionList[index] = null;
1302             });
1303         });
1304
1305         var valuesInConfig = requests.mapBy('value').filter(function (value) { return typeof(value) === 'number' && !isNaN(value); });
1306         var sum = Statistics.sum(valuesInConfig);
1307         var ciDelta = Statistics.confidenceIntervalDelta(0.95, valuesInConfig.length, sum, Statistics.squareSum(valuesInConfig));
1308         var mean = sum / valuesInConfig.length;
1309
1310         range.min = Math.min(range.min, Statistics.min(valuesInConfig));
1311         range.max = Math.max(range.max, Statistics.max(valuesInConfig));
1312         if (ciDelta && !isNaN(ciDelta)) {
1313             range.min = Math.min(range.min, mean - ciDelta);
1314             range.max = Math.max(range.max, mean + ciDelta);
1315         }
1316
1317         var summary = Ember.Object.create({
1318             isAverage: true,
1319             configLetter: configLetter,
1320             revisionList: summaryRevisions,
1321             formattedValue: isNaN(mean) ? null : testResults.formatWithDeltaAndUnit(mean, ciDelta),
1322             value: mean,
1323             confidenceIntervalDelta: ciDelta,
1324             valueRange: range,
1325             statusLabel: App.BuildRequest.aggregateStatuses(requests),
1326         });
1327
1328         return Ember.Object.create({summary: summary, items: requests, rootSet: rootSet});
1329     },
1330 });
1331
1332 App.BoxPlotComponent = Ember.Component.extend({
1333     classNames: ['box-plot'],
1334     range: null,
1335     value: null,
1336     delta: null,
1337     didInsertElement: function ()
1338     {
1339         var element = this.get('element');
1340         var svg = d3.select(element).append('svg')
1341             .attr('viewBox', '0 0 100 20')
1342             .attr('preserveAspectRatio', 'none')
1343             .style({width: '100%', height: '100%'});
1344
1345         this._percentageRect = svg
1346             .append('rect')
1347             .attr('x', 0)
1348             .attr('y', 0)
1349             .attr('width', 0)
1350             .attr('height', 20)
1351             .attr('class', 'percentage');
1352
1353         this._deltaRect = svg
1354             .append('rect')
1355             .attr('x', 0)
1356             .attr('y', 5)
1357             .attr('width', 0)
1358             .attr('height', 10)
1359             .attr('class', 'delta')
1360             .attr('opacity', 0.5)
1361         this._updateBars();
1362     },
1363     _updateBars: function ()
1364     {
1365         if (!this._percentageRect || typeof(this._percentage) !== 'number' || isNaN(this._percentage))
1366             return;
1367
1368         this._percentageRect.attr('width', this._percentage);
1369         if (typeof(this._delta) === 'number' && !isNaN(this._delta)) {
1370             this._deltaRect.attr('x', this._percentage - this._delta);
1371             this._deltaRect.attr('width', this._delta * 2);
1372         }
1373     },
1374     valueChanged: function ()
1375     {
1376         var range = this.get('range');
1377         var value = this.get('value');
1378         if (!range || !value)
1379             return;
1380         var scalingFactor = 100 / (range.max - range.min);
1381         var percentage = (value - range.min) * scalingFactor;
1382         this._percentage = percentage;
1383         this._delta = this.get('delta') * scalingFactor;
1384         this._updateBars();
1385     }.observes('value', 'range').on('init'),
1386 });