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._totalWidth = undefined;
22 this._totalHeight = undefined;
23 this._constructGraphIfPossible(chartData);
24 }.observes('chartData').on('init'),
25 didInsertElement: function ()
27 var chartData = this.get('chartData');
29 this._constructGraphIfPossible(chartData);
31 if (this.get('interactive')) {
32 var element = this.get('element');
33 this._attachEventListener(element, "mousemove", this._mouseMoved.bind(this));
34 this._attachEventListener(element, "mouseleave", this._mouseLeft.bind(this));
35 this._attachEventListener(element, "mousedown", this._mouseDown.bind(this));
36 this._attachEventListener($(element).parents("[tabindex]"), "keydown", this._keyPressed.bind(this));
39 willClearRender: function ()
41 this._eventHandlers.forEach(function (item) {
42 $(item[0]).off(item[1], item[2]);
45 _attachEventListener: function(target, eventName, listener)
47 this._eventHandlers.push([target, eventName, listener]);
48 $(target).on(eventName, listener);
50 _constructGraphIfPossible: function (chartData)
52 if (!this._needsConstruction || !this.get('element'))
55 var element = this.get('element');
57 this._x = d3.time.scale();
58 this._y = d3.scale.linear();
61 this._svgElement.remove();
62 this._svgElement = d3.select(element).append("svg")
63 .attr("width", "100%")
64 .attr("height", "100%");
66 var svg = this._svg = this._svgElement.append("g");
68 var clipId = element.id + "-clip";
69 this._clipPath = svg.append("defs").append("clipPath")
73 if (this.get('showXAxis')) {
74 this._xAxis = d3.svg.axis().scale(this._x).orient("bottom").ticks(6);
75 this._xAxisLabels = svg.append("g")
76 .attr("class", "x axis");
79 var isInteractive = this.get('interactive');
80 if (this.get('showYAxis')) {
81 this._yAxis = d3.svg.axis().scale(this._y).orient("left").ticks(6).tickFormat(chartData.formatter);
83 this._yAxisLabels = svg.append('g').attr('class', 'y axis' + (isInteractive ? ' interactive' : ''));
86 this._yAxisLabels.on('click', function () { self.toggleProperty('showFullYAxis'); });
90 this._clippedContainer = svg.append("g")
91 .attr("clip-path", "url(#" + clipId + ")");
95 this._timeLine = d3.svg.line()
96 .x(function(point) { return xScale(point.time); })
97 .y(function(point) { return yScale(point.value); });
99 this._confidenceArea = d3.svg.area()
100 // .interpolate("cardinal")
101 .x(function(point) { return xScale(point.time); })
102 .y0(function(point) { return point.interval ? yScale(point.interval[0]) : null; })
103 .y1(function(point) { return point.interval ? yScale(point.interval[1]) : null; });
108 this._highlights = null;
110 this._currentTimeSeries = chartData.current;
111 this._currentTimeSeriesData = this._currentTimeSeries.series();
112 this._baselineTimeSeries = chartData.baseline;
113 this._targetTimeSeries = chartData.target;
114 this._movingAverageTimeSeries = chartData.movingAverage;
116 if (this._baselineTimeSeries) {
117 this._paths.push(this._clippedContainer
119 .datum(this._baselineTimeSeries.series())
120 .attr("class", "baseline"));
122 if (this._targetTimeSeries) {
123 this._paths.push(this._clippedContainer
125 .datum(this._targetTimeSeries.series())
126 .attr("class", "target"));
129 var movingAverageIsVisible = this._movingAverageTimeSeries;
130 var foregroundClass = movingAverageIsVisible ? '' : ' foreground';
131 this._areas.push(this._clippedContainer
133 .datum(this._currentTimeSeriesData)
134 .attr("class", "area" + foregroundClass));
136 this._paths.push(this._clippedContainer
138 .datum(this._currentTimeSeriesData)
139 .attr("class", "current" + foregroundClass));
141 this._dots.push(this._clippedContainer
143 .data(this._currentTimeSeriesData)
144 .enter().append("circle")
145 .attr("class", "dot" + foregroundClass)
146 .attr("r", this.get('chartPointRadius') || 1));
148 if (movingAverageIsVisible) {
149 this._paths.push(this._clippedContainer
151 .datum(this._movingAverageTimeSeries.series())
152 .attr("class", "movingAverage"));
154 this._areas.push(this._clippedContainer
156 .datum(this._movingAverageTimeSeries.series())
157 .attr("class", "envelope"));
161 this._currentItemLine = this._clippedContainer
163 .attr("class", "current-item");
165 this._currentItemCircle = this._clippedContainer
167 .attr("class", "dot current-item")
172 if (this.get('enableSelection')) {
173 this._brush = d3.svg.brush()
175 .on("brush", this._brushChanged.bind(this));
177 this._brushRect = this._clippedContainer
179 .attr("class", "x brush");
182 this._updateDomain();
183 this._updateDimensionsIfNeeded();
185 // Work around the fact the brush isn't set if we updated it synchronously here.
186 setTimeout(this._selectionChanged.bind(this), 0);
188 setTimeout(this._selectedItemChanged.bind(this), 0);
190 this._needsConstruction = false;
192 this._highlightedItemsChanged();
193 this._rangesChanged();
195 _updateDomain: function ()
197 var xDomain = this.get('domain');
198 if (!xDomain || !this._currentTimeSeriesData)
200 var intrinsicXDomain = this._computeXAxisDomain(this._currentTimeSeriesData);
202 xDomain = intrinsicXDomain;
203 var yDomain = this._computeYAxisDomain(xDomain[0], xDomain[1]);
205 var currentXDomain = this._x.domain();
206 var currentYDomain = this._y.domain();
207 if (currentXDomain && App.domainsAreEqual(currentXDomain, xDomain)
208 && currentYDomain && App.domainsAreEqual(currentYDomain, yDomain))
209 return currentXDomain;
211 this._x.domain(xDomain);
212 this._y.domain(yDomain);
215 _updateDimensionsIfNeeded: function (newSelection)
217 var element = $(this.get('element'));
219 var newTotalWidth = element.width();
220 var newTotalHeight = element.height();
221 if (this._totalWidth == newTotalWidth && this._totalHeight == newTotalHeight)
224 this._totalWidth = newTotalWidth;
225 this._totalHeight = newTotalHeight;
228 this._rem = parseFloat(getComputedStyle(document.documentElement).fontSize);
231 var padding = 0.5 * rem;
232 var margin = {top: padding, right: padding, bottom: padding, left: padding};
234 margin.bottom += rem;
236 margin.left += 3 * rem;
238 this._margin = margin;
239 this._contentWidth = Math.max(0, this._totalWidth - margin.left - margin.right);
240 this._contentHeight = Math.max(0, this._totalHeight - margin.top - margin.bottom);
242 this._svg.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
245 .attr("width", this._contentWidth)
246 .attr("height", this._contentHeight);
248 this._x.range([0, this._contentWidth]);
249 this._y.range([this._contentHeight, 0]);
252 this._xAxis.ticks(Math.round(this._contentWidth / 4 / rem));
253 this._xAxis.tickSize(-this._contentHeight);
254 this._xAxisLabels.attr("transform", "translate(0," + this._contentHeight + ")");
258 this._yAxis.ticks(Math.round(this._contentHeight / 2 / rem));
259 this._yAxis.tickSize(-this._contentWidth);
262 if (this._currentItemLine) {
263 this._currentItemLine
265 .attr("y2", margin.top + this._contentHeight);
268 this._relayoutDataAndAxes(this._currentSelection());
270 _updateBrush: function ()
276 .attr("height", Math.max(0, this._contentHeight - 2));
277 this._updateSelectionToolbar();
279 _relayoutDataAndAxes: function (selection)
281 var timeline = this._timeLine;
282 this._paths.forEach(function (path) { path.attr("d", timeline); });
284 var confidenceArea = this._confidenceArea;
285 this._areas.forEach(function (path) { path.attr("d", confidenceArea); });
287 var xScale = this._x;
288 var yScale = this._y;
289 this._dots.forEach(function (dot) {
291 .attr("cx", function(measurement) { return xScale(measurement.time); })
292 .attr("cy", function(measurement) { return yScale(measurement.value); });
294 this._updateHighlightPositions();
295 this._updateRangeBarRects();
299 this._brush.extent(selection);
305 this._updateCurrentItemIndicators();
308 this._xAxisLabels.call(this._xAxis);
312 this._yAxisLabels.call(this._yAxis);
313 var x = - 3.2 * this._rem;
314 var y = this._contentHeight / 2;
316 _updateHighlightPositions: function () {
317 if (!this._highlights)
320 var xScale = this._x;
321 var yScale = this._y;
323 .attr("cy", function(point) { return yScale(point.value); })
324 .attr("cx", function(point) { return xScale(point.time); });
326 _computeXAxisDomain: function (timeSeries)
328 var extent = d3.extent(timeSeries, function(point) { return point.time; });
329 var margin = 3600 * 1000; // Use x.inverse to compute the right amount from a margin.
330 return [+extent[0] - margin, +extent[1] + margin];
332 _computeYAxisDomain: function (startTime, endTime)
334 var shouldShowFullYAxis = this.get('showFullYAxis');
335 var range = this._minMaxForAllTimeSeries(startTime, endTime, !shouldShowFullYAxis);
339 var highlightedItems = this.get('highlightedItems');
340 if (highlightedItems) {
341 var data = this._currentTimeSeriesData
342 .filter(function (point) { return startTime <= point.time && point.time <= endTime && highlightedItems[point.measurement.id()]; })
343 .map(function (point) { return point.value });
344 min = Math.min(min, Statistics.min(data));
345 max = Math.max(max, Statistics.max(data));
350 else if (shouldShowFullYAxis)
351 min = Math.min(min, 0);
352 var diff = max - min;
353 var margin = diff * 0.05;
355 yExtent = [min - margin, max + margin];
358 _minMaxForAllTimeSeries: function (startTime, endTime, ignoreOutliners)
360 var seriesList = [this._currentTimeSeries, this._movingAverageTimeSeries, this._baselineTimeSeries, this._targetTimeSeries];
363 for (var i = 0; i < seriesList.length; i++) {
365 var minMax = seriesList[i].minMaxForTimeRange(startTime, endTime, ignoreOutliners);
366 min = Math.min(min, minMax[0]);
367 max = Math.max(max, minMax[1]);
372 _currentSelection: function ()
374 return this._brush && !this._brush.empty() ? this._brush.extent() : null;
376 _domainChanged: function ()
378 var selection = this._currentSelection() || this.get('sharedSelection');
379 var newXDomain = this._updateDomain();
383 if (selection && newXDomain && selection[0] <= newXDomain[0] && newXDomain[1] <= selection[1])
384 selection = null; // Otherwise the user has no way of clearing the selection.
386 this._relayoutDataAndAxes(selection);
387 }.observes('domain', 'showFullYAxis'),
388 _selectionChanged: function ()
390 this._updateSelection(this.get('selection'));
391 }.observes('selection'),
392 _updateSelection: function (newSelection)
397 var currentSelection = this._currentSelection();
398 if (newSelection && currentSelection && App.domainsAreEqual(newSelection, currentSelection))
401 var domain = this._x.domain();
402 if (!newSelection || App.domainsAreEqual(domain, newSelection))
405 this._brush.extent(newSelection);
408 this._setCurrentSelection(newSelection);
410 _brushChanged: function ()
412 if (this._brush.empty()) {
413 if (!this._brushExtent)
416 this._setCurrentSelection(undefined);
418 // Avoid locking the indicator in _mouseDown when the brush was cleared in the same mousedown event.
419 this._brushJustChanged = true;
421 setTimeout(function () {
422 self._brushJustChanged = false;
428 this._setCurrentSelection(this._brush.extent());
430 _keyPressed: function (event)
432 if (!this._currentItemIndex || this._currentSelection())
436 switch (event.keyCode) {
438 newIndex = this._currentItemIndex - 1;
441 newIndex = this._currentItemIndex + 1;
449 // Unlike mousemove, keydown shouldn't move off the edge.
450 if (this._currentTimeSeriesData[newIndex])
451 this._setCurrentItem(newIndex);
453 _mouseMoved: function (event)
455 if (!this._margin || this._currentSelection() || this._currentItemLocked)
458 var point = this._mousePointInGraph(event);
460 this._selectClosestPointToMouseAsCurrentItem(point);
462 _mouseLeft: function (event)
464 if (!this._margin || this._currentItemLocked)
467 this._selectClosestPointToMouseAsCurrentItem(null);
469 _mouseDown: function (event)
471 if (!this._margin || this._currentSelection() || this._brushJustChanged)
474 var point = this._mousePointInGraph(event);
478 if (this._currentItemLocked) {
479 this._currentItemLocked = false;
480 this.set('selectedItem', null);
484 this._currentItemLocked = true;
485 this._selectClosestPointToMouseAsCurrentItem(point);
487 _mousePointInGraph: function (event)
489 var offset = $(this.get('element')).offset();
490 if (!offset || !$(event.target).closest('svg').length)
494 x: event.pageX - offset.left - this._margin.left,
495 y: event.pageY - offset.top - this._margin.top
498 var xScale = this._x;
499 var yScale = this._y;
500 var xDomain = xScale.domain();
501 var yDomain = yScale.domain();
502 if (point.x >= xScale(xDomain[0]) && point.x <= xScale(xDomain[1])
503 && point.y <= yScale(yDomain[0]) && point.y >= yScale(yDomain[1]))
508 _selectClosestPointToMouseAsCurrentItem: function (point)
510 var xScale = this._x;
511 var yScale = this._y;
512 var distanceHeuristics = function (m) {
513 var mX = xScale(m.time);
514 var mY = yScale(m.value);
515 var xDiff = mX - point.x;
516 var yDiff = mY - point.y;
517 return xDiff * xDiff + yDiff * yDiff / 16; // Favor horizontal affinity.
521 if (point && !this._currentSelection()) {
522 var distances = this._currentTimeSeriesData.map(distanceHeuristics);
523 var minDistance = Number.MAX_VALUE;
524 for (var i = 0; i < distances.length; i++) {
525 if (distances[i] < minDistance) {
527 minDistance = distances[i];
532 this._setCurrentItem(newItemIndex);
533 this._updateSelectionToolbar();
535 _currentTimeChanged: function ()
537 if (!this._margin || this._currentSelection() || this._currentItemLocked)
540 var currentTime = this.get('currentTime');
542 for (var i = 0; i < this._currentTimeSeriesData.length; i++) {
543 var point = this._currentTimeSeriesData[i];
544 if (point.time >= currentTime) {
545 this._setCurrentItem(i, /* doNotNotify */ true);
550 this._setCurrentItem(undefined, /* doNotNotify */ true);
551 }.observes('currentTime'),
552 _setCurrentItem: function (newItemIndex, doNotNotify)
554 if (newItemIndex === this._currentItemIndex) {
555 if (this._currentItemLocked)
556 this.set('selectedItem', this.get('currentItem') ? this.get('currentItem').measurement.id() : null);
560 var newItem = this._currentTimeSeriesData[newItemIndex];
561 this._brushExtent = undefined;
562 this._currentItemIndex = newItemIndex;
565 this._currentItemLocked = false;
566 this.set('selectedItem', null);
569 this._updateCurrentItemIndicators();
572 this.set('currentTime', newItem ? newItem.time : undefined);
574 this.set('currentItem', newItem);
575 if (this._currentItemLocked)
576 this.set('selectedItem', newItem ? newItem.measurement.id() : null);
578 _selectedItemChanged: function ()
583 var selectedId = this.get('selectedItem');
584 var currentItem = this.get('currentItem');
585 if (currentItem && currentItem.measurement.id() == selectedId)
588 var series = this._currentTimeSeriesData;
589 var selectedItemIndex = undefined;
590 for (var i = 0; i < series.length; i++) {
591 if (series[i].measurement.id() == selectedId) {
592 this._updateSelection(null);
593 this._currentItemLocked = true;
594 this._setCurrentItem(i);
595 this._updateSelectionToolbar();
599 }.observes('selectedItem').on('init'),
600 _highlightedItemsChanged: function () {
601 var highlightedItems = this.get('highlightedItems');
603 if (!this._clippedContainer || !highlightedItems)
606 var data = this._currentTimeSeriesData.filter(function (item) { return highlightedItems[item.measurement.id()]; });
608 if (this._highlights)
609 this._highlights.remove();
610 this._highlights = this._clippedContainer
611 .selectAll(".highlight")
613 .enter().append("circle")
614 .attr("class", "highlight")
615 .attr("r", (this.get('chartPointRadius') || 1) * 1.8);
617 this._domainChanged();
618 }.observes('highlightedItems'),
619 _rangesChanged: function ()
621 var linkRoute = this.get('rangeRoute');
622 this.set('rangeBars', (this.get('ranges') || []).map(function (range) {
623 return Ember.Object.create({
624 startTime: range.get('startTime'),
625 endTime: range.get('endTime'),
632 linkRoute: linkRoute,
633 linkId: range.get('id'),
634 label: range.get('label'),
635 status: range.get('status'),
639 this._updateRangeBarRects();
640 }.observes('ranges'),
641 _updateRangeBarRects: function () {
642 var rangeBars = this.get('rangeBars');
643 if (!rangeBars || !rangeBars.length)
646 var xScale = this._x;
647 var yScale = this._y;
649 // Expand the width of each range as needed and sort ranges by the left-edge of ranges.
651 var sortedBars = rangeBars.map(function (bar) {
652 var left = xScale(bar.get('startTime'));
653 var right = xScale(bar.get('endTime'));
654 if (right - left < minWidth) {
655 left -= minWidth / 2;
656 right += minWidth / 2;
658 bar.set('left', left);
659 bar.set('right', right);
661 }).sort(function (first, second) { return first.get('left') - second.get('left'); });
663 // At this point, left edges of all ranges prior to a range R1 is on the left of R1.
664 // 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.
666 sortedBars.forEach(function (bar) {
668 for (; rowIndex < rows.length; rowIndex++) {
669 var currentRow = rows[rowIndex];
670 if (currentRow[currentRow.length - 1].get('right') < bar.get('left')) {
671 currentRow.push(bar);
675 if (rowIndex >= rows.length)
677 bar.set('rowIndex', rowIndex);
679 var rowHeight = 0.6 * this._rem;
680 var firstRowTop = this._contentHeight - rows.length * rowHeight;
681 var barHeight = 0.5 * this._rem;
683 $(this.get('element')).find('.rangeBarsContainerInlineStyle').css({
684 left: this._margin.left + 'px',
685 top: this._margin.top + firstRowTop + 'px',
686 width: this._contentWidth + 'px',
687 height: rows.length * barHeight + 'px',
689 position: 'absolute',
692 var margin = this._margin;
693 sortedBars.forEach(function (bar) {
694 var top = bar.get('rowIndex') * rowHeight;
695 var height = barHeight;
696 var left = bar.get('left');
697 var width = bar.get('right') - left;
698 bar.set('inlineStyle', 'left: ' + left + 'px; top: ' + top + 'px; width: ' + width + 'px; height: ' + height + 'px;');
701 _updateCurrentItemIndicators: function ()
703 if (!this._currentItemLine)
706 var item = this._currentTimeSeriesData[this._currentItemIndex];
708 this._currentItemLine.attr("x1", -1000).attr("x2", -1000);
709 this._currentItemCircle.attr("cx", -1000);
713 var x = this._x(item.time);
714 var y = this._y(item.value);
716 this._currentItemLine
720 this._currentItemCircle
724 _setCurrentSelection: function (newSelection)
726 if (this._brushExtent === newSelection)
731 points = this._currentTimeSeriesData
732 .filter(function (point) { return point.time >= newSelection[0] && point.time <= newSelection[1]; });
737 this._brushExtent = newSelection;
738 this._setCurrentItem(undefined);
739 this._updateSelectionToolbar();
741 if (!App.domainsAreEqual(this.get('selection'), newSelection))
742 this.set('selection', newSelection);
743 this.set('selectedPoints', points);
745 _updateSelectionToolbar: function ()
747 if (!this.get('zoomable'))
750 var selection = this._currentSelection();
751 var selectionToolbar = $(this.get('element')).children('.selection-toolbar');
753 var left = this._x(selection[0]);
754 var right = this._x(selection[1]);
756 .css({left: this._margin.left + right, top: this._margin.top + this._contentHeight})
759 selectionToolbar.hide();
764 this.sendAction('zoom', this._currentSelection());
765 this.set('selection', null);
767 openRange: function (range)
769 this.sendAction('openRange', range);