From 589119c9ee9e3a21c7babd2c6a9cafe977e63c6f Mon Sep 17 00:00:00 2001 From: Sli Date: Sat, 10 Aug 2024 23:32:50 +0200 Subject: [PATCH] Improve update_query_string with enum action --- core/static/core/js/script.js | 21 ++++++++++++++++++--- sas/templates/sas/album.jinja | 6 +++--- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/core/static/core/js/script.js b/core/static/core/js/script.js index 390deeb2..13613740 100644 --- a/core/static/core/js/script.js +++ b/core/static/core/js/script.js @@ -69,20 +69,35 @@ function getCSRFToken() { const initialUrlParams = new URLSearchParams(window.location.search); -function update_query_string(key, value, push = true) { +/** + * @readonly + * @enum {number} + */ +const History = { + PUSH: 1, + REPLACE: 2, +}; + +/** + * @param {string} key + * @param {string | string[] | null} value + * @param {History} action + */ +function update_query_string(key, value, action = History.REPLACE) { const url = new URL(window.location.href); if (!value) { // If the value is null, undefined or empty => delete it url.searchParams.delete(key) } else if (Array.isArray(value)) { - url.searchParams.delete(key) value.forEach((v) => url.searchParams.append(key, v)) } else { url.searchParams.set(key, value); } - if (push){ + if (action === History.PUSH) { history.pushState(null, document.title, url.toString()); + } else if (action === History.REPLACE) { + history.replaceState(null, document.title, url.toString()); } } diff --git a/sas/templates/sas/album.jinja b/sas/templates/sas/album.jinja index e9363f6f..05a1eab0 100644 --- a/sas/templates/sas/album.jinja +++ b/sas/templates/sas/album.jinja @@ -129,7 +129,7 @@ Alpine.data("pictures", () => ({ pictures: {}, page: parseInt(initialUrlParams.get("page")) || 1, - pushstate: true, /* Used to avoid pushing a state on a back action */ + pushstate: History.PUSH, /* Used to avoid pushing a state on a back action */ loading: false, async init() { @@ -139,12 +139,12 @@ this.page === 1 ? null : this.page, this.pushstate ); - this.pushstate = true; + this.pushstate = History.PUSH; this.fetch_pictures(); }); window.addEventListener("popstate", () => { - this.pushstate = false; + this.pushstate = History.REPLACE; this.page = parseInt( new URLSearchParams(window.location.search).get("page") ) || 1;