Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .changeset/mosaic-profile-component.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
---
'@clerk/mosaic': minor
---

**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 />`.

```tsx
<Profile />
<Profile mode='user' />
<Profile mode='organization' afterLeaveOrganizationUrl='/organizations' />
```

`mode` defaults to `'combined'`. Without a `mode`, `Profile` follows `MosaicProvider`'s `profile.combined`, so `false` shows only the account's pages.

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.

| Before | After |
| --------------------------------------------------------- | --------------------------------------------- |
| `<UserProfile />` | `<Profile />` |
| `<UserProfile combined />` | `<Profile />` |
| `<UserProfile combined={false} />` | `<UserProfile />` or `<Profile mode='user' />` |
| `<UserProfile organizationProfileProps={...} />` | `<Profile organizationProfileProps={...} />` |

To find the code to update, run:

```sh
git grep -n '<UserProfile'
```

New exported types: `ProfileProps`, `CombinedProfileProps` and `ProfileMode`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
'use client';

import { MosaicProvider, Profile } from '@clerk/mosaic';

export default function Page() {
return (
<MosaicProvider>
<Profile
customPages={[{ label: 'Custom page', path: 'custom-page', content: <p>custom-page-content</p> }]}
organizationProfileProps={{
customPages: [{ label: 'Team page', path: 'team-page', content: <p>team-page-content</p> }],
}}
/>
</MosaicProvider>
);
}
102 changes: 102 additions & 0 deletions integration/tests/mosaic/profile.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import type { Organization } from '@clerk/backend';
import type { BrowserContext, Page } from '@playwright/test';
import { expect, test } from '@playwright/test';

import type { FakeUser } from '../../testUtils';
import { createTestUtils, testAgainstRunningApps } from '../../testUtils';

testAgainstRunningApps({ withPattern: ['next.appRouterMosaic.*'] })('Mosaic Profile @mosaic', ({ app }) => {
test.describe.configure({ mode: 'serial' });

let fakeUser: FakeUser;
let organization: Organization;
const cleanups: Array<() => Promise<unknown>> = [];

test.beforeAll(async () => {
const u = await createTestUtils({ app });
fakeUser = u.services.users.createFakeUser(test);
cleanups.push(() => fakeUser.deleteIfExists());
const user = await u.services.users.createBapiUser(fakeUser);
organization = await u.services.clerk.organizations.createOrganization({
name: `Mosaic ${Date.now()}`,
createdBy: user.id,
});
cleanups.push(() => u.services.clerk.organizations.deleteOrganization(organization.id));
});

test.afterAll(async () => {
const results = await Promise.allSettled(cleanups.map(cleanup => cleanup()));
await app.teardown();
const failures = results.flatMap(result => (result.status === 'rejected' ? [result.reason] : []));
if (failures.length > 0) {
throw new AggregateError(failures, 'Mosaic Profile cleanup failed');
}
});

const path = '/profile';
const tab = (page: Page, name: string) => page.getByRole('navigation').getByRole('tab', { name, exact: true });

async function signIn({ page, context }: { page: Page; context: BrowserContext }) {
const u = await createTestUtils({ app, page, context });
await page.setViewportSize({ width: 1280, height: 800 });
await u.po.signIn.goTo();
await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password });
await u.page.goToRelative(path);
await u.po.expect.toBeSignedIn();
await expect(tab(page, 'Account')).toBeVisible();
return u;
}

test('renders nothing when signed out', async ({ page, context }) => {
const u = await createTestUtils({ app, page, context });
await u.page.goToRelative(path);
await u.page.waitForClerkJsLoaded();

await expect(tab(page, 'Account')).toHaveCount(0);
});

test('opens on the account page with the signed-in user', async ({ page, context }) => {
await signIn({ page, context });

await expect(tab(page, 'Account')).toHaveAttribute('aria-selected', 'true');
await expect(page.getByText(fakeUser.email)).toBeVisible();
});

test("lists the active organization's pages after the account's", async ({ page, context }) => {
await signIn({ page, context });

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

await expect(tab(page, 'General')).toBeVisible();
await expect(page.getByRole('navigation').getByRole('tab')).toHaveText([
'Account',
'Security',
'Custom page',
'General',
'Members',
'Team page',
]);

await tab(page, 'General').click();
await expect(tab(page, 'General')).toHaveAttribute('aria-selected', 'true');
await expect(page.getByText(organization.name).first()).toBeVisible();
});

test("renders a custom page in the organization's group", async ({ page, context }) => {
await signIn({ page, context });

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

await tab(page, 'Team page').click();
await expect(page.getByText('team-page-content')).toBeVisible();
});

test('renders a custom page', async ({ page, context }) => {
await signIn({ page, context });

await tab(page, 'Custom page').click();
await expect(page.getByText('custom-page-content')).toBeVisible();
});
});
7 changes: 3 additions & 4 deletions integration/tests/mosaic/user-profile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,14 @@ testAgainstRunningApps({ withPattern: ['next.appRouterMosaic.*'] })('Mosaic User
await expect(page.getByText(fakeUser.email)).toBeVisible();
});

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

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

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

test('renders a custom page', async ({ page, context }) => {
Expand Down
5 changes: 3 additions & 2 deletions packages/mosaic/docs/documenting-components.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Worked examples: `button.stories.tsx` and `button.mdx` (archetype A, simple), `p
| Group | What lives here | Archetype |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ----------- |
| `Switcher` | Composed flow UI (e.g. `Switcher`) | C |
| `Profile` | Composed flow UI (`Profile`) | C |
| `User Profile` | Composed flow UI (e.g. `UserProfileProfilePanel`) | C |
| `Organization Profile` | Composed flow UI (e.g. `OrganizationProfileGeneralPanel`) | C |
| `Misc` | Standalone composed components (e.g. `OrganizationSwitcher`, `Waitlist`) | C |
Expand All @@ -31,7 +32,7 @@ Worked examples: `button.stories.tsx` and `button.mdx` (archetype A, simple), `p
| `Hooks` | Headless hooks (`useForm`) | B (adapted) |
| `Localization` | The `localization` prop on `MosaicProvider`: catalogs, overrides, locale, and the message helpers | B (adapted) |

`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).
`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).

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

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`).

