Skip to content

Commit 583bd3e

Browse files
committed
docs(mosaic): align skills and docs with the code
1 parent 83b200c commit 583bd3e

10 files changed

Lines changed: 109 additions & 68 deletions

File tree

‎.changeset/mosaic-docs-align.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
---
2+
---

‎.claude/skills/mosaic/SKILL.md‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,16 +63,21 @@ canonical contract for the whole design system — the `--cl-*` tokens, the
6363
architecture" section that defines the split. Read it for the _what_; this skill
6464
is the _how-to_.
6565

66-
`packages/mosaic/src/features/user-button/` is the fullest worked example of the split
67-
in the repo — model, controller, view, wrapper, types, messages, and a feature
68-
test. Copy from it. Tests go in its `__tests__/` folder, as
69-
`packages/mosaic/docs/testing.md` describes under "Test placement".
66+
`packages/mosaic/src/features/switcher/` is the fullest worked example of the split
67+
in the repo — model, controller, view, wrapper, types, layout and styles. Copy from
68+
it. `UserButton` wraps it, and its feature test is in
69+
`packages/mosaic/src/features/user-button/__tests__/`. Tests go in a `__tests__/`
70+
folder, as `packages/mosaic/docs/testing.md` describes under "Test placement".
7071

7172
`packages/mosaic/AGENTS.md` loads for any work in the package. It maps common
7273
problems (errors, pending state, focus after removal, debouncing, confirm steps)
7374
to the shared helper that already solves them, and says to ask the user before
7475
adding a new pattern. Check it before writing any of those by hand.
7576

77+
Its "Shaping a fix" section covers bug fixes: fix the shared helper rather than
78+
wrapping it, and treat a changed shared signature as a new pattern. Read it
79+
before any `fix` PR.
80+
7681
## Which reference to read
7782

7883
Use the "Task guides" table in `packages/mosaic/AGENTS.md`. It is the shared

‎packages/mosaic/AGENTS.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,22 @@ Stop and check the table if you are writing any of these in a feature:
9898

9999
The form rule applies when you add or rewrite a form. Some existing forms predate it.
100100

101+
## Shaping a fix
102+
103+
A bug in a feature is often a gap in a shared helper. These rules apply to `fix` PRs as much as to features.
104+
105+
- **Fix the owner, don't wrap it.** When a shared helper (`src/hooks/`, `src/blocks/`, `src/components/`, `src/machine/`, or `@clerk/shared`) behaves wrongly, change the helper and its tests, then delete the workarounds. Do not spread a helper's return value to swap one method, copy a `||` that undoes one of its fields, or add a second hook beside it for one caller.
106+
- **A changed shared signature is a new pattern.** A new parameter, a return type that goes from `void` to a promise, or a returned field whose meaning changes all go through "When nothing fits: ask first".
107+
- **One source of truth for busy.** When a machine, `usePendingAction` or `useForm` already knows an action is running, derive the flag from it: `isDisabled: actions.isPending || remove.isPending`. Do not mirror it into a second lock, or turn machine state into a promise to feed one.
108+
- **Handle staleness through lifecycle.** A new identity remounts through a React `key`. A busy state ignores close (Controllers → Rules). Do not thread run ids or `AbortSignal`s through the model, controller and machine.
109+
- **Extend a contract with an options object.** Make a field required when every caller has it: `connect(strategy, { walletName, onTarget })`, not `connect(strategy, walletName?, onTarget?)`.
110+
- **Pass shared results through whole.** The view gets `form`, not an object that renames `form.id`, `form.isSubmitting` and `form.handleSubmit`.
111+
- **Keep controller state off model types.** Pending and error flags the controller sets go on a row type the controller builds, not as optional fields on the type the model returns.
112+
- **Narrow by mounting.** A hook that needs loaded data takes it non-null. Mount its component once the model is ready instead of checking for `null` inside (Controllers → Composition and dialog lifetime).
113+
- **Machines:** `assign` stays pure. An effect the machine starts runs in `invoke`. The runtime has no spawned actors, so effects that run side by side, like `useForm`'s per-field `validateAsync`, run in the hook and report back by event, and the machine drops stale results. A phase of an action the user can see (queued, pending, failed) is a named state, not a context field plus a predicate. Screens that can sit on top of any state, like reverification's method picker and help, may be a stack in context, because the runtime has no parallel or history states.
114+
115+
If code or a test contradicts a rule in these docs, do not copy the code. Stop and ask which one is right, and fix the loser in the same PR.
116+
101117
## Nested radii
102118

