Эх сурвалжийг харах

[search] Introducting enable selection on histogram

Enrico Berti 11 жил өмнө
parent
commit
200cf519d4

+ 6 - 0
apps/search/src/search/templates/search2.mako

@@ -610,6 +610,7 @@ ${ commonheader(_('Search'), "search", user, "60px") | n,unicode }
 <script src="/static/ext/js/topojson.v1.min.js" type="text/javascript" charset="utf-8"></script>
 <script src="/static/ext/js/datamaps.all.min.js" type="text/javascript" charset="utf-8"></script>
 
+<script src="/search/static/js/nv.d3.legend.js" type="text/javascript" charset="utf-8"></script>
 <script src="/search/static/js/nv.d3.multiBarWithBrushChart.js" type="text/javascript" charset="utf-8"></script>
 <script src="/search/static/js/nv.d3.lineWithBrushChart.js" type="text/javascript" charset="utf-8"></script>
 <script src="/search/static/js/nv.d3.growingDiscreteBar.js" type="text/javascript" charset="utf-8"></script>
@@ -814,6 +815,11 @@ ${ commonheader(_('Search'), "search", user, "60px") | n,unicode }
     fill-opacity: .225!important;
   }
 
+  .nvd3 .nv-legend .disabled rect {
+    fill-opacity: 0;
+  }
+
+
   .fields-chooser li {
     cursor: pointer;
     margin-bottom: 10px;

+ 1 - 2
apps/search/static/js/charts.ko.js

@@ -194,7 +194,6 @@ function lineChart(element, options) {
 
   nv.addGraph(function () {
     var _chart = nv.models.lineWithBrushChart();
-    _chart.enableSelection();
     _chart.onSelectRange(options.onSelectRange);
     _chart.xAxis
         .showMaxMin(true)
@@ -232,7 +231,7 @@ function barChart(element, options, isTimeline) {
     var _chart;
     if (isTimeline) {
       _chart = nv.models.multiBarWithBrushChart();
-      _chart.enableSelection();
+      //_chart.enableSelection();
       _chart.onSelectRange(options.onSelectRange);
       _chart.xAxis
           .showMaxMin(true)

+ 1 - 1
apps/search/static/js/nv.d3.growingPie.js

@@ -112,7 +112,7 @@ nv.models.growingPie = function() {
       selectSlices = function(selected) {
         $(selected).each(function(cnt, item){
           slices.each(function(d, i) {
-            if (d.data.obj.value == item) {
+            if ((typeof d.data.obj.from != "undefined" && d.data.obj.from == item) || d.data.obj.value == item) {
               d3.select(this).classed('selected', true);
               d3.select(this).select("path").transition().duration(100).attr("d", arcOver);
             }

+ 300 - 0
apps/search/static/js/nv.d3.legend.js

@@ -0,0 +1,300 @@
+// Licensed to Cloudera, Inc. under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  Cloudera, Inc. licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+nv.models.legend = function() {
+  "use strict";
+  //============================================================
+  // Public Variables with Default Settings
+  //------------------------------------------------------------
+
+  var margin = {top: 5, right: 0, bottom: 5, left: 0}
+    , width = 400
+    , height = 20
+    , getKey = function(d) { return d.key }
+    , color = nv.utils.defaultColor()
+    , align = true
+    , rightAlign = true
+    , updateState = true   //If true, legend will update data.disabled and trigger a 'stateChange' dispatch.
+    , radioButtonMode = false   //If true, clicking legend items will cause it to behave like a radio button. (only one can be selected at a time)
+    , dispatch = d3.dispatch('legendClick', 'legendDblclick', 'legendMouseover', 'legendMouseout', 'stateChange')
+    ;
+
+  //============================================================
+
+
+  function chart(selection) {
+    selection.each(function(data) {
+      var availableWidth = width - margin.left - margin.right,
+          container = d3.select(this);
+
+      //------------------------------------------------------------
+      // Setup containers and skeleton of chart
+
+      var wrap = container.selectAll('g.nv-legend').data([data]);
+      var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-legend').append('g');
+      var g = wrap.select('g');
+
+      wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+      //------------------------------------------------------------
+
+
+      var series = g.selectAll('.nv-series')
+          .data(function(d) { return d });
+      var seriesEnter = series.enter().append('g').attr('class', 'nv-series')
+          .on('mouseover', function(d,i) {
+            dispatch.legendMouseover(d,i);  //TODO: Make consistent with other event objects
+          })
+          .on('mouseout', function(d,i) {
+            dispatch.legendMouseout(d,i);
+          })
+          .on('click', function(d,i) {
+            dispatch.legendClick(d,i);
+            if (updateState) {
+               if (radioButtonMode) {
+                   //Radio button mode: set every series to disabled,
+                   //  and enable the clicked series.
+                   data.forEach(function(series) { series.disabled = true});
+                   d.disabled = false;
+               }
+               else {
+                   d.disabled = !d.disabled;
+                   if (data.every(function(series) { return series.disabled})) {
+                       //the default behavior of NVD3 legends is, if every single series
+                       // is disabled, turn all series' back on.
+                       data.forEach(function(series) { series.disabled = false});
+                   }
+               }
+               dispatch.stateChange({
+                  disabled: data.map(function(d) { return !!d.disabled })
+               });
+            }
+          })
+          .on('dblclick', function(d,i) {
+            dispatch.legendDblclick(d,i);
+            if (updateState) {
+                //the default behavior of NVD3 legends, when double clicking one,
+                // is to set all other series' to false, and make the double clicked series enabled.
+                data.forEach(function(series) {
+                   series.disabled = true;
+                });
+                d.disabled = false;
+                dispatch.stateChange({
+                    disabled: data.map(function(d) { return !!d.disabled })
+                });
+            }
+          });
+      seriesEnter.append('circle')
+          .style('stroke-width', 2)
+          .attr('class','nv-legend-symbol')
+          .attr('r', 5)
+          .style('display', function(d){return d.checkbox?'none':'inline'});
+
+      seriesEnter.append('rect')
+          .style('stroke-width', 2)
+          .attr('class','nv-legend-symbol')
+          .attr('width', 10)
+          .attr('height', 10)
+          .attr('transform', 'translate(-5,-5)')
+          .style('display', function(d){return d.checkbox?'inline':'none'});
+
+      seriesEnter.append('text')
+          .attr('text-anchor', 'start')
+          .attr('class','nv-legend-text')
+          .attr('dy', '.32em')
+          .attr('dx', '8');
+      series.classed('disabled', function(d) { return d.disabled });
+      series.exit().remove();
+      series.select('circle')
+          .style('fill', function(d,i) { return d.color || color(d,i)})
+          .style('stroke', function(d,i) { return d.color || color(d, i) });
+      series.select('rect')
+          .style('fill', function(d,i) { return d.color || color(d,i)})
+          .style('stroke', function(d,i) { return d.color || color(d, i) });
+      series.select('text').text(getKey);
+
+
+      //TODO: implement fixed-width and max-width options (max-width is especially useful with the align option)
+
+      // NEW ALIGNING CODE, TODO: clean up
+      if (align) {
+
+        var seriesWidths = [];
+        series.each(function(d,i) {
+              var legendText = d3.select(this).select('text');
+              var nodeTextLength;
+              try {
+                nodeTextLength = legendText.getComputedTextLength();
+                // If the legendText is display:none'd (nodeTextLength == 0), simulate an error so we approximate, instead
+                if(nodeTextLength <= 0) throw Error();
+              }
+              catch(e) {
+                nodeTextLength = nv.utils.calcApproxTextWidth(legendText);
+              }
+
+              seriesWidths.push(nodeTextLength + 28); // 28 is ~ the width of the circle plus some padding
+            });
+
+        var seriesPerRow = 0;
+        var legendWidth = 0;
+        var columnWidths = [];
+
+        while ( legendWidth < availableWidth && seriesPerRow < seriesWidths.length) {
+          columnWidths[seriesPerRow] = seriesWidths[seriesPerRow];
+          legendWidth += seriesWidths[seriesPerRow++];
+        }
+        if (seriesPerRow === 0) seriesPerRow = 1; //minimum of one series per row
+
+
+        while ( legendWidth > availableWidth && seriesPerRow > 1 ) {
+          columnWidths = [];
+          seriesPerRow--;
+
+          for (var k = 0; k < seriesWidths.length; k++) {
+            if (seriesWidths[k] > (columnWidths[k % seriesPerRow] || 0) )
+              columnWidths[k % seriesPerRow] = seriesWidths[k];
+          }
+
+          legendWidth = columnWidths.reduce(function(prev, cur, index, array) {
+                          return prev + cur;
+                        });
+        }
+
+        var xPositions = [];
+        for (var i = 0, curX = 0; i < seriesPerRow; i++) {
+            xPositions[i] = curX;
+            curX += columnWidths[i];
+        }
+
+        series
+            .attr('transform', function(d, i) {
+              return 'translate(' + xPositions[i % seriesPerRow] + ',' + (5 + Math.floor(i / seriesPerRow) * 20) + ')';
+            });
+
+        //position legend as far right as possible within the total width
+        if (rightAlign) {
+           g.attr('transform', 'translate(' + (width - margin.right - legendWidth) + ',' + margin.top + ')');
+        }
+        else {
+           g.attr('transform', 'translate(0' + ',' + margin.top + ')');
+        }
+
+        height = margin.top + margin.bottom + (Math.ceil(seriesWidths.length / seriesPerRow) * 20);
+
+      } else {
+
+        var ypos = 5,
+            newxpos = 5,
+            maxwidth = 0,
+            xpos;
+        series
+            .attr('transform', function(d, i) {
+              var length = d3.select(this).select('text').node().getComputedTextLength() + 28;
+              xpos = newxpos;
+
+              if (width < margin.left + margin.right + xpos + length) {
+                newxpos = xpos = 5;
+                ypos += 20;
+              }
+
+              newxpos += length;
+              if (newxpos > maxwidth) maxwidth = newxpos;
+
+              return 'translate(' + xpos + ',' + ypos + ')';
+            });
+
+        //position legend as far right as possible within the total width
+        g.attr('transform', 'translate(' + (width - margin.right - maxwidth) + ',' + margin.top + ')');
+
+        height = margin.top + margin.bottom + ypos + 15;
+
+      }
+
+    });
+
+    return chart;
+  }
+
+
+  //============================================================
+  // Expose Public Variables
+  //------------------------------------------------------------
+
+  chart.dispatch = dispatch;
+  chart.options = nv.utils.optionsFunc.bind(chart);
+
+  chart.margin = function(_) {
+    if (!arguments.length) return margin;
+    margin.top    = typeof _.top    != 'undefined' ? _.top    : margin.top;
+    margin.right  = typeof _.right  != 'undefined' ? _.right  : margin.right;
+    margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
+    margin.left   = typeof _.left   != 'undefined' ? _.left   : margin.left;
+    return chart;
+  };
+
+  chart.width = function(_) {
+    if (!arguments.length) return width;
+    width = _;
+    return chart;
+  };
+
+  chart.height = function(_) {
+    if (!arguments.length) return height;
+    height = _;
+    return chart;
+  };
+
+  chart.key = function(_) {
+    if (!arguments.length) return getKey;
+    getKey = _;
+    return chart;
+  };
+
+  chart.color = function(_) {
+    if (!arguments.length) return color;
+    color = nv.utils.getColor(_);
+    return chart;
+  };
+
+  chart.align = function(_) {
+    if (!arguments.length) return align;
+    align = _;
+    return chart;
+  };
+
+  chart.rightAlign = function(_) {
+    if (!arguments.length) return rightAlign;
+    rightAlign = _;
+    return chart;
+  };
+
+  chart.updateState = function(_) {
+    if (!arguments.length) return updateState;
+    updateState = _;
+    return chart;
+  };
+
+  chart.radioButtonMode = function(_) {
+    if (!arguments.length) return radioButtonMode;
+    radioButtonMode = _;
+    return chart;
+  };
+
+  //============================================================
+
+
+  return chart;
+}

+ 77 - 50
apps/search/static/js/nv.d3.multiBarWithBrushChart.js

@@ -21,7 +21,13 @@ nv.models.multiBarWithBrushChart = function() {
   // Public Variables with Default Settings
   //------------------------------------------------------------
 
-  var multibar = nv.models.multiBar()
+  var LABELS = {
+    STACKED: "Stacked",
+    GROUPED: "Grouped",
+    SELECT: "Enable selection"
+  }
+
+  var multibar = nv.models.growingMultiBar()
     , xAxis = nv.models.axis()
     , yAxis = nv.models.axis()
     , legend = nv.models.legend()
@@ -52,7 +58,7 @@ nv.models.multiBarWithBrushChart = function() {
     , defaultState = null
     , noData = "No Data Available."
     , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState', 'brush')
-    , controlWidth = function() { return showControls ? 180 : 0 }
+    , controlWidth = function() { return showControls ? 300 : 0 }
     , transitionDuration = 250
     , extent
     , brushExtent = null
@@ -107,7 +113,15 @@ nv.models.multiBarWithBrushChart = function() {
           availableHeight = (height || parseInt(container.style('height')) || 400)
                              - margin.top - margin.bottom;
 
-      chart.update = function() { container.transition().duration(transitionDuration).call(chart) };
+      chart.update = function() {
+        container.transition().duration(transitionDuration).call(chart)
+        if (selectionEnabled){
+          enableSelection();
+        }
+        else {
+          disableSelection();
+        }
+      };
       chart.container = this;
 
       //set state.disabled
@@ -169,11 +183,6 @@ nv.models.multiBarWithBrushChart = function() {
       gEnter.append('g').attr('class', 'nv-legendWrap');
       gEnter.append('g').attr('class', 'nv-controlsWrap');
 
-      if (selectionEnabled){
-        gEnter.append('g').attr('class', 'nv-brushBackground');
-        gEnter.append('g').attr('class', 'nv-x nv-brush');
-      }
-
 
       //------------------------------------------------------------
 
@@ -211,8 +220,9 @@ nv.models.multiBarWithBrushChart = function() {
 
       if (showControls) {
         var controlsData = [
-          { key: 'Grouped', disabled: multibar.stacked() },
-          { key: 'Stacked', disabled: !multibar.stacked() }
+          { key: LABELS.GROUPED, disabled: multibar.stacked() },
+          { key: LABELS.STACKED, disabled: !multibar.stacked() },
+          { key: LABELS.SELECT, disabled: !selectionEnabled, checkbox: true }
         ];
 
         controls.width(controlWidth()).color(['#444', '#444', '#444']);
@@ -255,33 +265,49 @@ nv.models.multiBarWithBrushChart = function() {
       //------------------------------------------------------------
       // Setup Brush
       if (selectionEnabled){
-        brush
-          .x(x)
-          .on('brush', onBrush)
-          .on('brushend', onBrushEnd)
-
-        if (brushExtent) brush.extent(brushExtent);
-        var brushBG = g.select('.nv-brushBackground').selectAll('g')
-            .data([brushExtent || brush.extent()])
-        var brushBGenter = brushBG.enter()
-            .append('g');
-
-        brushBGenter.append('rect')
-            .attr('class', 'left')
-            .attr('x', 0)
-            .attr('y', 0)
-            .attr('height', availableHeight);
-
-        brushBGenter.append('rect')
-            .attr('class', 'right')
-            .attr('x', 0)
-            .attr('y', 0)
-            .attr('height', availableHeight);
-
-        var gBrush = g.select('.nv-x.nv-brush')
-            .call(brush);
-        gBrush.selectAll('rect')
-            .attr('height', availableHeight);
+        enableSelection();
+      }
+
+
+      function enableSelection() {
+        if (g.selectAll('.nv-brush')[0].length == 0) {
+          gEnter.append('g').attr('class', 'nv-brushBackground');
+          gEnter.append('g').attr('class', 'nv-x nv-brush');
+          brush
+              .x(x)
+              .on('brush', onBrush)
+              .on('brushend', onBrushEnd)
+
+          if (brushExtent) brush.extent(brushExtent);
+          var brushBG = g.select('.nv-brushBackground').selectAll('g')
+              .data([brushExtent || brush.extent()])
+          var brushBGenter = brushBG.enter()
+              .append('g');
+
+          brushBGenter.append('rect')
+              .attr('class', 'left')
+              .attr('x', 0)
+              .attr('y', 0)
+              .attr('height', availableHeight);
+
+          brushBGenter.append('rect')
+              .attr('class', 'right')
+              .attr('x', 0)
+              .attr('y', 0)
+              .attr('height', availableHeight);
+
+          var gBrush = g.select('.nv-x.nv-brush')
+              .call(brush);
+          gBrush.selectAll('rect')
+              .attr('height', availableHeight);
+        }
+        else {
+          g.selectAll('.nv-brush').attr('display', 'inline');
+        }
+      }
+
+      function disableSelection() {
+        g.selectAll('.nv-brush').attr('display', 'none');
       }
 
 
@@ -370,20 +396,25 @@ nv.models.multiBarWithBrushChart = function() {
       });
 
       controls.dispatch.on('legendClick', function(d,i) {
-        if (!d.disabled) return;
-        controlsData = controlsData.map(function(s) {
-          s.disabled = true;
-          return s;
-        });
-        d.disabled = false;
+        if (typeof d.checkbox == "undefined"){
+          if (!d.disabled) return;
+          controlsData = controlsData.map(function(s) {
+            s.disabled = true;
+            return s;
+          });
+          d.disabled = false;
+        }
 
         switch (d.key) {
-          case 'Grouped':
+          case LABELS.GROUPED:
             multibar.stacked(false);
             break;
-          case 'Stacked':
+          case LABELS.STACKED:
             multibar.stacked(true);
             break;
+          case LABELS.SELECT:
+            selectionEnabled = !selectionEnabled;
+            break;
         }
 
         state.stacked = multibar.stacked();
@@ -480,6 +511,7 @@ nv.models.multiBarWithBrushChart = function() {
   chart.legend = legend;
   chart.xAxis = xAxis;
   chart.yAxis = yAxis;
+  chart.LABELS = LABELS;
 
   d3.rebind(chart, multibar, 'x', 'y', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'clipEdge',
    'id', 'stacked', 'stackOffset', 'delay', 'barColor','groupSpacing');
@@ -605,11 +637,6 @@ nv.models.multiBarWithBrushChart = function() {
     return chart;
   };
 
-  chart.enableSelection = function() {
-    selectionEnabled = true;
-    return chart;
-  };
-
   chart.onSelectRange = function(_) {
     if (!arguments.length) return onSelectRange;
     onSelectRange = _;