react-page-tracker
Version:
A lightweight, zero-dependency library providing accurate navigation tracking, fixed document.referrer value, and complete history support for React frameworks.
2 lines (1 loc) • 2.19 kB
JavaScript
;"use client";import{useEffect as T,useRef as u}from"react";import{pageTrackerStore as E}from"./page-tracker-store";const d=!1;export const usePageTrackerHandler=({enableStrictModeHandler:e})=>{const{initStrictModeDetector:n,strictModeDetector:c}=h({enableStrictModeHandler:e}),t=u(0),r=u(1);T(()=>{P(),n();const A=_=>{const o=_.state,s=o.__REACT_PAGE_TRACKER_INTERNAL__?.pageIndex??0,i=t.current>s?"back":"forward";i==="forward"?t.current++:t.current=s??0;const a=[...o.__REACT_PAGE_TRACKER_INTERNAL__?.pageHistory||[]];E.setState({pageIndex:t.current,isFirstPage:t.current===0,isLastPage:a.length===r.current,referrer:o.__REACT_PAGE_TRACKER_INTERNAL__?.referrer??"",pageHistory:a,pageHistoryLength:r.current,pageEvent:i})},f=window.onpopstate,g=history.pushState.bind(history);return window.onpopstate=A,history.pushState=(_,o,s)=>{if(c())return g(_,o,s);const i=(history.state.__REACT_PAGE_TRACKER_INTERNAL__?.pageIndex??0)+1;t.current=i;const a=E.getImmutablePageHistory();a.push(s),r.current=a.length;const p={pageIndex:i,referrer:window.location.href,pageHistory:a,pageHistoryLength:r.current},R={..._,__REACT_PAGE_TRACKER_INTERNAL__:{...p}};return E.setState({...p,isFirstPage:!1,isLastPage:!0,pageEvent:"push"}),I(`pushState: stateWithPageInfo.pageIndex -->${R.__REACT_PAGE_TRACKER_INTERNAL__.pageIndex} ,pageIndex.current --> ${t.current} referrer -->${R.__REACT_PAGE_TRACKER_INTERNAL__.referrer}`),g(R,o||"",s||"")},()=>{window.onpopstate=f,history.pushState=g}},[])};const h=({enableStrictModeHandler:e})=>{const n=u(0),c=u(!1),t=()=>!!history.state.__PRIVATE_NEXTJS_INTERNALS_TREE,r=()=>(n.current++,c.current?n.current%2===0:!1);return{initStrictModeDetector:()=>{n.current++,n.current===2&&(c.current=!0)},strictModeDetector:()=>e===void 0?t()?r():!1:e?r():!1}},I=e=>{d&&console.debug(`[DEBUG PAGE CHANGE] ${e}`)},P=()=>{const e={__REACT_PAGE_TRACKER_INTERNAL__:{pageIndex:0,referrer:document.referrer,pageHistory:[location.href.replace(location.origin,"")],pageHistoryLength:1}};typeof history.state=="object"&&history.state!==null?history.replaceState({...history.state,...e},location.href):history.replaceState(e,""),E.setState(e.__REACT_PAGE_TRACKER_INTERNAL__)};