Refactoring

This commit is contained in:
Maxime Beauchemin 2016-01-13 08:50:55 -08:00
parent b6b8d046c8
commit 4f7a5f33bb
8 changed files with 48 additions and 103 deletions

View File

@ -77,7 +77,7 @@ var px = (function() {
return token.width(); return token.width();
}, },
height: function(){ height: function(){
return token.height(); return token.height() - 25;
}, },
render: function() { render: function() {
$('.btn-group.results span').attr('disabled','disabled'); $('.btn-group.results span').attr('disabled','disabled');
@ -222,7 +222,7 @@ var px = (function() {
$(".select2").select2({dropdownAutoWidth : true}); $(".select2").select2({dropdownAutoWidth : true});
$(".select2Sortable").select2(); $(".select2Sortable").select2();
$(".select2Sortable").select2Sortable(); $(".select2Sortable").select2Sortable({bindOrder: 'sortableStop'});
$("form").show(); $("form").show();
$('[data-toggle="tooltip"]').tooltip({container: 'body'}); $('[data-toggle="tooltip"]').tooltip({container: 'body'});

View File

@ -17,7 +17,7 @@ px.registerViz('big_number', function(slice) {
var f = d3.format('.3s'); var f = d3.format('.3s');
var fp = d3.format('+.1%'); var fp = d3.format('+.1%');
var width = slice.width(); var width = slice.width();
var height = slice.height() - 30; var height = slice.height();
var svg = div.append('svg'); var svg = div.append('svg');
svg.attr("width", width); svg.attr("width", width);
svg.attr("height", height); svg.attr("height", height);

View File

@ -25,19 +25,17 @@ function viz_nvd3(slice) {
]; ];
var refresh = function() { var refresh = function() {
$.getJSON(slice.jsonEndpoint(), function(payload) { $.getJSON(slice.jsonEndpoint(), function(payload) {
var data = payload.data; var fd = payload.form_data;
var viz = payload; var viz_type = fd.viz_type;
var viz_type = viz.form_data.viz_type;
var fd = viz.form_data;
var f = d3.format('.4s'); var f = d3.format('.4s');
nv.addGraph(function() { nv.addGraph(function() {
if (viz_type === 'line') { if (viz_type === 'line') {
if (viz.form_data.show_brush) { if (fd.show_brush) {
chart = nv.models.lineWithFocusChart(); chart = nv.models.lineWithFocusChart();
//chart.lines2.xScale( d3.time.scale.utc()); //chart.lines2.xScale( d3.time.scale.utc());
chart.lines2.xScale(d3.time.scale.utc()); chart.lines2.xScale(d3.time.scale.utc());
chart.x2Axis chart.x2Axis
.showMaxMin(viz.form_data.x_axis_showminmax) .showMaxMin(fd.x_axis_showminmax)
.tickFormat(formatDate) .tickFormat(formatDate)
.staggerLabels(true); .staggerLabels(true);
} else { } else {
@ -46,17 +44,17 @@ function viz_nvd3(slice) {
// To alter the tooltip header // To alter the tooltip header
// chart.interactiveLayer.tooltip.headerFormatter(function(){return '';}); // chart.interactiveLayer.tooltip.headerFormatter(function(){return '';});
chart.xScale(d3.time.scale.utc()); chart.xScale(d3.time.scale.utc());
chart.interpolate(viz.form_data.line_interpolation); chart.interpolate(fd.line_interpolation);
chart.xAxis chart.xAxis
.showMaxMin(viz.form_data.x_axis_showminmax) .showMaxMin(fd.x_axis_showminmax)
.tickFormat(formatDate) .tickFormat(formatDate)
.staggerLabels(true); .staggerLabels(true);
chart.showLegend(viz.form_data.show_legend); chart.showLegend(fd.show_legend);
chart.yAxis.tickFormat(d3.format('.3s')); chart.yAxis.tickFormat(d3.format('.3s'));
if (chart.y2Axis != undefined) { if (chart.y2Axis != undefined) {
chart.y2Axis.tickFormat(d3.format('.3s')); chart.y2Axis.tickFormat(d3.format('.3s'));
} }
if (viz.form_data.contribution || viz.form_data.num_period_compare) { if (fd.contribution || fd.num_period_compare) {
chart.yAxis.tickFormat(d3.format('.3p')); chart.yAxis.tickFormat(d3.format('.3p'));
if (chart.y2Axis != undefined) { if (chart.y2Axis != undefined) {
chart.y2Axis.tickFormat(d3.format('.3p')); chart.y2Axis.tickFormat(d3.format('.3p'));
@ -70,7 +68,7 @@ function viz_nvd3(slice) {
.showMaxMin(false) .showMaxMin(false)
.tickFormat(formatDate) .tickFormat(formatDate)
.staggerLabels(true); .staggerLabels(true);
chart.showLegend(viz.form_data.show_legend); chart.showLegend(fd.show_legend);
chart.yAxis.tickFormat(d3.format('.3s')); chart.yAxis.tickFormat(d3.format('.3s'));
} else if (viz_type === 'dist_bar') { } else if (viz_type === 'dist_bar') {
@ -85,8 +83,8 @@ function viz_nvd3(slice) {
} else if (viz_type === 'pie') { } else if (viz_type === 'pie') {
chart = nv.models.pieChart() chart = nv.models.pieChart()
chart.showLegend(viz.form_data.show_legend); chart.showLegend(fd.show_legend);
if (viz.form_data.donut) { if (fd.donut) {
chart.donut(true); chart.donut(true);
chart.donutLabelsOutside(true); chart.donutLabelsOutside(true);
} }
@ -106,7 +104,7 @@ function viz_nvd3(slice) {
.showMaxMin(false) .showMaxMin(false)
.tickFormat(formatDate) .tickFormat(formatDate)
.staggerLabels(true); .staggerLabels(true);
chart.showLegend(viz.form_data.show_legend); chart.showLegend(fd.show_legend);
chart.yAxis.tickFormat(d3.format('.3p')); chart.yAxis.tickFormat(d3.format('.3p'));
} else if (viz_type === 'bubble') { } else if (viz_type === 'bubble') {
@ -138,38 +136,38 @@ function viz_nvd3(slice) {
.showMaxMin(false) .showMaxMin(false)
.tickFormat(formatDate) .tickFormat(formatDate)
.staggerLabels(true); .staggerLabels(true);
chart.showLegend(viz.form_data.show_legend); chart.showLegend(fd.show_legend);
chart.yAxis.tickFormat(d3.format('.3s')); chart.yAxis.tickFormat(d3.format('.3s'));
} }
// make space for labels on right // make space for labels on right
//chart.height($(".chart").height() - 50).margin({"right": 50}); //chart.height($(".chart").height() - 50).margin({"right": 50});
if ((viz_type === "line" || viz_type === "area") && viz.form_data.rich_tooltip) { if ((viz_type === "line" || viz_type === "area") && fd.rich_tooltip) {
chart.useInteractiveGuideline(true); chart.useInteractiveGuideline(true);
} }
if (viz.form_data.y_axis_zero) { if (fd.y_axis_zero) {
chart.forceY([0, 1]); chart.forceY([0, 1]);
} }
else if (viz.form_data.y_log_scale) { else if (fd.y_log_scale) {
chart.yScale(d3.scale.log()); chart.yScale(d3.scale.log());
} }
if (viz.form_data.x_log_scale) { if (fd.x_log_scale) {
chart.xScale(d3.scale.log()); chart.xScale(d3.scale.log());
} }
if (viz.form_data.y_axis_format) { if (fd.y_axis_format) {
chart.yAxis.tickFormat(d3.format(viz.form_data.y_axis_format)); chart.yAxis.tickFormat(d3.format(fd.y_axis_format));
if (chart.y2Axis != undefined) { if (chart.y2Axis != undefined) {
chart.y2Axis.tickFormat(d3.format(viz.form_data.y_axis_format)); chart.y2Axis.tickFormat(d3.format(fd.y_axis_format));
} }
} }
chart.duration(0); chart.duration(0);
d3.select(slice.selector).append("svg") d3.select(slice.selector).append("svg")
.datum(data.chart_data) .datum(payload.data)
.transition().duration(500) .transition().duration(500)
.call(chart); .call(chart);
// if it is a two axis chart, rescale it down just a little so it fits in the div. // if it is a two axis chart, rescale it down just a little so it fits in the div.
if(chart.hasOwnProperty("x2Axis")) { if(chart.hasOwnProperty("x2Axis")) {
two_axis_chart = $(slice.selector + " > svg"); two_axis_chart = $(slice.selector + " > svg");
@ -177,10 +175,9 @@ function viz_nvd3(slice) {
h = two_axis_chart.height(); h = two_axis_chart.height();
two_axis_chart.get(0).setAttribute('viewBox', '0 0 '+w+' '+(h+30)); two_axis_chart.get(0).setAttribute('viewBox', '0 0 '+w+' '+(h+30));
} }
return chart; return chart;
}); });
slice.done(data); slice.done(payload);
}) })
.fail(function(xhr) { .fail(function(xhr) {
slice.error(xhr.responseText); slice.error(xhr.responseText);

View File

@ -4,19 +4,15 @@ Modified from http://bl.ocks.org/kerryrodden/7090426
function viz_sunburst(slice) { function viz_sunburst(slice) {
var container = d3.select(slice.selector); var container = d3.select(slice.selector);
var width = slice.width();
var height = slice.height() - 25;
var render = function() { var render = function() {
// Breadcrumb dimensions: width, height, spacing, width of tip/tail. var width = slice.width();
var b = { var height = slice.height() - 5;
w: 100, h: 30, s: 3, t: 10
};
var colorScale;
// Total size of all segments; we set this later, after loading the data. // Total size of all segments; we set this later, after loading the data.
var totalSize = 0; var totalSize = 0;
var radius = Math.min(width, height) / 2; var radius = Math.min(width, height) / 2;
container.select("svg").remove();
var vis = container.append("svg:svg") var vis = container.append("svg:svg")
.attr("width", width) .attr("width", width)
.attr("height", height) .attr("height", height)
@ -64,7 +60,7 @@ function viz_sunburst(slice) {
}); });
ext = d3.extent(nodes, function(d){return d.m2 / d.m1;}); ext = d3.extent(nodes, function(d){return d.m2 / d.m1;});
colorScale = d3.scale.linear() var colorScale = d3.scale.linear()
.domain([ext[0], ext[0] + ((ext[1] - ext[0]) / 2), ext[1]]) .domain([ext[0], ext[0] + ((ext[1] - ext[0]) / 2), ext[1]])
.range(["#00D1C1", "white","#FFB400"]); .range(["#00D1C1", "white","#FFB400"]);
@ -112,7 +108,6 @@ function viz_sunburst(slice) {
.text("m2/m1: " + fp(d.m2/d.m1)); .text("m2/m1: " + fp(d.m2/d.m1));
var sequenceArray = getAncestors(d); var sequenceArray = getAncestors(d);
updateBreadcrumbs(sequenceArray, percentageString);
// Fade all the segments. // Fade all the segments.
container.selectAll("path") container.selectAll("path")
@ -165,31 +160,6 @@ function viz_sunburst(slice) {
return path; return path;
} }
// Generate a string that describes the points of a breadcrumb polygon.
function breadcrumbPoints(d, i) {
var points = [];
points.push("0,0");
points.push(b.w + ",0");
points.push(b.w + b.t + "," + (b.h / 2));
points.push(b.w + "," + b.h);
points.push("0," + b.h);
if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.
points.push(b.t + "," + (b.h / 2));
}
return points.join(" ");
}
// Update the breadcrumb trail to show the current sequence and percentage.
function updateBreadcrumbs(nodeArray, percentageString) {
l = [];
for(var i=0; i<nodeArray.length; i++){
l.push(nodeArray[i].name)
}
s = l.join(' > ')
gMiddleText.append("text").text(s).classed("middle", true)
.attr("y", -75);
}
function buildHierarchy(rows) { function buildHierarchy(rows) {
var root = {"name": "root", "children": []}; var root = {"name": "root", "children": []};
for (var i = 0; i < rows.length; i++) { for (var i = 0; i < rows.length; i++) {

View File

@ -1,3 +1,3 @@
.world_map svg{ .world_map svg{
background-color: LightSkyBlue; background-color: #bce8f1;
} }

View File

@ -1,13 +1,14 @@
/* /*
Using the awesome lib at http://datamaps.github.io/ Using the awesome lib at http://datamaps.github.io/
*/ */
function viz_world_map(slice) { function viz_world_map(slice) {
var render = function() { var render = function() {
var container = slice.container; var container = slice.container;
var div = d3.select(slice.selector); var div = d3.select(slice.selector);
d3.json(slice.jsonEndpoint(), function(error, json){ d3.json(slice.jsonEndpoint(), function(error, json){
var fd = json.form_data;
if (error != null){ if (error != null){
slice.error(error.responseText); slice.error(error.responseText);
@ -16,14 +17,14 @@ function viz_world_map(slice) {
var ext = d3.extent(json.data, function(d){return d.m1}); var ext = d3.extent(json.data, function(d){return d.m1});
var extRadius = d3.extent(json.data, function(d){return d.m2}); var extRadius = d3.extent(json.data, function(d){return d.m2});
var radiusScale = d3.scale.linear() var radiusScale = d3.scale.linear()
.domain([extRadius[0], extRadius[1]]) .domain([extRadius[0], extRadius[1]])
.range([1, slice.data.form_data.max_bubble_size]); .range([1, fd.max_bubble_size]);
json.data.forEach(function(d){ json.data.forEach(function(d){
d.radius = radiusScale(d.m2); d.radius = radiusScale(d.m2);
}) });
var colorScale = d3.scale.linear() var colorScale = d3.scale.linear()
.domain([ext[0], ext[1]]) .domain([ext[0], ext[1]])
.range(["#FFF", "black"]); .range(["#FFF", "black"]);
var d = {}; var d = {};
for (var i=0; i<json.data.length; i++){ for (var i=0; i<json.data.length; i++){
var country = json.data[i]; var country = json.data[i];
@ -69,10 +70,10 @@ function viz_world_map(slice) {
highlightFillOpacity: 0.85, highlightFillOpacity: 0.85,
exitDelay: 100, exitDelay: 100,
key: JSON.stringify key: JSON.stringify
}, },
}); });
map.updateChoropleth(d); map.updateChoropleth(d);
if(slice.data.form_data.show_bubbles){ if(fd.show_bubbles){
map.bubbles(json.data); map.bubbles(json.data);
div.selectAll("circle.datamaps-bubble").style('fill', '#005a63'); div.selectAll("circle.datamaps-bubble").style('fill', '#005a63');
} }

View File

@ -168,12 +168,7 @@
<h4 class="modal-title">Query</h4> <h4 class="modal-title">Query</h4>
</div> </div>
<div class="modal-body"> <div class="modal-body">
<pre id="query_container"> <pre id="query_container"></pre>
{% if viz.query %}
{% else %}
<img width="250" src="{{ url_for('static', filename="img/penguins.png") }}" alt="Under construction">
{% endif %}
</pre>
</div> </div>
<div class="modal-footer"> <div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

View File

@ -540,11 +540,7 @@ class BubbleViz(NVD3Viz):
'key': k, 'key': k,
"color": utils.color(str(k)), "color": utils.color(str(k)),
'values': v }) 'values': v })
return dumps({ return dumps(chart_data)
'chart_data': chart_data,
'query': self.results.query,
'duration': self.results.duration,
})
class BigNumberViz(BaseViz): class BigNumberViz(BaseViz):
viz_type = "big_number" viz_type = "big_number"
@ -740,13 +736,7 @@ class NVD3TimeSeriesViz(NVD3Viz):
chart_data += self.to_series( chart_data += self.to_series(
df2, classed='dashed', title_suffix="---") df2, classed='dashed', title_suffix="---")
chart_data = sorted(chart_data, key=lambda x: x['key']) chart_data = sorted(chart_data, key=lambda x: x['key'])
return dumps(chart_data)
data = {
'chart_data': chart_data,
'query': self.results.query,
'duration': self.results.duration,
}
return dumps(data)
class NVD3TimeSeriesBarViz(NVD3TimeSeriesViz): class NVD3TimeSeriesBarViz(NVD3TimeSeriesViz):
@ -800,11 +790,7 @@ class DistributionPieViz(NVD3Viz):
df = df.reset_index() df = df.reset_index()
df.columns = ['x', 'y'] df.columns = ['x', 'y']
df['color'] = map(utils.color, df.x) df['color'] = map(utils.color, df.x)
return dumps({ return dumps(df.to_dict(orient="records"))
'chart_data': df.to_dict(orient="records"),
'query': self.results.query,
'duration': self.results.duration,
})
class DistributionBarViz(DistributionPieViz): class DistributionBarViz(DistributionPieViz):
@ -853,11 +839,7 @@ class DistributionBarViz(DistributionPieViz):
for i, ds in enumerate(df.timestamp)] for i, ds in enumerate(df.timestamp)]
} }
chart_data.append(d) chart_data.append(d)
return dumps({ return dumps(chart_data)
'chart_data': chart_data,
'query': self.results.query,
'duration': self.results.duration,
})
class SunburstViz(BaseViz): class SunburstViz(BaseViz):