103119
A part inset from a rounded surface gets its radius from that surface: `max(0px, calc(outer - border - padding))`. Do not pick a fixed step, or it stops matching when `--cl-radius-*` or `--cl-spacing` is overridden. This applies to small insets. When the inset is about as large as the outer radius or larger (Card content, TagInput tags), the part keeps its own radius.

‎packages/mosaic/ARCHITECTURE.md‎

Lines changed: 40 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,15 @@ A theme styles a part from CSS, against that class and its attributes:
5959
}
6060
```
6161

62-
A part exposes no `className` or `style` prop. Inside `@clerk/mosaic`, code that renders a part and needs to nudge it passes StyleX atoms through `xstyle`, declared in its own `stylex.create` and composed last so they win:
62+
A part exposes no `className` or `style` prop. Inside `@clerk/mosaic`, code that renders a part and needs to nudge it passes StyleX atoms through `xstyle`, declared in its own `*.styles.ts` file and composed last so they win:
63+
64+
```ts
65+
// reverification.styles.ts
66+
export const styles = stylex.create({ helpText: { textAlign: 'center' } });
67+
```
6368

6469
```tsx
65-
const styles = stylex.create({ helpText: { textAlign: 'center' } });
70+
import { styles } from './reverification.styles';
6671

6772
<Text
6873
size='xs'
@@ -187,20 +192,20 @@ and neither can its tests. `src/machine/ADOPTION.md` holds the criteria.
187192
A flow slice lives under `src/features/<feature>/` and is split by role, one file per layer, prefixed with the feature name. Use `.ts` unless the file renders JSX:
188193

189194
```text
190-
user-button.model.ts(x) // Clerk adapter — the only file that imports Clerk
191-
user-button.controller.ts(x) // local state (React state or a machine) + action wrapping
192-
user-button.view.tsx // rendering only
193-
user-button.tsx // composition wrapper and the public props type
195+
switcher.model.ts(x) // Clerk adapter — the only file that imports Clerk
196+
switcher.controller.ts(x) // local state (React state or a machine) + action wrapping
197+
switcher.view.tsx // rendering only
198+
switcher.tsx // composition wrapper and the public props type
194199
```
195200

196201
Supporting files carry the parts that would otherwise bloat those four:
197202

198203
```text
199-
user-button.types.ts // the data contract the model and view both agree on
200-
user-button.messages.ts // every string the surface renders, as one `as const` object
201-
user-button.layout.ts // pure derivation (which affordance goes in which slot)
202-
user-button.utils.ts // pure helpers
203-
user-button.styles.ts // `stylex.create` atoms (see the StyleX authoring rules)
204+
switcher.types.ts // the data contract the model and view both agree on
205+
switcher.messages.ts // every string the surface renders, as one `as const` object
206+
switcher.layout.ts // pure derivation (which affordance goes in which slot)
207+
switcher.utils.ts // pure helpers
208+
switcher.styles.ts // `stylex.create` atoms (see the StyleX authoring rules)
204209
<name>.dialog.tsx // a dialog the view opens, when it would crowd the view file
205210
```
206211

@@ -270,10 +275,10 @@ Two shapes, chosen by whether the slice fetches its own data.
270275
wrapper resolves the model, hands it to the controller, and branches on `status`:
271276

272277
```tsx
273-
export function UserButton(props: UserButtonProps = {}) {
278+
export function Switcher(props: SwitcherProps = {}) {
274279
const { showTriggerLabel, mode, fallback, ...options } = props;
275-
const model = useUserButtonModel(options);
276-
const controller = useUserButtonController(model, { mode });
280+
const model = useSwitcherModel(options);
281+
const controller = useSwitcherController(model, { mode });
277282

278283
if (controller.status === 'loading') {
279284
return <>{fallback}</>;
@@ -285,7 +290,7 @@ export function UserButton(props: UserButtonProps = {}) {
285290

286291
const { status: _status, ...viewController } = controller;
287292
return (
288-
<UserButtonView
293+
<SwitcherView
289294
{...viewController}
290295
showTriggerLabel={showTriggerLabel}
291296
/>
@@ -313,12 +318,12 @@ branches on one value rather than on a scatter of `isLoaded` flags. Every callba
313318
it exposes is a plain function over plain ids — never a Clerk resource:
314319

315320
```tsx
316-
export type UserButtonModel =
321+
export type SwitcherModel =
317322
| { status: 'loading' }
318323
| { status: 'hidden' }
319-
| (UserButtonData & UserButtonCallbacks & { status: 'ready'; organizationsEnabled: boolean });
324+
| (SwitcherData & SwitcherCallbacks & { status: 'ready'; organizationsEnabled: boolean });
320325

