Skip to content

Commit afdd068

Browse files
refactor(mosaic): let controllers own identifier row pending state
usePendingAction gains guard(), which runs a confirmation's confirm under the section lock, replacing runExternal and the wrapper each section copied. Section controllers put verify and primary pending flags on the rows they return, so views no longer compare pending keys. Confirmation drops the disabled prop, which no reachable state could set.
1 parent 6e0a702 commit afdd068

20 files changed

Lines changed: 87 additions & 159 deletions

‎packages/mosaic/AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ Most problems a feature hits already have a shared answer. Find the row for your
3434
| Problem | Use |
3535
| ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
3636
| An async action from a button or row: pending, an error, one lock | `usePendingAction` (`src/hooks/`) |
37-
| Direct actions and confirmation dialogs that must exclude each other | Section controller wraps `confirm` with `usePendingAction.runExternal` (`src/hooks/`, `src/blocks/confirm/`) |
37+
| Direct actions and confirmation dialogs that must exclude each other | `usePendingAction.guard` on the confirmation (`src/hooks/`, `src/blocks/confirm/`) |
3838
| A form: values, validation, submit, field errors | `useForm` (`src/components/form/`), with `validateAsync` for a server-side check |
3939
| A `<form>` element, without the browser's validation popup | `Form` (`src/primitives/form/`) |
4040
| A model save whose Clerk errors should land on form fields | `save` (`src/utils/errors.ts`) in the model, or reject with `FormSubmitError` |

‎packages/mosaic/docs/controllers.md‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,11 @@ It owns the error (see "Errors"):
4545
const actions = usePendingAction({ errorFallback: messages.errors.generic });
4646

4747
return {
48-
rows: rows.map(row => (actions.errorKey === row.id ? { ...row, error: actions.error } : row)),
49-
pendingId: actions.pendingKey,
48+
rows: rows.map(row => ({
49+
...row,
50+
isPending: actions.pendingKey === row.id,
51+
error: actions.errorKey === row.id ? actions.error : undefined,
52+
})),
5053
onRemove: id => void actions.run(id, () => onRemove(id)),
5154
};
5255
```
@@ -61,27 +64,24 @@ const remove = useConfirmController<UserProfileEmail>({
6164
});
6265

6366
return {
67+
contacts: contacts.map(contact => ({ ...contact, isPrimaryPending: actions.pendingKey === contact.id })),
6468
isDisabled: actions.isPending,
65-
pendingPrimaryId: actions.pendingKey,
66-
remove: {
67-
...remove,
68-
confirm: async contact => (await actions.runExternal(() => remove.confirm(contact))) ?? false,
69-
},
69+
remove: actions.guard(remove),
7070
};
7171
```
7272

7373
Keep this coordination in the section controller. Run direct actions with
74-
`actions.run(key, action)` and wrap the returned confirmation's `confirm` callback
75-
with `actions.runExternal`. Pass `actions.isPending` to the section controls'
76-
`disabled` props, including `Confirmation.disabled`.
74+
`actions.run(key, action)` and pass the confirmation through `actions.guard`, which
75+
runs its `confirm` under the same lock. Pass `actions.isPending` to the section
76+
controls' `disabled` props.
7777

7878
`confirm` resolves `true` when the operation succeeds, or `false` when it fails or
7979
the dialog ignores the call. Its promise follows the operation even if the
8080
dialog closes during cancellation. The shared pending owner waits for that
8181
promise, so closing the dialog does not enable another action before cancellation
8282
settles. Removal keeps its dialog errors, and inline row errors and focus keys
83-
stay unchanged. Views receive the pending and disabled props without coordinating
84-
the operations.
83+
stay unchanged. Put each row's pending state on the row the controller returns,
84+
so views render it without comparing pending keys.
8585

8686
`run` resolves `true` on success, so the caller can close a dialog or move
8787
focus. To hold pending through an OAuth redirect, await a delay inside the

