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();