Skip to content

Commit

Permalink
feat: integrate segment analytics
Browse files Browse the repository at this point in the history
  • Loading branch information
nounspaceryan committed Jul 2, 2024
1 parent f0c19d1 commit 458bc84
Show file tree
Hide file tree
Showing 11 changed files with 140 additions and 2 deletions.
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,5 @@ NEXT_PUBLIC_APP_FID = '123'
NEXT_PUBLIC_SUPABASE_URL = ''
NEXT_PUBLIC_SUPABASE_ANON_KEY = ''
NEXT_PUBLIC_PRIVY_API_KEY = ''
NEXT_PUBLIC_ALCHEMY_API_KEY = ''
NEXT_PUBLIC_ALCHEMY_API_KEY = ''
NEXT_PUBLIC_SEGMENT_WRITE_KEY = ''
8 changes: 8 additions & 0 deletions src/common/components/organisms/FidgetSettingsEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ import {
tabContentClasses,
} from "@/common/lib/theme/helpers";
import { mergeClasses } from "@/common/lib/utils/mergeClasses";
import {
analytics,
AnalyticsEvent,
} from "@/common/providers/AnalyticsProvider";

export type FidgetSettingsEditorProps = {
fidgetId: string;
Expand Down Expand Up @@ -125,13 +129,17 @@ export const FidgetSettingsEditor: React.FC<FidgetSettingsEditorProps> = ({
}) => {
const [showConfirmCancel, setShowConfirmCancel] = useState(false);
const [state, setState] = useState<FidgetSettings>(settings);

useEffect(() => {
setState(settings);
}, [settings]);

const _onSave = (e) => {
e.preventDefault();
onSave(state);
analytics.track(AnalyticsEvent.EDIT_FIDGET, {
fidgetType: properties.fidgetName,
});
};

const onKeyDown = (event: React.KeyboardEvent<HTMLFormElement>): void => {
Expand Down
10 changes: 10 additions & 0 deletions src/common/components/organisms/Navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ import { Button } from "../atoms/button";
import { FaPaintbrush, FaDiscord } from "react-icons/fa6";
import { NOUNISH_LOWFI_URL } from "@/constants/nounishLowfi";
import { UserTheme } from "@/common/lib/theme";
import {
AnalyticsEvent,
analytics,
} from "@/common/providers/AnalyticsProvider";

type NavItemProps = {
label: string;
Expand All @@ -23,6 +27,7 @@ type NavItemProps = {
href: string;
disable?: boolean;
openInNewTab?: boolean;
onClick?: () => void;
};

type NavProps = {
Expand Down Expand Up @@ -85,6 +90,7 @@ const Navigation: React.FC<NavProps> = ({
label,
Icon,
href,
onClick,
disable = false,
openInNewTab = false,
}) => {
Expand All @@ -96,6 +102,7 @@ const Navigation: React.FC<NavProps> = ({
"flex items-center p-2 text-gray-900 rounded-lg dark:text-white hover:bg-gray-100 dark:hover:bg-gray-700 group w-full",
href === currentUrl ? "bg-gray-100" : "",
)}
onClick={onClick}
rel={openInNewTab ? "noopener noreferrer" : undefined}
target={openInNewTab ? "_blank" : undefined}
>
Expand Down Expand Up @@ -131,6 +138,9 @@ const Navigation: React.FC<NavProps> = ({
label="Fair Launch"
Icon={IoMdRocket}
href="https://space.nounspace.com/"
onClick={() =>
analytics.track(AnalyticsEvent.CLICK_SPACE_FAIR_LAUNCH)
}
openInNewTab
/>
{/* <NavItem label="Explore" Icon={ExploreIcon} href="/explore"/> */}
Expand Down
5 changes: 5 additions & 0 deletions src/common/data/stores/app/accounts/farcasterStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import { concat, isUndefined } from "lodash";
import { hashObject } from "@/common/lib/signedFiles";
import moment from "moment";
import { bytesToHex } from "@noble/ciphers/utils";
import {
analytics,
AnalyticsEvent,
} from "@/common/providers/AnalyticsProvider";

type FarcasterActions = {
getFidsForCurrentIdentity: () => Promise<void>;
Expand Down Expand Up @@ -73,6 +77,7 @@ export const farcasterStore = (
);
if (!isUndefined(data.value)) {
get().account.addFidToCurrentIdentity(data.value!.fid);
analytics.track(AnalyticsEvent.LINK_FID);
}
},
});
5 changes: 5 additions & 0 deletions src/common/data/stores/app/accounts/identityStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ import {
signSignable,
} from "@/common/lib/signedFiles";
import { PreSpaceKeys } from "./prekeyStore";
import {
analytics,
AnalyticsEvent,
} from "@/common/providers/AnalyticsProvider";

export interface SpaceKeys {
publicKey: string;
Expand Down Expand Up @@ -284,6 +288,7 @@ export const identityStore = (
await axiosBackend.post("/api/space/identities", postData, {
headers: { "Content-Type": "application/json" },
});
analytics.track(AnalyticsEvent.SIGN_UP);
set((draft) => {
draft.account.spaceIdentities.push({
rootKeys: identityKeys,
Expand Down
5 changes: 5 additions & 0 deletions src/common/data/stores/app/homebase/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import stringify from "fast-json-stable-stringify";
import axiosBackend from "../../../api/backend";
import { SpaceConfig } from "@/common/components/templates/Space";
import INITIAL_HOMEBASE_CONFIG from "@/constants/intialHomebase";
import {
analytics,
AnalyticsEvent,
} from "@/common/providers/AnalyticsProvider";

interface HomeBaseStoreState {
homebaseConfig?: SpaceConfig;
Expand Down Expand Up @@ -79,6 +83,7 @@ export const createHomeBaseStoreFunc = (
set((draft) => {
draft.homebase.remoteHomebaseConfig = localCopy;
});
analytics.track(AnalyticsEvent.SAVE_HOMEBASE_THEME);
} catch (e) {
console.error(e);
throw e;
Expand Down
6 changes: 6 additions & 0 deletions src/common/data/stores/app/space/spaceStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ import { SignedFile, signSignable } from "@/common/lib/signedFiles";
import stringify from "fast-json-stable-stringify";
import { createClient } from "../../../database/supabase/clients/component";
import axios from "axios";
import {
analytics,
AnalyticsEvent,
} from "@/common/providers/AnalyticsProvider";

type SpaceId = string;

Expand Down Expand Up @@ -217,6 +221,8 @@ export const createSpaceStoreFunc = (
spaceConfig: file,
});

analytics.track(AnalyticsEvent.SAVE_SPACE_THEME);

set((draft) => {
draft.space.remoteSpaces[spaceId] = {
id: spaceId,
Expand Down
7 changes: 7 additions & 0 deletions src/common/lib/hooks/useCurrentSpaceIdentityPublicKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { useAppStore } from "@/common/data/stores/app";

export const useCurrentSpaceIdentityPublicKey = () => {
return useAppStore((state) => state.account.currentSpaceIdentityPublicKey);
};

export default useCurrentSpaceIdentityPublicKey;
81 changes: 81 additions & 0 deletions src/common/providers/AnalyticsProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"use client";
import React, { ReactNode, useEffect } from "react";
import { useRouter } from "next/router";
import { AnalyticsBrowser } from "@segment/analytics-next";
import { useCurrentSpaceIdentityPublicKey } from "@/common/lib/hooks/useCurrentSpaceIdentityPublicKey";

export enum AnalyticsEvent {
SIGN_UP = "Sign Up",
LINK_FID = "Link FID",
SAVE_SPACE_THEME = "Save Space Theme",
SAVE_HOMEBASE_THEME = "Save Homebase Theme",
ADD_FIDGET = "Add Fidget",
EDIT_FIDGET = "Edit Fidget",
CLICK_SPACE_FAIR_LAUNCH = "Click Space Fair Launch",
}

type AnalyticsEventProperties = {
[AnalyticsEvent.SIGN_UP]: Record<string, never>;
[AnalyticsEvent.LINK_FID]: Record<string, never>;
[AnalyticsEvent.SAVE_SPACE_THEME]: Record<string, never>;
[AnalyticsEvent.SAVE_HOMEBASE_THEME]: Record<string, never>;
[AnalyticsEvent.ADD_FIDGET]: { fidgetType: string };
[AnalyticsEvent.EDIT_FIDGET]: { fidgetType: string };
[AnalyticsEvent.CLICK_SPACE_FAIR_LAUNCH]: Record<string, never>;
};

const segment = new AnalyticsBrowser();

export const analytics = {
track: <T extends AnalyticsEvent>(
eventName: T,
properties?: AnalyticsEventProperties[T],
) => {
console.log(`analytics.track(${eventName})`);
segment.track(eventName, properties);
},
identify: (id: string) => {
console.log(`analytics.identify(${id})`);
segment.identify(id);
},
};

export const AnalyticsProvider: React.FC<{ children: ReactNode }> = ({
children,
}) => {
const router = useRouter();
const userId = useCurrentSpaceIdentityPublicKey();
const writeKey = process.env.NEXT_PUBLIC_SEGMENT_WRITE_KEY;

useEffect(() => {
if (writeKey) {
segment.load({ writeKey }).catch((e) => {
console.error(e);
});
}
}, [writeKey]);

useEffect(() => {
if (userId) {
analytics.identify(userId);
}
}, [userId]);

useEffect(() => {
segment.page();

const handleRouteChange = () => {
segment.page();
};

router.events.on("routeChangeComplete", handleRouteChange);

return () => {
router.events.off("routeChangeComplete", handleRouteChange);
};
}, [router.events]);

return children;
};

export default AnalyticsProvider;
5 changes: 4 additions & 1 deletion src/common/providers/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import AuthenticatorProvider from "./AutheticatorProvider";
import { AppStoreProvider } from "@/common/data/stores/app";
import UserThemeProvider from "@/common/lib/theme/UserThemeProvider";
import LoggedInStateProvider from "./LoggedInStateProvider";
import AnalyticsProvider from "./AnalyticsProvider";

export default function Providers({ children }: { children: React.ReactNode }) {
return (
Expand All @@ -18,7 +19,9 @@ export default function Providers({ children }: { children: React.ReactNode }) {
<AppStoreProvider>
<UserThemeProvider>
<AuthenticatorProvider>
<LoggedInStateProvider>{children}</LoggedInStateProvider>
<LoggedInStateProvider>
<AnalyticsProvider>{children}</AnalyticsProvider>
</LoggedInStateProvider>
</AuthenticatorProvider>
</UserThemeProvider>
</AppStoreProvider>
Expand Down
7 changes: 7 additions & 0 deletions src/fidgets/layout/Grid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ import EditorPanel from "@/common/components/organisms/EditorPanel";
import { FidgetWrapper } from "@/common/fidgets/FidgetWrapper";
import { debounce, map, reject } from "lodash";
import AddFidgetIcon from "@/common/components/atoms/icons/AddFidget";
import {
analytics,
AnalyticsEvent,
} from "@/common/providers/AnalyticsProvider";

export const resizeDirections = ["s", "w", "e", "n", "sw", "nw", "se", "ne"];
export type ResizeDirection = (typeof resizeDirections)[number];
Expand Down Expand Up @@ -279,6 +283,9 @@ const Grid: LayoutFidget<GridLayoutProps> = ({

saveLayout([...localLayout, newItem]);
removeFidgetFromTray(fidgetData.id);
analytics.track(AnalyticsEvent.ADD_FIDGET, {
fidgetType: fidgetData.fidgetType,
});
}

function removeFidgetFromTray(fidgetId: string) {
Expand Down

0 comments on commit 458bc84

Please sign in to comment.