feat(pages): starter templates, new page picker and duplicate

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:45:31 +08:00
1 parent fac045fad1
commit 57942f6eae
14 files changed
+379 -17

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 'PagesDuplicate', JSON_OBJECT('en_US', 'Duplicate', 'zh_CN', '复制'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDuplicate') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制') WHERE LOWER(code) = LOWER('PagesDuplicate') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesDuplicateNamed', JSON_OBJECT('en_US', 'Duplicate {title}', 'zh_CN', '复制 {title}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDuplicateNamed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制 {title}') WHERE LOWER(code) = LOWER('PagesDuplicateNamed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesChooseStart', JSON_OBJECT('en_US', 'How do you want to start?', 'zh_CN', '您想如何开始?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChooseStart') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '您想如何开始?') WHERE LOWER(code) = LOWER('PagesChooseStart') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesStartBlank', JSON_OBJECT('en_US', 'Blank page', 'zh_CN', '空白网页'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesStartBlank') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '空白网页') WHERE LOWER(code) = LOWER('PagesStartBlank') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesStartBlankHint', JSON_OBJECT('en_US', 'Start empty and add sections yourself.', 'zh_CN', '从空白开始,自行添加区块。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesStartBlankHint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '从空白开始,自行添加区块。') WHERE LOWER(code) = LOWER('PagesStartBlankHint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTemplateEvent', JSON_OBJECT('en_US', 'Event sign-up', 'zh_CN', '活动报名'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateEvent') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '活动报名') WHERE LOWER(code) = LOWER('PagesTemplateEvent') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTemplateEventHint', JSON_OBJECT('en_US', 'A page for one event: headline, benefits, steps, questions and the sign-up form.', 'zh_CN', '为单个活动准备的网页:标题、优势、步骤、常见问题和报名表。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateEventHint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '为单个活动准备的网页:标题、优势、步骤、常见问题和报名表。') WHERE LOWER(code) = LOWER('PagesTemplateEventHint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTemplateShowcase', JSON_OBJECT('en_US', 'Service showcase', 'zh_CN', '服务展示'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateShowcase') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '服务展示') WHERE LOWER(code) = LOWER('PagesTemplateShowcase') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTemplateShowcaseHint', JSON_OBJECT('en_US', 'Present a service with benefits, steps and a call to action, ending with the sign-up form.', 'zh_CN', '介绍一项服务:优势、步骤和行动号召,最后是报名表。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateShowcaseHint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '介绍一项服务:优势、步骤和行动号召,最后是报名表。') WHERE LOWER(code) = LOWER('PagesTemplateShowcaseHint') 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');
@@ -0,0 +1,39 @@
-- The labels added by add-page-drafts-and-templates, cut from the output of `npm run i18n:sql`. Run it only in an environment that already ran add-zh-cn-messages/sql/03-zh-cn-messages.sql; otherwise run that 03 file, which includes these labels.
SET NAMES utf8mb4;
USE `service-system`;
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 'PagesDuplicate', JSON_OBJECT('en_US', 'Duplicate', 'zh_CN', '复制'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDuplicate') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制') WHERE LOWER(code) = LOWER('PagesDuplicate') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesDuplicateNamed', JSON_OBJECT('en_US', 'Duplicate {title}', 'zh_CN', '复制 {title}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDuplicateNamed') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制 {title}') WHERE LOWER(code) = LOWER('PagesDuplicateNamed') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesChooseStart', JSON_OBJECT('en_US', 'How do you want to start?', 'zh_CN', '您想如何开始?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChooseStart') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '您想如何开始?') WHERE LOWER(code) = LOWER('PagesChooseStart') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesStartBlank', JSON_OBJECT('en_US', 'Blank page', 'zh_CN', '空白网页'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesStartBlank') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '空白网页') WHERE LOWER(code) = LOWER('PagesStartBlank') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesStartBlankHint', JSON_OBJECT('en_US', 'Start empty and add sections yourself.', 'zh_CN', '从空白开始,自行添加区块。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesStartBlankHint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '从空白开始,自行添加区块。') WHERE LOWER(code) = LOWER('PagesStartBlankHint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTemplateEvent', JSON_OBJECT('en_US', 'Event sign-up', 'zh_CN', '活动报名'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateEvent') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '活动报名') WHERE LOWER(code) = LOWER('PagesTemplateEvent') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTemplateEventHint', JSON_OBJECT('en_US', 'A page for one event: headline, benefits, steps, questions and the sign-up form.', 'zh_CN', '为单个活动准备的网页:标题、优势、步骤、常见问题和报名表。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateEventHint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '为单个活动准备的网页:标题、优势、步骤、常见问题和报名表。') WHERE LOWER(code) = LOWER('PagesTemplateEventHint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTemplateShowcase', JSON_OBJECT('en_US', 'Service showcase', 'zh_CN', '服务展示'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateShowcase') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '服务展示') WHERE LOWER(code) = LOWER('PagesTemplateShowcase') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTemplateShowcaseHint', JSON_OBJECT('en_US', 'Present a service with benefits, steps and a call to action, ending with the sign-up form.', 'zh_CN', '介绍一项服务:优势、步骤和行动号召,最后是报名表。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateShowcaseHint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '介绍一项服务:优势、步骤和行动号召,最后是报名表。') WHERE LOWER(code) = LOWER('PagesTemplateShowcaseHint') AND area = 'A';
@@ -2,3 +2,7 @@
-- publish or note them first. Then deploy the previous services-counter, which saves published pages directly.
USE `service-counter`;
ALTER TABLE `cms_page` DROP COLUMN `draft`;
-- Labels (02-draft-template-labels.sql).
USE `service-system`;
DELETE FROM message WHERE code IN ('PagesHasDraft', 'PagesDraftBanner', 'PagesPublishChanges', 'PagesDiscardChanges', 'PagesDiscardTitle', 'PagesDiscardMessage', 'PagesChangesPublished', 'PagesChangesDiscarded', 'PagesPreviewDraftBanner', 'PagesDuplicate', 'PagesDuplicateNamed', 'PagesChooseStart', 'PagesStartBlank', 'PagesStartBlankHint', 'PagesTemplateEvent', 'PagesTemplateEventHint', 'PagesTemplateShowcase', 'PagesTemplateShowcaseHint') AND area = 'A';
@@ -12,9 +12,9 @@ Design: `design.md` and `docs/superpowers/specs/2026-12-03-page-builder-design.m
## 2. Portal
- [ ] 2.1 BFF routes for publish and discard; services; the editor loads the draft, the published-page banner with Publish changes and Discard changes (confirm); preview shows the draft; list badge.
- [ ] 2.2 Templates (`pageTemplates.ts`, with a rules test) and the start picker on New page; Duplicate in the list and editor.
- [ ] 2.3 Labels in `defaultMessages.ts` and `zh_CN.seed.json`, `npm run i18n:sql`, `sql/02-draft-template-labels.sql`; rollback lines.
- [x] 2.1 BFF routes for publish and discard; services; the editor loads the draft, the published-page banner with Publish changes and Discard changes (confirm); preview shows the draft; list badge.
- [x] 2.2 Templates (`pageTemplates.ts`, with a rules test) and the start picker on New page; Duplicate in the list and editor.
- [x] 2.3 Labels in `defaultMessages.ts` and `zh_CN.seed.json`, `npm run i18n:sql`, `sql/02-draft-template-labels.sql`; rollback lines.
- Verify (2.1 to 2.3): `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`
## 3. Release
@@ -69,6 +69,11 @@ describe("PageEditor drafts", () => {
expect(screen.getByRole("link", { name: "View page" })).toHaveAttribute("href", "/p/INS/hotel-week");
});
it("offers Duplicate for a saved page", async () => {
render(<PageEditor pageId={5} />);
expect(await screen.findByRole("link", { name: "Duplicate" })).toHaveAttribute("href", "/pages/new?from=5");
});
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" } }));
@@ -46,19 +46,21 @@ function FieldError({ message }: { message?: string }) {
return message ? <p role="alert" className="text-sm text-destructive">{message}</p> : null;
}
export function PageEditor({ pageId }: { pageId?: number }) {
/** pageId edits a page; fromId opens an unsaved copy of one (Duplicate); initialBlocks start a new page (templates). */
export function PageEditor({ pageId, fromId, initialBlocks }: { pageId?: number; fromId?: number; initialBlocks?: CmsBlock[] }) {
const t = useT();
const router = useRouter();
const { isSuper, companyCode } = useAdminAuth();
const scope = useCompanyScope();
const justSaved = useSearchParams()?.get("saved") === "1";
const [draft, setDraft] = useState<CmsPageDraft>(() => ({ ...emptyPage(), companyId: scope.companyId }));
const [rows, setRows] = useState<Row[]>([]);
const [rows, setRows] = useState<Row[]>(() => (initialBlocks ?? []).map((block, i) => ({ key: -1 - i, block })));
const [pending, setPending] = useState<Record<number, { file: File; preview?: string }>>({});
// The page as last loaded or saved: what "View page" points at.
const [saved, setSaved] = useState<{ slug: string; status: PageStatus } | null>(null);
const [dirty, setDirty] = useState(false);
const [loading, setLoading] = useState(pageId != null);
const loadId = pageId ?? fromId;
const [loading, setLoading] = useState(loadId != null);
const [loadError, setLoadError] = useState<string | null>(null);
const [errors, setErrors] = useState<Record<string, string>>({});
const [summary, setSummary] = useState<string | null>(null);
@@ -86,17 +88,25 @@ export function PageEditor({ pageId }: { pageId?: number }) {
const code = (isSuper ? scope.codeOf(draft.companyId) : companyCode) || "";
useEffect(() => {
if (pageId == null) return;
if (loadId == null) return;
let cancelled = false;
getPage(pageId)
getPage(loadId)
.then((p) => {
if (!cancelled) show(p);
if (cancelled) return;
show(p);
if (pageId == null) {
// Duplicate: the same company's content as a new, unsaved draft page.
setDraft((d) => ({ ...d, id: undefined, status: "DRAFT", title: `${d.title} (copy)`, slug: `${d.slug}-copy` }));
setSaved(null);
setHasDraft(false);
setDirty(true);
}
})
.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]);
}, [loadId]);
// The FORM picker: the page company's enabled events that have not ended (Malaysia dates).
const eventsCompany = isSuper ? draft.companyId : undefined;
@@ -249,9 +259,14 @@ export function PageEditor({ pageId }: { pageId?: number }) {
<div className="flex flex-wrap items-center justify-end gap-2">
{saved && code ? <span className="mr-auto"><CopyAddress address={pageAddress(code, saved.slug)} /></span> : null}
{draft.id != null ? (
<Button variant="outline" asChild>
<Link href={`/pages/${draft.id}/preview`}>{t("PagesPreview")}</Link>
</Button>
<>
<Button variant="outline" asChild>
<Link href={`/pages/new?from=${draft.id}`}>{t("PagesDuplicate")}</Link>
</Button>
<Button variant="outline" asChild>
<Link href={`/pages/${draft.id}/preview`}>{t("PagesPreview")}</Link>
</Button>
</>
) : null}
{saved?.status === "PUBLISHED" && code ? (
<Button variant="outline" asChild>
@@ -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",
PagesDuplicate: "Duplicate",
PagesDuplicateNamed: "Duplicate {title}",
PagesChooseStart: "How do you want to start?",
PagesStartBlank: "Blank page",
PagesStartBlankHint: "Start empty and add sections yourself.",
PagesTemplateEvent: "Event sign-up",
PagesTemplateEventHint: "A page for one event: headline, benefits, steps, questions and the sign-up form.",
PagesTemplateShowcase: "Service showcase",
PagesTemplateShowcaseHint: "Present a service with benefits, steps and a call to action, ending with the sign-up form.",
PagesHasDraft: "Unpublished changes",
PagesDraftBanner: "You have unpublished changes. Visitors still see the published version until you publish them.",
PagesPublishChanges: "Publish changes",
@@ -726,6 +726,15 @@
"PagesMetaDescription": "搜索引擎描述",
"PagesPreview": "预览",
"PagesPreviewBanner": "预览。网页发布后访客才能看到。",
"PagesDuplicate": "复制",
"PagesDuplicateNamed": "复制 {title}",
"PagesChooseStart": "您想如何开始?",
"PagesStartBlank": "空白网页",
"PagesStartBlankHint": "从空白开始,自行添加区块。",
"PagesTemplateEvent": "活动报名",
"PagesTemplateEventHint": "为单个活动准备的网页:标题、优势、步骤、常见问题和报名表。",
"PagesTemplateShowcase": "服务展示",
"PagesTemplateShowcaseHint": "介绍一项服务:优势、步骤和行动号召,最后是报名表。",
"PagesHasDraft": "有未发布的修改",
"PagesDraftBanner": "您有未发布的修改。发布之前,访客看到的仍是已发布的版本。",
"PagesPublishChanges": "发布修改",
@@ -0,0 +1,72 @@
import { describe, it, expect } from "vitest";
import { ANCHOR, ICONS, isSafeLink, pageBody, emptyPage, type CmsBlock } from "@/app/lib/cmsPages";
import { PAGE_TEMPLATES } from "@/app/lib/pageTemplates";
// The server's block rules (CmsBlockValidator) that a template can break, so a starter page never saves with an
// error staff did not make. The event and images are left for staff to choose.
function problems(blocks: CmsBlock[]): string[] {
const out: string[] = [];
const anchors = new Set<string>();
const len = (v: string | undefined, max: number, path: string, required = false) => {
if (required && !v?.trim()) out.push(`${path} required`);
if (v && v.length > max) out.push(`${path} too long`);
};
blocks.forEach((b, i) => {
const p = `blocks[${i}]`;
if (b.anchor) {
if (!ANCHOR.test(b.anchor) || anchors.has(b.anchor)) out.push(`${p}.anchor`);
anchors.add(b.anchor);
}
const label = !!b.buttonLabel?.trim();
if (label !== !!b.buttonUrl?.trim()) out.push(`${p} button pair`);
if (b.buttonUrl && !isSafeLink(b.buttonUrl)) out.push(`${p}.buttonUrl`);
if (b.buttonUrl?.startsWith("#") && !blocks.some((x) => x.anchor === b.buttonUrl!.slice(1))) out.push(`${p}.buttonUrl target`);
len(b.buttonLabel, 40, `${p}.buttonLabel`, b.type === "CTA");
len(b.heading, 120, `${p}.heading`, ["HERO", "FEATURES", "STEPS", "CTA"].includes(b.type));
len(b.text, 300, `${p}.text`);
if (b.type === "TRUST" && b.heading != null) out.push(`${p}.heading unused`);
if (["FEATURES", "STEPS", "TRUST"].includes(b.type)) {
const cards = b.cards ?? [];
if (cards.length < 2 || cards.length > 6) out.push(`${p}.cards count`);
cards.forEach((c, j) => {
const cp = `${p}.cards[${j}]`;
if (b.type === "FEATURES" ? !(c.icon && c.icon in ICONS) : c.icon != null) out.push(`${cp}.icon`);
len(c.title, 80, `${cp}.title`, true);
if (b.type === "TRUST" ? c.text != null : !c.text?.trim()) out.push(`${cp}.text`);
len(c.text, 300, `${cp}.text`);
});
} else if (b.cards) out.push(`${p}.cards unused`);
if (b.type === "FAQ") {
if (!b.items?.length) out.push(`${p}.items count`);
b.items?.forEach((it, j) => { len(it.question, 300, `${p}.items[${j}].question`, true); len(it.answer, 2000, `${p}.items[${j}].answer`, true); });
}
});
return out;
}
describe("page templates", () => {
it.each(PAGE_TEMPLATES)("$id passes the server's block rules", (tpl) => {
expect(problems(pageBody({ ...emptyPage(), blocks: tpl.blocks() }).blocks)).toEqual([]);
});
it("the rules catch a broken block", () => {
expect(problems([{ type: "CTA", heading: "x", buttonLabel: "Go", buttonUrl: "#nowhere" }])).toEqual(["blocks[0].buttonUrl target"]);
});
it.each(PAGE_TEMPLATES)("$id ends with a sign-up form named signup and no event", (tpl) => {
const blocks = tpl.blocks();
expect(blocks.at(-1)).toMatchObject({ type: "FORM", anchor: "signup", eventUuid: null });
});
it("the sections are as designed", () => {
expect(PAGE_TEMPLATES.map((t) => t.blocks().map((b) => b.type + (b.look ? `:${b.look}` : "")))).toEqual([
["HERO:DARK", "TRUST", "FEATURES", "STEPS:MUTED", "FAQ", "FORM:MUTED"],
["HERO:DARK", "TRUST", "FEATURES", "STEPS", "FAQ", "CTA:ACCENT", "FORM:MUTED"],
]);
});
it("each use gets fresh blocks", () => {
const [a, b] = [PAGE_TEMPLATES[0].blocks(), PAGE_TEMPLATES[0].blocks()];
expect(a[0]).not.toBe(b[0]);
});
});
@@ -0,0 +1,62 @@
import type { CmsBlock } from "@/app/lib/cmsPages";
// add-page-drafts-and-templates: starter pages for marketing staff. Placeholder text in English, no images, the
// sign-up form without an event (staff choose it) and named "signup" so every button can link to it.
export interface PageTemplate {
id: "EVENT" | "SHOWCASE";
label: string;
description: string;
blocks: () => CmsBlock[];
}
const hero = (): CmsBlock => ({
type: "HERO", look: "DARK", heading: "Your event headline",
text: "One or two sentences on what visitors get and why they should come.",
buttonLabel: "Sign up now", buttonUrl: "#signup",
});
const trust = (): CmsBlock => ({
type: "TRUST", cards: [{ title: "Trusted by 500+ customers" }, { title: "Local support team" }, { title: "Free consultation" }],
});
const features = (): CmsBlock => ({
type: "FEATURES", heading: "What you get", text: "A short line introducing the benefits.",
cards: [
{ icon: "star", title: "First benefit", text: "Describe the first benefit in a sentence." },
{ icon: "shield-check", title: "Second benefit", text: "Describe the second benefit in a sentence." },
{ icon: "headset", title: "Third benefit", text: "Describe the third benefit in a sentence." },
],
});
const steps = (look?: CmsBlock["look"]): CmsBlock => ({
type: "STEPS", ...(look ? { look } : {}), heading: "How it works",
cards: [
{ title: "Sign up", text: "Fill in the form below." },
{ title: "We contact you", text: "Our team calls you to confirm the details." },
{ title: "Enjoy", text: "Say what happens next." },
],
});
const faq = (): CmsBlock => ({
type: "FAQ", heading: "Questions",
items: [
{ question: "A question visitors often ask?", answer: "The answer to it." },
{ question: "Another common question?", answer: "The answer to it." },
],
});
const form = (): CmsBlock => ({ type: "FORM", look: "MUTED", anchor: "signup", heading: "Sign up", eventUuid: null });
export const PAGE_TEMPLATES: PageTemplate[] = [
{
id: "EVENT", label: "PagesTemplateEvent", description: "PagesTemplateEventHint",
blocks: () => [hero(), trust(), features(), steps("MUTED"), faq(), form()],
},
{
id: "SHOWCASE", label: "PagesTemplateShowcase", description: "PagesTemplateShowcaseHint",
blocks: () => [hero(), trust(), features(), steps(), faq(),
{ type: "CTA", look: "ACCENT", heading: "Ready to start?", text: "One line that asks visitors to act.", buttonLabel: "Sign up", buttonUrl: "#signup" },
form()],
},
];
@@ -0,0 +1,81 @@
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
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 NewLandingPage from "./page";
// add-page-drafts-and-templates: New page starts from Blank or a template; Duplicate starts from a copy.
const published = {
id: 5, companyId: 2, slug: "hotel", title: "Hotel day", metaDescription: null, status: "PUBLISHED" as const, hideHeader: false,
blocks: [{ type: "CTA" as const, heading: "Live", buttonLabel: "Go", buttonUrl: "/x" }],
draft: { slug: "hotel", title: "Hotel day", metaDescription: null, hideHeader: true, blocks: [{ type: "CTA" as const, heading: "Draft", buttonLabel: "Go", buttonUrl: "/x" }] },
};
beforeEach(() => {
vi.clearAllMocks();
memoryRouter.reset("/pages/new");
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => m === "BO_PAGES", 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(published);
mocks.savePage.mockImplementation(async (_id: unknown, body: object) => ({ ...published, ...body, id: 8, draft: null }));
});
describe("New page", () => {
it("offers Blank and the two templates first", async () => {
render(<NewLandingPage />);
expect(await screen.findByRole("link", { name: /Blank page/ })).toHaveAttribute("href", "/pages/new?template=BLANK");
expect(screen.getByRole("link", { name: /Event sign-up/ })).toHaveAttribute("href", "/pages/new?template=EVENT");
expect(screen.getByRole("link", { name: /Service showcase/ })).toHaveAttribute("href", "/pages/new?template=SHOWCASE");
expect(screen.queryByLabelText("Title")).not.toBeInTheDocument();
});
it("a template fills the editor with its sections", async () => {
memoryRouter.reset("/pages/new", "template=EVENT");
render(<NewLandingPage />);
expect(await screen.findByDisplayValue("Your event headline")).toBeInTheDocument();
for (const legend of ["Block 1: Hero", "Block 2: Trust strip", "Block 3: Feature cards", "Block 4: Steps", "Block 5: FAQ", "Block 6: Sign-up form"]) {
expect(screen.getByText(legend)).toBeInTheDocument();
}
expect(screen.getByLabelText("Event")).toBeInTheDocument();
expect(mocks.savePage).not.toHaveBeenCalled();
});
it("Blank opens an empty editor", async () => {
memoryRouter.reset("/pages/new", "template=BLANK");
render(<NewLandingPage />);
expect(await screen.findByLabelText("Title")).toHaveValue("");
expect(screen.queryByLabelText("Heading")).not.toBeInTheDocument();
});
it("Duplicate copies the current content as a new draft page of the same company", async () => {
memoryRouter.reset("/pages/new", "from=5");
const user = userEvent.setup();
render(<NewLandingPage />);
expect(await screen.findByLabelText("Title")).toHaveValue("Hotel day (copy)");
expect(screen.getByLabelText("Slug")).toHaveValue("hotel-copy");
expect(screen.getByLabelText("Heading")).toHaveValue("Draft");
expect(screen.getByLabelText("Draft")).toBeChecked();
expect(screen.queryByRole("link", { name: "View page" })).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalled());
const [id, body] = mocks.savePage.mock.calls[0];
expect(id).toBeUndefined();
expect(body).toMatchObject({ companyId: 2, slug: "hotel-copy", title: "Hotel day (copy)", status: "DRAFT", hideHeader: true });
expect(body.blocks).toEqual([{ type: "CTA", heading: "Draft", buttonLabel: "Go", buttonUrl: "/x" }]);
});
});
+33 -4
View File
@@ -1,19 +1,46 @@
"use client";
import { Suspense } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { PageHeader } from "@/app/components/ui/page-header";
import { RequireModule } from "@/app/lib/RequireModule";
import { PageEditor } from "@/app/components/pages/PageEditor";
import { PAGE_TEMPLATES } from "@/app/lib/pageTemplates";
import { useT } from "@/app/lib/i18n/MessagesProvider";
// New page: staff first pick Blank or a starter template; ?from=<id> (Duplicate) opens a copy of that page.
const CHOICES = [{ id: "BLANK", label: "PagesStartBlank", description: "PagesStartBlankHint" }, ...PAGE_TEMPLATES];
function NewPageContent() {
const t = useT();
const params = useSearchParams();
const from = params?.get("from");
const fromId = from && /^\d+$/.test(from) ? Number(from) : undefined;
const choice = params?.get("template");
const template = PAGE_TEMPLATES.find((tpl) => tpl.id === choice);
const picked = fromId != null || choice === "BLANK" || template != null;
return (
<>
<PageHeader title={t("PagesNew")} />
<Suspense>
<PageEditor />
</Suspense>
{picked ? (
<PageEditor key={`${from}-${choice}`} fromId={fromId} initialBlocks={template?.blocks()} />
) : (
<div className="space-y-3">
<p className="text-sm text-muted-foreground">{t("PagesChooseStart")}</p>
<ul className="grid gap-3 sm:grid-cols-3">
{CHOICES.map((c) => (
<li key={c.id}>
<Link href={`/pages/new?template=${c.id}`}
className="block h-full rounded-lg border bg-card p-4 hover:border-primary focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
<span className="block font-medium">{t(c.label)}</span>
<span className="mt-1 block text-sm text-muted-foreground">{t(c.description)}</span>
</Link>
</li>
))}
</ul>
</div>
)}
</>
);
}
@@ -21,7 +48,9 @@ function NewPageContent() {
export default function NewLandingPage() {
return (
<RequireModule pathname="/pages">
<NewPageContent />
<Suspense>
<NewPageContent />
</Suspense>
</RequireModule>
);
}
@@ -56,6 +56,15 @@ describe("PagesPage", () => {
expect(await screen.findByText("Unpublished changes")).toBeInTheDocument();
});
it("offers Duplicate on each row", async () => {
mocks.listPages.mockResolvedValue({
items: [{ id: 5, companyId: 2, slug: "hotel-tech", title: "Hotel tech", status: "PUBLISHED", metaDescription: null, blocks: [] }],
total: 1,
});
render(<PagesPage />);
expect(await screen.findByRole("link", { name: "Duplicate Hotel tech" })).toHaveAttribute("href", "/pages/new?from=5");
});
it("searches by title", async () => {
mocks.listPages.mockResolvedValue({ items: [], total: 0 });
const user = userEvent.setup();
+10
View File
@@ -83,6 +83,16 @@ function PagesPageContent() {
header: t("PagesUpdated"),
cell: ({ row }) => <span className="tabular">{row.original.updatedAt ? formatEmailDate(row.original.updatedAt) : ""}</span>,
},
{
id: "actions",
header: () => <span className="sr-only">{t("CatActions")}</span>,
cell: ({ row }) => (
<Link href={`/pages/new?from=${row.original.id}`} aria-label={t("PagesDuplicateNamed", { title: row.original.title })}
className="text-sm text-primary underline-offset-4 hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
{t("PagesDuplicate")}
</Link>
),
},
], [t, showCompanyColumn, codeOf, companyCode]);
return (