From ede3da1cbeb83da4414b43d6592151b2ecfe1c27 Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 3 Dec 2026 15:01:16 +0800 Subject: [PATCH] feat(pages): ask before an in-app link leaves unsaved page edits Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- local/seed/04-zh-cn-messages.sql | 6 +++ .../app/components/pages/LeaveGuard.test.tsx | 51 +++++++++++++++++++ .../app/components/pages/LeaveGuard.tsx | 49 ++++++++++++++++++ .../pages/PageEditor.leave.test.tsx | 40 +++++++++++++++ .../app/components/pages/PageEditor.tsx | 2 + .../app/lib/i18n/defaultMessages.ts | 3 ++ .../app/lib/i18n/zh_CN.seed.json | 3 ++ 7 files changed, 154 insertions(+) create mode 100644 solvway-admin-portal/app/components/pages/LeaveGuard.test.tsx create mode 100644 solvway-admin-portal/app/components/pages/LeaveGuard.tsx create mode 100644 solvway-admin-portal/app/components/pages/PageEditor.leave.test.tsx diff --git a/local/seed/04-zh-cn-messages.sql b/local/seed/04-zh-cn-messages.sql index 105a85c..b182294 100644 --- a/local/seed/04-zh-cn-messages.sql +++ b/local/seed/04-zh-cn-messages.sql @@ -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'); diff --git a/solvway-admin-portal/app/components/pages/LeaveGuard.test.tsx b/solvway-admin-portal/app/components/pages/LeaveGuard.test.tsx new file mode 100644 index 0000000..f245160 --- /dev/null +++ b/solvway-admin-portal/app/components/pages/LeaveGuard.test.tsx @@ -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 = ( + +); + +describe("LeaveGuard", () => { + it("asks before an in-app link leaves unsaved edits: Cancel stays, Leave goes", async () => { + const user = userEvent.setup(); + render(<>{menu}); + 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}); + await user.click(screen.getByRole("link", { name: "Events" })); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + + rerender(<>{menu}); + 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(); + }); +}); diff --git a/solvway-admin-portal/app/components/pages/LeaveGuard.tsx b/solvway-admin-portal/app/components/pages/LeaveGuard.tsx new file mode 100644 index 0000000..4274711 --- /dev/null +++ b/solvway-admin-portal/app/components/pages/LeaveGuard.tsx @@ -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(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 ? ( + { setTo(null); router.push(to); }} + onCancel={() => setTo(null)} + /> + ) : null; +} diff --git a/solvway-admin-portal/app/components/pages/PageEditor.leave.test.tsx b/solvway-admin-portal/app/components/pages/PageEditor.leave.test.tsx new file mode 100644 index 0000000..433b350 --- /dev/null +++ b/solvway-admin-portal/app/components/pages/PageEditor.leave.test.tsx @@ -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(<>Events); + 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"); + }); +}); diff --git a/solvway-admin-portal/app/components/pages/PageEditor.tsx b/solvway-admin-portal/app/components/pages/PageEditor.tsx index f5a2856..fb4336e 100644 --- a/solvway-admin-portal/app/components/pages/PageEditor.tsx +++ b/solvway-admin-portal/app/components/pages/PageEditor.tsx @@ -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 + {confirmDiscard ? ( = { 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.", diff --git a/solvway-admin-portal/app/lib/i18n/zh_CN.seed.json b/solvway-admin-portal/app/lib/i18n/zh_CN.seed.json index a6d1dde..b23dd82 100644 --- a/solvway-admin-portal/app/lib/i18n/zh_CN.seed.json +++ b/solvway-admin-portal/app/lib/i18n/zh_CN.seed.json @@ -741,6 +741,9 @@ "PagesDiscardChanges": "放弃修改", "PagesDiscardTitle": "放弃未发布的修改?", "PagesDiscardMessage": "“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。", + "PagesLeaveTitle": "不保存就离开?", + "PagesLeaveMessage": "此页面的修改尚未保存。离开将丢失这些修改,确定离开吗?", + "PagesLeave": "离开", "PagesChangesPublished": "修改已发布。", "PagesChangesDiscarded": "修改已放弃。", "PagesPreviewDraftBanner": "未发布修改的预览。访客看到的仍是已发布的版本。",