diff --git a/.changeset/fifty-mirrors-wink.md b/.changeset/fifty-mirrors-wink.md new file mode 100644 index 000000000..73a925565 --- /dev/null +++ b/.changeset/fifty-mirrors-wink.md @@ -0,0 +1,5 @@ +--- +'svelte-ux': patch +--- + +[intersection action] Use closest scrollable parent/ancestor for InterSectionObserver root or `null` to use viewport diff --git a/packages/svelte-ux/src/lib/actions/observer.ts b/packages/svelte-ux/src/lib/actions/observer.ts index 1ce922400..8721817cb 100644 --- a/packages/svelte-ux/src/lib/actions/observer.ts +++ b/packages/svelte-ux/src/lib/actions/observer.ts @@ -1,3 +1,4 @@ +import { getScrollParent } from '$lib/utils/dom.js'; import type { Action } from 'svelte/action'; export const resize: Action = (node, options) => { @@ -15,23 +16,20 @@ export const resize: Action = (node, }; }; -export const intersection: Action = ( +export const intersection: Action = ( node, options = {} ) => { - // TODO: Support defininting `options.root = node.parentNode` easily (maybe querySelector() string?) + const scrollParent = getScrollParent(node); + // Use viewport (null) if scrollParent = `` + 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); diff --git a/packages/svelte-ux/src/routes/docs/components/InfiniteScroll/+page.svelte b/packages/svelte-ux/src/routes/docs/components/InfiniteScroll/+page.svelte index 32910ee08..a35fdd15c 100644 --- a/packages/svelte-ux/src/routes/docs/components/InfiniteScroll/+page.svelte +++ b/packages/svelte-ux/src/routes/docs/components/InfiniteScroll/+page.svelte @@ -32,3 +32,13 @@ + +

Viewport root (no overflown parent/ancestor)

+ + + + {#each visibleItems as item} + + {/each} + +