Skip to content

[fix] navigation scrollTop reset - #3629

Closed
nhe23 wants to merge 8 commits into
sveltejs:masterfrom
nhe23:navigation-scrolltop
Closed

nhe23 wants to merge 8 commits into
sveltejs:masterfrom
nhe23:navigation-scrolltop

Conversation

@nhe23

@nhe23 nhe23 commented Jan 30, 2022 •

Copy link
Copy Markdown
Contributor

Fixes #2733 by also scrolling the first child-element of #target that isn't scrolled to the top.
Currently if something like this

<div style="max-height: 100vh; overflow-y: auto;">
	<main>
		<slot />
	</main>
	<Footer />
</div>

is inside of a __layout component the page is not scrolled all the way to the top when using client-side navigation. One example where this happens is when a DaisyUI Drawer Component is used.

Please don't delete this checklist! Before submitting the PR, please make sure you do the following:

Tests

  • Run the tests with pnpm test and lint the project with pnpm lint and pnpm check

Changesets

  • If your PR makes a change that should be noted in one or more packages' changelogs, generate a changeset by running pnpx changeset and following the prompts. All changesets should be patch until SvelteKit 1.0

@changeset-bot

changeset-bot Bot commented Jan 30, 2022 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 5718088

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@sveltejs/kit Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@netlify

netlify Bot commented Jan 30, 2022 •

Copy link
Copy Markdown

✔️ Deploy Preview for kit-demo canceled.

🔨 Explore the source changes: 5718088

🔍 Inspect the deploy log: https://app.netlify.com/sites/kit-demo/deploys/61fc6123eca3a40007d53251

@nhe23 nhe23 changed the title [fix] navigation scrolltop [fix] navigation scrolltop reset Jan 30, 2022
@benmccann benmccann changed the title [fix] navigation scrolltop reset [fix] navigation scrollTop reset Jan 30, 2022
@Rich-Harris

Copy link
Copy Markdown
Member

Thank you — I don't yet 100% understand what this is doing 😅 but will try and wrap my head round it using the provided test. In the meantime though it's probably a good idea to hold off until @nikosgpet is able to provide a repro for #2733 (comment) and we can verify that it's fixed

@nhe23

nhe23 commented Feb 3, 2022

Copy link
Copy Markdown
Contributor Author

There were two use cases in which the page was not scrolled to the top using client side navigation.

  1. 'Overflowing' container inside of __layout.svelte (see PR description) -> fixed by scrolling first element inside of layout that is not scrolled up to the top (hence the overflowing container)
  2. 'Overflowing' body (see #2733 (comment)) -> fixed by scrolling document.body if scrollTop is > 0

There still might be other use cases in which the scrolling does not work ... however we cannot fix what we don't know 😄

@benmccann

Copy link
Copy Markdown
Member

Ok, I ran the new tests without the fixes and understand a bit better what is happening now:
In the body case, the layout adds a scrollbar to body and when you navigate it replaces the page but leaves the body / layout scrolled
The other case is almost the same. The layout wraps the page in a div with a scrollbar and when you navigate that div isn't scrolled back up to the top

const target_child_element = target_child.firstChild?.parentElement;
if (target_child_element && target_child_element.scrollTop > 0) {
target_child_element.scrollTo(0, 0);
break;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm not sure it's always safe to break here. What if you had one overflowed div inside another?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think I tested this exact usecase and it still worked. Elements that are siblings to the first overflown element don't matter as they cannot overflow more than the first overflown element. Overflowing elements inside the first overflown element also don't matter as they would only scroll inside their parent.
However it could be argued that after a page navigation every scroll position in the DOM should be at 0 because that's the "normal" behavior. But this could be very inefficient if there are many elements in the DOM. That's why I thought breaking as early as possible would be the best solution.

Comment on lines +388 to +389
// In some cases it is needed scroll first root element of target that
// is not scrolled to the top

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
// In some cases it is needed scroll first root element of target that
// is not scrolled to the top
// If there is an element with the overflow CSS property it may have a scrollbar
// We need to ensure the scroll is reset on these elements

});

