Skip to content

Commit 8229dfa

Browse files
feat(mosaic): add Profile and match the opened profile to the menu (#10758)
1 parent 0bba026 commit 8229dfa

38 files changed

Lines changed: 1253 additions & 595 deletions
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
---
2+
'@clerk/mosaic': minor
3+
---
4+
5+
**Breaking:** Add a `Profile` component that shows the account's pages, the active organization's pages, or both. `<UserProfile />` now shows only the account's pages, and `<OrganizationProfile />` only the organization's. To keep both in one profile, render `<Profile />`.
6+
7+
```tsx
8+
<Profile />
9+
<Profile mode='user' />
10+
<Profile mode='organization' afterLeaveOrganizationUrl='/organizations' />
11+
```
12+
13+
`mode` defaults to `'combined'`. Without a `mode`, `Profile` follows `MosaicProvider`'s `profile.combined`, so `false` shows only the account's pages.
14+
15+
With `experimental.newProfiles`, the profile a menu opens now matches the menu. `<UserButton />` and `<Switcher mode='user' />` open the account's pages, a lone `<OrganizationSwitcher />` opens the organization's pages, and only a combined `<Switcher />` opens one profile with both. `profile.combined: false` still splits a combined menu's profile in two.
16+
17+
| Before | After |
18+
| --------------------------------------------------------- | --------------------------------------------- |
19+
| `<UserProfile />` | `<Profile />` |
20+
| `<UserProfile combined />` | `<Profile />` |
21+
| `<UserProfile combined={false} />` | `<UserProfile />` or `<Profile mode='user' />` |
22+
| `<UserProfile organizationProfileProps={...} />` | `<Profile organizationProfileProps={...} />` |
23+
24+
To find the code to update, run:
25+
26+
```sh
27+
git grep -n '<UserProfile'
28+
```
29+
30+
New exported types: `ProfileProps`, `CombinedProfileProps` and `ProfileMode`.
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
'use client';
2+
3+
import { MosaicProvider, Profile } from '@clerk/mosaic';
4+
5+
export default function Page() {
6+
return (
7+
<MosaicProvider>
8+
<Profile
9+
customPages={[{ label: 'Custom page', path: 'custom-page', content: <p>custom-page-content</p> }]}
10+
organizationProfileProps={{
11+
customPages: [{ label: 'Team page', path: 'team-page', content: <p>team-page-content</p> }],
12+
}}
13+
/>
14+
</MosaicProvider>
15+
);
16+
}
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import type { Organization } from '@clerk/backend';
2+
import type { BrowserContext, Page } from '@playwright/test';
3+
import { expect, test } from '@playwright/test';
4+
5+
import type { FakeUser } from '../../testUtils';
6+
import { createTestUtils, testAgainstRunningApps } from '../../testUtils';
7+
8+
testAgainstRunningApps({ withPattern: ['next.appRouterMosaic.*'] })('Mosaic Profile @mosaic', ({ app }) => {
9+
test.describe.configure({ mode: 'serial' });
10+
11+
let fakeUser: FakeUser;
12+
let organization: Organization;
13+
const cleanups: Array<() => Promise<unknown>> = [];
14+
15+
test.beforeAll(async () => {
16+
const u = await createTestUtils({ app });
17+
fakeUser = u.services.users.createFakeUser(test);
18+
cleanups.push(() => fakeUser.deleteIfExists());
19+
const user = await u.services.users.createBapiUser(fakeUser);
20+
organization = await u.services.clerk.organizations.createOrganization({
21+
name: `Mosaic ${Date.now()}`,
22+
createdBy: user.id,
23+
});
24+
cleanups.push(() => u.services.clerk.organizations.deleteOrganization(organization.id));
25+
});
26+
27+
test.afterAll(async () => {
28+
const results = await Promise.allSettled(cleanups.map(cleanup => cleanup()));
29+
await app.teardown();
30+
const failures = results.flatMap(result => (result.status === 'rejected' ? [result.reason] : []));
31+
if (failures.length > 0) {
32+
throw new AggregateError(failures, 'Mosaic Profile cleanup failed');
33+
}
34+
});
35+
36+
const path = '/profile';
37+
const tab = (page: Page, name: string) => page.getByRole('navigation').getByRole('tab', { name, exact: true });
38+
39+
async function signIn({ page, context }: { page: Page; context: BrowserContext }) {
40+
const u = await createTestUtils({ app, page, context });
41+
await page.setViewportSize({ width: 1280, height: 800 });
42+
await u.po.signIn.goTo();
43+
await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password });
44+
await u.page.goToRelative(path);
45+
await u.po.expect.toBeSignedIn();
46+
await expect(tab(page, 'Account')).toBeVisible();
47+
return u;
48+
}
49+
50+
test('renders nothing when signed out', async ({ page, context }) => {
51+
const u = await createTestUtils({ app, page, context });
52+
await u.page.goToRelative(path);
53+
await u.page.waitForClerkJsLoaded();
54+
55+
await expect(tab(page, 'Account')).toHaveCount(0);
56+
});
57+
58+
test('opens on the account page with the signed-in user', async ({ page, context }) => {
59+
await signIn({ page, context });
60+
61+
await expect(tab(page, 'Account')).toHaveAttribute('aria-selected', 'true');
62+
await expect(page.getByText(fakeUser.email)).toBeVisible();
63+
});
64+
65+
test("lists the active organization's pages after the account's", async ({ page, context }) => {
66+
await signIn({ page, context });
67+
68+
await page.evaluate(orgId => window.Clerk?.setActive({ organization: orgId }), organization.id);
69+
await page.waitForFunction(orgId => window.Clerk?.organization?.id === orgId, organization.id);
70+
71+
await expect(tab(page, 'General')).toBeVisible();
72+
await expect(page.getByRole('navigation').getByRole('tab')).toHaveText([
73+
'Account',
74+
'Security',
75+
'Custom page',
76+
'General',
77+
'Members',
78+
'Team page',
79+
]);
80+
81+
await tab(page, 'General').click();
82+
await expect(tab(page, 'General')).toHaveAttribute('aria-selected', 'true');
83+
await expect(page.getByText(organization.name).first()).toBeVisible();
84+
});
85+
86+
test("renders a custom page in the organization's group", async ({ page, context }) => {
87+
await signIn({ page, context });
88+
89+
await page.evaluate(orgId => window.Clerk?.setActive({ organization: orgId }), organization.id);
90+
await page.waitForFunction(orgId => window.Clerk?.organization?.id === orgId, organization.id);
91+
92+
await tab(page, 'Team page').click();
93+
await expect(page.getByText('team-page-content')).toBeVisible();
94+
});
95+
96+
test('renders a custom page', async ({ page, context }) => {
97+
await signIn({ page, context });
98+
99+
await tab(page, 'Custom page').click();
100+
await expect(page.getByText('custom-page-content')).toBeVisible();
101+
});
102+
});

