Skip setup questions on the template path and collect name, photo, and description without recommendations.

Customize opens a dialog then walks the template decks; Use without changes lands on final review with Has Name Field. Template cards stay first, the engine is not called, and the catalog no longer shows a recommended tag.
This commit is contained in:
adilallo committed 2026-11-09 17:34:33 -07:00
1 parent 53d236d0d5
commit 6498d52541
37 files changed
+1450 -733

No files matched your search

@@ -0,0 +1,186 @@
"use client";
import {
useCallback,
useEffect,
useRef,
useState,
type ChangeEvent,
type RefObject,
} from "react";
import { fetchAuthSession } from "../../../../lib/create/api";
import {
COMMUNITY_AVATAR_ACCEPT,
messageKeyForCreateFlowUploadReason,
validateCreateFlowUploadFile,
} from "../../../../lib/create/createFlowUploadValidation";
import {
clearPendingCommunityAvatarFile,
storePendingCommunityAvatarFile,
} from "../../../../lib/create/pendingCommunityAvatarUpload";
import {
createFlowUploadFailureMessageKey,
uploadCreateFlowFile,
} from "../../../../lib/create/uploadToServer";
import { useMessages, useTranslation } from "../../../contexts/MessagesContext";
import { useCreateFlow } from "../context/CreateFlowContext";
function hasCommunityAvatarUrl(url: string | undefined): boolean {
return typeof url === "string" && url.trim().length > 0;
}
/**
* Pick and store a community logo for the create flow. Signed-in users upload
* immediately; guests keep the file in IndexedDB until they sign in.
*
* @example
* const avatar = useCommunityAvatarUpload();
* <input ref={avatar.fileInputRef} type="file" onChange={avatar.handleFileChange} />
*/
export function useCommunityAvatarUpload(): {
fileInputRef: RefObject<HTMLInputElement | null>;
accept: string;
busy: boolean;
errorMessage: string | null;
displaySrc: string | null;
fileName: string | undefined;
handlePickFile: () => void;
handleFileChange: (_event: ChangeEvent<HTMLInputElement>) => Promise<void>;
} {
const m = useMessages();
const u = m.create.community.communityUpload;
const tUpload = useTranslation("create.upload");
const { markCreateFlowInteraction, state, updateState } = useCreateFlow();
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);
useEffect(() => {
let cancelled = false;
void fetchAuthSession().then(({ user }) => {
if (!cancelled) setSignedIn(Boolean(user));
});
return () => {
cancelled = true;
};
}, []);
useEffect(
() => () => {
if (localPreviewUrl) URL.revokeObjectURL(localPreviewUrl);
},
[localPreviewUrl],
);
const serverAvatarUrl = hasCommunityAvatarUrl(state.communityAvatarUrl)
? state.communityAvatarUrl!.trim()
: null;
useEffect(() => {
if (serverAvatarUrl) {
setLocalPreviewUrl((prev) => {
if (prev) URL.revokeObjectURL(prev);
return null;
});
}
}, [serverAvatarUrl]);
const resolveUploadError = useCallback(
(err: unknown) => {
const key = createFlowUploadFailureMessageKey(err);
if (key === "errors.tooLarge") return u.fileTooLarge;
return tUpload(key);
},
[tUpload, u.fileTooLarge],
);
const handleFileChange = useCallback(
async (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
e.target.value = "";
if (!file) return;
markCreateFlowInteraction();
setErrorMessage(null);
if (signedIn === true) {
setBusy(true);
try {
const { url } = await uploadCreateFlowFile(file, "communityAvatar");
setLocalPreviewUrl((prev) => {
if (prev) URL.revokeObjectURL(prev);
return null;
});
setLocalFileName(file.name);
updateState({
communityAvatarUrl: url,
communityAvatarFileName: file.name,
});
} catch (err) {
setErrorMessage(resolveUploadError(err));
} finally {
setBusy(false);
}
return;
}
const validated = await validateCreateFlowUploadFile(
file,
"communityAvatar",
);
if (validated.ok === false) {
setErrorMessage(
validated.reason === "tooLarge"
? u.fileTooLarge
: tUpload(messageKeyForCreateFlowUploadReason(validated.reason)),
);
return;
}
try {
await storePendingCommunityAvatarFile(file);
setLocalPreviewUrl((prev) => {
if (prev) URL.revokeObjectURL(prev);
return URL.createObjectURL(file);
});
setLocalFileName(file.name);
updateState({ communityAvatarFileName: file.name });
} catch {
await clearPendingCommunityAvatarFile().catch(() => undefined);
setErrorMessage(tUpload("errors.generic"));
}
},
[
markCreateFlowInteraction,
resolveUploadError,
signedIn,
tUpload,
u.fileTooLarge,
updateState,
],
);
const handlePickFile = useCallback(() => {
if (!busy) fileInputRef.current?.click();
}, [busy]);
const displaySrc = serverAvatarUrl ?? localPreviewUrl;
const fileName =
localFileName ??
(typeof state.communityAvatarFileName === "string" &&
state.communityAvatarFileName.trim().length > 0
? state.communityAvatarFileName.trim()
: undefined);
return {
fileInputRef,
accept: COMMUNITY_AVATAR_ACCEPT,
busy,
errorMessage,
displaySrc,
fileName,
handlePickFile,
handleFileChange,
};
}
@@ -34,12 +34,10 @@ const blurActiveElement = (): void => {
*
* Resolves the active step from `/create/{screenId}` via
* {@link parseCreateFlowScreenFromPathname} (flowSteps). Footer Back uses
* {@link resolveCreateFlowBackTarget}: template **Use without changes** that
* still needs identity (direct from a template) walks name / description /
* photo, then Back from `community-name` returns to
* `/create/review-template/{slug}`. In-flow picks (`?fromFlow=1`) skip
* identity and land on `final-review`; Back from that step returns
* to the template instead of `conflict-management`.
* {@link resolveCreateFlowBackTarget}: template **Customize** walks values
* then the four decks, and Back from `core-values` returns to
* `/create/review-template/{slug}`. **Use without changes** lands on
* `final-review`; Back from that step returns to the template.
*
* Template review footer Back uses {@link buildTemplateReviewHref}’s
* `?fromFlow=1` marker (and persisted `templateReviewEntryFromCreateFlow`) so
@@ -87,14 +85,13 @@ export function useCreateFlowNavigation(
updateState,
]);
const identityOnly =
state.pendingTemplateAction?.mode === "useWithoutChanges";
const templatePathMode = state.pendingTemplateAction?.mode;
const navigationOptions = useMemo(
(): CreateFlowNavigationOptions => ({
skipCommunitySave: options?.skipCommunitySave,
useWithoutChangesIdentityOnly: identityOnly,
templatePathMode,
}),
[options?.skipCommunitySave, identityOnly],
[options?.skipCommunitySave, templatePathMode],
);
const nextStep = getNextStep(validStep, navigationOptions);
@@ -8,7 +8,11 @@ import {
groupAnswersForRecommendations,
type RecommendationSection,
} from "./useFacetRecommendations";
import { deckData } from "../../../../lib/create/deckRecommend";
import { deckData, templateDeck } from "../../../../lib/create/deckRecommend";
import {
templateCardIdsForDeck,
templatePathFromState,
} from "../../../../lib/create/templatePath";
import { useCreateFlow } from "../context/CreateFlowContext";
import { useMessages } from "../../../contexts/MessagesContext";
@@ -30,6 +34,8 @@ function orderByIds<T extends { id: string }>(
/**
* Deck order and the compact stack come from the job rule. Compact shows
* at most seven recommended cards. Selected cards still pin into the stack.
* On the template path the engine is not called: template cards first, then
* the rest of the deck, with no tag and no seven-card cut.
*/
export function useMethodCardDeckOrdering(
section: RecommendationSection,
@@ -38,15 +44,32 @@ export function useMethodCardDeckOrdering(
) {
const { state } = useCreateFlow();
const copy = useMessages().create.customRule.recommendations;
const compactLimit = deckData(section).config.displayLimit;
const templateSlug = templatePathFromState(state)?.slug;
const engineCompactLimit = deckData(section).config.displayLimit;
const answers = useMemo(
() => groupAnswersForRecommendations(state),
[state],
);
const deck = useMemo(
() => deriveCompactCards(section, answers, compactLimit),
[section, answers, compactLimit],
);
const deck = useMemo(() => {
if (templateSlug) {
const templateIds = templateCardIdsForDeck(templateSlug, section);
const firstIds =
templateIds.length > 0 ? templateIds : [...selectedIds];
const ordered = templateDeck(deckData(section), firstIds);
const orderedIds = [...ordered.first, ...ordered.rest];
return {
compactCardIds: orderedIds,
recommendedIds: new Set<string>(),
orderedIds,
fallback: true,
recommendedById: new Map(),
};
}
return deriveCompactCards(section, answers, engineCompactLimit);
}, [answers, engineCompactLimit, section, selectedIds, templateSlug]);
const compactLimit = templateSlug
? deck.orderedIds.length
: engineCompactLimit;
const rankedMethods = useMemo(
() => orderByIds(methods, deck.orderedIds),
@@ -4,6 +4,7 @@ import { useEffect, useMemo } from "react";
import { buildFacetQueryString } from "../../../../lib/create/buildFacetQueryString";
import { METHOD_FACET_API_SECTION_IDS } from "../../../../lib/create/customRuleFacets";
import { loadFacetScores } from "../../../../lib/create/facetRecommendationsLoad";
import { isTemplateCreatePath } from "../../../../lib/create/templatePath";
import { useCreateFlow } from "../context/CreateFlowContext";
/**
@@ -18,10 +19,12 @@ export function usePrefetchMethodFacetRecommendations(): void {
[state],
);
const skipEngine = isTemplateCreatePath(state);
useEffect(() => {
if (queryString.length === 0) return;
if (skipEngine || queryString.length === 0) return;
for (const section of METHOD_FACET_API_SECTION_IDS) {
void loadFacetScores(section, queryString);
}
}, [queryString]);
}, [queryString, skipEngine]);
}
+126 -131
View File
@@ -1,10 +1,14 @@
"use client";
import { useCallback, useMemo, useState } from "react";
import { buildTemplateCustomizePrefill } from "../../../../lib/create/applyTemplatePrefill";
import {
buildTemplateCustomizePrefill,
templatePresetDetailsFromPrefill,
} from "../../../../lib/create/applyTemplatePrefill";
import { loadTemplateReviewBySlug } from "../../../../lib/create/loadTemplateReviewBySlug";
import { methodSectionsPinsForHydratedSelections } from "../../../../lib/create/publishedDocumentToCreateFlowState";
import { stripCustomRuleSelectionFields } from "../../../../lib/create/stripCustomRuleSelectionFields";
import { templateChipCounts } from "../../../../lib/create/templatePath";
import messages from "../../../../messages/en/index";
import type {
CreateFlowContextValue,
@@ -16,6 +20,20 @@ type AppRouterLike = { push: (_href: string) => void };
type UpdateState = CreateFlowContextValue["updateState"];
type ReplaceStateFn = CreateFlowContextValue["replaceState"];
export type TemplateCustomizeDialogModel = {
slug: string;
templateTitle: string;
body: unknown;
valuesCount: number;
cardsCount: number;
};
export type TemplateCustomizeFields = {
title: string;
communityContext: string;
communityLocation: string;
};
export type UseTemplateReviewActionsResult = {
/** True iff the current pathname is a template-review route (locale/basePath tolerant). */
isTemplateReviewRoute: boolean;
@@ -27,47 +45,43 @@ export type UseTemplateReviewActionsResult = {
templateReviewApplyError: string | null;
setTemplateReviewApplyError: (_message: string | null) => void;
/**
* Customize: apply the template's selections onto state and route to
* `/create/core-values` (if community name is set) or `/create/informational`
* with a `pendingTemplateAction` pin so `/create/review` can later replace
* itself with `/create/core-values`. A named community skips setup
* questions, so leftover setup answers are dropped and cannot change
* suggested cards.
* Customize: open the name / photo / description dialog. Continue applies
* the template's cards and routes to `/create/core-values`. Setup questions
* are skipped.
*/
handleCustomize: () => Promise<void>;
/**
* Use without changes: scrub any prior customize picks, seed core values +
* method-card selections from the template body (same id mapping as
* Customize) so drilling from final-review via + shows selected cards, drop
* the Values row from `state.sections`. Direct template entry routes to
* `/create/community-name` with a pin so Next/Back collect only name →
* description → photo, and drops leftover setup answers along with the
* other identity fields. In-flow (`?fromFlow=1`, community steps already
* done) routes to `/create/final-review` and keeps those answers.
* Use without changes: seed the template's cards and go to final review.
* Direct entry clears leftover identity so the Rule card can collect name,
* photo, and description. In-flow keeps the community answers already given.
*/
handleUseWithoutChanges: () => Promise<void>;
customizeDialog: TemplateCustomizeDialogModel | null;
closeCustomizeDialog: () => void;
confirmCustomizeDialog: (_fields: TemplateCustomizeFields) => void;
};
function sectionsFromTemplateBody(
body: unknown,
): Record<string, unknown>[] | null {
if (!body || typeof body !== "object" || Array.isArray(body)) return null;
const sectionsRaw = (body as { sections?: unknown }).sections;
if (!Array.isArray(sectionsRaw) || sectionsRaw.length === 0) return null;
return sectionsRaw as Record<string, unknown>[];
}
/**
* Encapsulates the two template-review footer actions (Customize / Use
* without changes) plus the small amount of state they share (in-flight
* flag, error banner, parsed slug). Called from `CreateFlowLayoutClient`
* once; extracting it here keeps the layout shell focused on rendering
* rather than orchestrating template fetch + state seeding.
* without changes) plus the Customize dialog they share.
*
* @example
* const {
* isTemplateReviewRoute,
* templateReviewSlug,
* isApplyingTemplate,
* templateReviewApplyError,
* setTemplateReviewApplyError,
* handleCustomize,
* handleUseWithoutChanges,
* } = useTemplateReviewActions({
* pathname, state, updateState, replaceState, router,
* fromCreateWizard, markCreateFlowInteraction,
* });
* customizeDialog,
* closeCustomizeDialog,
* confirmCustomizeDialog,
* } = useTemplateReviewActions({ ... });
*/
export function useTemplateReviewActions({
pathname,
@@ -95,6 +109,8 @@ export function useTemplateReviewActions({
const [templateReviewApplyError, setTemplateReviewApplyError] = useState<
string | null
>(null);
const [customizeDialog, setCustomizeDialog] =
useState<TemplateCustomizeDialogModel | null>(null);
const templateReviewSlug = useMemo(() => {
const m = pathname?.match(/\/create\/review-template\/([^/?#]+)/);
@@ -116,42 +132,64 @@ export function useTemplateReviewActions({
setTemplateReviewApplyError(loaded.message);
return;
}
const prefill = buildTemplateCustomizePrefill(
loaded.template.body,
templateReviewSlug,
);
const pinPatch = methodSectionsPinsForHydratedSelections(prefill);
const hasCommunityName =
typeof state.title === "string" && state.title.trim().length > 0;
updateState({
...prefill,
methodSectionsPinCommitted: {
...state.methodSectionsPinCommitted,
...pinPatch,
},
templateReviewBackSlug: undefined,
...(hasCommunityName
? { pendingTemplateAction: undefined, setupTraits: undefined }
: {
pendingTemplateAction: {
slug: templateReviewSlug,
mode: "customize",
},
}),
const counts = templateChipCounts(templateReviewSlug);
setCustomizeDialog({
slug: templateReviewSlug,
templateTitle: loaded.template.title,
body: loaded.template.body,
valuesCount: counts?.values ?? 0,
cardsCount: counts?.cards ?? 0,
});
router.push(
hasCommunityName
? createFlowStepPath("core-values")
: createFlowStepPath("informational"),
);
}, [
router,
state.methodSectionsPinCommitted,
state.title,
templateReviewSlug,
updateState,
markCreateFlowInteraction,
]);
}, [markCreateFlowInteraction, templateReviewSlug]);
const closeCustomizeDialog = useCallback(() => {
setCustomizeDialog(null);
}, []);
const confirmCustomizeDialog = useCallback(
(fields: TemplateCustomizeFields) => {
if (!customizeDialog) return;
markCreateFlowInteraction();
const prefill = buildTemplateCustomizePrefill(
customizeDialog.body,
customizeDialog.slug,
);
const details = templatePresetDetailsFromPrefill(prefill);
const pinPatch = methodSectionsPinsForHydratedSelections(prefill);
const title = fields.title.trim();
const communityContext = fields.communityContext.trim();
const communityLocation = fields.communityLocation.trim();
updateState({
...prefill,
...details,
title: title.length > 0 ? title : undefined,
communityContext:
communityContext.length > 0 ? communityContext : undefined,
summary: communityContext.length > 0 ? communityContext : undefined,
communityLocation:
communityLocation.length > 0 ? communityLocation : undefined,
methodSectionsPinCommitted: {
...state.methodSectionsPinCommitted,
...pinPatch,
},
templateReviewBackSlug: customizeDialog.slug,
setupTraits: undefined,
pendingTemplateAction: {
slug: customizeDialog.slug,
mode: "customize",
},
});
setCustomizeDialog(null);
router.push(createFlowStepPath("core-values"));
},
[
customizeDialog,
markCreateFlowInteraction,
router,
state.methodSectionsPinCommitted,
updateState,
],
);
const handleUseWithoutChanges = useCallback(async () => {
if (!templateReviewSlug) return;
@@ -165,33 +203,21 @@ export function useTemplateReviewActions({
return;
}
const { template } = loaded;
const doc = template.body;
if (!doc || typeof doc !== "object" || Array.isArray(doc)) {
setTemplateReviewApplyError(
messages.create.templateReview.errors.applyFailed,
);
return;
}
const sectionsRaw = (doc as { sections?: unknown }).sections;
const sections = Array.isArray(sectionsRaw)
? (sectionsRaw as Record<string, unknown>[])
: [];
if (sections.length === 0) {
const sections = sectionsFromTemplateBody(template.body);
if (!sections) {
setTemplateReviewApplyError(
messages.create.templateReview.errors.applyFailed,
);
return;
}
// Atomic read-modify-write: strip prior custom-rule picks and merge template
// body in one replaceState so method ids are never lost across React batching
// (reset + update separately could leave selections undefined in Strict Mode).
replaceState((prev) => {
const base = stripCustomRuleSelectionFields(prev);
const customizePrefill = buildTemplateCustomizePrefill(
doc,
template.body,
templateReviewSlug ?? undefined,
);
const details = templatePresetDetailsFromPrefill(customizePrefill);
const hasValuesSeed =
customizePrefill.selectedCoreValueIds !== undefined;
@@ -209,68 +235,34 @@ export function useTemplateReviewActions({
const seeded: CreateFlowState = {
...base,
...(hasValuesSeed
? {
selectedCoreValueIds: customizePrefill.selectedCoreValueIds,
coreValuesChipsSnapshot:
customizePrefill.coreValuesChipsSnapshot,
}
: {}),
...(customizePrefill.selectedCommunicationMethodIds !== undefined
? {
selectedCommunicationMethodIds:
customizePrefill.selectedCommunicationMethodIds,
}
: {}),
...(customizePrefill.selectedMembershipMethodIds !== undefined
? {
selectedMembershipMethodIds:
customizePrefill.selectedMembershipMethodIds,
}
: {}),
...(customizePrefill.selectedDecisionApproachIds !== undefined
? {
selectedDecisionApproachIds:
customizePrefill.selectedDecisionApproachIds,
}
: {}),
...(customizePrefill.selectedConflictManagementIds !== undefined
? {
selectedConflictManagementIds:
customizePrefill.selectedConflictManagementIds,
}
: {}),
...customizePrefill,
...details,
sections: sectionsWithoutValues,
methodSectionsPinCommitted: pinPatch,
templateReviewBackSlug: templateReviewSlug,
};
if (fromCreateWizard) {
return {
...seeded,
pendingTemplateAction: undefined,
};
}
return {
...seeded,
title: undefined,
communityContext: undefined,
communityAvatarUrl: undefined,
currentStep: undefined,
templateReviewEntryFromCreateFlow: undefined,
setupTraits: undefined,
pendingTemplateAction: {
slug: templateReviewSlug,
mode: "useWithoutChanges",
},
};
if (fromCreateWizard) {
return seeded;
}
return {
...seeded,
title: undefined,
communityContext: undefined,
communityLocation: undefined,
communityAvatarUrl: undefined,
communityAvatarFileName: undefined,
currentStep: undefined,
templateReviewEntryFromCreateFlow: undefined,
};
});
router.push(
fromCreateWizard
? createFlowStepPath("final-review")
: createFlowStepPath("community-name"),
);
router.push(createFlowStepPath("final-review"));
}, [
fromCreateWizard,
markCreateFlowInteraction,
@@ -287,5 +279,8 @@ export function useTemplateReviewActions({
setTemplateReviewApplyError,
handleCustomize,
handleUseWithoutChanges,
customizeDialog,
closeCustomizeDialog,
confirmCustomizeDialog,
};
}