Skip to content

Commit

Permalink
fix: robustify bind:scrollX/Y binding (#11655)
Browse files Browse the repository at this point in the history
- we were scrolling to the given value, which we shouldn't for accessibility reasons (Svelte 4 didn't do it either)
- we need to notify of the value 0 if there's no scroll (#11623 (comment))
  • Loading branch information
dummdidumm committed May 16, 2024
1 parent d288735 commit 110a5a8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/popular-roses-teach.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"svelte": patch
---

fix: robustify `bind:scrollX/Y` binding
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { render_effect } from '../../../reactivity/effects.js';
import { effect, render_effect } from '../../../reactivity/effects.js';
import { listen } from './shared.js';

/**
Expand All @@ -22,18 +22,21 @@ export function bind_window_scroll(type, get_value, update) {
passive: true
});

var latest_value = 0;
var scrolling = false;

/** @type {ReturnType<typeof setTimeout>} */
var timeout;
var clear = () => {
scrolling = false;
};
var first = true;

render_effect(() => {
latest_value = get_value();
if (!scrolling && latest_value != null) {
var latest_value = get_value();
// Don't scroll to the initial value for accessibility reasons
if (first) {
first = false;
} else if (!scrolling && latest_value != null) {
scrolling = true;
clearTimeout(timeout);
if (is_scrolling_x) {
Expand All @@ -45,6 +48,15 @@ export function bind_window_scroll(type, get_value, update) {
}
});

// Browsers fire the scroll event only if the scroll position is not 0.
// This effect is (almost) guaranteed to run after the scroll event would've fired.
effect(() => {
var value = window[is_scrolling_x ? 'scrollX' : 'scrollY'];
if (value === 0) {
update(value);
}
});

render_effect(() => {
return () => {
removeEventListener('scroll', target_handler);
Expand Down

0 comments on commit 110a5a8

Please sign in to comment.