Walk Create Community through the current screens and restore a chosen logo after reload #96
No files matched your search
@@ -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
|
||||
|
||||
@@ -16,6 +16,7 @@ import messages from "../../../messages/en/index";
|
||||
import Alert from "../../components/modals/Alert";
|
||||
|
||||
import { isBackendSyncEnabled } from "../../../lib/create/backendSyncEnabled";
|
||||
import { flushPendingCommunityAvatar } from "../../../lib/create/flushPendingCommunityAvatar";
|
||||
|
||||
function buildPayloadWithStep(
|
||||
base: CreateFlowState,
|
||||
@@ -111,8 +112,15 @@ export function PostLoginDraftTransfer({
|
||||
return;
|
||||
}
|
||||
|
||||
const flushed = await flushPendingCommunityAvatar();
|
||||
if (cancelled) return;
|
||||
const transferred =
|
||||
flushed.status === "uploaded"
|
||||
? { ...payload, communityAvatarUrl: flushed.url }
|
||||
: payload;
|
||||
|
||||
if (isBackendSyncEnabled() && createFlowStateHasKeys(local)) {
|
||||
const saveResult = await saveDraftToServer(payload);
|
||||
const saveResult = await saveDraftToServer(transferred);
|
||||
if (cancelled) return;
|
||||
|
||||
if (saveResult.ok === false) {
|
||||
@@ -127,8 +135,23 @@ export function PostLoginDraftTransfer({
|
||||
}
|
||||
}
|
||||
|
||||
clearAnonymousCreateFlowStorage();
|
||||
replaceState(payload);
|
||||
clearAnonymousCreateFlowStorage({
|
||||
preservePendingAvatar: flushed.status === "failed",
|
||||
});
|
||||
replaceState((prev) => {
|
||||
const fromPayload =
|
||||
typeof transferred.communityAvatarUrl === "string"
|
||||
? transferred.communityAvatarUrl.trim()
|
||||
: "";
|
||||
const fromPrev =
|
||||
typeof prev.communityAvatarUrl === "string"
|
||||
? prev.communityAvatarUrl.trim()
|
||||
: "";
|
||||
const communityAvatarUrl = fromPayload || fromPrev;
|
||||
return communityAvatarUrl
|
||||
? { ...transferred, communityAvatarUrl }
|
||||
: transferred;
|
||||
});
|
||||
|
||||
if (pathname) {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
|
||||
@@ -1,19 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useCreateFlow } from "../context/CreateFlowContext";
|
||||
import {
|
||||
CreateFlowUploadValidationError,
|
||||
uploadCreateFlowFile,
|
||||
} from "../../../../lib/create/uploadToServer";
|
||||
import {
|
||||
clearPendingCommunityAvatarFile,
|
||||
readPendingCommunityAvatarFile,
|
||||
} from "../../../../lib/create/pendingCommunityAvatarUpload";
|
||||
import { flushPendingCommunityAvatar } from "../../../../lib/create/flushPendingCommunityAvatar";
|
||||
|
||||
/** Background tries after a transient upload failure. The file stays staged. */
|
||||
const MAX_FLUSH_ATTEMPTS = 4;
|
||||
|
||||
/**
|
||||
* After sign-in, uploads a community avatar staged in IndexedDB (anonymous pick)
|
||||
* and writes `communityAvatarUrl` on success.
|
||||
* and writes `communityAvatarUrl` on success. A transient failure retries with
|
||||
* backoff while this layout stays mounted.
|
||||
*/
|
||||
export function CreateFlowPendingAvatarFlush({
|
||||
sessionUser,
|
||||
@@ -23,7 +20,8 @@ export function CreateFlowPendingAvatarFlush({
|
||||
sessionResolved: boolean;
|
||||
}) {
|
||||
const { state, updateState } = useCreateFlow();
|
||||
/** One successful flush per signed-in user id (survives React StrictMode remounts). */
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
/** One successful flush per signed-in user id (survives the effect re-running). */
|
||||
const lastFlushedUserIdRef = useRef<string | null>(null);
|
||||
const hasServerAvatar =
|
||||
typeof state.communityAvatarUrl === "string" &&
|
||||
@@ -33,29 +31,31 @@ export function CreateFlowPendingAvatarFlush({
|
||||
if (!sessionResolved || !sessionUser) return;
|
||||
if (lastFlushedUserIdRef.current === sessionUser.id) return;
|
||||
if (hasServerAvatar) return;
|
||||
if (attempt >= MAX_FLUSH_ATTEMPTS) return;
|
||||
let cancelled = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
void (async () => {
|
||||
const file = await readPendingCommunityAvatarFile();
|
||||
if (cancelled || !file) return;
|
||||
try {
|
||||
const { url } = await uploadCreateFlowFile(file, "communityAvatar");
|
||||
const result = await flushPendingCommunityAvatar();
|
||||
if (cancelled) return;
|
||||
await clearPendingCommunityAvatarFile();
|
||||
updateState({ communityAvatarUrl: url });
|
||||
if (result.status === "uploaded") {
|
||||
updateState({ communityAvatarUrl: result.url });
|
||||
lastFlushedUserIdRef.current = sessionUser.id;
|
||||
} catch (err) {
|
||||
if (err instanceof CreateFlowUploadValidationError) {
|
||||
await clearPendingCommunityAvatarFile();
|
||||
}
|
||||
// Leave a transient (auth / UPLOAD_ROOT) failure in place to retry.
|
||||
return;
|
||||
}
|
||||
if (result.status !== "failed") return;
|
||||
if (attempt + 1 >= MAX_FLUSH_ATTEMPTS) return;
|
||||
const delay = Math.min(20_000, 5_000 * 2 ** attempt);
|
||||
timer = setTimeout(() => {
|
||||
if (!cancelled) setAttempt((current) => current + 1);
|
||||
}, delay);
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (timer) clearTimeout(timer);
|
||||
};
|
||||
}, [hasServerAvatar, sessionResolved, sessionUser, updateState]);
|
||||
}, [attempt, hasServerAvatar, sessionResolved, sessionUser, updateState]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { readPendingCommunityAvatarFile } from "../../../../lib/create/pendingCommunityAvatarUpload";
|
||||
|
||||
function trimmedAvatarUrl(url: string | null): string | null {
|
||||
if (typeof url !== "string") return null;
|
||||
const trimmed = url.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Logo src for review cards. Uses the uploaded URL when the draft has one,
|
||||
* otherwise the guest file staged in IndexedDB.
|
||||
*
|
||||
* @param serverUrl `communityAvatarUrl` from create-flow state, if any.
|
||||
* @returns A URL the Rule card can render, or `null` when there is no logo.
|
||||
*
|
||||
* @example
|
||||
* const logoUrl = useCommunityAvatarDisplayUrl(state.communityAvatarUrl ?? null);
|
||||
*/
|
||||
export function useCommunityAvatarDisplayUrl(
|
||||
serverUrl: string | null | undefined,
|
||||
): string | null {
|
||||
const resolvedServerUrl = trimmedAvatarUrl(serverUrl ?? null);
|
||||
const [objectUrl, setObjectUrl] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (resolvedServerUrl) {
|
||||
setObjectUrl((prev) => {
|
||||
if (prev) URL.revokeObjectURL(prev);
|
||||
return null;
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
let created: string | null = null;
|
||||
void (async () => {
|
||||
try {
|
||||
const file = await readPendingCommunityAvatarFile();
|
||||
if (cancelled || !file) return;
|
||||
created = URL.createObjectURL(file);
|
||||
if (cancelled) {
|
||||
URL.revokeObjectURL(created);
|
||||
created = null;
|
||||
return;
|
||||
}
|
||||
setObjectUrl((prev) => {
|
||||
if (prev && prev !== created) URL.revokeObjectURL(prev);
|
||||
return created;
|
||||
});
|
||||
} catch {
|
||||
// IndexedDB missing or blocked: the card keeps the placeholder.
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (created) URL.revokeObjectURL(created);
|
||||
};
|
||||
}, [resolvedServerUrl]);
|
||||
|
||||
return resolvedServerUrl ?? objectUrl;
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useCallback } from "react";
|
||||
import type { CreateFlowState, CreateFlowStep } from "../types";
|
||||
import { buildPublishPayload } from "../../../../lib/create/buildPublishPayload";
|
||||
import { stateWithPendingCommunityAvatar } from "../../../../lib/create/flushPendingCommunityAvatar";
|
||||
import { saveDraftToServer, updatePublishedRule } from "../../../../lib/create/api";
|
||||
import { writeLastPublishedRule } from "../../../../lib/create/lastPublishedRule";
|
||||
import { isBackendSyncEnabled } from "../../../../lib/create/backendSyncEnabled";
|
||||
@@ -33,26 +34,32 @@ 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;
|
||||
}
|
||||
|
||||
if (saveDraft && isBackendSyncEnabled()) {
|
||||
const prepared = await stateWithPendingCommunityAvatar(state);
|
||||
if (prepared.ok === false) {
|
||||
setDraftSaveBannerMessage?.(messages.create.upload.errors.generic);
|
||||
return;
|
||||
}
|
||||
const draftState = prepared.state;
|
||||
const editingId =
|
||||
typeof state.editingPublishedRuleId === "string"
|
||||
? state.editingPublishedRuleId.trim()
|
||||
typeof draftState.editingPublishedRuleId === "string"
|
||||
? draftState.editingPublishedRuleId.trim()
|
||||
: "";
|
||||
if (editingId.length > 0) {
|
||||
const payloadResult = buildPublishPayload(state);
|
||||
const payloadResult = buildPublishPayload(draftState);
|
||||
if (payloadResult.ok === false) {
|
||||
setDraftSaveBannerMessage?.(
|
||||
payloadResult.error === "missingCommunityName"
|
||||
@@ -82,7 +89,7 @@ export function useCreateFlowExit({
|
||||
}
|
||||
} else {
|
||||
const payload: CreateFlowState = {
|
||||
...state,
|
||||
...draftState,
|
||||
...(currentStep ? { currentStep } : {}),
|
||||
};
|
||||
const result = await saveDraftToServer(payload);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useCallback, useState } from "react";
|
||||
import { buildPublishPayload } from "../../../../lib/create/buildPublishPayload";
|
||||
import { stateWithPendingCommunityAvatar } from "../../../../lib/create/flushPendingCommunityAvatar";
|
||||
import { publishRule, updatePublishedRule } from "../../../../lib/create/api";
|
||||
import { writeLastPublishedRule } from "../../../../lib/create/lastPublishedRule";
|
||||
import { writePendingKeepRuleLogin } from "../../../../lib/create/pendingKeepRuleLogin";
|
||||
@@ -63,8 +64,19 @@ export function useCreateFlowFinalize({
|
||||
if (sessionUser === undefined) return;
|
||||
|
||||
setPublishBannerMessage(null);
|
||||
const payloadResult = buildPublishPayload(state);
|
||||
setIsPublishing(true);
|
||||
const prepared = await stateWithPendingCommunityAvatar(state);
|
||||
if (prepared.ok === false) {
|
||||
setIsPublishing(false);
|
||||
setPublishBannerMessage(messages.create.upload.errors.generic);
|
||||
return;
|
||||
}
|
||||
if (prepared.state.communityAvatarUrl !== state.communityAvatarUrl) {
|
||||
updateState({ communityAvatarUrl: prepared.state.communityAvatarUrl });
|
||||
}
|
||||
const payloadResult = buildPublishPayload(prepared.state);
|
||||
if (payloadResult.ok === false) {
|
||||
setIsPublishing(false);
|
||||
setPublishBannerMessage(
|
||||
payloadResult.error === "missingCommunityName"
|
||||
? messages.create.reviewAndComplete.publish.missingCommunityName
|
||||
@@ -73,7 +85,6 @@ export function useCreateFlowFinalize({
|
||||
return;
|
||||
}
|
||||
const { title, summary, document: ruleDocument } = payloadResult;
|
||||
setIsPublishing(true);
|
||||
|
||||
const editingId =
|
||||
typeof state.editingPublishedRuleId === "string"
|
||||
|
||||
@@ -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,9 +4,11 @@ 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 { useCommunityAvatarDisplayUrl } from "../../hooks/useCommunityAvatarDisplayUrl";
|
||||
import { useCreateFlowLgUp } from "../../hooks/useCreateFlowLgUp";
|
||||
import { CreateFlowStepShell } from "../../components/CreateFlowStepShell";
|
||||
import {
|
||||
@@ -19,11 +21,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();
|
||||
/**
|
||||
@@ -91,11 +149,33 @@ export function CommunityReviewScreen() {
|
||||
? state.communityContext.trim()
|
||||
: undefined;
|
||||
|
||||
const avatarUrl =
|
||||
typeof state.communityAvatarUrl === "string" &&
|
||||
state.communityAvatarUrl.trim().length > 0
|
||||
? state.communityAvatarUrl.trim()
|
||||
: null;
|
||||
const avatarUrl = useCommunityAvatarDisplayUrl(state.communityAvatarUrl);
|
||||
|
||||
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 +223,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 +236,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>
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
} from "../../components/FinalReviewChipEditModal";
|
||||
import { FinalReviewCommunityContextEditModal } from "../../components/FinalReviewCommunityContextEditModal";
|
||||
import { FinalReviewTitleEditModal } from "../../components/FinalReviewTitleEditModal";
|
||||
import { useCommunityAvatarDisplayUrl } from "../../hooks/useCommunityAvatarDisplayUrl";
|
||||
import { usePreviewSurfaceColor } from "../../hooks/usePreviewSurfaceColor";
|
||||
import { useCreateFlowNavigation } from "../../hooks/useCreateFlowNavigation";
|
||||
import { createFlowStepForFacetGroup } from "../../utils/facetGroupToCreateFlowStep";
|
||||
@@ -251,11 +252,7 @@ export function FinalReviewScreen({
|
||||
const descriptionEmptyHint =
|
||||
variant === "editPublished" ? t("communityContextEditModal.emptyHint") : undefined;
|
||||
|
||||
const avatarUrl =
|
||||
typeof state.communityAvatarUrl === "string" &&
|
||||
state.communityAvatarUrl.trim().length > 0
|
||||
? state.communityAvatarUrl.trim()
|
||||
: null;
|
||||
const avatarUrl = useCommunityAvatarDisplayUrl(state.communityAvatarUrl);
|
||||
const storedFallback =
|
||||
typeof state.previewSurfaceColor === "string"
|
||||
? state.previewSurfaceColor
|
||||
|
||||
@@ -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,14 +155,15 @@ export function CommunityUploadScreen() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (signedIn === false) {
|
||||
const validated = await validateCreateFlowUploadFile(
|
||||
file,
|
||||
"communityAvatar",
|
||||
);
|
||||
if (validated.ok === false) {
|
||||
setErrorMessage(
|
||||
tUpload(messageKeyForCreateFlowUploadReason(validated.reason)),
|
||||
validated.reason === "tooLarge"
|
||||
? u.fileTooLarge
|
||||
: tUpload(messageKeyForCreateFlowUploadReason(validated.reason)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -160,38 +173,34 @@ export function CommunityUploadScreen() {
|
||||
if (prev) URL.revokeObjectURL(prev);
|
||||
return URL.createObjectURL(file);
|
||||
});
|
||||
setLocalFileName(file.name);
|
||||
updateState({ communityAvatarFileName: file.name });
|
||||
} catch {
|
||||
setErrorMessage(tUpload("errors.generic"));
|
||||
}
|
||||
}
|
||||
},
|
||||
[
|
||||
markCreateFlowInteraction,
|
||||
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
|
||||
hasLabel={false}
|
||||
active={!busy}
|
||||
showHelpIcon={false}
|
||||
hintText={busy ? u.uploadingLabel : u.hintText}
|
||||
onClick={() => {
|
||||
if (!busy) fileInputRef.current?.click();
|
||||
}}
|
||||
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}
|
||||
/>
|
||||
)}
|
||||
{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>
|
||||
</div>
|
||||
</CreateFlowStepShell>
|
||||
);
|
||||
|
||||
@@ -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[];
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { CreateFlowState } from "../types";
|
||||
import { forgetFlushedCommunityAvatarUrl } from "../../../../lib/create/flushPendingCommunityAvatar";
|
||||
import { migrateLegacyCreateFlowState } from "../../../../lib/create/migrateLegacyCreateFlowState";
|
||||
import { clearPendingCommunityAvatarFile } from "../../../../lib/create/pendingCommunityAvatarUpload";
|
||||
|
||||
@@ -47,7 +48,10 @@ export function writeAnonymousCreateFlowState(value: CreateFlowState): void {
|
||||
}
|
||||
}
|
||||
|
||||
export function clearAnonymousCreateFlowStorage(): void {
|
||||
export function clearAnonymousCreateFlowStorage(options?: {
|
||||
/** Keep the staged logo so a failed upload can retry. */
|
||||
preservePendingAvatar?: boolean;
|
||||
}): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
window.localStorage.removeItem(CREATE_FLOW_ANONYMOUS_KEY);
|
||||
@@ -55,6 +59,8 @@ export function clearAnonymousCreateFlowStorage(): void {
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
if (options?.preservePendingAvatar) return;
|
||||
forgetFlushedCommunityAvatarUrl();
|
||||
void clearPendingCommunityAvatarFile();
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
+35
-11
@@ -31,6 +31,17 @@ function isPurpose(x: string): x is CreateFlowUploadPurpose {
|
||||
return x === "communityAvatar" || x === "customMethodAttachment";
|
||||
}
|
||||
|
||||
function clientIp(request: NextRequest): string {
|
||||
return (
|
||||
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ??
|
||||
request.headers.get("x-real-ip") ??
|
||||
"unknown"
|
||||
);
|
||||
}
|
||||
|
||||
/** Same spacing as a signed-in upload, keyed by IP so a guest cannot fill the disk. */
|
||||
const ANONYMOUS_COMMUNITY_AVATAR_MIN_INTERVAL_MS = 5_000;
|
||||
|
||||
function messageForValidationReason(
|
||||
reason: CreateFlowUploadValidationReason,
|
||||
): string {
|
||||
@@ -54,7 +65,19 @@ export const POST = apiRoute("uploads.post", async (request: NextRequest) => {
|
||||
}
|
||||
|
||||
const user = await getSessionUser();
|
||||
if (!user) {
|
||||
|
||||
let formData: FormData | null = null;
|
||||
try {
|
||||
formData = await request.formData();
|
||||
} catch {
|
||||
formData = null;
|
||||
}
|
||||
|
||||
const purposeRaw = formData?.get("purpose");
|
||||
// A guest publishes before they have a session. Only the community logo
|
||||
// can be stored without one; attachments stay signed-in. A body that
|
||||
// cannot be parsed is not a logo upload.
|
||||
if (!user && purposeRaw !== "communityAvatar") {
|
||||
return unauthorized();
|
||||
}
|
||||
|
||||
@@ -64,15 +87,7 @@ export const POST = apiRoute("uploads.post", async (request: NextRequest) => {
|
||||
);
|
||||
}
|
||||
|
||||
const rl = rateLimitKey(`upload:${user.id}`, 5_000);
|
||||
if (rl.ok === false) {
|
||||
return rateLimited(rl.retryAfterMs);
|
||||
}
|
||||
|
||||
let formData: FormData;
|
||||
try {
|
||||
formData = await request.formData();
|
||||
} catch {
|
||||
if (!formData) {
|
||||
return errorJson(
|
||||
"payload_too_large",
|
||||
"Upload body is too large or malformed.",
|
||||
@@ -80,9 +95,18 @@ export const POST = apiRoute("uploads.post", async (request: NextRequest) => {
|
||||
);
|
||||
}
|
||||
|
||||
const purposeRaw = formData.get("purpose");
|
||||
const file = asUploadedBlob(formData.get("file"));
|
||||
|
||||
const rl = user
|
||||
? rateLimitKey(`upload:${user.id}`, 5_000)
|
||||
: rateLimitKey(
|
||||
`upload-anon:${clientIp(request)}`,
|
||||
ANONYMOUS_COMMUNITY_AVATAR_MIN_INTERVAL_MS,
|
||||
);
|
||||
if (rl.ok === false) {
|
||||
return rateLimited(rl.retryAfterMs);
|
||||
}
|
||||
|
||||
if (typeof purposeRaw !== "string" || !isPurpose(purposeRaw)) {
|
||||
return errorJson(
|
||||
"validation_error",
|
||||
|
||||
@@ -163,14 +163,16 @@ export function RuleView({
|
||||
// Render logo/icon
|
||||
const renderLogo = () => {
|
||||
if (logoUrl) {
|
||||
// Check if it's a localhost URL or external URL that needs regular img tag
|
||||
const isLocalhost =
|
||||
// next/image cannot load blob previews or localhost optimizer targets.
|
||||
const useNativeImage =
|
||||
logoUrl.startsWith("blob:") ||
|
||||
logoUrl.startsWith("data:") ||
|
||||
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) {
|
||||
if (useNativeImage) {
|
||||
return (
|
||||
<div className={containerClass}>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
@@ -179,7 +181,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 +194,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;
|
||||
}
|
||||
@@ -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,7 +84,7 @@ function UploadView({
|
||||
} ${state === "active" ? "scale-[0.98]" : ""}`}
|
||||
aria-label={uploadAriaLabel}
|
||||
>
|
||||
{/* Upload icon */}
|
||||
{hasPreview ? null : (
|
||||
<div className={`relative shrink-0 size-[20px] ${iconColor}`}>
|
||||
<svg
|
||||
width="20"
|
||||
@@ -107,7 +120,7 @@ function UploadView({
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
{/* Button text */}
|
||||
)}
|
||||
<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,7 +45,7 @@ function NumberedListView({ items, size }: NumberedListViewProps) {
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
{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
|
||||
@@ -55,6 +55,7 @@ function NumberedListView({ items, size }: NumberedListViewProps) {
|
||||
>
|
||||
{item.description}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { CreateFlowState } from "../../app/(app)/create/types";
|
||||
import { CreateFlowUploadValidationError } from "./createFlowUploadValidation";
|
||||
import {
|
||||
clearPendingCommunityAvatarFile,
|
||||
readPendingCommunityAvatarFile,
|
||||
} from "./pendingCommunityAvatarUpload";
|
||||
import { uploadCreateFlowFile } from "./uploadToServer";
|
||||
|
||||
export type FlushPendingCommunityAvatarResult =
|
||||
| { status: "none" }
|
||||
| { status: "uploaded"; url: string }
|
||||
| { status: "invalid" }
|
||||
| { status: "failed" };
|
||||
|
||||
/**
|
||||
* URL from the last successful flush. The IndexedDB file is removed on
|
||||
* success, so a second caller (publish, sign-in transfer) can still apply
|
||||
* the same URL if React state has not caught up yet.
|
||||
* Cleared when anonymous draft storage is wiped.
|
||||
*/
|
||||
let lastUploadedUrl: string | null = null;
|
||||
let inFlight: Promise<FlushPendingCommunityAvatarResult> | null = null;
|
||||
|
||||
export function forgetFlushedCommunityAvatarUrl(): void {
|
||||
lastUploadedUrl = null;
|
||||
}
|
||||
|
||||
async function runFlush(): Promise<FlushPendingCommunityAvatarResult> {
|
||||
let file: File | null;
|
||||
try {
|
||||
file = await readPendingCommunityAvatarFile();
|
||||
} catch {
|
||||
return lastUploadedUrl
|
||||
? { status: "uploaded", url: lastUploadedUrl }
|
||||
: { status: "none" };
|
||||
}
|
||||
if (!file) {
|
||||
return lastUploadedUrl
|
||||
? { status: "uploaded", url: lastUploadedUrl }
|
||||
: { status: "none" };
|
||||
}
|
||||
|
||||
try {
|
||||
const { url } = await uploadCreateFlowFile(file, "communityAvatar");
|
||||
lastUploadedUrl = url;
|
||||
await clearPendingCommunityAvatarFile();
|
||||
return { status: "uploaded", url };
|
||||
} catch (err) {
|
||||
if (err instanceof CreateFlowUploadValidationError) {
|
||||
await clearPendingCommunityAvatarFile();
|
||||
return { status: "invalid" };
|
||||
}
|
||||
return { status: "failed" };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload the staged community logo, once, even if review and sign-in both ask.
|
||||
* A validation failure drops the file. A transient failure leaves it in place.
|
||||
*/
|
||||
export function flushPendingCommunityAvatar(): Promise<FlushPendingCommunityAvatarResult> {
|
||||
if (!inFlight) {
|
||||
inFlight = runFlush().finally(() => {
|
||||
inFlight = null;
|
||||
});
|
||||
}
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy a staged logo onto `state` as `communityAvatarUrl` when upload works.
|
||||
* `upload_failed` means the file is still staged and must not be published over.
|
||||
*/
|
||||
export async function stateWithPendingCommunityAvatar(
|
||||
state: CreateFlowState,
|
||||
): Promise<
|
||||
| { ok: true; state: CreateFlowState }
|
||||
| { ok: false; reason: "upload_failed" }
|
||||
> {
|
||||
const existing =
|
||||
typeof state.communityAvatarUrl === "string"
|
||||
? state.communityAvatarUrl.trim()
|
||||
: "";
|
||||
if (existing.length > 0) return { ok: true, state };
|
||||
|
||||
const flushed = await flushPendingCommunityAvatar();
|
||||
if (flushed.status === "uploaded") {
|
||||
return {
|
||||
ok: true,
|
||||
state: { ...state, communityAvatarUrl: flushed.url },
|
||||
};
|
||||
}
|
||||
if (flushed.status === "failed") {
|
||||
return { ok: false, reason: "upload_failed" };
|
||||
}
|
||||
return { ok: true, state };
|
||||
}
|
||||
@@ -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;
|
||||
return input.checkValidity();
|
||||
if (!input.checkValidity()) return false;
|
||||
}
|
||||
// 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(".");
|
||||
}
|
||||
@@ -28,8 +28,8 @@ function reasonFromUnknown(value: unknown): CreateFlowUploadValidationReason | n
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticated multipart upload to `POST /api/uploads`.
|
||||
* Caller must have a session cookie (same-origin fetch).
|
||||
* Multipart upload to `POST /api/uploads`.
|
||||
* `communityAvatar` is accepted for a guest; other purposes need a session.
|
||||
*/
|
||||
export async function uploadCreateFlowFile(
|
||||
file: File,
|
||||
|
||||
+1
-1
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { act } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { CreateFlowPendingAvatarFlush } from "../../app/(app)/create/components/CreateFlowPendingAvatarFlush";
|
||||
import { useCreateFlow } from "../../app/(app)/create/context/CreateFlowContext";
|
||||
import { flushPendingCommunityAvatar } from "../../lib/create/flushPendingCommunityAvatar";
|
||||
import {
|
||||
renderWithProviders as render,
|
||||
screen,
|
||||
} from "../utils/test-utils";
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
|
||||
vi.mock("../../lib/create/flushPendingCommunityAvatar", () => ({
|
||||
flushPendingCommunityAvatar: vi.fn(),
|
||||
}));
|
||||
|
||||
function AvatarProbe() {
|
||||
const { state } = useCreateFlow();
|
||||
return <div data-testid="avatar">{state.communityAvatarUrl ?? ""}</div>;
|
||||
}
|
||||
|
||||
describe("CreateFlowPendingAvatarFlush", () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.mocked(flushPendingCommunityAvatar).mockReset();
|
||||
});
|
||||
|
||||
it("retries a transient upload and then stores the url", async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.mocked(flushPendingCommunityAvatar)
|
||||
.mockResolvedValueOnce({ status: "failed" })
|
||||
.mockResolvedValueOnce({
|
||||
status: "uploaded",
|
||||
url: "/api/uploads/retry",
|
||||
});
|
||||
|
||||
render(
|
||||
<>
|
||||
<CreateFlowPendingAvatarFlush
|
||||
sessionUser={{ id: "user-1", email: "maya@example.com" }}
|
||||
sessionResolved
|
||||
/>
|
||||
<AvatarProbe />
|
||||
</>,
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(flushPendingCommunityAvatar).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByTestId("avatar")).toHaveTextContent("");
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
});
|
||||
|
||||
expect(flushPendingCommunityAvatar).toHaveBeenCalledTimes(2);
|
||||
expect(screen.getByTestId("avatar")).toHaveTextContent(
|
||||
"/api/uploads/retry",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useCreateFlow } from "../../app/(app)/create/context/CreateFlowContext";
|
||||
import { PostLoginDraftTransfer } from "../../app/(app)/create/PostLoginDraftTransfer";
|
||||
import {
|
||||
CREATE_FLOW_ANONYMOUS_KEY,
|
||||
CREATE_FLOW_TRANSFER_PENDING_KEY,
|
||||
} from "../../app/(app)/create/utils/anonymousDraftStorage";
|
||||
import { saveDraftToServer } from "../../lib/create/api";
|
||||
import { flushPendingCommunityAvatar } from "../../lib/create/flushPendingCommunityAvatar";
|
||||
import { clearPendingCommunityAvatarFile } from "../../lib/create/pendingCommunityAvatarUpload";
|
||||
import {
|
||||
renderWithProviders as render,
|
||||
screen,
|
||||
waitFor,
|
||||
} from "../utils/test-utils";
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
|
||||
vi.mock("../../lib/create/api", () => ({
|
||||
fetchDraftFromServer: vi.fn().mockResolvedValue(null),
|
||||
saveDraftToServer: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/create/flushPendingCommunityAvatar", () => ({
|
||||
flushPendingCommunityAvatar: vi.fn(),
|
||||
forgetFlushedCommunityAvatarUrl: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/create/pendingCommunityAvatarUpload", () => ({
|
||||
clearPendingCommunityAvatarFile: vi.fn().mockResolvedValue(undefined),
|
||||
readPendingCommunityAvatarFile: vi.fn().mockResolvedValue(null),
|
||||
storePendingCommunityAvatarFile: vi.fn(),
|
||||
}));
|
||||
|
||||
function mockSearchParams(value: string) {
|
||||
vi.mocked(useSearchParams).mockReturnValue(
|
||||
new URLSearchParams(value) as NonNullable<
|
||||
ReturnType<typeof useSearchParams>
|
||||
>,
|
||||
);
|
||||
}
|
||||
|
||||
function StateProbe() {
|
||||
const { state } = useCreateFlow();
|
||||
return (
|
||||
<div>
|
||||
<span data-testid="title">{state.title ?? ""}</span>
|
||||
<span data-testid="avatar">{state.communityAvatarUrl ?? ""}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
describe("PostLoginDraftTransfer", () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
localStorage.setItem(
|
||||
CREATE_FLOW_ANONYMOUS_KEY,
|
||||
JSON.stringify({ title: "Garden Club" }),
|
||||
);
|
||||
localStorage.setItem(CREATE_FLOW_TRANSFER_PENDING_KEY, "1");
|
||||
mockSearchParams("syncDraft=1");
|
||||
vi.mocked(flushPendingCommunityAvatar).mockReset();
|
||||
vi.mocked(saveDraftToServer).mockClear();
|
||||
vi.mocked(clearPendingCommunityAvatarFile).mockClear();
|
||||
});
|
||||
|
||||
it("uploads the staged logo before clearing the anonymous draft", async () => {
|
||||
let draftStillPresent = false;
|
||||
vi.mocked(flushPendingCommunityAvatar).mockImplementation(async () => {
|
||||
draftStillPresent =
|
||||
localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY) != null;
|
||||
return { status: "uploaded", url: "/api/uploads/from-guest" };
|
||||
});
|
||||
|
||||
render(
|
||||
<>
|
||||
<PostLoginDraftTransfer
|
||||
sessionUser={{ id: "user-1", email: "maya@example.com" }}
|
||||
/>
|
||||
<StateProbe />
|
||||
</>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("avatar")).toHaveTextContent(
|
||||
"/api/uploads/from-guest",
|
||||
);
|
||||
});
|
||||
expect(draftStillPresent).toBe(true);
|
||||
expect(localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY)).toBeNull();
|
||||
expect(saveDraftToServer).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
title: "Garden Club",
|
||||
communityAvatarUrl: "/api/uploads/from-guest",
|
||||
}),
|
||||
);
|
||||
expect(clearPendingCommunityAvatarFile).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the staged file when the upload fails", async () => {
|
||||
vi.mocked(flushPendingCommunityAvatar).mockResolvedValue({
|
||||
status: "failed",
|
||||
});
|
||||
|
||||
render(
|
||||
<>
|
||||
<PostLoginDraftTransfer
|
||||
sessionUser={{ id: "user-1", email: "maya@example.com" }}
|
||||
/>
|
||||
<StateProbe />
|
||||
</>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("title")).toHaveTextContent("Garden Club");
|
||||
});
|
||||
expect(clearPendingCommunityAvatarFile).not.toHaveBeenCalled();
|
||||
expect(screen.getByTestId("avatar")).toHaveTextContent("");
|
||||
});
|
||||
});
|
||||
@@ -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`
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { beforeEach, describe, it, expect } from "vitest";
|
||||
import { beforeEach, describe, it, expect, vi } from "vitest";
|
||||
import React, { useEffect } from "react";
|
||||
import {
|
||||
renderWithProviders as render,
|
||||
@@ -9,6 +9,13 @@ import "@testing-library/jest-dom/vitest";
|
||||
import { CommunityReviewScreen } from "../../app/(app)/create/screens/review/CommunityReviewScreen";
|
||||
import { useCreateFlow } from "../../app/(app)/create/context/CreateFlowContext";
|
||||
import { testRouter } from "../mocks/navigation";
|
||||
import { readPendingCommunityAvatarFile } from "../../lib/create/pendingCommunityAvatarUpload";
|
||||
|
||||
vi.mock("../../lib/create/pendingCommunityAvatarUpload", () => ({
|
||||
readPendingCommunityAvatarFile: vi.fn().mockResolvedValue(null),
|
||||
storePendingCommunityAvatarFile: vi.fn(),
|
||||
clearPendingCommunityAvatarFile: vi.fn(),
|
||||
}));
|
||||
|
||||
function ReviewWithTitle({ title }: { title: string }) {
|
||||
const { state, updateState } = useCreateFlow();
|
||||
@@ -22,10 +29,29 @@ 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();
|
||||
testRouter.push.mockReset();
|
||||
vi.mocked(readPendingCommunityAvatarFile).mockReset();
|
||||
vi.mocked(readPendingCommunityAvatarFile).mockResolvedValue(null);
|
||||
});
|
||||
|
||||
it("renders without crashing", () => {
|
||||
@@ -53,7 +79,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 +88,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();
|
||||
});
|
||||
@@ -72,6 +98,33 @@ describe("CommunityReviewScreen", () => {
|
||||
expect(screen.getByText("Garden Club")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows a guest logo staged in the browser on the rule card", async () => {
|
||||
const pending = new File([new Uint8Array([1, 2, 3])], "logo.png", {
|
||||
type: "image/png",
|
||||
});
|
||||
vi.mocked(readPendingCommunityAvatarFile).mockResolvedValue(pending);
|
||||
Object.defineProperty(URL, "createObjectURL", {
|
||||
value: vi.fn(() => "blob:pending-avatar"),
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
Object.defineProperty(URL, "revokeObjectURL", {
|
||||
value: vi.fn(),
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
render(<ReviewWithTitle title="Garden Club" />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole("img", { name: "Garden Club" })).toHaveAttribute(
|
||||
"src",
|
||||
"blob:pending-avatar",
|
||||
);
|
||||
});
|
||||
expect(readPendingCommunityAvatarFile).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("omits the Rule description when the user has not entered community context", () => {
|
||||
render(<ReviewWithTitle title="Garden Club" />);
|
||||
expect(
|
||||
@@ -81,6 +134,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");
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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: {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const clearPendingCommunityAvatarFile = vi.fn();
|
||||
const forgetFlushedCommunityAvatarUrl = vi.fn();
|
||||
|
||||
vi.mock("../../lib/create/pendingCommunityAvatarUpload", () => ({
|
||||
clearPendingCommunityAvatarFile: () => clearPendingCommunityAvatarFile(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/create/flushPendingCommunityAvatar", () => ({
|
||||
forgetFlushedCommunityAvatarUrl: () => forgetFlushedCommunityAvatarUrl(),
|
||||
}));
|
||||
|
||||
import {
|
||||
CREATE_FLOW_ANONYMOUS_KEY,
|
||||
CREATE_FLOW_TRANSFER_PENDING_KEY,
|
||||
clearAnonymousCreateFlowStorage,
|
||||
} from "../../app/(app)/create/utils/anonymousDraftStorage";
|
||||
|
||||
describe("clearAnonymousCreateFlowStorage", () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
clearPendingCommunityAvatarFile.mockReset();
|
||||
forgetFlushedCommunityAvatarUrl.mockReset();
|
||||
localStorage.setItem(CREATE_FLOW_ANONYMOUS_KEY, "{\"title\":\"Garden\"}");
|
||||
localStorage.setItem(CREATE_FLOW_TRANSFER_PENDING_KEY, "1");
|
||||
});
|
||||
|
||||
it("removes the draft and the staged logo", () => {
|
||||
clearAnonymousCreateFlowStorage();
|
||||
expect(localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY)).toBeNull();
|
||||
expect(localStorage.getItem(CREATE_FLOW_TRANSFER_PENDING_KEY)).toBeNull();
|
||||
expect(clearPendingCommunityAvatarFile).toHaveBeenCalledTimes(1);
|
||||
expect(forgetFlushedCommunityAvatarUrl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("keeps the staged logo when a transfer upload still needs to retry", () => {
|
||||
clearAnonymousCreateFlowStorage({ preservePendingAvatar: true });
|
||||
expect(localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY)).toBeNull();
|
||||
expect(clearPendingCommunityAvatarFile).not.toHaveBeenCalled();
|
||||
expect(forgetFlushedCommunityAvatarUrl).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -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",
|
||||
);
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { CreateFlowUploadValidationError } from "../../lib/create/createFlowUploadValidation";
|
||||
|
||||
const readPendingCommunityAvatarFile = vi.fn();
|
||||
const clearPendingCommunityAvatarFile = vi.fn();
|
||||
const uploadCreateFlowFile = vi.fn();
|
||||
|
||||
vi.mock("../../lib/create/pendingCommunityAvatarUpload", () => ({
|
||||
readPendingCommunityAvatarFile: (...args: unknown[]) =>
|
||||
readPendingCommunityAvatarFile(...args),
|
||||
clearPendingCommunityAvatarFile: (...args: unknown[]) =>
|
||||
clearPendingCommunityAvatarFile(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/create/uploadToServer", () => ({
|
||||
uploadCreateFlowFile: (...args: unknown[]) => uploadCreateFlowFile(...args),
|
||||
}));
|
||||
|
||||
import {
|
||||
flushPendingCommunityAvatar,
|
||||
forgetFlushedCommunityAvatarUrl,
|
||||
stateWithPendingCommunityAvatar,
|
||||
} from "../../lib/create/flushPendingCommunityAvatar";
|
||||
|
||||
const pending = new File([new Uint8Array([1, 2, 3])], "logo.png", {
|
||||
type: "image/png",
|
||||
});
|
||||
|
||||
describe("flushPendingCommunityAvatar", () => {
|
||||
beforeEach(() => {
|
||||
readPendingCommunityAvatarFile.mockReset();
|
||||
clearPendingCommunityAvatarFile.mockReset();
|
||||
uploadCreateFlowFile.mockReset();
|
||||
clearPendingCommunityAvatarFile.mockResolvedValue(undefined);
|
||||
forgetFlushedCommunityAvatarUrl();
|
||||
});
|
||||
|
||||
it("does nothing when no file is staged", async () => {
|
||||
readPendingCommunityAvatarFile.mockResolvedValue(null);
|
||||
await expect(flushPendingCommunityAvatar()).resolves.toEqual({
|
||||
status: "none",
|
||||
});
|
||||
expect(uploadCreateFlowFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uploads once and remembers the url after the file is cleared", async () => {
|
||||
readPendingCommunityAvatarFile
|
||||
.mockResolvedValueOnce(pending)
|
||||
.mockResolvedValue(null);
|
||||
uploadCreateFlowFile.mockResolvedValue({ url: "/api/uploads/logo" });
|
||||
|
||||
const [first, second] = await Promise.all([
|
||||
flushPendingCommunityAvatar(),
|
||||
flushPendingCommunityAvatar(),
|
||||
]);
|
||||
|
||||
expect(first).toEqual({ status: "uploaded", url: "/api/uploads/logo" });
|
||||
expect(second).toEqual(first);
|
||||
expect(uploadCreateFlowFile).toHaveBeenCalledTimes(1);
|
||||
expect(clearPendingCommunityAvatarFile).toHaveBeenCalledTimes(1);
|
||||
|
||||
await expect(flushPendingCommunityAvatar()).resolves.toEqual({
|
||||
status: "uploaded",
|
||||
url: "/api/uploads/logo",
|
||||
});
|
||||
expect(uploadCreateFlowFile).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("drops an invalid file and leaves a transient failure staged", async () => {
|
||||
readPendingCommunityAvatarFile.mockResolvedValue(pending);
|
||||
uploadCreateFlowFile.mockRejectedValueOnce(
|
||||
new CreateFlowUploadValidationError("tooLarge"),
|
||||
);
|
||||
|
||||
await expect(flushPendingCommunityAvatar()).resolves.toEqual({
|
||||
status: "invalid",
|
||||
});
|
||||
expect(clearPendingCommunityAvatarFile).toHaveBeenCalledTimes(1);
|
||||
|
||||
uploadCreateFlowFile.mockRejectedValueOnce(new Error("network"));
|
||||
await expect(flushPendingCommunityAvatar()).resolves.toEqual({
|
||||
status: "failed",
|
||||
});
|
||||
expect(clearPendingCommunityAvatarFile).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("copies a successful upload onto publish state and blocks on failure", async () => {
|
||||
readPendingCommunityAvatarFile.mockResolvedValue(pending);
|
||||
uploadCreateFlowFile.mockResolvedValue({ url: "/api/uploads/logo" });
|
||||
|
||||
await expect(
|
||||
stateWithPendingCommunityAvatar({ title: "Garden" }),
|
||||
).resolves.toEqual({
|
||||
ok: true,
|
||||
state: { title: "Garden", communityAvatarUrl: "/api/uploads/logo" },
|
||||
});
|
||||
|
||||
forgetFlushedCommunityAvatarUrl();
|
||||
uploadCreateFlowFile.mockRejectedValueOnce(new Error("network"));
|
||||
await expect(
|
||||
stateWithPendingCommunityAvatar({
|
||||
title: "Garden",
|
||||
communityAvatarFileName: "logo.png",
|
||||
}),
|
||||
).resolves.toEqual({ ok: false, reason: "upload_failed" });
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import type { CreateFlowState } from "../../../app/(app)/create/types";
|
||||
import { useCreateFlowFinalize } from "../../../app/(app)/create/hooks/useCreateFlowFinalize";
|
||||
import { publishRule, updatePublishedRule } from "../../../lib/create/api";
|
||||
import { buildPublishPayload } from "../../../lib/create/buildPublishPayload";
|
||||
import { stateWithPendingCommunityAvatar } from "../../../lib/create/flushPendingCommunityAvatar";
|
||||
import messages from "../../../messages/en/index";
|
||||
import { writeLastPublishedRule } from "../../../lib/create/lastPublishedRule";
|
||||
import { CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY } from "../../../lib/create/pendingKeepRuleLogin";
|
||||
import {
|
||||
@@ -24,6 +27,13 @@ vi.mock("../../../lib/create/api", () => ({
|
||||
updatePublishedRule: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../../lib/create/flushPendingCommunityAvatar", () => ({
|
||||
stateWithPendingCommunityAvatar: vi.fn(async (state: CreateFlowState) => ({
|
||||
ok: true as const,
|
||||
state,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("../../../lib/create/lastPublishedRule", () => ({
|
||||
writeLastPublishedRule: vi.fn(),
|
||||
}));
|
||||
@@ -41,6 +51,10 @@ describe("useCreateFlowFinalize", () => {
|
||||
vi.mocked(publishRule).mockReset();
|
||||
vi.mocked(updatePublishedRule).mockReset();
|
||||
vi.mocked(writeLastPublishedRule).mockReset();
|
||||
vi.mocked(stateWithPendingCommunityAvatar).mockReset();
|
||||
vi.mocked(stateWithPendingCommunityAvatar).mockImplementation(
|
||||
async (state) => ({ ok: true as const, state }),
|
||||
);
|
||||
router.push.mockReset();
|
||||
updateState.mockReset();
|
||||
openLogin.mockReset();
|
||||
@@ -148,6 +162,82 @@ describe("useCreateFlowFinalize", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("publishes a guest logo that was only staged in the browser", async () => {
|
||||
vi.mocked(publishRule).mockResolvedValue({
|
||||
ok: true,
|
||||
id: "guest-rule-id",
|
||||
title: "Published title",
|
||||
});
|
||||
vi.mocked(stateWithPendingCommunityAvatar).mockResolvedValue({
|
||||
ok: true,
|
||||
state: {
|
||||
communityAvatarFileName: "logo.png",
|
||||
communityAvatarUrl: "/api/uploads/guest-logo",
|
||||
},
|
||||
});
|
||||
vi.mocked(buildPublishPayload).mockImplementationOnce((draft) => ({
|
||||
ok: true as const,
|
||||
title: "Published title",
|
||||
summary: "Published summary",
|
||||
document: {
|
||||
communityAvatarUrl: draft.communityAvatarUrl,
|
||||
},
|
||||
}));
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useCreateFlowFinalize({
|
||||
state: { communityAvatarFileName: "logo.png" },
|
||||
router,
|
||||
openLogin,
|
||||
updateState,
|
||||
loginReturnPath: "/create/final-review",
|
||||
sessionUser: null,
|
||||
onGuestPublished,
|
||||
}),
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.finalize();
|
||||
});
|
||||
|
||||
expect(publishRule).toHaveBeenCalledWith({
|
||||
title: "Published title",
|
||||
summary: "Published summary",
|
||||
document: { communityAvatarUrl: "/api/uploads/guest-logo" },
|
||||
});
|
||||
expect(updateState).toHaveBeenCalledWith({
|
||||
communityAvatarUrl: "/api/uploads/guest-logo",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not publish when the staged logo fails to upload", async () => {
|
||||
vi.mocked(stateWithPendingCommunityAvatar).mockResolvedValue({
|
||||
ok: false,
|
||||
reason: "upload_failed",
|
||||
});
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useCreateFlowFinalize({
|
||||
state: { communityAvatarFileName: "logo.png" },
|
||||
router,
|
||||
openLogin,
|
||||
updateState,
|
||||
loginReturnPath: "/create/final-review",
|
||||
sessionUser: null,
|
||||
}),
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.finalize();
|
||||
});
|
||||
|
||||
expect(publishRule).not.toHaveBeenCalled();
|
||||
expect(result.current.publishBannerMessage).toBe(
|
||||
messages.create.upload.errors.generic,
|
||||
);
|
||||
expect(result.current.isPublishing).toBe(false);
|
||||
});
|
||||
|
||||
it("hints to claim later when a guest publishes without stakeholder emails", async () => {
|
||||
vi.mocked(publishRule).mockResolvedValue({
|
||||
ok: 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);
|
||||
});
|
||||
});
|
||||
@@ -80,6 +80,39 @@ describe("POST /api/uploads", () => {
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("returns 401 when a guest uploads an attachment", async () => {
|
||||
getSessionUserMock.mockResolvedValueOnce(null);
|
||||
const res = await POST(
|
||||
multipartRequest({
|
||||
purpose: "customMethodAttachment",
|
||||
fileName: "notes.pdf",
|
||||
fileContent: "hello",
|
||||
contentType: "application/pdf",
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("lets a guest submit a community logo and then validates it", async () => {
|
||||
getSessionUserMock.mockResolvedValueOnce(null);
|
||||
const res = await POST(
|
||||
multipartRequest({
|
||||
purpose: "communityAvatar",
|
||||
fileName: "empty.png",
|
||||
fileContent: "",
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
expect(res.status).toBe(400);
|
||||
const body = (await res.json()) as {
|
||||
error: { code: string };
|
||||
details?: { reason?: string };
|
||||
};
|
||||
expect(body.error.code).toBe("validation_error");
|
||||
expect(body.details?.reason).toBe("empty");
|
||||
});
|
||||
|
||||
it("returns 500 when UPLOAD_ROOT is unset", async () => {
|
||||
getUploadRootFromEnvMock.mockReturnValueOnce(null);
|
||||
const res = await POST(
|
||||
|
||||
Reference in new issue
Block a user