Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 21, 03:37 UTC
| 1 | 'use client'; |
| 2 | |
| 3 | import posthog from 'posthog-js'; |
| 4 | import { PostHogProvider as PHProvider, usePostHog } from 'posthog-js/react'; |
| 5 | import { Suspense, useEffect, useState } from 'react'; |
| 6 | import { usePathname, useSearchParams } from 'next/navigation'; |
| 7 | |
| 8 | export function getPostHogPageViewUrl( |
| 9 | origin: string, |
| 10 | pathname: string, |
| 11 | searchParams: URLSearchParams, |
| 12 | ): string { |
| 13 | const visibleParams = new URLSearchParams(searchParams.toString()); |
| 14 | if (pathname === '/kb/search') visibleParams.delete('q'); |
| 15 | const queryString = visibleParams.toString(); |
| 16 | return `${origin}${pathname}${queryString ? `?${queryString}` : ''}`; |
| 17 | } |
| 18 | |
| 19 | export function PostHogProvider({ children }: { children: React.ReactNode }) { |
| 20 | const [isInitialized, setIsInitialized] = useState(false); |
| 21 | |
| 22 | useEffect(() => { |
| 23 | if (typeof window !== 'undefined' && process.env.NEXT_PUBLIC_POSTHOG_KEY) { |
| 24 | // Already loaded (e.g., HMR, StrictMode remount) |
| 25 | if (posthog.__loaded) { |
| 26 | setIsInitialized(true); |
| 27 | return; |
| 28 | } |
| 29 | |
| 30 | posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, { |
| 31 | api_host: |
| 32 | process.env.NEXT_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com', |
| 33 | person_profiles: 'identified_only', |
| 34 | capture_pageview: false, // We capture manually below |
| 35 | capture_pageleave: true, |
| 36 | loaded: () => { |
| 37 | setIsInitialized(true); |
| 38 | }, |
| 39 | }); |
| 40 | } |
| 41 | }, []); |
| 42 | |
| 43 | if (!process.env.NEXT_PUBLIC_POSTHOG_KEY) { |
| 44 | return <>{children}</>; |
| 45 | } |
| 46 | |
| 47 | return ( |
| 48 | <PHProvider client={posthog}> |
| 49 | {isInitialized && <SuspendedPostHogPageView />} |
| 50 | {children} |
| 51 | </PHProvider> |
| 52 | ); |
| 53 | } |
| 54 | |
| 55 | function PostHogPageView() { |
| 56 | const pathname = usePathname(); |
| 57 | const searchParams = useSearchParams(); |
| 58 | const posthog = usePostHog(); |
| 59 | |
| 60 | useEffect(() => { |
| 61 | if (pathname && posthog) { |
| 62 | const url = getPostHogPageViewUrl(window.origin, pathname, searchParams); |
| 63 | posthog.capture('$pageview', { $current_url: url }); |
| 64 | } |
| 65 | }, [pathname, searchParams, posthog]); |
| 66 | |
| 67 | return null; |
| 68 | } |
| 69 | |
| 70 | function SuspendedPostHogPageView() { |
| 71 | return ( |
| 72 | <Suspense fallback={null}> |
| 73 | <PostHogPageView /> |
| 74 | </Suspense> |
| 75 | ); |
| 76 | } |