Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 7 additions & 11 deletions src/components/track-reader-depth.tsx
Original file line number Diff line number Diff line change
@@ -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<Milestone>();
const reachedMilestones = new Set<ReadProgressMilestone>();

const trackProgress = () => {
// calculate the progress based on the scroll position
Expand All @@ -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) &&
Expand Down
44 changes: 44 additions & 0 deletions src/hooks/usePlausibleEvent.tsx
Original file line number Diff line number Diff line change
@@ -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 (
* <button
* onClick={() => {
* emit('Some Typed Event', {
* props: {
* page: document.title,
* }
* });
* }}
* >
* Trigger event
* </button>
* );
* }
* ```
*/

export const usePlausibleEvent = () => {
const plausible = usePlausible<PlausibleEventProps>();

return {
emit: plausible,
};
};
2 changes: 2 additions & 0 deletions src/types/plausible.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const PROGRESS_MILESTONES = [25, 50, 75, 100] as const;
export type ReadProgressMilestone = (typeof PROGRESS_MILESTONES)[number];
Loading