Skip to content

feat(clerk-js): Correct mounted component/modal behaviour #707

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

Merged
merged 7 commits into from
Jan 30, 2023
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
15 changes: 15 additions & 0 deletions packages/clerk-js/src/core/clerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ import {
isAccountsHostedPages,
isDevOrStagingUrl,
isError,
noOrganizationExists,
noUserExists,
sessionExistsAndSingleSessionModeEnabled,
setSearchParameterInHash,
stripOrigin,
validateFrontendApi,
Expand Down Expand Up @@ -211,6 +214,9 @@ export default class Clerk implements ClerkInterface {

public openSignIn = (props?: SignInProps): void => {
this.assertComponentsReady(this.#componentControls);
if (sessionExistsAndSingleSessionModeEnabled(this, this.#environment) && this.#instanceType === 'development') {
return console.warn('Cannot open SignIn because a session exists and single session mode is enabled.');
}
this.#componentControls?.openModal('signIn', props || {});
};

Expand All @@ -221,6 +227,9 @@ export default class Clerk implements ClerkInterface {

public openSignUp = (props?: SignInProps): void => {
this.assertComponentsReady(this.#componentControls);
if (sessionExistsAndSingleSessionModeEnabled(this, this.#environment) && this.#instanceType === 'development') {
return console.warn('Cannot open SignUp because a session exists and single session mode is enabled.');
}
this.#componentControls?.openModal('signUp', props || {});
};

Expand All @@ -231,6 +240,9 @@ export default class Clerk implements ClerkInterface {

public openUserProfile = (props?: UserProfileProps): void => {
this.assertComponentsReady(this.#componentControls);
if (noUserExists(this) && this.#instanceType === 'development') {
return console.warn('Cannot open UserProfile because no session is present.');
}
this.#componentControls?.openModal('userProfile', props || {});
};

Expand All @@ -241,6 +253,9 @@ export default class Clerk implements ClerkInterface {

public openOrganizationProfile = (props?: OrganizationProfileProps): void => {
this.assertComponentsReady(this.#componentControls);
if (noOrganizationExists(this) && this.#instanceType === 'development') {
return console.warn('Cannot open OrganizationProfile because there is no active organization.');
}
this.#componentControls?.openModal('organizationProfile', props || {});
};

Expand Down
167 changes: 80 additions & 87 deletions packages/clerk-js/src/ui/common/__tests__/withRedirectToHome.test.tsx
Original file line number Diff line number Diff line change
@@ -1,108 +1,101 @@
import { render, screen } from '@clerk/shared/testUtils';
import type { EnvironmentResource } from '@clerk/types';
import React from 'react';

import type { AuthConfig, DisplayConfig } from '../../../core/resources';
import { CoreSessionContext, useEnvironment } from '../../contexts';
import { withRedirectToHome } from '../withRedirectToHome';
import { bindCreateFixtures, render, screen } from '../../../testUtils';
import {
withRedirectToHomeOrganizationGuard,
withRedirectToHomeSingleSessionGuard,
withRedirectToHomeUserGuard,
} from '../withRedirectToHome';

const mockNavigate = jest.fn();
jest.mock('ui/hooks', () => ({
useNavigate: () => ({ navigate: mockNavigate }),
}));
const { createFixtures } = bindCreateFixtures('SignIn');

jest.mock('ui/contexts', () => ({
...jest.requireActual('ui/contexts'),
useEnvironment: jest.fn(),
}));
describe('withRedirectToHome', () => {
describe('withRedirectToHomeSingleSessionGuard', () => {
it('redirects if a session is present and single session mode is enabled', async () => {
const { wrapper, fixtures } = await createFixtures(f => {
f.withUser({});
});

const Tester = () => <div>Tester</div>;
const WithHOC = withRedirectToHomeSingleSessionGuard(() => <></>);

describe('withRedirectToHome(Component)', () => {
beforeEach(() => {
mockNavigate.mockReset();
});
render(<WithHOC />, { wrapper });

describe('when there is a session', () => {
describe('and the instance is in single session mode', () => {
beforeEach(() => {
(useEnvironment as jest.Mock).mockImplementation(
() =>
({
displayConfig: {
homeUrl: 'http://my-home.com',
} as Partial<DisplayConfig>,
authConfig: {
singleSessionMode: true,
} as Partial<AuthConfig>,
} as Partial<EnvironmentResource>),
);
});
expect(fixtures.router.navigate).toHaveBeenCalledWith(fixtures.environment.displayConfig.homeUrl);
});

it('navigates to home_url', () => {
const Component = withRedirectToHome(Tester);
render(
<CoreSessionContext.Provider value={{ value: { id: 'sess_id' } as any }}>
<Component />
</CoreSessionContext.Provider>,
);
expect(mockNavigate).toHaveBeenNthCalledWith(1, 'http://my-home.com');
expect(screen.queryByText('Tester')).not.toBeInTheDocument();
});
it('renders the children if is a session is not present', async () => {
const { wrapper } = await createFixtures();

const WithHOC = withRedirectToHomeSingleSessionGuard(() => <>test</>);

render(<WithHOC />, { wrapper });

screen.getByText('test');
});

describe('and the instance is not in single session mode', () => {
beforeEach(() => {
(useEnvironment as jest.Mock).mockImplementation(
() =>
({
displayConfig: {
homeUrl: 'http://my-home.com',
} as Partial<DisplayConfig>,
authConfig: {
singleSessionMode: false,
} as Partial<AuthConfig>,
} as Partial<EnvironmentResource>),
);
it('renders the children if multi session mode is enabled and a session is present', async () => {
const { wrapper } = await createFixtures(f => {
f.withUser({});
f.withMultiSessionMode();
});

it('renders the wrapped component', () => {
const Component = withRedirectToHome(Tester);
render(
<CoreSessionContext.Provider value={{ value: { id: 'sess_id' } as any }}>
<Component />
</CoreSessionContext.Provider>,
);
expect(mockNavigate).not.toHaveBeenCalled();
expect(screen.queryByText('Tester')).toBeInTheDocument();
const WithHOC = withRedirectToHomeSingleSessionGuard(() => <>test</>);

render(<WithHOC />, { wrapper });

screen.getByText('test');
});
});

describe('redirectToHomeUserGuard', () => {
it('redirects if no user is present', async () => {
const { wrapper, fixtures } = await createFixtures();

const WithHOC = withRedirectToHomeUserGuard(() => <></>);

render(<WithHOC />, { wrapper });

expect(fixtures.router.navigate).toHaveBeenCalledWith(fixtures.environment.displayConfig.homeUrl);
});

it('renders the children if is a user is present', async () => {
const { wrapper } = await createFixtures(f => {
f.withUser({});
});

const WithHOC = withRedirectToHomeUserGuard(() => <>test</>);

render(<WithHOC />, { wrapper });

screen.getByText('test');
});
});

describe('when there is no session', () => {
beforeEach(() => {
(useEnvironment as jest.Mock).mockImplementation(
() =>
({
displayConfig: {
homeUrl: 'http://my-home.com',
} as Partial<DisplayConfig>,
authConfig: {
singleSessionMode: true,
} as Partial<AuthConfig>,
} as Partial<EnvironmentResource>),
);
describe('withRedirectToHomeOrganizationGuard', () => {
it('redirects if no organization is active', async () => {
const { wrapper, fixtures } = await createFixtures(f => {
f.withUser({});
f.withOrganizations();
});

const WithHOC = withRedirectToHomeOrganizationGuard(() => <></>);

render(<WithHOC />, { wrapper });

expect(fixtures.router.navigate).toHaveBeenCalledWith(fixtures.environment.displayConfig.homeUrl);
});

it('renders the wrapped component', () => {
const Component = withRedirectToHome(Tester);
render(
<CoreSessionContext.Provider value={{ value: undefined }}>
<Component />
</CoreSessionContext.Provider>,
);
expect(mockNavigate).not.toHaveBeenCalled();
expect(screen.queryByText('Tester')).toBeInTheDocument();
it('renders the children if is an organization is active', async () => {
const { wrapper } = await createFixtures(f => {
f.withUser({ organization_memberships: ['Org1'] });
f.withOrganizations();
});

const WithHOC = withRedirectToHomeOrganizationGuard(() => <>test</>);

render(<WithHOC />, { wrapper });

screen.getByText('test');
});
});
});
58 changes: 42 additions & 16 deletions packages/clerk-js/src/ui/common/withRedirectToHome.tsx
Original file line number Diff line number Diff line change
@@ -1,39 +1,65 @@
import type { SignInProps, SignUpProps } from '@clerk/types';
import React, { useContext } from 'react';
import type { ComponentType } from 'react';
import React from 'react';

import { useEnvironment } from '../contexts';
import { CoreSessionContext } from '../contexts/CoreSessionContext';
import type { AvailableComponentProps } from '../../ui/types';
import type { ComponentGuard } from '../../utils';
import { noOrganizationExists, noUserExists, sessionExistsAndSingleSessionModeEnabled } from '../../utils';
import { useCoreClerk, useEnvironment, useOptions } from '../contexts';
import { useNavigate } from '../hooks';

export function withRedirectToHome<P extends SignInProps | SignUpProps | { continueExisting?: boolean }>(
Component: React.ComponentType<P>,
displayName?: string,
function withRedirectToHome<P extends AvailableComponentProps>(
Component: ComponentType<P>,
condition: ComponentGuard,
warning?: string,
): (props: P) => null | JSX.Element {
displayName = displayName || Component.displayName || Component.name || 'Component';
const displayName = Component.displayName || Component.name || 'Component';
Component.displayName = displayName;

const HOC = (props: P) => {
const { navigate } = useNavigate();
const { authConfig, displayConfig } = useEnvironment();
const { singleSessionMode } = authConfig;
const ctx = useContext(CoreSessionContext);
const session = ctx?.value;
const clerk = useCoreClerk();
const environment = useEnvironment();
const options = useOptions();

const shouldRedirect = condition(clerk, environment, options);
React.useEffect(() => {
if (singleSessionMode && !!session) {
navigate(displayConfig.homeUrl);
if (shouldRedirect) {
if (warning && environment.displayConfig.instanceEnvironmentType === 'development') {
console.warn(warning);
}
navigate(environment.displayConfig.homeUrl);
}
}, []);

if (singleSessionMode && !!session) {
if (shouldRedirect) {
return null;
}

// @ts-ignore
return <Component {...props} />;
};

HOC.displayName = `withRedirectToHome(${displayName})`;

return HOC;
}

export const withRedirectToHomeSingleSessionGuard = <P extends AvailableComponentProps>(Component: ComponentType<P>) =>
withRedirectToHome(
Component,
sessionExistsAndSingleSessionModeEnabled,
'Cannot render the component as a session already exists and single session mode is enabled. Redirecting to the home url.',
);

export const withRedirectToHomeUserGuard = <P extends AvailableComponentProps>(Component: ComponentType<P>) =>
withRedirectToHome(
Component,
noUserExists,
'Cannot render the component as no user exists. Redirecting to the home url.',
);

export const withRedirectToHomeOrganizationGuard = <P extends AvailableComponentProps>(Component: ComponentType<P>) =>
withRedirectToHome(
Component,
noOrganizationExists,
'Cannot render the component as there is no active organization. Redirecting to the home url.',
);
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { OrganizationProfileProps } from '@clerk/types';
import React from 'react';

import { withOrganizationsEnabledGuard } from '../../common';
import { withOrganizationsEnabledGuard, withRedirectToHomeOrganizationGuard } from '../../common';
import { ComponentContext, useCoreOrganization, withCoreUserGuard } from '../../contexts';
import { Flow } from '../../customizables';
import { ProfileCard, withCardStateProvider } from '../../elements';
Expand Down Expand Up @@ -42,10 +42,10 @@ const AuthenticatedRoutes = withCoreUserGuard(() => {
);
});

export const OrganizationProfile = withOrganizationsEnabledGuard(
withCardStateProvider(_OrganizationProfile),
'OrganizationProfile',
{ mode: 'redirect' },
export const OrganizationProfile = withRedirectToHomeOrganizationGuard(
withOrganizationsEnabledGuard(withCardStateProvider(_OrganizationProfile), 'OrganizationProfile', {
mode: 'redirect',
}),
);

export const OrganizationProfileModal = (props: OrganizationProfileProps): JSX.Element => {
Expand Down
1 change: 1 addition & 0 deletions packages/clerk-js/src/ui/components/SignIn/SignIn.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { SignInSSOCallback } from './SignInSSOCallback';
import { SignInStart } from './SignInStart';

function RedirectToSignIn() {
// eslint-disable-next-line @typescript-eslint/unbound-method
const { redirectToSignIn } = useCoreClerk();
React.useEffect(() => {
void redirectToSignIn();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { withRedirectToHome } from '../../common/withRedirectToHome';
import { withRedirectToHomeSingleSessionGuard } from '../../common';
import { useEnvironment, useSignInContext } from '../../contexts';
import { Col, descriptors, Flow, Icon } from '../../customizables';
import { Card, CardAlert, Header, PreviewButton, UserPreview, withCardStateProvider } from '../../elements';
Expand Down Expand Up @@ -77,4 +77,6 @@ const _SignInAccountSwitcher = () => {
</Flow.Part>
);
};
export const SignInAccountSwitcher = withRedirectToHome(withCardStateProvider(_SignInAccountSwitcher));
export const SignInAccountSwitcher = withRedirectToHomeSingleSessionGuard(
withCardStateProvider(_SignInAccountSwitcher),
);
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { SignInFactor } from '@clerk/types';
import React from 'react';

import { withRedirectToHome } from '../../common/withRedirectToHome';
import { withRedirectToHomeSingleSessionGuard } from '../../common';
import { useCoreSignIn, useEnvironment } from '../../contexts';
import { ErrorCard, LoadingCard, withCardStateProvider } from '../../elements';
import { localizationKeys } from '../../localization';
Expand Down Expand Up @@ -117,4 +117,4 @@ export function _SignInFactorOne(): JSX.Element {
}
}

export const SignInFactorOne = withRedirectToHome(withCardStateProvider(_SignInFactorOne));
export const SignInFactorOne = withRedirectToHomeSingleSessionGuard(withCardStateProvider(_SignInFactorOne));
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { SignInFactor } from '@clerk/types';
import React from 'react';

import { withRedirectToHome } from '../../common/withRedirectToHome';
import { withRedirectToHomeSingleSessionGuard } from '../../common';
import { useCoreSignIn } from '../../contexts';
import { LoadingCard, withCardStateProvider } from '../../elements';
import { SignInFactorTwoAlternativeMethods } from './SignInFactorTwoAlternativeMethods';
Expand Down Expand Up @@ -81,4 +81,4 @@ export function _SignInFactorTwo(): JSX.Element {
}
}

export const SignInFactorTwo = withRedirectToHome(withCardStateProvider(_SignInFactorTwo));
export const SignInFactorTwo = withRedirectToHomeSingleSessionGuard(withCardStateProvider(_SignInFactorTwo));
Loading