New perf dashboard should have an ability to search commits by a keyword
[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('charts', {path: 'charts'});
5 });
6
7 App.DashboardRow = Ember.Object.extend({
8     header: null,
9     cells: [],
10
11     init: function ()
12     {
13         this._super();
14
15         var cellsInfo = this.get('cellsInfo') || [];
16         var columnCount = this.get('columnCount');
17         while (cellsInfo.length < columnCount)
18             cellsInfo.push([]);
19
20         this.set('cells', cellsInfo.map(this._createPane.bind(this)));
21     },
22     addPane: function (paneInfo)
23     {
24         var pane = this._createPane(paneInfo);
25         this.get('cells').pushObject(pane);
26         this.set('columnCount', this.get('columnCount') + 1);
27     },
28     _createPane: function (paneInfo)
29     {
30         if (!paneInfo || !paneInfo.length || (!paneInfo[0] && !paneInfo[1]))
31             paneInfo = null;
32
33         var pane = App.Pane.create({
34             platformId: paneInfo ? paneInfo[0] : null,
35             metricId: paneInfo ? paneInfo[1] : null,
36         });
37
38         return App.DashboardPaneProxyForPicker.create({content: pane});
39     },
40 });
41
42 App.DashboardPaneProxyForPicker = Ember.ObjectProxy.extend({
43     _platformOrMetricIdChanged: function ()
44     {
45         var self = this;
46         App.BuildPopup('choosePane', this)
47             .then(function (platforms) { self.set('pickerData', platforms); });
48     }.observes('platformId', 'metricId').on('init'),
49     paneList: function () {
50         return App.encodePrettifiedJSON([[this.get('platformId'), this.get('metricId'), null, null, false]]);
51     }.property('platformId', 'metricId'),
52 });
53
54 App.IndexController = Ember.Controller.extend({
55     queryParams: ['grid', 'numberOfDays'],
56     _previousGrid: {},
57     defaultTable: [],
58     headerColumns: [],
59     rows: [],
60     numberOfDays: 30,
61     editMode: false,
62
63     gridChanged: function ()
64     {
65         var grid = this.get('grid');
66         if (grid === this._previousGrid)
67             return;
68
69         var table = null;
70         try {
71             if (grid)
72                 table = JSON.parse(grid);
73         } catch (error) {
74             console.log("Failed to parse the grid:", error, grid);
75         }
76
77         if (!table || !table.length) // FIXME: We should fetch this from the manifest.
78             table = this.get('defaultTable');
79
80         table = this._normalizeTable(table);
81         var columnCount = table[0].length;
82         this.set('columnCount', columnCount);
83
84         this.set('headerColumns', table[0].map(function (name, index) {
85             return {label:name, index: index};
86         }));
87
88         this.set('rows', table.slice(1).map(function (rowParam) {
89             return App.DashboardRow.create({
90                 header: rowParam[0],
91                 cellsInfo: rowParam.slice(1),
92                 columnCount: columnCount,
93             })
94         }));
95
96         this.set('emptyRow', new Array(columnCount));
97     }.observes('grid').on('init'),
98
99     _normalizeTable: function (table)
100     {
101         var maxColumnCount = Math.max(table.map(function (column) { return column.length; }));
102         for (var i = 1; i < table.length; i++) {
103             var row = table[i];
104             for (var j = 1; j < row.length; j++) {
105                 if (row[j] && !(row[j] instanceof Array)) {
106                     console.log('Unrecognized (platform, metric) pair at column ' + i + ' row ' + j + ':' + row[j]);
107                     row[j] = [];
108                 }
109             }
110         }
111         return table;
112     },
113
114     updateGrid: function()
115     {
116         var headers = this.get('headerColumns').map(function (header) { return header.label; });
117         var table = [headers].concat(this.get('rows').map(function (row) {
118             return [row.get('header')].concat(row.get('cells').map(function (pane) {
119                 var platformAndMetric = [pane.get('platformId'), pane.get('metricId')];
120                 return platformAndMetric[0] || platformAndMetric[1] ? platformAndMetric : [];
121             }));
122         }));
123         this._previousGrid = JSON.stringify(table);
124         this.set('grid', this._previousGrid);
125     },
126
127     _sharedDomainChanged: function ()
128     {
129         var numberOfDays = this.get('numberOfDays');
130         if (!numberOfDays)
131             return;
132
133         numberOfDays = parseInt(numberOfDays);
134         var present = Date.now();
135         var past = present - numberOfDays * 24 * 3600 * 1000;
136         this.set('sharedDomain', [past, present]);
137     }.observes('numberOfDays').on('init'),
138
139     actions: {
140         setNumberOfDays: function (numberOfDays)
141         {
142             this.set('numberOfDays', numberOfDays);
143         },
144         choosePane: function (param)
145         {
146             var pane = param.position;
147             pane.set('platformId', param.platform.get('id'));
148             pane.set('metricId', param.metric.get('id'));
149         },
150         addColumn: function ()
151         {
152             this.get('headerColumns').pushObject({
153                 label: this.get('newColumnHeader'),
154                 index: this.get('headerColumns').length,
155             });
156             this.get('rows').forEach(function (row) {
157                 row.addPane();
158             });
159             this.set('newColumnHeader', null);
160         },
161         removeColumn: function (index)
162         {
163             this.get('headerColumns').removeAt(index);
164             this.get('rows').forEach(function (row) {
165                 row.get('cells').removeAt(index);
166             });
167         },
168         addRow: function ()
169         {
170             this.get('rows').pushObject(App.DashboardRow.create({
171                 header: this.get('newRowHeader'),
172                 columnCount: this.get('columnCount'),
173             }));
174             this.set('newRowHeader', null);
175         },
176         removeRow: function (row)
177         {
178             this.get('rows').removeObject(row);
179         },
180         resetPane: function (pane)
181         {
182             pane.set('platformId', null);
183             pane.set('metricId', null);
184         },
185         toggleEditMode: function ()
186         {
187             this.toggleProperty('editMode');
188             if (!this.get('editMode'))
189                 this.updateGrid();
190         },
191     },
192
193     init: function ()
194     {
195         this._super();
196         App.Manifest.fetch();
197     }
198 });
199
200 App.NumberOfDaysControlView = Ember.View.extend({
201     classNames: ['controls'],
202     templateName: 'number-of-days-controls',
203     didInsertElement: function ()
204     {
205         this._matchingElements(this._previousNumberOfDaysClass).addClass('active');
206     },
207     _numberOfDaysChanged: function ()
208     {
209         this._matchingElements(this._previousNumberOfDaysClass).removeClass('active');
210
211         var newNumberOfDaysClass = 'numberOfDaysIs' + this.get('numberOfDays');
212         this._matchingElements(this._previousNumberOfDaysClass).addClass('active');
213         this._previousNumberOfDaysClass = newNumberOfDaysClass;
214     }.observes('numberOfDays').on('init'),
215     _matchingElements: function (className)
216     {
217         var element = this.get('element');
218         if (!element)
219             return $([]);
220         return $(element.getElementsByClassName(className));
221     }
222 });
223
224 App.StartTimeSliderView = Ember.View.extend({
225     templateName: 'start-time-slider',
226     classNames: ['start-time-slider'],
227     startTime: Date.now() - 7 * 24 * 3600 * 1000,
228     oldestStartTime: null,
229     _numberOfDaysView: null,
230     _slider: null,
231     _startTimeInSlider: null,
232     _currentNumberOfDays: null,
233     _MILLISECONDS_PER_DAY: 24 * 3600 * 1000,
234
235     didInsertElement: function ()
236     {
237         this.oldestStartTime = Date.now() - 365 * 24 * 3600 * 1000;
238         this._slider = $(this.get('element')).find('input');
239         this._numberOfDaysView = $(this.get('element')).find('.numberOfDays');
240         this._sliderRangeChanged();
241         this._slider.change(this._sliderMoved.bind(this));
242     },
243     _sliderRangeChanged: function ()
244     {
245         var minimumNumberOfDays = 1;
246         var maximumNumberOfDays = this._timeInPastToNumberOfDays(this.get('oldestStartTime'));
247         var precision = 1000; // FIXME: Compute this from maximumNumberOfDays.
248         var slider = this._slider;
249         slider.attr('min', Math.floor(Math.log(Math.max(1, minimumNumberOfDays)) * precision) / precision);
250         slider.attr('max', Math.ceil(Math.log(maximumNumberOfDays) * precision) / precision);
251         slider.attr('step', 1 / precision);
252         this._startTimeChanged();
253     }.observes('oldestStartTime'),
254     _sliderMoved: function ()
255     {
256         this._currentNumberOfDays = Math.round(Math.exp(this._slider.val()));
257         this._numberOfDaysView.text(this._currentNumberOfDays);
258         this._startTimeInSlider = this._numberOfDaysToTimeInPast(this._currentNumberOfDays);
259         this.set('startTime', this._startTimeInSlider);
260     },
261     _startTimeChanged: function ()
262     {
263         var startTime = this.get('startTime');
264         if (startTime == this._startTimeSetBySlider)
265             return;
266         this._currentNumberOfDays = this._timeInPastToNumberOfDays(startTime);
267
268         if (this._slider) {
269             this._numberOfDaysView.text(this._currentNumberOfDays);
270             this._slider.val(Math.log(this._currentNumberOfDays));
271             this._startTimeInSlider = startTime;
272         }
273     }.observes('startTime').on('init'),
274     _timeInPastToNumberOfDays: function (timeInPast)
275     {
276         return Math.max(1, Math.round((Date.now() - timeInPast) / this._MILLISECONDS_PER_DAY));
277     },
278     _numberOfDaysToTimeInPast: function (numberOfDays)
279     {
280         return Date.now() - numberOfDays * this._MILLISECONDS_PER_DAY;
281     },
282 });
283
284 App.Pane = Ember.Object.extend({
285     platformId: null,
286     platform: null,
287     metricId: null,
288     metric: null,
289     selectedItem: null,
290     searchCommit: function (repository, keyword) {
291         var self = this;
292         var repositoryName = repository.get('id');
293         CommitLogs.fetchForTimeRange(repositoryName, null, null, keyword).then(function (commits) {
294             if (self.isDestroyed || !self.get('chartData') || !commits.length)
295                 return;
296             var currentRuns = self.get('chartData').current.timeSeriesByCommitTime().series();
297             if (!currentRuns.length)
298                 return;
299
300             var highlightedItems = {};
301             var commitIndex = 0;
302             for (var runIndex = 0; runIndex < currentRuns.length && commitIndex < commits.length; runIndex++) {
303                 var measurement = currentRuns[runIndex].measurement;
304                 var commitTime = measurement.commitTimeForRepository(repositoryName);
305                 if (!commitTime)
306                     continue;
307                 if (commits[commitIndex].time <= commitTime) {
308                     highlightedItems[measurement.id()] = true;
309                     do {
310                         commitIndex++;
311                     } while (commitIndex < commits.length && commits[commitIndex].time <= commitTime);
312                 }
313             }
314
315             self.set('highlightedItems', highlightedItems);
316         }, function () {
317             // FIXME: Report errors
318             this.set('highlightedItems', {});
319         });
320     },
321     _fetch: function () {
322         var platformId = this.get('platformId');
323         var metricId = this.get('metricId');
324         if (!platformId && !metricId) {
325             this.set('empty', true);
326             return;
327         }
328         this.set('empty', false);
329         this.set('platform', null);
330         this.set('chartData', null);
331         this.set('metric', null);
332         this.set('failure', null);
333
334         if (!this._isValidId(platformId))
335             this.set('failure', platformId ? 'Invalid platform id:' + platformId : 'Platform id was not specified');
336         else if (!this._isValidId(metricId))
337             this.set('failure', metricId ? 'Invalid metric id:' + metricId : 'Metric id was not specified');
338         else {
339             var self = this;
340
341             var metric;
342             var manifestPromise = App.Manifest.fetch(this.store).then(function () {
343                 return new Ember.RSVP.Promise(function (resolve, reject) {
344                     var platform = App.Manifest.platform(platformId);
345                     metric = App.Manifest.metric(metricId);
346                     if (!platform)
347                         reject('Could not find the platform "' + platformId + '"');
348                     else if (!metric)
349                         reject('Could not find the metric "' + metricId + '"');
350                     else {
351                         self.set('platform', platform);
352                         self.set('metric', metric);
353                         resolve(null);
354                     }
355                 });
356             });
357
358             Ember.RSVP.all([
359                 RunsData.fetchRuns(platformId, metricId),
360                 manifestPromise,
361             ]).then(function (values) {
362                 var runs = values[0];
363
364                 // FIXME: Include this information in JSON and process it in RunsData.fetchRuns
365                 var unit = {'Combined': '', // Assume smaller is better for now.
366                     'FrameRate': 'fps',
367                     'Runs': 'runs/s',
368                     'Time': 'ms',
369                     'Malloc': 'bytes',
370                     'JSHeap': 'bytes',
371                     'Allocations': 'bytes',
372                     'EndAllocations': 'bytes',
373                     'MaxAllocations': 'bytes',
374                     'MeanAllocations': 'bytes'}[metric.get('name')];
375                 runs.unit = unit;
376
377                 self.set('chartData', runs);
378             }, function (status) {
379                 self.set('failure', 'Failed to fetch the JSON with an error: ' + status);
380             });
381         }
382     }.observes('platformId', 'metricId').on('init'),
383     _isValidId: function (id)
384     {
385         if (typeof(id) == "number")
386             return true;
387         if (typeof(id) == "string")
388             return !!id.match(/^[A-Za-z0-9_]+$/);
389         return false;
390     }
391 });
392
393 App.encodePrettifiedJSON = function (plain)
394 {
395     function numberIfPossible(string) {
396         return string == parseInt(string) ? parseInt(string) : string;
397     }
398
399     function recursivelyConvertNumberIfPossible(input) {
400         if (input instanceof Array) {
401             return input.map(recursivelyConvertNumberIfPossible);
402         }
403         return numberIfPossible(input);
404     }
405
406     return JSON.stringify(recursivelyConvertNumberIfPossible(plain))
407         .replace(/\[/g, '(').replace(/\]/g, ')').replace(/\,/g, '-');
408 }
409
410 App.decodePrettifiedJSON = function (encoded)
411 {
412     var parsed = encoded.replace(/\(/g, '[').replace(/\)/g, ']').replace(/\-/g, ',');
413     try {
414         return JSON.parse(parsed);
415     } catch (exception) {
416         return null;
417     }
418 }
419
420 App.ChartsController = Ember.Controller.extend({
421     queryParams: ['paneList', 'zoom', 'since'],
422     needs: ['pane'],
423     _currentEncodedPaneList: null,
424     panes: [],
425     platforms: null,
426     sharedZoom: null,
427     startTime: null,
428     defaultSince: Date.now() - 7 * 24 * 3600 * 1000,
429
430     addPane: function (pane)
431     {
432         this.panes.unshiftObject(pane);
433     },
434
435     removePane: function (pane)
436     {
437         this.panes.removeObject(pane);
438     },
439
440     refreshPanes: function()
441     {
442         var paneList = this.get('paneList');
443         if (paneList === this._currentEncodedPaneList)
444             return;
445
446         var panes = this._parsePaneList(paneList || '[]');
447         if (!panes) {
448             console.log('Failed to parse', jsonPaneList, exception);
449             return;
450         }
451         this.set('panes', panes);
452         this._currentEncodedPaneList = paneList;
453     }.observes('paneList').on('init'),
454
455     refreshZoom: function()
456     {
457         var zoom = this.get('zoom');
458         if (!zoom) {
459             this.set('sharedZoom', null);
460             return;
461         }
462
463         zoom = zoom.split('-');
464         var selection = new Array(2);
465         try {
466             selection[0] = new Date(parseFloat(zoom[0]));
467             selection[1] = new Date(parseFloat(zoom[1]));
468         } catch (error) {
469             console.log('Failed to parse the zoom', zoom);
470         }
471         this.set('sharedZoom', selection);
472
473         var startTime = this.get('startTime');
474         if (startTime && startTime > selection[0])
475             this.set('startTime', selection[0]);
476
477     }.observes('zoom').on('init'),
478
479     updateSharedDomain: function ()
480     {
481         var panes = this.get('panes');
482         if (!panes.length)
483             return;
484
485         var union = [undefined, undefined];
486         for (var i = 0; i < panes.length; i++) {
487             var domain = panes[i].intrinsicDomain;
488             if (!domain)
489                 continue;
490             if (!union[0] || domain[0] < union[0])
491                 union[0] = domain[0];
492             if (!union[1] || domain[1] > union[1])
493                 union[1] = domain[1];
494         }
495         if (union[0] === undefined)
496             return;
497
498         var startTime = this.get('startTime');
499         var zoom = this.get('sharedZoom');
500         if (startTime)
501             union[0] = zoom ? Math.min(zoom[0], startTime) : startTime;
502
503         this.set('sharedDomain', union);
504     }.observes('panes.@each'),
505
506     _startTimeChanged: function () {
507         this.updateSharedDomain();
508         this._scheduleQueryStringUpdate();
509     }.observes('startTime'),
510
511     _sinceChanged: function () {
512         var since = parseInt(this.get('since'));
513         if (isNaN(since))
514             since = this.defaultSince;
515         this.set('startTime', new Date(since));
516     }.observes('since').on('init'),
517
518     _parsePaneList: function (encodedPaneList)
519     {
520         var parsedPaneList = App.decodePrettifiedJSON(encodedPaneList);
521         if (!parsedPaneList)
522             return null;
523
524         // Don't re-create all panes.
525         var self = this;
526         return parsedPaneList.map(function (paneInfo) {
527             var timeRange = null;
528             if (paneInfo[3] && paneInfo[3] instanceof Array) {
529                 var timeRange = paneInfo[3];
530                 try {
531                     timeRange = [new Date(timeRange[0]), new Date(timeRange[1])];
532                 } catch (error) {
533                     console.log("Failed to parse the time range:", timeRange, error);
534                 }
535             }
536             return App.Pane.create({
537                 info: paneInfo,
538                 platformId: paneInfo[0],
539                 metricId: paneInfo[1],
540                 selectedItem: paneInfo[2],
541                 timeRange: timeRange,
542                 timeRangeIsLocked: !!paneInfo[4],
543             });
544         });
545     },
546
547     _serializePaneList: function (panes)
548     {
549         if (!panes.length)
550             return undefined;
551         return App.encodePrettifiedJSON(panes.map(function (pane) {
552             return [
553                 pane.get('platformId'),
554                 pane.get('metricId'),
555                 pane.get('selectedItem'),
556                 pane.get('timeRange') ? pane.get('timeRange').map(function (date) { return date.getTime() }) : null,
557                 !!pane.get('timeRangeIsLocked'),
558             ];
559         }));
560     },
561
562     _scheduleQueryStringUpdate: function ()
563     {
564         Ember.run.debounce(this, '_updateQueryString', 500);
565     }.observes('sharedZoom')
566         .observes('panes.@each.platform', 'panes.@each.metric', 'panes.@each.selectedItem',
567         'panes.@each.timeRange', 'panes.@each.timeRangeIsLocked'),
568
569     _updateQueryString: function ()
570     {
571         this._currentEncodedPaneList = this._serializePaneList(this.get('panes'));
572         this.set('paneList', this._currentEncodedPaneList);
573
574         var zoom = undefined;
575         var selection = this.get('sharedZoom');
576         if (selection)
577             zoom = (selection[0] - 0) + '-' + (selection[1] - 0);
578         this.set('zoom', zoom);
579
580         if (this.get('startTime') - this.defaultSince)
581             this.set('since', this.get('startTime') - 0);
582     },
583
584     actions: {
585         addPaneByMetricAndPlatform: function (param)
586         {
587             this.addPane(App.Pane.create({
588                 platformId: param.platform.get('id'),
589                 metricId: param.metric.get('id'),
590                 showingDetails: false
591             }));
592         },
593     },
594
595     init: function ()
596     {
597         this._super();
598         var self = this;
599         App.BuildPopup('addPaneByMetricAndPlatform').then(function (platforms) {
600             self.set('platforms', platforms);
601         });
602     },
603 });
604
605 App.BuildPopup = function(action, position)
606 {
607     return App.Manifest.fetch().then(function () {
608         return App.Manifest.get('platforms').map(function (platform) {
609             return App.PlatformProxyForPopup.create({content: platform,
610                 action: action, position: position});
611         });
612     });
613 }
614
615 App.PlatformProxyForPopup = Ember.ObjectProxy.extend({
616     children: function ()
617     {
618         var platform = this.content;
619         var containsTest = this.content.containsTest.bind(this.content);
620         var action = this.get('action');
621         var position = this.get('position');
622         return App.Manifest.get('topLevelTests')
623             .filter(containsTest)
624             .map(function (test) {
625                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
626             });
627     }.property('App.Manifest.topLevelTests'),
628 });
629
630 App.TestProxyForPopup = Ember.ObjectProxy.extend({
631     platform: null,
632     children: function ()
633     {
634         var platform = this.get('platform');
635         var action = this.get('action');
636         var position = this.get('position');
637
638         var childTests = this.get('childTests')
639             .filter(function (test) { return platform.containsTest(test); })
640             .map(function (test) {
641                 return App.TestProxyForPopup.create({content: test, platform: platform, action: action, position: position});
642             });
643
644         var metrics = this.get('metrics')
645             .filter(function (metric) { return platform.containsMetric(metric); })
646             .map(function (metric) {
647                 var aggregator = metric.get('aggregator');
648                 return {
649                     actionName: action,
650                     actionArgument: {platform: platform, metric: metric, position:position},
651                     label: metric.get('label')
652                 };
653             });
654
655         if (childTests.length && metrics.length)
656             metrics.push({isSeparator: true});
657
658         return metrics.concat(childTests);
659     }.property('childTests', 'metrics'),
660 });
661
662 App.PaneController = Ember.ObjectController.extend({
663     needs: ['charts'],
664     sharedTime: Ember.computed.alias('parentController.sharedTime'),
665     sharedSelection: Ember.computed.alias('parentController.sharedSelection'),
666     selection: null,
667     actions: {
668         toggleDetails: function()
669         {
670             this.toggleProperty('showingDetails');
671         },
672         close: function ()
673         {
674             this.parentController.removePane(this.get('model'));
675         },
676         toggleSearch: function ()
677         {
678             if (!App.Manifest.repositoriesWithReportedCommits)
679                 return;
680             var model = this.get('model');
681             if (!model.get('commitSearchRepository'))
682                 model.set('commitSearchRepository', App.Manifest.repositoriesWithReportedCommits[0]);
683             this.toggleProperty('showingSearchPane');
684         },
685         searchCommit: function () {
686             var model = this.get('model');
687             model.searchCommit(model.get('commitSearchRepository'), model.get('commitSearchKeyword'));                
688         },
689         zoomed: function (selection)
690         {
691             this.set('mainPlotDomain', selection ? selection : this.get('overviewDomain'));
692             Ember.run.debounce(this, 'propagateZoom', 100);
693         },
694         overviewDomainChanged: function (domain, intrinsicDomain)
695         {
696             this.set('overviewDomain', domain);
697             this.set('intrinsicDomain', intrinsicDomain);
698             this.get('parentController').updateSharedDomain();
699         },
700         rangeChanged: function (extent, startPoint, endPoint)
701         {
702             if (!startPoint || !endPoint) {
703                 this._hasRange = false;
704                 this.set('details', null);
705                 this.set('timeRange', null);
706                 return;
707             }
708             this._hasRange = true;
709             this._showDetails(startPoint.measurement, endPoint.measurement, false);
710             this.set('timeRange', extent);
711         },
712     },
713     _overviewSelectionChanged: function ()
714     {
715         var overviewSelection = this.get('overviewSelection');
716         this.set('mainPlotDomain', overviewSelection);
717         Ember.run.debounce(this, 'propagateZoom', 100);
718     }.observes('overviewSelection'),
719     _sharedDomainChanged: function ()
720     {
721         var newDomain = this.get('parentController').get('sharedDomain');
722         if (newDomain == this.get('overviewDomain'))
723             return;
724         this.set('overviewDomain', newDomain);
725         if (!this.get('overviewSelection'))
726             this.set('mainPlotDomain', newDomain);
727     }.observes('parentController.sharedDomain').on('init'),
728     propagateZoom: function ()
729     {
730         this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
731     },
732     _sharedZoomChanged: function ()
733     {
734         var newSelection = this.get('parentController').get('sharedZoom');
735         if (newSelection == this.get('mainPlotDomain'))
736             return;
737         this.set('overviewSelection', newSelection);
738         this.set('mainPlotDomain', newSelection);
739     }.observes('parentController.sharedZoom').on('init'),
740     _currentItemChanged: function ()
741     {
742         if (this._hasRange)
743             return;
744         var point = this.get('currentItem');
745         if (!point || !point.measurement)
746             this.set('details', null);
747         else
748             this._showDetails(point.series.previousPoint(point).measurement, point.measurement, true);
749     }.observes('currentItem'),
750     _showDetails: function (oldMeasurement, currentMeasurement, isShowingEndPoint)
751     {
752         var revisions = [];
753
754         var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
755         var repositoryNames = [];
756         for (var repositoryName in formattedRevisions)
757             repositoryNames.push(repositoryName);
758         var revisions = [];
759         repositoryNames.sort().forEach(function (repositoryName) {
760             var revision = formattedRevisions[repositoryName];
761             var repository = App.Manifest.repository(repositoryName);
762             revision['url'] = false;
763             if (repository) {
764                 revision['url'] = revision.previousRevision
765                     ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
766                     : repository.urlForRevision(revision.currentRevision);
767             }
768             revision['name'] = repositoryName;
769             revision['repository'] = repository;
770             revisions.push(Ember.Object.create(revision));            
771         });
772
773         var buildNumber = null;
774         var buildURL = null;
775         if (isShowingEndPoint) {
776             buildNumber = currentMeasurement.buildNumber();
777             var builder = App.Manifest.builder(currentMeasurement.builderId());
778             if (builder)
779                 buildURL = builder.urlFromBuildNumber(buildNumber);
780         }
781         this.set('details', {
782             currentValue: currentMeasurement.mean().toFixed(2),
783             oldValue: oldMeasurement && !isShowingEndPoint ? oldMeasurement.mean().toFixed(2) : null,
784             buildNumber: buildNumber,
785             buildURL: buildURL,
786             buildTime: currentMeasurement.formattedBuildTime(),
787             revisions: revisions,
788         });
789     }
790 });
791
792 App.InteractiveChartComponent = Ember.Component.extend({
793     chartData: null,
794     showXAxis: true,
795     showYAxis: true,
796     interactive: false,
797     enableSelection: true,
798     classNames: ['chart'],
799     init: function ()
800     {
801         this._super();
802         this._needsConstruction = true;
803         this._eventHandlers = [];
804         $(window).resize(this._updateDimensionsIfNeeded.bind(this));
805     },
806     chartDataDidChange: function ()
807     {
808         var chartData = this.get('chartData');
809         if (!chartData)
810             return;
811         this._needsConstruction = true;
812         this._constructGraphIfPossible(chartData);
813     }.observes('chartData').on('init'),
814     didInsertElement: function ()
815     {
816         var chartData = this.get('chartData');
817         if (chartData)
818             this._constructGraphIfPossible(chartData);
819     },
820     willClearRender: function ()
821     {
822         this._eventHandlers.forEach(function (item) {
823             $(item[0]).off(item[1], item[2]);
824         })
825     },
826     _attachEventListener: function(target, eventName, listener)
827     {
828         this._eventHandlers.push([target, eventName, listener]);
829         $(target).on(eventName, listener);
830     },
831     _constructGraphIfPossible: function (chartData)
832     {
833         if (!this._needsConstruction || !this.get('element'))
834             return;
835
836         var element = this.get('element');
837
838         this._x = d3.time.scale();
839         this._y = d3.scale.linear();
840
841         // FIXME: Tear down the old SVG element.
842         this._svgElement = d3.select(element).append("svg")
843                 .attr("width", "100%")
844                 .attr("height", "100%");
845
846         var svg = this._svg = this._svgElement.append("g");
847
848         var clipId = element.id + "-clip";
849         this._clipPath = svg.append("defs").append("clipPath")
850             .attr("id", clipId)
851             .append("rect");
852
853         if (this.get('showXAxis')) {
854             this._xAxis = d3.svg.axis().scale(this._x).orient("bottom").ticks(6);
855             this._xAxisLabels = svg.append("g")
856                 .attr("class", "x axis");
857         }
858
859         if (this.get('showYAxis')) {
860             this._yAxis = d3.svg.axis().scale(this._y).orient("left").ticks(6).tickFormat(d3.format("s"));
861             this._yAxisLabels = svg.append("g")
862                 .attr("class", "y axis");
863         }
864
865         this._clippedContainer = svg.append("g")
866             .attr("clip-path", "url(#" + clipId + ")");
867
868         var xScale = this._x;
869         var yScale = this._y;
870         this._timeLine = d3.svg.line()
871             .x(function(point) { return xScale(point.time); })
872             .y(function(point) { return yScale(point.value); });
873
874         this._confidenceArea = d3.svg.area()
875 //            .interpolate("cardinal")
876             .x(function(point) { return xScale(point.time); })
877             .y0(function(point) { return point.interval ? yScale(point.interval[0]) : null; })
878             .y1(function(point) { return point.interval ? yScale(point.interval[1]) : null; });
879
880         if (this._paths)
881             this._paths.forEach(function (path) { path.remove(); });
882         this._paths = [];
883         if (this._areas)
884             this._areas.forEach(function (area) { area.remove(); });
885         this._areas = [];
886         if (this._dots)
887             this._dots.forEach(function (dot) { dots.remove(); });
888         this._dots = [];
889         if (this._highlights)
890             this._highlights.forEach(function (highlight) { _highlights.remove(); });
891         this._highlights = [];
892
893         this._currentTimeSeries = chartData.current.timeSeriesByCommitTime();
894         this._currentTimeSeriesData = this._currentTimeSeries.series();
895         this._baselineTimeSeries = chartData.baseline ? chartData.baseline.timeSeriesByCommitTime() : null;
896         this._targetTimeSeries = chartData.target ? chartData.target.timeSeriesByCommitTime() : null;
897
898         this._yAxisUnit = chartData.unit;
899
900         var minMax = this._minMaxForAllTimeSeries();
901         var smallEnoughValue = minMax[0] - (minMax[1] - minMax[0]) * 10;
902         var largeEnoughValue = minMax[1] + (minMax[1] - minMax[0]) * 10;
903
904         // FIXME: Flip the sides based on smallerIsBetter-ness.
905         if (this._baselineTimeSeries) {
906             var data = this._baselineTimeSeries.series();
907             this._areas.push(this._clippedContainer
908                 .append("path")
909                 .datum(data.map(function (point) { return {time: point.time, value: point.value, interval: point.interval ? point.interval : [point.value, largeEnoughValue]}; }))
910                 .attr("class", "area baseline"));
911         }
912         if (this._targetTimeSeries) {
913             var data = this._targetTimeSeries.series();
914             this._areas.push(this._clippedContainer
915                 .append("path")
916                 .datum(data.map(function (point) { return {time: point.time, value: point.value, interval: point.interval ? point.interval : [smallEnoughValue, point.value]}; }))
917                 .attr("class", "area target"));
918         }
919
920         this._areas.push(this._clippedContainer
921             .append("path")
922             .datum(this._currentTimeSeriesData)
923             .attr("class", "area"));
924
925         this._paths.push(this._clippedContainer
926             .append("path")
927             .datum(this._currentTimeSeriesData)
928             .attr("class", "commit-time-line"));
929
930         this._dots.push(this._clippedContainer
931             .selectAll(".dot")
932                 .data(this._currentTimeSeriesData)
933             .enter().append("circle")
934                 .attr("class", "dot")
935                 .attr("r", this.get('interactive') ? 2 : 1));
936
937         if (this.get('interactive')) {
938             this._attachEventListener(element, "mousemove", this._mouseMoved.bind(this));
939             this._attachEventListener(element, "mouseleave", this._mouseLeft.bind(this));
940             this._attachEventListener(element, "mousedown", this._mouseDown.bind(this));
941             this._attachEventListener($(element).parents("[tabindex]"), "keydown", this._keyPressed.bind(this));
942
943             this._currentItemLine = this._clippedContainer
944                 .append("line")
945                 .attr("class", "current-item");
946
947             this._currentItemCircle = this._clippedContainer
948                 .append("circle")
949                 .attr("class", "dot current-item")
950                 .attr("r", 3);
951         }
952
953         this._brush = null;
954         if (this.get('enableSelection')) {
955             this._brush = d3.svg.brush()
956                 .x(this._x)
957                 .on("brush", this._brushChanged.bind(this));
958
959             this._brushRect = this._clippedContainer
960                 .append("g")
961                 .attr("class", "x brush");
962         }
963
964         this._updateDomain();
965         this._updateDimensionsIfNeeded();
966
967         // Work around the fact the brush isn't set if we updated it synchronously here.
968         setTimeout(this._selectionChanged.bind(this), 0);
969
970         setTimeout(this._selectedItemChanged.bind(this), 0);
971
972         this._needsConstruction = false;
973     },
974     _updateDomain: function ()
975     {
976         var xDomain = this.get('domain');
977         var intrinsicXDomain = this._computeXAxisDomain(this._currentTimeSeriesData);
978         if (!xDomain)
979             xDomain = intrinsicXDomain;
980         var currentDomain = this._x.domain();
981         if (currentDomain && this._xDomainsAreSame(currentDomain, xDomain))
982             return currentDomain;
983
984         var yDomain = this._computeYAxisDomain(xDomain[0], xDomain[1]);
985         this._x.domain(xDomain);
986         this._y.domain(yDomain);
987         this.sendAction('domainChanged', xDomain, intrinsicXDomain);
988         return xDomain;
989     },
990     _updateDimensionsIfNeeded: function (newSelection)
991     {
992         var element = $(this.get('element'));
993
994         var newTotalWidth = element.width();
995         var newTotalHeight = element.height();
996         if (this._totalWidth == newTotalWidth && this._totalHeight == newTotalHeight)
997             return;
998
999         this._totalWidth = newTotalWidth;
1000         this._totalHeight = newTotalHeight;
1001
1002         if (!this._rem)
1003             this._rem = parseFloat(getComputedStyle(document.documentElement).fontSize);
1004         var rem = this._rem;
1005
1006         var padding = 0.5 * rem;
1007         var margin = {top: padding, right: padding, bottom: padding, left: padding};
1008         if (this._xAxis)
1009             margin.bottom += rem;
1010         if (this._yAxis)
1011             margin.left += 3 * rem;
1012
1013         this._margin = margin;
1014         this._contentWidth = this._totalWidth - margin.left - margin.right;
1015         this._contentHeight = this._totalHeight - margin.top - margin.bottom;
1016
1017         this._svg.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
1018
1019         this._clipPath
1020             .attr("width", this._contentWidth)
1021             .attr("height", this._contentHeight);
1022
1023         this._x.range([0, this._contentWidth]);
1024         this._y.range([this._contentHeight, 0]);
1025
1026         if (this._xAxis) {
1027             this._xAxis.tickSize(-this._contentHeight);
1028             this._xAxisLabels.attr("transform", "translate(0," + this._contentHeight + ")");
1029         }
1030
1031         if (this._yAxis)
1032             this._yAxis.tickSize(-this._contentWidth);
1033
1034         if (this._currentItemLine) {
1035             this._currentItemLine
1036                 .attr("y1", 0)
1037                 .attr("y2", margin.top + this._contentHeight);
1038         }
1039
1040         this._relayoutDataAndAxes(this._currentSelection());
1041     },
1042     _updateBrush: function ()
1043     {
1044         this._brushRect
1045             .call(this._brush)
1046         .selectAll("rect")
1047             .attr("y", 1)
1048             .attr("height", this._contentHeight - 2);
1049         this._updateSelectionToolbar();
1050     },
1051     _relayoutDataAndAxes: function (selection)
1052     {
1053         var timeline = this._timeLine;
1054         this._paths.forEach(function (path) { path.attr("d", timeline); });
1055
1056         var confidenceArea = this._confidenceArea;
1057         this._areas.forEach(function (path) { path.attr("d", confidenceArea); });
1058
1059         var xScale = this._x;
1060         var yScale = this._y;
1061         this._dots.forEach(function (dot) {
1062             dot
1063                 .attr("cx", function(measurement) { return xScale(measurement.time); })
1064                 .attr("cy", function(measurement) { return yScale(measurement.value); });
1065         });
1066         this._updateHighlightPositions();
1067
1068         if (this._brush) {
1069             if (selection)
1070                 this._brush.extent(selection);
1071             else
1072                 this._brush.clear();
1073             this._updateBrush();
1074         }
1075
1076         this._updateCurrentItemIndicators();
1077
1078         if (this._xAxis)
1079             this._xAxisLabels.call(this._xAxis);
1080         if (!this._yAxis)
1081             return;
1082
1083         this._yAxisLabels.call(this._yAxis);
1084         if (this._yAxisUnitContainer)
1085             this._yAxisUnitContainer.remove();
1086         this._yAxisUnitContainer = this._yAxisLabels.append("text")
1087             .attr("x", 0.5 * this._rem)
1088             .attr("y", this._rem)
1089             .attr("dy", '0.8rem')
1090             .style("text-anchor", "start")
1091             .style("z-index", "100")
1092             .text(this._yAxisUnit);
1093     },
1094     _updateHighlightPositions: function () {
1095         var xScale = this._x;
1096         var yScale = this._y;
1097         var y2 = this._margin.top + this._contentHeight;
1098         this._highlights.forEach(function (highlight) {
1099             highlight
1100                 .attr("y1", 0)
1101                 .attr("y2", y2)
1102                 .attr("y", function(measurement) { return yScale(measurement.value); })
1103                 .attr("x1", function(measurement) { return xScale(measurement.time); })
1104                 .attr("x2", function(measurement) { return xScale(measurement.time); });
1105         });
1106     },
1107     _computeXAxisDomain: function (timeSeries)
1108     {
1109         var extent = d3.extent(timeSeries, function(point) { return point.time; });
1110         var margin = 3600 * 1000; // Use x.inverse to compute the right amount from a margin.
1111         return [+extent[0] - margin, +extent[1] + margin];
1112     },
1113     _computeYAxisDomain: function (startTime, endTime)
1114     {
1115         var range = this._minMaxForAllTimeSeries(startTime, endTime);
1116         var min = range[0];
1117         var max = range[1];
1118         if (max < min)
1119             min = max = 0;
1120         var diff = max - min;
1121         var margin = diff * 0.05;
1122
1123         yExtent = [min - margin, max + margin];
1124 //        if (yMin !== undefined)
1125 //            yExtent[0] = parseInt(yMin);
1126         return yExtent;
1127     },
1128     _minMaxForAllTimeSeries: function (startTime, endTime)
1129     {
1130         var currentRange = this._currentTimeSeries.minMaxForTimeRange(startTime, endTime);
1131         var baselineRange = this._baselineTimeSeries ? this._baselineTimeSeries.minMaxForTimeRange(startTime, endTime) : [Number.MAX_VALUE, Number.MIN_VALUE];
1132         var targetRange = this._targetTimeSeries ? this._targetTimeSeries.minMaxForTimeRange(startTime, endTime) : [Number.MAX_VALUE, Number.MIN_VALUE];
1133         return [
1134             Math.min(currentRange[0], baselineRange[0], targetRange[0]),
1135             Math.max(currentRange[1], baselineRange[1], targetRange[1]),
1136         ];
1137     },
1138     _currentSelection: function ()
1139     {
1140         return this._brush && !this._brush.empty() ? this._brush.extent() : null;
1141     },
1142     _domainChanged: function ()
1143     {
1144         var selection = this._currentSelection() || this.get('sharedSelection');
1145         var newXDomain = this._updateDomain();
1146
1147         if (selection && newXDomain && selection[0] <= newXDomain[0] && newXDomain[1] <= selection[1])
1148             selection = null; // Otherwise the user has no way of clearing the selection.
1149
1150         this._relayoutDataAndAxes(selection);
1151     }.observes('domain'),
1152     _selectionChanged: function ()
1153     {
1154         this._updateSelection(this.get('selection'));
1155     }.observes('selection'),
1156     _sharedSelectionChanged: function ()
1157     {
1158         if (this.get('selectionIsLocked'))
1159             return;
1160         this._updateSelection(this.get('sharedSelection'));
1161     }.observes('sharedSelection'),
1162     _updateSelection: function (newSelection)
1163     {
1164         if (!this._brush)
1165             return;
1166
1167         var currentSelection = this._currentSelection();
1168         if (newSelection && currentSelection && this._xDomainsAreSame(newSelection, currentSelection))
1169             return;
1170
1171         var domain = this._x.domain();
1172         if (!newSelection || this._xDomainsAreSame(domain, newSelection))
1173             this._brush.clear();
1174         else
1175             this._brush.extent(newSelection);
1176         this._updateBrush();
1177
1178         this._setCurrentSelection(newSelection);
1179     },
1180     _xDomainsAreSame: function (domain1, domain2)
1181     {
1182         return !(domain1[0] - domain2[0]) && !(domain1[1] - domain2[1]);
1183     },
1184     _brushChanged: function ()
1185     {
1186         if (this._brush.empty()) {
1187             if (!this._brushExtent)
1188                 return;
1189
1190             this.set('selectionIsLocked', false);
1191             this._setCurrentSelection(undefined);
1192
1193             // Avoid locking the indicator in _mouseDown when the brush was cleared in the same mousedown event.
1194             this._brushJustChanged = true;
1195             var self = this;
1196             setTimeout(function () {
1197                 self._brushJustChanged = false;
1198             }, 0);
1199
1200             return;
1201         }
1202
1203         this.set('selectionIsLocked', true);
1204         this._setCurrentSelection(this._brush.extent());
1205     },
1206     _keyPressed: function (event)
1207     {
1208         if (!this._currentItemIndex || this._currentSelection())
1209             return;
1210
1211         var newIndex;
1212         switch (event.keyCode) {
1213         case 37: // Left
1214             newIndex = this._currentItemIndex - 1;
1215             break;
1216         case 39: // Right
1217             newIndex = this._currentItemIndex + 1;
1218             break;
1219         case 38: // Up
1220         case 40: // Down
1221         default:
1222             return;
1223         }
1224
1225         // Unlike mousemove, keydown shouldn't move off the edge.
1226         if (this._currentTimeSeriesData[newIndex])
1227             this._setCurrentItem(newIndex);
1228     },
1229     _mouseMoved: function (event)
1230     {
1231         if (!this._margin || this._currentSelection() || this._currentItemLocked)
1232             return;
1233
1234         var point = this._mousePointInGraph(event);
1235
1236         this._selectClosestPointToMouseAsCurrentItem(point);
1237     },
1238     _mouseLeft: function (event)
1239     {
1240         if (!this._margin || this._currentItemLocked)
1241             return;
1242
1243         this._selectClosestPointToMouseAsCurrentItem(null);
1244     },
1245     _mouseDown: function (event)
1246     {
1247         if (!this._margin || this._currentSelection() || this._brushJustChanged)
1248             return;
1249
1250         var point = this._mousePointInGraph(event);
1251         if (!point)
1252             return;
1253
1254         if (this._currentItemLocked) {
1255             this._currentItemLocked = false;
1256             this.set('selectedItem', null);
1257             return;
1258         }
1259
1260         this._currentItemLocked = true;
1261         this._selectClosestPointToMouseAsCurrentItem(point);
1262     },
1263     _mousePointInGraph: function (event)
1264     {
1265         var offset = $(this.get('element')).offset();
1266         if (!offset)
1267             return null;
1268
1269         var point = {
1270             x: event.pageX - offset.left - this._margin.left,
1271             y: event.pageY - offset.top - this._margin.top
1272         };
1273
1274         var xScale = this._x;
1275         var yScale = this._y;
1276         var xDomain = xScale.domain();
1277         var yDomain = yScale.domain();
1278         if (point.x >= xScale(xDomain[0]) && point.x <= xScale(xDomain[1])
1279             && point.y <= yScale(yDomain[0]) && point.y >= yScale(yDomain[1]))
1280             return point;
1281
1282         return null;
1283     },
1284     _selectClosestPointToMouseAsCurrentItem: function (point)
1285     {
1286         var xScale = this._x;
1287         var yScale = this._y;
1288         var distanceHeuristics = function (m) {
1289             var mX = xScale(m.time);
1290             var mY = yScale(m.value);
1291             var xDiff = mX - point.x;
1292             var yDiff = mY - point.y;
1293             return xDiff * xDiff + yDiff * yDiff / 16; // Favor horizontal affinity.
1294         };
1295         distanceHeuristics = function (m) {
1296             return Math.abs(xScale(m.time) - point.x);
1297         }
1298
1299         var newItemIndex;
1300         if (point && !this._currentSelection()) {
1301             var distances = this._currentTimeSeriesData.map(distanceHeuristics);
1302             var minDistance = Number.MAX_VALUE;
1303             for (var i = 0; i < distances.length; i++) {
1304                 if (distances[i] < minDistance) {
1305                     newItemIndex = i;
1306                     minDistance = distances[i];
1307                 }
1308             }
1309         }
1310
1311         this._setCurrentItem(newItemIndex);
1312         this._updateSelectionToolbar();
1313     },
1314     _currentTimeChanged: function ()
1315     {
1316         if (!this._margin || this._currentSelection() || this._currentItemLocked)
1317             return
1318
1319         var currentTime = this.get('currentTime');
1320         if (currentTime) {
1321             for (var i = 0; i < this._currentTimeSeriesData.length; i++) {
1322                 var point = this._currentTimeSeriesData[i];
1323                 if (point.time >= currentTime) {
1324                     this._setCurrentItem(i, /* doNotNotify */ true);
1325                     return;
1326                 }
1327             }
1328         }
1329         this._setCurrentItem(undefined, /* doNotNotify */ true);
1330     }.observes('currentTime'),
1331     _setCurrentItem: function (newItemIndex, doNotNotify)
1332     {
1333         if (newItemIndex === this._currentItemIndex) {
1334             if (this._currentItemLocked)
1335                 this.set('selectedItem', this.get('currentItem') ? this.get('currentItem').measurement.id() : null);
1336             return;
1337         }
1338
1339         var newItem = this._currentTimeSeriesData[newItemIndex];
1340         this._brushExtent = undefined;
1341         this._currentItemIndex = newItemIndex;
1342
1343         if (!newItem) {
1344             this._currentItemLocked = false;
1345             this.set('selectedItem', null);
1346         }
1347
1348         this._updateCurrentItemIndicators();
1349
1350         if (!doNotNotify)
1351             this.set('currentTime', newItem ? newItem.time : undefined);
1352
1353         this.set('currentItem', newItem);
1354         if (this._currentItemLocked)
1355             this.set('selectedItem', newItem ? newItem.measurement.id() : null);
1356     },
1357     _selectedItemChanged: function ()
1358     {
1359         if (!this._margin)
1360             return;
1361
1362         var selectedId = this.get('selectedItem');
1363         var currentItem = this.get('currentItem');
1364         if (currentItem && currentItem.measurement.id() == selectedId)
1365             return;
1366
1367         var series = this._currentTimeSeriesData;
1368         var selectedItemIndex = undefined;
1369         for (var i = 0; i < series.length; i++) {
1370             if (series[i].measurement.id() == selectedId) {
1371                 this._updateSelection(null);
1372                 this._currentItemLocked = true;
1373                 this._setCurrentItem(i);
1374                 this._updateSelectionToolbar();
1375                 return;
1376             }
1377         }
1378     }.observes('selectedItem').on('init'),
1379     _highlightedItemsChanged: function () {
1380         if (!this._margin)
1381             return;
1382
1383         var highlightedItems = this.get('highlightedItems');
1384
1385         var data = this._currentTimeSeriesData.filter(function (item) { return highlightedItems[item.measurement.id()]; });
1386
1387         if (this._highlights)
1388             this._highlights.forEach(function (highlight) { highlight.remove(); });
1389
1390         this._highlights.push(this._clippedContainer
1391             .selectAll(".highlight")
1392                 .data(data)
1393             .enter().append("line")
1394                 .attr("class", "highlight"));
1395
1396         this._updateHighlightPositions();
1397
1398     }.observes('highlightedItems'),
1399     _updateCurrentItemIndicators: function ()
1400     {
1401         if (!this._currentItemLine)
1402             return;
1403
1404         var item = this._currentTimeSeriesData[this._currentItemIndex];
1405         if (!item) {
1406             this._currentItemLine.attr("x1", -1000).attr("x2", -1000);
1407             this._currentItemCircle.attr("cx", -1000);
1408             return;
1409         }
1410
1411         var x = this._x(item.time);
1412         var y = this._y(item.value);
1413
1414         this._currentItemLine
1415             .attr("x1", x)
1416             .attr("x2", x);
1417
1418         this._currentItemCircle
1419             .attr("cx", x)
1420             .attr("cy", y);
1421     },
1422     _setCurrentSelection: function (newSelection)
1423     {
1424         if (this._brushExtent === newSelection)
1425             return;
1426
1427         if (newSelection) {
1428             var startPoint;
1429             var endPoint;
1430             for (var i = 0; i < this._currentTimeSeriesData.length; i++) {
1431                 var point = this._currentTimeSeriesData[i];
1432                 if (!startPoint) {
1433                     if (point.time >= newSelection[0]) {
1434                         if (point.time > newSelection[1])
1435                             break;
1436                         startPoint = point;
1437                     }
1438                 } else if (point.time > newSelection[1])
1439                     break;
1440                 if (point.time >= newSelection[0] && point.time <= newSelection[1])
1441                     endPoint = point;
1442             }
1443         }
1444
1445         this._brushExtent = newSelection;
1446         this._setCurrentItem(undefined);
1447         this._updateSelectionToolbar();
1448
1449         this.set('sharedSelection', newSelection);
1450         this.sendAction('selectionChanged', newSelection, startPoint, endPoint);
1451     },
1452     _updateSelectionToolbar: function ()
1453     {
1454         if (!this.get('interactive'))
1455             return;
1456
1457         var selection = this._currentSelection();
1458         var selectionToolbar = $(this.get('element')).children('.selection-toolbar');
1459         if (selection) {
1460             var left = this._x(selection[0]);
1461             var right = this._x(selection[1]);
1462             selectionToolbar
1463                 .css({left: this._margin.left + right, top: this._margin.top + this._contentHeight})
1464                 .show();
1465         } else
1466             selectionToolbar.hide();
1467     },
1468     actions: {
1469         zoom: function ()
1470         {
1471             this.sendAction('zoom', this._currentSelection());
1472             this.set('selection', null);
1473         },
1474     },
1475 });
1476
1477
1478
1479 App.CommitsViewerComponent = Ember.Component.extend({
1480     repository: null,
1481     revisionInfo: null,
1482     commits: null,
1483     commitsChanged: function ()
1484     {
1485         var revisionInfo = this.get('revisionInfo');
1486
1487         var to = revisionInfo.get('currentRevision');
1488         var from = revisionInfo.get('previousRevision') || to;
1489         var repository = this.get('repository');
1490         if (!from || !repository || !repository.get('hasReportedCommits'))
1491             return;
1492
1493         var self = this;
1494         CommitLogs.fetchForTimeRange(repository.get('id'), from, to).then(function (commits) {
1495             if (self.isDestroyed)
1496                 return;
1497             self.set('commits', commits.map(function (commit) {
1498                 return Ember.Object.create({
1499                     repository: repository,
1500                     revision: commit.revision,
1501                     url: repository.urlForRevision(commit.revision),
1502                     author: commit.authorName || commit.authorEmail,
1503                     message: commit.message ? commit.message.substr(0, 75) : null,
1504                 });
1505             }));
1506         }, function () {
1507             if (!self.isDestroyed)
1508                 self.set('commits', []);
1509         })
1510     }.observes('repository').observes('revisionInfo').on('init'),
1511 });