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: implement page, auth/registration and basic workstation tracking #250

Merged
merged 2 commits into from
Jul 5, 2022
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
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"yaml.schemas": {
"https://json.schemastore.org/github-workflow.json": ".github/workflows/build.yaml"
}
},
"cSpell.words": ["Supabase"]
}
4,655 changes: 4,404 additions & 251 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"web-vitals": "1.1.2"
},
"devDependencies": {
"@segment/analytics-next": "1.39.2",
"@simbathesailor/use-what-changed": "2.0.0",
"@testing-library/jest-dom": "5.14.1",
"@testing-library/react": "11.2.7",
Expand Down
6 changes: 6 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<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(){var t=Array.prototype.slice.call(arguments);t.unshift(e);analytics.push(t);return analytics}};for(var e=0;e<analytics.methods.length;e++){var key=analytics.methods[e];analytics[key]=analytics.factory(key)}analytics.load=function(key,e){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=e};analytics._writeKey="rktoQrG9OfAy7xL9G5i6VfsrWuSSKwZD";;analytics.SNIPPET_VERSION="4.15.3";
analytics.load("%REACT_APP_ANALYTICS_WRITE_KEY%");
analytics.page();
}}();
</script>
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Expand Down
10 changes: 4 additions & 6 deletions src/components/error-alert.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
import { ApiError } from "@supabase/supabase-js";
import { Alert, majorScale } from "evergreen-ui";
import { errorToString } from "utils/error-utils";

interface ErrorAlertProps {
error?: ApiError | Error | null;
}

