Walk Create Community through the Figma screens and restore a chosen logo after reload, so a guest can leave without saving until they reach the email step.

This commit is contained in:
adilallo committed 2026-11-05 16:14:04 -07:00
1 parent ca1f58a50c
commit 2348a9e94f
61 files changed
+1110 -421

No files matched your search

+161 -46
View File
@@ -87,7 +87,9 @@ import {
} from "./utils/customRuleConfirmFooterSteps";
import {
getDefaultFooterLabel,
isCommunityNameStepBlocked,
isCommunitySizeStepBlocked,
isCommunityStructureStepBlocked,
} from "./utils/createFlowFooterLabels";
import { useAuthModal } from "../../contexts/AuthModalContext";
import { useMessages, useTranslation } from "../../contexts/MessagesContext";
@@ -102,6 +104,10 @@ import {
CreateFlowDraftSaveBannerProvider,
useCreateFlowDraftSaveBanner,
} from "./context/CreateFlowDraftSaveBannerContext";
import {
CreateFlowContinueAttemptProvider,
useCreateFlowContinueAttempt,
} from "./context/CreateFlowContinueAttemptContext";
function CreateFlowSessionShell({ children }: { children: ReactNode }) {
const [sessionUser, setSessionUser] = useState<
@@ -128,6 +134,7 @@ function CreateFlowSessionShell({ children }: { children: ReactNode }) {
return (
<CreateFlowProvider enableLocalDraftMirroring={enableLocalDraftMirroring}>
<CreateFlowDraftSaveBannerProvider>
<CreateFlowContinueAttemptProvider>
<Suspense fallback={null}>
<CreateFlowLayoutContent
sessionUser={sessionUser}
@@ -136,6 +143,7 @@ function CreateFlowSessionShell({ children }: { children: ReactNode }) {
{children}
</CreateFlowLayoutContent>
</Suspense>
</CreateFlowContinueAttemptProvider>
</CreateFlowDraftSaveBannerProvider>
</CreateFlowProvider>
);
@@ -191,13 +199,14 @@ function CreateFlowLayoutContent({
editingPublishedRuleIdTrimmed.length > 0;
const { draftSaveBannerMessage, setDraftSaveBannerMessage } =
useCreateFlowDraftSaveBanner();
const { markAttempted, clearAttempted } = useCreateFlowContinueAttempt();
const [communitySaveMagicLinkSubmitting, setCommunitySaveMagicLinkSubmitting] =
useState(false);
const [communitySaveMagicLinkError, setCommunitySaveMagicLinkError] = useState<
string | null
>(null);
const [communitySaveMagicLinkSuccess, setCommunitySaveMagicLinkSuccess] =
useState(false);
const [saveSentEmail, setSaveSentEmail] = useState<string | null>(null);
const [isOffline, setIsOffline] = useState(false);
const [completedFlowBanner, setCompletedFlowBanner] = useState<{
key: string;
status: "positive" | "danger" | "warning";
@@ -208,24 +217,29 @@ function CreateFlowLayoutContent({
const [leaveConfirmOpen, setLeaveConfirmOpen] = useState(false);
const [completedHasPublishedRule, setCompletedHasPublishedRule] =
useState(false);
const leaveConfirmResolverRef = useRef<((proceed: boolean) => void) | null>(
null,
);
type LeaveConfirmChoice = "leave" | "save" | "cancel";
const leaveConfirmResolverRef = useRef<
((choice: LeaveConfirmChoice) => void) | null
>(null);
const confirmLeave = useCallback(
const requestLeaveChoice = useCallback(
() =>
new Promise<boolean>((resolve) => {
new Promise<LeaveConfirmChoice>((resolve) => {
leaveConfirmResolverRef.current = resolve;
setLeaveConfirmOpen(true);
}),
[],
);
const closeLeaveConfirm = useCallback((proceed: boolean) => {
const confirmLeave = useCallback(async () => {
return (await requestLeaveChoice()) === "leave";
}, [requestLeaveChoice]);
const closeLeaveConfirm = useCallback((choice: LeaveConfirmChoice) => {
setLeaveConfirmOpen(false);
const resolve = leaveConfirmResolverRef.current;
leaveConfirmResolverRef.current = null;
resolve?.(proceed);
resolve?.(choice);
}, []);
const {
@@ -359,6 +373,25 @@ function CreateFlowLayoutContent({
return;
}
if (!opts?.saveDraft) {
const choice = await requestLeaveChoice();
if (choice === "cancel") return;
if (choice === "save") {
if (sessionUser) {
await runAuthenticatedExit({ saveDraft: true });
return;
}
router.push(createFlowStepPath("community-save"));
return;
}
if (sessionUser) {
await runAuthenticatedExit({ saveDraft: false, skipConfirm: true });
return;
}
router.push(CREATE_ROUTES.root);
return;
}
if (sessionUser === null) {
const returnToTemplateReview =
templateReviewSlug != null
@@ -388,10 +421,25 @@ function CreateFlowLayoutContent({
}
}, [sessionResolved, sessionUser, currentStep, router]);
useEffect(() => {
clearAttempted();
}, [currentStep, clearAttempted]);
useEffect(() => {
const onOffline = () => setIsOffline(true);
const onOnline = () => setIsOffline(false);
setIsOffline(typeof navigator !== "undefined" && !navigator.onLine);
window.addEventListener("offline", onOffline);
window.addEventListener("online", onOnline);
return () => {
window.removeEventListener("offline", onOffline);
window.removeEventListener("online", onOnline);
};
}, []);
useEffect(() => {
if (currentStep !== "community-save") {
setCommunitySaveMagicLinkError(null);
setCommunitySaveMagicLinkSuccess(false);
setCommunitySaveMagicLinkSubmitting(false);
}
}, [currentStep]);
@@ -495,7 +543,6 @@ function CreateFlowLayoutContent({
formEl?: HTMLFormElement | null,
) => {
setCommunitySaveMagicLinkError(null);
setCommunitySaveMagicLinkSuccess(false);
const namedEmail = formEl?.elements.namedItem("email");
const emailField =
namedEmail instanceof HTMLInputElement
@@ -505,10 +552,6 @@ function CreateFlowLayoutContent({
: document.querySelector<HTMLInputElement>(
`input[name="email"][form="${CREATE_FLOW_COMMUNITY_SAVE_FORM_ID}"]`,
);
if (emailField != null && !emailField.checkValidity()) {
emailField.reportValidity();
return;
}
const raw =
emailField != null ? emailField.value : state.communitySaveEmail;
if (typeof raw !== "string" || !isValidCreateFlowSaveEmail(raw)) return;
@@ -544,13 +587,30 @@ function CreateFlowLayoutContent({
}
setTransferPendingFlag();
updateState({ communitySaveEmail: trimmed });
setCommunitySaveMagicLinkSuccess(true);
setSaveSentEmail(trimmed);
goToNextStep();
} catch {
setCommunitySaveMagicLinkError(tLogin("errors.network"));
} finally {
setCommunitySaveMagicLinkSubmitting(false);
}
}, [state, currentStep, tLogin, updateState]);
}, [state, currentStep, tLogin, updateState, goToNextStep]);
const handleResendSaveLink = useCallback(async () => {
if (!saveSentEmail) return;
setCommunitySaveMagicLinkError(null);
const nextPath = safeInternalPath("/create/review?syncDraft=1");
const draftPayload = buildCreateFlowDraftPayload(state, currentStep);
const result = await requestMagicLink(saveSentEmail, nextPath, {
...draftPayload,
communitySaveEmail: saveSentEmail,
});
if (result.ok === false) {
setCommunitySaveMagicLinkError(
result.error || tLogin("errors.generic"),
);
}
}, [saveSentEmail, state, currentStep, tLogin]);
const isCompletedStep = currentStep === "completed";
const isRightRailStep = currentStep === "decision-approaches";
@@ -589,6 +649,11 @@ function CreateFlowLayoutContent({
const proportionBarProgress = getProportionBarProgressForCreateFlowStep(
currentStep,
);
const hasCommunityLogo =
(typeof state.communityAvatarUrl === "string" &&
state.communityAvatarUrl.trim().length > 0) ||
(typeof state.communityAvatarFileName === "string" &&
state.communityAvatarFileName.trim().length > 0);
/**
* Custom Rule stage "confirm selection" steps: all five render the same
@@ -617,6 +682,9 @@ function CreateFlowLayoutContent({
title: string;
description?: string;
onClose: () => void;
actionLabel?: string;
onAction?: () => void;
type?: "banner" | "toast";
}> = [
draftSaveBannerMessage
? {
@@ -655,13 +723,28 @@ function CreateFlowLayoutContent({
onClose: () => setCommunitySaveMagicLinkError(null),
}
: null,
communitySaveMagicLinkSuccess
saveSentEmail
? {
key: "magicLinkSuccess",
status: "positive" as const,
title: communitySaveMessages.magicLinkSuccessTitle,
description: communitySaveMessages.magicLinkSuccessDescription,
onClose: () => setCommunitySaveMagicLinkSuccess(false),
type: "toast" as const,
title: communitySaveMessages.sentToastTitle,
description: communitySaveMessages.sentToastDescription.replace(
"{email}",
saveSentEmail,
),
actionLabel: communitySaveMessages.sentToastAction,
onAction: () => void handleResendSaveLink(),
onClose: () => setSaveSentEmail(null),
}
: null,
isOffline
? {
key: "offline",
status: "warning" as const,
title: messages.create.topNav.offlineTitle,
description: messages.create.topNav.offlineDescription,
onClose: () => setIsOffline(false),
}
: null,
completedFlowBanner
@@ -688,11 +771,13 @@ function CreateFlowLayoutContent({
className="pointer-events-auto mx-auto w-full max-w-[960px]"
>
<Alert
type="banner"
type={b.type ?? "banner"}
status={b.status}
title={b.title}
description={b.description}
onClose={b.onClose}
actionLabel={b.actionLabel}
onAction={b.onAction}
className="w-full"
/>
</div>
@@ -725,22 +810,23 @@ function CreateFlowLayoutContent({
/>
<Create
isOpen={leaveConfirmOpen}
onClose={() => closeLeaveConfirm(false)}
onClose={() => closeLeaveConfirm("cancel")}
title={messages.create.topNav.leaveConfirmTitle}
description={messages.create.topNav.leaveConfirmDescription}
showBackButton={false}
showNextButton
nextButtonText={messages.create.topNav.leaveConfirmProceed}
onNext={() => closeLeaveConfirm(true)}
nextButtonText={messages.create.topNav.leaveConfirmSaveProgress}
onNext={() => closeLeaveConfirm("save")}
footerContent={
<div className={MODAL_FOOTER_START_SLOT_CLASS}>
<Button
buttonType="ghost"
buttonType="outline"
danger
palette="default"
size="xsmall"
onClick={() => closeLeaveConfirm(false)}
onClick={() => closeLeaveConfirm("leave")}
>
{messages.create.topNav.leaveConfirmCancel}
{messages.create.topNav.leaveConfirmProceed}
</Button>
</div>
}
@@ -801,6 +887,7 @@ function CreateFlowLayoutContent({
className="hidden"
onSubmit={(e) => {
e.preventDefault();
markAttempted();
void handleCommunitySaveMagicLinkSubmit(e.currentTarget);
}}
/>
@@ -855,13 +942,13 @@ function CreateFlowLayoutContent({
buttonType="filled"
palette="default"
size="xsmall"
disabled={
isPublishing ||
typeof state.title !== "string" ||
state.title.trim().length === 0
}
disabled={isPublishing}
className={CREATE_FLOW_FOOTER_BUTTON_CLASS}
onClick={() => {
markAttempted();
if (isCommunityNameStepBlocked(currentStep, state.title)) {
return;
}
goToNextStep();
}}
>
@@ -879,7 +966,7 @@ function CreateFlowLayoutContent({
goToNextStep();
}}
>
{footer.saveLater}
{footer.skipForNow}
</Button>
<Button
type="submit"
@@ -888,10 +975,7 @@ function CreateFlowLayoutContent({
palette="default"
size="xsmall"
disabled={
isPublishing ||
communitySaveMagicLinkSubmitting ||
communitySaveMagicLinkSuccess ||
!isValidCreateFlowSaveEmail(state.communitySaveEmail)
isPublishing || communitySaveMagicLinkSubmitting
}
className={CREATE_FLOW_FOOTER_BUTTON_CLASS}
>
@@ -900,6 +984,19 @@ function CreateFlowLayoutContent({
: footer.submitEmail}
</Button>
</div>
) : currentStep === "community-upload" && nextStep ? (
<Button
buttonType={hasCommunityLogo ? "filled" : "outline"}
palette="default"
size="xsmall"
disabled={isPublishing}
className={CREATE_FLOW_FOOTER_BUTTON_CLASS}
onClick={() => {
goToNextStep();
}}
>
{hasCommunityLogo ? footer.next : footer.skip}
</Button>
) : currentStep === "review" && nextStep ? (
<div className="flex flex-shrink-0 items-center gap-3 md:gap-4">
<Button
@@ -988,20 +1085,38 @@ function CreateFlowLayoutContent({
palette="default"
size="xsmall"
disabled={
isPublishing ||
(isFinalReviewLike && !sessionResolved) ||
isCommunitySizeStepBlocked(
currentStep,
state.selectedCommunitySizeIds,
)
isPublishing || (isFinalReviewLike && !sessionResolved)
}
className={CREATE_FLOW_FOOTER_BUTTON_CLASS}
onClick={() => {
if (isFinalReviewLike) {
void handleFinalize();
} else {
goToNextStep();
return;
}
markAttempted();
if (
isCommunityStructureStepBlocked(
currentStep,
state.selectedOrganizationTypeIds,
state.selectedMaturityIds,
) ||
isCommunitySizeStepBlocked(
currentStep,
state.selectedCommunitySizeIds,
)
) {
return;
}
if (reviewReturnTarget) {
router.push(
createFlowStepPathAfterStrippingReviewReturn(
reviewReturnTarget,
searchParams,
),
);
return;
}
goToNextStep();
}}
>
{isFinalReviewLike
@@ -0,0 +1,50 @@
"use client";
import {
createContext,
useCallback,
useContext,
useMemo,
useState,
type ReactNode,
} from "react";
type CreateFlowContinueAttemptContextValue = {
attempted: boolean;
markAttempted: () => void;
clearAttempted: () => void;
};
const CreateFlowContinueAttemptContext =
createContext<CreateFlowContinueAttemptContextValue | null>(null);
export function CreateFlowContinueAttemptProvider({
children,
}: {
children: ReactNode;
}) {
const [attempted, setAttempted] = useState(false);
const markAttempted = useCallback(() => setAttempted(true), []);
const clearAttempted = useCallback(() => setAttempted(false), []);
const value = useMemo(
() => ({ attempted, markAttempted, clearAttempted }),
[attempted, markAttempted, clearAttempted],
);
return (
<CreateFlowContinueAttemptContext.Provider value={value}>
{children}
</CreateFlowContinueAttemptContext.Provider>
);
}
export function useCreateFlowContinueAttempt(): CreateFlowContinueAttemptContextValue {
const value = useContext(CreateFlowContinueAttemptContext);
if (!value) {
return {
attempted: false,
markAttempted: () => {},
clearAttempted: () => {},
};
}
return value;
}
+3 -3
View File
@@ -33,14 +33,14 @@ export function useCreateFlowExit({
setDraftSaveBannerMessage?: (_message: string | null) => void;
/** When exit would discard unsaved work, return true to proceed. Defaults to denying leave. */
confirmLeave?: () => Promise<boolean>;
}): (_options?: { saveDraft?: boolean }) => Promise<void> {
}): (_options?: { saveDraft?: boolean; skipConfirm?: boolean }) => Promise<void> {
return useCallback(
async (options?: { saveDraft?: boolean }) => {
async (options?: { saveDraft?: boolean; skipConfirm?: boolean }) => {
if (!user) return;
const saveDraft = options?.saveDraft ?? false;
if (!saveDraft) {
if (!saveDraft && !options?.skipConfirm) {
const confirmFn = confirmLeave ?? (async () => false);
const confirmed = await confirmFn();
if (!confirmed) return;
@@ -116,6 +116,7 @@ export function renderCreateFlowScreen(screenId: CreateFlowStep): ReactNode {
stateField="title"
maxLength={48}
required
autoFocus
/>
);
case "community-structure":
@@ -128,6 +129,8 @@ export function renderCreateFlowScreen(screenId: CreateFlowStep): ReactNode {
maxLength={200}
mainAlign="center"
multiline
locationField
autoFocus
/>
);
case "community-size":
@@ -144,6 +147,7 @@ export function renderCreateFlowScreen(screenId: CreateFlowStep): ReactNode {
inputType="email"
showCharacterCount={false}
headerJustification="center"
autoFocus
/>
);
case "review":
@@ -16,18 +16,9 @@ export function InformationalScreen() {
const copy = useMessages().create.community.informational;
const items = [
{
title: copy.steps["0"].title,
description: copy.steps["0"].description,
},
{
title: copy.steps["1"].title,
description: copy.steps["1"].description,
},
{
title: copy.steps["2"].title,
description: copy.steps["2"].description,
},
{ title: copy.steps["0"].title },
{ title: copy.steps["1"].title },
{ title: copy.steps["2"].title },
];
return (
@@ -4,7 +4,8 @@ import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import Rule from "../../../../components/cards/Rule";
import Button from "../../../../components/buttons/Button";
import { useTranslation } from "../../../../contexts/MessagesContext";
import InlineTextButton from "../../../../components/buttons/InlineTextButton";
import { useMessages, useTranslation } from "../../../../contexts/MessagesContext";
import { CreateFlowHeaderLockup } from "../../components/CreateFlowHeaderLockup";
import { useCreateFlow } from "../../context/CreateFlowContext";
import { useCreateFlowLgUp } from "../../hooks/useCreateFlowLgUp";
@@ -19,11 +20,67 @@ import {
} from "../../../../../lib/assetUtils";
import { methodSectionsPinsForHydratedSelections } from "../../../../../lib/create/publishedDocumentToCreateFlowState";
import { CREATE_ROUTES, createFlowStepPath } from "../../utils/createFlowPaths";
import { CREATE_FLOW_REVIEW_RETURN_QUERY_KEY } from "../../utils/flowSteps";
import type { CreateFlowStep } from "../../types";
function firstId(ids: readonly string[] | undefined): string | undefined {
return ids?.find((id) => id.length > 0);
}
function chipLabel(
id: string | undefined,
rows: readonly { id: string; label: string }[] | undefined,
snapshots: readonly { id: string; label: string }[] | undefined,
): string | undefined {
if (!id) return undefined;
const fromSnap = snapshots?.find((row) => row.id === id)?.label.trim();
if (fromSnap) return fromSnap;
return rows?.find((row) => row.id === id)?.label;
}
function reviewSizeValue(
id: string | undefined,
sizes: readonly { id: string; label: string }[],
peopleTemplate: string,
): string | undefined {
if (!id) return undefined;
const row = sizes.find((item) => item.id === id);
if (!row) return undefined;
if (id === "oneMember") return row.label;
return peopleTemplate.replace("{label}", row.label);
}
function CommunityReviewAnswerRow({
label,
value,
editLabel,
onEdit,
}: {
label: string;
value: string;
editLabel: string;
onEdit: () => void;
}) {
return (
<div className="flex w-full items-start justify-between gap-[var(--space-400)] py-[var(--space-300)]">
<div className="flex min-w-0 flex-1 flex-col gap-[var(--space-100)]">
<p className="text-small-label text-[color:var(--color-content-default-secondary)]">
{label}
</p>
<p className="text-medium-paragraph text-[color:var(--color-content-default-primary)]">
{value}
</p>
</div>
<InlineTextButton onClick={onEdit}>{editLabel}</InlineTextButton>
</div>
);
}
/** Create Community review — Figma `19706:12135` (`/create/review`; two columns from `lg:`; column caps in `createFlowLayoutTokens`). */
export function CommunityReviewScreen() {
const router = useRouter();
const lgUp = useCreateFlowLgUp();
const messages = useMessages();
const t = useTranslation("create.community.review");
const { state, updateState } = useCreateFlow();
/**
@@ -97,6 +154,32 @@ export function CommunityReviewScreen() {
? state.communityAvatarUrl.trim()
: null;
const structure = messages.create.community.communityStructure;
const sizes = messages.create.community.communitySize.communitySizes;
const kindValue = chipLabel(
firstId(state.selectedOrganizationTypeIds),
structure.organizationTypes,
state.communityStructureChipSnapshots?.organizationTypes,
);
const sizeValue = reviewSizeValue(
firstId(state.selectedCommunitySizeIds),
sizes,
t("rows.sizePeople"),
);
const maturityValue = chipLabel(
firstId(state.selectedMaturityIds),
structure.maturityOptions,
state.communityStructureChipSnapshots?.maturity,
);
const goEdit = (step: CreateFlowStep) => {
router.push(
createFlowStepPath(step, {
[CREATE_FLOW_REVIEW_RETURN_QUERY_KEY]: "review",
}),
);
};
if (state.pendingTemplateAction || !reviewReady) {
return null;
}
@@ -143,7 +226,7 @@ export function CommunityReviewScreen() {
description={t("header.description")}
/>
</div>
<div className={CREATE_FLOW_MD_UP_GRID_CELL_CLASS}>
<div className={`flex flex-col ${CREATE_FLOW_MD_UP_GRID_CELL_CLASS}`}>
<Rule
title={cardTitle}
description={cardDescription}
@@ -156,6 +239,32 @@ export function CommunityReviewScreen() {
logoAlt={cardTitle}
className="rounded-[24px]"
/>
<div className="mt-[var(--space-600)] flex w-full flex-col divide-y divide-[var(--color-border-default-secondary)]">
{kindValue ? (
<CommunityReviewAnswerRow
label={t("rows.kind")}
value={kindValue}
editLabel={t("rows.edit")}
onEdit={() => goEdit("community-structure")}
/>
) : null}
{sizeValue ? (
<CommunityReviewAnswerRow
label={t("rows.size")}
value={sizeValue}
editLabel={t("rows.edit")}
onEdit={() => goEdit("community-size")}
/>
) : null}
{maturityValue ? (
<CommunityReviewAnswerRow
label={t("rows.maturity")}
value={maturityValue}
editLabel={t("rows.edit")}
onEdit={() => goEdit("community-structure")}
/>
) : null}
</div>
</div>
</div>
</CreateFlowStepShell>
@@ -5,6 +5,7 @@ import MultiSelect from "../../../../components/controls/MultiSelect";
import type { ChipOption } from "../../../../components/controls/MultiSelect/MultiSelect.types";
import { useMessages } from "../../../../contexts/MessagesContext";
import { useCreateFlow } from "../../context/CreateFlowContext";
import { useCreateFlowContinueAttempt } from "../../context/CreateFlowContinueAttemptContext";
import { CreateFlowHeaderLockup } from "../../components/CreateFlowHeaderLockup";
import { CreateFlowTwoColumnSelectShell } from "../../components/CreateFlowTwoColumnSelectShell";
@@ -48,6 +49,7 @@ export function CommunitySizeSelectScreen() {
const m = useMessages();
const cs = m.create.community.communitySize;
const { markCreateFlowInteraction, updateState, state } = useCreateFlow();
const { attempted } = useCreateFlowContinueAttempt();
const [communitySizeOptions, setCommunitySizeOptions] = useState<
ChipOption[]
@@ -87,6 +89,9 @@ export function CommunitySizeSelectScreen() {
persistSelection(withSoleSelection(communitySizeOptions, nextId));
};
const showSizeError =
attempted && soleSizeId(state.selectedCommunitySizeIds) == null;
const multiSelectBlock = (
<MultiSelect
formHeader={false}
@@ -94,6 +99,7 @@ export function CommunitySizeSelectScreen() {
options={communitySizeOptions}
onChipClick={handleCommunitySizeClick}
addButton={false}
errorMessage={showSizeError ? cs.pickOneError : undefined}
/>
);
@@ -11,6 +11,7 @@ import MultiSelect from "../../../../components/controls/MultiSelect";
import type { ChipOption } from "../../../../components/controls/MultiSelect/MultiSelect.types";
import { useMessages } from "../../../../contexts/MessagesContext";
import { useCreateFlow } from "../../context/CreateFlowContext";
import { useCreateFlowContinueAttempt } from "../../context/CreateFlowContinueAttemptContext";
import type { CommunityStructureChipSnapshotRow } from "../../types";
import { CreateFlowHeaderLockup } from "../../components/CreateFlowHeaderLockup";
import { CreateFlowTwoColumnSelectShell } from "../../components/CreateFlowTwoColumnSelectShell";
@@ -73,10 +74,29 @@ function applySavedSelection(
);
}
function withSoleSelection(
options: ChipOption[],
selectedId: string | null,
): ChipOption[] {
return options.map((opt) =>
opt.state === "custom"
? opt
: {
...opt,
state:
opt.id === selectedId
? ("selected" as const)
: ("unselected" as const),
},
);
}
function selectedIdsFromOptions(options: ChipOption[]): string[] {
return options
.filter((o) => o.state === "selected")
.map((o) => o.id);
return options.filter((o) => o.state === "selected").map((o) => o.id);
}
function firstSelectedId(options: ChipOption[]): string | null {
return selectedIdsFromOptions(options)[0] ?? null;
}
function chipOptionsToSnapshotRows(
@@ -103,22 +123,46 @@ function snapshotRowsToChipOptions(
}));
}
/** Create Community step 3 — Figma `20094:18244` (responsive grid + column caps via `createFlowLayoutTokens`). */
function organizationIdsForPersist(
mainId: string | null,
otherIds: readonly string[],
): string[] {
if (!mainId) return [];
return [mainId, ...otherIds.filter((id) => id !== mainId)];
}
/** Create Community type step — Figma `25224:105767`. */
export function CommunityStructureSelectScreen() {
const m = useMessages();
const cs = m.create.community.communityStructure;
const { markCreateFlowInteraction, updateState, state } = useCreateFlow();
const { attempted } = useCreateFlowContinueAttempt();
const [organizationTypeOptions, setOrganizationTypeOptions] = useState<
ChipOption[]
>(() => {
const savedKindIds = state.selectedOrganizationTypeIds ?? [];
const savedMainIndex = savedKindIds.findIndex((id) => id.length > 0);
const savedMainId =
savedMainIndex >= 0 ? savedKindIds[savedMainIndex]! : null;
const savedOtherIds =
savedMainIndex >= 0 ? savedKindIds.slice(savedMainIndex + 1) : [];
const [mainKindOptions, setMainKindOptions] = useState<ChipOption[]>(() => {
const fromSnap = snapshotRowsToChipOptions(
state.communityStructureChipSnapshots?.organizationTypes,
);
return withSoleSelection(
fromSnap ?? chipRowsFromLabels(cs.organizationTypes),
savedMainId,
);
});
const [otherKindOptions, setOtherKindOptions] = useState<ChipOption[]>(() => {
const fromSnap = snapshotRowsToChipOptions(
state.communityStructureChipSnapshots?.otherOrganizationTypes,
);
if (fromSnap) return fromSnap;
return applySavedSelection(
chipRowsFromLabels(cs.organizationTypes),
state.selectedOrganizationTypeIds,
savedOtherIds,
);
});
@@ -137,29 +181,48 @@ export function CommunityStructureSelectScreen() {
const fromSnap = snapshotRowsToChipOptions(
state.communityStructureChipSnapshots?.maturity,
);
if (fromSnap) return fromSnap;
return applySavedSelection(
chipRowsFromLabels(cs.maturityOptions),
state.selectedMaturityIds,
);
const base = fromSnap ?? chipRowsFromLabels(cs.maturityOptions);
const maturityId =
(state.selectedMaturityIds ?? []).find((id) => id.length > 0) ?? null;
return withSoleSelection(base, maturityId);
});
useEffect(() => {
const fromSnap = snapshotRowsToChipOptions(
state.communityStructureChipSnapshots?.organizationTypes,
);
if (fromSnap) {
setOrganizationTypeOptions(fromSnap);
return;
}
setOrganizationTypeOptions((prev) =>
applySavedSelection(prev, state.selectedOrganizationTypeIds),
const mainId =
(state.selectedOrganizationTypeIds ?? []).find((id) => id.length > 0) ??
null;
setMainKindOptions(
withSoleSelection(
fromSnap ?? chipRowsFromLabels(cs.organizationTypes),
mainId,
),
);
}, [
cs.organizationTypes,
state.communityStructureChipSnapshots?.organizationTypes,
state.selectedOrganizationTypeIds,
]);
useEffect(() => {
const fromSnap = snapshotRowsToChipOptions(
state.communityStructureChipSnapshots?.otherOrganizationTypes,
);
const ids = state.selectedOrganizationTypeIds ?? [];
const mainId = ids.find((id) => id.length > 0);
const otherIds = mainId ? ids.slice(ids.indexOf(mainId) + 1) : [];
if (fromSnap) {
setOtherKindOptions(fromSnap);
return;
}
setOtherKindOptions((prev) => applySavedSelection(prev, otherIds));
}, [
state.communityStructureChipSnapshots?.otherOrganizationTypes,
state.selectedOrganizationTypeIds,
]);
useEffect(() => {
const fromSnap = snapshotRowsToChipOptions(
state.communityStructureChipSnapshots?.scale,
@@ -178,53 +241,50 @@ export function CommunityStructureSelectScreen() {
const fromSnap = snapshotRowsToChipOptions(
state.communityStructureChipSnapshots?.maturity,
);
const maturityId =
(state.selectedMaturityIds ?? []).find((id) => id.length > 0) ?? null;
if (fromSnap) {
setMaturityOptions(fromSnap);
setMaturityOptions(withSoleSelection(fromSnap, maturityId));
return;
}
setMaturityOptions((prev) =>
applySavedSelection(prev, state.selectedMaturityIds),
);
setMaturityOptions((prev) => withSoleSelection(prev, maturityId));
}, [
state.communityStructureChipSnapshots?.maturity,
state.selectedMaturityIds,
]);
const organizationCustomHandlers = useMemo(
const mainKindCustomHandlers = useMemo(
() =>
createListCustomHandlers(
setOrganizationTypeOptions,
setMainKindOptions,
"unselected",
markCreateFlowInteraction,
),
[markCreateFlowInteraction],
);
const scaleCustomHandlers = useMemo(
const otherKindCustomHandlers = useMemo(
() =>
createListCustomHandlers(
setScaleOptions,
"unselected",
markCreateFlowInteraction,
),
[markCreateFlowInteraction],
);
const maturityCustomHandlers = useMemo(
() =>
createListCustomHandlers(
setMaturityOptions,
setOtherKindOptions,
"unselected",
markCreateFlowInteraction,
),
[markCreateFlowInteraction],
);
const persistOrg = (next: ChipOption[]) => {
const persistKinds = (main: ChipOption[], others: ChipOption[]) => {
markCreateFlowInteraction();
setOrganizationTypeOptions(next);
setMainKindOptions(main);
setOtherKindOptions(others);
const mainId = firstSelectedId(main);
updateState({
selectedOrganizationTypeIds: selectedIdsFromOptions(next),
selectedOrganizationTypeIds: organizationIdsForPersist(
mainId,
selectedIdsFromOptions(others),
),
communityStructureChipSnapshots: {
organizationTypes: chipOptionsToSnapshotRows(next),
organizationTypes: chipOptionsToSnapshotRows(main),
otherOrganizationTypes: chipOptionsToSnapshotRows(others),
},
});
};
@@ -251,9 +311,16 @@ export function CommunityStructureSelectScreen() {
});
};
const handleOrganizationTypeClick = (chipId: string) => {
persistOrg(
organizationTypeOptions.map((opt) =>
const handleMainKindClick = (chipId: string) => {
const current = firstSelectedId(mainKindOptions);
const nextId = current === chipId ? null : chipId;
persistKinds(withSoleSelection(mainKindOptions, nextId), otherKindOptions);
};
const handleOtherKindClick = (chipId: string) => {
persistKinds(
mainKindOptions,
otherKindOptions.map((opt) =>
opt.id === chipId
? {
...opt,
@@ -284,49 +351,49 @@ export function CommunityStructureSelectScreen() {
};
const handleMaturityClick = (chipId: string) => {
persistMaturity(
maturityOptions.map((opt) =>
opt.id === chipId
? {
...opt,
state:
opt.state === "selected"
? ("unselected" as const)
: ("selected" as const),
}
: opt,
),
);
const current = firstSelectedId(maturityOptions);
const nextId = current === chipId ? null : chipId;
persistMaturity(withSoleSelection(maturityOptions, nextId));
};
const showMainError = attempted && firstSelectedId(mainKindOptions) == null;
const showMaturityError =
attempted && firstSelectedId(maturityOptions) == null;
const multiSelectBlock = (
<>
<MultiSelect
label={cs.organizationMultiSelect.label}
label={cs.mainKindMultiSelect.label}
helperText={cs.mainKindMultiSelect.helperText}
size="s"
options={organizationTypeOptions}
onChipClick={handleOrganizationTypeClick}
{...organizationCustomHandlers}
options={mainKindOptions}
onChipClick={handleMainKindClick}
{...mainKindCustomHandlers}
addButton
errorMessage={showMainError ? cs.pickOneError : undefined}
/>
<MultiSelect
label={cs.otherKindMultiSelect.label}
size="s"
options={otherKindOptions}
onChipClick={handleOtherKindClick}
{...otherKindCustomHandlers}
addButton
addButtonText={cs.organizationMultiSelect.addButtonText}
/>
<MultiSelect
label={cs.scaleMultiSelect.label}
size="s"
options={scaleOptions}
onChipClick={handleScaleClick}
{...scaleCustomHandlers}
addButton
addButtonText={cs.scaleMultiSelect.addButtonText}
addButton={false}
/>
<MultiSelect
label={cs.maturityMultiSelect.label}
size="s"
options={maturityOptions}
onChipClick={handleMaturityClick}
{...maturityCustomHandlers}
addButton
addButtonText={cs.maturityMultiSelect.addButtonText}
addButton={false}
errorMessage={showMaturityError ? cs.pickOneError : undefined}
/>
</>
);
@@ -6,6 +6,7 @@ import TextArea from "../../../../components/controls/TextArea";
import type { HeaderLockupJustificationValue } from "../../../../components/type/HeaderLockup/HeaderLockup.types";
import { useTranslation } from "../../../../contexts/MessagesContext";
import { useCreateFlow } from "../../context/CreateFlowContext";
import { useCreateFlowContinueAttempt } from "../../context/CreateFlowContinueAttemptContext";
import { useCreateFlowMdUp } from "../../hooks/useCreateFlowMdUp";
import { CreateFlowHeaderLockup } from "../../components/CreateFlowHeaderLockup";
import {
@@ -14,6 +15,7 @@ import {
} from "../../components/CreateFlowStepShell";
import { CREATE_FLOW_MD_UP_COLUMN_MAX_CLASS } from "../../components/createFlowLayoutTokens";
import { CREATE_FLOW_COMMUNITY_SAVE_FORM_ID } from "../../utils/createFlowPaths";
import { isValidCreateFlowSaveEmail } from "../../../../../lib/create/isValidCreateFlowSaveEmail";
import type { CreateFlowTextStateField } from "../../types";
type Props = {
@@ -31,6 +33,9 @@ type Props = {
headerJustification?: HeaderLockupJustificationValue;
/** Top spacing under top chrome (`CreateFlowStepShell` / `CreateFlowContentTopBelowMd`). */
contentTopBelowMd?: CreateFlowContentTopBelowMd;
autoFocus?: boolean;
/** Optional city/region field under the description. */
locationField?: boolean;
};
/**
@@ -47,35 +52,38 @@ export function CreateFlowTextFieldScreen({
showCharacterCount = true,
headerJustification = "left",
contentTopBelowMd = "space-1400",
autoFocus = false,
locationField = false,
}: Props) {
const { markCreateFlowInteraction, updateState, state } = useCreateFlow();
const { attempted } = useCreateFlowContinueAttempt();
const mdUp = useCreateFlowMdUp();
const t = useTranslation(messageNamespace);
const readFromState = (): string => {
const raw = state[stateField];
const readFromState = (field: CreateFlowTextStateField): string => {
const raw = state[field];
return typeof raw === "string" ? raw : "";
};
const [value, setValue] = useState(() => readFromState());
const [value, setValue] = useState(() => readFromState(stateField));
const [locationValue, setLocationValue] = useState(() =>
readFromState("communityLocation"),
);
useEffect(() => {
const incoming = readFromState();
const incoming = readFromState(stateField);
if (incoming.length === 0) return;
// eslint-disable-next-line react-hooks/set-state-in-effect -- sync when context hydrates from server/local
setValue((prev) => (prev === "" ? incoming : prev));
}, [state, stateField]);
const characterCount = value.length;
const hint =
showCharacterCount === false
? false
: t("characterCountTemplate")
.replace("{current}", String(characterCount))
.replace("{max}", String(maxLength));
const mainItems =
mainAlign === "center" ? "items-center" : "items-start";
useEffect(() => {
if (!locationField) return;
const incoming = readFromState("communityLocation");
if (incoming.length === 0) return;
// eslint-disable-next-line react-hooks/set-state-in-effect -- sync when context hydrates from server/local
setLocationValue((prev) => (prev === "" ? incoming : prev));
}, [locationField, state]);
const isEmail = inputType === "email";
const persistValue = (next: string) => {
@@ -83,6 +91,42 @@ export function CreateFlowTextFieldScreen({
markCreateFlowInteraction();
updateState({ [stateField]: next } as Record<string, string>);
};
const persistLocation = (next: string) => {
setLocationValue(next);
markCreateFlowInteraction();
updateState({ communityLocation: next });
};
const nameError =
required &&
!isEmail &&
!multiline &&
attempted &&
value.trim().length === 0;
const emailError =
isEmail &&
attempted &&
!isValidCreateFlowSaveEmail(value);
const showFieldError = nameError || emailError;
const errorCopy = nameError
? t("errorMessage")
: emailError
? t("errorMessage")
: "";
const characterCount = value.length;
const hint = showFieldError
? errorCopy
: isEmail
? t("skipHint")
: showCharacterCount === false
? false
: t("characterCountTemplate")
.replace("{current}", String(characterCount))
.replace("{max}", String(maxLength));
const mainItems =
mainAlign === "center" ? "items-center" : "items-start";
const fieldLabel = t("inputLabel");
@@ -101,7 +145,7 @@ export function CreateFlowTextFieldScreen({
justification={headerJustification}
/>
</div>
<div className="w-full">
<div className="flex w-full flex-col gap-[var(--space-800)]">
{multiline ? (
<TextArea
className="!transition-none"
@@ -119,6 +163,7 @@ export function CreateFlowTextFieldScreen({
textHint={hint}
maxLength={maxLength}
required={required}
autoFocus={autoFocus}
rows={4}
/>
) : (
@@ -149,13 +194,33 @@ export function CreateFlowTextFieldScreen({
formHeader={false}
showHelpIcon={false}
textHint={hint}
error={showFieldError}
maxLength={maxLength}
required={required || isEmail}
autoComplete={isEmail ? "email" : undefined}
inputMode={isEmail ? "email" : undefined}
form={isEmail ? CREATE_FLOW_COMMUNITY_SAVE_FORM_ID : undefined}
autoFocus={autoFocus}
/>
)}
{locationField ? (
<TextInput
className="!transition-none"
type="text"
label={t("locationLabel")}
placeholder={t("locationPlaceholder")}
value={locationValue}
onChange={(e) => persistLocation(e.target.value)}
onBlur={() => {
const trimmed = locationValue.trim();
if (trimmed !== locationValue) persistLocation(trimmed);
}}
inputSize={mdUp ? "medium" : "small"}
formHeader
showHelpIcon={false}
textHint={t("locationHint")}
/>
) : null}
</div>
</div>
</CreateFlowStepShell>
@@ -14,7 +14,6 @@ import { CreateFlowHeaderLockup } from "../../components/CreateFlowHeaderLockup"
import { CreateFlowStepShell } from "../../components/CreateFlowStepShell";
import { CREATE_FLOW_MD_UP_COLUMN_MAX_CLASS } from "../../components/createFlowLayoutTokens";
import { fetchAuthSession } from "../../../../../lib/create/api";
import { ASSETS, getAssetPath } from "../../../../../lib/assetUtils";
import {
createFlowUploadFailureMessageKey,
uploadCreateFlowFile,
@@ -34,7 +33,7 @@ function hasCommunityAvatarUrl(url: string | undefined): boolean {
return typeof url === "string" && url.trim().length > 0;
}
/** Create Community — Figma Flow — Upload `20094:41524`. */
/** Create Community — Figma Flow — Upload. */
export function CommunityUploadScreen() {
const m = useMessages();
const u = m.create.community.communityUpload;
@@ -44,6 +43,7 @@ export function CommunityUploadScreen() {
const fileInputRef = useRef<HTMLInputElement | null>(null);
const [signedIn, setSignedIn] = useState<boolean | null>(null);
const [localPreviewUrl, setLocalPreviewUrl] = useState<string | null>(null);
const [localFileName, setLocalFileName] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
@@ -104,6 +104,10 @@ export function CommunityUploadScreen() {
if (prev) URL.revokeObjectURL(prev);
return objectUrl;
});
setLocalFileName(file.name);
if (!state.communityAvatarFileName) {
updateState({ communityAvatarFileName: file.name });
}
} catch {
// Missing IndexedDB / quota: leave the picker empty.
}
@@ -111,11 +115,15 @@ export function CommunityUploadScreen() {
return () => {
cancelled = true;
};
}, []);
}, [state.communityAvatarFileName, updateState]);
const resolveUploadError = useCallback(
(err: unknown) => tUpload(createFlowUploadFailureMessageKey(err)),
[tUpload],
(err: unknown) => {
const key = createFlowUploadFailureMessageKey(err);
if (key === "errors.tooLarge") return u.fileTooLarge;
return tUpload(key);
},
[tUpload, u.fileTooLarge],
);
const handleFileChange = useCallback(
@@ -126,7 +134,7 @@ export function CommunityUploadScreen() {
markCreateFlowInteraction();
setErrorMessage(null);
if (signedIn) {
if (signedIn === true) {
setBusy(true);
try {
const { url } = await uploadCreateFlowFile(file, "communityAvatar");
@@ -134,7 +142,11 @@ export function CommunityUploadScreen() {
if (prev) URL.revokeObjectURL(prev);
return null;
});
updateState({ communityAvatarUrl: url });
setLocalFileName(file.name);
updateState({
communityAvatarUrl: url,
communityAvatarFileName: file.name,
});
} catch (err) {
setErrorMessage(resolveUploadError(err));
} finally {
@@ -143,26 +155,28 @@ export function CommunityUploadScreen() {
return;
}
if (signedIn === false) {
const validated = await validateCreateFlowUploadFile(
file,
"communityAvatar",
const validated = await validateCreateFlowUploadFile(
file,
"communityAvatar",
);
if (validated.ok === false) {
setErrorMessage(
validated.reason === "tooLarge"
? u.fileTooLarge
: tUpload(messageKeyForCreateFlowUploadReason(validated.reason)),
);
if (validated.ok === false) {
setErrorMessage(
tUpload(messageKeyForCreateFlowUploadReason(validated.reason)),
);
return;
}
try {
await storePendingCommunityAvatarFile(file);
setLocalPreviewUrl((prev) => {
if (prev) URL.revokeObjectURL(prev);
return URL.createObjectURL(file);
});
} catch {
setErrorMessage(tUpload("errors.generic"));
}
return;
}
try {
await storePendingCommunityAvatarFile(file);
setLocalPreviewUrl((prev) => {
if (prev) URL.revokeObjectURL(prev);
return URL.createObjectURL(file);
});
setLocalFileName(file.name);
updateState({ communityAvatarFileName: file.name });
} catch {
setErrorMessage(tUpload("errors.generic"));
}
},
[
@@ -170,28 +184,23 @@ export function CommunityUploadScreen() {
resolveUploadError,
signedIn,
tUpload,
u.fileTooLarge,
updateState,
],
);
const handleClearPendingUpload = useCallback(() => {
markCreateFlowInteraction();
setErrorMessage(null);
setLocalPreviewUrl((prev) => {
if (prev) URL.revokeObjectURL(prev);
return null;
});
if (hasCommunityAvatarUrl(state.communityAvatarUrl)) {
updateState({ communityAvatarUrl: undefined });
}
void clearPendingCommunityAvatarFile();
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
}, [markCreateFlowInteraction, state.communityAvatarUrl, updateState]);
const handlePickFile = useCallback(() => {
if (!busy) fileInputRef.current?.click();
}, [busy]);
const displaySrc = serverAvatarUrl ?? localPreviewUrl;
const hasPreview = typeof displaySrc === "string" && displaySrc.length > 0;
const fileName =
localFileName ??
(typeof state.communityAvatarFileName === "string" &&
state.communityAvatarFileName.trim().length > 0
? state.communityAvatarFileName.trim()
: undefined);
return (
<CreateFlowStepShell
@@ -214,60 +223,28 @@ export function CommunityUploadScreen() {
className="sr-only"
tabIndex={-1}
accept={COMMUNITY_AVATAR_ACCEPT}
aria-label={u.hintText}
aria-label={hasPreview ? u.replaceButton : u.hintText}
onChange={handleFileChange}
/>
<div className="flex w-full flex-col items-center gap-3">
{hasPreview ? (
<div className="relative inline-block max-w-full">
<button
type="button"
onClick={handleClearPendingUpload}
className="absolute right-[8px] top-[8px] z-[1] flex h-[32px] w-[32px] cursor-pointer items-center justify-center rounded-full bg-[var(--color-surface-default-secondary)] focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-border-invert-primary)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--color-surface-default-primary)]"
aria-label={u.clearPendingUploadAriaLabel}
title={u.clearPendingUploadTooltip}
>
{/* eslint-disable-next-line @next/next/no-img-element -- matches ModalHeader close control */}
<img
src={getAssetPath(ASSETS.ICON_CLOSE)}
alt=""
className="h-[16px] w-[16px]"
style={{
filter: "brightness(0) invert(1)",
}}
/>
</button>
{/* eslint-disable-next-line @next/next/no-img-element -- user/device file or same-origin upload URL */}
<img
src={displaySrc ?? ""}
alt={u.previewAlt}
className="max-h-[200px] max-w-full rounded-[var(--radius-200)] object-contain"
/>
</div>
) : (
<Upload
active={!busy}
showHelpIcon={false}
hintText={busy ? u.uploadingLabel : u.hintText}
onClick={() => {
if (!busy) fileInputRef.current?.click();
}}
/>
)}
{signedIn === false ? (
<p className="max-w-[474px] text-center font-[family-name:var(--font-body)] text-[length:var(--font-size-body-s)] text-[var(--color-content-default-tertiary)]">
{u.signInToUploadNote}
</p>
) : null}
{errorMessage ? (
<p
className="max-w-[474px] text-center font-[family-name:var(--font-body)] text-[length:var(--font-size-body-s)] text-[var(--color-content-default-secondary)]"
role="alert"
>
{errorMessage}
</p>
) : null}
</div>
<Upload
hasLabel={false}
active={!busy}
state={
errorMessage ? "error" : busy ? "disabled" : "default"
}
hintText={
errorMessage
? errorMessage
: busy
? u.uploadingLabel
: u.hintText
}
buttonLabel={hasPreview ? u.replaceButton : undefined}
previewSrc={hasPreview ? displaySrc ?? undefined : undefined}
previewAlt={u.previewAlt}
fileName={hasPreview ? fileName : undefined}
onClick={handlePickFile}
/>
</div>
</CreateFlowStepShell>
);
+10
View File
@@ -37,6 +37,7 @@ export type CreateFlowTextStateField =
| "title"
| "summary"
| "communityContext"
| "communityLocation"
| "communitySaveEmail";
/**
@@ -111,6 +112,8 @@ export interface CreateFlowState {
summary?: string;
/** Additional copy fields for multi-step Create Community text frames (Figma). */
communityContext?: string;
/** Optional city or region from the description step. */
communityLocation?: string;
/** Email collected on the “Save your progress” step (Figma Flow — Text `20097:14948`). */
communitySaveEmail?: string;
/**
@@ -118,6 +121,12 @@ export interface CreateFlowState {
* Set after successful `POST /api/uploads` with purpose `communityAvatar`.
*/
communityAvatarUrl?: string;
/**
* Original filename for the staged or uploaded community logo.
* Lets the upload control show Replace + filename after reload, including
* guest files that still live in IndexedDB.
*/
communityAvatarFileName?: string;
/**
* Light `hsl(...)` fill for the review card when no logo is uploaded.
* Picked once and kept on the draft so reload does not change it.
@@ -147,6 +156,7 @@ export interface CreateFlowState {
*/
communityStructureChipSnapshots?: {
organizationTypes?: CommunityStructureChipSnapshotRow[];
otherOrganizationTypes?: CommunityStructureChipSnapshotRow[];
scale?: CommunityStructureChipSnapshotRow[];
maturity?: CommunityStructureChipSnapshotRow[];
};
@@ -23,12 +23,34 @@ const DEFAULT_FOOTER_LABEL_BY_STEP: ReadonlyMap<
["community-size", "confirmSize"],
]);
function hasNonEmptyId(ids: readonly string[] | undefined): boolean {
return (ids ?? []).some((id) => id.length > 0);
}
export function isCommunityNameStepBlocked(
step: CreateFlowStep | null | undefined,
title: string | undefined,
): boolean {
if (step !== "community-name") return false;
return typeof title !== "string" || title.trim().length === 0;
}
export function isCommunityStructureStepBlocked(
step: CreateFlowStep | null | undefined,
selectedOrganizationTypeIds: readonly string[] | undefined,
selectedMaturityIds: readonly string[] | undefined,
): boolean {
if (step !== "community-structure") return false;
const mainKind = (selectedOrganizationTypeIds ?? []).find((id) => id.length > 0);
return !mainKind || !hasNonEmptyId(selectedMaturityIds);
}
export function isCommunitySizeStepBlocked(
step: CreateFlowStep | null | undefined,
selectedCommunitySizeIds: readonly string[] | undefined,
): boolean {
if (step !== "community-size") return false;
return !(selectedCommunitySizeIds ?? []).some((id) => id.length > 0);
return !hasNonEmptyId(selectedCommunitySizeIds);
}
/**
@@ -12,10 +12,10 @@ const PROPORTION_BY_STEP_INDEX: readonly ProportionBarState[] = [
"1-2", // community-structure
"1-3", // community-context
"1-4", // community-size
"1-5", // community-upload
"2-0", // community-save
"2-0", // review (Figma Flow — Review `19706:12135`: same segment fill as end of Create Community)
"2-0", // core-values (same segment as review / end of Create Community)
"1-6", // community-upload (1-5 is reserved for setup questions)
"1-7", // community-save
"1-8", // review
"2-0", // core-values (same fill as 1-8)
"2-1", // communication-methods (Figma — Compact Card Stack)
"2-2", // membership-methods (Figma — Compact Card Stack `20858:13947`)
"2-3", // decision-approaches (Figma Flow — Right Rail `20523:23509`)
@@ -41,7 +41,7 @@ export const CREATE_FLOW_SCREEN_REGISTRY: Record<
/** Figma: Flow — Informational (node 20094-16005). */
informational: {
layoutKind: "informational",
figmaNodeId: "20094-16005",
figmaNodeId: "25224-105191",
messageNamespace: "create.community.informational",
centeredBodyBelowMd: false,
},
@@ -59,13 +59,13 @@ export const CREATE_FLOW_SCREEN_REGISTRY: Record<
},
"community-context": {
layoutKind: "text",
figmaNodeId: "20094-41243",
figmaNodeId: "25224-106030",
messageNamespace: "create.community.communityContext",
centeredBodyBelowMd: true,
},
"community-structure": {
layoutKind: "select",
figmaNodeId: "20094-18244",
figmaNodeId: "25224-105767",
messageNamespace: "create.community.communityStructure",
centeredBodyBelowMd: false,
},
+12 -7
View File
@@ -172,13 +172,13 @@ export function getStepIndex(step: CreateFlowStep | null | undefined): number {
return FLOW_STEP_ORDER.indexOf(step);
}
/** First wizard step that offers Save & Exit (first Create Community select). */
const SAVE_EXIT_FROM_STEP_INDEX = getStepIndex("community-structure");
/** First wizard step that offers Save and exit (after the community is ready to keep). */
const SAVE_EXIT_FROM_STEP_INDEX = getStepIndex("community-save");
/**
* Top-nav Save & Exit (vs Exit). Guests and signed-in users share this from
* `community-structure` onward and on `edit-rule`. On completed, guests still
* get Save & Exit (claim/login); signed-in users get Exit (already owned).
* Top-nav Save and exit (vs Exit). Guests and signed-in users share this from
* `community-save` onward and on `edit-rule`. On completed, guests still
* get Save and exit (claim/login); signed-in users get Exit (already owned).
*
* @param sessionUser `null` is a guest. `undefined` (session in flight) is
* not a guest — completed stays Exit until the session resolves.
@@ -307,14 +307,19 @@ export const CREATE_FLOW_REVIEW_RETURN_QUERY_KEY = "reviewReturn" as const;
export const CREATE_FLOW_MANAGE_STAKEHOLDERS_QUERY = "manageStakeholders" as const;
export const CREATE_FLOW_MANAGE_STAKEHOLDERS_VALUE = "1" as const;
export type CreateFlowReviewReturnTarget = "final-review" | "edit-rule";
export type CreateFlowReviewReturnTarget =
| "final-review"
| "edit-rule"
| "review";
export function parseReviewReturnSearchParam(
searchParams: { get: (name: string) => string | null } | null | undefined,
): CreateFlowReviewReturnTarget | null {
if (!searchParams) return null;
const raw = searchParams.get(CREATE_FLOW_REVIEW_RETURN_QUERY_KEY);
if (raw === "final-review" || raw === "edit-rule") return raw;
if (raw === "final-review" || raw === "edit-rule" || raw === "review") {
return raw;
}
return null;
}
+3 -3
View File
@@ -168,7 +168,7 @@ export function RuleView({
logoUrl.startsWith("http://localhost") ||
logoUrl.startsWith("https://localhost");
const containerClass = `${logoContainerClass} relative rounded-full overflow-hidden mix-blend-luminosity`;
const containerClass = `${logoContainerClass} relative overflow-hidden rounded-full bg-[var(--color-surface-invert-brand-teal)]`;
if (isLocalhost) {
return (
@@ -179,7 +179,7 @@ export function RuleView({
alt={logoAlt || title}
width={logoSize}
height={logoSize}
className="w-full h-full object-cover rounded-full"
className="h-full w-full rounded-full object-cover opacity-70 mix-blend-color-burn"
/>
</div>
);
@@ -192,7 +192,7 @@ export function RuleView({
alt={logoAlt || title}
width={logoSize}
height={logoSize}
className="w-full h-full object-cover rounded-full"
className="h-full w-full rounded-full object-cover opacity-70 mix-blend-color-burn"
/>
</div>
);
@@ -21,6 +21,8 @@ const MultiSelectContainer = memo<MultiSelectProps>(
addButton: addButtonProp = true,
addButtonText,
formHeader = true,
helperText,
errorMessage,
onCustomChipConfirm,
onCustomChipClose,
maxSelections,
@@ -49,6 +51,8 @@ const MultiSelectContainer = memo<MultiSelectProps>(
chipSelectAriaLabel={t("chipSelect")}
chipDeselectAriaLabel={t("chipDeselect")}
formHeader={formHeader}
helperText={helperText}
errorMessage={errorMessage}
onCustomChipConfirm={onCustomChipConfirm}
onCustomChipClose={onCustomChipClose}
maxSelections={maxSelections}
@@ -54,6 +54,15 @@ export interface MultiSelectProps {
* @default true
*/
formHeader?: boolean;
/**
* Helper line beside the label (Figma “Pick one”). Wins over
* `selectionCountText` in the header.
*/
helperText?: string;
/**
* Danger hint under the chips for a required question left unanswered.
*/
errorMessage?: string;
/**
* Callback when a custom chip is confirmed (check button clicked)
*/
@@ -88,6 +97,8 @@ export interface MultiSelectViewProps {
chipSelectAriaLabel: string;
chipDeselectAriaLabel: string;
formHeader: boolean;
helperText?: string;
errorMessage?: string;
onCustomChipConfirm?: (chipId: string, value: string) => void;
onCustomChipClose?: (chipId: string) => void;
maxSelections?: number;
@@ -19,6 +19,8 @@ function MultiSelectView({
chipSelectAriaLabel,
chipDeselectAriaLabel,
formHeader = true,
helperText: helperTextProp,
errorMessage,
onCustomChipConfirm,
onCustomChipClose,
maxSelections,
@@ -39,7 +41,9 @@ function MultiSelectView({
const atLimit =
maxSelections != null && selectedCount >= maxSelections;
const countCaption = selectionCountText?.trim() ?? "";
const helperText = countCaption.length > 0 ? countCaption : false;
const headerHelper =
helperTextProp?.trim() ||
(countCaption.length > 0 ? countCaption : false);
return (
<div
@@ -51,16 +55,16 @@ function MultiSelectView({
label={label}
helpIcon={showHelpIcon}
asterisk={false}
helperText={helperText}
helperText={headerHelper}
size={size}
palette={palette}
/>
)}
{!formHeader || !label ? (
countCaption.length > 0 ? (
headerHelper && typeof headerHelper === "string" ? (
<p className="w-full text-x-small-paragraph text-[color:var(--color-content-default-tertiary)]">
{countCaption}
{headerHelper}
</p>
) : null
) : null}
@@ -177,6 +181,14 @@ function MultiSelectView({
</button>
)}
</div>
{errorMessage ? (
<p
className="w-full text-x-small-paragraph text-[color:var(--color-content-default-negative-primary)]"
role="alert"
>
{errorMessage}
</p>
) : null}
</div>
);
}
@@ -71,5 +71,6 @@ export interface TextInputViewProps {
inputMode?: React.HTMLAttributes<HTMLInputElement>["inputMode"];
required?: boolean;
form?: string;
autoFocus?: boolean;
onKeyDown?: React.KeyboardEventHandler<HTMLInputElement>;
}
@@ -35,6 +35,7 @@ export const TextInputView = forwardRef<HTMLInputElement, TextInputViewProps>(
inputMode,
required = false,
form,
autoFocus,
onKeyDown,
state: _state,
isFilled: _isFilled,
@@ -94,6 +95,7 @@ export const TextInputView = forwardRef<HTMLInputElement, TextInputViewProps>(
inputMode={inputMode}
required={required}
form={form}
autoFocus={autoFocus}
aria-invalid={error || undefined}
aria-required={required || undefined}
className={inputClasses}
@@ -18,12 +18,17 @@ const UploadContainer = memo<UploadProps>(
label,
showHelpIcon = true,
hintText,
buttonLabel,
previewSrc,
previewAlt,
fileName,
onClick,
className = "",
}) => {
const t = useTranslation("controlsChrome");
const resolvedState: UploadStateValue =
state ?? (active ? "default" : "disabled");
const uploadButtonLabel = buttonLabel ?? t("uploadButton");
return (
<UploadView
@@ -32,8 +37,11 @@ const UploadContainer = memo<UploadProps>(
label={label}
showHelpIcon={showHelpIcon}
hintText={hintText ?? t("uploadHintDefault")}
uploadButtonLabel={t("uploadButton")}
uploadAriaLabel={t("uploadAriaLabel")}
uploadButtonLabel={uploadButtonLabel}
uploadAriaLabel={uploadButtonLabel}
previewSrc={previewSrc}
previewAlt={previewAlt ?? t("uploadAriaLabel")}
fileName={fileName}
onClick={onClick}
className={className}
/>
@@ -32,6 +32,17 @@ export interface UploadProps {
* @default "Add image from your device"
*/
hintText?: string;
/**
* Label on the upload control. Defaults to the chrome “Upload” string.
* Pass “Replace” for the uploaded state.
*/
buttonLabel?: string;
/**
* Round preview of the selected file (Figma Has Preview).
*/
previewSrc?: string;
previewAlt?: string;
fileName?: string;
/**
* Callback when upload button is clicked
*/
@@ -50,6 +61,9 @@ export interface UploadViewProps {
hintText: string;
uploadButtonLabel: string;
uploadAriaLabel: string;
previewSrc?: string;
previewAlt: string;
fileName?: string;
onClick?: () => void;
className: string;
}
+62 -47
View File
@@ -12,13 +12,17 @@ function UploadView({
hintText,
uploadButtonLabel,
uploadAriaLabel,
previewSrc,
previewAlt,
fileName,
onClick,
className = "",
}: UploadViewProps) {
const isActive = state !== "disabled";
const isDisabled = state === "disabled";
const hasPreview =
typeof previewSrc === "string" && previewSrc.length > 0;
// Button styles based on active state
const buttonBgClass = isActive
? "bg-[var(--color-surface-invert-primary)]"
: "bg-[var(--color-surface-default-secondary)]";
@@ -27,12 +31,10 @@ function UploadView({
? "text-[color:var(--color-content-invert-primary)]"
: "text-[color:var(--color-content-invert-tertiary)]";
// Description text color based on active state
const descriptionTextColor = isActive
? "text-[color:var(--color-content-default-primary)]"
: "text-[color:var(--color-content-default-tertiary)]";
// Icon color based on active state
const iconColor = isActive
? "text-[color:var(--color-content-invert-primary)]"
: "text-[color:var(--color-content-invert-tertiary)]";
@@ -41,7 +43,6 @@ function UploadView({
<div
className={`flex flex-col gap-[var(--space-300)] items-start relative w-full ${className}`}
>
{/* Label using InputLabel component */}
{hasLabel && label ? (
<InputLabel
label={label}
@@ -53,15 +54,27 @@ function UploadView({
/>
) : null}
{/* Upload container — max width per create-flow spec */}
<div
className={`bg-[var(--color-surface-default-secondary)] mx-auto flex w-full max-w-[474px] shrink-0 items-center justify-center gap-[24px] rounded-[var(--radius-200)] px-[var(--space-600)] py-[var(--space-1200)] ${
state === "error"
? "border border-[var(--color-border-default-utility-negative)]"
? "border-2 border-[var(--color-border-default-negative-primary)]"
: ""
} ${state === "focus" ? "shadow-[var(--shadow-focus-default)]" : ""}`}
>
{/* Upload button */}
{hasPreview ? (
<div
className="relative size-[80px] shrink-0 overflow-hidden rounded-full bg-[var(--color-surface-invert-brand-teal)]"
aria-hidden={false}
>
{/* eslint-disable-next-line @next/next/no-img-element -- user/device file or same-origin upload URL */}
<img
src={previewSrc}
alt={previewAlt}
className="h-full w-full object-cover opacity-70 mix-blend-color-burn"
/>
</div>
) : null}
<button
type="button"
onClick={onClick}
@@ -71,43 +84,43 @@ function UploadView({
} ${state === "active" ? "scale-[0.98]" : ""}`}
aria-label={uploadAriaLabel}
>
{/* Upload icon */}
<div className={`relative shrink-0 size-[20px] ${iconColor}`}>
<svg
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className="size-full"
>
<path
d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
<polyline
points="17 8 12 3 7 8"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
<line
x1="12"
y1="3"
x2="12"
y2="15"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</div>
{/* Button text */}
{hasPreview ? null : (
<div className={`relative shrink-0 size-[20px] ${iconColor}`}>
<svg
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className="size-full"
>
<path
d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
<polyline
points="17 8 12 3 7 8"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
<line
x1="12"
y1="3"
x2="12"
y2="15"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</div>
)}
<div
className={`flex flex-col font-medium justify-center leading-[0] relative shrink-0 text-[length:var(--sizing-400)] whitespace-nowrap ${buttonTextColor}`}
>
@@ -115,11 +128,13 @@ function UploadView({
</div>
</button>
{/* Description text */}
<div
className={`flex flex-[1_0_0] flex-col font-normal h-[32px] justify-center leading-[0] min-h-px min-w-px relative text-[length:var(--sizing-350)] ${descriptionTextColor}`}
className={`flex flex-[1_0_0] flex-col font-normal min-h-[32px] justify-center leading-[0] min-w-px relative text-[length:var(--sizing-350)] ${descriptionTextColor}`}
role={state === "error" ? "alert" : undefined}
>
<p className="leading-[20px] whitespace-pre-wrap">{hintText}</p>
<p className="leading-[20px] whitespace-pre-wrap">
{hasPreview && fileName ? fileName : hintText}
</p>
</div>
</div>
</div>
@@ -73,6 +73,8 @@ const AlertContainer = memo<AlertProps>(
hasBodyText = true,
hasTrailingIcon: hasTrailingIconProp,
onClose,
actionLabel,
onAction,
className = "",
}) => {
const t = useTranslation("controlsChrome");
@@ -178,6 +180,8 @@ const AlertContainer = memo<AlertProps>(
closeButtonIconColor={statusStyles.closeButtonIconColor}
onClose={onClose}
closeAlertAriaLabel={t("closeAlert")}
actionLabel={actionLabel}
onAction={onAction}
/>
);
},
@@ -38,6 +38,9 @@ export interface AlertProps {
*/
hasTrailingIcon?: boolean;
onClose?: () => void;
/** Optional trailing action (Figma “Send it again”). */
actionLabel?: string;
onAction?: () => void;
className?: string;
}
@@ -58,4 +61,6 @@ export interface AlertViewProps {
closeButtonIconColor: string;
onClose?: () => void;
closeAlertAriaLabel: string;
actionLabel?: string;
onAction?: () => void;
}
@@ -18,6 +18,8 @@ export function AlertView({
closeButtonIconColor,
onClose,
closeAlertAriaLabel,
actionLabel,
onAction,
}: AlertViewProps) {
const getIcon = () => {
// Use the Icon_Alert.svg with dynamic fill color
@@ -55,6 +57,15 @@ export function AlertView({
{hasBodyText && description && (
<p className={descriptionClasses}>{description}</p>
)}
{actionLabel && onAction ? (
<button
type="button"
onClick={onAction}
className="mt-[var(--space-100)] cursor-pointer text-small-label text-[color:var(--color-content-invert-primary)] underline underline-offset-[3px]"
>
{actionLabel}
</button>
) : null}
</div>
{hasTrailingIcon && onClose ? (
<Button
@@ -7,6 +7,9 @@ export type ProportionBarState =
| "1-3"
| "1-4"
| "1-5"
| "1-6"
| "1-7"
| "1-8"
| "2-0"
| "2-1"
| "2-2"
@@ -27,13 +27,13 @@ export function ProportionBarView({
// Proportion bar type
const [fullSegments, partialSegment] = progress.split("-").map(Number);
// Calculate total progress:
// - For 1-X: first section is (X+1)/6 filled
// - For 1-X: first section is (X+1)/9 filled (intro 1-0 through review 1-8)
// - For 2-X: first section full, second section filled per Figma ratios (see `SECOND_SEGMENT_FILL_RATIO`)
// - For 3-X: first two sections full, third section X/3 filled
// Max is 3 full segments = 9 units
let totalProgress = 0;
if (fullSegments === 1) {
totalProgress = (partialSegment + 1) / 6; // 1/6 to 6/6 of first section
totalProgress = (partialSegment + 1) / 9; // 1/9 to 9/9 of first section
} else if (fullSegments === 2) {
totalProgress = 1 + getSecondSegmentFillRatio(partialSegment);
} else if (fullSegments === 3) {
@@ -53,7 +53,7 @@ export function ProportionBarView({
? `Progress: ${fullSegments} segments, ${partialSegment} of 3 parts filled (${progressPercentage}%)`
: fullSegments === 2
? `Progress: ${fullSegments} segments, ${partialSegment} of 3 parts filled (${progressPercentage}%)`
: `Progress: ${fullSegments} segment, ${partialSegment + 1} of 6 parts filled (${progressPercentage}%)`;
: `Progress: ${fullSegments} segment, ${partialSegment + 1} of 9 parts filled (${progressPercentage}%)`;
return (
<div
@@ -78,12 +78,12 @@ export function ProportionBarView({
background capsule.
*/}
<div className="absolute inset-0 flex gap-[var(--space-200)] px-[4px] overflow-hidden">
{/* First section - for 1-X: (X+1)/6 filled, for 2-X and 3-X: fully filled */}
{/* First section - for 1-X: (X+1)/9 filled, for 2-X and 3-X: fully filled */}
<div className="flex-1 h-full relative">
{fullSegments === 1 ? (
<div
className="absolute inset-y-0 left-0 bg-[var(--color-content-default-brand-primary)] rounded-l-[var(--radius-full)]"
style={{ width: `${((partialSegment + 1) / 6) * 100}%` }}
style={{ width: `${((partialSegment + 1) / 9) * 100}%` }}
/>
) : fullSegments >= 2 ? (
<div className="absolute inset-0 bg-[var(--color-content-default-brand-primary)] rounded-l-[var(--radius-full)]" />
@@ -2,7 +2,7 @@ export type NumberedListSizeValue = "M" | "S";
export interface NumberedListItem {
title: string;
description: string;
description?: string;
}
export interface NumberedListProps {
@@ -45,16 +45,17 @@ function NumberedListView({ items, size }: NumberedListViewProps) {
</h3>
</div>
{/* Description */}
<p
className={`max-w-[640px] overflow-hidden relative shrink-0 text-[var(--color-content-default-tertiary,#b4b4b4)] text-ellipsis w-full whitespace-pre-wrap ${
isM
? "text-small-paragraph"
: "text-x-small-paragraph"
}`}
>
{item.description}
</p>
{item.description ? (
<p
className={`max-w-[640px] overflow-hidden relative shrink-0 text-[var(--color-content-default-tertiary,#b4b4b4)] text-ellipsis w-full whitespace-pre-wrap ${
isM
? "text-small-paragraph"
: "text-x-small-paragraph"
}`}
>
{item.description}
</p>
) : null}
</div>
</li>
))}
+12 -6
View File
@@ -21,11 +21,17 @@ export function isValidCreateFlowSaveEmail(value: unknown): boolean {
// Native type=email rejects whitespace; jsdom’s checkValidity does not.
if (/\s/.test(value)) return false;
if (typeof document === "undefined") {
return EMAIL_FALLBACK_PATTERN.test(value);
if (!EMAIL_FALLBACK_PATTERN.test(value)) return false;
} else {
const input = document.createElement("input");
input.type = "email";
input.required = true;
input.value = value;
if (!input.checkValidity()) return false;
}
const input = document.createElement("input");
input.type = "email";
input.required = true;
input.value = value;
return input.checkValidity();
// Native type=email allows a single domain label (`maya@example`). The
// save-progress field needs a dotted domain so we can actually send mail.
const at = value.lastIndexOf("@");
const domain = at >= 0 ? value.slice(at + 1) : "";
return domain.includes(".");
}
+1 -1
View File
@@ -81,7 +81,7 @@ export async function sendMagicLinkEmail(
const { text, html } = buildVerifyLinkParts(
verifyUrl,
"Open this link to sign in (it expires in 60 minutes):",
"If you did not request this, you can ignore this email.",
"If you did not request this, you can ignore this email.\n\nSent because you saved a draft at communityrule.info",
"Sign in",
);
await sendHtmlMail({
@@ -22,6 +22,9 @@ const communityStructureChipSnapshotRowSchema = z.object({
const communityStructureChipSnapshotsSchema = z
.object({
organizationTypes: z.array(communityStructureChipSnapshotRowSchema).optional(),
otherOrganizationTypes: z
.array(communityStructureChipSnapshotRowSchema)
.optional(),
scale: z.array(communityStructureChipSnapshotRowSchema).optional(),
maturity: z.array(communityStructureChipSnapshotRowSchema).optional(),
})
@@ -104,8 +107,10 @@ export const createFlowStateSchema = z
title: z.string().max(500).optional(),
summary: z.string().max(8000).optional(),
communityContext: z.string().max(200).optional(),
communityLocation: z.string().max(200).optional(),
communitySaveEmail: z.string().max(320).optional(),
communityAvatarUrl: z.string().max(512).optional(),
communityAvatarFileName: z.string().max(255).optional(),
previewSurfaceColor: z
.string()
.max(32)
@@ -1,7 +1,10 @@
{
"title": "Why does your community exist?",
"description": "Optional. Write a short paragraph about your mission, goals, and scope. You can skip this and add it later.",
"title": "What does your community do?",
"description": "For example, we cook and share free meals with neighbors every Sunday.",
"inputLabel": "Community description",
"placeholder": "Describe your community",
"characterCountTemplate": "{current}/{max}"
"characterCountTemplate": "{current}/{max}",
"locationLabel": "Where is your community based?",
"locationPlaceholder": "City or region",
"locationHint": "Optional. A city or region is enough."
}
@@ -1,7 +1,8 @@
{
"title": "What is your community called?",
"description": "This will be the name of your community.",
"description": "Use the name your members know. You can change this later.",
"inputLabel": "Community name",
"placeholder": "Enter community name",
"characterCountTemplate": "{current}/{max}"
"characterCountTemplate": "{current}/{max}",
"errorMessage": "Add your community’s name to continue."
}
@@ -1,10 +1,12 @@
{
"title": "Save your progress",
"description": "We need your email to save your CommunityRule progress\nand make it accessible to you later.",
"description": "We will email a link so you can come back to your Rule. Only the person with this email can edit it.",
"inputLabel": "Email address",
"placeholder": "email@domain.com",
"characterCountTemplate": "{current}/{max}",
"magicLinkSuccessTitle": "Check your email to log in",
"magicLinkSuccessDescription": "We emailed a sign-in link. Open it on this device to continue — check spam or promotions if you don't see it.",
"magicLinkErrorTitle": "Could not send link"
"skipHint": "If you skip, your progress stays in this browser only.",
"errorMessage": "Check your email address. We need it to send your link.",
"magicLinkErrorTitle": "Could not send link",
"sentToastTitle": "Check your email",
"sentToastDescription": "A link back to your Rule is on its way to {email}.",
"sentToastAction": "Send it again"
}
@@ -3,6 +3,7 @@
"title": "How many people will be in your community in the near term?",
"description": "Count the people who have a say in your big decisions. If others take part without a vote, you can say so later in setup."
},
"pickOneError": "Pick one to continue.",
"communitySizes": [
{ "id": "oneMember", "label": "One member" },
{ "id": "twoToFive", "label": "2 to 5" },
@@ -1,20 +1,22 @@
{
"header": {
"title": "What kind of community would you like to improve?",
"description": "Choose tags that describe your community. You can also combine or add new values to the list."
"title": "What kind of community is this?",
"description": "Your answers shape which cards we suggest for your Rule."
},
"organizationMultiSelect": {
"label": "Organization Type",
"addButtonText": "Add organization type"
"mainKindMultiSelect": {
"label": "What kind of community are you, mainly?",
"helperText": "Pick one"
},
"otherKindMultiSelect": {
"label": "Anything else that fits?"
},
"scaleMultiSelect": {
"label": "Scale",
"addButtonText": "Add scale"
"label": "Scale"
},
"maturityMultiSelect": {
"label": "Maturity",
"addButtonText": "Add maturity"
"label": "Maturity"
},
"pickOneError": "Pick one to continue.",
"organizationTypes": [
{ "id": "workersCoop", "label": "Worker co-op" },
{ "id": "mutualAid", "label": "Mutual aid" },
@@ -1,10 +1,9 @@
{
"title": "Add a photo to identify your group",
"description": "This photo will be used as a profile picture for your group and will be editable later. If possible, try to use a simple logo or graphic.",
"title": "Add a logo",
"description": "Optional. A simple logo or graphic works best. Only people who can read your Rule can see this image. Skip this if your community needs to stay hard to identify.",
"hintText": "Add image from your device",
"signInToUploadNote": "Your photo will upload after you sign in (use Save progress from the next step, or Log in from the header).",
"uploadingLabel": "Uploading your photo…",
"previewAlt": "Selected community photo preview",
"clearPendingUploadAriaLabel": "Remove uploaded photo",
"clearPendingUploadTooltip": "Remove photo"
"replaceButton": "Replace",
"uploadingLabel": "Uploading your logo",
"previewAlt": "Selected community logo preview",
"fileTooLarge": "That file is too large. Try a smaller one"
}
@@ -1,18 +1,15 @@
{
"title": "How CommunityRule helps groups like yours",
"description": "This flow will give you recommendations to improve your community and help you put together a proposal for your group to consider.",
"title": "Write your community’s Rule",
"description": "Work through it together or on your own. Nothing is shared until you invite people, and you don’t need an account to start.",
"steps": {
"0": {
"title": "Tell us about your organization",
"description": "Start by providing your group's name, description, and profile image."
"title": "Tell us about your community"
},
"1": {
"title": "Define your group's CommunityRule.",
"description": "Outline decision-making processes, conflict resolution methods, and membership practices. Get recommendations."
"title": "Write your Rule"
},
"2": {
"title": "Share and evolve over time",
"description": "Review and refine your community framework before putting it into action and adapting it over time."
"title": "Review and finish"
}
}
}
+10 -2
View File
@@ -1,11 +1,19 @@
{
"header": {
"title": "Your community is added - congrats!",
"description": "In the next section, we'll go through membership, decision-making, conflict resolution, and community values and create a custom operating manual for your organization based on the specifics you just shared."
"title": "Here is your community",
"description": "Next you will write your Rule — the values, ways of talking, membership, decisions, and conflict practices your group wants to try."
},
"empty": {
"title": "No community in progress yet",
"description": "This step is for a community you have already named. Start from the beginning to add one.",
"startLabel": "Start creating"
},
"rows": {
"kind": "Kind",
"size": "Size",
"maturity": "Maturity",
"setup": "A few more things",
"edit": "Edit",
"sizePeople": "{label} people"
}
}
+4 -2
View File
@@ -1,7 +1,9 @@
{
"next": "Next",
"saveLater": "Save Later",
"submitEmail": "Submit Email",
"skip": "Skip",
"skipForNow": "Skip for now",
"saveLater": "Skip for now",
"submitEmail": "Submit email",
"submitEmailSending": "Sending link…",
"createCustom": "Create custom",
"createFromTemplate": "Create from template",
+8 -5
View File
@@ -1,7 +1,7 @@
{
"bannerAriaLabel": "Create rule flow navigation",
"navAriaLabel": "Create flow navigation",
"saveAndExit": "Save & Exit",
"saveAndExit": "Save and exit",
"exit": "Exit",
"share": "Share",
"export": "Export",
@@ -14,10 +14,13 @@
"moreOptionsAriaLabel": "More options",
"actionsMenuAriaLabel": "Create flow actions",
"leaveConfirmLoss": "Leave create flow? Your progress will be lost.",
"leaveConfirmTitle": "Leave create flow?",
"leaveConfirmDescription": "Your progress on this device will be lost unless you use Save & Exit first.",
"leaveConfirmProceed": "Leave",
"leaveConfirmTitle": "Leave without saving?",
"leaveConfirmDescription": "Your answers are not saved yet. Add your email and you can come back to them.",
"leaveConfirmProceed": "Leave anyway",
"leaveConfirmSaveProgress": "Save my progress",
"leaveConfirmCancel": "Stay",
"draftSaveBannerTitle": "Couldn't save draft",
"postLoginSaveFailedWithReason": "Could not save your draft to your account. Your progress is still stored on this device.\n\n{reason}"
"postLoginSaveFailedWithReason": "Could not save your draft to your account. Your progress is still stored on this device.\n\n{reason}",
"offlineTitle": "You're offline",
"offlineDescription": "Your progress stays in this browser until you reconnect."
}
@@ -28,6 +28,9 @@ export default {
"1-3",
"1-4",
"1-5",
"1-6",
"1-7",
"1-8",
"2-0",
"2-1",
"2-2",
+14
View File
@@ -57,4 +57,18 @@ describe("Alert dismiss control", () => {
screen.queryByRole("button", { name: "Close" }),
).not.toBeInTheDocument();
});
it("renders an action control when actionLabel and onAction are set", async () => {
const user = userEvent.setup();
const onAction = vi.fn();
render(
<Alert
title="Check your email"
actionLabel="Send it again"
onAction={onAction}
/>,
);
await user.click(screen.getByRole("button", { name: "Send it again" }));
expect(onAction).toHaveBeenCalledTimes(1);
});
});
@@ -8,21 +8,25 @@ describe("CommunityStructureSelectScreen", () => {
it("does not render dummy help icons", () => {
renderWithProviders(<CommunityStructureSelectScreen />);
expect(screen.getByText("Organization Type")).toBeInTheDocument();
expect(
screen.getByText("What kind of community are you, mainly?"),
).toBeInTheDocument();
expect(screen.getByText("Anything else that fits?")).toBeInTheDocument();
expect(screen.getByText("Scale")).toBeInTheDocument();
expect(screen.getByText("Maturity")).toBeInTheDocument();
expect(
screen.getByText(/Choose tags that describe your community/i),
screen.getByText(/Your answers shape which cards we suggest/i),
).toBeInTheDocument();
expect(screen.queryByAltText("Help")).not.toBeInTheDocument();
expect(screen.getByText("Pick one")).toBeInTheDocument();
});
it("gives structure chips Select/Deselect accessible names", () => {
renderWithProviders(<CommunityStructureSelectScreen />);
expect(
screen.getByRole("button", { name: "Select Worker co-op" }),
).toBeInTheDocument();
screen.getAllByRole("button", { name: "Select Worker co-op" }).length,
).toBeGreaterThanOrEqual(2);
expect(
screen.getByRole("button", { name: "Select Local" }),
).toBeInTheDocument();
+2 -2
View File
@@ -50,7 +50,7 @@ describe("CreateFlowFooter (behavioral tests)", () => {
});
expect(footer).toBeInTheDocument();
const bar = screen.getByRole("progressbar");
expect(bar).toHaveAttribute("aria-valuenow", String(1 / 6));
expect(bar).toHaveAttribute("aria-valuenow", String(1 / 9));
});
it("passes proportionBarProgress to the progress bar", () => {
@@ -63,7 +63,7 @@ describe("CreateFlowFooter (behavioral tests)", () => {
);
expect(screen.getByRole("progressbar")).toHaveAttribute(
"aria-valuenow",
String(2 / 6),
String(2 / 9),
);
});
+5 -5
View File
@@ -66,9 +66,9 @@ describe("CreateFlowTopNav (behavioral tests)", () => {
expect(exitButton).toBeInTheDocument();
});
it("shows Save & Exit when saveDraftOnExit is true", () => {
it("shows Save and exit when saveDraftOnExit is true", () => {
render(<CreateFlowTopNav saveDraftOnExit={true} />);
const exitButton = screen.getByRole("button", { name: "Save & Exit" });
const exitButton = screen.getByRole("button", { name: "Save and exit" });
expect(exitButton).toBeInTheDocument();
});
@@ -232,7 +232,7 @@ describe("CreateFlowTopNav (viewport < sm2 / 440px)", () => {
).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Edit" })).not.toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "Save & Exit" }),
screen.queryByRole("button", { name: "Save and exit" }),
).not.toBeInTheDocument();
});
@@ -255,7 +255,7 @@ describe("CreateFlowTopNav (viewport < sm2 / 440px)", () => {
).toBeInTheDocument();
expect(screen.getByRole("menuitem", { name: "Edit" })).toBeInTheDocument();
expect(
screen.getByRole("menuitem", { name: "Save & Exit" }),
screen.getByRole("menuitem", { name: "Save and exit" }),
).toBeInTheDocument();
});
@@ -284,7 +284,7 @@ describe("CreateFlowTopNav (viewport < sm2 / 440px)", () => {
expect(handleEdit).toHaveBeenCalledTimes(1);
await user.click(kebab);
await user.click(screen.getByRole("menuitem", { name: "Save & Exit" }));
await user.click(screen.getByRole("menuitem", { name: "Save and exit" }));
expect(handleExit).toHaveBeenCalledTimes(1);
});
});
+3 -3
View File
@@ -8,7 +8,7 @@ describe("InformationalScreen", () => {
render(<InformationalScreen />);
expect(
screen.getByRole("heading", {
name: "How CommunityRule helps groups like yours",
name: "Write your community’s Rule",
}),
).toBeInTheDocument();
});
@@ -17,7 +17,7 @@ describe("InformationalScreen", () => {
render(<InformationalScreen />);
expect(
screen.getByText(
/This flow will give you recommendations to improve your community/i,
/Work through it together or on your own/i,
),
).toBeInTheDocument();
});
@@ -30,7 +30,7 @@ describe("InformationalScreen", () => {
it("renders first numbered list item title", () => {
render(<InformationalScreen />);
expect(
screen.getByText("Tell us about your organization"),
screen.getByText("Tell us about your community"),
).toBeInTheDocument();
});
});
+23
View File
@@ -252,4 +252,27 @@ describe("MultiSelect – behaviour specifics", () => {
expect(handleClose).toHaveBeenCalled();
});
it("shows a danger hint under the chips when errorMessage is set", () => {
render(
<MultiSelect
options={defaultChipOptions}
errorMessage="Pick one to continue."
/>,
);
expect(screen.getByRole("alert")).toHaveTextContent(
"Pick one to continue.",
);
});
it("shows helper text beside the label", () => {
render(
<MultiSelect
label="Main kind"
helperText="Pick one"
options={defaultChipOptions}
/>,
);
expect(screen.getByText("Pick one")).toBeInTheDocument();
});
});
+3 -2
View File
@@ -61,8 +61,9 @@ describe("ProportionBar (behavioral tests)", () => {
it("handles all proportion states correctly", () => {
const testCases = [
{ progress: "1-0" as const, expected: 1 / 6 }, // First section 1/6 filled
{ progress: "1-5" as const, expected: 1 }, // First section 6/6 filled (fully filled)
{ progress: "1-0" as const, expected: 1 / 9 },
{ progress: "1-5" as const, expected: 6 / 9 },
{ progress: "1-8" as const, expected: 1 },
{ progress: "2-0" as const, expected: 1 }, // First section full, second empty
{ progress: "2-2" as const, expected: 1 + 1 / 2 }, // 1 + 1/2 per Figma `18861:15250`
{ progress: "2-3" as const, expected: 1 + 3 / 4 }, // 1 + 3/4 per Figma `21434:17632`
+30 -2
View File
@@ -22,6 +22,23 @@ function ReviewWithTitle({ title }: { title: string }) {
return <CommunityReviewScreen />;
}
function ReviewWithAnswers() {
const { state, updateState } = useCreateFlow();
const seededRef = React.useRef(false);
useEffect(() => {
if (seededRef.current) return;
seededRef.current = true;
updateState({
title: "Garden Club",
selectedOrganizationTypeIds: ["mutualAid"],
selectedCommunitySizeIds: ["thirteenToOneHundred"],
selectedMaturityIds: ["established"],
});
}, [updateState]);
if (state.title !== "Garden Club") return null;
return <CommunityReviewScreen />;
}
describe("CommunityReviewScreen", () => {
beforeEach(() => {
testRouter.replace.mockReset();
@@ -53,7 +70,7 @@ describe("CommunityReviewScreen", () => {
render(<ReviewWithTitle title="Garden Club" />);
expect(
screen.getByRole("heading", {
name: "Your community is added - congrats!",
name: "Here is your community",
}),
).toBeInTheDocument();
});
@@ -62,7 +79,7 @@ describe("CommunityReviewScreen", () => {
render(<ReviewWithTitle title="Garden Club" />);
expect(
screen.getByText(
/In the next section, we'll go through membership, decision-making, conflict resolution, and community values and create a custom operating manual for your organization based on the specifics you just shared./i,
/Next you will write your Rule/i,
),
).toBeInTheDocument();
});
@@ -81,6 +98,17 @@ describe("CommunityReviewScreen", () => {
).not.toBeInTheDocument();
});
it("lists kind, size, and maturity with Edit controls", () => {
render(<ReviewWithAnswers />);
expect(screen.getByText("Kind")).toBeInTheDocument();
expect(screen.getByText("Mutual aid")).toBeInTheDocument();
expect(screen.getByText("Size")).toBeInTheDocument();
expect(screen.getByText("13 to 100 people")).toBeInTheDocument();
expect(screen.getByText("Maturity")).toBeInTheDocument();
expect(screen.getByText("Established")).toBeInTheDocument();
expect(screen.getAllByRole("button", { name: "Edit" })).toHaveLength(3);
});
it("renders Rule as a button when a community name exists", () => {
render(<ReviewWithTitle title="Garden Club" />);
const buttons = screen.getAllByRole("button");
+13 -2
View File
@@ -31,7 +31,7 @@ describe("CreateFlowTextFieldScreen (community name)", () => {
/>,
);
expect(
screen.getByText("This will be the name of your community."),
screen.getByText("Use the name your members know. You can change this later."),
).toBeInTheDocument();
const input = screen.getByRole("textbox", { name: "Community name" });
expect(input).toBeInTheDocument();
@@ -46,18 +46,29 @@ describe("CreateFlowTextFieldScreen (community description)", () => {
<CreateFlowTextFieldScreen
messageNamespace="create.community.communityContext"
stateField="communityContext"
locationField="communityLocation"
maxLength={200}
multiline
/>,
);
expect(
screen.getByText(/Optional\. Write a short paragraph/i),
screen.getByText(
"For example, we cook and share free meals with neighbors every Sunday.",
),
).toBeInTheDocument();
const field = screen.getByRole("textbox", {
name: "Community description",
});
expect(field.tagName).toBe("TEXTAREA");
expect(field).not.toBeRequired();
const location = screen.getByRole("textbox", {
name: "Where is your community based?",
});
expect(location).toHaveAttribute("placeholder", "City or region");
expect(location).not.toBeRequired();
expect(
screen.getByText("Optional. A city or region is enough."),
).toBeInTheDocument();
});
});
+16
View File
@@ -109,4 +109,20 @@ describe("Upload (behavioral tests)", () => {
"text-[color:var(--color-content-default-tertiary)]",
);
});
it("shows a round preview, Replace, and filename when previewSrc is set", () => {
render(
<Upload
previewSrc="blob:logo"
previewAlt="Selected community logo preview"
fileName="logo.png"
buttonLabel="Replace"
/>,
);
expect(
screen.getByRole("img", { name: "Selected community logo preview" }),
).toHaveAttribute("src", "blob:logo");
expect(screen.getByRole("button", { name: "Replace" })).toBeInTheDocument();
expect(screen.getByText("logo.png")).toBeInTheDocument();
});
});
+9 -18
View File
@@ -5,7 +5,6 @@ import {
fireEvent,
cleanup,
} from "../utils/test-utils";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom/vitest";
import { CommunityUploadScreen } from "../../app/(app)/create/screens/upload/CommunityUploadScreen";
import {
@@ -70,7 +69,7 @@ describe("CommunityUploadScreen", () => {
render(<CommunityUploadScreen />);
expect(
screen.getByRole("heading", {
name: "Add a photo to identify your group",
name: "Add a logo",
}),
).toBeInTheDocument();
});
@@ -80,13 +79,12 @@ describe("CommunityUploadScreen", () => {
expect(screen.getByRole("button", { name: "Upload" })).toBeInTheDocument();
expect(
screen.getByText(
/This photo will be used as a profile picture for your group/i,
/Only people who can read your Rule can see this image/i,
),
).toBeInTheDocument();
});
it("restores a pending IndexedDB photo and lets the user remove it", async () => {
const user = userEvent.setup();
it("restores a pending IndexedDB photo into the uploaded preview", async () => {
const pending = new File([pngBytes], "avatar.png", { type: "image/png" });
vi.mocked(readPendingCommunityAvatarFile).mockResolvedValue(pending);
@@ -94,22 +92,15 @@ describe("CommunityUploadScreen", () => {
const preview = await screen.findByRole("img", { name: copy.previewAlt });
expect(preview).toHaveAttribute("src", "blob:pending-avatar");
const remove = screen.getByRole("button", {
name: copy.clearPendingUploadAriaLabel,
});
await user.click(remove);
expect(clearPendingCommunityAvatarFile).toHaveBeenCalled();
expect(screen.getByRole("button", { name: "Upload" })).toBeInTheDocument();
expect(
screen.queryByRole("img", { name: copy.previewAlt }),
).not.toBeInTheDocument();
screen.getByRole("button", { name: copy.replaceButton }),
).toBeInTheDocument();
expect(screen.getByText("avatar.png")).toBeInTheDocument();
});
it("rejects an empty file with a clear error and does not stage it", async () => {
render(<CommunityUploadScreen />);
await screen.findByText(copy.signInToUploadNote);
await screen.findByRole("heading", { name: copy.title });
fireEvent.change(fileInput(), {
target: { files: [new File([], "empty.png", { type: "image/png" })] },
@@ -123,7 +114,7 @@ describe("CommunityUploadScreen", () => {
it("rejects a text file renamed as PNG", async () => {
render(<CommunityUploadScreen />);
await screen.findByText(copy.signInToUploadNote);
await screen.findByRole("heading", { name: copy.title });
fireEvent.change(fileInput(), {
target: {
@@ -139,7 +130,7 @@ describe("CommunityUploadScreen", () => {
it("rejects SVG uploads", async () => {
render(<CommunityUploadScreen />);
await screen.findByText(copy.signInToUploadNote);
await screen.findByRole("heading", { name: copy.title });
fireEvent.change(fileInput(), {
target: {
+39 -1
View File
@@ -1,7 +1,11 @@
import { describe, expect, it } from "vitest";
import communitySize from "../../messages/en/create/community/communitySize.json";
import { SIZE_BANDS } from "../../lib/create/deckTypes";
import { isCommunitySizeStepBlocked } from "../../app/(app)/create/utils/createFlowFooterLabels";
import {
isCommunityNameStepBlocked,
isCommunitySizeStepBlocked,
isCommunityStructureStepBlocked,
} from "../../app/(app)/create/utils/createFlowFooterLabels";
/**
* Inclusive bounds. 100 stays in 13 to 100. More than 100 starts at 101.
@@ -64,3 +68,37 @@ describe("community size bands", () => {
).toBe(false);
});
});
describe("community name and type continue gates", () => {
it("blocks the name step until a title is entered", () => {
expect(isCommunityNameStepBlocked("community-name", undefined)).toBe(true);
expect(isCommunityNameStepBlocked("community-name", " ")).toBe(true);
expect(isCommunityNameStepBlocked("community-name", "Garden Club")).toBe(
false,
);
expect(isCommunityNameStepBlocked("community-size", "")).toBe(false);
});
it("blocks the type step until a main kind and a maturity are chosen", () => {
expect(
isCommunityStructureStepBlocked("community-structure", [], ["earlyStage"]),
).toBe(true);
expect(
isCommunityStructureStepBlocked(
"community-structure",
["mutualAid"],
[],
),
).toBe(true);
expect(
isCommunityStructureStepBlocked(
"community-structure",
["mutualAid"],
["established"],
),
).toBe(false);
expect(
isCommunityStructureStepBlocked("community-size", [], []),
).toBe(false);
});
});
@@ -17,11 +17,14 @@ describe("getProportionBarProgressForCreateFlowStep", () => {
);
});
it("uses 2-0 on community-save, review, and core-values (Create Community segment / same fill)", () => {
expect(getProportionBarProgressForCreateFlowStep("community-save")).toBe(
"2-0",
it("maps the rest of Create Community onto part 1, skipping setup at 1-5", () => {
expect(getProportionBarProgressForCreateFlowStep("community-upload")).toBe(
"1-6",
);
expect(getProportionBarProgressForCreateFlowStep("review")).toBe("2-0");
expect(getProportionBarProgressForCreateFlowStep("community-save")).toBe(
"1-7",
);
expect(getProportionBarProgressForCreateFlowStep("review")).toBe("1-8");
expect(getProportionBarProgressForCreateFlowStep("core-values")).toBe(
"2-0",
);
+6
View File
@@ -25,4 +25,10 @@ describe("create footer messages", () => {
"Publish CommunityRule",
);
});
it("exposes Skip and Skip for now for optional community steps", () => {
expect(messages.create.footer.skip).toBe("Skip");
expect(messages.create.footer.skipForNow).toBe("Skip for now");
expect(messages.create.footer.submitEmail).toBe("Submit email");
});
});
+9 -3
View File
@@ -175,7 +175,7 @@ describe("flowSteps", () => {
).toBeNull();
});
it("parseReviewReturnSearchParam accepts only final-review and edit-rule", () => {
it("parseReviewReturnSearchParam accepts final-review, edit-rule, and review", () => {
expect(
parseReviewReturnSearchParam(
new URLSearchParams("reviewReturn=final-review"),
@@ -186,16 +186,22 @@ describe("flowSteps", () => {
new URLSearchParams("reviewReturn=edit-rule"),
),
).toBe("edit-rule");
expect(
parseReviewReturnSearchParam(new URLSearchParams("reviewReturn=review")),
).toBe("review");
expect(
parseReviewReturnSearchParam(new URLSearchParams("reviewReturn=nope")),
).toBeNull();
expect(parseReviewReturnSearchParam(null)).toBeNull();
});
it("offers Save & Exit from community-structure through final-review and on edit-rule", () => {
it("offers Save and exit from community-save through final-review and on edit-rule", () => {
expect(shouldOfferCreateFlowSaveAndExit("informational")).toBe(false);
expect(shouldOfferCreateFlowSaveAndExit("community-name")).toBe(false);
expect(shouldOfferCreateFlowSaveAndExit("community-structure")).toBe(true);
expect(shouldOfferCreateFlowSaveAndExit("community-structure")).toBe(false);
expect(shouldOfferCreateFlowSaveAndExit("community-upload")).toBe(false);
expect(shouldOfferCreateFlowSaveAndExit("community-save")).toBe(true);
expect(shouldOfferCreateFlowSaveAndExit("review")).toBe(true);
expect(shouldOfferCreateFlowSaveAndExit("final-review")).toBe(true);
expect(shouldOfferCreateFlowSaveAndExit("edit-rule")).toBe(true);
});
@@ -18,4 +18,8 @@ describe("isValidCreateFlowSaveEmail", () => {
it("accepts a required type=email value", () => {
expect(isValidCreateFlowSaveEmail("user@example.com")).toBe(true);
});
it("rejects a domain with no dot", () => {
expect(isValidCreateFlowSaveEmail("maya@example")).toBe(false);
});
});