Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 38 additions & 18 deletions strategies/useNearScreen.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,47 @@
import {useState, useEffect} from 'react'

const targetCallbacks = new WeakMap()
const observerP =
typeof window !== 'undefined' &&
Promise.resolve(
typeof window.IntersectionObserver === 'undefined' &&
import('intersection-observer')
).then(
() =>
new window.IntersectionObserver(entries => {
entries
.filter(e => e.isIntersecting)
.map(e => targetCallbacks.get(e.target))
.filter(Boolean)
.forEach(cb => cb())
})
)

function whenIntersecting(target, cb) {
function unsubscribe() {
observerP.then(observer => {
observer.unobserve(target)
targetCallbacks.delete(target)
})
}

observerP.then(observer => {
observer.observe(target)
targetCallbacks.set(target, () => {
unsubscribe()
cb()
})
})

return unsubscribe
}

export const useNearScreen = ({ref}) => {
const [show, setShow] = useState(false)

useEffect(
function() {
if (!ref || !ref.current) return

Promise.resolve(
typeof window.IntersectionObserver !== 'undefined'
? window.IntersectionObserver
: import('intersection-observer')
).then(() => {
const observer = new window.IntersectionObserver(function(entries) {
const {isIntersecting} = entries[0]
if (isIntersecting) {
setShow(true)
observer.disconnect()
}
})
observer.observe(ref.current)
})
},
() =>
ref && ref.current && whenIntersecting(ref.current, () => setShow(true)),
[ref]
)

Expand Down