Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Refactor nutrion.js to adhere to coding standard

Peter van der Doesedf2b6b2ae66
diff --git a/wger/nutrition/static/js/nutrition.js b/wger/nutrition/static/js/nutrition.js
index 1a108038a..608656f7c 100644
--- a/wger/nutrition/static/js/nutrition.js
+++ b/wger/nutrition/static/js/nutrition.js
@@ -1,274 +1,319 @@
/*
- * This file is part of wger Workout Manager.
- *
- * wger Workout Manager is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * wger Workout Manager is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
+ This file is part of wger Workout Manager.
+
+ wger Workout Manager is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ wger Workout Manager is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
*/
/*
* wger Nutriton functions
*/
-"use strict";
-
-function update_ingredient_value(url)
-{
- var form_data = $('#nutritional-values-form').serializeArray();
- $.get(url, form_data, function(data) {
-
- // Show any validation errors
- $('#calculator-errors').html('');
- if (data['errors'])
- {
- $.each(data['errors'], function(index, value) {
- $('#calculator-errors').append('<p class="ym-message">'+value+'</p>');
- });
- }
-
- // Replace the nutritional values
- $('#value-energy').html(parseFloat(data['energy']).toFixed(2));
- $('#value-protein').html(parseFloat(data['protein']).toFixed(2));
- $('#value-carbohydrates').html(parseFloat(data['carbohydrates']).toFixed(2));
- $('#value-carbohydrates-sugar').html(parseFloat(data['carbohydrates_sugar']).toFixed(2));
- $('#value-fat').html(parseFloat(data['fat']).toFixed(2));
- $('#value-fat-saturated').html(parseFloat(data['fat_saturated']).toFixed(2));
- $('#value-fibres').html(parseFloat(data['fibres']).toFixed(2));
- $('#value-sodium').html(parseFloat(data['sodium']).toFixed(2));
- });
+'use strict';
+
+function updateIngredientValue(url) {
+ var formData = $('#nutritional-values-form').serializeArray();
+ $.get(url, formData, function (data) {
+ // Show any validation errors
+ $('#calculator-errors').html('');
+ if (data.errors) {
+ $.each(data.errors, function (index, value) {
+ $('#calculator-errors').append('<p class="ym-message">' + value + '</p>');
+ });
+ }
+
+ // Replace the nutritional values
+ $('#value-energy').html(parseFloat(data.energy).toFixed(2));
+ $('#value-protein').html(parseFloat(data.protein).toFixed(2));
+ $('#value-carbohydrates').html(parseFloat(data.carbohydrates).toFixed(2));
+ $('#value-carbohydrates-sugar').html(parseFloat(data.carbohydrates_sugar).toFixed(2));
+ $('#value-fat').html(parseFloat(data.fat).toFixed(2));
+ $('#value-fat-saturated').html(parseFloat(data.fat_saturated).toFixed(2));
+ $('#value-fibres').html(parseFloat(data.fibres).toFixed(2));
+ $('#value-sodium').html(parseFloat(data.sodium).toFixed(2));
+ });
}
-function init_ingredient_detail(url)
-{
- // Prevent the form from being sent
- $('#nutritional-values-form').submit(function(e) {
- e.preventDefault();
- });
+// noinspection Eslint
+function initIngredientDetail(url) {
+ // Prevent the form from being sent
+ $('#nutritional-values-form').submit(function (e) {
+ e.preventDefault();
+ });
- $('#id_amount').keyup(function(){
- update_ingredient_value(url);
- });
+ $('#id_amount').keyup(function () {
+ updateIngredientValue(url);
+ });
- $('#id_unit').change(function(){
- update_ingredient_value(url);
- });
+ $('#id_unit').change(function () {
+ updateIngredientValue(url);
+ });
}
-
-
/*
* Update the user's preferences
*/
-function init_ingredient_autocompleter()
-{
- // Init the autocompleter
- $('#id_ingredient_searchfield').devbridgeAutocomplete({
- serviceUrl: '/api/v2/ingredient/search/',
- onSelect: function (suggestion) {
- var ingredient_id = suggestion.data.id;
-
- // After clicking on a result set the value of the hidden field
- $('#id_ingredient').val(ingredient_id);
- $('#exercise_name').html(suggestion.value);
-
- // See if the ingredient has any units and set the values for the forms
- $.get('/api/v2/ingredientweightunit/?ingredient=' + ingredient_id, function(unit_data) {
-
- // Remove any old units, if any
- var options = $('#id_weight_unit').find('option');
- $.each(options, function(index, option_obj) {
- if (option_obj.value != '')
- {
- $(option_obj).remove();
- }
- });
-
- // Add new units, if any
- $.each(unit_data.results, function(index, value) {
- $.get('/api/v2/weightunit/' + value.unit + '/', function(unit) {
- var unit_name = unit.name + ' (' + value.gram + 'g)';
- $('#id_unit').append(new Option(unit_name, value.id));
- $('#id_weight_unit').append(new Option(unit_name, value.id));
- });
- });
- });
- },
- paramName: 'term',
- transformResult: function(response) {
- // why is response not already a JSON object??
- var jsonResponse = $.parseJSON(response);
- return {
- suggestions: $.map(jsonResponse, function(item) {
- return {value: item.value, data: {id: item.id}};
- })
- };
- }
- });
-}
+// noinspection Eslint
+function initIngredientAutocompleter() {
+ // Init the autocompleter
+ $('#id_ingredient_searchfield').devbridgeAutocomplete({
+ serviceUrl: '/api/v2/ingredient/search/',
+ onSelect: function (suggestion) {
+ var ingredientId = suggestion.data.id;
+
+ // After clicking on a result set the value of the hidden field
+ $('#id_ingredient').val(ingredientId);
+ $('#exercise_name').html(suggestion.value);
+
+ // See if the ingredient has any units and set the values for the forms
+ $.get('/api/v2/ingredientweightunit/?ingredient=' + ingredientId, function (unitData) {
+ // Remove any old units, if any
+ var options = $('#id_weight_unit').find('option');
+ $.each(options, function (index, optionObj) {
+ if (optionObj.value !== '') {
+ $(optionObj).remove();
+ }
+ });
+ // Add new units, if any
+ $.each(unitData.results, function (index, value) {
+ $.get('/api/v2/weightunit/' + value.unit + '/', function (unit) {
+ var unitName = unit.name + ' (' + value.gram + 'g)';
+ $('#id_unit').append(new Option(unitName, value.id));
+ $('#id_weight_unit').append(new Option(unitName, value.id));
+ });
+ });
+ });
+ },
+ paramName: 'term',
+ transformResult: function (response) {
+ // why is response not already a JSON object??
+ var jsonResponse = $.parseJSON(response);
+ return {
+ suggestions: $.map(jsonResponse, function (item) {
+ return { value: item.value, data: { id: item.id } };
+ })
+ };
+ }
+ });
+}
/*
* Draw the BMI chart
*/
-function render_bmi(width_factor)
-{
- // Delete the other diagrams
- d3.selectAll('svg').remove();
-
- // Calculate the size
- var width_factor = typeof width_factor !== 'undefined' ? width_factor: 600;
- var height_factor = width_factor / 600 * 300;
-
- var margin = {top: 20, right: 80, bottom: 30, left: 50},
- width = width_factor - margin.left - margin.right,
- height = height_factor - margin.top - margin.bottom;
-
- var x = d3.scaleLinear()
- .range([0, width]);
-
- var y = d3.scaleLinear()
- .range([height, 0]);
-
- var z = d3.scaleOrdinal().range(['#000080', '#0000ff', '#00ffff', '#00ff00', '#ffff00', '#ff7f2a', '#ff0000', '#800000']);
-
- var xAxis = d3.axisBottom(x);
-
- var yAxis = d3.axisLeft(y);
-
- var stack = d3.stack();
-
- var nest = d3.nest()
- .key(function(d) { return d.key; });
-
- var area = d3.area()
- .x(function(d) { return x(d.height); })
- .y1(function(d) { return y(d.weight); });
-
-
- var svg = d3.select("#bmi-chart").append("svg")
- .attr("width", width + margin.left + margin.right)
- .attr("height", height + margin.top + margin.bottom)
- .append("g")
- .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
-
- // Clip path, drawings outside are removed
- svg.append("defs").append("clipPath")
- .attr("id", "clip")
- .append("rect")
- .attr("width", width)
- .attr("height", height);
-
-
- d3.json("/nutrition/calculator/bmi/chart-data", function(data) {
-
- stack.keys(["filler", "severe_thinness","moderate_thinness","mild_thinness","normal_range","pre_obese","obese_class_2","obese_class_3"]);
- var layers = stack(nest.entries(data));
-
- // Manually set the domains
- x.domain([150, 200]); // height, in cm
- y.domain([30, 160]); // weight, in kg
-
- svg.selectAll(".layer")
- .data(layers)
- .enter().append("path")
- .attr("class", "layer")
- .attr("id", function(d, i) { return "key-" + d.key; })
- .attr("clip-path", "url(#clip)")
- .attr("d", function(d, i) { return area(d[i].data.values); })
- .style("fill", function(d, i) { return z(i); })
- .style("opacity", 1);
-
- svg.append("g")
- .attr("class", "x axis")
- .attr("transform", "translate(0," + height + ")")
- .call(xAxis);
-
- svg.append("g")
- //.attr("transform", "translate(" + width + ",0)")
- .attr("class", "y axis")
- .call(yAxis);
-
- var url = $("#bmi-form").attr( 'action' );
+// noinspection Eslint
+function renderBodyMassIndex(w) {
+ var svg;
+ var area;
+ var nest;
+ var stack;
+ var yAxis;
+ var xAxis;
+ var z;
+ var y;
+ var x;
+ var margin;
+ var width;
+ var height;
+ var heightFactor;
+ var widthFactor;
+
+ // Delete the other diagrams
+ d3.selectAll('svg').remove();
+
+ // Calculate the size
+ if (typeof w === 'undefined') {
+ widthFactor = 600;
+ } else {
+ widthFactor = w;
+ }
+
+ heightFactor = widthFactor / (600 * 300);
+
+ margin = { top: 20, right: 80, bottom: 30, left: 50 };
+ width = widthFactor - margin.left - margin.right;
+ height = heightFactor - margin.top - margin.bottom;
+
+ x = d3.scaleLinear()
+ .range([0, width]);
+
+ y = d3.scaleLinear()
+ .range([height, 0]);
+
+ z = d3.scaleOrdinal().range(['#000080',
+ '#0000ff',
+ '#00ffff',
+ '#00ff00',
+ '#ffff00',
+ '#ff7f2a',
+ '#ff0000',
+ '#800000']);
+
+ xAxis = d3.axisBottom(x);
+
+ yAxis = d3.axisLeft(y);
+
+ stack = d3.stack();
+
+ nest = d3.nest()
+ .key(function (d) {
+ return d.key;
+ });
- $.post(url,
- $("#bmi-form").serialize(),
- function(data) {
- $('#bmi-result-container').show();
- $('#bmi-result-value').html(data.bmi);
- svg.append("circle")
- .attr("cx", x(data.height))
- .attr("cy", y(data.weight))
- .attr("fill", "black")
- .attr("r", 5);
- });
+ area = d3.area()
+ .x(function (d) {
+ return x(d.height);
+ })
+ .y1(function (d) {
+ return y(d.weight);
});
+ svg = d3.select('#bmi-chart').append('svg')
+ .attr('width', width + margin.left + margin.right)
+ .attr('height', height + margin.top + margin.bottom)
+ .append('g')
+ .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
+
+ // Clip path, drawings outside are removed
+ svg.append('defs').append('clipPath')
+ .attr('id', 'clip')
+ .append('rect')
+ .attr('width', width)
+ .attr('height', height);
+
+ d3.json('/nutrition/calculator/bmi/chart-data', function (data) {
+ var $bmiForm;
+ var url;
+ var layers;
+ stack.keys(['filler',
+ 'severe_thinness',
+ 'moderate_thinness',
+ 'mild_thinness',
+ 'normal_range',
+ 'pre_obese',
+ 'obese_class_2',
+ 'obese_class_3']);
+ layers = stack(nest.entries(data));
+
+ // Manually set the domains
+ x.domain([150, 200]); // height, in cm
+ y.domain([30, 160]); // weight, in kg
+
+ svg.selectAll('.layer')
+ .data(layers)
+ .enter().append('path')
+ .attr('class', 'layer')
+ .attr('id', function (d) {
+ return 'key-' + d.key;
+ })
+ .attr('clip-path', 'url(#clip)')
+ .attr('d', function (d, i) {
+ return area(d[i].data.values);
+ })
+ .style('fill', function (d, i) {
+ return z(i);
+ })
+ .style('opacity', 1);
+
+ svg.append('g')
+ .attr('class', 'x axis')
+ .attr('transform', 'translate(0,' + height + ')')
+ .call(xAxis);
+
+ svg.append('g')
+ .attr('class', 'y axis')
+ .call(yAxis);
+
+ $bmiForm = $('#bmi-form');
+ url = $bmiForm.attr('action');
+
+ $.post(url,
+ $bmiForm.serialize(),
+ function (postData) {
+ $('#bmi-result-container').show();
+ $('#bmi-result-value').html(postData.bmi);
+ svg.append('circle')
+ .attr('cx', x(postData.height))
+ .attr('cy', y(postData.weight))
+ .attr('fill', 'black')
+ .attr('r', 5);
+ });
+ });
}
-
/*
* Calories calculator
*/
-function init_calories_calculator()
-{
- $("#form-transfer-calories").click(function(e){
- e.preventDefault();
- var base_calories = Number($('#id_base_calories').html());
- $('#id_calories').val(base_calories);
- });
-
- $("#add-calories-total").click(function(e){
- e.preventDefault();
- var base_calories = Number($('#id_base_calories').html());
- var additional_calories = Number($('#id_additional_calories').val());
- $('#id_calories').val(base_calories + additional_calories);
- });
-
- $("#form-update-calories").click(function(e){
- e.preventDefault();
-
- // Get own ID and update the user profile
- $.get('/api/v2/userprofile', function(data) {
- }).done(function(userprofile) {
- var total_calories = $("#id_calories")[0].value;
- $.ajax({
- url:'/api/v2/userprofile/' + userprofile.results[0].id + '/',
- type: 'PATCH',
- data: {calories: total_calories}
- });
- });
- });
-
- $(".calories-autoform").click(function(e){
- e.preventDefault();
-
- // BMR
- var bmr_url = $("#bmr-form").attr('action');
- $.post(bmr_url,
- $("#bmr-form").serialize(),
- function(data) {
- $('#bmr-result-container').show();
- $('#bmr-result-value').html(data.bmr);
-
- // Activities
- var activities_url = $("#activities-form").attr('action');
- $.post(activities_url,
- $("#activities-form").serialize(),
- function(data) {
- $('#activities-result-container').show();
- $('#activities-result-value').html(data.factor);
-
- // Total calories
- $('#id_base_calories').html(data.activities);
- });
- });
+// noinspection Eslint
+function initCaloriesCalculator() {
+ $('#form-transfer-calories').click(function (e) {
+ var baseCalories;
+ e.preventDefault();
+ baseCalories = Number($('#id_base_calories').html());
+ $('#id_calories').val(baseCalories);
+ });
+
+ $('#add-calories-total').click(function (e) {
+ var additionalCalories;
+ var baseCalories;
+ e.preventDefault();
+ baseCalories = Number($('#id_base_calories').html());
+ additionalCalories = Number($('#id_additional_calories').val());
+ $('#id_calories').val(baseCalories + additionalCalories);
+ });
+
+ $('#form-update-calories').click(function (e) {
+ e.preventDefault();
+
+ // Get own ID and update the user profile
+ $.get('/api/v2/userprofile', function () {
+ }).done(function (userprofile) {
+ var totalCalories = $('#id_calories')[0].value;
+ $.ajax({
+ url: '/api/v2/userprofile/' + userprofile.results[0].id + '/',
+ type: 'PATCH',
+ data: { calories: totalCalories }
+ });
});
+ });
+
+ $('.calories-autoform').click(function (e) {
+ var $bmrForm;
+ var bmrUrl;
+ e.preventDefault();
+
+ // BMR
+ $bmrForm = $('#bmr-form');
+ bmrUrl = $bmrForm.attr('action');
+ $.post(bmrUrl,
+ $bmrForm.serialize(),
+ function (data) {
+ var $activitiesForm;
+ var activitiesUrl;
+ $('#bmr-result-container').show();
+ $('#bmr-result-value').html(data.bmr);
+
+ // Activities
+ $activitiesForm = $('#activities-form');
+ activitiesUrl = $activitiesForm.attr('action');
+ $.post(activitiesUrl,
+ $activitiesForm.serialize(),
+ function (activitiesData) {
+ $('#activities-result-container').show();
+ $('#activities-result-value').html(activitiesData.factor);
+
+ // Total calories
+ $('#id_base_calories').html(activitiesData.activities);
+ });
+ });
+ });
}
diff --git a/wger/nutrition/templates/bmi/form.html b/wger/nutrition/templates/bmi/form.html
index 30e23f945..35fe697f7 100644
--- a/wger/nutrition/templates/bmi/form.html
+++ b/wger/nutrition/templates/bmi/form.html
@@ -26,14 +26,14 @@ div.bmi-legend {
<script>
$(document).ready(function () {
- render_bmi({% if flavour = 'mobile'%}$('#content').width() * 0.95{% endif %});
+ renderBodyMassIndex({% if flavour = 'mobile'%}$('#content').width() * 0.95{% endif %});
/*
* Process the form
*/
$("#bmi-form").click(function(e){
e.preventDefault();
- render_bmi({% if flavour = 'mobile'%}$('#content').width() * 0.95{% endif %});
+ renderBodyMassIndex({% if flavour = 'mobile'%}$('#content').width() * 0.95{% endif %});
});
});
diff --git a/wger/nutrition/templates/ingredient/view.html b/wger/nutrition/templates/ingredient/view.html
index 1e7714190..d20926346 100644
--- a/wger/nutrition/templates/ingredient/view.html
+++ b/wger/nutrition/templates/ingredient/view.html
@@ -6,7 +6,7 @@
{% block header %}
<script>
$(document).ready(function() {
- init_ingredient_detail("{% url 'api-ingredient-get-values' ingredient.id %}");
+ initIngredientDetail("{% url 'api-ingredient-get-values' ingredient.id %}");
});
</script>
{% endblock %}
diff --git a/wger/nutrition/templates/meal_item/edit.html b/wger/nutrition/templates/meal_item/edit.html
index e1decb275..4ae155d55 100644
--- a/wger/nutrition/templates/meal_item/edit.html
+++ b/wger/nutrition/templates/meal_item/edit.html
@@ -11,7 +11,7 @@
<script type="text/javascript">
$(document).ready(function() {
// Init the autocompleter
- init_ingredient_autocompleter();
+ initIngredientAutocompleter();
});
</script>
{% endblock %}
diff --git a/wger/nutrition/templates/mobile/plan/view.html b/wger/nutrition/templates/mobile/plan/view.html
index 0cfc55f88..27bc3b167 100644
--- a/wger/nutrition/templates/mobile/plan/view.html
+++ b/wger/nutrition/templates/mobile/plan/view.html
@@ -26,7 +26,7 @@
function custom_modal_init()
{
// Init the autocompleter after loading the modal dialog
- init_ingredient_autocompleter();
+ initIngredientAutocompleter();
}
$(document).ready(function() {
@@ -381,4 +381,4 @@ $(document).ready(function() {
{% endif %}
</ul>
</div>
-{% endblock %}
\ No newline at end of file
+{% endblock %}
diff --git a/wger/nutrition/templates/plan/view.html b/wger/nutrition/templates/plan/view.html
index 55ee8ff81..93aa39ef3 100644
--- a/wger/nutrition/templates/plan/view.html
+++ b/wger/nutrition/templates/plan/view.html
@@ -27,7 +27,7 @@
function custom_modal_init()
{
// Init the autocompleter after loading the modal dialog
- init_ingredient_autocompleter();
+ initIngredientAutocompleter();
}
</script>
{% endblock %}
@@ -318,4 +318,4 @@ function custom_modal_init()
{% endif %}
</ul>
</div>
-{% endblock %}
\ No newline at end of file
+{% endblock %}
diff --git a/wger/nutrition/templates/rate/form.html b/wger/nutrition/templates/rate/form.html
index 7da8fa230..19b4f2859 100644
--- a/wger/nutrition/templates/rate/form.html
+++ b/wger/nutrition/templates/rate/form.html
@@ -6,7 +6,7 @@
{% block header %}
<script>
$(document).ready(function() {
- init_calories_calculator();
+ initCaloriesCalculator();
});
</script>
{% endblock %}