feat(pages): ask before an in-app link leaves unsaved page edits

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-03 15:01:16 +08:00
1 parent 6b3498d123
commit ede3da1cbe
7 files changed
+154

No files matched your search

+6
View File
@@ -1491,6 +1491,12 @@ INSERT INTO message (code, content, area) SELECT 'PagesDiscardTitle', JSON_OBJEC
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '放弃未发布的修改?') WHERE LOWER(code) = LOWER('PagesDiscardTitle') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesDiscardMessage', JSON_OBJECT('en_US', 'Your unpublished changes to "{title}" will be lost. Visitors keep seeing the published version.', 'zh_CN', '“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardMessage') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。') WHERE LOWER(code) = LOWER('PagesDiscardMessage') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesLeaveTitle', JSON_OBJECT('en_US', 'Leave without saving?', 'zh_CN', '不保存就离开?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLeaveTitle') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不保存就离开?') WHERE LOWER(code) = LOWER('PagesLeaveTitle') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesLeaveMessage', JSON_OBJECT('en_US', 'Your changes to this page are not saved. Leave and lose them?', 'zh_CN', '此页面的修改尚未保存。离开将丢失这些修改,确定离开吗?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLeaveMessage') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此页面的修改尚未保存。离开将丢失这些修改,确定离开吗?') WHERE LOWER(code) = LOWER('PagesLeaveMessage') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesLeave', JSON_OBJECT('en_US', 'Leave', 'zh_CN', '离开'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLeave') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '离开') WHERE LOWER(code) = LOWER('PagesLeave') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesChangesPublished', JSON_OBJECT('en_US', 'Changes published.', 'zh_CN', '修改已发布。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChangesPublished') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '修改已发布。') WHERE LOWER(code) = LOWER('PagesChangesPublished') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesChangesDiscarded', JSON_OBJECT('en_US', 'Changes discarded.', 'zh_CN', '修改已放弃。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChangesDiscarded') AND area = 'A');
@@ -0,0 +1,51 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Link from "next/link";
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { memoryRouter } from "@/test/memoryRouter";
import { LeaveGuard } from "./LeaveGuard";
// add-page-visual-editor: unsaved edits are guarded against in-app links too, not only reloads.
beforeEach(() => memoryRouter.reset("/pages/5"));
const menu = (
<nav>
<Link href="/events">Events</Link>
<a href="/p/INS/hotel" target="_blank" rel="noopener noreferrer">View page</a>
<a href="#top">Top</a>
</nav>
);
describe("LeaveGuard", () => {
it("asks before an in-app link leaves unsaved edits: Cancel stays, Leave goes", async () => {
const user = userEvent.setup();
render(<>{menu}<LeaveGuard dirty /></>);
await user.click(screen.getByRole("link", { name: "Events" }));
expect(screen.getByRole("dialog", { name: "Leave without saving?" })).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Cancel" }));
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(memoryRouter.push).not.toHaveBeenCalled();
await user.click(screen.getByRole("link", { name: "Events" }));
await user.click(screen.getByRole("button", { name: "Leave" }));
expect(memoryRouter.push).toHaveBeenCalledWith("/events");
});
it("lets links through when nothing is unsaved, and never stops a new tab or a link within the page", async () => {
const user = userEvent.setup();
const { rerender } = render(<>{menu}<LeaveGuard dirty={false} /></>);
await user.click(screen.getByRole("link", { name: "Events" }));
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
rerender(<>{menu}<LeaveGuard dirty /></>);
await user.click(screen.getByRole("link", { name: "View page" }));
await user.click(screen.getByRole("link", { name: "Top" }));
await user.keyboard("{Control>}");
await user.click(screen.getByRole("link", { name: "Events" }));
await user.keyboard("{/Control}");
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
});
@@ -0,0 +1,49 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
import { useT } from "@/app/lib/i18n/MessagesProvider";
/** The in-app address a plain left click on this event would go to, or null when the click stays or opens elsewhere. */
function leavingTo(e: MouseEvent): string | null {
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return null;
const link = (e.target as Element | null)?.closest?.("a[href]") as HTMLAnchorElement | null;
if (!link || (link.target && link.target !== "_self") || link.hasAttribute("download")) return null;
const url = new URL(link.href, location.href);
if (url.origin !== location.origin) return null;
if (url.pathname === location.pathname && url.search === location.search) return null; // a #name on this page
return url.pathname + url.search + url.hash;
}
/**
* Asks before an in-app link leaves unsaved edits (add-page-visual-editor). The browser asks for reloads and closing
* (usePageDraft). ponytail: browser Back is not guarded; the App Router has no hook for it.
*/
export function LeaveGuard({ dirty }: { dirty: boolean }) {
const t = useT();
const router = useRouter();
const [to, setTo] = useState<string | null>(null);
useEffect(() => {
if (!dirty) return;
// Capture phase on the document: before the link's own handler, which then sees the click is taken.
const onClick = (e: MouseEvent) => {
const href = leavingTo(e);
if (!href) return;
e.preventDefault();
setTo(href);
};
document.addEventListener("click", onClick, true);
return () => document.removeEventListener("click", onClick, true);
}, [dirty]);
return to ? (
<ConfirmDialog
title={t("PagesLeaveTitle")}
message={t("PagesLeaveMessage")}
confirmLabel={t("PagesLeave")}
destructive
onConfirm={() => { setTo(null); router.push(to); }}
onCancel={() => setTo(null)}
/>
) : null;
}
@@ -0,0 +1,40 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Link from "next/link";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ getPage: vi.fn(), listAdminEvents: vi.fn(), useAdminAuth: vi.fn(), useCompanyScope: vi.fn() }));
vi.mock("@/app/lib/services/adminPages", () => ({ getPage: mocks.getPage }));
vi.mock("@/app/lib/services/adminEvents", () => ({ listAdminEvents: mocks.listAdminEvents }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { memoryRouter } from "@/test/memoryRouter";
import { PageEditor } from "./PageEditor";
// add-page-visual-editor: a menu link with unsaved edits asks first, in the form editor too.
beforeEach(() => {
vi.clearAllMocks();
memoryRouter.reset("/pages/5");
mocks.useAdminAuth.mockReturnValue({ isSuper: false, companyCode: "INS" });
mocks.useCompanyScope.mockReturnValue({ companyId: undefined, companies: [], codeOf: () => "INS" });
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
mocks.getPage.mockResolvedValue({ id: 5, companyId: 2, slug: "hotel", title: "Hotel", metaDescription: null, status: "DRAFT", blocks: [] });
});
describe("PageEditor: leaving with unsaved edits", () => {
it("asks before a menu link only once something is changed", async () => {
const user = userEvent.setup();
render(<><Link href="/events">Events</Link><PageEditor pageId={5} /></>);
const title = await screen.findByLabelText("Title");
await user.click(screen.getByRole("link", { name: "Events" }));
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
await user.type(title, " day");
await user.click(screen.getByRole("link", { name: "Events" }));
expect(screen.getByRole("dialog", { name: "Leave without saving?" })).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Leave" }));
expect(memoryRouter.push).toHaveBeenCalledWith("/events");
});
});
@@ -16,6 +16,7 @@ import { BLOCK_LABELS, BLOCK_TYPES, pageAddress, type CmsBlock } from "@/app/lib
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { BlockFields } from "./BlockFields";
import { usePageDraft } from "./usePageDraft";
import { LeaveGuard } from "./LeaveGuard";
// The landing-page form editor, ported from babyboo's PageEditor. State and actions live in usePageDraft, shared
// with the on-page editor; this is the layout for narrow windows.
@@ -164,6 +165,7 @@ export function PageEditor(props: { pageId?: number; fromId?: number; initialBlo
<Button type="button" disabled={saving} onClick={() => void p.save()}>{t("Save")}</Button>
</div>
<LeaveGuard dirty={p.dirty} />
{confirmDiscard ? (
<ConfirmDialog
title={t("PagesDiscardTitle")}
@@ -757,6 +757,9 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
PagesDiscardChanges: "Discard changes",
PagesDiscardTitle: "Discard unpublished changes?",
PagesDiscardMessage: "Your unpublished changes to \"{title}\" will be lost. Visitors keep seeing the published version.",
PagesLeaveTitle: "Leave without saving?",
PagesLeaveMessage: "Your changes to this page are not saved. Leave and lose them?",
PagesLeave: "Leave",
PagesChangesPublished: "Changes published.",
PagesChangesDiscarded: "Changes discarded.",
PagesPreviewDraftBanner: "Preview of unpublished changes. Visitors still see the published version.",
@@ -741,6 +741,9 @@
"PagesDiscardChanges": "放弃修改",
"PagesDiscardTitle": "放弃未发布的修改?",
"PagesDiscardMessage": "“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。",
"PagesLeaveTitle": "不保存就离开?",
"PagesLeaveMessage": "此页面的修改尚未保存。离开将丢失这些修改,确定离开吗?",
"PagesLeave": "离开",
"PagesChangesPublished": "修改已发布。",
"PagesChangesDiscarded": "修改已放弃。",
"PagesPreviewDraftBanner": "未发布修改的预览。访客看到的仍是已发布的版本。",