Raw
1 "use client"
2
3 import posthog from "posthog-js"
4 import React, {
5 createContext,
6 useCallback,
7 useContext,
8 useEffect,
9 useState,
10 } from "react"
11 import { useSegmentAnalytics } from "./providers/segment"
12 import { usePostHogAnalytics } from "./providers/posthog"
13 import { useReoDevAnalytics } from "./providers/reo-dev"
14 import { usePathname } from "next/navigation"
15
16 export type ExtraData = {
17 section?: string
18 [key: string]: unknown
19 }
20
21 export type AnalyticsContextType = {
22 track: ({
23 event,
24 instant,
25 }: {
26 event: TrackedEvent
27 instant?: boolean
28 }) => void
29 }
30
31 type Trackers = "segment" | "posthog"
32
33 export type TrackedEvent = {
34 event: string
35 options?: Record<string, unknown>
36 callback?: () => void
37 tracker?: Trackers | Trackers[]
38 }
39
40 const AnalyticsContext = createContext<AnalyticsContextType | null>(null)
41
42 export type AnalyticsProviderProps = {
43 segmentWriteKey?: string
44 reoDevKey?: string
45 children?: React.ReactNode
46 }
47
48 const DEFAULT_TRACKER: Trackers = "posthog"
49
50 export const AnalyticsProvider = ({
51 segmentWriteKey,
52 reoDevKey,
53 children,
54 }: AnalyticsProviderProps) => {
55 useEffect(() => {
56 const getCookie = (name: string) => {
57 const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`))
58 return match ? decodeURIComponent(match[1]) : undefined
59 }
60
61 const userId = getCookie("mc_cloud_user_id")
62 const orgId = getCookie("mc_cloud_org_id")
63
64 if (userId && !posthog._isIdentified()) {
65 posthog.identify(userId)
66 if (orgId) {
67 posthog.group("organization", orgId)
68 }
69 }
70 }, [])
71
72 const [eventsQueue, setEventsQueue] = useState<TrackedEvent[]>([])
73 const { track: trackWithSegment } = useSegmentAnalytics({
74 segmentWriteKey,
75 setEventsQueue,
76 })
77 const { track: trackWithPostHog } = usePostHogAnalytics()
78 useReoDevAnalytics({ reoDevKey })
79 const pathname = usePathname()
80
81 const processEvent = useCallback(
82 async (event: TrackedEvent) => {
83 const trackers = !event.tracker
84 ? [DEFAULT_TRACKER]
85 : Array.isArray(event.tracker)
86 ? event.tracker
87 : [event.tracker]
88
89 event.options = {
90 url: pathname,
91 label: document.title,
92 os: window.navigator.userAgent,
93 ...event.options,
94 }
95
96 await Promise.all(
97 trackers.map(async (tracker) => {
98 switch (tracker) {
99 case "posthog":
100 return trackWithPostHog(event)
101 case "segment":
102 default:
103 return trackWithSegment(event)
104 }
105 })
106 )
107 },
108 [trackWithSegment, trackWithPostHog, pathname]
109 )
110
111 const track = ({ event }: { event: TrackedEvent }) => {
112 // Always queue events - this makes tracking non-blocking
113 setEventsQueue((prevQueue) => [...prevQueue, event])
114
115 // Process event callback immediately
116 // This ensures that the callback is called even if the event is queued
117 event.callback?.()
118 }
119
120 useEffect(() => {
121 if (!eventsQueue.length) {
122 return
123 }
124
125 // Process queue in background without blocking
126 const currentQueue = [...eventsQueue]
127 setEventsQueue([])
128
129 // Process events asynchronously in batches to avoid overwhelming the system
130 const batchSize = 5
131 for (let i = 0; i < currentQueue.length; i += batchSize) {
132 const batch = currentQueue.slice(i, i + batchSize)
133 setTimeout(() => {
134 batch.forEach(processEvent)
135 }, i * 10) // Small delay between batches
136 }
137 }, [eventsQueue, processEvent])
138
139 return (
140 <AnalyticsContext.Provider
141 value={{
142 track,
143 }}
144 >
145 {children}
146 </AnalyticsContext.Provider>
147 )
148 }
149
150 export const useAnalytics = () => {
151 const context = useContext(AnalyticsContext)
152
153 if (!context) {
154 throw new Error("useAnalytics must be used within a AnalyticsProvider")
155 }
156
157 return context
158 }