-
Notifications
You must be signed in to change notification settings - Fork 683
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add intersection observer to homepage sections (#2361)
- Loading branch information
1 parent
74f906d
commit cb8365a
Showing
2 changed files
with
87 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import { useEffect } from 'react' | ||
import { HomepageView } from '../../modules/ui/asset/homepage/types' | ||
|
||
type IntersectionObserverProps = { | ||
refs: Map<HomepageView, HTMLDivElement> | ||
onIntersect: (view: HomepageView) => void | ||
options?: IntersectionObserverInit | ||
} | ||
|
||
export const useIntersectionObserver = ({ refs, onIntersect, options = {} }: IntersectionObserverProps) => { | ||
useEffect(() => { | ||
// Keep track of which sections have been loaded | ||
const loadedSections = new Set<HomepageView>() | ||
|
||
const observer = new IntersectionObserver( | ||
entries => { | ||
entries.forEach(entry => { | ||
// Find which view this element corresponds to | ||
const view = Array.from(refs.entries()).find(([_, element]) => element === entry.target)?.[0] | ||
|
||
if (view && entry.isIntersecting && !loadedSections.has(view)) { | ||
loadedSections.add(view) | ||
onIntersect(view) | ||
} | ||
}) | ||
}, | ||
{ | ||
rootMargin: '100px', | ||
threshold: 0.1, | ||
...options | ||
} | ||
) | ||
|
||
// Observe all section refs | ||
refs.forEach(element => { | ||
observer.observe(element) | ||
}) | ||
|
||
return () => { | ||
observer.disconnect() | ||
} | ||
}, [refs, onIntersect, options]) | ||
} |