|
| 1 | +import { isBrowser } from '@bassist/utils' |
| 2 | +import { VueAnalytics } from '../analytics' |
| 3 | +import { getMajorVersion, getGlobalProperty } from '../utils' |
| 4 | +import type { Platform } from '@web-analytics/core' |
| 5 | +import type { |
| 6 | + CreateVitePressAnalyticsInstanceOptions, |
| 7 | + RegisterProviderOptions, |
| 8 | + VueInstance, |
| 9 | +} from '../types' |
| 10 | + |
| 11 | +function registerProvider<P extends Platform>({ |
| 12 | + analytics, |
| 13 | + platform, |
| 14 | +}: RegisterProviderOptions<P>) { |
| 15 | + return ( |
| 16 | + app: VueInstance, |
| 17 | + options: CreateVitePressAnalyticsInstanceOptions |
| 18 | + ) => { |
| 19 | + if (!isBrowser) return |
| 20 | + |
| 21 | + // Synchronize the real properties with the prototype to the exported instance |
| 22 | + const analyticsInstance = new VueAnalytics<P>({ platform, ...options }) |
| 23 | + for (const key in analyticsInstance) { |
| 24 | + if (Object.prototype.hasOwnProperty.call(analyticsInstance, key)) { |
| 25 | + // @ts-ignore |
| 26 | + analytics[key] = analyticsInstance[key] |
| 27 | + } |
| 28 | + } |
| 29 | + const prototype = Object.getPrototypeOf(analyticsInstance) |
| 30 | + Object.setPrototypeOf(analytics, prototype) |
| 31 | + |
| 32 | + // Add a global property to Vue instance |
| 33 | + const property = getGlobalProperty(platform) |
| 34 | + const version = getMajorVersion(app) |
| 35 | + switch (version) { |
| 36 | + case 2: { |
| 37 | + app.prototype[property] = analytics |
| 38 | + break |
| 39 | + } |
| 40 | + case 3: { |
| 41 | + app.config.globalProperties[property] = analytics |
| 42 | + break |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +export function createVitePressBaiduAnalytics() { |
| 49 | + // @ts-ignore |
| 50 | + const baiduAnalytics: VueAnalytics<'baidu'> = {} |
| 51 | + |
| 52 | + return { |
| 53 | + baiduAnalytics, |
| 54 | + registerBaiduAnalytics: registerProvider({ |
| 55 | + analytics: baiduAnalytics, |
| 56 | + platform: 'baidu', |
| 57 | + }), |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +export function createVitePressCnzzAnalytics() { |
| 62 | + // @ts-ignore |
| 63 | + const cnzzAnalytics: VueAnalytics<'cnzz'> = {} |
| 64 | + |
| 65 | + return { |
| 66 | + cnzzAnalytics, |
| 67 | + registerCnzzAnalytics: registerProvider({ |
| 68 | + analytics: cnzzAnalytics, |
| 69 | + platform: 'cnzz', |
| 70 | + }), |
| 71 | + } |
| 72 | +} |
0 commit comments