feat(pages): on-page editor with canvas, side panel, section tools, undo and refusals
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
1 parent
d31661fd3e
commit
5f2ddf90ba
10 files changed
+660
-121
No files matched your search
@@ -1499,6 +1499,28 @@ INSERT INTO message (code, content, area) SELECT 'PagesLeave', JSON_OBJECT('en_U
|
||||
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 'PagesAddSection', JSON_OBJECT('en_US', 'Add section', 'zh_CN', '添加区块'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddSection') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加区块') WHERE LOWER(code) = LOWER('PagesAddSection') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDragSection', JSON_OBJECT('en_US', 'Drag to move', 'zh_CN', '拖动以移动'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDragSection') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '拖动以移动') WHERE LOWER(code) = LOWER('PagesDragSection') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDuplicateSection', JSON_OBJECT('en_US', 'Duplicate section', 'zh_CN', '复制区块'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDuplicateSection') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制区块') WHERE LOWER(code) = LOWER('PagesDuplicateSection') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesPageSettings', JSON_OBJECT('en_US', 'Page settings', 'zh_CN', '页面设置'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPageSettings') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '页面设置') WHERE LOWER(code) = LOWER('PagesPageSettings') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesCanvas', JSON_OBJECT('en_US', 'Page canvas', 'zh_CN', '页面画布'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCanvas') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '页面画布') WHERE LOWER(code) = LOWER('PagesCanvas') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesCanvasView', JSON_OBJECT('en_US', 'Canvas view', 'zh_CN', '画布视图'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCanvasView') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '画布视图') WHERE LOWER(code) = LOWER('PagesCanvasView') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDesktop', JSON_OBJECT('en_US', 'Desktop', 'zh_CN', '桌面'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDesktop') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '桌面') WHERE LOWER(code) = LOWER('PagesDesktop') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesPhone', JSON_OBJECT('en_US', 'Phone', 'zh_CN', '手机'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPhone') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '手机') WHERE LOWER(code) = LOWER('PagesPhone') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesUndo', JSON_OBJECT('en_US', 'Undo', 'zh_CN', '撤销'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUndo') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '撤销') WHERE LOWER(code) = LOWER('PagesUndo') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesRedo', JSON_OBJECT('en_US', 'Redo', 'zh_CN', '重做'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesRedo') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '重做') WHERE LOWER(code) = LOWER('PagesRedo') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesUntitled', JSON_OBJECT('en_US', 'Untitled page', 'zh_CN', '未命名页面'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUntitled') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '未命名页面') WHERE LOWER(code) = LOWER('PagesUntitled') 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');
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
-- The labels added by add-page-visual-editor, 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 'PagesLeaveTitle', JSON_OBJECT('en_US', 'Leave without saving?', 'zh_CN', '不保存就离开?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLeaveTitle') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不保存就离开?') WHERE LOWER(code) = LOWER('PagesLeaveTitle') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesLeaveMessage', JSON_OBJECT('en_US', 'Your changes to this page are not saved. Leave and lose them?', 'zh_CN', '此页面的修改尚未保存。离开将丢失这些修改,确定离开吗?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLeaveMessage') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此页面的修改尚未保存。离开将丢失这些修改,确定离开吗?') WHERE LOWER(code) = LOWER('PagesLeaveMessage') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesLeave', JSON_OBJECT('en_US', 'Leave', 'zh_CN', '离开'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLeave') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '离开') WHERE LOWER(code) = LOWER('PagesLeave') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT '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 '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 'PagesAddSection', JSON_OBJECT('en_US', 'Add section', 'zh_CN', '添加区块'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddSection') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加区块') WHERE LOWER(code) = LOWER('PagesAddSection') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDragSection', JSON_OBJECT('en_US', 'Drag to move', 'zh_CN', '拖动以移动'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDragSection') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '拖动以移动') WHERE LOWER(code) = LOWER('PagesDragSection') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDuplicateSection', JSON_OBJECT('en_US', 'Duplicate section', 'zh_CN', '复制区块'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDuplicateSection') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制区块') WHERE LOWER(code) = LOWER('PagesDuplicateSection') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesPageSettings', JSON_OBJECT('en_US', 'Page settings', 'zh_CN', '页面设置'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPageSettings') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '页面设置') WHERE LOWER(code) = LOWER('PagesPageSettings') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesCanvas', JSON_OBJECT('en_US', 'Page canvas', 'zh_CN', '页面画布'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCanvas') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '页面画布') WHERE LOWER(code) = LOWER('PagesCanvas') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesCanvasView', JSON_OBJECT('en_US', 'Canvas view', 'zh_CN', '画布视图'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCanvasView') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '画布视图') WHERE LOWER(code) = LOWER('PagesCanvasView') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDesktop', JSON_OBJECT('en_US', 'Desktop', 'zh_CN', '桌面'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDesktop') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '桌面') WHERE LOWER(code) = LOWER('PagesDesktop') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesPhone', JSON_OBJECT('en_US', 'Phone', 'zh_CN', '手机'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPhone') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '手机') WHERE LOWER(code) = LOWER('PagesPhone') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesUndo', JSON_OBJECT('en_US', 'Undo', 'zh_CN', '撤销'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUndo') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '撤销') WHERE LOWER(code) = LOWER('PagesUndo') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesRedo', JSON_OBJECT('en_US', 'Redo', 'zh_CN', '重做'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesRedo') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '重做') WHERE LOWER(code) = LOWER('PagesRedo') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesUntitled', JSON_OBJECT('en_US', 'Untitled page', 'zh_CN', '未命名页面'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUntitled') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '未命名页面') WHERE LOWER(code) = LOWER('PagesUntitled') AND area = 'A';
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Co-Lite change add-page-visual-editor: rollback. Deploy the previous portal image first; this only removes its labels.
|
||||
USE `service-system`;
|
||||
DELETE FROM message WHERE code IN ('PagesLeaveTitle', 'PagesLeaveMessage', 'PagesLeave', 'PagesSaveToUpdate', 'PagesLinkRefused', 'PagesAddSection', 'PagesDragSection', 'PagesDuplicateSection', 'PagesPageSettings', 'PagesCanvas', 'PagesCanvasView', 'PagesDesktop', 'PagesPhone', 'PagesUndo', 'PagesRedo', 'PagesUntitled') AND area = 'A';
|
||||
@@ -25,20 +25,20 @@ 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.
|
||||
- [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.
|
||||
- [x] 2.4 Custom HTML on the canvas: the saved-draft frame, the "Save to update" mark, and a reload after save.
|
||||
|
||||
## 3. Editor
|
||||
|
||||
- [ ] 3.1 `VisualEditor` layout:
|
||||
- [x] 3.1 `VisualEditor` layout:
|
||||
- The top bar: title, status, Desktop and Phone, undo and redo, Duplicate, Preview, View page, Delete, Save.
|
||||
- The change 2 banner with Publish changes and Discard changes.
|
||||
- The side panel: `BlockFields` for the selected block, or the page settings.
|
||||
- The editor is chosen by width, 1024 px and up.
|
||||
- [ ] 3.2 Selection and section actions: select, toolbar (up, down, duplicate, delete), "Add section" between sections and at the end, native drag reorder (reorder function unit-tested), and the keyboard path.
|
||||
- [ ] 3.3 Undo and redo: history of 50, one step per field edit and per action, Ctrl+Z and Ctrl+Shift+Z, kept across saves.
|
||||
- [ ] 3.4 Refusals on the canvas: select, outline, scroll into view, message at the panel field; page-field refusals in the page settings.
|
||||
- [ ] 3.5 Templates (`?template=`) and Duplicate (`?from=`) open in the visual editor.
|
||||
- [ ] 3.6 Labels in `defaultMessages.ts` and `zh_CN.seed.json`, `npm run i18n:sql`, `sql/01-visual-editor-labels.sql`, `sql/99-rollback.sql`.
|
||||
- [x] 3.2 Selection and section actions: select, toolbar (up, down, duplicate, delete), "Add section" between sections and at the end, native drag reorder (reorder function unit-tested), and the keyboard path.
|
||||
- [x] 3.3 Undo and redo: history of 50, one step per field edit and per action, Ctrl+Z and Ctrl+Shift+Z, kept across saves.
|
||||
- [x] 3.4 Refusals on the canvas: select, outline, scroll into view, message at the panel field; page-field refusals in the page settings.
|
||||
- [x] 3.5 Templates (`?template=`) and Duplicate (`?from=`) open in the visual editor.
|
||||
- [x] 3.6 Labels in `defaultMessages.ts` and `zh_CN.seed.json`, `npm run i18n:sql`, `sql/01-visual-editor-labels.sql`, `sql/99-rollback.sql`.
|
||||
|
||||
## 4. Release
|
||||
|
||||
|
||||
@@ -129,7 +129,7 @@ export function EditSection({ index, children }: { index: number; children: Reac
|
||||
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" : ""}`}>
|
||||
className={`group/section 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>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useRef, useState, useSyncExternalStore, type RefObject } from "react";
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
|
||||
@@ -17,97 +17,197 @@ import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { BlockFields } from "./BlockFields";
|
||||
import { usePageDraft } from "./usePageDraft";
|
||||
import { LeaveGuard } from "./LeaveGuard";
|
||||
import { VisualEditor } from "./visual/VisualEditor";
|
||||
|
||||
// The landing-page form editor, ported from babyboo's PageEditor. State and actions live in usePageDraft, shared
|
||||
// with the on-page editor; this is the layout for narrow windows.
|
||||
// The landing-page editor, ported from babyboo's PageEditor. State and actions live in usePageDraft, owned here so
|
||||
// they survive a window resize that switches between the on-page editor (1024 px and up) and the form editor.
|
||||
|
||||
function FieldError({ message }: { message?: string }) {
|
||||
export type Draft = ReturnType<typeof usePageDraft>;
|
||||
/** Asks before the destructive actions; the dialogs are the editor's, whichever layout shows. */
|
||||
export interface Ask { remove(): void; discard(): void }
|
||||
|
||||
export function FieldError({ message }: { message?: string }) {
|
||||
return message ? <p role="alert" className="text-sm text-destructive">{message}</p> : null;
|
||||
}
|
||||
|
||||
const WIDE = "(min-width: 1024px)";
|
||||
const wideNow = () => window.matchMedia(WIDE).matches;
|
||||
const onWideChange = (cb: () => void) => {
|
||||
const query = window.matchMedia(WIDE);
|
||||
query.addEventListener("change", cb);
|
||||
return () => query.removeEventListener("change", cb);
|
||||
};
|
||||
|
||||
/** pageId edits a page; fromId opens an unsaved copy of one (Duplicate); initialBlocks start a new page (templates). */
|
||||
export function PageEditor(props: { pageId?: number; fromId?: number; initialBlocks?: CmsBlock[] }) {
|
||||
const t = useT();
|
||||
const p = usePageDraft(props);
|
||||
const { draft, rows, errors, saving, saved, code } = p;
|
||||
const wide = useSyncExternalStore(onWideChange, wideNow, () => false);
|
||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||
const [confirmDiscard, setConfirmDiscard] = useState(false);
|
||||
const ask: Ask = { remove: () => setConfirmDelete(true), discard: () => setConfirmDiscard(true) };
|
||||
|
||||
if (p.loadError) return <ErrorState message={t(p.loadError)} />;
|
||||
if (p.loading) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{wide ? <VisualEditor p={p} ask={ask} /> : <FormEditor p={p} ask={ask} />}
|
||||
<LeaveGuard dirty={p.dirty} />
|
||||
{confirmDiscard ? (
|
||||
<ConfirmDialog
|
||||
title={t("PagesDiscardTitle")}
|
||||
message={t("PagesDiscardMessage", { title: p.draft.title })}
|
||||
confirmLabel={t("PagesDiscardChanges")}
|
||||
destructive
|
||||
busy={p.saving}
|
||||
onConfirm={() => void p.discardChanges().finally(() => setConfirmDiscard(false))}
|
||||
onCancel={() => setConfirmDiscard(false)}
|
||||
/>
|
||||
) : null}
|
||||
{confirmDelete ? (
|
||||
<ConfirmDialog
|
||||
title={t("PagesDeleteTitle")}
|
||||
message={t("PagesDeleteMessage", { title: p.draft.title })}
|
||||
confirmLabel={t("PagesDelete")}
|
||||
destructive
|
||||
busy={p.saving}
|
||||
onConfirm={() => void p.remove().then((ok) => { if (!ok) setConfirmDelete(false); })}
|
||||
onCancel={() => setConfirmDelete(false)}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** The page's own links: its address, Duplicate, Preview and, once published, View page. */
|
||||
export function PageLinks({ p }: { p: Draft }) {
|
||||
const t = useT();
|
||||
const { draft, saved, code } = p;
|
||||
return (
|
||||
<>
|
||||
{saved && code ? <span className="mr-auto"><CopyAddress address={pageAddress(code, saved.slug)} /></span> : null}
|
||||
{draft.id != null ? (
|
||||
<>
|
||||
<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>
|
||||
<a href={pageAddress(code, saved.slug)} target="_blank" rel="noopener noreferrer">{t("PagesViewPage")}</a>
|
||||
</Button>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** The save outcome, and for a published page with unsaved-to-live edits, Publish changes and Discard changes. */
|
||||
export function PageMessages({ p, ask, banner }: { p: Draft; ask: Ask; banner?: RefObject<HTMLDivElement | null> }) {
|
||||
const t = useT();
|
||||
return (
|
||||
<>
|
||||
{p.summary && <p role="alert" className="text-sm text-destructive">{p.summary}</p>}
|
||||
{p.notice && <p role="status" className="text-sm text-positive">{t(p.notice)}</p>}
|
||||
{p.hasDraft && p.draft.status === "PUBLISHED" ? (
|
||||
<div ref={banner} className="flex scroll-mt-20 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={p.saving} onClick={ask.discard}>{t("PagesDiscardChanges")}</Button>
|
||||
<Button type="button" size="sm" disabled={p.saving} onClick={() => void p.publishChanges()}>{t("PagesPublishChanges")}</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Company (a super admin's new page), title, slug and meta description. */
|
||||
export function PageSettings({ p }: { p: Draft }) {
|
||||
const t = useT();
|
||||
const { draft, errors, saving, code } = p;
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader><CardTitle>{t("PagesPageCard")}</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{p.isSuper && p.isNew ? (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="page-company">{t("Company")}</Label>
|
||||
<Select value={draft.companyId ? String(draft.companyId) : ""} disabled={saving} onValueChange={(v) => p.changeCompany(Number(v))}>
|
||||
<SelectTrigger id="page-company" aria-invalid={!!errors.companyId} className="w-full"><SelectValue placeholder={t("SelectCompany")} /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{p.companies.map((c) => <SelectItem key={c.id} value={String(c.id)}>{c.code}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FieldError message={errors.companyId} />
|
||||
</div>
|
||||
) : null}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="page-title">{t("Title")}</Label>
|
||||
<Input id="page-title" value={draft.title} disabled={saving} aria-invalid={!!errors.title} onChange={(e) => p.setTitle(e.target.value)} />
|
||||
<FieldError message={errors.title} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="page-slug">{t("PagesSlug")}</Label>
|
||||
<Input id="page-slug" value={draft.slug} disabled={saving} aria-invalid={!!errors.slug} onChange={(e) => p.patch({ slug: e.target.value, slugTouched: true })} />
|
||||
<p className="text-xs text-muted-foreground">{t("PagesAddressHint", { address: pageAddress(code || "…", draft.slug || "…") })}</p>
|
||||
<FieldError message={errors.slug} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="page-meta">{t("PagesMetaDescription")}</Label>
|
||||
<Textarea id="page-meta" rows={3} value={draft.metaDescription} disabled={saving} aria-invalid={!!errors.metaDescription} onChange={(e) => p.patch({ metaDescription: e.target.value })} />
|
||||
<p className="tabular text-xs text-muted-foreground">{`${draft.metaDescription.trim().length}/160`}</p>
|
||||
<FieldError message={errors.metaDescription} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/** Draft or published, and the hide-header switch. */
|
||||
export function StatusSettings({ p }: { p: Draft }) {
|
||||
const t = useT();
|
||||
const { draft, errors, saving } = p;
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader><CardTitle>{t("Status")}</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
{(["DRAFT", "PUBLISHED"] as const).map((s) => (
|
||||
<label key={s} className="flex items-center gap-2 text-sm">
|
||||
<input type="radio" name="page-status" value={s} checked={draft.status === s} disabled={saving} onChange={() => p.patch({ status: s })} />
|
||||
{t(s === "PUBLISHED" ? "PagesPublished" : "PagesDraft")}
|
||||
</label>
|
||||
))}
|
||||
<FieldError message={errors.status} />
|
||||
<div className="flex items-center gap-2 pt-2 text-sm">
|
||||
<Switch id="page-hide-header" checked={draft.hideHeader} disabled={saving} onCheckedChange={(on) => p.patch({ hideHeader: on })} />
|
||||
<Label htmlFor="page-hide-header">{t("PagesHideHeader")}</Label>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/** The form editor: narrow windows. */
|
||||
function FormEditor({ p, ask }: { p: Draft; ask: Ask }) {
|
||||
const t = useT();
|
||||
const { draft, rows, errors, saving } = p;
|
||||
// Save sits below a long form, so the unpublished-changes banner is scrolled into view after a save that leaves one.
|
||||
const draftBanner = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (p.revealDraft) draftBanner.current?.scrollIntoView?.({ behavior: "smooth", block: "nearest" });
|
||||
}, [p.revealDraft]);
|
||||
|
||||
if (p.loadError) return <ErrorState message={t(p.loadError)} />;
|
||||
if (p.loading) return null;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<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/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>
|
||||
<a href={pageAddress(code, saved.slug)} target="_blank" rel="noopener noreferrer">{t("PagesViewPage")}</a>
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
{p.summary && <p role="alert" className="text-sm text-destructive">{p.summary}</p>}
|
||||
{p.notice && <p role="status" className="text-sm text-positive">{t(p.notice)}</p>}
|
||||
{p.hasDraft && draft.status === "PUBLISHED" ? (
|
||||
<div ref={draftBanner} className="flex scroll-mt-20 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 p.publishChanges()}>{t("PagesPublishChanges")}</Button>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="flex flex-wrap items-center justify-end gap-2"><PageLinks p={p} /></div>
|
||||
<PageMessages p={p} ask={ask} banner={draftBanner} />
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
|
||||
<div className="space-y-4">
|
||||
<Card>
|
||||
<CardHeader><CardTitle>{t("PagesPageCard")}</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{p.isSuper && p.isNew ? (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="page-company">{t("Company")}</Label>
|
||||
<Select value={draft.companyId ? String(draft.companyId) : ""} disabled={saving} onValueChange={(v) => p.changeCompany(Number(v))}>
|
||||
<SelectTrigger id="page-company" aria-invalid={!!errors.companyId} className="w-full"><SelectValue placeholder={t("SelectCompany")} /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{p.companies.map((c) => <SelectItem key={c.id} value={String(c.id)}>{c.code}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FieldError message={errors.companyId} />
|
||||
</div>
|
||||
) : null}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="page-title">{t("Title")}</Label>
|
||||
<Input id="page-title" value={draft.title} disabled={saving} aria-invalid={!!errors.title} onChange={(e) => p.setTitle(e.target.value)} />
|
||||
<FieldError message={errors.title} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="page-slug">{t("PagesSlug")}</Label>
|
||||
<Input id="page-slug" value={draft.slug} disabled={saving} aria-invalid={!!errors.slug} onChange={(e) => p.patch({ slug: e.target.value, slugTouched: true })} />
|
||||
<p className="text-xs text-muted-foreground">{t("PagesAddressHint", { address: pageAddress(code || "…", draft.slug || "…") })}</p>
|
||||
<FieldError message={errors.slug} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="page-meta">{t("PagesMetaDescription")}</Label>
|
||||
<Textarea id="page-meta" rows={3} value={draft.metaDescription} disabled={saving} aria-invalid={!!errors.metaDescription} onChange={(e) => p.patch({ metaDescription: e.target.value })} />
|
||||
<p className="tabular text-xs text-muted-foreground">{`${draft.metaDescription.trim().length}/160`}</p>
|
||||
<FieldError message={errors.metaDescription} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<PageSettings p={p} />
|
||||
{rows.map((row, index) => (
|
||||
<BlockFields
|
||||
key={row.key}
|
||||
@@ -136,58 +236,17 @@ export function PageEditor(props: { pageId?: number; fromId?: number; initialBlo
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<Card>
|
||||
<CardHeader><CardTitle>{t("Status")}</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
{(["DRAFT", "PUBLISHED"] as const).map((s) => (
|
||||
<label key={s} className="flex items-center gap-2 text-sm">
|
||||
<input type="radio" name="page-status" value={s} checked={draft.status === s} disabled={saving} onChange={() => p.patch({ status: s })} />
|
||||
{t(s === "PUBLISHED" ? "PagesPublished" : "PagesDraft")}
|
||||
</label>
|
||||
))}
|
||||
<FieldError message={errors.status} />
|
||||
<div className="flex items-center gap-2 pt-2 text-sm">
|
||||
<Switch id="page-hide-header" checked={draft.hideHeader} disabled={saving} onCheckedChange={(on) => p.patch({ hideHeader: on })} />
|
||||
<Label htmlFor="page-hide-header">{t("PagesHideHeader")}</Label>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<div className="space-y-4"><StatusSettings p={p} /></div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
{draft.id != null ? (
|
||||
<Button type="button" variant="outline" className="text-destructive" disabled={saving} onClick={() => setConfirmDelete(true)}>
|
||||
<Button type="button" variant="outline" className="text-destructive" disabled={saving} onClick={ask.remove}>
|
||||
{t("PagesDelete")}
|
||||
</Button>
|
||||
) : <span />}
|
||||
<Button type="button" disabled={saving} onClick={() => void p.save()}>{t("Save")}</Button>
|
||||
</div>
|
||||
|
||||
<LeaveGuard dirty={p.dirty} />
|
||||
{confirmDiscard ? (
|
||||
<ConfirmDialog
|
||||
title={t("PagesDiscardTitle")}
|
||||
message={t("PagesDiscardMessage", { title: draft.title })}
|
||||
confirmLabel={t("PagesDiscardChanges")}
|
||||
destructive
|
||||
busy={saving}
|
||||
onConfirm={() => void p.discardChanges().finally(() => setConfirmDiscard(false))}
|
||||
onCancel={() => setConfirmDiscard(false)}
|
||||
/>
|
||||
) : null}
|
||||
{confirmDelete ? (
|
||||
<ConfirmDialog
|
||||
title={t("PagesDeleteTitle")}
|
||||
message={t("PagesDeleteMessage", { title: draft.title })}
|
||||
confirmLabel={t("PagesDelete")}
|
||||
destructive
|
||||
busy={saving}
|
||||
onConfirm={() => void p.remove().then((ok) => { if (!ok) setConfirmDelete(false); })}
|
||||
onCancel={() => setConfirmDelete(false)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } 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", () => mocks);
|
||||
vi.mock("@/app/lib/services/adminEvents", () => ({ listAdminEvents: mocks.listAdminEvents }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import { PageEditor } from "../PageEditor";
|
||||
|
||||
// add-page-visual-editor: the on-page editor at 1024 px and up.
|
||||
const stored = {
|
||||
id: 5, companyId: 2, slug: "hotel", title: "Hotel", metaDescription: null, status: "DRAFT" as const,
|
||||
company: { code: "INS", name: "INS Sdn Bhd", logoImageId: null, accentColor: null },
|
||||
blocks: [
|
||||
{ type: "HERO" as const, heading: "Hi" },
|
||||
{ type: "FEATURES" as const, heading: "Why", cards: [{ title: "Fast" }, { title: "Local" }, { title: "Safe" }] },
|
||||
{ type: "FAQ" as const, heading: "Questions", items: [{ question: "Parking?", answer: "Yes" }] },
|
||||
{ type: "FORM" as const, heading: "Join", eventUuid: null },
|
||||
],
|
||||
};
|
||||
|
||||
const wide = (matches: boolean) => Object.defineProperty(window, "matchMedia", {
|
||||
writable: true, configurable: true,
|
||||
value: (query: string) => ({ matches, media: query, onchange: null, addListener: () => {}, removeListener: () => {}, addEventListener: () => {}, removeEventListener: () => {}, dispatchEvent: () => false }),
|
||||
});
|
||||
const original = window.matchMedia;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
wide(true);
|
||||
memoryRouter.reset("/pages/5");
|
||||
mocks.useAdminAuth.mockReturnValue({ isSuper: false, companyCode: "INS" });
|
||||
mocks.useCompanyScope.mockReturnValue({ companyId: undefined, companies: [], codeOf: () => "INS" });
|
||||
mocks.listAdminEvents.mockResolvedValue({ items: [{ uuid: "77", name: "Hotel week", endDate: "2099-12-31", enabled: true, location: "", startDate: "" }], total: 1 });
|
||||
mocks.getPage.mockResolvedValue(stored);
|
||||
mocks.savePage.mockImplementation(async (id: number, body: object) => ({ ...stored, ...body, id }));
|
||||
});
|
||||
afterEach(() => { window.matchMedia = original; });
|
||||
|
||||
const frame = () => screen.getByTitle("Page canvas") as HTMLIFrameElement;
|
||||
async function open() {
|
||||
const view = render(<PageEditor pageId={5} />);
|
||||
await waitFor(() => expect(frame().contentDocument!.querySelector("[data-index]")).not.toBeNull());
|
||||
return Object.assign(within(frame().contentDocument!.body), { rerender: view.rerender });
|
||||
}
|
||||
const section = (i: number) => frame().contentDocument!.querySelector(`[data-index="${i}"]`) as HTMLElement;
|
||||
const panel = () => screen.getByRole("complementary");
|
||||
const typeInto = (el: HTMLElement, value: string) => { el.focus(); el.textContent = value; fireEvent.input(el); };
|
||||
|
||||
describe("VisualEditor", () => {
|
||||
it("keeps the form editor in a narrow window", async () => {
|
||||
wide(false);
|
||||
render(<PageEditor pageId={5} />);
|
||||
expect((await screen.findAllByLabelText("Title"))[0]).toHaveValue("Hotel");
|
||||
expect(screen.queryByTitle("Page canvas")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the page on the canvas with the page settings beside it, and Desktop or Phone", async () => {
|
||||
const canvas = await open();
|
||||
expect(canvas.getByRole("heading", { level: 1, name: "Hotel" })).toBeInTheDocument();
|
||||
expect(within(panel()).getByLabelText("Title")).toHaveValue("Hotel");
|
||||
expect(frame()).toHaveStyle({ width: "1280px" });
|
||||
await userEvent.setup().click(screen.getByRole("button", { name: "Phone" }));
|
||||
expect(frame()).toHaveStyle({ width: "390px" });
|
||||
});
|
||||
|
||||
it("edits a heading in place: the canvas and the side panel both show it", async () => {
|
||||
const canvas = await open();
|
||||
typeInto(canvas.getAllByRole("textbox", { name: "Heading" })[0], "Hotel week");
|
||||
fireEvent.click(section(0));
|
||||
expect(within(panel()).getAllByRole("textbox").find((el) => (el as HTMLInputElement).value === "Hotel week")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("selects a section on click and shows its settings; a change there shows on the canvas at once", async () => {
|
||||
const user = userEvent.setup();
|
||||
const canvas = await open();
|
||||
fireEvent.click(section(1));
|
||||
expect(section(1)).toHaveAttribute("data-selected", "true");
|
||||
const title = within(panel()).getAllByLabelText("Title")[0];
|
||||
await user.clear(title);
|
||||
await user.type(title, "Quick");
|
||||
expect(canvas.getAllByRole("textbox", { name: "Title" })[0]).toHaveTextContent("Quick");
|
||||
await user.click(within(panel()).getByRole("button", { name: "Page settings" }));
|
||||
expect(within(panel()).getByLabelText("Title")).toHaveValue("Hotel");
|
||||
});
|
||||
|
||||
it("duplicates the selected section as the next one and selects the copy", async () => {
|
||||
const canvas = await open();
|
||||
fireEvent.click(section(1));
|
||||
fireEvent.click(canvas.getByRole("button", { name: "Duplicate section" }));
|
||||
expect(frame().contentDocument!.querySelectorAll("[data-index]")).toHaveLength(5);
|
||||
expect(section(2)).toHaveAttribute("data-selected", "true");
|
||||
expect(within(section(2)).getAllByRole("textbox", { name: "Heading" })[0]).toHaveTextContent("Why");
|
||||
});
|
||||
|
||||
it("adds a section between two and selects it", async () => {
|
||||
const canvas = await open();
|
||||
fireEvent.click(within(section(0)).getByRole("button", { name: "Add section" }));
|
||||
fireEvent.click(canvas.getByRole("menuitem", { name: "Steps" }));
|
||||
expect(section(1)).toHaveAttribute("data-selected", "true");
|
||||
expect(within(panel()).getByRole("group", { name: /Steps/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("moves a section with the toolbar's keyboard-reachable buttons", async () => {
|
||||
const canvas = await open();
|
||||
fireEvent.click(section(2));
|
||||
fireEvent.click(canvas.getByRole("button", { name: "Move up" }));
|
||||
expect(within(section(1)).getAllByRole("textbox", { name: "Heading" })[0]).toHaveTextContent("Questions");
|
||||
expect(section(1)).toHaveAttribute("data-selected", "true");
|
||||
});
|
||||
|
||||
it("undoes a delete with Ctrl+Z and redoes it with Ctrl+Shift+Z", async () => {
|
||||
const canvas = await open();
|
||||
fireEvent.click(section(2));
|
||||
fireEvent.click(canvas.getByRole("button", { name: "Remove block" }));
|
||||
expect(canvas.queryByText("Parking?")).not.toBeInTheDocument();
|
||||
fireEvent.keyDown(section(0), { key: "z", ctrlKey: true });
|
||||
expect(within(section(2)).getByRole("textbox", { name: "Question 1" })).toHaveTextContent("Parking?");
|
||||
fireEvent.keyDown(section(0), { key: "Z", ctrlKey: true, shiftKey: true });
|
||||
expect(canvas.queryByText("Parking?")).not.toBeInTheDocument();
|
||||
await userEvent.setup().click(screen.getByRole("button", { name: "Undo" }));
|
||||
expect(canvas.getByRole("textbox", { name: "Question 1" })).toHaveTextContent("Parking?");
|
||||
});
|
||||
|
||||
it("selects, outlines and explains a refused form: the message is at the Event field", async () => {
|
||||
mocks.savePage.mockRejectedValueOnce(new ApiError("x", 422, { code: "PagesEventRequired", details: { field: "blocks[3].eventUuid" } }));
|
||||
await open();
|
||||
await userEvent.setup().click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(section(3)).toHaveAttribute("data-selected", "true"));
|
||||
expect(within(panel()).getByLabelText("Event")).toBeInTheDocument();
|
||||
expect(within(panel()).getByRole("alert")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("marks a Custom HTML block 'Save to update' while its HTML is unsaved, and reloads it after Save", async () => {
|
||||
const user = userEvent.setup();
|
||||
mocks.getPage.mockResolvedValue({ ...stored, blocks: [{ type: "HTML", html: "<p>Old</p>" }] });
|
||||
const canvas = await open();
|
||||
const sealed = () => frame().contentDocument!.querySelector("iframe[sandbox]") as HTMLIFrameElement;
|
||||
const before = sealed().getAttribute("src");
|
||||
expect(before).toMatch(/^\/pages\/5\/preview\/frame\/0\?v=\d+$/);
|
||||
expect(canvas.queryByText("Save to update")).not.toBeInTheDocument();
|
||||
fireEvent.click(canvas.getByRole("button", { name: "Custom HTML" }));
|
||||
const box = within(panel()).getByRole("textbox", { name: /HTML/ });
|
||||
await user.clear(box);
|
||||
await user.type(box, "New");
|
||||
expect(canvas.getByText("Save to update")).toBeInTheDocument();
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(canvas.queryByText("Save to update")).not.toBeInTheDocument());
|
||||
expect(sealed().getAttribute("src")).not.toBe(before);
|
||||
});
|
||||
|
||||
it("opens a template and a duplicate on the canvas", async () => {
|
||||
const { unmount } = render(<PageEditor initialBlocks={[{ type: "CTA", heading: "Sign up today" }]} />);
|
||||
await waitFor(() => expect(within(frame().contentDocument!.body).getByRole("textbox", { name: "Heading" })).toHaveTextContent("Sign up today"));
|
||||
unmount();
|
||||
render(<PageEditor fromId={5} />);
|
||||
await waitFor(() => expect(within(panel()).getByLabelText("Title")).toHaveValue("Hotel (copy)"));
|
||||
await waitFor(() => expect(section(1)).not.toBeNull());
|
||||
expect(screen.queryByRole("button", { name: "Delete" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps unsaved edits when the window narrows to the form editor", async () => {
|
||||
const canvas = await open();
|
||||
typeInto(canvas.getAllByRole("textbox", { name: "Heading" })[0], "Hotel week");
|
||||
wide(false);
|
||||
canvas.rerender(<PageEditor pageId={5} />);
|
||||
expect(screen.queryByTitle("Page canvas")).not.toBeInTheDocument();
|
||||
expect(screen.getAllByLabelText("Heading")[0]).toHaveValue("Hotel week");
|
||||
expect(mocks.getPage).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,218 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState, type DragEvent, type KeyboardEvent, type ReactNode } from "react";
|
||||
import { ArrowDown, ArrowLeft, ArrowUp, Copy, GripVertical, Plus, Redo2, Trash2, Undo2 } from "lucide-react";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { BLOCK_LABELS, BLOCK_TYPES, type BlockType } from "@/app/lib/cmsPages";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { BlockFields } from "../BlockFields";
|
||||
import { LandingPage } from "../CmsBlocks";
|
||||
import type { PageEdit } from "../CmsEdit";
|
||||
import { PageCanvas, type Device } from "../PageCanvas";
|
||||
import { FieldError, PageLinks, PageMessages, PageSettings, StatusSettings, type Ask, type Draft } from "../PageEditor";
|
||||
|
||||
// The on-page editor (add-page-visual-editor): the page on a canvas, edited in place, with the selected section's
|
||||
// settings (or the page's) in the side panel. State and actions are the shared usePageDraft.
|
||||
|
||||
/** The focused element, looking into same-origin frames (the canvas). */
|
||||
function focused(): HTMLElement | null {
|
||||
let el = document.activeElement;
|
||||
while (el instanceof HTMLIFrameElement && el.contentDocument?.activeElement) el = el.contentDocument.activeElement;
|
||||
return el as HTMLElement | null;
|
||||
}
|
||||
|
||||
export function VisualEditor({ p, ask }: { p: Draft; ask: Ask }) {
|
||||
const t = useT();
|
||||
const { draft, rows, saving } = p;
|
||||
const [device, setDevice] = useState<Device>("DESKTOP");
|
||||
// The "Add section" menu open at this place, and a section being dragged with where it would land.
|
||||
const [adding, setAdding] = useState<number | null>(null);
|
||||
const [drag, setDrag] = useState<{ from: number; to: number | null } | null>(null);
|
||||
const file = useRef<HTMLInputElement>(null);
|
||||
const imageFor = useRef<number | null>(null);
|
||||
const canvas = useRef<HTMLDivElement>(null);
|
||||
const selected = p.selected != null && p.selected < rows.length ? p.selected : null;
|
||||
const row = selected != null ? rows[selected] : null;
|
||||
|
||||
// A refused block: bring it into view on the canvas.
|
||||
useEffect(() => {
|
||||
if (!p.revealed) return;
|
||||
const doc = canvas.current?.querySelector("iframe")?.contentDocument;
|
||||
doc?.querySelector(`[data-index="${p.revealed.index}"]`)?.scrollIntoView?.({ behavior: "smooth", block: "center" });
|
||||
}, [p.revealed]);
|
||||
|
||||
/** Undo and redo put back values: a focused field is let go first, so it shows them. */
|
||||
const history = (redo: boolean) => {
|
||||
focused()?.blur();
|
||||
if (redo) p.redo(); else p.undo();
|
||||
};
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (!(e.ctrlKey || e.metaKey) || e.key.toLowerCase() !== "z") return;
|
||||
// Inside rich text, its own undo works on the text until it loses focus.
|
||||
if ((e.target as Element).closest?.(".ProseMirror")) return;
|
||||
e.preventDefault();
|
||||
history(e.shiftKey);
|
||||
};
|
||||
|
||||
const addMenu = (at: number) => (
|
||||
<div role="menu" aria-label={t("PagesAddSection")} className="absolute top-full left-1/2 z-30 mt-1 grid w-56 -translate-x-1/2 gap-0.5 rounded-md border bg-popover p-1 text-popover-foreground shadow-md">
|
||||
{BLOCK_TYPES.map((type: BlockType) => (
|
||||
<button key={type} type="button" role="menuitem" className="rounded-sm px-2 py-1.5 text-left text-sm hover:bg-accent hover:text-accent-foreground"
|
||||
onClick={(e) => { e.stopPropagation(); p.insertBlock(at, type); setAdding(null); }}>
|
||||
{t(BLOCK_LABELS[type])}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
|
||||
const dropZone = (i: number) => {
|
||||
if (!drag) return null;
|
||||
const over = (e: DragEvent<HTMLDivElement>) => {
|
||||
e.preventDefault();
|
||||
const box = e.currentTarget.getBoundingClientRect();
|
||||
const to = e.clientY < box.top + box.height / 2 ? i : i + 1;
|
||||
if (drag.to !== to) setDrag({ ...drag, to });
|
||||
};
|
||||
const drop = (e: DragEvent<HTMLDivElement>) => {
|
||||
e.preventDefault();
|
||||
if (drag.to != null) p.moveBlockTo(drag.from, drag.to > drag.from ? drag.to - 1 : drag.to);
|
||||
setDrag(null);
|
||||
};
|
||||
return (
|
||||
<div className="absolute inset-0 z-40" onDragOver={over} onDrop={drop}>
|
||||
{drag.to === i ? <div className="absolute -top-1 right-0 left-0 h-1 rounded bg-primary" /> : null}
|
||||
{drag.to === i + 1 ? <div className="absolute right-0 -bottom-1 left-0 h-1 rounded bg-primary" /> : null}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const tool = (label: string, icon: ReactNode, onClick: () => void, disabled?: boolean) => (
|
||||
<Button type="button" size="icon" variant="ghost" className="size-8" aria-label={label} title={label} disabled={disabled || saving}
|
||||
onClick={(e) => { e.stopPropagation(); onClick(); }}>
|
||||
{icon}
|
||||
</Button>
|
||||
);
|
||||
|
||||
const edit: PageEdit = {
|
||||
selected,
|
||||
select: (i) => { p.select(i); setAdding(null); },
|
||||
text: (i, path, value) => p.text(rows[i].key, path, value),
|
||||
html: (i, value) => p.html(rows[i].key, value),
|
||||
image: (i) => { imageFor.current = rows[i].key; file.current?.click(); },
|
||||
preview: (i) => p.pending[rows[i]?.key]?.preview,
|
||||
stale: p.stale,
|
||||
frameVersion: p.frameVersion,
|
||||
chrome: (i) => (
|
||||
<>
|
||||
{selected === i ? (
|
||||
<div role="toolbar" aria-label={t(BLOCK_LABELS[rows[i].block.type])} onClick={(e) => e.stopPropagation()}
|
||||
className="absolute -top-5 right-2 z-30 flex items-center gap-0.5 rounded-md border bg-popover p-0.5 text-popover-foreground shadow-md">
|
||||
<span draggable aria-label={t("PagesDragSection")} title={t("PagesDragSection")}
|
||||
className="flex size-8 cursor-grab items-center justify-center rounded-md hover:bg-accent"
|
||||
onDragStart={(e) => { e.dataTransfer.setData("text/plain", String(i)); e.dataTransfer.effectAllowed = "move"; setDrag({ from: i, to: null }); }}
|
||||
onDragEnd={() => setDrag(null)}>
|
||||
<GripVertical aria-hidden="true" className="size-4" />
|
||||
</span>
|
||||
{tool(t("PagesMoveUp"), <ArrowUp />, () => p.moveBlock(i, -1), i === 0)}
|
||||
{tool(t("PagesMoveDown"), <ArrowDown />, () => p.moveBlock(i, 1), i === rows.length - 1)}
|
||||
{tool(t("PagesDuplicateSection"), <Copy />, () => p.duplicateBlock(i))}
|
||||
{tool(t("PagesRemoveBlock"), <Trash2 />, () => p.removeBlock(rows[i].key))}
|
||||
</div>
|
||||
) : null}
|
||||
<div className={`absolute bottom-0 left-1/2 z-20 -translate-x-1/2 translate-y-1/2 ${selected === i || adding === i + 1 ? "" : "opacity-0 group-hover/section:opacity-100 focus-within:opacity-100"}`}>
|
||||
<Button type="button" size="sm" variant="outline" className="h-7 rounded-full bg-background shadow-sm" disabled={saving}
|
||||
aria-expanded={adding === i + 1} onClick={(e) => { e.stopPropagation(); setAdding(adding === i + 1 ? null : i + 1); }}>
|
||||
<Plus aria-hidden="true" />{t("PagesAddSection")}
|
||||
</Button>
|
||||
{adding === i + 1 ? addMenu(i + 1) : null}
|
||||
</div>
|
||||
{dropZone(i)}
|
||||
</>
|
||||
),
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3" onKeyDown={onKeyDown} onBlur={p.endTyping}>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h2 className="max-w-80 truncate text-lg font-semibold">{draft.title || t("PagesUntitled")}</h2>
|
||||
<Badge variant={draft.status === "PUBLISHED" ? "positive" : "secondary"}>{t(draft.status === "PUBLISHED" ? "PagesPublished" : "PagesDraft")}</Badge>
|
||||
<div role="group" aria-label={t("PagesCanvasView")} className="ml-2 inline-flex rounded-md border p-0.5">
|
||||
{(["DESKTOP", "PHONE"] as const).map((d) => (
|
||||
<Button key={d} type="button" size="sm" variant={device === d ? "secondary" : "ghost"} aria-pressed={device === d} onClick={() => setDevice(d)}>
|
||||
{t(d === "PHONE" ? "PagesPhone" : "PagesDesktop")}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<Button type="button" size="icon" variant="ghost" aria-label={t("PagesUndo")} title={t("PagesUndo")} disabled={!p.canUndo || saving} onClick={() => history(false)}><Undo2 /></Button>
|
||||
<Button type="button" size="icon" variant="ghost" aria-label={t("PagesRedo")} title={t("PagesRedo")} disabled={!p.canRedo || saving} onClick={() => history(true)}><Redo2 /></Button>
|
||||
<span className="mx-auto" />
|
||||
<PageLinks p={p} />
|
||||
{draft.id != null ? (
|
||||
<Button type="button" variant="outline" className="text-destructive" disabled={saving} onClick={ask.remove}>{t("PagesDelete")}</Button>
|
||||
) : null}
|
||||
<Button type="button" disabled={saving} onClick={() => void p.save()}>{t("Save")}</Button>
|
||||
</div>
|
||||
<PageMessages p={p} ask={ask} />
|
||||
|
||||
<div className="grid h-[calc(100svh-14rem)] min-h-[480px] grid-cols-[minmax(0,1fr)_360px] gap-4">
|
||||
<div ref={canvas} className="min-h-0 rounded-lg border bg-muted/40 p-2">
|
||||
<PageCanvas device={device} title={t("PagesCanvas")}>
|
||||
<LandingPage
|
||||
company={p.branding ?? { code: p.code, name: p.code }}
|
||||
page={{ slug: draft.slug, title: draft.title, hideHeader: draft.hideHeader, blocks: rows.map((r) => r.block) }}
|
||||
preview
|
||||
// A page never saved has no saved version to show: its Custom HTML frames stay blank, marked "Save to update".
|
||||
frameBase={draft.id != null ? `/pages/${draft.id}/preview/frame` : "about:blank#"}
|
||||
edit={edit}
|
||||
/>
|
||||
</PageCanvas>
|
||||
</div>
|
||||
<aside aria-label={t(row ? BLOCK_LABELS[row.block.type] : "PagesPageSettings")} className="min-h-0 space-y-4 overflow-y-auto pr-1">
|
||||
{row && selected != null ? (
|
||||
<>
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => p.select(null)}><ArrowLeft aria-hidden="true" />{t("PagesPageSettings")}</Button>
|
||||
<BlockFields
|
||||
key={row.key}
|
||||
id={row.key}
|
||||
block={row.block}
|
||||
index={selected}
|
||||
count={rows.length}
|
||||
errors={p.blockErrors(selected)}
|
||||
saving={saving}
|
||||
events={p.events}
|
||||
pendingImage={p.pending[row.key] && { name: p.pending[row.key].file.name, preview: p.pending[row.key].preview }}
|
||||
onChange={(update) => p.updateBlock(row.key, update)}
|
||||
onMove={(delta) => p.moveBlock(selected, delta)}
|
||||
onRemove={() => p.removeBlock(row.key)}
|
||||
onChooseImage={(f) => p.chooseImage(row.key, f)}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<PageSettings p={p} />
|
||||
<StatusSettings p={p} />
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium">{t("PagesAddSection")}</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{BLOCK_TYPES.map((type) => (
|
||||
<Button key={type} type="button" variant="outline" size="sm" disabled={saving} onClick={() => p.addBlock(type)}>
|
||||
{t("PagesAddBlock", { type: t(BLOCK_LABELS[type]) })}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<FieldError message={p.errors.blocks} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</aside>
|
||||
</div>
|
||||
<input ref={file} type="file" accept="image/png,image/jpeg,image/webp" hidden aria-hidden="true" tabIndex={-1}
|
||||
onChange={(e) => {
|
||||
const chosen = e.target.files?.[0];
|
||||
if (chosen && imageFor.current != null) p.chooseImage(imageFor.current, chosen);
|
||||
e.target.value = "";
|
||||
}} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -761,6 +761,17 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
PagesLeaveMessage: "Your changes to this page are not saved. Leave and lose them?",
|
||||
PagesLeave: "Leave",
|
||||
PagesSaveToUpdate: "Save to update",
|
||||
PagesAddSection: "Add section",
|
||||
PagesDragSection: "Drag to move",
|
||||
PagesDuplicateSection: "Duplicate section",
|
||||
PagesPageSettings: "Page settings",
|
||||
PagesCanvas: "Page canvas",
|
||||
PagesCanvasView: "Canvas view",
|
||||
PagesDesktop: "Desktop",
|
||||
PagesPhone: "Phone",
|
||||
PagesUndo: "Undo",
|
||||
PagesRedo: "Redo",
|
||||
PagesUntitled: "Untitled page",
|
||||
PagesChangesPublished: "Changes published.",
|
||||
PagesChangesDiscarded: "Changes discarded.",
|
||||
PagesPreviewDraftBanner: "Preview of unpublished changes. Visitors still see the published version.",
|
||||
|
||||
@@ -745,6 +745,17 @@
|
||||
"PagesLeaveMessage": "此页面的修改尚未保存。离开将丢失这些修改,确定离开吗?",
|
||||
"PagesLeave": "离开",
|
||||
"PagesSaveToUpdate": "保存后更新",
|
||||
"PagesAddSection": "添加区块",
|
||||
"PagesDragSection": "拖动以移动",
|
||||
"PagesDuplicateSection": "复制区块",
|
||||
"PagesPageSettings": "页面设置",
|
||||
"PagesCanvas": "页面画布",
|
||||
"PagesCanvasView": "画布视图",
|
||||
"PagesDesktop": "桌面",
|
||||
"PagesPhone": "手机",
|
||||
"PagesUndo": "撤销",
|
||||
"PagesRedo": "重做",
|
||||
"PagesUntitled": "未命名页面",
|
||||
"PagesChangesPublished": "修改已发布。",
|
||||
"PagesChangesDiscarded": "修改已放弃。",
|
||||
"PagesPreviewDraftBanner": "未发布修改的预览。访客看到的仍是已发布的版本。",
|
||||
|
||||
Reference in new issue
Block a user