Keep finished Rules and drafts from overwriting each other #114

Merged
an.di merged 10 commits from adilallo/fix/CR-339-finish-drafts into main 2026-11-23 04:49:47 +00:00
17 changed files with 280 additions and 14 deletions
Showing only changes of commit 942c7cc9de - Show all commits

No files matched your search

@@ -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
}
}
+7
View File
@@ -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([]);
@@ -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}
/>
))}
</div>
@@ -449,7 +452,8 @@ export function ProfilePageView({
description={rule.summary ?? undefined}
expanded
size={ruleCardSize}
href={`/invite/${encodeURIComponent(rule.id)}`}
href={`/rules/${encodeURIComponent(rule.id)}`}
ariaLabel={rule.title}
communityInitials={communityInitialsFromTitle(
rule.title,
)}
+2
View File
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server";
import { isDatabaseConfigured } from "../../../../lib/server/env";
import { dbUnavailable } from "../../../../lib/server/responses";
import { clearGuestRuleClaimCookie } from "../../../../lib/server/guestRuleClaim";
import { destroySessionFromRequest } from "../../../../lib/server/session";
import { apiRoute } from "../../../../lib/server/apiRoute";
@@ -10,5 +11,6 @@ export const POST = apiRoute("auth.logout", async () => {
}
await destroySessionFromRequest();
await clearGuestRuleClaimCookie();
return NextResponse.json({ ok: true });
});
+2
View File
@@ -6,6 +6,7 @@ import {
internalError,
unauthorized,
} from "../../../../lib/server/responses";
import { clearGuestRuleClaimCookie } from "../../../../lib/server/guestRuleClaim";
import {
clearSessionCookie,
getSessionUser,
@@ -37,6 +38,7 @@ export const DELETE = apiRoute("user.me.delete", async () => {
}
await clearSessionCookie();
await clearGuestRuleClaimCookie();
return NextResponse.json({ ok: true });
});
+7 -2
View File
@@ -36,6 +36,7 @@ const RuleContainer = memo<RuleProps>(
className = "",
onClick,
href,
ariaLabel: ariaLabelProp,
expanded = false,
size: sizeProp,
categories,
@@ -67,7 +68,11 @@ const RuleContainer = memo<RuleProps>(
const size = sizeProp ?? "L";
const isInteractive = interactive ?? !hasBottomLinks;
const t = useTranslation("ruleCard");
const cardAriaLabel = t("ariaLabel")?.replace("{title}", title) || title;
const trimmedAriaLabel = ariaLabelProp?.trim() ?? "";
const cardAriaLabel =
trimmedAriaLabel.length > 0
? trimmedAriaLabel
: t("ariaLabel")?.replace("{title}", title) || title;
const recommendedLabel = t("recommendedLabel");
const handleClick = () => {
@@ -111,7 +116,7 @@ const RuleContainer = memo<RuleProps>(
icon={icon}
backgroundColor={backgroundColor}
className={className}
href={isInteractive && !hasBottomLinks ? href : undefined}
href={href}
onClick={isInteractive && !hasBottomLinks ? handleClick : undefined}
onKeyDown={
isInteractive && !hasBottomLinks && !href ? handleKeyDown : undefined
+8 -1
View File
@@ -56,9 +56,16 @@ export interface RuleProps {
onClick?: () => void;
/**
* When set, the card is a real link (focusable, Enter, open in a new tab)
* instead of a click-only `role="button"` surface.
* instead of a click-only `role="button"` surface. Combined with
* {@link hasBottomLinks}, the link is a stretched overlay so Invite /
* Duplicate / Delete stay separate controls.
*/
href?: string;
/**
* Accessible name for the card or its overlay link. Defaults to the
* `ruleCard` “Learn more about {title}…” string.
*/
ariaLabel?: string;
expanded?: boolean;
size?: RuleSizeValue;
categories?: Category[];
+25 -1
View File
@@ -298,6 +298,7 @@ export function RuleView({
<NavigationLink
key={link.id}
{...shared}
className={`${shared.className} pointer-events-auto relative z-10`}
href={link.href}
onClick={(e) => e.stopPropagation()}
/>
@@ -307,6 +308,7 @@ export function RuleView({
<NavigationLink
key={link.id}
{...shared}
className={`${shared.className} pointer-events-auto relative z-10`}
onClick={(e) => {
e.stopPropagation();
link.onClick?.();
@@ -319,7 +321,8 @@ export function RuleView({
const surfaceStyle = surfaceColor
? { backgroundColor: surfaceColor }
: undefined;
const isLinkCard = Boolean(href) && interactiveCard;
const isLinkCard = Boolean(href) && interactiveCard && !hasBottomLinks;
const overlayHref = hasBottomLinks && href ? href : undefined;
const hasCategories = Boolean(categories && categories.length > 0);
const expandedDescriptionFrameClass = [
@@ -610,6 +613,27 @@ export function RuleView({
);
}
if (overlayHref) {
return (
<div
className={`${cardClassName} cursor-pointer`}
style={surfaceStyle}
role="article"
>
<NextLink
href={overlayHref}
className="absolute inset-0 z-0 rounded-[inherit]"
aria-label={ariaLabel}
/>
<div
className={`relative z-[1] flex w-full flex-col items-start pointer-events-none ${cardGap}`}
>
{cardBody}
</div>
</div>
);
}
return (
<div
className={cardClassName}
+7 -2
View File
@@ -2,8 +2,8 @@ import type { CopiedNameHit } from "./copiedRuleDocument";
/**
* Bridges final-review → completed without query strings, and re-opens a rule
* from profile (`/create/completed?ruleId=…`) after GET /api/rules/[id]. Profile
* "Manage" links here; stakeholder "View" uses `/invite/[id]`.
* from profile (`/create/completed?ruleId=…`) after GET /api/rules/[id].
* Stakeholder cards on Profile open the reader page at `/rules/[id]`.
*/
export const CREATE_FLOW_LAST_PUBLISHED_KEY = "createFlow.lastPublished";
@@ -35,6 +35,11 @@ export function writeLastPublishedRule(data: StoredLastPublishedRule): void {
sessionStorage.setItem(CREATE_FLOW_LAST_PUBLISHED_KEY, JSON.stringify(data));
}
export function clearLastPublishedRule(): void {
if (typeof sessionStorage === "undefined") return;
sessionStorage.removeItem(CREATE_FLOW_LAST_PUBLISHED_KEY);
}
export function readLastPublishedRule(): StoredLastPublishedRule | null {
if (typeof sessionStorage === "undefined") return null;
const raw = sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY);
+1 -1
View File
@@ -61,7 +61,7 @@ export async function issueGuestRuleClaimCookie(token: string): Promise<void> {
);
}
async function clearGuestRuleClaimCookie(): Promise<void> {
export async function clearGuestRuleClaimCookie(): Promise<void> {
const store = await cookies();
store.set(GUEST_RULE_CLAIM_COOKIE_NAME, "", {
...cookieOptions(),
+63 -1
View File
@@ -1,6 +1,10 @@
import { useSearchParams } from "next/navigation";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders as render, screen } from "../utils/test-utils";
import {
renderWithProviders as render,
screen,
waitFor,
} from "../utils/test-utils";
import "@testing-library/jest-dom/vitest";
import { CompletedScreen } from "../../app/(app)/create/screens/completed/CompletedScreen";
import { CREATE_FLOW_LAST_PUBLISHED_KEY } from "../../lib/create/lastPublishedRule";
@@ -8,6 +12,14 @@ import {
CREATE_FLOW_COMPLETED_CELEBRATE_QUERY,
CREATE_FLOW_COMPLETED_CELEBRATE_VALUE,
} from "../../app/(app)/create/utils/flowSteps";
import { testRouter } from "../mocks/navigation";
const fetchPublishedRuleDetail = vi.hoisted(() => vi.fn());
vi.mock("../../lib/create/api", () => ({
fetchPublishedRuleDetail: (...args: unknown[]) =>
fetchPublishedRuleDetail(...args),
}));
const storedRuleFixture = {
id: "rule-fixture-1",
@@ -48,6 +60,8 @@ function mockSearchParams(record?: Record<string, string>) {
describe("CompletedScreen", () => {
beforeEach(() => {
sessionStorage.removeItem(CREATE_FLOW_LAST_PUBLISHED_KEY);
fetchPublishedRuleDetail.mockReset();
testRouter.replace.mockReset();
mockSearchParams();
});
@@ -165,4 +179,52 @@ describe("CompletedScreen", () => {
),
).toBe(true);
});
it("loads an owned Rule from ?ruleId= and stores it", async () => {
fetchPublishedRuleDetail.mockResolvedValue({
viewerIsOwner: true,
rule: {
id: "rule-owned",
title: "QA Tenants Union",
summary: "How we share the building.",
document: storedRuleFixture.document,
createdAt: "2026-11-01T00:00:00.000Z",
},
});
mockSearchParams({ ruleId: "rule-owned" });
render(<CompletedScreen />);
expect(
await screen.findByRole("heading", { name: "QA Tenants Union" }),
).toBeInTheDocument();
await waitFor(() => {
expect(testRouter.replace).toHaveBeenCalledWith("/create/completed");
});
const stored = JSON.parse(
sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY) ?? "null",
);
expect(stored).toMatchObject({
id: "rule-owned",
title: "QA Tenants Union",
});
});
it("sends a non-owner ?ruleId= load to the reader page", async () => {
fetchPublishedRuleDetail.mockResolvedValue({
viewerIsOwner: false,
rule: {
id: "rule-other",
title: "Someone else's Rule",
summary: null,
document: storedRuleFixture.document,
},
});
mockSearchParams({ ruleId: "rule-other" });
render(<CompletedScreen />);
await waitFor(() => {
expect(testRouter.replace).toHaveBeenCalledWith("/rules/rule-other");
});
expect(sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY)).toBeNull();
});
});
+5 -2
View File
@@ -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();
+19
View File
@@ -94,6 +94,25 @@ describe("Rule Component", () => {
expect(handleClick).toHaveBeenCalledTimes(1);
});
it("keeps bottom links and names the overlay link with ariaLabel", () => {
const onInvite = vi.fn();
render(
<Rule
{...defaultProps}
href="/create/completed?ruleId=rule-1"
ariaLabel="Garden coop"
hasBottomLinks
bottomLinks={[{ id: "invite", label: "Invite your members", onClick: onInvite }]}
/>,
);
expect(
screen.getByRole("link", { name: "Garden coop" }),
).toHaveAttribute("href", "/create/completed?ruleId=rule-1");
fireEvent.click(screen.getByRole("button", { name: "Invite your members" }));
expect(onInvite).toHaveBeenCalledTimes(1);
});
it("applies hover effects correctly", () => {
render(<Rule {...defaultProps} />);
+55
View File
@@ -0,0 +1,55 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { CREATE_FLOW_ANONYMOUS_KEY } from "../../app/(app)/create/utils/anonymousDraftStorage";
import { clearBrowserRuleData } from "../../app/(app)/create/utils/clearBrowserRuleData";
import { CORE_VALUE_DETAILS_STORAGE_KEY } from "../../app/(app)/create/utils/coreValueDetailsLocalStorage";
import { CREATE_FLOW_LAST_PUBLISHED_KEY } from "../../lib/create/lastPublishedRule";
import { CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY } from "../../lib/create/pendingKeepRuleLogin";
const deleteServerDraft = vi.fn();
vi.mock("../../lib/create/api", () => ({
deleteServerDraft: (...args: unknown[]) => deleteServerDraft(...args),
}));
describe("clearBrowserRuleData", () => {
beforeEach(() => {
deleteServerDraft.mockReset();
window.localStorage.clear();
window.sessionStorage.clear();
});
afterEach(() => {
window.localStorage.clear();
window.sessionStorage.clear();
});
it("clears local draft keys and lastPublished without deleting the server draft", () => {
window.localStorage.setItem(
CREATE_FLOW_ANONYMOUS_KEY,
JSON.stringify({ title: "Stale" }),
);
window.localStorage.setItem(
CORE_VALUE_DETAILS_STORAGE_KEY,
JSON.stringify({ v1: { meaning: "x" } }),
);
window.localStorage.setItem("create-flow-state", "{}");
window.localStorage.setItem("create-flow-draft", "{}");
window.sessionStorage.setItem(
CREATE_FLOW_LAST_PUBLISHED_KEY,
JSON.stringify({ id: "rule-1", title: "Garden", document: {} }),
);
window.sessionStorage.setItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY, "1");
clearBrowserRuleData();
expect(window.localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY)).toBeNull();
expect(window.localStorage.getItem(CORE_VALUE_DETAILS_STORAGE_KEY)).toBeNull();
expect(window.localStorage.getItem("create-flow-state")).toBeNull();
expect(window.localStorage.getItem("create-flow-draft")).toBeNull();
expect(window.sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY)).toBeNull();
expect(
window.sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY),
).toBeNull();
expect(deleteServerDraft).not.toHaveBeenCalled();
});
});
+16
View File
@@ -35,6 +35,7 @@ vi.mock("../../lib/logger", () => ({
import {
claimGuestRulesForUser,
clearGuestRuleClaimCookie,
issueGuestRuleClaimCookie,
} from "../../lib/server/guestRuleClaim";
@@ -76,6 +77,21 @@ describe("issueGuestRuleClaimCookie", () => {
});
});
describe("clearGuestRuleClaimCookie", () => {
it("expires the claim cookie", async () => {
await clearGuestRuleClaimCookie();
expect(cookieSetMock).toHaveBeenCalledWith(
"cr_rule_claim",
"",
expect.objectContaining({
httpOnly: true,
path: "/",
maxAge: 0,
}),
);
});
});
describe("claimGuestRulesForUser", () => {
it("returns 0 when the cookie is empty", async () => {
cookieGetMock.mockReturnValue(undefined);
+29 -2
View File
@@ -1,5 +1,10 @@
import { describe, expect, it } from "vitest";
import { finishedAtIso } from "../../lib/create/lastPublishedRule";
import { afterEach, describe, expect, it } from "vitest";
import {
CREATE_FLOW_LAST_PUBLISHED_KEY,
clearLastPublishedRule,
finishedAtIso,
writeLastPublishedRule,
} from "../../lib/create/lastPublishedRule";
describe("finishedAtIso", () => {
it("normalizes strings and dates", () => {
@@ -17,3 +22,25 @@ describe("finishedAtIso", () => {
expect(finishedAtIso(null)).toBeUndefined();
});
});
describe("clearLastPublishedRule", () => {
afterEach(() => {
sessionStorage.removeItem(CREATE_FLOW_LAST_PUBLISHED_KEY);
});
it("removes the stored finished Rule", () => {
writeLastPublishedRule({
id: "rule-1",
title: "Garden coop",
document: { sections: [] },
});
expect(sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY)).not.toBeNull();
clearLastPublishedRule();
expect(sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY)).toBeNull();
});
it("does nothing when the key is already missing", () => {
expect(() => clearLastPublishedRule()).not.toThrow();
expect(sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY)).toBeNull();
});
});
+4
View File
@@ -26,6 +26,10 @@ vi.mock("../../lib/server/uploads/deleteUploadedFiles", () => ({
deleteUploadsForUser: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("../../lib/server/guestRuleClaim", () => ({
clearGuestRuleClaimCookie: vi.fn().mockResolvedValue(undefined),
}));
import { DELETE } from "../../app/api/user/me/route";
beforeEach(() => {