From 942c7cc9ded6944f6d44241cfb7db139a3bce929 Mon Sep 17 00:00:00 2001 From: adilallo <39313955+adilallo@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:47:46 -0700 Subject: [PATCH 01/10] Open a finished Rule from its Profile card, and drop it from the browser on Log out. --- .../create/utils/clearBrowserRuleData.ts | 24 +++++++ app/(app)/profile/ProfilePageClient.tsx | 7 ++ .../profile/_components/ProfilePage.view.tsx | 8 ++- app/api/auth/logout/route.ts | 2 + app/api/user/me/route.ts | 2 + app/components/cards/Rule/Rule.container.tsx | 9 ++- app/components/cards/Rule/Rule.types.ts | 9 ++- app/components/cards/Rule/Rule.view.tsx | 26 +++++++- lib/create/lastPublishedRule.ts | 9 ++- lib/server/guestRuleClaim.ts | 2 +- tests/components/CompletedPage.test.tsx | 64 ++++++++++++++++++- tests/pages/profile.test.tsx | 7 +- tests/unit/Rule.test.jsx | 19 ++++++ tests/unit/clearBrowserRuleData.test.ts | 55 ++++++++++++++++ tests/unit/guestRuleClaim.test.ts | 16 +++++ tests/unit/lastPublishedRule.test.ts | 31 ++++++++- tests/unit/userMeDeleteRoute.test.ts | 4 ++ 17 files changed, 280 insertions(+), 14 deletions(-) create mode 100644 app/(app)/create/utils/clearBrowserRuleData.ts create mode 100644 tests/unit/clearBrowserRuleData.test.ts diff --git a/app/(app)/create/utils/clearBrowserRuleData.ts b/app/(app)/create/utils/clearBrowserRuleData.ts new file mode 100644 index 0000000..b2bb9e5 --- /dev/null +++ b/app/(app)/create/utils/clearBrowserRuleData.ts @@ -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 + } +} diff --git a/app/(app)/profile/ProfilePageClient.tsx b/app/(app)/profile/ProfilePageClient.tsx index 2b527c8..a5293f6 100644 --- a/app/(app)/profile/ProfilePageClient.tsx +++ b/app/(app)/profile/ProfilePageClient.tsx @@ -23,7 +23,9 @@ import { downloadStoredRuleAsPdf, } from "../../../lib/create/ruleExport"; import { + clearLastPublishedRule, finishedAtIso, + readLastPublishedRule, writeLastPublishedRule, type StoredLastPublishedRule, } from "../../../lib/create/lastPublishedRule"; @@ -36,6 +38,7 @@ import { } from "../create/utils/flowSteps"; import type { CreateFlowStep } from "../create/types"; import { clearAnonymousCreateFlowStorage } from "../create/utils/anonymousDraftStorage"; +import { clearBrowserRuleData } from "../create/utils/clearBrowserRuleData"; import { clearCoreValueDetailsLocalStorage } from "../create/utils/coreValueDetailsLocalStorage"; import { prepareFreshCreateFlowEntrySync } from "../create/utils/prepareFreshCreateFlowEntry"; import { createFlowStepPath } from "../create/utils/createFlowPaths"; @@ -203,6 +206,7 @@ export default function ProfilePageClient() { const handleSignOut = useCallback(async () => { setActionError(null); await logout(); + clearBrowserRuleData(); setUser(null); setRules([]); setDraft(null); @@ -228,6 +232,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; @@ -392,6 +398,7 @@ export default function ProfilePageClient() { const res = await deleteAccount(); setAccountDeleteBusy(false); if (res.ok) { + clearBrowserRuleData(); setAccountDeleteOpen(false); setUser(null); setRules([]); diff --git a/app/(app)/profile/_components/ProfilePage.view.tsx b/app/(app)/profile/_components/ProfilePage.view.tsx index 48d442d..41f34cb 100644 --- a/app/(app)/profile/_components/ProfilePage.view.tsx +++ b/app/(app)/profile/_components/ProfilePage.view.tsx @@ -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, @@ -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} /> ))} @@ -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, )} diff --git a/app/api/auth/logout/route.ts b/app/api/auth/logout/route.ts index dfa2936..1e84a54 100644 --- a/app/api/auth/logout/route.ts +++ b/app/api/auth/logout/route.ts @@ -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 }); }); diff --git a/app/api/user/me/route.ts b/app/api/user/me/route.ts index 7548601..b84d3b5 100644 --- a/app/api/user/me/route.ts +++ b/app/api/user/me/route.ts @@ -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 }); }); diff --git a/app/components/cards/Rule/Rule.container.tsx b/app/components/cards/Rule/Rule.container.tsx index 17c5506..63f1e34 100644 --- a/app/components/cards/Rule/Rule.container.tsx +++ b/app/components/cards/Rule/Rule.container.tsx @@ -36,6 +36,7 @@ const RuleContainer = memo( className = "", onClick, href, + ariaLabel: ariaLabelProp, expanded = false, size: sizeProp, categories, @@ -67,7 +68,11 @@ const RuleContainer = memo( 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( icon={icon} backgroundColor={backgroundColor} className={className} - href={isInteractive && !hasBottomLinks ? href : undefined} + href={href} onClick={isInteractive && !hasBottomLinks ? handleClick : undefined} onKeyDown={ isInteractive && !hasBottomLinks && !href ? handleKeyDown : undefined diff --git a/app/components/cards/Rule/Rule.types.ts b/app/components/cards/Rule/Rule.types.ts index 9901345..3497bf2 100644 --- a/app/components/cards/Rule/Rule.types.ts +++ b/app/components/cards/Rule/Rule.types.ts @@ -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[]; diff --git a/app/components/cards/Rule/Rule.view.tsx b/app/components/cards/Rule/Rule.view.tsx index 9367397..405ed95 100644 --- a/app/components/cards/Rule/Rule.view.tsx +++ b/app/components/cards/Rule/Rule.view.tsx @@ -298,6 +298,7 @@ export function RuleView({ e.stopPropagation()} /> @@ -307,6 +308,7 @@ export function RuleView({ { 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 ( +
+ +
+ {cardBody} +
+
+ ); + } + return (
{ ); } -async function clearGuestRuleClaimCookie(): Promise { +export async function clearGuestRuleClaimCookie(): Promise { const store = await cookies(); store.set(GUEST_RULE_CLAIM_COOKIE_NAME, "", { ...cookieOptions(), diff --git a/tests/components/CompletedPage.test.tsx b/tests/components/CompletedPage.test.tsx index ab31b05..920979d 100644 --- a/tests/components/CompletedPage.test.tsx +++ b/tests/components/CompletedPage.test.tsx @@ -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) { 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(); + + 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(); + + await waitFor(() => { + expect(testRouter.replace).toHaveBeenCalledWith("/rules/rule-other"); + }); + expect(sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY)).toBeNull(); + }); }); diff --git a/tests/pages/profile.test.tsx b/tests/pages/profile.test.tsx index a24976c..fd92bad 100644 --- a/tests/pages/profile.test.tsx +++ b/tests/pages/profile.test.tsx @@ -242,6 +242,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 +277,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(); diff --git a/tests/unit/Rule.test.jsx b/tests/unit/Rule.test.jsx index 7ec2b34..1e5347d 100644 --- a/tests/unit/Rule.test.jsx +++ b/tests/unit/Rule.test.jsx @@ -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( + , + ); + + 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(); diff --git a/tests/unit/clearBrowserRuleData.test.ts b/tests/unit/clearBrowserRuleData.test.ts new file mode 100644 index 0000000..4b329ae --- /dev/null +++ b/tests/unit/clearBrowserRuleData.test.ts @@ -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(); + }); +}); diff --git a/tests/unit/guestRuleClaim.test.ts b/tests/unit/guestRuleClaim.test.ts index 5a17ed8..c05a197 100644 --- a/tests/unit/guestRuleClaim.test.ts +++ b/tests/unit/guestRuleClaim.test.ts @@ -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); diff --git a/tests/unit/lastPublishedRule.test.ts b/tests/unit/lastPublishedRule.test.ts index 37997d3..f37866d 100644 --- a/tests/unit/lastPublishedRule.test.ts +++ b/tests/unit/lastPublishedRule.test.ts @@ -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(); + }); +}); diff --git a/tests/unit/userMeDeleteRoute.test.ts b/tests/unit/userMeDeleteRoute.test.ts index 4d72134..98c86ef 100644 --- a/tests/unit/userMeDeleteRoute.test.ts +++ b/tests/unit/userMeDeleteRoute.test.ts @@ -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(() => { From d576ed81d964ee75676e08d977bc3abb97b25f01 Mon Sep 17 00:00:00 2001 From: adilallo <39313955+adilallo@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:49:09 -0700 Subject: [PATCH 02/10] Load the finished Rule itself on Edit, and ask before replacing a draft in progress. --- app/(app)/create/CreateFlowLayoutClient.tsx | 32 ++++++-- lib/create/beginEditingPublishedRule.ts | 64 ++++++++++++++++ messages/en/create/topNav.json | 4 + tests/unit/beginEditingPublishedRule.test.ts | 78 ++++++++++++++++++++ 4 files changed, 171 insertions(+), 7 deletions(-) create mode 100644 lib/create/beginEditingPublishedRule.ts create mode 100644 tests/unit/beginEditingPublishedRule.test.ts diff --git a/app/(app)/create/CreateFlowLayoutClient.tsx b/app/(app)/create/CreateFlowLayoutClient.tsx index c41097f..57e86c6 100644 --- a/app/(app)/create/CreateFlowLayoutClient.tsx +++ b/app/(app)/create/CreateFlowLayoutClient.tsx @@ -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); @@ -889,6 +895,7 @@ function CreateFlowLayoutContent({ backdropVariant="blurredYellow" ariaLabel={messages.create.topNav.leaveConfirmTitle} /> + {confirmDialog} { - 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 } diff --git a/lib/create/beginEditingPublishedRule.ts b/lib/create/beginEditingPublishedRule.ts new file mode 100644 index 0000000..fb5ca4c --- /dev/null +++ b/lib/create/beginEditingPublishedRule.ts @@ -0,0 +1,64 @@ +import type { CreateFlowState } from "../../app/(app)/create/types"; +import { createFlowStateHasKeys } from "./draftHydrationUtils"; +import { 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(","); +} + +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; + for (const key of PUBLISHED_CUSTOM_RULE_SELECTION_KEYS) { + if (sortedIds(state[key]) !== sortedIds(patch[key])) 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), + }; +} diff --git a/messages/en/create/topNav.json b/messages/en/create/topNav.json index 913b8bc..904d076 100644 --- a/messages/en/create/topNav.json +++ b/messages/en/create/topNav.json @@ -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", diff --git a/tests/unit/beginEditingPublishedRule.test.ts b/tests/unit/beginEditingPublishedRule.test.ts new file mode 100644 index 0000000..449587f --- /dev/null +++ b/tests/unit/beginEditingPublishedRule.test.ts @@ -0,0 +1,78 @@ +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); + }); +}); + +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([]); + }); +}); From d31045b0e5bd31431e1445ad547d6ea0a14b4f45 Mon Sep 17 00:00:00 2001 From: adilallo <39313955+adilallo@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:50:06 -0700 Subject: [PATCH 03/10] Keep the browser draft on screen after Save your progress, including when the save link is dead. --- .../create/context/CreateFlowContext.tsx | 19 ++--- .../create/utils/anonymousDraftStorage.ts | 10 +++ app/components/modals/Login/LoginForm.tsx | 2 + tests/components/LoginForm.test.tsx | 35 +++++++++- tests/contexts/CreateFlowContext.test.tsx | 70 ++++++++++++++++++- tests/unit/anonymousDraftStorage.test.ts | 17 +++++ 6 files changed, 141 insertions(+), 12 deletions(-) diff --git a/app/(app)/create/context/CreateFlowContext.tsx b/app/(app)/create/context/CreateFlowContext.tsx index 8aba4a0..17af270 100644 --- a/app/(app)/create/context/CreateFlowContext.tsx +++ b/app/(app)/create/context/CreateFlowContext.tsx @@ -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(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); diff --git a/app/(app)/create/utils/anonymousDraftStorage.ts b/app/(app)/create/utils/anonymousDraftStorage.ts index 627e014..60341df 100644 --- a/app/(app)/create/utils/anonymousDraftStorage.ts +++ b/app/(app)/create/utils/anonymousDraftStorage.ts @@ -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; diff --git a/app/components/modals/Login/LoginForm.tsx b/app/components/modals/Login/LoginForm.tsx index a8c8dfd..420c818 100644 --- a/app/components/modals/Login/LoginForm.tsx +++ b/app/components/modals/Login/LoginForm.tsx @@ -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]); diff --git a/tests/components/LoginForm.test.tsx b/tests/components/LoginForm.test.tsx index 2483c44..43650bb 100644 --- a/tests/components/LoginForm.test.tsx +++ b/tests/components/LoginForm.test.tsx @@ -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(); diff --git a/tests/contexts/CreateFlowContext.test.tsx b/tests/contexts/CreateFlowContext.test.tsx index 5f9a653..f6b6e4a 100644 --- a/tests/contexts/CreateFlowContext.test.tsx +++ b/tests/contexts/CreateFlowContext.test.tsx @@ -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() {
{state.methodSectionsPinCommitted?.communication ? "yes" : "no"}
+
+ {(state.selectedCommunitySizeIds ?? []).join(",")} +
+
+ {(state.selectedOrganizationTypeIds ?? []).join(",")} +
+
+ {(state.selectedMaturityIds ?? []).join(",")} +
); } @@ -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( + + + , + ); + rerender( + + + , + ); + + 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; + expect(stored.title).toBe("Juniper Street Tenants Union"); + expect(stored.selectedCommunitySizeIds).toEqual(["thirteenToOneHundred"]); + expect(stored.selectedOrganizationTypeIds).toEqual(["housing"]); + expect(stored.selectedMaturityIds).toEqual(["forming"]); + }); + }); +}); diff --git a/tests/unit/anonymousDraftStorage.test.ts b/tests/unit/anonymousDraftStorage.test.ts index a96a293..60294ef 100644 --- a/tests/unit/anonymousDraftStorage.test.ts +++ b/tests/unit/anonymousDraftStorage.test.ts @@ -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\"}", + ); + }); +}); From a846169960419a67222bb3eed3b62881258887af Mon Sep 17 00:00:00 2001 From: adilallo <39313955+adilallo@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:51:21 -0700 Subject: [PATCH 04/10] Resume the draft from Create rule instead of deleting it. --- .../create/hooks/useCreateFlowNavigation.ts | 8 +++ app/(app)/create/utils/createRuleEntry.ts | 26 +++++++++ app/(app)/profile/ProfilePageClient.tsx | 5 +- .../navigation/Top/Top.container.tsx | 14 ++--- .../HeroBanner/HeroBanner.container.tsx | 25 ++------- .../sections/YourTurn/YourTurn.container.tsx | 25 ++------- docs/create-flow.md | 12 ++--- tests/components/Top.test.tsx | 21 ++++---- tests/unit/createRuleEntry.test.ts | 54 +++++++++++++++++++ 9 files changed, 119 insertions(+), 71 deletions(-) create mode 100644 app/(app)/create/utils/createRuleEntry.ts create mode 100644 tests/unit/createRuleEntry.test.ts diff --git a/app/(app)/create/hooks/useCreateFlowNavigation.ts b/app/(app)/create/hooks/useCreateFlowNavigation.ts index e7d7e41..778291d 100644 --- a/app/(app)/create/hooks/useCreateFlowNavigation.ts +++ b/app/(app)/create/hooks/useCreateFlowNavigation.ts @@ -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 ( diff --git a/app/(app)/create/utils/createRuleEntry.ts b/app/(app)/create/utils/createRuleEntry.ts new file mode 100644 index 0000000..0bb4e06 --- /dev/null +++ b/app/(app)/create/utils/createRuleEntry.ts @@ -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(["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; +} diff --git a/app/(app)/profile/ProfilePageClient.tsx b/app/(app)/profile/ProfilePageClient.tsx index a5293f6..be93235 100644 --- a/app/(app)/profile/ProfilePageClient.tsx +++ b/app/(app)/profile/ProfilePageClient.tsx @@ -40,7 +40,7 @@ import type { CreateFlowStep } from "../create/types"; import { clearAnonymousCreateFlowStorage } from "../create/utils/anonymousDraftStorage"; import { clearBrowserRuleData } from "../create/utils/clearBrowserRuleData"; import { clearCoreValueDetailsLocalStorage } from "../create/utils/coreValueDetailsLocalStorage"; -import { prepareFreshCreateFlowEntrySync } from "../create/utils/prepareFreshCreateFlowEntry"; +import { createRuleEntryPath } from "../create/utils/createRuleEntry"; import { createFlowStepPath } from "../create/utils/createFlowPaths"; import { useMediaQuery } from "../../hooks/useMediaQuery"; import { @@ -310,8 +310,7 @@ export default function ProfilePageClient() { }, [draft, router]); const handleStartNewCustomRule = useCallback(() => { - prepareFreshCreateFlowEntrySync({ signedIn: true }); - router.push("/create/informational"); + router.push(createRuleEntryPath()); }, [router]); const handleRequestDeleteDraft = useCallback(() => { diff --git a/app/components/navigation/Top/Top.container.tsx b/app/components/navigation/Top/Top.container.tsx index d847933..28fa8ff 100644 --- a/app/components/navigation/Top/Top.container.tsx +++ b/app/components/navigation/Top/Top.container.tsx @@ -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( /** * `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); diff --git a/app/components/sections/HeroBanner/HeroBanner.container.tsx b/app/components/sections/HeroBanner/HeroBanner.container.tsx index 6805c4e..b665d01 100644 --- a/app/components/sections/HeroBanner/HeroBanner.container.tsx +++ b/app/components/sections/HeroBanner/HeroBanner.container.tsx @@ -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( 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(() => { const groups = messages.heroBanner.ruleCard.categories; diff --git a/app/components/sections/YourTurn/YourTurn.container.tsx b/app/components/sections/YourTurn/YourTurn.container.tsx index 1f0095f..6b1ced1 100644 --- a/app/components/sections/YourTurn/YourTurn.container.tsx +++ b/app/components/sections/YourTurn/YourTurn.container.tsx @@ -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 ( <> diff --git a/docs/create-flow.md b/docs/create-flow.md index 697ba9b..04d76ce 100644 --- a/docs/create-flow.md +++ b/docs/create-flow.md @@ -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. +- **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`. 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. +- **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. Direct template picks still call it today; replacing a draft from a template is a separate confirm. -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 still use **`prepareFreshCreateFlowEntry`** until that confirm ships. --- @@ -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. --- diff --git a/tests/components/Top.test.tsx b/tests/components/Top.test.tsx index 34b82bb..31a95cf 100644 --- a/tests/components/Top.test.tsx +++ b/tests/components/Top.test.tsx @@ -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", () => { diff --git a/tests/unit/createRuleEntry.test.ts b/tests/unit/createRuleEntry.test.ts new file mode 100644 index 0000000..29ea7b1 --- /dev/null +++ b/tests/unit/createRuleEntry.test.ts @@ -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"); + }); +}); From a2815ae05fea11911336bc2277ed1930bc62c219 Mon Sep 17 00:00:00 2001 From: adilallo <39313955+adilallo@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:56:38 -0700 Subject: [PATCH 05/10] Keep every picked card on the finished Rule, and wait for its words before Continue. --- .../screens/review/FinalReviewScreen.tsx | 23 ++- .../create/utils/createFlowFooterLabels.ts | 14 +- lib/create/buildPublishPayload.ts | 34 ++-- lib/create/finalReviewChipPresets.ts | 19 ++- lib/create/finalReviewChipWarnings.ts | 136 +++++++++++++-- lib/create/methodCardWizardPrefill.ts | 2 +- .../normalizePublishedDocumentForEdit.ts | 40 +---- .../publishedDocumentToDisplaySections.ts | 12 +- .../ruleSectionsFromMethodSelections.ts | 7 +- .../create/reviewAndComplete/finalReview.json | 4 + tests/components/FinalReviewPage.test.tsx | 8 + tests/unit/buildPublishPayload.test.ts | 28 ++-- tests/unit/finalReviewContinue.test.ts | 158 +++++++++++++++++- ...publishedDocumentToDisplaySections.test.ts | 5 +- tests/unit/ruleInviteCardMeta.test.ts | 31 ++++ .../ruleSectionsFromMethodSelections.test.ts | 10 ++ 16 files changed, 417 insertions(+), 114 deletions(-) diff --git a/app/(app)/create/screens/review/FinalReviewScreen.tsx b/app/(app)/create/screens/review/FinalReviewScreen.tsx index e4e084a..bd313dc 100644 --- a/app/(app)/create/screens/review/FinalReviewScreen.tsx +++ b/app/(app)/create/screens/review/FinalReviewScreen.tsx @@ -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 ? ( + + ) : null} {bindingArbitrationNeedsSeparateYes(state) ? ( { + 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), + ), + ); } /** diff --git a/lib/create/buildPublishPayload.ts b/lib/create/buildPublishPayload.ts index 55db1db..a733b95 100644 --- a/lib/create/buildPublishPayload.ts +++ b/lib/create/buildPublishPayload.ts @@ -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 } : {}), }; }); diff --git a/lib/create/finalReviewChipPresets.ts b/lib/create/finalReviewChipPresets.ts index bf97fba..d120cc8 100644 --- a/lib/create/finalReviewChipPresets.ts +++ b/lib/create/finalReviewChipPresets.ts @@ -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, diff --git a/lib/create/finalReviewChipWarnings.ts b/lib/create/finalReviewChipWarnings.ts index aa1e7c5..c04f7a6 100644 --- a/lib/create/finalReviewChipWarnings.ts +++ b/lib/create/finalReviewChipWarnings.ts @@ -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, + 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; +} diff --git a/lib/create/methodCardWizardPrefill.ts b/lib/create/methodCardWizardPrefill.ts index 4eefee8..4fd7d70 100644 --- a/lib/create/methodCardWizardPrefill.ts +++ b/lib/create/methodCardWizardPrefill.ts @@ -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); diff --git a/lib/create/normalizePublishedDocumentForEdit.ts b/lib/create/normalizePublishedDocumentForEdit.ts index f31ea9e..fc128bb 100644 --- a/lib/create/normalizePublishedDocumentForEdit.ts +++ b/lib/create/normalizePublishedDocumentForEdit.ts @@ -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, - id: string, -): Record { - switch (groupKey) { - case "communication": - return { ...communicationPresetFor(id) } as Record; - case "membership": - return { ...membershipPresetFor(id) } as Record; - case "decisionApproaches": - return { ...decisionApproachPresetFor(id) } as Record; - case "conflictManagement": - return { ...conflictManagementPresetFor(id) } as Record; - } -} - function sectionsRecordFromEntry( entry: CommunityRuleSection["entries"][number], groupKey: Exclude, - presetId: string, ): Record { 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) { diff --git a/lib/create/publishedDocumentToDisplaySections.ts b/lib/create/publishedDocumentToDisplaySections.ts index 452b914..ebb07be 100644 --- a/lib/create/publishedDocumentToDisplaySections.ts +++ b/lib/create/publishedDocumentToDisplaySections.ts @@ -80,7 +80,6 @@ const CM_LABELS: Record = { 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; - 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); diff --git a/lib/create/ruleSectionsFromMethodSelections.ts b/lib/create/ruleSectionsFromMethodSelections.ts index fc1b469..a24b327 100644 --- a/lib/create/ruleSectionsFromMethodSelections.ts +++ b/lib/create/ruleSectionsFromMethodSelections.ts @@ -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[], diff --git a/messages/en/create/reviewAndComplete/finalReview.json b/messages/en/create/reviewAndComplete/finalReview.json index 59a6508..f5440f6 100644 --- a/messages/en/create/reviewAndComplete/finalReview.json +++ b/messages/en/create/reviewAndComplete/finalReview.json @@ -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", diff --git a/tests/components/FinalReviewPage.test.tsx b/tests/components/FinalReviewPage.test.tsx index 9cffcba..f8f2f72 100644 --- a/tests/components/FinalReviewPage.test.tsx +++ b/tests/components/FinalReviewPage.test.tsx @@ -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 () => { diff --git a/tests/unit/buildPublishPayload.test.ts b/tests/unit/buildPublishPayload.test.ts index d7c92f8..b87bcdd 100644 --- a/tests/unit/buildPublishPayload.test.ts +++ b/tests/unit/buildPublishPayload.test.ts @@ -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", () => { diff --git a/tests/unit/finalReviewContinue.test.ts b/tests/unit/finalReviewContinue.test.ts index 2351fcf..dc7edf8 100644 --- a/tests/unit/finalReviewContinue.test.ts +++ b/tests/unit/finalReviewContinue.test.ts @@ -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", () => { diff --git a/tests/unit/publishedDocumentToDisplaySections.test.ts b/tests/unit/publishedDocumentToDisplaySections.test.ts index 7a38a7b..3836ef1 100644 --- a/tests/unit/publishedDocumentToDisplaySections.test.ts +++ b/tests/unit/publishedDocumentToDisplaySections.test.ts @@ -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", () => { diff --git a/tests/unit/ruleInviteCardMeta.test.ts b/tests/unit/ruleInviteCardMeta.test.ts index 2470ef2..1934e83 100644 --- a/tests/unit/ruleInviteCardMeta.test.ts +++ b/tests/unit/ruleInviteCardMeta.test.ts @@ -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", () => { diff --git a/tests/unit/ruleSectionsFromMethodSelections.test.ts b/tests/unit/ruleSectionsFromMethodSelections.test.ts index 28069d4..08212e3 100644 --- a/tests/unit/ruleSectionsFromMethodSelections.test.ts +++ b/tests/unit/ruleSectionsFromMethodSelections.test.ts @@ -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( From 851133e56d1b9ae2a597dbaab4bb03eac1ebdb23 Mon Sep 17 00:00:00 2001 From: adilallo <39313955+adilallo@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:01:56 -0700 Subject: [PATCH 06/10] Turn a saved draft into the finished Rule, and greet with congratulations. --- .../create/hooks/useCreateFlowFinalize.ts | 9 ++- app/(app)/create/utils/flowSteps.ts | 9 +++ app/(app)/profile/ProfilePageClient.tsx | 14 +---- app/api/drafts/me/route.ts | 11 +--- app/api/rules/route.ts | 15 +++++ lib/server/ruleDrafts.ts | 14 +++++ tests/pages/profile.test.tsx | 11 ++++ tests/unit/flowSteps.test.ts | 9 +++ .../unit/hooks/useCreateFlowFinalize.test.tsx | 11 +++- tests/unit/ruleDrafts.test.ts | 58 +++++++++++++++++++ tests/unit/rulesPublishPostRoute.test.ts | 12 ++++ 11 files changed, 150 insertions(+), 23 deletions(-) create mode 100644 lib/server/ruleDrafts.ts create mode 100644 tests/unit/ruleDrafts.test.ts diff --git a/app/(app)/create/hooks/useCreateFlowFinalize.ts b/app/(app)/create/hooks/useCreateFlowFinalize.ts index 8962f8d..670e088 100644 --- a/app/(app)/create/hooks/useCreateFlowFinalize.ts +++ b/app/(app)/create/hooks/useCreateFlowFinalize.ts @@ -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"; @@ -150,6 +154,7 @@ export function useCreateFlowFinalize({ document: ruleDocument, }); updateState({ editingPublishedRuleId: undefined }); + void deleteServerDraft(); router.push(createFlowStepPath("completed")); return; } @@ -203,6 +208,8 @@ export function useCreateFlowFinalize({ if (isGuest) { writePendingKeepRuleLogin(); onGuestPublished?.({ skippedInvites: skippedGuestInvites }); + } else { + void deleteServerDraft(); } router.push( createFlowStepPath("completed", { diff --git a/app/(app)/create/utils/flowSteps.ts b/app/(app)/create/utils/flowSteps.ts index 504a111..c6bd232 100644 --- a/app/(app)/create/utils/flowSteps.ts +++ b/app/(app)/create/utils/flowSteps.ts @@ -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/...`). diff --git a/app/(app)/profile/ProfilePageClient.tsx b/app/(app)/profile/ProfilePageClient.tsx index be93235..d759e90 100644 --- a/app/(app)/profile/ProfilePageClient.tsx +++ b/app/(app)/profile/ProfilePageClient.tsx @@ -33,10 +33,8 @@ 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 { clearBrowserRuleData } from "../create/utils/clearBrowserRuleData"; import { clearCoreValueDetailsLocalStorage } from "../create/utils/coreValueDetailsLocalStorage"; @@ -48,14 +46,6 @@ import { ProfilePageView, } from "./_components/ProfilePage.view"; -function resolveContinueStepState( - state: { currentStep?: CreateFlowStep } & Record, -): 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(); @@ -303,7 +293,7 @@ export default function ProfilePageClient() { const handleContinueDraft = useCallback(() => { if (draft == null || !draft.hasDraft) return; - const step = resolveContinueStepState(draft.state); + const step = resumeCreateFlowStep(draft.state); clearAnonymousCreateFlowStorage(); clearCoreValueDetailsLocalStorage(); router.push(`/create/${step}`); diff --git a/app/api/drafts/me/route.ts b/app/api/drafts/me/route.ts index e5fed6c..f575ed9 100644 --- a/app/api/drafts/me/route.ts +++ b/app/api/drafts/me/route.ts @@ -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 }); }); diff --git a/app/api/rules/route.ts b/app/api/rules/route.ts index 4e207cc..6e9a963 100644 --- a/app/api/rules/route.ts +++ b/app/api/rules/route.ts @@ -35,6 +35,7 @@ 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; @@ -170,6 +171,13 @@ export const POST = apiRoute( document, userId: user.id, }); + try { + await deleteRuleDraftForUser(user.id); + } catch (err) { + logRouteError("rules.publish", requestId, err, { + phase: "deleteRuleDraftForUser", + }); + } return NextResponse.json({ rule: { @@ -261,6 +269,13 @@ export const POST = apiRoute( document, userId: user.id, }); + try { + await deleteRuleDraftForUser(user.id); + } catch (err) { + logRouteError("rules.publish", requestId, err, { + phase: "deleteRuleDraftForUser", + }); + } return NextResponse.json({ rule: { diff --git a/lib/server/ruleDrafts.ts b/lib/server/ruleDrafts.ts new file mode 100644 index 0000000..0300f28 --- /dev/null +++ b/lib/server/ruleDrafts.ts @@ -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 { + const draft = await prisma.ruleDraft.findUnique({ + where: { userId }, + select: { id: true }, + }); + if (draft) { + await deleteUploadsForDraft(draft.id); + } + await prisma.ruleDraft.deleteMany({ where: { userId } }); +} diff --git a/tests/pages/profile.test.tsx b/tests/pages/profile.test.tsx index fd92bad..02af657 100644 --- a/tests/pages/profile.test.tsx +++ b/tests/pages/profile.test.tsx @@ -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(); @@ -343,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(); }); }); diff --git a/tests/unit/flowSteps.test.ts b/tests/unit/flowSteps.test.ts index 6edf967..80f3925 100644 --- a/tests/unit/flowSteps.test.ts +++ b/tests/unit/flowSteps.test.ts @@ -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); }); diff --git a/tests/unit/hooks/useCreateFlowFinalize.test.tsx b/tests/unit/hooks/useCreateFlowFinalize.test.tsx index 6934b21..a10f69e 100644 --- a/tests/unit/hooks/useCreateFlowFinalize.test.tsx +++ b/tests/unit/hooks/useCreateFlowFinalize.test.tsx @@ -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(undefined); vi.mocked(writeLastPublishedRule).mockReset(); vi.mocked(stateWithPendingCommunityAvatar).mockReset(); vi.mocked(stateWithPendingCommunityAvatar).mockImplementation( @@ -101,6 +108,7 @@ describe("useCreateFlowFinalize", () => { expect( sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY), ).toBeNull(); + expect(deleteServerDraft).toHaveBeenCalledTimes(1); }); it("does not publish while the session is unresolved", async () => { @@ -408,6 +416,7 @@ describe("useCreateFlowFinalize", () => { summary: "Published summary", document: {}, }); + expect(deleteServerDraft).toHaveBeenCalledTimes(1); expect(updateState).toHaveBeenCalledWith({ editingPublishedRuleId: undefined, }); diff --git a/tests/unit/ruleDrafts.test.ts b/tests/unit/ruleDrafts.test.ts new file mode 100644 index 0000000..9b0ae5a --- /dev/null +++ b/tests/unit/ruleDrafts.test.ts @@ -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" }, + }); + }); +}); diff --git a/tests/unit/rulesPublishPostRoute.test.ts b/tests/unit/rulesPublishPostRoute.test.ts index 992e49d..d59676d 100644 --- a/tests/unit/rulesPublishPostRoute.test.ts +++ b/tests/unit/rulesPublishPostRoute.test.ts @@ -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) => @@ -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,7 @@ describe("POST /api/rules", () => { ).toBeUndefined(); expect(issueGuestRuleClaimCookieMock).not.toHaveBeenCalled(); expect(sendInviteMock).not.toHaveBeenCalled(); + expect(deleteRuleDraftForUserMock).toHaveBeenCalledWith("user-1"); }); it("stores place and group type from the published document", async () => { @@ -196,6 +205,7 @@ describe("POST /api/rules", () => { }), ); expect(publishedRuleCreateMock).not.toHaveBeenCalled(); + expect(deleteRuleDraftForUserMock).toHaveBeenCalledWith("user-1"); }); it("rolls back publish when mail fails", async () => { @@ -238,6 +248,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 () => { @@ -329,6 +340,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 () => { From 55b071aa83f4e31e73973b31716b60d292384fcb Mon Sep 17 00:00:00 2001 From: adilallo <39313955+adilallo@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:08:34 -0700 Subject: [PATCH 07/10] Open a template from its cards even when a saved draft exists. --- app/(app)/create/CreateFlowLayoutClient.tsx | 22 ++- app/(app)/create/SignedInDraftHydration.tsx | 12 +- .../create/hooks/useTemplateReviewActions.ts | 187 +++++++++--------- .../utils/prepareFreshCreateFlowEntry.ts | 30 +++ .../profile/_components/ProfilePage.view.tsx | 4 +- lib/create/applyTemplatePrefill.ts | 70 +++++++ messages/en/create/templateReview.json | 6 + tests/pages/profile.test.tsx | 2 +- tests/unit/applyTemplatePrefill.test.ts | 26 +++ .../hooks/useTemplateReviewActions.test.tsx | 84 ++++---- .../unit/prepareFreshCreateFlowEntry.test.ts | 23 +++ 11 files changed, 326 insertions(+), 140 deletions(-) diff --git a/app/(app)/create/CreateFlowLayoutClient.tsx b/app/(app)/create/CreateFlowLayoutClient.tsx index 57e86c6..9ef3388 100644 --- a/app/(app)/create/CreateFlowLayoutClient.tsx +++ b/app/(app)/create/CreateFlowLayoutClient.tsx @@ -336,6 +336,8 @@ function CreateFlowLayoutContent({ replaceState, router, fromCreateWizard, + signedIn: Boolean(sessionUser), + requestConfirm, markCreateFlowInteraction, }); const isCreateTemplatesPickerRoute = @@ -901,15 +903,25 @@ function CreateFlowLayoutContent({ 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} diff --git a/app/(app)/create/SignedInDraftHydration.tsx b/app/(app)/create/SignedInDraftHydration.tsx index edf431a..bceb6cc 100644 --- a/app/(app)/create/SignedInDraftHydration.tsx +++ b/app/(app)/create/SignedInDraftHydration.tsx @@ -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. diff --git a/app/(app)/create/hooks/useTemplateReviewActions.ts b/app/(app)/create/hooks/useTemplateReviewActions.ts index 3098a4d..da11bcd 100644 --- a/app/(app)/create/hooks/useTemplateReviewActions.ts +++ b/app/(app)/create/hooks/useTemplateReviewActions.ts @@ -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[] | 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[]; +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 { + 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; 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 => { + 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, ]); diff --git a/app/(app)/create/utils/prepareFreshCreateFlowEntry.ts b/app/(app)/create/utils/prepareFreshCreateFlowEntry.ts index 8b917dc..78e8292 100644 --- a/app/(app)/create/utils/prepareFreshCreateFlowEntry.ts +++ b/app/(app)/create/utils/prepareFreshCreateFlowEntry.ts @@ -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 { diff --git a/app/(app)/profile/_components/ProfilePage.view.tsx b/app/(app)/profile/_components/ProfilePage.view.tsx index 41f34cb..a793dd3 100644 --- a/app/(app)/profile/_components/ProfilePage.view.tsx +++ b/app/(app)/profile/_components/ProfilePage.view.tsx @@ -258,7 +258,7 @@ export function ProfilePageView({ id: "create-template", title: t("optionCreateTemplate"), description: "", - href: "/templates?fromFlow=1", + href: "/templates", leadingIcon: "content_copy", showDescription: false, }, @@ -356,7 +356,7 @@ export function ProfilePageView({ createLabel={t("emptyCardCreate")} browseLabel={t("emptyCardBrowse")} onCreate={onStartNewCustomRule} - browseHref="/templates?fromFlow=1" + browseHref="/templates" /> ) : (
diff --git a/lib/create/applyTemplatePrefill.ts b/lib/create/applyTemplatePrefill.ts index b610c3e..16318f4 100644 --- a/lib/create/applyTemplatePrefill.ts +++ b/lib/create/applyTemplatePrefill.ts @@ -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[] | 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[]; +} + +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; +} diff --git a/messages/en/create/templateReview.json b/messages/en/create/templateReview.json index fe2bd29..1b729f3 100644 --- a/messages/en/create/templateReview.json +++ b/messages/en/create/templateReview.json @@ -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", diff --git a/tests/pages/profile.test.tsx b/tests/pages/profile.test.tsx index 02af657..b489191 100644 --- a/tests/pages/profile.test.tsx +++ b/tests/pages/profile.test.tsx @@ -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 }), diff --git a/tests/unit/applyTemplatePrefill.test.ts b/tests/unit/applyTemplatePrefill.test.ts index e37de5d..cc335a0 100644 --- a/tests/unit/applyTemplatePrefill.test.ts +++ b/tests/unit/applyTemplatePrefill.test.ts @@ -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({ diff --git a/tests/unit/hooks/useTemplateReviewActions.test.tsx b/tests/unit/hooks/useTemplateReviewActions.test.tsx index c13a5c4..dd7c1de 100644 --- a/tests/unit/hooks/useTemplateReviewActions.test.tsx +++ b/tests/unit/hooks/useTemplateReviewActions.test.tsx @@ -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(); + }); }); diff --git a/tests/unit/prepareFreshCreateFlowEntry.test.ts b/tests/unit/prepareFreshCreateFlowEntry.test.ts index 3653f73..0814614 100644 --- a/tests/unit/prepareFreshCreateFlowEntry.test.ts +++ b/tests/unit/prepareFreshCreateFlowEntry.test.ts @@ -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(); From f634a91bb24f836c057103379b4f1e8b9a961cb8 Mon Sep 17 00:00:00 2001 From: adilallo <39313955+adilallo@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:08:35 -0700 Subject: [PATCH 08/10] Keep a draft when opening a template from the catalog, instead of deleting it on click. --- app/(marketing)/templates/TemplatesPageClient.tsx | 11 +---------- .../sections/RuleStack/RuleStack.container.tsx | 5 ----- docs/create-flow.md | 12 ++++++------ 3 files changed, 7 insertions(+), 21 deletions(-) diff --git a/app/(marketing)/templates/TemplatesPageClient.tsx b/app/(marketing)/templates/TemplatesPageClient.tsx index ced6626..40f3a4d 100644 --- a/app/(marketing)/templates/TemplatesPageClient.tsx +++ b/app/(marketing)/templates/TemplatesPageClient.tsx @@ -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 }); - } - }} /> ); } diff --git a/app/components/sections/RuleStack/RuleStack.container.tsx b/app/components/sections/RuleStack/RuleStack.container.tsx index fc4b3ed..a4ca689 100644 --- a/app/components/sections/RuleStack/RuleStack.container.tsx +++ b/app/components/sections/RuleStack/RuleStack.container.tsx @@ -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( } } 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 ( diff --git a/docs/create-flow.md b/docs/create-flow.md index 04d76ce..b623328 100644 --- a/docs/create-flow.md +++ b/docs/create-flow.md @@ -66,9 +66,9 @@ The step persists **`stakeholderEmails`** on `CreateFlowState` (validated on `PU - **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`. 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. -- **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. Direct template picks still call it today; replacing a draft from a template is a separate confirm. +- **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 **`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 still use **`prepareFreshCreateFlowEntry`** until that confirm ships. +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,15 +91,15 @@ 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. From 54a4871ad105f623b55493c73bfe941a5d9be588 Mon Sep 17 00:00:00 2001 From: adilallo <39313955+adilallo@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:10:44 -0700 Subject: [PATCH 09/10] Show the remade card names on template detail, matching final review, and say one size fits all. --- .../TemplateReviewCard/TemplateReviewCard.tsx | 12 +- lib/create/templateReviewMapping.ts | 135 +++++++++++++++++- messages/en/create/templateReview.json | 2 +- tests/unit/templateReviewMapping.test.ts | 115 +++++++++++++++ 4 files changed, 256 insertions(+), 8 deletions(-) diff --git a/app/components/cards/TemplateReviewCard/TemplateReviewCard.tsx b/app/components/cards/TemplateReviewCard/TemplateReviewCard.tsx index 63871e9..78390f6 100644 --- a/app/components/cards/TemplateReviewCard/TemplateReviewCard.tsx +++ b/app/components/cards/TemplateReviewCard/TemplateReviewCard.tsx @@ -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); diff --git a/lib/create/templateReviewMapping.ts b/lib/create/templateReviewMapping.ts index 8448606..c471b45 100644 --- a/lib/create/templateReviewMapping.ts +++ b/lib/create/templateReviewMapping.ts @@ -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; + +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, + 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). */ diff --git a/messages/en/create/templateReview.json b/messages/en/create/templateReview.json index 1b729f3..94d5448 100644 --- a/messages/en/create/templateReview.json +++ b/messages/en/create/templateReview.json @@ -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", diff --git a/tests/unit/templateReviewMapping.test.ts b/tests/unit/templateReviewMapping.test.ts index a0a0f66..1987171 100644 --- a/tests/unit/templateReviewMapping.test.ts +++ b/tests/unit/templateReviewMapping.test.ts @@ -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 }).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", + ); + }); +}); From 7c0876609292b83ef2fbff927f891557b9817b72 Mon Sep 17 00:00:00 2001 From: adilallo <39313955+adilallo@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:31:07 -0700 Subject: [PATCH 10/10] Keep a continued draft on screen, ask before Edit drops rewritten copy, and retry clearing the draft after publish. --- .../create/hooks/useCreateFlowFinalize.ts | 13 ++- .../utils/seedContinuedDraftLocalStorage.ts | 21 +++++ app/(app)/profile/ProfilePageClient.tsx | 7 +- app/api/rules/route.ts | 41 ++++++---- docs/create-flow.md | 4 +- lib/create/api.ts | 15 ++-- lib/create/beginEditingPublishedRule.ts | 80 +++++++++++++++++-- tests/unit/beginEditingPublishedRule.test.ts | 60 ++++++++++++++ .../unit/hooks/useCreateFlowFinalize.test.tsx | 30 ++++++- tests/unit/rulesPublishPostRoute.test.ts | 61 ++++++++++++-- .../seedContinuedDraftLocalStorage.test.ts | 70 ++++++++++++++++ 11 files changed, 361 insertions(+), 41 deletions(-) create mode 100644 app/(app)/create/utils/seedContinuedDraftLocalStorage.ts create mode 100644 tests/unit/seedContinuedDraftLocalStorage.test.ts diff --git a/app/(app)/create/hooks/useCreateFlowFinalize.ts b/app/(app)/create/hooks/useCreateFlowFinalize.ts index 670e088..c9691b6 100644 --- a/app/(app)/create/hooks/useCreateFlowFinalize.ts +++ b/app/(app)/create/hooks/useCreateFlowFinalize.ts @@ -18,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 { + for (let attempt = 0; attempt < DRAFT_DELETE_ATTEMPTS; attempt += 1) { + if (await deleteServerDraft()) return; + } +} + type AppRouterLike = { push: (_href: string) => void }; type OpenLogin = (args: { @@ -154,7 +163,7 @@ export function useCreateFlowFinalize({ document: ruleDocument, }); updateState({ editingPublishedRuleId: undefined }); - void deleteServerDraft(); + void deleteServerDraftAfterPublish(); router.push(createFlowStepPath("completed")); return; } @@ -209,7 +218,7 @@ export function useCreateFlowFinalize({ writePendingKeepRuleLogin(); onGuestPublished?.({ skippedInvites: skippedGuestInvites }); } else { - void deleteServerDraft(); + void deleteServerDraftAfterPublish(); } router.push( createFlowStepPath("completed", { diff --git a/app/(app)/create/utils/seedContinuedDraftLocalStorage.ts b/app/(app)/create/utils/seedContinuedDraftLocalStorage.ts new file mode 100644 index 0000000..4e2b62c --- /dev/null +++ b/app/(app)/create/utils/seedContinuedDraftLocalStorage.ts @@ -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(); +} diff --git a/app/(app)/profile/ProfilePageClient.tsx b/app/(app)/profile/ProfilePageClient.tsx index d759e90..4c99f77 100644 --- a/app/(app)/profile/ProfilePageClient.tsx +++ b/app/(app)/profile/ProfilePageClient.tsx @@ -37,9 +37,9 @@ import { } from "../create/utils/flowSteps"; import { clearAnonymousCreateFlowStorage } from "../create/utils/anonymousDraftStorage"; import { clearBrowserRuleData } from "../create/utils/clearBrowserRuleData"; -import { clearCoreValueDetailsLocalStorage } from "../create/utils/coreValueDetailsLocalStorage"; 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, @@ -294,9 +294,8 @@ export default function ProfilePageClient() { const handleContinueDraft = useCallback(() => { if (draft == null || !draft.hasDraft) return; const step = resumeCreateFlowStep(draft.state); - clearAnonymousCreateFlowStorage(); - clearCoreValueDetailsLocalStorage(); - router.push(`/create/${step}`); + seedContinuedDraftLocalStorage(draft.state); + router.push(createFlowStepPath(step)); }, [draft, router]); const handleStartNewCustomRule = useCallback(() => { diff --git a/app/api/rules/route.ts b/app/api/rules/route.ts index 6e9a963..912b3cb 100644 --- a/app/api/rules/route.ts +++ b/app/api/rules/route.ts @@ -40,6 +40,31 @@ 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 { + 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() ?? @@ -171,13 +196,7 @@ export const POST = apiRoute( document, userId: user.id, }); - try { - await deleteRuleDraftForUser(user.id); - } catch (err) { - logRouteError("rules.publish", requestId, err, { - phase: "deleteRuleDraftForUser", - }); - } + await deleteDraftAfterPublish(user.id, requestId); return NextResponse.json({ rule: { @@ -269,13 +288,7 @@ export const POST = apiRoute( document, userId: user.id, }); - try { - await deleteRuleDraftForUser(user.id); - } catch (err) { - logRouteError("rules.publish", requestId, err, { - phase: "deleteRuleDraftForUser", - }); - } + await deleteDraftAfterPublish(user.id, requestId); return NextResponse.json({ rule: { diff --git a/docs/create-flow.md b/docs/create-flow.md index b623328..bba8f07 100644 --- a/docs/create-flow.md +++ b/docs/create-flow.md @@ -65,7 +65,7 @@ The step persists **`stakeholderEmails`** on `CreateFlowState` (validated on `PU **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`. - **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`. 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. +- **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 **`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. @@ -101,7 +101,7 @@ From that page, **Customize** opens a dialog for name, optional logo, descriptio 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). diff --git a/lib/create/api.ts b/lib/create/api.ts index cfa01c6..fc974ed 100644 --- a/lib/create/api.ts +++ b/lib/create/api.ts @@ -164,19 +164,20 @@ async function errorBodyMessage(res: Response): Promise { } /** - * 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 { +export async function deleteServerDraft(): Promise { 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; } } diff --git a/lib/create/beginEditingPublishedRule.ts b/lib/create/beginEditingPublishedRule.ts index fb5ca4c..4659fcf 100644 --- a/lib/create/beginEditingPublishedRule.ts +++ b/lib/create/beginEditingPublishedRule.ts @@ -1,6 +1,9 @@ import type { CreateFlowState } from "../../app/(app)/create/types"; import { createFlowStateHasKeys } from "./draftHydrationUtils"; -import { PUBLISHED_CUSTOM_RULE_SELECTION_KEYS } from "./customRuleFacets"; +import { + CUSTOM_RULE_FACETS, + PUBLISHED_CUSTOM_RULE_SELECTION_KEYS, +} from "./customRuleFacets"; import type { StoredLastPublishedRule } from "./lastPublishedRule"; import { createFlowStateFromPublishedRule, @@ -17,19 +20,86 @@ function sortedIds(value: unknown): string { .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; + const out: Record = {}; + 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() : ""; + 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; } diff --git a/tests/unit/beginEditingPublishedRule.test.ts b/tests/unit/beginEditingPublishedRule.test.ts index 449587f..d8af360 100644 --- a/tests/unit/beginEditingPublishedRule.test.ts +++ b/tests/unit/beginEditingPublishedRule.test.ts @@ -63,6 +63,66 @@ describe("publishedRuleEditWouldReplaceDraft", () => { }; 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", () => { diff --git a/tests/unit/hooks/useCreateFlowFinalize.test.tsx b/tests/unit/hooks/useCreateFlowFinalize.test.tsx index a10f69e..2f2bf3d 100644 --- a/tests/unit/hooks/useCreateFlowFinalize.test.tsx +++ b/tests/unit/hooks/useCreateFlowFinalize.test.tsx @@ -56,7 +56,7 @@ describe("useCreateFlowFinalize", () => { vi.mocked(publishRule).mockReset(); vi.mocked(updatePublishedRule).mockReset(); vi.mocked(deleteServerDraft).mockReset(); - vi.mocked(deleteServerDraft).mockResolvedValue(undefined); + vi.mocked(deleteServerDraft).mockResolvedValue(true); vi.mocked(writeLastPublishedRule).mockReset(); vi.mocked(stateWithPendingCommunityAvatar).mockReset(); vi.mocked(stateWithPendingCommunityAvatar).mockImplementation( @@ -111,6 +111,34 @@ describe("useCreateFlowFinalize", () => { 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 () => { const { result } = renderHook(() => useCreateFlowFinalize({ diff --git a/tests/unit/rulesPublishPostRoute.test.ts b/tests/unit/rulesPublishPostRoute.test.ts index d59676d..2983924 100644 --- a/tests/unit/rulesPublishPostRoute.test.ts +++ b/tests/unit/rulesPublishPostRoute.test.ts @@ -123,6 +123,60 @@ describe("POST /api/rules", () => { 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 () => { publishedRuleCreateMock.mockResolvedValueOnce({ id: "rule-counts", @@ -259,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, - ) => { + async (fn: (tx: { publishedRule: { create: typeof vi.fn }; ruleStakeholder: { create: typeof vi.fn } }) => Promise) => { const tx = { publishedRule: { create: vi.fn().mockResolvedValue(created), diff --git a/tests/unit/seedContinuedDraftLocalStorage.test.ts b/tests/unit/seedContinuedDraftLocalStorage.test.ts new file mode 100644 index 0000000..62106a5 --- /dev/null +++ b/tests/unit/seedContinuedDraftLocalStorage.test.ts @@ -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", + }); + }); +});