Files
ComfyUI_frontend/src/composables/useIntersectionObserver.ts
Alexander Brown f6405e9125 Knip: More Pruning (#5374)
* knip: Don't ignore exports that are only used within a given file

* knip: More pruning after rebase

* knip: Vite plugin config fix

* knip: vitest plugin config

* knip: Playwright config, remove unnecessary ignores.

* knip: Simplify project file enumeration.

* knip: simplify the config file patterns ?(.optional_segment)

* knip: tailwind v4 fix

* knip: A little more, explain some of the deps.
Should be good for this PR.

* knip: remove unused disabling of classMembers.
It's opt-in, which we should probably do.

* knip: floating comments
We should probably delete _one_ of these parallell trees, right?

* knip: Add additional entrypoints

* knip: Restore UserData that's exposed via the types for now.

* knip: Add as an entry file even though knip says it's not necessary.

* knip: re-export functions used by nodes (h/t @christian-byrne)
2025-09-07 01:10:32 -07:00

60 lines
1.3 KiB
TypeScript

import { type Ref, onBeforeUnmount, ref, watch } from 'vue'
interface UseIntersectionObserverOptions extends IntersectionObserverInit {
immediate?: boolean
}
export function useIntersectionObserver(
target: Ref<Element | null>,
callback: IntersectionObserverCallback,
options: UseIntersectionObserverOptions = {}
) {
const { immediate = true, ...observerOptions } = options
const isSupported =
typeof window !== 'undefined' && 'IntersectionObserver' in window
const isIntersecting = ref(false)
let observer: IntersectionObserver | null = null
const cleanup = () => {
if (observer) {
observer.disconnect()
observer = null
}
}
const observe = () => {
cleanup()
if (!isSupported || !target.value) return
observer = new IntersectionObserver((entries) => {
isIntersecting.value = entries.some((entry) => entry.isIntersecting)
callback(entries, observer!)
}, observerOptions)
observer.observe(target.value)
}
const unobserve = () => {
if (observer && target.value) {
observer.unobserve(target.value)
}
}
if (immediate) {
watch(target, observe, { immediate: true, flush: 'post' })
}
onBeforeUnmount(cleanup)
return {
isSupported,
isIntersecting,
observe,
unobserve,
cleanup
}
}