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
17 changes: 17 additions & 0 deletions .changeset/mosaic-switcher.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@clerk/mosaic': minor
---

**Breaking:** Add `Switcher`, the account and organization menu, and make `UserButton` list accounts only. `Switcher` takes `mode`: `'combined'` (the default) lists accounts and organizations, `'user'` lists accounts only, and `'organization'` lists organizations. `<UserButton />` is now `<Switcher mode='user' />` and `<OrganizationSwitcher />` is `<Switcher mode='organization' />`. Each mode takes only its own props, so TypeScript flags organization options on `UserButton` and `triggerVariant` outside `combined`. A `mode` chosen at runtime takes only the props every mode shares.
Comment thread
alexcarpenter marked this conversation as resolved.
Resolved

| Before | After |
| --------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| `<UserButton />` (accounts and organizations) | `<Switcher />` |
| `<UserButton combined={false} />` | `<UserButton />` or `<Switcher mode='user' />` |
| `<UserButton triggerVariant='condensed' />` | `<Switcher triggerVariant='condensed' />` |
| Organization props on `UserButton` (`hidePersonal`, `afterSelectOrganizationUrl`, `createOrganizationUrl`, ...) | The same props on `Switcher` |
| `UserButtonProps` (combined menu) | `CombinedSwitcherProps` |
| `UserButtonProps` (user-only menu) | `UserButtonProps`, which now takes account options only |
| `.cl-user-button-*` classes on the combined menu | `.cl-switcher-*`; `UserButton` keeps `.cl-user-button-*` |

Find usages with `git grep -n -e "UserButton" -e "cl-user-button-"`.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client';

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

export default function Page() {
return (
Expand All @@ -12,7 +12,7 @@ export default function Page() {
},
}}
>
<UserButton customMenuItems={[{ id: 'custom-link', label: 'Custom link', href: '/custom/link-target' }]} />
<Switcher customMenuItems={[{ id: 'custom-link', label: 'Custom link', href: '/custom/link-target' }]} />
</MosaicProvider>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use client';

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

export function MosaicSwitcher() {
return (
<MosaicProvider experimental={{ newProfiles: true }}>
<Switcher />
</MosaicProvider>
);
}
4 changes: 2 additions & 2 deletions integration/templates/next-app-router-mosaic/src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Show, SignInButton } from '@clerk/nextjs';

import { MosaicUserButton } from './mosaic-user-button';
import { MosaicSwitcher } from './mosaic-switcher';

export default function Home() {
return (
Expand All @@ -12,7 +12,7 @@ export default function Home() {
<Show when='signed-in'>
<p>signed-in-state</p>
</Show>
<MosaicUserButton />
<MosaicSwitcher />
</header>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

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

export function MosaicUserButton() {
export default function Page() {
return (
<MosaicProvider experimental={{ newProfiles: true }}>
<UserButton />
<UserButton customMenuItems={[{ id: 'custom-link', label: 'Custom link', href: '/custom/link-target' }]} />
</MosaicProvider>
);
}
127 changes: 127 additions & 0 deletions integration/tests/mosaic/switcher.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
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 Switcher @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 Switcher cleanup failed');
}
});

const trigger = (page: Page) => page.getByRole('button', { name: /^Open account menu for / });
const popup = (page: Page) => page.getByRole('dialog', { name: 'Account' });

async function signIn({ page, context }: { page: Page; context: BrowserContext }, path = '/') {
const u = await createTestUtils({ app, page, context });
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(trigger(page)).toBeVisible();
return u;
}

async function openProfileSettings(page: Page) {
await popup(page).getByRole('button', { name: 'Settings' }).click();
const profileSettings = page.getByRole('menuitem', { name: 'Manage profile' });
const profile = page.getByRole('tab', { name: 'Account', exact: true });
await profileSettings.or(profile).first().waitFor();
if (await profileSettings.isVisible()) {
await profileSettings.click();
}
}

test('switches the active organization and keeps it across a reload', async ({ page, context }) => {
const u = await signIn({ page, context });
const { id, name } = organization;

await trigger(page).click();
await popup(page).getByRole('button', { name: 'Personal account' }).click();
await page.waitForFunction(() => window.Clerk?.organization === null);
await page.keyboard.press('Escape');
await expect(popup(page)).toBeHidden();

await trigger(page).click();
await popup(page).getByRole('button', { name }).click();
await page.waitForFunction(orgId => window.Clerk?.organization?.id === orgId, id);

await u.page.reload();
await u.page.waitForClerkJsLoaded();
await page.waitForFunction(orgId => window.Clerk?.organization?.id === orgId, id);
});

test('signs out', async ({ page, context }) => {
const u = await signIn({ page, context });

await trigger(page).click();
await popup(page).getByRole('button', { name: 'Sign out', exact: true }).click();

await u.po.expect.toBeSignedOut();
await expect(trigger(page)).toHaveCount(0);
});

test('sends add account to the sign-in page', async ({ page, context }) => {
await signIn({ page, context });

await trigger(page).click();
await popup(page).getByRole('button', { name: 'Add account' }).click();

await page.waitForURL(url => url.pathname.startsWith('/sign-in'));
});

test('follows a custom menu link', async ({ page, context }) => {
await signIn({ page, context }, '/custom');

await trigger(page).click();
await popup(page).getByRole('link', { name: 'Custom link' }).click();
await expect(page.getByText('custom-link-target')).toBeVisible();
});

test('opens the Mosaic UserProfile in a modal', async ({ page, context }) => {
await page.setViewportSize({ width: 1280, height: 800 });
await signIn({ page, context });

await trigger(page).click();
await openProfileSettings(page);

await expect(page.getByRole('tab', { name: 'Account', exact: true })).toHaveAttribute('aria-selected', 'true');
await expect(page.locator('.cl-userProfile-root')).toHaveCount(0);
await expect(popup(page)).toBeHidden();
});

test('renders a custom page inside the UserProfile modal', async ({ page, context }) => {
await page.setViewportSize({ width: 1280, height: 800 });
await signIn({ page, context }, '/custom');

await trigger(page).click();
await openProfileSettings(page);

await page.getByRole('tab', { name: 'Custom page', exact: true }).click();
await expect(page.getByText('custom-page-content')).toBeVisible();
});
});
66 changes: 18 additions & 48 deletions integration/tests/mosaic/user-button.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,11 @@ testAgainstRunningApps({ withPattern: ['next.appRouterMosaic.*'] })('Mosaic User
}
});

