diff --git a/.changeset/mosaic-links.md b/.changeset/mosaic-links.md
new file mode 100644
index 00000000000..f0bb7542904
--- /dev/null
+++ b/.changeset/mosaic-links.md
@@ -0,0 +1,7 @@
+---
+'@clerk/mosaic': minor
+---
+
+A `?.user=security` link now opens a Mosaic component on that page in every routing mode, not only in `query` mode: the param is named after the component's base, so `?.modal.user=account` opens the profile modal on its account page. A component in `virtual`, `path` or `hash` mode moves to the page the link names and removes the param from the URL, including when the link is followed while the page is already open; a component that already has a page in the URL when it loads keeps it.
+
+Redirect flows in `UserProfile` (connecting an OAuth or enterprise account, and verifying an email address through an identity provider) return to the page and modal they started from through such a link, in every routing mode. The `__clerk_mosaic_modal` query param is no longer written or read.
diff --git a/packages/mosaic/src/__tests__/feature/routing.tsx b/packages/mosaic/src/__tests__/feature/routing.tsx
new file mode 100644
index 00000000000..4e3f76b9eba
--- /dev/null
+++ b/packages/mosaic/src/__tests__/feature/routing.tsx
@@ -0,0 +1,20 @@
+import type { ReactNode } from 'react';
+
+import { MosaicRoutingScope } from '../../routing/routing-scope';
+import type { RoutingMode } from '../../routing/use-mosaic-location';
+import { useRouterScope } from '../../routing/use-router';
+
+const routes = { root: '' } as const;
+
+export function InRoutingScope({
+ path,
+ routing = 'virtual',
+ children,
+}: {
+ path: string;
+ routing?: RoutingMode;
+ children: ReactNode;
+}) {
+ const { scope } = useRouterScope(routes, { routing, path, root: 'root' });
+ return {children};
+}
diff --git a/packages/mosaic/src/features/profile-pages/profile-pages.controller.ts b/packages/mosaic/src/features/profile-pages/profile-pages.controller.ts
index 10cd0284316..70e430135f6 100644
--- a/packages/mosaic/src/features/profile-pages/profile-pages.controller.ts
+++ b/packages/mosaic/src/features/profile-pages/profile-pages.controller.ts
@@ -14,11 +14,11 @@ const NO_PAGE = '';
// there when it is.
export function useProfilePagesController(pageIds: readonly string[] | undefined, options: ProfilePagesOptions) {
const ids = pageIds ?? [];
- const { route, go } = useRouterScope(Object.fromEntries(ids.map(id => [id, pageSegment(id)])), {
+ const { route, go, scope } = useRouterScope(Object.fromEntries(ids.map(id => [id, pageSegment(id)])), {
...options,
root: ids[0] ?? NO_PAGE,
ready: pageIds !== undefined,
});
- return { activePage: route, onPageChange: go };
+ return { activePage: route, onPageChange: go, scope };
}
diff --git a/packages/mosaic/src/features/profile/profile.modal-content.tsx b/packages/mosaic/src/features/profile/profile.modal-content.tsx
index 25b1a34e398..0456ecaf18a 100644
--- a/packages/mosaic/src/features/profile/profile.modal-content.tsx
+++ b/packages/mosaic/src/features/profile/profile.modal-content.tsx
@@ -50,7 +50,6 @@ export function ModalProfile({
diff --git a/packages/mosaic/src/features/profile/profile.tsx b/packages/mosaic/src/features/profile/profile.tsx
index 90fa6c76466..fc8c7e69628 100644
--- a/packages/mosaic/src/features/profile/profile.tsx
+++ b/packages/mosaic/src/features/profile/profile.tsx
@@ -2,6 +2,7 @@
import type { ReactNode } from 'react';
+import { MosaicRoutingScope } from '../../routing/routing-scope';
import type { RoutingMode } from '../../routing/use-mosaic-location';
import type { APIKeysPageProps } from '../api-keys/api-keys-table';
import type { OrganizationProfileProps } from '../organization-profile/organization-profile';
@@ -22,7 +23,6 @@ import { useMosaicProfile } from '../profile-pages/use-mosaic-profile';
import { useUserProfilePages } from '../switcher/switcher.pages';
import type { UserProfileProps } from '../user-profile/user-profile';
import { ORGANIZATION_PAGE_PREFIX, userProfilePageIds } from '../user-profile/user-profile.layout';
-import type { UserProfileOptions } from '../user-profile/user-profile.provider';
import { UserProfileProvider } from '../user-profile/user-profile.provider';
import type { UserProfileViewProps } from '../user-profile/user-profile.view';
import { UserProfileView } from '../user-profile/user-profile.view';
@@ -105,7 +105,6 @@ export function Profile(props: ProfileProps): ReactNode {
return (
);
@@ -118,7 +117,6 @@ export function Profile(props: ProfileProps): ReactNode {
('organizationProfileProps' in ownProps ? ownProps.organizationProfileProps : undefined) ?? {},
provider.organizationProfileProps,
)}
- presentation='mounted'
combined
/>
);
@@ -157,7 +155,6 @@ function withOrganizationDefaults; combined: boolean }) {
+}: CombinedProfileProps & { combined: boolean }) {
const model = useUserProfileUserModel();
const builtInPages = useUserProfilePages();
@@ -193,11 +190,7 @@ export function UserProfileSurface({
};
return (
-
+
{combined ? (
+
+
+
);
}
@@ -252,7 +247,7 @@ function CombinedUserProfileView({
? { pages: organizationProfilePanels(model.pages, apiKeysProps), customPages, pageOrder }
: undefined;
const pageIds = model.status === 'loading' ? undefined : userProfilePageIds({ ...viewProps, organization });
- const { activePage, onPageChange } = useProfilePagesController(pageIds, {
+ const { activePage, onPageChange, scope } = useProfilePagesController(pageIds, {
routing,
path,
notFound: parts =>
@@ -267,12 +262,14 @@ function CombinedUserProfileView({
return (
-
+
+
+
);
}
@@ -288,7 +285,7 @@ export function OrganizationProfileSurface({
}: OrganizationProfileProps) {
const model = useOrganizationProfileModel();
const pages = model.status === 'ready' ? organizationProfilePanels(model.pages, apiKeysProps) : undefined;
- const { activePage, onPageChange } = useProfilePagesController(
+ const { activePage, onPageChange, scope } = useProfilePagesController(
pages && organizationProfilePageIds({ pages, customPages, pageOrder }),
{ routing, path },
);
@@ -302,14 +299,16 @@ export function OrganizationProfileSurface({
return (
-
+
+
+
);
}
diff --git a/packages/mosaic/src/features/switcher/__tests__/switcher.new-profiles.feature.test.tsx b/packages/mosaic/src/features/switcher/__tests__/switcher.new-profiles.feature.test.tsx
index b082a193f74..76785a562a7 100644
--- a/packages/mosaic/src/features/switcher/__tests__/switcher.new-profiles.feature.test.tsx
+++ b/packages/mosaic/src/features/switcher/__tests__/switcher.new-profiles.feature.test.tsx
@@ -128,8 +128,8 @@ describe('Switcher with experimental.newProfiles', () => {
});
it.each([
- { name: 'combined', props: {}, expected: 'profile/account' },
- { name: 'user-only', props: { mode: 'user' as const }, expected: 'user-profile/account' },
+ { name: 'combined', props: {}, expected: '.modal.profile' },
+ { name: 'user-only', props: { mode: 'user' as const }, expected: '.modal.user' },
])('opens the $name profile as a modal, so an OAuth connection returns to it', async ({ props, expected }) => {
await renderWithNewProfiles(props, withConnectedAccounts([]));
const request = holdRequests('post', '/v1/me/external_accounts');
@@ -141,7 +141,7 @@ describe('Switcher with experimental.newProfiles', () => {
const body = new URLSearchParams(await request.requests[0]?.text());
const params = new URL(body.get('redirect_url') || '').searchParams;
- expect(params.get('__clerk_mosaic_modal')).toBe(expected);
+ expect(params.get(expected)).toBe('account');
expect(params.has('__clerk_modal_state')).toBe(false);
request.fail();
});
diff --git a/packages/mosaic/src/features/user-profile/__tests__/user-profile.feature.test.tsx b/packages/mosaic/src/features/user-profile/__tests__/user-profile.feature.test.tsx
index 1c85d9babef..bd6a3d95476 100644
--- a/packages/mosaic/src/features/user-profile/__tests__/user-profile.feature.test.tsx
+++ b/packages/mosaic/src/features/user-profile/__tests__/user-profile.feature.test.tsx
@@ -362,16 +362,16 @@ describe('UserProfile routed in the URL', () => {
it('starts over from the URL when its mode changes', async () => {
serve();
- startAt('/app?.user=security');
+ startAt('/app#.user=security');
const { rerender } = await renderWithClerk();
const user = userEvent.setup();
expectSelected('Account');
await user.click(screen.getByRole('tab', { name: 'Security' }));
- rerender();
+ rerender();
expectSelected('Account');
- rerender();
+ rerender();
expectSelected('Security');
});
diff --git a/packages/mosaic/src/features/user-profile/__tests__/user-profile.modal-return.feature.test.tsx b/packages/mosaic/src/features/user-profile/__tests__/user-profile.modal-return.feature.test.tsx
deleted file mode 100644
index 1f50cf890b7..00000000000
--- a/packages/mosaic/src/features/user-profile/__tests__/user-profile.modal-return.feature.test.tsx
+++ /dev/null
@@ -1,175 +0,0 @@
-import { Clerk } from '@clerk/clerk-js';
-import { ClerkContextProvider } from '@clerk/shared/react';
-import { act, configure, render, screen, within } from '@testing-library/react';
-import React from 'react';
-import { beforeAll, describe, expect, it, onTestFinished, vi } from 'vitest';
-import { page } from 'vitest/browser';
-
-import { publishableKey, serveFapi } from '../../../__tests__/feature/fake-fapi';
-import {
- fapiClient,
- fapiEnvironment,
- fapiMembership,
- fapiOrganization,
- fapiSession,
- fapiUser,
-} from '../../../__tests__/feature/fapi';
-import { renderWithClerk } from '../../../__tests__/feature/render';
-import { MosaicProvider } from '../../../mosaic-provider';
-import type { MosaicProfile } from '../../profile-pages/use-mosaic-profile';
-
-beforeAll(async () => {
- await import('../user-profile.modal-content');
-});
-
-beforeAll(() => page.viewport(1280, 800));
-
-function serve() {
- serveFapi({
- environment: fapiEnvironment(),
- client: fapiClient([fapiSession({ id: 'sess_1', user: fapiUser({ id: 'user_1' }) })]),
- });
-}
-
-function visit(search: string) {
- const original = window.location.href;
- window.history.replaceState(null, '', `${window.location.pathname}${search}#accounts`);
- onTestFinished(() => window.history.replaceState(null, '', original));
-}
-
-function strictMode() {
- configure({ reactStrictMode: true });
- onTestFinished(() => configure({ reactStrictMode: false }));
-}
-
-function PatchesHistoryOnMount({
- onReplaceState,
- children,
-}: {
- onReplaceState: (url: string) => void;
- children: React.ReactNode;
-}) {
- React.useEffect(() => {
- const original = window.history.replaceState.bind(window.history);
- window.history.replaceState = (state, unused, url) => {
- onReplaceState(String(url));
- original(state, unused, url);
- };
- return () => {
- window.history.replaceState = original;
- };
- }, [onReplaceState]);
- return children;
-}
-
-describe('UserProfile modal return', () => {
- it.each([
- { name: 'renders normally', strict: false },
- { name: 'renders in StrictMode', strict: true },
- ])('reopens the profile on the account page and clears the param when it $name', async ({ strict }) => {
- if (strict) {
- strictMode();
- }
- serve();
- visit('?__clerk_mosaic_modal=user-profile%2Faccount&tab=connections');
-
- await renderWithClerk(Page
);
-
- const dialog = await screen.findByRole('dialog');
- expect(await within(dialog).findByRole('tab', { name: 'Account' })).toHaveAttribute('aria-selected', 'true');
- expect(window.location.search).toBe('?tab=connections');
- expect(window.location.hash).toBe('#accounts');
- });
-
- it('clears the param through a history patch that a parent installs while mounting', async () => {
- serve();
- visit('?__clerk_mosaic_modal=user-profile%2Faccount');
- const onReplaceState = vi.fn();
- const clerk = new Clerk(publishableKey());
-
- const tree = () => (
-
-
-
- Page
-
-
-
- );
- const view = render(tree());
- await act(() => clerk.load());
- view.rerender(tree());
-
- await screen.findByRole('dialog');
- expect(window.location.search).toBe('');
- expect(onReplaceState).toHaveBeenCalledTimes(1);
- });
-
- describe("with the provider's profile", () => {
- const memberships = [fapiMembership(fapiOrganization({ id: 'org_1', name: 'Acme' }))];
-
- function serveInOrganization() {
- serveFapi({
- environment: fapiEnvironment(),
- client: fapiClient([
- fapiSession({
- id: 'sess_1',
- user: fapiUser({ id: 'user_1', organization_memberships: memberships }),
- last_active_organization_id: 'org_1',
- }),
- ]),
- memberships,
- });
- }
-
- async function tabsAfterReturning(profile: MosaicProfile, param = 'user-profile%2Faccount') {
- serveInOrganization();
- visit(`?__clerk_mosaic_modal=${param}`);
-
- await renderWithClerk(Page
, undefined, undefined, undefined, profile);
-
- const dialog = await screen.findByRole('dialog');
- await within(dialog).findByRole('tab', { name: 'Account' });
- return within(dialog)
- .getAllByRole('tab')
- .map(tab => tab.textContent);
- }
-
- it('keeps the custom pages', async () => {
- const tabs = await tabsAfterReturning({
- userProfileProps: { customPages: [{ label: 'Terms', path: 'terms', content: Terms body
}] },
- });
-
- expect(tabs).toContain('Terms');
- });
-
- it.each([
- { name: 'a user profile', param: 'user-profile%2Faccount', profile: {}, expected: ['Account', 'Security'] },
- {
- name: 'a combined profile',
- param: 'profile%2Faccount',
- profile: { combined: false },
- expected: ['Account', 'Security', 'General'],
- },
- ])('reopens $name whatever the provider says', async ({ param, profile, expected }) => {
- const tabs = await tabsAfterReturning(profile, param);
-
- expect(tabs).toEqual(expected);
- });
- });
-
- it('ignores an unknown value', async () => {
- serve();
- visit('?__clerk_mosaic_modal=organization-profile%2Fgeneral&tab=connections');
-
- await renderWithClerk(Page
);
-
- expect(await screen.findByText('Page')).toBeVisible();
- expect(screen.queryByRole('dialog')).toBeNull();
- expect(window.location.search).toBe('?__clerk_mosaic_modal=organization-profile%2Fgeneral&tab=connections');
- expect(window.location.hash).toBe('#accounts');
- });
-});
diff --git a/packages/mosaic/src/features/user-profile/__tests__/user-profile.return.feature.test.tsx b/packages/mosaic/src/features/user-profile/__tests__/user-profile.return.feature.test.tsx
new file mode 100644
index 00000000000..e9d50cf1c9b
--- /dev/null
+++ b/packages/mosaic/src/features/user-profile/__tests__/user-profile.return.feature.test.tsx
@@ -0,0 +1,146 @@
+import { configure, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { beforeAll, describe, expect, it, onTestFinished } from 'vitest';
+import { page } from 'vitest/browser';
+
+import { holdRequests, serveFapi } from '../../../__tests__/feature/fake-fapi';
+import {
+ fapiClient,
+ fapiEnvironment,
+ fapiMembership,
+ fapiOrganization,
+ fapiSession,
+ fapiUser,
+} from '../../../__tests__/feature/fapi';
+import { renderWithClerk } from '../../../__tests__/feature/render';
+import type { MosaicProfile } from '../../profile-pages/use-mosaic-profile';
+import { UserProfile } from '../user-profile';
+import { signedIn } from '../user-profile-connected-accounts-section/__tests__/user-profile-connected-accounts.fixtures';
+
+beforeAll(async () => {
+ await import('../user-profile.modal-content');
+ await import('../../profile/profile.modal-content');
+});
+
+beforeAll(() => page.viewport(1280, 800));
+
+function serve() {
+ serveFapi({
+ environment: fapiEnvironment(),
+ client: fapiClient([fapiSession({ id: 'sess_1', user: fapiUser({ id: 'user_1' }) })]),
+ });
+}
+
+function visit(search: string) {
+ const original = window.location.href;
+ window.history.replaceState(null, '', `${window.location.pathname}${search}#accounts`);
+ onTestFinished(() => window.history.replaceState(null, '', original));
+}
+
+function strictMode() {
+ configure({ reactStrictMode: true });
+ onTestFinished(() => configure({ reactStrictMode: false }));
+}
+
+describe('UserProfile return after a redirect', () => {
+ it.each([
+ { name: 'renders normally', strict: false },
+ { name: 'renders in StrictMode', strict: true },
+ ])('reopens the profile modal on the page it names and removes the param when it $name', async ({ strict }) => {
+ if (strict) {
+ strictMode();
+ }
+ serve();
+ visit('?.modal.user=security&tab=connections');
+
+ await renderWithClerk(Page
);
+
+ const dialog = await screen.findByRole('dialog');
+ expect(await within(dialog).findByRole('tab', { name: 'Security' })).toHaveAttribute('aria-selected', 'true');
+ expect(window.location.search).toBe('?tab=connections');
+ expect(window.location.hash).toBe('#accounts');
+ });
+
+ it('reopens the combined profile modal on the page it names', async () => {
+ serve();
+ visit('?.modal.profile=security');
+
+ await renderWithClerk(Page
);
+
+ const dialog = await screen.findByRole('dialog');
+ expect(await within(dialog).findByRole('tab', { name: 'Security' })).toHaveAttribute('aria-selected', 'true');
+ expect(window.location.search).toBe('');
+ });
+
+ it('shows an inline profile on the page it names', async () => {
+ serve();
+ visit('?.user=security');
+
+ await renderWithClerk();
+
+ const tab = await screen.findByRole('tab', { name: 'Security' });
+ await waitFor(() => expect(tab).toHaveAttribute('aria-selected', 'true'));
+ expect(window.location.search).toBe('');
+ });
+
+ it('sends a connection from an inline profile back to its account page', async () => {
+ serveFapi(signedIn([]));
+ visit('?tab=connections');
+ await renderWithClerk();
+ const request = holdRequests('post', '/v1/me/external_accounts');
+
+ await userEvent.setup().click(await screen.findByRole('button', { name: 'Connect GitHub' }));
+ await waitFor(() => expect(request.requests).toHaveLength(1));
+ const body = new URLSearchParams(await request.requests[0]?.text());
+ const returned = new URL(body.get('redirect_url') || '');
+ expect(returned.searchParams.get('.user')).toBe('account');
+ expect(returned.searchParams.get('tab')).toBe('connections');
+ expect(returned.hash).toBe('#accounts');
+ request.fail();
+ });
+
+ describe("with the provider's profile", () => {
+ const memberships = [fapiMembership(fapiOrganization({ id: 'org_1', name: 'Acme' }))];
+
+ function serveInOrganization() {
+ serveFapi({
+ environment: fapiEnvironment(),
+ client: fapiClient([
+ fapiSession({
+ id: 'sess_1',
+ user: fapiUser({ id: 'user_1', organization_memberships: memberships }),
+ last_active_organization_id: 'org_1',
+ }),
+ ]),
+ memberships,
+ });
+ }
+
+ async function tabsAfterReturning(profile: MosaicProfile) {
+ serveInOrganization();
+ visit('?.modal.user=account');
+
+ await renderWithClerk(Page
, undefined, undefined, undefined, profile);
+
+ const dialog = await screen.findByRole('dialog');
+ await within(dialog).findByRole('tab', { name: 'Account' });
+ return within(dialog)
+ .getAllByRole('tab')
+ .map(tab => tab.textContent);
+ }
+
+ it('keeps the custom pages', async () => {
+ const tabs = await tabsAfterReturning({
+ userProfileProps: { customPages: [{ label: 'Terms', path: 'terms', content: Terms body
}] },
+ });
+
+ expect(tabs).toContain('Terms');
+ });
+
+ it('stays account-only when the provider turns combined off', async () => {
+ const tabs = await tabsAfterReturning({ combined: false });
+
+ expect(tabs).not.toContain('General');
+ });
+ });
+});
diff --git a/packages/mosaic/src/features/user-profile/user-profile-connected-accounts-section/__tests__/user-profile-connected-accounts.connect.feature.test.tsx b/packages/mosaic/src/features/user-profile/user-profile-connected-accounts-section/__tests__/user-profile-connected-accounts.connect.feature.test.tsx
index 5a61178dc54..926da25f780 100644
--- a/packages/mosaic/src/features/user-profile/user-profile-connected-accounts-section/__tests__/user-profile-connected-accounts.connect.feature.test.tsx
+++ b/packages/mosaic/src/features/user-profile/user-profile-connected-accounts-section/__tests__/user-profile-connected-accounts.connect.feature.test.tsx
@@ -20,6 +20,7 @@ import {
fapiVerification,
} from '../../../../__tests__/feature/fapi';
import { renderWithClerk } from '../../../../__tests__/feature/render';
+import { InRoutingScope } from '../../../../__tests__/feature/routing';
import { MosaicProvider } from '../../../../mosaic-provider';
import { UserProfileProvider } from '../../user-profile.provider';
import { UserProfileConnectedAccountsSection } from '../user-profile-connected-accounts-section';
@@ -214,39 +215,21 @@ describe('connected accounts', () => {
expect(await screen.findByText('The connection could not start. Please try again.')).toBeInTheDocument();
});
- it('returns to the profile modal after connecting', async () => {
+ it('returns to the account page of the profile it is in', async () => {
serveFapi(signedIn([]));
await renderWithClerk(
-
+
- ,
- );
- const request = holdRequests('post', '/v1/me/external_accounts');
-
- await userEvent.setup().click(screen.getByRole('button', { name: 'Connect GitHub' }));
- await waitFor(() => expect(request.requests).toHaveLength(1));
- const body = new URLSearchParams(await request.requests[0]?.text());
- const params = new URL(body.get('redirect_url') || '').searchParams;
- expect(params.get('__clerk_mosaic_modal')).toBe('user-profile/account');
- expect(params.has('__clerk_modal_state')).toBe(false);
- request.fail();
- });
-
- it('returns to the page without modal state when connecting from a mounted profile', async () => {
- serveFapi(signedIn([]));
- await renderWithClerk(
-
-
- ,
+ ,
);
const request = holdRequests('post', '/v1/me/external_accounts');
await userEvent.setup().click(screen.getByRole('button', { name: 'Connect GitHub' }));
await waitFor(() => expect(request.requests).toHaveLength(1));
const body = new URLSearchParams(await request.requests[0]?.text());
- const params = new URL(body.get('redirect_url') || '').searchParams;
- expect(params.has('__clerk_mosaic_modal')).toBe(false);
- expect(params.has('__clerk_modal_state')).toBe(false);
+ const returned = new URL(body.get('redirect_url') || '');
+ expect(returned.searchParams.get('.modal.user')).toBe('account');
+ expect(returned.pathname).toBe(window.location.pathname);
request.fail();
});
diff --git a/packages/mosaic/src/features/user-profile/user-profile-connected-accounts-section/__tests__/user-profile-connected-accounts.reconnect.feature.test.tsx b/packages/mosaic/src/features/user-profile/user-profile-connected-accounts-section/__tests__/user-profile-connected-accounts.reconnect.feature.test.tsx
index be98c19e55a..3b821df47ef 100644
--- a/packages/mosaic/src/features/user-profile/user-profile-connected-accounts-section/__tests__/user-profile-connected-accounts.reconnect.feature.test.tsx
+++ b/packages/mosaic/src/features/user-profile/user-profile-connected-accounts-section/__tests__/user-profile-connected-accounts.reconnect.feature.test.tsx
@@ -12,6 +12,7 @@ import {
} from '../../../../__tests__/feature/fapi';
import { openMenu } from '../../../../__tests__/feature/menu';
import { renderWithClerk } from '../../../../__tests__/feature/render';
+import { InRoutingScope } from '../../../../__tests__/feature/routing';
import { UserProfileProvider } from '../../user-profile.provider';
import { UserProfileConnectedAccountsSection } from '../user-profile-connected-accounts-section';
import {
@@ -99,12 +100,12 @@ describe('connected accounts', () => {
expect(open).not.toHaveBeenCalled();
});
- it('returns to the profile modal after reconnecting', async () => {
+ it('returns to the account page of the profile it is in after reconnecting', async () => {
serveFapi(signedIn([disconnectedGoogle]));
await renderWithClerk(
-
+
- ,
+ ,
);
const request = holdRequests('post', '/v1/me/external_accounts');
const user = userEvent.setup();
@@ -113,8 +114,7 @@ describe('connected accounts', () => {
await waitFor(() => expect(request.requests).toHaveLength(1));
const body = new URLSearchParams(await request.requests[0]?.text());
const params = new URL(body.get('redirect_url') || '').searchParams;
- expect(params.get('__clerk_mosaic_modal')).toBe('user-profile/account');
- expect(params.has('__clerk_modal_state')).toBe(false);
+ expect(params.get('.modal.user')).toBe('account');
request.fail();
});
diff --git a/packages/mosaic/src/features/user-profile/user-profile-connected-accounts-section/user-profile-connected-accounts-section.model.ts b/packages/mosaic/src/features/user-profile/user-profile-connected-accounts-section/user-profile-connected-accounts-section.model.ts
index 3f20842acdb..8d254be5183 100644
--- a/packages/mosaic/src/features/user-profile/user-profile-connected-accounts-section/user-profile-connected-accounts-section.model.ts
+++ b/packages/mosaic/src/features/user-profile/user-profile-connected-accounts-section/user-profile-connected-accounts-section.model.ts
@@ -16,10 +16,11 @@ import type {
import { useMosaicEnvironment } from '../../../hooks/use-mosaic-environment';
import { useMosaicRouter } from '../../../hooks/use-mosaic-router';
+import { useReturnUrl } from '../../../routing/use-router';
import { allowsIdentificationCreation } from '../../../utils/allows-identification-creation';
import type { ReverificationController } from '../../reverification';
import { useReverificationFlow } from '../../reverification';
-import { withUserProfileModalReturn } from '../user-profile.modal-return';
+import { USER_PROFILE_ROUTES } from '../user-profile.layout';
import { useUserProfileOptions } from '../user-profile.provider';
import { isMonochromeProvider } from '../user-profile-provider.utils';
import type {
@@ -227,7 +228,8 @@ function unavailable() {
}
export function useUserProfileConnectedAccountsModel(): UserProfileConnectedAccountsModel {
- const { additionalOAuthScopes, mode, combined } = useUserProfileOptions();
+ const { additionalOAuthScopes } = useUserProfileOptions();
+ const returnUrl = useReturnUrl(USER_PROFILE_ROUTES);
const clerk = useClerk();
const { isLoaded, user } = useUser();
const environment = useMosaicEnvironment();
@@ -282,8 +284,7 @@ export function useUserProfileConnectedAccountsModel(): UserProfileConnectedAcco
return current;
};
- const getRedirectUrl = async () => (transport ? String(await transport.getRedirectUrl()) : window.location.href);
- const withModalState = (url: string) => withUserProfileModalReturn(url, { mode, combined });
+ const getRedirectUrl = async () => (transport ? String(await transport.getRedirectUrl()) : returnUrl('account'));
const completeVerification = async (response: ExternalAccountResource): Promise => {
const url = response.verification?.externalVerificationRedirectURL;
@@ -318,7 +319,7 @@ export function useUserProfileConnectedAccountsModel(): UserProfileConnectedAcco
const current = requireCurrentUser();
const response = await createAccount(current, {
strategy: provider.strategy,
- redirectUrl: withModalState(redirectUrl),
+ redirectUrl,
additionalScopes: additionalOAuthScopes ? additionalOAuthScopes[provider.provider] : [],
});
return completeVerification(response);
@@ -339,11 +340,11 @@ export function useUserProfileConnectedAccountsModel(): UserProfileConnectedAcco
recovery.kind === 'reauthorize'
? await account.reauthorize({
additionalScopes: recovery.additionalScopes,
- redirectUrl: withModalState(redirectUrl),
+ redirectUrl,
})
: await recreateAccount(current, {
strategy: recovery.strategy,
- redirectUrl: withModalState(redirectUrl),
+ redirectUrl,
additionalScopes: recovery.additionalScopes,
});
return completeVerification(response);
diff --git a/packages/mosaic/src/features/user-profile/user-profile-email-section/__tests__/user-profile-email-section.feature.test.tsx b/packages/mosaic/src/features/user-profile/user-profile-email-section/__tests__/user-profile-email-section.feature.test.tsx
index f9789877eae..6af834bff86 100644
--- a/packages/mosaic/src/features/user-profile/user-profile-email-section/__tests__/user-profile-email-section.feature.test.tsx
+++ b/packages/mosaic/src/features/user-profile/user-profile-email-section/__tests__/user-profile-email-section.feature.test.tsx
@@ -25,7 +25,7 @@ import {
} from '../../../../__tests__/feature/fapi';
import { openMenu } from '../../../../__tests__/feature/menu';
import { renderWithClerk } from '../../../../__tests__/feature/render';
-import { UserProfileProvider } from '../../user-profile.provider';
+import { InRoutingScope } from '../../../../__tests__/feature/routing';
import { UserProfileEmailSection } from '../user-profile-email-section';
const VERIFIED = fapiVerification('email_code', { status: 'verified' });
@@ -270,7 +270,7 @@ describe('the user profile email section', () => {
await waitFor(() => expect(windowNavigate).toHaveBeenCalledWith(new URL('https://idp.acme.co/sso')));
});
- it('returns to the profile modal after verifying through the identity provider', async () => {
+ it('returns to the account page of the profile it is in after verifying through the identity provider', async () => {
const sso = fapiEmailAddress({
id: 'idn_sso',
email_address: 'alice@acme.co',
@@ -278,9 +278,9 @@ describe('the user profile email section', () => {
});
serveFapi(signedInWithEmails([PRIMARY, sso]));
await renderWithClerk(
-
+
- ,
+ ,
);
const actor = userEvent.setup();
const prepare = holdRequests('post', '/v1/me/email_addresses/:id/prepare_verification');
@@ -292,8 +292,7 @@ describe('the user profile email section', () => {
await waitFor(() => expect(prepare.requests).toHaveLength(1));
const body = new URLSearchParams(await prepare.requests[0]?.text());
const params = new URL(body.get('redirect_url') || '').searchParams;
- expect(params.get('__clerk_mosaic_modal')).toBe('user-profile/account');
- expect(params.has('__clerk_modal_state')).toBe(false);
+ expect(params.get('.modal.user')).toBe('account');
prepare.fail();
});
diff --git a/packages/mosaic/src/features/user-profile/user-profile-email-section/user-profile-email-section.model.ts b/packages/mosaic/src/features/user-profile/user-profile-email-section/user-profile-email-section.model.ts
index e66eceb1f85..9b977369f0b 100644
--- a/packages/mosaic/src/features/user-profile/user-profile-email-section/user-profile-email-section.model.ts
+++ b/packages/mosaic/src/features/user-profile/user-profile-email-section/user-profile-email-section.model.ts
@@ -3,12 +3,11 @@ import type { EmailAddressResource, UserResource } from '@clerk/shared/types';
import type { MosaicRouter } from '../../../hooks/use-mosaic-router';
import { useMosaicRouter } from '../../../hooks/use-mosaic-router';
+import { useReturnUrl } from '../../../routing/use-router';
import { allowsIdentificationCreation } from '../../../utils/allows-identification-creation';
import { save } from '../../../utils/errors';
import { useReverificationFlow } from '../../reverification';
-import { withUserProfileModalReturn } from '../user-profile.modal-return';
-import type { UserProfileOptions } from '../user-profile.provider';
-import { useUserProfileOptions } from '../user-profile.provider';
+import { USER_PROFILE_ROUTES } from '../user-profile.layout';
import type { UserProfileEmailVerification, UserProfileEmailVerifier } from '../user-profile-contact.types';
import { byId, toContactAccess, toContacts } from '../user-profile-contact.utils';
import { useUserProfileUserModel } from '../user-profile-user.model';
@@ -36,7 +35,7 @@ function startEmailVerification(
email: EmailAddressResource,
linkRedirectUrl: string | undefined,
router: MosaicRouter,
- profile: Pick,
+ returnUrl: () => string,
): UserProfileEmailVerification {
if (email.matchesSsoConnection) {
return {
@@ -50,7 +49,7 @@ function startEmailVerification(
save(async () => {
const prepared = await email.prepareVerification({
strategy: 'enterprise_sso',
- redirectUrl: withUserProfileModalReturn(window.location.href, profile),
+ redirectUrl: returnUrl(),
});
const url = prepared.verification.externalVerificationRedirectURL;
if (!url) {
@@ -75,10 +74,10 @@ function toEmailVerifier(
email: EmailAddressResource,
linkRedirectUrl: string | undefined,
router: MosaicRouter,
- profile: Pick,
+ returnUrl: () => string,
): UserProfileEmailVerifier {
return {
- start: () => startEmailVerification(email, linkRedirectUrl, router, profile),
+ start: () => startEmailVerification(email, linkRedirectUrl, router, returnUrl),
verifyCode: code => save(() => email.attemptVerification({ code }), ADD_EMAIL_FIELDS),
};
}
@@ -86,7 +85,7 @@ function toEmailVerifier(
export function useUserProfileEmailSectionModel(): UserProfileEmailSectionModel {
const model = useUserProfileUserModel();
const router = useMosaicRouter();
- const { mode, combined } = useUserProfileOptions();
+ const returnUrl = useReturnUrl(USER_PROFILE_ROUTES);
const [removeEmail, removeReverification] = useReverificationFlow((user: UserResource, id: string) =>
byId(user.emailAddresses, id, 'email address').destroy(),
);
@@ -116,7 +115,7 @@ export function useUserProfileEmailSectionModel(): UserProfileEmailSectionModel
const verifiesByLink = Boolean(attributes.email_address?.verifications.includes('email_link'));
const linkRedirectUrl = verifiesByLink ? verifyRedirectUrl(environment.displayConfig.userProfileUrl) : undefined;
const verifierFor = (email: EmailAddressResource) =>
- toEmailVerifier(email, linkRedirectUrl, router, { mode, combined });
+ toEmailVerifier(email, linkRedirectUrl, router, () => returnUrl('account'));
return {
status: 'ready',
diff --git a/packages/mosaic/src/features/user-profile/user-profile-enterprise-accounts-section/__tests__/user-profile-enterprise-accounts.feature.test.tsx b/packages/mosaic/src/features/user-profile/user-profile-enterprise-accounts-section/__tests__/user-profile-enterprise-accounts.feature.test.tsx
index d436e0b7bd6..7dda9eb300d 100644
--- a/packages/mosaic/src/features/user-profile/user-profile-enterprise-accounts-section/__tests__/user-profile-enterprise-accounts.feature.test.tsx
+++ b/packages/mosaic/src/features/user-profile/user-profile-enterprise-accounts-section/__tests__/user-profile-enterprise-accounts.feature.test.tsx
@@ -21,8 +21,8 @@ import {
fapiVerification,
} from '../../../../__tests__/feature/fapi';
import { renderWithClerk } from '../../../../__tests__/feature/render';
+import { InRoutingScope } from '../../../../__tests__/feature/routing';
import { MosaicProvider } from '../../../../mosaic-provider';
-import { UserProfileProvider } from '../../user-profile.provider';
import { UserProfileEnterpriseAccountsSection } from '../user-profile-enterprise-accounts-section';
import { useUserProfileEnterpriseAccountsModel } from '../user-profile-enterprise-accounts-section.model';
import { custom, enterpriseAccountSeed as signedIn, enterpriseMember, okta } from './enterprise-accounts.fixtures';
@@ -185,12 +185,12 @@ describe('enterprise accounts', () => {
);
});
- it('returns to the profile modal after connecting', async () => {
+ it('returns to the account page of the profile it is in', async () => {
serveFapi(signedIn());
await renderWithClerk(
-
+
- ,
+ ,
);
const request = holdRequests('post', '/v1/me/external_accounts');
@@ -198,26 +198,7 @@ describe('enterprise accounts', () => {
await waitFor(() => expect(request.requests).toHaveLength(1));
const body = new URLSearchParams(await request.requests[0]?.text());
const params = new URL(body.get('redirect_url') || '').searchParams;
- expect(params.get('__clerk_mosaic_modal')).toBe('user-profile/account');
- expect(params.has('__clerk_modal_state')).toBe(false);
- request.fail();
- });
-
- it('returns to the page without modal state when connecting from a mounted profile', async () => {
- serveFapi(signedIn());
- await renderWithClerk(
-
-
- ,
- );
- const request = holdRequests('post', '/v1/me/external_accounts');
-
- await userEvent.setup().click(await screen.findByRole('button', { name: 'Connect Acme Okta' }));
- await waitFor(() => expect(request.requests).toHaveLength(1));
- const body = new URLSearchParams(await request.requests[0]?.text());
- const params = new URL(body.get('redirect_url') || '').searchParams;
- expect(params.has('__clerk_mosaic_modal')).toBe(false);
- expect(params.has('__clerk_modal_state')).toBe(false);
+ expect(params.get('.modal.user')).toBe('account');
request.fail();
});
diff --git a/packages/mosaic/src/features/user-profile/user-profile-enterprise-accounts-section/user-profile-enterprise-accounts-section.model.ts b/packages/mosaic/src/features/user-profile/user-profile-enterprise-accounts-section/user-profile-enterprise-accounts-section.model.ts
index b2c45aff52c..7b03689f5e9 100644
--- a/packages/mosaic/src/features/user-profile/user-profile-enterprise-accounts-section/user-profile-enterprise-accounts-section.model.ts
+++ b/packages/mosaic/src/features/user-profile/user-profile-enterprise-accounts-section/user-profile-enterprise-accounts-section.model.ts
@@ -4,10 +4,10 @@ import type { EnterpriseAccountResource, EnterpriseConnectionResource, UserResou
import { useMosaicEnvironment } from '../../../hooks/use-mosaic-environment';
import { useMosaicRouter } from '../../../hooks/use-mosaic-router';
+import { useReturnUrl } from '../../../routing/use-router';
import type { ReverificationController } from '../../reverification';
import { useReverificationFlow } from '../../reverification';
-import { withUserProfileModalReturn } from '../user-profile.modal-return';
-import { useUserProfileOptions } from '../user-profile.provider';
+import { USER_PROFILE_ROUTES } from '../user-profile.layout';
import { isMonochromeProvider, providerId } from '../user-profile-provider.utils';
import type {
EnterpriseAccountActionResult,
@@ -83,7 +83,7 @@ export type UserProfileEnterpriseAccountsModel =
};
export function useUserProfileEnterpriseAccountsModel(): UserProfileEnterpriseAccountsModel {
- const { mode, combined } = useUserProfileOptions();
+ const returnUrl = useReturnUrl(USER_PROFILE_ROUTES);
const clerk = useClerk();
const router = useMosaicRouter();
const [createAccount, connectReverification] = useReverificationFlow(
@@ -137,7 +137,7 @@ export function useUserProfileEnterpriseAccountsModel(): UserProfileEnterpriseAc
if (!projection.connections.some(connection => connection.id === connectionId)) {
throw unavailable();
}
- const redirectUrl = withUserProfileModalReturn(window.location.href, { mode, combined });
+ const redirectUrl = returnUrl('account');
const account = await createAccount(current, { enterpriseConnectionId: connectionId, redirectUrl });
currentUser();
const redirect = account.verification?.externalVerificationRedirectURL;
diff --git a/packages/mosaic/src/features/user-profile/user-profile.layout.ts b/packages/mosaic/src/features/user-profile/user-profile.layout.ts
index d8b4b976a26..e61173763ea 100644
--- a/packages/mosaic/src/features/user-profile/user-profile.layout.ts
+++ b/packages/mosaic/src/features/user-profile/user-profile.layout.ts
@@ -8,12 +8,19 @@ import { UserCircle } from '../../icons/glyphs/user-circle';
import { applyOrder } from '../../utils/apply-order';
import { organizationProfilePageIds } from '../organization-profile/organization-profile.layout';
import type { OrganizationProfilePageListOptions } from '../organization-profile/organization-profile.types';
-import { withRoutablePaths, withUniquePaths } from '../profile-pages/profile-pages.layout';
+import { pageSegment, withRoutablePaths, withUniquePaths } from '../profile-pages/profile-pages.layout';
import type { CustomProfilePage, UserProfilePageId, UserProfilePages } from './user-profile.types';
/** The built-in pages in the order the profile lists them before a consumer reorders anything. */
export const USER_PROFILE_PAGE_IDS: readonly UserProfilePageId[] = ['account', 'security', 'billing', 'apiKeys'];
+export const USER_PROFILE_ROUTES: Readonly> = {
+ account: pageSegment('account'),
+ security: pageSegment('security'),
+ billing: pageSegment('billing'),
+ apiKeys: pageSegment('apiKeys'),
+};
+
/** Sets an organization page's id apart from an account page's when the profile shows both. */
export const ORGANIZATION_PAGE_PREFIX = 'organization/';
diff --git a/packages/mosaic/src/features/user-profile/user-profile.modal-return.ts b/packages/mosaic/src/features/user-profile/user-profile.modal-return.ts
deleted file mode 100644
index 5ca086da78c..00000000000
--- a/packages/mosaic/src/features/user-profile/user-profile.modal-return.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import React from 'react';
-
-import { useModal } from '../../modals/use-modal';
-import { profileModal } from '../profile/profile.modal';
-import { profileModalOptions, useMosaicProfile, userProfileModalOptions } from '../profile-pages/use-mosaic-profile';
-import { userProfileModal } from './user-profile.modal';
-import type { UserProfileOptions } from './user-profile.provider';
-
-const MODAL_PARAM = '__clerk_mosaic_modal';
-const USER_ACCOUNT_PAGE = 'user-profile/account';
-const COMBINED_ACCOUNT_PAGE = 'profile/account';
-
-export function withUserProfileModalReturn(
- url: string,
- { mode, combined = false }: Pick,
-): string {
- if (mode !== 'modal') {
- return url;
- }
- const next = new URL(url);
- next.searchParams.set(MODAL_PARAM, combined ? COMBINED_ACCOUNT_PAGE : USER_ACCOUNT_PAGE);
- return next.toString();
-}
-
-export function UserProfileModalReturn(): null {
- const { open: openUserProfile } = useModal(userProfileModal);
- const { open: openProfile } = useModal(profileModal);
- const profile = useMosaicProfile();
-
- React.useEffect(() => {
- queueMicrotask(() => {
- const url = new URL(window.location.href);
- const page = url.searchParams.get(MODAL_PARAM);
- if (page !== USER_ACCOUNT_PAGE && page !== COMBINED_ACCOUNT_PAGE) {
- return;
- }
- url.searchParams.delete(MODAL_PARAM);
- window.history.replaceState(null, '', url);
- if (page === COMBINED_ACCOUNT_PAGE) {
- openProfile({ ...profileModalOptions(profile), page: 'account' });
- } else {
- openUserProfile({ ...userProfileModalOptions(profile), page: 'account' });
- }
- });
- }, [openProfile, openUserProfile, profile]);
-
- return null;
-}
diff --git a/packages/mosaic/src/features/user-profile/user-profile.provider.tsx b/packages/mosaic/src/features/user-profile/user-profile.provider.tsx
index add24253b09..b56d0919643 100644
--- a/packages/mosaic/src/features/user-profile/user-profile.provider.tsx
+++ b/packages/mosaic/src/features/user-profile/user-profile.provider.tsx
@@ -10,8 +10,6 @@ export interface UserProfileOptions {
* @example { google: ['https://www.googleapis.com/auth/calendar.readonly'] }
*/
additionalOAuthScopes?: AdditionalOAuthScopes;
- mode?: 'modal' | 'mounted';
- combined?: boolean;
}
export interface UserProfileProviderProps extends UserProfileOptions {
@@ -20,12 +18,8 @@ export interface UserProfileProviderProps extends UserProfileOptions {
const UserProfileContext = createContext({});
-export function UserProfileProvider({ additionalOAuthScopes, mode, combined, children }: UserProfileProviderProps) {
- return (
-
- {children}
-
- );
+export function UserProfileProvider({ additionalOAuthScopes, children }: UserProfileProviderProps) {
+ return {children};
}
export function useUserProfileOptions(): UserProfileOptions {
diff --git a/packages/mosaic/src/modals/modal-host.tsx b/packages/mosaic/src/modals/modal-host.tsx
index 3164c038383..fd2bddfc5e5 100644
--- a/packages/mosaic/src/modals/modal-host.tsx
+++ b/packages/mosaic/src/modals/modal-host.tsx
@@ -8,6 +8,7 @@ import { useMessages } from '../localization';
import { useActor } from '../machine/use-machine';
import type { PortalContainer } from '../primitives/portal';
import { PortalProvider } from '../primitives/portal';
+import { useConsumeLink } from '../routing/consume-link';
import { useRoutingConfig } from '../routing/router-adapter';
import { useFixedRoutingMode, useHostPathname, useMosaicLocation } from '../routing/use-mosaic-location';
import type { ModalHandle, ModalRoutingMode, ModalSurface, ModalSurfaces } from './modal.types';
@@ -76,7 +77,8 @@ export function ModalSurfaceHost({
});
const base = surface.path ?? `/modal/${surface.id}`;
const location = useMosaicLocation({ routing, path: base });
- const isOpen = location.useSegmentParts() !== undefined;
+ const segment = useConsumeLink(location, location.useSegmentParts(), { routing, path: base });
+ const isOpen = segment !== undefined;
const page = useHostPathname(routing);
// Close the modal when the host moves to another pathname, in every mode
diff --git a/packages/mosaic/src/mosaic-provider.tsx b/packages/mosaic/src/mosaic-provider.tsx
index 0afe8f71a33..04bcba5b791 100644
--- a/packages/mosaic/src/mosaic-provider.tsx
+++ b/packages/mosaic/src/mosaic-provider.tsx
@@ -6,7 +6,6 @@ import { profileModal } from './features/profile/profile.modal';
import type { MosaicProfile } from './features/profile-pages/use-mosaic-profile';
import { MosaicProfileProvider } from './features/profile-pages/use-mosaic-profile';
import { userProfileModal } from './features/user-profile/user-profile.modal';
-import { UserProfileModalReturn } from './features/user-profile/user-profile.modal-return';
import type { MosaicExperimental } from './hooks/use-mosaic-experimental';
import { MosaicExperimentalProvider } from './hooks/use-mosaic-experimental';
import { MosaicNowProvider } from './hooks/use-now';
@@ -75,10 +74,7 @@ export function MosaicProvider({
modals={routing?.modals}
>
-
-
- {children}
-
+ {children}
diff --git a/packages/mosaic/src/routing/__tests__/consume-link.test.tsx b/packages/mosaic/src/routing/__tests__/consume-link.test.tsx
new file mode 100644
index 00000000000..4cd4c2e13fd
--- /dev/null
+++ b/packages/mosaic/src/routing/__tests__/consume-link.test.tsx
@@ -0,0 +1,156 @@
+import { act, cleanup, configure, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { useEffect } from 'react';
+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';
+
+import { defineModalSurface } from '../../modals/define-modal-surface';
+import { ModalHost } from '../../modals/modal-host';
+import type { RoutingOptions } from '../router-adapter';
+import { RoutingConfigProvider } from '../router-adapter';
+import type { RoutingMode } from '../use-mosaic-location';
+import { useRouterScope } from '../use-router';
+import { VirtualStoreProvider } from '../virtual-store';
+
+beforeEach(() => window.history.replaceState(null, '', '/'));
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+const url = () => `${window.location.pathname}${window.location.search}${window.location.hash}`;
+
+const flush = () =>
+ act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 0));
+ });
+
+const routes = { index: '', security: 'security' } as const;
+
+function Owner({ routing }: { routing: RoutingMode }) {
+ const { route } = useRouterScope(routes, { routing, path: '/user', root: 'index' });
+ return ;
+}
+
+function Page({ routing = {}, children }: { routing?: RoutingOptions; children: ReactNode }) {
+ return (
+
+ {children}
+
+ );
+}
+
+const linkedModal = defineModalSurface({
+ id: 'linked',
+ variant: 'card',
+ load: () => Promise.resolve({ default: () => Linked modal
}),
+});
+
+describe('a link in the query string', () => {
+ it('is left alone in query mode, where it is the segment', async () => {
+ window.history.replaceState(null, '', '/page?.user=security&a=1');
+ const replaceState = vi.spyOn(window.history, 'replaceState');
+ render(
+
+
+ ,
+ );
+ await flush();
+
+ expect(screen.getByTestId('route').textContent).toBe('security');
+ expect(url()).toBe('/page?.user=security&a=1');
+ expect(replaceState).not.toHaveBeenCalled();
+ });
+
+ it('is left in the URL while nothing owns its base', async () => {
+ window.history.replaceState(null, '', '/page?.user=security');
+ render(
+
+ Page
+ ,
+ );
+ await flush();
+
+ expect(url()).toBe('/page?.user=security');
+ });
+
+ it('is removed once in StrictMode', async () => {
+ configure({ reactStrictMode: true });
+ onTestFinished(() => configure({ reactStrictMode: false }));
+ window.history.replaceState(null, '', '/page?.user=security&a=1');
+ const replaceState = vi.spyOn(window.history, 'replaceState');
+ render(
+
+
+ ,
+ );
+ await flush();
+
+ expect(screen.getByTestId('route').textContent).toBe('security');
+ expect(url()).toBe('/page?a=1');
+ expect(replaceState).toHaveBeenCalledTimes(1);
+ });
+
+ it('writes no history state when it is removed', async () => {
+ window.history.replaceState({ __NA: true, router: 'state' }, '', '/page?.user=security');
+ render(
+
+
+ ,
+ );
+ await flush();
+
+ expect(url()).toBe('/page');
+ expect(window.history.state).toBeNull();
+ });
+
+ it('is removed through a history patch that a parent installs while mounting', async () => {
+ window.history.replaceState(null, '', '/page?.user=security');
+ const patched = vi.fn();
+ function PatchesHistoryOnMount({ children }: { children: ReactNode }) {
+ useEffect(() => {
+ const original = window.history.replaceState.bind(window.history);
+ window.history.replaceState = (state, unused, next) => {
+ patched(String(next));
+ original(state, unused, next);
+ };
+ return () => {
+ window.history.replaceState = original;
+ };
+ }, []);
+ return children;
+ }
+
+ render(
+
+
+
+
+ ,
+ );
+ await flush();
+
+ expect(patched).toHaveBeenCalledTimes(1);
+ expect(url()).toBe('/page');
+ });
+
+ it.each([
+ { name: 'virtual', routing: {}, after: '/page?a=1' },
+ { name: 'hash', routing: { modals: 'hash' }, after: '/page?a=1#.modal.linked=' },
+ ] satisfies { name: string; routing: RoutingOptions; after: string }[])(
+ 'opens a modal through the modal host in $name mode',
+ async ({ routing, after }) => {
+ window.history.replaceState(null, '', '/page?.modal.linked=&a=1');
+ render(
+
+
+ Page
+
+ ,
+ );
+ await flush();
+
+ expect(await screen.findByRole('heading', { name: 'Linked modal' })).toBeInTheDocument();
+ expect(url()).toBe(after);
+ },
+ );
+});
diff --git a/packages/mosaic/src/routing/__tests__/location-contract.test.tsx b/packages/mosaic/src/routing/__tests__/location-contract.test.tsx
index 83bfc6b5467..90f0a57c47b 100644
--- a/packages/mosaic/src/routing/__tests__/location-contract.test.tsx
+++ b/packages/mosaic/src/routing/__tests__/location-contract.test.tsx
@@ -37,13 +37,23 @@ interface LocationMode {
dropsOnMove?: boolean;
// Parking keeps a hidden owner's segment in the owner. A URL mode keeps it in the URL instead.
parks?: boolean;
+ // A link in the query string is the query mode's own entry, so it stays in the URL.
+ linkIsEntry?: boolean;
};
}
+function VirtualProvider({ initial, children }: { initial?: Record; children: ReactNode }) {
+ return (
+
+ {children}
+
+ );
+}
+
const virtual: LocationMode = {
name: 'virtual',
routing: 'virtual',
- Provider: VirtualStoreProvider,
+ Provider: VirtualProvider,
useEntry: base => useVirtualEntries().get(normalizeBase(base)) ?? null,
useOutsideWrite: useVirtualWrite,
leave: { away: unmount => unmount(), back: remount => remount() },
@@ -148,7 +158,12 @@ const path = urlMode(
{ severalBases: true },
);
-function paramMode(routing: 'hash' | 'query', field: 'hash' | 'search', prefix: string) {
+function paramMode(
+ routing: 'hash' | 'query',
+ field: 'hash' | 'search',
+ prefix: string,
+ excludes: LocationMode['excludes'] = {},
+) {
return urlMode(
routing,
{
@@ -162,11 +177,24 @@ function paramMode(routing: 'hash' | 'query', field: 'hash' | 'search', prefix:
[field]: withPair(url[field], paramName(prefix, base), parts === undefined ? undefined : encode(parts)),
}),
},
- {},
+ excludes,
);
}
-const modes: LocationMode[] = [virtual, path, paramMode('hash', 'hash', ''), paramMode('query', 'search', '')];
+const modes: LocationMode[] = [
+ virtual,
+ path,
+ paramMode('hash', 'hash', ''),
+ paramMode('query', 'search', '', { linkIsEntry: true }),
+];
+
+const flush = () =>
+ act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 0));
+ });
+
+const withLink = (url: HostUrl, base: string, value: string) =>
+ urlOf({ ...url, search: withPair(url.search, paramName('', base), value) });
beforeEach(() => {
markSettled();
@@ -519,6 +547,89 @@ describe.each(modes)('$name location', mode => {
warn.mockRestore();
});
+ it('opens on the page a link in the query string names, at the base in path mode too', async () => {
+ window.history.replaceState(null, '', '/user?a=1&.user=security#h');
+ render(
+
+
+
+ ,
+ );
+ await flush();
+ expect(route()).toBe('security');
+ expect(entry()).toEqual(['security']);
+ });
+
+ it('shows the page a link names in its first render', async () => {
+ window.history.replaceState(null, '', '/user?.user=billing/statement/s1');
+ const seen: string[] = [];
+ render(
+
+
+ ,
+ );
+ expect(seen[0]).toBe('statement');
+ await flush();
+ expect(seen).not.toContain('index');
+ });
+
+ it.skipIf(mode.excludes.linkIsEntry)('removes the link and keeps every other param and the hash', async () => {
+ window.history.replaceState(null, '', '/user?a=1&.user=security&b=2#h');
+ render(
+
+
+ ,
+ );
+ await flush();
+ expect(window.location.search).toBe('?a=1&b=2');
+ expect(new URLSearchParams(window.location.hash.slice(1)).has('h')).toBe(true);
+ });
+
+ it.skipIf(mode.excludes.linkIsEntry)('keeps the entry it has over a link it mounts with', async () => {
+ window.history.replaceState(null, '', '/user?.user=billing/statement/s1');
+ render(
+
+
+
+ ,
+ );
+ await flush();
+ expect(route()).toBe('security');
+ expect(entry()).toEqual(['security']);
+ expect(window.location.search).toBe('');
+ });
+
+ it('follows a link that arrives after mount, over the entry it has', async () => {
+ render(
+
+
+
+ ,
+ );
+ await flush();
+ click('Go to security /user');
+ act(() => navigate(withLink(currentUrl(), '/user', 'billing/statement/s1')));
+ await flush();
+ expect(entry()).toEqual(['billing', 'statement', 's1']);
+ expect(new URLSearchParams(window.location.search).has('.user')).toBe(Boolean(mode.excludes.linkIsEntry));
+ });
+
+ it.skipIf(mode.excludes.severalBases)('lets each owner take its own link and leaves the rest', async () => {
+ window.history.replaceState(null, '', '/user?.user=security&a=1&.organization=members&b=2');
+ render(
+
+
+
+ ,
+ );
+ await flush();
+ expect(route()).toBe('security');
+ expect(other('/organization')).toBe('members');
+ expect(window.location.search).toBe(
+ mode.excludes.linkIsEntry ? '?.user=security&a=1&.organization=members&b=2' : '?a=1&b=2',
+ );
+ });
+
it.skipIf(mode.excludes.severalBases)('keeps owners of different bases independent', () => {
render(
diff --git a/packages/mosaic/src/routing/__tests__/use-return-url.test.tsx b/packages/mosaic/src/routing/__tests__/use-return-url.test.tsx
new file mode 100644
index 00000000000..70c22afb6a7
--- /dev/null
+++ b/packages/mosaic/src/routing/__tests__/use-return-url.test.tsx
@@ -0,0 +1,116 @@
+import { act, renderHook } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { RoutingOptions } from '../router-adapter';
+import { RoutingConfigProvider } from '../router-adapter';
+import { MosaicRoutingScope } from '../routing-scope';
+import type { MosaicLocationOptions } from '../use-mosaic-location';
+import { useReturnUrl, useRouterScope } from '../use-router';
+import { useVirtualEntries, VirtualStoreProvider } from '../virtual-store';
+
+beforeEach(() => window.history.replaceState(null, '', '/page?q=a+b#top'));
+afterEach(() => vi.restoreAllMocks());
+
+const routes = {
+ account: 'account',
+ security: 'security',
+ statement: 'billing/statement/:statementId',
+} as const;
+
+const url = () => `${window.location.pathname}${window.location.search}${window.location.hash}`;
+const relative = (href: string) => href.slice(window.location.origin.length);
+
+function Scope({ options, children }: { options: MosaicLocationOptions; children: ReactNode }) {
+ const { scope } = useRouterScope(routes, { ...options, root: 'account' });
+ return {children};
+}
+
+function renderReturnUrl(options: MosaicLocationOptions | undefined, routing: RoutingOptions = {}) {
+ return renderHook(() => ({ returnUrl: useReturnUrl(routes), entries: useVirtualEntries() }), {
+ wrapper: ({ children }: { children: ReactNode }) => (
+
+ {options ? {children} : children}
+
+ ),
+ });
+}
+
+describe('useReturnUrl', () => {
+ it('adds the query link for the scope in virtual mode, and changes nothing else', () => {
+ const { result } = renderReturnUrl({ routing: 'virtual', path: '/user' });
+
+ expect(result.current.returnUrl('security')).toBe(`${window.location.origin}/page?q=a+b&.user=security#top`);
+ expect(url()).toBe('/page?q=a+b#top');
+ expect(result.current.entries.size).toBe(0);
+ });
+
+ it.each([
+ { routing: 'query', at: '/page?q=a+b#top', returned: '/page?q=a+b&.user=security#top' },
+ { routing: 'hash', at: '/page?q=a+b#top', returned: '/page?q=a+b#top=&.user=security' },
+ { routing: 'path', at: '/user?q=a+b#top', returned: '/user/security?q=a+b#top' },
+ ] as const)('writes the segment into the URL in $routing mode without navigating', ({ routing, at, returned }) => {
+ window.history.replaceState(null, '', at);
+ const { result } = renderReturnUrl({ routing, path: '/user' });
+
+ expect(relative(result.current.returnUrl('security'))).toBe(returned);
+ expect(url()).toBe(at);
+ });
+
+ it('replaces a segment the URL already has', () => {
+ window.history.replaceState(null, '', '/page?.user=account&q=1');
+ const { result } = renderReturnUrl({ routing: 'query', path: '/user' });
+
+ expect(relative(result.current.returnUrl('security'))).toBe('/page?.user=security&q=1');
+ });
+
+ it('uses the base of the scope it is under', () => {
+ const { result } = renderReturnUrl({ routing: 'virtual', path: '/modal/user' });
+
+ expect(relative(result.current.returnUrl('account'))).toBe('/page?q=a+b&.modal.user=account#top');
+ });
+
+ it('names the link in virtual mode with the provider’s query prefix', () => {
+ const { result } = renderReturnUrl({ routing: 'virtual', path: '/user' }, { keyPrefix: { query: 'app' } });
+
+ expect(relative(result.current.returnUrl('security'))).toBe('/page?q=a+b&app.user=security#top');
+ });
+
+ it('builds the parts of a route with params', () => {
+ const { result } = renderReturnUrl({ routing: 'virtual', path: '/user' });
+
+ expect(relative(result.current.returnUrl('statement', { statementId: 'st 1' }))).toBe(
+ '/page?q=a+b&.user=billing%2Fstatement%2Fst%25201#top',
+ );
+ });
+
+ it('starts from the page as it is when it is called', () => {
+ const { result } = renderReturnUrl({ routing: 'virtual', path: '/user' });
+ window.history.replaceState(null, '', '/elsewhere');
+
+ expect(relative(result.current.returnUrl('security'))).toBe('/elsewhere?.user=security');
+ });
+
+ it('returns the page as it is outside a scope', () => {
+ const { result } = renderReturnUrl(undefined);
+
+ expect(result.current.returnUrl('security')).toBe(`${window.location.origin}/page?q=a+b#top`);
+ });
+
+ it.each(['100%', 'two words', 'a+b', 'a&b', 'a=b', 'a#b', 'a?b', 'åäö', '%2F'])(
+ 'comes back as the same parts through a virtual owner for %s',
+ async statementId => {
+ const { result, unmount } = renderReturnUrl({ routing: 'virtual', path: '/user' });
+ window.history.replaceState(null, '', relative(result.current.returnUrl('statement', { statementId })));
+ unmount();
+
+ const returned = renderReturnUrl({ routing: 'virtual', path: '/user' });
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ expect(returned.result.current.entries.get('/user')).toEqual(['billing', 'statement', statementId]);
+ expect(url()).toBe('/page?q=a+b#top');
+ },
+ );
+});
diff --git a/packages/mosaic/src/routing/consume-link.ts b/packages/mosaic/src/routing/consume-link.ts
new file mode 100644
index 00000000000..8f7735c4f5d
--- /dev/null
+++ b/packages/mosaic/src/routing/consume-link.ts
@@ -0,0 +1,62 @@
+import { useEffect, useMemo, useRef } from 'react';
+
+import type { MosaicLocation, SegmentParts } from './location';
+import { useRoutingConfig } from './router-adapter';
+import { urlOf } from './url-location';
+import { decodeParts, paramKey, readParam, writeParam } from './url-params';
+import type { MosaicLocationOptions } from './use-mosaic-location';
+import { useAdapterRead } from './use-mosaic-location';
+import { readWindowUrl, useWindowUrl, writeWindowUrl } from './window-location';
+
+function holds(routing: MosaicLocationOptions['routing'], segment: SegmentParts | undefined): boolean {
+ return routing === 'path' ? segment !== undefined && segment.length > 0 : segment !== undefined;
+}
+
+export function useConsumeLink(
+ location: MosaicLocation,
+ segment: SegmentParts | undefined,
+ { routing, path = '/' }: MosaicLocationOptions,
+): SegmentParts | undefined {
+ const { queryPrefix, reads } = useRoutingConfig();
+ const consumes = routing !== 'query';
+ const fromAdapter = useAdapterRead(consumes ? reads.useSearchParams : () => undefined, '?');
+ const fromWindow = useWindowUrl(consumes)?.search;
+ const search = fromAdapter ?? fromWindow;
+ const key = paramKey(queryPrefix, path);
+ const held = holds(routing, segment);
+ const linked = consumes && key !== '' && search !== undefined ? readParam(search, key) : undefined;
+ const fromLink = useMemo(() => (linked === undefined ? undefined : decodeParts(linked)), [linked]);
+ const settled = useRef(false);
+
+ useEffect(() => {
+ if (!consumes || key === '') {
+ return;
+ }
+ let live = true;
+ queueMicrotask(() => {
+ if (!live) {
+ return;
+ }
+ const atMount = !settled.current;
+ settled.current = true;
+ const before = readWindowUrl();
+ const value = before === undefined ? undefined : readParam(before.search, key);
+ if (value === undefined) {
+ return;
+ }
+ if (!atMount || !held) {
+ location.write(decodeParts(value), { replace: true });
+ }
+ const page = readWindowUrl();
+ if (page === undefined) {
+ return;
+ }
+ writeWindowUrl(urlOf({ ...page, search: writeParam(page.search, key, undefined) }), true);
+ });
+ return () => {
+ live = false;
+ };
+ }, [search, consumes, key, held, location]);
+
+ return held ? segment : (fromLink ?? segment);
+}
diff --git a/packages/mosaic/src/routing/router.ts b/packages/mosaic/src/routing/router.ts
index 3085b9c80a6..ec88ac04951 100644
--- a/packages/mosaic/src/routing/router.ts
+++ b/packages/mosaic/src/routing/router.ts
@@ -16,6 +16,9 @@ export interface Route {
params: Record;
}
+export type RouteParamsArgs =
+ Record extends RouteParams ? [params?: RouteParams] : [params: RouteParams];
+
type RouteArgs =
Record extends RouteParams
? [params?: RouteParams, rest?: Rest]
diff --git a/packages/mosaic/src/routing/routes.test-d.ts b/packages/mosaic/src/routing/routes.test-d.ts
index 6f276ca4273..78ade2d59c9 100644
--- a/packages/mosaic/src/routing/routes.test-d.ts
+++ b/packages/mosaic/src/routing/routes.test-d.ts
@@ -3,6 +3,7 @@ import { describe, expectTypeOf, test } from 'vitest';
import type { MosaicLocation } from './location';
import { createRouter } from './router';
import type { RouteParams } from './routes';
+import type { ReturnUrl } from './use-router';
describe('RouteParams', () => {
test('infers required and optional params from the pattern', () => {
@@ -36,3 +37,18 @@ describe('Router', () => {
expectTypeOf(router.parse([])?.name).toEqualTypeOf<'index' | 'security' | 'statement' | undefined>();
});
});
+
+describe('ReturnUrl', () => {
+ const returnUrl: ReturnUrl<{ security: 'security'; statement: 'billing/statement/:statementId' }> = () => '';
+
+ test('takes the params a pattern declares and returns a URL', () => {
+ expectTypeOf(returnUrl('security')).toEqualTypeOf();
+ returnUrl('statement', { statementId: 'st_1' });
+ // @ts-expect-error statementId is required
+ returnUrl('statement');
+ // @ts-expect-error unknown route
+ returnUrl('billing');
+ // @ts-expect-error a return URL takes no write options
+ returnUrl('security', {}, { replace: true });
+ });
+});
diff --git a/packages/mosaic/src/routing/use-mosaic-location.ts b/packages/mosaic/src/routing/use-mosaic-location.ts
index 5f5b778bf79..29269216777 100644
--- a/packages/mosaic/src/routing/use-mosaic-location.ts
+++ b/packages/mosaic/src/routing/use-mosaic-location.ts
@@ -32,7 +32,7 @@ const MODE_READS: Record = {
const LEADING: Record = { pathname: '', search: '?', hash: '#' };
-function useAdapterRead(useRead: AdapterRead, leading: string): string | undefined {
+export function useAdapterRead(useRead: AdapterRead, leading: string): string | undefined {
const value = useRead() ?? undefined;
const text = typeof value === 'object' ? value.toString() : value;
return text?.startsWith(leading) ? text.slice(leading.length) : text;
diff --git a/packages/mosaic/src/routing/use-router.ts b/packages/mosaic/src/routing/use-router.ts
index 65005268772..a515d948db4 100644
--- a/packages/mosaic/src/routing/use-router.ts
+++ b/packages/mosaic/src/routing/use-router.ts
@@ -1,15 +1,21 @@
import { logger } from '@clerk/shared/logger';
import { useEffect, useMemo, useRef, useState } from 'react';
+import { useConsumeLink } from './consume-link';
import type { MosaicLocation, SegmentParts } from './location';
-import type { Route, Router } from './router';
+import type { Route, RouteParamsArgs, Router } from './router';
import { createRouter } from './router';
+import type { RoutingConfig } from './router-adapter';
+import { useRoutingConfig } from './router-adapter';
import type { RouteName, RouteTable } from './routes';
import { isRouteName, routeParts } from './routes';
import type { RoutingScope } from './routing-scope';
import { createRoutingScope, useInheritedScope } from './routing-scope';
+import type { SegmentCodec } from './url-location';
+import { createSegmentCodec, urlOf, urlWith } from './url-location';
import type { MosaicLocationOptions } from './use-mosaic-location';
import { useFixedRoutingMode, useMosaicLocation } from './use-mosaic-location';
+import { readWindowUrl } from './window-location';
const EMPTY_PARAMS: Record = Object.freeze({});
const EMPTY_PARTS: SegmentParts = Object.freeze([]);
@@ -153,7 +159,8 @@ export function useRouterScope(
const scope = useMemo(() => createRoutingScope({ routing, path }), [routing, path]);
const rooted: Routes = { ...routes, [root]: '' };
const { location, table, router, segment } = useRouting(rooted, { routing, path });
- const held = useOwnedSegment(location, segment, routing === 'virtual');
+ const linked = useConsumeLink(location, segment, { routing, path });
+ const held = useOwnedSegment(location, linked, routing === 'virtual');
const { parts, matched } = useMatch(router, held);
const fallback = useMemo | undefined>(() => {
if (!ready || matched !== undefined) {
@@ -205,3 +212,35 @@ export function useRouter(routes: Routes): Nest
[router, matched],
);
}
+
+export type ReturnUrl = >(
+ name: Name,
+ ...args: RouteParamsArgs
+) => string;
+
+function returnCodec(
+ { routing, path = '/' }: MosaicLocationOptions,
+ { queryPrefix, hashPrefix }: RoutingConfig,
+): SegmentCodec {
+ return createSegmentCodec(routing === 'virtual' ? 'query' : routing, path, { query: queryPrefix, hash: hashPrefix });
+}
+
+export function useReturnUrl(routes: Routes): ReturnUrl {
+ const scope = useInheritedScope();
+ const config = useRoutingConfig();
+ const table = useStableTable(routes);
+ const codec = useMemo(() => (scope === undefined ? undefined : returnCodec(scope, config)), [scope, config]);
+
+ return useMemo>(
+ () =>
+ (name, ...[params]) => {
+ const page = readWindowUrl();
+ if (page === undefined) {
+ return '';
+ }
+ const url = codec === undefined ? undefined : urlWith(codec, page, routeParts(table, name, params));
+ return `${window.location.origin}${url ?? urlOf(page)}`;
+ },
+ [codec, table],
+ );
+}