wwf
3 天以前 a430284aa21e3ae1f0d5654e55b2ad2852519cc2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { useEffect } from 'react'
import { useMarketplaceContext } from '@/app/components/plugins/marketplace/context'
 
export const useScrollIntersection = (
  anchorRef: React.RefObject<HTMLDivElement>,
  intersectionContainerId = 'marketplace-container',
) => {
  const intersected = useMarketplaceContext(v => v.intersected)
  const setIntersected = useMarketplaceContext(v => v.setIntersected)
 
  useEffect(() => {
    const container = document.getElementById(intersectionContainerId)
    let observer: IntersectionObserver | undefined
    if (container && anchorRef.current) {
      observer = new IntersectionObserver((entries) => {
        const isIntersecting = entries[0].isIntersecting
 
        if (isIntersecting && !intersected)
          setIntersected(true)
 
        if (!isIntersecting && intersected)
          setIntersected(false)
      }, {
        root: container,
      })
      observer.observe(anchorRef.current)
    }
    return () => observer?.disconnect()
  }, [anchorRef, intersected, setIntersected, intersectionContainerId])
}