( ref: Solid.Accessor<T | null>, callback: (entry?: IntersectionObserverEntry) => void, preload: Solid.Accessor<unknown>, )
| 7 | * cancel a pending preload. |
| 8 | */ |
| 9 | export function useIntersectionObserver<T extends Element>( |
| 10 | ref: Solid.Accessor<T | null>, |
| 11 | callback: (entry?: IntersectionObserverEntry) => void, |
| 12 | preload: Solid.Accessor<unknown>, |
| 13 | ): void { |
| 14 | Solid.createEffect(() => { |
| 15 | const r = ref() |
| 16 | const mode = preload() |
| 17 | if ( |
| 18 | mode === 'viewport' && |
| 19 | r && |
| 20 | typeof IntersectionObserver === 'function' |
| 21 | ) { |
| 22 | let active = true |
| 23 | const observer = new IntersectionObserver( |
| 24 | (entries) => { |
| 25 | // Queued notifications can arrive after this effect has cleaned up. |
| 26 | if (active) { |
| 27 | callback(entries.pop()) |
| 28 | } |
| 29 | }, |
| 30 | { rootMargin: '100px' }, |
| 31 | ) |
| 32 | observer.observe(r) |
| 33 | Solid.onCleanup(() => { |
| 34 | active = false |
| 35 | observer.disconnect() |
| 36 | callback() |
| 37 | }) |
| 38 | } else if (mode) { |
| 39 | // Intent preloading still needs timer cleanup without an observer. |
| 40 | Solid.onCleanup(() => callback()) |
| 41 | } |
| 42 | }) |
| 43 | } |
no test coverage detected