Skip to content

Commit

Permalink
Improve readability of buildUrl function
Browse files Browse the repository at this point in the history
  • Loading branch information
kulmann committed Feb 16, 2022
1 parent cec78c2 commit 4ab1dfc
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions packages/web-runtime/src/router/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,20 +108,30 @@ export const router = patchRouter(
)

export const buildUrl = (pathname) => {
const baseUrl = new URL(window.location.href.split('#')[0])
if (baseUrl.pathname.endsWith('/index.html')) {
baseUrl.pathname = baseUrl.pathname.split('/').slice(0, -1).filter(Boolean).join('/')
const isHistoryMode = !!base
let baseUrl
if (isHistoryMode) {
// in history mode we can't determine the baseUrl, it must be provided by the document
baseUrl = new URL(base.href)
} else {
// in hash mode, determine baseUrl by removing `/index.html` and following parts
baseUrl = new URL(window.location.href.split('#')[0])
if (baseUrl.pathname.endsWith('/index.html')) {
baseUrl.pathname = baseUrl.pathname.split('/').slice(0, -1).filter(Boolean).join('/')
}
}

/**
* build full url by either
* - concatenating baseUrl and pathname (for unknown/non-router urls, e.g. `oidc-callback.html`) or
* - resolving via router (for known routes)
*/
if (/\.(html?)$/i.test(pathname)) {
baseUrl.pathname = [
...(base ? new URL(base.href) : baseUrl).pathname.split('/'),
...pathname.split('/')
]
baseUrl.pathname = [...baseUrl.pathname.split('/'), ...pathname.split('/')]
.filter(Boolean)
.join('/')
} else {
baseUrl[base ? 'pathname' : 'hash'] = router.resolve(pathname).href
baseUrl[isHistoryMode ? 'pathname' : 'hash'] = router.resolve(pathname).href
}

return baseUrl.href
Expand Down

0 comments on commit 4ab1dfc

Please sign in to comment.