Keep finished Rules and drafts from overwriting each other #114
No files matched your search
@@ -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 (
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { createFlowStateHasKeys } from "../../../../lib/create/draftHydrationUtils";
|
||||
import type { CreateFlowStep } from "../types";
|
||||
import { readAnonymousCreateFlowState } from "./anonymousDraftStorage";
|
||||
import { CREATE_ROUTES, createFlowStepPath } from "./createFlowPaths";
|
||||
import { readCoreValueDetailsFromLocalStorage } from "./coreValueDetailsLocalStorage";
|
||||
import { isValidStep } from "./flowSteps";
|
||||
|
||||
const NON_RESUME_STEPS = new Set<CreateFlowStep>(["completed", "edit-rule"]);
|
||||
|
||||
export function hasBrowserCreateFlowDraft(): boolean {
|
||||
if (createFlowStateHasKeys(readAnonymousCreateFlowState())) return true;
|
||||
return Object.keys(readCoreValueDetailsFromLocalStorage()).length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Path for header / Home / Profile **Create rule**. Never clears the browser
|
||||
* draft or `DELETE`s `/api/drafts/me` — resume where the draft was left.
|
||||
*/
|
||||
export function createRuleEntryPath(): string {
|
||||
const local = readAnonymousCreateFlowState();
|
||||
const step = local.currentStep;
|
||||
if (isValidStep(step) && !NON_RESUME_STEPS.has(step)) {
|
||||
return createFlowStepPath(step);
|
||||
}
|
||||
return CREATE_ROUTES.createFirstStep;
|
||||
}
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -15,7 +15,7 @@ import AvatarContainer from "../../asset/AvatarContainer";
|
||||
import Avatar from "../../asset/Avatar";
|
||||
import { getAssetPath, ASSETS } from "../../../../lib/assetUtils";
|
||||
import { PRODUCTION_SITE_ORIGIN, websiteJsonLd } from "../../../../lib/siteMetadata";
|
||||
import { prepareFreshCreateFlowEntrySync } from "../../../(app)/create/utils/prepareFreshCreateFlowEntry";
|
||||
import { createRuleEntryPath } from "../../../(app)/create/utils/createRuleEntry";
|
||||
import { TopView } from "./Top.view";
|
||||
import type { TopProps } from "./Top.types";
|
||||
|
||||
@@ -59,16 +59,12 @@ const TopContainer = memo<TopProps>(
|
||||
|
||||
/**
|
||||
* `Top` is hidden on `/create` routes by ConditionalNavigationClient, so
|
||||
* this button is always clicked from outside the wizard. Clears anonymous
|
||||
* `localStorage` synchronously and, when backend sync is on, fires the
|
||||
* server `DELETE /api/drafts/me` in the background. `SignedInDraftHydration`
|
||||
* reads the `create:fresh-entry-pending` sentinel and waits before fetching
|
||||
* (see {@link prepareFreshCreateFlowEntrySync}).
|
||||
* this button is always clicked from outside the wizard. Resume the draft
|
||||
* in the browser instead of wiping it.
|
||||
*/
|
||||
const handleCreateRuleClick = useCallback(() => {
|
||||
prepareFreshCreateFlowEntrySync({ signedIn: loggedIn });
|
||||
router.push("/create/informational");
|
||||
}, [loggedIn, router]);
|
||||
router.push(createRuleEntryPath());
|
||||
}, [router]);
|
||||
|
||||
const schemaData = websiteJsonLd(siteOrigin);
|
||||
|
||||
|
||||
@@ -4,11 +4,10 @@
|
||||
* Figma: "Section / Hero Banner" (18477:15473)
|
||||
*/
|
||||
|
||||
import { memo, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { memo, useCallback, useMemo } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useMessages, useTranslation } from "../../../contexts/MessagesContext";
|
||||
import { fetchAuthSession } from "../../../../lib/create/api";
|
||||
import { prepareFreshCreateFlowEntrySync } from "../../../(app)/create/utils/prepareFreshCreateFlowEntry";
|
||||
import { createRuleEntryPath } from "../../../(app)/create/utils/createRuleEntry";
|
||||
import type { Category } from "../../cards/Rule";
|
||||
import type { ChipOption } from "../../controls/MultiSelect/MultiSelect.types";
|
||||
import HeroBannerView from "./HeroBanner.view";
|
||||
@@ -28,26 +27,10 @@ const HeroBannerContainer = memo<HeroBannerProps>(
|
||||
const messages = useMessages();
|
||||
const tHome = useTranslation("pages.home.heroBanner");
|
||||
const tHero = useTranslation("heroBanner");
|
||||
const [signedIn, setSignedIn] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void fetchAuthSession()
|
||||
.then(({ user }) => {
|
||||
if (!cancelled) setSignedIn(Boolean(user));
|
||||
})
|
||||
.catch(() => {
|
||||
/* guest fallback */
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleCreateRule = useCallback(() => {
|
||||
prepareFreshCreateFlowEntrySync({ signedIn });
|
||||
router.push("/create/informational");
|
||||
}, [router, signedIn]);
|
||||
router.push(createRuleEntryPath());
|
||||
}, [router]);
|
||||
|
||||
const ruleCategories = useMemo<Category[]>(() => {
|
||||
const groups = messages.heroBanner.ruleCard.categories;
|
||||
|
||||
@@ -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 (
|
||||
<>
|
||||
|
||||
+6
-6
@@ -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.
|
||||
|
||||
---
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user