Skip to content

Commit

Permalink
[intersection action] Use closest scrollable parent/ancestor for Inte…
Browse files Browse the repository at this point in the history
…rSectionObserver root or `null` to use viewport (#463)
  • Loading branch information
techniq authored Aug 14, 2024
1 parent 32e3169 commit 1ffa403
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/fifty-mirrors-wink.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte-ux': patch
---

[intersection action] Use closest scrollable parent/ancestor for InterSectionObserver root or `null` to use viewport
14 changes: 6 additions & 8 deletions packages/svelte-ux/src/lib/actions/observer.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getScrollParent } from '$lib/utils/dom.js';
import type { Action } from 'svelte/action';

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

export const intersection: Action<Element, IntersectionObserverInit | undefined> = (
export const intersection: Action<HTMLElement, IntersectionObserverInit | undefined> = (
node,
options = {}
) => {
// TODO: Support defininting `options.root = node.parentNode` easily (maybe querySelector() string?)
const scrollParent = getScrollParent(node);
// Use viewport (null) if scrollParent = `<body>`
const root = scrollParent === document.body ? null : scrollParent;

let observer = new IntersectionObserver(
(entries, observer) => {
const entry = entries[0];
node.dispatchEvent(new CustomEvent('intersecting', { detail: entry }));
// if (entry.intersectionRatio > 0) {
// node.dispatchEvent(new CustomEvent('visible', { detail: entry }));
// } else {
// node.dispatchEvent(new CustomEvent('invisible', { detail: entry }));
// }
},
{ root: node.parentElement, ...options }
{ root, ...options }
);
observer.observe(node);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,13 @@
</InfiniteScroll>
</div>
</Preview>

<h2>Viewport root (no overflown parent/ancestor)</h2>

<Preview>
<InfiniteScroll {items} let:visibleItems>
{#each visibleItems as item}
<ListItem title={item.name} />
{/each}
</InfiniteScroll>
</Preview>

0 comments on commit 1ffa403

Please sign in to comment.