Skip to content

Commit 0d56855

Browse files
zonemeenbrc-dd
andauthoredSep 22, 2023
fix(build): consistent route.path across dev and ssr (#2997)
Co-authored-by: Divyansh Singh <40380293+brc-dd@users.noreply.github.com>
1 parent aa40cec commit 0d56855

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed
 

‎src/client/app/router.ts

+19-13
Original file line numberDiff line numberDiff line change
@@ -64,16 +64,8 @@ export function createRouter(
6464
}
6565

6666
async function go(href: string = inBrowser ? location.href : '/') {
67+
href = normalizeHref(href)
6768
if ((await router.onBeforeRouteChange?.(href)) === false) return
68-
const url = new URL(href, fakeHost)
69-
if (!siteDataRef.value.cleanUrls) {
70-
// ensure correct deep link so page refresh lands on correct files.
71-
// if cleanUrls is enabled, the server should handle this
72-
if (!url.pathname.endsWith('/') && !url.pathname.endsWith('.html')) {
73-
url.pathname += '.html'
74-
href = url.pathname + url.search + url.hash
75-
}
76-
}
7769
updateHistory(href)
7870
await loadPage(href)
7971
await router.onAfterRouteChanged?.(href)
@@ -230,7 +222,10 @@ export function createRouter(
230222
)
231223

232224
window.addEventListener('popstate', (e) => {
233-
loadPage(location.href, (e.state && e.state.scrollPosition) || 0)
225+
loadPage(
226+
normalizeHref(location.href),
227+
(e.state && e.state.scrollPosition) || 0
228+
)
234229
})
235230

236231
window.addEventListener('hashchange', (e) => {
@@ -327,17 +322,28 @@ function handleHMR(route: Route): void {
327322
}
328323

329324
function shouldHotReload(payload: PageDataPayload): boolean {
330-
const payloadPath = payload.path.replace(/(\bindex)?\.md$/, '')
325+
const payloadPath = payload.path.replace(/(?:(^|\/)index)?\.md$/, '$1')
331326
const locationPath = location.pathname
332-
.replace(/(\bindex)?\.html$/, '')
327+
.replace(/(?:(^|\/)index)?\.html$/, '')
333328
.slice(siteDataRef.value.base.length - 1)
334329
return payloadPath === locationPath
335330
}
336331

337332
function updateHistory(href: string) {
338-
if (inBrowser && href !== location.href) {
333+
if (inBrowser && href !== normalizeHref(location.href)) {
339334
// save scroll position before changing url
340335
history.replaceState({ scrollPosition: window.scrollY }, document.title)
341336
history.pushState(null, '', href)
342337
}
343338
}
339+
340+
function normalizeHref(href: string): string {
341+
const url = new URL(href, fakeHost)
342+
url.pathname = url.pathname.replace(/(^|\/)index(\.html)?$/, '$1')
343+
// ensure correct deep link so page refresh lands on correct files.
344+
if (siteDataRef.value.cleanUrls)
345+
url.pathname = url.pathname.replace(/\.html$/, '')
346+
else if (!url.pathname.endsWith('/') && !url.pathname.endsWith('.html'))
347+
url.pathname += '.html'
348+
return url.pathname + url.search + url.hash
349+
}

0 commit comments

Comments
 (0)
Please sign in to comment.