- {onDescriptionClick ? (
+ {hasNameField && onDescriptionChange ? (
+
event.stopPropagation()}
+ >
+
+
+ ) : onDescriptionClick ? (
- {renderLogo() && (
+ {(renderLogoControl() || hasNameField) && (
- {renderLogo()}
+ {renderLogoControl()}
)}
- {title && (
+ {(title || hasNameField) && (
) : null}
- {onTitleClick ? (
+ {hasNameField && onNameChange ? (
+
event.stopPropagation()}
+ >
+
+ onNameChange(event.target.value)}
+ inputSize="small"
+ formHeader={false}
+ showHelpIcon={false}
+ required
+ autoFocus={nameValue.trim().length === 0}
+ />
+
+ ) : onTitleClick ? (
;
-
function prefillFromTemplateChips(slug: string): Partial | null {
- const templates = (
- templateChipsFile as { templates: Record }
- ).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,
+): Partial {
+ 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,
+ };
+}
diff --git a/lib/create/fetchTemplates.ts b/lib/create/fetchTemplates.ts
index 59fbd5f..ee71352 100644
--- a/lib/create/fetchTemplates.ts
+++ b/lib/create/fetchTemplates.ts
@@ -15,18 +15,8 @@ export type RuleTemplateDto = {
type TemplatesResponse = {
templates?: RuleTemplateDto[];
- scores?: Record;
};
-function parseScoresPayload(
- raw: unknown,
-): Record {
- if (raw && typeof raw === "object" && !Array.isArray(raw)) {
- return raw as Record;
- }
- 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;
-};
-
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 {
- 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 }>;
diff --git a/lib/create/templatePath.ts b/lib/create/templatePath.ts
new file mode 100644
index 0000000..4255e8f
--- /dev/null
+++ b/lib/create/templatePath.ts
@@ -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;
+
+/**
+ * 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,
+): 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,
+): boolean {
+ return templatePathFromState(state) !== null;
+}
+
+export function templateChipsForSlug(slug: string): TemplateChipSet | null {
+ const templates = (
+ templateChipsFile as { templates: Record }
+ ).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(
+ items: readonly T[],
+ firstIds: readonly string[],
+): T[] {
+ const byId = new Map(items.map((item) => [item.id, item] as const));
+ const seen = new Set();
+ 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))];
+}
diff --git a/lib/templates/governanceTemplateCatalog.ts b/lib/templates/governanceTemplateCatalog.ts
index 3faad39..5f83878 100644
--- a/lib/templates/governanceTemplateCatalog.ts
+++ b/lib/templates/governanceTemplateCatalog.ts
@@ -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;
};
diff --git a/lib/templates/templateGridPresentation.ts b/lib/templates/templateGridPresentation.ts
index 069779a..d4d36f8 100644
--- a/lib/templates/templateGridPresentation.ts
+++ b/lib/templates/templateGridPresentation.ts
@@ -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,
- limit: number,
-): Set {
- 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,
- 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));
diff --git a/messages/en/create/community/communityContext.json b/messages/en/create/community/communityContext.json
index 61a5019..dda075a 100644
--- a/messages/en/create/community/communityContext.json
+++ b/messages/en/create/community/communityContext.json
@@ -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",
diff --git a/messages/en/create/templateCustomize.json b/messages/en/create/templateCustomize.json
new file mode 100644
index 0000000..a167fc5
--- /dev/null
+++ b/messages/en/create/templateCustomize.json
@@ -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."
+}
diff --git a/messages/en/index.ts b/messages/en/index.ts
index 04f350b..faa971c 100644
--- a/messages/en/index.ts
+++ b/messages/en/index.ts
@@ -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,
},
diff --git a/tests/components/ReviewPage.test.tsx b/tests/components/ReviewPage.test.tsx
index 6bf7ad1..ce0358c 100644
--- a/tests/components/ReviewPage.test.tsx
+++ b/tests/components/ReviewPage.test.tsx
@@ -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();
await waitFor(() => {
- expect(testRouter.replace).toHaveBeenCalledWith("/create/community-name");
+ expect(testRouter.replace).toHaveBeenCalledWith("/create/final-review");
});
expect(testRouter.push).not.toHaveBeenCalled();
});
diff --git a/tests/pages/create-templates.test.tsx b/tests/pages/create-templates.test.tsx
index 31ca58b..b7e1fae 100644
--- a/tests/pages/create-templates.test.tsx
+++ b/tests/pages/create-templates.test.tsx
@@ -30,5 +30,6 @@ describe("Create flow templates picker", () => {
"href",
"/create/review-template/solidarity-network?fromFlow=1",
);
+ expect(screen.queryByText("RECOMMENDED")).not.toBeInTheDocument();
});
});
diff --git a/tests/pages/templates.test.jsx b/tests/pages/templates.test.jsx
index 0ac5795..5bc0f3d 100644
--- a/tests/pages/templates.test.jsx
+++ b/tests/pages/templates.test.jsx
@@ -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", () => {
diff --git a/tests/unit/Rule.test.jsx b/tests/unit/Rule.test.jsx
index 87fdaae..7ec2b34 100644
--- a/tests/unit/Rule.test.jsx
+++ b/tests/unit/Rule.test.jsx
@@ -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(
+ ,
+ );
+
+ 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);
+ });
});
diff --git a/tests/unit/applyTemplatePrefill.test.ts b/tests/unit/applyTemplatePrefill.test.ts
index 61a46ed..e37de5d 100644
--- a/tests/unit/applyTemplatePrefill.test.ts
+++ b/tests/unit/applyTemplatePrefill.test.ts
@@ -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("");
+ });
+});
diff --git a/tests/unit/flowSteps.test.ts b/tests/unit/flowSteps.test.ts
index 652b58c..ce5144c 100644
--- a/tests/unit/flowSteps.test.ts
+++ b/tests/unit/flowSteps.test.ts
@@ -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),
diff --git a/tests/unit/hooks/useTemplateReviewActions.test.tsx b/tests/unit/hooks/useTemplateReviewActions.test.tsx
index 2f36b56..c13a5c4 100644
--- a/tests/unit/hooks/useTemplateReviewActions.test.tsx
+++ b/tests/unit/hooks/useTemplateReviewActions.test.tsx
@@ -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");
- });
});
diff --git a/tests/unit/templateGridFacetScores.test.ts b/tests/unit/templateGridFacetScores.test.ts
index aa367eb..3ff5a15 100644
--- a/tests/unit/templateGridFacetScores.test.ts
+++ b/tests/unit/templateGridFacetScores.test.ts
@@ -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);
});
});
diff --git a/tests/unit/templatePath.test.ts b/tests/unit/templatePath.test.ts
new file mode 100644
index 0000000..ce88135
--- /dev/null
+++ b/tests/unit/templatePath.test.ts
@@ -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);
+ });
+});
--
2.53.0
From c7f88e5515e65e4b2790e76eb71acbee7b9713a5 Mon Sep 17 00:00:00 2001
From: adilallo <39313955+adilallo@users.noreply.github.com>
Date: Mon, 9 Nov 2026 17:42:04 -0700
Subject: [PATCH 2/3] Keep a reopened template draft off the setup questions.
---
app/(app)/create/CreateFlowLayoutClient.tsx | 19 +++++++++++++---
app/(app)/create/utils/flowSteps.ts | 14 ++++++++++++
tests/unit/flowSteps.test.ts | 25 +++++++++++++++++++++
3 files changed, 55 insertions(+), 3 deletions(-)
diff --git a/app/(app)/create/CreateFlowLayoutClient.tsx b/app/(app)/create/CreateFlowLayoutClient.tsx
index 85496b7..89e0d01 100644
--- a/app/(app)/create/CreateFlowLayoutClient.tsx
+++ b/app/(app)/create/CreateFlowLayoutClient.tsx
@@ -25,6 +25,7 @@ import {
CREATE_FLOW_REVIEW_RETURN_QUERY_KEY,
getNextStep,
parseReviewReturnSearchParam,
+ templatePathSkippedCommunityRedirect,
shouldOfferCreateFlowSaveAndExit,
isDirectTemplateReviewEntry,
createFlowStepUsesSelectSplitScroll,
@@ -101,6 +102,7 @@ import {
EMPTY_SETUP_TRAITS,
hasTickedSetupTrait,
} from "../../../lib/create/setupTraits";
+import { templatePathFromState } from "../../../lib/create/templatePath";
import { useAuthModal } from "../../contexts/AuthModalContext";
import { useMessages, useTranslation } from "../../contexts/MessagesContext";
import { PostLoginDraftTransfer } from "./PostLoginDraftTransfer";
@@ -424,7 +426,18 @@ function CreateFlowLayoutContent({
await runAuthenticatedExit(opts);
};
+ const templatePathRedirect = templatePathSkippedCommunityRedirect(
+ currentStep,
+ templatePathFromState(state)?.mode,
+ );
+
useEffect(() => {
+ if (!templatePathRedirect) return;
+ router.replace(createFlowStepPath(templatePathRedirect));
+ }, [router, templatePathRedirect]);
+
+ useEffect(() => {
+ if (templatePathRedirect) return;
if (
sessionResolved &&
sessionUser &&
@@ -432,7 +445,7 @@ function CreateFlowLayoutContent({
) {
router.replace(CREATE_ROUTES.review);
}
- }, [sessionResolved, sessionUser, currentStep, router]);
+ }, [sessionResolved, sessionUser, currentStep, router, templatePathRedirect]);
useEffect(() => {
clearAttempted();
@@ -967,9 +980,9 @@ function CreateFlowLayoutContent({
- {children}
+ {templatePathRedirect ? null : children}
- {!isCompletedStep && (
+ {!isCompletedStep && !templatePathRedirect && (
{
expect(getPreviousStep("final-review", opts)).toBeNull();
});
+ it("templatePathSkippedCommunityRedirect resumes setup steps and leaves decks", () => {
+ expect(
+ templatePathSkippedCommunityRedirect("setup-questions", "customize"),
+ ).toBe("core-values");
+ expect(templatePathSkippedCommunityRedirect("review", "customize")).toBe(
+ "core-values",
+ );
+ expect(
+ templatePathSkippedCommunityRedirect(
+ "community-name",
+ "useWithoutChanges",
+ ),
+ ).toBe("final-review");
+ expect(
+ templatePathSkippedCommunityRedirect("core-values", "useWithoutChanges"),
+ ).toBeNull();
+ expect(
+ templatePathSkippedCommunityRedirect("final-review", "customize"),
+ ).toBeNull();
+ expect(
+ templatePathSkippedCommunityRedirect("setup-questions", undefined),
+ ).toBeNull();
+ });
+
it("templatePathMode composes with skipCommunitySave", () => {
const opts = {
skipCommunitySave: true,
--
2.53.0
From c950795844ae214d8847d656398bbf78901d94ff Mon Sep 17 00:00:00 2001
From: adilallo <39313955+adilallo@users.noreply.github.com>
Date: Mon, 9 Nov 2026 19:04:17 -0700
Subject: [PATCH 3/3] Use the blurred yellow backdrop on the Customize dialog.
---
.../components/TemplateCustomizeDialog.tsx | 2 +-
.../TemplateCustomizeDialog.test.tsx | 24 +++++++++++++++++++
2 files changed, 25 insertions(+), 1 deletion(-)
create mode 100644 tests/components/TemplateCustomizeDialog.test.tsx
diff --git a/app/(app)/create/components/TemplateCustomizeDialog.tsx b/app/(app)/create/components/TemplateCustomizeDialog.tsx
index 8bdc726..779f050 100644
--- a/app/(app)/create/components/TemplateCustomizeDialog.tsx
+++ b/app/(app)/create/components/TemplateCustomizeDialog.tsx
@@ -147,7 +147,7 @@ export function TemplateCustomizeDialog({
diff --git a/tests/components/TemplateCustomizeDialog.test.tsx b/tests/components/TemplateCustomizeDialog.test.tsx
new file mode 100644
index 0000000..1460c52
--- /dev/null
+++ b/tests/components/TemplateCustomizeDialog.test.tsx
@@ -0,0 +1,24 @@
+import { describe, expect, it } from "vitest";
+import "@testing-library/jest-dom/vitest";
+import { renderWithProviders as render } from "../utils/test-utils";
+import { TemplateCustomizeDialog } from "../../app/(app)/create/components/TemplateCustomizeDialog";
+
+describe("TemplateCustomizeDialog", () => {
+ it("uses the same blurred yellow backdrop as other create-flow Create modals", () => {
+ render(
+ undefined}
+ onContinue={() => undefined}
+ />,
+ );
+
+ expect(document.querySelector(".backdrop-blur-md")).toBeInTheDocument();
+ });
+});
--
2.53.0