|
1 | 1 | <script lang="ts">
|
| 2 | + import { getRenderingEngine } from '$lib/featuredetect.js'; |
| 3 | + import { onMount } from 'svelte'; |
| 4 | +
|
2 | 5 | let {
|
3 | 6 | //
|
4 | 7 | scrollContainer = $bindable({} as HTMLDivElement),
|
|
12 | 15 | });
|
13 | 16 | }
|
14 | 17 |
|
15 |
| - let targetScrollTop = $state(0); |
| 18 | + let scrollBehavior: ScrollBehavior; |
| 19 | + let targetScrollTop = 0; |
16 | 20 | let scrollTopUpdateTask = -1;
|
17 | 21 |
|
18 | 22 | function onScrollCapture() {
|
|
38 | 42 | This appears to work pretty reliably in Chromium and Firefox (haven't tested Safari), so I'm happy with it.
|
39 | 43 | */
|
40 | 44 |
|
41 |
| - // Calling scrollTo while a previous call is still animating will cancel the current animation. |
42 |
| - // This is how we trick the browser into giving the same _feel_ as a normal scroll would have. |
| 45 | + let newTargetScrollTop = targetScrollTop - e.deltaY; // Note that the scroll direction is inverted. |
| 46 | +
|
| 47 | + const maxScroll = scrollContainer.scrollHeight - scrollContainer.clientHeight; |
| 48 | + if (newTargetScrollTop < 0) { |
| 49 | + newTargetScrollTop = 0; // Min. |
| 50 | + } else if (newTargetScrollTop > maxScroll) { |
| 51 | + newTargetScrollTop = maxScroll; // Max. |
| 52 | + } |
| 53 | +
|
| 54 | + if (newTargetScrollTop == targetScrollTop) { |
| 55 | + return; // Don't call scrollTo() unnecessarily. |
| 56 | + } |
43 | 57 |
|
44 |
| - targetScrollTop = targetScrollTop - e.deltaY; // Note that the scroll direction is inverted. |
| 58 | + targetScrollTop = newTargetScrollTop; |
45 | 59 | scrollContainer.scrollTo({
|
46 |
| - top: targetScrollTop, |
47 |
| - behavior: 'smooth' |
| 60 | + top: newTargetScrollTop, |
| 61 | + behavior: scrollBehavior |
48 | 62 | });
|
49 | 63 | }
|
| 64 | +
|
| 65 | + onMount(() => { |
| 66 | + // Allowlist specific rendering engines for smooth scrolling. |
| 67 | + // Some browsers have a built-in debounce that won't start the animation until our final scrollTo() call |
| 68 | + // which prevents our scrolling implementation from working correctly. |
| 69 | + // |
| 70 | + // So we allow for smooth scrolling if the browser behaves how we want it to. |
| 71 | + switch (getRenderingEngine()) { |
| 72 | + case 'webkit': // a.k.a safari |
| 73 | + case 'gecko': // a.k.a firefox |
| 74 | + scrollBehavior = 'smooth'; |
| 75 | + break; |
| 76 | +
|
| 77 | + default: |
| 78 | + scrollBehavior = 'instant'; |
| 79 | + break; |
| 80 | + } |
| 81 | + }); |
50 | 82 | </script>
|
51 | 83 |
|
52 | 84 | <div
|
|
0 commit comments