Skip to content

Commit 5f095cf

Browse files
fix: better hash normalization for redirects (#620)
* fix: better hash normalization for redirects * fix/simplify * actually it looks like we do need this --------- Co-authored-by: Rich Harris <[email protected]>
1 parent 5877aed commit 5f095cf

File tree

1 file changed

+16
-20
lines changed

1 file changed

+16
-20
lines changed

apps/svelte.dev/src/routes/docs/[...path]/+page.svelte

Lines changed: 16 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,8 @@
55
import { onMount } from 'svelte';
66
import OnThisPage from './OnThisPage.svelte';
77
import Breadcrumbs from './Breadcrumbs.svelte';
8-
import { goto } from '$app/navigation';
9-
import { page } from '$app/stores';
108
import PageControls from '$lib/components/PageControls.svelte';
9+
import { goto } from '$app/navigation';
1110
1211
let { data } = $props();
1312
@@ -21,32 +20,29 @@
2120
return `https://github.com/sveltejs/${name}/edit/main/documentation/${link}`;
2221
});
2322
24-
// make hash case-insensitive
25-
// hash was lowercase in v4 docs and varying case in v5 docs
26-
function get_url_to_redirect_to() {
27-
const hash = $page.url.hash.slice(1);
28-
if (hash === '') return;
23+
onMount(() => {
24+
// hash was lowercase in v4 docs and varying case in v5 docs
25+
const hash = location.hash.slice(1);
2926
30-
// if there's an exact match, use that. no need to redirect
27+
// if there's no hash, or an exact match, no need to redirect
3128
// also semi-handles the case where one appears twice with difference casing
3229
// e.g. https://svelte.dev/docs/kit/@sveltejs-kit#redirect vs https://svelte.dev/docs/kit/@sveltejs-kit#Redirect
3330
// but browsers make it impossible to really do: https://github.com/sveltejs/svelte.dev/issues/590
34-
if (document.querySelector(`[id="${hash}"]`)) {
31+
if (hash === '' || content.querySelector(`[id="${hash}"]`)) {
3532
return;
3633
}
3734
38-
const heading = document.querySelector(`[id="${hash}" i]`);
39-
if (heading) {
40-
const url = new URL($page.url);
41-
url.hash = heading.id;
42-
return url;
43-
}
44-
}
35+
const id = hash.toLowerCase().replaceAll(':', '-');
4536
46-
onMount(() => {
47-
const redirect = get_url_to_redirect_to();
48-
if (redirect) {
49-
goto(redirect, { replaceState: true });
37+
for (const heading of content.querySelectorAll('[id]')) {
38+
// e.g. we want to redirect progressive-enhancement-use-enhance to Progressive-enhancement-use:enhance
39+
if (heading.id.toLowerCase().replaceAll(':', '-') === id) {
40+
goto(`#${heading.id}`, {
41+
replaceState: true
42+
});
43+
44+
break;
45+
}
5046
}
5147
});
5248
</script>

0 commit comments

Comments
 (0)