Skip to content

Commit 1ffa403

Browse files
authored
[intersection action] Use closest scrollable parent/ancestor for InterSectionObserver root or null to use viewport (#463)
1 parent 32e3169 commit 1ffa403

3 files changed

Lines changed: 21 additions & 8 deletions

File tree

.changeset/fifty-mirrors-wink.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte-ux': patch
3+
---
4+
5+
[intersection action] Use closest scrollable parent/ancestor for InterSectionObserver root or `null` to use viewport

packages/svelte-ux/src/lib/actions/observer.ts

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { getScrollParent } from '$lib/utils/dom.js';
12
import type { Action } from 'svelte/action';
23

34
export const resize: Action<Element, ResizeObserverOptions | undefined> = (node, options) => {
@@ -15,23 +16,20 @@ export const resize: Action<Element, ResizeObserverOptions | undefined> = (node,
1516
};
1617
};
1718

18-
export const intersection: Action<Element, IntersectionObserverInit | undefined> = (
19+
export const intersection: Action<HTMLElement, IntersectionObserverInit | undefined> = (
1920
node,
2021
options = {}
2122
) => {
22-
// TODO: Support defininting `options.root = node.parentNode` easily (maybe querySelector() string?)
23+
const scrollParent = getScrollParent(node);
24+
// Use viewport (null) if scrollParent = `<body>`
25+
const root = scrollParent === document.body ? null : scrollParent;
2326

2427
let observer = new IntersectionObserver(
2528
(entries, observer) => {
2629
const entry = entries[0];
2730
node.dispatchEvent(new CustomEvent('intersecting', { detail: entry }));
28-
// if (entry.intersectionRatio > 0) {
29-
// node.dispatchEvent(new CustomEvent('visible', { detail: entry }));
30-
// } else {
31-
// node.dispatchEvent(new CustomEvent('invisible', { detail: entry }));
32-
// }
3331
},
34-
{ root: node.parentElement, ...options }
32+
{ root, ...options }
3533
);
3634
observer.observe(node);
3735

packages/svelte-ux/src/routes/docs/components/InfiniteScroll/+page.svelte

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,13 @@
3232
</InfiniteScroll>
3333
</div>
3434
</Preview>
35+
36+
<h2>Viewport root (no overflown parent/ancestor)</h2>
37+
38+
<Preview>
39+
<InfiniteScroll {items} let:visibleItems>
40+
{#each visibleItems as item}
41+
<ListItem title={item.name} />
42+
{/each}
43+
</InfiniteScroll>
44+
</Preview>

0 commit comments

Comments
 (0)