test.only('scroll to top works with overflowing root container', async ({ page, clicknav }) => {
await page.goto('/scroll-top/overflow');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I feel like scroll-top isn't super descriptive about what this is testing because we have other scroll tests that test scrolling to the top. How about something like scroll-overflowed?

// In some cases it is needed scroll first root element of target that
// is not scrolled to the top
for (const target_child of this.target.childNodes) {
const target_child_element = target_child.firstChild?.parentElement;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

why do you get the parent of the child? wouldn't that just give you back the original element?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

target_child is the node and not the element itself. As element nodes must have at least one child in order to be an element-node (the node could also be just text) I implicitly check this by selecting the parent of the child. Also the node object does not have the same properties that an element object has. I'm happy to change the implementation if there is a better way 😄

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

you can use this.target.children, which only includes elements

@benmccann

Copy link
Copy Markdown
Member

Thanks for your patience on this one while we fixed the other scroll handling issues.

Handling the body case here seems fairly reasonable. The div case though seems trickier because the document could take any form and I'm not sure how we'd know which divs need to be scrolled. I somewhat think that the answer might be to simply say that is the user's responsibility. I'm curious what @Rich-Harris's opinion about this would be

@Rich-Harris

Copy link
Copy Markdown
Member

Ok, I've finally had a chance to try and get my head round this PR.

Unfortunately I just don't think it can work. Because it restricts the scroll reset to direct children of the target element, and breaks when we first encounter a scrolled element, it fails when there are multiple scrolled elements or if there's an additional wrapper element anywhere. See this demo for an example — try scrolling both columns to the bottom, then clicking the button.

There's another tricky problem we haven't yet solved: restoring the scroll positions of non-root elements on popstate.

I'm not sure what a working solution does look like; it might be worth seeing how/if other frameworks tackle this case.

@PH4NTOMiki

PH4NTOMiki commented Mar 1, 2022 •

Copy link
Copy Markdown
Contributor

@Rich-Harris I know that Next.js and Remix don't handle anything other than body/html, and I just checked Chrome doesn't handle it as well, so I don't think that this is a issue framework needs solving.

Edit: I'm talkink about restoring non-root elements on popstate.

@nhe23

nhe23 commented Mar 2, 2022

Copy link
Copy Markdown
Contributor Author

It's probably a good idea to remove the 'scroll first overflow element of target'-thing and just scroll the body. We could then add a FAQ that explains what behaviour prevents scrolling and what the user can do to solve this. Thoughts?

@Rich-Harris

Copy link
Copy Markdown
Member

It's probably a good idea to remove the 'scroll first overflow element of target'-thing and just scroll the body

Is that different to what Kit currently does? I'm not 100% sure I understand

We could then add a FAQ that explains what behaviour prevents scrolling and what the user can do to solve this. Thoughts?

Right now I'm not sure there is much that a user could do. It would be good to brainstorm some possible solutions

@PH4NTOMiki

Copy link
Copy Markdown
Contributor

I just checked and I was right, Next, Remix and Nuxt all don't handle scroll to 0 for non-root elements on navigation,

But one way we can at least partially solve it is to do something similar to this PR but remove break, and use top-level-components(like Layout) to limit the scope of the scroll elements, because statistically the most elements are going to be in the lower-level Slot components than top-level ones.

The second option is to write it in FAQ/docs because user knows what elements are scrollable and can account(set scrollTop of those elements) for those elements in beforeNavigate like for ex. I use for expanding navbar, I have a isNavbarOpen boolean and in beforeNavigate I set it to false.

@mrkishi

mrkishi commented Mar 2, 2022

Copy link
Copy Markdown
Member

I also don't think it makes sense to tackle this automatically. If I were to intentionally add an overflowing element, there would be a reason behind it and it might be incompatible with some automatic scrolling.

However, it might be worth considering whether we could give before/afterNavigate access to custom user state from the history's session storage. That way users would at least be able to behave a little more consistently should they wish to.

@Rich-Harris

Copy link
Copy Markdown
Member

I think providing access to history state is the most promising solution, yeah. If we do a good job of designing it, we could address #3236 (comment) at the same time.

I'm thinking along these lines:

<script>
  import { beforeNavigate, afterNavigate } from '$app/navigation';

  let sidebar;

  beforeNavigate(({ state }) => {
    state.sidebar_scroll = sidebar.scrollTop;
  });

  afterNavigate(({ type, state }) => {
    if (type === 'popstate') {
      sidebar.scrollTop = state.sidebar_scroll;
    }
  });
</script>

<aside bind:this={sidebar}>
  <!-- ... -->
</aside>

<style>
  aside {
    overflow-y: auto;
  }
</style>

@Rich-Harris

Copy link
Copy Markdown
Member

But one way we can at least partially solve it is to do something similar to this PR but remove break

I definitely understand the appeal, but something I've learned the hard way as an OSS maintainer is that it's better for something to remain broken than to appear fixed

@PH4NTOMiki

Copy link
Copy Markdown
Contributor

But one way we can at least partially solve it is to do something similar to this PR but remove break

I definitely understand the appeal, but something I've learned the hard way as an OSS maintainer is that it's better for something to remain broken than to appear fixed

I understand and agree, but I did some testing(basic stuff just to see the stats) like this(it was conducted on a page with 3405 DOM nodes, so pretty large):

const domNodes = Array.from(document.querySelectorAll('html, body, body *')); // length is 3405

and then run this many times:

console.time();
domNodes.forEach(node => node.scrollTo(0, 0));
console.timeEnd();

and the times came at 12ms most of the times, at most 15ms
so even if we traverse the whole tree and do scrollTo we don't get much impact, and most web apps don't have that many nodes. so it should be much less time, also if I added a check for node.scrollTop>0 it added 2-5ms to the results so if we decide to do this we should just skip checking it and do scrollTo for every node.

@mrkishi

mrkishi commented Mar 3, 2022

Copy link
Copy Markdown
Member

It might be very performant, but it's still implementation specific. By the way, if we were to scroll them all to the top, I'd also expect us to save and restore their positions on history navigation—but how would we correctly identify the elements?

Of note, even Chromium browsers don't save and scroll all overflown elements on history navigation, and they are operating on a level where uniquely identifying elements isn't an issue..

With that in mind, I propose we:

  • Provide the custom history state API on before/afterNavigate; this could be used not only for scrolling but other navigation page-specific state, so it's a win all-around imo.
  • Introduce a sveltekit:track [1] attribute: this attribute would give elements supposed to have scrolling handled by SvelteKit a unique id, sveltekit:track="sidebar". This would mean we could target only the children intended to be scrolled, and also save their positions to history consistently.

[1] 🐐 sveltekit:scroll? I don't know what to call it; track isn't very meaningful, but scroll could cause confusion with anchors' noscroll.

@PH4NTOMiki

Copy link
Copy Markdown
Contributor

Of note, even Chromium browsers don't save and scroll all overflown elements on history navigation, and they are operating on a level where uniquely identifying elements isn't an issue..

Yeah, I wrote that here #3629 (comment)
We just shouldn't even bother with that, Chrome and every other framework don't do it,
but scrolling to 0 should be something we should do as a framework if it is possible.

@Rich-Harris

Copy link
Copy Markdown
Member

I've been keeping this PR open until I got a chance to write up an issue with a proposal for @mrkishi's idea. I've done that now, so I'll close this — thanks

#5478

This branch was successfully deployed

3 active (1 outdated) deployments
Preview – kit — 57180889 Deployed Feb 3, 2022 by vercel[bot]
Preview – kit-svelte-dev — 57180889 Deployed Feb 3, 2022 by vercel[bot]
Preview — e923265e Deployed Jan 30, 2022 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Page scroll position not reset to top on navigation (regression)

5 participants