1 App.InteractiveChartComponent = Ember.Component.extend({
11 this._needsConstruction = true;
12 this._eventHandlers = [];
13 $(window).resize(this._updateDimensionsIfNeeded.bind(this));
15 chartDataDidChange: function ()
17 var chartData = this.get('chartData');
20 this._needsConstruction = true;
21 this._constructGraphIfPossible(chartData);
22 }.observes('chartData').on('init'),
23 didInsertElement: function ()
25 var chartData = this.get('chartData');
27 this._constructGraphIfPossible(chartData);
29 willClearRender: function ()
31 this._eventHandlers.forEach(function (item) {
32 $(item[0]).off(item[1], item[2]);
35 _attachEventListener: function(target, eventName, listener)
37 this._eventHandlers.push([target, eventName, listener]);
38 $(target).on(eventName, listener);
40 _constructGraphIfPossible: function (chartData)
42 if (!this._needsConstruction || !this.get('element'))
45 var element = this.get('element');
47 this._x = d3.time.scale();
48 this._y = d3.scale.linear();
50 // FIXME: Tear down the old SVG element.
51 this._svgElement = d3.select(element).append("svg")
52 .attr("width", "100%")
53 .attr("height", "100%");
55 var svg = this._svg = this._svgElement.append("g");
57 var clipId = element.id + "-clip";
58 this._clipPath = svg.append("defs").append("clipPath")
62 if (this.get('showXAxis')) {
63 this._xAxis = d3.svg.axis().scale(this._x).orient("bottom").ticks(6);
64 this._xAxisLabels = svg.append("g")
65 .attr("class", "x axis");
68 if (this.get('showYAxis')) {
69 this._yAxis = d3.svg.axis().scale(this._y).orient("left").ticks(6).tickFormat(
70 chartData.useSI ? d3.format("s") : d3.format(".3g"));
71 this._yAxisLabels = svg.append("g")
72 .attr("class", "y axis");
75 this._clippedContainer = svg.append("g")
76 .attr("clip-path", "url(#" + clipId + ")");
80 this._timeLine = d3.svg.line()
81 .x(function(point) { return xScale(point.time); })
82 .y(function(point) { return yScale(point.value); });
84 this._confidenceArea = d3.svg.area()
85 // .interpolate("cardinal")
86 .x(function(point) { return xScale(point.time); })
87 .y0(function(point) { return point.interval ? yScale(point.interval[0]) : null; })
88 .y1(function(point) { return point.interval ? yScale(point.interval[1]) : null; });
91 this._paths.forEach(function (path) { path.remove(); });
94 this._areas.forEach(function (area) { area.remove(); });
97 this._dots.forEach(function (dot) { dots.remove(); });
100 this._highlights.remove();
101 this._highlights = null;
103 this._currentTimeSeries = chartData.current.timeSeriesByCommitTime();
104 this._currentTimeSeriesData = this._currentTimeSeries.series();
105 this._baselineTimeSeries = chartData.baseline ? chartData.baseline.timeSeriesByCommitTime() : null;
106 this._targetTimeSeries = chartData.target ? chartData.target.timeSeriesByCommitTime() : null;
108 this._yAxisUnit = chartData.unit;
110 var minMax = this._minMaxForAllTimeSeries();
111 var smallEnoughValue = minMax[0] - (minMax[1] - minMax[0]) * 10;
112 var largeEnoughValue = minMax[1] + (minMax[1] - minMax[0]) * 10;
114 // FIXME: Flip the sides based on smallerIsBetter-ness.
115 if (this._baselineTimeSeries) {
116 var data = this._baselineTimeSeries.series();
117 this._areas.push(this._clippedContainer
119 .datum(data.map(function (point) { return {time: point.time, value: point.value, interval: point.interval ? point.interval : [point.value, largeEnoughValue]}; }))
120 .attr("class", "area baseline"));
122 if (this._targetTimeSeries) {
123 var data = this._targetTimeSeries.series();
124 this._areas.push(this._clippedContainer
126 .datum(data.map(function (point) { return {time: point.time, value: point.value, interval: point.interval ? point.interval : [smallEnoughValue, point.value]}; }))
127 .attr("class", "area target"));
130 this._areas.push(this._clippedContainer
132 .datum(this._currentTimeSeriesData)
133 .attr("class", "area"));
135 this._paths.push(this._clippedContainer
137 .datum(this._currentTimeSeriesData)
138 .attr("class", "commit-time-line"));
140 this._dots.push(this._clippedContainer
142 .data(this._currentTimeSeriesData)
143 .enter().append("circle")
144 .attr("class", "dot")
145 .attr("r", this.get('chartPointRadius') || 1));
147 if (this.get('interactive')) {
148 this._attachEventListener(element, "mousemove", this._mouseMoved.bind(this));
149 this._attachEventListener(element, "mouseleave", this._mouseLeft.bind(this));
150 this._attachEventListener(element, "mousedown", this._mouseDown.bind(this));
151 this._attachEventListener($(element).parents("[tabindex]"), "keydown", this._keyPressed.bind(this));
153 this._currentItemLine = this._clippedContainer
155 .attr("class", "current-item");
157 this._currentItemCircle = this._clippedContainer
159 .attr("class", "dot current-item")
164 if (this.get('enableSelection')) {
165 this._brush = d3.svg.brush()
167 .on("brush", this._brushChanged.bind(this));
169 this._brushRect = this._clippedContainer
171 .attr("class", "x brush");
174 this._updateDomain();
175 this._updateDimensionsIfNeeded();
177 // Work around the fact the brush isn't set if we updated it synchronously here.
178 setTimeout(this._selectionChanged.bind(this), 0);
180 setTimeout(this._selectedItemChanged.bind(this), 0);
182 this._needsConstruction = false;
184 this._highlightedItemsChanged();
185 this._rangesChanged();
187 _updateDomain: function ()
189 var xDomain = this.get('domain');
190 var intrinsicXDomain = this._computeXAxisDomain(this._currentTimeSeriesData);
192 xDomain = intrinsicXDomain;
193 var currentDomain = this._x.domain();
194 if (currentDomain && App.domainsAreEqual(currentDomain, xDomain))
195 return currentDomain;
197 var yDomain = this._computeYAxisDomain(xDomain[0], xDomain[1]);
198 this._x.domain(xDomain);
199 this._y.domain(yDomain);
202 _updateDimensionsIfNeeded: function (newSelection)
204 var element = $(this.get('element'));
206 var newTotalWidth = element.width();
207 var newTotalHeight = element.height();
208 if (this._totalWidth == newTotalWidth && this._totalHeight == newTotalHeight)
211 this._totalWidth = newTotalWidth;
212 this._totalHeight = newTotalHeight;
215 this._rem = parseFloat(getComputedStyle(document.documentElement).fontSize);
218 var padding = 0.5 * rem;
219 var margin = {top: padding, right: padding, bottom: padding, left: padding};
221 margin.bottom += rem;
223 margin.left += 3 * rem;
225 this._margin = margin;
226 this._contentWidth = this._totalWidth - margin.left - margin.right;
227 this._contentHeight = this._totalHeight - margin.top - margin.bottom;
229 this._svg.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
232 .attr("width", this._contentWidth)
233 .attr("height", this._contentHeight);
235 this._x.range([0, this._contentWidth]);
236 this._y.range([this._contentHeight, 0]);
239 this._xAxis.tickSize(-this._contentHeight);
240 this._xAxisLabels.attr("transform", "translate(0," + this._contentHeight + ")");
244 this._yAxis.tickSize(-this._contentWidth);
246 if (this._currentItemLine) {
247 this._currentItemLine
249 .attr("y2", margin.top + this._contentHeight);
252 this._relayoutDataAndAxes(this._currentSelection());
254 _updateBrush: function ()
260 .attr("height", this._contentHeight - 2);
261 this._updateSelectionToolbar();
263 _relayoutDataAndAxes: function (selection)
265 var timeline = this._timeLine;
266 this._paths.forEach(function (path) { path.attr("d", timeline); });
268 var confidenceArea = this._confidenceArea;
269 this._areas.forEach(function (path) { path.attr("d", confidenceArea); });
271 var xScale = this._x;
272 var yScale = this._y;
273 this._dots.forEach(function (dot) {
275 .attr("cx", function(measurement) { return xScale(measurement.time); })
276 .attr("cy", function(measurement) { return yScale(measurement.value); });
278 this._updateHighlightPositions();
279 this._updateRangeBarRects();
283 this._brush.extent(selection);
289 this._updateCurrentItemIndicators();
292 this._xAxisLabels.call(this._xAxis);
296 this._yAxisLabels.call(this._yAxis);
297 if (this._yAxisUnitContainer)
298 this._yAxisUnitContainer.remove();
299 var x = - 3 * this._rem;
300 var y = this._contentHeight / 2;
301 this._yAxisUnitContainer = this._yAxisLabels.append("text")
302 .attr("transform", "rotate(90 0 0) translate(" + y + ", " + (-x) + ")")
303 .style("text-anchor", "middle")
304 .text(this._yAxisUnit);
306 _updateHighlightPositions: function () {
307 if (!this._highlights)
310 var xScale = this._x;
311 var yScale = this._y;
313 .attr("cy", function(point) { return yScale(point.value); })
314 .attr("cx", function(point) { return xScale(point.time); });
316 _computeXAxisDomain: function (timeSeries)
318 var extent = d3.extent(timeSeries, function(point) { return point.time; });
319 var margin = 3600 * 1000; // Use x.inverse to compute the right amount from a margin.
320 return [+extent[0] - margin, +extent[1] + margin];
322 _computeYAxisDomain: function (startTime, endTime)
324 var range = this._minMaxForAllTimeSeries(startTime, endTime);
329 var diff = max - min;
330 var margin = diff * 0.05;
332 yExtent = [min - margin, max + margin];
333 // if (yMin !== undefined)
334 // yExtent[0] = parseInt(yMin);
337 _minMaxForAllTimeSeries: function (startTime, endTime)
339 var currentRange = this._currentTimeSeries.minMaxForTimeRange(startTime, endTime);
340 var baselineRange = this._baselineTimeSeries ? this._baselineTimeSeries.minMaxForTimeRange(startTime, endTime) : [Number.MAX_VALUE, Number.MIN_VALUE];
341 var targetRange = this._targetTimeSeries ? this._targetTimeSeries.minMaxForTimeRange(startTime, endTime) : [Number.MAX_VALUE, Number.MIN_VALUE];
343 Math.min(currentRange[0], baselineRange[0], targetRange[0]),
344 Math.max(currentRange[1], baselineRange[1], targetRange[1]),
347 _currentSelection: function ()
349 return this._brush && !this._brush.empty() ? this._brush.extent() : null;
351 _domainChanged: function ()
353 var selection = this._currentSelection() || this.get('sharedSelection');
354 var newXDomain = this._updateDomain();
356 if (selection && newXDomain && selection[0] <= newXDomain[0] && newXDomain[1] <= selection[1])
357 selection = null; // Otherwise the user has no way of clearing the selection.
359 this._relayoutDataAndAxes(selection);
360 }.observes('domain'),
361 _selectionChanged: function ()
363 this._updateSelection(this.get('selection'));
364 }.observes('selection'),
365 _updateSelection: function (newSelection)
370 var currentSelection = this._currentSelection();
371 if (newSelection && currentSelection && App.domainsAreEqual(newSelection, currentSelection))
374 var domain = this._x.domain();
375 if (!newSelection || App.domainsAreEqual(domain, newSelection))
378 this._brush.extent(newSelection);
381 this._setCurrentSelection(newSelection);
383 _brushChanged: function ()
385 if (this._brush.empty()) {
386 if (!this._brushExtent)
389 this.set('selectionIsLocked', false);
390 this._setCurrentSelection(undefined);
392 // Avoid locking the indicator in _mouseDown when the brush was cleared in the same mousedown event.
393 this._brushJustChanged = true;
395 setTimeout(function () {
396 self._brushJustChanged = false;
402 this.set('selectionIsLocked', true);
403 this._setCurrentSelection(this._brush.extent());
405 _keyPressed: function (event)
407 if (!this._currentItemIndex || this._currentSelection())
411 switch (event.keyCode) {
413 newIndex = this._currentItemIndex - 1;
416 newIndex = this._currentItemIndex + 1;
424 // Unlike mousemove, keydown shouldn't move off the edge.
425 if (this._currentTimeSeriesData[newIndex])
426 this._setCurrentItem(newIndex);
428 _mouseMoved: function (event)
430 if (!this._margin || this._currentSelection() || this._currentItemLocked)
433 var point = this._mousePointInGraph(event);
435 this._selectClosestPointToMouseAsCurrentItem(point);
437 _mouseLeft: function (event)
439 if (!this._margin || this._currentItemLocked)
442 this._selectClosestPointToMouseAsCurrentItem(null);
444 _mouseDown: function (event)
446 if (!this._margin || this._currentSelection() || this._brushJustChanged)
449 var point = this._mousePointInGraph(event);
453 if (this._currentItemLocked) {
454 this._currentItemLocked = false;
455 this.set('selectedItem', null);
459 this._currentItemLocked = true;
460 this._selectClosestPointToMouseAsCurrentItem(point);
462 _mousePointInGraph: function (event)
464 var offset = $(this.get('element')).offset();
465 if (!offset || !$(event.target).closest('svg').length)
469 x: event.pageX - offset.left - this._margin.left,
470 y: event.pageY - offset.top - this._margin.top
473 var xScale = this._x;
474 var yScale = this._y;
475 var xDomain = xScale.domain();
476 var yDomain = yScale.domain();
477 if (point.x >= xScale(xDomain[0]) && point.x <= xScale(xDomain[1])
478 && point.y <= yScale(yDomain[0]) && point.y >= yScale(yDomain[1]))
483 _selectClosestPointToMouseAsCurrentItem: function (point)
485 var xScale = this._x;
486 var yScale = this._y;
487 var distanceHeuristics = function (m) {
488 var mX = xScale(m.time);
489 var mY = yScale(m.value);
490 var xDiff = mX - point.x;
491 var yDiff = mY - point.y;
492 return xDiff * xDiff + yDiff * yDiff / 16; // Favor horizontal affinity.
494 distanceHeuristics = function (m) {
495 return Math.abs(xScale(m.time) - point.x);
499 if (point && !this._currentSelection()) {
500 var distances = this._currentTimeSeriesData.map(distanceHeuristics);
501 var minDistance = Number.MAX_VALUE;
502 for (var i = 0; i < distances.length; i++) {
503 if (distances[i] < minDistance) {
505 minDistance = distances[i];
510 this._setCurrentItem(newItemIndex);
511 this._updateSelectionToolbar();
513 _currentTimeChanged: function ()
515 if (!this._margin || this._currentSelection() || this._currentItemLocked)
518 var currentTime = this.get('currentTime');
520 for (var i = 0; i < this._currentTimeSeriesData.length; i++) {
521 var point = this._currentTimeSeriesData[i];
522 if (point.time >= currentTime) {
523 this._setCurrentItem(i, /* doNotNotify */ true);
528 this._setCurrentItem(undefined, /* doNotNotify */ true);
529 }.observes('currentTime'),
530 _setCurrentItem: function (newItemIndex, doNotNotify)
532 if (newItemIndex === this._currentItemIndex) {
533 if (this._currentItemLocked)
534 this.set('selectedItem', this.get('currentItem') ? this.get('currentItem').measurement.id() : null);
538 var newItem = this._currentTimeSeriesData[newItemIndex];
539 this._brushExtent = undefined;
540 this._currentItemIndex = newItemIndex;
543 this._currentItemLocked = false;
544 this.set('selectedItem', null);
547 this._updateCurrentItemIndicators();
550 this.set('currentTime', newItem ? newItem.time : undefined);
552 this.set('currentItem', newItem);
553 if (this._currentItemLocked)
554 this.set('selectedItem', newItem ? newItem.measurement.id() : null);
556 _selectedItemChanged: function ()
561 var selectedId = this.get('selectedItem');
562 var currentItem = this.get('currentItem');
563 if (currentItem && currentItem.measurement.id() == selectedId)
566 var series = this._currentTimeSeriesData;
567 var selectedItemIndex = undefined;
568 for (var i = 0; i < series.length; i++) {
569 if (series[i].measurement.id() == selectedId) {
570 this._updateSelection(null);
571 this._currentItemLocked = true;
572 this._setCurrentItem(i);
573 this._updateSelectionToolbar();
577 }.observes('selectedItem').on('init'),
578 _highlightedItemsChanged: function () {
579 var highlightedItems = this.get('highlightedItems');
581 if (!this._clippedContainer || !highlightedItems)
584 var data = this._currentTimeSeriesData.filter(function (item) { return highlightedItems[item.measurement.id()]; });
586 if (this._highlights)
587 this._highlights.remove();
588 this._highlights = this._clippedContainer
589 .selectAll(".highlight")
591 .enter().append("circle")
592 .attr("class", "highlight")
593 .attr("r", (this.get('chartPointRadius') || 1) * 1.8);
595 this._updateHighlightPositions();
596 }.observes('highlightedItems'),
597 _rangesChanged: function ()
599 if (!this._currentTimeSeries)
602 function midPoint(firstPoint, secondPoint) {
603 if (firstPoint && secondPoint)
604 return (+firstPoint.time + +secondPoint.time) / 2;
606 return firstPoint.time;
607 return secondPoint.time;
609 var currentTimeSeries = this._currentTimeSeries;
610 var linkRoute = this.get('rangeRoute');
611 this.set('rangeBars', (this.get('ranges') || []).map(function (range) {
612 var start = currentTimeSeries.findPointByMeasurementId(range.get('startRun'));
613 var end = currentTimeSeries.findPointByMeasurementId(range.get('endRun'));
614 return Ember.Object.create({
615 startTime: midPoint(currentTimeSeries.previousPoint(start), start),
616 endTime: midPoint(end, currentTimeSeries.nextPoint(end)),
623 linkRoute: linkRoute,
624 linkId: range.get('id'),
625 label: range.get('label'),
629 this._updateRangeBarRects();
630 }.observes('ranges'),
631 _updateRangeBarRects: function () {
632 var rangeBars = this.get('rangeBars');
633 if (!rangeBars || !rangeBars.length)
636 var xScale = this._x;
637 var yScale = this._y;
639 // Expand the width of each range as needed and sort ranges by the left-edge of ranges.
641 var sortedBars = rangeBars.map(function (bar) {
642 var left = xScale(bar.get('startTime'));
643 var right = xScale(bar.get('endTime'));
644 if (right - left < minWidth) {
645 left -= minWidth / 2;
646 right += minWidth / 2;
648 bar.set('left', left);
649 bar.set('right', right);
651 }).sort(function (first, second) { return first.get('left') - second.get('left'); });
653 // At this point, left edges of all ranges prior to a range R1 is on the left of R1.
654 // Place R1 into a row in which right edges of all ranges prior to R1 is on the left of R1 to avoid overlapping ranges.
656 sortedBars.forEach(function (bar) {
658 for (; rowIndex < rows.length; rowIndex++) {
659 var currentRow = rows[rowIndex];
660 if (currentRow[currentRow.length - 1].get('right') < bar.get('left')) {
661 currentRow.push(bar);
665 if (rowIndex >= rows.length)
667 bar.set('rowIndex', rowIndex);
669 var rowHeight = 0.6 * this._rem;
670 var firstRowTop = this._contentHeight - rows.length * rowHeight;
671 var barHeight = 0.5 * this._rem;
673 $(this.get('element')).find('.rangeBarsContainerInlineStyle').css({
674 left: this._margin.left + 'px',
675 top: this._margin.top + firstRowTop + 'px',
676 width: this._contentWidth + 'px',
677 height: rows.length * barHeight + 'px',
679 position: 'absolute',
682 var margin = this._margin;
683 sortedBars.forEach(function (bar) {
684 var top = bar.get('rowIndex') * rowHeight;
685 var height = barHeight;
686 var left = bar.get('left');
687 var width = bar.get('right') - left;
688 bar.set('inlineStyle', 'left: ' + left + 'px; top: ' + top + 'px; width: ' + width + 'px; height: ' + height + 'px;');
691 _updateCurrentItemIndicators: function ()
693 if (!this._currentItemLine)
696 var item = this._currentTimeSeriesData[this._currentItemIndex];
698 this._currentItemLine.attr("x1", -1000).attr("x2", -1000);
699 this._currentItemCircle.attr("cx", -1000);
703 var x = this._x(item.time);
704 var y = this._y(item.value);
706 this._currentItemLine
710 this._currentItemCircle
714 _setCurrentSelection: function (newSelection)
716 if (this._brushExtent === newSelection)
721 points = this._currentTimeSeriesData
722 .filter(function (point) { return point.time >= newSelection[0] && point.time <= newSelection[1]; });
727 this._brushExtent = newSelection;
728 this._setCurrentItem(undefined);
729 this._updateSelectionToolbar();
731 if (!App.domainsAreEqual(this.get('selection'), newSelection))
732 this.set('selection', newSelection);
733 this.set('selectedPoints', points);
735 _updateSelectionToolbar: function ()
737 if (!this.get('interactive'))
740 var selection = this._currentSelection();
741 var selectionToolbar = $(this.get('element')).children('.selection-toolbar');
743 var left = this._x(selection[0]);
744 var right = this._x(selection[1]);
746 .css({left: this._margin.left + right, top: this._margin.top + this._contentHeight})
749 selectionToolbar.hide();
754 this.sendAction('zoom', this._currentSelection());
755 this.set('selection', null);
757 openRange: function (range)
759 this.sendAction('openRange', range);