Open History to see the last commit
1import * as Solid from 'solid-js'
2β
3/**
4 * Observe a Link's element while it preloads on `'viewport'`: `callback`
5 * receives each intersection entry. Whenever the element or preload mode
6 * changes, and on cleanup, a preloading Link gets `callback()` so it can
7 * cancel a pending preload.
8 */
9export 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}