const ErrorAlert: React.FC<ErrorAlertProps> = (props: ErrorAlertProps) => {
const { error } = props;
if (error == null) {
const message = errorToString(error);
if (message == null) {
return null;
}

return (
<Alert intent="danger" marginTop={majorScale(2)}>
{error?.message}
</Alert>
);
return <Alert intent="danger" marginTop={majorScale(2)} title={message} />;
};

export { ErrorAlert };
15 changes: 13 additions & 2 deletions src/components/nested-routes.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import React from "react";
import { Route, Routes, Navigate } from "react-router-dom";
import React, { useEffect, useRef } from "react";
import { Route, Routes, Navigate, useLocation } from "react-router-dom";
import { flattenRoutes } from "utils/route-utils";
import { RouteMap } from "interfaces/route-map";
import { trackPage } from "utils/analytics-utils";

interface NestedRoutesProps {
routes?: RouteMap;
Expand All @@ -11,6 +12,16 @@ const NestedRoutes: React.FC<NestedRoutesProps> = (
props: NestedRoutesProps
) => {
const { routes } = props;
const { pathname } = useLocation();
const pathnameRef = useRef<string>(pathname);
useEffect(() => {
if (pathnameRef.current === pathname) {
return;
}

pathnameRef.current = pathname;
trackPage();
}, [pathname]);
return <Routes>{renderRoutes(routes)}</Routes>;
};

Expand Down
35 changes: 27 additions & 8 deletions src/components/workstation/file-tab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ import { isNotNilOrEmpty } from "utils/core-utils";
import { ExportDialog } from "components/workstation/export-dialog";
import { useKeyboardShortcut } from "utils/hooks/use-keyboard-shortcut";
import { Key } from "enums/key";
import {
trackProjectSavedFromFileMenu,
trackProjectSavedFromKeyboardShortcut,
trackProjectSyncFailed,
} from "utils/analytics-utils";

interface FileTabProps {}

Expand Down Expand Up @@ -59,19 +64,22 @@ const FileTab: React.FC<FileTabProps> = (props: FileTabProps) => {
const [confirmationAction, setConfirmationAction] =
useState<ConfirmationAction>(ConfirmationAction.NewProject);
const { resultObject: files } = useListFiles();
const alertDecription =
const alertDescription =
confirmationAction === ConfirmationAction.NewProject
? "Opening a new project will wipe out any unsaved changes."
: "Reverting the project to the last saved state will wipe out any unsaved changes.";
const theme = useTheme();

const handleSyncError = useCallback(
(error: Error) =>
(error: Error) => {
trackProjectSyncFailed(project, error);
toaster.danger("There was an error syncing the project", {
description: error.message,
}),
[]
});
},
[project]
);

const handleSyncSuccess = useCallback(
(workstationState: WorkstationStateRecord) => {
setState(workstationState);
Expand Down Expand Up @@ -131,8 +139,11 @@ const FileTab: React.FC<FileTabProps> = (props: FileTabProps) => {

const { label } = useKeyboardShortcut(
`${Key.Control}+s`,
() => handleSave()(),
[handleSave]
() => {
trackProjectSavedFromKeyboardShortcut(project);
handleSave()();
},
[handleSave, project]
);

const handleRevertToSavedClick = useCallback(
Expand Down Expand Up @@ -190,6 +201,14 @@ const FileTab: React.FC<FileTabProps> = (props: FileTabProps) => {
[handleOpenExportDialog]
);

const handleSaveClick = useCallback(
(closePopover: () => void) => () => {
trackProjectSavedFromFileMenu(project);
handleSave(closePopover)();
},
[handleSave, project]
);

return (
<React.Fragment>
<Popover
Expand All @@ -202,7 +221,7 @@ const FileTab: React.FC<FileTabProps> = (props: FileTabProps) => {
Open
</Menu.Item>
<Menu.Item
onClick={handleSave(closePopover)}
onClick={handleSaveClick(closePopover)}
secondaryText={label}>
Save
</Menu.Item>
Expand Down Expand Up @@ -257,7 +276,7 @@ const FileTab: React.FC<FileTabProps> = (props: FileTabProps) => {
)}
{isConfirmDialogOpen && (
<ConfirmationDialog
alertDescription={alertDecription}
alertDescription={alertDescription}
alertTitle="You currently have unsaved changes."
onCloseComplete={handleCloseConfirmDialog}
onConfirm={handleDirtyConfirm}
Expand Down
119 changes: 119 additions & 0 deletions src/utils/analytics-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { SupabaseUser } from "types/supabase-user";
import { Project } from "generated/interfaces/project";
import { pick } from "utils/core-utils";
import { isPersisted } from "utils/auditable-utils";
import { errorToString } from "utils/error-utils";
import { ApiError } from "@supabase/supabase-js";
import { isError } from "lodash";

const { analytics } = window;

enum EventName {
LoginFailed = "Login Failed",
PasswordResetRequested = "Password Reset Requested",
ProjectCreated = "Project Created",
ProjectSaved = "Project Saved",
ProjectSyncFailed = "Project Sync Failed",
UserCreated = "User Created",
UserCreationAttempted = "User Creation Attempted",
}

enum ProjectSaveLocation {
FileMenu = "File Menu",
KeyboardShortcut = "Keyboard Shortcut",
}

const identifyUser = (user: SupabaseUser): void => {
analytics.identify(user.id, pick(user, "email"));
};

const trackLoginFailed = (email: string, error: ApiError | Error): void => {
analytics.track(EventName.LoginFailed, {
email,
..._pickErrorProperties(error),
});
};

const trackPage = (): void => {
analytics.page();
};

const trackUserCreated = (user: SupabaseUser): void => {
analytics.track(EventName.UserCreated, pick(user, "id", "email"));
};

const trackUserCreationAttempted = (email: string): void => {
analytics.track(EventName.UserCreationAttempted, { email });
};

const trackPasswordResetRequested = (email: string): void => {
analytics.track(EventName.PasswordResetRequested, { email });
};

const trackProjectCreated = (project: Project): void => {
if (isPersisted(project)) {
return;
}

analytics.track(EventName.ProjectCreated, _pickProjectProperties(project));
};

const trackProjectSavedFromFileMenu = (project: Project): void =>
_trackProjectSaved(project, ProjectSaveLocation.FileMenu);

const trackProjectSavedFromKeyboardShortcut = (project: Project): void =>
_trackProjectSaved(project, ProjectSaveLocation.KeyboardShortcut);

const trackProjectSyncFailed = (project: Project, error: Error): void => {
analytics.track(EventName.ProjectSyncFailed, {
..._pickProjectProperties(project),
...{ error: _pickErrorProperties(error) },
});
};

const _pickErrorProperties = (
error?: ApiError | Error
): Record<string, string | null> => {
if (error == null) {
return {};
}

let stackTrace: string | null = null;
if (isError(error) && error.stack != null) {
stackTrace = error.stack;
}

const name = isError(error) ? error.name : "ApiError";

return {
message: errorToString(error),
name,
stack_trace: stackTrace,
};
};

const _pickProjectProperties = (project: Project): Partial<Project> =>
pick(project, "id", "name");

const _trackProjectSaved = (
project: Project,
location: ProjectSaveLocation
): void => {
analytics.track(EventName.ProjectSaved, {
..._pickProjectProperties(project),
location,
});
};

export {
identifyUser,
trackPage,
trackProjectSavedFromFileMenu,
trackProjectSavedFromKeyboardShortcut,
trackPasswordResetRequested,
trackUserCreated,
trackLoginFailed,
trackUserCreationAttempted,
trackProjectCreated,
trackProjectSyncFailed,
};
8 changes: 7 additions & 1 deletion src/utils/core-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { BorderPropsOptions } from "interfaces/border-props-options";
import { BorderProps } from "interfaces/border-props";
import { RequiredOrNil } from "types/required-or-nil";
import { List, Record } from "immutable";
import { isEqual as lodashIsEqual } from "lodash";
import { isEqual as lodashIsEqual, pick as lodashPick } from "lodash";
import { Constructor } from "types/constructor";
import { Range } from "types/range";

Expand Down Expand Up @@ -91,6 +91,11 @@ const isNotNilOrEmpty = <T = any[] | List<any> | string>(
const makeDefaultValues = <T>(defaultValues: RequiredOrNil<T>): T =>
defaultValues as T;

const pick = <T extends object, K extends keyof T = keyof T>(
object: T,
...values: Array<K>
) => lodashPick<T, K>(object, ...values);

const randomInt = (range: Range): number => {
const [min, max] = range;
return Math.floor(Math.random() * (max - min + 1)) + min;
Expand Down Expand Up @@ -121,6 +126,7 @@ export {
isEqual,
isInstanceOf,
isNilOrEmpty,
pick,
isNotNilOrEmpty,
makeDefaultValues,
randomInt,
Expand Down
19 changes: 14 additions & 5 deletions src/utils/error-utils.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
import { ApiError } from "@supabase/supabase-js";
import { ErrorMessages } from "constants/error-messages";
import { isString } from "lodash";

export const isNotFoundError = (error?: Error | string | null): boolean => {
const isNotFoundError = (error?: Error | string | null): boolean =>
errorToString(error) === ErrorMessages.USER_NOT_FOUND;

const errorToString = (
error?: ApiError | Error | string | null
): string | null => {
if (error == null) {
return false;
return null;
}

if (error instanceof Error) {
return error.message === ErrorMessages.USER_NOT_FOUND;
if (isString(error)) {
return error;
}

return error === ErrorMessages.USER_NOT_FOUND;
return error.message;
};

export { errorToString, isNotFoundError };
3 changes: 2 additions & 1 deletion src/utils/hooks/supabase/use-auth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { SupabaseAuthClient } from "@supabase/supabase-js/dist/module/lib/SupabaseAuthClient";
import { SupabaseClient } from "generated/supabase-client";

const useAuth = () => {
const useAuth = (): SupabaseAuthClient => {
const { auth } = SupabaseClient;

return auth;
Expand Down
17 changes: 11 additions & 6 deletions src/utils/hooks/supabase/use-login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useAuth } from "utils/hooks/supabase/use-auth";
import { useMutation } from "utils/hooks/use-mutation";
import { ErrorMessages } from "constants/error-messages";
import { SupabaseUser } from "types/supabase-user";
import { identifyUser, trackLoginFailed } from "utils/analytics-utils";

interface UseLoginOptions {
onError?: (error: Error) => void;
Expand All @@ -21,20 +22,24 @@ const useLogin = (options?: UseLoginOptions) => {
{ redirectTo }
);

const { error } = loginResult;
const emailNotConfirmedError =
error != null &&
error.message === ErrorMessages.EMAIL_NOT_CONFIRMED;
const { error, user } = loginResult;
if (error != null) {
trackLoginFailed(email, error);
}

const emailIsNotConfirmed =
error?.message === ErrorMessages.EMAIL_NOT_CONFIRMED;

if (emailNotConfirmedError) {
if (emailIsNotConfirmed) {
throw new Error(ErrorMessages.EMAIL_NOT_CONFIRMED_CHECK_EMAIL);
}

if (error != null) {
throw error;
}

return loginResult.user!;
identifyUser(user!);
return user!;
},
onError,
onSuccess,
Expand Down
Loading