Skip to content

Commit

Permalink
Extract function for core logic of "staying on the same page when swi…
Browse files Browse the repository at this point in the history
…tching versions"

We will add unit tests for this functions in the next commit.

The function gets its own file because I was unable to get the test runner ("mocha") to work otherwise. See the child commit's description for more details.
  • Loading branch information
ilyagr committed Jul 8, 2024
1 parent 73d50aa commit 355c14d
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 12 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// This is a separate file so that `mocha` can load it without needing
// DOM shims.

import { Sitemap } from "../sitemap"

type CorrespondingURLParams = {
selectedVersionSitemap: Sitemap
selectedVersionBaseURL: URL
currentLocation: URL
currentBaseURL: string
}

/**
* Choose a URL to navigate to when the user chooses a version in the version
* selector.
*
* @param selectedVersionSitemap
* @param selectedVersionBaseURL
* @param currentLocation
* @param currentBaseURL
* @returns the URL to navigate to or null if we can't be sure that the
* corresponding page to the current page exists in the selected version
*/
export function selectedVersionCorrespondingURL(
{selectedVersionSitemap,
selectedVersionBaseURL,
currentLocation,
currentBaseURL}: CorrespondingURLParams
): URL | undefined {
const result = currentLocation.href.replace(
currentBaseURL,
selectedVersionBaseURL.href,
)
return selectedVersionSitemap.has(result.split("#")[0])
? new URL(result)
: undefined
}
27 changes: 15 additions & 12 deletions src/templates/assets/javascripts/integrations/version/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ import {

import { fetchSitemap } from "../sitemap"

import { selectedVersionCorrespondingURL } from "./correspondingPage"

/* ----------------------------------------------------------------------------
* Helper types
* ------------------------------------------------------------------------- */
Expand Down Expand Up @@ -122,22 +124,23 @@ export function setupVersionSelector(
return EMPTY
}
ev.preventDefault()
return of(url)
return of(new URL(url))
}
}
return EMPTY
}),
switchMap(url => {
return fetchSitemap(new URL(url))
.pipe(
map(sitemap => {
const location = getLocation()
const path = location.href.replace(config.base, url)
return sitemap.has(path.split("#")[0])
? new URL(path)
: new URL(url)
})
)
switchMap(selectedVersionBaseURL => {
return fetchSitemap(selectedVersionBaseURL).pipe(
map(
sitemap =>
selectedVersionCorrespondingURL({
selectedVersionSitemap: sitemap,
selectedVersionBaseURL,
currentLocation: getLocation(),
currentBaseURL: config.base
}) ?? selectedVersionBaseURL,
),
)
})
)
)
Expand Down

0 comments on commit 355c14d

Please sign in to comment.