sveltejs / svelte-scroller

A <Scroller> component for Svelte apps
https://svelte.dev/repl/76846b7ae27b3a21becb64ffd6e9d4a6
Other
347 stars 25 forks source link

Hard-coding `width` causes unwelcome consequences on bindings #13

Closed basilesimon closed 3 years ago

basilesimon commented 3 years ago

The manual setting of width and its use to set svelte-scroller-background-container's styles appears to get in the way of binding to clientWidth inside <Scroller />.

Here is a fork of the official example reproducing the behaviour I mention. Notice how the SVG box initially inherits a small width incompatible with its parent's supposed 100%, before this property being naturally altered by, say, a window resize.

mhkeller commented 3 years ago

I'm also seeing this as causing problems. Here's a REPL reproduction where a div inside of the background slot has a 0 width.

If you get rid of the width style declaration here, it is a little better. But the background slot width is not stable because it switches from absolute to fixed position.

I thought of syncing the foreground slot width and the background slot width in this example but that doesn't seem to work. I'm not sure why, though...

mhkeller commented 3 years ago

I think I found a solution building off of the previous REPL link.

First attempt

In this try, instead of setting the width:0px in the style variable, I bound it to the foreground clientWidth. For some reason, that value does not get detected on load and you still get 0.

Second attempt

If you remove the width declaration from style entirely, it works on load, but without a specific CSS width, the container expands beyond the bounds of its parent when the position switches to fixed.

The solution, shown in this example, is to only set the width declaration when the position is fixed. I'm not sure why this trigger's svelte's reactivity better than the current version – but it does. We get proper dimension on load because of the regular CSS and then we get it constrained to the parent's bounds when the fixed variable changes.

I wasn't sure if this would fail if you reload the page at a scroll depth inside the scroller but it seems to work. I'll put together a PR.

mhkeller commented 3 years ago

@basilesimon does this solution work in your use case?