const path = '/user-button';
const trigger = (page: Page) => page.getByRole('button', { name: /^Open account menu for / });
const popup = (page: Page) => page.getByRole('dialog', { name: 'Account' });

async function signIn({ page, context }: { page: Page; context: BrowserContext }, path = '/') {
async function signIn({ page, context }: { page: Page; context: BrowserContext }) {
const u = await createTestUtils({ app, page, context });
await u.po.signIn.goTo();
await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password });
Expand All @@ -46,33 +47,25 @@ testAgainstRunningApps({ withPattern: ['next.appRouterMosaic.*'] })('Mosaic User
return u;
}

async function openProfileSettings(page: Page) {
await popup(page).getByRole('button', { name: 'Settings' }).click();
const profileSettings = page.getByRole('menuitem', { name: 'Manage profile' });
const profile = page.getByRole('tab', { name: 'Account', exact: true });
await profileSettings.or(profile).first().waitFor();
if (await profileSettings.isVisible()) {
await profileSettings.click();
}
}
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();

test('switches the active organization and keeps it across a reload', async ({ page, context }) => {
const u = await signIn({ page, context });
const { id, name } = organization;
await expect(trigger(page)).toHaveCount(0);
});

await trigger(page).click();
await popup(page).getByRole('button', { name: 'Personal account' }).click();
await page.waitForFunction(() => window.Clerk?.organization === null);
await page.keyboard.press('Escape');
await expect(popup(page)).toBeHidden();
test('lists no organizations while one is active', 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(trigger(page)).not.toContainText(organization.name);
await trigger(page).click();
await popup(page).getByRole('button', { name }).click();
await page.waitForFunction(orgId => window.Clerk?.organization?.id === orgId, id);

await u.page.reload();
await u.page.waitForClerkJsLoaded();
await page.waitForFunction(orgId => window.Clerk?.organization?.id === orgId, id);
await expect(popup(page).getByRole('button', { name: 'Sign out', exact: true })).toBeVisible();
await expect(popup(page).getByText(organization.name)).toHaveCount(0);
await expect(popup(page).getByText('Personal account')).toHaveCount(0);
await expect(popup(page).getByRole('button', { name: 'Invite members' })).toHaveCount(0);
});