‎packages/mosaic/src/blocks/confirmation/__tests__/confirmation.feature.test.tsx‎

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,7 @@ function Host<Payload>({
3838

3939
async function renderAccount(
4040
options: ConfirmControllerOptions<void>,
41-
{
42-
localization,
43-
description,
44-
disabled,
45-
}: { localization?: MosaicLocalization; description?: ReactNode; disabled?: boolean } = {},
41+
{ localization, description }: { localization?: MosaicLocalization; description?: ReactNode } = {},
4642
) {
4743
const ref: { current: ConfirmController | undefined } = { current: undefined };
4844
serveFapi({ client: fapiClient([session]) });
@@ -57,7 +53,6 @@ async function renderAccount(
5753
title={TITLE}
5854
description={description ?? 'Google will be removed from this account.'}
5955
actionLabel='Remove'
60-
disabled={disabled}
6156
/>
6257
);
6358
}}
@@ -75,19 +70,6 @@ async function renderAccount(
7570
const confirmButton = () => screen.getByRole('button', { name: 'Remove' });
7671

7772
describe('Confirmation', () => {
78-
it('disables confirmation while leaving Cancel usable', async () => {
79-
const onConfirm = vi.fn(() => Promise.resolve());
80-
const { user, open, closed } = await renderAccount({ onConfirm }, { disabled: true });
81-
await open();
82-
83-
expect(confirmButton()).toBeDisabled();
84-
await user.click(confirmButton());
85-
expect(onConfirm).not.toHaveBeenCalled();
86-
87-
await user.click(screen.getByRole('button', { name: 'Cancel' }));
88-
await closed();
89-
});
90-
9173
it('opens from its trigger, confirms, closes once the action lands, and hands focus back', async () => {
9274
const run = deferred<void>();
9375
const onConfirm = vi.fn(() => run.promise);

‎packages/mosaic/src/blocks/confirmation/confirmation.tsx‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ export type ConfirmationColor = 'negative' | 'primary';
1010
export interface ConfirmationProps<Payload = void> extends ConfirmBlockProps<Payload> {
1111
/** The weight the confirming button carries. An action that can be undone takes `primary` (default: `negative`) */
1212
color?: ConfirmationColor;
13-
disabled?: boolean;
1413
}
1514

1615
/**
@@ -37,7 +36,7 @@ export interface ConfirmationProps<Payload = void> extends ConfirmBlockProps<Pay
3736
* actionLabel='Remove'
3837
* />
3938
*/
40-
export function Confirmation<Payload = void>({ color = 'negative', disabled, ...props }: ConfirmationProps<Payload>) {
39+
export function Confirmation<Payload = void>({ color = 'negative', ...props }: ConfirmationProps<Payload>) {
4140
return (
4241
<ConfirmShell {...props}>
4342
{({ title, description, actionLabel, cancelLabel, isPending, errorMessage, confirm }) => (
@@ -68,7 +67,6 @@ export function Confirmation<Payload = void>({ color = 'negative', disabled, ...
6867
fullWidth
6968
color={color}
7069
isPending={isPending}
71-
disabled={disabled && !isPending}
7270
onClick={confirm}
7371
>
7472
{actionLabel}

‎packages/mosaic/src/features/user-profile/user-profile-contact-list-row.view.tsx‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { Section } from '../../components/section';
1010
import { Plus } from '../../icons/glyphs/plus';
1111
import { fill, useMessages } from '../../localization';
1212
import { truncationStyles } from '../../styles/typography.styles';
13-
import type { UserProfileContact } from './user-profile-contact.types';
13+
import type { UserProfileContact, UserProfileContactRow } from './user-profile-contact.types';
1414
import { styles } from './user-profile-profile-panel.styles';
1515

1616
export interface UserProfileContactListRowViewProps {
@@ -19,11 +19,9 @@ export interface UserProfileContactListRowViewProps {
1919
addAction?: ReactNode;
2020
kind: 'email' | 'phone';
2121
label: string;
22-
items: UserProfileContact[];
22+
items: UserProfileContactRow[];
2323
onAdd?: () => void;
2424
onVerify?: (id: string) => void;
25-
pendingVerifyId?: string;
26-
pendingPrimaryId?: string;
2725
isDisabled?: boolean;
2826
onSetPrimary?: (id: string) => void;
2927
onRemove?: (item: UserProfileContact) => void;
@@ -36,8 +34,6 @@ export function UserProfileContactListRowView({
3634
items,
3735
onAdd,
3836
onVerify,
39-
pendingVerifyId,
40-
pendingPrimaryId,
4137
isDisabled = false,
4238
onSetPrimary,
4339
onRemove,
@@ -96,13 +92,13 @@ export function UserProfileContactListRowView({
9692
actions.push({
9793
label: item.isDefault ? m.completeVerification : m[kind].verify,
9894
onClick: () => onVerify(item.id),
99-
status: pendingVerifyId === item.id ? 'pending' : 'idle',
95+
status: item.isVerifyPending ? 'pending' : 'idle',
10096
});
10197
} else if (item.isVerified && !item.isDefault && onSetPrimary) {
10298
actions.push({
10399
label: m.setPrimary,
104100
onClick: () => onSetPrimary(item.id),
105-
status: pendingPrimaryId === item.id ? 'pending' : 'idle',
101+
status: item.isPrimaryPending ? 'pending' : 'idle',
106102
});
107103
}
108104

‎packages/mosaic/src/features/user-profile/user-profile-contact.types.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@ export interface UserProfileContact {
55
isVerified: boolean;
66
}
77

8+
export interface UserProfileContactRow extends UserProfileContact {
9+
isVerifyPending: boolean;
10+
isPrimaryPending: boolean;
11+
}
12+
813
export type UserProfileEmail = UserProfileContact;
914

1015
export type UserProfilePhone = UserProfileContact;

‎packages/mosaic/src/features/user-profile/user-profile-email-section/user-profile-email-section.controller.ts‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,20 +36,18 @@ export function useUserProfileEmailSectionController({
3636
});
3737

3838
return {
39-
emails,
39+
emails: emails.map(email => ({
40+
...email,
41+
isVerifyPending: verification.pendingVerifyId === email.id,
42+
isPrimaryPending: actions.pendingKey === email.id,
43+
})),
4044
canAdd: Boolean(onCreateEmail),
4145
verification,
4246
error: actions.error,
4347
isDisabled: actions.isPending,
44-
pendingPrimaryId: actions.pendingKey,
4548
rowRef,
4649
registerTrigger: removalFocus.registerTrigger,
47-
remove: onRemoveEmail
48-
? {
49-
...remove,
50-
confirm: async email => (await actions.runExternal(() => remove.confirm(email))) ?? false,
51-
}
52-
: undefined,
50+
remove: onRemoveEmail ? actions.guard(remove) : undefined,
5351
finalFocus: removalFocus.finalFocus,
5452
verificationFinalFocus: () => (verification.verifyingId ? removalFocus.trigger(verification.verifyingId) : null),
5553
setPrimaryReverification,

‎packages/mosaic/src/features/user-profile/user-profile-email-section/user-profile-email-section.types.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,13 @@ import type { Ref } from 'react';
33
import type { ConfirmController } from '../../../blocks/confirm';
44
import type { DialogFocusTarget } from '../../../components/dialog';
55
import type { ReverificationController } from '../../reverification';
6-
import type { UserProfileEmail, UserProfileEmailVerifier } from '../user-profile-contact.types';
6+
import type { UserProfileContactRow, UserProfileEmail, UserProfileEmailVerifier } from '../user-profile-contact.types';
77
import type { UserProfileAddEmailController } from './user-profile-add-email.controller';
88

99
export interface UserProfileEmailSectionViewProps {
10-
emails: UserProfileEmail[];
10+
emails: UserProfileContactRow[];
1111
canAdd: boolean;
1212
isDisabled: boolean;
13-
pendingPrimaryId: string | undefined;
1413
verification: UserProfileAddEmailController;
1514
error: string | undefined;
1615
rowRef: Ref<HTMLDivElement>;

‎packages/mosaic/src/features/user-profile/user-profile-email-section/user-profile-email-section.view.tsx‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ export function UserProfileEmailSectionView({
1414
emails,
1515
canAdd,
1616
isDisabled,
17-
pendingPrimaryId,
1817
verification,
1918
error,
2019
rowRef,
@@ -63,8 +62,6 @@ export function UserProfileEmailSectionView({
6362
onSetPrimary={onSetPrimary}
6463
onVerify={onVerify}
6564
isDisabled={isDisabled}
66-
pendingPrimaryId={pendingPrimaryId}
67-
pendingVerifyId={verification.pendingVerifyId}
6865
>
6966
<Section.Error>{error}</Section.Error>
7067
</UserProfileContactListRowView>
@@ -79,7 +76,6 @@ export function UserProfileEmailSectionView({
7976
{remove ? (
8077
<Confirmation
8178
controller={remove}
82-
disabled={isDisabled}
8379
title={m.email.removeDialog.title}
8480
description={email =>
8581
fill(email.isVerified ? m.email.removeDialog.verifiedDescription : m.email.removeDialog.description, {

‎packages/mosaic/src/features/user-profile/user-profile-phone-section/user-profile-phone-section.controller.ts‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,21 +36,20 @@ export function useUserProfilePhoneSectionController({
3636
});
3737

3838
return {
39-
phones: phones.map(phone => ({ ...phone, value: stringToFormattedPhoneString(phone.value) })),
39+
phones: phones.map(phone => ({
40+
...phone,
41+
value: stringToFormattedPhoneString(phone.value),
42+
isVerifyPending: verification.pendingVerifyId === phone.id,
43+
isPrimaryPending: actions.pendingKey === phone.id,
44+
})),
4045
defaultPhoneCountry,
4146
canAdd: Boolean(onCreatePhone),
4247
verification,
4348
error: actions.error,
4449
isDisabled: actions.isPending,
45-
pendingPrimaryId: actions.pendingKey,
4650
rowRef,
4751
registerTrigger: removalFocus.registerTrigger,
48-
remove: onRemovePhone
49-
? {
50-
...remove,
51-
confirm: async phone => (await actions.runExternal(() => remove.confirm(phone))) ?? false,
52-
}
53-
: undefined,
52+
remove: onRemovePhone ? actions.guard(remove) : undefined,
5453
finalFocus: removalFocus.finalFocus,
5554
verificationFinalFocus: () => (verification.verifyingId ? removalFocus.trigger(verification.verifyingId) : null),
5655
setPrimaryReverification,

0 commit comments

Comments
 (0)