history.js
79 lines
| 1 | /** |
| 2 | * External dependencies |
| 3 | */ |
| 4 | import { createBrowserHistory } from 'history'; |
| 5 | |
| 6 | /** |
| 7 | * WordPress dependencies |
| 8 | */ |
| 9 | import { buildQueryString } from '@wordpress/url'; |
| 10 | |
| 11 | const history = createBrowserHistory(); |
| 12 | |
| 13 | const originalHistoryPush = history.push; |
| 14 | const originalHistoryReplace = history.replace; |
| 15 | |
| 16 | /** |
| 17 | * Custom push/replace wrappers that accept a plain params object instead of |
| 18 | * a full location descriptor. |
| 19 | * |
| 20 | * Navigation contract: params you don't pass are dropped, except for the |
| 21 | * WordPress-admin routing params in PRESERVED_PARAM_KEYS. Those must survive |
| 22 | * every navigation — otherwise admin.php loses the query args it needs to |
| 23 | * route back to this page on reload (`?page=presto-dashboard&post_type=…`). |
| 24 | * |
| 25 | * Any app-level param the caller wants to keep must be passed explicitly. |
| 26 | */ |
| 27 | const PRESERVED_PARAM_KEYS = [ 'page', 'post_type' ]; |
| 28 | |
| 29 | function mergeParams( incoming ) { |
| 30 | const currentAll = Object.fromEntries( |
| 31 | new URLSearchParams( history.location.search ) |
| 32 | ); |
| 33 | const preserved = {}; |
| 34 | for ( const key of PRESERVED_PARAM_KEYS ) { |
| 35 | if ( currentAll[ key ] !== undefined ) { |
| 36 | preserved[ key ] = currentAll[ key ]; |
| 37 | } |
| 38 | } |
| 39 | const merged = { ...preserved, ...incoming }; |
| 40 | // Remove keys explicitly set to null or undefined (allows param deletion) |
| 41 | Object.keys( merged ).forEach( ( key ) => { |
| 42 | if ( merged[ key ] == null ) { |
| 43 | delete merged[ key ]; |
| 44 | } |
| 45 | } ); |
| 46 | return merged; |
| 47 | } |
| 48 | |
| 49 | function push( params, state ) { |
| 50 | const search = buildQueryString( mergeParams( params ) ); |
| 51 | return originalHistoryPush.call( history, { search }, state ); |
| 52 | } |
| 53 | |
| 54 | function replace( params, state ) { |
| 55 | const search = buildQueryString( mergeParams( params ) ); |
| 56 | return originalHistoryReplace.call( history, { search }, state ); |
| 57 | } |
| 58 | |
| 59 | const locationMemo = new WeakMap(); |
| 60 | function getLocationWithParams() { |
| 61 | const location = history.location; |
| 62 | let locationWithParams = locationMemo.get( location ); |
| 63 | if ( ! locationWithParams ) { |
| 64 | locationWithParams = { |
| 65 | ...location, |
| 66 | params: Object.fromEntries( |
| 67 | new URLSearchParams( location.search ) |
| 68 | ), |
| 69 | }; |
| 70 | locationMemo.set( location, locationWithParams ); |
| 71 | } |
| 72 | return locationWithParams; |
| 73 | } |
| 74 | |
| 75 | history.push = push; |
| 76 | history.replace = replace; |
| 77 | history.getLocationWithParams = getLocationWithParams; |
| 78 | |
| 79 | export default history; |