feat(pages): editor draft banner with publish and discard, list badge, preview shows the draft

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 11:39:40 +08:00
1 parent 8203839b09
commit fac045fad1
15 files changed
+286 -16

No files matched your search

+18
View File
@@ -1461,6 +1461,24 @@ INSERT INTO message (code, content, area) SELECT 'PagesPreviewBanner', JSON_OBJE
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '预览。网页发布后访客才能看到。') WHERE LOWER(code) = LOWER('PagesPreviewBanner') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesViewPage', JSON_OBJECT('en_US', 'View page', 'zh_CN', '查看网页'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesViewPage') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '查看网页') WHERE LOWER(code) = LOWER('PagesViewPage') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesHasDraft', JSON_OBJECT('en_US', 'Unpublished changes', 'zh_CN', '有未发布的修改'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHasDraft') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '有未发布的修改') WHERE LOWER(code) = LOWER('PagesHasDraft') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesDraftBanner', JSON_OBJECT('en_US', 'You have unpublished changes. Visitors still see the published version until you publish them.', 'zh_CN', '您有未发布的修改。发布之前,访客看到的仍是已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDraftBanner') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '您有未发布的修改。发布之前,访客看到的仍是已发布的版本。') WHERE LOWER(code) = LOWER('PagesDraftBanner') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesPublishChanges', JSON_OBJECT('en_US', 'Publish changes', 'zh_CN', '发布修改'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPublishChanges') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '发布修改') WHERE LOWER(code) = LOWER('PagesPublishChanges') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesDiscardChanges', JSON_OBJECT('en_US', 'Discard changes', 'zh_CN', '放弃修改'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardChanges') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '放弃修改') WHERE LOWER(code) = LOWER('PagesDiscardChanges') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesDiscardTitle', JSON_OBJECT('en_US', 'Discard unpublished changes?', 'zh_CN', '放弃未发布的修改?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardTitle') AND area = 'A');
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 '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');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '修改已放弃。') WHERE LOWER(code) = LOWER('PagesChangesDiscarded') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesPreviewDraftBanner', JSON_OBJECT('en_US', 'Preview of unpublished changes. Visitors still see the published version.', 'zh_CN', '未发布修改的预览。访客看到的仍是已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPreviewDraftBanner') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '未发布修改的预览。访客看到的仍是已发布的版本。') WHERE LOWER(code) = LOWER('PagesPreviewDraftBanner') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesSaved', JSON_OBJECT('en_US', 'Page saved.', 'zh_CN', '网页已保存。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesSaved') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '网页已保存。') WHERE LOWER(code) = LOWER('PagesSaved') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesSaveFailed', JSON_OBJECT('en_US', 'Could not save the page. Try again.', 'zh_CN', '无法保存网页,请重试。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesSaveFailed') AND area = 'A');
@@ -0,0 +1,15 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
type Ctx = { params: Promise<{ id: string }> };
export async function POST(_req: NextRequest, { params }: Ctx) {
const token = await getToken();
if (!token) return unauthorized();
const { id } = await params;
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/pages/${encodeURIComponent(id)}/discard`, { method: "POST", token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,15 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
type Ctx = { params: Promise<{ id: string }> };
export async function POST(_req: NextRequest, { params }: Ctx) {
const token = await getToken();
if (!token) return unauthorized();
const { id } = await params;
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/pages/${encodeURIComponent(id)}/publish`, { method: "POST", token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -8,6 +8,8 @@ vi.mock("@/app/lib/server/clientContext", () => ({ clientIp: () => "203.0.113.9"
import * as list from "./route";
import * as one from "./[id]/route";
import * as images from "./images/route";
import * as publish from "./[id]/publish/route";
import * as discard from "./[id]/discard/route";
import * as form from "../public/pages/[company]/[slug]/form/[block]/route";
import * as image from "../public/page-images/[id]/route";
import * as branding from "../companies/[id]/branding/route";
@@ -42,6 +44,10 @@ describe("admin page routes", () => {
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages/1", { method: "PUT", body: { title: "T" }, token: "jwt" });
await one.DELETE(req("/api/pages/1", { method: "DELETE" }), ctx({ id: "1" }));
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages/1", { method: "DELETE", token: "jwt" });
await publish.POST(req("/api/pages/1/publish", { method: "POST" }), ctx({ id: "1/x" }));
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages/1%2Fx/publish", { method: "POST", token: "jwt" });
await discard.POST(req("/api/pages/1/discard", { method: "POST" }), ctx({ id: "1" }));
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages/1/discard", { method: "POST", token: "jwt" });
await list.POST(req("/api/pages", { method: "POST", body: JSON.stringify({ title: "T" }) }));
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages", { method: "POST", body: { title: "T" }, token: "jwt" });
});
@@ -0,0 +1,94 @@
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { ApiError } from "@/app/lib/clientApi";
const mocks = vi.hoisted(() => ({
getPage: vi.fn(), savePage: vi.fn(), deletePage: vi.fn(), uploadPageImage: vi.fn(), publishPage: vi.fn(), discardPage: vi.fn(),
listAdminEvents: vi.fn(), useAdminAuth: vi.fn(), useCompanyScope: vi.fn(),
}));
vi.mock("@/app/lib/services/adminPages", () => ({
getPage: mocks.getPage, savePage: mocks.savePage, deletePage: mocks.deletePage, uploadPageImage: mocks.uploadPageImage,
publishPage: mocks.publishPage, discardPage: mocks.discardPage,
}));
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-drafts-and-templates: a published page's edits stay a draft until Publish changes.
const live = {
id: 5, companyId: 2, slug: "hotel", title: "Hotel day", metaDescription: null, status: "PUBLISHED" as const, hideHeader: false,
blocks: [{ type: "CTA" as const, heading: "Live heading", buttonLabel: "Go", buttonUrl: "#signup" }], draft: null, hasDraft: false,
};
const draft = { slug: "hotel-week", title: "Hotel week", metaDescription: null, hideHeader: false, blocks: [{ type: "CTA" as const, heading: "Draft heading", buttonLabel: "Go", buttonUrl: "#signup" }] };
const withDraft = { ...live, draft, hasDraft: true };
beforeEach(() => {
vi.clearAllMocks();
memoryRouter.reset("/pages/5");
mocks.useAdminAuth.mockReturnValue({ isSuper: false, companyCode: "INS" });
mocks.useCompanyScope.mockReturnValue({ companyId: undefined, companies: [], codeOf: (id?: number) => (id === 2 ? "INS" : "") });
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
mocks.getPage.mockResolvedValue(live);
mocks.savePage.mockResolvedValue(withDraft);
mocks.publishPage.mockResolvedValue({ ...live, slug: "hotel-week", title: "Hotel week", blocks: draft.blocks });
mocks.discardPage.mockResolvedValue(live);
});
describe("PageEditor drafts", () => {
it("edits the draft when there is one, while View page stays on the live address", async () => {
mocks.getPage.mockResolvedValue(withDraft);
render(<PageEditor pageId={5} />);
expect(await screen.findByLabelText("Title")).toHaveValue("Hotel week");
expect(screen.getByLabelText("Heading")).toHaveValue("Draft heading");
expect(screen.getByRole("link", { name: "View page" })).toHaveAttribute("href", "/p/INS/hotel");
expect(screen.getByText(/Visitors still see the published version/)).toBeInTheDocument();
});
it("saving a published page shows the banner, and Publish changes saves then publishes", async () => {
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
expect(await screen.findByLabelText("Title")).toHaveValue("Hotel day");
expect(screen.queryByText(/Visitors still see the published version/)).not.toBeInTheDocument();
await user.clear(screen.getByLabelText("Title"));
await user.type(screen.getByLabelText("Title"), "Hotel week");
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText(/Visitors still see the published version/)).toBeInTheDocument();
expect(screen.getByLabelText("Title")).toHaveValue("Hotel week");
await user.click(screen.getByRole("button", { name: "Publish changes" }));
await waitFor(() => expect(mocks.publishPage).toHaveBeenCalledWith(5));
expect(mocks.savePage).toHaveBeenCalledTimes(2);
expect(mocks.savePage.mock.invocationCallOrder[1]).toBeLessThan(mocks.publishPage.mock.invocationCallOrder[0]);
await waitFor(() => expect(screen.queryByText(/Visitors still see the published version/)).not.toBeInTheDocument());
expect(screen.getByRole("status")).toHaveTextContent("Changes published");
expect(screen.getByRole("link", { name: "View page" })).toHaveAttribute("href", "/p/INS/hotel-week");
});
it("a publish refusal shows at its field and keeps the banner", async () => {
mocks.getPage.mockResolvedValue(withDraft);
mocks.publishPage.mockRejectedValue(new ApiError("x", 409, { code: "PagesSlugTaken", details: { field: "slug" } }));
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
await user.click(await screen.findByRole("button", { name: "Publish changes" }));
expect(await screen.findByRole("alert")).toHaveTextContent("Another page already uses this slug.");
expect(screen.getByText(/Visitors still see the published version/)).toBeInTheDocument();
});
it("Discard changes asks first, then shows the live page again", async () => {
mocks.getPage.mockResolvedValue(withDraft);
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
await user.click(await screen.findByRole("button", { name: "Discard changes" }));
expect(mocks.discardPage).not.toHaveBeenCalled();
await user.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Discard changes" }));
await waitFor(() => expect(mocks.discardPage).toHaveBeenCalledWith(5));
expect(await screen.findByLabelText("Title")).toHaveValue("Hotel day");
expect(screen.getByLabelText("Heading")).toHaveValue("Live heading");
expect(screen.queryByText(/Visitors still see the published version/)).not.toBeInTheDocument();
});
});
@@ -16,8 +16,8 @@ import { ApiError } from "@/app/lib/clientApi";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { useCompanyScope } from "@/app/lib/CompanyScope";
import { CopyAddress } from "./CopyAddress";
import { BLOCK_LABELS, BLOCK_TYPES, emptyBlock, emptyPage, pageAddress, pageBody, withTitle, type CmsBlock, type CmsPageDraft, type PageStatus } from "@/app/lib/cmsPages";
import { deletePage, getPage, savePage, uploadPageImage } from "@/app/lib/services/adminPages";
import { BLOCK_LABELS, BLOCK_TYPES, emptyBlock, emptyPage, pageAddress, pageBody, withTitle, type CmsBlock, type CmsPage, type CmsPageDraft, type PageStatus } from "@/app/lib/cmsPages";
import { deletePage, discardPage, getPage, publishPage, savePage, uploadPageImage } from "@/app/lib/services/adminPages";
import { listAdminEvents } from "@/app/lib/services/adminEvents";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { BlockFields, type EventOption } from "./BlockFields";
@@ -65,10 +65,24 @@ export function PageEditor({ pageId }: { pageId?: number }) {
const [notice, setNotice] = useState<string | null>(justSaved ? "PagesSaved" : null);
const [saving, setSaving] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
const [confirmDiscard, setConfirmDiscard] = useState(false);
// A published page's edits are saved as a draft; visitors see the live version until Publish changes.
const [hasDraft, setHasDraft] = useState(false);
const [events, setEvents] = useState<EventOption[]>([]);
const nextKey = useRef(0);
const toRows = (blocks: CmsBlock[]) => blocks.map((block) => ({ key: ++nextKey.current, block }));
const isNew = draft.id == null;
/** Shows a loaded page: its draft when there is one, else the live content. */
function show(p: CmsPage) {
const c = p.draft ?? p;
setDraft({ id: p.id, companyId: p.companyId, slug: c.slug, slugTouched: true, title: c.title, metaDescription: c.metaDescription ?? "", status: p.status, hideHeader: !!c.hideHeader, blocks: [] });
setRows(toRows(c.blocks ?? []));
setPending({});
setSaved({ slug: p.slug, status: p.status });
setHasDraft(!!p.draft);
setDirty(false);
}
const code = (isSuper ? scope.codeOf(draft.companyId) : companyCode) || "";
useEffect(() => {
@@ -76,14 +90,12 @@ export function PageEditor({ pageId }: { pageId?: number }) {
let cancelled = false;
getPage(pageId)
.then((p) => {
if (cancelled) return;
setDraft({ id: p.id, companyId: p.companyId, slug: p.slug, slugTouched: true, title: p.title, metaDescription: p.metaDescription ?? "", status: p.status, hideHeader: !!p.hideHeader, blocks: [] });
setRows(toRows(p.blocks ?? []));
setSaved({ slug: p.slug, status: p.status });
if (!cancelled) show(p);
})
.catch((err: unknown) => { if (!cancelled) setLoadError(err instanceof ApiError && err.status === 404 ? "PagesNotFound" : "PagesLoadFailed"); })
.finally(() => { if (!cancelled) setLoading(false); });
return () => { cancelled = true; };
// eslint-disable-next-line react-hooks/exhaustive-deps -- show only sets state; load again only for another page.
}, [pageId]);
// The FORM picker: the page company's enabled events that have not ended (Malaysia dates).
@@ -141,13 +153,13 @@ export function PageEditor({ pageId }: { pageId?: number }) {
else setSummary(message);
}
async function save() {
async function save(): Promise<boolean> {
setSummary(null);
setNotice(null);
setErrors({});
if (isNew && isSuper && !draft.companyId) {
setErrors({ companyId: t("ChooseCompany") });
return;
return false;
}
setSaving(true);
const next = rows.map((r) => ({ ...r }));
@@ -162,11 +174,14 @@ export function PageEditor({ pageId }: { pageId?: number }) {
const page = await savePage(draft.id, pageBody({ ...draft, blocks: next.map((r) => r.block) }));
setDraft((d) => ({ ...d, id: page.id, companyId: page.companyId }));
setSaved({ slug: page.slug, status: page.status });
setHasDraft(!!page.draft);
setDirty(false);
setNotice("PagesSaved");
if (isNew) router.replace(`/pages/${page.id}?saved=1`);
return true;
} catch (err) {
showError(err);
return false;
} finally {
// Uploaded images stay on their blocks and leave the pending set, success or not.
setRows(next);
@@ -175,6 +190,37 @@ export function PageEditor({ pageId }: { pageId?: number }) {
}
}
/** Saves the current edits, then makes the draft live. */
async function publishChanges() {
if (draft.id == null || !(await save())) return;
setSaving(true);
try {
show(await publishPage(draft.id));
setNotice("PagesChangesPublished");
} catch (err) {
setNotice(null);
showError(err);
} finally {
setSaving(false);
}
}
async function discardChanges() {
if (draft.id == null) return;
setSaving(true);
setSummary(null);
setErrors({});
try {
show(await discardPage(draft.id));
setNotice("PagesChangesDiscarded");
} catch (err) {
showError(err);
} finally {
setConfirmDiscard(false);
setSaving(false);
}
}
async function remove() {
if (draft.id == null) return;
setSaving(true);
@@ -215,6 +261,13 @@ export function PageEditor({ pageId }: { pageId?: number }) {
</div>
{summary && <p role="alert" className="text-sm text-destructive">{summary}</p>}
{notice && <p role="status" className="text-sm text-positive">{t(notice)}</p>}
{hasDraft && draft.status === "PUBLISHED" ? (
<div className="flex flex-wrap items-center gap-2 rounded-md border border-warning/30 bg-warning/10 px-3 py-2 text-sm">
<p className="mr-auto">{t("PagesDraftBanner")}</p>
<Button type="button" size="sm" variant="outline" disabled={saving} onClick={() => setConfirmDiscard(true)}>{t("PagesDiscardChanges")}</Button>
<Button type="button" size="sm" disabled={saving} onClick={() => void publishChanges()}>{t("PagesPublishChanges")}</Button>
</div>
) : null}
<div className="grid gap-4 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
<div className="space-y-4">
@@ -313,6 +366,17 @@ export function PageEditor({ pageId }: { pageId?: number }) {
<Button type="button" disabled={saving} onClick={() => void save()}>{t("Save")}</Button>
</div>
{confirmDiscard ? (
<ConfirmDialog
title={t("PagesDiscardTitle")}
message={t("PagesDiscardMessage", { title: draft.title })}
confirmLabel={t("PagesDiscardChanges")}
destructive
busy={saving}
onConfirm={() => void discardChanges()}
onCancel={() => setConfirmDiscard(false)}
/>
) : null}
{confirmDelete ? (
<ConfirmDialog
title={t("PagesDeleteTitle")}
+13
View File
@@ -72,6 +72,19 @@ export interface CmsPage {
hideHeader?: boolean;
blocks: CmsBlock[];
updatedAt?: string | null;
/** Unpublished changes of a published page (editor reads only). */
draft?: PageContent | null;
/** List rows: the page has unpublished changes. */
hasDraft?: boolean;
}
/** What a draft holds; status and company stay on the page. */
export interface PageContent {
slug: string;
title: string;
metaDescription: string | null;
hideHeader?: boolean;
blocks: CmsBlock[];
}
export interface CmsPageDraft {
@@ -63,6 +63,14 @@ describe("preview frame", () => {
expect(res.headers.get("content-security-policy")).toMatch(/^sandbox allow-scripts/);
});
it("serves the unpublished changes' HTML block when the page has a draft", async () => {
const draft = { slug: "hotel", title: "Hotel", blocks: [{ type: "HTML", html: "<p>draft only</p>" }] };
mocks.callMobileApi.mockResolvedValueOnce({ ok: true, data: { slug: "hotel", title: "Hotel", blocks: [{ type: "FAQ" }], draft } });
const res = await preview.GET(req, ctx({ id: "5", block: "0" }));
expect(res.status).toBe(200);
expect(await res.text()).toContain("draft only");
});
it("is not found without a session, for a bad id, a refused page or a non-HTML block", async () => {
mocks.getToken.mockResolvedValueOnce(null);
expect((await preview.GET(req, ctx({ id: "5", block: "0" }))).status).toBe(404);
@@ -742,6 +742,15 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
PagesPreview: "Preview",
PagesPreviewBanner: "Preview. Visitors see this page only once it is published.",
PagesViewPage: "View page",
PagesHasDraft: "Unpublished changes",
PagesDraftBanner: "You have unpublished changes. Visitors still see the published version until you publish them.",
PagesPublishChanges: "Publish changes",
PagesDiscardChanges: "Discard changes",
PagesDiscardTitle: "Discard unpublished changes?",
PagesDiscardMessage: "Your unpublished changes to \"{title}\" will be lost. Visitors keep seeing the published version.",
PagesChangesPublished: "Changes published.",
PagesChangesDiscarded: "Changes discarded.",
PagesPreviewDraftBanner: "Preview of unpublished changes. Visitors still see the published version.",
PagesSaved: "Page saved.",
PagesSaveFailed: "Could not save the page. Try again.",
PagesNotFound: "Page not found.",
@@ -726,6 +726,15 @@
"PagesMetaDescription": "搜索引擎描述",
"PagesPreview": "预览",
"PagesPreviewBanner": "预览。网页发布后访客才能看到。",
"PagesHasDraft": "有未发布的修改",
"PagesDraftBanner": "您有未发布的修改。发布之前,访客看到的仍是已发布的版本。",
"PagesPublishChanges": "发布修改",
"PagesDiscardChanges": "放弃修改",
"PagesDiscardTitle": "放弃未发布的修改?",
"PagesDiscardMessage": "“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。",
"PagesChangesPublished": "修改已发布。",
"PagesChangesDiscarded": "修改已放弃。",
"PagesPreviewDraftBanner": "未发布修改的预览。访客看到的仍是已发布的版本。",
"PagesViewPage": "查看网页",
"PagesSaved": "网页已保存。",
"PagesSaveFailed": "无法保存网页,请重试。",
@@ -24,6 +24,11 @@ export const getPage = (id: number) => apiGet<CmsPage>(`/api/pages/${id}`);
export const savePage = (id: number | undefined, body: ReturnType<typeof pageBody>) =>
id == null ? apiPost<CmsPage>("/api/pages", body) : apiPut<CmsPage>(`/api/pages/${id}`, body);
/** Makes a published page's saved draft live; refusals carry a field like a save. */
export const publishPage = (id: number) => apiPost<CmsPage>(`/api/pages/${id}/publish`, {});
export const discardPage = (id: number) => apiPost<CmsPage>(`/api/pages/${id}/discard`, {});
export const deletePage = (id: number) => apiDelete<unknown>(`/api/pages/${id}`);
/** Base64 without the data-URL prefix; the counter checks type (PNG, JPEG, WebP) and size (2 MB). */
@@ -2,7 +2,7 @@ import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { frameNotFound, frameResponse, htmlBlock } from "@/app/lib/frameHtml";
// add-custom-html-block: a draft page's Custom HTML block for the staff preview, sealed like the public frame.
// add-custom-html-block: a draft page's (or a published page's unpublished changes') Custom HTML block for the staff preview, sealed like the public frame.
// The admin API checks BO_PAGES and the caller's company; anything it refuses is not found here.
type Ctx = { params: Promise<{ id: string; block: string }> };
@@ -10,8 +10,8 @@ export async function GET(_req: Request, { params }: Ctx): Promise<Response> {
const { id, block } = await params;
const token = await getToken();
if (!token || !/^\d{1,19}$/.test(id) || !/^\d{1,2}$/.test(block)) return frameNotFound();
const result = await callMobileApi<{ blocks?: unknown }>(`/api/admin/pages/${encodeURIComponent(id)}`, { token });
const result = await callMobileApi<{ blocks?: unknown; draft?: { blocks?: unknown } | null }>(`/api/admin/pages/${encodeURIComponent(id)}`, { token });
if (!result.ok) return frameNotFound();
const html = htmlBlock(result.data.blocks, block);
const html = htmlBlock((result.data.draft ?? result.data).blocks, block);
return html === null ? frameNotFound() : frameResponse(html, { preview: true });
}
@@ -15,6 +15,8 @@ interface AdminPage {
hideHeader?: boolean;
blocks: PublicBlock[];
company?: Branding;
/** Unpublished changes of a published page: the preview shows them. */
draft?: { title: string; hideHeader?: boolean; blocks: PublicBlock[] } | null;
}
export default async function PagePreview({ params }: Props) {
@@ -24,8 +26,8 @@ export default async function PagePreview({ params }: Props) {
const result = await callMobileApi<AdminPage>(`/api/admin/pages/${encodeURIComponent(id)}`, { token });
if (!result.ok) notFound();
const t = await getServerT();
const page = result.data;
const banner = <p role="status" className="bg-warning/15 px-4 py-2 text-center text-sm font-medium">{t("PagesPreviewBanner")}</p>;
const page = result.data.draft ? { ...result.data, ...result.data.draft } : result.data;
const banner = <p role="status" className="bg-warning/15 px-4 py-2 text-center text-sm font-medium">{t(result.data.draft ? "PagesPreviewDraftBanner" : "PagesPreviewBanner")}</p>;
return (
<RequireModule pathname="/pages">
<LandingPage company={page.company ?? { code: "", name: "" }} page={page} banner={banner} preview frameBase={`/pages/${encodeURIComponent(id)}/preview/frame`} />
@@ -47,6 +47,15 @@ describe("PagesPage", () => {
expect(screen.getByRole("link", { name: /new page/i })).toHaveAttribute("href", "/pages/new");
});
it("marks a published page with unpublished changes", async () => {
mocks.listPages.mockResolvedValue({
items: [{ id: 5, companyId: 2, slug: "hotel-tech", title: "Hotel tech", status: "PUBLISHED", metaDescription: null, blocks: [], hasDraft: true }],
total: 1,
});
render(<PagesPage />);
expect(await screen.findByText("Unpublished changes")).toBeInTheDocument();
});
it("searches by title", async () => {
mocks.listPages.mockResolvedValue({ items: [], total: 0 });
const user = userEvent.setup();
+6 -3
View File
@@ -70,9 +70,12 @@ function PagesPageContent() {
accessorKey: "status",
header: t("Status"),
cell: ({ row }) => (
<Badge variant={row.original.status === "PUBLISHED" ? "positive" : "neutral"}>
{t(row.original.status === "PUBLISHED" ? "PagesPublished" : "PagesDraft")}
</Badge>
<span className="flex flex-wrap gap-1">
<Badge variant={row.original.status === "PUBLISHED" ? "positive" : "neutral"}>
{t(row.original.status === "PUBLISHED" ? "PagesPublished" : "PagesDraft")}
</Badge>
{row.original.hasDraft ? <Badge variant="warning">{t("PagesHasDraft")}</Badge> : null}
</span>
),
},
{