feat(pages): page canvas and in-place editing of landing page text

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:15:32 +08:00
1 parent 537ac65dc0
commit 54ceb7b631
9 files changed
+387 -49

No files matched your search

+2
View File
@@ -1497,6 +1497,8 @@ INSERT INTO message (code, content, area) SELECT 'PagesLeaveMessage', JSON_OBJEC
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 'PagesSaveToUpdate', JSON_OBJECT('en_US', 'Save to update', 'zh_CN', '保存后更新'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesSaveToUpdate') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '保存后更新') WHERE LOWER(code) = LOWER('PagesSaveToUpdate') 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');
@@ -22,8 +22,8 @@ Design: `design.md`. Every task is TDD. Work is serial in the main session, with
## 2. Canvas
- [ ] 2.1 `PageCanvas`: the frame, the Desktop view (1280 px scaled) and the Phone view (390 px), live updates from the draft, and links and buttons inert.
- [ ] 2.2 Edit-mode hooks in `CmsBlocks`: `EditContext`, `EditableText` for every plain text field with its server limit, image spots, `Section` outline and `data-index`. Public rendering stays unchanged: the existing `CmsBlocks*.test.tsx` stay green.
- [x] 2.1 `PageCanvas`: the frame, the Desktop view (1280 px scaled) and the Phone view (390 px), live updates from the draft, and links and buttons inert.
- [x] 2.2 Edit-mode hooks in `CmsBlocks`: `EditContext`, `EditableText` for every plain text field with its server limit, image spots, `Section` outline and `data-index`. Public rendering stays unchanged: the existing `CmsBlocks*.test.tsx` stay green.
- [ ] 2.3 Rich text in place: `RichTextEditor` bare mode with a floating toolbar (test: an unsafe link is refused with a message).
- [ ] 2.4 Custom HTML on the canvas: the saved-draft frame, the "Save to update" mark, and a reload after save.
@@ -0,0 +1,104 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import { describe, it, expect, vi } from "vitest";
import { LandingPage, type PublicBlock } from "./CmsBlocks";
import { setField, type PageEdit } from "./CmsEdit";
// add-page-visual-editor: the page in edit mode. Text edits in place, sections select, images open the picker, and
// nothing navigates. Without `edit` the page renders exactly as before (CmsBlocks*.test.tsx).
const company = { code: "INS", name: "INS Sdn Bhd" };
const page = (blocks: PublicBlock[]) => ({ slug: "hotel", title: "Hotel day", blocks });
function editor(overrides: Partial<PageEdit> = {}): PageEdit {
return {
selected: null, select: vi.fn(), text: vi.fn(), html: vi.fn(), image: vi.fn(),
preview: () => undefined, stale: () => false, frameVersion: 0, chrome: () => null, ...overrides,
};
}
const typeInto = (el: HTMLElement, value: string) => { el.textContent = value; fireEvent.input(el); };
describe("LandingPage in edit mode", () => {
it("edits a heading, a card title and a FAQ answer in place as plain text", () => {
const edit = editor();
render(<LandingPage company={company} page={page([
{ type: "HERO", heading: "Hotel week" },
{ type: "FEATURES", heading: "Why", cards: [{ title: "A" }, { title: "B" }] },
{ type: "FAQ", items: [{ question: "Q", answer: "A1" }] },
])} edit={edit} preview />);
const heading = screen.getAllByRole("textbox", { name: "Heading" })[0];
expect(heading).toHaveAttribute("contenteditable", "plaintext-only");
expect(heading).toHaveTextContent("Hotel week");
typeInto(heading, "Hotel month");
expect(edit.text).toHaveBeenLastCalledWith(0, "heading", "Hotel month");
typeInto(screen.getAllByRole("textbox", { name: "Title" })[1], "Second");
expect(edit.text).toHaveBeenLastCalledWith(1, "cards.1.title", "Second");
typeInto(screen.getByRole("textbox", { name: "Answer 1" }), "Yes\nno");
expect(edit.text).toHaveBeenLastCalledWith(2, "items.0.answer", "Yes\nno");
});
it("offers an empty heading as a spot to type, and shows the limit once close to it", () => {
render(<LandingPage company={company} page={page([{ type: "CTA", heading: "x".repeat(100) }, { type: "FEATURES", cards: [{ title: "A" }, { title: "B" }] }])} edit={editor()} preview />);
expect(screen.getByText("100/120")).toBeInTheDocument();
expect(screen.getAllByRole("textbox", { name: "Heading" })[1]).toHaveTextContent("");
});
it("selects a section on click, outlines the selected one, and draws the editor's tools in it", () => {
const edit = editor({ selected: 1, chrome: (i) => <span>tools {i}</span> });
render(<LandingPage company={company} page={page([{ type: "CTA", heading: "One" }, { type: "CTA", heading: "Two" }])} edit={edit} preview />);
const sections = document.querySelectorAll("[data-index]");
expect([...sections].map((s) => s.getAttribute("data-index"))).toEqual(["0", "1"]);
expect(sections[1]).toHaveAttribute("data-selected", "true");
expect(sections[0]).not.toHaveAttribute("data-selected");
expect(within(sections[1] as HTMLElement).getByText("tools 1")).toBeInTheDocument();
fireEvent.click(sections[0]);
expect(edit.select).toHaveBeenCalledWith(0);
});
it("keeps links and buttons from navigating, and edits a button's label", () => {
const edit = editor();
render(<LandingPage company={company} page={page([{ type: "CTA", heading: "Go", buttonLabel: "Join", buttonUrl: "https://example.com" }])} edit={edit} preview />);
const label = screen.getByRole("textbox", { name: "Button label" });
const link = label.closest("a")!;
expect(fireEvent.click(link)).toBe(false); // default prevented
typeInto(label, "Join now");
expect(edit.text).toHaveBeenLastCalledWith(0, "buttonLabel", "Join now");
});
it("opens the picker from an image spot and shows a chosen image before it is saved", () => {
const edit = editor({ preview: (i) => (i === 0 ? "data:image/png;base64,AAAA" : undefined) });
render(<LandingPage company={company} page={page([{ type: "IMAGE_TEXT", heading: "Pic", imageId: 4 }, { type: "IMAGE_TEXT", heading: "None" }])} edit={edit} preview />);
const spots = screen.getAllByRole("button", { name: "Image" });
expect(spots).toHaveLength(2);
expect(spots[0].querySelector("img")).toHaveAttribute("src", "data:image/png;base64,AAAA");
fireEvent.click(spots[1]);
expect(edit.image).toHaveBeenCalledWith(1);
});
it("shows a Custom HTML block's saved version, selectable, marked while its HTML has unsaved edits", () => {
const edit = editor({ stale: (i) => i === 0, frameVersion: 3 });
render(<LandingPage company={company} page={page([{ type: "HTML", html: "<p>x</p>" }])} edit={edit} preview frameBase="/pages/5/preview/frame" />);
expect(document.querySelector("iframe")).toHaveAttribute("src", "/pages/5/preview/frame/0?v=3");
expect(screen.getByText("Save to update")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Custom HTML" }));
expect(edit.select).toHaveBeenCalledWith(0);
});
it("renders no editing without edit mode", () => {
render(<LandingPage company={company} page={page([{ type: "HERO", heading: "Hotel week" }, { type: "IMAGE_TEXT", heading: "Pic", imageId: 4 }])} />);
expect(document.querySelector("[contenteditable]")).toBeNull();
expect(document.querySelector("[data-index]")).toBeNull();
expect(screen.queryByRole("button")).toBeNull();
expect(screen.getByRole("heading", { level: 2, name: "Hotel week" })).toBeInTheDocument();
});
});
describe("setField", () => {
it("sets a top-level field or one inside a card or question, leaving the rest", () => {
const block = { type: "FEATURES" as const, heading: "H", cards: [{ title: "A", text: "a" }, { title: "B" }] };
expect(setField(block, "heading", "New")).toEqual({ ...block, heading: "New" });
expect(setField(block, "cards.1.title", "C").cards).toEqual([{ title: "A", text: "a" }, { title: "C" }]);
expect(block.cards[1].title).toBe("B");
expect(setField({ type: "FAQ", items: [{ question: "Q", answer: "A" }] }, "items.0.answer", "Z").items).toEqual([{ question: "Q", answer: "Z" }]);
});
});
@@ -4,6 +4,7 @@ import type { RegistrationInfo } from "@/app/lib/services/publicRegistration";
import { SafeHtml } from "./SafeHtml";
import { LandingForm } from "./LandingForm";
import { HtmlFrame } from "./HtmlFrame";
import { EditContext, EditSection, HeroShade, HtmlSpot, ImageSpot, Text, stopNavigation, type PageEdit } from "./CmsEdit";
// Landing-page blocks, ported from babyboo's CmsBlocks minus the product blocks. HTML only goes through SafeHtml;
// images are this company's uploads; buttons render only for a safe link, checked again here. A Custom HTML block is
@@ -28,34 +29,34 @@ const BANDS: Record<Exclude<Look, "DEFAULT">, string> = {
};
const bandOf = (look: unknown) => (LOOKS.includes(look as Look) && look !== "DEFAULT" ? (look as Exclude<Look, "DEFAULT">) : null);
function ButtonLink({ block }: { block: CmsBlock }) {
if (!block.buttonLabel || !isSafeLink(block.buttonUrl)) return null;
function ButtonLink({ block, index, edit }: { block: CmsBlock; index: number; edit?: boolean }) {
// In edit mode a button with a label shows whatever its link, so its label can be typed in place.
if (!block.buttonLabel || (!edit && !isSafeLink(block.buttonUrl))) return null;
const external = /^https:/i.test(block.buttonUrl!);
const colours = bandOf(block.look) === "ACCENT" ? "bg-background text-foreground" : "bg-primary text-primary-foreground";
return (
<a href={block.buttonUrl} {...(external ? { target: "_blank", rel: "noopener noreferrer" } : {})}
className={`inline-flex h-11 items-center rounded-md px-5 text-sm font-medium hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none ${colours}`}>
{block.buttonLabel}
<Text as="span" index={index} path="buttonLabel" value={block.buttonLabel} max={40} code="PagesButtonLabel" />
</a>
);
}
function BlockImage({ id, className }: { id?: number | null; className: string }) {
// eslint-disable-next-line @next/next/no-img-element -- an uploaded image of unknown size
return id ? <img src={imageSrc(id)} alt="" className={className} /> : null;
}
function Block({ block, index, company, slug, preview }: { block: PublicBlock; index: number; company: string; slug: string; preview?: boolean }) {
function Block({ block, index, company, slug, preview, edit }: { block: PublicBlock; index: number; company: string; slug: string; preview?: boolean; edit?: boolean }) {
const image = block.imageId ? imageSrc(block.imageId) : undefined;
const button = <ButtonLink block={block} index={index} edit={edit} />;
switch (block.type) {
case "HERO":
return (
<section className={`relative overflow-hidden rounded-lg ${bandOf(block.look) ? "" : "bg-muted"}`}>
<BlockImage id={block.imageId} className="absolute inset-0 h-full w-full object-cover" />
<div className={block.imageId ? "relative flex min-h-72 flex-col justify-end gap-3 bg-gradient-to-t from-black/80 via-black/50 to-transparent p-6 text-white sm:min-h-96" : "flex flex-col gap-3 p-6"}>
{block.heading ? <h2 className="text-3xl font-semibold sm:text-4xl">{block.heading}</h2> : null}
{block.text ? <p className="max-w-2xl text-lg">{block.text}</p> : null}
<div><ButtonLink block={block} /></div>
</div>
<ImageSpot index={index} src={image} className="absolute inset-0 h-full w-full object-cover" corner />
<HeroShade index={index} image={!!image}
shaded="relative flex min-h-72 flex-col justify-end gap-3 bg-gradient-to-t from-black/80 via-black/50 to-transparent p-6 text-white sm:min-h-96"
plain="flex flex-col gap-3 p-6">
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-3xl font-semibold sm:text-4xl" />
<Text as="p" index={index} path="text" value={block.text} max={300} code="PagesText" className="max-w-2xl text-lg" />
<div>{button}</div>
</HeroShade>
</section>
);
case "RICH_TEXT":
@@ -63,32 +64,43 @@ function Block({ block, index, company, slug, preview }: { block: PublicBlock; i
case "IMAGE_TEXT":
return (
<section className="grid items-center gap-6 md:grid-cols-2">
<BlockImage id={block.imageId} className={`w-full rounded-lg object-cover ${block.imagePosition === "RIGHT" ? "md:order-2" : ""}`} />
{image || edit ? (
<div className={block.imagePosition === "RIGHT" ? "md:order-2" : undefined}>
<ImageSpot index={index} src={image} className="w-full rounded-lg object-cover" />
</div>
) : null}
<div className="space-y-3">
{block.heading ? <h2 className="text-2xl font-semibold">{block.heading}</h2> : null}
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold" />
{block.html ? <SafeHtml html={block.html} className={PROSE} /> : null}
<ButtonLink block={block} />
{button}
</div>
</section>
);
case "FAQ":
return block.items?.length ? (
<section className="space-y-3">
{block.heading ? <h2 className="text-2xl font-semibold">{block.heading}</h2> : null}
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold" />
<div className="divide-y rounded-lg border">
{block.items.map((item, i) => (
<details key={i} name={`faq-${index}`} className="group p-4">
<summary className="cursor-pointer font-medium">{item.question}</summary>
<p className="mt-2 whitespace-pre-line text-muted-foreground">{item.answer}</p>
</details>
))}
{block.items.map((item, i) => {
const question = <Text as="span" index={index} path={`items.${i}.question`} value={item.question} max={300} code="PagesQuestionN" n={i + 1} />;
const answer = <Text as="p" index={index} path={`items.${i}.answer`} value={item.answer} max={2000} code="PagesAnswerN" n={i + 1} multiline className="mt-2 whitespace-pre-line text-muted-foreground" />;
// In edit mode every answer shows: a <summary> would toggle on a click or a typed space.
return edit ? (
<div key={i} className="p-4"><p className="font-medium">{question}</p>{answer}</div>
) : (
<details key={i} name={`faq-${index}`} className="group p-4">
<summary className="cursor-pointer font-medium">{item.question}</summary>
{answer}
</details>
);
})}
</div>
</section>
) : null;
case "FORM":
return (
<section className="mx-auto w-full max-w-md space-y-4 rounded-lg border bg-card p-6 shadow-card">
{block.heading ? <h2 className="text-2xl font-semibold">{block.heading}</h2> : null}
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold" />
<LandingForm companyCode={company} slug={slug} index={index} info={block.closed ? undefined : block.form} preview={preview} />
</section>
);
@@ -96,8 +108,8 @@ function Block({ block, index, company, slug, preview }: { block: PublicBlock; i
return (
<section className="space-y-6">
<div className="max-w-2xl space-y-2">
{block.heading ? <h2 className="text-2xl font-semibold sm:text-3xl">{block.heading}</h2> : null}
{block.text ? <p className="text-lg opacity-80">{block.text}</p> : null}
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold sm:text-3xl" />
<Text as="p" index={index} path="text" value={block.text} max={300} code="PagesText" className="text-lg opacity-80" />
</div>
<ul className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{(block.cards ?? []).map((card, i) => {
@@ -105,8 +117,8 @@ function Block({ block, index, company, slug, preview }: { block: PublicBlock; i
return (
<li key={i} className="space-y-2 rounded-lg border bg-card p-5 text-card-foreground shadow-card">
{Icon ? <Icon aria-hidden="true" className="size-7 text-primary" /> : null}
<h3 className="text-lg font-semibold">{card.title}</h3>
<p className="text-muted-foreground">{card.text}</p>
<Text as="h3" index={index} path={`cards.${i}.title`} value={card.title} max={80} code="PagesCardTitle" className="text-lg font-semibold" />
<Text as="p" index={index} path={`cards.${i}.text`} value={card.text} max={300} code="PagesCardText" className="text-muted-foreground" />
</li>
);
})}
@@ -116,14 +128,14 @@ function Block({ block, index, company, slug, preview }: { block: PublicBlock; i
case "STEPS":
return (
<section className="space-y-6">
{block.heading ? <h2 className="text-2xl font-semibold sm:text-3xl">{block.heading}</h2> : null}
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold sm:text-3xl" />
<ol className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
{(block.cards ?? []).map((card, i) => (
<li key={i} className="flex gap-4">
<span aria-hidden="true" className="flex size-10 shrink-0 items-center justify-center rounded-full border-2 border-current text-lg font-semibold">{i + 1}</span>
<div className="space-y-1">
<h3 className="text-lg font-semibold">{card.title}</h3>
<p className="opacity-80">{card.text}</p>
<Text as="h3" index={index} path={`cards.${i}.title`} value={card.title} max={80} code="PagesCardTitle" className="text-lg font-semibold" />
<Text as="p" index={index} path={`cards.${i}.text`} value={card.text} max={300} code="PagesCardText" className="opacity-80" />
</div>
</li>
))}
@@ -134,16 +146,16 @@ function Block({ block, index, company, slug, preview }: { block: PublicBlock; i
return (
<section>
<ul className="flex flex-wrap items-center justify-center gap-x-8 gap-y-2 text-center font-medium">
{(block.cards ?? []).map((card, i) => <li key={i}>{card.title}</li>)}
{(block.cards ?? []).map((card, i) => <li key={i}><Text as="span" index={index} path={`cards.${i}.title`} value={card.title} max={80} code="PagesCardTitle" /></li>)}
</ul>
</section>
);
case "CTA":
return (
<section className="flex flex-col items-center gap-4 py-4 text-center">
<h2 className="text-2xl font-semibold sm:text-3xl">{block.heading}</h2>
{block.text ? <p className="max-w-2xl text-lg opacity-80">{block.text}</p> : null}
<ButtonLink block={block} />
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold sm:text-3xl" />
<Text as="p" index={index} path="text" value={block.text} max={300} code="PagesText" className="max-w-2xl text-lg opacity-80" />
{button}
</section>
);
default:
@@ -154,13 +166,15 @@ function Block({ block, index, company, slug, preview }: { block: PublicBlock; i
const WIDTH = "mx-auto w-full max-w-5xl px-4";
/** A block in the page width; with a non-default look, inside a full-width band of that colour. */
function Section({ block, children }: { block: PublicBlock; children: ReactNode }) {
function Section({ block, index, children }: { block: PublicBlock; index: number; children: ReactNode }) {
const band = bandOf(block.look);
if (!band) return <div id={anchorId(block.anchor)} className={WIDTH}>{children}</div>;
if (!band) return <EditSection index={index}><div id={anchorId(block.anchor)} className={WIDTH}>{children}</div></EditSection>;
return (
<div id={anchorId(block.anchor)} data-look={band} className={`py-12 ${BANDS[band]}`}>
<div className={WIDTH}>{children}</div>
</div>
<EditSection index={index}>
<div id={anchorId(block.anchor)} data-look={band} className={`py-12 ${BANDS[band]}`}>
<div className={WIDTH}>{children}</div>
</div>
</EditSection>
);
}
@@ -168,7 +182,7 @@ function Section({ block, children }: { block: PublicBlock; children: ReactNode
* A whole landing page: the company header (logo, accent), the title as the only h1, then the blocks. Custom HTML
* blocks run full width; with hideHeader the header goes and the title is for screen readers only.
*/
export function LandingPage({ company, page, banner, preview, frameBase }: {
export function LandingPage({ company, page, banner, preview, frameBase, edit }: {
company: Branding;
page: { slug: string; title: string; hideHeader?: boolean; blocks: PublicBlock[] };
banner?: ReactNode;
@@ -176,12 +190,14 @@ export function LandingPage({ company, page, banner, preview, frameBase }: {
preview?: boolean;
/** Where block frames load from; the public page's frame address by default. */
frameBase?: string;
/** The on-page editor's canvas (add-page-visual-editor): text edits in place and nothing navigates. */
edit?: PageEdit;
}) {
const frames = frameBase ?? `/p/${encodeURIComponent(company.code)}/${encodeURIComponent(page.slug)}/frame`;
const accent = company.accentColor && /^#[0-9A-Fa-f]{6}$/.test(company.accentColor) ? company.accentColor : null;
const style = accent ? ({ "--primary": accent, "--primary-foreground": contrastText(accent), "--ring": accent } as CSSProperties) : undefined;
return (
<div style={style} className="min-h-svh bg-background">
const body = (
<div style={style} className="min-h-svh bg-background" onClickCapture={edit ? stopNavigation : undefined}>
{banner}
{page.hideHeader ? null : <header className="border-b bg-card">
<div className="mx-auto flex max-w-5xl items-center gap-3 px-4 py-3">
@@ -197,10 +213,11 @@ export function LandingPage({ company, page, banner, preview, frameBase }: {
<h1 className={page.hideHeader ? "sr-only" : `${WIDTH} mb-10 text-3xl font-semibold sm:text-4xl`}>{page.title}</h1>
<div className="space-y-10">
{page.blocks.map((block, i) => block.type === "HTML"
? <HtmlFrame key={i} id={anchorId(block.anchor)} src={`${frames}/${i}`} title={page.title} />
: <Section key={i} block={block}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} /></Section>)}
? <HtmlSpot key={i} index={i}><HtmlFrame id={anchorId(block.anchor)} src={`${frames}/${i}${edit ? `?v=${edit.frameVersion}` : ""}`} title={page.title} /></HtmlSpot>
: <Section key={i} block={block} index={i}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} edit={!!edit} /></Section>)}
</div>
</main>
</div>
);
return edit ? <EditContext.Provider value={edit}>{body}</EditContext.Provider> : body;
}
@@ -0,0 +1,160 @@
"use client";
import { createContext, useContext, useLayoutEffect, useRef, type ElementType, type FormEvent, type KeyboardEvent, type MouseEvent, type ReactNode } from "react";
import { ImagePlus } from "lucide-react";
import { BLOCK_LABELS, type CmsBlock } from "@/app/lib/cmsPages";
import { useT } from "@/app/lib/i18n/MessagesProvider";
// add-page-visual-editor: the landing page in edit mode, on the on-page editor's canvas. The public page and the
// preview never provide an edit context, so every part here renders exactly the public markup without one.
export interface PageEdit {
/** The selected block's index, or null. */
selected: number | null;
select(index: number): void;
/** A plain text field changed: `path` is "heading", "text", "buttonLabel", "cards.<i>.title|text" or "items.<i>.question|answer". */
text(index: number, path: string, value: string): void;
/** A rich text block's HTML changed. */
html(index: number, html: string): void;
/** An image spot was clicked: the editor opens its file picker. */
image(index: number): void;
/** A chosen image not yet uploaded, as a data URL. */
preview(index: number): string | undefined;
/** A Custom HTML block whose HTML has unsaved edits: its frame still shows the saved version. */
stale(index: number): boolean;
/** Bumped after each save, so Custom HTML frames reload the saved version. */
frameVersion: number;
/** The editor's own tools for a selected section (toolbar, add section). */
chrome(index: number): ReactNode;
}
export const EditContext = createContext<PageEdit | null>(null);
export const useEdit = () => useContext(EditContext);
/** The block with one plain text field set, by its path (see PageEdit.text). */
export function setField(block: CmsBlock, path: string, value: string): CmsBlock {
const [list, at, key] = path.split(".");
if (key === undefined) return { ...block, [list]: value };
const items = [...((block[list as "cards" | "items"] ?? []) as object[])];
items[Number(at)] = { ...items[Number(at)], [key]: value };
return { ...block, [list]: items };
}
/**
* A plain text field: the text as-is on the public page; in edit mode the same element, typed into in place. It is
* never re-rendered from its value while focused, so the caret stays where it is.
*/
export function Text({ as: Tag, index, path, value, max, code, n, className, multiline }: {
as: ElementType;
index: number;
path: string;
value: string | undefined;
max: number;
/** The field's label code, the editable's name; `n` fills its {number}. */
code: string;
n?: number;
className?: string;
multiline?: boolean;
}) {
const edit = useEdit();
if (!edit) return value ? <Tag className={className}>{value}</Tag> : null;
return <EditableText as={Tag} edit={edit} index={index} path={path} value={value ?? ""} max={max} code={code} n={n} className={className} multiline={multiline} />;
}
function EditableText({ as: Tag, edit, index, path, value, max, code, n, className, multiline }: {
as: ElementType; edit: PageEdit; index: number; path: string; value: string; max: number; code: string; n?: number; className?: string; multiline?: boolean;
}) {
const t = useT();
const ref = useRef<HTMLElement>(null);
useLayoutEffect(() => {
const el = ref.current;
if (el && el.ownerDocument.activeElement !== el && el.textContent !== value) el.textContent = value;
}, [value]);
const near = value.length > max * 0.8;
const name = t(code, n === undefined ? undefined : { number: n });
return (
<>
<Tag ref={ref} role="textbox" aria-label={name} aria-multiline={multiline || undefined} contentEditable="plaintext-only"
suppressContentEditableWarning data-placeholder={name}
className={`${className ?? ""} cursor-text rounded-sm outline-none hover:outline-dashed hover:outline-1 hover:outline-primary/50 focus:outline-2 focus:outline-primary empty:before:opacity-50 empty:before:content-[attr(data-placeholder)]`}
onInput={(e: FormEvent<HTMLElement>) => edit.text(index, path, e.currentTarget.textContent ?? "")}
onKeyDown={(e: KeyboardEvent) => { if (e.key === "Enter" && !multiline) e.preventDefault(); }} />
{near ? <span aria-live="polite" className={`text-xs tabular-nums ${value.length > max ? "text-destructive" : "opacity-60"}`}>{`${value.length}/${max}`}</span> : null}
</>
);
}
/**
* An image of a block: in edit mode a button that opens the editor's file picker, showing a chosen image at once.
* A background image (`corner`) stays as it is, with a small button in the corner instead.
*/
export function ImageSpot({ index, src, className, corner }: { index: number; src: string | undefined; className: string; corner?: boolean }) {
const t = useT();
const edit = useEdit();
const shown = edit?.preview(index) ?? src;
// eslint-disable-next-line @next/next/no-img-element -- an uploaded image of unknown size
const img = shown ? <img src={shown} alt="" className={className} /> : null;
if (!edit) return img;
const open = (e: MouseEvent) => { e.stopPropagation(); edit.select(index); edit.image(index); };
if (corner) {
return (
<>
{img}
<button type="button" aria-label={t("PagesImage")} onClick={open}
className="absolute top-3 right-3 z-10 flex size-10 cursor-pointer items-center justify-center rounded-full bg-background/90 text-foreground shadow hover:bg-background">
<ImagePlus aria-hidden="true" className="size-5" />
</button>
</>
);
}
return (
<button type="button" aria-label={t("PagesImage")} onClick={open}
className={`group/img relative block w-full cursor-pointer ${shown ? "" : "flex min-h-40 items-center justify-center rounded-lg border-2 border-dashed border-current/30"}`}>
{img ?? <ImagePlus aria-hidden="true" className="size-8 opacity-60" />}
<span className="absolute inset-0 rounded-lg ring-primary group-hover/img:ring-2" />
</button>
);
}
/** In edit mode, the whole page: clicks never follow a link or submit. */
export function stopNavigation(e: MouseEvent) {
if ((e.target as Element).closest("a[href], button[type=submit], form")) e.preventDefault();
}
/** A section's frame in edit mode: selected on click, outlined when hovered or selected, with the editor's tools. */
export function EditSection({ index, children }: { index: number; children: ReactNode }) {
const edit = useEdit();
if (!edit) return <>{children}</>;
const selected = edit.selected === index;
return (
<div data-index={index} data-selected={selected || undefined} onClick={() => edit.select(index)}
className={`relative outline-offset-2 hover:outline-dashed hover:outline-1 hover:outline-primary/60 ${selected ? "outline-2 outline-primary hover:outline-solid hover:outline-2" : ""}`}>
{children}
{edit.chrome(index)}
</div>
);
}
/** A Custom HTML block in edit mode: its saved version, covered so a click selects it, marked while unsaved. */
export function HtmlSpot({ index, children }: { index: number; children: ReactNode }) {
const t = useT();
const edit = useEdit();
if (!edit) return <>{children}</>;
return (
<EditSection index={index}>
<div className="relative">
{children}
<button type="button" aria-label={t(BLOCK_LABELS.HTML)} className="absolute inset-0 cursor-pointer" onClick={() => edit.select(index)} />
{edit.stale(index) ? (
<span className="absolute top-2 left-2 rounded-md border border-warning/40 bg-background px-2 py-1 text-xs font-medium text-warning shadow">{t("PagesSaveToUpdate")}</span>
) : null}
</div>
</EditSection>
);
}
/** The hero's text area: shaded over an image, including one chosen in the editor and not saved yet. */
export function HeroShade({ index, image, shaded, plain, children }: { index: number; image: boolean; shaded: string; plain: string; children: ReactNode }) {
const edit = useEdit();
return <div className={image || edit?.preview(index) ? shaded : plain}>{children}</div>;
}
@@ -0,0 +1,17 @@
import { render, waitFor, within } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import { PageCanvas } from "./PageCanvas";
// add-page-visual-editor: the canvas is a device screen, Desktop 1280 px (scaled to fit) or Phone 390 px.
const frame = () => document.querySelector("iframe") as HTMLIFrameElement;
describe("PageCanvas", () => {
it("shows the page on a 1280 px desktop screen or a 390 px phone screen", async () => {
const { rerender } = render(<PageCanvas device="DESKTOP" title="Canvas"><p>Hello</p></PageCanvas>);
expect(frame()).toHaveStyle({ width: "1280px" });
await waitFor(() => expect(within(frame().contentDocument!.body).getByText("Hello")).toBeInTheDocument());
rerender(<PageCanvas device="PHONE" title="Canvas"><p>Hello</p></PageCanvas>);
expect(frame()).toHaveStyle({ width: "390px" });
expect(within(frame().contentDocument!.body).getByText("Hello")).toBeInTheDocument();
});
});
@@ -0,0 +1,36 @@
"use client";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { CanvasFrame } from "./CanvasFrame";
export type Device = "DESKTOP" | "PHONE";
/**
* The on-page editor's canvas (add-page-visual-editor, design Decision 2): the page on a device screen. Desktop is a
* 1280 px screen scaled down to the space it has, so a laptop shows the desktop layout; Phone is 390 px at full size.
*/
export function PageCanvas({ device, title, children }: { device: Device; title: string; children: ReactNode }) {
const box = useRef<HTMLDivElement>(null);
const [space, setSpace] = useState({ width: 0, height: 0 });
useEffect(() => {
const el = box.current;
if (!el) return;
const measure = () => setSpace({ width: el.clientWidth, height: el.clientHeight });
const observer = new ResizeObserver(measure);
observer.observe(el);
measure();
return () => observer.disconnect();
}, []);
const width = device === "PHONE" ? 390 : 1280;
const scale = device === "PHONE" || !space.width ? 1 : Math.min(1, space.width / width);
const height = (space.height || 800) / scale;
return (
<div ref={box} className="h-full min-h-0 w-full overflow-hidden">
<div className={`mx-auto overflow-hidden ${device === "PHONE" ? "rounded-xl border shadow-card" : ""}`} style={{ width: width * scale, height: height * scale }}>
<div style={{ width, transform: scale === 1 ? undefined : `scale(${scale})`, transformOrigin: "top left" }}>
<CanvasFrame width={width} height={height} title={title}>{children}</CanvasFrame>
</div>
</div>
</div>
);
}
@@ -760,6 +760,7 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
PagesLeaveTitle: "Leave without saving?",
PagesLeaveMessage: "Your changes to this page are not saved. Leave and lose them?",
PagesLeave: "Leave",
PagesSaveToUpdate: "Save to update",
PagesChangesPublished: "Changes published.",
PagesChangesDiscarded: "Changes discarded.",
PagesPreviewDraftBanner: "Preview of unpublished changes. Visitors still see the published version.",
@@ -744,6 +744,7 @@
"PagesLeaveTitle": "不保存就离开?",
"PagesLeaveMessage": "此页面的修改尚未保存。离开将丢失这些修改,确定离开吗?",
"PagesLeave": "离开",
"PagesSaveToUpdate": "保存后更新",
"PagesChangesPublished": "修改已发布。",
"PagesChangesDiscarded": "修改已放弃。",
"PagesPreviewDraftBanner": "未发布修改的预览。访客看到的仍是已发布的版本。",