22
33import posthog from "posthog-js" ;
44import { PostHogProvider as PHProvider } from "posthog-js/react" ;
5- import { useEffect , useState } from "react" ;
5+ import { useEffect , useState , useRef } from "react" ;
66import { CookieConsent , getConsentStatus , type ConsentStatus } from "./CookieConsent" ;
77
88function initPostHog ( ) {
@@ -25,9 +25,39 @@ function initPostHog() {
2525 }
2626}
2727
28+ function useScrollDepthTracking ( enabled : boolean ) {
29+ const trackedDepths = useRef < Set < number > > ( new Set ( ) ) ;
30+
31+ useEffect ( ( ) => {
32+ if ( ! enabled || typeof window === "undefined" ) return ;
33+
34+ const handleScroll = ( ) => {
35+ const scrollTop = window . scrollY ;
36+ const docHeight = document . documentElement . scrollHeight - window . innerHeight ;
37+ if ( docHeight <= 0 ) return ;
38+
39+ const scrollPercent = Math . round ( ( scrollTop / docHeight ) * 100 ) ;
40+ const thresholds = [ 25 , 50 , 75 , 100 ] ;
41+
42+ for ( const threshold of thresholds ) {
43+ if ( scrollPercent >= threshold && ! trackedDepths . current . has ( threshold ) ) {
44+ trackedDepths . current . add ( threshold ) ;
45+ posthog . capture ( "scroll_depth" , { depth : threshold } ) ;
46+ }
47+ }
48+ } ;
49+
50+ window . addEventListener ( "scroll" , handleScroll , { passive : true } ) ;
51+ return ( ) => window . removeEventListener ( "scroll" , handleScroll ) ;
52+ } , [ enabled ] ) ;
53+ }
54+
2855export function PostHogProvider ( { children } : { children : React . ReactNode } ) {
2956 const [ consentStatus , setConsentStatus ] = useState < ConsentStatus > ( "pending" ) ;
3057
58+ // Track scroll depth when consent is granted
59+ useScrollDepthTracking ( consentStatus === "granted" ) ;
60+
3161 useEffect ( ( ) => {
3262 const status = getConsentStatus ( ) ;
3363 setConsentStatus ( status ) ;
0 commit comments