From d05fbd1a55a6dfa83ce4eef1a3b0c67cb99de940 Mon Sep 17 00:00:00 2001 From: Morgan Aubert Date: Sat, 14 Oct 2023 09:44:04 -0400 Subject: [PATCH] Add initFavoriteButtons helper --- .../templates/blogging/article_detail.html | 8 ++--- .../blogging/ArticleDetailController.js | 2 ++ src/assets/js/core/initFavoriteButtons.js | 35 +++++++++++++++++++ 3 files changed, 41 insertions(+), 4 deletions(-) create mode 100644 src/assets/js/core/initFavoriteButtons.js diff --git a/src/apps/blogging/templates/blogging/article_detail.html b/src/apps/blogging/templates/blogging/article_detail.html index 24a54d4..1fb5404 100644 --- a/src/apps/blogging/templates/blogging/article_detail.html +++ b/src/apps/blogging/templates/blogging/article_detail.html @@ -25,9 +25,9 @@

{{ article.title }}

   {% endif %} - {% if request.user? && request.user.profile == article.author %} @@ -71,9 +71,9 @@

{{ article.title }}

   {% endif %} - {% if request.user? && request.user.profile == article.author %}
diff --git a/src/assets/js/controllers/blogging/ArticleDetailController.js b/src/assets/js/controllers/blogging/ArticleDetailController.js index 56538e3..977f262 100644 --- a/src/assets/js/controllers/blogging/ArticleDetailController.js +++ b/src/assets/js/controllers/blogging/ArticleDetailController.js @@ -1,8 +1,10 @@ +import initFavoriteButtons from '../../core/initFavoriteButtons'; import initFollowButtons from '../../core/initFollowButtons'; export default { async init() { const articlePageDiv = document.getElementById('article_page'); await initFollowButtons(articlePageDiv.dataset.authorUsername); + await initFavoriteButtons(); }, }; diff --git a/src/assets/js/core/initFavoriteButtons.js b/src/assets/js/core/initFavoriteButtons.js new file mode 100644 index 0000000..acbc03f --- /dev/null +++ b/src/assets/js/core/initFavoriteButtons.js @@ -0,0 +1,35 @@ +import axios from 'axios'; + +import getCSRFToken from './getCSRFToken'; + +export default async function initFavoriteButtons() { + const favoriteButtons = document.querySelectorAll('.favorite-button'); + + if (favoriteButtons.length > 0) { + const csrfToken = getCSRFToken(); + favoriteButtons.forEach((favoriteButton) => { + const slug = favoriteButton.dataset.articleSlug; + favoriteButton.addEventListener('click', async () => { + const response = await axios.post( + `/article/${slug}/favorite`, + {}, + { headers: { 'X-CSRF-Token': csrfToken } }, + ); + + favoriteButtons.forEach((b) => { + if (b.dataset.articleSlug === slug) { + b.classList.toggle('btn-outline-primary'); + b.classList.toggle('btn-primary'); + const counter = b.querySelector('.counter'); + + if (response.data.favorited) { + counter.textContent = parseInt(counter.textContent, 10) + 1; + } else { + counter.textContent = parseInt(counter.textContent, 10) - 1; + } + } + }); + }); + }); + } +}