Skip to content

Commit 9fa424b

Browse files
fix: redirect hashes with different casing (#586)
* fix: redirect hashes with different casing * add comment * defensive copy * simplify * Update apps/svelte.dev/src/routes/docs/[...path]/+page.svelte Co-authored-by: Rich Harris <[email protected]> * Update apps/svelte.dev/src/routes/docs/[...path]/+page.svelte Co-authored-by: Rich Harris <[email protected]> * Update apps/svelte.dev/src/routes/docs/[...path]/+page.svelte Co-authored-by: Rich Harris <[email protected]> * Update apps/svelte.dev/src/routes/docs/[...path]/+page.svelte Co-authored-by: Rich Harris <[email protected]> --------- Co-authored-by: Rich Harris <[email protected]>
1 parent 0142ab2 commit 9fa424b

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@
22
import { Text } from '@sveltejs/site-kit/components';
33
import { legacy_details } from '@sveltejs/site-kit/actions';
44
import { setupDocsHovers } from '@sveltejs/site-kit/docs';
5+
import { onMount } from 'svelte';
56
import OnThisPage from './OnThisPage.svelte';
67
import Breadcrumbs from './Breadcrumbs.svelte';
8+
import { goto } from '$app/navigation';
9+
import { page } from '$app/stores';
710
import PageControls from '$lib/components/PageControls.svelte';
811
912
let { data } = $props();
@@ -17,6 +20,35 @@
1720
const link = 'docs/' + data.document.file.split('/').slice(2).join('/');
1821
return `https://github.com/sveltejs/${name}/edit/main/documentation/${link}`;
1922
});
23+
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;
29+
30+
// if there's an exact match, use that. no need to redirect
31+
// also semi-handles the case where one appears twice with difference casing
32+
// e.g. https://svelte.dev/docs/kit/@sveltejs-kit#redirect vs https://svelte.dev/docs/kit/@sveltejs-kit#Redirect
33+
// but browsers make it impossible to really do: https://github.com/sveltejs/svelte.dev/issues/590
34+
if (document.querySelector(`[id="${hash}"]`)) {
35+
return;
36+
}
37+
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+
}
45+
46+
onMount(() => {
47+
const redirect = get_url_to_redirect_to();
48+
if (redirect) {
49+
goto(redirect, { replaceState: true });
50+
}
51+
});
2052
</script>
2153

2254
<svelte:head>

0 commit comments

Comments
 (0)