Skip setup questions on the template path #101
No files matched your search
@@ -15,6 +15,7 @@ import { useCreateFlowExit } from "./hooks/useCreateFlowExit";
|
||||
import { usePrefetchMethodFacetRecommendations } from "./hooks/usePrefetchMethodFacetRecommendations";
|
||||
import { useCreateFlowFinalize } from "./hooks/useCreateFlowFinalize";
|
||||
import { useTemplateReviewActions } from "./hooks/useTemplateReviewActions";
|
||||
import { TemplateCustomizeDialog } from "./components/TemplateCustomizeDialog";
|
||||
import { useCompletedRuleShareExport } from "./hooks/useCompletedRuleShareExport";
|
||||
import CreateFlowFooter from "../../components/navigation/CreateFlowFooter";
|
||||
import CreateFlowTopNav from "../../components/navigation/CreateFlowTopNav";
|
||||
@@ -323,6 +324,9 @@ function CreateFlowLayoutContent({
|
||||
setTemplateReviewApplyError,
|
||||
handleCustomize: handleCustomizeTemplate,
|
||||
handleUseWithoutChanges: handleUseTemplateWithoutChanges,
|
||||
customizeDialog,
|
||||
closeCustomizeDialog,
|
||||
confirmCustomizeDialog,
|
||||
} = useTemplateReviewActions({
|
||||
pathname,
|
||||
state,
|
||||
@@ -876,6 +880,25 @@ function CreateFlowLayoutContent({
|
||||
backdropVariant="blurredYellow"
|
||||
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
|
||||
hasShare={isCompletedStep}
|
||||
hasExport={isCompletedStep}
|
||||
|
||||
@@ -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="default"
|
||||
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
|
||||
* {@link parseCreateFlowScreenFromPathname} (flowSteps). Footer Back uses
|
||||
* {@link resolveCreateFlowBackTarget}: template **Use without changes** that
|
||||
* still needs identity (direct from a template) walks name / description /
|
||||
* photo, then Back from `community-name` returns to
|
||||
* `/create/review-template/{slug}`. In-flow picks (`?fromFlow=1`) skip
|
||||
* identity and land on `final-review`; Back from that step returns
|
||||
* to the template instead of `conflict-management`.
|
||||
* {@link resolveCreateFlowBackTarget}: template **Customize** walks values
|
||||
* then the four decks, and Back from `core-values` returns to
|
||||
* `/create/review-template/{slug}`. **Use without changes** lands on
|
||||
* `final-review`; Back from that step returns to the template.
|
||||
*
|
||||
* Template review footer Back uses {@link buildTemplateReviewHref}’s
|
||||
* `?fromFlow=1` marker (and persisted `templateReviewEntryFromCreateFlow`) so
|
||||
@@ -87,14 +85,13 @@ export function useCreateFlowNavigation(
|
||||
updateState,
|
||||
]);
|
||||
|
||||
const identityOnly =
|
||||
state.pendingTemplateAction?.mode === "useWithoutChanges";
|
||||
const templatePathMode = state.pendingTemplateAction?.mode;
|
||||
const navigationOptions = useMemo(
|
||||
(): CreateFlowNavigationOptions => ({
|
||||
skipCommunitySave: options?.skipCommunitySave,
|
||||
useWithoutChangesIdentityOnly: identityOnly,
|
||||
templatePathMode,
|
||||
}),
|
||||
[options?.skipCommunitySave, identityOnly],
|
||||
[options?.skipCommunitySave, templatePathMode],
|
||||
);
|
||||
|
||||
const nextStep = getNextStep(validStep, navigationOptions);
|
||||
|
||||
@@ -8,7 +8,11 @@ import {
|
||||
groupAnswersForRecommendations,
|
||||
type RecommendationSection,
|
||||
} from "./useFacetRecommendations";
|
||||
import { deckData } from "../../../../lib/create/deckRecommend";
|
||||
import { deckData, templateDeck } from "../../../../lib/create/deckRecommend";
|
||||
import {
|
||||
templateCardIdsForDeck,
|
||||
templatePathFromState,
|
||||
} from "../../../../lib/create/templatePath";
|
||||
import { useCreateFlow } from "../context/CreateFlowContext";
|
||||
import { useMessages } from "../../../contexts/MessagesContext";
|
||||
|
||||
@@ -30,6 +34,8 @@ function orderByIds<T extends { id: string }>(
|
||||
/**
|
||||
* Deck order and the compact stack come from the job rule. Compact shows
|
||||
* at most seven recommended cards. Selected cards still pin into the stack.
|
||||
* On the template path the engine is not called: template cards first, then
|
||||
* the rest of the deck, with no tag and no seven-card cut.
|
||||
*/
|
||||
export function useMethodCardDeckOrdering(
|
||||
section: RecommendationSection,
|
||||
@@ -38,15 +44,32 @@ export function useMethodCardDeckOrdering(
|
||||
) {
|
||||
const { state } = useCreateFlow();
|
||||
const copy = useMessages().create.customRule.recommendations;
|
||||
const compactLimit = deckData(section).config.displayLimit;
|
||||
const templateSlug = templatePathFromState(state)?.slug;
|
||||
const engineCompactLimit = deckData(section).config.displayLimit;
|
||||
const answers = useMemo(
|
||||
() => groupAnswersForRecommendations(state),
|
||||
[state],
|
||||
);
|
||||
const deck = useMemo(
|
||||
() => deriveCompactCards(section, answers, compactLimit),
|
||||
[section, answers, compactLimit],
|
||||
);
|
||||
const deck = useMemo(() => {
|
||||
if (templateSlug) {
|
||||
const templateIds = templateCardIdsForDeck(templateSlug, section);
|
||||
const firstIds =
|
||||
templateIds.length > 0 ? templateIds : [...selectedIds];
|
||||
const ordered = templateDeck(deckData(section), firstIds);
|
||||
const orderedIds = [...ordered.first, ...ordered.rest];
|
||||
return {
|
||||
compactCardIds: orderedIds,
|
||||
recommendedIds: new Set<string>(),
|
||||
orderedIds,
|
||||
fallback: true,
|
||||
recommendedById: new Map(),
|
||||
};
|
||||
}
|
||||
return deriveCompactCards(section, answers, engineCompactLimit);
|
||||
}, [answers, engineCompactLimit, section, selectedIds, templateSlug]);
|
||||
const compactLimit = templateSlug
|
||||
? deck.orderedIds.length
|
||||
: engineCompactLimit;
|
||||
|
||||
const rankedMethods = useMemo(
|
||||
() => orderByIds(methods, deck.orderedIds),
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useEffect, useMemo } from "react";
|
||||
import { buildFacetQueryString } from "../../../../lib/create/buildFacetQueryString";
|
||||
import { METHOD_FACET_API_SECTION_IDS } from "../../../../lib/create/customRuleFacets";
|
||||
import { loadFacetScores } from "../../../../lib/create/facetRecommendationsLoad";
|
||||
import { isTemplateCreatePath } from "../../../../lib/create/templatePath";
|
||||
import { useCreateFlow } from "../context/CreateFlowContext";
|
||||
|
||||
/**
|
||||
@@ -18,10 +19,12 @@ export function usePrefetchMethodFacetRecommendations(): void {
|
||||
[state],
|
||||
);
|
||||
|
||||
const skipEngine = isTemplateCreatePath(state);
|
||||
|
||||
useEffect(() => {
|
||||
if (queryString.length === 0) return;
|
||||
if (skipEngine || queryString.length === 0) return;
|
||||
for (const section of METHOD_FACET_API_SECTION_IDS) {
|
||||
void loadFacetScores(section, queryString);
|
||||
}
|
||||
}, [queryString]);
|
||||
}, [queryString, skipEngine]);
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { buildTemplateCustomizePrefill } from "../../../../lib/create/applyTemplatePrefill";
|
||||
import {
|
||||
buildTemplateCustomizePrefill,
|
||||
templatePresetDetailsFromPrefill,
|
||||
} from "../../../../lib/create/applyTemplatePrefill";
|
||||
import { loadTemplateReviewBySlug } from "../../../../lib/create/loadTemplateReviewBySlug";
|
||||
import { methodSectionsPinsForHydratedSelections } from "../../../../lib/create/publishedDocumentToCreateFlowState";
|
||||
import { stripCustomRuleSelectionFields } from "../../../../lib/create/stripCustomRuleSelectionFields";
|
||||
import { templateChipCounts } from "../../../../lib/create/templatePath";
|
||||
import messages from "../../../../messages/en/index";
|
||||
import type {
|
||||
CreateFlowContextValue,
|
||||
@@ -16,6 +20,20 @@ type AppRouterLike = { push: (_href: string) => void };
|
||||
type UpdateState = CreateFlowContextValue["updateState"];
|
||||
type ReplaceStateFn = CreateFlowContextValue["replaceState"];
|
||||
|
||||
export type TemplateCustomizeDialogModel = {
|
||||
slug: string;
|
||||
templateTitle: string;
|
||||
body: unknown;
|
||||
valuesCount: number;
|
||||
cardsCount: number;
|
||||
};
|
||||
|
||||
export type TemplateCustomizeFields = {
|
||||
title: string;
|
||||
communityContext: string;
|
||||
communityLocation: string;
|
||||
};
|
||||
|
||||
export type UseTemplateReviewActionsResult = {
|
||||
/** True iff the current pathname is a template-review route (locale/basePath tolerant). */
|
||||
isTemplateReviewRoute: boolean;
|
||||
@@ -27,47 +45,43 @@ export type UseTemplateReviewActionsResult = {
|
||||
templateReviewApplyError: string | null;
|
||||
setTemplateReviewApplyError: (_message: string | null) => void;
|
||||
/**
|
||||
* Customize: apply the template's selections onto state and route to
|
||||
* `/create/core-values` (if community name is set) or `/create/informational`
|
||||
* with a `pendingTemplateAction` pin so `/create/review` can later replace
|
||||
* itself with `/create/core-values`. A named community skips setup
|
||||
* questions, so leftover setup answers are dropped and cannot change
|
||||
* suggested cards.
|
||||
* Customize: open the name / photo / description dialog. Continue applies
|
||||
* the template's cards and routes to `/create/core-values`. Setup questions
|
||||
* are skipped.
|
||||
*/
|
||||
handleCustomize: () => Promise<void>;
|
||||
/**
|
||||
* Use without changes: scrub any prior customize picks, seed core values +
|
||||
* method-card selections from the template body (same id mapping as
|
||||
* Customize) so drilling from final-review via + shows selected cards, drop
|
||||
* the Values row from `state.sections`. Direct template entry routes to
|
||||
* `/create/community-name` with a pin so Next/Back collect only name →
|
||||
* description → photo, and drops leftover setup answers along with the
|
||||
* other identity fields. In-flow (`?fromFlow=1`, community steps already
|
||||
* done) routes to `/create/final-review` and keeps those answers.
|
||||
* Use without changes: seed the template's cards and go to final review.
|
||||
* Direct entry clears leftover identity so the Rule card can collect name,
|
||||
* photo, and description. In-flow keeps the community answers already given.
|
||||
*/
|
||||
handleUseWithoutChanges: () => Promise<void>;
|
||||
customizeDialog: TemplateCustomizeDialogModel | null;
|
||||
closeCustomizeDialog: () => void;
|
||||
confirmCustomizeDialog: (_fields: TemplateCustomizeFields) => void;
|
||||
};
|
||||
|
||||
function sectionsFromTemplateBody(
|
||||
body: unknown,
|
||||
): Record<string, unknown>[] | null {
|
||||
if (!body || typeof body !== "object" || Array.isArray(body)) return null;
|
||||
const sectionsRaw = (body as { sections?: unknown }).sections;
|
||||
if (!Array.isArray(sectionsRaw) || sectionsRaw.length === 0) return null;
|
||||
return sectionsRaw as Record<string, unknown>[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Encapsulates the two template-review footer actions (Customize / Use
|
||||
* without changes) plus the small amount of state they share (in-flight
|
||||
* flag, error banner, parsed slug). Called from `CreateFlowLayoutClient`
|
||||
* once; extracting it here keeps the layout shell focused on rendering
|
||||
* rather than orchestrating template fetch + state seeding.
|
||||
* without changes) plus the Customize dialog they share.
|
||||
*
|
||||
* @example
|
||||
* const {
|
||||
* isTemplateReviewRoute,
|
||||
* templateReviewSlug,
|
||||
* isApplyingTemplate,
|
||||
* templateReviewApplyError,
|
||||
* setTemplateReviewApplyError,
|
||||
* handleCustomize,
|
||||
* handleUseWithoutChanges,
|
||||
* } = useTemplateReviewActions({
|
||||
* pathname, state, updateState, replaceState, router,
|
||||
* fromCreateWizard, markCreateFlowInteraction,
|
||||
* });
|
||||
* customizeDialog,
|
||||
* closeCustomizeDialog,
|
||||
* confirmCustomizeDialog,
|
||||
* } = useTemplateReviewActions({ ... });
|
||||
*/
|
||||
export function useTemplateReviewActions({
|
||||
pathname,
|
||||
@@ -95,6 +109,8 @@ export function useTemplateReviewActions({
|
||||
const [templateReviewApplyError, setTemplateReviewApplyError] = useState<
|
||||
string | null
|
||||
>(null);
|
||||
const [customizeDialog, setCustomizeDialog] =
|
||||
useState<TemplateCustomizeDialogModel | null>(null);
|
||||
|
||||
const templateReviewSlug = useMemo(() => {
|
||||
const m = pathname?.match(/\/create\/review-template\/([^/?#]+)/);
|
||||
@@ -116,42 +132,64 @@ export function useTemplateReviewActions({
|
||||
setTemplateReviewApplyError(loaded.message);
|
||||
return;
|
||||
}
|
||||
const prefill = buildTemplateCustomizePrefill(
|
||||
loaded.template.body,
|
||||
templateReviewSlug,
|
||||
);
|
||||
const pinPatch = methodSectionsPinsForHydratedSelections(prefill);
|
||||
const hasCommunityName =
|
||||
typeof state.title === "string" && state.title.trim().length > 0;
|
||||
updateState({
|
||||
...prefill,
|
||||
methodSectionsPinCommitted: {
|
||||
...state.methodSectionsPinCommitted,
|
||||
...pinPatch,
|
||||
},
|
||||
templateReviewBackSlug: undefined,
|
||||
...(hasCommunityName
|
||||
? { pendingTemplateAction: undefined, setupTraits: undefined }
|
||||
: {
|
||||
pendingTemplateAction: {
|
||||
slug: templateReviewSlug,
|
||||
mode: "customize",
|
||||
},
|
||||
}),
|
||||
const counts = templateChipCounts(templateReviewSlug);
|
||||
setCustomizeDialog({
|
||||
slug: templateReviewSlug,
|
||||
templateTitle: loaded.template.title,
|
||||
body: loaded.template.body,
|
||||
valuesCount: counts?.values ?? 0,
|
||||
cardsCount: counts?.cards ?? 0,
|
||||
});
|
||||
router.push(
|
||||
hasCommunityName
|
||||
? createFlowStepPath("core-values")
|
||||
: createFlowStepPath("informational"),
|
||||
);
|
||||
}, [
|
||||
router,
|
||||
state.methodSectionsPinCommitted,
|
||||
state.title,
|
||||
templateReviewSlug,
|
||||
updateState,
|
||||
markCreateFlowInteraction,
|
||||
]);
|
||||
}, [markCreateFlowInteraction, templateReviewSlug]);
|
||||
|
||||
const closeCustomizeDialog = useCallback(() => {
|
||||
setCustomizeDialog(null);
|
||||
}, []);
|
||||
|
||||
const confirmCustomizeDialog = useCallback(
|
||||
(fields: TemplateCustomizeFields) => {
|
||||
if (!customizeDialog) return;
|
||||
markCreateFlowInteraction();
|
||||
const prefill = buildTemplateCustomizePrefill(
|
||||
customizeDialog.body,
|
||||
customizeDialog.slug,
|
||||
);
|
||||
const details = templatePresetDetailsFromPrefill(prefill);
|
||||
const pinPatch = methodSectionsPinsForHydratedSelections(prefill);
|
||||
const title = fields.title.trim();
|
||||
const communityContext = fields.communityContext.trim();
|
||||
const communityLocation = fields.communityLocation.trim();
|
||||
updateState({
|
||||
...prefill,
|
||||
...details,
|
||||
title: title.length > 0 ? title : undefined,
|
||||
communityContext:
|
||||
communityContext.length > 0 ? communityContext : undefined,
|
||||
summary: communityContext.length > 0 ? communityContext : undefined,
|
||||
communityLocation:
|
||||
communityLocation.length > 0 ? communityLocation : undefined,
|
||||
methodSectionsPinCommitted: {
|
||||
...state.methodSectionsPinCommitted,
|
||||
...pinPatch,
|
||||
},
|
||||
templateReviewBackSlug: customizeDialog.slug,
|
||||
setupTraits: undefined,
|
||||
pendingTemplateAction: {
|
||||
slug: customizeDialog.slug,
|
||||
mode: "customize",
|
||||
},
|
||||
});
|
||||
setCustomizeDialog(null);
|
||||
router.push(createFlowStepPath("core-values"));
|
||||
},
|
||||
[
|
||||
customizeDialog,
|
||||
markCreateFlowInteraction,
|
||||
router,
|
||||
state.methodSectionsPinCommitted,
|
||||
updateState,
|
||||
],
|
||||
);
|
||||
|
||||
const handleUseWithoutChanges = useCallback(async () => {
|
||||
if (!templateReviewSlug) return;
|
||||
@@ -165,33 +203,21 @@ export function useTemplateReviewActions({
|
||||
return;
|
||||
}
|
||||
const { template } = loaded;
|
||||
const doc = template.body;
|
||||
if (!doc || typeof doc !== "object" || Array.isArray(doc)) {
|
||||
setTemplateReviewApplyError(
|
||||
messages.create.templateReview.errors.applyFailed,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const sectionsRaw = (doc as { sections?: unknown }).sections;
|
||||
const sections = Array.isArray(sectionsRaw)
|
||||
? (sectionsRaw as Record<string, unknown>[])
|
||||
: [];
|
||||
if (sections.length === 0) {
|
||||
const sections = sectionsFromTemplateBody(template.body);
|
||||
if (!sections) {
|
||||
setTemplateReviewApplyError(
|
||||
messages.create.templateReview.errors.applyFailed,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Atomic read-modify-write: strip prior custom-rule picks and merge template
|
||||
// body in one replaceState so method ids are never lost across React batching
|
||||
// (reset + update separately could leave selections undefined in Strict Mode).
|
||||
replaceState((prev) => {
|
||||
const base = stripCustomRuleSelectionFields(prev);
|
||||
const customizePrefill = buildTemplateCustomizePrefill(
|
||||
doc,
|
||||
template.body,
|
||||
templateReviewSlug ?? undefined,
|
||||
);
|
||||
const details = templatePresetDetailsFromPrefill(customizePrefill);
|
||||
const hasValuesSeed =
|
||||
customizePrefill.selectedCoreValueIds !== undefined;
|
||||
|
||||
@@ -209,68 +235,34 @@ export function useTemplateReviewActions({
|
||||
|
||||
const seeded: CreateFlowState = {
|
||||
...base,
|
||||
...(hasValuesSeed
|
||||
? {
|
||||
selectedCoreValueIds: customizePrefill.selectedCoreValueIds,
|
||||
coreValuesChipsSnapshot:
|
||||
customizePrefill.coreValuesChipsSnapshot,
|
||||
}
|
||||
: {}),
|
||||
...(customizePrefill.selectedCommunicationMethodIds !== undefined
|
||||
? {
|
||||
selectedCommunicationMethodIds:
|
||||
customizePrefill.selectedCommunicationMethodIds,
|
||||
}
|
||||
: {}),
|
||||
...(customizePrefill.selectedMembershipMethodIds !== undefined
|
||||
? {
|
||||
selectedMembershipMethodIds:
|
||||
customizePrefill.selectedMembershipMethodIds,
|
||||
}
|
||||
: {}),
|
||||
...(customizePrefill.selectedDecisionApproachIds !== undefined
|
||||
? {
|
||||
selectedDecisionApproachIds:
|
||||
customizePrefill.selectedDecisionApproachIds,
|
||||
}
|
||||
: {}),
|
||||
...(customizePrefill.selectedConflictManagementIds !== undefined
|
||||
? {
|
||||
selectedConflictManagementIds:
|
||||
customizePrefill.selectedConflictManagementIds,
|
||||
}
|
||||
: {}),
|
||||
...customizePrefill,
|
||||
...details,
|
||||
sections: sectionsWithoutValues,
|
||||
methodSectionsPinCommitted: pinPatch,
|
||||
templateReviewBackSlug: templateReviewSlug,
|
||||
};
|
||||
|
||||
if (fromCreateWizard) {
|
||||
return {
|
||||
...seeded,
|
||||
pendingTemplateAction: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...seeded,
|
||||
title: undefined,
|
||||
communityContext: undefined,
|
||||
communityAvatarUrl: undefined,
|
||||
currentStep: undefined,
|
||||
templateReviewEntryFromCreateFlow: undefined,
|
||||
setupTraits: undefined,
|
||||
pendingTemplateAction: {
|
||||
slug: templateReviewSlug,
|
||||
mode: "useWithoutChanges",
|
||||
},
|
||||
};
|
||||
|
||||
if (fromCreateWizard) {
|
||||
return seeded;
|
||||
}
|
||||
|
||||
return {
|
||||
...seeded,
|
||||
title: undefined,
|
||||
communityContext: undefined,
|
||||
communityLocation: undefined,
|
||||
communityAvatarUrl: undefined,
|
||||
communityAvatarFileName: undefined,
|
||||
currentStep: undefined,
|
||||
templateReviewEntryFromCreateFlow: undefined,
|
||||
};
|
||||
});
|
||||
router.push(
|
||||
fromCreateWizard
|
||||
? createFlowStepPath("final-review")
|
||||
: createFlowStepPath("community-name"),
|
||||
);
|
||||
router.push(createFlowStepPath("final-review"));
|
||||
}, [
|
||||
fromCreateWizard,
|
||||
markCreateFlowInteraction,
|
||||
@@ -287,5 +279,8 @@ export function useTemplateReviewActions({
|
||||
setTemplateReviewApplyError,
|
||||
handleCustomize,
|
||||
handleUseWithoutChanges,
|
||||
customizeDialog,
|
||||
closeCustomizeDialog,
|
||||
confirmCustomizeDialog,
|
||||
};
|
||||
}
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
getAssetPath,
|
||||
vectorMarkPath,
|
||||
} from "../../../../../lib/assetUtils";
|
||||
import { methodSectionsPinsForHydratedSelections } from "../../../../../lib/create/publishedDocumentToCreateFlowState";
|
||||
import { CREATE_ROUTES, createFlowStepPath } from "../../utils/createFlowPaths";
|
||||
import { CREATE_FLOW_REVIEW_RETURN_QUERY_KEY } from "../../utils/flowSteps";
|
||||
import type { CreateFlowStep } from "../../types";
|
||||
@@ -83,7 +82,7 @@ export function CommunityReviewScreen() {
|
||||
const lgUp = useCreateFlowLgUp();
|
||||
const messages = useMessages();
|
||||
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
|
||||
* 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
|
||||
* stage, we pinned `pendingTemplateAction` so this screen can skip itself
|
||||
* and `replace` to `core-values`. **Use without changes** does not skip
|
||||
* 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.
|
||||
* Leftover pin from an older draft: bounce off community review onto the
|
||||
* template path. Customize walks the decks; Use without changes lands on
|
||||
* final review. The pin stays so decks skip the engine.
|
||||
*
|
||||
* Ref guard covers React 18 StrictMode's double-mount in dev so we don't
|
||||
* fire `router.replace` twice on the same transition.
|
||||
@@ -109,31 +106,13 @@ export function CommunityReviewScreen() {
|
||||
if (firedRedirectRef.current) return;
|
||||
const pending = state.pendingTemplateAction;
|
||||
if (!pending) return;
|
||||
if (pending.mode !== "customize") {
|
||||
firedRedirectRef.current = true;
|
||||
router.replace(createFlowStepPath("community-name"));
|
||||
return;
|
||||
}
|
||||
const target = createFlowStepPath("core-values");
|
||||
firedRedirectRef.current = true;
|
||||
const pinMerge = {
|
||||
methodSectionsPinCommitted: {
|
||||
...state.methodSectionsPinCommitted,
|
||||
...methodSectionsPinsForHydratedSelections(state),
|
||||
},
|
||||
};
|
||||
updateState({ pendingTemplateAction: undefined, ...pinMerge });
|
||||
router.replace(target);
|
||||
}, [
|
||||
router,
|
||||
state.pendingTemplateAction,
|
||||
state.methodSectionsPinCommitted,
|
||||
state.selectedCommunicationMethodIds,
|
||||
state.selectedMembershipMethodIds,
|
||||
state.selectedDecisionApproachIds,
|
||||
state.selectedConflictManagementIds,
|
||||
updateState,
|
||||
]);
|
||||
router.replace(
|
||||
createFlowStepPath(
|
||||
pending.mode === "customize" ? "core-values" : "final-review",
|
||||
),
|
||||
);
|
||||
}, [router, state.pendingTemplateAction]);
|
||||
|
||||
const cardTitle =
|
||||
typeof state.title === "string" && state.title.trim().length > 0
|
||||
|
||||
@@ -29,11 +29,19 @@ import {
|
||||
type FinalReviewChipEditPatch,
|
||||
type FinalReviewChipEditTarget,
|
||||
} from "../../components/FinalReviewChipEditModal";
|
||||
import { FinalReviewCommunityContextEditModal } from "../../components/FinalReviewCommunityContextEditModal";
|
||||
import { FinalReviewTitleEditModal } from "../../components/FinalReviewTitleEditModal";
|
||||
import {
|
||||
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 { usePreviewSurfaceColor } from "../../hooks/usePreviewSurfaceColor";
|
||||
import { useCreateFlowNavigation } from "../../hooks/useCreateFlowNavigation";
|
||||
import { useCommunityAvatarUpload } from "../../hooks/useCommunityAvatarUpload";
|
||||
import { isTemplateCreatePath } from "../../../../../lib/create/templatePath";
|
||||
import { createFlowStepForFacetGroup } from "../../utils/facetGroupToCreateFlowStep";
|
||||
import { isPreviewSurfaceColor } from "../../../../../lib/create/previewSurfaceColor";
|
||||
import {
|
||||
@@ -225,7 +233,10 @@ export function FinalReviewScreen({
|
||||
|
||||
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 =
|
||||
typeof state.previewSurfaceColor === "string"
|
||||
? state.previewSurfaceColor
|
||||
@@ -275,23 +286,73 @@ export function FinalReviewScreen({
|
||||
hasTrailingIcon={false}
|
||||
/>
|
||||
) : 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
|
||||
title={ruleCardTitle}
|
||||
description={ruleCardDescription}
|
||||
onTitleClick={() => setTitleModalOpen(true)}
|
||||
description={
|
||||
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")}
|
||||
onDescriptionClick={() => setCommunityContextModalOpen(true)}
|
||||
onDescriptionClick={
|
||||
templatePath ? undefined : () => setCommunityContextModalOpen(true)
|
||||
}
|
||||
descriptionEmptyHint={descriptionEmptyHint}
|
||||
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"}
|
||||
expanded={true}
|
||||
descriptionAtBottom
|
||||
backgroundColor="bg-transparent"
|
||||
surfaceColor={surfaceColor}
|
||||
logoUrl={avatarUrl}
|
||||
logoUrl={avatarUrl ?? undefined}
|
||||
logoAlt={ruleCardTitle}
|
||||
communityInitials={
|
||||
avatarUrl ? undefined : communityInitialsFromTitle(ruleCardTitle)
|
||||
avatarUrl || templatePath
|
||||
? undefined
|
||||
: communityInitialsFromTitle(ruleCardTitle)
|
||||
}
|
||||
categories={finalReviewCategories}
|
||||
className={`${CREATE_FLOW_REVIEW_RULE_LAYOUT_CLASS}${surfaceColor ? "" : " invisible"}`}
|
||||
@@ -312,24 +373,28 @@ export function FinalReviewScreen({
|
||||
onClose={() => setActiveReadOnlyDetail(null)}
|
||||
detail={activeReadOnlyDetail}
|
||||
/>
|
||||
<FinalReviewTitleEditModal
|
||||
isOpen={titleModalOpen}
|
||||
onClose={() => setTitleModalOpen(false)}
|
||||
initialValue={rawTitleForModal}
|
||||
onSave={(value) => {
|
||||
markCreateFlowInteraction();
|
||||
updateState({ title: value });
|
||||
}}
|
||||
/>
|
||||
<FinalReviewCommunityContextEditModal
|
||||
isOpen={communityContextModalOpen}
|
||||
onClose={() => setCommunityContextModalOpen(false)}
|
||||
initialValue={rawCommunityContextForModal}
|
||||
onSave={(value) => {
|
||||
markCreateFlowInteraction();
|
||||
updateState({ communityContext: value, summary: value });
|
||||
}}
|
||||
/>
|
||||
{templatePath ? null : (
|
||||
<>
|
||||
<FinalReviewTitleEditModal
|
||||
isOpen={titleModalOpen}
|
||||
onClose={() => setTitleModalOpen(false)}
|
||||
initialValue={rawTitleForModal}
|
||||
onSave={(value) => {
|
||||
markCreateFlowInteraction();
|
||||
updateState({ title: value });
|
||||
}}
|
||||
/>
|
||||
<FinalReviewCommunityContextEditModal
|
||||
isOpen={communityContextModalOpen}
|
||||
onClose={() => setCommunityContextModalOpen(false)}
|
||||
initialValue={rawCommunityContextForModal}
|
||||
onSave={(value) => {
|
||||
markCreateFlowInteraction();
|
||||
updateState({ communityContext: value, summary: value });
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</CreateFlowLockupCardStepShell>
|
||||
);
|
||||
}
|
||||
@@ -35,6 +35,11 @@ import {
|
||||
} from "../../../../../lib/create/methodCardWizardPrefill";
|
||||
import type { CustomMethodCardFieldBlock } from "../../../../../lib/create/customMethodCardFieldBlocks";
|
||||
import { uploadCreateFlowFile } from "../../../../../lib/create/uploadToServer";
|
||||
import {
|
||||
orderIdsFirst,
|
||||
templatePathFromState,
|
||||
templateValueIdsForSlug,
|
||||
} from "../../../../../lib/create/templatePath";
|
||||
|
||||
const MAX_CORE_VALUES = MAX_SELECTED_CORE_VALUES;
|
||||
|
||||
@@ -114,13 +119,16 @@ export function CoreValuesSelectScreen() {
|
||||
const initialDraftRef = useRef<CoreValueDetailEntry | null>(null);
|
||||
const pendingEphemeralCoreDuplicateRef = useRef<string | null>(null);
|
||||
|
||||
const [coreValueOptions, setCoreValueOptions] = useState<ChipOption[]>(() =>
|
||||
buildCoreValueChipOptionsFromDraft(
|
||||
const [coreValueOptions, setCoreValueOptions] = useState<ChipOption[]>(() => {
|
||||
const base = buildCoreValueChipOptionsFromDraft(
|
||||
presets,
|
||||
state.coreValuesChipsSnapshot,
|
||||
state.selectedCoreValueIds,
|
||||
),
|
||||
);
|
||||
);
|
||||
const path = templatePathFromState(state);
|
||||
if (!path) return base;
|
||||
return orderIdsFirst(base, templateValueIdsForSlug(path.slug));
|
||||
});
|
||||
|
||||
const [activeModalChipId, setActiveModalChipId] = useState<string | null>(
|
||||
null,
|
||||
@@ -137,18 +145,23 @@ export function CoreValuesSelectScreen() {
|
||||
CustomMethodCardFieldBlock[] | null
|
||||
>(null);
|
||||
|
||||
const templatePathSlug = templatePathFromState(state)?.slug;
|
||||
useEffect(() => {
|
||||
const base = buildCoreValueChipOptionsFromDraft(
|
||||
presets,
|
||||
state.coreValuesChipsSnapshot,
|
||||
state.selectedCoreValueIds,
|
||||
);
|
||||
setCoreValueOptions(
|
||||
buildCoreValueChipOptionsFromDraft(
|
||||
presets,
|
||||
state.coreValuesChipsSnapshot,
|
||||
state.selectedCoreValueIds,
|
||||
),
|
||||
templatePathSlug
|
||||
? orderIdsFirst(base, templateValueIdsForSlug(templatePathSlug))
|
||||
: base,
|
||||
);
|
||||
}, [
|
||||
presets,
|
||||
state.coreValuesChipsSnapshot,
|
||||
state.selectedCoreValueIds,
|
||||
templatePathSlug,
|
||||
]);
|
||||
|
||||
/** 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 type { TemplateGridCardEntry } from "../../../../lib/templates/templateGridPresentation";
|
||||
import { useTranslation } from "../../../contexts/MessagesContext";
|
||||
import { useTemplatesFacetGridEntries } from "../../../(marketing)/templates/useTemplatesFacetGridEntries";
|
||||
import { CreateFlowHeaderLockup } from "../components/CreateFlowHeaderLockup";
|
||||
import { CreateFlowStepShell } from "../components/CreateFlowStepShell";
|
||||
import { CREATE_FLOW_TWO_COLUMN_MAX_WIDTH_CLASS } from "../components/createFlowLayoutTokens";
|
||||
@@ -15,10 +14,6 @@ export function CreateFlowTemplatesPageClient({
|
||||
initialGridEntries: TemplateGridCardEntry[];
|
||||
}) {
|
||||
const t = useTranslation("pages.templates");
|
||||
const entries = useTemplatesFacetGridEntries({
|
||||
initialGridEntries,
|
||||
enableFacetRecommendations: true,
|
||||
});
|
||||
|
||||
return (
|
||||
<CreateFlowStepShell
|
||||
@@ -34,7 +29,7 @@ export function CreateFlowTemplatesPageClient({
|
||||
justification="left"
|
||||
/>
|
||||
<GovernanceTemplateGrid
|
||||
entries={entries}
|
||||
entries={initialGridEntries}
|
||||
hrefForTemplate={(slug) =>
|
||||
buildTemplateReviewHref(slug, { fromCreateWizard: true })
|
||||
}
|
||||
|
||||
@@ -219,24 +219,19 @@ export interface CreateFlowState {
|
||||
*/
|
||||
customMethodCardFieldBlocksById?: Record<string, CustomMethodCardFieldBlock[]>;
|
||||
/**
|
||||
* Set when a user picks a template (Customize or Use without changes) before
|
||||
* completing the community stage. Customize: the community-review screen
|
||||
* `router.replace`s past `/create/review` to `core-values`. Use without
|
||||
* changes: navigation skips to name → description → optional photo, then
|
||||
* `confirm-stakeholders` (the pin keeps that skip list active). Set only for
|
||||
* **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.
|
||||
* Set when a user starts from a template (Customize or Use without changes).
|
||||
* Kept for the rest of the wizard so community setup is skipped, decks skip
|
||||
* the engine, and final-review Back / identity fields know which path it is.
|
||||
* Customize walks values and the four decks; Use without changes lands on
|
||||
* final review. Cleared when the flow is reset.
|
||||
*/
|
||||
pendingTemplateAction?: {
|
||||
slug: string;
|
||||
mode: "customize" | "useWithoutChanges";
|
||||
};
|
||||
/**
|
||||
* Set when the user chooses **Use without changes** on a template-review
|
||||
* page. Used so Back from `community-name` (identity-only path) returns to
|
||||
* `/create/review-template/{slug}` instead of the intro. Cleared when the user
|
||||
* picks **Customize** from template review or when the flow state is cleared.
|
||||
* Template-review slug to return to from Customize values or from
|
||||
* Use-without-changes final review. Cleared when the flow state is cleared.
|
||||
*/
|
||||
templateReviewBackSlug?: string;
|
||||
/**
|
||||
|
||||
@@ -50,26 +50,32 @@ export const FIRST_STEP: CreateFlowStep = FLOW_STEP_ORDER[0];
|
||||
export type CreateFlowNavigationOptions = {
|
||||
skipCommunitySave?: boolean;
|
||||
/**
|
||||
* Template **Use without changes**: collect community name, description, and
|
||||
* optional photo only. Skips intro, structure, size, setup questions, save,
|
||||
* community review, and the custom-rule authoring segment.
|
||||
* Template path. Skips size, kind, scale, maturity, and setup questions.
|
||||
* Customize still walks values and the four decks; Use without changes
|
||||
* 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
|
||||
* {@link CreateFlowNavigationOptions.useWithoutChangesIdentityOnly} is set.
|
||||
* Remaining identity steps: `community-name` → `community-context` →
|
||||
* `community-upload`, then `final-review`.
|
||||
* Community questionnaire skipped on both template-path modes. Identity is
|
||||
* collected in the Customize dialog or on the final-review Rule card.
|
||||
*/
|
||||
const USE_WITHOUT_CHANGES_IDENTITY_SKIP = new Set<CreateFlowStep>([
|
||||
const TEMPLATE_PATH_COMMUNITY_SKIP = new Set<CreateFlowStep>([
|
||||
"informational",
|
||||
"community-name",
|
||||
"community-structure",
|
||||
"community-context",
|
||||
"community-size",
|
||||
"setup-questions",
|
||||
"community-upload",
|
||||
"community-save",
|
||||
"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",
|
||||
"communication-methods",
|
||||
"membership-methods",
|
||||
@@ -82,9 +88,11 @@ function shouldSkipStep(
|
||||
options?: CreateFlowNavigationOptions,
|
||||
): boolean {
|
||||
if (options?.skipCommunitySave && step === "community-save") return true;
|
||||
return Boolean(
|
||||
options?.useWithoutChangesIdentityOnly &&
|
||||
USE_WITHOUT_CHANGES_IDENTITY_SKIP.has(step),
|
||||
if (!options?.templatePathMode) return false;
|
||||
if (TEMPLATE_PATH_COMMUNITY_SKIP.has(step)) return true;
|
||||
return (
|
||||
options.templatePathMode === "useWithoutChanges" &&
|
||||
TEMPLATE_PATH_DECK_SKIP.has(step)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -128,13 +136,10 @@ export function getPreviousStep(
|
||||
* Where the create-flow footer Back action should go. Usually the previous
|
||||
* step in {@link FLOW_STEP_ORDER}.
|
||||
*
|
||||
* Template **Use without changes** exceptions:
|
||||
* - Direct from a template (`useWithoutChangesIdentityOnly`): Back from
|
||||
* `community-name` returns to template review; Back from
|
||||
* `final-review` is `community-upload`.
|
||||
* - In-flow (`?fromFlow=1`, community identity already collected): Back
|
||||
* from `final-review` returns to template review instead of
|
||||
* `conflict-management`.
|
||||
* Template path:
|
||||
* - Customize: Back from `core-values` returns to template review; Back from
|
||||
* `final-review` is the conflict deck.
|
||||
* - Use without changes: Back from `final-review` returns to template review.
|
||||
*/
|
||||
export type CreateFlowBackTarget =
|
||||
| { kind: "step"; step: CreateFlowStep }
|
||||
@@ -149,19 +154,14 @@ export function resolveCreateFlowBackTarget(
|
||||
typeof templateReviewBackSlug === "string"
|
||||
? templateReviewBackSlug.trim()
|
||||
: "";
|
||||
if (
|
||||
currentStep === "community-name" &&
|
||||
options?.useWithoutChangesIdentityOnly &&
|
||||
slug.length > 0
|
||||
) {
|
||||
return { kind: "templateReview", slug };
|
||||
}
|
||||
if (
|
||||
currentStep === "final-review" &&
|
||||
slug.length > 0 &&
|
||||
!options?.useWithoutChangesIdentityOnly
|
||||
) {
|
||||
return { kind: "templateReview", slug };
|
||||
const mode = options?.templatePathMode;
|
||||
if (slug.length > 0) {
|
||||
if (currentStep === "core-values" && mode === "customize") {
|
||||
return { kind: "templateReview", slug };
|
||||
}
|
||||
if (currentStep === "final-review" && mode !== "customize") {
|
||||
return { kind: "templateReview", slug };
|
||||
}
|
||||
}
|
||||
const prev = getPreviousStep(currentStep, options);
|
||||
return prev != null ? { kind: "step", step: prev } : null;
|
||||
@@ -289,14 +289,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. */
|
||||
export const CREATE_FLOW_COMPLETED_CELEBRATE_QUERY = "celebrate" 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 type { TemplateGridCardEntry } from "../../../lib/templates/templateGridPresentation";
|
||||
import { prepareFreshCreateFlowEntrySync } from "../../(app)/create/utils/prepareFreshCreateFlowEntry";
|
||||
import {
|
||||
buildTemplateReviewHref,
|
||||
TEMPLATES_FACET_RECOMMEND_QUERY,
|
||||
TEMPLATES_FACET_RECOMMEND_VALUE,
|
||||
} from "../../(app)/create/utils/flowSteps";
|
||||
import { buildTemplateReviewHref } from "../../(app)/create/utils/flowSteps";
|
||||
import { useTranslation } from "../../contexts/MessagesContext";
|
||||
import { useTemplatesFacetGridEntries } from "./useTemplatesFacetGridEntries";
|
||||
|
||||
export interface TemplatesPageClientProps {
|
||||
initialGridEntries: TemplateGridCardEntry[];
|
||||
@@ -69,8 +64,7 @@ export default function TemplatesPageClient({
|
||||
/**
|
||||
* - `fromFlow=1` — skip `prepareFreshCreateFlowEntry` on template click
|
||||
* (draft preserved). Used by profile “Create from template”.
|
||||
* - `recommendTemplates=1` — rank templates + “RECOMMENDED”
|
||||
* from `GET /api/templates?facet.*` using the persisted community draft.
|
||||
* Templates carry no recommendation; the grid stays in curated order.
|
||||
*/
|
||||
function TemplatesGridWithSearchParams({
|
||||
initialGridEntries,
|
||||
@@ -79,14 +73,9 @@ function TemplatesGridWithSearchParams({
|
||||
}) {
|
||||
const searchParams = useSearchParams();
|
||||
const fromFlow = searchParams.get("fromFlow") === "1";
|
||||
const enableFacetRecommendations =
|
||||
searchParams.get(TEMPLATES_FACET_RECOMMEND_QUERY) ===
|
||||
TEMPLATES_FACET_RECOMMEND_VALUE;
|
||||
const entries = useTemplatesFacetGridEntries({
|
||||
initialGridEntries,
|
||||
enableFacetRecommendations,
|
||||
});
|
||||
return <TemplatesGrid entries={entries} fromFlow={fromFlow} />;
|
||||
return (
|
||||
<TemplatesGrid entries={initialGridEntries} fromFlow={fromFlow} />
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
descriptionAtBottom = false,
|
||||
surfaceColor,
|
||||
hasNameField = false,
|
||||
nameValue,
|
||||
nameLabel,
|
||||
namePlaceholder,
|
||||
onNameChange,
|
||||
descriptionLabel,
|
||||
descriptionPlaceholder,
|
||||
descriptionHelperText,
|
||||
onDescriptionChange,
|
||||
onLogoClick,
|
||||
logoUploadAriaLabel,
|
||||
}) => {
|
||||
const size = sizeProp ?? "L";
|
||||
const isInteractive = interactive ?? !hasBottomLinks;
|
||||
@@ -123,6 +134,17 @@ const RuleContainer = memo<RuleProps>(
|
||||
surfaceColor={surfaceColor}
|
||||
cardAriaLabel={cardAriaLabel}
|
||||
recommendedLabel={recommendedLabel}
|
||||
hasNameField={hasNameField}
|
||||
nameValue={nameValue}
|
||||
nameLabel={nameLabel}
|
||||
namePlaceholder={namePlaceholder}
|
||||
onNameChange={onNameChange}
|
||||
descriptionLabel={descriptionLabel}
|
||||
descriptionPlaceholder={descriptionPlaceholder}
|
||||
descriptionHelperText={descriptionHelperText}
|
||||
onDescriptionChange={onDescriptionChange}
|
||||
onLogoClick={onLogoClick}
|
||||
logoUploadAriaLabel={logoUploadAriaLabel}
|
||||
/>
|
||||
);
|
||||
},
|
||||
|
||||
@@ -103,6 +103,21 @@ export interface RuleProps {
|
||||
* {@link backgroundColor}.
|
||||
*/
|
||||
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 {
|
||||
@@ -138,4 +153,15 @@ export interface RuleViewProps {
|
||||
/** Interactive card aria-label; supplied by the container from `ruleCard` messages. */
|
||||
cardAriaLabel: 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;
|
||||
}
|
||||
@@ -4,8 +4,11 @@ import Image from "next/image";
|
||||
import NextLink from "next/link";
|
||||
import MultiSelect from "../../controls/MultiSelect";
|
||||
import InlineTextButton from "../../buttons/InlineTextButton";
|
||||
import TextInput from "../../controls/TextInput";
|
||||
import TextArea from "../../controls/TextArea";
|
||||
import NavigationLink from "../../navigation/Link";
|
||||
import Tag from "../../utility/Tag";
|
||||
import InputLabel from "../../type/InputLabel";
|
||||
import type { RuleBottomLink, RuleViewProps } from "./Rule.types";
|
||||
|
||||
export function RuleView({
|
||||
@@ -40,6 +43,17 @@ export function RuleView({
|
||||
surfaceColor,
|
||||
cardAriaLabel,
|
||||
recommendedLabel,
|
||||
hasNameField = false,
|
||||
nameValue = "",
|
||||
nameLabel,
|
||||
namePlaceholder,
|
||||
onNameChange,
|
||||
descriptionLabel,
|
||||
descriptionPlaceholder,
|
||||
descriptionHelperText,
|
||||
onDescriptionChange,
|
||||
onLogoClick,
|
||||
logoUploadAriaLabel,
|
||||
}: RuleViewProps) {
|
||||
const ariaLabel = cardAriaLabel;
|
||||
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;
|
||||
};
|
||||
|
||||
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
|
||||
const borderRadiusClass = className?.includes("rounded-")
|
||||
? "" // If className already has border radius, don't add size-based one
|
||||
@@ -291,12 +335,36 @@ export function RuleView({
|
||||
.join(" ");
|
||||
|
||||
const showExpandedDescription = Boolean(
|
||||
hasNameField ||
|
||||
description ||
|
||||
(onDescriptionClick && typeof descriptionEmptyHint === "string"),
|
||||
);
|
||||
const expandedDescription = showExpandedDescription ? (
|
||||
<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
|
||||
type="button"
|
||||
underline={false}
|
||||
@@ -333,12 +401,12 @@ export function RuleView({
|
||||
w-full shrink-0 items-center gap-px
|
||||
"
|
||||
>
|
||||
{renderLogo() && (
|
||||
{(renderLogoControl() || hasNameField) && (
|
||||
<div className={headerIconCellClass}>
|
||||
{renderLogo()}
|
||||
{renderLogoControl()}
|
||||
</div>
|
||||
)}
|
||||
{title && (
|
||||
{(title || hasNameField) && (
|
||||
<div
|
||||
className={`
|
||||
flex min-w-0 flex-1 flex-col justify-center
|
||||
@@ -365,7 +433,31 @@ export function RuleView({
|
||||
{recommendedLabel}
|
||||
</Tag>
|
||||
) : 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
|
||||
type="button"
|
||||
underline={false}
|
||||
|
||||
+9
-13
@@ -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.
|
||||
|
||||
**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/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.
|
||||
|
||||
**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.
|
||||
- **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 (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.
|
||||
|
||||
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`.
|
||||
- **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)** — 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. Back still returns to template review.
|
||||
|
||||
**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]` |
|
||||
| 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.
|
||||
|
||||
**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).
|
||||
|
||||
**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).
|
||||
**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).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -249,34 +249,19 @@ decision-approaches → conflict-management → confirm-stakeholders → final-r
|
||||
| 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` |
|
||||
|
||||
**Marketing UIs** may omit `facet.*` (curated ordering only). When facets
|
||||
are passed, templates are ranked and `scores` may be returned. Template **Customize**
|
||||
now prefills the custom-rule flow via
|
||||
[`buildTemplateCustomizePrefill`](../../lib/create/applyTemplatePrefill.ts)
|
||||
(applied in `CreateFlowLayoutClient.tsx`) and routes to `core-values`
|
||||
when Community already has input, else to `informational`. Template **Use
|
||||
without changes** writes `template.body.sections` into `state.sections`.
|
||||
Direct catalog / marketing entry routes to `community-name` and Next/Back
|
||||
collect only name, description, and optional photo, then
|
||||
`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
|
||||
**Marketing UIs** omit `facet.*`. Templates carry no recommendation; the
|
||||
grid is curated order with no RECOMMENDED tag. Seeded facet marks remain
|
||||
in the database unused. Template **Customize** opens a name / photo /
|
||||
description dialog, prefills cards via
|
||||
[`buildTemplateCustomizePrefill`](../../lib/create/applyTemplatePrefill.ts),
|
||||
and routes to `core-values` (setup questions skipped). Template **Use
|
||||
without changes** writes the template’s cards and routes to
|
||||
`final-review`. Identity is collected in the dialog or on the
|
||||
final-review Rule card. The pin
|
||||
`pendingTemplateAction: { slug, mode: "customize" | "useWithoutChanges" }`
|
||||
on `CreateFlowState`. Customize then routes to `informational`. Direct
|
||||
Use without changes routes to `community-name` (identity-only skip list
|
||||
while the pin is set). Once the user reaches `/create/review`, `CommunityReviewScreen`
|
||||
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.
|
||||
stays for the rest of the wizard so decks skip the engine. See
|
||||
[`docs/create-flow.md`](../create-flow.md). The user exits via
|
||||
`final-review → handleFinalize → publishRule`.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -3,10 +3,19 @@ import type {
|
||||
CreateFlowState,
|
||||
} from "../../app/(app)/create/types";
|
||||
import coreValuesMessages from "../../messages/en/create/customRule/coreValues.json";
|
||||
import templateChipsFile from "../../data/templates/templateChips.json";
|
||||
import { assignTemplateMethodSlugsToPrefill } from "./customRuleFacets";
|
||||
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 TemplateSection = { categoryName: unknown; entries: unknown };
|
||||
@@ -101,13 +110,8 @@ function buildCoreValuePrefill(
|
||||
*
|
||||
* Returns an empty object for malformed bodies (no sections array).
|
||||
*/
|
||||
type TemplateChipSet = Record<DeckId | "coreValues", string[]>;
|
||||
|
||||
function prefillFromTemplateChips(slug: string): Partial<CreateFlowState> | null {
|
||||
const templates = (
|
||||
templateChipsFile as { templates: Record<string, TemplateChipSet> }
|
||||
).templates;
|
||||
const chips = templates[slug];
|
||||
const chips: TemplateChipSet | null = templateChipsForSlug(slug);
|
||||
if (!chips) return null;
|
||||
const selected = new Set(chips.coreValues);
|
||||
return {
|
||||
@@ -173,3 +177,49 @@ export function buildCoreValuesPrefillFromTemplateBody(
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -15,18 +15,8 @@ export type RuleTemplateDto = {
|
||||
|
||||
type TemplatesResponse = {
|
||||
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(
|
||||
queryString: string,
|
||||
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 = {
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
@@ -100,37 +79,6 @@ export async function fetchTemplates(
|
||||
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 = {
|
||||
template: RuleTemplateDto;
|
||||
methods: Array<{ section: string; slug: string }>;
|
||||
|
||||
@@ -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))];
|
||||
}
|
||||
@@ -14,8 +14,8 @@ export type GovernanceTemplateCatalogEntry = {
|
||||
/** Path under public/ for getAssetPath() — Figma Asset / Template Mark */
|
||||
iconPath: string;
|
||||
/**
|
||||
* When true, static catalog rows show the “RECOMMENDED” tag. Facet-ranked
|
||||
* `/templates` sets this in `gridEntriesWithFacetScores` instead.
|
||||
* Templates carry no recommendation. Kept so grid card rows stay a
|
||||
* stable shape; always treat as false.
|
||||
*/
|
||||
recommended?: boolean;
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { RuleTemplateDto, TemplateFacetScoreDto } from "../create/fetchTemplates";
|
||||
import type { RuleTemplateDto } from "../create/fetchTemplates";
|
||||
import { templateSummaryFromBody } from "../create/templateReviewMapping";
|
||||
import type { GovernanceTemplateCatalogEntry } from "./governanceTemplateCatalog";
|
||||
import {
|
||||
@@ -25,7 +25,7 @@ function presentationForSlug(slug: string): Pick<
|
||||
return {
|
||||
iconPath: catalog.iconPath,
|
||||
backgroundColor: catalog.backgroundColor,
|
||||
recommended: catalog.recommended === true,
|
||||
recommended: false,
|
||||
};
|
||||
}
|
||||
return TEMPLATE_GRID_FALLBACK_PRESENTATION;
|
||||
@@ -43,74 +43,10 @@ export function ruleTemplateToGridEntry(template: RuleTemplateDto): TemplateGrid
|
||||
description,
|
||||
iconPath: pres.iconPath,
|
||||
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[]) =>
|
||||
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.",
|
||||
"inputLabel": "Community description",
|
||||
"placeholder": "Describe your community",
|
||||
"optional": "Optional",
|
||||
"characterCountTemplate": "{current}/{max}",
|
||||
"locationLabel": "Where is your community based?",
|
||||
"locationPlaceholder": "City or region",
|
||||
|
||||
@@ -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."
|
||||
}
|
||||
@@ -74,6 +74,7 @@ import createFooter from "./create/footer.json";
|
||||
import createTopNav from "./create/topNav.json";
|
||||
import createDraftHydration from "./create/draftHydration.json";
|
||||
import createTemplateReview from "./create/templateReview.json";
|
||||
import createTemplateCustomize from "./create/templateCustomize.json";
|
||||
import createUpload from "./create/upload.json";
|
||||
import createDraftField from "./create/draftField.json";
|
||||
|
||||
@@ -150,6 +151,7 @@ export default {
|
||||
topNav: createTopNav,
|
||||
draftHydration: createDraftHydration,
|
||||
templateReview: createTemplateReview,
|
||||
templateCustomize: createTemplateCustomize,
|
||||
upload: createUpload,
|
||||
draftField: createDraftField,
|
||||
},
|
||||
|
||||
@@ -196,10 +196,10 @@ describe("CommunityReviewScreen — pendingTemplateAction redirect", () => {
|
||||
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" />);
|
||||
await waitFor(() => {
|
||||
expect(testRouter.replace).toHaveBeenCalledWith("/create/community-name");
|
||||
expect(testRouter.replace).toHaveBeenCalledWith("/create/final-review");
|
||||
});
|
||||
expect(testRouter.push).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -30,5 +30,6 @@ describe("Create flow templates picker", () => {
|
||||
"href",
|
||||
"/create/review-template/solidarity-network?fromFlow=1",
|
||||
);
|
||||
expect(screen.queryByText("RECOMMENDED")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -52,6 +52,7 @@ describe("Templates page (/templates)", () => {
|
||||
for (const entry of GOVERNANCE_TEMPLATE_CATALOG) {
|
||||
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", () => {
|
||||
|
||||
@@ -332,4 +332,37 @@ describe("Rule Component", () => {
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildCoreValuesPrefillFromTemplateBody,
|
||||
buildTemplateCustomizePrefill,
|
||||
templatePresetDetailsFromPrefill,
|
||||
} from "../../lib/create/applyTemplatePrefill";
|
||||
import { methodSectionsPinsForHydratedSelections } from "../../lib/create/publishedDocumentToCreateFlowState";
|
||||
import coreValuesMessages from "../../messages/en/create/customRule/coreValues.json";
|
||||
@@ -196,3 +197,45 @@ describe("buildTemplateCustomizePrefill + method card pins", () => {
|
||||
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("");
|
||||
});
|
||||
});
|
||||
@@ -92,30 +92,67 @@ describe("flowSteps", () => {
|
||||
expect(getPreviousStep("communication-methods", opts)).toBe("core-values");
|
||||
});
|
||||
|
||||
it("useWithoutChangesIdentityOnly walks name → description → photo → final-review", () => {
|
||||
const opts = { useWithoutChangesIdentityOnly: true } as const;
|
||||
expect(getNextStep("community-name", opts)).toBe("community-context");
|
||||
expect(getNextStep("community-context", opts)).toBe("community-upload");
|
||||
expect(getNextStep("community-size", opts)).toBe("community-upload");
|
||||
expect(getNextStep("setup-questions", opts)).toBe("community-upload");
|
||||
expect(getNextStep("community-upload", opts)).toBe("final-review");
|
||||
expect(getNextStep("final-review", opts)).toBe("confirm-stakeholders");
|
||||
expect(getPreviousStep("community-context", opts)).toBe("community-name");
|
||||
expect(getPreviousStep("community-upload", opts)).toBe("community-context");
|
||||
expect(getPreviousStep("final-review", opts)).toBe("community-upload");
|
||||
expect(getPreviousStep("community-name", opts)).toBeNull();
|
||||
it("templatePathMode customize skips community setup and walks the decks", () => {
|
||||
const opts = { templatePathMode: "customize" as const };
|
||||
expect(getNextStep("informational", opts)).toBe("core-values");
|
||||
expect(getNextStep("community-name", opts)).toBe("core-values");
|
||||
expect(getNextStep("setup-questions", opts)).toBe("core-values");
|
||||
expect(getNextStep("core-values", opts)).toBe("communication-methods");
|
||||
expect(getNextStep("conflict-management", opts)).toBe("final-review");
|
||||
expect(getPreviousStep("core-values", opts)).toBeNull();
|
||||
expect(getPreviousStep("final-review", opts)).toBe("conflict-management");
|
||||
});
|
||||
|
||||
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("templatePathMode composes with skipCommunitySave", () => {
|
||||
const opts = {
|
||||
skipCommunitySave: true,
|
||||
useWithoutChangesIdentityOnly: true,
|
||||
} as const;
|
||||
templatePathMode: "useWithoutChanges" as const,
|
||||
};
|
||||
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(
|
||||
resolveCreateFlowBackTarget(
|
||||
"final-review",
|
||||
@@ -125,26 +162,6 @@ describe("flowSteps", () => {
|
||||
).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", () => {
|
||||
expect(
|
||||
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({});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleUseWithoutChanges();
|
||||
await result.current.handleCustomize();
|
||||
});
|
||||
|
||||
expect(markCreateFlowInteraction).toHaveBeenCalled();
|
||||
expect(router.push).toHaveBeenCalledWith("/create/community-name");
|
||||
expect(applied?.pendingTemplateAction).toEqual({
|
||||
slug: "mutual-aid-mondays",
|
||||
mode: "useWithoutChanges",
|
||||
});
|
||||
expect(router.push).not.toHaveBeenCalled();
|
||||
expect(result.current.customizeDialog).toEqual(
|
||||
expect.objectContaining({
|
||||
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(
|
||||
(updater: (_prev: CreateFlowState) => CreateFlowState) => {
|
||||
applied = updater({
|
||||
@@ -101,15 +135,18 @@ describe("useTemplateReviewActions", () => {
|
||||
await result.current.handleUseWithoutChanges();
|
||||
});
|
||||
|
||||
expect(router.push).toHaveBeenCalledWith("/create/community-name");
|
||||
expect(router.push).toHaveBeenCalledWith("/create/final-review");
|
||||
expect(applied?.title).toBeUndefined();
|
||||
expect(applied?.communityContext).toBeUndefined();
|
||||
expect(applied?.currentStep).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(
|
||||
(updater: (_prev: CreateFlowState) => CreateFlowState) => {
|
||||
applied = updater({
|
||||
@@ -132,38 +169,11 @@ describe("useTemplateReviewActions", () => {
|
||||
expect(router.push).toHaveBeenCalledWith("/create/final-review");
|
||||
expect(applied?.title).toBe("Neighborhood");
|
||||
expect(applied?.communityContext).toBe("We meet weekly");
|
||||
expect(applied?.setupTraits).toEqual({ employer: true });
|
||||
expect(applied?.pendingTemplateAction).toBeUndefined();
|
||||
expect(applied?.setupTraits).toBeUndefined();
|
||||
expect(applied?.pendingTemplateAction).toEqual({
|
||||
slug: "mutual-aid-mondays",
|
||||
mode: "useWithoutChanges",
|
||||
});
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import {
|
||||
deriveRecommendedTemplateSlugs,
|
||||
gridEntriesWithFacetScores,
|
||||
} from "../../lib/templates/templateGridPresentation";
|
||||
import { fetchRankedTemplatesByFacets } from "../../lib/create/fetchTemplates";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { ruleTemplateToGridEntry } from "../../lib/templates/templateGridPresentation";
|
||||
import type { RuleTemplateDto } from "../../lib/create/fetchTemplates";
|
||||
|
||||
const minimalTemplate = (slug: string, title: string): RuleTemplateDto => ({
|
||||
@@ -17,116 +13,9 @@ const minimalTemplate = (slug: string, title: string): RuleTemplateDto => ({
|
||||
featured: false,
|
||||
});
|
||||
|
||||
describe("deriveRecommendedTemplateSlugs", () => {
|
||||
it("returns at most limit slugs in the top score tier (API order for ties)", () => {
|
||||
const templates = ["a", "b", "c", "d", "e", "f"].map((s) => ({ slug: s }));
|
||||
const scores = Object.fromEntries(
|
||||
["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);
|
||||
describe("ruleTemplateToGridEntry", () => {
|
||||
it("never marks a template recommended", () => {
|
||||
const row = ruleTemplateToGridEntry(minimalTemplate("do-ocracy", "Do-ocracy"));
|
||||
expect(row.recommended).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user