fix: umami analytics send app loaded event (#1928)

This commit is contained in:
Louis 2024-02-05 15:53:11 +07:00 committed by GitHub
parent 4f751338b7
commit ee5a44a799
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,65 +1,31 @@
import { useEffect } from 'react' import { useEffect } from 'react'
import Script from 'next/script'
// Define the type for the umami data object
interface UmamiData {
version: string
}
declare global {
interface Window {
umami:
| {
track: (event: string, data?: UmamiData) => void
}
| undefined
}
}
const Umami = () => { const Umami = () => {
const appVersion = VERSION
const analyticsHost = ANALYTICS_HOST
const analyticsId = ANALYTICS_ID
useEffect(() => { useEffect(() => {
if (!appVersion || !analyticsHost || !analyticsId) return if (!VERSION || !ANALYTICS_HOST || !ANALYTICS_ID) return
const ping = () => { fetch(ANALYTICS_HOST, {
// Check if umami is defined before ping method: 'POST',
if (window.umami !== null && typeof window.umami !== 'undefined') { // eslint-disable-next-line @typescript-eslint/naming-convention
window.umami.track(appVersion, { headers: { 'Content-Type': 'application/json' },
version: appVersion, body: JSON.stringify({
payload: {
website: ANALYTICS_ID,
hostname: 'jan.ai',
screen: `${screen.width}x${screen.height}`,
language: navigator.language,
referrer: 'index.html',
data: { version: VERSION },
type: 'event',
title: document.title,
url: 'index.html',
name: VERSION,
},
type: 'event',
}),
}) })
} }, [])
}
// Wait for umami to be defined before ping return <></>
if (window.umami !== null && typeof window.umami !== 'undefined') {
ping()
} else {
// Listen for umami script load event
document.addEventListener('umami:loaded', ping)
}
// Cleanup function to remove event listener if the component unmounts
return () => {
document.removeEventListener('umami:loaded', ping)
}
}, [appVersion, analyticsHost, analyticsId])
return (
<>
{appVersion && analyticsHost && analyticsId && (
<Script
src={analyticsHost}
data-website-id={analyticsId}
data-cache="true"
defer
onLoad={() => document.dispatchEvent(new Event('umami:loaded'))}
/>
)}
</>
)
} }
export default Umami export default Umami