omnivore/packages/web/lib/analytics.ts

60 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-02-11 17:24:33 +00:00
import { UserBasicData } from './networking/queries/useGetViewerQuery'
import { intercomAppID, posthogApiKey, webBaseURL } from './appConfig'
2023-09-13 02:22:45 +00:00
import posthog from 'posthog-js'
2023-10-27 08:13:03 +00:00
const userInfo = (
user: UserBasicData
): { user_id: string; name: string; user_hash: string } => {
2022-02-11 17:24:33 +00:00
return {
user_id: user.id,
name: user.name,
2023-10-27 08:13:03 +00:00
user_hash: user.intercomHash,
2022-02-11 17:24:33 +00:00
}
}
const initAnalytics = (user?: UserBasicData): void => {
window.intercomSettings = {
app_id: intercomAppID ?? '',
hide_default_launcher: true,
vertical_padding: 120,
custom_launcher_selector: '.custom-intercom-launcher',
}
if (posthogApiKey) {
posthog.init(posthogApiKey, {
2023-09-13 05:23:26 +00:00
api_host: `${webBaseURL}/collect`,
2023-09-13 06:05:35 +00:00
autocapture: false,
disable_session_recording: false,
advanced_disable_decide: true,
advanced_disable_feature_flags: true,
advanced_disable_toolbar_metrics: true,
})
}
2022-02-11 17:24:33 +00:00
if (user) {
window.Intercom('boot', userInfo(user))
}
window.ANALYTICS_INITIALIZED = true
}
export const setupAnalytics = (user?: UserBasicData): void => {
2023-09-13 02:22:45 +00:00
if (!intercomAppID || !window.Intercom) {
return
}
if (!window.ANALYTICS_INITIALIZED) {
initAnalytics(user)
}
2022-02-11 17:24:33 +00:00
if (user) {
window.Intercom('update', userInfo(user))
2023-09-13 02:22:45 +00:00
posthog.identify(user.id, {
name: user.name,
username: user.profile.username,
})
2022-02-11 17:24:33 +00:00
}
}
export const deinitAnalytics = (): void => {
if (posthog && posthogApiKey) {
posthog.reset(true)
}
}