dify/web/app/components/plugins/marketplace/intersection-line/hooks.ts

31 lines
1.0 KiB
TypeScript
Raw Normal View History

2024-10-12 12:46:29 +08:00
import { useEffect } from 'react'
2024-10-12 18:02:24 +08:00
import { useMarketplaceContext } from '@/app/components/plugins/marketplace/context'
2024-10-12 12:46:29 +08:00
export const useScrollIntersection = (
anchorRef: React.RefObject<HTMLDivElement>,
2024-12-05 14:54:04 +08:00
intersectionContainerId = 'marketplace-container',
2024-10-12 12:46:29 +08:00
) => {
2024-10-12 18:02:24 +08:00
const intersected = useMarketplaceContext(v => v.intersected)
const setIntersected = useMarketplaceContext(v => v.setIntersected)
2024-10-12 12:46:29 +08:00
useEffect(() => {
2024-12-05 14:54:04 +08:00
const container = document.getElementById(intersectionContainerId)
2024-10-12 12:46:29 +08:00
let observer: IntersectionObserver | undefined
2024-11-07 15:06:55 +08:00
if (container && anchorRef.current) {
2024-10-12 12:46:29 +08:00
observer = new IntersectionObserver((entries) => {
2024-10-12 16:34:02 +08:00
const isIntersecting = entries[0].isIntersecting
2024-10-12 18:02:24 +08:00
if (isIntersecting && !intersected)
setIntersected(true)
if (!isIntersecting && intersected)
setIntersected(false)
2024-10-12 12:46:29 +08:00
}, {
2024-11-07 15:06:55 +08:00
root: container,
2024-10-12 12:46:29 +08:00
})
observer.observe(anchorRef.current)
}
return () => observer?.disconnect()
2024-12-05 14:54:04 +08:00
}, [anchorRef, intersected, setIntersected, intersectionContainerId])
2024-10-12 12:46:29 +08:00
}