|
| 1 | +import type { RegistryScriptInput } from '#nuxt-scripts/types' |
| 2 | +import { useRegistryScript } from '../utils' |
| 3 | +import { MixpanelAnalyticsOptions } from './schemas' |
| 4 | + |
| 5 | +export { MixpanelAnalyticsOptions } |
| 6 | + |
| 7 | +export type MixpanelAnalyticsInput = RegistryScriptInput<typeof MixpanelAnalyticsOptions> |
| 8 | + |
| 9 | +export interface MixpanelAnalyticsApi { |
| 10 | + mixpanel: { |
| 11 | + track: (event: string, properties?: Record<string, any>) => void |
| 12 | + identify: (distinctId: string) => void |
| 13 | + reset: () => void |
| 14 | + people: { |
| 15 | + set: (properties: Record<string, any>) => void |
| 16 | + } |
| 17 | + register: (properties: Record<string, any>) => void |
| 18 | + init: (token: string, config?: Record<string, any>) => void |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +declare global { |
| 23 | + interface Window { |
| 24 | + mixpanel: MixpanelAnalyticsApi['mixpanel'] |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +const methods = ['track', 'identify', 'reset', 'register'] as const |
| 29 | +const peopleMethods = ['set'] as const |
| 30 | + |
| 31 | +export function useScriptMixpanelAnalytics<T extends MixpanelAnalyticsApi>(_options?: MixpanelAnalyticsInput) { |
| 32 | + return useRegistryScript<T, typeof MixpanelAnalyticsOptions>('mixpanelAnalytics', (options) => { |
| 33 | + return { |
| 34 | + scriptInput: { |
| 35 | + src: 'https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js', |
| 36 | + }, |
| 37 | + schema: import.meta.dev ? MixpanelAnalyticsOptions : undefined, |
| 38 | + scriptOptions: { |
| 39 | + use() { |
| 40 | + return { |
| 41 | + mixpanel: window.mixpanel, |
| 42 | + } |
| 43 | + }, |
| 44 | + }, |
| 45 | + clientInit: import.meta.server |
| 46 | + ? undefined |
| 47 | + : () => { |
| 48 | + const mp = (window.mixpanel = (window.mixpanel || []) as any) |
| 49 | + if (!mp.__SV) { |
| 50 | + mp.__SV = 1.2 |
| 51 | + mp._i = mp._i || [] |
| 52 | + |
| 53 | + mp.init = (token: string, config?: Record<string, any>, name = 'mixpanel') => { |
| 54 | + const target = name === 'mixpanel' ? mp : (mp[name] = []) |
| 55 | + target.people = target.people || [] |
| 56 | + for (const method of methods) { |
| 57 | + target[method] = (...args: any[]) => { |
| 58 | + target.push([method, ...args]) |
| 59 | + } |
| 60 | + } |
| 61 | + for (const method of peopleMethods) { |
| 62 | + target.people[method] = (...args: any[]) => { |
| 63 | + target.push([`people.${method}`, ...args]) |
| 64 | + } |
| 65 | + } |
| 66 | + mp._i.push([token, config, name]) |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + if (options?.token) |
| 71 | + mp.init(options.token) |
| 72 | + }, |
| 73 | + } |
| 74 | + }, _options) |
| 75 | +} |
0 commit comments