Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Remove unused js code

Roland Geider4e1f54cec319
diff --git a/wger/core/static/js/wger-core.js b/wger/core/static/js/wger-core.js
index 877f01d70..d6daf501a 100644
--- a/wger/core/static/js/wger-core.js
+++ b/wger/core/static/js/wger-core.js
@@ -15,44 +15,6 @@
*/
'use strict';
-/*
- AJAX related functions
-
- See https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax for
- more information
- */
-function getCookie(name) {
- var cookie;
- var cookies;
- var cookieValue = null;
- var loopCounter;
- if (document.cookie && document.cookie !== '') {
- cookies = document.cookie.split(';');
- for (loopCounter = 0; loopCounter < cookies.length; loopCounter++) {
- cookie = jQuery.trim(cookies[loopCounter]);
- // Does this cookie string begin with the name we want?
- if (cookie.substring(0, name.length + 1) === (name + '=')) {
- cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
- break;
- }
- }
- }
- return cookieValue;
-}
-
-function csrfSafeMethod(method) {
- // These HTTP methods do not require CSRF protection
- return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
-}
-
-$.ajaxSetup({
- crossDomain: false, // obviates need for sameOrigin test
- beforeSend: function (xhr, settings) {
- if (!csrfSafeMethod(settings.type)) {
- xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
- }
- }
-});
function getCurrentLanguage() {
// Returns a short name, like 'en' or 'de'
@@ -60,154 +22,6 @@ function getCurrentLanguage() {
}
-/*
- Open a modal dialog for form editing
- */
-function modalDialogFormEdit() {
- var $submit;
- var $form;
- $form = $('#ajax-info-content').find('form');
- $submit = $($form).find('#form-save');
-
- $submit.click(function (e) {
- var formData;
- var formAction;
- e.preventDefault();
- formAction = $form.attr('action');
- formData = $form.serialize();
-
- // Unbind all click elements, so the form doesn't get submitted twice
- // if the user clicks 2 times on the button (while there is already a request
- // happening in the background)
- $submit.off();
-
- // Show a loader while we fetch the real page
- $form.html('<div style="text-align:center;">' +
- '<img src="/static/images/loader.svg" ' +
- 'width="48" ' +
- 'height="48"> ' +
- '</div>');
- $('#ajax-info-title').html('Processing'); // TODO: translate this
-
- // OK, we did the POST, what do we do with the result?
- $.ajax({
- type: 'POST',
- url: formAction,
- data: formData,
- beforeSend: function (jqXHR) {
- // Send a custom header so django's messages are not displayed in the next
- // request which will be not be displayed to the user, but on the next one
- // that will
- jqXHR.setRequestHeader('X-wger-no-messages', '1');
- },
- success: function (data, textStatus, jqXHR) {
- var url = jqXHR.getResponseHeader('X-wger-redirect');
- if (url) {
- window.location.href = url;
- /*
- if(document.URL.indexOf(url)) {
- history.pushState({}, "", url);
- }
- */
- } else if ($(data).find('form .has-error').length > 0) {
- // we must do the same with the new form as before, binding the click-event,
- // checking for errors etc, so it calls itself here again.
- $form.html($(data).find('form').html());
- $('#ajax-info-title').html($(data).find('#page-title').html());
- modalDialogFormEdit();
- } else {
- console.log('No X-wger-redirect found but also no .has-error!');
- $('#wger-ajax-info').modal('hide');
- $form.html(data);
- }
-
- // Call other custom initialisation functions
- // (e.g. if the form as an autocompleter, it has to be initialised again)
- if (typeof wgerCustomModalInit !== 'undefined') {
- wgerCustomModalInit(); // eslint-disable-line no-undef
- }
-
- if (typeof wgerCustomPageInit !== 'undefined') {
- wgerCustomPageInit(); // eslint-disable-line no-undef
- }
- },
- error: function (jqXHR) {
- // console.log(errorThrown); // INTERNAL SERVER ERROR
- $('#ajax-info-content').html(jqXHR.responseText);
- }
- });
- });
-}
-
-function wgerFormModalDialog() {
- var $wgerModalDialog;
- $wgerModalDialog = $('.wger-modal-dialog');
- // Unbind all other click events so we don't do this more than once
- $wgerModalDialog.off();
-
- // Load the edit dialog when the user clicks on an edit link
- $wgerModalDialog.click(function (e) {
- var $ajaxInfoContent;
- var targetUrl;
- e.preventDefault();
- targetUrl = $(this).attr('href');
-
- // It's not possible to have more than one modal open at any time, so close them
- $('.modal').modal('hide');
-
- // Show a loader while we fetch the real page
- $ajaxInfoContent = $('#ajax-info-content');
- $ajaxInfoContent.html('<div style="text-align:center;">' +
- '<img src="/static/images/loader.svg" ' +
- 'width="48" ' +
- 'height="48"> ' +
- '</div>');
- $('#ajax-info-title').html('Loading...');
- $('#wger-ajax-info').modal('show');
-
- $ajaxInfoContent.load(targetUrl + ' .wger-form',
- function (responseText, textStatus, XMLHttpRequest) {
- var $ajaxInfoTitle;
- var modalTitle;
- $ajaxInfoTitle = $('#ajax-info-title');
- if (textStatus === 'error') {
- $ajaxInfoTitle.html('Sorry but an error occured');
- $('#ajax-info-content').html(XMLHttpRequest.status + ' ' + XMLHttpRequest.statusText);
- }
-
- // Call other custom initialisation functions
- // (e.g. if the form as an autocompleter, it has to be initialised again)
- if (typeof wgerCustomModalInit !== 'undefined') {
- // Function is defined in templates. Eslint doesn't check the templates resulting in a
- // un-def error message.
- wgerCustomModalInit(); // eslint-disable-line no-undef
- }
-
- // Set the new title
- modalTitle = '';
- if ($(responseText).find('#page-title').length > 0) {
- // Complete HTML page
- modalTitle = $(responseText).find('#page-title').html();
- } else {
- // Page fragment
- modalTitle = $(responseText).filter('#page-title').html();
- }
- $ajaxInfoTitle.html(modalTitle);
-
- // If there is a form in the modal dialog (there usually is) prevent the submit
- // button from submitting it and do it here with an AJAX request. If there
- // are errors (there is an element with the class 'ym-error' in the result)
- // reload the content back into the dialog so the user can correct the entries.
- // If there isn't assume all was saved correctly and load that result into the
- // page's main DIV (#main-content). All this must be done like this because there
- // doesn't seem to be any reliable and easy way to detect redirects with AJAX.
- if ($(responseText).find('.wger-form').length > 0) {
- modalDialogFormEdit();
- }
- });
- });
-}
-
/*
Returns a random hex string. This is useful, e.g. to add a unique ID to generated
HTML elements
@@ -223,8 +37,8 @@ function getRandomHex() {
Template-like function that adds form elements to the ajax exercise selection in the edit set page
*/
function addExercise(exercise) {
- var $exerciseSearchLog;
- var resultDiv;
+ let $exerciseSearchLog;
+ let resultDiv;
resultDiv = '<div id="DIV-ID" class="ajax-exercise-select">\n' +
' <a href="#" ' +
'data-role="button" ' +
@@ -248,15 +62,15 @@ function addExercise(exercise) {
}
function getExerciseFormset(baseId) {
- var formsetUrl;
- var setValue;
+ let formsetUrl;
+ let setValue;
setValue = $('#id_sets').val();
if (setValue && parseInt(setValue, 10) && baseId && parseInt(baseId, 10)) {
formsetUrl = '/' + getCurrentLanguage() +
'/routine/set/get-formset/' + baseId + '/' + setValue;
$.get(formsetUrl, function (data) {
- var $formsets;
+ let $formsets;
$formsets = $('#formsets');
$formsets.append(data);
$('#exercise-search-log').scrollTop(0);
@@ -269,13 +83,13 @@ function getExerciseFormset(baseId) {
Updates all exercise formsets, e.g. when the number of sets changed
*/
function updateAllExerciseFormset() {
- var setValue;
+ let setValue;
setValue = $('#id_sets').val();
if (setValue && parseInt(setValue, 10)) {
$.each($('#exercise-search-log').find('input'), function (index, value) {
- var promise;
- var exerciseId;
- var formsetUrl;
+ let promise;
+ let exerciseId;
+ let formsetUrl;
exerciseId = value.value;
promise = $().promise();
if (exerciseId && parseInt(exerciseId, 10)) {
@@ -284,7 +98,7 @@ function updateAllExerciseFormset() {
'get-formset/' + exerciseId + '/' + setValue;
promise.done(function () {
promise = $.get(formsetUrl, function (data) {
- var $formsets;
+ let $formsets;
$('#formset-base-' + exerciseId).remove();
$formsets = $('#formsets');
$formsets.append(data);
@@ -303,7 +117,7 @@ function updateAllExerciseFormset() {
*/
function initRemoveExerciseFormset() {
$('.ajax-exercise-select a').click(function (e) {
- var baseId;
+ let baseId;
e.preventDefault();
baseId = $(this).parent('div').find('input').val();
$('#formset-base-' + baseId).remove();
@@ -352,9 +166,9 @@ function wgerInitEditSet() {
// Mobile select box
$('#id_exercise_list').change(function () {
- var $idExerciseList;
- var baseId;
- var exerciseName;
+ let $idExerciseList;
+ let baseId;
+ let exerciseName;
$idExerciseList = $('#id_exercise_list');
baseId = $idExerciseList.val();
exerciseName = $idExerciseList.find(':selected').text();
@@ -385,10 +199,10 @@ function wgerInitEditSet() {
$('#id_categories_list').on('change', function () {
// Remember to filter by exercise language
$.get('/api/v2/language/?short_name=' + getCurrentLanguage(), function (data) {
- var filter;
- var baseUrl;
- var categoryPk;
- var languagePk;
+ let filter;
+ let baseUrl;
+ let categoryPk;
+ let languagePk;
languagePk = data.results[0].id;
categoryPk = $('#id_categories_list').val();
baseUrl = '/api/v2/exercise/';
@@ -401,7 +215,7 @@ function wgerInitEditSet() {
$.get(baseUrl + filter, function (exerciseData) {
// Sort the results by name, at the moment it's not possible
// to search and sort the API at the same time
- var $idExerciseList;
+ let $idExerciseList;
exerciseData.results.sort(function (a, b) {
if (a.name < b.name) {
return -1;
@@ -428,28 +242,6 @@ function wgerInitEditSet() {
});
}
-/*
- Helper function to load the target of a link into the main-content DIV (the main left colum)
- */
-function wgerLoadMaincontent() {
- $('.load-maincontent').click(function (e) {
- var targetUrl;
- e.preventDefault();
- targetUrl = $(this).attr('href');
-
- $.get(targetUrl, function (data) {
- var currentUrl;
- // Load the data
- $('#main-content').html($(data).find('#main-content').html());
-
- // Update the browser's history
- currentUrl = $(data).find('#current-url').data('currentUrl');
- history.pushState({}, '', currentUrl);
-
- wgerLoadMaincontent();
- });
- });
-}
/*
Helper function used in the workout log dialog to fetch existing workout sessions through the
@@ -457,7 +249,7 @@ function wgerLoadMaincontent() {
*/
function wgerGetWorkoutSession() {
$('#id_date').on('change', function () {
- var date = $('#id_date').val();
+ let date = $('#id_date').val();
if (date) {
$.get('/api/v2/workoutsession/?date=' + date, function (data) {
if (data.results.length === 1) {
@@ -479,14 +271,14 @@ function wgerGetWorkoutSession() {
$(document).ready(function () {
// Handle the workout PDF download options for workouts
$('#download-pdf-button').click(function (e) {
- var targetUrl;
- var token;
- var uid;
- var workoutId;
- var downloadComments;
- var downloadImages;
- var downloadType;
- var downloadInfo;
+ let targetUrl;
+ let token;
+ let uid;
+ let workoutId;
+ let downloadComments;
+ let downloadImages;
+ let downloadType;
+ let downloadInfo;
e.preventDefault();
downloadInfo = $('#pdf-download-info');
@@ -511,14 +303,14 @@ $(document).ready(function () {
// Handle the workout PDF download options for schedules
$('#download-pdf-button-schedule').click(function (e) {
- var targetUrl;
- var token;
- var uid;
- var scheduleId;
- var downloadComments;
- var downloadImages;
- var downloadType;
- var downloadInfo;
+ let targetUrl;
+ let token;
+ let uid;
+ let scheduleId;
+ let downloadComments;
+ let downloadImages;
+ let downloadType;
+ let downloadInfo;
e.preventDefault();
downloadInfo = $('#pdf-download-info');
diff --git a/wger/core/templates/form_content.html b/wger/core/templates/form_content.html
new file mode 100644
index 000000000..195a85b24
--- /dev/null
+++ b/wger/core/templates/form_content.html
@@ -0,0 +1,29 @@
+{% extends 'base.html' %}
+{% load i18n static crispy_forms_tags %}
+
+{% block header %}
+ {{ form.media }}
+ {% if custom_js %}
+ <script type="text/javascript">
+ $(document).ready(function () {
+ {{ custom_js|safe }}
+ });
+ </script>
+ {% endif %}
+{% endblock %}
+
+{% block title %}{{ title }}{% endblock %}
+
+{% block content %}
+ {% if form %}
+ {% crispy form %}
+ {% else %}
+ Looks like you clicked on an invalid link. Please try again.
+ {% endif %}
+{% endblock %}
+
+
+<!--
+ Sidebar
+-->
+{% block sidebar %}{% if sidebar %}{% include sidebar %}{% endif %}{% endblock %}
diff --git a/wger/core/templates/navigation.html b/wger/core/templates/navigation.html
index 14eefac3a..a8a9eaa6e 100644
--- a/wger/core/templates/navigation.html
+++ b/wger/core/templates/navigation.html
@@ -175,7 +175,8 @@
</a>
</li>
<li>
- <a class="dropdown-item" href="{% url 'nutrition:ingredient:list' %}">
+ <a class="dropdown-item"
+ href="{% url 'nutrition:ingredient:list' %}">
{% translate "Ingredient overview" %}
</a>
</li>
@@ -183,7 +184,8 @@
<li class="dropdown-divider"></li>
<li class="dropdown-header">{% translate "Administration" %}</li>
<li>
- <a class="dropdown-item" href="{% url 'nutrition:weight_unit:list' %}">
+ <a class="dropdown-item"
+ href="{% url 'nutrition:weight_unit:list' %}">
{% translate "Ingredient weight units" %}
</a>
</li>
@@ -211,11 +213,8 @@
</a>
</li>
<li>
- <a class="dropdown-item"
- href="{% url 'weight:add' %}"
- rel="nofollow">
- {% translate "Add weight entry" %}
- </a>
+ {% translate 'Add weight entry' as text %}
+ {% modal_link url='weight:add' text=text css_class='dropdown-item' %}
</li>
</ul>
</li>
diff --git a/wger/core/templates/template.html b/wger/core/templates/template.html
index 1bca5d834..cbba76db8 100644
--- a/wger/core/templates/template.html
+++ b/wger/core/templates/template.html
@@ -89,12 +89,6 @@
if (typeof wgerCustomPageInit !== "undefined") {
wgerCustomPageInit();
}
-
- // Init the modal dialog for editing forms
- wgerFormModalDialog();
-
- // Initialise the hook to reload the main-content
- wgerLoadMaincontent();
});
</script>
diff --git a/wger/core/views/user.py b/wger/core/views/user.py
index dda9f59f9..143b08167 100644
--- a/wger/core/views/user.py
+++ b/wger/core/views/user.py
@@ -104,7 +104,6 @@ from wger.utils.generic_views import (
from wger.utils.language import load_language
from wger.weight.models import WeightEntry
-
logger = logging.getLogger(__name__)
@@ -297,7 +296,7 @@ def registration(request):
template_data['form'] = form
template_data['title'] = _('Register')
- return render(request, 'form.html', template_data)
+ return render(request, 'form_content.html', template_data)
@login_required
@@ -549,8 +548,8 @@ class UserDetailView(LoginRequiredMixin, WgerMultiplePermissionRequiredMixin, De
)
context['workouts'] = out
context['weight_entries'] = WeightEntry.objects.filter(user=self.object).order_by('-date')[
- :5
- ]
+ :5
+ ]
context['nutrition_plans'] = NutritionPlan.objects.filter(user=self.object).order_by(
'-creation_date'
)[:5]
@@ -606,7 +605,7 @@ class UserListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):
class WgerPasswordChangeView(PasswordChangeView):
- template_name = 'form.html'
+ template_name = 'form_content.html'
success_url = reverse_lazy('core:user:preferences')
title = gettext_lazy('Change password')
@@ -627,7 +626,7 @@ class WgerPasswordChangeView(PasswordChangeView):
class WgerPasswordResetView(PasswordResetView):
- template_name = 'form.html'
+ template_name = 'form_content.html'
email_template_name = 'registration/password_reset_email.html'
success_url = reverse_lazy('core:user:password_reset_done')
from_email = settings.WGER_SETTINGS['EMAIL_FROM']
@@ -641,7 +640,7 @@ class WgerPasswordResetView(PasswordResetView):
class WgerPasswordResetConfirmView(PasswordResetConfirmView):
- template_name = 'form.html'
+ template_name = 'form_content.html'
success_url = reverse_lazy('core:user:login')
def get_form(self, form_class=None):
diff --git a/wger/manager/templates/schedule/view.html b/wger/manager/templates/schedule/view.html
index 9cfe22609..27c89d78b 100644
--- a/wger/manager/templates/schedule/view.html
+++ b/wger/manager/templates/schedule/view.html
@@ -48,7 +48,6 @@
$.get(current_url, function (data) {
$('#schedule-table').html($(data).find('#schedule-table').html());
init_sortable();
- wgerFormModalDialog();
});
}
});
diff --git a/wger/manager/templates/set/add.html b/wger/manager/templates/set/add.html
index 4b2ae04e1..75073a26f 100644
--- a/wger/manager/templates/set/add.html
+++ b/wger/manager/templates/set/add.html
@@ -1,4 +1,4 @@
-{% extends extend_template %}
+{% extends 'base_empty.html' %}
{% load i18n static crispy_forms_tags %}
diff --git a/wger/manager/views/day.py b/wger/manager/views/day.py
index 56d8cd71a..ad56fb8ba 100644
--- a/wger/manager/views/day.py
+++ b/wger/manager/views/day.py
@@ -41,7 +41,6 @@ from wger.manager.models import (
)
from wger.utils.generic_views import WgerFormMixin
-
logger = logging.getLogger(__name__)
@@ -105,6 +104,7 @@ class DayCreateView(DayView, CreateView):
title = gettext_lazy('Add workout day')
owner_object = {'pk': 'workout_pk', 'class': Workout}
+ template_name = 'form_content.html'
def form_valid(self, form):
"""
diff --git a/wger/nutrition/tests/test_ingredient.py b/wger/nutrition/tests/test_ingredient.py
index 240c68b7d..aab26eb2e 100644
--- a/wger/nutrition/tests/test_ingredient.py
+++ b/wger/nutrition/tests/test_ingredient.py
@@ -249,8 +249,7 @@ class IngredientSearchTestCase(WgerTestCase):
Helper function
"""
- kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
- response = self.client.get(reverse('ingredient-search'), {'term': 'test'}, **kwargs)
+ response = self.client.get(reverse('ingredient-search'), {'term': 'test'})
self.assertEqual(response.status_code, 200)
result = json.loads(response.content.decode('utf8'))
self.assertEqual(len(result['suggestions']), 2)
diff --git a/wger/utils/context_processor.py b/wger/utils/context_processor.py
index 81cb46aff..737f20929 100644
--- a/wger/utils/context_processor.py
+++ b/wger/utils/context_processor.py
@@ -30,7 +30,6 @@ def processor(request):
full_path = request.get_full_path()
i18n_path = {}
static_path = static('images/logos/logo-social.png')
- is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
for lang in settings.AVAILABLE_LANGUAGES:
i18n_path[lang[0]] = '/{0}/{1}'.format(lang[0], '/'.join(full_path.split('/')[2:]))
@@ -72,9 +71,6 @@ def processor(request):
# current gym, if available
'custom_header': get_custom_header(request),
-
- # Template to extend in forms, kinda ugly but will be removed in the future
- 'extend_template': 'base_empty.html' if is_ajax else 'base.html',
}
# yapf: enable