Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

filip(feat): add analytics and osano consent #635

Merged
merged 4 commits into from
Jul 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion docusaurus.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,20 @@ const config: Config = {
locales: ['en'],
},

customFields: {
posthogApiKey: 'phc_GB82t5tMT4EVKUpOCPTOuhezu3trmJUCGtSnFHB3fK3',
posthogApiHost: 'https://eu.posthog.com',
posthogProjectId: 11673,
},

scripts: [
{
// GDPR
src: 'https://cmp.osano.com/AzZXI3TYiFWNB5yus/b2ba081d-c77c-4db8-bbf7-46c47e1d7f80/osano.js',
async: false,
},
],

plugins: [
[
'@cmfcmf/docusaurus-search-local',
Expand Down Expand Up @@ -69,7 +83,10 @@ const config: Config = {
routeBasePath: '/',
},
theme: {
customCss: './src/css/custom.css',
customCss: [
require.resolve('./src/css/custom.css'),
require.resolve('./src/css/osano.css'),
],
},
} satisfies Preset.Options,
],
Expand Down
97 changes: 97 additions & 0 deletions src/analytics/AnalyticsContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import React, {
PropsWithChildren,
createContext,
useCallback,
useEffect,
useState,
} from 'react'
import { PostHog, PostHogProvider } from 'posthog-js/react'
import useDocusaurusContext from '@docusaurus/useDocusaurusContext'
import { posthog } from 'posthog-js'
import dayjs from 'dayjs'
import TrackRoute from './TrackRoute'
import useHasConsent, { ConsentType } from './useHasConsent'

export const AnalyticsContext = createContext<
(eventName: string, eventProps?: Record<string, unknown>) => void
>(() => {})

export function AnalyticsProvider({ children }: PropsWithChildren) {
const {
siteConfig: { customFields },
} = useDocusaurusContext()
const [client, setClient] = useState<PostHog | undefined>()
const analyticsAccepted = useHasConsent(ConsentType.ANALYTICS)

const baseEventProps = useCallback(
() => ({
sent_at_local: dayjs().format(),
posthog_project_id: customFields.posthogProjectId,
}),
[customFields.posthogProjectId],
)

const capture = useCallback(
(
eventName: string,
eventProperties: Record<string | number, unknown> = {},
) => {
client?.capture(eventName, {
...baseEventProps(),
...eventProperties,
})
},
[client, baseEventProps],
)

useEffect(() => {
const { posthogApiKey, posthogApiHost } = customFields
const turnOn =
analyticsAccepted === true &&
typeof posthogApiKey === 'string' &&
posthogApiKey &&
typeof posthogApiHost === 'string' &&
posthogApiHost

setClient((oldClient) => {
if (turnOn) {
const client =
oldClient ??
(posthog.init(posthogApiKey ?? '', {
api_host: posthogApiHost,
capture_pageleave: false,
capture_pageview: false,
}) as PostHog)

// clear localStorage state that might have been set by previous clients
client.clear_opt_in_out_capturing()

// we got consent, start capturing
client.opt_in_capturing({
capture_properties: baseEventProps(),
})
// calling a private function as a fix for bug https://github.com/PostHog/posthog-js/issues/336
client._start_queue_if_opted_in()

return client
} else {
oldClient?.opt_out_capturing()
return undefined
}
})
}, [
customFields.posthogApiKey,
customFields.posthogApiHost,
analyticsAccepted,
baseEventProps,
])

return (
<PostHogProvider client={client}>
<AnalyticsContext.Provider value={capture}>
<TrackRoute />
{children}
</AnalyticsContext.Provider>
</PostHogProvider>
)
}
14 changes: 14 additions & 0 deletions src/analytics/TrackRoute.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { useLocation } from '@docusaurus/router'
import React, { useContext, useEffect } from 'react'
import { AnalyticsContext } from './AnalyticsContext'

export default function TrackRoute() {
const location = useLocation()
const capture = useContext(AnalyticsContext)

useEffect(() => {
capture('$pageview')
}, [capture, location.pathname, location.search])

return null
}
41 changes: 41 additions & 0 deletions src/analytics/osano.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
export enum OsanoConsentType {
ESSENTIAL = 'ESSENTIAL',
STORAGE = 'STORAGE',
MARKETING = 'MARKETING',
PERSONALIZATION = 'PERSONALIZATION',
ANALYTICS = 'ANALYTICS',
OPT_OUT = 'OPT_OUT',
}

export enum OsanoConsentDecision {
ACCEPT = 'ACCEPT',
DENY = 'DENY',
}

export type OsanoConsentMap = Record<OsanoConsentType, OsanoConsentDecision>

export enum OsanoEvent {
CONSENT_SAVED = 'osano-cm-consent-saved',
}

export type OsanoEventCallback = {
[OsanoEvent.CONSENT_SAVED]: (changed: Partial<OsanoConsentMap>) => void
}

declare global {
interface Osano {
cm?: {
getConsent(): OsanoConsentMap
addEventListener: <T extends OsanoEvent>(
ev: T,
callback: OsanoEventCallback[T],
) => void
removeEventListener: <T extends OsanoEvent>(
ev: T,
callback: OsanoEventCallback[T],
) => void
}
}

var Osano: Osano | undefined
}
43 changes: 43 additions & 0 deletions src/analytics/useHasConsent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { useEffect, useState } from 'react'
import {
OsanoConsentDecision,
OsanoConsentType,
OsanoEvent,
OsanoEventCallback,
} from './osano'

export { OsanoConsentType as ConsentType }

export default function useHasConsent(
type: OsanoConsentType,
): boolean | undefined {
const initialConsent =
typeof Osano !== 'undefined'
? Osano.cm?.getConsent()[type] === OsanoConsentDecision.ACCEPT
: undefined

const [state, setState] = useState<boolean | undefined>(initialConsent)

useEffect(() => {
const cm = typeof Osano !== 'undefined' ? Osano.cm : undefined

if (!cm) {
return
}

setState(cm.getConsent()[type] === OsanoConsentDecision.ACCEPT)

const handler: OsanoEventCallback[OsanoEvent.CONSENT_SAVED] = (changed) => {
if (type in changed) {
setState(changed[type] === OsanoConsentDecision.ACCEPT)
}
}

cm.addEventListener(OsanoEvent.CONSENT_SAVED, handler)
return () => {
cm.removeEventListener(OsanoEvent.CONSENT_SAVED, handler)
}
}, [type])

return state
}
Loading
Loading