test('signs out', async ({ page, context }) => {
Expand All @@ -95,33 +88,10 @@ testAgainstRunningApps({ withPattern: ['next.appRouterMosaic.*'] })('Mosaic User
});

test('follows a custom menu link', async ({ page, context }) => {
await signIn({ page, context }, '/custom');
await signIn({ page, context });

await trigger(page).click();
await popup(page).getByRole('link', { name: 'Custom link' }).click();
await expect(page.getByText('custom-link-target')).toBeVisible();
});

test('opens the Mosaic UserProfile in a modal', async ({ page, context }) => {
await page.setViewportSize({ width: 1280, height: 800 });
await signIn({ page, context });

await trigger(page).click();
await openProfileSettings(page);

await expect(page.getByRole('tab', { name: 'Account', exact: true })).toHaveAttribute('aria-selected', 'true');
await expect(page.locator('.cl-userProfile-root')).toHaveCount(0);
await expect(popup(page)).toBeHidden();
});

test('renders a custom page inside the UserProfile modal', async ({ page, context }) => {
await page.setViewportSize({ width: 1280, height: 800 });
await signIn({ page, context }, '/custom');

await trigger(page).click();
await openProfileSettings(page);

await page.getByRole('tab', { name: 'Custom page', exact: true }).click();
await expect(page.getByText('custom-page-content')).toBeVisible();
});
});
2 changes: 1 addition & 1 deletion packages/mosaic/.claude/skills/verify-mosaic/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ $ CS ab eval '(() => document.querySelector("[role=dialog]").dataset.variant)()'

Conventions:

- Routes are `/<group-slug>/<component-slug>`: `/components/button`, `/components/dialog`, `/user-button/user-button`, `/misc/organization-switcher`. The slug is the story's `meta.group` and `meta.title` run through `packages/swingset/src/lib/slug.ts`. A wrong path still returns 200 with `No docs found`, so check the level-1 heading. Read the paths of the expanded sidebar groups with `CS ab eval '(() => [...document.querySelectorAll("[data-sidebar] a")].map(a => a.getAttribute("href")))()'`, or click the link with `CS ab click 'a[href="/user-button/user-button"]'`.
- Routes are `/<group-slug>/<component-slug>`: `/components/button`, `/components/dialog`, `/switcher/switcher`, `/misc/organization-switcher`. The slug is the story's `meta.group` and `meta.title` run through `packages/swingset/src/lib/slug.ts`. A wrong path still returns 200 with `No docs found`, so check the level-1 heading. Read the paths of the expanded sidebar groups with `CS ab eval '(() => [...document.querySelectorAll("[data-sidebar] a")].map(a => a.getAttribute("href")))()'`, or click the link with `CS ab click 'a[href="/switcher/switcher"]'`.
- Prefer role and accessible name (`find role button --name …`). When `find` cannot resolve a name, as with the header switches, take `snapshot -i` and use the `@ref`. Refs change after every navigation and every re-render, so take a new snapshot first.
- Mosaic parts carry their identity in the DOM: a `.cl-<slot>` class plus `data-<axis>` attributes (`data-variant`, `data-size`, `data-color`, `data-open`). Assert on those, not on computed colours or class hashes. `data-style-src` lists the StyleX source lines that styled the element.
- Wrap every `eval` body in an IIFE. The page keeps `const`s between `eval` calls, and a second `const b` throws.
Expand Down
2 changes: 1 addition & 1 deletion packages/mosaic/.claude/skills/verify-mosaic/notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Prove it looks right in every state you touched.

Prove it works the way a user would test it: do the task end to end and check the result on the page.

- Pages are under the flow's group: `/user-button/...`, `/user-profile/...`, `/organization-profile/...`, `/misc/...`, `/blocks/...`. A section page such as `/user-profile/user-profile-email-section` has the default story first, then error and pending stories below it.
- Pages are under the flow's group: `/switcher/...`, `/user-profile/...`, `/organization-profile/...`, `/misc/...`, `/blocks/...`. A section page such as `/user-profile/user-profile-email-section` has the default story first, then error and pending stories below it.
- The data is fixtures, and they keep state on the page. On the email section, `Add email` β†’ type an address β†’ `Continue` β†’ type `424242` adds `Manage <address>` to the list.
- Drive the default story through the change, then the error story for the failure path. Prove the end state with a snapshot, not a screenshot alone.
- Turn on Chaos to check long and multi-script data.
Expand Down
4 changes: 2 additions & 2 deletions packages/mosaic/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,13 @@ Import the stylesheet and render Mosaic components beneath the SDK `ClerkProvide

```tsx
import { ClerkProvider } from '@clerk/react';
import { UserButton } from '@clerk/mosaic';
import { Switcher } from '@clerk/mosaic';
import '@clerk/mosaic/styles.css';

export function App({ children }) {
return (
<ClerkProvider publishableKey={process.env.CLERK_PUBLISHABLE_KEY}>
<UserButton />
<Switcher />
{children}
</ClerkProvider>
);
Expand Down
Loading
Loading