1 window.App = Ember.Application.create();
3 App.Router.map(function () {
4 this.resource('charts', {path: 'charts'});
7 App.DashboardRow = Ember.Object.extend({
15 var cellsInfo = this.get('cellsInfo') || [];
16 var columnCount = this.get('columnCount');
17 while (cellsInfo.length < columnCount)
20 this.set('cells', cellsInfo.map(this._createPane.bind(this)));
22 addPane: function (paneInfo)
24 var pane = this._createPane(paneInfo);
25 this.get('cells').pushObject(pane);
26 this.set('columnCount', this.get('columnCount') + 1);
28 _createPane: function (paneInfo)
30 if (!paneInfo || !paneInfo.length || (!paneInfo[0] && !paneInfo[1]))
33 var pane = App.Pane.create({
34 platformId: paneInfo ? paneInfo[0] : null,
35 metricId: paneInfo ? paneInfo[1] : null,
38 return App.DashboardPaneProxyForPicker.create({content: pane});
42 App.DashboardPaneProxyForPicker = Ember.ObjectProxy.extend({
43 _platformOrMetricIdChanged: function ()
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'),
54 App.IndexController = Ember.Controller.extend({
55 queryParams: ['grid', 'numberOfDays'],
63 gridChanged: function ()
65 var grid = this.get('grid');
66 if (grid === this._previousGrid)
72 table = JSON.parse(grid);
74 console.log("Failed to parse the grid:", error, grid);
77 if (!table || !table.length) // FIXME: We should fetch this from the manifest.
78 table = this.get('defaultTable');
80 table = this._normalizeTable(table);
81 var columnCount = table[0].length;
82 this.set('columnCount', columnCount);
84 this.set('headerColumns', table[0].map(function (name, index) {
85 return {label:name, index: index};
88 this.set('rows', table.slice(1).map(function (rowParam) {
89 return App.DashboardRow.create({
91 cellsInfo: rowParam.slice(1),
92 columnCount: columnCount,
96 this.set('emptyRow', new Array(columnCount));
97 }.observes('grid').on('init'),
99 _normalizeTable: function (table)
101 var maxColumnCount = Math.max(table.map(function (column) { return column.length; }));
102 for (var i = 1; i < table.length; 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]);
114 updateGrid: function()
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 : [];
123 this._previousGrid = JSON.stringify(table);
124 this.set('grid', this._previousGrid);
127 _sharedDomainChanged: function ()
129 var numberOfDays = this.get('numberOfDays');
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'),
140 setNumberOfDays: function (numberOfDays)
142 this.set('numberOfDays', numberOfDays);
144 choosePane: function (param)
146 var pane = param.position;
147 pane.set('platformId', param.platform.get('id'));
148 pane.set('metricId', param.metric.get('id'));
150 addColumn: function ()
152 this.get('headerColumns').pushObject({
153 label: this.get('newColumnHeader'),
154 index: this.get('headerColumns').length,
156 this.get('rows').forEach(function (row) {
159 this.set('newColumnHeader', null);
161 removeColumn: function (index)
163 this.get('headerColumns').removeAt(index);
164 this.get('rows').forEach(function (row) {
165 row.get('cells').removeAt(index);
170 this.get('rows').pushObject(App.DashboardRow.create({
171 header: this.get('newRowHeader'),
172 columnCount: this.get('columnCount'),
174 this.set('newRowHeader', null);
176 removeRow: function (row)
178 this.get('rows').removeObject(row);
180 resetPane: function (pane)
182 pane.set('platformId', null);
183 pane.set('metricId', null);
185 toggleEditMode: function ()
187 this.toggleProperty('editMode');
188 if (!this.get('editMode'))
196 App.Manifest.fetch();
200 App.NumberOfDaysControlView = Ember.View.extend({
201 classNames: ['controls'],
202 templateName: 'number-of-days-controls',
203 didInsertElement: function ()
205 this._matchingElements(this._previousNumberOfDaysClass).addClass('active');
207 _numberOfDaysChanged: function ()
209 this._matchingElements(this._previousNumberOfDaysClass).removeClass('active');
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)
217 var element = this.get('element');
220 return $(element.getElementsByClassName(className));
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,
231 _startTimeInSlider: null,
232 _currentNumberOfDays: null,
233 _MILLISECONDS_PER_DAY: 24 * 3600 * 1000,
235 didInsertElement: function ()
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));
243 _sliderRangeChanged: function ()
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 ()
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);
261 _startTimeChanged: function ()
263 var startTime = this.get('startTime');
264 if (startTime == this._startTimeSetBySlider)
266 this._currentNumberOfDays = this._timeInPastToNumberOfDays(startTime);
269 this._numberOfDaysView.text(this._currentNumberOfDays);
270 this._slider.val(Math.log(this._currentNumberOfDays));
271 this._startTimeInSlider = startTime;
273 }.observes('startTime').on('init'),
274 _timeInPastToNumberOfDays: function (timeInPast)
276 return Math.max(1, Math.round((Date.now() - timeInPast) / this._MILLISECONDS_PER_DAY));
278 _numberOfDaysToTimeInPast: function (numberOfDays)
280 return Date.now() - numberOfDays * this._MILLISECONDS_PER_DAY;
284 App.Pane = Ember.Object.extend({
290 searchCommit: function (repository, keyword) {
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)
296 var currentRuns = self.get('chartData').current.timeSeriesByCommitTime().series();
297 if (!currentRuns.length)
300 var highlightedItems = {};
302 for (var runIndex = 0; runIndex < currentRuns.length && commitIndex < commits.length; runIndex++) {
303 var measurement = currentRuns[runIndex].measurement;
304 var commitTime = measurement.commitTimeForRepository(repositoryName);
307 if (commits[commitIndex].time <= commitTime) {
308 highlightedItems[measurement.id()] = true;
311 } while (commitIndex < commits.length && commits[commitIndex].time <= commitTime);
315 self.set('highlightedItems', highlightedItems);
317 // FIXME: Report errors
318 this.set('highlightedItems', {});
321 _fetch: function () {
322 var platformId = this.get('platformId');
323 var metricId = this.get('metricId');
324 if (!platformId && !metricId) {
325 this.set('empty', true);
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);
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');
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);
347 reject('Could not find the platform "' + platformId + '"');
349 reject('Could not find the metric "' + metricId + '"');
351 self.set('platform', platform);
352 self.set('metric', metric);
359 RunsData.fetchRuns(platformId, metricId),
361 ]).then(function (values) {
362 var runs = values[0];
364 // FIXME: Include this information in JSON and process it in RunsData.fetchRuns
365 var unit = {'Combined': '', // Assume smaller is better for now.
371 'Allocations': 'bytes',
372 'EndAllocations': 'bytes',
373 'MaxAllocations': 'bytes',
374 'MeanAllocations': 'bytes'}[metric.get('name')];
377 self.set('chartData', runs);
378 }, function (status) {
379 self.set('failure', 'Failed to fetch the JSON with an error: ' + status);
382 }.observes('platformId', 'metricId').on('init'),
383 _isValidId: function (id)
385 if (typeof(id) == "number")
387 if (typeof(id) == "string")
388 return !!id.match(/^[A-Za-z0-9_]+$/);
393 App.encodePrettifiedJSON = function (plain)
395 function numberIfPossible(string) {
396 return string == parseInt(string) ? parseInt(string) : string;
399 function recursivelyConvertNumberIfPossible(input) {
400 if (input instanceof Array) {
401 return input.map(recursivelyConvertNumberIfPossible);
403 return numberIfPossible(input);
406 return JSON.stringify(recursivelyConvertNumberIfPossible(plain))
407 .replace(/\[/g, '(').replace(/\]/g, ')').replace(/\,/g, '-');
410 App.decodePrettifiedJSON = function (encoded)
412 var parsed = encoded.replace(/\(/g, '[').replace(/\)/g, ']').replace(/\-/g, ',');
414 return JSON.parse(parsed);
415 } catch (exception) {
420 App.ChartsController = Ember.Controller.extend({
421 queryParams: ['paneList', 'zoom', 'since'],
423 _currentEncodedPaneList: null,
428 defaultSince: Date.now() - 7 * 24 * 3600 * 1000,
430 addPane: function (pane)
432 this.panes.unshiftObject(pane);
435 removePane: function (pane)
437 this.panes.removeObject(pane);
440 refreshPanes: function()
442 var paneList = this.get('paneList');
443 if (paneList === this._currentEncodedPaneList)
446 var panes = this._parsePaneList(paneList || '[]');
448 console.log('Failed to parse', jsonPaneList, exception);
451 this.set('panes', panes);
452 this._currentEncodedPaneList = paneList;
453 }.observes('paneList').on('init'),
455 refreshZoom: function()
457 var zoom = this.get('zoom');
459 this.set('sharedZoom', null);
463 zoom = zoom.split('-');
464 var selection = new Array(2);
466 selection[0] = new Date(parseFloat(zoom[0]));
467 selection[1] = new Date(parseFloat(zoom[1]));
469 console.log('Failed to parse the zoom', zoom);
471 this.set('sharedZoom', selection);
473 var startTime = this.get('startTime');
474 if (startTime && startTime > selection[0])
475 this.set('startTime', selection[0]);
477 }.observes('zoom').on('init'),
479 updateSharedDomain: function ()
481 var panes = this.get('panes');
485 var union = [undefined, undefined];
486 for (var i = 0; i < panes.length; i++) {
487 var domain = panes[i].intrinsicDomain;
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];
495 if (union[0] === undefined)
498 var startTime = this.get('startTime');
499 var zoom = this.get('sharedZoom');
501 union[0] = zoom ? Math.min(zoom[0], startTime) : startTime;
503 this.set('sharedDomain', union);
504 }.observes('panes.@each'),
506 _startTimeChanged: function () {
507 this.updateSharedDomain();
508 this._scheduleQueryStringUpdate();
509 }.observes('startTime'),
511 _sinceChanged: function () {
512 var since = parseInt(this.get('since'));
514 since = this.defaultSince;
515 this.set('startTime', new Date(since));
516 }.observes('since').on('init'),
518 _parsePaneList: function (encodedPaneList)
520 var parsedPaneList = App.decodePrettifiedJSON(encodedPaneList);
524 // Don't re-create all panes.
526 return parsedPaneList.map(function (paneInfo) {
527 var timeRange = null;
528 if (paneInfo[3] && paneInfo[3] instanceof Array) {
529 var timeRange = paneInfo[3];
531 timeRange = [new Date(timeRange[0]), new Date(timeRange[1])];
533 console.log("Failed to parse the time range:", timeRange, error);
536 return App.Pane.create({
538 platformId: paneInfo[0],
539 metricId: paneInfo[1],
540 selectedItem: paneInfo[2],
541 timeRange: timeRange,
542 timeRangeIsLocked: !!paneInfo[4],
547 _serializePaneList: function (panes)
551 return App.encodePrettifiedJSON(panes.map(function (pane) {
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'),
562 _scheduleQueryStringUpdate: function ()
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'),
569 _updateQueryString: function ()
571 this._currentEncodedPaneList = this._serializePaneList(this.get('panes'));
572 this.set('paneList', this._currentEncodedPaneList);
574 var zoom = undefined;
575 var selection = this.get('sharedZoom');
577 zoom = (selection[0] - 0) + '-' + (selection[1] - 0);
578 this.set('zoom', zoom);
580 if (this.get('startTime') - this.defaultSince)
581 this.set('since', this.get('startTime') - 0);
585 addPaneByMetricAndPlatform: function (param)
587 this.addPane(App.Pane.create({
588 platformId: param.platform.get('id'),
589 metricId: param.metric.get('id'),
590 showingDetails: false
599 App.BuildPopup('addPaneByMetricAndPlatform').then(function (platforms) {
600 self.set('platforms', platforms);
605 App.BuildPopup = function(action, position)
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});
615 App.PlatformProxyForPopup = Ember.ObjectProxy.extend({
616 children: function ()
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});
627 }.property('App.Manifest.topLevelTests'),
630 App.TestProxyForPopup = Ember.ObjectProxy.extend({
632 children: function ()
634 var platform = this.get('platform');
635 var action = this.get('action');
636 var position = this.get('position');
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});
644 var metrics = this.get('metrics')
645 .filter(function (metric) { return platform.containsMetric(metric); })
646 .map(function (metric) {
647 var aggregator = metric.get('aggregator');
650 actionArgument: {platform: platform, metric: metric, position:position},
651 label: metric.get('label')
655 if (childTests.length && metrics.length)
656 metrics.push({isSeparator: true});
658 return metrics.concat(childTests);
659 }.property('childTests', 'metrics'),
662 App.PaneController = Ember.ObjectController.extend({
664 sharedTime: Ember.computed.alias('parentController.sharedTime'),
665 sharedSelection: Ember.computed.alias('parentController.sharedSelection'),
668 toggleDetails: function()
670 this.toggleProperty('showingDetails');
674 this.parentController.removePane(this.get('model'));
676 toggleBugsPane: function ()
678 if (!App.Manifest.bugTrackers || !this.get('singlySelectedPoint'))
680 if (this.toggleProperty('showingBugsPane'))
681 this.set('showingSearchPane', false);
683 associateBug: function (bugTracker, bugNumber)
685 var point = this.get('singlySelectedPoint');
689 point.measurement.associateBug(bugTracker.get('id'), bugNumber).then(function () {
691 self._updateMarkedPoints();
694 toggleSearchPane: function ()
696 if (!App.Manifest.repositoriesWithReportedCommits)
698 var model = this.get('model');
699 if (!model.get('commitSearchRepository'))
700 model.set('commitSearchRepository', App.Manifest.repositoriesWithReportedCommits[0]);
701 if (this.toggleProperty('showingSearchPane'))
702 this.set('showingBugsPane', false);
704 searchCommit: function () {
705 var model = this.get('model');
706 model.searchCommit(model.get('commitSearchRepository'), model.get('commitSearchKeyword'));
708 zoomed: function (selection)
710 this.set('mainPlotDomain', selection ? selection : this.get('overviewDomain'));
711 Ember.run.debounce(this, 'propagateZoom', 100);
713 overviewDomainChanged: function (domain, intrinsicDomain)
715 this.set('overviewDomain', domain);
716 this.set('intrinsicDomain', intrinsicDomain);
717 this.get('parentController').updateSharedDomain();
719 rangeChanged: function (extent, points)
722 this._hasRange = false;
723 this.set('details', null);
724 this.set('timeRange', null);
727 this._hasRange = true;
728 this._showDetails(points);
729 this.set('timeRange', extent);
732 _detailsChanged: function ()
734 this.set('showingBugsPane', false);
735 this.set('singlySelectedPoint', !this._hasRange && this._selectedPoints ? this._selectedPoints[0] : null);
736 }.observes('details'),
737 _overviewSelectionChanged: function ()
739 var overviewSelection = this.get('overviewSelection');
740 this.set('mainPlotDomain', overviewSelection);
741 Ember.run.debounce(this, 'propagateZoom', 100);
742 }.observes('overviewSelection'),
743 _sharedDomainChanged: function ()
745 var newDomain = this.get('parentController').get('sharedDomain');
746 if (newDomain == this.get('overviewDomain'))
748 this.set('overviewDomain', newDomain);
749 if (!this.get('overviewSelection'))
750 this.set('mainPlotDomain', newDomain);
751 }.observes('parentController.sharedDomain').on('init'),
752 propagateZoom: function ()
754 this.get('parentController').set('sharedZoom', this.get('mainPlotDomain'));
756 _sharedZoomChanged: function ()
758 var newSelection = this.get('parentController').get('sharedZoom');
759 if (newSelection == this.get('mainPlotDomain'))
761 this.set('overviewSelection', newSelection);
762 this.set('mainPlotDomain', newSelection);
763 }.observes('parentController.sharedZoom').on('init'),
764 _currentItemChanged: function ()
768 var point = this.get('currentItem');
769 if (!point || !point.measurement)
770 this.set('details', null);
772 var previousPoint = point.series.previousPoint(point);
773 this._showDetails(previousPoint ? [previousPoint, point] : [point]);
775 }.observes('currentItem'),
776 _showDetails: function (points)
778 var isShowingEndPoint = !this._hasRange;
779 var currentMeasurement = points[points.length - 1].measurement;
780 var oldMeasurement = points[0].measurement;
781 var formattedRevisions = currentMeasurement.formattedRevisions(oldMeasurement);
782 var revisions = App.Manifest.get('repositories')
783 .filter(function (repository) { return formattedRevisions[repository.get('id')]; })
784 .map(function (repository) {
785 var repositoryName = repository.get('id');
786 var revision = Ember.Object.create(formattedRevisions[repositoryName]);
787 revision['url'] = revision.previousRevision
788 ? repository.urlForRevisionRange(revision.previousRevision, revision.currentRevision)
789 : repository.urlForRevision(revision.currentRevision);
790 revision['name'] = repositoryName;
791 revision['repository'] = repository;
795 var buildNumber = null;
797 if (isShowingEndPoint) {
798 buildNumber = currentMeasurement.buildNumber();
799 var builder = App.Manifest.builder(currentMeasurement.builderId());
801 buildURL = builder.urlFromBuildNumber(buildNumber);
804 this._selectedPoints = points;
805 this.set('details', Ember.Object.create({
806 currentValue: currentMeasurement.mean().toFixed(2),
807 oldValue: oldMeasurement && !isShowingEndPoint ? oldMeasurement.mean().toFixed(2) : null,
808 buildNumber: buildNumber,
810 buildTime: currentMeasurement.formattedBuildTime(),
811 revisions: revisions,
815 _updateBugs: function ()
817 if (!this._selectedPoints)
820 var bugTrackers = App.Manifest.get('bugTrackers');
821 var trackerToBugNumbers = {};
822 bugTrackers.forEach(function (tracker) { trackerToBugNumbers[tracker.get('id')] = new Array(); });
823 this._selectedPoints.map(function (point) {
824 var bugs = point.measurement.bugs();
825 bugTrackers.forEach(function (tracker) {
826 var bugNumber = bugs[tracker.get('id')];
828 trackerToBugNumbers[tracker.get('id')].push(bugNumber);
832 this.set('details.bugTrackers', App.Manifest.get('bugTrackers').map(function (tracker) {
833 var bugNumbers = trackerToBugNumbers[tracker.get('id')];
834 return Ember.ObjectProxy.create({
836 bugs: bugNumbers.map(function (bugNumber) {
838 bugNumber: bugNumber,
839 bugUrl: bugNumber && tracker.get('bugUrl') ? tracker.get('bugUrl').replace(/\$number/g, bugNumber) : null
842 editedBugNumber: this._hasRange ? null : bugNumbers[0],
843 }); // FIXME: Create urls for new bugs.
846 _updateMarkedPoints: function ()
848 var chartData = this.get('chartData');
849 if (!chartData || !chartData.current) {
850 this.set('markedPoints', {});
854 var series = chartData.current.timeSeriesByCommitTime().series();
855 var markedPoints = {};
856 for (var i = 0; i < series.length; i++) {
857 var measurement = series[i].measurement;
858 if (measurement.hasBugs())
859 markedPoints[measurement.id()] = true;
861 this.set('markedPoints', markedPoints);
862 }.observes('chartData'),
865 App.InteractiveChartComponent = Ember.Component.extend({
870 enableSelection: true,
871 classNames: ['chart'],
875 this._needsConstruction = true;
876 this._eventHandlers = [];
877 $(window).resize(this._updateDimensionsIfNeeded.bind(this));
879 chartDataDidChange: function ()
881 var chartData = this.get('chartData');
884 this._needsConstruction = true;
885 this._constructGraphIfPossible(chartData);
886 }.observes('chartData').on('init'),
887 didInsertElement: function ()
889 var chartData = this.get('chartData');
891 this._constructGraphIfPossible(chartData);
893 willClearRender: function ()
895 this._eventHandlers.forEach(function (item) {
896 $(item[0]).off(item[1], item[2]);
899 _attachEventListener: function(target, eventName, listener)
901 this._eventHandlers.push([target, eventName, listener]);
902 $(target).on(eventName, listener);
904 _constructGraphIfPossible: function (chartData)
906 if (!this._needsConstruction || !this.get('element'))
909 var element = this.get('element');
911 this._x = d3.time.scale();
912 this._y = d3.scale.linear();
914 // FIXME: Tear down the old SVG element.
915 this._svgElement = d3.select(element).append("svg")
916 .attr("width", "100%")
917 .attr("height", "100%");
919 var svg = this._svg = this._svgElement.append("g");
921 var clipId = element.id + "-clip";
922 this._clipPath = svg.append("defs").append("clipPath")
926 if (this.get('showXAxis')) {
927 this._xAxis = d3.svg.axis().scale(this._x).orient("bottom").ticks(6);
928 this._xAxisLabels = svg.append("g")
929 .attr("class", "x axis");
932 if (this.get('showYAxis')) {
933 this._yAxis = d3.svg.axis().scale(this._y).orient("left").ticks(6).tickFormat(d3.format("s"));
934 this._yAxisLabels = svg.append("g")
935 .attr("class", "y axis");
938 this._clippedContainer = svg.append("g")
939 .attr("clip-path", "url(#" + clipId + ")");
941 var xScale = this._x;
942 var yScale = this._y;
943 this._timeLine = d3.svg.line()
944 .x(function(point) { return xScale(point.time); })
945 .y(function(point) { return yScale(point.value); });
947 this._confidenceArea = d3.svg.area()
948 // .interpolate("cardinal")
949 .x(function(point) { return xScale(point.time); })
950 .y0(function(point) { return point.interval ? yScale(point.interval[0]) : null; })
951 .y1(function(point) { return point.interval ? yScale(point.interval[1]) : null; });
954 this._paths.forEach(function (path) { path.remove(); });
957 this._areas.forEach(function (area) { area.remove(); });
960 this._dots.forEach(function (dot) { dots.remove(); });
962 if (this._highlights)
963 this._highlights.forEach(function (highlight) { _highlights.remove(); });
964 this._highlights = [];
966 this._currentTimeSeries = chartData.current.timeSeriesByCommitTime();
967 this._currentTimeSeriesData = this._currentTimeSeries.series();
968 this._baselineTimeSeries = chartData.baseline ? chartData.baseline.timeSeriesByCommitTime() : null;
969 this._targetTimeSeries = chartData.target ? chartData.target.timeSeriesByCommitTime() : null;
971 this._yAxisUnit = chartData.unit;
973 var minMax = this._minMaxForAllTimeSeries();
974 var smallEnoughValue = minMax[0] - (minMax[1] - minMax[0]) * 10;
975 var largeEnoughValue = minMax[1] + (minMax[1] - minMax[0]) * 10;
977 // FIXME: Flip the sides based on smallerIsBetter-ness.
978 if (this._baselineTimeSeries) {
979 var data = this._baselineTimeSeries.series();
980 this._areas.push(this._clippedContainer
982 .datum(data.map(function (point) { return {time: point.time, value: point.value, interval: point.interval ? point.interval : [point.value, largeEnoughValue]}; }))
983 .attr("class", "area baseline"));
985 if (this._targetTimeSeries) {
986 var data = this._targetTimeSeries.series();
987 this._areas.push(this._clippedContainer
989 .datum(data.map(function (point) { return {time: point.time, value: point.value, interval: point.interval ? point.interval : [smallEnoughValue, point.value]}; }))
990 .attr("class", "area target"));
993 this._areas.push(this._clippedContainer
995 .datum(this._currentTimeSeriesData)
996 .attr("class", "area"));
998 this._paths.push(this._clippedContainer
1000 .datum(this._currentTimeSeriesData)
1001 .attr("class", "commit-time-line"));
1003 this._dots.push(this._clippedContainer
1005 .data(this._currentTimeSeriesData)
1006 .enter().append("circle")
1007 .attr("class", "dot")
1008 .attr("r", this.get('chartPointRadius') || 1));
1010 if (this.get('interactive')) {
1011 this._attachEventListener(element, "mousemove", this._mouseMoved.bind(this));
1012 this._attachEventListener(element, "mouseleave", this._mouseLeft.bind(this));
1013 this._attachEventListener(element, "mousedown", this._mouseDown.bind(this));
1014 this._attachEventListener($(element).parents("[tabindex]"), "keydown", this._keyPressed.bind(this));
1016 this._currentItemLine = this._clippedContainer
1018 .attr("class", "current-item");
1020 this._currentItemCircle = this._clippedContainer
1022 .attr("class", "dot current-item")
1027 if (this.get('enableSelection')) {
1028 this._brush = d3.svg.brush()
1030 .on("brush", this._brushChanged.bind(this));
1032 this._brushRect = this._clippedContainer
1034 .attr("class", "x brush");
1037 this._updateDomain();
1038 this._updateDimensionsIfNeeded();
1040 // Work around the fact the brush isn't set if we updated it synchronously here.
1041 setTimeout(this._selectionChanged.bind(this), 0);
1043 setTimeout(this._selectedItemChanged.bind(this), 0);
1045 this._needsConstruction = false;
1047 _updateDomain: function ()
1049 var xDomain = this.get('domain');
1050 var intrinsicXDomain = this._computeXAxisDomain(this._currentTimeSeriesData);
1052 xDomain = intrinsicXDomain;
1053 var currentDomain = this._x.domain();
1054 if (currentDomain && this._xDomainsAreSame(currentDomain, xDomain))
1055 return currentDomain;
1057 var yDomain = this._computeYAxisDomain(xDomain[0], xDomain[1]);
1058 this._x.domain(xDomain);
1059 this._y.domain(yDomain);
1060 this.sendAction('domainChanged', xDomain, intrinsicXDomain);
1063 _updateDimensionsIfNeeded: function (newSelection)
1065 var element = $(this.get('element'));
1067 var newTotalWidth = element.width();
1068 var newTotalHeight = element.height();
1069 if (this._totalWidth == newTotalWidth && this._totalHeight == newTotalHeight)
1072 this._totalWidth = newTotalWidth;
1073 this._totalHeight = newTotalHeight;
1076 this._rem = parseFloat(getComputedStyle(document.documentElement).fontSize);
1077 var rem = this._rem;
1079 var padding = 0.5 * rem;
1080 var margin = {top: padding, right: padding, bottom: padding, left: padding};
1082 margin.bottom += rem;
1084 margin.left += 3 * rem;
1086 this._margin = margin;
1087 this._contentWidth = this._totalWidth - margin.left - margin.right;
1088 this._contentHeight = this._totalHeight - margin.top - margin.bottom;
1090 this._svg.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
1093 .attr("width", this._contentWidth)
1094 .attr("height", this._contentHeight);
1096 this._x.range([0, this._contentWidth]);
1097 this._y.range([this._contentHeight, 0]);
1100 this._xAxis.tickSize(-this._contentHeight);
1101 this._xAxisLabels.attr("transform", "translate(0," + this._contentHeight + ")");
1105 this._yAxis.tickSize(-this._contentWidth);
1107 if (this._currentItemLine) {
1108 this._currentItemLine
1110 .attr("y2", margin.top + this._contentHeight);
1113 this._relayoutDataAndAxes(this._currentSelection());
1115 _updateBrush: function ()
1121 .attr("height", this._contentHeight - 2);
1122 this._updateSelectionToolbar();
1124 _relayoutDataAndAxes: function (selection)
1126 var timeline = this._timeLine;
1127 this._paths.forEach(function (path) { path.attr("d", timeline); });
1129 var confidenceArea = this._confidenceArea;
1130 this._areas.forEach(function (path) { path.attr("d", confidenceArea); });
1132 var xScale = this._x;
1133 var yScale = this._y;
1134 this._dots.forEach(function (dot) {
1136 .attr("cx", function(measurement) { return xScale(measurement.time); })
1137 .attr("cy", function(measurement) { return yScale(measurement.value); });
1139 this._updateMarkedDots();
1140 this._updateHighlightPositions();
1144 this._brush.extent(selection);
1146 this._brush.clear();
1147 this._updateBrush();
1150 this._updateCurrentItemIndicators();
1153 this._xAxisLabels.call(this._xAxis);
1157 this._yAxisLabels.call(this._yAxis);
1158 if (this._yAxisUnitContainer)
1159 this._yAxisUnitContainer.remove();
1160 this._yAxisUnitContainer = this._yAxisLabels.append("text")
1161 .attr("x", 0.5 * this._rem)
1162 .attr("y", this._rem)
1163 .attr("dy", '0.8rem')
1164 .style("text-anchor", "start")
1165 .style("z-index", "100")
1166 .text(this._yAxisUnit);
1168 _updateMarkedDots: function () {
1169 var markedPoints = this.get('markedPoints') || {};
1170 var defaultDotRadius = this.get('chartPointRadius') || 1;
1171 this._dots.forEach(function (dot) {
1172 dot.classed('marked', function (point) { return markedPoints[point.measurement.id()]; });
1173 dot.attr('r', function (point) {
1174 return markedPoints[point.measurement.id()] ? defaultDotRadius * 1.5 : defaultDotRadius; });
1176 }.observes('markedPoints'),
1177 _updateHighlightPositions: function () {
1178 var xScale = this._x;
1179 var yScale = this._y;
1180 var y2 = this._margin.top + this._contentHeight;
1181 this._highlights.forEach(function (highlight) {
1185 .attr("y", function(measurement) { return yScale(measurement.value); })
1186 .attr("x1", function(measurement) { return xScale(measurement.time); })
1187 .attr("x2", function(measurement) { return xScale(measurement.time); });
1190 _computeXAxisDomain: function (timeSeries)
1192 var extent = d3.extent(timeSeries, function(point) { return point.time; });
1193 var margin = 3600 * 1000; // Use x.inverse to compute the right amount from a margin.
1194 return [+extent[0] - margin, +extent[1] + margin];
1196 _computeYAxisDomain: function (startTime, endTime)
1198 var range = this._minMaxForAllTimeSeries(startTime, endTime);
1203 var diff = max - min;
1204 var margin = diff * 0.05;
1206 yExtent = [min - margin, max + margin];
1207 // if (yMin !== undefined)
1208 // yExtent[0] = parseInt(yMin);
1211 _minMaxForAllTimeSeries: function (startTime, endTime)
1213 var currentRange = this._currentTimeSeries.minMaxForTimeRange(startTime, endTime);
1214 var baselineRange = this._baselineTimeSeries ? this._baselineTimeSeries.minMaxForTimeRange(startTime, endTime) : [Number.MAX_VALUE, Number.MIN_VALUE];
1215 var targetRange = this._targetTimeSeries ? this._targetTimeSeries.minMaxForTimeRange(startTime, endTime) : [Number.MAX_VALUE, Number.MIN_VALUE];
1217 Math.min(currentRange[0], baselineRange[0], targetRange[0]),
1218 Math.max(currentRange[1], baselineRange[1], targetRange[1]),
1221 _currentSelection: function ()
1223 return this._brush && !this._brush.empty() ? this._brush.extent() : null;
1225 _domainChanged: function ()
1227 var selection = this._currentSelection() || this.get('sharedSelection');
1228 var newXDomain = this._updateDomain();
1230 if (selection && newXDomain && selection[0] <= newXDomain[0] && newXDomain[1] <= selection[1])
1231 selection = null; // Otherwise the user has no way of clearing the selection.
1233 this._relayoutDataAndAxes(selection);
1234 }.observes('domain'),
1235 _selectionChanged: function ()
1237 this._updateSelection(this.get('selection'));
1238 }.observes('selection'),
1239 _sharedSelectionChanged: function ()
1241 if (this.get('selectionIsLocked'))
1243 this._updateSelection(this.get('sharedSelection'));
1244 }.observes('sharedSelection'),
1245 _updateSelection: function (newSelection)
1250 var currentSelection = this._currentSelection();
1251 if (newSelection && currentSelection && this._xDomainsAreSame(newSelection, currentSelection))
1254 var domain = this._x.domain();
1255 if (!newSelection || this._xDomainsAreSame(domain, newSelection))
1256 this._brush.clear();
1258 this._brush.extent(newSelection);
1259 this._updateBrush();
1261 this._setCurrentSelection(newSelection);
1263 _xDomainsAreSame: function (domain1, domain2)
1265 return !(domain1[0] - domain2[0]) && !(domain1[1] - domain2[1]);
1267 _brushChanged: function ()
1269 if (this._brush.empty()) {
1270 if (!this._brushExtent)
1273 this.set('selectionIsLocked', false);
1274 this._setCurrentSelection(undefined);
1276 // Avoid locking the indicator in _mouseDown when the brush was cleared in the same mousedown event.
1277 this._brushJustChanged = true;
1279 setTimeout(function () {
1280 self._brushJustChanged = false;
1286 this.set('selectionIsLocked', true);
1287 this._setCurrentSelection(this._brush.extent());
1289 _keyPressed: function (event)
1291 if (!this._currentItemIndex || this._currentSelection())
1295 switch (event.keyCode) {
1297 newIndex = this._currentItemIndex - 1;
1300 newIndex = this._currentItemIndex + 1;
1308 // Unlike mousemove, keydown shouldn't move off the edge.
1309 if (this._currentTimeSeriesData[newIndex])
1310 this._setCurrentItem(newIndex);
1312 _mouseMoved: function (event)
1314 if (!this._margin || this._currentSelection() || this._currentItemLocked)
1317 var point = this._mousePointInGraph(event);
1319 this._selectClosestPointToMouseAsCurrentItem(point);
1321 _mouseLeft: function (event)
1323 if (!this._margin || this._currentItemLocked)
1326 this._selectClosestPointToMouseAsCurrentItem(null);
1328 _mouseDown: function (event)
1330 if (!this._margin || this._currentSelection() || this._brushJustChanged)
1333 var point = this._mousePointInGraph(event);
1337 if (this._currentItemLocked) {
1338 this._currentItemLocked = false;
1339 this.set('selectedItem', null);
1343 this._currentItemLocked = true;
1344 this._selectClosestPointToMouseAsCurrentItem(point);
1346 _mousePointInGraph: function (event)
1348 var offset = $(this.get('element')).offset();
1353 x: event.pageX - offset.left - this._margin.left,
1354 y: event.pageY - offset.top - this._margin.top
1357 var xScale = this._x;
1358 var yScale = this._y;
1359 var xDomain = xScale.domain();
1360 var yDomain = yScale.domain();
1361 if (point.x >= xScale(xDomain[0]) && point.x <= xScale(xDomain[1])
1362 && point.y <= yScale(yDomain[0]) && point.y >= yScale(yDomain[1]))
1367 _selectClosestPointToMouseAsCurrentItem: function (point)
1369 var xScale = this._x;
1370 var yScale = this._y;
1371 var distanceHeuristics = function (m) {
1372 var mX = xScale(m.time);
1373 var mY = yScale(m.value);
1374 var xDiff = mX - point.x;
1375 var yDiff = mY - point.y;
1376 return xDiff * xDiff + yDiff * yDiff / 16; // Favor horizontal affinity.
1378 distanceHeuristics = function (m) {
1379 return Math.abs(xScale(m.time) - point.x);
1383 if (point && !this._currentSelection()) {
1384 var distances = this._currentTimeSeriesData.map(distanceHeuristics);
1385 var minDistance = Number.MAX_VALUE;
1386 for (var i = 0; i < distances.length; i++) {
1387 if (distances[i] < minDistance) {
1389 minDistance = distances[i];
1394 this._setCurrentItem(newItemIndex);
1395 this._updateSelectionToolbar();
1397 _currentTimeChanged: function ()
1399 if (!this._margin || this._currentSelection() || this._currentItemLocked)
1402 var currentTime = this.get('currentTime');
1404 for (var i = 0; i < this._currentTimeSeriesData.length; i++) {
1405 var point = this._currentTimeSeriesData[i];
1406 if (point.time >= currentTime) {
1407 this._setCurrentItem(i, /* doNotNotify */ true);
1412 this._setCurrentItem(undefined, /* doNotNotify */ true);
1413 }.observes('currentTime'),
1414 _setCurrentItem: function (newItemIndex, doNotNotify)
1416 if (newItemIndex === this._currentItemIndex) {
1417 if (this._currentItemLocked)
1418 this.set('selectedItem', this.get('currentItem') ? this.get('currentItem').measurement.id() : null);
1422 var newItem = this._currentTimeSeriesData[newItemIndex];
1423 this._brushExtent = undefined;
1424 this._currentItemIndex = newItemIndex;
1427 this._currentItemLocked = false;
1428 this.set('selectedItem', null);
1431 this._updateCurrentItemIndicators();
1434 this.set('currentTime', newItem ? newItem.time : undefined);
1436 this.set('currentItem', newItem);
1437 if (this._currentItemLocked)
1438 this.set('selectedItem', newItem ? newItem.measurement.id() : null);
1440 _selectedItemChanged: function ()
1445 var selectedId = this.get('selectedItem');
1446 var currentItem = this.get('currentItem');
1447 if (currentItem && currentItem.measurement.id() == selectedId)
1450 var series = this._currentTimeSeriesData;
1451 var selectedItemIndex = undefined;
1452 for (var i = 0; i < series.length; i++) {
1453 if (series[i].measurement.id() == selectedId) {
1454 this._updateSelection(null);
1455 this._currentItemLocked = true;
1456 this._setCurrentItem(i);
1457 this._updateSelectionToolbar();
1461 }.observes('selectedItem').on('init'),
1462 _highlightedItemsChanged: function () {
1466 var highlightedItems = this.get('highlightedItems');
1468 var data = this._currentTimeSeriesData.filter(function (item) { return highlightedItems[item.measurement.id()]; });
1470 if (this._highlights)
1471 this._highlights.forEach(function (highlight) { highlight.remove(); });
1473 this._highlights.push(this._clippedContainer
1474 .selectAll(".highlight")
1476 .enter().append("line")
1477 .attr("class", "highlight"));
1479 this._updateHighlightPositions();
1481 }.observes('highlightedItems'),
1482 _updateCurrentItemIndicators: function ()
1484 if (!this._currentItemLine)
1487 var item = this._currentTimeSeriesData[this._currentItemIndex];
1489 this._currentItemLine.attr("x1", -1000).attr("x2", -1000);
1490 this._currentItemCircle.attr("cx", -1000);
1494 var x = this._x(item.time);
1495 var y = this._y(item.value);
1497 this._currentItemLine
1501 this._currentItemCircle
1505 _setCurrentSelection: function (newSelection)
1507 if (this._brushExtent === newSelection)
1512 points = this._currentTimeSeriesData
1513 .filter(function (point) { return point.time >= newSelection[0] && point.time <= newSelection[1]; });
1518 this._brushExtent = newSelection;
1519 this._setCurrentItem(undefined);
1520 this._updateSelectionToolbar();
1522 this.set('sharedSelection', newSelection);
1523 this.sendAction('selectionChanged', newSelection, points);
1525 _updateSelectionToolbar: function ()
1527 if (!this.get('interactive'))
1530 var selection = this._currentSelection();
1531 var selectionToolbar = $(this.get('element')).children('.selection-toolbar');
1533 var left = this._x(selection[0]);
1534 var right = this._x(selection[1]);
1536 .css({left: this._margin.left + right, top: this._margin.top + this._contentHeight})
1539 selectionToolbar.hide();
1544 this.sendAction('zoom', this._currentSelection());
1545 this.set('selection', null);
1552 App.CommitsViewerComponent = Ember.Component.extend({
1556 commitsChanged: function ()
1558 var revisionInfo = this.get('revisionInfo');
1560 var to = revisionInfo.get('currentRevision');
1561 var from = revisionInfo.get('previousRevision');
1562 var repository = this.get('repository');
1563 if (!from || !repository || !repository.get('hasReportedCommits'))
1567 CommitLogs.fetchForTimeRange(repository.get('id'), from, to).then(function (commits) {
1568 if (self.isDestroyed)
1570 self.set('commits', commits.map(function (commit) {
1571 return Ember.Object.create({
1572 repository: repository,
1573 revision: commit.revision,
1574 url: repository.urlForRevision(commit.revision),
1575 author: commit.authorName || commit.authorEmail,
1576 message: commit.message ? commit.message.substr(0, 75) : null,
1580 if (!self.isDestroyed)
1581 self.set('commits', []);
1583 }.observes('repository').observes('revisionInfo').on('init'),