-
Notifications
You must be signed in to change notification settings - Fork 212
/
use-analytics.ts
68 lines (60 loc) · 1.71 KB
/
use-analytics.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { computed, onMounted } from "vue"
import { useContext } from "@nuxtjs/composition-api"
import type { Events, EventName } from "~/types/analytics"
import { useUiStore } from "~/stores/ui"
import { useFeatureFlagStore } from "~/stores/feature-flag"
import { log } from "~/utils/console"
/**
* The `ctx` parameter must be supplied if using this composable outside the
* bounds of the composition API.
*/
export const useAnalytics = () => {
const { $plausible } = useContext()
const uiStore = useUiStore()
const featureFlagStore = useFeatureFlagStore()
onMounted(() => {
featureFlagStore.syncAnalyticsWithLocalStorage()
})
/**
* the Plausible props that work identically on the server-side and the
* client-side; This excludes props that need `window`.
*/
const isomorphicProps = computed(() => ({
breakpoint: uiStore.breakpoint,
}))
/**
* the Plausible props that work only on the client-side; This only includes
* props that need `window`.
*/
const windowProps = computed(() =>
window
? {
width: window.innerWidth,
height: window.innerHeight,
}
: {}
)
/**
* Send a custom event to Plausible. Mandatory props are automatically merged
* with the event-specific props.
*
* @param name - the name of the event being recorded
* @param payload - the additional information to record about the event
*/
const sendCustomEvent = <T extends EventName>(
name: T,
payload: Events[T]
) => {
log(`Analytics event: ${name}`, payload)
$plausible.trackEvent(name, {
props: {
...isomorphicProps.value,
...windowProps.value,
...payload,
},
})
}
return {
sendCustomEvent,
}
}