Skip to content

Commit d50c67c

Browse files
committed
Introduce root route to resolve tasks
1 parent a8a6526 commit d50c67c

18 files changed

+143
-90
lines changed

packages/clerk-js/src/core/__tests__/clerk.test.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -486,14 +486,14 @@ describe('Clerk singleton', () => {
486486
getToken: jest.fn(),
487487
lastActiveToken: { getRawString: () => 'mocked-token' },
488488
tasks: [{ key: 'org' }],
489-
currentTask: { key: 'org', __internal_getUrl: () => 'https://foocorp.com/add-organization' },
489+
currentTask: { key: 'org', __internal_getUrl: () => 'https://sut/tasks/add-organization' },
490490
reload: jest.fn(() =>
491491
Promise.resolve({
492492
id: '1',
493493
status: 'pending',
494494
user: {},
495495
tasks: [{ key: 'org' }],
496-
currentTask: { key: 'org', __internal_getUrl: () => 'https://foocorp.com/add-organization' },
496+
currentTask: { key: 'org', __internal_getUrl: () => 'https://sut/tasks/add-organization' },
497497
}),
498498
),
499499
};
@@ -2276,7 +2276,7 @@ describe('Clerk singleton', () => {
22762276
status: 'pending',
22772277
user: {},
22782278
tasks: [{ key: 'org' }],
2279-
currentTask: { key: 'org', __internal_getUrl: () => 'https://foocorp.com/add-organization' },
2279+
currentTask: { key: 'org', __internal_getUrl: () => 'https://sut/tasks/add-organization' },
22802280
lastActiveToken: { getRawString: () => 'mocked-token' },
22812281
};
22822282

@@ -2305,7 +2305,7 @@ describe('Clerk singleton', () => {
23052305
await sut.setActive({ session: mockResource as any as PendingSessionResource });
23062306
await sut.__experimental_nextTask();
23072307

2308-
expect(mockNavigate.mock.calls[0][0]).toBe('/sign-in#/add-organization');
2308+
expect(mockNavigate.mock.calls[0][0]).toBe('/sign-in#/tasks/add-organization');
23092309
});
23102310
});
23112311

packages/clerk-js/src/core/sessionTasks.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ export function navigateToTask(
3030
const taskRoute = `/tasks/${SESSION_TASK_ROUTE_BY_KEY[routeKey]}`;
3131

3232
if (componentNavigationContext) {
33-
return componentNavigationContext.navigate(componentNavigationContext.indexPath + routeKey);
33+
return componentNavigationContext.navigate(componentNavigationContext.indexPath + taskRoute);
3434
}
3535

3636
const signInUrl = options['signInUrl'] || environment.displayConfig.signInUrl;

packages/clerk-js/src/core/warnings.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ const createMessageForDisabledOrganizations = (
1212
);
1313
};
1414
const warnings = {
15-
cannotRenderComponentWhenSessionExists:
16-
'The <SignUp/> and <SignIn/> components cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the Home URL instead.',
15+
cannotRenderComponentWithoutSession:
16+
'The component cannot render if the user does not have a valid session. Clerk is redirecting to the value set in `signInUrl` URL instead.',
1717
cannotRenderSignUpComponentWhenSessionExists:
1818
'The <SignUp/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the value set in `afterSignUp` URL instead.',
1919
cannotRenderSignUpComponentWhenTaskExists:

packages/clerk-js/src/ui/common/redirects.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { SessionTask } from '@clerk/types';
22

3+
import { SESSION_TASK_ROUTE_BY_KEY } from '../../core/sessionTasks';
34
import { buildURL } from '../../utils/url';
45
import type { SignInContextType, SignUpContextType, UserProfileContextType } from './../contexts';
56

@@ -44,7 +45,7 @@ export function buildSessionTaskRedirectUrl({
4445
routing,
4546
baseUrl,
4647
path,
47-
endpoint: '/tasks',
48+
endpoint: `/tasks/${SESSION_TASK_ROUTE_BY_KEY[task.key]}`,
4849
authQueryString: null,
4950
});
5051
}

packages/clerk-js/src/ui/common/withRedirect.tsx

+22-3
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@ import { isDevelopmentFromPublishableKey } from '@clerk/shared/keys';
22
import { useClerk } from '@clerk/shared/react';
33
import type { Clerk, ClerkOptions, EnvironmentResource } from '@clerk/types';
44
import type { ComponentType } from 'react';
5-
import React from 'react';
5+
import React, { useContext } from 'react';
66

