Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable a modal to edit bookmark categories #1799

Merged
merged 3 commits into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions accounts/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@
path('bookmarks/get_form_for_sound/<int:sound_id>/', bookmarks.get_form_for_sound, name="bookmarks-add-form-for-sound"),
path('bookmarks/category/<int:category_id>/delete/', bookmarks.delete_bookmark_category, name="delete-bookmark-category"),
path('bookmarks/<int:bookmark_id>/delete/', bookmarks.delete_bookmark, name="delete-bookmark"),
path('bookmarks/category/<int:category_id>/edit_modal/', bookmarks.edit_bookmark_category, name="edit-bookmark-category"),


path('messages/', messages.inbox, name='messages'),
path('messages/sent/', messages.sent_messages, name='messages-sent'),
Expand Down
8 changes: 8 additions & 0 deletions bookmarks/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,15 @@ class Meta:
widgets = {
'name': forms.TextInput(attrs={'class': 'category_name_widget'}),
}

def clean(self):
cleaned_data = super().clean()
name = self.cleaned_data.get("name", )

if BookmarkCategory.objects.filter(user=self.instance.user, name=name).exists():
raise forms.ValidationError("This name already exists for a bookmark category")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This error message could be improved. Maybe "You have already created a bookmark category with that name"


return cleaned_data

class BookmarkForm(forms.Form):
category = forms.ChoiceField(
Expand Down
29 changes: 28 additions & 1 deletion bookmarks/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from bookmarks.forms import BookmarkForm
from bookmarks.forms import BookmarkForm, BookmarkCategoryForm
from bookmarks.models import Bookmark, BookmarkCategory
from sounds.models import Sound
from utils.pagination import paginate
Expand Down Expand Up @@ -85,6 +85,33 @@ def delete_bookmark_category(request, category_id):
return HttpResponseRedirect(reverse("bookmarks-for-user", args=[request.user.username]))


@transaction.atomic()
def edit_bookmark_category(request, category_id):

if not request.GET.get('ajax'):
return HttpResponseRedirect(reverse("bookmarks-for-user", args=[request.user.username]))

category = get_object_or_404(BookmarkCategory, id=category_id, user=request.user)

if request.method == "POST":
edit_form = BookmarkCategoryForm(request.POST, instance=category)
print(edit_form.is_bound)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😲

if edit_form.is_valid():
category.name = edit_form.cleaned_data["name"]
category.save()
return JsonResponse({"success":True})
if not edit_form.is_valid():
print(edit_form.errors.as_json())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😲 😲
I guess this whole if clause can be removed

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess you're referring to the second if block that just prints the form errors? I probably forgot to erase that since I think it was for debugging purposes. The first if statement I am quite sure it is required in order to update the category name in the database.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, the one for printing only

else:
initial = {"name":category.name}
edit_form = BookmarkCategoryForm(initial=initial)

tvars = {"category": category,
"form": edit_form}
return render(request, 'bookmarks/modal_edit_bookmark_category.html', tvars)



@login_required
@transaction.atomic()
def add_bookmark(request, sound_id):
Expand Down
2 changes: 1 addition & 1 deletion freesound/static/bw-frontend/src/components/loginModals.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ const handleRegistrationModal = () => {
// If registration succeeded, redirect to the registration feedback page
const data = JSON.parse(req.responseText);
window.location.href = data.redirectURL;
}, undefined);
}, undefined, undefined);
}

