@@ -3,11 +3,23 @@ import { Nullable } from '@constructor-io/constructorio-client-javascript/lib/ty
33import ConstructorIO from '@constructor-io/constructorio-client-javascript' ;
44import { Section } from '../types' ;
55
6+ /**
7+ * Custom hook that observes the visibility of recommendation sections and calls trackRecommendationView event.
8+ * This is done by using the IntersectionObserver API to observe the visibility of each recommendation section.
9+ * That is done by passing the ref of each recommendation section to the IntersectionObserver.
10+ * The refs are either passed by the user in section config or generated by the library by default.
11+ * Either way the refs are stored in the sections array.
12+ *
13+ * @param menuIsOpen - A boolean indicating whether the menu is open.
14+ * @param sections - An array of sections to observe.
15+ * @param constructorIO - An instance of the ConstructorIO client.
16+ * @param trackRecommendationView - A callback function to track the recommendation view event.
17+ */
618function useRecommendationsObserver (
719 menuIsOpen : boolean ,
820 sections : Section [ ] ,
921 constructorIO : Nullable < ConstructorIO > ,
10- callback : (
22+ trackRecommendationView : (
1123 target : HTMLElement ,
1224 sections : Section [ ] ,
1325 constructorIO : Nullable < ConstructorIO >
@@ -19,21 +31,20 @@ function useRecommendationsObserver(
1931 . map ( ( section ) => section . ref ) ;
2032
2133 useEffect ( ( ) => {
22- const observer = new IntersectionObserver (
23- ( entries ) => {
24- // For each section, check if it's intersecting
25- entries . forEach ( ( entry ) => {
26- if ( entry . isIntersecting ) {
27- // Call the callback, which will be trackRecommendationView in our case
28- callback ( entry . target as HTMLElement , sections , constructorIO ) ;
29- }
30- } ) ;
31- } ,
32- {
33- root : null ,
34- threshold : 0.1 ,
35- }
36- ) ;
34+ const intersectionObserverOptions = {
35+ // Root element is the bounding target for the observer to observe. If null, then the document viewport is used.
36+ root : null ,
37+ // 0.1 indicate the callback should be called when that proportion of the target is visible (e.g., 10% visible).
38+ threshold : 0.1 ,
39+ } ;
40+ const observer = new IntersectionObserver ( ( entries ) => {
41+ // For each section, check if it's intersecting
42+ entries . forEach ( ( entry ) => {
43+ if ( entry . isIntersecting ) {
44+ trackRecommendationView ( entry . target as HTMLElement , sections , constructorIO ) ;
45+ }
46+ } ) ;
47+ } , intersectionObserverOptions ) ;
3748
3849 // Observe each section
3950 refs . forEach ( ( ref ) => {
0 commit comments