77
import { warnings } from '../../core/warnings';
88
import type { ComponentGuard } from '../../utils';
9-
import { sessionExistsAndSingleSessionModeEnabled } from '../../utils';
10-
import { useEnvironment, useOptions, useSignInContext, useSignUpContext } from '../contexts';
9+
import { noSessionExists, sessionExistsAndSingleSessionModeEnabled } from '../../utils';
10+
import { SignInContext, useEnvironment, useOptions, useSignInContext, useSignUpContext } from '../contexts';
1111
import { useRouter } from '../router';
1212
import type { AvailableComponentProps } from '../types';
1313

@@ -93,3 +93,22 @@ export const withRedirectToAfterSignUp = <P extends AvailableComponentProps>(Com
9393

9494
return HOC;
9595
};
96+
97+
export const withRedirectToSignIn = <P extends AvailableComponentProps>(Component: ComponentType<P>) => {
98+
const displayName = Component.displayName || Component.name || 'Component';
99+
Component.displayName = displayName;
100+
101+
const HOC = (props: P) => {
102+
const signInCtx = useContext(SignInContext);
103+
return withRedirect(
104+
Component,
105+
noSessionExists,
106+
({ clerk }) => signInCtx?.signInUrl || clerk.buildSignInUrl(),
107+
warnings.cannotRenderComponentWithoutSession,
108+
)(props);
109+
};
110+
111+
HOC.displayName = `withRedirectToSignIn(${displayName})`;
112+
113+
return HOC;
114+
};

packages/clerk-js/src/ui/components/OrganizationList/OrganizationListPage.tsx

+5-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { useOrganizationList, useUser } from '@clerk/shared/react';
22
import { useContext, useState } from 'react';
33

