Open a template from its cards even when a saved draft exists.

This commit is contained in:
adilallo committed 2026-11-22 18:08:34 -07:00
1 parent 851133e56d
commit 55b071aa83
11 files changed
+326 -140

No files matched your search

+17 -5
View File
@@ -336,6 +336,8 @@ function CreateFlowLayoutContent({
replaceState, replaceState,
router, router,
fromCreateWizard, fromCreateWizard,
signedIn: Boolean(sessionUser),
requestConfirm,
markCreateFlowInteraction, markCreateFlowInteraction,
}); });
const isCreateTemplatesPickerRoute = const isCreateTemplatesPickerRoute =
@@ -901,15 +903,25 @@ function CreateFlowLayoutContent({
templateTitle={customizeDialog?.templateTitle ?? ""} templateTitle={customizeDialog?.templateTitle ?? ""}
valuesCount={customizeDialog?.valuesCount ?? 0} valuesCount={customizeDialog?.valuesCount ?? 0}
cardsCount={customizeDialog?.cardsCount ?? 0} cardsCount={customizeDialog?.cardsCount ?? 0}
initialTitle={typeof state.title === "string" ? state.title : ""} initialTitle={
fromCreateWizard && state.templateReviewEntryFromCreateFlow === true
? typeof state.title === "string"
? state.title
: ""
: ""
}
initialDescription={ initialDescription={
typeof state.communityContext === "string" fromCreateWizard && state.templateReviewEntryFromCreateFlow === true
? state.communityContext ? typeof state.communityContext === "string"
? state.communityContext
: ""
: "" : ""
} }
initialLocation={ initialLocation={
typeof state.communityLocation === "string" fromCreateWizard && state.templateReviewEntryFromCreateFlow === true
? state.communityLocation ? typeof state.communityLocation === "string"
? state.communityLocation
: ""
: "" : ""
} }
onClose={closeCustomizeDialog} onClose={closeCustomizeDialog}
+11 -1
View File
@@ -21,7 +21,11 @@ import {
isCreateFlowTemplatesPickerPath, isCreateFlowTemplatesPickerPath,
parseCreateFlowScreenFromPathname, parseCreateFlowScreenFromPathname,
} from "./utils/flowSteps"; } from "./utils/flowSteps";
import { hasFreshEntryPending } from "./utils/prepareFreshCreateFlowEntry"; import {
hasFreshEntryPending,
hasTemplateApplyLatch,
clearTemplateApplyLatch,
} from "./utils/prepareFreshCreateFlowEntry";
import { isBackendSyncEnabled } from "../../../lib/create/backendSyncEnabled"; import { isBackendSyncEnabled } from "../../../lib/create/backendSyncEnabled";
@@ -94,6 +98,12 @@ export function SignedInDraftHydration({
return; return;
} }
if (hasTemplateApplyLatch()) {
finishedUserIdRef.current = userId;
clearTemplateApplyLatch();
return;
}
// Local draft wins over server: no fetch, no replaceState. The provider // Local draft wins over server: no fetch, no replaceState. The provider
// already hydrated from localStorage at mount, so the user sees their // already hydrated from localStorage at mount, so the user sees their
// unsaved keystrokes immediately. // unsaved keystrokes immediately.
@@ -2,19 +2,25 @@
import { useCallback, useMemo, useState } from "react"; import { useCallback, useMemo, useState } from "react";
import { import {
buildTemplateCustomizePrefill, buildAppliedTemplateCreateFlowState,
templatePresetDetailsFromPrefill, sectionsFromTemplateBody,
} from "../../../../lib/create/applyTemplatePrefill"; } from "../../../../lib/create/applyTemplatePrefill";
import { fetchDraftFromServer } from "../../../../lib/create/api";
import { createFlowStateHasKeys } from "../../../../lib/create/draftHydrationUtils";
import { loadTemplateReviewBySlug } from "../../../../lib/create/loadTemplateReviewBySlug"; 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 { templateChipCounts } from "../../../../lib/create/templatePath";
import messages from "../../../../messages/en/index"; import messages from "../../../../messages/en/index";
import type { AsyncConfirmOptions } from "../../../hooks/useAsyncConfirm";
import type { import type {
CreateFlowContextValue, CreateFlowContextValue,
CreateFlowState, CreateFlowState,
} from "../types"; } from "../types";
import { hasBrowserCreateFlowDraft } from "../utils/createRuleEntry";
import { createFlowStepPath } from "../utils/createFlowPaths"; import { createFlowStepPath } from "../utils/createFlowPaths";
import {
latchTemplateApply,
prepareFreshCreateFlowEntrySync,
} from "../utils/prepareFreshCreateFlowEntry";
type AppRouterLike = { push: (_href: string) => void }; type AppRouterLike = { push: (_href: string) => void };
type UpdateState = CreateFlowContextValue["updateState"]; type UpdateState = CreateFlowContextValue["updateState"];
@@ -61,13 +67,27 @@ export type UseTemplateReviewActionsResult = {
confirmCustomizeDialog: (_fields: TemplateCustomizeFields) => void; confirmCustomizeDialog: (_fields: TemplateCustomizeFields) => void;
}; };
function sectionsFromTemplateBody( const TEMPLATE_NAV_KEYS = new Set([
body: unknown, "templateReviewEntryFromCreateFlow",
): Record<string, unknown>[] | null { "templateReviewBackSlug",
if (!body || typeof body !== "object" || Array.isArray(body)) return null; "pendingTemplateAction",
const sectionsRaw = (body as { sections?: unknown }).sections; "currentStep",
if (!Array.isArray(sectionsRaw) || sectionsRaw.length === 0) return null; "methodSectionsPinCommitted",
return sectionsRaw as Record<string, unknown>[]; ]);
function createFlowStateLooksLikeProgress(state: CreateFlowState): boolean {
return Object.keys(state).some((key) => !TEMPLATE_NAV_KEYS.has(key));
}
async function hasDraftToReplace(
state: CreateFlowState,
signedIn: boolean,
): Promise<boolean> {
if (createFlowStateLooksLikeProgress(state)) return true;
if (hasBrowserCreateFlowDraft()) return true;
if (!signedIn) return false;
const server = await fetchDraftFromServer();
return server != null && createFlowStateHasKeys(server);
} }
/** /**
@@ -86,10 +106,11 @@ function sectionsFromTemplateBody(
export function useTemplateReviewActions({ export function useTemplateReviewActions({
pathname, pathname,
state, state,
updateState,
replaceState, replaceState,
router, router,
fromCreateWizard = false, fromCreateWizard = false,
signedIn = false,
requestConfirm,
markCreateFlowInteraction, markCreateFlowInteraction,
}: { }: {
pathname: string | null | undefined; pathname: string | null | undefined;
@@ -103,6 +124,8 @@ export function useTemplateReviewActions({
* draft title must not count as “community steps already done”. * draft title must not count as “community steps already done”.
*/ */
fromCreateWizard?: boolean; fromCreateWizard?: boolean;
signedIn?: boolean;
requestConfirm?: (_opts: AsyncConfirmOptions) => Promise<boolean>;
markCreateFlowInteraction: () => void; markCreateFlowInteraction: () => void;
}): UseTemplateReviewActionsResult { }): UseTemplateReviewActionsResult {
const [isApplyingTemplate, setIsApplyingTemplate] = useState(false); const [isApplyingTemplate, setIsApplyingTemplate] = useState(false);
@@ -121,10 +144,26 @@ export function useTemplateReviewActions({
pathname?.includes("/create/review-template/"), pathname?.includes("/create/review-template/"),
); );
const keepInFlowIdentity =
fromCreateWizard && state.templateReviewEntryFromCreateFlow === true;
const confirmReplaceDraft = useCallback(async (): Promise<boolean> => {
if (!requestConfirm) return true;
if (!(await hasDraftToReplace(state, signedIn))) return true;
const copy = messages.create.templateReview.replaceDraft;
return requestConfirm({
title: copy.title,
description: copy.description,
proceedText: copy.proceed,
cancelText: copy.cancel,
});
}, [requestConfirm, signedIn, state]);
const handleCustomize = useCallback(async () => { const handleCustomize = useCallback(async () => {
if (!templateReviewSlug) return; if (!templateReviewSlug) return;
markCreateFlowInteraction(); markCreateFlowInteraction();
setTemplateReviewApplyError(null); setTemplateReviewApplyError(null);
if (!(await confirmReplaceDraft())) return;
setIsApplyingTemplate(true); setIsApplyingTemplate(true);
const loaded = await loadTemplateReviewBySlug(templateReviewSlug); const loaded = await loadTemplateReviewBySlug(templateReviewSlug);
setIsApplyingTemplate(false); setIsApplyingTemplate(false);
@@ -140,7 +179,11 @@ export function useTemplateReviewActions({
valuesCount: counts?.values ?? 0, valuesCount: counts?.values ?? 0,
cardsCount: counts?.cards ?? 0, cardsCount: counts?.cards ?? 0,
}); });
}, [markCreateFlowInteraction, templateReviewSlug]); }, [
confirmReplaceDraft,
markCreateFlowInteraction,
templateReviewSlug,
]);
const closeCustomizeDialog = useCallback(() => { const closeCustomizeDialog = useCallback(() => {
setCustomizeDialog(null); setCustomizeDialog(null);
@@ -150,44 +193,29 @@ export function useTemplateReviewActions({
(fields: TemplateCustomizeFields) => { (fields: TemplateCustomizeFields) => {
if (!customizeDialog) return; if (!customizeDialog) return;
markCreateFlowInteraction(); markCreateFlowInteraction();
const prefill = buildTemplateCustomizePrefill( prepareFreshCreateFlowEntrySync({ signedIn });
customizeDialog.body, latchTemplateApply();
customizeDialog.slug, replaceState(() =>
); buildAppliedTemplateCreateFlowState({
const details = templatePresetDetailsFromPrefill(prefill);
const pinPatch = methodSectionsPinsForHydratedSelections(prefill);
const title = fields.title.trim();
const communityContext = fields.communityContext.trim();
const communityLocation = fields.communityLocation.trim();
updateState({
...prefill,
...details,
title: title.length > 0 ? title : undefined,
communityContext:
communityContext.length > 0 ? communityContext : undefined,
summary: communityContext.length > 0 ? communityContext : undefined,
communityLocation:
communityLocation.length > 0 ? communityLocation : undefined,
methodSectionsPinCommitted: {
...state.methodSectionsPinCommitted,
...pinPatch,
},
templateReviewBackSlug: customizeDialog.slug,
setupTraits: undefined,
pendingTemplateAction: {
slug: customizeDialog.slug, slug: customizeDialog.slug,
body: customizeDialog.body,
mode: "customize", mode: "customize",
}, identity: {
}); title: fields.title,
communityContext: fields.communityContext,
communityLocation: fields.communityLocation,
},
}),
);
setCustomizeDialog(null); setCustomizeDialog(null);
router.push(createFlowStepPath("core-values")); router.push(createFlowStepPath("core-values"));
}, },
[ [
customizeDialog, customizeDialog,
markCreateFlowInteraction, markCreateFlowInteraction,
replaceState,
router, router,
state.methodSectionsPinCommitted, signedIn,
updateState,
], ],
); );
@@ -195,6 +223,7 @@ export function useTemplateReviewActions({
if (!templateReviewSlug) return; if (!templateReviewSlug) return;
markCreateFlowInteraction(); markCreateFlowInteraction();
setTemplateReviewApplyError(null); setTemplateReviewApplyError(null);
if (!(await confirmReplaceDraft())) return;
setIsApplyingTemplate(true); setIsApplyingTemplate(true);
const loaded = await loadTemplateReviewBySlug(templateReviewSlug); const loaded = await loadTemplateReviewBySlug(templateReviewSlug);
setIsApplyingTemplate(false); setIsApplyingTemplate(false);
@@ -211,63 +240,33 @@ export function useTemplateReviewActions({
return; return;
} }
replaceState((prev) => { prepareFreshCreateFlowEntrySync({ signedIn });
const base = stripCustomRuleSelectionFields(prev); latchTemplateApply();
const customizePrefill = buildTemplateCustomizePrefill( replaceState(() =>
template.body, buildAppliedTemplateCreateFlowState({
templateReviewSlug ?? undefined, slug: templateReviewSlug,
); body: template.body,
const details = templatePresetDetailsFromPrefill(customizePrefill); mode: "useWithoutChanges",
const hasValuesSeed = identity: keepInFlowIdentity
customizePrefill.selectedCoreValueIds !== undefined; ? {
title: state.title,
const sectionsWithoutValues = hasValuesSeed communityContext: state.communityContext,
? sections.filter((s) => { communityLocation: state.communityLocation,
const name = (s as { categoryName?: unknown }).categoryName; }
if (typeof name !== "string") return true; : undefined,
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,
};
});
router.push(createFlowStepPath("final-review")); router.push(createFlowStepPath("final-review"));
}, [ }, [
fromCreateWizard, confirmReplaceDraft,
keepInFlowIdentity,
markCreateFlowInteraction, markCreateFlowInteraction,
replaceState, replaceState,
router, router,
state.communityContext,
state.communityLocation,
signedIn,
state.title,
templateReviewSlug, templateReviewSlug,
]); ]);
@@ -11,6 +11,9 @@ import { isBackendSyncEnabled } from "../../../../lib/create/backendSyncEnabled"
*/ */
export const FRESH_ENTRY_PENDING_KEY = "create:fresh-entry-pending"; 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 = { export type PrepareFreshCreateFlowEntryOptions = {
/** /**
* When `true`, and backend sync is on, also `DELETE /api/drafts/me`. * 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 { function setFreshEntryPending(): void {
if (typeof window === "undefined") return; if (typeof window === "undefined") return;
try { try {
@@ -258,7 +258,7 @@ export function ProfilePageView({
id: "create-template", id: "create-template",
title: t("optionCreateTemplate"), title: t("optionCreateTemplate"),
description: "", description: "",
href: "/templates?fromFlow=1", href: "/templates",
leadingIcon: "content_copy", leadingIcon: "content_copy",
showDescription: false, showDescription: false,
}, },
@@ -356,7 +356,7 @@ export function ProfilePageView({
createLabel={t("emptyCardCreate")} createLabel={t("emptyCardCreate")}
browseLabel={t("emptyCardBrowse")} browseLabel={t("emptyCardBrowse")}
onCreate={onStartNewCustomRule} onCreate={onStartNewCustomRule}
browseHref="/templates?fromFlow=1" browseHref="/templates"
/> />
) : ( ) : (
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
+70
View File
@@ -12,6 +12,7 @@ import {
decisionApproachPresetFor, decisionApproachPresetFor,
membershipPresetFor, membershipPresetFor,
} from "./finalReviewChipPresets"; } from "./finalReviewChipPresets";
import { methodSectionsPinsForHydratedSelections } from "./publishedDocumentToCreateFlowState";
import { import {
templateChipsForSlug, templateChipsForSlug,
type TemplateChipSet, type TemplateChipSet,
@@ -223,3 +224,72 @@ export function templatePresetDetailsFromPrefill(
coreValueDetailsByChipId, coreValueDetailsByChipId,
}; };
} }
export function sectionsFromTemplateBody(
body: unknown,
): Record<string, unknown>[] | null {
if (!body || typeof body !== "object" || Array.isArray(body)) return null;
const sectionsRaw = (body as { sections?: unknown }).sections;
if (!Array.isArray(sectionsRaw) || sectionsRaw.length === 0) return null;
return sectionsRaw as Record<string, unknown>[];
}
export type TemplateApplyIdentity = {
title?: string;
communityContext?: string;
communityLocation?: string;
};
/**
* Fresh wizard state for a template. Does not spread a previous draft, so a
* leftover logo, setup answers, or another community's cards cannot ride along.
*/
export function buildAppliedTemplateCreateFlowState(args: {
slug: string;
body: unknown;
mode: "customize" | "useWithoutChanges";
identity?: TemplateApplyIdentity;
}): CreateFlowState {
const prefill = buildTemplateCustomizePrefill(args.body, args.slug);
const details = templatePresetDetailsFromPrefill(prefill);
const pinPatch = methodSectionsPinsForHydratedSelections(prefill);
const title = args.identity?.title?.trim();
const communityContext = args.identity?.communityContext?.trim();
const communityLocation = args.identity?.communityLocation?.trim();
const seeded: CreateFlowState = {
...prefill,
...details,
methodSectionsPinCommitted: pinPatch,
templateReviewBackSlug: args.slug,
pendingTemplateAction: {
slug: args.slug,
mode: args.mode,
},
};
if (title) seeded.title = title;
if (communityContext) {
seeded.communityContext = communityContext;
seeded.summary = communityContext;
}
if (communityLocation) seeded.communityLocation = communityLocation;
if (args.identity) seeded.templateReviewEntryFromCreateFlow = true;
if (args.mode === "useWithoutChanges") {
const sections = sectionsFromTemplateBody(args.body);
if (sections) {
const hasValuesSeed = seeded.selectedCoreValueIds !== undefined;
seeded.sections = hasValuesSeed
? sections.filter((section) => {
const name = (section as { categoryName?: unknown }).categoryName;
if (typeof name !== "string") return true;
const key = name.toLowerCase().replace(/[^a-z]+/g, "");
return key !== "values" && key !== "corevalues";
})
: sections;
}
}
return seeded;
}
+6
View File
@@ -12,6 +12,12 @@
"notFound": "This template was not found.", "notFound": "This template was not found.",
"applyFailed": "Something went wrong. Please try again." "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…", "loading": "Loading template…",
"chipDetailModal": { "chipDetailModal": {
"closeButton": "Close", "closeButton": "Close",
+1 -1
View File
@@ -121,7 +121,7 @@ describe("ProfilePageView", () => {
expect(screen.getByText(copy.emptyCardBody)).toBeInTheDocument(); expect(screen.getByText(copy.emptyCardBody)).toBeInTheDocument();
expect( expect(
screen.getByRole("link", { name: copy.emptyCardBrowse }), screen.getByRole("link", { name: copy.emptyCardBrowse }),
).toHaveAttribute("href", "/templates?fromFlow=1"); ).toHaveAttribute("href", "/templates");
await user.click( await user.click(
screen.getByRole("button", { name: copy.emptyCardCreate }), screen.getByRole("button", { name: copy.emptyCardCreate }),
+26
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { import {
buildAppliedTemplateCreateFlowState,
buildCoreValuesPrefillFromTemplateBody, buildCoreValuesPrefillFromTemplateBody,
buildTemplateCustomizePrefill, buildTemplateCustomizePrefill,
templatePresetDetailsFromPrefill, 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", () => { describe("templatePresetDetailsFromPrefill", () => {
it("fills catalog copy for each prefilled chip", () => { it("fills catalog copy for each prefilled chip", () => {
const details = templatePresetDetailsFromPrefill({ const details = templatePresetDetailsFromPrefill({
@@ -35,10 +35,15 @@ describe("useTemplateReviewActions", () => {
const router = { push: vi.fn() }; const router = { push: vi.fn() };
const updateState = vi.fn(); const updateState = vi.fn();
const markCreateFlowInteraction = vi.fn(); const markCreateFlowInteraction = vi.fn();
const requestConfirm = vi.fn();
let applied: CreateFlowState | undefined; let applied: CreateFlowState | undefined;
const replaceState = vi.fn( const replaceState = vi.fn(
(updater: (_prev: CreateFlowState) => CreateFlowState) => { (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(); router.push.mockReset();
updateState.mockReset(); updateState.mockReset();
markCreateFlowInteraction.mockReset(); markCreateFlowInteraction.mockReset();
requestConfirm.mockReset();
requestConfirm.mockResolvedValue(true);
replaceState.mockClear(); replaceState.mockClear();
applied = undefined; applied = undefined;
window.sessionStorage.clear();
window.localStorage.clear();
}); });
function renderActions( function renderActions(
@@ -64,6 +73,7 @@ describe("useTemplateReviewActions", () => {
replaceState, replaceState,
router, router,
fromCreateWizard, fromCreateWizard,
requestConfirm,
markCreateFlowInteraction, 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({ const { result } = renderActions({
setupTraits: { employer: true }, setupTraits: { employer: true },
communityAvatarUrl: "/old.png",
}); });
await act(async () => { await act(async () => {
@@ -103,32 +114,19 @@ describe("useTemplateReviewActions", () => {
}); });
expect(router.push).toHaveBeenCalledWith("/create/core-values"); expect(router.push).toHaveBeenCalledWith("/create/core-values");
expect(updateState).toHaveBeenCalledWith( expect(applied?.title).toBe("Neighborhood");
expect.objectContaining({ expect(applied?.communityContext).toBe("We meet weekly");
title: "Neighborhood", expect(applied?.communityLocation).toBe("Oakland");
communityContext: "We meet weekly", expect(applied?.communityAvatarUrl).toBeUndefined();
communityLocation: "Oakland", expect(applied?.setupTraits).toBeUndefined();
setupTraits: undefined, expect(applied?.pendingTemplateAction).toEqual({
pendingTemplateAction: { slug: "mutual-aid-mondays",
slug: "mutual-aid-mondays", mode: "customize",
mode: "customize", });
}, expect(applied?.templateReviewBackSlug).toBe("mutual-aid-mondays");
templateReviewBackSlug: "mutual-aid-mondays",
}),
);
}); });
it("direct Use without changes goes to final review and clears leftover identity", async () => { 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" }); const { result } = renderActions({ title: "Neighborhood" });
await act(async () => { await act(async () => {
@@ -138,8 +136,9 @@ describe("useTemplateReviewActions", () => {
expect(router.push).toHaveBeenCalledWith("/create/final-review"); expect(router.push).toHaveBeenCalledWith("/create/final-review");
expect(applied?.title).toBeUndefined(); expect(applied?.title).toBeUndefined();
expect(applied?.communityContext).toBeUndefined(); expect(applied?.communityContext).toBeUndefined();
expect(applied?.currentStep).toBeUndefined(); expect(applied?.communityAvatarUrl).toBeUndefined();
expect(applied?.setupTraits).toBeUndefined(); expect(applied?.setupTraits).toBeUndefined();
expect(applied?.currentStep).toBeUndefined();
expect(applied?.pendingTemplateAction).toEqual({ expect(applied?.pendingTemplateAction).toEqual({
slug: "mutual-aid-mondays", slug: "mutual-aid-mondays",
mode: "useWithoutChanges", mode: "useWithoutChanges",
@@ -147,18 +146,12 @@ describe("useTemplateReviewActions", () => {
}); });
it("in-flow Use without changes keeps the community name and pins the template path", async () => { it("in-flow Use without changes keeps the community name and pins the template path", async () => {
replaceState.mockImplementation(
(updater: (_prev: CreateFlowState) => CreateFlowState) => {
applied = updater({
title: "Neighborhood",
communityContext: "We meet weekly",
templateReviewEntryFromCreateFlow: true,
setupTraits: { employer: true },
});
},
);
const { result } = renderActions( const { result } = renderActions(
{ title: "Neighborhood", templateReviewEntryFromCreateFlow: true }, {
title: "Neighborhood",
communityContext: "We meet weekly",
templateReviewEntryFromCreateFlow: true,
},
true, true,
); );
@@ -176,4 +169,21 @@ describe("useTemplateReviewActions", () => {
}); });
expect(applied?.templateReviewBackSlug).toBe("mutual-aid-mondays"); 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();
});
}); });
@@ -1,7 +1,11 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { import {
FRESH_ENTRY_PENDING_KEY, FRESH_ENTRY_PENDING_KEY,
TEMPLATE_APPLY_LATCH_KEY,
clearTemplateApplyLatch,
hasFreshEntryPending, hasFreshEntryPending,
hasTemplateApplyLatch,
latchTemplateApply,
prepareFreshCreateFlowEntry, prepareFreshCreateFlowEntry,
prepareFreshCreateFlowEntrySync, prepareFreshCreateFlowEntrySync,
} from "../../app/(app)/create/utils/prepareFreshCreateFlowEntry"; } 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", () => { describe("prepareFreshCreateFlowEntry", () => {
beforeEach(() => { beforeEach(() => {
deleteServerDraft.mockReset(); deleteServerDraft.mockReset();