|
| 1 | +import * as React from 'react' |
| 2 | +import * as redux from 'react-redux' |
| 3 | +import { useLocation } from 'react-router-dom' |
| 4 | + |
| 5 | +import cfg from 'constants/config' |
| 6 | +import * as Auth from 'containers/Auth' |
| 7 | +import usePrevious from 'utils/usePrevious' |
| 8 | + |
| 9 | +type HsqCommand = |
| 10 | + | ['setPath', string] |
| 11 | + | ['trackPageView'] |
| 12 | + | ['identify', { email: string }] |
| 13 | + |
| 14 | +function hsq(...cmd: HsqCommand[]) { |
| 15 | + // eslint-disable-next-line no-underscore-dangle |
| 16 | + const q = ((window as any)._hsq = (window as any)._hsq || []) |
| 17 | + cmd.forEach((c) => q.push(c)) |
| 18 | +} |
| 19 | + |
| 20 | +function HubSpotTracker() { |
| 21 | + const location = useLocation() |
| 22 | + const email: string | undefined = redux.useSelector(Auth.selectors.email) |
| 23 | + const path = `${location.pathname}${location.search}` |
| 24 | + |
| 25 | + React.useEffect(() => { |
| 26 | + const script = document.createElement('script') |
| 27 | + script.type = 'text/javascript' |
| 28 | + script.id = 'hs-script-loader' |
| 29 | + script.async = true |
| 30 | + script.defer = true |
| 31 | + script.src = `https://js.hs-scripts.com/${cfg.hubspotId}.js` |
| 32 | + document.head.appendChild(script) |
| 33 | + return () => { |
| 34 | + script.remove() |
| 35 | + } |
| 36 | + }, []) |
| 37 | + |
| 38 | + // Track SPA navigations (initial page load is auto-tracked by HubSpot) |
| 39 | + usePrevious(path, (prevPath) => { |
| 40 | + if (prevPath !== undefined && prevPath !== path) { |
| 41 | + hsq(['setPath', path], ['trackPageView']) |
| 42 | + } |
| 43 | + }) |
| 44 | + |
| 45 | + // Identify contact on sign-in |
| 46 | + usePrevious(email, (prevEmail) => { |
| 47 | + if (email && email !== prevEmail) { |
| 48 | + hsq(['identify', { email }], ['trackPageView']) |
| 49 | + } |
| 50 | + }) |
| 51 | + |
| 52 | + return null |
| 53 | +} |
| 54 | + |
| 55 | +export default function HubSpot({ children }: { children?: React.ReactNode }) { |
| 56 | + if (!cfg.hubspotId) return <>{children}</> |
| 57 | + return ( |
| 58 | + <> |
| 59 | + <HubSpotTracker /> |
| 60 | + {children} |
| 61 | + </> |
| 62 | + ) |
| 63 | +} |
0 commit comments