Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / webapp / static / fusion / raptor / d3 / js / models / scatter.js
1
2 nv.models.scatter = function() {
3   "use strict";
4   //============================================================
5   // Public Variables with Default Settings
6   //------------------------------------------------------------
7
8   var margin       = {top: 0, right: 0, bottom: 0, left: 0}
9     , width        = 960
10     , height       = 500
11     , color        = nv.utils.defaultColor() // chooses color
12     , id           = Math.floor(Math.random() * 100000) //Create semi-unique ID incase user doesn't select one
13     , x            = d3.scale.linear()
14     , y            = d3.scale.linear()
15     , z            = d3.scale.linear() //linear because d3.svg.shape.size is treated as area
16     , getX         = function(d) { return d.x } // accessor to get the x value
17     , getY         = function(d) { return d.y } // accessor to get the y value
18     , getSize      = function(d) { return d.size || 1} // accessor to get the point size
19     , getShape     = function(d) { return d.shape || 'circle' } // accessor to get point shape
20     , onlyCircles  = true // Set to false to use shapes
21     , forceX       = [] // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.)
22     , forceY       = [] // List of numbers to Force into the Y scale
23     , forceSize    = [] // List of numbers to Force into the Size scale
24     , interactive  = true // If true, plots a voronoi overlay for advanced point intersection
25     , pointKey     = null
26     , pointActive  = function(d) { return !d.notActive } // any points that return false will be filtered out
27     , padData      = false // If true, adds half a data points width to front and back, for lining up a line chart with a bar chart
28     , padDataOuter = .1 //outerPadding to imitate ordinal scale outer padding
29     , clipEdge     = false // if true, masks points within x and y scale
30     , clipVoronoi  = true // if true, masks each point with a circle... can turn off to slightly increase performance
31     , clipRadius   = function() { return 25 } // function to get the radius for voronoi point clips
32     , xDomain      = null // Override x domain (skips the calculation from data)
33     , yDomain      = null // Override y domain
34     , xRange       = null // Override x range
35     , yRange       = null // Override y range
36     , sizeDomain   = null // Override point size domain
37     , sizeRange    = null
38     , singlePoint  = false
39     , dispatch     = d3.dispatch('elementClick', 'elementMouseover', 'elementMouseout')
40     , useVoronoi   = true
41     ;
42
43   //============================================================
44
45
46   //============================================================
47   // Private Variables
48   //------------------------------------------------------------
49
50   var x0, y0, z0 // used to store previous scales
51     , timeoutID
52     , needsUpdate = false // Flag for when the points are visually updating, but the interactive layer is behind, to disable tooltips
53     ;
54
55   //============================================================
56
57
58   function chart(selection) {
59     selection.each(function(data) {
60       var availableWidth = width - margin.left - margin.right,
61           availableHeight = height - margin.top - margin.bottom,
62           container = d3.select(this);
63
64       //add series index to each data point for reference
65       data.forEach(function(series, i) {
66         series.values.forEach(function(point) {
67           point.series = i;
68         });
69       });
70
71       //------------------------------------------------------------
72       // Setup Scales
73
74       // remap and flatten the data for use in calculating the scales' domains
75       var seriesData = (xDomain && yDomain && sizeDomain) ? [] : // if we know xDomain and yDomain and sizeDomain, no need to calculate.... if Size is constant remember to set sizeDomain to speed up performance
76             d3.merge(
77               data.map(function(d) {
78                 return d.values.map(function(d,i) {
79                   return { x: getX(d,i), y: getY(d,i), size: getSize(d,i) }
80                 })
81               })
82             );
83
84       x   .domain(xDomain || d3.extent(seriesData.map(function(d) { return d.x; }).concat(forceX)))
85
86       if (padData && data[0])
87         x.range(xRange || [(availableWidth * padDataOuter +  availableWidth) / (2 *data[0].values.length), availableWidth - availableWidth * (1 + padDataOuter) / (2 * data[0].values.length)  ]);
88         //x.range([availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5)  / data[0].values.length ]);
89       else
90         x.range(xRange || [0, availableWidth]);
91
92       y   .domain(yDomain || d3.extent(seriesData.map(function(d) { return d.y }).concat(forceY)))
93           .range(yRange || [availableHeight, 0]);
94
95       z   .domain(sizeDomain || d3.extent(seriesData.map(function(d) { return d.size }).concat(forceSize)))
96           .range(sizeRange || [16, 256]);
97
98       // If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
99       if (x.domain()[0] === x.domain()[1] || y.domain()[0] === y.domain()[1]) singlePoint = true;
100       if (x.domain()[0] === x.domain()[1])
101         x.domain()[0] ?
102             x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
103           : x.domain([-1,1]);
104
105       if (y.domain()[0] === y.domain()[1])
106         y.domain()[0] ?
107             y.domain([y.domain()[0] - y.domain()[0] * 0.01, y.domain()[1] + y.domain()[1] * 0.01])
108           : y.domain([-1,1]);
109
110       if ( isNaN(x.domain()[0])) {
111           x.domain([-1,1]);
112       }
113
114       if ( isNaN(y.domain()[0])) {
115           y.domain([-1,1]);
116       }
117
118
119       x0 = x0 || x;
120       y0 = y0 || y;
121       z0 = z0 || z;
122
123       //------------------------------------------------------------
124
125
126       //------------------------------------------------------------
127       // Setup containers and skeleton of chart
128
129       var wrap = container.selectAll('g.nv-wrap.nv-scatter').data([data]);
130       var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatter nv-chart-' + id + (singlePoint ? ' nv-single-point' : ''));
131       var defsEnter = wrapEnter.append('defs');
132       var gEnter = wrapEnter.append('g');
133       var g = wrap.select('g');
134
135       gEnter.append('g').attr('class', 'nv-groups');
136       gEnter.append('g').attr('class', 'nv-point-paths');
137
138       wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
139
140       //------------------------------------------------------------
141
142
143       defsEnter.append('clipPath')
144           .attr('id', 'nv-edge-clip-' + id)
145         .append('rect');
146
147       wrap.select('#nv-edge-clip-' + id + ' rect')
148           .attr('width', availableWidth)
149           .attr('height', availableHeight);
150
151       g   .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : '');
152
153
154       function updateInteractiveLayer() {
155
156         if (!interactive) return false;
157
158         var eventElements;
159
160         var vertices = d3.merge(data.map(function(group, groupIndex) {
161             return group.values
162               .map(function(point, pointIndex) {
163                 // *Adding noise to make duplicates very unlikely
164                 // *Injecting series and point index for reference
165                 /* *Adding a 'jitter' to the points, because there's an issue in d3.geom.voronoi.
166                 */
167                 var pX = getX(point,pointIndex);
168                 var pY = getY(point,pointIndex);
169
170                 return [x(pX)+ Math.random() * 1e-7,
171                         y(pY)+ Math.random() * 1e-7,
172                         groupIndex,
173                         pointIndex, point]; //temp hack to add noise untill I think of a better way so there are no duplicates
174               })
175               .filter(function(pointArray, pointIndex) {
176                 return pointActive(pointArray[4], pointIndex); // Issue #237.. move filter to after map, so pointIndex is correct!
177               })
178           })
179         );
180
181
182
183         //inject series and point index for reference into voronoi
184         if (useVoronoi === true) {
185
186           if (clipVoronoi) {
187             var pointClipsEnter = wrap.select('defs').selectAll('.nv-point-clips')
188                 .data([id])
189               .enter();
190
191             pointClipsEnter.append('clipPath')
192                   .attr('class', 'nv-point-clips')
193                   .attr('id', 'nv-points-clip-' + id);
194
195             var pointClips = wrap.select('#nv-points-clip-' + id).selectAll('circle')
196                 .data(vertices);
197             pointClips.enter().append('circle')
198                 .attr('r', clipRadius);
199             pointClips.exit().remove();
200             pointClips
201                 .attr('cx', function(d) { return d[0] })
202                 .attr('cy', function(d) { return d[1] });
203
204             wrap.select('.nv-point-paths')
205                 .attr('clip-path', 'url(#nv-points-clip-' + id + ')');
206           }
207
208
209           if(vertices.length) {
210             // Issue #283 - Adding 2 dummy points to the voronoi b/c voronoi requires min 3 points to work
211             vertices.push([x.range()[0] - 20, y.range()[0] - 20, null, null]);
212             vertices.push([x.range()[1] + 20, y.range()[1] + 20, null, null]);
213             vertices.push([x.range()[0] - 20, y.range()[0] + 20, null, null]);
214             vertices.push([x.range()[1] + 20, y.range()[1] - 20, null, null]);
215           }
216
217           var bounds = d3.geom.polygon([
218               [-10,-10],
219               [-10,height + 10],
220               [width + 10,height + 10],
221               [width + 10,-10]
222           ]);
223
224           var voronoi = d3.geom.voronoi(vertices).map(function(d, i) {
225               return {
226                 'data': bounds.clip(d),
227                 'series': vertices[i][2],
228                 'point': vertices[i][3]
229               }
230             });
231
232
233           var pointPaths = wrap.select('.nv-point-paths').selectAll('path')
234               .data(voronoi);
235           pointPaths.enter().append('path')
236               .attr('class', function(d,i) { return 'nv-path-'+i; });
237           pointPaths.exit().remove();
238           pointPaths
239               .attr('d', function(d) {
240                 if (d.data.length === 0)
241                     return 'M 0 0'
242                 else
243                     return 'M' + d.data.join('L') + 'Z';
244               });
245
246           var mouseEventCallback = function(d,mDispatch) {
247                 if (needsUpdate) return 0;
248                 var series = data[d.series];
249                 if (typeof series === 'undefined') return;
250
251                 var point  = series.values[d.point];
252
253                 mDispatch({
254                   point: point,
255                   series: series,
256                   pos: [x(getX(point, d.point)) + margin.left, y(getY(point, d.point)) + margin.top],
257                   seriesIndex: d.series,
258                   pointIndex: d.point
259                 });
260           };
261
262           pointPaths
263               .on('click', function(d) {
264                 mouseEventCallback(d, dispatch.elementClick);
265               })
266               .on('mouseover', function(d) {
267                 mouseEventCallback(d, dispatch.elementMouseover);
268               })
269               .on('mouseout', function(d, i) {
270                 mouseEventCallback(d, dispatch.elementMouseout);
271               });
272
273
274         } else {
275           /*
276           // bring data in form needed for click handlers
277           var dataWithPoints = vertices.map(function(d, i) {
278               return {
279                 'data': d,
280                 'series': vertices[i][2],
281                 'point': vertices[i][3]
282               }
283             });
284            */
285
286           // add event handlers to points instead voronoi paths
287           wrap.select('.nv-groups').selectAll('.nv-group')
288             .selectAll('.nv-point')
289               //.data(dataWithPoints)
290               //.style('pointer-events', 'auto') // recativate events, disabled by css
291               .on('click', function(d,i) {
292                 //nv.log('test', d, i);
293                 if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point
294                 var series = data[d.series],
295                     point  = series.values[i];
296
297                 dispatch.elementClick({
298                   point: point,
299                   series: series,
300                   pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top],
301                   seriesIndex: d.series,
302                   pointIndex: i
303                 });
304               })
305               .on('mouseover', function(d,i) {
306                 if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point
307                 var series = data[d.series],
308                     point  = series.values[i];
309
310                 dispatch.elementMouseover({
311                   point: point,
312                   series: series,
313                   pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top],
314                   seriesIndex: d.series,
315                   pointIndex: i
316                 });
317               })
318               .on('mouseout', function(d,i) {
319                 if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point
320                 var series = data[d.series],
321                     point  = series.values[i];
322
323                 dispatch.elementMouseout({
324                   point: point,
325                   series: series,
326                   seriesIndex: d.series,
327                   pointIndex: i
328                 });
329               });
330           }
331
332           needsUpdate = false;
333       }
334
335       needsUpdate = true;
336
337       var groups = wrap.select('.nv-groups').selectAll('.nv-group')
338           .data(function(d) { return d }, function(d) { return d.key });
339       groups.enter().append('g')
340           .style('stroke-opacity', 1e-6)
341           .style('fill-opacity', 1e-6);
342       groups.exit()
343           .remove();
344       groups
345           .attr('class', function(d,i) { return 'nv-group nv-series-' + i })
346           .classed('hover', function(d) { return d.hover });
347       groups
348           .transition()
349           .style('fill', function(d,i) { return color(d, i) })
350           .style('stroke', function(d,i) { return color(d, i) })
351           .style('stroke-opacity', 1)
352           .style('fill-opacity', .5);
353
354
355       if (onlyCircles) {
356
357         var points = groups.selectAll('circle.nv-point')
358             .data(function(d) { return d.values }, pointKey);
359         points.enter().append('circle')
360             .style('fill', function (d,i) { return d.color })
361             .style('stroke', function (d,i) { return d.color })
362             .attr('cx', function(d,i) { return nv.utils.NaNtoZero(x0(getX(d,i))) })
363             .attr('cy', function(d,i) { return nv.utils.NaNtoZero(y0(getY(d,i))) })
364             .attr('r', function(d,i) { return Math.sqrt(z(getSize(d,i))/Math.PI) });
365         points.exit().remove();
366         groups.exit().selectAll('path.nv-point').transition()
367             .attr('cx', function(d,i) { return nv.utils.NaNtoZero(x(getX(d,i))) })
368             .attr('cy', function(d,i) { return nv.utils.NaNtoZero(y(getY(d,i))) })
369             .remove();
370         points.each(function(d,i) {
371           d3.select(this)
372             .classed('nv-point', true)
373             .classed('nv-point-' + i, true)
374             .classed('hover',false)
375             ;
376         });
377         points.transition()
378             .attr('cx', function(d,i) { return nv.utils.NaNtoZero(x(getX(d,i))) })
379             .attr('cy', function(d,i) { return nv.utils.NaNtoZero(y(getY(d,i))) })
380             .attr('r', function(d,i) { return Math.sqrt(z(getSize(d,i))/Math.PI) });
381
382       } else {
383
384         var points = groups.selectAll('path.nv-point')
385             .data(function(d) { return d.values });
386         points.enter().append('path')
387             .style('fill', function (d,i) { return d.color })
388             .style('stroke', function (d,i) { return d.color })
389             .attr('transform', function(d,i) {
390               return 'translate(' + x0(getX(d,i)) + ',' + y0(getY(d,i)) + ')'
391             })
392             .attr('d',
393               d3.svg.symbol()
394                 .type(getShape)
395                 .size(function(d,i) { return z(getSize(d,i)) })
396             );
397         points.exit().remove();
398         groups.exit().selectAll('path.nv-point')
399             .transition()
400             .attr('transform', function(d,i) {
401               return 'translate(' + x(getX(d,i)) + ',' + y(getY(d,i)) + ')'
402             })
403             .remove();
404         points.each(function(d,i) {
405           d3.select(this)
406             .classed('nv-point', true)
407             .classed('nv-point-' + i, true)
408             .classed('hover',false)
409             ;
410         });
411         points.transition()
412             .attr('transform', function(d,i) {
413               //nv.log(d,i,getX(d,i), x(getX(d,i)));
414               return 'translate(' + x(getX(d,i)) + ',' + y(getY(d,i)) + ')'
415             })
416             .attr('d',
417               d3.svg.symbol()
418                 .type(getShape)
419                 .size(function(d,i) { return z(getSize(d,i)) })
420             );
421       }
422
423
424       // Delay updating the invisible interactive layer for smoother animation
425       clearTimeout(timeoutID); // stop repeat calls to updateInteractiveLayer
426       timeoutID = setTimeout(updateInteractiveLayer, 300);
427       //updateInteractiveLayer();
428
429       //store old scales for use in transitions on update
430       x0 = x.copy();
431       y0 = y.copy();
432       z0 = z.copy();
433
434     });
435
436     return chart;
437   }
438
439
440   //============================================================
441   // Event Handling/Dispatching (out of chart's scope)
442   //------------------------------------------------------------
443   chart.clearHighlights = function() {
444       //Remove the 'hover' class from all highlighted points.
445       d3.selectAll(".nv-chart-" + id + " .nv-point.hover").classed("hover",false);
446   };
447
448   chart.highlightPoint = function(seriesIndex,pointIndex,isHoverOver) {
449       d3.select(".nv-chart-" + id + " .nv-series-" + seriesIndex + " .nv-point-" + pointIndex)
450           .classed("hover",isHoverOver);
451   };
452
453
454   dispatch.on('elementMouseover.point', function(d) {
455      if (interactive) chart.highlightPoint(d.seriesIndex,d.pointIndex,true);
456   });
457
458   dispatch.on('elementMouseout.point', function(d) {
459      if (interactive) chart.highlightPoint(d.seriesIndex,d.pointIndex,false);
460   });
461
462   //============================================================
463
464
465   //============================================================
466   // Expose Public Variables
467   //------------------------------------------------------------
468
469   chart.dispatch = dispatch;
470   chart.options = nv.utils.optionsFunc.bind(chart);
471
472   chart.x = function(_) {
473     if (!arguments.length) return getX;
474     getX = d3.functor(_);
475     return chart;
476   };
477
478   chart.y = function(_) {
479     if (!arguments.length) return getY;
480     getY = d3.functor(_);
481     return chart;
482   };
483
484   chart.size = function(_) {
485     if (!arguments.length) return getSize;
486     getSize = d3.functor(_);
487     return chart;
488   };
489
490   chart.margin = function(_) {
491     if (!arguments.length) return margin;
492     margin.top    = typeof _.top    != 'undefined' ? _.top    : margin.top;
493     margin.right  = typeof _.right  != 'undefined' ? _.right  : margin.right;
494     margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
495     margin.left   = typeof _.left   != 'undefined' ? _.left   : margin.left;
496     return chart;
497   };
498
499   chart.width = function(_) {
500     if (!arguments.length) return width;
501     width = _;
502     return chart;
503   };
504
505   chart.height = function(_) {
506     if (!arguments.length) return height;
507     height = _;
508     return chart;
509   };
510
511   chart.xScale = function(_) {
512     if (!arguments.length) return x;
513     x = _;
514     return chart;
515   };
516
517   chart.yScale = function(_) {
518     if (!arguments.length) return y;
519     y = _;
520     return chart;
521   };
522
523   chart.zScale = function(_) {
524     if (!arguments.length) return z;
525     z = _;
526     return chart;
527   };
528
529   chart.xDomain = function(_) {
530     if (!arguments.length) return xDomain;
531     xDomain = _;
532     return chart;
533   };
534
535   chart.yDomain = function(_) {
536     if (!arguments.length) return yDomain;
537     yDomain = _;
538     return chart;
539   };
540
541   chart.sizeDomain = function(_) {
542     if (!arguments.length) return sizeDomain;
543     sizeDomain = _;
544     return chart;
545   };
546
547   chart.xRange = function(_) {
548     if (!arguments.length) return xRange;
549     xRange = _;
550     return chart;
551   };
552
553   chart.yRange = function(_) {
554     if (!arguments.length) return yRange;
555     yRange = _;
556     return chart;
557   };
558
559   chart.sizeRange = function(_) {
560     if (!arguments.length) return sizeRange;
561     sizeRange = _;
562     return chart;
563   };
564
565   chart.forceX = function(_) {
566     if (!arguments.length) return forceX;
567     forceX = _;
568     return chart;
569   };
570
571   chart.forceY = function(_) {
572     if (!arguments.length) return forceY;
573     forceY = _;
574     return chart;
575   };
576
577   chart.forceSize = function(_) {
578     if (!arguments.length) return forceSize;
579     forceSize = _;
580     return chart;
581   };
582
583   chart.interactive = function(_) {
584     if (!arguments.length) return interactive;
585     interactive = _;
586     return chart;
587   };
588
589   chart.pointKey = function(_) {
590     if (!arguments.length) return pointKey;
591     pointKey = _;
592     return chart;
593   };
594
595   chart.pointActive = function(_) {
596     if (!arguments.length) return pointActive;
597     pointActive = _;
598     return chart;
599   };
600
601   chart.padData = function(_) {
602     if (!arguments.length) return padData;
603     padData = _;
604     return chart;
605   };
606
607   chart.padDataOuter = function(_) {
608     if (!arguments.length) return padDataOuter;
609     padDataOuter = _;
610     return chart;
611   };
612
613   chart.clipEdge = function(_) {
614     if (!arguments.length) return clipEdge;
615     clipEdge = _;
616     return chart;
617   };
618
619   chart.clipVoronoi= function(_) {
620     if (!arguments.length) return clipVoronoi;
621     clipVoronoi = _;
622     return chart;
623   };
624
625   chart.useVoronoi= function(_) {
626     if (!arguments.length) return useVoronoi;
627     useVoronoi = _;
628     if (useVoronoi === false) {
629         clipVoronoi = false;
630     }
631     return chart;
632   };
633
634   chart.clipRadius = function(_) {
635     if (!arguments.length) return clipRadius;
636     clipRadius = _;
637     return chart;
638   };
639
640   chart.color = function(_) {
641     if (!arguments.length) return color;
642     color = nv.utils.getColor(_);
643     return chart;
644   };
645
646   chart.shape = function(_) {
647     if (!arguments.length) return getShape;
648     getShape = _;
649     return chart;
650   };
651
652   chart.onlyCircles = function(_) {
653     if (!arguments.length) return onlyCircles;
654     onlyCircles = _;
655     return chart;
656   };
657
658   chart.id = function(_) {
659     if (!arguments.length) return id;
660     id = _;
661     return chart;
662   };
663
664   chart.singlePoint = function(_) {
665     if (!arguments.length) return singlePoint;
666     singlePoint = _;
667     return chart;
668   };
669
670   //============================================================
671
672
673   return chart;
674 }