Skip to content

Commit

Permalink
#11421 part two (#11540)
Browse files Browse the repository at this point in the history
* Capture scroll position when using `pushState`

* Added test

* Format

* Added changeset

* Update .changeset/healthy-windows-rush.md

Co-authored-by: Ben McCann <[email protected]>

* move test

* lint

---------

Co-authored-by: Patrick <[email protected]>
Co-authored-by: Patrick <[email protected]>
Co-authored-by: Ben McCann <[email protected]>
Co-authored-by: Rich Harris <[email protected]>
  • Loading branch information
5 people authored Jan 8, 2024
1 parent 0679801 commit 129a9a3
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/healthy-windows-rush.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@sveltejs/kit": patch
---

fix: capture scroll position when using `pushState`
1 change: 1 addition & 0 deletions packages/kit/src/runtime/client/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -1611,6 +1611,7 @@ export function create_client(app, target) {
}
}

update_scroll_positions(current_history_index);
const opts = {
[HISTORY_INDEX]: (current_history_index += 1),
[NAVIGATION_INDEX]: current_navigation_index,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<script>
import { pushState } from '$app/navigation';
import { page } from '$app/stores';
function handleClick() {
pushState('', { active: true });
}
</script>

<a id="subpage-link" href="/scroll/push-state/a">Subpage</a>

{#each { length: 20 } as _, n}
<p>#{n}</p>
{/each}

<button id="shallow-button" type="button" on:click={handleClick}>Shallow</button>

{#if $page.state.active}
<button id="back-button" type="button" on:click={() => history.back()}>Back</button>
{/if}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<button id="back-button" type="button" on:click={() => history.back()}>Back</button>
16 changes: 16 additions & 0 deletions packages/kit/test/apps/basics/test/cross-platform/client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,22 @@ test.describe('Scrolling', () => {
expect(await page.evaluate(() => window.scrollY)).toBe(0);
}
});

test('Scroll position is correct after going back from a shallow route', async ({ page }) => {
await page.goto('/scroll/push-state');
await page.locator('#subpage-link').click();
await page.locator('#back-button').click();

await page.evaluate(() => window.scrollTo(0, 9999));

const scroll = await page.evaluate(() => window.scrollY);
expect(scroll).toBeGreaterThan(0);

await page.locator('#shallow-button').click();
await page.locator('#back-button').click();

expect(await page.evaluate(() => window.scrollY)).toBe(scroll);
});
});

test.describe('CSS', () => {
Expand Down

0 comments on commit 129a9a3

Please sign in to comment.