Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/forty-houses-collect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

fix: correctly handle relative anchors when using the hash router
6 changes: 6 additions & 0 deletions packages/kit/src/runtime/client/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,12 @@ export function get_link_info(a, base, uses_hash_router) {

try {
url = new URL(a instanceof SVGAElement ? a.href.baseVal : a.href, document.baseURI);

// if the hash doesn't start with `#/` then it's probably linking to an id on the current page
if (uses_hash_router && url.hash.match(/^#[^/]/)) {
const route = location.hash.split('#')[1] || '/';
url.hash = `#${route}${url.hash}`;
}
} catch {}

const target = a instanceof SVGAElement ? a.target.baseVal : a.target;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<a href="#test">go to #test</a>

<p id="test">#test</p>
9 changes: 9 additions & 0 deletions packages/kit/test/apps/hash-based-routing/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,13 @@
url = new URL(page.url());
expect(url.hash).toBe('#/reroute-b');
});

test('relative anchor works', async ({ page }) => {

Check warning on line 93 in packages/kit/test/apps/hash-based-routing/test/test.js

View workflow job for this annotation

GitHub Actions / test-kit (18, ubuntu-latest, chromium)

flaky test: relative anchor works

retries: 2

Check warning on line 93 in packages/kit/test/apps/hash-based-routing/test/test.js

View workflow job for this annotation

GitHub Actions / test-kit (20, ubuntu-latest, chromium)

flaky test: relative anchor works

retries: 2

Check warning on line 93 in packages/kit/test/apps/hash-based-routing/test/test.js

View workflow job for this annotation

GitHub Actions / test-kit (22, ubuntu-latest, chromium)

flaky test: relative anchor works

retries: 2
await page.goto('/#/anchor');

await page.locator('a[href="#test"]').click();
await expect(page.locator('#test')).toHaveText('#test');
const url = new URL(page.url());
expect(url.hash).toBe('#/anchor#test');
});
});
Loading