44
import { useEnvironment, useOrganizationListContext } from '../../contexts';
5-
import { SessionTaskContext } from '../../contexts/components/SessionTask';
5+
import { SessionTasksContext } from '../../contexts/components/SessionTasks';
66
import { Box, Col, descriptors, Flex, localizationKeys, Spinner } from '../../customizables';
77
import { Action, Actions, Card, Header, useCardState, withCardStateProvider } from '../../elements';
88
import { useInView } from '../../hooks';
@@ -17,6 +17,8 @@ import { organizationListParams } from './utils';
1717
const useOrganizationListInView = () => {
1818
const { userMemberships, userInvitations, userSuggestions } = useOrganizationList(organizationListParams);
1919

20+
console.log({ userMemberships });
21+
2022
const { ref } = useInView({
2123
threshold: 0,
2224
onChange: inView => {
@@ -112,7 +114,7 @@ export const OrganizationListPage = withCardStateProvider(() => {
112114
const OrganizationListFlows = ({ showListInitially }: { showListInitially: boolean }) => {
113115
const { navigateAfterCreateOrganization, skipInvitationScreen, hideSlug } = useOrganizationListContext();
114116
const [isCreateOrganizationFlow, setCreateOrganizationFlow] = useState(!showListInitially);
115-
const sessionTaskContext = useContext(SessionTaskContext);
117+
const sessionTasksContext = useContext(SessionTasksContext);
116118
return (
117119
<>
118120
{!isCreateOrganizationFlow && (
@@ -127,7 +129,7 @@ const OrganizationListFlows = ({ showListInitially }: { showListInitially: boole
127129
>
128130
<CreateOrganizationForm
129131
flow='organizationList'
130-
onComplete={sessionTaskContext?.nextTask}
132+
onComplete={sessionTasksContext?.nextTask}
131133
startPage={{ headerTitle: localizationKeys('organizationList.createOrganization') }}
132134
skipInvitationScreen={skipInvitationScreen}
133135
navigateAfterCreateOrganization={org =>

packages/clerk-js/src/ui/components/OrganizationList/UserMembershipList.tsx

+4-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { OrganizationResource } from '@clerk/types';
33
import { useContext } from 'react';
44

55
import { useOrganizationListContext } from '../../contexts';
6-
import { SessionTaskContext } from '../../contexts/components/SessionTask';
6+
import { SessionTasksContext } from '../../contexts/components/SessionTasks';
77
import { OrganizationPreview, PersonalWorkspacePreview, useCardState, withCardStateProvider } from '../../elements';
88
import { localizationKeys } from '../../localization';
99
import { OrganizationListPreviewButton, sharedMainIdentifierSx } from './shared';
@@ -12,7 +12,7 @@ export const MembershipPreview = withCardStateProvider((props: { organization: O
1212
const card = useCardState();
1313
const { navigateAfterSelectOrganization } = useOrganizationListContext();
1414
const { isLoaded, setActive } = useOrganizationList();
15-
const sessionTaskContext = useContext(SessionTaskContext);
15+
const sessionTasksContext = useContext(SessionTasksContext);
1616

1717
if (!isLoaded) {
1818
return null;
@@ -23,8 +23,8 @@ export const MembershipPreview = withCardStateProvider((props: { organization: O
2323
organization,
2424
});
2525

26-
if (sessionTaskContext?.nextTask) {
27-
return sessionTaskContext?.nextTask();
26+
if (sessionTasksContext?.nextTask) {
27+
return sessionTasksContext?.nextTask();
2828
}
2929

3030
await navigateAfterSelectOrganization(organization);

packages/clerk-js/src/ui/components/SessionTasks/OrganizationSelectionTask.tsx

-18
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,59 @@
11
import { useClerk } from '@clerk/shared/react';
22
import { eventComponentMounted } from '@clerk/shared/telemetry';
33
import type { SessionTask } from '@clerk/types';
4-
import { useCallback, useEffect } from 'react';
4+
import { useCallback, useContext, useEffect } from 'react';
55

66
import { SESSION_TASK_ROUTE_BY_KEY } from '../../../core/sessionTasks';
7-
import { SessionTaskContext as SessionTaskContext } from '../../contexts/components/SessionTask';
7+
import { withRedirectToSignIn } from '../../../ui/common';
8+
import { OrganizationListContext, SignInContext, SignUpContext } from '../../../ui/contexts';
9+
import { Card, LoadingCardContainer, withCardStateProvider } from '../../../ui/elements';
10+
import { SessionTasksContext as SessionTasksContext } from '../../contexts/components/SessionTasks';
811
import { Route, Switch, useRouter } from '../../router';
9-
import { LazyOrganizationSelectionTask } from './lazyTasks';
10-
import { usePreloadTasks } from './usePreloadTasks';
12+
import { OrganizationList } from '../OrganizationList';
13+
14+
const SessionTasksStart = withCardStateProvider(() => {
15+
const clerk = useClerk();
16+
const { navigate } = useRouter();
17+
18+
useEffect(() => {
19+
const timeoutId = setTimeout(() => {
20+
void clerk.session?.reload().then(session => {
21+
if (!session.currentTask?.key) {
22+
void navigate(clerk.buildAfterSignInUrl());
23+
return;
24+
}
25+
26+
void navigate(SESSION_TASK_ROUTE_BY_KEY[session.currentTask?.key]);
27+
});
28+
}, 1000);
29+
return () => clearTimeout(timeoutId);
30+
}, [navigate, clerk]);
31+
32+
return (
33+
<Card.Root>
34+
<Card.Content>
35+
<LoadingCardContainer />
36+
</Card.Content>
37+
<Card.Footer />
38+
</Card.Root>
39+
);
40+
});
1141

1242
function SessionTaskRoutes(): JSX.Element {
1343
return (
1444
<Switch>
1545
<Route path={SESSION_TASK_ROUTE_BY_KEY['org']}>
16-
<LazyOrganizationSelectionTask />
46+
<OrganizationListContext.Provider
47+
value={{
48+
componentName: 'OrganizationList',
49+
skipInvitationScreen: true,
50+
}}
51+
>
52+
<OrganizationList />
53+
</OrganizationListContext.Provider>
54+
</Route>
55+
<Route index>
56+
<SessionTasksStart />
1757
</Route>
1858
</Switch>
1959
);
@@ -22,31 +62,38 @@ function SessionTaskRoutes(): JSX.Element {
2262
/**
2363
* @internal
2464
*/
25-
export function SessionTask({ redirectUrlComplete }: { redirectUrlComplete: string }): JSX.Element {
26-
usePreloadTasks();
27-
28-
const { __experimental_nextTask, session, telemetry } = useClerk();
65+
function _SessionTask(): JSX.Element {
66+
const clerk = useClerk();
2967
const { navigate } = useRouter();
68+
const signInContext = useContext(SignInContext);
69+
const signUpContext = useContext(SignUpContext);
3070

31-
const task = session?.currentTask;
71+
const redirectUrlComplete =
72+
signInContext?.afterSignInUrl ?? signUpContext?.afterSignUpUrl ?? clerk?.buildAfterSignInUrl();
3273

3374
useEffect(() => {
34-
if (task) {
35-
telemetry?.record(eventComponentMounted('SessionTask', { task: task.key }));
75+
const task = clerk.session?.currentTask;
76+
77+
if (!task) {
78+
void navigate(redirectUrlComplete);
3679
return;
3780
}
3881

39-
void navigate(redirectUrlComplete);
40-
}, [task, telemetry, navigate, redirectUrlComplete]);
82+
clerk.telemetry?.record(eventComponentMounted('SessionTask', { task: task.key }));
83+
}, [clerk, navigate, redirectUrlComplete]);
4184

4285
const nextTask = useCallback(
43-
() => __experimental_nextTask({ redirectUrlComplete }),
44-
[__experimental_nextTask, redirectUrlComplete],
86+
() => clerk.__experimental_nextTask({ redirectUrlComplete: redirectUrlComplete }),
87+
[clerk, redirectUrlComplete],
4588
);
4689

4790
return (
48-
<SessionTaskContext.Provider value={{ nextTask }}>
91+
<SessionTasksContext.Provider value={{ nextTask }}>
4992
<SessionTaskRoutes />
50-
</SessionTaskContext.Provider>
93+
</SessionTasksContext.Provider>
5194
);
5295
}
96+
97+
const SessionTask = withRedirectToSignIn(_SessionTask);
98+
99+
export { SessionTask };
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,22 @@
11
import { lazy } from 'react';
22

3-
export const preloadOrganizationSelectionTask = () =>
4-
import(/* webpackChunkName: "session-tasks"*/ './OrganizationSelectionTask');
3+
import { useEnvironment } from '../../contexts';
4+
import { useFetch } from '../../hooks';
55

6-
const LazyOrganizationSelectionTask = lazy(() =>
7-
import(/* webpackChunkName: "session-tasks"*/ './OrganizationSelectionTask').then(module => ({
8-
default: module.OrganizationSelectionTask,
9-
})),
10-
);
6+
/**
7+
* Preloads tasks based on the environment settings
8+
* @internal
9+
*/
10+
export function usePreloadTasks() {
11+
const { organizationSettings } = useEnvironment();
12+
13+
const hasTasks = organizationSettings.forceOrganizationSelection;
1114

12-
export { LazyOrganizationSelectionTask };
15+
void useFetch(hasTasks ? () => import(/* webpackChunkName: "session-tasks" */ '.') : undefined, 'preloadComponent', {
16+
staleTime: Infinity,
17+
});
18+
}
19+
20+
export const LazySessionTasks = lazy(() =>
21+
import(/* webpackChunkName: "session-tasks" */ '.').then(module => ({ default: module.SessionTask })),
22+
);
Original file line numberDiff line numberDiff line change
@@ -1,15 +0,0 @@
1-
import { useEnvironment } from '../../../ui/contexts';
2-
import { useFetch } from '../../../ui/hooks';
3-
import { preloadOrganizationSelectionTask } from './lazyTasks';
4-
5-
/**
6-
* Preloads tasks based on the environment settings
7-
* @internal
8-
*/
9-
export function usePreloadTasks() {
10-
const { organizationSettings } = useEnvironment();
11-
12-
if (organizationSettings.forceOrganizationSelection) {
13-
void useFetch(preloadOrganizationSelectionTask, 'preloadComponent', { staleTime: Infinity });
14-
}
15-
}

packages/clerk-js/src/ui/components/SignIn/SignIn.tsx

+5-3
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ import {
1414
} from '../../contexts';
1515
import { Flow } from '../../customizables';
1616
import { useFetch } from '../../hooks';
17-
import { SessionTasks } from '../../lazyModules/components';
1817
import { Route, Switch, useRouter, VIRTUAL_ROUTER_BASE_PATH } from '../../router';
18+
import { LazySessionTasks, usePreloadTasks } from '../SessionTasks/lazyTasks';
1919
import {
2020
LazySignUpContinue,
2121
LazySignUpSSOCallback,
@@ -130,7 +130,7 @@ function SignInRoutes(): JSX.Element {
130130
<LazySignUpVerifyPhone />
131131
</Route>
132132
<Route path='tasks'>
133-
<SessionTasks redirectUrlComplete={signInContext.afterSignInUrl} />
133+
<LazySessionTasks />
134134
</Route>
135135
<Route index>
136136
<LazySignUpContinue />
@@ -142,7 +142,7 @@ function SignInRoutes(): JSX.Element {
142142
</Route>
143143
)}
144144
<Route path='tasks'>
145-
<SessionTasks redirectUrlComplete={signInContext.afterSignInUrl} />
145+
<LazySessionTasks />
146146
</Route>
147147
<Route index>
148148
<SignInStart />
@@ -179,6 +179,8 @@ function SignInRoot() {
179179
*/
180180
usePreloadSignUp(signInContext.isCombinedFlow);
181181

182+
usePreloadTasks();
183+
182184
React.useEffect(() => {
183185
return __internal_setComponentNavigationContext?.({ indexPath, navigate });
184186
}, [indexPath, navigate]);

0 commit comments

Comments
 (0)