Fix: Only call enable/disableScroll on open/close #47
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Background
I have a Svelte app that keeps track of a variable in App, and passes it down to multiple child components. When the variable is updated I'm encountering some odd scrolling behaviour.
Observed Behaviour
I've created a minimal REPL example with a basic counter variable: https://svelte.dev/repl/24df7129ba5c45c4903f87f9a8d0d36e?version=3.38.3
Two odd behaviours occur (seen in latest Firefox/Chrome/Edge on Windows 10):
Cause
Svelte will update the Modal component when the counter is updated, even if the state of the Modal itself hasn't changed. Because
open
andclose
are called insvelte.afterUpdate
, this meansenableScroll
ordisableScroll
may be called multiple times without the modal actually opening or closing.This means:
enableScroll
is called, which in turn callswindow.scrollTo(0, scrollY)
where scrollY is undefined and treated as 0.disableScroll
gets run a second time, which means the cached values (like previousBodyPosition) get overwritten with the identical current values. This means e.g. when the modal is closed the the body keepsposition: fixed
.Fix
Explicitly calling disable/enable during open/close fixes the issue for me. I do appreciate the elegance of using
afterUpdate
but it seems Svelte has other ideas :)