mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
at schema-errors 80 lines 2.1 kB view raw
1import React from 'react' 2import {createClient} from '@segment/analytics-react' 3import {sha256} from 'js-sha256' 4import {Browser} from 'sentry-expo' 5 6import {ScreenPropertiesMap, TrackPropertiesMap} from './types' 7import {useSession, SessionAccount} from '#/state/session' 8import {logger} from '#/logger' 9 10type SegmentClient = ReturnType<typeof createClient> 11 12// Delay creating until first actual use. 13let segmentClient: SegmentClient | null = null 14function getClient(): SegmentClient { 15 if (!segmentClient) { 16 segmentClient = createClient( 17 { 18 writeKey: '8I6DsgfiSLuoONyaunGoiQM7A6y2ybdI', 19 }, 20 { 21 integrations: { 22 'Segment.io': { 23 apiHost: 'api.events.bsky.app/v1', 24 }, 25 }, 26 }, 27 ) 28 } 29 return segmentClient 30} 31 32export const track = async <E extends keyof TrackPropertiesMap>( 33 event: E, 34 properties?: TrackPropertiesMap[E], 35) => { 36 await getClient().track(event, properties) 37} 38 39export function useAnalytics() { 40 const {hasSession} = useSession() 41 42 return React.useMemo(() => { 43 if (hasSession) { 44 return { 45 async screen<E extends keyof ScreenPropertiesMap>( 46 event: E, 47 properties?: ScreenPropertiesMap[E], 48 ) { 49 await getClient().screen(event, properties) 50 }, 51 async track<E extends keyof TrackPropertiesMap>( 52 event: E, 53 properties?: TrackPropertiesMap[E], 54 ) { 55 await getClient().track(event, properties) 56 }, 57 } 58 } 59 // dont send analytics pings for anonymous users 60 return { 61 screen: async () => {}, 62 track: async () => {}, 63 } 64 }, [hasSession]) 65} 66 67export function init(account: SessionAccount | undefined) { 68 if (account) { 69 const client = getClient() 70 if (account.did) { 71 const did_hashed = sha256(account.did) 72 client.identify(did_hashed, {did_hashed}) 73 Browser.setUser({id: did_hashed}) 74 logger.debug('Ping w/hash') 75 } else { 76 logger.debug('Ping w/o hash') 77 client.identify() 78 } 79 } 80}