|
1 | 1 | export const EVENT_HISTORY_STATE_CHANGED = 'history-state-changed'; |
2 | | - |
| 2 | +export const QUERY_FRAGMENT = '_kap_fragment'; |
| 3 | +export const QUERY_BASEPATH = '_kap_basepath'; |
3 | 4 |
|
4 | 5 | function getBasePathForFrame(frame: Element) { |
5 | 6 | const basePath = frame.getAttribute('data-base-path'); |
@@ -69,9 +70,8 @@ export function replaceStateOnWindow(win: Window, path: string) { |
69 | 70 | try { |
70 | 71 | const currentPath = getFullPath(win); |
71 | 72 | if (!isSamePath(currentPath, path)) { |
72 | | - console.log('Replacing state on window: %s > %s', currentPath, path); |
73 | 73 | // Only replace if the path has changed |
74 | | - win.history.replaceState({}, '', path); |
| 74 | + win.history.replaceState({}, '', normalizePath(path)); |
75 | 75 | win.dispatchEvent(new CustomEvent(EVENT_HISTORY_STATE_CHANGED)); |
76 | 76 | } |
77 | 77 | } catch (e) { |
@@ -128,10 +128,26 @@ function syncLocationToChildFrames() { |
128 | 128 | */ |
129 | 129 |
|
130 | 130 | function normalizePath(path: string) { |
131 | | - if (path.endsWith('/')) { |
132 | | - return path.substring(0, path.length - 1); |
| 131 | + let [pathname, searchpart] = path.split('?'); |
| 132 | + let [search, hash] = searchpart?.split('#') || []; |
| 133 | + |
| 134 | + if (pathname.endsWith('/')) { |
| 135 | + pathname = pathname.substring(0, path.length - 1); |
| 136 | + } |
| 137 | + let normalized = pathname; |
| 138 | + if (search) { |
| 139 | + const params = new URLSearchParams(search); |
| 140 | + params.delete(QUERY_BASEPATH); |
| 141 | + params.delete(QUERY_FRAGMENT); |
| 142 | + search = params.toString(); |
| 143 | + if (search) { |
| 144 | + normalized += '?' + params.toString(); |
| 145 | + } |
133 | 146 | } |
134 | | - return path; |
| 147 | + if (hash) { |
| 148 | + normalized += '#' + hash; |
| 149 | + } |
| 150 | + return normalized; |
135 | 151 | } |
136 | 152 |
|
137 | 153 | function isSamePath(path1: string, path2: string) { |
@@ -218,11 +234,11 @@ export function toFullPath(urlString: string) { |
218 | 234 | } |
219 | 235 | const url = new URL(urlString); |
220 | 236 | let out = url.pathname; |
221 | | - if (url.search) { |
222 | | - out += '?' + url.search; |
| 237 | + if (url.search && url.search.length > 1) { |
| 238 | + out += url.search; |
223 | 239 | } |
224 | | - if (url.hash) { |
225 | | - out += '#' + url.hash; |
| 240 | + if (url.hash && url.hash.length > 1) { |
| 241 | + out += url.hash; |
226 | 242 | } |
227 | 243 | return out; |
228 | 244 | } |
0 commit comments