Merge pull request 'Skip setup questions on the template path' (#101) from adilallo/fix/CR-296-template-path into main

Reviewed-on: #101
This commit was merged in pull request #101.
This commit is contained in:
an.di committed 2026-11-10 02:04:47 +00:00
commit 642551064c
38 files changed
+1529 -736

No files matched your search

+39 -3
View File
@@ -15,6 +15,7 @@ import { useCreateFlowExit } from "./hooks/useCreateFlowExit";
import { usePrefetchMethodFacetRecommendations } from "./hooks/usePrefetchMethodFacetRecommendations"; import { usePrefetchMethodFacetRecommendations } from "./hooks/usePrefetchMethodFacetRecommendations";
import { useCreateFlowFinalize } from "./hooks/useCreateFlowFinalize"; import { useCreateFlowFinalize } from "./hooks/useCreateFlowFinalize";
import { useTemplateReviewActions } from "./hooks/useTemplateReviewActions"; import { useTemplateReviewActions } from "./hooks/useTemplateReviewActions";
import { TemplateCustomizeDialog } from "./components/TemplateCustomizeDialog";
import { useCompletedRuleShareExport } from "./hooks/useCompletedRuleShareExport"; import { useCompletedRuleShareExport } from "./hooks/useCompletedRuleShareExport";
import CreateFlowFooter from "../../components/navigation/CreateFlowFooter"; import CreateFlowFooter from "../../components/navigation/CreateFlowFooter";
import CreateFlowTopNav from "../../components/navigation/CreateFlowTopNav"; import CreateFlowTopNav from "../../components/navigation/CreateFlowTopNav";
@@ -24,6 +25,7 @@ import {
CREATE_FLOW_REVIEW_RETURN_QUERY_KEY, CREATE_FLOW_REVIEW_RETURN_QUERY_KEY,
getNextStep, getNextStep,
parseReviewReturnSearchParam, parseReviewReturnSearchParam,
templatePathSkippedCommunityRedirect,
shouldOfferCreateFlowSaveAndExit, shouldOfferCreateFlowSaveAndExit,
isDirectTemplateReviewEntry, isDirectTemplateReviewEntry,
createFlowStepUsesSelectSplitScroll, createFlowStepUsesSelectSplitScroll,
@@ -100,6 +102,7 @@ import {
EMPTY_SETUP_TRAITS, EMPTY_SETUP_TRAITS,
hasTickedSetupTrait, hasTickedSetupTrait,
} from "../../../lib/create/setupTraits"; } from "../../../lib/create/setupTraits";
import { templatePathFromState } from "../../../lib/create/templatePath";
import { useAuthModal } from "../../contexts/AuthModalContext"; import { useAuthModal } from "../../contexts/AuthModalContext";
import { useMessages, useTranslation } from "../../contexts/MessagesContext"; import { useMessages, useTranslation } from "../../contexts/MessagesContext";
import { PostLoginDraftTransfer } from "./PostLoginDraftTransfer"; import { PostLoginDraftTransfer } from "./PostLoginDraftTransfer";
@@ -323,6 +326,9 @@ function CreateFlowLayoutContent({
setTemplateReviewApplyError, setTemplateReviewApplyError,
handleCustomize: handleCustomizeTemplate, handleCustomize: handleCustomizeTemplate,
handleUseWithoutChanges: handleUseTemplateWithoutChanges, handleUseWithoutChanges: handleUseTemplateWithoutChanges,
customizeDialog,
closeCustomizeDialog,
confirmCustomizeDialog,
} = useTemplateReviewActions({ } = useTemplateReviewActions({
pathname, pathname,
state, state,
@@ -420,7 +426,18 @@ function CreateFlowLayoutContent({
await runAuthenticatedExit(opts); await runAuthenticatedExit(opts);
}; };
const templatePathRedirect = templatePathSkippedCommunityRedirect(
currentStep,
templatePathFromState(state)?.mode,
);
useEffect(() => { useEffect(() => {
if (!templatePathRedirect) return;
router.replace(createFlowStepPath(templatePathRedirect));
}, [router, templatePathRedirect]);
useEffect(() => {
if (templatePathRedirect) return;
if ( if (
sessionResolved && sessionResolved &&
sessionUser && sessionUser &&
@@ -428,7 +445,7 @@ function CreateFlowLayoutContent({
) { ) {
router.replace(CREATE_ROUTES.review); router.replace(CREATE_ROUTES.review);
} }
}, [sessionResolved, sessionUser, currentStep, router]); }, [sessionResolved, sessionUser, currentStep, router, templatePathRedirect]);
useEffect(() => { useEffect(() => {
clearAttempted(); clearAttempted();
@@ -876,6 +893,25 @@ function CreateFlowLayoutContent({
backdropVariant="blurredYellow" backdropVariant="blurredYellow"
ariaLabel={messages.create.topNav.leaveConfirmTitle} ariaLabel={messages.create.topNav.leaveConfirmTitle}
/> />
<TemplateCustomizeDialog
isOpen={customizeDialog !== null}
templateTitle={customizeDialog?.templateTitle ?? ""}
valuesCount={customizeDialog?.valuesCount ?? 0}
cardsCount={customizeDialog?.cardsCount ?? 0}
initialTitle={typeof state.title === "string" ? state.title : ""}
initialDescription={
typeof state.communityContext === "string"
? state.communityContext
: ""
}
initialLocation={
typeof state.communityLocation === "string"
? state.communityLocation
: ""
}
onClose={closeCustomizeDialog}
onContinue={confirmCustomizeDialog}
/>
<CreateFlowTopNav <CreateFlowTopNav
hasShare={isCompletedStep} hasShare={isCompletedStep}
hasExport={isCompletedStep} hasExport={isCompletedStep}
@@ -944,9 +980,9 @@ function CreateFlowLayoutContent({
<main <main
className={`flex min-h-0 min-w-0 flex-1 w-full max-w-full overflow-x-hidden ${CREATE_FLOW_SCROLL_REGION_CLASS} ${mainContentClass} ${mainResponsiveLayout}`} className={`flex min-h-0 min-w-0 flex-1 w-full max-w-full overflow-x-hidden ${CREATE_FLOW_SCROLL_REGION_CLASS} ${mainContentClass} ${mainResponsiveLayout}`}
> >
{children} {templatePathRedirect ? null : children}
</main> </main>
{!isCompletedStep && ( {!isCompletedStep && !templatePathRedirect && (
<CreateFlowFooter <CreateFlowFooter
className="shrink-0" className="shrink-0"
contentMaxClass={getCreateFlowContentMaxClass({ contentMaxClass={getCreateFlowContentMaxClass({
@@ -0,0 +1,256 @@
"use client";
/**
* Figma: "Modal / Customize (template)" (24991:40503).
* Name, optional logo, description, and optional location before the
* template decks.
*/
import { useEffect, useState } from "react";
import Button from "../../../components/buttons/Button";
import Icon from "../../../components/asset/icon";
import TextInput from "../../../components/controls/TextInput";
import TextArea from "../../../components/controls/TextArea";
import Create from "../../../components/modals/Create";
import HeaderLockup from "../../../components/type/HeaderLockup";
import InputLabel from "../../../components/type/InputLabel";
import { useMessages, useTranslation } from "../../../contexts/MessagesContext";
import { COMMUNITY_TITLE_FIELD_MAX_LENGTH } from "./FinalReviewTitleEditModal";
import { COMMUNITY_CONTEXT_FIELD_MAX_LENGTH } from "./FinalReviewCommunityContextEditModal";
import { useCommunityAvatarUpload } from "../hooks/useCommunityAvatarUpload";
import type { TemplateCustomizeFields } from "../hooks/useTemplateReviewActions";
const COMMUNITY_LOCATION_MAX_LENGTH = 200;
const COUNT_WORD_KEYS = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
] as const;
function countWord(
count: number,
words: Record<string, string>,
): string {
const key = String(count);
if ((COUNT_WORD_KEYS as readonly string[]).includes(key)) {
const word = words[key];
if (typeof word === "string" && word.length > 0) return word;
}
return key;
}
function countPhrase(
count: number,
one: string,
many: string,
words: Record<string, string>,
): string {
if (count === 1) return one;
return many.replace("{word}", countWord(count, words));
}
export function TemplateCustomizeDialog({
isOpen,
templateTitle,
valuesCount,
cardsCount,
initialTitle,
initialDescription,
initialLocation,
onClose,
onContinue,
}: {
isOpen: boolean;
templateTitle: string;
valuesCount: number;
cardsCount: number;
initialTitle: string;
initialDescription: string;
initialLocation: string;
onClose: () => void;
onContinue: (_fields: TemplateCustomizeFields) => void;
}) {
const copy = useMessages().create.templateCustomize;
const tName = useTranslation("create.community.communityName");
const tContext = useTranslation("create.community.communityContext");
const avatar = useCommunityAvatarUpload();
const [title, setTitle] = useState(initialTitle);
const [description, setDescription] = useState(initialDescription);
const [location, setLocation] = useState(initialLocation);
const [attempted, setAttempted] = useState(false);
useEffect(() => {
if (!isOpen) {
setAttempted(false);
return;
}
setTitle(initialTitle);
setDescription(initialDescription);
setLocation(initialLocation);
}, [isOpen, initialTitle, initialDescription, initialLocation]);
const words = copy.countWords;
const valuesPhrase = countPhrase(
valuesCount,
copy.valuesOne,
copy.valuesMany,
words,
);
const cardsPhrase = countPhrase(
cardsCount,
copy.cardsOne,
copy.cardsMany,
words,
);
const heading = copy.title.replace("{template}", templateTitle);
const lockupDescription = copy.description
.replaceAll("{template}", templateTitle)
.replace("{valuesPhrase}", valuesPhrase)
.replace("{cardsPhrase}", cardsPhrase);
const trimmedTitle = title.trim();
const nameError = attempted && trimmedTitle.length === 0;
const canContinue = trimmedTitle.length > 0 && !avatar.busy;
const nameHint = nameError ? copy.nameRequired : copy.nameHint;
const handleContinue = () => {
setAttempted(true);
if (!canContinue) return;
onContinue({
title: trimmedTitle,
communityContext: description.trim(),
communityLocation: location.trim(),
});
};
return (
<Create
isOpen={isOpen}
onClose={onClose}
backdropVariant="blurredYellow"
ariaLabel={heading}
headerContent={
<div className="px-[24px] pt-[8px]">
<HeaderLockup
title={heading}
description={lockupDescription}
justification="left"
size="M"
/>
</div>
}
showBackButton={false}
showCancelButton
showNextButton
cancelButtonText={copy.cancel}
nextButtonText={copy.continue}
nextButtonDisabled={!canContinue}
onCancel={onClose}
onNext={handleContinue}
>
<div className="flex flex-col gap-[16px]">
<TextInput
className="!transition-none"
type="text"
label={tName("title")}
placeholder={tName("placeholder")}
value={title}
onChange={(event) => setTitle(event.target.value)}
inputSize="medium"
formHeader
showHelpIcon={false}
textHint={nameHint}
error={nameError}
maxLength={COMMUNITY_TITLE_FIELD_MAX_LENGTH}
required
autoFocus
/>
<div className="flex flex-col gap-[8px]">
<InputLabel
label={copy.logoLabel}
helpIcon={false}
size="s"
palette="default"
/>
<div className="flex items-center gap-[12px]">
<input
ref={avatar.fileInputRef}
type="file"
className="sr-only"
tabIndex={-1}
accept={avatar.accept}
aria-label={copy.upload}
onChange={(event) => void avatar.handleFileChange(event)}
/>
<Button
type="button"
buttonType="outline"
palette="default"
size="xsmall"
hasIconLeading
disabled={avatar.busy}
onClick={avatar.handlePickFile}
>
<Icon name="image" size={14} />
{copy.upload}
</Button>
<p className="min-w-0 flex-1 text-x-small-label text-[color:var(--color-content-default-secondary)]">
{avatar.errorMessage ??
(avatar.fileName && avatar.displaySrc
? avatar.fileName
: copy.logoHint)}
</p>
</div>
</div>
<TextArea
className="!transition-none"
label={tContext("title")}
placeholder={copy.descriptionPlaceholder}
value={description}
onChange={(event) => setDescription(event.target.value)}
size="medium"
formHeader
showHelpIcon={false}
maxLength={COMMUNITY_CONTEXT_FIELD_MAX_LENGTH}
rows={2}
/>
<TextInput
className="!transition-none"
type="text"
label={tContext("locationLabel")}
placeholder={tContext("locationPlaceholder")}
value={location}
onChange={(event) => setLocation(event.target.value)}
inputSize="medium"
formHeader
showHelpIcon={false}
textHint={tContext("locationHint")}
maxLength={COMMUNITY_LOCATION_MAX_LENGTH}
/>
<p className="text-small-paragraph text-[color:var(--color-content-default-tertiary)]">
{copy.privacyNote}
</p>
</div>
</Create>
);
}
@@ -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 * Resolves the active step from `/create/{screenId}` via
* {@link parseCreateFlowScreenFromPathname} (flowSteps). Footer Back uses * {@link parseCreateFlowScreenFromPathname} (flowSteps). Footer Back uses
* {@link resolveCreateFlowBackTarget}: template **Use without changes** that * {@link resolveCreateFlowBackTarget}: template **Customize** walks values
* still needs identity (direct from a template) walks name / description / * then the four decks, and Back from `core-values` returns to
* photo, then Back from `community-name` returns to * `/create/review-template/{slug}`. **Use without changes** lands on
* `/create/review-template/{slug}`. In-flow picks (`?fromFlow=1`) skip * `final-review`; Back from that step returns to the template.
* identity and land on `final-review`; Back from that step returns
* to the template instead of `conflict-management`.
* *
* Template review footer Back uses {@link buildTemplateReviewHref}’s * Template review footer Back uses {@link buildTemplateReviewHref}’s
* `?fromFlow=1` marker (and persisted `templateReviewEntryFromCreateFlow`) so * `?fromFlow=1` marker (and persisted `templateReviewEntryFromCreateFlow`) so
@@ -87,14 +85,13 @@ export function useCreateFlowNavigation(
updateState, updateState,
]); ]);
const identityOnly = const templatePathMode = state.pendingTemplateAction?.mode;
state.pendingTemplateAction?.mode === "useWithoutChanges";
const navigationOptions = useMemo( const navigationOptions = useMemo(
(): CreateFlowNavigationOptions => ({ (): CreateFlowNavigationOptions => ({
skipCommunitySave: options?.skipCommunitySave, skipCommunitySave: options?.skipCommunitySave,
useWithoutChangesIdentityOnly: identityOnly, templatePathMode,
}), }),
[options?.skipCommunitySave, identityOnly], [options?.skipCommunitySave, templatePathMode],
); );
const nextStep = getNextStep(validStep, navigationOptions); const nextStep = getNextStep(validStep, navigationOptions);
@@ -8,7 +8,11 @@ import {
groupAnswersForRecommendations, groupAnswersForRecommendations,
type RecommendationSection, type RecommendationSection,
} from "./useFacetRecommendations"; } 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 { useCreateFlow } from "../context/CreateFlowContext";
import { useMessages } from "../../../contexts/MessagesContext"; 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 * 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. * 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( export function useMethodCardDeckOrdering(
section: RecommendationSection, section: RecommendationSection,
@@ -38,15 +44,32 @@ export function useMethodCardDeckOrdering(
) { ) {
const { state } = useCreateFlow(); const { state } = useCreateFlow();
const copy = useMessages().create.customRule.recommendations; 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( const answers = useMemo(
() => groupAnswersForRecommendations(state), () => groupAnswersForRecommendations(state),
[state], [state],
); );
const deck = useMemo( const deck = useMemo(() => {
() => deriveCompactCards(section, answers, compactLimit), if (templateSlug) {
[section, answers, compactLimit], 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( const rankedMethods = useMemo(
() => orderByIds(methods, deck.orderedIds), () => orderByIds(methods, deck.orderedIds),
@@ -4,6 +4,7 @@ import { useEffect, useMemo } from "react";
import { buildFacetQueryString } from "../../../../lib/create/buildFacetQueryString"; import { buildFacetQueryString } from "../../../../lib/create/buildFacetQueryString";
import { METHOD_FACET_API_SECTION_IDS } from "../../../../lib/create/customRuleFacets"; import { METHOD_FACET_API_SECTION_IDS } from "../../../../lib/create/customRuleFacets";
import { loadFacetScores } from "../../../../lib/create/facetRecommendationsLoad"; import { loadFacetScores } from "../../../../lib/create/facetRecommendationsLoad";
import { isTemplateCreatePath } from "../../../../lib/create/templatePath";
import { useCreateFlow } from "../context/CreateFlowContext"; import { useCreateFlow } from "../context/CreateFlowContext";
/** /**
@@ -18,10 +19,12 @@ export function usePrefetchMethodFacetRecommendations(): void {
[state], [state],
); );
const skipEngine = isTemplateCreatePath(state);
useEffect(() => { useEffect(() => {
if (queryString.length === 0) return; if (skipEngine || queryString.length === 0) return;
for (const section of METHOD_FACET_API_SECTION_IDS) { for (const section of METHOD_FACET_API_SECTION_IDS) {
void loadFacetScores(section, queryString); void loadFacetScores(section, queryString);
} }
}, [queryString]); }, [queryString, skipEngine]);
} }
+126 -131
View File
@@ -1,10 +1,14 @@
"use client"; "use client";
import { useCallback, useMemo, useState } from "react"; 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 { loadTemplateReviewBySlug } from "../../../../lib/create/loadTemplateReviewBySlug";
import { methodSectionsPinsForHydratedSelections } from "../../../../lib/create/publishedDocumentToCreateFlowState"; import { methodSectionsPinsForHydratedSelections } from "../../../../lib/create/publishedDocumentToCreateFlowState";
import { stripCustomRuleSelectionFields } from "../../../../lib/create/stripCustomRuleSelectionFields"; import { stripCustomRuleSelectionFields } from "../../../../lib/create/stripCustomRuleSelectionFields";
import { templateChipCounts } from "../../../../lib/create/templatePath";
import messages from "../../../../messages/en/index"; import messages from "../../../../messages/en/index";
import type { import type {
CreateFlowContextValue, CreateFlowContextValue,
@@ -16,6 +20,20 @@ type AppRouterLike = { push: (_href: string) => void };
type UpdateState = CreateFlowContextValue["updateState"]; type UpdateState = CreateFlowContextValue["updateState"];
type ReplaceStateFn = CreateFlowContextValue["replaceState"]; 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 = { export type UseTemplateReviewActionsResult = {
/** True iff the current pathname is a template-review route (locale/basePath tolerant). */ /** True iff the current pathname is a template-review route (locale/basePath tolerant). */
isTemplateReviewRoute: boolean; isTemplateReviewRoute: boolean;
@@ -27,47 +45,43 @@ export type UseTemplateReviewActionsResult = {
templateReviewApplyError: string | null; templateReviewApplyError: string | null;
setTemplateReviewApplyError: (_message: string | null) => void; setTemplateReviewApplyError: (_message: string | null) => void;
/** /**
* Customize: apply the template's selections onto state and route to * Customize: open the name / photo / description dialog. Continue applies
* `/create/core-values` (if community name is set) or `/create/informational` * the template's cards and routes to `/create/core-values`. Setup questions
* with a `pendingTemplateAction` pin so `/create/review` can later replace * are skipped.
* itself with `/create/core-values`. A named community skips setup
* questions, so leftover setup answers are dropped and cannot change
* suggested cards.
*/ */
handleCustomize: () => Promise<void>; handleCustomize: () => Promise<void>;
/** /**
* Use without changes: scrub any prior customize picks, seed core values + * Use without changes: seed the template's cards and go to final review.
* method-card selections from the template body (same id mapping as * Direct entry clears leftover identity so the Rule card can collect name,
* Customize) so drilling from final-review via + shows selected cards, drop * photo, and description. In-flow keeps the community answers already given.
* 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.
*/ */
handleUseWithoutChanges: () => Promise<void>; 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 * Encapsulates the two template-review footer actions (Customize / Use
* without changes) plus the small amount of state they share (in-flight * without changes) plus the Customize dialog they share.
* 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.
* *
* @example * @example
* const { * const {
* isTemplateReviewRoute,
* templateReviewSlug,
* isApplyingTemplate,
* templateReviewApplyError,
* setTemplateReviewApplyError,
* handleCustomize, * handleCustomize,
* handleUseWithoutChanges, * handleUseWithoutChanges,
* } = useTemplateReviewActions({ * customizeDialog,
* pathname, state, updateState, replaceState, router, * closeCustomizeDialog,
* fromCreateWizard, markCreateFlowInteraction, * confirmCustomizeDialog,
* }); * } = useTemplateReviewActions({ ... });
*/ */
export function useTemplateReviewActions({ export function useTemplateReviewActions({
pathname, pathname,
@@ -95,6 +109,8 @@ export function useTemplateReviewActions({
const [templateReviewApplyError, setTemplateReviewApplyError] = useState< const [templateReviewApplyError, setTemplateReviewApplyError] = useState<
string | null string | null
>(null); >(null);
const [customizeDialog, setCustomizeDialog] =
useState<TemplateCustomizeDialogModel | null>(null);
const templateReviewSlug = useMemo(() => { const templateReviewSlug = useMemo(() => {
const m = pathname?.match(/\/create\/review-template\/([^/?#]+)/); const m = pathname?.match(/\/create\/review-template\/([^/?#]+)/);
@@ -116,42 +132,64 @@ export function useTemplateReviewActions({
setTemplateReviewApplyError(loaded.message); setTemplateReviewApplyError(loaded.message);
return; return;
} }
const prefill = buildTemplateCustomizePrefill( const counts = templateChipCounts(templateReviewSlug);
loaded.template.body, setCustomizeDialog({
templateReviewSlug, slug: templateReviewSlug,
); templateTitle: loaded.template.title,
const pinPatch = methodSectionsPinsForHydratedSelections(prefill); body: loaded.template.body,
const hasCommunityName = valuesCount: counts?.values ?? 0,
typeof state.title === "string" && state.title.trim().length > 0; cardsCount: counts?.cards ?? 0,
updateState({
...prefill,
methodSectionsPinCommitted: {
...state.methodSectionsPinCommitted,
...pinPatch,
},
templateReviewBackSlug: undefined,
...(hasCommunityName
? { pendingTemplateAction: undefined, setupTraits: undefined }
: {
pendingTemplateAction: {
slug: templateReviewSlug,
mode: "customize",
},
}),
}); });
router.push( }, [markCreateFlowInteraction, templateReviewSlug]);
hasCommunityName
? createFlowStepPath("core-values") const closeCustomizeDialog = useCallback(() => {
: createFlowStepPath("informational"), setCustomizeDialog(null);
); }, []);
}, [
router, const confirmCustomizeDialog = useCallback(
state.methodSectionsPinCommitted, (fields: TemplateCustomizeFields) => {
state.title, if (!customizeDialog) return;
templateReviewSlug, markCreateFlowInteraction();
updateState, const prefill = buildTemplateCustomizePrefill(
markCreateFlowInteraction, 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 () => { const handleUseWithoutChanges = useCallback(async () => {
if (!templateReviewSlug) return; if (!templateReviewSlug) return;
@@ -165,33 +203,21 @@ export function useTemplateReviewActions({
return; return;
} }
const { template } = loaded; const { template } = loaded;
const doc = template.body; const sections = sectionsFromTemplateBody(template.body);
if (!doc || typeof doc !== "object" || Array.isArray(doc)) { if (!sections) {
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) {
setTemplateReviewApplyError( setTemplateReviewApplyError(
messages.create.templateReview.errors.applyFailed, messages.create.templateReview.errors.applyFailed,
); );
return; 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) => { replaceState((prev) => {
const base = stripCustomRuleSelectionFields(prev); const base = stripCustomRuleSelectionFields(prev);
const customizePrefill = buildTemplateCustomizePrefill( const customizePrefill = buildTemplateCustomizePrefill(
doc, template.body,
templateReviewSlug ?? undefined, templateReviewSlug ?? undefined,
); );
const details = templatePresetDetailsFromPrefill(customizePrefill);
const hasValuesSeed = const hasValuesSeed =
customizePrefill.selectedCoreValueIds !== undefined; customizePrefill.selectedCoreValueIds !== undefined;
@@ -209,68 +235,34 @@ export function useTemplateReviewActions({
const seeded: CreateFlowState = { const seeded: CreateFlowState = {
...base, ...base,
...(hasValuesSeed ...customizePrefill,
? { ...details,
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,
}
: {}),
sections: sectionsWithoutValues, sections: sectionsWithoutValues,
methodSectionsPinCommitted: pinPatch, methodSectionsPinCommitted: pinPatch,
templateReviewBackSlug: templateReviewSlug, templateReviewBackSlug: templateReviewSlug,
};
if (fromCreateWizard) {
return {
...seeded,
pendingTemplateAction: undefined,
};
}
return {
...seeded,
title: undefined,
communityContext: undefined,
communityAvatarUrl: undefined,
currentStep: undefined,
templateReviewEntryFromCreateFlow: undefined,
setupTraits: undefined, setupTraits: undefined,
pendingTemplateAction: { pendingTemplateAction: {
slug: templateReviewSlug, slug: templateReviewSlug,
mode: "useWithoutChanges", mode: "useWithoutChanges",
}, },
}; };
if (fromCreateWizard) {
return seeded;
}
return {
...seeded,
title: undefined,
communityContext: undefined,
communityLocation: undefined,
communityAvatarUrl: undefined,
communityAvatarFileName: undefined,
currentStep: undefined,
templateReviewEntryFromCreateFlow: undefined,
};
}); });
router.push( router.push(createFlowStepPath("final-review"));
fromCreateWizard
? createFlowStepPath("final-review")
: createFlowStepPath("community-name"),
);
}, [ }, [
fromCreateWizard, fromCreateWizard,
markCreateFlowInteraction, markCreateFlowInteraction,
@@ -287,5 +279,8 @@ export function useTemplateReviewActions({
setTemplateReviewApplyError, setTemplateReviewApplyError,
handleCustomize, handleCustomize,
handleUseWithoutChanges, handleUseWithoutChanges,
customizeDialog,
closeCustomizeDialog,
confirmCustomizeDialog,
}; };
} }
@@ -19,7 +19,6 @@ import {
getAssetPath, getAssetPath,
vectorMarkPath, vectorMarkPath,
} from "../../../../../lib/assetUtils"; } from "../../../../../lib/assetUtils";
import { methodSectionsPinsForHydratedSelections } from "../../../../../lib/create/publishedDocumentToCreateFlowState";
import { CREATE_ROUTES, createFlowStepPath } from "../../utils/createFlowPaths"; import { CREATE_ROUTES, createFlowStepPath } from "../../utils/createFlowPaths";
import { CREATE_FLOW_REVIEW_RETURN_QUERY_KEY } from "../../utils/flowSteps"; import { CREATE_FLOW_REVIEW_RETURN_QUERY_KEY } from "../../utils/flowSteps";
import type { CreateFlowStep } from "../../types"; import type { CreateFlowStep } from "../../types";
@@ -83,7 +82,7 @@ export function CommunityReviewScreen() {
const lgUp = useCreateFlowLgUp(); const lgUp = useCreateFlowLgUp();
const messages = useMessages(); const messages = useMessages();
const t = useTranslation("create.community.review"); const t = useTranslation("create.community.review");
const { state, updateState } = useCreateFlow(); const { state } = useCreateFlow();
/** /**
* Server layout has an empty context; the client layout may already hold a * Server layout has an empty context; the client layout may already hold a
* named draft. Defer empty-vs-congrats until after mount so the first paint * named draft. Defer empty-vs-congrats until after mount so the first paint
@@ -95,11 +94,9 @@ export function CommunityReviewScreen() {
}, []); }, []);
/** /**
* If the user picked **Customize** from a template before finishing community * Leftover pin from an older draft: bounce off community review onto the
* stage, we pinned `pendingTemplateAction` so this screen can skip itself * template path. Customize walks the decks; Use without changes lands on
* and `replace` to `core-values`. **Use without changes** does not skip * final review. The pin stays so decks skip the engine.
* identity: if they land here with that pin, send them to `community-name`
* and leave the pin so name → description → photo stay in the skip list.
* *
* Ref guard covers React 18 StrictMode's double-mount in dev so we don't * Ref guard covers React 18 StrictMode's double-mount in dev so we don't
* fire `router.replace` twice on the same transition. * fire `router.replace` twice on the same transition.
@@ -109,31 +106,13 @@ export function CommunityReviewScreen() {
if (firedRedirectRef.current) return; if (firedRedirectRef.current) return;
const pending = state.pendingTemplateAction; const pending = state.pendingTemplateAction;
if (!pending) return; if (!pending) return;
if (pending.mode !== "customize") {
firedRedirectRef.current = true;
router.replace(createFlowStepPath("community-name"));
return;
}
const target = createFlowStepPath("core-values");
firedRedirectRef.current = true; firedRedirectRef.current = true;
const pinMerge = { router.replace(
methodSectionsPinCommitted: { createFlowStepPath(
...state.methodSectionsPinCommitted, pending.mode === "customize" ? "core-values" : "final-review",
...methodSectionsPinsForHydratedSelections(state), ),
}, );
}; }, [router, state.pendingTemplateAction]);
updateState({ pendingTemplateAction: undefined, ...pinMerge });
router.replace(target);
}, [
router,
state.pendingTemplateAction,
state.methodSectionsPinCommitted,
state.selectedCommunicationMethodIds,
state.selectedMembershipMethodIds,
state.selectedDecisionApproachIds,
state.selectedConflictManagementIds,
updateState,
]);
const cardTitle = const cardTitle =
typeof state.title === "string" && state.title.trim().length > 0 typeof state.title === "string" && state.title.trim().length > 0
@@ -29,11 +29,19 @@ import {
type FinalReviewChipEditPatch, type FinalReviewChipEditPatch,
type FinalReviewChipEditTarget, type FinalReviewChipEditTarget,
} from "../../components/FinalReviewChipEditModal"; } from "../../components/FinalReviewChipEditModal";
import { FinalReviewCommunityContextEditModal } from "../../components/FinalReviewCommunityContextEditModal"; import {
import { FinalReviewTitleEditModal } from "../../components/FinalReviewTitleEditModal"; FinalReviewCommunityContextEditModal,
COMMUNITY_CONTEXT_FIELD_MAX_LENGTH,
} from "../../components/FinalReviewCommunityContextEditModal";
import {
FinalReviewTitleEditModal,
COMMUNITY_TITLE_FIELD_MAX_LENGTH,
} from "../../components/FinalReviewTitleEditModal";
import { useCommunityAvatarDisplayUrl } from "../../hooks/useCommunityAvatarDisplayUrl"; import { useCommunityAvatarDisplayUrl } from "../../hooks/useCommunityAvatarDisplayUrl";
import { usePreviewSurfaceColor } from "../../hooks/usePreviewSurfaceColor"; import { usePreviewSurfaceColor } from "../../hooks/usePreviewSurfaceColor";
import { useCreateFlowNavigation } from "../../hooks/useCreateFlowNavigation"; import { useCreateFlowNavigation } from "../../hooks/useCreateFlowNavigation";
import { useCommunityAvatarUpload } from "../../hooks/useCommunityAvatarUpload";
import { isTemplateCreatePath } from "../../../../../lib/create/templatePath";
import { createFlowStepForFacetGroup } from "../../utils/facetGroupToCreateFlowStep"; import { createFlowStepForFacetGroup } from "../../utils/facetGroupToCreateFlowStep";
import { isPreviewSurfaceColor } from "../../../../../lib/create/previewSurfaceColor"; import { isPreviewSurfaceColor } from "../../../../../lib/create/previewSurfaceColor";
import { import {
@@ -225,7 +233,10 @@ export function FinalReviewScreen({
const descriptionEmptyHint = t("communityContextEditModal.emptyHint"); const descriptionEmptyHint = t("communityContextEditModal.emptyHint");
const avatarUrl = useCommunityAvatarDisplayUrl(state.communityAvatarUrl); const templatePath = isTemplateCreatePath(state);
const avatarUpload = useCommunityAvatarUpload();
const serverAvatarUrl = useCommunityAvatarDisplayUrl(state.communityAvatarUrl);
const avatarUrl = avatarUpload.displaySrc ?? serverAvatarUrl;
const storedFallback = const storedFallback =
typeof state.previewSurfaceColor === "string" typeof state.previewSurfaceColor === "string"
? state.previewSurfaceColor ? state.previewSurfaceColor
@@ -275,23 +286,73 @@ export function FinalReviewScreen({
hasTrailingIcon={false} hasTrailingIcon={false}
/> />
) : null} ) : null}
{templatePath ? (
<input
ref={avatarUpload.fileInputRef}
type="file"
className="sr-only"
tabIndex={-1}
accept={avatarUpload.accept}
aria-label={m.create.community.communityUpload.title}
onChange={(event) => void avatarUpload.handleFileChange(event)}
/>
) : null}
<Rule <Rule
title={ruleCardTitle} title={ruleCardTitle}
description={ruleCardDescription} description={
onTitleClick={() => setTitleModalOpen(true)} templatePath ? rawCommunityContextForModal : ruleCardDescription
}
interactive={!templatePath}
hasNameField={templatePath}
nameValue={rawTitleForModal}
nameLabel={m.create.community.communityName.inputLabel}
namePlaceholder={m.create.community.communityName.placeholder}
onNameChange={
templatePath
? (value) => {
markCreateFlowInteraction();
updateState({
title: value.slice(0, COMMUNITY_TITLE_FIELD_MAX_LENGTH),
});
}
: undefined
}
onTitleClick={
templatePath ? undefined : () => setTitleModalOpen(true)
}
titleEditAriaLabel={t("titleEditModal.ariaEditTitle")} titleEditAriaLabel={t("titleEditModal.ariaEditTitle")}
onDescriptionClick={() => setCommunityContextModalOpen(true)} onDescriptionClick={
templatePath ? undefined : () => setCommunityContextModalOpen(true)
}
descriptionEmptyHint={descriptionEmptyHint} descriptionEmptyHint={descriptionEmptyHint}
descriptionEditAriaLabel={t("communityContextEditModal.ariaEditDescription")} descriptionEditAriaLabel={t("communityContextEditModal.ariaEditDescription")}
descriptionLabel={m.create.community.communityContext.title}
descriptionPlaceholder={m.create.community.communityContext.placeholder}
descriptionHelperText={m.create.community.communityContext.optional}
onDescriptionChange={
templatePath
? (value) => {
markCreateFlowInteraction();
const next = value.slice(0, COMMUNITY_CONTEXT_FIELD_MAX_LENGTH);
updateState({ communityContext: next, summary: next });
}
: undefined
}
onLogoClick={
templatePath ? avatarUpload.handlePickFile : undefined
}
logoUploadAriaLabel={m.create.community.communityUpload.title}
size={mdUp ? "L" : "M"} size={mdUp ? "L" : "M"}
expanded={true} expanded={true}
descriptionAtBottom descriptionAtBottom
backgroundColor="bg-transparent" backgroundColor="bg-transparent"
surfaceColor={surfaceColor} surfaceColor={surfaceColor}
logoUrl={avatarUrl} logoUrl={avatarUrl ?? undefined}
logoAlt={ruleCardTitle} logoAlt={ruleCardTitle}
communityInitials={ communityInitials={
avatarUrl ? undefined : communityInitialsFromTitle(ruleCardTitle) avatarUrl || templatePath
? undefined
: communityInitialsFromTitle(ruleCardTitle)
} }
categories={finalReviewCategories} categories={finalReviewCategories}
className={`${CREATE_FLOW_REVIEW_RULE_LAYOUT_CLASS}${surfaceColor ? "" : " invisible"}`} className={`${CREATE_FLOW_REVIEW_RULE_LAYOUT_CLASS}${surfaceColor ? "" : " invisible"}`}
@@ -312,24 +373,28 @@ export function FinalReviewScreen({
onClose={() => setActiveReadOnlyDetail(null)} onClose={() => setActiveReadOnlyDetail(null)}
detail={activeReadOnlyDetail} detail={activeReadOnlyDetail}
/> />
<FinalReviewTitleEditModal {templatePath ? null : (
isOpen={titleModalOpen} <>
onClose={() => setTitleModalOpen(false)} <FinalReviewTitleEditModal
initialValue={rawTitleForModal} isOpen={titleModalOpen}
onSave={(value) => { onClose={() => setTitleModalOpen(false)}
markCreateFlowInteraction(); initialValue={rawTitleForModal}
updateState({ title: value }); onSave={(value) => {
}} markCreateFlowInteraction();
/> updateState({ title: value });
<FinalReviewCommunityContextEditModal }}
isOpen={communityContextModalOpen} />
onClose={() => setCommunityContextModalOpen(false)} <FinalReviewCommunityContextEditModal
initialValue={rawCommunityContextForModal} isOpen={communityContextModalOpen}
onSave={(value) => { onClose={() => setCommunityContextModalOpen(false)}
markCreateFlowInteraction(); initialValue={rawCommunityContextForModal}
updateState({ communityContext: value, summary: value }); onSave={(value) => {
}} markCreateFlowInteraction();
/> updateState({ communityContext: value, summary: value });
}}
/>
</>
)}
</CreateFlowLockupCardStepShell> </CreateFlowLockupCardStepShell>
); );
} }
@@ -35,6 +35,11 @@ import {
} from "../../../../../lib/create/methodCardWizardPrefill"; } from "../../../../../lib/create/methodCardWizardPrefill";
import type { CustomMethodCardFieldBlock } from "../../../../../lib/create/customMethodCardFieldBlocks"; import type { CustomMethodCardFieldBlock } from "../../../../../lib/create/customMethodCardFieldBlocks";
import { uploadCreateFlowFile } from "../../../../../lib/create/uploadToServer"; import { uploadCreateFlowFile } from "../../../../../lib/create/uploadToServer";
import {
orderIdsFirst,
templatePathFromState,
templateValueIdsForSlug,
} from "../../../../../lib/create/templatePath";
const MAX_CORE_VALUES = MAX_SELECTED_CORE_VALUES; const MAX_CORE_VALUES = MAX_SELECTED_CORE_VALUES;
@@ -114,13 +119,16 @@ export function CoreValuesSelectScreen() {
const initialDraftRef = useRef<CoreValueDetailEntry | null>(null); const initialDraftRef = useRef<CoreValueDetailEntry | null>(null);
const pendingEphemeralCoreDuplicateRef = useRef<string | null>(null); const pendingEphemeralCoreDuplicateRef = useRef<string | null>(null);
const [coreValueOptions, setCoreValueOptions] = useState<ChipOption[]>(() => const [coreValueOptions, setCoreValueOptions] = useState<ChipOption[]>(() => {
buildCoreValueChipOptionsFromDraft( const base = buildCoreValueChipOptionsFromDraft(
presets, presets,
state.coreValuesChipsSnapshot, state.coreValuesChipsSnapshot,
state.selectedCoreValueIds, state.selectedCoreValueIds,
), );
); const path = templatePathFromState(state);
if (!path) return base;
return orderIdsFirst(base, templateValueIdsForSlug(path.slug));
});
const [activeModalChipId, setActiveModalChipId] = useState<string | null>( const [activeModalChipId, setActiveModalChipId] = useState<string | null>(
null, null,
@@ -137,18 +145,23 @@ export function CoreValuesSelectScreen() {
CustomMethodCardFieldBlock[] | null CustomMethodCardFieldBlock[] | null
>(null); >(null);
const templatePathSlug = templatePathFromState(state)?.slug;
useEffect(() => { useEffect(() => {
const base = buildCoreValueChipOptionsFromDraft(
presets,
state.coreValuesChipsSnapshot,
state.selectedCoreValueIds,
);
setCoreValueOptions( setCoreValueOptions(
buildCoreValueChipOptionsFromDraft( templatePathSlug
presets, ? orderIdsFirst(base, templateValueIdsForSlug(templatePathSlug))
state.coreValuesChipsSnapshot, : base,
state.selectedCoreValueIds,
),
); );
}, [ }, [
presets, presets,
state.coreValuesChipsSnapshot, state.coreValuesChipsSnapshot,
state.selectedCoreValueIds, state.selectedCoreValueIds,
templatePathSlug,
]); ]);
/** Sync chips to create-flow draft. Never call `updateState` from inside a `setCoreValueOptions` updater — defer with `queueMicrotask`. */ /** Sync chips to create-flow draft. Never call `updateState` from inside a `setCoreValueOptions` updater — defer with `queueMicrotask`. */
@@ -3,7 +3,6 @@
import { GovernanceTemplateGrid } from "../../../components/sections/GovernanceTemplateGrid"; import { GovernanceTemplateGrid } from "../../../components/sections/GovernanceTemplateGrid";
import type { TemplateGridCardEntry } from "../../../../lib/templates/templateGridPresentation"; import type { TemplateGridCardEntry } from "../../../../lib/templates/templateGridPresentation";
import { useTranslation } from "../../../contexts/MessagesContext"; import { useTranslation } from "../../../contexts/MessagesContext";
import { useTemplatesFacetGridEntries } from "../../../(marketing)/templates/useTemplatesFacetGridEntries";
import { CreateFlowHeaderLockup } from "../components/CreateFlowHeaderLockup"; import { CreateFlowHeaderLockup } from "../components/CreateFlowHeaderLockup";
import { CreateFlowStepShell } from "../components/CreateFlowStepShell"; import { CreateFlowStepShell } from "../components/CreateFlowStepShell";
import { CREATE_FLOW_TWO_COLUMN_MAX_WIDTH_CLASS } from "../components/createFlowLayoutTokens"; import { CREATE_FLOW_TWO_COLUMN_MAX_WIDTH_CLASS } from "../components/createFlowLayoutTokens";
@@ -15,10 +14,6 @@ export function CreateFlowTemplatesPageClient({
initialGridEntries: TemplateGridCardEntry[]; initialGridEntries: TemplateGridCardEntry[];
}) { }) {
const t = useTranslation("pages.templates"); const t = useTranslation("pages.templates");
const entries = useTemplatesFacetGridEntries({
initialGridEntries,
enableFacetRecommendations: true,
});
return ( return (
<CreateFlowStepShell <CreateFlowStepShell
@@ -34,7 +29,7 @@ export function CreateFlowTemplatesPageClient({
justification="left" justification="left"
/> />
<GovernanceTemplateGrid <GovernanceTemplateGrid
entries={entries} entries={initialGridEntries}
hrefForTemplate={(slug) => hrefForTemplate={(slug) =>
buildTemplateReviewHref(slug, { fromCreateWizard: true }) buildTemplateReviewHref(slug, { fromCreateWizard: true })
} }
+7 -12
View File
@@ -219,24 +219,19 @@ export interface CreateFlowState {
*/ */
customMethodCardFieldBlocksById?: Record<string, CustomMethodCardFieldBlock[]>; customMethodCardFieldBlocksById?: Record<string, CustomMethodCardFieldBlock[]>;
/** /**
* Set when a user picks a template (Customize or Use without changes) before * Set when a user starts from a template (Customize or Use without changes).
* completing the community stage. Customize: the community-review screen * Kept for the rest of the wizard so community setup is skipped, decks skip
* `router.replace`s past `/create/review` to `core-values`. Use without * the engine, and final-review Back / identity fields know which path it is.
* changes: navigation skips to name → description → optional photo, then * Customize walks values and the four decks; Use without changes lands on
* `confirm-stakeholders` (the pin keeps that skip list active). Set only for * final review. Cleared when the flow is reset.
* **direct** template entry, not when community identity was already collected
* in-flow. Cleared when community-review consumes a customize pin, or when
* the flow is reset.
*/ */
pendingTemplateAction?: { pendingTemplateAction?: {
slug: string; slug: string;
mode: "customize" | "useWithoutChanges"; mode: "customize" | "useWithoutChanges";
}; };
/** /**
* Set when the user chooses **Use without changes** on a template-review * Template-review slug to return to from Customize values or from
* page. Used so Back from `community-name` (identity-only path) returns to * Use-without-changes final review. Cleared when the flow state is cleared.
* `/create/review-template/{slug}` instead of the intro. Cleared when the user
* picks **Customize** from template review or when the flow state is cleared.
*/ */
templateReviewBackSlug?: string; templateReviewBackSlug?: string;
/** /**
+46 -40
View File
@@ -50,26 +50,32 @@ export const FIRST_STEP: CreateFlowStep = FLOW_STEP_ORDER[0];
export type CreateFlowNavigationOptions = { export type CreateFlowNavigationOptions = {
skipCommunitySave?: boolean; skipCommunitySave?: boolean;
/** /**
* Template **Use without changes**: collect community name, description, and * Template path. Skips size, kind, scale, maturity, and setup questions.
* optional photo only. Skips intro, structure, size, setup questions, save, * Customize still walks values and the four decks; Use without changes
* community review, and the custom-rule authoring segment. * jumps to final review. Identity is collected in the Customize dialog or
* on the final-review Rule card.
*/ */
useWithoutChangesIdentityOnly?: boolean; templatePathMode?: "customize" | "useWithoutChanges";
}; };
/** /**
* Community + custom-rule steps skipped when * Community questionnaire skipped on both template-path modes. Identity is
* {@link CreateFlowNavigationOptions.useWithoutChangesIdentityOnly} is set. * collected in the Customize dialog or on the final-review Rule card.
* Remaining identity steps: `community-name` → `community-context` →
* `community-upload`, then `final-review`.
*/ */
const USE_WITHOUT_CHANGES_IDENTITY_SKIP = new Set<CreateFlowStep>([ const TEMPLATE_PATH_COMMUNITY_SKIP = new Set<CreateFlowStep>([
"informational", "informational",
"community-name",
"community-structure", "community-structure",
"community-context",
"community-size", "community-size",
"setup-questions", "setup-questions",
"community-upload",
"community-save", "community-save",
"review", "review",
]);
/** Use without changes does not run values or the four decks unless + Add opens one. */
const TEMPLATE_PATH_DECK_SKIP = new Set<CreateFlowStep>([
"core-values", "core-values",
"communication-methods", "communication-methods",
"membership-methods", "membership-methods",
@@ -82,12 +88,28 @@ function shouldSkipStep(
options?: CreateFlowNavigationOptions, options?: CreateFlowNavigationOptions,
): boolean { ): boolean {
if (options?.skipCommunitySave && step === "community-save") return true; if (options?.skipCommunitySave && step === "community-save") return true;
return Boolean( if (!options?.templatePathMode) return false;
options?.useWithoutChangesIdentityOnly && if (TEMPLATE_PATH_COMMUNITY_SKIP.has(step)) return true;
USE_WITHOUT_CHANGES_IDENTITY_SKIP.has(step), return (
options.templatePathMode === "useWithoutChanges" &&
TEMPLATE_PATH_DECK_SKIP.has(step)
); );
} }
/**
* Where to send a template-path draft that reopened on a community setup
* step. Customize resumes at values; Use without changes resumes at final
* review. Deck steps stay put so final-review + Add can open one.
*/
export function templatePathSkippedCommunityRedirect(
currentStep: CreateFlowStep | null | undefined,
mode: CreateFlowNavigationOptions["templatePathMode"],
): CreateFlowStep | null {
if (!currentStep || !mode) return null;
if (!TEMPLATE_PATH_COMMUNITY_SKIP.has(currentStep)) return null;
return mode === "customize" ? "core-values" : "final-review";
}
/** /**
* Returns the next step in the flow, or null if current is last/invalid * Returns the next step in the flow, or null if current is last/invalid
*/ */
@@ -128,13 +150,10 @@ export function getPreviousStep(
* Where the create-flow footer Back action should go. Usually the previous * Where the create-flow footer Back action should go. Usually the previous
* step in {@link FLOW_STEP_ORDER}. * step in {@link FLOW_STEP_ORDER}.
* *
* Template **Use without changes** exceptions: * Template path:
* - Direct from a template (`useWithoutChangesIdentityOnly`): Back from * - Customize: Back from `core-values` returns to template review; Back from
* `community-name` returns to template review; Back from * `final-review` is the conflict deck.
* `final-review` is `community-upload`. * - Use without changes: Back from `final-review` returns to template review.
* - In-flow (`?fromFlow=1`, community identity already collected): Back
* from `final-review` returns to template review instead of
* `conflict-management`.
*/ */
export type CreateFlowBackTarget = export type CreateFlowBackTarget =
| { kind: "step"; step: CreateFlowStep } | { kind: "step"; step: CreateFlowStep }
@@ -149,19 +168,14 @@ export function resolveCreateFlowBackTarget(
typeof templateReviewBackSlug === "string" typeof templateReviewBackSlug === "string"
? templateReviewBackSlug.trim() ? templateReviewBackSlug.trim()
: ""; : "";
if ( const mode = options?.templatePathMode;
currentStep === "community-name" && if (slug.length > 0) {
options?.useWithoutChangesIdentityOnly && if (currentStep === "core-values" && mode === "customize") {
slug.length > 0 return { kind: "templateReview", slug };
) { }
return { kind: "templateReview", slug }; if (currentStep === "final-review" && mode !== "customize") {
} return { kind: "templateReview", slug };
if ( }
currentStep === "final-review" &&
slug.length > 0 &&
!options?.useWithoutChangesIdentityOnly
) {
return { kind: "templateReview", slug };
} }
const prev = getPreviousStep(currentStep, options); const prev = getPreviousStep(currentStep, options);
return prev != null ? { kind: "step", step: prev } : null; return prev != null ? { kind: "step", step: prev } : null;
@@ -289,14 +303,6 @@ export function isDirectTemplateReviewEntry(
); );
} }
/**
* Only set from `/create/review` “Create from template” with `fromFlow=1`.
* Enables facet-ranked `GET /api/templates` + “RECOMMENDED” on the grid; omit
* on profile and marketing so stale localStorage facets never show badges.
*/
export const TEMPLATES_FACET_RECOMMEND_QUERY = "recommendTemplates" as const;
export const TEMPLATES_FACET_RECOMMEND_VALUE = "1" as const;
/** `/create/completed?celebrate=1` — post-publish toast; set only after **initial** POST publish, not PATCH updates. */ /** `/create/completed?celebrate=1` — post-publish toast; set only after **initial** POST publish, not PATCH updates. */
export const CREATE_FLOW_COMPLETED_CELEBRATE_QUERY = "celebrate" as const; export const CREATE_FLOW_COMPLETED_CELEBRATE_QUERY = "celebrate" as const;
export const CREATE_FLOW_COMPLETED_CELEBRATE_VALUE = "1" as const; export const CREATE_FLOW_COMPLETED_CELEBRATE_VALUE = "1" as const;
@@ -6,13 +6,8 @@ import HeaderLockup from "../../components/type/HeaderLockup";
import { GovernanceTemplateGrid } from "../../components/sections/GovernanceTemplateGrid"; import { GovernanceTemplateGrid } from "../../components/sections/GovernanceTemplateGrid";
import type { TemplateGridCardEntry } from "../../../lib/templates/templateGridPresentation"; import type { TemplateGridCardEntry } from "../../../lib/templates/templateGridPresentation";
import { prepareFreshCreateFlowEntrySync } from "../../(app)/create/utils/prepareFreshCreateFlowEntry"; import { prepareFreshCreateFlowEntrySync } from "../../(app)/create/utils/prepareFreshCreateFlowEntry";
import { import { buildTemplateReviewHref } from "../../(app)/create/utils/flowSteps";
buildTemplateReviewHref,
TEMPLATES_FACET_RECOMMEND_QUERY,
TEMPLATES_FACET_RECOMMEND_VALUE,
} from "../../(app)/create/utils/flowSteps";
import { useTranslation } from "../../contexts/MessagesContext"; import { useTranslation } from "../../contexts/MessagesContext";
import { useTemplatesFacetGridEntries } from "./useTemplatesFacetGridEntries";
export interface TemplatesPageClientProps { export interface TemplatesPageClientProps {
initialGridEntries: TemplateGridCardEntry[]; initialGridEntries: TemplateGridCardEntry[];
@@ -69,8 +64,7 @@ export default function TemplatesPageClient({
/** /**
* - `fromFlow=1` — skip `prepareFreshCreateFlowEntry` on template click * - `fromFlow=1` — skip `prepareFreshCreateFlowEntry` on template click
* (draft preserved). Used by profile “Create from template”. * (draft preserved). Used by profile “Create from template”.
* - `recommendTemplates=1` — rank templates + “RECOMMENDED” * Templates carry no recommendation; the grid stays in curated order.
* from `GET /api/templates?facet.*` using the persisted community draft.
*/ */
function TemplatesGridWithSearchParams({ function TemplatesGridWithSearchParams({
initialGridEntries, initialGridEntries,
@@ -79,14 +73,9 @@ function TemplatesGridWithSearchParams({
}) { }) {
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const fromFlow = searchParams.get("fromFlow") === "1"; const fromFlow = searchParams.get("fromFlow") === "1";
const enableFacetRecommendations = return (
searchParams.get(TEMPLATES_FACET_RECOMMEND_QUERY) === <TemplatesGrid entries={initialGridEntries} fromFlow={fromFlow} />
TEMPLATES_FACET_RECOMMEND_VALUE; );
const entries = useTemplatesFacetGridEntries({
initialGridEntries,
enableFacetRecommendations,
});
return <TemplatesGrid entries={entries} fromFlow={fromFlow} />;
} }
function TemplatesGrid({ function TemplatesGrid({
@@ -1,71 +0,0 @@
"use client";
import { useEffect, useState } from "react";
import { readAnonymousCreateFlowState } from "../../(app)/create/utils/anonymousDraftStorage";
import { buildFacetQueryString } from "../../../lib/create/buildFacetQueryString";
import {
fetchRankedTemplatesByFacets,
isTemplatesFetchAborted,
} from "../../../lib/create/fetchTemplates";
import {
gridEntriesWithFacetScores,
type TemplateGridCardEntry,
} from "../../../lib/templates/templateGridPresentation";
type UseTemplatesFacetGridEntriesArgs = {
initialGridEntries: TemplateGridCardEntry[];
enableFacetRecommendations: boolean;
};
/**
* When `enableFacetRecommendations` (in-flow `/create/templates`, or marketing
* `/templates?recommendTemplates=1`), re-fetch ranked templates from
* `GET /api/templates?facet.*` using the persisted create-flow draft.
* Otherwise returns `initialGridEntries` from SSR.
*/
export function useTemplatesFacetGridEntries({
initialGridEntries,
enableFacetRecommendations,
}: UseTemplatesFacetGridEntriesArgs): TemplateGridCardEntry[] {
const [entries, setEntries] = useState(initialGridEntries);
useEffect(() => {
if (!enableFacetRecommendations) {
setEntries(initialGridEntries);
return;
}
const state = readAnonymousCreateFlowState();
const facetQuery = buildFacetQueryString(state);
if (facetQuery.length === 0) {
setEntries(initialGridEntries);
return;
}
const ac = new AbortController();
void (async () => {
try {
const result = await fetchRankedTemplatesByFacets({
signal: ac.signal,
facetQuery,
});
if (ac.signal.aborted) return;
if ("error" in result) {
setEntries(initialGridEntries);
return;
}
setEntries(
gridEntriesWithFacetScores(result.templates, result.scores),
);
} catch (e) {
if (isTemplatesFetchAborted(e)) return;
setEntries(initialGridEntries);
}
})();
return () => {
ac.abort();
};
}, [enableFacetRecommendations, initialGridEntries]);
return entries;
}
@@ -52,6 +52,17 @@ const RuleContainer = memo<RuleProps>(
fluidWidth = false, fluidWidth = false,
descriptionAtBottom = false, descriptionAtBottom = false,
surfaceColor, surfaceColor,
hasNameField = false,
nameValue,
nameLabel,
namePlaceholder,
onNameChange,
descriptionLabel,
descriptionPlaceholder,
descriptionHelperText,
onDescriptionChange,
onLogoClick,
logoUploadAriaLabel,
}) => { }) => {
const size = sizeProp ?? "L"; const size = sizeProp ?? "L";
const isInteractive = interactive ?? !hasBottomLinks; const isInteractive = interactive ?? !hasBottomLinks;
@@ -123,6 +134,17 @@ const RuleContainer = memo<RuleProps>(
surfaceColor={surfaceColor} surfaceColor={surfaceColor}
cardAriaLabel={cardAriaLabel} cardAriaLabel={cardAriaLabel}
recommendedLabel={recommendedLabel} recommendedLabel={recommendedLabel}
hasNameField={hasNameField}
nameValue={nameValue}
nameLabel={nameLabel}
namePlaceholder={namePlaceholder}
onNameChange={onNameChange}
descriptionLabel={descriptionLabel}
descriptionPlaceholder={descriptionPlaceholder}
descriptionHelperText={descriptionHelperText}
onDescriptionChange={onDescriptionChange}
onLogoClick={onLogoClick}
logoUploadAriaLabel={logoUploadAriaLabel}
/> />
); );
}, },
+26
View File
@@ -103,6 +103,21 @@ export interface RuleProps {
* {@link backgroundColor}. * {@link backgroundColor}.
*/ */
surfaceColor?: string; surfaceColor?: string;
/**
* Figma Has Name Field: inline community name, optional logo upload, and
* labeled description. Used on the template-path final review.
*/
hasNameField?: boolean;
nameValue?: string;
nameLabel?: string;
namePlaceholder?: string;
onNameChange?: (_value: string) => void;
descriptionLabel?: string;
descriptionPlaceholder?: string;
descriptionHelperText?: string;
onDescriptionChange?: (_value: string) => void;
onLogoClick?: () => void;
logoUploadAriaLabel?: string;
} }
export interface RuleViewProps { export interface RuleViewProps {
@@ -138,4 +153,15 @@ export interface RuleViewProps {
/** Interactive card aria-label; supplied by the container from `ruleCard` messages. */ /** Interactive card aria-label; supplied by the container from `ruleCard` messages. */
cardAriaLabel: string; cardAriaLabel: string;
recommendedLabel: string; recommendedLabel: string;
hasNameField?: boolean;
nameValue?: string;
nameLabel?: string;
namePlaceholder?: string;
onNameChange?: (_value: string) => void;
descriptionLabel?: string;
descriptionPlaceholder?: string;
descriptionHelperText?: string;
onDescriptionChange?: (_value: string) => void;
onLogoClick?: () => void;
logoUploadAriaLabel?: string;
} }
+97 -5
View File
@@ -4,8 +4,11 @@ import Image from "next/image";
import NextLink from "next/link"; import NextLink from "next/link";
import MultiSelect from "../../controls/MultiSelect"; import MultiSelect from "../../controls/MultiSelect";
import InlineTextButton from "../../buttons/InlineTextButton"; import InlineTextButton from "../../buttons/InlineTextButton";
import TextInput from "../../controls/TextInput";
import TextArea from "../../controls/TextArea";
import NavigationLink from "../../navigation/Link"; import NavigationLink from "../../navigation/Link";
import Tag from "../../utility/Tag"; import Tag from "../../utility/Tag";
import InputLabel from "../../type/InputLabel";
import type { RuleBottomLink, RuleViewProps } from "./Rule.types"; import type { RuleBottomLink, RuleViewProps } from "./Rule.types";
export function RuleView({ export function RuleView({
@@ -40,6 +43,17 @@ export function RuleView({
surfaceColor, surfaceColor,
cardAriaLabel, cardAriaLabel,
recommendedLabel, recommendedLabel,
hasNameField = false,
nameValue = "",
nameLabel,
namePlaceholder,
onNameChange,
descriptionLabel,
descriptionPlaceholder,
descriptionHelperText,
onDescriptionChange,
onLogoClick,
logoUploadAriaLabel,
}: RuleViewProps) { }: RuleViewProps) {
const ariaLabel = cardAriaLabel; const ariaLabel = cardAriaLabel;
const interactiveCard = interactive ?? !hasBottomLinks; const interactiveCard = interactive ?? !hasBottomLinks;
@@ -229,9 +243,39 @@ export function RuleView({
); );
} }
if (hasNameField) {
return (
<span
className={`${logoContainerClass} flex items-center justify-center rounded-full border border-dashed border-[var(--color-content-invert-primary)] text-[24px] leading-none text-[var(--color-content-invert-primary)]`}
aria-hidden={onLogoClick ? true : undefined}
>
+
</span>
);
}
return null; return null;
}; };
const renderLogoControl = () => {
const inner = renderLogo();
if (!inner) return null;
if (!onLogoClick) return inner;
return (
<button
type="button"
className="cursor-pointer rounded-full p-0"
aria-label={logoUploadAriaLabel}
onClick={(event) => {
event.stopPropagation();
onLogoClick();
}}
>
{inner}
</button>
);
};
// Border radius - use CSS classes if provided via className, otherwise use size-based logic // Border radius - use CSS classes if provided via className, otherwise use size-based logic
const borderRadiusClass = className?.includes("rounded-") const borderRadiusClass = className?.includes("rounded-")
? "" // If className already has border radius, don't add size-based one ? "" // If className already has border radius, don't add size-based one
@@ -291,12 +335,36 @@ export function RuleView({
.join(" "); .join(" ");
const showExpandedDescription = Boolean( const showExpandedDescription = Boolean(
hasNameField ||
description || description ||
(onDescriptionClick && typeof descriptionEmptyHint === "string"), (onDescriptionClick && typeof descriptionEmptyHint === "string"),
); );
const expandedDescription = showExpandedDescription ? ( const expandedDescription = showExpandedDescription ? (
<div className={expandedDescriptionFrameClass}> <div className={expandedDescriptionFrameClass}>
{onDescriptionClick ? ( {hasNameField && onDescriptionChange ? (
<div
className="flex w-full min-w-0 flex-col gap-[6px]"
data-testid="rule-description-field"
onClick={(event) => event.stopPropagation()}
>
<InputLabel
label={descriptionLabel ?? ""}
helpIcon={false}
helperText={descriptionHelperText}
size="s"
/>
<TextArea
label={descriptionLabel}
placeholder={descriptionPlaceholder}
value={description ?? ""}
onChange={(event) => onDescriptionChange(event.target.value)}
size="small"
formHeader={false}
showHelpIcon={false}
rows={2}
/>
</div>
) : onDescriptionClick ? (
<InlineTextButton <InlineTextButton
type="button" type="button"
underline={false} underline={false}
@@ -333,12 +401,12 @@ export function RuleView({
w-full shrink-0 items-center gap-px w-full shrink-0 items-center gap-px
" "
> >
{renderLogo() && ( {(renderLogoControl() || hasNameField) && (
<div className={headerIconCellClass}> <div className={headerIconCellClass}>
{renderLogo()} {renderLogoControl()}
</div> </div>
)} )}
{title && ( {(title || hasNameField) && (
<div <div
className={` className={`
flex min-w-0 flex-1 flex-col justify-center flex min-w-0 flex-1 flex-col justify-center
@@ -365,7 +433,31 @@ export function RuleView({
{recommendedLabel} {recommendedLabel}
</Tag> </Tag>
) : null} ) : null}
{onTitleClick ? ( {hasNameField && onNameChange ? (
<div
className="flex w-full min-w-0 flex-col gap-[6px]"
data-testid="rule-name-field"
onClick={(event) => event.stopPropagation()}
>
<InputLabel
label={nameLabel ?? ""}
helpIcon={false}
asterisk
size="s"
/>
<TextInput
label={nameLabel}
placeholder={namePlaceholder}
value={nameValue}
onChange={(event) => onNameChange(event.target.value)}
inputSize="small"
formHeader={false}
showHelpIcon={false}
required
autoFocus={nameValue.trim().length === 0}
/>
</div>
) : onTitleClick ? (
<InlineTextButton <InlineTextButton
type="button" type="button"
underline={false} underline={false}
+9 -13
View File
@@ -16,7 +16,7 @@ The Figma **Create Community** sequence is the **source of truth** for the first
Treat these stages as the **canonical product sections** when adding chrome (e.g. stage headers, progress copy), breaking work across teams, or reusing flows in other surfaces. **Layout kind** is **not** encoded in the URL; it lives in [`CREATE_FLOW_SCREEN_REGISTRY`](../app/(app)/create/utils/createFlowScreenRegistry.ts) (Figma node id + `layoutKind` per step). Figma still names eight layout kinds: **informational**, **text**, **select**, **upload**, **review**, **card**, **right-rail**, **completed**. Question-and-options steps (**select**, **card**, **right-rail**) share [`CreateFlowTwoColumnSelectShell`](../app/(app)/create/components/CreateFlowTwoColumnSelectShell.tsx) and [`Selection`](../app/components/cards/Selection/) size variants (`s` chip, `m` tile, `l` row). `app/(app)/create/screens/` still mirrors the Figma kind names. Treat these stages as the **canonical product sections** when adding chrome (e.g. stage headers, progress copy), breaking work across teams, or reusing flows in other surfaces. **Layout kind** is **not** encoded in the URL; it lives in [`CREATE_FLOW_SCREEN_REGISTRY`](../app/(app)/create/utils/createFlowScreenRegistry.ts) (Figma node id + `layoutKind` per step). Figma still names eight layout kinds: **informational**, **text**, **select**, **upload**, **review**, **card**, **right-rail**, **completed**. Question-and-options steps (**select**, **card**, **right-rail**) share [`CreateFlowTwoColumnSelectShell`](../app/(app)/create/components/CreateFlowTwoColumnSelectShell.tsx) and [`Selection`](../app/components/cards/Selection/) size variants (`s` chip, `m` tile, `l` row). `app/(app)/create/screens/` still mirrors the Figma kind names.
**Create from template (future):** A full **template-driven** create path is **not** finalized; it will likely live on **additional route(s)** (and may reuse these stages where it overlaps the custom trajectory). Today, **`/create/review-template/[slug]`** is only an auxiliary **preview** in the create shell; it is **not** a Figma stage and not the final template-create entry. See **Out of scope** in [CR-89](https://linear.app/community-rule/issue/CR-89/product-canon-custom-create-rule-wizard-routes-resume-progress-repo). **Create from template:** Starting from a template skips size, kind, scale, maturity, and the six setup questions. The group enters only name, photo, and description. There is no recommendation engine on this path. **Customize** opens a dialog, then walks values and the four decks with the template’s cards first. **Use without changes** skips the dialog and decks and lands on final review with the template’s cards. Identity is collected in the Customize dialog or on the final-review Rule card (Has Name Field). The pin is `pendingTemplateAction: { slug, mode }` on `CreateFlowState`.
--- ---
@@ -79,19 +79,17 @@ Call sites for **`prepareFreshCreateFlowEntry`**: [`Top.container.tsx`](../app/c
| `/create/review-template/[slug]` | Template preview in the create shell; uses the same layout/footer chrome as other create pages but **is not** part of `FLOW_STEP_ORDER` **or** the three Figma stages above. | | `/create/review-template/[slug]` | Template preview in the create shell; uses the same layout/footer chrome as other create pages but **is not** part of `FLOW_STEP_ORDER` **or** the three Figma stages above. |
| `/create/templates` | In-flow template catalog after review **Create from template**. Same create chrome (Back, Save & Exit); cards link to `/create/review-template/[slug]?fromFlow=1`. Marketing `/templates` stays the public catalog. | | `/create/templates` | In-flow template catalog after review **Create from template**. Same create chrome (Back, Save & Exit); cards link to `/create/review-template/[slug]?fromFlow=1`. Marketing `/templates` stays the public catalog. |
From that page, **Customize** pre-fills the custom-rule selections on the current `CreateFlowState` (via [`buildTemplateCustomizePrefill`](../lib/create/applyTemplatePrefill.ts)) and routes to **`/create/core-values`** when the community name (`state.title`) is already set, otherwise to **`/create/informational`**. Name-only is the gate because other community-stage fields (e.g. `communityStructureChipSnapshots`) are sticky once the user lands on those screens; a non-empty title is also the minimum bar [`buildPublishPayload`](../lib/create/buildPublishPayload.ts) enforces, so the two checks stay aligned. No query-param plumbing: state persists via the usual anonymous/server-draft mirrors. From that page, **Customize** opens a dialog for name, optional logo, description (“What does your community do?”), and optional city or region. Continue prefills the template’s cards and values (via [`buildTemplateCustomizePrefill`](../lib/create/applyTemplatePrefill.ts) plus catalog copy from [`templatePresetDetailsFromPrefill`](../lib/create/applyTemplatePrefill.ts)), pins `pendingTemplateAction: { slug, mode: "customize" }`, and routes to **`/create/core-values`**. Size, kind, scale, maturity, and setup questions are skipped. The decks show the template’s cards first, then the rest of the deck, with no RECOMMENDED tag, no seven-card cut, and no engine call (`templateDeck` in [`deckRecommend.ts`](../lib/create/deckRecommend.ts)). Confirm on each deck walks communication → membership → decisions → conflict → final review. Back from values returns to template review; Back from named final review returns to the conflict deck.
**Exit on template preview.** Direct catalog / marketing entry (`/create/review-template/[slug]` without `?fromFlow=1`) has nothing to save — top-nav **Exit** clears client state and goes home, with no save-progress modal and no leave confirm. In-flow (`?fromFlow=1`) still has community progress, so Exit keeps the usual save / leave-confirm path. **Exit on template preview.** Direct catalog / marketing entry (`/create/review-template/[slug]` without `?fromFlow=1`) has nothing to save — top-nav **Exit** clears client state and goes home, with no save-progress modal and no leave confirm. In-flow (`?fromFlow=1`) still has community progress, so Exit keeps the usual save / leave-confirm path.
**Use without changes** writes the template's `body.sections` into `state.sections` (chip titles only; bodies are empty in seeded templates), resets any prior Customize chip selections so they don't bleed into `document.coreValues`, and skips custom-rule authoring. It does **not** copy the template catalog `description` into `state.summary` — the published rule summary comes from **`communityContext` first**, then `summary`, when the user publishes. At publish, [`buildPublishPayload`](../lib/create/buildPublishPayload.ts) derives `methodSelections` from those section titles, merges preset copy into `document.sections`, and emits structured `methodSelections`. Continue on final review opens **Invite your members**. Finishing there runs **`handleFinalize → publishRule`**. Guests can publish without signing in (`POST /api/rules` with `userId` null); stakeholder invites are sent only when a session exists. **Use without changes** skips the dialog, seeds the template’s cards (chip ids from [`templateChips.json`](../data/templates/templateChips.json) plus `state.sections` titles), pins `pendingTemplateAction: { slug, mode: "useWithoutChanges" }`, and routes to **`/create/final-review`**. Direct catalog entry clears leftover identity so the Rule card can collect name, photo, and description. In-flow keeps the community answers already given. Continue on final review waits for a name, then opens **Invite your members**. Finishing there runs **`handleFinalize → publishRule`**. Guests can publish without signing in (`POST /api/rules` with `userId` null); stakeholder invites are sent only when a session exists. Every card that reads the group’s share uses three quarters (`LAUNCH_SUPERMAJORITY_SHARE`); final review does not ask for a share.
**Entering a template before community stage is done.** Both handlers apply their side effects eagerly (prefill for Customize; `sections` for Use without changes) *and* pin a `pendingTemplateAction: { slug, mode }` when the community questionnaire still needs to run. **The pin stays for the rest of the wizard** so decks skip the engine, final review shows Has Name Field, and Back knows the path. If a leftover pin lands on `/create/review`, [`CommunityReviewScreen`](../app/(app)/create/screens/review/CommunityReviewScreen.tsx) `replace`s to `core-values` (Customize) or `final-review` (Use without changes).
- **Customize** routes to `/create/informational` and walks the full Create Community questionnaire. Once the user reaches `/create/review`, [`CommunityReviewScreen`](../app/(app)/create/screens/review/CommunityReviewScreen.tsx) reads the action on mount, clears it via `updateState`, and `router.replace`s to `/create/core-values`. `replace` (not `push`) keeps `community-save` as the Back-button target from that destination. - **Customize** — dialog, then values and the four decks, then final review with the dialog’s Community name filled in. Add chips on final review open that template deck or the template values; Confirm returns to final review (`?reviewReturn=final-review`).
- **Use without changes (direct from a template)** — home Popular templates, `/templates` without `fromFlow`, or a pasted review-template URL. Always routes to `/create/community-name` and walks **name → description → optional photo**, then `/create/final-review`. A leftover draft title is **not** “community already done”; those identity fields are cleared so cache cannot skip or pre-fill the path. Intro, structure, size, setup questions, save, community review, and custom-rule authoring are skipped. Back from name returns to template review. - **Use without changes (direct)** — home Popular templates, `/templates` without `fromFlow`, or a pasted review-template URL. Identity is collected on the final-review Rule card. Back returns to template review.
- **Use without changes (in-flow)** — `/create/review` → `/create/templates` → template. Community identity is already collected, so this action seeds the template and routes to `/create/final-review`. Back returns to template review. - **Use without changes (in-flow)** — `/create/review` → `/create/templates` → template. Community identity is already collected. Back still returns to template review.
The action for Customize is cleared on the first fire so later direct visits to `/create/review` render normally. The review screen is not part of the Use-without-changes identity path. If they land on `/create/review` with a leftover Use-without-changes pin, the screen `replace`s to `community-name`.
**Direct entry vs in-flow template pick.** The same `/create/review-template/[slug]` URL is reached from two different origins. We disambiguate at the *click site*, not on the review-template page. **Direct** picks call [`prepareFreshCreateFlowEntry`](../app/(app)/create/utils/prepareFreshCreateFlowEntry.ts) **before** navigation (local + server draft when sync is on — see **Fresh start vs continue draft** above). **In-flow** picks skip that call so the user’s community-stage state survives the detour. Because `CreateFlowProvider` reads `localStorage` in its `useState` initializer, clearing **before** `push` means a direct entry mounts without stale anonymous keys; signed-in users also avoid a stale server draft overwriting the empty mirror. **Direct entry vs in-flow template pick.** The same `/create/review-template/[slug]` URL is reached from two different origins. We disambiguate at the *click site*, not on the review-template page. **Direct** picks call [`prepareFreshCreateFlowEntry`](../app/(app)/create/utils/prepareFreshCreateFlowEntry.ts) **before** navigation (local + server draft when sync is on — see **Fresh start vs continue draft** above). **In-flow** picks skip that call so the user’s community-stage state survives the detour. Because `CreateFlowProvider` reads `localStorage` in its `useState` initializer, clearing **before** `push` means a direct entry mounts without stale anonymous keys; signed-in users also avoid a stale server draft overwriting the empty mirror.
@@ -101,13 +99,11 @@ The action for Customize is cleared on the first fire so later direct visits to
| `/templates` index ([`TemplatesPageClient.tsx`](../app/(marketing)/templates/TemplatesPageClient.tsx)) visited directly / via pasted URL | `fromFlow` absent → `await prepareFreshCreateFlowEntry()` then navigate | `/create/review-template/[slug]` | | `/templates` index ([`TemplatesPageClient.tsx`](../app/(marketing)/templates/TemplatesPageClient.tsx)) visited directly / via pasted URL | `fromFlow` absent → `await prepareFreshCreateFlowEntry()` then navigate | `/create/review-template/[slug]` |
| In-flow: `/create/review` footer "Create from template" → `/create/templates` → template click | no fresh-entry prep; cards are `?fromFlow=1` links | `/create/review-template/[slug]?fromFlow=1` | | In-flow: `/create/review` footer "Create from template" → `/create/templates` → template click | no fresh-entry prep; cards are `?fromFlow=1` links | `/create/review-template/[slug]?fromFlow=1` |
Only one `?fromFlow=1` marker exists on template-review URLs. In-flow catalog clicks on `/create/templates` always include it so **Use without changes** can tell in-flow (skip identity) from a direct catalog start (collect name / description / photo). Profile still uses marketing `/templates?fromFlow=1`. **Customize** still branches on `state.title` (full questionnaire vs `core-values`). Only one `?fromFlow=1` marker exists on template-review URLs. In-flow catalog clicks on `/create/templates` always include it so **Use without changes** can keep in-flow identity instead of clearing it. Profile still uses marketing `/templates?fromFlow=1`. Templates on `/templates` and `/create/templates` show in curated order with no RECOMMENDED tag; facet scoring is unused.
**Resume from profile** remains explicit-only: **Continue** clears local mirrors then opens `/create/{step}` so [`SignedInDraftHydration`](../app/(app)/create/SignedInDraftHydration.tsx) can load `/api/drafts/me` when the client buffer is empty. There is no automatic “pick template from marketing → silently merge server draft” path. **Resume from profile** remains explicit-only: **Continue** clears local mirrors then opens `/create/{step}` so [`SignedInDraftHydration`](../app/(app)/create/SignedInDraftHydration.tsx) can load `/api/drafts/me` when the client buffer is empty. There is no automatic “pick template from marketing → silently merge server draft” path.
**Final-review Rule category chips** are derived from `CreateFlowState` via [`buildFinalReviewCategoriesFromState`](../lib/create/buildFinalReviewCategories.ts): for the Customize / plain custom-rule path it resolves `selected{Communication,Membership,DecisionApproach,ConflictManagement}MethodIds` against the curated method presets in `messages/en/create/customRule/*.json`, and `buildCoreValuesForDocument` supplies the `Values` row from `coreValuesChipsSnapshot` + `selectedCoreValueIds`. For the Use-without-changes path the template body lives in `state.sections`; the helper renders `categoryName` + entry titles directly. The demo chips shipped in `finalReview.json` remain the fallback only when nothing in state resolves to any chip (e.g. direct navigation for development). **Final-review Rule category chips** are derived from `CreateFlowState` via [`buildFinalReviewCategoriesFromState`](../lib/create/buildFinalReviewCategories.ts): for the Customize / plain custom-rule path it resolves `selected{Communication,Membership,DecisionApproach,ConflictManagement}MethodIds` against the curated method presets in `messages/en/create/customRule/*.json`, and `buildCoreValuesForDocument` supplies the `Values` row from `coreValuesChipsSnapshot` + `selectedCoreValueIds`. For the Use-without-changes path the template body lives in `state.sections`; the helper renders `categoryName` + entry titles directly, and preset ids from the chip file keep chips editable. The demo chips shipped in `finalReview.json` remain the fallback only when nothing in state resolves to any chip (e.g. direct navigation for development).
**Starting the wizard from a template at `final-review` directly** is out of scope until a dedicated product ticket ships. A **full create-from-template** experience will **likely use separate route(s)** when product and eng define it (may still align conceptually with the same three stages where behavior overlaps the custom path).
--- ---
+12 -27
View File
@@ -249,34 +249,19 @@ decision-approaches → conflict-management → confirm-stakeholders → final-r
| API detail | `app/api/templates/[slug]/route.ts` (`GET` — §9.4) | | API detail | `app/api/templates/[slug]/route.ts` (`GET` — §9.4) |
| API catalog | `app/api/create-flow/methods/route.ts` (`GET` — §9.2); `lib/server/governanceCatalog.ts` | | API catalog | `app/api/create-flow/methods/route.ts` (`GET` — §9.2); `lib/server/governanceCatalog.ts` |
**Marketing UIs** may omit `facet.*` (curated ordering only). When facets **Marketing UIs** omit `facet.*`. Templates carry no recommendation; the
are passed, templates are ranked and `scores` may be returned. Template **Customize** grid is curated order with no RECOMMENDED tag. Seeded facet marks remain
now prefills the custom-rule flow via in the database unused. Template **Customize** opens a name / photo /
[`buildTemplateCustomizePrefill`](../../lib/create/applyTemplatePrefill.ts) description dialog, prefills cards via
(applied in `CreateFlowLayoutClient.tsx`) and routes to `core-values` [`buildTemplateCustomizePrefill`](../../lib/create/applyTemplatePrefill.ts),
when Community already has input, else to `informational`. Template **Use and routes to `core-values` (setup questions skipped). Template **Use
without changes** writes `template.body.sections` into `state.sections`. without changes** writes the template’s cards and routes to
Direct catalog / marketing entry routes to `community-name` and Next/Back `final-review`. Identity is collected in the dialog or on the
collect only name, description, and optional photo, then final-review Rule card. The pin
`confirm-stakeholders`. A leftover draft title does not skip those
identity steps. In-flow (`?fromFlow=1` after the community questionnaire)
skips identity and opens `confirm-stakeholders`. The user
exits via the normal
`final-review → handleFinalize → publishRule` path and picks up the
server-enforced 401 sign-in gate for free.
When the user picks a template **before** completing the community
stage, both handlers still apply their side effects eagerly (prefill or
`sections`/`summary`) and pin a
`pendingTemplateAction: { slug, mode: "customize" | "useWithoutChanges" }` `pendingTemplateAction: { slug, mode: "customize" | "useWithoutChanges" }`
on `CreateFlowState`. Customize then routes to `informational`. Direct stays for the rest of the wizard so decks skip the engine. See
Use without changes routes to `community-name` (identity-only skip list [`docs/create-flow.md`](../create-flow.md). The user exits via
while the pin is set). Once the user reaches `/create/review`, `CommunityReviewScreen` `final-review → handleFinalize → publishRule`.
consumes the pin and `router.replace`s past itself — to `core-values` for
`customize`, to `community-name` for `useWithoutChanges`. The
community-review screen is therefore only shown when the user came from
"Create Custom" (no template), matching the intent already expressed at the
template-review step.
--- ---
+58 -8
View File
@@ -3,10 +3,19 @@ import type {
CreateFlowState, CreateFlowState,
} from "../../app/(app)/create/types"; } from "../../app/(app)/create/types";
import coreValuesMessages from "../../messages/en/create/customRule/coreValues.json"; import coreValuesMessages from "../../messages/en/create/customRule/coreValues.json";
import templateChipsFile from "../../data/templates/templateChips.json";
import { assignTemplateMethodSlugsToPrefill } from "./customRuleFacets"; import { assignTemplateMethodSlugsToPrefill } from "./customRuleFacets";
import { methodSlugFromTitle } from "./methodSlugFromTitle"; import { methodSlugFromTitle } from "./methodSlugFromTitle";
import type { DeckId } from "./deckTypes"; import {
communicationPresetFor,
conflictManagementPresetFor,
coreValuePresetFor,
decisionApproachPresetFor,
membershipPresetFor,
} from "./finalReviewChipPresets";
import {
templateChipsForSlug,
type TemplateChipSet,
} from "./templatePath";
type TemplateEntry = { title: unknown }; type TemplateEntry = { title: unknown };
type TemplateSection = { categoryName: unknown; entries: unknown }; type TemplateSection = { categoryName: unknown; entries: unknown };
@@ -101,13 +110,8 @@ function buildCoreValuePrefill(
* *
* Returns an empty object for malformed bodies (no sections array). * Returns an empty object for malformed bodies (no sections array).
*/ */
type TemplateChipSet = Record<DeckId | "coreValues", string[]>;
function prefillFromTemplateChips(slug: string): Partial<CreateFlowState> | null { function prefillFromTemplateChips(slug: string): Partial<CreateFlowState> | null {
const templates = ( const chips: TemplateChipSet | null = templateChipsForSlug(slug);
templateChipsFile as { templates: Record<string, TemplateChipSet> }
).templates;
const chips = templates[slug];
if (!chips) return null; if (!chips) return null;
const selected = new Set(chips.coreValues); const selected = new Set(chips.coreValues);
return { return {
@@ -173,3 +177,49 @@ export function buildCoreValuesPrefillFromTemplateBody(
coreValuesChipsSnapshot: full.coreValuesChipsSnapshot, coreValuesChipsSnapshot: full.coreValuesChipsSnapshot,
}; };
} }
/**
* Catalog copy for each prefilled chip, so a template copy keeps the card
* text instead of opening empty Generate-draft fields.
*/
export function templatePresetDetailsFromPrefill(
prefill: Partial<CreateFlowState>,
): Partial<CreateFlowState> {
const communicationMethodDetailsById: NonNullable<
CreateFlowState["communicationMethodDetailsById"]
> = {};
for (const id of prefill.selectedCommunicationMethodIds ?? []) {
communicationMethodDetailsById[id] = communicationPresetFor(id);
}
const membershipMethodDetailsById: NonNullable<
CreateFlowState["membershipMethodDetailsById"]
> = {};
for (const id of prefill.selectedMembershipMethodIds ?? []) {
membershipMethodDetailsById[id] = membershipPresetFor(id);
}
const decisionApproachDetailsById: NonNullable<
CreateFlowState["decisionApproachDetailsById"]
> = {};
for (const id of prefill.selectedDecisionApproachIds ?? []) {
decisionApproachDetailsById[id] = decisionApproachPresetFor(id);
}
const conflictManagementDetailsById: NonNullable<
CreateFlowState["conflictManagementDetailsById"]
> = {};
for (const id of prefill.selectedConflictManagementIds ?? []) {
conflictManagementDetailsById[id] = conflictManagementPresetFor(id);
}
const coreValueDetailsByChipId: NonNullable<
CreateFlowState["coreValueDetailsByChipId"]
> = {};
for (const id of prefill.selectedCoreValueIds ?? []) {
coreValueDetailsByChipId[id] = coreValuePresetFor(id);
}
return {
communicationMethodDetailsById,
membershipMethodDetailsById,
decisionApproachDetailsById,
conflictManagementDetailsById,
coreValueDetailsByChipId,
};
}
-52
View File
@@ -15,18 +15,8 @@ export type RuleTemplateDto = {
type TemplatesResponse = { type TemplatesResponse = {
templates?: RuleTemplateDto[]; templates?: RuleTemplateDto[];
scores?: Record<string, TemplateFacetScoreDto>;
}; };
function parseScoresPayload(
raw: unknown,
): Record<string, TemplateFacetScoreDto> {
if (raw && typeof raw === "object" && !Array.isArray(raw)) {
return raw as Record<string, TemplateFacetScoreDto>;
}
return {};
}
async function getTemplatesJson( async function getTemplatesJson(
queryString: string, queryString: string,
signal: AbortSignal | undefined, signal: AbortSignal | undefined,
@@ -51,17 +41,6 @@ async function getTemplatesJson(
} }
} }
/** Matches `listRankedRuleTemplatesFromDb` / GET `/api/templates` with facet params. */
export type TemplateFacetScoreDto = {
score: number;
matchedFacets: string[];
};
export type RankedTemplatesFetchResult = {
templates: RuleTemplateDto[];
scores: Record<string, TemplateFacetScoreDto>;
};
export type FetchTemplatesOptions = { export type FetchTemplatesOptions = {
signal?: AbortSignal; signal?: AbortSignal;
}; };
@@ -100,37 +79,6 @@ export async function fetchTemplates(
return Array.isArray(data.templates) ? data.templates : []; return Array.isArray(data.templates) ? data.templates : [];
} }
/**
* Facet-ranked list + per-template scores (CR-88). Query must be non-empty
* `facet.size=…&…` from {@link buildFacetQueryString}.
*/
export async function fetchRankedTemplatesByFacets(options: {
facetQuery: string;
signal?: AbortSignal;
}): Promise<RankedTemplatesFetchResult | { error: string }> {
if (options.facetQuery.length === 0) {
return { error: "Could not load templates" };
}
const got = await getTemplatesJson(options.facetQuery, options.signal);
if (got.ok === false) {
if (got.error === "aborted") {
throw new DOMException("Aborted", "AbortError");
}
return { error: "Could not load templates" };
}
const { data, statusOk } = got;
if (!statusOk) {
return {
error:
typeof data.error === "string"
? data.error
: "Could not load templates",
};
}
const templates = Array.isArray(data.templates) ? data.templates : [];
return { templates, scores: parseScoresPayload(data.scores) };
}
export type TemplateDetailDto = { export type TemplateDetailDto = {
template: RuleTemplateDto; template: RuleTemplateDto;
methods: Array<{ section: string; slug: string }>; methods: Array<{ section: string; slug: string }>;
+92
View File
@@ -0,0 +1,92 @@
import type { CreateFlowState } from "../../app/(app)/create/types";
import type { DeckId } from "./deckTypes";
import templateChipsFile from "../../data/templates/templateChips.json";
export type TemplatePathMode = "customize" | "useWithoutChanges";
export type TemplatePath = {
slug: string;
mode: TemplatePathMode;
};
export type TemplateChipSet = Record<DeckId | "coreValues", string[]>;
/**
* Persistent template-path pin. Kept for the rest of the wizard so decks skip
* the engine, final review shows identity fields, and Back knows whether to
* return to the template or to the conflict deck.
*/
export function templatePathFromState(
state: Pick<CreateFlowState, "pendingTemplateAction">,
): TemplatePath | null {
const pending = state.pendingTemplateAction;
if (!pending) return null;
const slug = pending.slug.trim();
if (!slug) return null;
if (pending.mode !== "customize" && pending.mode !== "useWithoutChanges") {
return null;
}
return { slug, mode: pending.mode };
}
export function isTemplateCreatePath(
state: Pick<CreateFlowState, "pendingTemplateAction">,
): boolean {
return templatePathFromState(state) !== null;
}
export function templateChipsForSlug(slug: string): TemplateChipSet | null {
const templates = (
templateChipsFile as { templates: Record<string, TemplateChipSet> }
).templates;
const chips = templates[slug];
return chips ?? null;
}
export function templateCardIdsForDeck(
slug: string,
deck: DeckId,
): string[] {
const chips = templateChipsForSlug(slug);
if (!chips) return [];
return [...chips[deck]];
}
export function templateValueIdsForSlug(slug: string): string[] {
const chips = templateChipsForSlug(slug);
if (!chips) return [];
return [...chips.coreValues];
}
export function templateChipCounts(slug: string): {
values: number;
cards: number;
} | null {
const chips = templateChipsForSlug(slug);
if (!chips) return null;
return {
values: chips.coreValues.length,
cards:
chips.communication.length +
chips.membership.length +
chips.decisionApproaches.length +
chips.conflictManagement.length,
};
}
/** Put `firstIds` at the head (stable), then the remaining items in their original order. */
export function orderIdsFirst<T extends { id: string }>(
items: readonly T[],
firstIds: readonly string[],
): T[] {
const byId = new Map(items.map((item) => [item.id, item] as const));
const seen = new Set<string>();
const head: T[] = [];
for (const id of firstIds) {
const item = byId.get(id);
if (!item || seen.has(id)) continue;
seen.add(id);
head.push(item);
}
return [...head, ...items.filter((item) => !seen.has(item.id))];
}
+2 -2
View File
@@ -14,8 +14,8 @@ export type GovernanceTemplateCatalogEntry = {
/** Path under public/ for getAssetPath() — Figma Asset / Template Mark */ /** Path under public/ for getAssetPath() — Figma Asset / Template Mark */
iconPath: string; iconPath: string;
/** /**
* When true, static catalog rows show the “RECOMMENDED” tag. Facet-ranked * Templates carry no recommendation. Kept so grid card rows stay a
* `/templates` sets this in `gridEntriesWithFacetScores` instead. * stable shape; always treat as false.
*/ */
recommended?: boolean; recommended?: boolean;
}; };
+3 -67
View File
@@ -1,4 +1,4 @@
import type { RuleTemplateDto, TemplateFacetScoreDto } from "../create/fetchTemplates"; import type { RuleTemplateDto } from "../create/fetchTemplates";
import { templateSummaryFromBody } from "../create/templateReviewMapping"; import { templateSummaryFromBody } from "../create/templateReviewMapping";
import type { GovernanceTemplateCatalogEntry } from "./governanceTemplateCatalog"; import type { GovernanceTemplateCatalogEntry } from "./governanceTemplateCatalog";
import { import {
@@ -25,7 +25,7 @@ function presentationForSlug(slug: string): Pick<
return { return {
iconPath: catalog.iconPath, iconPath: catalog.iconPath,
backgroundColor: catalog.backgroundColor, backgroundColor: catalog.backgroundColor,
recommended: catalog.recommended === true, recommended: false,
}; };
} }
return TEMPLATE_GRID_FALLBACK_PRESENTATION; return TEMPLATE_GRID_FALLBACK_PRESENTATION;
@@ -43,74 +43,10 @@ export function ruleTemplateToGridEntry(template: RuleTemplateDto): TemplateGrid
description, description,
iconPath: pres.iconPath, iconPath: pres.iconPath,
backgroundColor: pres.backgroundColor, backgroundColor: pres.backgroundColor,
recommended: pres.recommended, recommended: false,
}; };
} }
/**
* Max templates that show the “RECOMMENDED” tag when facet-ranked. Within the
* **top score tier** only: we do not pad with lower-scoring templates (e.g. two
* at score 4 and three at 3 → recommend the two 4s only), but if the top tier
* exceeds this cap we still take the first `limit` in API order.
*/
export const TEMPLATE_GRID_COMPACT_RECOMMENDED_LIMIT = 5;
/**
* Among templates in **API rank order** (score desc) with `score > 0`, mark
* only those in the **maximum-score tier** (no lower tiers), at most `limit`
* (API order is the tie-break when many tie for first place).
*/
export function deriveRecommendedTemplateSlugs(
templatesInRankOrder: ReadonlyArray<{ slug: string }>,
scores: Record<string, { score?: number } | undefined>,
limit: number,
): Set<string> {
if (limit <= 0) return new Set();
const matched = templatesInRankOrder.filter(
(t) => (scores[t.slug]?.score ?? 0) > 0,
);
if (matched.length === 0) return new Set();
let maxScore = 0;
for (const t of matched) {
const s = scores[t.slug]?.score ?? 0;
if (s > maxScore) maxScore = s;
}
const topTier = matched.filter(
(t) => (scores[t.slug]?.score ?? 0) === maxScore,
);
return new Set(topTier.slice(0, limit).map((t) => t.slug));
}
export type GridEntriesWithFacetScoresOptions = {
/** Default {@link TEMPLATE_GRID_COMPACT_RECOMMENDED_LIMIT}. */
compactRecommendedLimit?: number;
};
/**
* After `GET /api/templates?facet.*` with `scores`, mark `recommended` only
* for the top facet matches (see {@link deriveRecommendedTemplateSlugs}).
*/
export function gridEntriesWithFacetScores(
templates: RuleTemplateDto[],
scores: Record<string, TemplateFacetScoreDto>,
options?: GridEntriesWithFacetScoresOptions,
): TemplateGridCardEntry[] {
const cap =
options?.compactRecommendedLimit ?? TEMPLATE_GRID_COMPACT_RECOMMENDED_LIMIT;
const recommendedSlugs = deriveRecommendedTemplateSlugs(
templates,
scores,
cap,
);
return templates.map((t) => {
const base = ruleTemplateToGridEntry(t);
return {
...base,
recommended: recommendedSlugs.has(t.slug),
};
});
}
const bySlug = (templates: RuleTemplateDto[]) => const bySlug = (templates: RuleTemplateDto[]) =>
new Map(templates.map((t) => [t.slug, t] as const)); new Map(templates.map((t) => [t.slug, t] as const));
@@ -3,6 +3,7 @@
"description": "For example, we cook and share free meals with neighbors every Sunday.", "description": "For example, we cook and share free meals with neighbors every Sunday.",
"inputLabel": "Community description", "inputLabel": "Community description",
"placeholder": "Describe your community", "placeholder": "Describe your community",
"optional": "Optional",
"characterCountTemplate": "{current}/{max}", "characterCountTemplate": "{current}/{max}",
"locationLabel": "Where is your community based?", "locationLabel": "Where is your community based?",
"locationPlaceholder": "City or region", "locationPlaceholder": "City or region",
+40
View File
@@ -0,0 +1,40 @@
{
"_comment": "Customize dialog on template review. Figma Modal / Customize (template) 24991:40503.",
"title": "Customize the {template} template",
"description": "Your Rule starts with the {template} template's {valuesPhrase} and {cardsPhrase}. Next you can add, remove or rewrite any of them.",
"valuesOne": "one value",
"valuesMany": "{word} values",
"cardsOne": "one card",
"cardsMany": "{word} cards",
"countWords": {
"1": "one",
"2": "two",
"3": "three",
"4": "four",
"5": "five",
"6": "six",
"7": "seven",
"8": "eight",
"9": "nine",
"10": "ten",
"11": "eleven",
"12": "twelve",
"13": "thirteen",
"14": "fourteen",
"15": "fifteen",
"16": "sixteen",
"17": "seventeen",
"18": "eighteen",
"19": "nineteen",
"20": "twenty"
},
"nameHint": "You can change this later.",
"logoLabel": "Add a logo",
"logoHint": "Optional. A simple logo or graphic works best.",
"upload": "Upload",
"descriptionPlaceholder": "Say what your community does in one short sentence",
"privacyNote": "Only you can see your Rule until you invite your members.",
"cancel": "Cancel",
"continue": "Continue",
"nameRequired": "Add your community’s name to continue."
}
+2
View File
@@ -74,6 +74,7 @@ import createFooter from "./create/footer.json";
import createTopNav from "./create/topNav.json"; import createTopNav from "./create/topNav.json";
import createDraftHydration from "./create/draftHydration.json"; import createDraftHydration from "./create/draftHydration.json";
import createTemplateReview from "./create/templateReview.json"; import createTemplateReview from "./create/templateReview.json";
import createTemplateCustomize from "./create/templateCustomize.json";
import createUpload from "./create/upload.json"; import createUpload from "./create/upload.json";
import createDraftField from "./create/draftField.json"; import createDraftField from "./create/draftField.json";
@@ -150,6 +151,7 @@ export default {
topNav: createTopNav, topNav: createTopNav,
draftHydration: createDraftHydration, draftHydration: createDraftHydration,
templateReview: createTemplateReview, templateReview: createTemplateReview,
templateCustomize: createTemplateCustomize,
upload: createUpload, upload: createUpload,
draftField: createDraftField, draftField: createDraftField,
}, },
+2 -2
View File
@@ -196,10 +196,10 @@ describe("CommunityReviewScreen — pendingTemplateAction redirect", () => {
expect(testRouter.push).not.toHaveBeenCalled(); expect(testRouter.push).not.toHaveBeenCalled();
}); });
it("redirects Use without changes to community-name so identity is not skipped", async () => { it("redirects Use without changes leftover pins to final review", async () => {
render(<ReviewWithPendingAction mode="useWithoutChanges" />); render(<ReviewWithPendingAction mode="useWithoutChanges" />);
await waitFor(() => { await waitFor(() => {
expect(testRouter.replace).toHaveBeenCalledWith("/create/community-name"); expect(testRouter.replace).toHaveBeenCalledWith("/create/final-review");
}); });
expect(testRouter.push).not.toHaveBeenCalled(); expect(testRouter.push).not.toHaveBeenCalled();
}); });
@@ -0,0 +1,24 @@
import { describe, expect, it } from "vitest";
import "@testing-library/jest-dom/vitest";
import { renderWithProviders as render } from "../utils/test-utils";
import { TemplateCustomizeDialog } from "../../app/(app)/create/components/TemplateCustomizeDialog";
describe("TemplateCustomizeDialog", () => {
it("uses the same blurred yellow backdrop as other create-flow Create modals", () => {
render(
<TemplateCustomizeDialog
isOpen
templateTitle="Consensus"
valuesCount={3}
cardsCount={10}
initialTitle=""
initialDescription=""
initialLocation=""
onClose={() => undefined}
onContinue={() => undefined}
/>,
);
expect(document.querySelector(".backdrop-blur-md")).toBeInTheDocument();
});
});
+1
View File
@@ -30,5 +30,6 @@ describe("Create flow templates picker", () => {
"href", "href",
"/create/review-template/solidarity-network?fromFlow=1", "/create/review-template/solidarity-network?fromFlow=1",
); );
expect(screen.queryByText("RECOMMENDED")).not.toBeInTheDocument();
}); });
}); });
+1
View File
@@ -52,6 +52,7 @@ describe("Templates page (/templates)", () => {
for (const entry of GOVERNANCE_TEMPLATE_CATALOG) { for (const entry of GOVERNANCE_TEMPLATE_CATALOG) {
expect(screen.getByText(entry.title)).toBeInTheDocument(); expect(screen.getByText(entry.title)).toBeInTheDocument();
} }
expect(screen.queryByText("RECOMMENDED")).not.toBeInTheDocument();
}); });
test("each template card is a link to review flow for its slug", () => { test("each template card is a link to review flow for its slug", () => {
+33
View File
@@ -332,4 +332,37 @@ describe("Rule Component", () => {
expect(screen.queryByText("RECOMMENDED")).not.toBeInTheDocument(); expect(screen.queryByText("RECOMMENDED")).not.toBeInTheDocument();
}); });
it("renders name, logo upload, and description fields when hasNameField is set", () => {
const onNameChange = vi.fn();
const onDescriptionChange = vi.fn();
const onLogoClick = vi.fn();
render(
<Rule
title=""
interactive={false}
expanded
hasNameField
nameValue=""
nameLabel="Community name"
namePlaceholder="Enter community name"
onNameChange={onNameChange}
descriptionLabel="What does your community do?"
descriptionPlaceholder="Describe your community"
descriptionHelperText="Optional"
onDescriptionChange={onDescriptionChange}
onLogoClick={onLogoClick}
logoUploadAriaLabel="Add a logo"
/>,
);
expect(screen.getByLabelText("Community name")).toBeInTheDocument();
expect(screen.getByPlaceholderText("Enter community name")).toBeInTheDocument();
expect(
screen.getByLabelText("What does your community do?"),
).toBeInTheDocument();
expect(screen.getByText("Optional")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Add a logo" }));
expect(onLogoClick).toHaveBeenCalledTimes(1);
});
}); });
+43
View File
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import { import {
buildCoreValuesPrefillFromTemplateBody, buildCoreValuesPrefillFromTemplateBody,
buildTemplateCustomizePrefill, buildTemplateCustomizePrefill,
templatePresetDetailsFromPrefill,
} from "../../lib/create/applyTemplatePrefill"; } from "../../lib/create/applyTemplatePrefill";
import { methodSectionsPinsForHydratedSelections } from "../../lib/create/publishedDocumentToCreateFlowState"; import { methodSectionsPinsForHydratedSelections } from "../../lib/create/publishedDocumentToCreateFlowState";
import coreValuesMessages from "../../messages/en/create/customRule/coreValues.json"; import coreValuesMessages from "../../messages/en/create/customRule/coreValues.json";
@@ -196,3 +197,45 @@ describe("buildTemplateCustomizePrefill + method card pins", () => {
expect(methodSectionsPinsForHydratedSelections(prefill)).toEqual({}); expect(methodSectionsPinsForHydratedSelections(prefill)).toEqual({});
}); });
}); });
describe("buildTemplateCustomizePrefill from templateChips.json", () => {
it("prefers chip ids for a known slug over body titles", () => {
const prefill = buildTemplateCustomizePrefill(
{
sections: [
{
categoryName: "Communication",
entries: [{ title: "Signal" }],
},
],
},
"consensus",
);
expect(prefill.selectedCommunicationMethodIds).toEqual([
"how-we-run-meetings",
"in-person-meetings",
"loomio",
]);
expect(prefill.selectedCoreValueIds).toEqual([
"consensus",
"community-care",
"horizontalism",
]);
});
});
describe("templatePresetDetailsFromPrefill", () => {
it("fills catalog copy for each prefilled chip", () => {
const details = templatePresetDetailsFromPrefill({
selectedCommunicationMethodIds: ["in-person-meetings"],
selectedCoreValueIds: ["consensus"],
});
expect(
details.communicationMethodDetailsById?.["in-person-meetings"]
?.corePrinciple,
).not.toBe("");
expect(
details.coreValueDetailsByChipId?.consensus?.meaning,
).not.toBe("");
});
});
+79 -37
View File
@@ -10,6 +10,7 @@ import {
parseCreateFlowScreenFromPathname, parseCreateFlowScreenFromPathname,
resolveCreateFlowBackTarget, resolveCreateFlowBackTarget,
shouldOfferCreateFlowSaveAndExit, shouldOfferCreateFlowSaveAndExit,
templatePathSkippedCommunityRedirect,
isDirectTemplateReviewEntry, isDirectTemplateReviewEntry,
isCreateFlowTemplatesPickerPath, isCreateFlowTemplatesPickerPath,
createFlowStepUsesSelectSplitScroll, createFlowStepUsesSelectSplitScroll,
@@ -92,30 +93,91 @@ describe("flowSteps", () => {
expect(getPreviousStep("communication-methods", opts)).toBe("core-values"); expect(getPreviousStep("communication-methods", opts)).toBe("core-values");
}); });
it("useWithoutChangesIdentityOnly walks name → description → photo → final-review", () => { it("templatePathMode customize skips community setup and walks the decks", () => {
const opts = { useWithoutChangesIdentityOnly: true } as const; const opts = { templatePathMode: "customize" as const };
expect(getNextStep("community-name", opts)).toBe("community-context"); expect(getNextStep("informational", opts)).toBe("core-values");
expect(getNextStep("community-context", opts)).toBe("community-upload"); expect(getNextStep("community-name", opts)).toBe("core-values");
expect(getNextStep("community-size", opts)).toBe("community-upload"); expect(getNextStep("setup-questions", opts)).toBe("core-values");
expect(getNextStep("setup-questions", opts)).toBe("community-upload"); expect(getNextStep("core-values", opts)).toBe("communication-methods");
expect(getNextStep("community-upload", opts)).toBe("final-review"); expect(getNextStep("conflict-management", opts)).toBe("final-review");
expect(getNextStep("final-review", opts)).toBe("confirm-stakeholders"); expect(getPreviousStep("core-values", opts)).toBeNull();
expect(getPreviousStep("community-context", opts)).toBe("community-name"); expect(getPreviousStep("final-review", opts)).toBe("conflict-management");
expect(getPreviousStep("community-upload", opts)).toBe("community-context");
expect(getPreviousStep("final-review", opts)).toBe("community-upload");
expect(getPreviousStep("community-name", opts)).toBeNull();
}); });
it("useWithoutChangesIdentityOnly composes with skipCommunitySave", () => { it("templatePathMode useWithoutChanges skips community setup and the decks", () => {
const opts = { templatePathMode: "useWithoutChanges" as const };
expect(getNextStep("informational", opts)).toBe("final-review");
expect(getNextStep("community-name", opts)).toBe("final-review");
expect(getNextStep("setup-questions", opts)).toBe("final-review");
expect(getNextStep("core-values", opts)).toBe("final-review");
expect(getNextStep("final-review", opts)).toBe("confirm-stakeholders");
expect(getPreviousStep("final-review", opts)).toBeNull();
});
it("templatePathSkippedCommunityRedirect resumes setup steps and leaves decks", () => {
expect(
templatePathSkippedCommunityRedirect("setup-questions", "customize"),
).toBe("core-values");
expect(templatePathSkippedCommunityRedirect("review", "customize")).toBe(
"core-values",
);
expect(
templatePathSkippedCommunityRedirect(
"community-name",
"useWithoutChanges",
),
).toBe("final-review");
expect(
templatePathSkippedCommunityRedirect("core-values", "useWithoutChanges"),
).toBeNull();
expect(
templatePathSkippedCommunityRedirect("final-review", "customize"),
).toBeNull();
expect(
templatePathSkippedCommunityRedirect("setup-questions", undefined),
).toBeNull();
});
it("templatePathMode composes with skipCommunitySave", () => {
const opts = { const opts = {
skipCommunitySave: true, skipCommunitySave: true,
useWithoutChangesIdentityOnly: true, templatePathMode: "useWithoutChanges" as const,
} as const; };
expect(getNextStep("community-upload", opts)).toBe("final-review"); expect(getNextStep("community-upload", opts)).toBe("final-review");
expect(getPreviousStep("final-review", opts)).toBe("community-upload"); expect(getPreviousStep("final-review", opts)).toBeNull();
}); });
it("resolveCreateFlowBackTarget returns template review when use-without slug is set on final-review", () => { it("resolveCreateFlowBackTarget returns template review from use-without-changes final-review", () => {
expect(
resolveCreateFlowBackTarget(
"final-review",
{ templatePathMode: "useWithoutChanges" },
"mutual-aid-mondays",
),
).toEqual({ kind: "templateReview", slug: "mutual-aid-mondays" });
});
it("resolveCreateFlowBackTarget returns template review from customize values", () => {
expect(
resolveCreateFlowBackTarget(
"core-values",
{ templatePathMode: "customize" },
"mutual-aid-mondays",
),
).toEqual({ kind: "templateReview", slug: "mutual-aid-mondays" });
});
it("resolveCreateFlowBackTarget sends customize final-review back to the conflict deck", () => {
expect(
resolveCreateFlowBackTarget(
"final-review",
{ templatePathMode: "customize" },
"mutual-aid-mondays",
),
).toEqual({ kind: "step", step: "conflict-management" });
});
it("resolveCreateFlowBackTarget returns template review when a slug is set without a mode", () => {
expect( expect(
resolveCreateFlowBackTarget( resolveCreateFlowBackTarget(
"final-review", "final-review",
@@ -125,26 +187,6 @@ describe("flowSteps", () => {
).toEqual({ kind: "templateReview", slug: "mutual-aid-mondays" }); ).toEqual({ kind: "templateReview", slug: "mutual-aid-mondays" });
}); });
it("resolveCreateFlowBackTarget sends identity-only community-name back to template review", () => {
expect(
resolveCreateFlowBackTarget(
"community-name",
{ useWithoutChangesIdentityOnly: true },
"mutual-aid-mondays",
),
).toEqual({ kind: "templateReview", slug: "mutual-aid-mondays" });
});
it("resolveCreateFlowBackTarget uses photo step behind final-review on the identity-only path", () => {
expect(
resolveCreateFlowBackTarget(
"final-review",
{ useWithoutChangesIdentityOnly: true },
"mutual-aid-mondays",
),
).toEqual({ kind: "step", step: "community-upload" });
});
it("resolveCreateFlowBackTarget falls back to linear previous when slug is absent", () => { it("resolveCreateFlowBackTarget falls back to linear previous when slug is absent", () => {
expect( expect(
resolveCreateFlowBackTarget("confirm-stakeholders", undefined, undefined), resolveCreateFlowBackTarget("confirm-stakeholders", undefined, undefined),
@@ -69,22 +69,56 @@ describe("useTemplateReviewActions", () => {
); );
} }
it("direct Use without changes walks identity from community-name", async () => { it("Customize opens the dialog and does not route until Continue", async () => {
const { result } = renderActions({}); const { result } = renderActions({});
await act(async () => { await act(async () => {
await result.current.handleUseWithoutChanges(); await result.current.handleCustomize();
}); });
expect(markCreateFlowInteraction).toHaveBeenCalled(); expect(markCreateFlowInteraction).toHaveBeenCalled();
expect(router.push).toHaveBeenCalledWith("/create/community-name"); expect(router.push).not.toHaveBeenCalled();
expect(applied?.pendingTemplateAction).toEqual({ expect(result.current.customizeDialog).toEqual(
slug: "mutual-aid-mondays", expect.objectContaining({
mode: "useWithoutChanges", slug: "mutual-aid-mondays",
}); templateTitle: "Mutual Aid Mondays",
}),
);
}); });
it("direct Use without changes ignores a leftover draft title", async () => { it("Customize Continue prefills cards, drops setup answers, and walks the decks", async () => {
const { result } = renderActions({
setupTraits: { employer: true },
});
await act(async () => {
await result.current.handleCustomize();
});
act(() => {
result.current.confirmCustomizeDialog({
title: "Neighborhood",
communityContext: "We meet weekly",
communityLocation: "Oakland",
});
});
expect(router.push).toHaveBeenCalledWith("/create/core-values");
expect(updateState).toHaveBeenCalledWith(
expect.objectContaining({
title: "Neighborhood",
communityContext: "We meet weekly",
communityLocation: "Oakland",
setupTraits: undefined,
pendingTemplateAction: {
slug: "mutual-aid-mondays",
mode: "customize",
},
templateReviewBackSlug: "mutual-aid-mondays",
}),
);
});
it("direct Use without changes goes to final review and clears leftover identity", async () => {
replaceState.mockImplementation( replaceState.mockImplementation(
(updater: (_prev: CreateFlowState) => CreateFlowState) => { (updater: (_prev: CreateFlowState) => CreateFlowState) => {
applied = updater({ applied = updater({
@@ -101,15 +135,18 @@ describe("useTemplateReviewActions", () => {
await result.current.handleUseWithoutChanges(); await result.current.handleUseWithoutChanges();
}); });
expect(router.push).toHaveBeenCalledWith("/create/community-name"); expect(router.push).toHaveBeenCalledWith("/create/final-review");
expect(applied?.title).toBeUndefined(); expect(applied?.title).toBeUndefined();
expect(applied?.communityContext).toBeUndefined(); expect(applied?.communityContext).toBeUndefined();
expect(applied?.currentStep).toBeUndefined(); expect(applied?.currentStep).toBeUndefined();
expect(applied?.setupTraits).toBeUndefined(); expect(applied?.setupTraits).toBeUndefined();
expect(applied?.pendingTemplateAction?.mode).toBe("useWithoutChanges"); expect(applied?.pendingTemplateAction).toEqual({
slug: "mutual-aid-mondays",
mode: "useWithoutChanges",
});
}); });
it("in-flow Use without changes skips identity and keeps the community name", async () => { it("in-flow Use without changes keeps the community name and pins the template path", async () => {
replaceState.mockImplementation( replaceState.mockImplementation(
(updater: (_prev: CreateFlowState) => CreateFlowState) => { (updater: (_prev: CreateFlowState) => CreateFlowState) => {
applied = updater({ applied = updater({
@@ -132,38 +169,11 @@ describe("useTemplateReviewActions", () => {
expect(router.push).toHaveBeenCalledWith("/create/final-review"); expect(router.push).toHaveBeenCalledWith("/create/final-review");
expect(applied?.title).toBe("Neighborhood"); expect(applied?.title).toBe("Neighborhood");
expect(applied?.communityContext).toBe("We meet weekly"); expect(applied?.communityContext).toBe("We meet weekly");
expect(applied?.setupTraits).toEqual({ employer: true }); expect(applied?.setupTraits).toBeUndefined();
expect(applied?.pendingTemplateAction).toBeUndefined(); expect(applied?.pendingTemplateAction).toEqual({
slug: "mutual-aid-mondays",
mode: "useWithoutChanges",
});
expect(applied?.templateReviewBackSlug).toBe("mutual-aid-mondays"); expect(applied?.templateReviewBackSlug).toBe("mutual-aid-mondays");
}); });
it("customize with a community name drops leftover setup answers", async () => {
const { result } = renderActions({
title: "Neighborhood",
setupTraits: { employer: true },
});
await act(async () => {
await result.current.handleCustomize();
});
expect(router.push).toHaveBeenCalledWith("/create/core-values");
expect(updateState).toHaveBeenCalledWith(
expect.objectContaining({ setupTraits: undefined }),
);
});
it("customize without a community name leaves setup answers for the questionnaire", async () => {
const { result } = renderActions({
setupTraits: { employer: true },
});
await act(async () => {
await result.current.handleCustomize();
});
expect(router.push).toHaveBeenCalledWith("/create/informational");
const patch = updateState.mock.calls[0]?.[0] as CreateFlowState;
expect(patch).not.toHaveProperty("setupTraits");
});
}); });
+6 -117
View File
@@ -1,9 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { describe, it, expect } from "vitest";
import { import { ruleTemplateToGridEntry } from "../../lib/templates/templateGridPresentation";
deriveRecommendedTemplateSlugs,
gridEntriesWithFacetScores,
} from "../../lib/templates/templateGridPresentation";
import { fetchRankedTemplatesByFacets } from "../../lib/create/fetchTemplates";
import type { RuleTemplateDto } from "../../lib/create/fetchTemplates"; import type { RuleTemplateDto } from "../../lib/create/fetchTemplates";
const minimalTemplate = (slug: string, title: string): RuleTemplateDto => ({ const minimalTemplate = (slug: string, title: string): RuleTemplateDto => ({
@@ -17,116 +13,9 @@ const minimalTemplate = (slug: string, title: string): RuleTemplateDto => ({
featured: false, featured: false,
}); });
describe("deriveRecommendedTemplateSlugs", () => { describe("ruleTemplateToGridEntry", () => {
it("returns at most limit slugs in the top score tier (API order for ties)", () => { it("never marks a template recommended", () => {
const templates = ["a", "b", "c", "d", "e", "f"].map((s) => ({ slug: s })); const row = ruleTemplateToGridEntry(minimalTemplate("do-ocracy", "Do-ocracy"));
const scores = Object.fromEntries( expect(row.recommended).toBe(false);
["a", "b", "c", "d", "e", "f"].map((s) => [
s,
{ score: 1, matchedFacets: [] as string[] },
]),
);
const set = deriveRecommendedTemplateSlugs(templates, scores, 5);
expect(set.size).toBe(5);
expect([...set]).toEqual(["a", "b", "c", "d", "e"]);
});
it("only recommends the highest score group, not lower tiers to fill the cap", () => {
const templates = ["a", "b", "c", "d", "e"].map((s) => ({ slug: s }));
const scores = {
a: { score: 4, matchedFacets: [] as string[] },
b: { score: 4, matchedFacets: [] as string[] },
c: { score: 3, matchedFacets: [] as string[] },
d: { score: 3, matchedFacets: [] as string[] },
e: { score: 3, matchedFacets: [] as string[] },
};
const set = deriveRecommendedTemplateSlugs(templates, scores, 5);
expect([...set]).toEqual(["a", "b"]);
});
});
describe("gridEntriesWithFacetScores", () => {
it("sets recommended true only for top compact matches (like card decks)", () => {
const t = minimalTemplate("do-ocracy", "Do-ocracy");
const [row] = gridEntriesWithFacetScores([t], {
"do-ocracy": { score: 3, matchedFacets: ["a"] },
});
expect(row.recommended).toBe(true);
});
it("does not mark lower-scoring templates recommended when a higher tier exists", () => {
const high = [
minimalTemplate("a", "A"),
minimalTemplate("b", "B"),
];
const low = minimalTemplate("c", "C");
const rows = gridEntriesWithFacetScores([...high, low], {
a: { score: 4, matchedFacets: [] },
b: { score: 4, matchedFacets: [] },
c: { score: 3, matchedFacets: [] },
});
const rec = rows.filter((r) => r.recommended).map((r) => r.slug);
expect(rec).toEqual(["a", "b"]);
});
it("caps top-tier recommended badges to compactRecommendedLimit", () => {
const slugs = ["a", "b", "c", "d", "e", "f"];
const templates = slugs.map((s) => minimalTemplate(s, s));
const scores = Object.fromEntries(
slugs.map((s) => [s, { score: 1, matchedFacets: [] as string[] }]),
);
const rows = gridEntriesWithFacetScores(templates, scores, {
compactRecommendedLimit: 5,
});
expect(rows.filter((r) => r.recommended).map((r) => r.slug)).toEqual([
"a",
"b",
"c",
"d",
"e",
]);
});
it("sets recommended false when score is zero or missing", () => {
const t = minimalTemplate("consensus", "Consensus");
const [a] = gridEntriesWithFacetScores([t], {
consensus: { score: 0, matchedFacets: [] },
});
const [b] = gridEntriesWithFacetScores([t], {});
expect(a.recommended).toBe(false);
expect(b.recommended).toBe(false);
});
});
describe("fetchRankedTemplatesByFacets", () => {
beforeEach(() => {
global.fetch = vi.fn();
});
afterEach(() => {
vi.restoreAllMocks();
});
it("parses ok JSON with templates and scores", async () => {
const template = minimalTemplate("s", "T");
vi.mocked(global.fetch).mockResolvedValue({
ok: true,
json: async () => ({
templates: [template],
scores: { s: { score: 1, matchedFacets: ["size:oneMember"] } },
}),
} as Response);
const r = await fetchRankedTemplatesByFacets({
facetQuery: "facet.size=oneMember",
});
expect("error" in r).toBe(false);
if (!("error" in r)) {
expect(r.templates).toEqual([template]);
expect(r.scores.s?.score).toBe(1);
}
});
it("returns error when facetQuery is empty", async () => {
const r = await fetchRankedTemplatesByFacets({ facetQuery: "" });
expect("error" in r).toBe(true);
}); });
}); });
+93
View File
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import { deckData, templateDeck } from "../../lib/create/deckRecommend";
import {
isTemplateCreatePath,
orderIdsFirst,
templateCardIdsForDeck,
templateChipCounts,
templatePathFromState,
templateValueIdsForSlug,
} from "../../lib/create/templatePath";
describe("templatePathFromState", () => {
it("reads a customize or use-without-changes pin", () => {
expect(templatePathFromState({})).toBeNull();
expect(
templatePathFromState({
pendingTemplateAction: { slug: "consensus", mode: "customize" },
}),
).toEqual({ slug: "consensus", mode: "customize" });
expect(
isTemplateCreatePath({
pendingTemplateAction: {
slug: "consensus",
mode: "useWithoutChanges",
},
}),
).toBe(true);
});
it("ignores a pin with no slug or an unknown mode", () => {
expect(
templatePathFromState({
pendingTemplateAction: { slug: " ", mode: "customize" },
}),
).toBeNull();
expect(
templatePathFromState({
pendingTemplateAction: {
slug: "consensus",
mode: "other" as "customize",
},
}),
).toBeNull();
});
});
describe("template chips", () => {
it("returns the consensus template's values and communication cards", () => {
expect(templateValueIdsForSlug("consensus")).toEqual([
"consensus",
"community-care",
"horizontalism",
]);
expect(templateCardIdsForDeck("consensus", "communication")).toEqual([
"how-we-run-meetings",
"in-person-meetings",
"loomio",
]);
expect(templateChipCounts("consensus")).toEqual({
values: 3,
cards: 10,
});
});
it("returns null counts for an unknown slug", () => {
expect(templateChipCounts("not-a-template")).toBeNull();
});
});
describe("orderIdsFirst", () => {
it("puts named ids first and keeps the rest in their original order", () => {
const items = [{ id: "a" }, { id: "b" }, { id: "c" }, { id: "d" }];
expect(orderIdsFirst(items, ["c", "a", "missing"])).toEqual([
{ id: "c" },
{ id: "a" },
{ id: "b" },
{ id: "d" },
]);
});
});
describe("templateDeck", () => {
it("puts the template's cards first, then the rest of the deck, with no cut", () => {
const data = deckData("communication");
const firstIds = templateCardIdsForDeck("consensus", "communication");
const ordered = templateDeck(data, firstIds);
expect(ordered.first).toEqual(firstIds);
expect(ordered.rest.some((id) => firstIds.includes(id))).toBe(false);
const all = [...ordered.first, ...ordered.rest];
expect(new Set(all).size).toBe(all.length);
expect(all.length).toBe(Object.keys(data.engine.cards).length);
});
});