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(() => {