Skip to content

Commit

Permalink
History: simplify the push and replace methods (#60112)
Browse files Browse the repository at this point in the history
Co-authored-by: jsnajdr <[email protected]>
Co-authored-by: tyxla <[email protected]>
  • Loading branch information
3 people authored Mar 27, 2024
1 parent 6f9b290 commit d9d8564
Showing 1 changed file with 10 additions and 15 deletions.
25 changes: 10 additions & 15 deletions packages/router/src/history.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,26 @@ import { createBrowserHistory } from 'history';
/**
* WordPress dependencies
*/
import { addQueryArgs, getQueryArgs, removeQueryArgs } from '@wordpress/url';
import { buildQueryString } from '@wordpress/url';

const history = createBrowserHistory();

const originalHistoryPush = history.push;
const originalHistoryReplace = history.replace;

function buildSearch( params ) {
const queryString = buildQueryString( params );
return queryString.length > 0 ? '?' + queryString : queryString;
}

function push( params, state ) {
const currentArgs = getQueryArgs( window.location.href );
const currentUrlWithoutArgs = removeQueryArgs(
window.location.href,
...Object.keys( currentArgs )
);
const newUrl = addQueryArgs( currentUrlWithoutArgs, params );
return originalHistoryPush.call( history, newUrl, state );
const search = buildSearch( params );
return originalHistoryPush.call( history, { search }, state );
}

function replace( params, state ) {
const currentArgs = getQueryArgs( window.location.href );
const currentUrlWithoutArgs = removeQueryArgs(
window.location.href,
...Object.keys( currentArgs )
);
const newUrl = addQueryArgs( currentUrlWithoutArgs, params );
return originalHistoryReplace.call( history, newUrl, state );
const search = buildSearch( params );
return originalHistoryReplace.call( history, { search }, state );
}

history.push = push;
Expand Down

0 comments on commit d9d8564

Please sign in to comment.