1
0

AnalyticsManager.tsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import ls from '@livesession/sdk'
  2. import { FC, useCallback, useEffect } from 'react'
  3. import ReactGA from 'react-ga'
  4. import { useLocation } from 'react-router-dom'
  5. import { atlasConfig } from '@/config'
  6. import { BUILD_ENV } from '@/config/env'
  7. import { usePersonalDataStore } from '@/providers/personalData'
  8. export const AnalyticsManager: FC = () => {
  9. const cookiesAccepted = usePersonalDataStore((state) => state.cookiesAccepted)
  10. const analyticsEnabled = BUILD_ENV === 'production' && cookiesAccepted
  11. const location = useLocation()
  12. const initUsersnap = useCallback(() => {
  13. if (!atlasConfig.analytics.usersnap?.id) return
  14. // @ts-ignore custom prop required by usersnap
  15. window.onUsersnapCXLoad = function (api) {
  16. api.init()
  17. // @ts-ignore custom prop required by usersnap
  18. window.Usersnap = api
  19. }
  20. const script = document.createElement('script')
  21. script.defer = true
  22. script.src = `https://widget.usersnap.com/global/load/${atlasConfig.analytics.usersnap.id}?onload=onUsersnapCXLoad`
  23. document.getElementsByTagName('head')[0].appendChild(script)
  24. }, [])
  25. const initLiveSession = useCallback(() => {
  26. if (!atlasConfig.analytics.livesession?.id) return
  27. ls.init(atlasConfig.analytics.livesession.id, {
  28. keystrokes: true,
  29. ...(atlasConfig.analytics.livesession.rootHostname
  30. ? { rootHostname: atlasConfig.analytics.livesession.rootHostname }
  31. : {}),
  32. })
  33. ls.newPageView()
  34. }, [])
  35. const initGA = useCallback(() => {
  36. if (!atlasConfig.analytics.GA?.id) return
  37. ReactGA.initialize(atlasConfig.analytics.GA.id)
  38. }, [])
  39. // initialize livesession
  40. useEffect(() => {
  41. if (!analyticsEnabled) return
  42. initLiveSession()
  43. }, [analyticsEnabled, initLiveSession])
  44. // initialize usersnap
  45. useEffect(() => {
  46. if (!analyticsEnabled) return
  47. initUsersnap()
  48. }, [analyticsEnabled, initUsersnap])
  49. //initialize Google Analytics
  50. useEffect(() => {
  51. if (!analyticsEnabled) return
  52. initGA()
  53. }, [analyticsEnabled, initGA])
  54. //track pageview in GA
  55. useEffect(() => {
  56. if (!analyticsEnabled || !atlasConfig.analytics.GA?.id) {
  57. return
  58. }
  59. ReactGA.pageview(location.pathname)
  60. }, [location.pathname, analyticsEnabled])
  61. return null
  62. }