mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import React from 'react'
2import {
3 createClient,
4 AnalyticsProvider,
5 useAnalytics as useAnalyticsOrig,
6} from '@segment/analytics-react'
7import {RootStoreModel} from 'state/models/root-store'
8import {useStores} from 'state/models/root-store'
9import {sha256} from 'js-sha256'
10
11const segmentClient = createClient(
12 {
13 writeKey: '8I6DsgfiSLuoONyaunGoiQM7A6y2ybdI',
14 },
15 {
16 integrations: {
17 'Segment.io': {
18 apiHost: 'api.evt.bsky.app/v1',
19 },
20 },
21 },
22)
23export const track = segmentClient?.track?.bind?.(segmentClient)
24
25export function useAnalytics() {
26 const store = useStores()
27 const methods = useAnalyticsOrig()
28 return React.useMemo(() => {
29 if (store.session.hasSession) {
30 return methods
31 }
32 // dont send analytics pings for anonymous users
33 return {
34 screen: () => {},
35 track: () => {},
36 identify: () => {},
37 flush: () => {},
38 group: () => {},
39 alias: () => {},
40 reset: () => {},
41 }
42 }, [store, methods])
43}
44
45export function init(store: RootStoreModel) {
46 store.onSessionLoaded(() => {
47 const sess = store.session.currentSession
48 if (sess) {
49 if (sess.email) {
50 store.log.debug('Ping w/hash')
51 const email_hashed = sha256(sess.email)
52 segmentClient.identify(email_hashed, {email_hashed})
53 } else {
54 store.log.debug('Ping w/o hash')
55 segmentClient.identify()
56 }
57 }
58 })
59}
60
61export function Provider({children}: React.PropsWithChildren<{}>) {
62 return (
63 <AnalyticsProvider client={segmentClient}>{children}</AnalyticsProvider>
64 )
65}