Skip to content
Open
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
2 changes: 2 additions & 0 deletions .changeset/mosaic-task-choose-organization-internal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
11 changes: 11 additions & 0 deletions packages/mosaic/src/__tests__/feature/fake-fapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
EnterpriseConnectionJSON,
OAuthConsentInfoJSON,
OAuthProvider,
OrganizationCreationDefaultsJSON,
OrganizationInvitationJSON,
OrganizationJSON,
OrganizationMembershipJSON,
Expand Down Expand Up @@ -85,6 +86,7 @@ export interface FakeFapiState {
mfa: FakeMfaState;
activeDevices?: ActiveDeviceRecord[];
deviceTrackingEnabled: boolean;
organizationCreationDefaults?: OrganizationCreationDefaultsJSON;
oauthConsent?: OAuthConsentInfoJSON;
oauthConsentRequests: URL[];
}
Expand Down Expand Up @@ -513,8 +515,14 @@ export function serveFapi(seed: FakeFapiSeed = {}): FakeFapiState {
return missing();
}
const organizationId = body.get('active_organization_id') || null;
const choosesOrganization = organizationId !== null && session.tasks?.[0]?.key === 'choose-organization';
const remainingTasks = choosesOrganization ? (session.tasks?.slice(1) ?? []) : session.tasks;
const touched = {
...session,
...(choosesOrganization && {
tasks: remainingTasks?.length ? remainingTasks : null,
status: remainingTasks?.length ? session.status : ('active' as const),
}),
last_active_organization_id: organizationId,
last_active_token: fapiToken({ sid: session.id, sub: session.user.id, org_id: organizationId }),
};
Expand Down Expand Up @@ -846,6 +854,9 @@ export function serveFapi(seed: FakeFapiSeed = {}): FakeFapiState {
}));
return envelope(organization, state.client);
}),
http.get(fapiUrl('/v1/me/organization_creation_defaults'), () =>
state.organizationCreationDefaults ? envelope(state.organizationCreationDefaults, state.client) : missing(),
),
http.get(fapiUrl('/v1/organizations/:organizationId'), ({ params }) => {
const membership = state.memberships.find(m => m.organization.id === params.organizationId);
return membership ? envelope(membership.organization, null) : missing();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ import { isSlug, toSlug } from './create-organization.utils';

export type CreateOrganizationReadyModel = Extract<CreateOrganizationModel, { status: 'ready' }>;

const initialValues: CreateOrganizationValues = { name: '', slug: '', logo: null };

export interface CreateOrganizationController {
step: CreateOrganizationStep;
form: UseFormResult<CreateOrganizationValues>;
Expand All @@ -26,9 +24,14 @@ export interface CreateOrganizationController {
onInvitationsSent: () => void;
}

export interface CreateOrganizationControllerOptions {
onRestart?: () => void;
initialValues?: Partial<Pick<CreateOrganizationValues, 'name' | 'slug'>>;
}

export function useCreateOrganizationController(
model: CreateOrganizationReadyModel,
{ onRestart }: { onRestart?: () => void } = {},
{ onRestart, initialValues }: CreateOrganizationControllerOptions = {},
): CreateOrganizationController {
const m = useMessages('createOrganization');
const [step, setStep] = useState<CreateOrganizationStep>({ step: 'create' });
Expand All @@ -39,7 +42,7 @@ export function useCreateOrganizationController(
};

const form = useForm<CreateOrganizationValues, CreatedOrganization>({
initialValues,
initialValues: { name: initialValues?.name ?? '', slug: initialValues?.slug ?? '', logo: null },
fields: {
slug: {
validate: slug =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import type { ReactElement, ReactNode } from 'react';
import { useState } from 'react';

import { useMembersPanelRolesModel } from '../organization-profile/organization-profile-members-panel/organization-profile-members-panel.model';
import type { CreateOrganizationReadyModel } from './create-organization.controller';
import type {
CreateOrganizationControllerOptions,
CreateOrganizationReadyModel,
} from './create-organization.controller';
import {
useCreateOrganizationController,
useCreateOrganizationInviteController,
Expand Down Expand Up @@ -88,7 +91,7 @@ function ConnectedCreateOrganization({

export function useCreateOrganizationFlow(
model: CreateOrganizationReadyModel,
options: { onRestart?: () => void } = {},
options: CreateOrganizationControllerOptions = {},
): CreateOrganizationStepsProps {
const controller = useCreateOrganizationController(model, options);
const organizationId = controller.step.step === 'create' ? null : controller.step.organizationId;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useMergeRefs } from '@floating-ui/react';
import { useState } from 'react';

import { AvatarUpload } from '../../blocks/avatar-upload';
import { Banner } from '../../components/banner';
import { Button, SubmitButton } from '../../components/button';
import { Card } from '../../components/card';
import { Field } from '../../components/field';
Expand All @@ -25,6 +26,7 @@ export interface CreateOrganizationStepsProps {
invite: InviteMembersForm;
onFinish: () => void;
onCancel?: () => void;
notice?: string;
}

export interface CreateOrganizationViewProps extends CreateOrganizationStepsProps {
Expand Down Expand Up @@ -62,7 +64,7 @@ export function CreateOrganizationSteps(props: CreateOrganizationStepsProps) {
);
}

function CreateStep({ form, slugEnabled, onNameChange, onCancel }: CreateOrganizationStepsProps) {
function CreateStep({ form, slugEnabled, onNameChange, onCancel, notice }: CreateOrganizationStepsProps) {
const m = useMessages('createOrganization');
const { ref: nameRef, onChange: _onChange, ...nameControl } = form.register('name');
const autoFocus = useFlowAutoFocus();
Expand All @@ -89,6 +91,11 @@ function CreateStep({ form, slugEnabled, onNameChange, onCancel }: CreateOrganiz
/>
}
>
{notice ? (
<Banner.Root color='warning'>
<Banner.Label>{notice}</Banner.Label>
</Banner.Root>
) : null}
Comment on lines +94 to +98

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hm, should this be using card.banner? that sits above the content?

<LogoField
name={form.values.name}
logo={form.values.logo}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,15 @@ describe('OrganizationList', () => {

await user.click(screen.getByRole('button', { name: 'Request to join' }));

expect(await screen.findByText('Pending approval')).toBeVisible();
const pending = await screen.findByRole('button', { name: 'Pending approval' });
await waitFor(() => expect(pending).not.toHaveAttribute('aria-busy'));
expect(pending).toHaveAttribute('aria-disabled', 'true');
expect(pending).toHaveFocus();
expect(screen.queryByRole('button', { name: 'Request to join' })).toBeNull();
expect(fapi.suggestions[0]?.status).toBe('accepted');

await user.click(pending);
expect(fapi.suggestions[0]?.status).toBe('accepted');
});

it('stands the other rows down while one action runs, and shows why it failed', async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useMemo, useState } from 'react';

import { useSpinDelay } from '../../hooks/use-spin-delay';
import type { ErrorDescription } from '../../localization';
Expand All @@ -7,68 +7,72 @@ import { setup } from '../../machine/setup';
import { useMachine } from '../../machine/use-machine';
import { toLocalizableError } from '../../utils/errors';
import type { OrganizationListModel } from './organization-list.model';
import type { OrganizationListData } from './organization-list.types';
import { organizationListBusyKeys } from './organization-list.types';

export type OrganizationListReadyModel = Extract<OrganizationListModel, { status: 'ready' }>;

interface OrganizationListMachineContext {
interface OrganizationListMachineContext<M> {
pendingKey: string | null;
frozenModel: OrganizationListReadyModel | null;
frozenModel: M | null;
run: () => Promise<unknown>;
error: ErrorDescription | undefined;
}

type OrganizationListMachineEvent =
| { type: 'RUN'; key: string; frozenModel: OrganizationListReadyModel; run: () => Promise<unknown> }
type OrganizationListMachineEvent<M> =
| { type: 'RUN'; key: string; frozenModel: M; run: () => Promise<unknown> }
| { type: 'DISMISS' };

const { createMachine, assign, fromPromise } = setup<OrganizationListMachineContext, OrganizationListMachineEvent>();

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

const organizationListMachine = createMachine({
id: 'organizationList',
initial: 'idle',
context: {
pendingKey: null,
frozenModel: null,
run: () => Promise.resolve(),
error: undefined,
},
states: {
idle: {
on: {
RUN: {
target: 'busy',
actions: assign((_, event) => ({
pendingKey: event.key,
frozenModel: event.frozenModel,
run: event.run,
error: undefined,
})),
},
DISMISS: { actions: assign(() => ({ error: undefined })) },
},
function createOrganizationListMachine<M>() {
const { createMachine, assign, fromPromise } = setup<
OrganizationListMachineContext<M>,
OrganizationListMachineEvent<M>
>();
const settled = { pendingKey: null, frozenModel: null };

return createMachine({
id: 'organizationList',
initial: 'idle',
context: {
pendingKey: null,
frozenModel: null,
run: () => Promise.resolve(),
error: undefined,
},
busy: {
invoke: fromPromise(context => context.run(), {
onDone: { target: 'idle', actions: assign(() => settled) },
onError: {
target: 'idle',
actions: assign((_, event) => ({ ...settled, error: toLocalizableError(event.error) })),
states: {
idle: {
on: {
RUN: {
target: 'busy',
actions: assign((_, event) => ({
pendingKey: event.key,
frozenModel: event.frozenModel,
run: event.run,
error: undefined,
})),
},
DISMISS: { actions: assign(() => ({ error: undefined })) },
},
}),
},
busy: {
invoke: fromPromise(context => context.run(), {
onDone: { target: 'idle', actions: assign(() => settled) },
onError: {
target: 'idle',
actions: assign((_, event) => ({ ...settled, error: toLocalizableError(event.error) })),
},
}),
},
},
},
});
});
}

type OrganizationListActions = 'onSelectOrganization' | 'onAcceptInvitation' | 'onAcceptSuggestion';

export type OrganizationListController =
export type OrganizationListController<M extends OrganizationListReadyModel = OrganizationListReadyModel> =
| { status: 'loading' }
| { status: 'hidden' }
| (OrganizationListData & {
| (Omit<M, 'status' | OrganizationListActions> & {
status: 'ready';
createOrganization?: OrganizationListReadyModel['createOrganization'];
pendingKey: string | null;
error: string | undefined;
onDismissError: () => void;
Expand All @@ -77,12 +81,16 @@ export type OrganizationListController =
onAcceptSuggestion: (suggestionId: string) => void;
});

export type OrganizationListReadyController = Extract<OrganizationListController, { status: 'ready' }>;
export type OrganizationListReadyController<M extends OrganizationListReadyModel = OrganizationListReadyModel> =
Extract<OrganizationListController<M>, { status: 'ready' }>;

export function useOrganizationListController(model: OrganizationListModel): OrganizationListController {
export function useOrganizationListController<M extends OrganizationListReadyModel = OrganizationListReadyModel>(
model: M | Exclude<OrganizationListModel, { status: 'ready' }>,
): OrganizationListController<M> {
const m = useMessages('organizationList');
const errorText = useErrorText();
const [{ context }, send] = useMachine(organizationListMachine);
const machine = useMemo(() => createOrganizationListMachine<M>(), []);
const [{ context }, send] = useMachine(machine);
const pendingKey = useSpinDelay(context.pendingKey, { delay: 0 });

const resolvedModel = context.frozenModel ?? model;
Expand Down Expand Up @@ -117,7 +125,10 @@ export interface OrganizationListScreenController {
}

export function useOrganizationListScreenController(
controller: OrganizationListReadyController,
controller: Pick<
OrganizationListReadyController,
'memberships' | 'invitations' | 'suggestions' | 'hidePersonal' | 'createOrganization' | 'onDismissError'
>,
): OrganizationListScreenController {
const hasOrganizations =
controller.memberships.length + controller.invitations.length + controller.suggestions.length > 0;
Expand Down
Loading
Loading