321-
export function useUserButtonModel(options?: UserButtonModelOptions): UserButtonModel {
326+
export function useSwitcherModel(options?: SwitcherModelOptions): SwitcherModel {
322327
const { isLoaded: isUserLoaded, user } = useUser();
323328
const { isLoaded: isSessionLoaded, session } = useSession();
324329
const clerk = useClerk();
@@ -353,19 +358,19 @@ local state, wraps the model's actions to drive pending state, keeps the surface
353358
stable while an action runs, and closes the surface on the actions that should
354359
close it.
355360

356-
How it holds that state is a complexity call. `UserButton` earns a machine — an
361+
How it holds that state is a complexity call. `Switcher` earns a machine — an
357362
action is async, `open` and `pendingKey` constrain each other, and dismissing
358363
must not abandon an in-flight invoke — so the machine is declared in the same
359364
file with `setup<Context, Event>()`, and its context carries the injected effect.
360365
Abridged from `features/switcher/switcher.controller.tsx`:
361366

362367
```tsx
363-
const { createMachine, assign, fromPromise } = setup<UserButtonMachineContext, UserButtonMachineEvent>();
368+
const { createMachine, assign, fromPromise } = setup<SwitcherMachineContext, SwitcherMachineEvent>();
364369

365370
const settled = { pendingKey: null, frozenModel: null };
366371

367-
const userButtonMachine = createMachine({
368-
id: 'userButton',
372+
const switcherMachine = createMachine({
373+
id: 'switcher',
369374
initial: 'idle',
370375
context: { open: false, pendingKey: null, frozenModel: null, run: () => Promise.resolve(), closeOnSuccess: false },
371376
states: {
@@ -400,14 +405,20 @@ const userButtonMachine = createMachine({
400405
},
401406
{ target: 'idle', actions: assign(() => settled) },
402407
],
403-
onError: { target: 'idle', actions: assign(() => settled) },
408+
onError: {
409+
target: 'idle',
410+
actions: [
411+
assign(() => settled),
412+
(_, event) => console.error('[Clerk] User button action failed', event.error),
413+
],
414+
},
404415
}),
405416
},
406417
},
407418
});
408419

409-
export function useUserButtonController(model: UserButtonModel, options = {}): UserButtonController {
410-
const [{ context }, send] = useMachine(userButtonMachine);
420+
export function useSwitcherController(model: SwitcherModel, options = {}): SwitcherController {
421+
const [{ context }, send] = useMachine(switcherMachine);
411422
const displayPendingKey = useSpinDelay(context.pendingKey, { delay: 0 });
412423

413424
// While an action runs, render the model it started from, not the live one.
@@ -433,7 +444,7 @@ export function useUserButtonController(model: UserButtonModel, options = {}): U
433444
open: context.open,
434445
onOpenChange: next => send(next ? { type: 'OPEN' } : { type: 'CLOSE' }),
435446
pendingKey: displayPendingKey,
436-
onSelectOrganization: runAction(userButtonBusyKeys.selectOrganization, resolvedModel.onSelectOrganization, true),
447+
onSelectOrganization: runAction(switcherBusyKeys.selectOrganization, resolvedModel.onSelectOrganization, true),
437448
// …
438449
};
439450
}
@@ -474,7 +485,7 @@ export function useUserProfileEditUsernameController({ username = '', required =
474485
```
475486

476487
Reaching for a machine here would produce a two-state machine with one event,
477-
which is a boolean spelled long. Reaching for `useState` in `UserButton` would
488+
which is a boolean spelled long. Reaching for `useState` in `Switcher` would
478489
produce the flag soup the machine exists to prevent. `src/machine/ADOPTION.md` has
479490
the criteria and worked before/afters for the calls in between.
480491

@@ -485,7 +496,7 @@ derived — `open`, `pendingKey`, an absent callback — never on a machine snap
485496
so the view needs neither the machine nor Clerk:
486497

487498
```tsx
488-
export function UserButtonView({ open, onOpenChange, pendingKey, onSignOutAll, ...data }: UserButtonProps) {
499+
export function SwitcherView({ open, onOpenChange, pendingKey, onSignOutAll, ...data }: SwitcherViewProps) {
489500
return (
490501
<Popover
491502
open={open}
@@ -495,7 +506,7 @@ export function UserButtonView({ open, onOpenChange, pendingKey, onSignOutAll, .
495506
{onSignOutAll ? (
496507
<Item
497508
onClick={onSignOutAll}
498-
busy={pendingKey === userButtonBusyKeys.signOutAll()}
509+
busy={pendingKey === switcherBusyKeys.signOutAll()}
499510
>
500511
{m.accounts.signOutAll}
501512
</Item>

‎packages/mosaic/docs/controllers.md‎

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ error and releases the lock. It is not for:
6565

6666
`useConfirmController` earns a machine: the confirm is async, a failure must land
6767
back on the confirming step with a reason, and a cancelled reverification must
68-
close without one. `useUserButtonController` earns one because `open` and
68+
close without one. `useSwitcherController` earns one because `open` and
6969
`pendingKey` constrain each other and dismissing must not abandon an in-flight
7070
invoke.
7171

@@ -161,34 +161,35 @@ it. The runtime is documented next to the code:
161161
are the full API. Shared async test helpers are in
162162
`src/__tests__/async.ts`.
163163

164-
A machine never calls Clerk. The effect it invokes arrives through context as a
165-
plain function, seated by `useMachine(machine, { context })`, which re-seats
166-
context every render so the machine always invokes the latest one. From
167-
`user-profile-rename-passkey.controller.ts`:
164+
A machine never calls Clerk. The effect it runs arrives as a plain function. An
165+
effect that differs per action rides on the event and is assigned to context.
166+
From `blocks/confirm/confirm.controller.ts`:
168167

169168
```ts
170-
saving: {
171-
invoke: fromPromise(async context => context.onRename?.(context.passkeyId, context.name), {
172-
onDone: { target: 'idle' },
169+
confirming: {
170+
on: {
171+
CONFIRM: { target: 'pending', actions: assign((_, event) => ({ run: event.run, error: undefined })) },
172+
},
173+
},
174+
pending: {
175+
invoke: fromPromise(context => context.run(), {
176+
onDone: { target: 'idle', actions: assign(() => ({ error: undefined, open: false })) },
173177
onError: {
174-
target: 'editing',
178+
target: 'confirming',
175179
actions: assign((_, event) => ({ error: toLocalizableError(event.error) })),
176180
},
177181
}),
178-
}
179-
180-
const [snapshot, send] = useMachine(userProfileRenamePasskeyMachine, {
181-
context: { passkeyId: id, savedName: name, onRename },
182-
});
182+
},
183183
```
184184

185-
An effect that differs per action can ride on the event instead and be assigned
186-
to context, as `confirmationMachine` does with `CONFIRM`
187-
(`blocks/confirmation/confirmation.controller.ts`).
185+
An effect fixed for the controller's lifetime is seated by
186+
`useMachine(machine, { context })`, which re-seats context every render so the
187+
machine always runs the latest one (`onRedirect` in
188+
`features/waitlist/waitlist.controller.ts`).
188189

189190
Context holds the `ErrorDescription`, never copy (see "Errors"). A machine whose
190191
surface shows no error still logs it, so a failure is never silent
191-
(`user-button.controller.tsx`).
192+
(`features/switcher/switcher.controller.tsx`).
192193

193194
## Responsibilities
194195

@@ -334,7 +335,7 @@ One path, so every error a user sees goes through the `errors.*` catalog:
334335
dialogs), or `useForm` (forms). The first two call
335336
`toLocalizableError(cause)` from `utils/errors.ts`. Use one of them instead of
336337
catching in a feature. A controller with its own machine maps in the machine's
337-
`onError` (`user-profile-rename-passkey.controller.ts`).
338+
`onError` (`organization-list.controller.ts`).
338339
- **Machines that display all errors use `toLocalizableErrors(cause)`.** It
339340
preserves each error and its parameter name. Reverification stores this array,
340341
routes matching parameters to the active field and everything else to the

‎packages/mosaic/docs/models.md‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@ A discriminated union on `status`, so consumers branch on one value instead of a
1414
scatter of `isLoaded` flags:
1515

1616
```tsx
17-
export type UserButtonModel =
17+
export type SwitcherModel =
1818
| { status: 'loading' }
1919
| { status: 'hidden' }
20-
| (UserButtonData & UserButtonCallbacks & { status: 'ready'; organizationsEnabled: boolean });
20+
| (SwitcherData & SwitcherCallbacks & { status: 'ready'; organizationsEnabled: boolean });
2121
```
2222

2323
`hidden` is an **answer**, not an absence: signed out is settled, so the wrapper
@@ -53,17 +53,23 @@ drops the fallback instead of holding the space open. Keep the two apart.
5353
The view hides the affordance an absent callback drives, so the model never has
5454
to describe UI.
5555

56-
- **Own revalidate timing.** Call `.revalidate()` / `.reload()` after a mutation,
57-
from inside the callback that made it. Deciding _when_ is model logic:
56+
- **Own cache updates.** Update the cache after a mutation, from inside the
57+
callback that made it. Deciding _how_ is model logic: patch the returned
58+
resource in with `replaceInPages` on success, and revalidate on failure, since
59+
a failed mutation might mean stale state:
5860

5961
```tsx
6062
onAcceptSuggestion: async suggestionId => {
6163
try {
62-
await suggestionData.find(s => s.id === suggestionId)?.accept();
63-
} finally {
64-
// Always revalidate — a failed accept might be stale state. allSettled never throws,
64+
const accepted = await suggestionData.find(s => s.id === suggestionId)?.accept();
65+
if (accepted) {
66+
await userSuggestions.setData?.(pages => replaceInPages(pages ?? [], accepted));
67+
}
68+
} catch (error) {
69+
// A failed accept might be stale state. allSettled never throws,
6570
// so a failed revalidate doesn't look like a failed accept.
6671
await Promise.allSettled([userSuggestions.revalidate?.()]);
72+
throw error;
6773
}
6874
},
6975
```

‎packages/mosaic/docs/skeletons.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ peaking in the middle, sweeps left to right across two bone widths, over 1.6s
109109

110110
Not decided by the skeleton. The component that owns the loading state shows it for as
111111
long as the data is loading. The planned gate is
112-
`useSpinDelay(loading, { delay: 150, minDuration: 500 })` with the skeleton mounted
112+
`useSpinDelay(loading || null, { delay: 150, minDuration: 500 }) !== null` with the skeleton mounted
113113
but `visibility: hidden` until the delay passes, so a fast load never flashes it and
114114
nothing shifts when it appears.
115115

‎packages/mosaic/docs/views.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ The view renders plain props and calls plain callbacks. Nothing else.
1313
machine guard or works out for itself whether an action is allowed.
1414

1515
```tsx
16-
export function UserButtonView({ open, onOpenChange, pendingKey, onSignOutAll, ...data }: UserButtonProps) {
16+
export function SwitcherView({ open, onOpenChange, pendingKey, onSignOutAll, ...data }: SwitcherViewProps) {
1717
return (
1818
<Popover
1919
open={open}
@@ -22,7 +22,7 @@ export function UserButtonView({ open, onOpenChange, pendingKey, onSignOutAll, .
2222
{onSignOutAll ? (
2323
<Item
2424
onClick={onSignOutAll}
25-
busy={pendingKey === userButtonBusyKeys.signOutAll()}
25+
busy={pendingKey === switcherBusyKeys.signOutAll()}
2626
>
2727
{m.accounts.signOutAll}
2828
</Item>
@@ -37,7 +37,7 @@ export function UserButtonView({ open, onOpenChange, pendingKey, onSignOutAll, .
3737
Two shapes, chosen by whether the slice fetches its own data:
3838

3939
- A **wrapper composes** model + controller + view, and the view is a pure
40-
function of props (`user-button.tsx`).
40+
function of props (`switcher.tsx`).
4141
- A **leaf view owns its controller** and takes the effect as a prop
4242
(`UserProfileUsernameRowView` calls `useUserProfileEditUsernameController`
4343
with its `onSubmit`). Still no Clerk — the effect arrives from above.

0 commit comments

Comments
 (0)