‎integration/tests/mosaic/user-profile.test.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,15 +62,14 @@ testAgainstRunningApps({ withPattern: ['next.appRouterMosaic.*'] })('Mosaic User
6262
await expect(page.getByText(fakeUser.email)).toBeVisible();
6363
});
6464

65-
test("lists the active organization's pages after the account's", async ({ page, context }) => {
65+
test("leaves out the organization's pages with an active organization", async ({ page, context }) => {
6666
await signIn({ page, context });
6767

6868
await page.evaluate(orgId => window.Clerk?.setActive({ organization: orgId }), organization.id);
6969
await page.waitForFunction(orgId => window.Clerk?.organization?.id === orgId, organization.id);
7070

71-
await tab(page, 'General').click();
72-
await expect(tab(page, 'General')).toHaveAttribute('aria-selected', 'true');
73-
await expect(page.getByText(organization.name).first()).toBeVisible();
71+
await expect(tab(page, 'Security')).toBeVisible();
72+
await expect(tab(page, 'General')).toHaveCount(0);
7473
});
7574

7675
test('renders a custom page', async ({ page, context }) => {

‎packages/mosaic/docs/documenting-components.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ Worked examples: `button.stories.tsx` and `button.mdx` (archetype A, simple), `p
2020
| Group | What lives here | Archetype |
2121
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ----------- |
2222
| `Switcher` | Composed flow UI (e.g. `Switcher`) | C |
23+
| `Profile` | Composed flow UI (`Profile`) | C |
2324
| `User Profile` | Composed flow UI (e.g. `UserProfileProfilePanel`) | C |
2425
| `Organization Profile` | Composed flow UI (e.g. `OrganizationProfileGeneralPanel`) | C |
2526
| `Misc` | Standalone composed components (e.g. `OrganizationSwitcher`, `Waitlist`) | C |
@@ -31,7 +32,7 @@ Worked examples: `button.stories.tsx` and `button.mdx` (archetype A, simple), `p
3132
| `Hooks` | Headless hooks (`useForm`) | B (adapted) |
3233
| `Localization` | The `localization` prop on `MosaicProvider`: catalogs, overrides, locale, and the message helpers | B (adapted) |
3334

34-
`Switcher` / `User Profile` / `Organization Profile` / `Misc` / `Blocks` → `Components` → `Primitives` runs high-level-composition → low-level-primitive. Composed layers are documented as compositions of lower layers (archetype C); leaf layers (Components, Primitives) get full prop/knob docs (archetypes A and B).
35+
`Switcher` / `Profile` / `User Profile` / `Organization Profile` / `Misc` / `Blocks` → `Components` → `Primitives` runs high-level-composition → low-level-primitive. Composed layers are documented as compositions of lower layers (archetype C); leaf layers (Components, Primitives) get full prop/knob docs (archetypes A and B).
3536

3637
`Styles` and `Hooks` are the non-component layers: there is no element to knob, so they follow
3738
archetype B's shape (Example → Usage → Parts → Styling) with `Props` replaced by whatever the export
@@ -205,7 +206,7 @@ The story is `meta` (no `styles`) plus a single `Default` export that renders th
205206

206207
Every props table has a **Default** column, and the `Type` stays a plain union, never with the default inlined. The auto `<PropTable>` fills it from `meta.styles._defaultVariants`; hand-written tables (`Prop | Type | Default | Description`) fill it by hand. Name the default member (`'bottom-start'`), use `—` when there is none and append `(required)` for a required prop, and state a behavioral default in words (`inherits Root`).
207208

208-
## Archetype C — composed layer (`Switcher`, `User Profile`, `Organization Profile`, `Misc`, `Blocks`, `Authentication`)
209+
## Archetype C — composed layer (`Switcher`, `Profile`, `User Profile`, `Organization Profile`, `Misc`, `Blocks`, `Authentication`)
209210

210211
These compose lower layers, so the docs lead with the composition rather than knobs. Required MDX:
211212

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,15 @@ describe('OrganizationProfile', () => {
8080
expect(screen.queryByText('Loading profile')).toBeNull();
8181
});
8282

83+
it("adds the provider's organization pages", async () => {
84+
serve();
85+
await renderWithClerk(<OrganizationProfile />, undefined, undefined, undefined, {
86+
userProfileProps: { customPages: [{ path: 'usage', label: 'Usage', content: <p>Usage</p> }] },
87+
organizationProfileProps: { customPages: [{ path: 'audit', label: 'Audit log', content: <p>Audit</p> }] },
88+
});
89+
expect(tabNames()).toEqual(['General', 'Members', 'Audit log']);
90+
});
91+
8392
it('renders nothing when signed out', async () => {
8493
const fapi = serve();
8594
fapi.client = fapiClient();

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

Lines changed: 7 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,9 @@
33
import type { ReactNode } from 'react';
44

55
import type { APIKeysPageProps } from '../api-keys/api-keys-table';
6-
import { useProfilePagesController } from '../profile-pages/profile-pages.controller';
7-
import { useMosaicProfile } from '../profile-pages/use-mosaic-profile';
8-
import { organizationProfilePageIds } from './organization-profile.layout';
9-
import { useOrganizationProfileModel } from './organization-profile.model';
6+
import { Profile } from '../profile/profile';
107
import type { OrganizationProfileOptions } from './organization-profile.provider';
11-
import { OrganizationProfileProvider } from './organization-profile.provider';
12-
import type { OrganizationProfilePageId, OrganizationProfilePages } from './organization-profile.types';
138
import type { OrganizationProfileViewProps } from './organization-profile.view';
14-
import { OrganizationProfileView } from './organization-profile.view';
15-
import { OrganizationProfileApiKeysPanel } from './organization-profile-api-keys-panel';
16-
import { OrganizationProfileGeneralPanel } from './organization-profile-general-panel';
17-
import { OrganizationProfileMembersPanel } from './organization-profile-members-panel/organization-profile-members-panel';
189

1910
/** Everything `<OrganizationProfile />` takes: your own pages and their order, the page it opens on, and where leaving the organization lands. */
2011
export interface OrganizationProfileProps
@@ -40,7 +31,7 @@ export interface OrganizationProfileProps
4031
}
4132

4233
/**
43-
* The active organization's profile: General, Members when the user may read or manage
34+
* The active organization's profile, the same as `<Profile mode='organization' />`: General, Members when the user may read or manage
4435
* memberships, and API keys when the instance enables them and the user may use them, with your own
4536
* pages alongside. It reads the organization from Clerk, so it takes no data. It renders `fallback`
4637
* until Clerk answers, and nothing at all when there is no active organization or nobody is signed in.
@@ -72,56 +63,11 @@ export interface OrganizationProfileProps
7263
* <OrganizationProfile afterLeaveOrganizationUrl='/organizations' />
7364
* ```
7465
*/
75-
export function OrganizationProfile(props: OrganizationProfileProps) {
76-
const { organizationProfileProps } = useMosaicProfile();
77-
const {
78-
customPages = organizationProfileProps?.customPages,
79-
pageOrder = organizationProfileProps?.pageOrder,
80-
path = organizationProfileProps?.path ?? '/organization',
81-
afterLeaveOrganizationUrl = organizationProfileProps?.afterLeaveOrganizationUrl,
82-
fallback,
83-
apiKeysProps = organizationProfileProps?.apiKeysProps,
84-
} = props;
85-
const model = useOrganizationProfileModel();
86-
const pages = model.status === 'ready' ? organizationProfilePanels(model.pages, apiKeysProps) : undefined;
87-
const { activePage, onPageChange } = useProfilePagesController(
88-
pages && organizationProfilePageIds({ pages, customPages, pageOrder }),
89-
{ routing: 'virtual', path },
90-
);
91-
92-
if (model.status === 'loading') {
93-
return fallback ?? null;
94-
}
95-
if (!pages || activePage === undefined) {
96-
return null;
97-
}
98-
66+
export function OrganizationProfile(props: OrganizationProfileProps): ReactNode {
9967
return (
100-
<OrganizationProfileProvider afterLeaveOrganizationUrl={afterLeaveOrganizationUrl}>
101-
<OrganizationProfileView
102-
elevation='flush'
103-
activePage={activePage}
104-
onPageChange={onPageChange}
105-
customPages={customPages}
106-
pageOrder={pageOrder}
107-
pages={pages}
108-
/>
109-
</OrganizationProfileProvider>
68+
<Profile
69+
{...props}
70+
mode='organization'
71+
/>
11072
);
11173
}
112-
113-
/**
114-
* The organization's built-in panels, for the pages the instance has turned on. `apiKeysProps.hide`
115-
* leaves the API keys panel out; the rest of `apiKeysProps` goes to it.
116-
*/
117-
export function organizationProfilePanels(
118-
available: readonly OrganizationProfilePageId[],
119-
{ hide: hideAPIKeys = false, ...apiKeysProps }: APIKeysPageProps = {},
120-
): OrganizationProfilePages {
121-
return {
122-
general: <OrganizationProfileGeneralPanel />,
123-
members: available.includes('members') ? <OrganizationProfileMembersPanel /> : undefined,
124-
apiKeys:
125-
available.includes('apiKeys') && !hideAPIKeys ? <OrganizationProfileApiKeysPanel {...apiKeysProps} /> : undefined,
126-
};
127-
}

‎packages/mosaic/src/features/profile-pages/use-mosaic-profile.ts‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,17 @@ import { createContext, useContext } from 'react';
22

33
import type { OrganizationProfileProps } from '../organization-profile/organization-profile';
44
import type { OrganizationProfilePageId } from '../organization-profile/organization-profile.types';
5+
import type { ProfileModalOptions } from '../profile/profile.modal.types';
56
import type { UserProfileProps } from '../user-profile/user-profile';
7+
import type { UserProfileModalOptions } from '../user-profile/user-profile.modal.types';
68
import type { CustomProfilePage, UserProfilePageId } from '../user-profile/user-profile.types';
79

810
export interface MosaicProfile {
911
/**
10-
* Whether one profile carries the account's pages and the active organization's. `false` keeps them
11-
* in separate profiles. It decides the profile's shape, not what `UserButton`'s menu lists.
12+
* Whether a menu that carries both the account and the organization opens one profile with both
13+
* groups of pages. `false` opens them as separate profiles. A menu that carries only one of them
14+
* always opens that one's profile. It is also the mode of a `<Profile />` without a `mode`:
15+
* `false` shows the account's pages alone.
1216
*
1317
* @default true
1418
*/
@@ -67,10 +71,14 @@ export function useMosaicProfile(): MosaicProfile {
6771
}
6872

6973
/** What the user profile modal opens with, whichever path opens it. */
70-
export function userProfileModalOptions({
71-
combined = true,
74+
export function userProfileModalOptions({ userProfileProps }: MosaicProfile): UserProfileModalOptions {
75+
return { ...userProfileProps };
76+
}
77+
78+
/** What the combined profile modal opens with, whichever path opens it. */
79+
export function profileModalOptions({
7280
userProfileProps,
7381
organizationProfileProps,
74-
}: MosaicProfile) {
75-
return { ...userProfileProps, combined, organizationProfileProps };
82+
}: MosaicProfile): ProfileModalOptions {
83+
return { ...userProfileProps, organizationProfileProps };
7684
}

0 commit comments

Comments
 (0)