From ec1d41261a805baba172ad9d538cc2a5ccd6ff25 Mon Sep 17 00:00:00 2001 From: Philipp Stracker Date: Fri, 13 Dec 2024 12:31:20 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20own=20integration=20of=20the?= =?UTF-8?q?=20=E2=80=9Cnavigation=E2=80=9D=20module?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../resources/js/utils/navigation.js | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 modules/ppcp-settings/resources/js/utils/navigation.js diff --git a/modules/ppcp-settings/resources/js/utils/navigation.js b/modules/ppcp-settings/resources/js/utils/navigation.js new file mode 100644 index 000000000..f2106bc1d --- /dev/null +++ b/modules/ppcp-settings/resources/js/utils/navigation.js @@ -0,0 +1,39 @@ +import { addQueryArgs } from '@wordpress/url'; + +const getLocation = () => window.location; + +const pushHistory = ( path ) => window.history.pushState( { path }, '', path ); + +/** + * Get the current path from the browser. + * + * @return {string} Current path. + */ +export const getPath = () => getLocation().pathname; + +/** + * Get the current query string, parsed into an object, from history. + * + * @return {Object} Current query object, defaults to empty object. + */ +export const getQuery = () => + Object.fromEntries( new URLSearchParams( getLocation().search ) ); + +/** + * Updates the query parameters of the current page. + * + * @param {Object} query Object of params to be updated. + * @throws {TypeError} If the query is not an object. + */ +export const updateQueryString = ( query ) => + pushHistory( getNewPath( query ) ); + +/** + * Return a URL with set query parameters. + * + * @param {Object} query Object of params to be updated. + * @param {string} basePath Optional. Define the path for the new URL. + * @return {string} Updated URL merging query params into existing params. + */ +export const getNewPath = ( query, basePath = getPath() ) => + addQueryArgs( basePath, { ...getQuery(), ...query } );