This commit is contained in:
taskylizard 2024-08-16 18:07:09 +00:00
parent 3e37eb6bc4
commit 1d73378e5f
No known key found for this signature in database
GPG key ID: 1820131ED1A24120
5 changed files with 150 additions and 0 deletions

View file

@ -0,0 +1,92 @@
import {
createPlausibleTracker,
type Plausible,
type PlausibleOptions
} from '@barbapapazes/plausible-tracker'
import {
useAutoPageviews,
useAutoOutboundTracking
} from '@barbapapazes/plausible-tracker/extensions'
import type { App } from 'vue'
import { inject } from 'vue'
interface ScriptLoaderOption extends Partial<HTMLScriptElement> {
'data-domain': string
}
function loadScript(
source: string,
options: ScriptLoaderOption = {} as ScriptLoaderOption
) {
return new Promise((resolve, reject) => {
const head = document.head || document.getElementsByTagName('head')[0]
const script = document.createElement('script')
const {
src,
type = 'text/javascript',
defer = false,
async = false,
...restAttrs
} = options
script.type = type
script.defer = defer
script.async = async
script.src = src || source
script.setAttribute('data-domain', options['data-domain'])
Object.keys(restAttrs).forEach((attr) => {
; (script as any)[attr] = (restAttrs as any)[attr]
})
head.appendChild(script)
script.onload = resolve
script.onerror = reject
})
}
export function createPlausible(
options: Partial<PlausibleOptions> & { domain: string; apiHost: string }
): {
install(app: App): void
} {
const plausible = {
install(app: App): void {
if (
// only in production
process.env.NODE_ENV === 'production' &&
// and we are ready
typeof window !== 'undefined'
) {
const $plausible = createPlausibleTracker(options)
const { install: _useAutoPageviews } =
// biome-ignore lint/correctness/useHookAtTopLevel: <explanation>
useAutoPageviews($plausible)
const { install: _useAutoOutboundTracking } =
// biome-ignore lint/correctness/useHookAtTopLevel: <explanation>
useAutoOutboundTracking($plausible)
_useAutoPageviews()
_useAutoOutboundTracking()
app.config.globalProperties.$plausible = $plausible
app.provide('$plausible', $plausible)
}
}
}
return plausible
}
export function usePlausible() {
const plausible = inject('$plausible') as Plausible
return {
...plausible
}
}
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$plausible: Plausible
}
}

View file

@ -5,6 +5,7 @@ import Post from './PostLayout.vue'
import { loadProgress } from './composables/nprogress'
import './style.css'
import 'uno.css'
import { createPlausible } from './composables/plausible'
export default {
extends: DefaultTheme,
@ -12,5 +13,11 @@ export default {
enhanceApp({ router, app }) {
app.component('Post', Post)
loadProgress(router)
app.use(
createPlausible({
apiHost: `https://${process.env.ANALYTICS_URL}`,
domain: 'https://web-24.fmhy.pages.dev'
})
)
}
} satisfies Theme