Skip to content

Commit

Permalink
fix(analytics): adjust cookies modal and posthog setup, implement GA …
Browse files Browse the repository at this point in the history
…custom events for feed search and sidebar
  • Loading branch information
ncarazon authored Oct 24, 2024
1 parent c5bab79 commit 655dc57
Show file tree
Hide file tree
Showing 9 changed files with 149 additions and 46 deletions.
21 changes: 16 additions & 5 deletions front_end/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion front_end/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
"next-themes": "^0.3.0",
"nextjs-toploader": "^1.6.12",
"percent-round": "^2.3.1",
"posthog-js": "^1.160.0",
"posthog-js": "^1.175.0",
"puppeteer": "^22.12.1",
"rc-slider": "^10.6.2",
"react": "^18",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use client";

import { sendGAEvent } from "@next/third-parties/google";
import { useSearchParams } from "next/navigation";
import { FC, useEffect, useState } from "react";

Expand Down Expand Up @@ -39,6 +40,7 @@ const TournamentFeed: FC<Props> = ({ slug }) => {
setIsLoading(true);
setError(undefined);
try {
sendGAEvent("event", "feedSearch", { value: pageFilters });
const { questions } = (await fetchPosts(
pageFilters,
0,
Expand Down
47 changes: 26 additions & 21 deletions front_end/src/app/(main)/components/cookies_banner/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"use client";

import Link from "next/link";
import { useTranslations } from "next-intl";
// import posthog from "posthog-js";
import posthog from "posthog-js";
import { FC, useEffect, useState } from "react";

import Button from "@/components/ui/button";
Expand All @@ -15,26 +16,31 @@ const STORAGE_KEY = "analytic_cookie_consent";
const CookiesBanner: FC = () => {
const t = useTranslations();

// const [isModalOpen, setIsModalOpen] = useState(false);
const [isModalOpen, setIsModalOpen] = useState(false);
const [consentGiven, setConsentGiven] = useState<ConsentGiven | null>(null);
const [analyticsCheckboxValue, setAnalyticsCheckboxValue] =
useState<boolean>(true);

// const openModal = () => setIsModalOpen(true);
// const closeModal = () => setIsModalOpen(false);
const openModal = () => setIsModalOpen(true);
const closeModal = () => setIsModalOpen(false);

useEffect(() => {
setConsentGiven(getAnalyticsCookieConsentGiven());
}, []);

// TODO: uncomment once we want to support cookies configuration
// useEffect(() => {
// if (consentGiven !== null) {
// posthog.set_config({
// persistence: consentGiven === "yes" ? "localStorage+cookie" : "memory",
// });
// }
// }, [consentGiven]);
useEffect(() => {
if (consentGiven !== null) {
posthog.set_config({
persistence: consentGiven === "yes" ? "localStorage+cookie" : "memory",
});

if (typeof window !== "undefined" && window.gtag) {
window.gtag("consent", "update", {
analytics_storage: consentGiven === "yes" ? "granted" : "denied",
});
}
}
}, [consentGiven]);

const submitBanner = () => {
const consentValue = analyticsCheckboxValue ? "yes" : "no";
Expand Down Expand Up @@ -67,21 +73,20 @@ const CookiesBanner: FC = () => {
</p>
</div>
<div className="flex items-center gap-2">
{/*TODO: uncomment once we want to support cookies configuration*/}
{/*<Button onClick={openModal}>{t("customize")}</Button>*/}
<Button onClick={openModal}>{t("customize")}</Button>
<Button variant="primary" onClick={submitBanner}>
{t("acceptAndClose")}
</Button>
</div>
</div>

{/*<CookiesModal*/}
{/* isOpen={isModalOpen}*/}
{/* onClose={closeModal}*/}
{/* analyticsValue={analyticsCheckboxValue}*/}
{/* onAnalyticsValueChange={setAnalyticsCheckboxValue}*/}
{/* onSubmit={submitBanner}*/}
{/*/>*/}
<CookiesModal
isOpen={isModalOpen}
onClose={closeModal}
analyticsValue={analyticsCheckboxValue}
onAnalyticsValueChange={setAnalyticsCheckboxValue}
onSubmit={submitBanner}
/>
</div>
);
};
Expand Down
51 changes: 46 additions & 5 deletions front_end/src/app/(main)/questions/components/question_topics.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
faHome,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { sendGAEvent } from "@next/third-parties/google";
import classNames from "classnames";
import { useTranslations } from "next-intl";
import { FC, useMemo, useState } from "react";
Expand Down Expand Up @@ -112,13 +113,23 @@ const QuestionTopics: FC<Props> = ({ topics }) => {
<TopicItem
text={t("myPredictions")}
emoji={"👤"}
onClick={() => switchFeed(FeedType.MY_PREDICTIONS)}
onClick={() => {
sendGAEvent("event", "sidebarClick", {
value: t("myPredictions"),
});
switchFeed(FeedType.MY_PREDICTIONS);
}}
isActive={currentFeed === FeedType.MY_PREDICTIONS}
/>
<TopicItem
text={t("myQuestionsAndPosts")}
emoji={"✍️"}
onClick={() => switchFeed(FeedType.MY_QUESTIONS_AND_POSTS)}
onClick={() => {
sendGAEvent("event", "sidebarClick", {
value: t("myQuestionsAndPosts"),
});
switchFeed(FeedType.MY_QUESTIONS_AND_POSTS);
}}
isActive={currentFeed === FeedType.MY_QUESTIONS_AND_POSTS}
/>
</>
Expand All @@ -128,12 +139,22 @@ const QuestionTopics: FC<Props> = ({ topics }) => {
emoji="🤖🔭"
text="AI Benchmarking"
href="/aib"
onClick={() =>
sendGAEvent("event", "sidebarClick", {
value: "AI Benchmarking",
})
}
/>
<TopicItem
isActive={false}
emoji="🇺🇸"
text="2024 US Election Hub"
href="/experiments/elections"
onClick={() =>
sendGAEvent("event", "sidebarClick", {
value: "2024 US Election Hub",
})
}
/>
{!!hotTopics.length && (
<>
Expand All @@ -144,7 +165,12 @@ const QuestionTopics: FC<Props> = ({ topics }) => {
isActive={selectedTopic === topic.slug}
emoji={topic.emoji}
text={topic.name}
onClick={() => selectTopic(topic)}
onClick={() => {
sendGAEvent("event", "sidebarClick", {
value: topic.name,
});
selectTopic(topic);
}}
/>
))}
</>
Expand All @@ -159,7 +185,12 @@ const QuestionTopics: FC<Props> = ({ topics }) => {
isActive={selectedTopic === category.slug}
emoji={category.emoji}
text={category.name}
onClick={() => selectTopic(category)}
onClick={() => {
sendGAEvent("event", "sidebarClick", {
value: category.name,
});
selectTopic(category);
}}
/>
))}
</>
Expand All @@ -170,13 +201,23 @@ const QuestionTopics: FC<Props> = ({ topics }) => {
text={t("seeAllCategories")}
emoji={<FontAwesomeIcon icon={faEllipsis} />}
isActive={false}
onClick={() => {
sendGAEvent("event", "sidebarClick", {
value: t("seeAllCategories"),
});
}}
/>
<hr className="mb-0 mt-0"></hr>
{user && (
<TopicItem
text={t("inReview")}
emoji={<FontAwesomeIcon icon={faFileClipboard} />}
onClick={() => switchFeed(FeedType.IN_REVIEW)}
onClick={() => {
sendGAEvent("event", "sidebarClick", {
value: t("inReview"),
});
switchFeed(FeedType.IN_REVIEW);
}}
isActive={currentFeed === FeedType.IN_REVIEW}
/>
)}
Expand Down
9 changes: 9 additions & 0 deletions front_end/src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import "@fortawesome/fontawesome-svg-core/styles.css";
import { GoogleAnalytics } from "@next/third-parties/google";
import type { Metadata } from "next";
import "./globals.css";
import dynamic from "next/dynamic";
import localFont from "next/font/local";
import { NextIntlClientProvider } from "next-intl";
import { getLocale, getMessages } from "next-intl/server";
Expand All @@ -19,6 +20,13 @@ import ProfileApi from "@/services/profile";

import { CSPostHogProvider } from "./providers";

const PostHogPageView = dynamic(
() => import("@/components/posthog_page_view"),
{
ssr: false,
}
);

config.autoAddCss = false;

const sourceSerifPro = localFont({
Expand Down Expand Up @@ -128,6 +136,7 @@ export default async function RootLayout({
>
<CSPostHogProvider>
<body className="min-h-screen w-full bg-blue-200 dark:bg-blue-50-dark">
<PostHogPageView />
<AppThemeProvided>
<NextIntlClientProvider messages={messages}>
<AuthProvider user={user}>
Expand Down
30 changes: 18 additions & 12 deletions front_end/src/app/providers.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,27 @@
"use client";
import posthog from "posthog-js";
import { PostHogProvider } from "posthog-js/react";
import { useEffect } from "react";

import { getAnalyticsCookieConsentGiven } from "@/app/(main)/components/cookies_banner";

export function CSPostHogProvider({ children }: { children: any }) {
if (typeof window !== "undefined" && process.env.NEXT_PUBLIC_POSTHOG_KEY) {
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
// set to 'always' to create profiles for anonymous users as well
person_profiles: "identified_only",
// TODO: uncomment once we want to support cookies configuration
// persistence:
// getAnalyticsCookieConsentGiven() === "yes"
// ? "localStorage+cookie"
// : "memory",
});
}
useEffect(() => {
if (process.env.NEXT_PUBLIC_POSTHOG_KEY) {
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
// set to 'always' to create profiles for anonymous users as well
person_profiles: "identified_only",
// Disable automatic pageview capture, as we capture manually
capture_pageview: false,
disable_session_recording: true,
persistence:
getAnalyticsCookieConsentGiven() === "yes"
? "localStorage+cookie"
: "memory",
});
}
}, []);

return <PostHogProvider client={posthog}>{children}</PostHogProvider>;
}
24 changes: 24 additions & 0 deletions front_end/src/components/posthog_page_view.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"use client";

import { usePathname, useSearchParams } from "next/navigation";
import { usePostHog } from "posthog-js/react";
import { useEffect } from "react";

export default function PostHogPageView() {
const pathname = usePathname();
const searchParams = useSearchParams();
const posthog = usePostHog();
useEffect(() => {
if (pathname && posthog) {
let url = window.origin + pathname;
if (searchParams.toString()) {
url = url + `?${searchParams.toString()}`;
}
posthog.capture("$pageview", {
$current_url: url,
});
}
}, [pathname, searchParams, posthog]);

return null;
}
9 changes: 7 additions & 2 deletions front_end/src/components/posts_feed/paginated_feed.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use client";
import * as Sentry from "@sentry/nextjs";
import { sendGAEvent } from "@next/third-parties/google";
import { useTranslations } from "next-intl";
import { FC, Fragment, useState } from "react";
import { FC, Fragment, useEffect, useState } from "react";

import { fetchMorePosts } from "@/app/(main)/questions/actions";
import NewsCard from "@/components/news_card";
Expand Down Expand Up @@ -42,11 +42,16 @@ const PaginatedPostsFeed: FC<Props> = ({
(Error & { digest?: string }) | undefined
>();

useEffect(() => {
// capture search event from AwaitedPostsFeed
sendGAEvent("event", "feedSearch", { value: filters });
}, [filters]);
const loadMorePosts = async () => {
if (hasMoreData) {
setIsLoading(true);
setError(undefined);
try {
sendGAEvent("event", "feedSearch", { value: filters });
const { newPosts, hasNextPage } = await fetchMorePosts(
filters,
offset,
Expand Down

0 comments on commit 655dc57

Please sign in to comment.