Skip to content

Commit c9bdae3

Browse files
authored
feat(mosaic): add routing (#10602)
1 parent a331f11 commit c9bdae3

42 files changed

Lines changed: 2726 additions & 138 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.changeset/curly-books-pull.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@clerk/mosaic': minor
3+
---
4+
5+
`UserProfile` and `OrganizationProfile` now route their pages through a location instead of local state, which changes a few things for consumers:
6+
7+
- The `defaultPage` prop is removed. A profile opens on the first page in its navigation, as the legacy components do. To open on another page, put it first with `pageOrder`, or open the profile as a modal with the `page` option.
8+
- A new `path` prop sets the base a profile's pages live under, `/user` and `/organization` by default. Two profiles on one page need different bases.
9+
- There is no path or hash mode yet, so urls are not updated, this will come in a later version.
10+
- A custom page whose `path` cannot be a route, because it is percent-encoded, starts with a colon, or is the URL segment of a built-in page such as `api-keys`, is left out of the navigation with a console warning instead of rendering a page that cannot be reached.

‎packages/mosaic/eslint/__tests__/boundaries.test.mjs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,16 @@ ruleTester.run('dependencies', boundaries.rules.dependencies, {
201201
filename: 'src/modals/sample.ts',
202202
code: "import { setup } from '../machine/setup';",
203203
},
204+
{
205+
name: "src/modals/sample.ts may import down or across: import { useMosaicLocation } from '../routing/use-mosaic-location';",
206+
filename: 'src/modals/sample.ts',
207+
code: "import { useMosaicLocation } from '../routing/use-mosaic-location';",
208+
},
209+
{
210+
name: "src/features/reverification/sample.controller.ts may import down or across: import { useRouterScope } from '../../routing/use-router';",
211+
filename: 'src/features/reverification/sample.controller.ts',
212+
code: "import { useRouterScope } from '../../routing/use-router';",
213+
},
204214
{
205215
name: "src/blocks/sample.tsx may import down or across: import { Reverification } from '../features/reverification';",
206216
filename: 'src/blocks/sample.tsx',
@@ -425,5 +435,17 @@ ruleTester.run('dependencies', boundaries.rules.dependencies, {
425435
code: "import { Button } from '../components/button';",
426436
errors: [/down/],
427437
},
438+
{
439+
name: "src/routing/sample.ts cannot import up: import { ModalHost } from '../modals/modal-host';",
440+
filename: 'src/routing/sample.ts',
441+
code: "import { ModalHost } from '../modals/modal-host';",
442+
errors: [/down/],
443+
},
444+
{
445+
name: "src/components/sample.tsx cannot import up: import { useRouter } from '../routing/use-router';",
446+
filename: 'src/components/sample.tsx',
447+
code: "import { useRouter } from '../routing/use-router';",
448+
errors: [/down/],
449+
},
428450
].map(testCase => ({ ...testCase, options, settings: config.settings })),
429451
});

‎packages/mosaic/oxlint.config.mjs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ export default defineConfig({
4949
})),
5050
{ type: 'queries', pattern: 'src/queries', partialMatch: false },
5151
{ type: 'modals', pattern: 'src/modals', partialMatch: false },
52+
{ type: 'routing', pattern: 'src/routing', partialMatch: false },
5253
{ type: 'blocks', pattern: 'src/blocks', partialMatch: false },
5354
{ type: 'features', pattern: 'src/features/*', partialMatch: false, capture: ['feature'] },
5455
{ type: 'root', pattern: 'src', partialMatch: false },
@@ -286,7 +287,7 @@ export default defineConfig({
286287
checkUnknownLocals: true,
287288
checkInternals: true,
288289
message:
289-
'Mosaic layers import down: features, then blocks, modals and queries, then components, hooks, utils and styles, then primitives. Move the shared piece down a layer, or pass it in as a prop.',
290+
'Mosaic layers import down: features, then blocks, modals, queries and routing, then components, hooks, utils and styles, then primitives. Move the shared piece down a layer, or pass it in as a prop.',
290291
policies: [
291292
{ allow: { to: { module: { origin: ['external', 'core'] } } } },
292293
{ allow: { to: { element: { type: '{{ from.element.type }}' } } } },
@@ -296,6 +297,7 @@ export default defineConfig({
296297
from: { element: { type: ['utils', 'hooks', 'styles', 'components', 'localization', 'modals'] } },
297298
allow: { to: { element: { type: SHARED } } },
298299
},
300+
{ from: { element: { type: 'modals' } }, allow: { to: { element: { type: 'routing' } } } },
299301
{
300302
from: { element: { type: 'localization' } },
301303
allow: { to: { file: { categories: 'messages' } } },
@@ -309,7 +311,7 @@ export default defineConfig({
309311
},
310312
{
311313
from: { element: { type: 'features' } },
312-
allow: { to: { element: { type: [...SHARED, 'queries', 'modals', 'blocks'] } } },
314+
allow: { to: { element: { type: [...SHARED, 'queries', 'modals', 'blocks', 'routing'] } } },
313315
},
314316
{
315317
from: FLOW_UI,

‎packages/mosaic/src/features/organization-profile/__tests__/organization-profile.feature.test.tsx‎

Lines changed: 65 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@ import {
1414
fapiUser,
1515
} from '../../../__tests__/feature/fapi';
1616
import { renderWithClerk } from '../../../__tests__/feature/render';
17+
import { useModal } from '../../../modals/use-modal';
18+
import { useVirtualEntries } from '../../../routing/virtual-store';
1719
import { OrganizationProfile } from '../organization-profile';
20+
import { organizationProfileModal } from '../organization-profile.modal';
1821

1922
const acme = fapiOrganization({ id: 'org_1', name: 'Acme', slug: 'acme' });
2023

@@ -46,6 +49,17 @@ function tabNames() {
4649
.map(tab => tab.textContent);
4750
}
4851

52+
function Entry({ base }: { base: string }) {
53+
return <output data-testid='entry'>{JSON.stringify(useVirtualEntries().get(base) ?? null)}</output>;
54+
}
55+
56+
const entry = () => JSON.parse(screen.getByTestId('entry').textContent ?? 'null');
57+
58+
function OpenProfile({ page }: { page: string }) {
59+
const profile = useModal(organizationProfileModal);
60+
return <button onClick={() => profile.open({ page })}>Open profile</button>;
61+
}
62+
4963
describe('OrganizationProfile', () => {
5064
it('shows the fallback while Clerk loads, then the general page', async () => {
5165
serve();
@@ -108,21 +122,64 @@ describe('OrganizationProfile', () => {
108122

109123
it('passes the API keys options to the API keys page', async () => {
110124
serve({ orgAPIKeysEnabled: true, permissions: ['org:sys_api_keys:read', 'org:sys_api_keys:manage'] });
111-
await renderWithClerk(
112-
<OrganizationProfile
113-
defaultPage='apiKeys'
114-
apiKeysProps={{ showDescription: true }}
115-
/>,
116-
);
125+
await renderWithClerk(<OrganizationProfile apiKeysProps={{ showDescription: true }} />);
117126
const user = userEvent.setup();
118127

128+
await user.click(profileNav().getByRole('tab', { name: 'API Keys' }));
119129
await screen.findByText('API keys loaded');
120130
const dialog = await openDialog(user, screen.getByRole('button', { name: 'Create API key' }), {
121131
name: 'Add new API key',
122132
});
123133
expect(within(dialog).getByRole('textbox', { name: 'Description' })).toBeVisible();
124134
});
125135

136+
it('starts on the first page again after it was unmounted', async () => {
137+
serve();
138+
const { rerender } = await renderWithClerk(<OrganizationProfile key='first' />);
139+
const user = userEvent.setup();
140+
141+
await user.click(profileNav().getByRole('tab', { name: 'Members' }));
142+
rerender(<p>Elsewhere</p>);
143+
rerender(<OrganizationProfile key='second' />);
144+
145+
expect(profileNav().getByRole('tab', { name: 'General' })).toHaveAttribute('aria-selected', 'true');
146+
expect(screen.getByRole('heading', { level: 3, name: 'General' })).toBeVisible();
147+
});
148+
149+
it('routes two profiles on one page independently when they have different bases', async () => {
150+
serve();
151+
await renderWithClerk(
152+
<>
153+
<OrganizationProfile path='/first' />
154+
<OrganizationProfile path='/second' />
155+
</>,
156+
);
157+
const user = userEvent.setup();
158+
const [first, second] = screen.getAllByRole('navigation', { name: 'Organization' }).map(nav => within(nav));
159+
160+
await user.click(first.getByRole('tab', { name: 'Members' }));
161+
162+
expect(first.getByRole('tab', { name: 'Members' })).toHaveAttribute('aria-selected', 'true');
163+
expect(second.getByRole('tab', { name: 'General' })).toHaveAttribute('aria-selected', 'true');
164+
});
165+
166+
it('opens as a modal on the requested page, writing the segment legacy used', async () => {
167+
serve({ orgAPIKeysEnabled: true, permissions: ['org:sys_memberships:read', 'org:sys_api_keys:read'] });
168+
await renderWithClerk(
169+
<>
170+
<OpenProfile page='apiKeys' />
171+
<Entry base='/modal/organization' />
172+
</>,
173+
);
174+
const user = userEvent.setup();
175+
176+
await user.click(screen.getByRole('button', { name: 'Open profile' }));
177+
const dialog = await screen.findByRole('dialog');
178+
179+
expect(await within(dialog).findByRole('tab', { name: 'API Keys' })).toHaveAttribute('aria-selected', 'true');
180+
expect(entry()).toEqual(['api-keys']);
181+
});
182+
126183
it('switches pages from the navigation', async () => {
127184
serve({ orgAPIKeysEnabled: true, permissions: ['org:sys_memberships:read', 'org:sys_api_keys:read'] });
128185
await renderWithClerk(<OrganizationProfile />);
@@ -149,20 +206,6 @@ describe('OrganizationProfile', () => {
149206
expect(screen.getByText('Usage this month')).toBeVisible();
150207
});
151208

152-
it('opens on the default page without reordering the navigation', async () => {
153-
serve();
154-
await renderWithClerk(<OrganizationProfile defaultPage='members' />);
155-
expect(tabNames()).toEqual(['General', 'Members']);
156-
expect(profileNav().getByRole('tab', { name: 'Members' })).toHaveAttribute('aria-selected', 'true');
157-
expect(screen.getByRole('heading', { level: 3, name: 'Members' })).toBeVisible();
158-
});
159-
160-
it('opens on the first page when the default page is unavailable', async () => {
161-
serve({ orgAPIKeysEnabled: false });
162-
await renderWithClerk(<OrganizationProfile defaultPage='apiKeys' />);
163-
expect(profileNav().getByRole('tab', { name: 'General' })).toHaveAttribute('aria-selected', 'true');
164-
});
165-
166209
it('sends the user to afterLeaveOrganizationUrl after leaving from the general page', async () => {
167210
const fapi = serve();
168211
const { navigate } = await renderWithClerk(<OrganizationProfile afterLeaveOrganizationUrl='/organizations' />);
@@ -190,7 +233,8 @@ describe('OrganizationProfile', () => {
190233
client: fapiClient([fapiSession({ id: 'sess_1', user, last_active_organization_id: acme.id })]),
191234
memberships,
192235
});
193-
const { clerk } = await renderWithClerk(<OrganizationProfile defaultPage='members' />);
236+
const { clerk } = await renderWithClerk(<OrganizationProfile />);
237+
await userEvent.setup().click(profileNav().getByRole('tab', { name: 'Members' }));
194238

195239
await act(() => clerk.setActive({ organization: globex.id }));
196240
await waitFor(() => expect(tabNames()).toEqual(['General']));

‎packages/mosaic/src/features/organization-profile/__tests__/organization-profile.layout.test.tsx‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,16 @@ describe('resolveOrganizationProfilePages', () => {
1717
});
1818
});
1919

20+
describe('resolveOrganizationProfilePages custom paths', () => {
21+
it("accepts a path that is only a built-in segment in the user profile's combined view", () => {
22+
const keys: CustomOrganizationProfilePage = { label: 'Keys', path: 'organization/api-keys', content: null };
23+
expect(resolveOrganizationProfilePages(['general'], [keys])).toEqual([
24+
{ id: 'general' },
25+
{ id: 'organization/api-keys', custom: keys },
26+
]);
27+
});
28+
});
29+
2030
describe('getAvailableOrganizationProfilePages', () => {
2131
it('lists api keys given content', () => {
2232
expect(getAvailableOrganizationProfilePages({ general, apiKeys: <p>API keys</p> })).toEqual(['general', 'apiKeys']);

‎packages/mosaic/src/features/organization-profile/organization-profile.layout.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { Key } from '../../icons/glyphs/key';
55
import { SecurityLockSquare } from '../../icons/glyphs/security-lock-square';
66
import { Users } from '../../icons/glyphs/users';
77
import { applyOrder } from '../../utils/apply-order';
8-
import { withUniquePaths } from '../profile-pages/profile-pages.layout';
8+
import { withRoutablePaths, withUniquePaths } from '../profile-pages/profile-pages.layout';
99
import type {
1010
CustomOrganizationProfilePage,
1111
OrganizationProfilePageId,
@@ -45,7 +45,7 @@ export function resolveOrganizationProfilePages(
4545
customPages: readonly CustomOrganizationProfilePage[] = [],
4646
order?: readonly string[],
4747
): OrganizationProfileNavEntry[] {
48-
const uniqueCustomPages = withUniquePaths(customPages);
48+
const uniqueCustomPages = withUniquePaths(withRoutablePaths(customPages, ORGANIZATION_PROFILE_PAGE_IDS));
4949
const customById = new Map(uniqueCustomPages.map(page => [page.path, page]));
5050
const builtInIds = new Set<string>(builtIn);
5151
const entries: OrganizationProfileNavEntry[] = [

‎packages/mosaic/src/features/organization-profile/organization-profile.modal-content.tsx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import type { OrganizationProfileModalContentProps } from './organization-profil
77
export default function OrganizationProfileModalContent({
88
options,
99
close,
10+
path,
1011
}: OrganizationProfileModalContentProps): React.ReactElement {
1112
const { isLoaded, organization } = useOrganization();
1213
const inactive = isLoaded && !organization;
@@ -17,11 +18,11 @@ export default function OrganizationProfileModalContent({
1718
}
1819
}, [inactive, close]);
1920

20-
const { page, ...props } = options ?? {};
21+
const { page: _page, ...props } = options ?? {};
2122
return (
2223
<OrganizationProfile
2324
{...props}
24-
defaultPage={page}
25+
path={path}
2526
/>
2627
);
2728
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
import { defineModalSurface } from '../../modals/define-modal-surface';
2+
import { pageParts } from '../profile-pages/profile-pages.layout';
23
import type { OrganizationProfileModalOptions } from './organization-profile.modal.types';
34

45
export const organizationProfileModal = defineModalSurface<OrganizationProfileModalOptions>({
56
id: 'organizationProfile',
67
variant: 'profile',
78
load: () => import('./organization-profile.modal-content'),
9+
path: '/modal/organization',
10+
initialParts: options => pageParts(options?.page),
811
});
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import type { ModalContentProps } from '../../modals/modal.types';
22
import type { OrganizationProfileProps } from './organization-profile';
3+
import type { OrganizationProfileViewProps } from './organization-profile.view';
34

45
export interface OrganizationProfileModalOptions extends Pick<
56
OrganizationProfileProps,
67
'customPages' | 'pageOrder' | 'afterLeaveOrganizationUrl' | 'apiKeysProps'
78
> {
8-
page?: OrganizationProfileProps['defaultPage'];
9+
page?: OrganizationProfileViewProps['activePage'];
910
}
1011

1112
export type OrganizationProfileModalContentProps = ModalContentProps<OrganizationProfileModalOptions>;

‎packages/mosaic/src/features/organization-profile/organization-profile.tsx‎

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,11 @@ export interface OrganizationProfileProps
2222
Pick<OrganizationProfileViewProps, 'customPages' | 'pageOrder'>,
2323
Pick<OrganizationProfileOptions, 'afterLeaveOrganizationUrl'> {
2424
/**
25-
* The page the profile opens on: a built-in page's id, or a custom page's `path`. Unlike
26-
* `pageOrder`, it leaves the navigation order alone. A page the navigation does not list opens
27-
* the first page instead.
25+
* The base the profile's pages are nested under. Two profiles on one page need different bases.
2826
*
29-
* @default the first page in the navigation
27+
* @default '/organization'
3028
*/
31-
defaultPage?: OrganizationProfileViewProps['activePage'];
29+
path?: string;
3230
/**
3331
* Rendered while Clerk is loading. Nothing renders once the answer is that there is no active
3432
* organization.
@@ -60,12 +58,6 @@ export interface OrganizationProfileProps
6058
* ```
6159
*
6260
* @example
63-
* `defaultPage` picks the page the profile opens on without moving it in the navigation.
64-
* ```tsx
65-
* <OrganizationProfile defaultPage='members' />
66-
* ```
67-
*
68-
* @example
6961
* `customPages` adds your own pages; `pageOrder` places them among the built-in ones.
7062
* ```tsx
7163
* <OrganizationProfile
@@ -85,30 +77,31 @@ export function OrganizationProfile(props: OrganizationProfileProps) {
8577
const {
8678
customPages = organizationProfileProps?.customPages,
8779
pageOrder = organizationProfileProps?.pageOrder,
88-
defaultPage,
80+
path = organizationProfileProps?.path ?? '/organization',
8981
afterLeaveOrganizationUrl = organizationProfileProps?.afterLeaveOrganizationUrl,
9082
fallback,
9183
apiKeysProps = organizationProfileProps?.apiKeysProps,
9284
} = props;
9385
const model = useOrganizationProfileModel();
9486
const pages = model.status === 'ready' ? organizationProfilePanels(model.pages, apiKeysProps) : undefined;
95-
const navigation = useProfilePagesController(
96-
defaultPage ?? pageOrder?.[0] ?? 'general',
87+
const { activePage, onPageChange } = useProfilePagesController(
9788
pages && organizationProfilePageIds({ pages, customPages, pageOrder }),
89+
{ routing: 'virtual', path },
9890
);
9991

10092
if (model.status === 'loading') {
10193
return fallback ?? null;
10294
}
103-
if (!pages) {
95+
if (!pages || activePage === undefined) {
10496
return null;
10597
}
10698

10799
return (
108100
<OrganizationProfileProvider afterLeaveOrganizationUrl={afterLeaveOrganizationUrl}>
109101
<OrganizationProfileView
110102
elevation='flush'
111-
{...navigation}
103+
activePage={activePage}
104+
onPageChange={onPageChange}
112105
customPages={customPages}
113106
pageOrder={pageOrder}
114107
pages={pages}

0 commit comments

Comments
 (0)