Self hosted FLOSS fitness/workout, nutrition and weight tracker
Refactor the weight chart code
Roland Geider0cab94c71fc4
diff --git a/manager/static/js/workout-manager.js b/manager/static/js/workout-manager.jsindex 8609fd707..54dae1967 100644--- a/manager/static/js/workout-manager.js+++ b/manager/static/js/workout-manager.js@@ -344,3 +344,96 @@ function init_weight_datepicker(){$( "#id_creation_date" ).datepicker({ dateFormat: "dd.mm.yy" });}++++/*+ *+ * D3js functions+ *+ */+// Simple helper function that simply returns the y component of an entry+function y_value(d) { return d.y; }++function getDate(d) {+ return new Date(d);+}++function weight_chart(data)+{+ var minDate = getDate(data[0].x),+ maxDate = getDate(data[data.length-1].x);++ var margin = {top: 10, right: 10, bottom: 20, left: 40},+ width = 600 - margin.left - margin.right,+ height = 300 - margin.top - margin.bottom;++ var x = d3.time.scale()+ .domain([minDate, maxDate])+ .range([0, width]);++ var min_y_value = d3.min(data, y_value) - 1;+ var max_y_value = d3.max(data, y_value) + 1;+++ var y = d3.scale.linear()+ .domain([min_y_value, max_y_value])+ .range([height, 0]);++ var xAxis = d3.svg.axis()+ .scale(x)+ .orient("bottom");++ var yAxis = d3.svg.axis()+ .scale(y)+ .orient("left");++ var line = d3.svg.line()+ .x(function(d) { return x(getDate(d.x)); })+ .y(function(d) { return y(d.y); });++ var area = d3.svg.area()+ .x(line.x())+ .y1(line.y())+ .y0(y(min_y_value));++ var svg = d3.select("#weight_diagram").append("svg")+ .datum(data)+ .attr("width", width + margin.left + margin.right)+ .attr("height", height + margin.top + margin.bottom)+ .append("g")+ .attr("transform", "translate(" + margin.left + "," + margin.top + ")");++ svg.append("path")+ .attr("class", "area")+ .attr("d", area);++ svg.append("g")+ .attr("class", "x axis")+ .attr("transform", "translate(0," + height + ")")+ .call(xAxis);++ svg.append("g")+ .attr("class", "y axis")+ .call(yAxis);++ svg.append("path")+ .attr("class", "line")+ .attr("d", line);++ svg.selectAll(".dot")+ .data(data.filter(function(d) { return d.y; }))+ .enter().append("circle")+ .attr("class", "dot")+ .attr("id", function(d) { return d.id; })+ .attr("cx", line.x())+ .attr("cy", line.y())+ .attr("r", 5);+++ // Make the circles clickable: open their edit dialog+ $('circle').click(function(e) {+ entry_id = $(this).attr('id').match(/\d+/);+ scatterplot_modal_dialog(entry_id);+ });+}\ No newline at end of filediff --git a/weight/templates/weight_overview.html b/weight/templates/weight_overview.htmlindex 9e028e631..1097d82f4 100644--- a/weight/templates/weight_overview.html+++ b/weight/templates/weight_overview.html@@ -25,98 +25,29 @@ function custom_modal_init(){init_weight_datepicker();}-// Simple helper function that simply returns the y component of an entry-function y_value(d) { return d.y; }--function getDate(d) {- return new Date(d);-}+$(document).ready(function () {+$.getJSON("/weight/api/get_weight_data/", function(json) {+ weight_chart(json);+});-$(document).ready(function () {+$("#weight_filter_from").datepicker({ dateFormat: "dd.mm.yy",+ minDate: {{min_date}}+ });+$("#weight_filter_to").datepicker({ dateFormat: "dd.mm.yy",+ maxDate: {{max_date}}+ });// Init the modal dialogform_modal_dialog();-var data = {{chart_data|safe}};---var minDate = getDate(data[0].x),- maxDate = getDate(data[data.length-1].x);--var margin = {top: 10, right: 10, bottom: 20, left: 40},- width = 600 - margin.left - margin.right,- height = 300 - margin.top - margin.bottom;--var x = d3.time.scale()- .domain([minDate, maxDate])- .range([0, width]);--var min_y_value = d3.min(data, y_value) - 1;-var max_y_value = d3.max(data, y_value) + 1;---var y = d3.scale.linear()- .domain([min_y_value, max_y_value])- .range([height, 0]);--var xAxis = d3.svg.axis()- .scale(x)- .orient("bottom");--var yAxis = d3.svg.axis()- .scale(y)- .orient("left");--var line = d3.svg.line()- .x(function(d) { return x(getDate(d.x)); })- .y(function(d) { return y(d.y); });--var area = d3.svg.area()- .x(line.x())- .y1(line.y())- .y0(y(min_y_value));--var svg = d3.select("#weight_diagram").append("svg")- .datum(data)- .attr("width", width + margin.left + margin.right)- .attr("height", height + margin.top + margin.bottom)- .append("g")- .attr("transform", "translate(" + margin.left + "," + margin.top + ")");--svg.append("path")- .attr("class", "area")- .attr("d", area);--svg.append("g")- .attr("class", "x axis")- .attr("transform", "translate(0," + height + ")")- .call(xAxis);-svg.append("g")- .attr("class", "y axis")- .call(yAxis);-svg.append("path")- .attr("class", "line")- .attr("d", line);-svg.selectAll(".dot")- .data(data.filter(function(d) { return d.y; }))- .enter().append("circle")- .attr("class", "dot")- .attr("id", function(d) { return d.id; })- .attr("cx", line.x())- .attr("cy", line.y())- .attr("r", 5);+//alert(data);-// Make the circles clickable: open their edit dialog-$('circle').click(function(e) {- entry_id = $(this).attr('id').match(/\d+/);- scatterplot_modal_dialog(entry_id);- });});</script>{% endblock %}@@ -147,7 +78,22 @@ $('circle').click(function(e) {-->{% block sidebar %}<h3>{% trans "Filter options" %}</h3>-<p>Filter widgets etc come here</p>+<form>+{% trans "from" %}+<input type="text"+ id="weight_filter_from"+ name="weight_filter_from"+ maxlength="9"+ style="width: 6em;">+{% trans "till" %}+<input type="text"+ id="weight_filter_to"+ name="weight_filter_to"+ maxlength="9"+ style="width: 6em;">+<input class="ajax-form-submit" type="submit" value="{% trans 'Filter' %}">++</form><h3>{% trans "Options" %}</h3><p>diff --git a/weight/urls.py b/weight/urls.pyindex d7e875af9..a4329312d 100644--- a/weight/urls.py+++ b/weight/urls.py@@ -4,6 +4,7 @@ urlpatterns = patterns('weight.views',url(r'^weight/add/(?P<id>\w*)$', 'add'),url(r'^weight/export_csv/$', 'export_csv'),url(r'^weight/overview/$', 'overview'),+ url(r'^weight/api/get_weight_data/$', 'get_weight_data'),)diff --git a/weight/views.py b/weight/views.pyindex 0d2d60b91..e4c1879a4 100644--- a/weight/views.py+++ b/weight/views.py@@ -28,6 +28,8 @@ from django.core.context_processors import csrffrom django.core.urlresolvers import reversefrom django.contrib.auth.decorators import login_requiredfrom django.utils.translation import ugettext as _+from django.db.models import Min+from django.db.models import Maxfrom weight.models import WeightEntry@@ -105,25 +107,45 @@ def overview(request):* http://d3js.org/"""template_data = {}- weights = WeightEntry.objects.filter(user = request.user)- template_data['weights'] = weightstemplate_data['active_tab'] = 'weight'- # Process the data to pass it to the JS libraries to generate an SVG image- chart_data = "[\n"-- for i in weights:- chart_data += '{x: "%(month)s/%(day)s/%(year)s", y: %(weight)s, id: %(id)s},\n' % {- 'year': i.creation_date.year,- 'month': i.creation_date.month,- 'day': i.creation_date.day,- 'weight': i.weight,- 'id': '"entry-%s"' % i.id}-- chart_data = chart_data.rstrip(',')- chart_data += "]"- template_data['chart_data'] = chart_data-+ min_date = WeightEntry.objects.filter(user = request.user).aggregate(Min('creation_date'))['creation_date__min']+ max_date = WeightEntry.objects.filter(user = request.user).aggregate(Max('creation_date'))['creation_date__max']+ template_data['min_date'] = 'new Date(%(year)s, %(month)s, %(day)s)' % {'year': min_date.year,+ 'month': min_date.month,+ 'day': min_date.day}+ template_data['max_date'] = 'new Date(%(year)s, %(month)s, %(day)s)' % {'year': max_date.year,+ 'month': max_date.month,+ 'day': max_date.day}return render_to_response('weight_overview.html',template_data,context_instance=RequestContext(request))++@login_required+def get_weight_data(request):+ # Process the data to pass it to the JS libraries to generate an SVG image++ if request.is_ajax():+ date_min = request.GET.get('date_min', False)+ date_max = request.GET.get('date_max', True)++ if date_min and date_max:+ weights = WeightEntry.objects.filter(user = request.user,+ creation_date__range=(date_min, date_max))+ else:+ weights = WeightEntry.objects.filter(user = request.user)++ chart_data = []++ for i in weights:+ chart_data.append({'x': "%(month)s/%(day)s/%(year)s" % {+ 'year': i.creation_date.year,+ 'month': i.creation_date.month,+ 'day': i.creation_date.day},+ 'y': i.weight,+ 'id': i.id})+++ # Return the results to the server+ mimetype = 'application/json'+ return HttpResponse(json.dumps(chart_data), mimetype)\ No newline at end of file