Keep finished Rules and drafts from overwriting each other #114

Merged
an.di merged 10 commits from adilallo/fix/CR-339-finish-drafts into main 2026-11-23 04:49:47 +00:00
76 changed files with 2204 additions and 427 deletions

No files matched your search

+42 -12
View File
@@ -64,6 +64,11 @@ import {
} from "../../../lib/create/publishedDocumentToCreateFlowState";
import { METHOD_FACET_API_SECTION_IDS } from "../../../lib/create/customRuleFacets";
import { readLastPublishedRule } from "../../../lib/create/lastPublishedRule";
import {
createFlowStateForEditingPublishedRule,
publishedRuleEditWouldReplaceDraft,
} from "../../../lib/create/beginEditingPublishedRule";
import { useAsyncConfirm } from "../../hooks/useAsyncConfirm";
import {
CREATE_FLOW_COPIED_QUERY,
CREATE_FLOW_COPIED_VALUE,
@@ -225,6 +230,7 @@ function CreateFlowLayoutContent({
} | null>(null);
const [shareModalOpen, setShareModalOpen] = useState(false);
const [leaveConfirmOpen, setLeaveConfirmOpen] = useState(false);
const { requestConfirm, confirmDialog } = useAsyncConfirm();
const [completedHasPublishedRule, setCompletedHasPublishedRule] =
useState(false);
const [completedCopiedReady, setCompletedCopiedReady] = useState(false);
@@ -330,6 +336,8 @@ function CreateFlowLayoutContent({
replaceState,
router,
fromCreateWizard,
signedIn: Boolean(sessionUser),
requestConfirm,
markCreateFlowInteraction,
});
const isCreateTemplatesPickerRoute =
@@ -889,20 +897,31 @@ function CreateFlowLayoutContent({
backdropVariant="blurredYellow"
ariaLabel={messages.create.topNav.leaveConfirmTitle}
/>
{confirmDialog}
<TemplateCustomizeDialog
isOpen={customizeDialog !== null}
templateTitle={customizeDialog?.templateTitle ?? ""}
valuesCount={customizeDialog?.valuesCount ?? 0}
cardsCount={customizeDialog?.cardsCount ?? 0}
initialTitle={typeof state.title === "string" ? state.title : ""}
initialTitle={
fromCreateWizard && state.templateReviewEntryFromCreateFlow === true
? typeof state.title === "string"
? state.title
: ""
: ""
}
initialDescription={
typeof state.communityContext === "string"
? state.communityContext
fromCreateWizard && state.templateReviewEntryFromCreateFlow === true
? typeof state.communityContext === "string"
? state.communityContext
: ""
: ""
}
initialLocation={
typeof state.communityLocation === "string"
? state.communityLocation
fromCreateWizard && state.templateReviewEntryFromCreateFlow === true
? typeof state.communityLocation === "string"
? state.communityLocation
: ""
: ""
}
onClose={closeCustomizeDialog}
@@ -926,13 +945,24 @@ function CreateFlowLayoutContent({
onEdit={
isCompletedStep
? () => {
const last = readLastPublishedRule();
if (!last) return;
updateState({
editingPublishedRuleId: last.id,
sections: [],
});
router.push(createFlowStepPath("final-review"));
void (async () => {
const last = readLastPublishedRule();
if (!last) return;
if (publishedRuleEditWouldReplaceDraft(state, last)) {
const agreed = await requestConfirm({
title: messages.create.topNav.editReplaceDraftTitle,
description:
messages.create.topNav.editReplaceDraftDescription,
proceedText:
messages.create.topNav.editReplaceDraftProceed,
cancelText:
messages.create.topNav.editReplaceDraftCancel,
});
if (!agreed) return;
}
replaceState(createFlowStateForEditingPublishedRule(last));
router.push(createFlowStepPath("final-review"));
})();
}
: undefined
}
+11 -1
View File
@@ -21,7 +21,11 @@ import {
isCreateFlowTemplatesPickerPath,
parseCreateFlowScreenFromPathname,
} from "./utils/flowSteps";
import { hasFreshEntryPending } from "./utils/prepareFreshCreateFlowEntry";
import {
hasFreshEntryPending,
hasTemplateApplyLatch,
clearTemplateApplyLatch,
} from "./utils/prepareFreshCreateFlowEntry";
import { isBackendSyncEnabled } from "../../../lib/create/backendSyncEnabled";
@@ -94,6 +98,12 @@ export function SignedInDraftHydration({
return;
}
if (hasTemplateApplyLatch()) {
finishedUserIdRef.current = userId;
clearTemplateApplyLatch();
return;
}
// Local draft wins over server: no fetch, no replaceState. The provider
// already hydrated from localStorage at mount, so the user sees their
// unsaved keystrokes immediately.
+10 -9
View File
@@ -18,7 +18,6 @@ import type {
import {
clearAnonymousCreateFlowStorage,
clearLegacyCreateFlowKeysOnce,
hasTransferPendingFlag,
readAnonymousCreateFlowState,
writeAnonymousCreateFlowState,
} from "../utils/anonymousDraftStorage";
@@ -65,6 +64,7 @@ export function CreateFlowProvider({
const [currentStep] = useState<CreateFlowStep | null>(initialStep);
const prevPersistRef = useRef(enableLocalDraftMirroring);
const persistWriteSkipRef = useRef(true);
const coreValueWriteSkipRef = useRef(true);
const initialHydrateDoneRef = useRef(false);
useEffect(() => {
@@ -115,13 +115,6 @@ export function CreateFlowProvider({
const wasOff = !prevPersistRef.current;
prevPersistRef.current = true;
if (!wasOff) return;
if (hasTransferPendingFlag()) return;
if (
typeof window !== "undefined" &&
new URLSearchParams(window.location.search).get("syncDraft") === "1"
) {
return;
}
const from = readAnonymousCreateFlowState();
if (Object.keys(from).length === 0) return;
// eslint-disable-next-line react-hooks/set-state-in-effect -- hydrate local draft when mirroring turns on
@@ -160,8 +153,16 @@ export function CreateFlowProvider({
/** Meaning/signals for core values: survives refresh for signed-in users; merged with anonymous draft when both exist. */
useEffect(() => {
if (!enableLocalDraftMirroring) {
coreValueWriteSkipRef.current = true;
return;
}
if (coreValueWriteSkipRef.current) {
coreValueWriteSkipRef.current = false;
return;
}
writeCoreValueDetailsToLocalStorage(state.coreValueDetailsByChipId);
}, [state.coreValueDetailsByChipId]);
}, [state.coreValueDetailsByChipId, enableLocalDraftMirroring]);
const markCreateFlowInteraction = useCallback(() => {
setInteractionTouched(true);
@@ -3,7 +3,11 @@
import { useCallback, useState } from "react";
import { buildPublishPayload } from "../../../../lib/create/buildPublishPayload";
import { stateWithPendingCommunityAvatar } from "../../../../lib/create/flushPendingCommunityAvatar";
import { publishRule, updatePublishedRule } from "../../../../lib/create/api";
import {
deleteServerDraft,
publishRule,
updatePublishedRule,
} from "../../../../lib/create/api";
import { writeLastPublishedRule } from "../../../../lib/create/lastPublishedRule";
import { writePendingKeepRuleLogin } from "../../../../lib/create/pendingKeepRuleLogin";
import messages from "../../../../messages/en/index";
@@ -14,6 +18,15 @@ import {
} from "../utils/flowSteps";
import { createFlowStepPath } from "../utils/createFlowPaths";
const DRAFT_DELETE_ATTEMPTS = 3;
/** The rule is saved. Keep trying until the source draft is actually gone. */
async function deleteServerDraftAfterPublish(): Promise<void> {
for (let attempt = 0; attempt < DRAFT_DELETE_ATTEMPTS; attempt += 1) {
if (await deleteServerDraft()) return;
}
}
type AppRouterLike = { push: (_href: string) => void };
type OpenLogin = (args: {
@@ -150,6 +163,7 @@ export function useCreateFlowFinalize({
document: ruleDocument,
});
updateState({ editingPublishedRuleId: undefined });
void deleteServerDraftAfterPublish();
router.push(createFlowStepPath("completed"));
return;
}
@@ -203,6 +217,8 @@ export function useCreateFlowFinalize({
if (isGuest) {
writePendingKeepRuleLogin();
onGuestPublished?.({ skippedInvites: skippedGuestInvites });
} else {
void deleteServerDraftAfterPublish();
}
router.push(
createFlowStepPath("completed", {
@@ -68,6 +68,14 @@ export function useCreateFlowNavigation(
const validStep = parseCreateFlowScreenFromPathname(pathname ?? null);
useLayoutEffect(() => {
if (!validStep || validStep === "completed" || validStep === "edit-rule") {
return;
}
if (state.currentStep === validStep) return;
updateState({ currentStep: validStep });
}, [validStep, state.currentStep, updateState]);
useLayoutEffect(() => {
if (!pathname?.includes("/create/review-template/")) return;
if (
@@ -2,19 +2,25 @@
import { useCallback, useMemo, useState } from "react";
import {
buildTemplateCustomizePrefill,
templatePresetDetailsFromPrefill,
buildAppliedTemplateCreateFlowState,
sectionsFromTemplateBody,
} from "../../../../lib/create/applyTemplatePrefill";
import { fetchDraftFromServer } from "../../../../lib/create/api";
import { createFlowStateHasKeys } from "../../../../lib/create/draftHydrationUtils";
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 { AsyncConfirmOptions } from "../../../hooks/useAsyncConfirm";
import type {
CreateFlowContextValue,
CreateFlowState,
} from "../types";
import { hasBrowserCreateFlowDraft } from "../utils/createRuleEntry";
import { createFlowStepPath } from "../utils/createFlowPaths";
import {
latchTemplateApply,
prepareFreshCreateFlowEntrySync,
} from "../utils/prepareFreshCreateFlowEntry";
type AppRouterLike = { push: (_href: string) => void };
type UpdateState = CreateFlowContextValue["updateState"];
@@ -61,13 +67,27 @@ export type UseTemplateReviewActionsResult = {
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>[];
const TEMPLATE_NAV_KEYS = new Set([
"templateReviewEntryFromCreateFlow",
"templateReviewBackSlug",
"pendingTemplateAction",
"currentStep",
"methodSectionsPinCommitted",
]);
function createFlowStateLooksLikeProgress(state: CreateFlowState): boolean {
return Object.keys(state).some((key) => !TEMPLATE_NAV_KEYS.has(key));
}
async function hasDraftToReplace(
state: CreateFlowState,
signedIn: boolean,
): Promise<boolean> {
if (createFlowStateLooksLikeProgress(state)) return true;
if (hasBrowserCreateFlowDraft()) return true;
if (!signedIn) return false;
const server = await fetchDraftFromServer();
return server != null && createFlowStateHasKeys(server);
}
/**
@@ -86,10 +106,11 @@ function sectionsFromTemplateBody(
export function useTemplateReviewActions({
pathname,
state,
updateState,
replaceState,
router,
fromCreateWizard = false,
signedIn = false,
requestConfirm,
markCreateFlowInteraction,
}: {
pathname: string | null | undefined;
@@ -103,6 +124,8 @@ export function useTemplateReviewActions({
* draft title must not count as “community steps already done”.
*/
fromCreateWizard?: boolean;
signedIn?: boolean;
requestConfirm?: (_opts: AsyncConfirmOptions) => Promise<boolean>;
markCreateFlowInteraction: () => void;
}): UseTemplateReviewActionsResult {
const [isApplyingTemplate, setIsApplyingTemplate] = useState(false);
@@ -121,10 +144,26 @@ export function useTemplateReviewActions({
pathname?.includes("/create/review-template/"),
);
const keepInFlowIdentity =
fromCreateWizard && state.templateReviewEntryFromCreateFlow === true;
const confirmReplaceDraft = useCallback(async (): Promise<boolean> => {
if (!requestConfirm) return true;
if (!(await hasDraftToReplace(state, signedIn))) return true;
const copy = messages.create.templateReview.replaceDraft;
return requestConfirm({
title: copy.title,
description: copy.description,
proceedText: copy.proceed,
cancelText: copy.cancel,
});
}, [requestConfirm, signedIn, state]);
const handleCustomize = useCallback(async () => {
if (!templateReviewSlug) return;
markCreateFlowInteraction();
setTemplateReviewApplyError(null);
if (!(await confirmReplaceDraft())) return;
setIsApplyingTemplate(true);
const loaded = await loadTemplateReviewBySlug(templateReviewSlug);
setIsApplyingTemplate(false);
@@ -140,7 +179,11 @@ export function useTemplateReviewActions({
valuesCount: counts?.values ?? 0,
cardsCount: counts?.cards ?? 0,
});
}, [markCreateFlowInteraction, templateReviewSlug]);
}, [
confirmReplaceDraft,
markCreateFlowInteraction,
templateReviewSlug,
]);
const closeCustomizeDialog = useCallback(() => {
setCustomizeDialog(null);
@@ -150,44 +193,29 @@ export function useTemplateReviewActions({
(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: {
prepareFreshCreateFlowEntrySync({ signedIn });
latchTemplateApply();
replaceState(() =>
buildAppliedTemplateCreateFlowState({
slug: customizeDialog.slug,
body: customizeDialog.body,
mode: "customize",
},
});
identity: {
title: fields.title,
communityContext: fields.communityContext,
communityLocation: fields.communityLocation,
},
}),
);
setCustomizeDialog(null);
router.push(createFlowStepPath("core-values"));
},
[
customizeDialog,
markCreateFlowInteraction,
replaceState,
router,
state.methodSectionsPinCommitted,
updateState,
signedIn,
],
);
@@ -195,6 +223,7 @@ export function useTemplateReviewActions({
if (!templateReviewSlug) return;
markCreateFlowInteraction();
setTemplateReviewApplyError(null);
if (!(await confirmReplaceDraft())) return;
setIsApplyingTemplate(true);
const loaded = await loadTemplateReviewBySlug(templateReviewSlug);
setIsApplyingTemplate(false);
@@ -211,63 +240,33 @@ export function useTemplateReviewActions({
return;
}
replaceState((prev) => {
const base = stripCustomRuleSelectionFields(prev);
const customizePrefill = buildTemplateCustomizePrefill(
template.body,
templateReviewSlug ?? undefined,
);
const details = templatePresetDetailsFromPrefill(customizePrefill);
const hasValuesSeed =
customizePrefill.selectedCoreValueIds !== undefined;
const sectionsWithoutValues = hasValuesSeed
? sections.filter((s) => {
const name = (s as { categoryName?: unknown }).categoryName;
if (typeof name !== "string") return true;
const key = name.toLowerCase().replace(/[^a-z]+/g, "");
return key !== "values" && key !== "corevalues";
})
: sections;
const pinPatch =
methodSectionsPinsForHydratedSelections(customizePrefill);
const seeded: CreateFlowState = {
...base,
...customizePrefill,
...details,
sections: sectionsWithoutValues,
methodSectionsPinCommitted: pinPatch,
templateReviewBackSlug: templateReviewSlug,
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,
};
});
prepareFreshCreateFlowEntrySync({ signedIn });
latchTemplateApply();
replaceState(() =>
buildAppliedTemplateCreateFlowState({
slug: templateReviewSlug,
body: template.body,
mode: "useWithoutChanges",
identity: keepInFlowIdentity
? {
title: state.title,
communityContext: state.communityContext,
communityLocation: state.communityLocation,
}
: undefined,
}),
);
router.push(createFlowStepPath("final-review"));
}, [
fromCreateWizard,
confirmReplaceDraft,
keepInFlowIdentity,
markCreateFlowInteraction,
replaceState,
router,
state.communityContext,
state.communityLocation,
signedIn,
state.title,
templateReviewSlug,
]);
@@ -18,7 +18,10 @@ import {
type FinalReviewCategoryRowDetailed,
} from "../../../../../lib/create/buildFinalReviewCategories";
import { communityInitialsFromTitle } from "../../../../../lib/create/communityInitials";
import { finalReviewChipHasWarning } from "../../../../../lib/create/finalReviewChipWarnings";
import {
finalReviewChipHasWarning,
finalReviewMissingWordsLabels,
} from "../../../../../lib/create/finalReviewChipWarnings";
import { applyFinalReviewChipEditPatch } from "../../../../../lib/create/applyFinalReviewChipEditPatch";
import type {
TemplateChipDetail,
@@ -234,6 +237,11 @@ export function FinalReviewScreen({
const descriptionEmptyHint = t("communityContextEditModal.emptyHint");
const missingWordsLabels = useMemo(
() => finalReviewMissingWordsLabels(state),
[state],
);
const templatePath = isTemplateCreatePath(state);
const avatarUpload = useCommunityAvatarUpload();
const serverAvatarUrl = useCommunityAvatarDisplayUrl(state.communityAvatarUrl);
@@ -277,6 +285,19 @@ export function FinalReviewScreen({
: t("description")
}
>
{missingWordsLabels.length > 0 ? (
<Alert
type="banner"
status="warning"
size="m"
title={t("missingWordsWarning.title")}
description={t("missingWordsWarning.description").replace(
"{labels}",
missingWordsLabels.join(", "),
)}
hasTrailingIcon={false}
/>
) : null}
{bindingArbitrationNeedsSeparateYes(state) ? (
<Alert
type="banner"
@@ -84,6 +84,16 @@ export function hasTransferPendingFlag(): boolean {
}
}
/** Drop the transfer flag without touching the stored draft. */
export function clearTransferPendingFlag(): void {
if (typeof window === "undefined") return;
try {
window.localStorage.removeItem(CREATE_FLOW_TRANSFER_PENDING_KEY);
} catch {
// ignore
}
}
/** One-time cleanup of pre–anonymous-draft keys. */
export function clearLegacyCreateFlowKeysOnce(): void {
if (typeof window === "undefined") return;
@@ -0,0 +1,24 @@
import { clearPendingKeepRuleLogin } from "../../../../lib/create/pendingKeepRuleLogin";
import { clearLastPublishedRule } from "../../../../lib/create/lastPublishedRule";
import { clearCreateFlowPersistedDrafts } from "./clearCreateFlowPersistedDrafts";
const LEGACY_LIVE_KEY = "create-flow-state";
const LEGACY_DRAFT_KEY = "create-flow-draft";
/**
* Drop every Rule the browser is holding: the anonymous draft, last finished
* Rule, keep-this-rule prompt, and leftover pre-anonymous keys. Does not
* `DELETE /api/drafts/me`. Call after Log out and Delete account.
*/
export function clearBrowserRuleData(): void {
clearCreateFlowPersistedDrafts();
clearLastPublishedRule();
clearPendingKeepRuleLogin();
if (typeof window === "undefined") return;
try {
window.localStorage.removeItem(LEGACY_LIVE_KEY);
window.localStorage.removeItem(LEGACY_DRAFT_KEY);
} catch {
// ignore
}
}
@@ -3,6 +3,7 @@ import {
buildFinalReviewCategoryRowsDetailed,
type FinalReviewCategoryNames,
} from "../../../../lib/create/buildFinalReviewCategories";
import { finalReviewChipBlocksContinue } from "../../../../lib/create/finalReviewChipWarnings";
import type { TemplateFacetGroupKey } from "../../../../lib/create/templateReviewMapping";
import type { CreateFlowState, CreateFlowStep } from "../types";
@@ -75,8 +76,9 @@ const FINAL_REVIEW_REQUIRED_GROUPS: readonly TemplateFacetGroupKey[] = [
] as const;
/**
* Continue on final review waits for a community name and at least one card
* on each of the four questions. Skipped values do not block.
* Continue on final review waits for a community name, at least one card on
* each of the four questions, every picked card's words, and every picked
* value's meaning. Skipped values and missing signals do not block.
*/
export function isFinalReviewContinueBlocked(state: CreateFlowState): boolean {
const title = typeof state.title === "string" ? state.title.trim() : "";
@@ -85,10 +87,16 @@ export function isFinalReviewContinueBlocked(state: CreateFlowState): boolean {
state,
FINAL_REVIEW_BLOCK_NAMES,
);
return FINAL_REVIEW_REQUIRED_GROUPS.some((groupKey) => {
const missingRequiredCard = FINAL_REVIEW_REQUIRED_GROUPS.some((groupKey) => {
const row = rows.find((candidate) => candidate.groupKey === groupKey);
return !row || row.entries.length === 0;
});
if (missingRequiredCard) return true;
return rows.some((row) =>
row.entries.some((entry) =>
finalReviewChipBlocksContinue(state, entry.groupKey, entry.overrideKey),
),
);
}
/**
+26
View File
@@ -0,0 +1,26 @@
import { createFlowStateHasKeys } from "../../../../lib/create/draftHydrationUtils";
import type { CreateFlowStep } from "../types";
import { readAnonymousCreateFlowState } from "./anonymousDraftStorage";
import { CREATE_ROUTES, createFlowStepPath } from "./createFlowPaths";
import { readCoreValueDetailsFromLocalStorage } from "./coreValueDetailsLocalStorage";
import { isValidStep } from "./flowSteps";
const NON_RESUME_STEPS = new Set<CreateFlowStep>(["completed", "edit-rule"]);
export function hasBrowserCreateFlowDraft(): boolean {
if (createFlowStateHasKeys(readAnonymousCreateFlowState())) return true;
return Object.keys(readCoreValueDetailsFromLocalStorage()).length > 0;
}
/**
* Path for header / Home / Profile **Create rule**. Never clears the browser
* draft or `DELETE`s `/api/drafts/me` — resume where the draft was left.
*/
export function createRuleEntryPath(): string {
const local = readAnonymousCreateFlowState();
const step = local.currentStep;
if (isValidStep(step) && !NON_RESUME_STEPS.has(step)) {
return createFlowStepPath(step);
}
return CREATE_ROUTES.createFirstStep;
}
+9
View File
@@ -247,6 +247,15 @@ export function isValidStep(
);
}
/** Resume a saved draft on the screen it was left on. */
export function resumeCreateFlowStep(
state: { currentStep?: CreateFlowStep } | null | undefined,
): CreateFlowStep {
const step = state?.currentStep;
if (step && isValidStep(step)) return step;
return FIRST_STEP;
}
/**
* Parses `/create/{screenId}` (and optional trailing segments) from pathname.
* Returns null for non-wizard paths (e.g. `/create/review-template/...`).
@@ -11,6 +11,9 @@ import { isBackendSyncEnabled } from "../../../../lib/create/backendSyncEnabled"
*/
export const FRESH_ENTRY_PENDING_KEY = "create:fresh-entry-pending";
/** Set when a template is applied so server-draft hydration cannot replace it. */
export const TEMPLATE_APPLY_LATCH_KEY = "create:template-apply-latch";
export type PrepareFreshCreateFlowEntryOptions = {
/**
* When `true`, and backend sync is on, also `DELETE /api/drafts/me`.
@@ -28,6 +31,33 @@ export function hasFreshEntryPending(): boolean {
}
}
export function latchTemplateApply(): void {
if (typeof window === "undefined") return;
try {
window.sessionStorage.setItem(TEMPLATE_APPLY_LATCH_KEY, "1");
} catch {
/* ignore — sessionStorage may be unavailable */
}
}
export function hasTemplateApplyLatch(): boolean {
if (typeof window === "undefined") return false;
try {
return window.sessionStorage.getItem(TEMPLATE_APPLY_LATCH_KEY) === "1";
} catch {
return false;
}
}
export function clearTemplateApplyLatch(): void {
if (typeof window === "undefined") return;
try {
window.sessionStorage.removeItem(TEMPLATE_APPLY_LATCH_KEY);
} catch {
/* ignore */
}
}
function setFreshEntryPending(): void {
if (typeof window === "undefined") return;
try {
@@ -0,0 +1,21 @@
import type { CreateFlowState } from "../types";
import { forgetFlushedCommunityAvatarUrl } from "../../../../lib/create/flushPendingCommunityAvatar";
import { clearPendingCommunityAvatarFile } from "../../../../lib/create/pendingCommunityAvatarUpload";
import {
clearTransferPendingFlag,
writeAnonymousCreateFlowState,
} from "./anonymousDraftStorage";
import { writeCoreValueDetailsToLocalStorage } from "./coreValueDetailsLocalStorage";
/**
* Profile already has the server draft. Write that snapshot into the browser
* before opening the wizard so the create flow can mount it immediately,
* including when backend sync is off and hydration will not refetch.
*/
export function seedContinuedDraftLocalStorage(state: CreateFlowState): void {
writeAnonymousCreateFlowState(state);
writeCoreValueDetailsToLocalStorage(state.coreValueDetailsByChipId);
clearTransferPendingFlag();
forgetFlushedCommunityAvatarUrl();
void clearPendingCommunityAvatarFile();
}
+14 -19
View File
@@ -23,7 +23,9 @@ import {
downloadStoredRuleAsPdf,
} from "../../../lib/create/ruleExport";
import {
clearLastPublishedRule,
finishedAtIso,
readLastPublishedRule,
writeLastPublishedRule,
type StoredLastPublishedRule,
} from "../../../lib/create/lastPublishedRule";
@@ -31,28 +33,19 @@ import {
CREATE_FLOW_MANAGE_STAKEHOLDERS_QUERY,
CREATE_FLOW_MANAGE_STAKEHOLDERS_VALUE,
CREATE_FLOW_REVIEW_RETURN_QUERY_KEY,
FIRST_STEP,
isValidStep,
resumeCreateFlowStep,
} from "../create/utils/flowSteps";
import type { CreateFlowStep } from "../create/types";
import { clearAnonymousCreateFlowStorage } from "../create/utils/anonymousDraftStorage";
import { clearCoreValueDetailsLocalStorage } from "../create/utils/coreValueDetailsLocalStorage";
import { prepareFreshCreateFlowEntrySync } from "../create/utils/prepareFreshCreateFlowEntry";
import { clearBrowserRuleData } from "../create/utils/clearBrowserRuleData";
import { createRuleEntryPath } from "../create/utils/createRuleEntry";
import { createFlowStepPath } from "../create/utils/createFlowPaths";
import { seedContinuedDraftLocalStorage } from "../create/utils/seedContinuedDraftLocalStorage";
import { useMediaQuery } from "../../hooks/useMediaQuery";
import {
ProfilePageSignedOutView,
ProfilePageView,
} from "./_components/ProfilePage.view";
function resolveContinueStepState(
state: { currentStep?: CreateFlowStep } & Record<string, unknown>,
): CreateFlowStep {
const s = state.currentStep;
if (s && isValidStep(s)) return s;
return FIRST_STEP;
}
export default function ProfilePageClient() {
const t = useTranslation("pages.profile");
const router = useRouter();
@@ -203,6 +196,7 @@ export default function ProfilePageClient() {
const handleSignOut = useCallback(async () => {
setActionError(null);
await logout();
clearBrowserRuleData();
setUser(null);
setRules([]);
setDraft(null);
@@ -228,6 +222,8 @@ export default function ProfilePageClient() {
const res = await deletePublishedRule(id);
setRuleDeleteBusy(false);
if (res.ok === true) {
const stored = readLastPublishedRule();
if (stored?.id === id) clearLastPublishedRule();
setRuleDeleteTargetId(null);
void load();
return;
@@ -297,15 +293,13 @@ export default function ProfilePageClient() {
const handleContinueDraft = useCallback(() => {
if (draft == null || !draft.hasDraft) return;
const step = resolveContinueStepState(draft.state);
clearAnonymousCreateFlowStorage();
clearCoreValueDetailsLocalStorage();
router.push(`/create/${step}`);
const step = resumeCreateFlowStep(draft.state);
seedContinuedDraftLocalStorage(draft.state);
router.push(createFlowStepPath(step));
}, [draft, router]);
const handleStartNewCustomRule = useCallback(() => {
prepareFreshCreateFlowEntrySync({ signedIn: true });
router.push("/create/informational");
router.push(createRuleEntryPath());
}, [router]);
const handleRequestDeleteDraft = useCallback(() => {
@@ -392,6 +386,7 @@ export default function ProfilePageClient() {
const res = await deleteAccount();
setAccountDeleteBusy(false);
if (res.ok) {
clearBrowserRuleData();
setAccountDeleteOpen(false);
setUser(null);
setRules([]);
@@ -14,6 +14,7 @@ import Alert from "../../../components/modals/Alert";
import HeaderLockup from "../../../components/type/HeaderLockup";
import { useTranslation } from "../../../contexts/MessagesContext";
import type { CreateFlowState } from "../../create/types";
import { createCompletedPath } from "../../create/utils/createFlowPaths";
import type {
MyPublishedRule,
ServerDraftForProfile,
@@ -257,7 +258,7 @@ export function ProfilePageView({
id: "create-template",
title: t("optionCreateTemplate"),
description: "",
href: "/templates?fromFlow=1",
href: "/templates",
leadingIcon: "content_copy",
showDescription: false,
},
@@ -355,7 +356,7 @@ export function ProfilePageView({
createLabel={t("emptyCardCreate")}
browseLabel={t("emptyCardBrowse")}
onCreate={onStartNewCustomRule}
browseHref="/templates?fromFlow=1"
browseHref="/templates"
/>
) : (
<div className="flex flex-col gap-3">
@@ -399,6 +400,8 @@ export function ProfilePageView({
description={rule.summary ?? undefined}
expanded
size={ruleCardSize}
href={createCompletedPath({ ruleId: rule.id })}
ariaLabel={rule.title}
hasBottomLinks
bottomStatusLabel={t("finishedBadge")}
bottomLinks={[
@@ -422,7 +425,7 @@ export function ProfilePageView({
rule.title,
)}
backgroundColor="bg-[var(--color-surface-invert-brand-teal)]"
className={ownedRuleCardShellClass}
className={ruleCardShellClass}
/>
))}
</div>
@@ -449,7 +452,8 @@ export function ProfilePageView({
description={rule.summary ?? undefined}
expanded
size={ruleCardSize}
href={`/invite/${encodeURIComponent(rule.id)}`}
href={`/rules/${encodeURIComponent(rule.id)}`}
ariaLabel={rule.title}
communityInitials={communityInitialsFromTitle(
rule.title,
)}
@@ -5,7 +5,6 @@ import { useSearchParams } from "next/navigation";
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 } from "../../(app)/create/utils/flowSteps";
import { useTranslation } from "../../contexts/MessagesContext";
@@ -62,8 +61,7 @@ export default function TemplatesPageClient({
}
/**
* - `fromFlow=1` — skip `prepareFreshCreateFlowEntry` on template click
* (draft preserved). Used by profile “Create from template”.
* - `fromFlow=1` — in-wizard catalog; community answers stay until apply.
* Templates carry no recommendation; the grid stays in curated order.
*/
function TemplatesGridWithSearchParams({
@@ -91,13 +89,6 @@ function TemplatesGrid({
hrefForTemplate={(slug) =>
buildTemplateReviewHref(slug, { fromCreateWizard: fromFlow })
}
onTemplateClick={() => {
if (!fromFlow) {
// Marketing /templates has no session in hand; DELETE is
// best-effort and the sentinel blocks stale-draft hydration.
prepareFreshCreateFlowEntrySync({ signedIn: true });
}
}}
/>
);
}
+2
View File
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server";
import { isDatabaseConfigured } from "../../../../lib/server/env";
import { dbUnavailable } from "../../../../lib/server/responses";
import { clearGuestRuleClaimCookie } from "../../../../lib/server/guestRuleClaim";
import { destroySessionFromRequest } from "../../../../lib/server/session";
import { apiRoute } from "../../../../lib/server/apiRoute";
@@ -10,5 +11,6 @@ export const POST = apiRoute("auth.logout", async () => {
}
await destroySessionFromRequest();
await clearGuestRuleClaimCookie();
return NextResponse.json({ ok: true });
});
+2 -9
View File
@@ -11,7 +11,7 @@ import { apiRoute } from "../../../../lib/server/apiRoute";
import { putDraftBodySchema } from "../../../../lib/server/validation/createFlowSchemas";
import { readLimitedJson } from "../../../../lib/server/validation/requestBody";
import { jsonFromZodError } from "../../../../lib/server/validation/zodHttp";
import { deleteUploadsForDraft } from "../../../../lib/server/uploads/deleteUploadedFiles";
import { deleteRuleDraftForUser } from "../../../../lib/server/ruleDrafts";
import { linkUploadsToDraft } from "../../../../lib/server/uploads/linkUploads";
export const GET = apiRoute("drafts.me.get", async () => {
@@ -92,14 +92,7 @@ export const DELETE = apiRoute("drafts.me.delete", async () => {
// Idempotent: missing draft is a no-op so callers can fire-and-forget after
// publish / exit without worrying about prior state.
const draft = await prisma.ruleDraft.findUnique({
where: { userId: user.id },
select: { id: true },
});
if (draft) {
await deleteUploadsForDraft(draft.id);
}
await prisma.ruleDraft.deleteMany({ where: { userId: user.id } });
await deleteRuleDraftForUser(user.id);
return NextResponse.json({ ok: true });
});
+28
View File
@@ -35,10 +35,36 @@ import {
import { readLimitedJson } from "../../../lib/server/validation/requestBody";
import { jsonFromZodError } from "../../../lib/server/validation/zodHttp";
import { publishedRuleAnalyticsColumns } from "../../../lib/server/publishedRulePersist";
import { deleteRuleDraftForUser } from "../../../lib/server/ruleDrafts";
/** One anonymous publish per IP per minute (in-memory limiter). */
const ANONYMOUS_PUBLISH_IP_MIN_INTERVAL_MS = 60_000;
const DRAFT_DELETE_ATTEMPTS = 3;
/**
* The rule is already saved. Retry clearing the source draft so Profile does
* not keep showing it as in progress. A leftover draft is logged, not a
* failed publish.
*/
async function deleteDraftAfterPublish(
userId: string,
requestId: string,
): Promise<void> {
let lastError: unknown;
for (let attempt = 0; attempt < DRAFT_DELETE_ATTEMPTS; attempt += 1) {
try {
await deleteRuleDraftForUser(userId);
return;
} catch (err) {
lastError = err;
}
}
logRouteError("rules.publish", requestId, lastError, {
phase: "deleteRuleDraftForUser",
});
}
function clientIp(request: NextRequest): string {
return (
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ??
@@ -170,6 +196,7 @@ export const POST = apiRoute(
document,
userId: user.id,
});
await deleteDraftAfterPublish(user.id, requestId);
return NextResponse.json({
rule: {
@@ -261,6 +288,7 @@ export const POST = apiRoute(
document,
userId: user.id,
});
await deleteDraftAfterPublish(user.id, requestId);
return NextResponse.json({
rule: {
+2
View File
@@ -6,6 +6,7 @@ import {
internalError,
unauthorized,
} from "../../../../lib/server/responses";
import { clearGuestRuleClaimCookie } from "../../../../lib/server/guestRuleClaim";
import {
clearSessionCookie,
getSessionUser,
@@ -37,6 +38,7 @@ export const DELETE = apiRoute("user.me.delete", async () => {
}
await clearSessionCookie();
await clearGuestRuleClaimCookie();
return NextResponse.json({ ok: true });
});
+7 -2
View File
@@ -36,6 +36,7 @@ const RuleContainer = memo<RuleProps>(
className = "",
onClick,
href,
ariaLabel: ariaLabelProp,
expanded = false,
size: sizeProp,
categories,
@@ -67,7 +68,11 @@ const RuleContainer = memo<RuleProps>(
const size = sizeProp ?? "L";
const isInteractive = interactive ?? !hasBottomLinks;
const t = useTranslation("ruleCard");
const cardAriaLabel = t("ariaLabel")?.replace("{title}", title) || title;
const trimmedAriaLabel = ariaLabelProp?.trim() ?? "";
const cardAriaLabel =
trimmedAriaLabel.length > 0
? trimmedAriaLabel
: t("ariaLabel")?.replace("{title}", title) || title;
const recommendedLabel = t("recommendedLabel");
const handleClick = () => {
@@ -111,7 +116,7 @@ const RuleContainer = memo<RuleProps>(
icon={icon}
backgroundColor={backgroundColor}
className={className}
href={isInteractive && !hasBottomLinks ? href : undefined}
href={href}
onClick={isInteractive && !hasBottomLinks ? handleClick : undefined}
onKeyDown={
isInteractive && !hasBottomLinks && !href ? handleKeyDown : undefined
+8 -1
View File
@@ -56,9 +56,16 @@ export interface RuleProps {
onClick?: () => void;
/**
* When set, the card is a real link (focusable, Enter, open in a new tab)
* instead of a click-only `role="button"` surface.
* instead of a click-only `role="button"` surface. Combined with
* {@link hasBottomLinks}, the link is a stretched overlay so Invite /
* Duplicate / Delete stay separate controls.
*/
href?: string;
/**
* Accessible name for the card or its overlay link. Defaults to the
* `ruleCard` “Learn more about {title}…” string.
*/
ariaLabel?: string;
expanded?: boolean;
size?: RuleSizeValue;
categories?: Category[];
+25 -1
View File
@@ -298,6 +298,7 @@ export function RuleView({
<NavigationLink
key={link.id}
{...shared}
className={`${shared.className} pointer-events-auto relative z-10`}
href={link.href}
onClick={(e) => e.stopPropagation()}
/>
@@ -307,6 +308,7 @@ export function RuleView({
<NavigationLink
key={link.id}
{...shared}
className={`${shared.className} pointer-events-auto relative z-10`}
onClick={(e) => {
e.stopPropagation();
link.onClick?.();
@@ -319,7 +321,8 @@ export function RuleView({
const surfaceStyle = surfaceColor
? { backgroundColor: surfaceColor }
: undefined;
const isLinkCard = Boolean(href) && interactiveCard;
const isLinkCard = Boolean(href) && interactiveCard && !hasBottomLinks;
const overlayHref = hasBottomLinks && href ? href : undefined;
const hasCategories = Boolean(categories && categories.length > 0);
const expandedDescriptionFrameClass = [
@@ -610,6 +613,27 @@ export function RuleView({
);
}
if (overlayHref) {
return (
<div
className={`${cardClassName} cursor-pointer`}
style={surfaceStyle}
role="article"
>
<NextLink
href={overlayHref}
className="absolute inset-0 z-0 rounded-[inherit]"
aria-label={ariaLabel}
/>
<div
className={`relative z-[1] flex w-full flex-col items-start pointer-events-none ${cardGap}`}
>
{cardBody}
</div>
</div>
);
}
return (
<div
className={cardClassName}
@@ -7,7 +7,7 @@ import type { Category, RuleProps } from "../Rule";
import { getAssetPath } from "../../../../lib/assetUtils";
import type { RuleTemplateDto } from "../../../../lib/create/fetchTemplates";
import {
templateBodyToReviewData,
templateReviewDataForSlug,
templateSummaryFromBody,
} from "../../../../lib/create/templateReviewMapping";
import {
@@ -26,9 +26,9 @@ export interface TemplateReviewCardProps {
/**
* Expanded Rule for template review: surfaces + icon from Figma catalog (21764-16435);
* tag rows from API `body`. Chip clicks open a read-only detail modal per
* facet group (values / communication / membership / decision-making / conflict
* management) so reviewers can see what each chip means without editing.
* tag rows from the remade catalog chips. Chip clicks open a read-only detail
* modal per facet group (values / communication / membership / decision-making /
* conflict management) so reviewers can see what each chip means without editing.
*/
export function TemplateReviewCard({
template,
@@ -38,8 +38,8 @@ export function TemplateReviewCard({
const catalog = getGovernanceTemplateCatalogEntry(template.slug);
const pres = catalog ?? TEMPLATE_GRID_FALLBACK_PRESENTATION;
const { categories: rawCategories, chipDetailsByChipId } = useMemo(
() => templateBodyToReviewData(template.body),
[template.body],
() => templateReviewDataForSlug(template.slug, template.body),
[template.slug, template.body],
);
const summary = templateSummaryFromBody(template.description, template.body);
@@ -14,6 +14,7 @@ import { buildCreateFlowDraftPayload } from "../../../../lib/create/buildCreateF
import { MAGIC_LINK_TTL_MINUTES } from "../../../../lib/privacyRetention";
import { safeInternalPath } from "../../../../lib/safeInternalPath";
import {
clearTransferPendingFlag,
readAnonymousCreateFlowState,
setTransferPendingFlag,
} from "../../../(app)/create/utils/anonymousDraftStorage";
@@ -212,6 +213,7 @@ export default function LoginForm({
useEffect(() => {
if (isExpiredLinkError(errorParam)) {
setLinkExpired(true);
clearTransferPendingFlag();
}
}, [errorParam]);
@@ -15,7 +15,7 @@ import AvatarContainer from "../../asset/AvatarContainer";
import Avatar from "../../asset/Avatar";
import { getAssetPath, ASSETS } from "../../../../lib/assetUtils";
import { PRODUCTION_SITE_ORIGIN, websiteJsonLd } from "../../../../lib/siteMetadata";
import { prepareFreshCreateFlowEntrySync } from "../../../(app)/create/utils/prepareFreshCreateFlowEntry";
import { createRuleEntryPath } from "../../../(app)/create/utils/createRuleEntry";
import { TopView } from "./Top.view";
import type { TopProps } from "./Top.types";
@@ -59,16 +59,12 @@ const TopContainer = memo<TopProps>(
/**
* `Top` is hidden on `/create` routes by ConditionalNavigationClient, so
* this button is always clicked from outside the wizard. Clears anonymous
* `localStorage` synchronously and, when backend sync is on, fires the
* server `DELETE /api/drafts/me` in the background. `SignedInDraftHydration`
* reads the `create:fresh-entry-pending` sentinel and waits before fetching
* (see {@link prepareFreshCreateFlowEntrySync}).
* this button is always clicked from outside the wizard. Resume the draft
* in the browser instead of wiping it.
*/
const handleCreateRuleClick = useCallback(() => {
prepareFreshCreateFlowEntrySync({ signedIn: loggedIn });
router.push("/create/informational");
}, [loggedIn, router]);
router.push(createRuleEntryPath());
}, [router]);
const schemaData = websiteJsonLd(siteOrigin);
@@ -4,11 +4,10 @@
* Figma: "Section / Hero Banner" (18477:15473)
*/
import { memo, useCallback, useEffect, useMemo, useState } from "react";
import { memo, useCallback, useMemo } from "react";
import { useRouter } from "next/navigation";
import { useMessages, useTranslation } from "../../../contexts/MessagesContext";
import { fetchAuthSession } from "../../../../lib/create/api";
import { prepareFreshCreateFlowEntrySync } from "../../../(app)/create/utils/prepareFreshCreateFlowEntry";
import { createRuleEntryPath } from "../../../(app)/create/utils/createRuleEntry";
import type { Category } from "../../cards/Rule";
import type { ChipOption } from "../../controls/MultiSelect/MultiSelect.types";
import HeroBannerView from "./HeroBanner.view";
@@ -28,26 +27,10 @@ const HeroBannerContainer = memo<HeroBannerProps>(
const messages = useMessages();
const tHome = useTranslation("pages.home.heroBanner");
const tHero = useTranslation("heroBanner");
const [signedIn, setSignedIn] = useState(false);
useEffect(() => {
let cancelled = false;
void fetchAuthSession()
.then(({ user }) => {
if (!cancelled) setSignedIn(Boolean(user));
})
.catch(() => {
/* guest fallback */
});
return () => {
cancelled = true;
};
}, []);
const handleCreateRule = useCallback(() => {
prepareFreshCreateFlowEntrySync({ signedIn });
router.push("/create/informational");
}, [router, signedIn]);
router.push(createRuleEntryPath());
}, [router]);
const ruleCategories = useMemo<Category[]>(() => {
const groups = messages.heroBanner.ruleCard.categories;
@@ -7,7 +7,6 @@
import { memo, useEffect, useState } from "react";
import { useTranslation } from "../../../contexts/MessagesContext";
import { logger } from "../../../../lib/logger";
import { prepareFreshCreateFlowEntrySync } from "../../../(app)/create/utils/prepareFreshCreateFlowEntry";
import { buildTemplateReviewHref } from "../../../(app)/create/utils/flowSteps";
import {
fetchTemplates,
@@ -96,10 +95,6 @@ const RuleStackContainer = memo<RuleStackProps>(
}
}
logger.debug(`${slug} template clicked`);
// Marketing home “Popular templates”: same fresh start as Top “Create rule”.
// `signedIn: true` because this surface has no session in hand; DELETE is
// best-effort and the sentinel blocks stale-draft hydration.
prepareFreshCreateFlowEntrySync({ signedIn: true });
};
return (
@@ -4,38 +4,21 @@
* Figma: "Section / Your Turn" (24239:1397)
*/
import { memo, useCallback, useEffect, useState } from "react";
import { memo, useCallback, useState } from "react";
import { useRouter } from "next/navigation";
import { useMessages } from "../../../contexts/MessagesContext";
import { fetchAuthSession } from "../../../../lib/create/api";
import { prepareFreshCreateFlowEntrySync } from "../../../(app)/create/utils/prepareFreshCreateFlowEntry";
import { createRuleEntryPath } from "../../../(app)/create/utils/createRuleEntry";
import AskOrganizerInquiryModal from "../../modals/AskOrganizerInquiry";
import YourTurnView from "./YourTurn.view";
const YourTurnContainer = memo(() => {
const router = useRouter();
const copy = useMessages().pages.about.yourTurn;
const [signedIn, setSignedIn] = useState(false);
const [inquiryOpen, setInquiryOpen] = useState(false);
useEffect(() => {
let cancelled = false;
void fetchAuthSession()
.then(({ user }) => {
if (!cancelled) setSignedIn(Boolean(user));
})
.catch(() => {
/* guest fallback */
});
return () => {
cancelled = true;
};
}, []);
const onCreateRule = useCallback(() => {
prepareFreshCreateFlowEntrySync({ signedIn });
router.push("/create/informational");
}, [router, signedIn]);
router.push(createRuleEntryPath());
}, [router]);
return (
<>
+12 -12
View File
@@ -44,7 +44,7 @@ Order is defined in code by [`FLOW_STEP_ORDER`](../app/(app)/create/utils/flowSt
| 16 | Review and complete | `confirm-stakeholders` | `/create/confirm-stakeholders` |
| 17 | Review and complete | `completed` | `/create/completed` |
**Primary entry:** marketing header **Create rule** and profile **Create new custom Rule** both run **`prepareFreshCreateFlowEntry`** then navigate to **`/create`**, which redirects to **`/create/informational`** (see [`Top.container.tsx`](../app/components/navigation/Top/Top.container.tsx) and [`ProfilePageClient.tsx`](../app/(app)/profile/ProfilePageClient.tsx)).
**Primary entry:** marketing header **Create rule** and profile **Create new custom Rule** both call [`createRuleEntryPath`](../app/(app)/create/utils/createRuleEntry.ts) and resume the browser draft at its last step. They do **not** clear storage or `DELETE /api/drafts/me` (see [`Top.container.tsx`](../app/components/navigation/Top/Top.container.tsx) and [`ProfilePageClient.tsx`](../app/(app)/profile/ProfilePageClient.tsx)).
Active step for chrome and navigation is resolved from the pathname via [`parseCreateFlowScreenFromPathname`](../app/(app)/create/utils/flowSteps.ts) inside [`useCreateFlowNavigation`](../app/(app)/create/hooks/useCreateFlowNavigation.ts).
@@ -62,13 +62,13 @@ The step persists **`stakeholderEmails`** on `CreateFlowState` (validated on `PU
### Fresh start vs continue draft (signed-in + sync)
**Established pattern:** anonymous and signed-in users should see the **same** wizard when starting a **new** rule from marketing or profile: empty state at the first step, with no surprise reload of old work. Both can **publish** (guests get an unlisted public `/rules/{id}` with no owner). Both see **Save & Exit** from `community-structure` onward (and `edit-rule`). On **`/create/completed`**, guests still get **Save & Exit** (keep-this-rule magic-link modal); signed-in users get **Exit**. Wizard guests open the save-progress magic-link modal; signed-in users may **PUT** `/api/drafts/me` when `NEXT_PUBLIC_ENABLE_BACKEND_SYNC=true`.
**Established pattern:** **Create rule** in the header, on Home, and on Profile resumes the draft in the browser. It never wipes that draft or `DELETE`s `/api/drafts/me`. Starting over is the confirmed Delete on a Profile Draft card (or a later template-replace confirm). Both guests and signed-in people can **publish** (guests get an unlisted public `/rules/{id}` with no owner). Both see **Save & Exit** from `community-structure` onward (and `edit-rule`). On **`/create/completed`**, guests still get **Save & Exit** (keep-this-rule magic-link modal); signed-in users get **Exit**. Wizard guests open the save-progress magic-link modal; signed-in users may **PUT** `/api/drafts/me` when `NEXT_PUBLIC_ENABLE_BACKEND_SYNC=true`.
- **New rule entry** (always a clean slate): call [`prepareFreshCreateFlowEntry`](../app/(app)/create/utils/prepareFreshCreateFlowEntry.ts) **before** `router.push` into `/create` or `/create/review-template/...`. It clears **`create-flow-anonymous`** and the core-value-details `localStorage` key; when sync is on, it **`DELETE`s `/api/drafts/me`** so [`SignedInDraftHydration`](../app/(app)/create/SignedInDraftHydration.tsx) does not rehydrate a stale server draft after local storage was wiped.
- **Continue saved draft** (profile): do **not** call `prepareFreshCreateFlowEntry`. Clear the same `localStorage` keys **only** (see [`ProfilePageClient`](../app/(app)/profile/ProfilePageClient.tsx) `handleContinueDraft`) so the client mirror is empty, then navigate to **`/create/{savedStep}`**. Hydration loads the server draft; the URL may be corrected to `currentStep` when it differs from the path.
- **Local-only wipe** without touching the server: [`clearCreateFlowPersistedDrafts`](../app/(app)/create/utils/clearCreateFlowPersistedDrafts.ts) (same two `localStorage` keys). Prefer **`prepareFreshCreateFlowEntry`** for any user-facing “start new rule” navigation so signed-in + sync stays aligned with anonymous.
- **Create rule entry:** call [`createRuleEntryPath`](../app/(app)/create/utils/createRuleEntry.ts) and `router.push` that path. Do **not** call `prepareFreshCreateFlowEntry`.
- **Continue saved draft** (profile): do **not** call `prepareFreshCreateFlowEntry`. Write the server draft Profile already loaded into `create-flow-anonymous` and the core-value details key (see [`ProfilePageClient`](../app/(app)/profile/ProfilePageClient.tsx) `handleContinueDraft`), then navigate to **`/create/{savedStep}`**. The wizard reads that snapshot on mount, including when backend sync is off. Do not clear those keys and wait for a second fetch.
- **Confirmed wipe:** [`prepareFreshCreateFlowEntry`](../app/(app)/create/utils/prepareFreshCreateFlowEntry.ts) still clears **`create-flow-anonymous`** and, when sync is on, **`DELETE`s `/api/drafts/me`**. Use it only after the person agrees to start over, including when they confirm replacing a draft with a template.
Call sites for **`prepareFreshCreateFlowEntry`**: [`Top.container.tsx`](../app/components/navigation/Top/Top.container.tsx) (Create rule), profile **Create new custom Rule** ([`ProfilePageClient.tsx`](../app/(app)/profile/ProfilePageClient.tsx)), home **Popular templates** ([`RuleStack.container.tsx`](../app/components/sections/RuleStack/RuleStack.container.tsx)), and **direct** `/templates` template picks ([`TemplatesPageClient.tsx`](../app/(marketing)/templates/TemplatesPageClient.tsx)) when **`fromFlow` is absent**.
Call sites for **`createRuleEntryPath`**: [`Top.container.tsx`](../app/components/navigation/Top/Top.container.tsx) (Create rule), Home hero, About, and profile **Create new custom Rule** ([`ProfilePageClient.tsx`](../app/(app)/profile/ProfilePageClient.tsx)). Template catalog clicks do **not** wipe a draft; **Use without changes** / **Customize** ask first, then apply from an empty seed.
---
@@ -91,17 +91,17 @@ From that page, **Customize** opens a dialog for name, optional logo, descriptio
- **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.
**Direct entry vs in-flow template pick.** The same `/create/review-template/[slug]` URL is reached from two different origins. **Direct** picks (home Popular templates, `/templates`) do not wipe a draft on click. **Use without changes** and **Customize** ask before replacing a draft, then seed from the template with no leftover logo or setup answers. **In-flow** picks (`/create/templates?fromFlow=1`) keep the community name, description, and place already given. A hydration latch stops a saved server draft from overwriting the template after apply.
| Origin | Click-site behavior | URL the user lands on |
| --- | --- | --- |
| Home marketing "Popular templates" ([`RuleStack.container.tsx`](../app/components/sections/RuleStack/RuleStack.container.tsx)) | always `await prepareFreshCreateFlowEntry()` then navigate | `/create/review-template/[slug]` |
| `/templates` index ([`TemplatesPageClient.tsx`](../app/(marketing)/templates/TemplatesPageClient.tsx)) visited directly / via pasted URL | `fromFlow` absent → `await prepareFreshCreateFlowEntry()` then navigate | `/create/review-template/[slug]` |
| Home marketing "Popular templates" ([`RuleStack.container.tsx`](../app/components/sections/RuleStack/RuleStack.container.tsx)) | navigate only; apply asks before replacing a draft | `/create/review-template/[slug]` |
| `/templates` index ([`TemplatesPageClient.tsx`](../app/(marketing)/templates/TemplatesPageClient.tsx)) visited directly / via pasted URL | `fromFlow` absent → navigate only | `/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 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.
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 **Create from template** uses marketing `/templates` without that marker, so a saved draft is not treated as this community’s name. Templates on `/templates` and `/create/templates` show in curated order with no RECOMMENDED tag; facet scoring is unused.
**Resume from profile** remains explicit-only: **Continue** clears local mirrors then opens `/create/{step}` so [`SignedInDraftHydration`](../app/(app)/create/SignedInDraftHydration.tsx) can load `/api/drafts/me` when the client buffer is empty. There is no automatic “pick template from marketing → silently merge server draft” path.
**Resume from profile** remains explicit-only: **Continue** writes the loaded server draft into the browser, then opens `/create/{step}`. 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, 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).
@@ -120,7 +120,7 @@ Details and edge cases (conflict confirm, banners, `?syncDraft=1`) match **Ticke
## Known implementation gaps
- **Profile + drafts (CR-86):** The profile page lists the server draft. **Continue** clears anonymous `localStorage` (and core-value details) then deep-links to `/create/{currentStep}` so hydration loads the server draft. **Create new custom Rule** and marketing **Create rule** use **`prepareFreshCreateFlowEntry`** (local + `DELETE /api/drafts/me` when sync is on) before opening the wizard so signed-in behavior matches a fresh anonymous start. `SignedInDraftHydration` may `router.replace` to the saved step when it applies a server draft so the URL matches hydrated state. Remaining edge cases (e.g. template review routes) are handled when they surface in QA.
- **Profile + drafts (CR-86):** The profile page lists the server draft. **Continue** clears anonymous `localStorage` (and core-value details) then deep-links to `/create/{currentStep}` so hydration loads the server draft. **Create new custom Rule** and marketing **Create rule** resume the browser draft via **`createRuleEntryPath`** and do not delete the server draft. `SignedInDraftHydration` may `router.replace` to the saved step when it applies a server draft so the URL matches hydrated state. Remaining edge cases (e.g. template review routes) are handled when they surface in QA.
- **Inner “text/select shells”:** deferred until Create Community is stable; screens use **`CreateFlowStepShell`** only for Stage 1.
---
+8 -7
View File
@@ -164,19 +164,20 @@ async function errorBodyMessage(res: Response): Promise<string> {
}
/**
* Wipe the signed-in user's saved draft. Fire-and-forget: any non-2xx (including
* the sync-flag-off `503` and the unauthenticated `401`) is swallowed because
* callers only invoke this on already-published / explicitly-discarded flows
* where a leftover server draft is acceptable.
* Wipe the signed-in user's saved draft.
* Returns true when the server confirms the draft is gone.
* Callers that only need a best-effort wipe can ignore a false result
* (`503` when sync is off, `401` when signed out, or a network error).
*/
export async function deleteServerDraft(): Promise<void> {
export async function deleteServerDraft(): Promise<boolean> {
try {
await fetch("/api/drafts/me", {
const res = await fetch("/api/drafts/me", {
method: "DELETE",
credentials: "include",
});
return res.ok;
} catch {
/* ignore — server draft cleanup is best-effort */
return false;
}
}
+70
View File
@@ -12,6 +12,7 @@ import {
decisionApproachPresetFor,
membershipPresetFor,
} from "./finalReviewChipPresets";
import { methodSectionsPinsForHydratedSelections } from "./publishedDocumentToCreateFlowState";
import {
templateChipsForSlug,
type TemplateChipSet,
@@ -223,3 +224,72 @@ export function templatePresetDetailsFromPrefill(
coreValueDetailsByChipId,
};
}
export 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>[];
}
export type TemplateApplyIdentity = {
title?: string;
communityContext?: string;
communityLocation?: string;
};
/**
* Fresh wizard state for a template. Does not spread a previous draft, so a
* leftover logo, setup answers, or another community's cards cannot ride along.
*/
export function buildAppliedTemplateCreateFlowState(args: {
slug: string;
body: unknown;
mode: "customize" | "useWithoutChanges";
identity?: TemplateApplyIdentity;
}): CreateFlowState {
const prefill = buildTemplateCustomizePrefill(args.body, args.slug);
const details = templatePresetDetailsFromPrefill(prefill);
const pinPatch = methodSectionsPinsForHydratedSelections(prefill);
const title = args.identity?.title?.trim();
const communityContext = args.identity?.communityContext?.trim();
const communityLocation = args.identity?.communityLocation?.trim();
const seeded: CreateFlowState = {
...prefill,
...details,
methodSectionsPinCommitted: pinPatch,
templateReviewBackSlug: args.slug,
pendingTemplateAction: {
slug: args.slug,
mode: args.mode,
},
};
if (title) seeded.title = title;
if (communityContext) {
seeded.communityContext = communityContext;
seeded.summary = communityContext;
}
if (communityLocation) seeded.communityLocation = communityLocation;
if (args.identity) seeded.templateReviewEntryFromCreateFlow = true;
if (args.mode === "useWithoutChanges") {
const sections = sectionsFromTemplateBody(args.body);
if (sections) {
const hasValuesSeed = seeded.selectedCoreValueIds !== undefined;
seeded.sections = hasValuesSeed
? sections.filter((section) => {
const name = (section as { categoryName?: unknown }).categoryName;
if (typeof name !== "string") return true;
const key = name.toLowerCase().replace(/[^a-z]+/g, "");
return key !== "values" && key !== "corevalues";
})
: sections;
}
}
return seeded;
}
+134
View File
@@ -0,0 +1,134 @@
import type { CreateFlowState } from "../../app/(app)/create/types";
import { createFlowStateHasKeys } from "./draftHydrationUtils";
import {
CUSTOM_RULE_FACETS,
PUBLISHED_CUSTOM_RULE_SELECTION_KEYS,
} from "./customRuleFacets";
import type { StoredLastPublishedRule } from "./lastPublishedRule";
import {
createFlowStateFromPublishedRule,
methodSectionsPinsFromPublishedHydratePatch,
} from "./publishedDocumentToCreateFlowState";
function sortedIds(value: unknown): string {
if (!Array.isArray(value)) return "";
return value
.filter((id): id is string => typeof id === "string")
.map((id) => id.trim())
.filter((id) => id.length > 0)
.sort()
.join(",");
}
function trimmedText(value: unknown): string {
return typeof value === "string" ? value.trim() : "";
}
function canonical(value: unknown): unknown {
if (Array.isArray(value)) return value.map(canonical);
if (value && typeof value === "object") {
const record = value as Record<string, unknown>;
const out: Record<string, unknown> = {};
for (const key of Object.keys(record).sort()) {
const child = record[key];
if (child === undefined) continue;
out[key] = canonical(child);
}
return out;
}
return value;
}
/** Missing and empty objects are the same: the author has not written that copy. */
function sameCopy(a: unknown, b: unknown): boolean {
const normalize = (value: unknown): unknown => {
if (value == null) return null;
if (
typeof value === "object" &&
!Array.isArray(value) &&
Object.keys(value as object).length === 0
) {
return null;
}
return value;
};
return (
JSON.stringify(canonical(normalize(a))) ===
JSON.stringify(canonical(normalize(b)))
);
}
export function createFlowStateMatchesPublishedRule(
state: CreateFlowState,
last: StoredLastPublishedRule,
): boolean {
const patch = createFlowStateFromPublishedRule(last);
const title = typeof state.title === "string" ? state.title.trim() : "";
const patchTitle = typeof patch.title === "string" ? patch.title.trim() : "";
if (title !== patchTitle) return false;
if (
trimmedText(state.communityContext) !== trimmedText(patch.communityContext)
) {
return false;
}
if (trimmedText(state.summary) !== trimmedText(patch.summary)) {
return false;
}
for (const key of PUBLISHED_CUSTOM_RULE_SELECTION_KEYS) {
if (sortedIds(state[key]) !== sortedIds(patch[key])) return false;
}
for (const row of CUSTOM_RULE_FACETS) {
if (
!sameCopy(
state[row.detailOverridesStateKey],
patch[row.detailOverridesStateKey],
)
) {
return false;
}
}
if (
!sameCopy(
state.customMethodCardFieldBlocksById,
patch.customMethodCardFieldBlocksById,
)
) {
return false;
}
if (
!sameCopy(state.customMethodCardMetaById, patch.customMethodCardMetaById)
) {
return false;
}
return true;
}
/**
* True when Edit would drop a different in-progress draft to load this
* finished Rule. Empty state and a draft that already is this Rule do not
* need a confirm.
*/
export function publishedRuleEditWouldReplaceDraft(
state: CreateFlowState,
last: StoredLastPublishedRule,
): boolean {
if (!createFlowStateHasKeys(state)) return false;
const editingId =
typeof state.editingPublishedRuleId === "string"
? state.editingPublishedRuleId.trim()
: "";
if (editingId.length > 0 && editingId !== last.id) return true;
return !createFlowStateMatchesPublishedRule(state, last);
}
/** Full wizard state for editing a finished Rule — not a merge onto another draft. */
export function createFlowStateForEditingPublishedRule(
last: StoredLastPublishedRule,
): CreateFlowState {
const patch = createFlowStateFromPublishedRule(last);
return {
...patch,
methodSectionsPinCommitted:
methodSectionsPinsFromPublishedHydratePatch(patch),
};
}
+13 -21
View File
@@ -8,11 +8,10 @@ import type {
import type { CommunityRuleSection } from "../../app/components/type/CommunityRule/CommunityRule.types";
import { resolveMethodPresetIdFromLabel } from "./buildFinalReviewCategories";
import {
communicationPresetFor,
conflictManagementPresetFor,
decisionApproachPresetFor,
membershipPresetFor,
mergeCoreValueDetailWithPresets,
emptyCommunicationDetails,
emptyConflictManagementDetails,
emptyDecisionApproachDetails,
emptyMembershipDetails,
publishedMethodDisplayLabel,
} from "./finalReviewChipPresets";
import { isDocumentEntry } from "./documentEntryGuards";
@@ -61,12 +60,12 @@ export function buildCoreValuesForDocument(state: CreateFlowState): Array<{
return snap
.filter((r) => selected.has(r.id))
.map((r) => {
const merged = mergeCoreValueDetailWithPresets(r.id, r.label, details[r.id]);
const saved = details[r.id];
return {
chipId: r.id,
label: r.label,
meaning: merged.meaning,
signals: merged.signals,
meaning: typeof saved?.meaning === "string" ? saved.meaning : "",
signals: typeof saved?.signals === "string" ? saved.signals : "",
};
});
}
@@ -278,10 +277,8 @@ function publishedRowSupportText(
/**
* Merge `selected*MethodIds` with any saved `{group}MethodDetailsById`
* overrides authored on the final-review screen. Preset defaults from the
* shipped `messages/en/create/customRule/*.json` seed any sub-fields the
* user didn't edit so consumers of `document.methodSelections` always see
* a complete payload per method.
* overrides authored on the final-review screen. Blank parts stay blank —
* library presets are not filled in for text the pen holder never wrote.
*/
export function buildMethodSelectionsForDocument(
state: CreateFlowState,
@@ -297,7 +294,6 @@ export function buildMethodSelectionsForDocument(
);
if (commIds.length > 0) {
out.communication = commIds.map((id) => {
const preset = communicationPresetFor(id);
const override = state.communicationMethodDetailsById?.[id];
const supportText = publishedRowSupportText(
id,
@@ -310,7 +306,7 @@ export function buildMethodSelectionsForDocument(
id,
state.customMethodCardMetaById,
),
sections: override ? { ...preset, ...override } : preset,
sections: override ?? emptyCommunicationDetails(),
...(supportText ? { supportText } : {}),
};
});
@@ -322,7 +318,6 @@ export function buildMethodSelectionsForDocument(
);
if (memIds.length > 0) {
out.membership = memIds.map((id) => {
const preset = membershipPresetFor(id);
const override = state.membershipMethodDetailsById?.[id];
const supportText = publishedRowSupportText(
id,
@@ -335,7 +330,7 @@ export function buildMethodSelectionsForDocument(
id,
state.customMethodCardMetaById,
),
sections: override ? { ...preset, ...override } : preset,
sections: override ?? emptyMembershipDetails(),
...(supportText ? { supportText } : {}),
};
});
@@ -347,13 +342,11 @@ export function buildMethodSelectionsForDocument(
);
if (daIds.length > 0) {
out.decisionApproaches = daIds.map((id) => {
const preset = decisionApproachPresetFor(id);
const override = state.decisionApproachDetailsById?.[id];
const supportText = publishedRowSupportText(
id,
state.customMethodCardMetaById,
);
const merged = override ? { ...preset, ...override } : preset;
return {
id,
label: publishedMethodDisplayLabel(
@@ -362,7 +355,7 @@ export function buildMethodSelectionsForDocument(
state.customMethodCardMetaById,
),
sections: withoutUnpublishedDecisionConsensus(
{ ...merged },
{ ...(override ?? emptyDecisionApproachDetails()) },
state.customMethodCardFieldBlocksById?.[id],
) as DecisionApproachDetailEntry,
...(supportText ? { supportText } : {}),
@@ -376,7 +369,6 @@ export function buildMethodSelectionsForDocument(
);
if (cmIds.length > 0) {
out.conflictManagement = cmIds.map((id) => {
const preset = conflictManagementPresetFor(id);
const override = state.conflictManagementDetailsById?.[id];
const supportText = publishedRowSupportText(
id,
@@ -389,7 +381,7 @@ export function buildMethodSelectionsForDocument(
id,
state.customMethodCardMetaById,
),
sections: override ? { ...preset, ...override } : preset,
sections: override ?? emptyConflictManagementDetails(),
...(supportText ? { supportText } : {}),
};
});
+14 -5
View File
@@ -15,9 +15,8 @@ import type {
/**
* Catalog copy for method/value sections. Generate draft inserts these into
* empty creation-modal fields. Publish still merges them onto saved overrides
* so every method carries a complete section payload when the author only
* edited a subset of fields.
* empty creation-modal fields. Publish keeps blank parts blank — it does not
* fill library text the pen holder never wrote.
*/
type CustomRuleMethodRow = {
id: string;
@@ -145,6 +144,16 @@ export function emptyDecisionApproachTextFields(
};
}
export function emptyDecisionApproachDetails(): DecisionApproachDetailEntry {
return {
corePrinciple: "",
applicableScope: [],
selectedApplicableScope: [],
stepByStepInstructions: "",
objectionsDeadlocks: "",
};
}
export function conflictManagementPresetFor(
id: string,
): ConflictManagementDetailEntry {
@@ -233,8 +242,8 @@ export function coreValuePresetForLabel(label: string): CoreValueDetailEntry {
}
/**
* Published / display copy: saved draft wins when non-empty; otherwise preset
* by chip id (numeric presets), then by label match in `coreValues.json`.
* Generate draft and legacy placeholder replacement: saved copy wins when
* non-empty; otherwise preset by chip id, then by label match.
*/
export function mergeCoreValueDetailWithPresets(
chipId: string,
+124 -12
View File
@@ -5,12 +5,34 @@ import type {
DecisionApproachDetailEntry,
MembershipMethodDetailEntry,
} from "../../app/(app)/create/types";
import {
buildFinalReviewCategoryRowsDetailed,
type FinalReviewCategoryNames,
} from "./buildFinalReviewCategories";
import type { CustomMethodCardFieldBlock } from "./customMethodCardFieldBlocks";
import { facetBlockHasContent } from "./methodCardWizardPrefill";
import type { TemplateFacetGroupKey } from "./templateReviewMapping";
import { usesWizardFieldBlocksModalBody } from "./usesWizardFieldBlocksModalBody";
const LABEL_NAMES: FinalReviewCategoryNames = {
values: "values",
communication: "communication",
membership: "membership",
decisions: "decisions",
conflict: "conflict",
};
function missingText(...values: readonly (string | undefined)[]): boolean {
return values.some((value) => (value ?? "").trim().length === 0);
}
function customFieldBlocksHaveWords(
blocks: readonly CustomMethodCardFieldBlock[] | undefined,
): boolean {
if (!blocks || blocks.length === 0) return false;
return blocks.every(facetBlockHasContent);
}
function communicationMissingWords(
saved: CommunicationMethodDetailEntry | undefined,
): boolean {
@@ -55,21 +77,30 @@ function conflictMissingWords(
);
}
/**
* A review chip shows a warning when its value is missing meaning or signals,
* or a card is missing its words.
*/
export function finalReviewChipHasWarning(
function methodUsesCustomFieldBlocks(
state: CreateFlowState,
groupKey: TemplateFacetGroupKey | null,
overrideKey: string | null,
overrideKey: string,
): boolean {
if (!groupKey || !overrideKey) return true;
return usesWizardFieldBlocksModalBody({
methodId: overrideKey,
meta: state.customMethodCardMetaById,
fieldBlocksById: state.customMethodCardFieldBlocksById,
modalEditUnlocked: true,
draftFieldBlocks: null,
});
}
function methodCardMissingWords(
state: CreateFlowState,
groupKey: Exclude<TemplateFacetGroupKey, "coreValues">,
overrideKey: string,
): boolean {
if (methodUsesCustomFieldBlocks(state, overrideKey)) {
return !customFieldBlocksHaveWords(
state.customMethodCardFieldBlocksById?.[overrideKey],
);
}
switch (groupKey) {
case "coreValues": {
const saved = state.coreValueDetailsByChipId?.[overrideKey];
return missingText(saved?.meaning, saved?.signals);
}
case "communication":
return communicationMissingWords(
state.communicationMethodDetailsById?.[overrideKey],
@@ -88,3 +119,84 @@ export function finalReviewChipHasWarning(
);
}
}
function valueHasMeaning(
state: CreateFlowState,
overrideKey: string,
): boolean {
const saved = state.coreValueDetailsByChipId?.[overrideKey];
if ((saved?.meaning ?? "").trim().length > 0) return true;
const blocks = state.customMethodCardFieldBlocksById?.[overrideKey];
if (!blocks || blocks.length === 0) return false;
return blocks.some(
(block) =>
block.kind === "text" &&
block.id !== "facet-signals" &&
facetBlockHasContent(block),
);
}
function valueHasSignals(
state: CreateFlowState,
overrideKey: string,
): boolean {
const saved = state.coreValueDetailsByChipId?.[overrideKey];
if ((saved?.signals ?? "").trim().length > 0) return true;
const blocks = state.customMethodCardFieldBlocksById?.[overrideKey];
if (!blocks || blocks.length === 0) return false;
const signalsBlock = blocks.find(
(block) => block.kind === "text" && block.id === "facet-signals",
);
if (!signalsBlock) return true;
return facetBlockHasContent(signalsBlock);
}
/**
* A review chip shows a warning when its value is missing meaning or signals,
* or a card is missing its words. Custom field text counts as those words.
*/
export function finalReviewChipHasWarning(
state: CreateFlowState,
groupKey: TemplateFacetGroupKey | null,
overrideKey: string | null,
): boolean {
if (!groupKey || !overrideKey) return true;
if (groupKey === "coreValues") {
return !valueHasMeaning(state, overrideKey) || !valueHasSignals(state, overrideKey);
}
return methodCardMissingWords(state, groupKey, overrideKey);
}
/**
* Continue waits for every picked card's words and every picked value's
* meaning. Missing signals stay a warning only.
*/
export function finalReviewChipBlocksContinue(
state: CreateFlowState,
groupKey: TemplateFacetGroupKey | null,
overrideKey: string | null,
): boolean {
if (!groupKey || !overrideKey) return false;
if (groupKey === "coreValues") {
return !valueHasMeaning(state, overrideKey);
}
return methodCardMissingWords(state, groupKey, overrideKey);
}
/** Chip labels that still need words before Continue. */
export function finalReviewMissingWordsLabels(
state: CreateFlowState,
): string[] {
const rows = buildFinalReviewCategoryRowsDetailed(state, LABEL_NAMES);
const labels: string[] = [];
for (const row of rows) {
for (const entry of row.entries) {
if (
finalReviewChipBlocksContinue(state, entry.groupKey, entry.overrideKey)
) {
labels.push(entry.label);
}
}
}
return labels;
}
+7 -2
View File
@@ -2,8 +2,8 @@ import type { CopiedNameHit } from "./copiedRuleDocument";
/**
* Bridges final-review → completed without query strings, and re-opens a rule
* from profile (`/create/completed?ruleId=…`) after GET /api/rules/[id]. Profile
* "Manage" links here; stakeholder "View" uses `/invite/[id]`.
* from profile (`/create/completed?ruleId=…`) after GET /api/rules/[id].
* Stakeholder cards on Profile open the reader page at `/rules/[id]`.
*/
export const CREATE_FLOW_LAST_PUBLISHED_KEY = "createFlow.lastPublished";
@@ -35,6 +35,11 @@ export function writeLastPublishedRule(data: StoredLastPublishedRule): void {
sessionStorage.setItem(CREATE_FLOW_LAST_PUBLISHED_KEY, JSON.stringify(data));
}
export function clearLastPublishedRule(): void {
if (typeof sessionStorage === "undefined") return;
sessionStorage.removeItem(CREATE_FLOW_LAST_PUBLISHED_KEY);
}
export function readLastPublishedRule(): StoredLastPublishedRule | null {
if (typeof sessionStorage === "undefined") return null;
const raw = sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY);
+1 -1
View File
@@ -233,7 +233,7 @@ export function facetDetailsToWizardFieldBlocks(
return mapFacetPrefillToWizardFieldBlocks(prefill);
}
function facetBlockHasContent(block: CustomMethodCardFieldBlock): boolean {
export function facetBlockHasContent(block: CustomMethodCardFieldBlock): boolean {
switch (block.kind) {
case "text":
return hasTrimmedText(block.placeholderText);
@@ -4,13 +4,6 @@ import type { PublishedMethodSelections } from "./buildPublishPayload";
import { parseDocumentSectionsForDisplay } from "./buildPublishPayload";
import { resolveMethodPresetIdFromLabel } from "./buildFinalReviewCategories";
import { resolveCoreValueChipIdFromLabel } from "./finalReviewChipPresets";
import {
communicationPresetFor,
conflictManagementPresetFor,
decisionApproachPresetFor,
membershipPresetFor,
mergeCoreValueDetailWithPresets,
} from "./finalReviewChipPresets";
import { templateCategoryToGroupKey } from "./templateReviewMapping";
import type { TemplateFacetGroupKey } from "./templateReviewMapping";
import { RULE_SECTION_CATEGORY } from "./ruleSectionsFromMethodSelections";
@@ -110,26 +103,9 @@ function sectionsRecordFromBlocks(
return out;
}
function presetForMethod(
groupKey: Exclude<TemplateFacetGroupKey, "coreValues">,
id: string,
): Record<string, unknown> {
switch (groupKey) {
case "communication":
return { ...communicationPresetFor(id) } as Record<string, unknown>;
case "membership":
return { ...membershipPresetFor(id) } as Record<string, unknown>;
case "decisionApproaches":
return { ...decisionApproachPresetFor(id) } as Record<string, unknown>;
case "conflictManagement":
return { ...conflictManagementPresetFor(id) } as Record<string, unknown>;
}
}
function sectionsRecordFromEntry(
entry: CommunityRuleSection["entries"][number],
groupKey: Exclude<TemplateFacetGroupKey, "coreValues">,
presetId: string,
): Record<string, unknown> {
const labelByKey = LABELS_BY_GROUP[groupKey];
const consensusKey =
@@ -140,16 +116,16 @@ function sectionsRecordFromEntry(
consensusLevelKey: consensusKey,
});
if (Object.keys(fromBlocks).length > 0) {
return { ...presetForMethod(groupKey, presetId), ...fromBlocks };
return fromBlocks;
}
}
const body = (entry.body ?? "").trim();
if (body.length === 0) {
return presetForMethod(groupKey, presetId);
return {};
}
return { ...presetForMethod(groupKey, presetId), corePrinciple: body };
return { corePrinciple: body };
}
function coreValuesFromValuesSection(
@@ -169,18 +145,14 @@ function coreValuesFromValuesSection(
const parts = body.length > 0 ? body.split(/\n\n+/) : [];
const meaning = (parts[0] ?? "").trim();
const signals = parts.slice(1).join("\n\n").trim();
const merged = mergeCoreValueDetailWithPresets("", label, {
meaning,
signals,
});
const chipId =
resolveCoreValueChipIdFromLabel(label) ??
`hydrated-${label.toLowerCase()}`;
out.push({
chipId,
label,
meaning: merged.meaning,
signals: merged.signals,
meaning,
signals,
});
}
@@ -213,7 +185,7 @@ function methodSelectionsFromDisplaySections(
rows.push({
id,
label,
sections: sectionsRecordFromEntry(entry, groupKey, id),
sections: sectionsRecordFromEntry(entry, groupKey),
});
}
if (rows.length > 0) {
@@ -80,7 +80,6 @@ const CM_LABELS: Record<string, string> = {
function needsPlaceholderPresetEnrichment(entry: CommunityRuleEntry): boolean {
if (entry.blocks && entry.blocks.length > 0) return false;
const b = (entry.body ?? "").trim();
if (b.length === 0) return true;
return b === TEMPLATE_COMPOSITION_SUGGESTED_BODY;
}
@@ -196,15 +195,12 @@ function sectionFromStoredCoreValues(
for (const row of raw) {
if (!row || typeof row !== "object") continue;
const o = row as Record<string, unknown>;
const chipId = typeof o.chipId === "string" ? o.chipId : "";
const label = nonEmptyTrimmed(o.label);
if (!label) continue;
const merged = mergeCoreValueDetailWithPresets(chipId, label, {
meaning: typeof o.meaning === "string" ? o.meaning : "",
signals: typeof o.signals === "string" ? o.signals : "",
});
const meaning = (merged.meaning ?? "").trim();
const signals = (merged.signals ?? "").trim();
const meaning =
typeof o.meaning === "string" ? o.meaning.trim() : "";
const signals =
typeof o.signals === "string" ? o.signals.trim() : "";
const bodyParts: string[] = [];
if (meaning.length > 0) bodyParts.push(meaning);
if (signals.length > 0) bodyParts.push(signals);
@@ -221,8 +221,7 @@ export function communityRuleEntryFromMethodChip(
const blocks = [...presetBlocks, ...wizardBlocks];
const description = nonEmptyTrimmed(options?.supportText);
if (blocks.length === 0) {
if (!description) return null;
return { title, body: description };
return { title, body: description ?? "" };
}
return {
title,
@@ -387,8 +386,8 @@ export function sectionFromConflict(
}
/**
* Swap template `sections` method rows for fully-resolved entries built from
* `methodSelections` (preset + overrides).
* Swap template `sections` method rows for entries built from
* `methodSelections`.
*/
export function replaceMethodSectionsWithMethodSelections(
sections: CommunityRuleSection[],
+134 -1
View File
@@ -1,9 +1,14 @@
import type { Category } from "../../app/components/cards/Rule";
import type { ChipOption } from "../../app/components/controls/MultiSelect/MultiSelect.types";
import type { CommunityRuleSection } from "../../app/components/type/CommunityRule/CommunityRule.types";
import coreValuesMessages from "../../messages/en/create/customRule/coreValues.json";
import type { TemplateFacetGroupKey } from "./customRuleFacets";
import { templateCategoryToFacetGroupKey } from "./customRuleFacets";
import {
readMethodPresetsForFacetGroup,
templateCategoryToFacetGroupKey,
} from "./customRuleFacets";
import { isDocumentEntry } from "./documentEntryGuards";
import { templateChipsForSlug, type TemplateChipSet } from "./templatePath";
export type { TemplateFacetGroupKey } from "./customRuleFacets";
@@ -91,6 +96,134 @@ export function templateBodyToCategories(body: unknown): Category[] {
return templateBodyToReviewData(body).categories;
}
type ReviewData = ReturnType<typeof templateBodyToReviewData>;
const CHIP_REVIEW_GROUPS: readonly {
groupKey: TemplateFacetGroupKey;
categoryName: string;
idsOf: (_chips: TemplateChipSet) => readonly string[];
}[] = [
{
groupKey: "coreValues",
categoryName: "Values",
idsOf: (chips) => chips.coreValues,
},
{
groupKey: "communication",
categoryName: "Communication",
idsOf: (chips) => chips.communication,
},
{
groupKey: "membership",
categoryName: "Membership",
idsOf: (chips) => chips.membership,
},
{
groupKey: "decisionApproaches",
categoryName: "Decision-making",
idsOf: (chips) => chips.decisionApproaches,
},
{
groupKey: "conflictManagement",
categoryName: "Conflict management",
idsOf: (chips) => chips.conflictManagement,
},
];
function coreValueLabelById(id: string): string | null {
const values = (coreValuesMessages as { values?: unknown }).values;
if (!Array.isArray(values)) return null;
for (const raw of values) {
if (!raw || typeof raw !== "object") continue;
const row = raw as { id?: unknown; label?: unknown };
if (row.id === id && typeof row.label === "string" && row.label.trim()) {
return row.label;
}
}
return null;
}
/** Same order as `coreValuesChipsSnapshot` / final review: catalog list, then leftovers. */
function orderedCoreValueIds(ids: readonly string[]): string[] {
const wanted = new Set(ids);
const out: string[] = [];
const values = (coreValuesMessages as { values?: unknown }).values;
if (Array.isArray(values)) {
for (const raw of values) {
if (!raw || typeof raw !== "object") continue;
const id = (raw as { id?: unknown }).id;
if (typeof id === "string" && wanted.delete(id)) out.push(id);
}
}
for (const id of ids) {
if (wanted.has(id)) out.push(id);
}
return out;
}
function methodLabelById(
groupKey: Exclude<TemplateFacetGroupKey, "coreValues">,
id: string,
): string | null {
const row = readMethodPresetsForFacetGroup(groupKey).find(
(method) => method.id === id,
);
return row?.label ?? null;
}
function templateChipsToReviewData(slug: string): ReviewData | null {
const chips = templateChipsForSlug(slug);
if (!chips) return null;
const categories: Category[] = [];
const chipDetailsByChipId: ReviewData["chipDetailsByChipId"] = {};
for (const group of CHIP_REVIEW_GROUPS) {
const chipOptions: ChipOption[] = [];
const ids =
group.groupKey === "coreValues"
? orderedCoreValueIds(group.idsOf(chips))
: group.idsOf(chips);
for (const id of ids) {
const chipLabel =
group.groupKey === "coreValues"
? coreValueLabelById(id)
: methodLabelById(group.groupKey, id);
if (!chipLabel) continue;
chipDetailsByChipId[id] = {
chipId: id,
chipLabel,
categoryName: group.categoryName,
groupKey: group.groupKey,
body: "",
};
chipOptions.push({
id,
label: chipLabel,
state: "unselected",
});
}
if (chipOptions.length === 0) continue;
categories.push({
name: group.categoryName,
chipOptions,
});
}
return { categories, chipDetailsByChipId };
}
/**
* Detail-page chips. Prefer the remade catalog ids in templateChips.json so
* the list matches final review; fall back to API body titles for unknown slugs.
*/
export function templateReviewDataForSlug(
slug: string,
body: unknown,
): ReviewData {
return templateChipsToReviewData(slug) ?? templateBodyToReviewData(body);
}
/**
* Summary line under tag rows: prefer API description; else first entry bodies (short).
*/
+1 -1
View File
@@ -61,7 +61,7 @@ export async function issueGuestRuleClaimCookie(token: string): Promise<void> {
);
}
async function clearGuestRuleClaimCookie(): Promise<void> {
export async function clearGuestRuleClaimCookie(): Promise<void> {
const store = await cookies();
store.set(GUEST_RULE_CLAIM_COOKIE_NAME, "", {
...cookieOptions(),
+14
View File
@@ -0,0 +1,14 @@
import { prisma } from "./db";
import { deleteUploadsForDraft } from "./uploads/deleteUploadedFiles";
/** Remove the signed-in user's in-progress draft and any files still tied to it. */
export async function deleteRuleDraftForUser(userId: string): Promise<void> {
const draft = await prisma.ruleDraft.findUnique({
where: { userId },
select: { id: true },
});
if (draft) {
await deleteUploadsForDraft(draft.id);
}
await prisma.ruleDraft.deleteMany({ where: { userId } });
}
@@ -30,6 +30,10 @@
"title": "Binding arbitration needs each member’s own yes",
"description": "Open admission and membership by token do not record that yes. Each member still has to agree separately before binding arbitration applies to them."
},
"missingWordsWarning": {
"title": "Add words before you finish",
"description": "These still need words: {labels}."
},
"categories": [
{
"name": "Values",
+7 -1
View File
@@ -1,7 +1,7 @@
{
"intro": {
"title": "CommunityRule Template",
"description": "These templates can get you started with a proven approach to governance and decision-making. As useful as these templates are, they are not one size fit all solutions though. We recommend that you use them as a starting place for your community to adapt and customize according to your group's specific needs."
"description": "These templates can get you started with a proven approach to governance and decision-making. As useful as these templates are, they are not one size fits all solutions though. We recommend that you use them as a starting place for your community to adapt and customize according to your group's specific needs."
},
"footer": {
"useWithoutChanges": "Use without changes",
@@ -12,6 +12,12 @@
"notFound": "This template was not found.",
"applyFailed": "Something went wrong. Please try again."
},
"replaceDraft": {
"title": "Replace the draft in progress?",
"description": "Starting this template replaces the draft you have been working on.",
"proceed": "Use this template",
"cancel": "Keep my draft"
},
"loading": "Loading template…",
"chipDetailModal": {
"closeButton": "Close",
+4
View File
@@ -19,6 +19,10 @@
"leaveConfirmProceed": "Leave anyway",
"leaveConfirmSaveProgress": "Save my progress",
"leaveConfirmCancel": "Stay",
"editReplaceDraftTitle": "Replace the draft in progress?",
"editReplaceDraftDescription": "Edit opens this finished Rule. The draft you have been working on will be replaced in this browser.",
"editReplaceDraftProceed": "Edit this Rule",
"editReplaceDraftCancel": "Keep my draft",
"draftSaveBannerTitle": "Couldn't save draft",
"postLoginSaveFailedWithReason": "Could not save your draft to your account. Your progress is still stored on this device.\n\n{reason}",
"offlineTitle": "You're offline",
+63 -1
View File
@@ -1,6 +1,10 @@
import { useSearchParams } from "next/navigation";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders as render, screen } from "../utils/test-utils";
import {
renderWithProviders as render,
screen,
waitFor,
} from "../utils/test-utils";
import "@testing-library/jest-dom/vitest";
import { CompletedScreen } from "../../app/(app)/create/screens/completed/CompletedScreen";
import { CREATE_FLOW_LAST_PUBLISHED_KEY } from "../../lib/create/lastPublishedRule";
@@ -8,6 +12,14 @@ import {
CREATE_FLOW_COMPLETED_CELEBRATE_QUERY,
CREATE_FLOW_COMPLETED_CELEBRATE_VALUE,
} from "../../app/(app)/create/utils/flowSteps";
import { testRouter } from "../mocks/navigation";
const fetchPublishedRuleDetail = vi.hoisted(() => vi.fn());
vi.mock("../../lib/create/api", () => ({
fetchPublishedRuleDetail: (...args: unknown[]) =>
fetchPublishedRuleDetail(...args),
}));
const storedRuleFixture = {
id: "rule-fixture-1",
@@ -48,6 +60,8 @@ function mockSearchParams(record?: Record<string, string>) {
describe("CompletedScreen", () => {
beforeEach(() => {
sessionStorage.removeItem(CREATE_FLOW_LAST_PUBLISHED_KEY);
fetchPublishedRuleDetail.mockReset();
testRouter.replace.mockReset();
mockSearchParams();
});
@@ -165,4 +179,52 @@ describe("CompletedScreen", () => {
),
).toBe(true);
});
it("loads an owned Rule from ?ruleId= and stores it", async () => {
fetchPublishedRuleDetail.mockResolvedValue({
viewerIsOwner: true,
rule: {
id: "rule-owned",
title: "QA Tenants Union",
summary: "How we share the building.",
document: storedRuleFixture.document,
createdAt: "2026-11-01T00:00:00.000Z",
},
});
mockSearchParams({ ruleId: "rule-owned" });
render(<CompletedScreen />);
expect(
await screen.findByRole("heading", { name: "QA Tenants Union" }),
).toBeInTheDocument();
await waitFor(() => {
expect(testRouter.replace).toHaveBeenCalledWith("/create/completed");
});
const stored = JSON.parse(
sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY) ?? "null",
);
expect(stored).toMatchObject({
id: "rule-owned",
title: "QA Tenants Union",
});
});
it("sends a non-owner ?ruleId= load to the reader page", async () => {
fetchPublishedRuleDetail.mockResolvedValue({
viewerIsOwner: false,
rule: {
id: "rule-other",
title: "Someone else's Rule",
summary: null,
document: storedRuleFixture.document,
},
});
mockSearchParams({ ruleId: "rule-other" });
render(<CompletedScreen />);
await waitFor(() => {
expect(testRouter.replace).toHaveBeenCalledWith("/rules/rule-other");
});
expect(sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY)).toBeNull();
});
});
@@ -241,6 +241,14 @@ describe("FinalReviewScreen — prefilled selections", () => {
expect(
screen.getByRole("button", { name: "Signal, missing words" }),
).toBeInTheDocument();
expect(
screen.getByText("Add words before you finish"),
).toBeInTheDocument();
expect(
screen.getByText(
/These still need words: Accessibility, Signal, Open admission/,
),
).toBeInTheDocument();
});
it("warns when binding arbitration sits next to a join that records no yes", async () => {
+34 -1
View File
@@ -45,7 +45,11 @@ vi.mock("../../app/(app)/create/utils/anonymousDraftStorage", async (importOrigi
import { EMAIL_MAX_LEN } from "../../lib/create/isValidCreateFlowSaveEmail";
import { requestMagicLink } from "../../lib/create/api";
import { setTransferPendingFlag } from "../../app/(app)/create/utils/anonymousDraftStorage";
import {
CREATE_FLOW_ANONYMOUS_KEY,
CREATE_FLOW_TRANSFER_PENDING_KEY,
setTransferPendingFlag,
} from "../../app/(app)/create/utils/anonymousDraftStorage";
function renderLoginForm() {
return renderWithProviders(
@@ -62,6 +66,7 @@ describe("LoginForm", () => {
navMock.replace.mockReset();
navMock.pathname = "/";
navMock.searchParams = new URLSearchParams();
window.localStorage.clear();
});
it("renders title, email field, and submit control", () => {
@@ -368,6 +373,34 @@ describe("LoginForm", () => {
).toBeInTheDocument();
});
it("clears the transfer flag on an expired link and keeps the browser draft", () => {
window.localStorage.setItem(
CREATE_FLOW_ANONYMOUS_KEY,
JSON.stringify({ title: "Garden coop" }),
);
window.localStorage.setItem(CREATE_FLOW_TRANSFER_PENDING_KEY, "1");
navMock.searchParams = new URLSearchParams("error=expired_link");
renderLoginForm();
expect(window.localStorage.getItem(CREATE_FLOW_TRANSFER_PENDING_KEY)).toBeNull();
expect(window.localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY)).toContain(
"Garden coop",
);
});
it("clears the transfer flag on an already-used link and keeps the browser draft", () => {
window.localStorage.setItem(
CREATE_FLOW_ANONYMOUS_KEY,
JSON.stringify({ title: "Garden coop" }),
);
window.localStorage.setItem(CREATE_FLOW_TRANSFER_PENDING_KEY, "1");
navMock.searchParams = new URLSearchParams("error=invalid_link");
renderLoginForm();
expect(window.localStorage.getItem(CREATE_FLOW_TRANSFER_PENDING_KEY)).toBeNull();
expect(window.localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY)).toContain(
"Garden coop",
);
});
it("shows URL-driven error for invalid_link", () => {
navMock.searchParams = new URLSearchParams("error=invalid_link");
renderLoginForm();
+10 -11
View File
@@ -67,16 +67,13 @@ describe('Top "Create rule" button', () => {
window.localStorage.clear();
});
/**
* Guards against localStorage stickiness on the marketing homepage: hitting
* the top-nav "Create rule" from anywhere outside `/create` must wipe the
* in-flight anonymous draft so the wizard always starts fresh. See
* handleCreateRuleClick in Top.container.tsx for the contract.
*/
it("clears anonymous draft + core-value-details localStorage before routing to /create/informational", async () => {
it("keeps the browser draft and resumes the step it was left on", async () => {
window.localStorage.setItem(
CREATE_FLOW_ANONYMOUS_KEY,
JSON.stringify({ title: "Stale community" }),
JSON.stringify({
title: "Stale community",
currentStep: "community-name",
}),
);
window.localStorage.setItem(
CORE_VALUE_DETAILS_STORAGE_KEY,
@@ -91,12 +88,14 @@ describe('Top "Create rule" button', () => {
await userEvent.click(btn);
await waitFor(() => {
expect(pushMock).toHaveBeenCalledWith("/create/informational");
expect(pushMock).toHaveBeenCalledWith("/create/community-name");
});
expect(window.localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY)).toBeNull();
expect(window.localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY)).toContain(
"Stale community",
);
expect(
window.localStorage.getItem(CORE_VALUE_DETAILS_STORAGE_KEY),
).toBeNull();
).not.toBeNull();
});
it("pads the standard header to hug Create rule", () => {
+68 -2
View File
@@ -1,10 +1,14 @@
import { describe, it, expect } from "vitest";
import { act, render, screen } from "@testing-library/react";
import { afterEach, describe, it, expect } from "vitest";
import { act, render, screen, waitFor } from "@testing-library/react";
import "@testing-library/jest-dom/vitest";
import {
CreateFlowProvider,
useCreateFlow,
} from "../../app/(app)/create/context/CreateFlowContext";
import {
CREATE_FLOW_ANONYMOUS_KEY,
CREATE_FLOW_TRANSFER_PENDING_KEY,
} from "../../app/(app)/create/utils/anonymousDraftStorage";
/**
* Harness: mounts a consumer that renders the state we want to assert on and
@@ -46,6 +50,15 @@ function Harness() {
<div data-testid="pin-method">
{state.methodSectionsPinCommitted?.communication ? "yes" : "no"}
</div>
<div data-testid="size">
{(state.selectedCommunitySizeIds ?? []).join(",")}
</div>
<div data-testid="kind">
{(state.selectedOrganizationTypeIds ?? []).join(",")}
</div>
<div data-testid="maturity">
{(state.selectedMaturityIds ?? []).join(",")}
</div>
</>
);
}
@@ -129,3 +142,56 @@ describe("CreateFlowContext — resetCustomRuleSelections", () => {
expect(screen.getByTestId("core").textContent).toBe("");
});
});
describe("CreateFlowContext — draft hydration after Save your progress", () => {
afterEach(() => {
window.localStorage.clear();
});
it("loads the stored draft when mirroring turns on, even with the transfer flag", async () => {
window.localStorage.setItem(
CREATE_FLOW_ANONYMOUS_KEY,
JSON.stringify({
title: "Juniper Street Tenants",
selectedCommunitySizeIds: ["thirteenToOneHundred"],
selectedOrganizationTypeIds: ["housing"],
selectedMaturityIds: ["forming"],
}),
);
window.localStorage.setItem(CREATE_FLOW_TRANSFER_PENDING_KEY, "1");
const { rerender } = render(
<CreateFlowProvider enableLocalDraftMirroring={false}>
<Harness />
</CreateFlowProvider>,
);
rerender(
<CreateFlowProvider enableLocalDraftMirroring>
<Harness />
</CreateFlowProvider>,
);
await waitFor(() => {
expect(screen.getByTestId("title").textContent).toBe(
"Juniper Street Tenants",
);
});
expect(screen.getByTestId("size").textContent).toBe("thirteenToOneHundred");
expect(screen.getByTestId("kind").textContent).toBe("housing");
expect(screen.getByTestId("maturity").textContent).toBe("forming");
act(() => {
getUpdateState()({ title: "Juniper Street Tenants Union" });
});
await waitFor(() => {
const stored = JSON.parse(
window.localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY) ?? "{}",
) as Record<string, unknown>;
expect(stored.title).toBe("Juniper Street Tenants Union");
expect(stored.selectedCommunitySizeIds).toEqual(["thirteenToOneHundred"]);
expect(stored.selectedOrganizationTypeIds).toEqual(["housing"]);
expect(stored.selectedMaturityIds).toEqual(["forming"]);
});
});
});
+17 -3
View File
@@ -121,7 +121,7 @@ describe("ProfilePageView", () => {
expect(screen.getByText(copy.emptyCardBody)).toBeInTheDocument();
expect(
screen.getByRole("link", { name: copy.emptyCardBrowse }),
).toHaveAttribute("href", "/templates?fromFlow=1");
).toHaveAttribute("href", "/templates");
await user.click(
screen.getByRole("button", { name: copy.emptyCardCreate }),
@@ -224,6 +224,11 @@ describe("ProfilePageView", () => {
/>,
);
expect(
screen.getByRole("heading", {
name: copy.welcomeTitle.replace("{{name}}", "dani@example.com"),
}),
).toBeInTheDocument();
expect(
screen.getByText(copy.welcomeBodyFirstRule),
).toBeInTheDocument();
@@ -242,6 +247,9 @@ describe("ProfilePageView", () => {
expect(
screen.getByRole("button", { name: copy.deleteRule }),
).toBeInTheDocument();
expect(
screen.getByRole("link", { name: "Garden coop" }),
).toHaveAttribute("href", "/create/completed?ruleId=rule-1");
});
test("lists invited Rules under Rules you belong to, not Your Rules", () => {
@@ -274,8 +282,8 @@ describe("ProfilePageView", () => {
screen.getByRole("heading", { name: copy.rulesYouBelongToHeading }),
).toBeInTheDocument();
expect(
screen.getByRole("link", { name: /Hawthorn Row Seed Library/ }),
).toHaveAttribute("href", "/invite/rule-invited");
screen.getByRole("link", { name: "Hawthorn Row Seed Library" }),
).toHaveAttribute("href", "/rules/rule-invited");
expect(
screen.queryByRole("button", { name: copy.viewPublic }),
).not.toBeInTheDocument();
@@ -340,5 +348,11 @@ describe("ProfilePageView", () => {
expect(
screen.getByRole("button", { name: copy.continueDraft }),
).toBeInTheDocument();
expect(
screen.getByRole("button", { name: copy.deleteRule }),
).toBeInTheDocument();
expect(
screen.queryByRole("button", { name: copy.inviteMembers }),
).not.toBeInTheDocument();
});
});
+19
View File
@@ -94,6 +94,25 @@ describe("Rule Component", () => {
expect(handleClick).toHaveBeenCalledTimes(1);
});
it("keeps bottom links and names the overlay link with ariaLabel", () => {
const onInvite = vi.fn();
render(
<Rule
{...defaultProps}
href="/create/completed?ruleId=rule-1"
ariaLabel="Garden coop"
hasBottomLinks
bottomLinks={[{ id: "invite", label: "Invite your members", onClick: onInvite }]}
/>,
);
expect(
screen.getByRole("link", { name: "Garden coop" }),
).toHaveAttribute("href", "/create/completed?ruleId=rule-1");
fireEvent.click(screen.getByRole("button", { name: "Invite your members" }));
expect(onInvite).toHaveBeenCalledTimes(1);
});
it("applies hover effects correctly", () => {
render(<Rule {...defaultProps} />);
+17
View File
@@ -15,6 +15,7 @@ import {
CREATE_FLOW_ANONYMOUS_KEY,
CREATE_FLOW_TRANSFER_PENDING_KEY,
clearAnonymousCreateFlowStorage,
clearTransferPendingFlag,
} from "../../app/(app)/create/utils/anonymousDraftStorage";
describe("clearAnonymousCreateFlowStorage", () => {
@@ -41,3 +42,19 @@ describe("clearAnonymousCreateFlowStorage", () => {
expect(forgetFlushedCommunityAvatarUrl).not.toHaveBeenCalled();
});
});
describe("clearTransferPendingFlag", () => {
beforeEach(() => {
localStorage.clear();
localStorage.setItem(CREATE_FLOW_ANONYMOUS_KEY, "{\"title\":\"Garden\"}");
localStorage.setItem(CREATE_FLOW_TRANSFER_PENDING_KEY, "1");
});
it("removes the flag and leaves the stored draft", () => {
clearTransferPendingFlag();
expect(localStorage.getItem(CREATE_FLOW_TRANSFER_PENDING_KEY)).toBeNull();
expect(localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY)).toBe(
"{\"title\":\"Garden\"}",
);
});
});
+26
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import {
buildAppliedTemplateCreateFlowState,
buildCoreValuesPrefillFromTemplateBody,
buildTemplateCustomizePrefill,
templatePresetDetailsFromPrefill,
@@ -224,6 +225,31 @@ describe("buildTemplateCustomizePrefill from templateChips.json", () => {
});
});
describe("buildAppliedTemplateCreateFlowState", () => {
it("starts from the template and drops leftover draft identity", () => {
const seeded = buildAppliedTemplateCreateFlowState({
slug: "mutual-aid-mondays",
body: {
sections: [
{
categoryName: "Communication",
entries: [{ title: "Signal" }],
},
],
},
mode: "useWithoutChanges",
});
expect(seeded.title).toBeUndefined();
expect(seeded.communityAvatarUrl).toBeUndefined();
expect(seeded.setupTraits).toBeUndefined();
expect(seeded.selectedCommunicationMethodIds).toEqual(["signal"]);
expect(seeded.pendingTemplateAction).toEqual({
slug: "mutual-aid-mondays",
mode: "useWithoutChanges",
});
});
});
describe("templatePresetDetailsFromPrefill", () => {
it("fills catalog copy for each prefilled chip", () => {
const details = templatePresetDetailsFromPrefill({
@@ -0,0 +1,138 @@
import { describe, expect, it } from "vitest";
import {
createFlowStateForEditingPublishedRule,
createFlowStateMatchesPublishedRule,
publishedRuleEditWouldReplaceDraft,
} from "../../lib/create/beginEditingPublishedRule";
import type { StoredLastPublishedRule } from "../../lib/create/lastPublishedRule";
import type { CreateFlowState } from "../../app/(app)/create/types";
const published: StoredLastPublishedRule = {
id: "rule-qa",
title: "QA Tenants Union",
summary: "How we share the building.",
document: {
coreValues: [
{
chipId: "accountability",
label: "Accountability",
meaning: "We say what we will do.",
signals: "",
},
],
methodSelections: {
communication: [
{
id: "signal",
label: "Signal",
sections: {
corePrinciple: "We write it down.",
logisticsAdmin: "A shared thread.",
codeOfConduct: "No pile-ons.",
},
},
],
},
},
};
describe("publishedRuleEditWouldReplaceDraft", () => {
it("is false when there is no draft", () => {
expect(publishedRuleEditWouldReplaceDraft({}, published)).toBe(false);
});
it("is false when the draft is already this finished Rule", () => {
const state = createFlowStateForEditingPublishedRule(published);
expect(publishedRuleEditWouldReplaceDraft(state, published)).toBe(false);
expect(createFlowStateMatchesPublishedRule(state, published)).toBe(true);
});
it("is true when the draft is a different community", () => {
const state: CreateFlowState = {
title: "The CommunityRule Project",
selectedCoreValueIds: ["solidarity"],
selectedCommunicationMethodIds: ["loomio"],
};
expect(publishedRuleEditWouldReplaceDraft(state, published)).toBe(true);
});
it("is true when the draft is already marked as an edit of another Rule", () => {
const state: CreateFlowState = {
...createFlowStateForEditingPublishedRule(published),
editingPublishedRuleId: "some-other-rule",
};
expect(publishedRuleEditWouldReplaceDraft(state, published)).toBe(true);
});
it("is true when the same cards have different description, details, or field blocks", () => {
const loaded = createFlowStateForEditingPublishedRule(published);
const rewrittenContext: CreateFlowState = {
...loaded,
communityContext: "A different description.",
summary: "A different description.",
};
expect(
createFlowStateMatchesPublishedRule(rewrittenContext, published),
).toBe(false);
expect(
publishedRuleEditWouldReplaceDraft(rewrittenContext, published),
).toBe(true);
const rewrittenMeaning: CreateFlowState = {
...loaded,
coreValueDetailsByChipId: {
accountability: {
meaning: "We changed what this means.",
signals: "",
},
},
};
expect(
publishedRuleEditWouldReplaceDraft(rewrittenMeaning, published),
).toBe(true);
const rewrittenMethod: CreateFlowState = {
...loaded,
communicationMethodDetailsById: {
signal: {
corePrinciple: "We say it out loud.",
logisticsAdmin: "A shared thread.",
codeOfConduct: "No pile-ons.",
},
},
};
expect(publishedRuleEditWouldReplaceDraft(rewrittenMethod, published)).toBe(
true,
);
const rewrittenBlocks: CreateFlowState = {
...loaded,
customMethodCardFieldBlocksById: {
signal: [
{
kind: "text",
id: "notes",
blockTitle: "Notes",
placeholderText: "What changed",
},
],
},
};
expect(publishedRuleEditWouldReplaceDraft(rewrittenBlocks, published)).toBe(
true,
);
});
});
describe("createFlowStateForEditingPublishedRule", () => {
it("loads the finished Rule's own name and cards, not leftover draft fields", () => {
const state = createFlowStateForEditingPublishedRule(published);
expect(state.title).toBe("QA Tenants Union");
expect(state.editingPublishedRuleId).toBe("rule-qa");
expect(state.selectedCommunicationMethodIds).toEqual(["signal"]);
expect(state.selectedOrganizationTypeIds).toBeUndefined();
expect(state.communityAvatarUrl).toBeUndefined();
expect(state.sections).toEqual([]);
});
});
+10 -18
View File
@@ -4,7 +4,6 @@ import {
parseDocumentSectionsForDisplay,
parseSectionsFromCreateFlowState,
} from "../../lib/create/buildPublishPayload";
import { mergeCoreValueDetailWithPresets } from "../../lib/create/finalReviewChipPresets";
import type { CreateFlowState } from "../../app/(app)/create/types";
describe("buildPublishPayload", () => {
@@ -144,15 +143,9 @@ describe("buildPublishPayload", () => {
});
expect(r.ok).toBe(true);
if (!r.ok) return;
const preset2 = mergeCoreValueDetailWithPresets("2", "Beta", undefined);
expect(r.document.coreValues).toEqual([
{ chipId: "1", label: "Alpha", meaning: "m1", signals: "s1" },
{
chipId: "2",
label: "Beta",
meaning: preset2.meaning,
signals: preset2.signals,
},
{ chipId: "2", label: "Beta", meaning: "", signals: "" },
]);
});
});
@@ -188,11 +181,12 @@ describe("buildPublishPayload — methodSelections", () => {
expect(ms?.communication?.length).toBe(1);
expect(ms?.communication?.[0]?.id).toBe("slack");
const first = ms?.communication?.[0];
expect(first?.sections.corePrinciple.length).toBeGreaterThan(10);
expect(first?.sections.corePrinciple).toBe("");
const entries =
(r.document.sections as Array<{ entries: Array<{ blocks?: unknown[] }> }>)[0]
?.entries;
expect(entries?.[0]?.blocks?.length).toBeGreaterThanOrEqual(1);
(r.document.sections as Array<{
entries: Array<{ title: string; body: string; blocks?: unknown[] }>;
}>)[0]?.entries;
expect(entries?.[0]).toEqual({ title: "Slack", body: "" });
});
it("uses customMethodCardMetaById label when preset id is unknown", () => {
@@ -251,7 +245,7 @@ describe("buildPublishPayload — methodSelections", () => {
]);
});
it("emits preset-only sections when a method is selected without an override", () => {
it("keeps blank card parts blank when a method is selected without an override", () => {
const r = buildPublishPayload({
title: "T",
selectedCommunicationMethodIds: ["signal"],
@@ -270,9 +264,7 @@ describe("buildPublishPayload — methodSelections", () => {
};
expect(entry.id).toBe("signal");
expect(entry.label).toBe("Signal");
// Preset corePrinciple is non-empty for `signal` in the shipped messages
// file — proves we read presets when no override is present.
expect(entry.sections.corePrinciple.length).toBeGreaterThan(0);
expect(entry.sections.corePrinciple).toBe("");
});
it("does not seed 75% consensus on a custom decision-making card", () => {
@@ -311,7 +303,7 @@ describe("buildPublishPayload — methodSelections", () => {
expect(ms.decisionApproaches?.[0]?.sections.consensusLevel).toBeUndefined();
});
it("keeps catalog decision consensus in methodSelections", () => {
it("does not fill catalog decision consensus when the card has no words", () => {
const r = buildPublishPayload({
title: "T",
selectedDecisionApproachIds: ["lazy-consensus"],
@@ -321,7 +313,7 @@ describe("buildPublishPayload — methodSelections", () => {
const ms = r.document.methodSelections as {
decisionApproaches?: Array<{ sections: { consensusLevel?: number } }>;
};
expect(ms.decisionApproaches?.[0]?.sections.consensusLevel).toBe(100);
expect(ms.decisionApproaches?.[0]?.sections.consensusLevel).toBeUndefined();
});
it("merges override on top of preset for the selected method", () => {
+55
View File
@@ -0,0 +1,55 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { CREATE_FLOW_ANONYMOUS_KEY } from "../../app/(app)/create/utils/anonymousDraftStorage";
import { clearBrowserRuleData } from "../../app/(app)/create/utils/clearBrowserRuleData";
import { CORE_VALUE_DETAILS_STORAGE_KEY } from "../../app/(app)/create/utils/coreValueDetailsLocalStorage";
import { CREATE_FLOW_LAST_PUBLISHED_KEY } from "../../lib/create/lastPublishedRule";
import { CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY } from "../../lib/create/pendingKeepRuleLogin";
const deleteServerDraft = vi.fn();
vi.mock("../../lib/create/api", () => ({
deleteServerDraft: (...args: unknown[]) => deleteServerDraft(...args),
}));
describe("clearBrowserRuleData", () => {
beforeEach(() => {
deleteServerDraft.mockReset();
window.localStorage.clear();
window.sessionStorage.clear();
});
afterEach(() => {
window.localStorage.clear();
window.sessionStorage.clear();
});
it("clears local draft keys and lastPublished without deleting the server draft", () => {
window.localStorage.setItem(
CREATE_FLOW_ANONYMOUS_KEY,
JSON.stringify({ title: "Stale" }),
);
window.localStorage.setItem(
CORE_VALUE_DETAILS_STORAGE_KEY,
JSON.stringify({ v1: { meaning: "x" } }),
);
window.localStorage.setItem("create-flow-state", "{}");
window.localStorage.setItem("create-flow-draft", "{}");
window.sessionStorage.setItem(
CREATE_FLOW_LAST_PUBLISHED_KEY,
JSON.stringify({ id: "rule-1", title: "Garden", document: {} }),
);
window.sessionStorage.setItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY, "1");
clearBrowserRuleData();
expect(window.localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY)).toBeNull();
expect(window.localStorage.getItem(CORE_VALUE_DETAILS_STORAGE_KEY)).toBeNull();
expect(window.localStorage.getItem("create-flow-state")).toBeNull();
expect(window.localStorage.getItem("create-flow-draft")).toBeNull();
expect(window.sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY)).toBeNull();
expect(
window.sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY),
).toBeNull();
expect(deleteServerDraft).not.toHaveBeenCalled();
});
});
+54
View File
@@ -0,0 +1,54 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { CREATE_FLOW_ANONYMOUS_KEY } from "../../app/(app)/create/utils/anonymousDraftStorage";
import { CORE_VALUE_DETAILS_STORAGE_KEY } from "../../app/(app)/create/utils/coreValueDetailsLocalStorage";
import {
createRuleEntryPath,
hasBrowserCreateFlowDraft,
} from "../../app/(app)/create/utils/createRuleEntry";
describe("createRuleEntryPath", () => {
beforeEach(() => {
window.localStorage.clear();
});
afterEach(() => {
window.localStorage.clear();
});
it("opens the first step when there is no draft", () => {
expect(hasBrowserCreateFlowDraft()).toBe(false);
expect(createRuleEntryPath()).toBe("/create/informational");
});
it("resumes the stored step", () => {
window.localStorage.setItem(
CREATE_FLOW_ANONYMOUS_KEY,
JSON.stringify({
title: "Garden coop",
currentStep: "community-size",
}),
);
expect(hasBrowserCreateFlowDraft()).toBe(true);
expect(createRuleEntryPath()).toBe("/create/community-size");
});
it("does not resume a finished Rule screen", () => {
window.localStorage.setItem(
CREATE_FLOW_ANONYMOUS_KEY,
JSON.stringify({
title: "Garden coop",
currentStep: "completed",
}),
);
expect(createRuleEntryPath()).toBe("/create/informational");
});
it("treats leftover core-value details as a draft", () => {
window.localStorage.setItem(
CORE_VALUE_DETAILS_STORAGE_KEY,
JSON.stringify({ "1": { meaning: "m", signals: "s" } }),
);
expect(hasBrowserCreateFlowDraft()).toBe(true);
expect(createRuleEntryPath()).toBe("/create/informational");
});
});
+153 -5
View File
@@ -1,7 +1,11 @@
import { describe, it, expect } from "vitest";
import { isFinalReviewContinueBlocked } from "../../app/(app)/create/utils/createFlowFooterLabels";
import { communityInitialsFromTitle } from "../../lib/create/communityInitials";
import { finalReviewChipHasWarning } from "../../lib/create/finalReviewChipWarnings";
import {
finalReviewChipBlocksContinue,
finalReviewChipHasWarning,
finalReviewMissingWordsLabels,
} from "../../lib/create/finalReviewChipWarnings";
import type { CreateFlowState } from "../../app/(app)/create/types";
const completeCards: CreateFlowState = {
@@ -12,11 +16,47 @@ const completeCards: CreateFlowState = {
selectedConflictManagementIds: ["conflict-ladder"],
};
const completeCardsWithWords: CreateFlowState = {
...completeCards,
communicationMethodDetailsById: {
signal: {
corePrinciple: "We talk in the open.",
logisticsAdmin: "Post in Signal.",
codeOfConduct: "No pile-ons.",
},
},
membershipMethodDetailsById: {
"open-admission": {
eligibility: "Anyone who shares the work.",
joiningProcess: "Show up.",
expectations: "Keep the keys.",
},
},
decisionApproachDetailsById: {
"lazy-consensus": {
corePrinciple: "Silence is assent.",
applicableScope: [],
selectedApplicableScope: [],
stepByStepInstructions: "Post the proposal.",
objectionsDeadlocks: "A named block stops it.",
},
},
conflictManagementDetailsById: {
"conflict-ladder": {
corePrinciple: "Start small.",
applicableScope: [],
selectedApplicableScope: [],
processProtocol: "Talk, then mediate.",
restorationFallbacks: "A panel if that fails.",
},
},
};
describe("isFinalReviewContinueBlocked", () => {
it("blocks when the community name is empty", () => {
expect(
isFinalReviewContinueBlocked({
...completeCards,
...completeCardsWithWords,
title: " ",
}),
).toBe(true);
@@ -25,14 +65,45 @@ describe("isFinalReviewContinueBlocked", () => {
it("blocks when any of the four questions has no card", () => {
expect(
isFinalReviewContinueBlocked({
...completeCards,
...completeCardsWithWords,
selectedMembershipMethodIds: [],
}),
).toBe(true);
});
it("does not block when values are empty and the four questions have cards", () => {
expect(isFinalReviewContinueBlocked(completeCards)).toBe(false);
it("blocks when a picked card is missing its words", () => {
expect(isFinalReviewContinueBlocked(completeCards)).toBe(true);
});
it("does not block when values are empty and every card has its words", () => {
expect(isFinalReviewContinueBlocked(completeCardsWithWords)).toBe(false);
});
it("blocks when a picked value is missing its meaning", () => {
expect(
isFinalReviewContinueBlocked({
...completeCardsWithWords,
selectedCoreValueIds: ["1"],
coreValuesChipsSnapshot: [
{ id: "1", label: "Care", state: "selected" },
],
}),
).toBe(true);
});
it("does not block when a value has meaning but no signals", () => {
expect(
isFinalReviewContinueBlocked({
...completeCardsWithWords,
selectedCoreValueIds: ["1"],
coreValuesChipsSnapshot: [
{ id: "1", label: "Care", state: "selected" },
],
coreValueDetailsByChipId: {
"1": { meaning: "We look after each other.", signals: "" },
},
}),
).toBe(false);
});
});
@@ -70,6 +141,83 @@ describe("finalReviewChipHasWarning", () => {
),
).toBe(false);
});
it("clears the warning when a custom card's fields have text", () => {
const customId = "00000000-0000-4000-8000-000000000190";
expect(
finalReviewChipHasWarning(
{
customMethodCardMetaById: {
[customId]: { label: "S13 comms card", supportText: "" },
},
customMethodCardFieldBlocksById: {
[customId]: [
{
kind: "text",
id: "b1",
blockTitle: "How we talk",
placeholderText: "Post in the hall.",
},
],
},
},
"communication",
customId,
),
).toBe(false);
});
});
describe("finalReviewChipBlocksContinue", () => {
it("does not block a value that has meaning but no signals", () => {
expect(
finalReviewChipBlocksContinue(
{
coreValueDetailsByChipId: {
"1": { meaning: "Care", signals: "" },
},
},
"coreValues",
"1",
),
).toBe(false);
});
it("blocks a custom card until its fields have text", () => {
const customId = "00000000-0000-4000-8000-000000000191";
expect(
finalReviewChipBlocksContinue(
{
customMethodCardMetaById: {
[customId]: { label: "S13 comms card", supportText: "" },
},
customMethodCardFieldBlocksById: {
[customId]: [
{
kind: "text",
id: "b1",
blockTitle: "How we talk",
placeholderText: "",
},
],
},
},
"communication",
customId,
),
).toBe(true);
});
});
describe("finalReviewMissingWordsLabels", () => {
it("names the cards that still need words", () => {
expect(finalReviewMissingWordsLabels(completeCards)).toEqual([
"Signal",
"Open admission",
"Lazy consensus",
"Conflict ladder",
]);
});
});
describe("communityInitialsFromTitle", () => {
+9
View File
@@ -5,6 +5,7 @@ import {
getNextStep,
getPreviousStep,
isValidStep,
resumeCreateFlowStep,
getStepIndex,
parseReviewReturnSearchParam,
parseCreateFlowScreenFromPathname,
@@ -46,6 +47,14 @@ describe("flowSteps", () => {
expect(getPreviousStep(null)).toBeNull();
});
it("resumeCreateFlowStep opens the screen the draft was left on", () => {
expect(resumeCreateFlowStep({ currentStep: "core-values" })).toBe(
"core-values",
);
expect(resumeCreateFlowStep({})).toBe("informational");
expect(resumeCreateFlowStep(null)).toBe("informational");
});
it("isValidStep allows branch-only edit-rule URL segment", () => {
expect(isValidStep("edit-rule")).toBe(true);
});
+16
View File
@@ -35,6 +35,7 @@ vi.mock("../../lib/logger", () => ({
import {
claimGuestRulesForUser,
clearGuestRuleClaimCookie,
issueGuestRuleClaimCookie,
} from "../../lib/server/guestRuleClaim";
@@ -76,6 +77,21 @@ describe("issueGuestRuleClaimCookie", () => {
});
});
describe("clearGuestRuleClaimCookie", () => {
it("expires the claim cookie", async () => {
await clearGuestRuleClaimCookie();
expect(cookieSetMock).toHaveBeenCalledWith(
"cr_rule_claim",
"",
expect.objectContaining({
httpOnly: true,
path: "/",
maxAge: 0,
}),
);
});
});
describe("claimGuestRulesForUser", () => {
it("returns 0 when the cookie is empty", async () => {
cookieGetMock.mockReturnValue(undefined);
@@ -2,7 +2,11 @@ import { renderHook, act } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { CreateFlowState } from "../../../app/(app)/create/types";
import { useCreateFlowFinalize } from "../../../app/(app)/create/hooks/useCreateFlowFinalize";
import { publishRule, updatePublishedRule } from "../../../lib/create/api";
import {
deleteServerDraft,
publishRule,
updatePublishedRule,
} from "../../../lib/create/api";
import { buildPublishPayload } from "../../../lib/create/buildPublishPayload";
import { stateWithPendingCommunityAvatar } from "../../../lib/create/flushPendingCommunityAvatar";
import messages from "../../../messages/en/index";
@@ -25,6 +29,7 @@ vi.mock("../../../lib/create/buildPublishPayload", () => ({
vi.mock("../../../lib/create/api", () => ({
publishRule: vi.fn(),
updatePublishedRule: vi.fn(),
deleteServerDraft: vi.fn(),
}));
vi.mock("../../../lib/create/flushPendingCommunityAvatar", () => ({
@@ -50,6 +55,8 @@ describe("useCreateFlowFinalize", () => {
beforeEach(() => {
vi.mocked(publishRule).mockReset();
vi.mocked(updatePublishedRule).mockReset();
vi.mocked(deleteServerDraft).mockReset();
vi.mocked(deleteServerDraft).mockResolvedValue(true);
vi.mocked(writeLastPublishedRule).mockReset();
vi.mocked(stateWithPendingCommunityAvatar).mockReset();
vi.mocked(stateWithPendingCommunityAvatar).mockImplementation(
@@ -101,6 +108,35 @@ describe("useCreateFlowFinalize", () => {
expect(
sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY),
).toBeNull();
expect(deleteServerDraft).toHaveBeenCalledTimes(1);
});
it("retries clearing the server draft when the first delete fails", async () => {
vi.mocked(publishRule).mockResolvedValue({
ok: true,
id: "new-rule-id",
title: "Published title",
});
vi.mocked(deleteServerDraft)
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true);
const { result } = renderHook(() =>
useCreateFlowFinalize({
state: emptyState,
router,
openLogin,
updateState,
loginReturnPath: "/create/final-review",
sessionUser: signedIn,
}),
);
await act(async () => {
await result.current.finalize();
});
expect(deleteServerDraft).toHaveBeenCalledTimes(2);
});
it("does not publish while the session is unresolved", async () => {
@@ -408,6 +444,7 @@ describe("useCreateFlowFinalize", () => {
summary: "Published summary",
document: {},
});
expect(deleteServerDraft).toHaveBeenCalledTimes(1);
expect(updateState).toHaveBeenCalledWith({
editingPublishedRuleId: undefined,
});
@@ -35,10 +35,15 @@ describe("useTemplateReviewActions", () => {
const router = { push: vi.fn() };
const updateState = vi.fn();
const markCreateFlowInteraction = vi.fn();
const requestConfirm = vi.fn();
let applied: CreateFlowState | undefined;
const replaceState = vi.fn(
(updater: (_prev: CreateFlowState) => CreateFlowState) => {
applied = updater({});
applied = updater({
title: "Juniper Street Tenants",
communityAvatarUrl: "/old.png",
setupTraits: { employer: true },
});
},
);
@@ -48,8 +53,12 @@ describe("useTemplateReviewActions", () => {
router.push.mockReset();
updateState.mockReset();
markCreateFlowInteraction.mockReset();
requestConfirm.mockReset();
requestConfirm.mockResolvedValue(true);
replaceState.mockClear();
applied = undefined;
window.sessionStorage.clear();
window.localStorage.clear();
});
function renderActions(
@@ -64,6 +73,7 @@ describe("useTemplateReviewActions", () => {
replaceState,
router,
fromCreateWizard,
requestConfirm,
markCreateFlowInteraction,
}),
);
@@ -86,9 +96,10 @@ describe("useTemplateReviewActions", () => {
);
});
it("Customize Continue prefills cards, drops setup answers, and walks the decks", async () => {
it("Customize Continue prefills cards, drops leftover identity, and walks the decks", async () => {
const { result } = renderActions({
setupTraits: { employer: true },
communityAvatarUrl: "/old.png",
});
await act(async () => {
@@ -103,32 +114,19 @@ describe("useTemplateReviewActions", () => {
});
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",
}),
);
expect(applied?.title).toBe("Neighborhood");
expect(applied?.communityContext).toBe("We meet weekly");
expect(applied?.communityLocation).toBe("Oakland");
expect(applied?.communityAvatarUrl).toBeUndefined();
expect(applied?.setupTraits).toBeUndefined();
expect(applied?.pendingTemplateAction).toEqual({
slug: "mutual-aid-mondays",
mode: "customize",
});
expect(applied?.templateReviewBackSlug).toBe("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({
title: "Neighborhood",
communityContext: "Stale description",
currentStep: "confirm-stakeholders",
setupTraits: { employer: true, network: false },
});
},
);
const { result } = renderActions({ title: "Neighborhood" });
await act(async () => {
@@ -138,8 +136,9 @@ describe("useTemplateReviewActions", () => {
expect(router.push).toHaveBeenCalledWith("/create/final-review");
expect(applied?.title).toBeUndefined();
expect(applied?.communityContext).toBeUndefined();
expect(applied?.currentStep).toBeUndefined();
expect(applied?.communityAvatarUrl).toBeUndefined();
expect(applied?.setupTraits).toBeUndefined();
expect(applied?.currentStep).toBeUndefined();
expect(applied?.pendingTemplateAction).toEqual({
slug: "mutual-aid-mondays",
mode: "useWithoutChanges",
@@ -147,18 +146,12 @@ describe("useTemplateReviewActions", () => {
});
it("in-flow Use without changes keeps the community name and pins the template path", async () => {
replaceState.mockImplementation(
(updater: (_prev: CreateFlowState) => CreateFlowState) => {
applied = updater({
title: "Neighborhood",
communityContext: "We meet weekly",
templateReviewEntryFromCreateFlow: true,
setupTraits: { employer: true },
});
},
);
const { result } = renderActions(
{ title: "Neighborhood", templateReviewEntryFromCreateFlow: true },
{
title: "Neighborhood",
communityContext: "We meet weekly",
templateReviewEntryFromCreateFlow: true,
},
true,
);
@@ -176,4 +169,21 @@ describe("useTemplateReviewActions", () => {
});
expect(applied?.templateReviewBackSlug).toBe("mutual-aid-mondays");
});
it("asks before replacing a draft in progress", async () => {
requestConfirm.mockResolvedValueOnce(false);
const { result } = renderActions({ title: "Juniper Street Tenants" });
await act(async () => {
await result.current.handleUseWithoutChanges();
});
expect(requestConfirm).toHaveBeenCalledWith(
expect.objectContaining({
title: "Replace the draft in progress?",
}),
);
expect(router.push).not.toHaveBeenCalled();
expect(replaceState).not.toHaveBeenCalled();
});
});
+29 -2
View File
@@ -1,5 +1,10 @@
import { describe, expect, it } from "vitest";
import { finishedAtIso } from "../../lib/create/lastPublishedRule";
import { afterEach, describe, expect, it } from "vitest";
import {
CREATE_FLOW_LAST_PUBLISHED_KEY,
clearLastPublishedRule,
finishedAtIso,
writeLastPublishedRule,
} from "../../lib/create/lastPublishedRule";
describe("finishedAtIso", () => {
it("normalizes strings and dates", () => {
@@ -17,3 +22,25 @@ describe("finishedAtIso", () => {
expect(finishedAtIso(null)).toBeUndefined();
});
});
describe("clearLastPublishedRule", () => {
afterEach(() => {
sessionStorage.removeItem(CREATE_FLOW_LAST_PUBLISHED_KEY);
});
it("removes the stored finished Rule", () => {
writeLastPublishedRule({
id: "rule-1",
title: "Garden coop",
document: { sections: [] },
});
expect(sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY)).not.toBeNull();
clearLastPublishedRule();
expect(sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY)).toBeNull();
});
it("does nothing when the key is already missing", () => {
expect(() => clearLastPublishedRule()).not.toThrow();
expect(sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY)).toBeNull();
});
});
@@ -1,7 +1,11 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
FRESH_ENTRY_PENDING_KEY,
TEMPLATE_APPLY_LATCH_KEY,
clearTemplateApplyLatch,
hasFreshEntryPending,
hasTemplateApplyLatch,
latchTemplateApply,
prepareFreshCreateFlowEntry,
prepareFreshCreateFlowEntrySync,
} from "../../app/(app)/create/utils/prepareFreshCreateFlowEntry";
@@ -66,6 +70,25 @@ describe("prepareFreshCreateFlowEntrySync", () => {
});
});
describe("template apply latch", () => {
beforeEach(() => {
window.sessionStorage.clear();
});
afterEach(() => {
window.sessionStorage.clear();
});
it("sets, reads, and clears the session flag", () => {
expect(hasTemplateApplyLatch()).toBe(false);
latchTemplateApply();
expect(window.sessionStorage.getItem(TEMPLATE_APPLY_LATCH_KEY)).toBe("1");
expect(hasTemplateApplyLatch()).toBe(true);
clearTemplateApplyLatch();
expect(hasTemplateApplyLatch()).toBe(false);
});
});
describe("prepareFreshCreateFlowEntry", () => {
beforeEach(() => {
deleteServerDraft.mockReset();
@@ -81,7 +81,7 @@ describe("parsePublishedDocumentForCommunityRuleDisplay", () => {
expect(out[0].entries[0].body).toBe("x\n\ny");
});
it("enriches empty core value copy from presets (label match)", () => {
it("keeps empty core value copy blank instead of filling library text", () => {
const doc = {
sections: [],
coreValues: [
@@ -89,7 +89,8 @@ describe("parsePublishedDocumentForCommunityRuleDisplay", () => {
],
};
const out = parsePublishedDocumentForCommunityRuleDisplay(doc);
expect(out[0].entries[0].body).toMatch(/well-being is bound up/);
expect(out[0].entries[0].title).toBe("Interdependence");
expect(out[0].entries[0].body).toBe("");
});
it("replaces template placeholder bodies with preset copy, Values first", () => {
+58
View File
@@ -0,0 +1,58 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const findUniqueMock = vi.fn();
const deleteManyMock = vi.fn();
const deleteUploadsForDraftMock = vi.fn();
vi.mock("../../lib/server/db", () => ({
prisma: {
ruleDraft: {
findUnique: (...args: unknown[]) => findUniqueMock(...args),
deleteMany: (...args: unknown[]) => deleteManyMock(...args),
},
},
}));
vi.mock("../../lib/server/uploads/deleteUploadedFiles", () => ({
deleteUploadsForDraft: (...args: unknown[]) =>
deleteUploadsForDraftMock(...args),
}));
import { deleteRuleDraftForUser } from "../../lib/server/ruleDrafts";
describe("deleteRuleDraftForUser", () => {
beforeEach(() => {
findUniqueMock.mockReset();
deleteManyMock.mockReset();
deleteUploadsForDraftMock.mockReset();
});
it("removes the draft and files still tied to it", async () => {
findUniqueMock.mockResolvedValueOnce({ id: "draft-1" });
deleteUploadsForDraftMock.mockResolvedValueOnce(undefined);
deleteManyMock.mockResolvedValueOnce({ count: 1 });
await deleteRuleDraftForUser("user-1");
expect(findUniqueMock).toHaveBeenCalledWith({
where: { userId: "user-1" },
select: { id: true },
});
expect(deleteUploadsForDraftMock).toHaveBeenCalledWith("draft-1");
expect(deleteManyMock).toHaveBeenCalledWith({
where: { userId: "user-1" },
});
});
it("still deletes when there is no draft row", async () => {
findUniqueMock.mockResolvedValueOnce(null);
deleteManyMock.mockResolvedValueOnce({ count: 0 });
await deleteRuleDraftForUser("user-1");
expect(deleteUploadsForDraftMock).not.toHaveBeenCalled();
expect(deleteManyMock).toHaveBeenCalledWith({
where: { userId: "user-1" },
});
});
});
+31
View File
@@ -61,6 +61,37 @@ describe("inviteRuleCountsLabel", () => {
}),
).toBe("3 VALUES AND 2 CARDS");
});
it("counts titled cards that still have no words", () => {
expect(
inviteRuleCountsLabel({
methodSelections: {
communication: [
{
id: "signal",
label: "Signal",
sections: {
corePrinciple: "",
logisticsAdmin: "",
codeOfConduct: "",
},
},
],
membership: [
{
id: "open-admission",
label: "Open admission",
sections: {
eligibility: "",
joiningProcess: "",
expectations: "",
},
},
],
},
}),
).toBe("0 VALUES AND 2 CARDS");
});
});
describe("inviteRuleCountsSpoken", () => {
@@ -45,6 +45,16 @@ describe("withoutUnpublishedDecisionConsensus", () => {
});
describe("communityRuleEntryFromMethodChip", () => {
it("keeps a titled card when there are no words yet", () => {
expect(
communityRuleEntryFromMethodChip(
"Signal",
{ corePrinciple: "" },
{ corePrinciple: "Core Principle" },
),
).toEqual({ title: "Signal", body: "" });
});
it("publishes supportText as body when there are no labeled blocks", () => {
expect(
communityRuleEntryFromMethodChip(
+67 -6
View File
@@ -48,6 +48,12 @@ vi.mock("../../lib/server/uploads/linkUploads", () => ({
linkUploadsToRule: vi.fn().mockResolvedValue(undefined),
}));
const deleteRuleDraftForUserMock = vi.fn();
vi.mock("../../lib/server/ruleDrafts", () => ({
deleteRuleDraftForUser: (...args: unknown[]) =>
deleteRuleDraftForUserMock(...args),
}));
vi.mock("../../lib/server/db", () => ({
prisma: {
$transaction: (fn: (tx: unknown) => Promise<unknown>) =>
@@ -72,6 +78,8 @@ beforeEach(() => {
sendInviteMock.mockReset();
rateLimitKeyMock.mockReset();
issueGuestRuleClaimCookieMock.mockReset();
deleteRuleDraftForUserMock.mockReset();
deleteRuleDraftForUserMock.mockResolvedValue(undefined);
rateLimitKeyMock.mockReturnValue({ ok: true as const });
getSessionUserMock.mockResolvedValue({
id: "user-1",
@@ -112,6 +120,61 @@ describe("POST /api/rules", () => {
).toBeUndefined();
expect(issueGuestRuleClaimCookieMock).not.toHaveBeenCalled();
expect(sendInviteMock).not.toHaveBeenCalled();
expect(deleteRuleDraftForUserMock).toHaveBeenCalledWith("user-1");
});
it("retries draft deletion after publish and still returns the rule", async () => {
publishedRuleCreateMock.mockResolvedValueOnce({
id: "rule-solo",
title: "T",
summary: null,
createdAt: new Date("2026-01-01T00:00:00.000Z"),
});
deleteRuleDraftForUserMock
.mockRejectedValueOnce(new Error("draft delete failed"))
.mockResolvedValueOnce(undefined);
const res = await POST(
new NextRequest("https://x.test/api/rules", {
method: "POST",
body: JSON.stringify({
title: "T",
summary: null,
document: {},
}),
}),
undefined,
);
expect(res.status).toBe(200);
expect(deleteRuleDraftForUserMock).toHaveBeenCalledTimes(2);
});
it("publishes when draft deletion keeps failing", async () => {
publishedRuleCreateMock.mockResolvedValueOnce({
id: "rule-solo",
title: "T",
summary: null,
createdAt: new Date("2026-01-01T00:00:00.000Z"),
});
deleteRuleDraftForUserMock.mockRejectedValue(
new Error("draft delete failed"),
);
const res = await POST(
new NextRequest("https://x.test/api/rules", {
method: "POST",
body: JSON.stringify({
title: "T",
summary: null,
document: {},
}),
}),
undefined,
);
expect(res.status).toBe(200);
expect(deleteRuleDraftForUserMock).toHaveBeenCalledTimes(3);
});
it("stores place and group type from the published document", async () => {
@@ -196,6 +259,7 @@ describe("POST /api/rules", () => {
}),
);
expect(publishedRuleCreateMock).not.toHaveBeenCalled();
expect(deleteRuleDraftForUserMock).toHaveBeenCalledWith("user-1");
});
it("rolls back publish when mail fails", async () => {
@@ -238,6 +302,7 @@ describe("POST /api/rules", () => {
expect(publishedRuleDeleteMock).toHaveBeenCalledWith({
where: { id: "rule-new" },
});
expect(deleteRuleDraftForUserMock).not.toHaveBeenCalled();
});
it("keeps the rule when a later invite send fails after one succeeded", async () => {
@@ -248,12 +313,7 @@ describe("POST /api/rules", () => {
createdAt: new Date("2026-01-02T00:00:00.000Z"),
};
transactionMock.mockImplementation(
async (
fn: (tx: {
publishedRule: { create: typeof vi.fn };
ruleStakeholder: { create: typeof vi.fn };
}) => Promise<unknown>,
) => {
async (fn: (tx: { publishedRule: { create: typeof vi.fn }; ruleStakeholder: { create: typeof vi.fn } }) => Promise<unknown>) => {
const tx = {
publishedRule: {
create: vi.fn().mockResolvedValue(created),
@@ -329,6 +389,7 @@ describe("POST /api/rules", () => {
expect(sendInviteMock).not.toHaveBeenCalled();
const body = (await res.json()) as { rule: { id: string } };
expect(body.rule.id).toBe("rule-guest");
expect(deleteRuleDraftForUserMock).not.toHaveBeenCalled();
});
it("rate-limits anonymous publish by IP", async () => {
@@ -0,0 +1,70 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const clearPendingCommunityAvatarFile = vi.fn();
const forgetFlushedCommunityAvatarUrl = vi.fn();
vi.mock("../../lib/create/pendingCommunityAvatarUpload", () => ({
clearPendingCommunityAvatarFile: () => clearPendingCommunityAvatarFile(),
}));
vi.mock("../../lib/create/flushPendingCommunityAvatar", () => ({
forgetFlushedCommunityAvatarUrl: () => forgetFlushedCommunityAvatarUrl(),
}));
import {
CREATE_FLOW_ANONYMOUS_KEY,
CREATE_FLOW_TRANSFER_PENDING_KEY,
} from "../../app/(app)/create/utils/anonymousDraftStorage";
import { CORE_VALUE_DETAILS_STORAGE_KEY } from "../../app/(app)/create/utils/coreValueDetailsLocalStorage";
import { seedContinuedDraftLocalStorage } from "../../app/(app)/create/utils/seedContinuedDraftLocalStorage";
import type { CreateFlowState } from "../../app/(app)/create/types";
describe("seedContinuedDraftLocalStorage", () => {
beforeEach(() => {
localStorage.clear();
clearPendingCommunityAvatarFile.mockReset();
forgetFlushedCommunityAvatarUrl.mockReset();
localStorage.setItem(
CREATE_FLOW_ANONYMOUS_KEY,
JSON.stringify({ title: "Stale" }),
);
localStorage.setItem(
CORE_VALUE_DETAILS_STORAGE_KEY,
JSON.stringify({ old: { meaning: "old", signals: "" } }),
);
localStorage.setItem(CREATE_FLOW_TRANSFER_PENDING_KEY, "1");
});
it("writes the server draft over the browser mirror", () => {
const state: CreateFlowState = {
title: "Garden",
currentStep: "core-values",
coreValueDetailsByChipId: {
solidarity: { meaning: "We show up.", signals: "" },
},
};
seedContinuedDraftLocalStorage(state);
expect(
JSON.parse(localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY) ?? "{}"),
).toEqual(state);
expect(
JSON.parse(localStorage.getItem(CORE_VALUE_DETAILS_STORAGE_KEY) ?? "{}"),
).toEqual(state.coreValueDetailsByChipId);
expect(localStorage.getItem(CREATE_FLOW_TRANSFER_PENDING_KEY)).toBeNull();
expect(clearPendingCommunityAvatarFile).toHaveBeenCalledTimes(1);
expect(forgetFlushedCommunityAvatarUrl).toHaveBeenCalledTimes(1);
});
it("clears core-value details when the continued draft has none", () => {
seedContinuedDraftLocalStorage({ title: "Garden" });
expect(localStorage.getItem(CORE_VALUE_DETAILS_STORAGE_KEY)).toBeNull();
expect(
JSON.parse(localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY) ?? "{}"),
).toEqual({
title: "Garden",
});
});
});
+115
View File
@@ -1,10 +1,15 @@
import { describe, expect, it } from "vitest";
import { buildAppliedTemplateCreateFlowState } from "../../lib/create/applyTemplatePrefill";
import { buildFinalReviewCategoriesFromState } from "../../lib/create/buildFinalReviewCategories";
import {
templateBodyToCategories,
templateBodyToReviewData,
templateCategoryToGroupKey,
templateReviewDataForSlug,
templateSummaryFromBody,
} from "../../lib/create/templateReviewMapping";
import templateChipsFile from "../../data/templates/templateChips.json";
import templateReviewMessages from "../../messages/en/create/templateReview.json";
describe("templateReviewMapping", () => {
it("maps body sections to Rule categories", () => {
@@ -117,3 +122,113 @@ describe("templateReviewMapping", () => {
});
});
});
const FINAL_REVIEW_NAMES = {
values: "Values",
communication: "Communication",
membership: "Membership",
decisions: "Decision-making",
conflict: "Conflict management",
};
const STALE_CONSENSUS_BODY = {
sections: [
{
categoryName: "Values",
entries: [{ title: "Community Care", body: "" }],
},
{
categoryName: "Communication",
entries: [
{ title: "In-Person Meetings", body: "" },
{ title: "Loomio", body: "" },
],
},
{
categoryName: "Membership",
entries: [{ title: "Peer Sponsorship", body: "" }],
},
{
categoryName: "Decision-making",
entries: [
{ title: "Consensus or Vote-Based Approval", body: "" },
{ title: "Consensus Decision-Making", body: "" },
],
},
{
categoryName: "Conflict management",
entries: [{ title: "Facilitated Negotiation", body: "" }],
},
],
};
describe("templateReviewDataForSlug", () => {
it("lists remade catalog names for consensus, not API body titles", () => {
const { categories } = templateReviewDataForSlug(
"consensus",
STALE_CONSENSUS_BODY,
);
const labels = categories.flatMap((row) =>
row.chipOptions.map((chip) => chip.label),
);
expect(labels).toContain("How we run meetings");
expect(labels).toContain("In-person meetings");
expect(labels).toContain("Conflict ladder");
expect(labels).toContain("Community care");
expect(labels).toContain("Decision speeds");
expect(labels).not.toContain("In-Person Meetings");
expect(labels).not.toContain("Community Care");
expect(labels).not.toContain("Peer Sponsorship");
expect(labels).not.toContain("Facilitated Negotiation");
});
it("matches Use without changes final-review labels", () => {
const slugs = Object.keys(
(templateChipsFile as { templates: Record<string, unknown> }).templates,
);
for (const slug of slugs) {
const detail = templateReviewDataForSlug(slug, STALE_CONSENSUS_BODY);
const seeded = buildAppliedTemplateCreateFlowState({
slug,
body: STALE_CONSENSUS_BODY,
mode: "useWithoutChanges",
});
const review = buildFinalReviewCategoriesFromState(
seeded,
FINAL_REVIEW_NAMES,
);
const detailByName = new Map(
detail.categories.map((row) => [
row.name,
row.chipOptions.map((chip) => chip.label),
]),
);
for (const row of review) {
if (row.chips.length === 0) continue;
expect(detailByName.get(row.name), slug).toEqual(row.chips);
}
}
});
it("falls back to body titles when the slug is not in the catalog", () => {
const cats = templateReviewDataForSlug("unknown-template", {
sections: [
{
categoryName: "Values",
entries: [{ title: "Solidarity", body: "Long body" }],
},
],
}).categories;
expect(cats[0].chipOptions.map((chip) => chip.label)).toEqual([
"Solidarity",
]);
});
});
describe("template review intro", () => {
it("reads one size fits all", () => {
expect(templateReviewMessages.intro.description).toContain(
"one size fits all",
);
});
});
+4
View File
@@ -26,6 +26,10 @@ vi.mock("../../lib/server/uploads/deleteUploadedFiles", () => ({
deleteUploadsForUser: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("../../lib/server/guestRuleClaim", () => ({
clearGuestRuleClaimCookie: vi.fn().mockResolvedValue(undefined),
}));
import { DELETE } from "../../app/api/user/me/route";
beforeEach(() => {