From b35e1a476edace0a164436bcabced478a2d569c3 Mon Sep 17 00:00:00 2001 From: Sli Date: Sat, 10 Aug 2024 18:38:04 +0200 Subject: [PATCH] Fix back function in album pagination --- core/static/core/js/script.js | 7 +++++-- sas/templates/sas/album.jinja | 18 +++++++++++++++--- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/core/static/core/js/script.js b/core/static/core/js/script.js index f2c365ff..390deeb2 100644 --- a/core/static/core/js/script.js +++ b/core/static/core/js/script.js @@ -69,7 +69,7 @@ function getCSRFToken() { const initialUrlParams = new URLSearchParams(window.location.search); -function update_query_string(key, value) { +function update_query_string(key, value, push = true) { const url = new URL(window.location.href); if (!value) { // If the value is null, undefined or empty => delete it @@ -81,5 +81,8 @@ function update_query_string(key, value) { } else { url.searchParams.set(key, value); } - history.pushState(null, document.title, url.toString()); + + if (push){ + history.pushState(null, document.title, url.toString()); + } } diff --git a/sas/templates/sas/album.jinja b/sas/templates/sas/album.jinja index fed66e66..e9363f6f 100644 --- a/sas/templates/sas/album.jinja +++ b/sas/templates/sas/album.jinja @@ -129,13 +129,25 @@ Alpine.data("pictures", () => ({ pictures: {}, page: parseInt(initialUrlParams.get("page")) || 1, + pushstate: true, /* Used to avoid pushing a state on a back action */ loading: false, async init() { await this.fetch_pictures(); this.$watch("page", () => { - update_query_string("page", this.page === 1 ? null : this.page); - this.fetch_pictures() + update_query_string("page", + this.page === 1 ? null : this.page, + this.pushstate + ); + this.pushstate = true; + this.fetch_pictures(); + }); + + window.addEventListener("popstate", () => { + this.pushstate = false; + this.page = parseInt( + new URLSearchParams(window.location.search).get("page") + ) || 1; }); }, @@ -146,7 +158,7 @@ +`&page=${this.page}` +"&page_size={{ settings.SITH_SAS_IMAGES_PER_PAGE }}"; this.pictures = await (await fetch(url)).json(); - this.loading=false; + this.loading = false; }, nb_pages() {