const handleRegistrationFeedbackModal = () => {
Expand Down
18 changes: 12 additions & 6 deletions freesound/static/bw-frontend/src/components/modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,19 +85,22 @@ const bindConfirmationModalElements = (container) => {

// Logic to bind default modals

const handleDefaultModal = (modalUrl, modalActivationParam, atPage) => {
if ((atPage !== undefined) && modalUrl.indexOf('&page') == -1){
modalUrl += '&page=' + atPage;
}
const handleDefaultModal = (modalUrl, modalActivationParam) => {
handleGenericModal(modalUrl, undefined, undefined, true, true, modalActivationParam);
}

const handleDefaultModalWithForm = (modalUrl, modalActivationParam) => {
handleGenericModalWithForm(modalUrl, undefined, undefined, (req) => {showToast('Form submitted succesfully!')}, undefined, true, true, modalActivationParam, true);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are enabling the reload on success by default, and also not providing a way to disable it unless handleGenericModalWithForm is used directly instead of an automatic binding. You should probably add a parameter to handleDefaultModalWithForm (e.g. reloadOnSuccess) which defaults to false, and then in the bind function, see if the element has a specific dataset property to decide if reloadOnSuccess should be true or false (e.g. data-reload-on-success)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure that I fully understood your suggestion because to my understanding you do not need to check anything in the bind function if the parameter is sent properly in handeDefaultModalWithForm. By now my proposal would be to:

  1. set triggerPageReloadSucces to false in handleGenericModalWithForm
  2. add "element" as a parameter in handeDefaultModalWithForm
  3. send element.reloadOnSuccess to handleGenericModalWithForm or false as a default value if it is not specified.
  4. define a data-reload-on-success="true" parameter in the html definition of the toggle

There are other implemented changes you proposed in another branch (as in messageOnSuccess). Anyway, the result seems to work fine and would allow not to reload the page by default (only when specified in the element). Did I understand it correctly?

image

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, it might be a good idea to simply pass element (also when binding), you can do it like that

}

const bindDefaultModals = (container) => {
bindModalActivationElements('[data-toggle="modal-default"]', handleDefaultModal, container);
bindModalActivationElements('[data-toggle="modal-default-with-form"]', handleDefaultModalWithForm, container);
}

const activateDefaultModalsIfParameters = () => {
activateModalsIfParameters('[data-toggle="modal-default"]', handleDefaultModal);
activateModalsIfParameters('[data-toggle="modal-default-with-form"]', handleDefaultModalWithForm);
}


Expand Down Expand Up @@ -195,7 +198,7 @@ const handleGenericModal = (fetchContentUrl, onLoadedCallback, onClosedCallback,
};


const handleGenericModalWithForm = (fetchContentUrl, onLoadedCallback, onClosedCallback, onFormSubmissionSucceeded, onFormSubmissionError, doRequestAsync, showLoadingToast, modalActivationParam) => {
const handleGenericModalWithForm = (fetchContentUrl, onLoadedCallback, onClosedCallback, onFormSubmissionSucceeded, onFormSubmissionError, doRequestAsync, showLoadingToast, modalActivationParam, dataReloadOnSuccess) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dataReloadOnSuccess should probably be called triggerPageReloadOnSuccess for making it fully self-explainable

// This version of the generic modal is useful for modal contents that contain forms which, upon submission, will return HTML content if there were form errors
// which should be used to replace the current contents of the form, and will return a JSON response if the form validated correctly in the backend. That JSON
// response could include some relevant data or no data at all, but is used to differentiate from the HTML response
Expand All @@ -218,6 +221,9 @@ const handleGenericModalWithForm = (fetchContentUrl, onLoadedCallback, onClosedC
if (onFormSubmissionSucceeded !== undefined){
onFormSubmissionSucceeded(req);
}
if(dataReloadOnSuccess == true){
location.reload()
}
} else {
// If the response is not JSON, that means the response are the HTML elements of the
// form (including error warnings) and we should replace current modal HTML with this one
Expand Down Expand Up @@ -278,4 +284,4 @@ const handleGenericModalWithForm = (fetchContentUrl, onLoadedCallback, onClosedC
}, onClosedCallback, doRequestAsync, showLoadingToast, modalActivationParam)
}

export {activateModal, dismissModal, handleGenericModal, handleGenericModalWithForm, handleDefaultModal, bindModalActivationElements, bindConfirmationModalElements, activateModalsIfParameters, bindDefaultModals, activateDefaultModalsIfParameters};
export {activateModal, dismissModal, handleGenericModal, handleGenericModalWithForm, handleDefaultModal, handleDefaultModalWithForm, bindModalActivationElements, bindConfirmationModalElements, activateModalsIfParameters, bindDefaultModals, activateDefaultModalsIfParameters};
2 changes: 1 addition & 1 deletion freesound/static/bw-frontend/src/pages/sound.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ const initSoundFlagForm = (modalContainer) => {
}

const handleFlagSoundModal = () => {
handleGenericModalWithForm(flagSoundButton.dataset.modalContentUrl, initSoundFlagForm, undefined, (req) => {showToast('Sound flagged successfully!')}, undefined);
handleGenericModalWithForm(flagSoundButton.dataset.modalContentUrl, initSoundFlagForm, undefined, (req) => {showToast('Sound flagged successfully!')}, undefined, undefined);
}

if (flagSoundModalParamValue) {
Expand Down
3 changes: 2 additions & 1 deletion templates/bookmarks/bookmarks.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ <h4>Bookmark categories</h4>
<li><a href="{% url "bookmarks-for-user-for-category" user.username cat.id %}" {% if category.id == cat.id %}style="font-weight:bold"{% endif %} aria-label="Category: {{cat.name}}">{{cat.name}}</a> <span class="text-grey"> · {{cat.num_bookmarks|bw_intcomma}} bookmark{{ cat.num_bookmarks|pluralize }}</span>
{% if is_owner %}
<a class="cursor-pointer h-spacing-left-1" data-toggle="confirmation-modal" data-modal-confirmation-title="Are you sure you want to remove this bookmark category?" data-modal-confirmation-help-text="Note that all the bookmarks inside this category will also be removed" data-modal-confirmation-url="{% url "delete-bookmark-category" cat.id %}{% if cat.id != category.id %}?next={{request.path}}&page={{current_page}}{% endif %}" title="Remove bookmark category" aria-label="Remove bookmark category">{% bw_icon 'trash' %}</a>
<a class="cursor-pointer h-spacing-left-1" data-toggle="modal-default-with-form" data-modal-content-url="{% url 'edit-bookmark-category' cat.id %}?ajax=1" title="Edit bookmark category" aria-label="Edit bookmark category">{% bw_icon 'edit' %}</a>
{% endif %}</li>
{% endfor %}
</ul>
Expand All @@ -39,7 +40,7 @@ <h4><span class="text-light-grey">Category:</span> {% if category %}{{category.n
<div class="col-6 col-md-4">
{% display_sound_small bookmark.sound %}
{% if is_owner %}
<div class="right v-spacing-4 v-spacing-top-negative-2"><a class="cursor-pointer bw-link--grey" data-toggle="confirmation-modal" data-modal-confirmation-title="Are you sure you want to remove this bookmark from '{{bookmark.category_name_or_uncategorized}}'?" data-modal-confirmation-url="{% url "delete-bookmark" bookmark.id %}?next={{request.path}}&page={{current_page}}" title="Remove from bookmarks" aria-label="Remove from bookmarks">{% bw_icon 'trash' %} Remove bookmark</a></div>
<div class="right v-spacing-4 v-spacing-top-negative-2"><a class="cursor-pointer bw-link--grey" data-toggle="confirmation-modal" data-modal-confirmation-title="Are you sure you want to remove this bookmark from '{{bookmark.category_name_or_uncategorized}}'?" data-modal-confirmation-url="{% url "delete-bookmark" bookmark.id %}?next={{request.path}}&page={{current_page}}" title="Remove from bookmarks" aria-label="Remove from bookmarks">{% bw_icon 'trash' %} Remove bookmark</a></div>
{% endif %}
</div>
{% endfor %}
Expand Down
21 changes: 21 additions & 0 deletions templates/bookmarks/modal_edit_bookmark_category.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{% extends "molecules/modal_base.html" %}
{% load util %}

{% block id %}editBookMarkCategory{% endblock %}
{% block extra-class %}{% endblock %}
{% block aria-label %}Edit Bookmark Category{% endblock %}

{% block body %}
<div class="col-12">
<div class="text-center">
<h4 class="v-spacing-5">Edit bookmark Category</h4>
<form method="post" action="{% url 'edit-bookmark-category' category.id %}?ajax=1." class = "disable-on-submit">{% csrf_token %}
{{form}}
<button class="btn-primary v-spacing-top-3">Change bookmark category name</button>
</form>
</div>
<div class="v-spacing-4">

</div>
</div>
{% endblock %}
Loading