Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(frontend-analytics): Segment frontend tracking #154

Merged
merged 7 commits into from
Aug 2, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,7 @@ Thumbs.db
.nx-container

.env.local
schema.graphql
schema.graphql

# playground
playground
11 changes: 7 additions & 4 deletions apps/console/src/app/components/prompts/views/PromptEditView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { FunctionsFormModal } from "../FormModal";
import { InlineCodeSnippet } from "../../common/InlineCodeSnippet";
import { colors } from "../../../lib/theme/colors";
import { ConsumePromptModal } from "../ConsumePromptModal";
import { trackEvent } from "../../../lib/utils/analytics";

const FUNCTIONS_FEATURE_FLAG = true;

Expand All @@ -44,6 +45,11 @@ export const PromptEditView = () => {
const [isPublishModalOpen, setIsPublishModalOpen] = useState(false);
const [isFunctionsModalOpen, setIsFunctionsModalOpen] = useState(false);

const onConsumeClick = () => {
setIsConsumePromptModalOpen(true);
trackEvent("how_to_consume_prompt");
};

return (
!isPromptLoading && (
<>
Expand All @@ -56,10 +62,7 @@ export const PromptEditView = () => {
>
<Space>
{isPublishEnabled && (
<Button
onClick={() => setIsConsumePromptModalOpen(true)}
icon={<CodeOutlined />}
>
<Button onClick={onConsumeClick} icon={<CodeOutlined />}>
How to Consume
</Button>
)}
Expand Down
4 changes: 4 additions & 0 deletions apps/console/src/app/lib/providers/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { LayoutWrapper } from "../../components/layout/LayoutWrapper";
import { Loading3QuartersOutlined } from "@ant-design/icons";
import { colors } from "../theme/colors";
import { Loader } from "../../components/common/Loader";
import { useIdentify, useTrackInit } from "../utils/analytics";

const SpinnerOverlay = styled(Row)`
height: 100%;
Expand Down Expand Up @@ -48,6 +49,9 @@ export const AuthProvider = ({ children }) => {
}
}, [value.currentUser]);

useTrackInit(value.currentUser?.id);
useIdentify(value.currentUser);

return (
<AuthProviderContext.Provider value={value}>
{isLoading || isError || !data ? (
Expand Down
61 changes: 61 additions & 0 deletions apps/console/src/app/lib/utils/analytics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import React from "react";
import { GetMeQuery } from "../../../@generated/graphql/graphql";
import { SEGMENT_WRITE_KEY } from "../../../env";
import { AnalyticsEvent } from "./event.types";

const shouldTrack = !!SEGMENT_WRITE_KEY;
if (!shouldTrack) {
console.log("Segment analytics disabled");
window.analytics = {
identify: (...args: never) => null,
group: (...args: never) => null,
track: (...args: never) => null,
load: (...args: never) => null,
flush: (...args: never) => null,
};
}

export const useTrackInit = (userId: string) => {
React.useEffect(() => {
if (!window.analytics) return;
(window.analytics as any)._writeKey = SEGMENT_WRITE_KEY;
window.analytics.load(SEGMENT_WRITE_KEY);
}, []);

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

// Can be handled on backend
export const useIdentify = (user: GetMeQuery["me"]) => {
React.useEffect(() => {
if (!user) return;
const groupId = JSON.parse(localStorage.getItem("currentOrgId"));

const identifyRequest = {
userId: user.id,
name: user.name,
email: user.email,
avatar: user.photoUrl,
groupId,
};

window.analytics.identify(identifyRequest);
window.analytics.group(groupId);
}, [user]);
};

export const trackEvent = (
event: keyof AnalyticsEvent,
properties?: Record<string, any>
) => {
const groupId = JSON.parse(localStorage.getItem("currentOrgId"));
const context = { groupId };
window.analytics.track(
event,
{ ...properties, organizationId: groupId },
context
);
};
5 changes: 5 additions & 0 deletions apps/console/src/app/lib/utils/event.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export type AnalyticsEvent = {
login: "login";
logout: "logout";
how_to_consume_prompt: "how_to_consume_prompt";
};
2 changes: 2 additions & 0 deletions apps/console/src/app/lib/utils/sign-out.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { signOut as supertokensSignOut } from "supertokens-auth-react/recipe/session";
import { trackEvent } from "./analytics";

export async function signOut() {
trackEvent("logout");
await supertokensSignOut();
localStorage.removeItem("currentOrgId");
window.location.href = "/login";
Expand Down
1 change: 1 addition & 0 deletions apps/console/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ export const SUPERTOKENS_WEBSITE_DOMAIN = getEnvVariable(
"NX_SUPERTOKENS_WEBSITE_DOMAIN"
);
export const SENTRY_DSN_URL = getEnvVariable("NX_SENTRY_DSN_URL");
export const SEGMENT_WRITE_KEY = getEnvVariable("NX_SEGMENT_WRITE_KEY");
48 changes: 48 additions & 0 deletions apps/console/src/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
export {};

declare global {
eylonmiz marked this conversation as resolved.
Show resolved Hide resolved
class Analytics {
load(writeKey: string);

/* The identify method lets you tie a user to their actions and record
traits about them. */
identify(
message: Identity & {
traits?: any;
timestamp?: Date | undefined;
context?: any;
integrations?: Integrations | undefined;
},
callback?: (err: Error) => void
): Analytics;

/* The track method lets you record the actions your users perform. */
track(
event: string,
properties: any,
context: { groupId: string; projectId?: string }
): Analytics;

/* Group calls can be used to associate individual users with shared
accounts or companies. */
group(
message: Identity & {
groupId: string | number;
traits?: any;
context?: any;
timestamp?: Date | undefined;
integrations?: Integrations | undefined;
},
callback?: (err: Error) => void
): Analytics;

/* Flush batched calls to make sure nothing is left in the queue */
flush(
callback?: (err: Error, data: Data) => void
): Promise<{ batch: any; timestamp: string; sentAt: string }>;
}

interface Window {
analytics: Analytics;
}
}
62 changes: 62 additions & 0 deletions apps/console/src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,68 @@
sizes="16x16"
href="./assets/favicon/favicon-16x16.png"
/>
<script>
!(function () {
var analytics = (window.analytics = window.analytics || []);
if (!analytics.initialize)
if (analytics.invoked)
window.console &&
console.error &&
console.error("Segment snippet included twice.");
else {
analytics.invoked = !0;
analytics.methods = [
"trackSubmit",
"trackClick",
"trackLink",
"trackForm",
"pageview",
"identify",
"reset",
"group",
"track",
"ready",
"alias",
"debug",
"page",
"once",
"off",
"on",
"addSourceMiddleware",
"addIntegrationMiddleware",
"setAnonymousId",
"addDestinationMiddleware",
];
analytics.factory = function (e) {
return function () {
if (window.analytics.initialized)
return window.analytics[e].apply(window.analytics, arguments);
var i = Array.prototype.slice.call(arguments);
i.unshift(e);
analytics.push(i);
return analytics;
};
};
for (var i = 0; i < analytics.methods.length; i++) {
var key = analytics.methods[i];
analytics[key] = analytics.factory(key);
}
analytics.load = function (key, i) {
var t = document.createElement("script");
t.type = "text/javascript";
t.async = !0;
t.src =
"https://cdn.segment.com/analytics.js/v1/" +
key +
"/analytics.min.js";
var n = document.getElementsByTagName("script")[0];
n.parentNode.insertBefore(t, n);
analytics._loadOptions = i;
};
analytics.SNIPPET_VERSION = "4.16.1";
}
})();
</script>
</head>
<body>
<div id="root"></div>
Expand Down
Loading