feat(pages): edit rich text in place on the canvas; say why a link is refused

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:20:16 +08:00
1 parent 54ceb7b631
commit af1bab4afa
9 files changed
+75 -11

No files matched your search

+2
View File
@@ -1725,6 +1725,8 @@ INSERT INTO message (code, content, area) SELECT 'PagesLink', JSON_OBJECT('en_US
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接') WHERE LOWER(code) = LOWER('PagesLink') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesLinkPrompt', JSON_OBJECT('en_US', 'Link address (https://, mailto:, tel:, / or #name)', 'zh_CN', '链接地址(https://、mailto:、tel:、/ 或 #名称)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLinkPrompt') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接地址(https://、mailto:、tel:、/ 或 #名称)') WHERE LOWER(code) = LOWER('PagesLinkPrompt') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesLinkRefused', JSON_OBJECT('en_US', 'That link is not allowed. Use https://, mailto:, tel:, a path starting with / or #name.', 'zh_CN', '不允许此链接。请使用 https://、mailto:、tel:、以 / 开头的路径或 #名称。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLinkRefused') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不允许此链接。请使用 https://、mailto:、tel:、以 / 开头的路径或 #名称。') WHERE LOWER(code) = LOWER('PagesLinkRefused') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesClearFormatting', JSON_OBJECT('en_US', 'Clear formatting', 'zh_CN', '清除格式'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesClearFormatting') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '清除格式') WHERE LOWER(code) = LOWER('PagesClearFormatting') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTooManyBlocks', JSON_OBJECT('en_US', 'A page can have at most 30 blocks.', 'zh_CN', '每个网页最多 30 个区块。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTooManyBlocks') AND area = 'A');
@@ -24,7 +24,7 @@ Design: `design.md`. Every task is TDD. Work is serial in the main session, with
- [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).
- [x] 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.
## 3. Editor
@@ -84,6 +84,15 @@ describe("LandingPage in edit mode", () => {
expect(edit.select).toHaveBeenCalledWith(0);
});
it("edits rich text in place in the page's own style, for a Text block and an image-and-text block", async () => {
render(<LandingPage company={company} page={page([{ type: "RICH_TEXT", html: "<p>Body copy</p>" }, { type: "IMAGE_TEXT", heading: "Pic", html: "" }])} edit={editor()} preview />);
const boxes = await screen.findAllByRole("textbox", { name: "Content" });
expect(boxes).toHaveLength(2);
expect(boxes[0]).toHaveAttribute("contenteditable", "true");
expect(boxes[0]).toHaveTextContent("Body copy");
expect(screen.getAllByText("Body copy")).toHaveLength(1);
});
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();
@@ -4,7 +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";
import { EditContext, EditSection, HeroShade, HtmlSpot, ImageSpot, RichSpot, 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
@@ -60,7 +60,9 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
</section>
);
case "RICH_TEXT":
return block.html ? <section><SafeHtml html={block.html} className={PROSE} /></section> : null;
return block.html || edit ? (
<section><RichSpot index={index} html={block.html} className={PROSE}>{block.html ? <SafeHtml html={block.html} className={PROSE} /> : null}</RichSpot></section>
) : null;
case "IMAGE_TEXT":
return (
<section className="grid items-center gap-6 md:grid-cols-2">
@@ -71,7 +73,7 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
) : null}
<div className="space-y-3">
<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}
<RichSpot index={index} html={block.html} className={PROSE}>{block.html ? <SafeHtml html={block.html} className={PROSE} /> : null}</RichSpot>
{button}
</div>
</section>
@@ -1,6 +1,7 @@
"use client";
import { createContext, useContext, useLayoutEffect, useRef, type ElementType, type FormEvent, type KeyboardEvent, type MouseEvent, type ReactNode } from "react";
import dynamic from "next/dynamic";
import { ImagePlus } from "lucide-react";
import { BLOCK_LABELS, type CmsBlock } from "@/app/lib/cmsPages";
import { useT } from "@/app/lib/i18n/MessagesProvider";
@@ -158,3 +159,18 @@ export function HeroShade({ index, image, shaded, plain, children }: { index: nu
const edit = useEdit();
return <div className={image || edit?.preview(index) ? shaded : plain}>{children}</div>;
}
// Loaded only when the canvas shows rich text: visitors' pages never download the editor.
const RichTextEditor = dynamic(() => import("./RichTextEditor").then((m) => m.RichTextEditor), { ssr: false });
/** A block's rich text: the sanitised HTML on the public page (`children`); in edit mode, edited in place. */
export function RichSpot({ index, html, className, children }: { index: number; html: string | undefined; className: string; children: ReactNode }) {
const t = useT();
const edit = useEdit();
if (!edit) return <>{children}</>;
return (
<div className={className}>
<RichTextEditor bare label={t("PagesContent")} value={html ?? ""} onChange={(value) => edit.html(index, value)} />
</div>
);
}
@@ -0,0 +1,25 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi } from "vitest";
import { RichTextEditor } from "./RichTextEditor";
// add-page-visual-editor: links follow the page link rule, and a refused one says why instead of vanishing.
describe("RichTextEditor", () => {
it("refuses an unsafe link with a message, and adds nothing", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
vi.spyOn(window, "prompt").mockReturnValue("javascript:alert(1)");
render(<RichTextEditor label="Content" value="<p>Hello</p>" onChange={onChange} />);
await screen.findByRole("textbox", { name: "Content" });
await user.click(screen.getByRole("button", { name: "Link" }));
expect(screen.getByRole("alert")).toHaveTextContent("That link is not allowed");
expect(onChange).not.toHaveBeenCalled();
});
it("in bare mode drops the box and keeps the toolbar for when the text is being edited", async () => {
render(<RichTextEditor bare label="Content" value="<p>Hello</p>" onChange={() => {}} />);
const box = await screen.findByRole("textbox", { name: "Content" });
expect(box.closest(".border")).toBeNull();
expect(screen.getByRole("toolbar", { name: "Formatting" })).toBeInTheDocument();
});
});
@@ -1,6 +1,6 @@
"use client";
import { useEffect, useRef, type ReactNode } from "react";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { EditorContent, useEditor, useEditorState, type Editor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import TextAlign from "@tiptap/extension-text-align";
@@ -15,15 +15,18 @@ import { isSafeLink } from "@/app/lib/cmsPages";
const htmlOf = (editor: Editor) => (editor.isEmpty ? "" : editor.getHTML());
export function RichTextEditor({ id, label, value, onChange, disabled, invalid }: {
export function RichTextEditor({ id, label, value, onChange, disabled, invalid, bare }: {
id?: string;
label?: string;
value: string;
onChange: (html: string) => void;
disabled?: boolean;
invalid?: boolean;
/** On the page canvas (add-page-visual-editor): the text in the page's own style, the toolbar floating above it while edited. */
bare?: boolean;
}) {
const t = useT();
const [refused, setRefused] = useState(false);
const emitted = useRef(value);
const editor = useEditor({
immediatelyRender: false,
@@ -37,7 +40,7 @@ export function RichTextEditor({ id, label, value, onChange, disabled, invalid }
}),
TextAlign.configure({ types: ["heading", "paragraph"], alignments: ["left", "center", "right"] }),
],
editorProps: { attributes: { ...(id ? { id } : {}), ...(label ? { "aria-label": label } : {}), ...(invalid ? { "aria-invalid": "true" } : {}), class: "min-h-[140px] px-3 py-2 text-sm outline-none" } },
editorProps: { attributes: { ...(id ? { id } : {}), ...(label ? { "aria-label": label } : {}), ...(invalid ? { "aria-invalid": "true" } : {}), class: bare ? "min-h-[1.5em] outline-none" : "min-h-[140px] px-3 py-2 text-sm outline-none" } },
onUpdate: ({ editor }) => {
const html = htmlOf(editor);
emitted.current = html;
@@ -76,13 +79,17 @@ export function RichTextEditor({ id, label, value, onChange, disabled, invalid }
function addLink() {
const url = window.prompt(t("PagesLinkPrompt"));
setRefused(!!url && !isSafeLink(url));
if (!url || !isSafeLink(url)) return;
run((e) => e.chain().focus().extendMarkRange("link").setLink({ href: url }).run());
}
const toolbar = bare
? "absolute bottom-full left-0 z-20 mb-2 hidden flex-wrap items-center gap-1 rounded-md border bg-popover p-1 text-popover-foreground shadow-md group-focus-within/rt:flex"
: "flex flex-wrap items-center gap-1";
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-1" role="toolbar" aria-label={t("PagesToolbar")}>
<div className={bare ? "group/rt relative rounded-sm hover:outline-dashed hover:outline-1 hover:outline-primary/50 focus-within:outline-2 focus-within:outline-primary" : "space-y-2"}>
<div className={toolbar} role="toolbar" aria-label={t("PagesToolbar")}>
<select aria-label={t("PagesTextStyle")} title={t("PagesTextStyle")} disabled={off} value={state?.level ?? "0"}
className="h-9 rounded-md border border-input bg-transparent px-2 text-sm"
onChange={(ev) => {
@@ -106,10 +113,11 @@ export function RichTextEditor({ id, label, value, onChange, disabled, invalid }
{btn(t("PagesDivider"), <Minus />, () => run((e) => e.chain().focus().setHorizontalRule().run()))}
{btn(t("PagesLink"), <LinkIcon />, addLink, state?.active.link)}
{btn(t("PagesClearFormatting"), <Eraser />, () => run((e) => e.chain().focus().unsetAllMarks().clearNodes().run()))}
{refused ? <p role="alert" className="basis-full px-1 text-sm text-destructive">{t("PagesLinkRefused")}</p> : null}
</div>
<div className="rounded-md border border-input [&_.ProseMirror_a]:underline [&_.ProseMirror_blockquote]:border-l-2 [&_.ProseMirror_blockquote]:pl-3 [&_.ProseMirror_h2]:text-xl [&_.ProseMirror_h2]:font-semibold [&_.ProseMirror_h3]:text-lg [&_.ProseMirror_h3]:font-semibold [&_.ProseMirror_ol]:list-decimal [&_.ProseMirror_ol]:pl-5 [&_.ProseMirror_ul]:list-disc [&_.ProseMirror_ul]:pl-5">
{bare ? <EditorContent editor={editor} /> : <div className="rounded-md border border-input [&_.ProseMirror_a]:underline [&_.ProseMirror_blockquote]:border-l-2 [&_.ProseMirror_blockquote]:pl-3 [&_.ProseMirror_h2]:text-xl [&_.ProseMirror_h2]:font-semibold [&_.ProseMirror_h3]:text-lg [&_.ProseMirror_h3]:font-semibold [&_.ProseMirror_ol]:list-decimal [&_.ProseMirror_ol]:pl-5 [&_.ProseMirror_ul]:list-disc [&_.ProseMirror_ul]:pl-5">
<EditorContent editor={editor} />
</div>
</div>}
</div>
);
}
@@ -874,6 +874,7 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
PagesDivider: "Divider",
PagesLink: "Link",
PagesLinkPrompt: "Link address (https://, mailto:, tel:, / or #name)",
PagesLinkRefused: "That link is not allowed. Use https://, mailto:, tel:, a path starting with / or #name.",
PagesClearFormatting: "Clear formatting",
// Server refusals (the code is the message key; the field says where it shows)
PagesTooManyBlocks: "A page can have at most 30 blocks.",
@@ -859,6 +859,7 @@
"PagesDivider": "分隔线",
"PagesLink": "链接",
"PagesLinkPrompt": "链接地址(https://、mailto:、tel:、/ 或 #名称)",
"PagesLinkRefused": "不允许此链接。请使用 https://、mailto:、tel:、以 / 开头的路径或 #名称。",
"PagesClearFormatting": "清除格式",
"PagesTooManyBlocks": "每个网页最多 30 个区块。",
"PagesUnknownType": "不支持此区块类型。",