( ref: Solid.Accessor<T | null>, callback: (entry?: IntersectionObserverEntry) => void, disabled: Solid.Accessor<boolean>, cleanupWhenDisabled?: Solid.Accessor<boolean>, )
| 25 | * ``` |
| 26 | */ |
| 27 | export function useIntersectionObserver<T extends Element>( |
| 28 | ref: Solid.Accessor<T | null>, |
| 29 | callback: (entry?: IntersectionObserverEntry) => void, |
| 30 | disabled: Solid.Accessor<boolean>, |
| 31 | cleanupWhenDisabled?: Solid.Accessor<boolean>, |
| 32 | ): Solid.Accessor<IntersectionObserver | null> { |
| 33 | const isIntersectionObserverAvailable = |
| 34 | typeof IntersectionObserver === 'function' |
| 35 | let observerRef: IntersectionObserver | null = null |
| 36 | |
| 37 | Solid.createEffect(() => { |
| 38 | const r = ref() |
| 39 | if (disabled() || !r || !isIntersectionObserverAvailable) { |
| 40 | if (cleanupWhenDisabled?.() ?? true) { |
| 41 | Solid.onCleanup(() => callback()) |
| 42 | } |
| 43 | return |
| 44 | } |
| 45 | |
| 46 | let active = true |
| 47 | const observer = new IntersectionObserver( |
| 48 | (entries) => { |
| 49 | // Queued notifications can arrive after this effect has cleaned up. |
| 50 | if (active) { |
| 51 | callback(entries.pop()) |
| 52 | } |
| 53 | }, |
| 54 | { rootMargin: '100px' }, |
| 55 | ) |
| 56 | |
| 57 | observerRef = observer |
| 58 | observer.observe(r) |
| 59 | |
| 60 | Solid.onCleanup(() => { |
| 61 | active = false |
| 62 | observer.disconnect() |
| 63 | callback() |
| 64 | }) |
| 65 | }) |
| 66 | |
| 67 | return () => observerRef |
| 68 | } |
no test coverage detected