## Archetype C — composed layer (`Switcher`, `User Profile`, `Organization Profile`, `Misc`, `Blocks`, `Authentication`)
## Archetype C — composed layer (`Switcher`, `Profile`, `User Profile`, `Organization Profile`, `Misc`, `Blocks`, `Authentication`)

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,15 @@ describe('OrganizationProfile', () => {
expect(screen.queryByText('Loading profile')).toBeNull();
});

it("adds the provider's organization pages", async () => {
serve();
await renderWithClerk(<OrganizationProfile />, undefined, undefined, undefined, {
userProfileProps: { customPages: [{ path: 'usage', label: 'Usage', content: <p>Usage</p> }] },
organizationProfileProps: { customPages: [{ path: 'audit', label: 'Audit log', content: <p>Audit</p> }] },
});
expect(tabNames()).toEqual(['General', 'Members', 'Audit log']);
});

it('renders nothing when signed out', async () => {
const fapi = serve();
fapi.client = fapiClient();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,9 @@
import type { ReactNode } from 'react';

import type { APIKeysPageProps } from '../api-keys/api-keys-table';
import { useProfilePagesController } from '../profile-pages/profile-pages.controller';
import { useMosaicProfile } from '../profile-pages/use-mosaic-profile';
import { organizationProfilePageIds } from './organization-profile.layout';
import { useOrganizationProfileModel } from './organization-profile.model';
import { Profile } from '../profile/profile';
import type { OrganizationProfileOptions } from './organization-profile.provider';
import { OrganizationProfileProvider } from './organization-profile.provider';
import type { OrganizationProfilePageId, OrganizationProfilePages } from './organization-profile.types';
import type { OrganizationProfileViewProps } from './organization-profile.view';
import { OrganizationProfileView } from './organization-profile.view';
import { OrganizationProfileApiKeysPanel } from './organization-profile-api-keys-panel';
import { OrganizationProfileGeneralPanel } from './organization-profile-general-panel';
import { OrganizationProfileMembersPanel } from './organization-profile-members-panel/organization-profile-members-panel';

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

/**
* The active organization's profile: General, Members when the user may read or manage
* The active organization's profile, the same as `<Profile mode='organization' />`: General, Members when the user may read or manage
* memberships, and API keys when the instance enables them and the user may use them, with your own
* pages alongside. It reads the organization from Clerk, so it takes no data. It renders `fallback`
* until Clerk answers, and nothing at all when there is no active organization or nobody is signed in.
Expand Down Expand Up @@ -72,56 +63,11 @@ export interface OrganizationProfileProps
* <OrganizationProfile afterLeaveOrganizationUrl='/organizations' />
* ```
*/
export function OrganizationProfile(props: OrganizationProfileProps) {
const { organizationProfileProps } = useMosaicProfile();
const {
customPages = organizationProfileProps?.customPages,
pageOrder = organizationProfileProps?.pageOrder,
path = organizationProfileProps?.path ?? '/organization',
afterLeaveOrganizationUrl = organizationProfileProps?.afterLeaveOrganizationUrl,
fallback,
apiKeysProps = organizationProfileProps?.apiKeysProps,
} = props;
const model = useOrganizationProfileModel();
const pages = model.status === 'ready' ? organizationProfilePanels(model.pages, apiKeysProps) : undefined;
const { activePage, onPageChange } = useProfilePagesController(
pages && organizationProfilePageIds({ pages, customPages, pageOrder }),
{ routing: 'virtual', path },
);

if (model.status === 'loading') {
return fallback ?? null;
}
if (!pages || activePage === undefined) {
return null;
}

export function OrganizationProfile(props: OrganizationProfileProps): ReactNode {
return (
<OrganizationProfileProvider afterLeaveOrganizationUrl={afterLeaveOrganizationUrl}>
<OrganizationProfileView
elevation='flush'
activePage={activePage}
onPageChange={onPageChange}
customPages={customPages}
pageOrder={pageOrder}
pages={pages}
/>
</OrganizationProfileProvider>
<Profile
{...props}
mode='organization'
/>
);
}

/**
* The organization's built-in panels, for the pages the instance has turned on. `apiKeysProps.hide`
* leaves the API keys panel out; the rest of `apiKeysProps` goes to it.
*/
export function organizationProfilePanels(
available: readonly OrganizationProfilePageId[],
{ hide: hideAPIKeys = false, ...apiKeysProps }: APIKeysPageProps = {},
): OrganizationProfilePages {
return {
general: <OrganizationProfileGeneralPanel />,
members: available.includes('members') ? <OrganizationProfileMembersPanel /> : undefined,
apiKeys:
available.includes('apiKeys') && !hideAPIKeys ? <OrganizationProfileApiKeysPanel {...apiKeysProps} /> : undefined,
};
}
20 changes: 14 additions & 6 deletions packages/mosaic/src/features/profile-pages/use-mosaic-profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@ import { createContext, useContext } from 'react';

import type { OrganizationProfileProps } from '../organization-profile/organization-profile';
import type { OrganizationProfilePageId } from '../organization-profile/organization-profile.types';
import type { ProfileModalOptions } from '../profile/profile.modal.types';
import type { UserProfileProps } from '../user-profile/user-profile';
import type { UserProfileModalOptions } from '../user-profile/user-profile.modal.types';
import type { CustomProfilePage, UserProfilePageId } from '../user-profile/user-profile.types';

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

/** What the user profile modal opens with, whichever path opens it. */
export function userProfileModalOptions({
combined = true,
export function userProfileModalOptions({ userProfileProps }: MosaicProfile): UserProfileModalOptions {
return { ...userProfileProps };
}

/** What the combined profile modal opens with, whichever path opens it. */
export function profileModalOptions({
userProfileProps,
organizationProfileProps,
}: MosaicProfile) {
return { ...userProfileProps, combined, organizationProfileProps };
}: MosaicProfile): ProfileModalOptions {
return { ...userProfileProps, organizationProfileProps };
}
Loading
Loading