Skip to content

Reset scroll position after navigation. Fixes #10482 #12423

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 24, 2019
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
6 changes: 3 additions & 3 deletions src/Components/Web.JS/dist/Release/blazor.server.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/Components/Web.JS/dist/Release/blazor.webassembly.js

Large diffs are not rendered by default.

17 changes: 17 additions & 0 deletions src/Components/Web.JS/src/Rendering/Renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ interface BrowserRendererRegistry {
[browserRendererId: number]: BrowserRenderer;
}
const browserRenderers: BrowserRendererRegistry = {};
let shouldResetScrollAfterNextBatch = false;

export function attachRootComponentToLogicalElement(browserRendererId: number, logicalElement: LogicalElement, componentId: number): void {

Expand Down Expand Up @@ -67,4 +68,20 @@ export function renderBatch(browserRendererId: number, batch: RenderBatch): void
const eventHandlerId = batch.disposedEventHandlerIdsEntry(disposedEventHandlerIdsValues, i);
browserRenderer.disposeEventHandler(eventHandlerId);
}

resetScrollIfNeeded();
}

export function resetScrollAfterNextBatch() {
shouldResetScrollAfterNextBatch = true;
}

function resetScrollIfNeeded() {
if (shouldResetScrollAfterNextBatch) {
shouldResetScrollAfterNextBatch = false;

// This assumes the scroller is on the window itself. There isn't a general way to know
// if some other element is playing the role of the primary scroll region.
window.scrollTo && window.scrollTo(0, 0);
}
}
8 changes: 8 additions & 0 deletions src/Components/Web.JS/src/Services/UriHelper.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import '@dotnet/jsinterop';
import { resetScrollAfterNextBatch } from '../Rendering/Renderer';

let hasRegisteredNavigationInterception = false;
let hasRegisteredNavigationEventListeners = false;
Expand Down Expand Up @@ -81,6 +82,13 @@ export function navigateTo(uri: string, forceLoad: boolean) {
}

function performInternalNavigation(absoluteInternalHref: string, interceptedLink: boolean) {
// Since this was *not* triggered by a back/forward gesture (that goes through a different
// code path starting with a popstate event), we don't want to preserve the current scroll
// position, so reset it.
// To avoid ugly flickering effects, we don't want to change the scroll position until the
// we render the new page. As a best approximation, wait until the next batch.
resetScrollAfterNextBatch();

history.pushState(null, /* ignored title */ '', absoluteInternalHref);
notifyLocationChanged(interceptedLink);
}
Expand Down
34 changes: 34 additions & 0 deletions src/Components/test/E2ETest/Tests/RoutingTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,40 @@ public void RoutingToComponentOutsideMainAppDoesNotWork()
Assert.Equal("Oops, that component wasn't found!", app.FindElement(By.Id("test-info")).Text);
}

[Fact]
public void ResetsScrollPositionWhenPerformingInternalNavigation_LinkClick()
{
SetUrlViaPushState("/LongPage1");
var app = MountTestComponent<TestRouter>();
Browser.Equal("This is a long page you can scroll.", () => app.FindElement(By.Id("test-info")).Text);
BrowserScrollY = 500;
Browser.True(() => BrowserScrollY > 300); // Exact position doesn't matter

app.FindElement(By.LinkText("Long page 2")).Click();
Browser.Equal("This is another long page you can scroll.", () => app.FindElement(By.Id("test-info")).Text);
Browser.Equal(0, () => BrowserScrollY);
}

[Fact]
public void ResetsScrollPositionWhenPerformingInternalNavigation_ProgrammaticNavigation()
{
SetUrlViaPushState("/LongPage1");
var app = MountTestComponent<TestRouter>();
Browser.Equal("This is a long page you can scroll.", () => app.FindElement(By.Id("test-info")).Text);
BrowserScrollY = 500;
Browser.True(() => BrowserScrollY > 300); // Exact position doesn't matter

app.FindElement(By.Id("go-to-longpage2")).Click();
Browser.Equal("This is another long page you can scroll.", () => app.FindElement(By.Id("test-info")).Text);
Browser.Equal(0, () => BrowserScrollY);
}

private long BrowserScrollY
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is kind of confusing. I would have simply used methods for this.

{
get => (long)((IJavaScriptExecutor)Browser).ExecuteScript("return window.scrollY");
set => ((IJavaScriptExecutor)Browser).ExecuteScript($"window.scrollTo(0, {value})");
}

private string SetUrlViaPushState(string relativeUri)
{
var pathBaseWithoutHash = ServerPathBase.Split('#')[0];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
<li><NavLink href="/subdir/Other#blah">Other with hash</NavLink></li>
<li><NavLink href="/subdir/WithParameters/Name/Abc">With parameters</NavLink></li>
<li><NavLink href="/subdir/WithParameters/Name/Abc/LastName/McDef">With more parameters</NavLink></li>
<li><NavLink href="/subdir/LongPage1">Long page 1</NavLink></li>
<li><NavLink href="/subdir/LongPage2">Long page 2</NavLink></li>
</ul>

<button id="do-navigation" @onclick=@(x => uriHelper.NavigateTo("Other"))>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
@page "/LongPage1"
@inject IUriHelper UriHelper
<div id="test-info">This is a long page you can scroll.</div>

<div style="border: 2px dashed red; margin: 1rem; padding: 1rem; height: 1500px;">
Scroll past me to find the links
</div>

<button id="go-to-longpage2" @onclick="@(() => UriHelper.NavigateTo("LongPage2"))">
Navigate programmatically to long page 2
</button>

<Links />
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
@page "/LongPage2"
<div id="test-info">This is another long page you can scroll.</div>

<div style="border: 2px dashed blue; margin: 1rem; padding: 1rem; height: 1500px;">
Scroll past me to find the links
</div>

<Links />