epicweb-dev / restore-scroll

πŸŒ€ Restore scroll position of elements on page navigation
https://github.com/epicweb-dev/restore-scroll
241 stars 4 forks source link

Clarify browser behaviour #8

Open OliverJAsh opened 1 month ago

OliverJAsh commented 1 month ago

Hey! πŸ‘‹ I just wanted to drop a note about something in the documentation that I think is incorrect:

If the user scrolls a list, then navigates back and forth, the browser will scroll the page to the top, but the list will still be scrolled to the position it was at when the user left the page.

Browsers can actually restore scroll positions for nested scroll containers. Here's a reduced test case to demonstrate that scroll restoration does work for non-body aka nested scroll containers: https://codepen.io/OliverJAsh/pen/bGPqyRw

Relevant specs:

I think the issue you're referring to is what happens when an element is removed from the DOM after leaving one page and then restored when navigating back. In this case, the browser can't restore scroll because it has no way of knowing that we're remounting the same element as before. Reduced test case: https://codepen.io/OliverJAsh/pen/gONmJZM

Perhaps we could clarify this in the documentation? Or perhaps I've misunderstood πŸ˜„

OliverJAsh commented 1 month ago

While I'm here, I'm also curious why you decided to use session storage instead of location state (i.e. the state in window.history.state).

kentcdodds commented 1 month ago

That kind of clarification is welcome. I think people who end up here are experiencing a situation where scroll isn't being restored as they want it to so they don't need the clarification, but I'm happy to accept a PR to clarify things :)

OliverJAsh commented 1 month ago

Thanks! I partly just wanted to validate my mental model for this. Glad to hear I'm not going crazy πŸ˜„

While I'm here, I'm also curious why you decided to use session storage instead of location state (i.e. the state in window.history.state).

I'd love to get your thoughts on this.

(I'm looking at implementing something similar for the modal on Unsplash.)

kentcdodds commented 1 month ago

Sorry I missed your earlier question (I blame GitHub, but it's probably my fault πŸ˜…). I remember when I helped Ryan build <ScrollRestoration /> into Remix (now React Router), we thought about using window.history.state and I can't recall why we decided that wouldn't work and session storage should be used. Sorry that's not a very useful answer, but we did consider it and our decision made sense at the time! πŸ˜