Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(signup): revised paywall / onboarding / signup (#324)

teob09bb288a24a
diff --git a/js/app/packages/app/component/EmailAuth.tsx b/js/app/packages/app/component/EmailAuth.tsx
new file mode 100644
index 0000000000..e6b6590dbc
--- /dev/null
+++ b/js/app/packages/app/component/EmailAuth.tsx
@@ -0,0 +1,82 @@
+import { updateUserAuth } from '@core/auth';
+import { redirectToEmailAuth } from '@core/auth/email';
+import { LoadingBlock } from '@core/component/LoadingBlock';
+import { toast } from '@core/component/Toast/Toast';
+import { useEmailLinks } from '@core/email-link';
+import { whenSettled } from '@core/util/whenSettled';
+import { updateUserInfo } from '@service-gql/client';
+import { useNavigate } from '@solidjs/router';
+import { onMount, Suspense } from 'solid-js';
+
+type EmailAuthParams = {
+ callbackPath: string;
+ successPath: string;
+};
+
+export function makeEmailAuthComponents(params: EmailAuthParams) {
+ return {
+ EmailCallback: () => (
+ <Suspense>
+ <EmailCallback successPath={params.successPath} />
+ </Suspense>
+ ),
+ EmailSignUp: () => (
+ <Suspense>
+ <EmailSignUp
+ callbackPath={params.callbackPath}
+ successPath={params.successPath}
+ />
+ </Suspense>
+ ),
+ CALLBACK_PATH: params.callbackPath,
+ };
+}
+
+function EmailCallback(props: Pick<EmailAuthParams, 'successPath'>) {
+ const navigate = useNavigate();
+ const { query, maybeSync } = useEmailLinks();
+
+ const onSuccessfulAuth = async () => {
+ await updateUserAuth();
+ await updateUserInfo();
+ const channel = new BroadcastChannel('auth');
+ channel.postMessage({ type: 'login-success' });
+ };
+
+ whenSettled(
+ query,
+ async (links) => {
+ let result = maybeSync(links);
+ if (result) {
+ toast.success('Syncing emails', 'this might take a while');
+ }
+ onSuccessfulAuth();
+ navigate(props.successPath, {
+ replace: true,
+ });
+ },
+ (error) => {
+ toast.failure(error.message);
+ }
+ );
+
+ return <LoadingBlock />;
+}
+
+function EmailSignUp(props: EmailAuthParams) {
+ const navigate = useNavigate();
+ const { query: emailLinks } = useEmailLinks();
+
+ const withAppPrefix = (path: string) => `/app${path}`;
+
+ onMount(() => {
+ if (emailLinks.data && emailLinks.data?.length > 0) {
+ navigate(props.successPath);
+ return;
+ }
+ redirectToEmailAuth({
+ returnPath: withAppPrefix(props.callbackPath),
+ });
+ });
+ return <LoadingBlock />;
+}
diff --git a/js/app/packages/app/component/HelpDrawer.tsx b/js/app/packages/app/component/HelpDrawer.tsx
index 562d060802..10f9ed9085 100644
--- a/js/app/packages/app/component/HelpDrawer.tsx
+++ b/js/app/packages/app/component/HelpDrawer.tsx
@@ -1,7 +1,7 @@
-import { connectEmail, useEmailLinksStatus } from '@app/signal/emailAuth';
import { IconButton } from '@core/component/IconButton';
import { toast } from '@core/component/Toast/Toast';
import { fileSelector } from '@core/directive/fileSelector';
+import { useEmailLinks, useEmailLinksStatus } from '@core/email-link';
import { TOKENS } from '@core/hotkey/tokens';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { isMobileWidth } from '@core/mobile/mobileWidth';
@@ -17,6 +17,7 @@ false && fileSelector;
export function HelpDrawer(props: { viewId?: ViewId }) {
const emailActive = useEmailLinksStatus();
+ const { connect: connectEmail } = useEmailLinks();
return (
<Switch>
diff --git a/js/app/packages/app/component/Layout.tsx b/js/app/packages/app/component/Layout.tsx
index 6d23eec2f0..a8bd7bc4db 100644
--- a/js/app/packages/app/component/Layout.tsx
+++ b/js/app/packages/app/component/Layout.tsx
@@ -24,6 +24,15 @@ import { QuickCreateMenu } from './QuickCreateMenu';
import { RightbarWrapper } from './rightbar/Rightbar';
import { Settings, setViewportOffset } from './settings/Settings';
+const AUTH_URLS = [
+ '/app/login',
+ '/app/login/popup',
+ '/app/login/popup/success',
+ '/app/onboarding',
+ '/app/signup',
+ '/app/email-signup-callback',
+];
+
export function Layout(props: RouteSectionProps) {
const isAuthenticated = useIsAuthenticated();
const { paywallOpen, showPaywall } = usePaywallState();
@@ -115,12 +124,7 @@ export function Layout(props: RouteSectionProps) {
<QuickCreateMenu />
<GlobalBulkEditEntityModal />
</Show>
- <Show
- when={
- !isAuthenticated() &&
- !['/app/login', '/app/onboarding'].includes(location.pathname)
- }
- >
+ <Show when={!isAuthenticated() && !AUTH_URLS.includes(location.pathname)}>
<Banner />
</Show>
{/* <Show when={isAuthenticated() && isTutorialCompleted() === false}>
@@ -145,7 +149,7 @@ export function Layout(props: RouteSectionProps) {
</ItemDndProvider>
</Resize.Zone>
</div>
- <Show when={isAuthenticated() && '/app/onboarding' !== location.pathname}>
+ <Show when={isAuthenticated() && !AUTH_URLS.includes(location.pathname)}>
<Dock />
<Launcher open={createMenuOpen()} onOpenChange={setCreateMenuOpen} />
</Show>
diff --git a/js/app/packages/app/component/Onboarding.tsx b/js/app/packages/app/component/Onboarding.tsx
index 156f5b0015..583bf43f82 100644
--- a/js/app/packages/app/component/Onboarding.tsx
+++ b/js/app/packages/app/component/Onboarding.tsx
@@ -1,5 +1,4 @@
import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
-import { connectEmail, useEmailLinksStatus } from '@app/signal/emailAuth';
import { withAnalytics } from '@coparse/analytics';
import { updateUserAuth, useIsAuthenticated } from '@core/auth';
import { useHasPaidAccess } from '@core/auth/license';
@@ -7,6 +6,7 @@ import { BrightJoins } from '@core/component/BrightJoins';
import BrightJoinsProgressMeter from '@core/component/BrightJoinsProgressMeter';
import { ActionSequence } from '@core/component/FormControls/ActionSequence';
import MacroLogo from '@core/component/MacroLogo';
+import { useEmailLinks, useEmailLinksStatus } from '@core/email-link';
import { licenseChannel } from '@core/util/licenseUpdateBroadcastChannel';
import { updateUserInfo } from '@service-gql/client';
import { stripeServiceClient } from '@service-stripe/client';
@@ -21,6 +21,8 @@ export default function Onboarding() {
const connected = useEmailLinksStatus();
const subscribed = useHasPaidAccess();
+ const { connect: connectEmail } = useEmailLinks();
+
const navigate = useNavigate();
const [searchParams] = useSearchParams();
diff --git a/js/app/packages/app/component/QuickCreateMenu.tsx b/js/app/packages/app/component/QuickCreateMenu.tsx
index b44f05cc3e..b4eb466e49 100644
--- a/js/app/packages/app/component/QuickCreateMenu.tsx
+++ b/js/app/packages/app/component/QuickCreateMenu.tsx
@@ -39,6 +39,7 @@ import { TextButton } from '@core/component/TextButton';
import { toast } from '@core/component/Toast/Toast';
import { LabelAndHotKey, Tooltip } from '@core/component/Tooltip';
import { IS_MAC } from '@core/constant/isMac';
+import { useEmailLinksStatus } from '@core/email-link';
import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';
@@ -89,7 +90,6 @@ import {
Switch,
useContext,
} from 'solid-js';
-import { useEmailLinksStatus } from '../signal/emailAuth';
import { useSplitLayout } from './split-layout/layout';
type CreateType = 'note' | 'email' | 'message';
diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsx
index 47d4a0d11a..c45d42251b 100644
--- a/js/app/packages/app/component/Root.tsx
+++ b/js/app/packages/app/component/Root.tsx
@@ -1,5 +1,4 @@
import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
-import { useEmailLinksStatus } from '@app/signal/emailAuth';
import { withAnalytics } from '@coparse/analytics';
import { useIsAuthenticated } from '@core/auth';
import { ChannelsContextProvider } from '@core/component/ChannelsProvider';
@@ -11,6 +10,7 @@ import {
ENABLE_WEBSOCKET_DEBUGGER,
PROD_MODE_ENV,
} from '@core/constant/featureFlags';
+import { useEmailLinksStatus } from '@core/email-link';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { createBlockOrchestrator } from '@core/orchestrator';
import { formatTabTitle, tabTitleSignal } from '@core/signal/tabTitle';
@@ -59,6 +59,7 @@ import { useSoundHover } from '../util/soundHover';
import { updateCookie } from '../util/updateCookie';
import { Login } from './auth/Login';
import { LOGIN_COOKIE_AGE, setCookie } from './auth/Shared';
+import { makeEmailAuthComponents } from './EmailAuth';
import { GlobalAppStateProvider } from './GlobalAppState';
import { Layout } from './Layout';
import MacroJump from './MacroJump';
@@ -173,12 +174,25 @@ function NotFound() {
return '';
}
+const { EmailSignUp, EmailCallback, CALLBACK_PATH } = makeEmailAuthComponents({
+ callbackPath: '/email-signup-callback',
+ successPath: '/',
+});
+
const ROUTES: RouteDefinition[] = [
LAYOUT_ROUTE,
{
path: '/',
component: BasePathComponent,
},
+ {
+ path: '/signup',
+ component: EmailSignUp,
+ },
+ {
+ path: CALLBACK_PATH,
+ component: EmailCallback,
+ },
{
path: '/login/popup/success',
component: () => {
diff --git a/js/app/packages/app/component/UnifiedListEmptyState.tsx b/js/app/packages/app/component/UnifiedListEmptyState.tsx
index 7ccf1900bd..6f8bec3d15 100644
--- a/js/app/packages/app/component/UnifiedListEmptyState.tsx
+++ b/js/app/packages/app/component/UnifiedListEmptyState.tsx
@@ -1,9 +1,8 @@
-import { useEmailLinksStatus } from '@app/signal/emailAuth';
import { useHandleFileUpload } from '@app/util/handleFileUpload';
-
import { useMaybeBlockId, useMaybeBlockName } from '@core/block';
import { fileSelector } from '@core/directive/fileSelector';
import { folderSelector } from '@core/directive/folderSelector';
+import { useEmailLinksStatus } from '@core/email-link';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { isMobileWidth } from '@core/mobile/mobileWidth';
import type { ViewId } from '@core/types/view';
diff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsx
index e8cb6a9504..4f7032adc4 100644
--- a/js/app/packages/app/component/UnifiedListView.tsx
+++ b/js/app/packages/app/component/UnifiedListView.tsx
@@ -2,10 +2,6 @@ import {
useGlobalBlockOrchestrator,
useGlobalNotificationSource,
} from '@app/component/GlobalAppState';
-import {
- emailRefetchInterval,
- useEmailLinksStatus,
-} from '@app/signal/emailAuth';
import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
import { URL_PARAMS as MD_PARAMS } from '@block-md/constants';
import { URL_PARAMS as PDF_PARAMS } from '@block-pdf/signal/location';
@@ -26,6 +22,7 @@ import {
ENABLE_PROPERTY_DISPLAY_CONTROL,
ENABLE_SOUP_FROM_FILTER,
} from '@core/constant/featureFlags';
+import { emailRefetchInterval, useEmailLinksStatus } from '@core/email-link';
import { registerHotkey } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
diff --git a/js/app/packages/app/component/settings/Account.tsx b/js/app/packages/app/component/settings/Account.tsx
index ee8b0c9609..8266736f95 100644
--- a/js/app/packages/app/component/settings/Account.tsx
+++ b/js/app/packages/app/component/settings/Account.tsx
@@ -29,10 +29,9 @@ import { authServiceClient } from '@service-auth/client';
import { useEmail, useLicenseStatus, useUserId } from '@service-gql/client';
import { createMemo, createResource, createSignal, Show } from 'solid-js';
import {
- connectEmail,
- disconnectEmail,
+ useEmailLinks,
useEmailLinksStatus,
-} from '../../signal/emailAuth';
+} from '@core/email-link';
import { BetaTooltip } from '../BetaTooltip';
// NOTE: solid directives
@@ -69,6 +68,8 @@ export function Account() {
const hasPaidAccess = useHasPaidAccess();
const [showEmailModal, setShowEmailModal] = createSignal<boolean>(false);
+ const { connect: connectEmail, disconnect: disconnectEmail } = useEmailLinks();
+
const userName = useUserName();
const [updatedFirstName, setUpdatedFirstName] = createSignal<
string | undefined
diff --git a/js/app/packages/app/signal/emailAuth.ts b/js/app/packages/app/signal/emailAuth.ts
deleted file mode 100644
index 22a74d80c3..0000000000
--- a/js/app/packages/app/signal/emailAuth.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-import { updateUserAuth } from '@core/auth';
-import { toast } from '@core/component/Toast/Toast';
-import { SERVER_HOSTS } from '@core/constant/servers';
-import { isErr, ok } from '@core/util/maybeResult';
-import { queryKeys } from '@macro-entity';
-import { emailClient } from '@service-email/client';
-import { updateUserInfo } from '@service-gql/client';
-import { createSingletonRoot } from '@solid-primitives/rootless';
-import { createMemo, createResource, createSignal } from 'solid-js';
-import { queryClient } from '../../macro-entity/src/queries/client';
-import { broadcastChannels, setBroadcastChannels } from './broadcastChannels';
-
-export const [emailRefetchInterval, setEmailRefetchInterval] = createSignal<
- number | undefined
->();
-
-const emailLinksResource = createSingletonRoot(() => {
- const fetchLinks = async () => {
- return await emailClient.getLinks();
- };
- return createResource(fetchLinks, {
- initialValue: ok({ links: [] }),
- });
-});
-
-// Returns true if user has at least one email link
-export const useEmailLinksStatus = createSingletonRoot(() => {
- const [resource] = emailLinksResource();
- return createMemo(() => {
- if (isErr(resource.latest)) return false;
- const [, links] = resource.latest;
- return links.links.length > 0;
- });
-});
-
-export async function refetchEmailLinks(force = false) {
- const [resource, { refetch }] = emailLinksResource();
- if (force) return await refetch();
- if (resource.loading) return resource.latest;
- return await refetch();
-}
-
-export async function connectEmail() {
- if (!broadcastChannels().get('auth')) {
- const channel = new BroadcastChannel('auth');
- setBroadcastChannels(broadcastChannels().set('auth', channel));
- }
- const channel = broadcastChannels().get('auth');
-
- const emailConnected = useEmailLinksStatus();
-
- const idpName = 'google_gmail';
- const originalUrl = `${window.location.origin}/app/login/popup/success`;
-
- const width = 600;
- const height = 600;
- const left = window.screenX + (window.outerWidth - width) / 2;
- const top = window.screenY + (window.outerHeight - height) / 2;
-
- const ssoUrl = `${SERVER_HOSTS['auth-service']}/login/sso?idp_name=${idpName}&original_url=${originalUrl}`;
-
- window.open(
- ssoUrl,
- '_blank',
- `width=${width},height=${height},left=${left},top=${top}`
- );
-
- if (!channel) return;
-
- return new Promise((resolve) => {
- channel.onmessage = async (event) => {
- if (event.data.type === 'login-success') {
- await refetchEmailLinks();
- if (emailConnected()) {
- await updateUserAuth();
- await updateUserInfo();
- resolve(true);
- return;
- }
- const syncResult = await emailClient.init();
- if (isErr(syncResult) && !isErr(syncResult, 'HTTP_ERROR')) {
- toast.failure('Failed to connect to Gmail account');
- } else {
- toast.success(
- 'Gmail account connected. Starting to sync your emails.',
- 'If you have lots of emails this may take a few hours to complete.'
- );
- // We start polling for emails every second for the next 20 seconds
- setEmailRefetchInterval(1000);
- setTimeout(() => {
- setEmailRefetchInterval(undefined);
- }, 20000);
- await refetchEmailLinks();
- await updateUserAuth();
- await updateUserInfo();
- resolve(true);
- }
- }
- };
- });
-}
-
-export async function disconnectEmail() {
- const response = await emailClient.stopSync();
- if (isErr(response) && !isErr(response, 'NOT_FOUND')) {
- toast.failure(
- 'Failed to disconnect Gmail account',
- 'Please try again later'
- );
- } else {
- toast.success(
- 'Gmail account disconnected. Deleting your email data...',
- 'This may take a little while to complete.'
- );
- refetchEmailLinks();
- setEmailRefetchInterval(undefined);
- await queryClient.cancelQueries({ queryKey: queryKeys.all.email });
- queryClient.setQueriesData({ queryKey: queryKeys.all.email }, () => ({
- pages: [],
- pageParams: [],
- }));
- refetchEmailLinks();
- }
-}
diff --git a/js/app/packages/block-email/component/Compose.tsx b/js/app/packages/block-email/component/Compose.tsx
index 3bd01c632b..c586540cf8 100644
--- a/js/app/packages/block-email/component/Compose.tsx
+++ b/js/app/packages/block-email/component/Compose.tsx
@@ -3,12 +3,12 @@ import {
SplitHeaderBadge,
StaticSplitLabel,
} from '@app/component/split-layout/components/SplitLabel';
-import { connectEmail } from '@app/signal/emailAuth';
import { useHasPaidAccess } from '@core/auth';
import { RecipientSelector } from '@core/component/RecipientSelector';
import { TextButton } from '@core/component/TextButton';
import { usePaywallState } from '@core/constant/PaywallState';
import { fileDrop } from '@core/directive/fileDrop';
+import { useEmailLinks } from '@core/email-link';
import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';
import { useDisplayName, type WithCustomUserInput } from '@core/user';
import { isErr } from '@core/util/maybeResult';
@@ -70,6 +70,8 @@ export function EmailCompose() {
const [triedToSubmit, _setTriedToSubmit] = createSignal(false);
+ const { connect: connectEmail } = useEmailLinks();
+
const previewName = createMemo(() => {
const recipients = selectedRecipients();
if (recipients.length === 0) {
diff --git a/js/app/packages/core/auth/channel.ts b/js/app/packages/core/auth/channel.ts
new file mode 100644
index 0000000000..a82b84f88d
--- /dev/null
+++ b/js/app/packages/core/auth/channel.ts
@@ -0,0 +1,81 @@
+import {
+ broadcastChannels,
+ setBroadcastChannels,
+} from '@app/signal/broadcastChannels';
+import { errAsync, okAsync, ResultAsync } from 'neverthrow';
+
+const AUTH_CHANNEL = 'auth';
+const LOGIN_SUCCESS = 'login-success';
+
+/**
+ * Gets or creates a broadcast channel for the authentication process.
+ *
+ * @returns The broadcast channel.
+ */
+export function getOrCreateAuthChannel(): BroadcastChannel {
+ let channel = broadcastChannels().get(AUTH_CHANNEL);
+ if (!channel) {
+ channel = new BroadcastChannel(AUTH_CHANNEL);
+ setBroadcastChannels(broadcastChannels().set(AUTH_CHANNEL, channel));
+ }
+ return channel;
+}
+
+export function waitForAuthSuccess(channel: BroadcastChannel): Promise<void> {
+ return new Promise((resolve) => {
+ channel.onmessage = (event) => {
+ if (event.data.type === LOGIN_SUCCESS) {
+ resolve();
+ }
+ };
+ });
+}
+
+/** Errot type for a promise timing out. */
+export type TimeoutError = { tag: 'TimeoutError'; message: string };
+
+/**
+ * Waits for the auth success message to be received on the given channel.
+ *
+ * @param channel The channel to wait for the message on.
+ * @param timeout The timeout in milliseconds.
+ * @returns A promise that resolves when the auth success message is received.
+ */
+export function waitForAuthSuccessOrTimeout(
+ channel: BroadcastChannel,
+ timeout: number
+): ResultAsync<void, TimeoutError> {
+ return new ResultAsync(
+ new Promise((resolve) => {
+ const timeoutId = setTimeout(() => {
+ resolve(
+ errAsync({
+ tag: 'TimeoutError',
+ message: 'Timeout waiting for auth success',
+ })
+ );
+ }, timeout);
+
+ channel.onmessage = (event) => {
+ if (event.data.type === LOGIN_SUCCESS) {
+ clearTimeout(timeoutId);
+ resolve(okAsync(undefined));
+ }
+ };
+ })
+ );
+}
+
+const AUTH_TIMEOUT = 60_000;
+/**
+ * Waits for the auth success message to be received on the channel.
+ *
+ * @returns A promise that resolves when the auth success message is received.
+ */
+export function authenticateWithEmailPermissions(): ResultAsync<
+ void,
+ TimeoutError
+> {
+ const channel = getOrCreateAuthChannel();
+ return waitForAuthSuccessOrTimeout(channel, AUTH_TIMEOUT);
+}
diff --git a/js/app/packages/core/auth/email.ts b/js/app/packages/core/auth/email.ts
new file mode 100644
index 0000000000..f1ef876dfd
--- /dev/null
+++ b/js/app/packages/core/auth/email.ts
@@ -0,0 +1,39 @@
+import { SERVER_HOSTS } from '@core/constant/servers';
+
+const GOOGLE_GMAIL_IDP = 'google_gmail';
+type IDPName = 'google_gmail';
+
+const DEFAULT_RETURN_PATH = '/app';
+
+type EmailAuthParams = {
+ idpName?: IDPName;
+ returnPath?: string;
+};
+
+function emailAuthUrl(params: EmailAuthParams) {
+ const idpName = params.idpName ?? GOOGLE_GMAIL_IDP;
+ const returnUrl = `${window.location.origin}${params.returnPath ?? DEFAULT_RETURN_PATH}`;
+
+ return `${SERVER_HOSTS['auth-service']}/login/sso?idp_name=${idpName}&original_url=${returnUrl}`;
+}
+
+export function redirectToEmailAuth(params: EmailAuthParams) {
+ window.location.href = emailAuthUrl(params);
+}
+
+const POPUP_DIMENSIONS = {
+ width: 600,
+ height: 600,
+ left: window.screenX + (window.outerWidth - 600) / 2,
+ top: window.screenY + (window.outerHeight - 600) / 2,
+};
+
+function toPopupDimensionsString(dimensions: typeof POPUP_DIMENSIONS) {
+ return `width=${dimensions.width},height=${dimensions.height},left=${dimensions.left},top=${dimensions.top}`;
+}
+
+export function openEmailAuthPopup(params: EmailAuthParams) {
+ const ssoUrl = emailAuthUrl(params);
+
+ window.open(ssoUrl, '_blank', toPopupDimensionsString(POPUP_DIMENSIONS));
+}
diff --git a/js/app/packages/core/component/TopBar/LoginButton.tsx b/js/app/packages/core/component/TopBar/LoginButton.tsx
index 09316f18be..a977cbaa74 100644
--- a/js/app/packages/core/component/TopBar/LoginButton.tsx
+++ b/js/app/packages/core/component/TopBar/LoginButton.tsx
@@ -15,7 +15,7 @@ export function LoginButton() {
<div class="flex gap-2 justify-center w-max items-baseline font-mono">
<Button onClick={() => navigate('/login')}>Login</Button>
<span class="italic">or</span>
- <Button onClick={() => navigate('/onboarding')}>Sign Up</Button>
+ <Button onClick={() => navigate('/signup')}>Sign Up</Button>
</div>
);
}
diff --git a/js/app/packages/core/email-link/index.ts b/js/app/packages/core/email-link/index.ts
new file mode 100644
index 0000000000..a99fe5f273
--- /dev/null
+++ b/js/app/packages/core/email-link/index.ts
@@ -0,0 +1,208 @@
+import { updateUserAuth } from '@core/auth';
+import {
+ authenticateWithEmailPermissions,
+ type TimeoutError,
+} from '@core/auth/channel';
+import { openEmailAuthPopup } from '@core/auth/email';
+import { isErr } from '@core/util/maybeResult';
+import { queryKeys } from '@macro-entity';
+import { emailClient } from '@service-email/client';
+import type { Link } from '@service-email/generated/schemas/link';
+import { updateUserInfo } from '@service-gql/client';
+import { useQuery } from '@tanstack/solid-query';
+import { err, okAsync, type Result, ResultAsync } from 'neverthrow';
+import { createSignal } from 'solid-js';
+import { queryClient } from '../../macro-entity/src/queries/client';
+
+export const [emailRefetchInterval, setEmailRefetchInterval] = createSignal<
+ number | undefined
+>();
+
+const EMAIL_LINKS_QUERY_KEY = ['email-links'];
+
+async function fetchEmailLinks() {
+ const result = await emailClient.getLinks();
+ if (isErr(result)) {
+ throw new Error('Failed to fetch email links', { cause: result[0] });
+ }
+ return result[1]?.links ?? [];
+}
+
+export function useEmailLinksQuery() {
+ return useQuery(() => ({
+ queryKey: EMAIL_LINKS_QUERY_KEY,
+ queryFn: fetchEmailLinks,
+ suspense: false,
+ refetchOnMount: 'always',
+ }));
+}
+
+export function useEmailLinksStatus() {
+ const links = useEmailLinksQuery();
+ return () => {
+ if (!links.data || links.error) {
+ return false;
+ }
+ return links.data?.length > 0;
+ };
+}
+
+function invalidateEmailLinks() {
+ queryClient.invalidateQueries({
+ queryKey: EMAIL_LINKS_QUERY_KEY,
+ });
+ queryClient.cancelQueries({ queryKey: queryKeys.all.email });
+ queryClient.setQueriesData({ queryKey: queryKeys.all.email }, () => ({
+ pages: [],
+ pageParams: [],
+ }));
+}
+
+/** Arbitrary threshold in ms between created_at and updated_at */
+const CREATED_UPDATED_AT_THRESHOLD = 1_000;
+
+/**
+ * Try and determine if the link is the first time it was created
+ * by checking if the created_at and updated_at are within the threshold
+ */
+function isFirstTimeEmailLink(link: Link) {
+ const createdAt = new Date(link.created_at);
+ const updatedAt = new Date(link.updated_at);
+
+ return (
+ createdAt.getTime() - updatedAt.getTime() < CREATED_UPDATED_AT_THRESHOLD
+ );
+}
+
+/** Returns true if the link needs to be synced */
+function linkNeedsSync(link: Link) {
+ return link.is_sync_active === false && isFirstTimeEmailLink(link);
+}
+
+/** Returns true if any of the links need to be synced */
+function anyLinksNeedSync(links: Link[]) {
+ return links.some(linkNeedsSync);
+}
+
+type EmailSyncError =
+ /** The email link has already been initialized*/
+ | { tag: 'AlreadyInitialized' }
+ | { tag: 'FailedToInitialize'; message: string };
+
+/**
+ * Calls email service to start syncing and initialize a new email link.
+ *
+ * @returns ok if syncing was started, err if syncing failed
+ */
+async function syncEmails(): Promise<Result<void, EmailSyncError>> {
+ const initResult = await emailClient.init();
+
+ if (isErr(initResult)) {
+ const [errors] = initResult;
+ const badRequestError = errors.find((err) => err.code === '400');
+ return err(
+ badRequestError
+ ? { tag: 'AlreadyInitialized' as const }
+ : {
+ tag: 'FailedToInitialize' as const,
+ message: 'Failed to initialize',
+ }
+ );
+ }
+
+ return okAsync(undefined);
+}
+
+/**
+ * The time in ms between making a polling fetch for
+ * new emails during the sync process.
+ */
+const EMAIL_POLLING_INTERVAL = 1_000;
+
+/**
+ * How long in ms we should poll for emails during the sync process.
+ */
+const EMAIL_POLLING_TIMEOUT = 20_000;
+
+/**
+ * Starts a polling fetch for new emails during the sync process.
+ */
+function startEmailPolling() {
+ if (emailRefetchInterval()) return;
+ setEmailRefetchInterval(EMAIL_POLLING_INTERVAL);
+ setTimeout(() => {
+ stopEmailPolling();
+ }, EMAIL_POLLING_TIMEOUT);
+}
+
+/**
+ * Stops the polling fetch for new emails during the sync process.
+ */
+function stopEmailPolling() {
+ setEmailRefetchInterval(undefined);
+}
+
+/**
+ * Starts syncing and polling emails if there is a new link
+ *
+ * @returns true if syncing emails was started
+ */
+function maybeStartEmailSync(links: Link[]): boolean {
+ if (!anyLinksNeedSync(links)) {
+ return false;
+ }
+ syncEmails();
+ startEmailPolling();
+ return true;
+}
+
+/**
+ * Disconnects the email service and invalidates the email links query.
+ *
+ * NOTE: only to be used in development
+ *
+ * @returns ok if the email service was disconnected, err if it failed to disconnect
+ */
+function disconnectEmail(): ResultAsync<void, 'failed-to-disconnect'> {
+ return ResultAsync.fromSafePromise(emailClient.stopSync()).andThen(
+ (response) =>
+ isErr(response) ? err('failed-to-disconnect') : okAsync(void 0)
+ );
+}
+
+/**
+ * Connects to the email service and authenticates with email permissions.
+ *
+ * @returns A promise that resolves when the auth success message is received.
+ */
+function connectEmail(): ResultAsync<void, TimeoutError> {
+ openEmailAuthPopup({
+ idpName: 'google_gmail',
+ returnPath: '/app/login/popup/success',
+ });
+
+ return authenticateWithEmailPermissions();
+}
+
+/**
+ * Hooks for interacting with email links.
+ */
+export function useEmailLinks() {
+ const invalidations = async () => {
+ // invalidateEmailLinks();
+ await updateUserAuth();
+ await updateUserInfo();
+ };
+
+ const query = useEmailLinksQuery();
+
+ return {
+ query: query,
+ status: useEmailLinksStatus(),
+ connect: () => connectEmail().andTee(invalidations),
+ disconnect: () => disconnectEmail().andTee(invalidations),
+ maybeSync: maybeStartEmailSync,
+ invalidate: () => invalidateEmailLinks(),
+ refetchInterval: emailRefetchInterval,
+ };
+}
diff --git a/js/app/packages/core/util/whenSettled.ts b/js/app/packages/core/util/whenSettled.ts
new file mode 100644
index 0000000000..8711d3f629
--- /dev/null
+++ b/js/app/packages/core/util/whenSettled.ts
@@ -0,0 +1,74 @@
+import type { UseQueryResult } from '@tanstack/solid-query';
+import type { Resource } from 'solid-js';
+import { createEffect, createRoot, onCleanup, untrack } from 'solid-js';
+
+type Suspendable<T> = Resource<T> | UseQueryResult<T>;
+
+type SettledState<T> =
+ | { status: 'pending' }
+ | { status: 'success'; data: T }
+ | { status: 'error'; error: Error };
+
+function getSettledState<T>(suspendable: Suspendable<T>): SettledState<T> {
+ if ('loading' in suspendable && !('isSuccess' in suspendable)) {
+ const resource = suspendable as Resource<T>;
+ if (resource.error) {
+ return { status: 'error', error: resource.error };
+ }
+ if (!resource.loading && resource() !== undefined) {
+ return { status: 'success', data: resource()! };
+ }
+ return { status: 'pending' };
+ }
+
+ const query = suspendable as UseQueryResult<T>;
+ if (query.isError && query.error) {
+ return { status: 'error', error: query.error as Error };
+ }
+ if (query.isSuccess && query.data !== undefined) {
+ return { status: 'success', data: query.data };
+ }
+ return { status: 'pending' };
+}
+
+/**
+ * A helper function to run a callback ONCE when a Suspendable has settled.
+ *
+ * Essentially a convenience wrapper around `createEffect` calls callback once
+ * once !t.eror and !t.loading are true.
+ *
+ * @param suspendable The Suspendable to wait for.
+ * @param onSettled The callback to run once the Suspendable has settled.
+ * @param onError The callback to run if the Suspendable fails.
+ * @returns A function that can be called to cancel the callback.
+ */
+export function whenSettled<T>(
+ suspendable: Suspendable<T>,
+ onSettled: (data: T) => void,
+ onError?: (error: Error) => void
+): () => void {
+ let dispose: (() => void) | undefined;
+
+ createRoot((d) => {
+ dispose = d;
+
+ createEffect(() => {
+ const state = getSettledState(suspendable);
+
+ if (state.status === 'pending') return;
+
+ untrack(() => {
+ if (state.status === 'error') {
+ onError?.(state.error);
+ } else {
+ onSettled(state.data);
+ }
+ });
+ d();
+ });
+ });
+
+ onCleanup(() => dispose?.());
+
+ return () => dispose?.();
+}