Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / webapp / static / fusion / raptor / d3 / js / models / lineChart.js
1
2 nv.models.lineChart = function() {
3   "use strict";
4   //============================================================
5   // Public Variables with Default Settings
6   //------------------------------------------------------------
7
8   var lines = nv.models.line()
9     , xAxis = nv.models.axis()
10     , yAxis = nv.models.axis()
11     , legend = nv.models.legend()
12     , interactiveLayer = nv.interactiveGuideline()
13     ;
14
15   var margin = {top: 30, right: 20, bottom: 50, left: 60}
16     , color = nv.utils.defaultColor()
17     , width = null
18     , height = null
19     , showLegend = true
20     , showXAxis = true
21     , showYAxis = true
22     , rightAlignYAxis = false
23     , useInteractiveGuideline = false
24     , tooltips = true
25     , tooltip = function(key, x, y, e, graph) {
26         return '<h3>' + key + '</h3>' +
27                '<p>' +  y + ' at ' + x + '</p>'
28       }
29     , x
30     , y
31     , state = {}
32     , defaultState = null
33     , noData = 'No Data Available.'
34     , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState')
35     , transitionDuration = 250
36     ;
37
38   xAxis
39     .orient('bottom')
40     .tickPadding(7)
41     ;
42   yAxis
43     .orient((rightAlignYAxis) ? 'right' : 'left')
44     ;
45
46   //============================================================
47
48
49   //============================================================
50   // Private Variables
51   //------------------------------------------------------------
52
53   var showTooltip = function(e, offsetElement) {
54     var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
55         top = e.pos[1] + ( offsetElement.offsetTop || 0),
56         x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)),
57         y = yAxis.tickFormat()(lines.y()(e.point, e.pointIndex)),
58         content = tooltip(e.series.key, x, y, e, chart);
59
60     nv.tooltip.show([left, top], content, null, null, offsetElement);
61   };
62
63   //============================================================
64
65
66   function chart(selection) {
67     selection.each(function(data) {
68       var container = d3.select(this),
69           that = this;
70
71       var availableWidth = (width  || parseInt(container.style('width')) || 960)
72                              - margin.left - margin.right,
73           availableHeight = (height || parseInt(container.style('height')) || 400)
74                              - margin.top - margin.bottom;
75
76
77       chart.update = function() { container.transition().duration(transitionDuration).call(chart) };
78       chart.container = this;
79
80       //set state.disabled
81       state.disabled = data.map(function(d) { return !!d.disabled });
82
83     
84       if (!defaultState) {
85         var key;
86         defaultState = {};
87         for (key in state) {
88           if (state[key] instanceof Array)
89             defaultState[key] = state[key].slice(0);
90           else
91             defaultState[key] = state[key];
92         }
93       }
94
95       //------------------------------------------------------------
96       // Display noData message if there's nothing to show.
97
98       if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
99         var noDataText = container.selectAll('.nv-noData').data([noData]);
100
101         noDataText.enter().append('text')
102           .attr('class', 'nvd3 nv-noData')
103           .attr('dy', '-.7em')
104           .style('text-anchor', 'middle');
105
106         noDataText
107           .attr('x', margin.left + availableWidth / 2)
108           .attr('y', margin.top + availableHeight / 2)
109           .text(function(d) { return d });
110
111         return chart;
112       } else {
113         container.selectAll('.nv-noData').remove();
114       }
115
116       //------------------------------------------------------------
117
118
119       //------------------------------------------------------------
120       // Setup Scales
121
122       x = lines.xScale();
123       y = lines.yScale();
124
125       //------------------------------------------------------------
126
127
128       //------------------------------------------------------------
129       // Setup containers and skeleton of chart
130
131       var wrap = container.selectAll('g.nv-wrap.nv-lineChart').data([data]);
132       var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-lineChart').append('g');
133       var g = wrap.select('g');
134
135       gEnter.append("rect").style("opacity",0);
136       gEnter.append('g').attr('class', 'nv-x nv-axis');
137       gEnter.append('g').attr('class', 'nv-y nv-axis');
138       gEnter.append('g').attr('class', 'nv-linesWrap');
139       gEnter.append('g').attr('class', 'nv-legendWrap');
140       gEnter.append('g').attr('class', 'nv-interactive');
141
142       g.select("rect").attr("width",availableWidth).attr("height",availableHeight);
143       //------------------------------------------------------------
144       // Legend
145
146       if (showLegend) {
147         legend.width(availableWidth);
148
149         g.select('.nv-legendWrap')
150             .datum(data)
151             .call(legend);
152
153         if ( margin.top != legend.height()) {
154           margin.top = legend.height();
155           availableHeight = (height || parseInt(container.style('height')) || 400)
156                              - margin.top - margin.bottom;
157         }
158
159         wrap.select('.nv-legendWrap')
160             .attr('transform', 'translate(0,' + (-margin.top) +')')
161       }
162
163       //------------------------------------------------------------
164
165       wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
166
167       if (rightAlignYAxis) {
168           g.select(".nv-y.nv-axis")
169               .attr("transform", "translate(" + availableWidth + ",0)");
170       }
171
172       //------------------------------------------------------------
173       // Main Chart Component(s)
174
175       
176       //------------------------------------------------------------
177       //Set up interactive layer
178       if (useInteractiveGuideline) {
179         interactiveLayer
180            .width(availableWidth)
181            .height(availableHeight)
182            .margin({left:margin.left, top:margin.top})
183            .svgContainer(container)
184            .xScale(x);
185         wrap.select(".nv-interactive").call(interactiveLayer);
186       }
187
188
189       lines
190         .width(availableWidth)
191         .height(availableHeight)
192         .color(data.map(function(d,i) {
193           return d.color || color(d, i);
194         }).filter(function(d,i) { return !data[i].disabled }));
195
196
197       var linesWrap = g.select('.nv-linesWrap')
198           .datum(data.filter(function(d) { return !d.disabled }))
199
200       linesWrap.transition().call(lines);
201
202       //------------------------------------------------------------
203
204
205       //------------------------------------------------------------
206       // Setup Axes
207
208       if (showXAxis) {
209         xAxis
210           .scale(x)
211           .ticks( availableWidth / 100 )
212           .tickSize(-availableHeight, 0);
213
214         g.select('.nv-x.nv-axis')
215             .attr('transform', 'translate(0,' + y.range()[0] + ')');
216         g.select('.nv-x.nv-axis')
217             .transition()
218             .call(xAxis);
219       }
220
221       if (showYAxis) {
222         yAxis
223           .scale(y)
224           .ticks( availableHeight / 36 )
225           .tickSize( -availableWidth, 0);
226
227         g.select('.nv-y.nv-axis')
228             .transition()
229             .call(yAxis);
230       }
231       //------------------------------------------------------------
232
233
234       //============================================================
235       // Event Handling/Dispatching (in chart's scope)
236       //------------------------------------------------------------
237
238       legend.dispatch.on('stateChange', function(newState) {
239           state = newState;
240           dispatch.stateChange(state);
241           chart.update();
242       });
243
244       interactiveLayer.dispatch.on('elementMousemove', function(e) {
245           lines.clearHighlights();
246           var singlePoint, pointIndex, pointXLocation, allData = [];
247           data
248           .filter(function(series, i) { 
249             series.seriesIndex = i;
250             return !series.disabled; 
251           })
252           .forEach(function(series,i) {
253               pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x());
254               lines.highlightPoint(i, pointIndex, true);
255               var point = series.values[pointIndex];
256               if (typeof point === 'undefined') return;
257               if (typeof singlePoint === 'undefined') singlePoint = point;
258               if (typeof pointXLocation === 'undefined') pointXLocation = chart.xScale()(chart.x()(point,pointIndex));
259               allData.push({
260                   key: series.key,
261                   value: chart.y()(point, pointIndex),
262                   color: color(series,series.seriesIndex)
263               });
264           });
265           //Highlight the tooltip entry based on which point the mouse is closest to.
266           if (allData.length > 2) {
267             var yValue = chart.yScale().invert(e.mouseY);
268             var domainExtent = Math.abs(chart.yScale().domain()[0] - chart.yScale().domain()[1]);
269             var threshold = 0.03 * domainExtent;
270             var indexToHighlight = nv.nearestValueIndex(allData.map(function(d){return d.value}),yValue,threshold);
271             if (indexToHighlight !== null)
272               allData[indexToHighlight].highlight = true;
273           }
274
275           var xValue = xAxis.tickFormat()(chart.x()(singlePoint,pointIndex));
276           interactiveLayer.tooltip
277                   .position({left: pointXLocation + margin.left, top: e.mouseY + margin.top})
278                   .chartContainer(that.parentNode)
279                   .enabled(tooltips)
280                   .valueFormatter(function(d,i) {
281                      return yAxis.tickFormat()(d);
282                   })
283                   .data(
284                       {
285                         value: xValue,
286                         series: allData
287                       }
288                   )();
289
290           interactiveLayer.renderGuideLine(pointXLocation);
291
292       });
293
294       interactiveLayer.dispatch.on("elementMouseout",function(e) {
295           dispatch.tooltipHide();
296           lines.clearHighlights();
297       });
298
299       dispatch.on('tooltipShow', function(e) {
300         if (tooltips) showTooltip(e, that.parentNode);
301       });
302
303
304       dispatch.on('changeState', function(e) {
305
306         if (typeof e.disabled !== 'undefined') {
307           data.forEach(function(series,i) {
308             series.disabled = e.disabled[i];
309           });
310
311           state.disabled = e.disabled;
312         }
313
314         chart.update();
315       });
316
317       //============================================================
318
319     });
320
321     return chart;
322   }
323
324
325   //============================================================
326   // Event Handling/Dispatching (out of chart's scope)
327   //------------------------------------------------------------
328
329   lines.dispatch.on('elementMouseover.tooltip', function(e) {
330     e.pos = [e.pos[0] +  margin.left, e.pos[1] + margin.top];
331     dispatch.tooltipShow(e);
332   });
333
334   lines.dispatch.on('elementMouseout.tooltip', function(e) {
335     dispatch.tooltipHide(e);
336   });
337
338   dispatch.on('tooltipHide', function() {
339     if (tooltips) nv.tooltip.cleanup();
340   });
341
342   //============================================================
343
344
345   //============================================================
346   // Expose Public Variables
347   //------------------------------------------------------------
348
349   // expose chart's sub-components
350   chart.dispatch = dispatch;
351   chart.lines = lines;
352   chart.legend = legend;
353   chart.xAxis = xAxis;
354   chart.yAxis = yAxis;
355   chart.interactiveLayer = interactiveLayer;
356
357   d3.rebind(chart, lines, 'defined', 'isArea', 'x', 'y', 'size', 'xScale', 'yScale', 'xDomain', 'yDomain', 'xRange', 'yRange'
358     , 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'useVoronoi','id', 'interpolate');
359
360   chart.options = nv.utils.optionsFunc.bind(chart);
361
362   chart.margin = function(_) {
363     if (!arguments.length) return margin;
364     margin.top    = typeof _.top    != 'undefined' ? _.top    : margin.top;
365     margin.right  = typeof _.right  != 'undefined' ? _.right  : margin.right;
366     margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
367     margin.left   = typeof _.left   != 'undefined' ? _.left   : margin.left;
368     return chart;
369   };
370
371   chart.width = function(_) {
372     if (!arguments.length) return width;
373     width = _;
374     return chart;
375   };
376
377   chart.height = function(_) {
378     if (!arguments.length) return height;
379     height = _;
380     return chart;
381   };
382
383   chart.color = function(_) {
384     if (!arguments.length) return color;
385     color = nv.utils.getColor(_);
386     legend.color(color);
387     return chart;
388   };
389
390   chart.showLegend = function(_) {
391     if (!arguments.length) return showLegend;
392     showLegend = _;
393     return chart;
394   };
395
396   chart.showXAxis = function(_) {
397     if (!arguments.length) return showXAxis;
398     showXAxis = _;
399     return chart;
400   };
401
402   chart.showYAxis = function(_) {
403     if (!arguments.length) return showYAxis;
404     showYAxis = _;
405     return chart;
406   };
407
408   chart.rightAlignYAxis = function(_) {
409     if(!arguments.length) return rightAlignYAxis;
410     rightAlignYAxis = _;
411     yAxis.orient( (_) ? 'right' : 'left');
412     return chart;
413   };
414
415   chart.useInteractiveGuideline = function(_) {
416     if(!arguments.length) return useInteractiveGuideline;
417     useInteractiveGuideline = _;
418     if (_ === true) {
419        chart.interactive(false);
420        chart.useVoronoi(false);
421     }
422     return chart;
423   };
424
425   chart.tooltips = function(_) {
426     if (!arguments.length) return tooltips;
427     tooltips = _;
428     return chart;
429   };
430
431   chart.tooltipContent = function(_) {
432     if (!arguments.length) return tooltip;
433     tooltip = _;
434     return chart;
435   };
436
437   chart.state = function(_) {
438     if (!arguments.length) return state;
439     state = _;
440     return chart;
441   };
442
443   chart.defaultState = function(_) {
444     if (!arguments.length) return defaultState;
445     defaultState = _;
446     return chart;
447   };
448
449   chart.noData = function(_) {
450     if (!arguments.length) return noData;
451     noData = _;
452     return chart;
453   };
454
455   chart.transitionDuration = function(_) {
456     if (!arguments.length) return transitionDuration;
457     transitionDuration = _;
458     return chart;
459   };
460
461   //============================================================
462
463
464   return chart;
465 }