diff --git a/src/components/track-reader-depth.tsx b/src/components/track-reader-depth.tsx index 8717c71c3bb69..9759d13e31a16 100644 --- a/src/components/track-reader-depth.tsx +++ b/src/components/track-reader-depth.tsx @@ -1,23 +1,19 @@ 'use client'; import {useEffect} from 'react'; -import {usePlausible} from 'next-plausible'; +import {usePlausibleEvent} from 'sentry-docs/hooks/usePlausibleEvent'; +import {PROGRESS_MILESTONES, ReadProgressMilestone} from 'sentry-docs/types/plausible'; import {debounce} from 'sentry-docs/utils'; -const EVENT = 'Read Progress'; -const milestones = [25, 50, 75, 100] as const; -type Milestone = (typeof milestones)[number]; -type EVENT_PROPS = {page: string; readProgress: Milestone}; - export function ReaderDepthTracker() { - const plausible = usePlausible<{[EVENT]: EVENT_PROPS}>(); + const {emit} = usePlausibleEvent(); - const sendProgressToPlausible = (progress: Milestone) => { - plausible(EVENT, {props: {readProgress: progress, page: document.title}}); + const sendProgressToPlausible = (progress: ReadProgressMilestone) => { + emit('Read Progress', {props: {readProgress: progress, page: document.title}}); }; useEffect(() => { - const reachedMilestones = new Set(); + const reachedMilestones = new Set(); const trackProgress = () => { // calculate the progress based on the scroll position @@ -30,7 +26,7 @@ export function ReaderDepthTracker() { } // find the biggest milestone that has not been reached yet - const milestone = milestones.findLast( + const milestone = PROGRESS_MILESTONES.findLast( m => progress >= m && !reachedMilestones.has(m) && diff --git a/src/hooks/usePlausibleEvent.tsx b/src/hooks/usePlausibleEvent.tsx new file mode 100644 index 0000000000000..071eeb5fdf6ca --- /dev/null +++ b/src/hooks/usePlausibleEvent.tsx @@ -0,0 +1,44 @@ +import {usePlausible} from 'next-plausible'; + +import {ReadProgressMilestone} from 'sentry-docs/types/plausible'; + +// Adding custom events here will make them available via the hook +type PlausibleEventProps = { + ['Read Progress']: { + page: string; + readProgress: ReadProgressMilestone; + }; +}; + +/** + * A hook that provides type-safe access to Plausible Analytics events. + * + * @example + * ```tsx + * function MyComponent() { + * const {emit} = usePlausibleEvent(); + * + * return ( + * + * ); + * } + * ``` + */ + +export const usePlausibleEvent = () => { + const plausible = usePlausible(); + + return { + emit: plausible, + }; +}; diff --git a/src/types/plausible.ts b/src/types/plausible.ts new file mode 100644 index 0000000000000..fd2ed363b7bb7 --- /dev/null +++ b/src/types/plausible.ts @@ -0,0 +1,2 @@ +export const PROGRESS_MILESTONES = [25, 50, 75, 100] as const; +export type ReadProgressMilestone = (typeof PROGRESS_MILESTONES)[number];