Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d42e60d104 | ||
|
|
7f43869444 | ||
|
|
5c216551fa | ||
|
|
68159086a9 | ||
|
|
cd3c2e1987 | ||
|
|
d977467182 | ||
|
|
5f2ddf90ba | ||
|
|
d31661fd3e | ||
|
|
af1bab4afa | ||
|
|
54ceb7b631 | ||
|
|
537ac65dc0 | ||
|
|
ede3da1cbe | ||
|
|
6b3498d123 | ||
|
|
7e916b77b9 | ||
|
|
b768b66f6f | ||
|
|
5f4f3bc1ee | ||
|
|
55d9535ef2 | ||
|
|
a0691188ca |
No files matched your search
+5
-1
@@ -465,10 +465,14 @@ Marketing builds public pages under **Events → Pages**. Each page has blocks (
|
||||
- **Jump to the form.** To make a button jump to the sign-up form, give the form block a link name, for example `signup`, and link the button to `#signup`. Links inside a Custom HTML block work the same way: on the INS page, change the HTML's `#consult` links to `#signup`. A `#name` link inside the HTML that matches an `id` in that same HTML (such as `#top`) scrolls to that spot instead.
|
||||
5. **Drafts of published pages.** Once a page is published, Save keeps the changes as a draft: visitors still see the published version, and the editor shows **Publish changes** and **Discard changes**. Preview shows the draft. The pages list marks such pages "Unpublished changes". Publish changes checks the page again (an ended event, for example, is refused at its field). Switching the status back to Draft and saving takes the page offline and drops the separate draft. Two people saving the same page overwrite each other's draft, last save wins.
|
||||
6. **Templates and Duplicate.** New page offers a blank page, **Event sign-up** and **Service showcase**. A template fills the editor with sections and placeholder text; staff replace the text and choose the form's event before saving. **Duplicate** (on the list and in the editor) opens a copy titled "… (copy)" with slug "…-copy" as a new draft; nothing is stored until Save.
|
||||
7. **Check.** Publish a page, open its address signed out, sign up through its form with `?utm_source=test` on the address, and check that the event lead shows source **Web page**, the page address and the campaign. Delete that test lead afterwards.
|
||||
7. **The on-page editor.** On a screen 1024 px or wider, the editor shows the page itself on a canvas, as visitors see it, with **Desktop** (a 1280 px screen scaled to fit) and **Phone** (390 px). Staff click a heading, text, button label, card or FAQ entry and type; rich text gets a small toolbar; clicking an image opens the file picker. Clicking a section selects it: its settings (look, link name, button link, event) show in the side panel, and its toolbar moves, duplicates, deletes or drags it. **Add section** sits under each section. Undo and redo (Ctrl+Z, Ctrl+Shift+Z) go back up to 50 steps and survive Save. A refused save selects the section and shows the message at its field in the panel. Narrower windows keep the form editor; resizing switches between them without losing unsaved edits. Leaving with unsaved edits, by a menu link too, asks first.
|
||||
8. **Custom HTML on the canvas.** The canvas shows a Custom HTML block as last saved, marked **Save to update** while its HTML has unsaved edits; it shows the new HTML after Save. Preview always shows the saved version.
|
||||
9. **Check.** Publish a page, open its address signed out, sign up through its form with `?utm_source=test` on the address, and check that the event lead shows source **Web page**, the page address and the campaign. Delete that test lead afterwards.
|
||||
|
||||
A form stops taking sign-ups when its event is disabled, its end date has passed (Malaysia time), or the company has no privacy notice; the page then says sign-up is closed and still shows its other blocks. Sign-ups share the QR pages' rate limits.
|
||||
|
||||
**Release add-page-drafts-and-templates (SQL, in its OpenSpec change folder):** run `sql/01-page-draft.sql` (adds `cms_page.draft`) before the new services-counter starts, then deploy services-counter, mobile-api and the portal, then run `sql/02-draft-template-labels.sql`. Rollback: previous images, then `sql/99-rollback.sql`, which drops every unpublished draft, so publish or note them first.
|
||||
|
||||
**Release add-page-visual-editor (SQL, in its OpenSpec change folder):** portal only. Deploy the portal, then run `sql/01-visual-editor-labels.sql`. Rollback: the previous portal image, then `sql/99-rollback.sql` (labels only). No data changes.
|
||||
|
||||
**New portal dependencies:** `@tiptap/react`, `@tiptap/pm`, `@tiptap/starter-kit` and `@tiptap/extension-text-align` (the editor, loaded only on the editor screens), and `sanitize-html` (cleans page text on the server before it reaches a visitor). The image build installs them from `package-lock.json`; nothing to do by hand.
|
||||
@@ -1491,6 +1491,36 @@ INSERT INTO message (code, content, area) SELECT 'PagesDiscardTitle', JSON_OBJEC
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '放弃未发布的修改?') WHERE LOWER(code) = LOWER('PagesDiscardTitle') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDiscardMessage', JSON_OBJECT('en_US', 'Your unpublished changes to "{title}" will be lost. Visitors keep seeing the published version.', 'zh_CN', '“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardMessage') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。') WHERE LOWER(code) = LOWER('PagesDiscardMessage') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT '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 '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');
|
||||
@@ -1717,6 +1747,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');
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-12-03
|
||||
@@ -0,0 +1,109 @@
|
||||
# Design: add-page-visual-editor
|
||||
|
||||
## Context
|
||||
|
||||
- **Design doc:** `docs/superpowers/specs/2026-12-03-page-builder-design.md`, change 3. Changes 1 and 2 are live: section types and looks, draft and live content, templates, and Duplicate.
|
||||
- **Today's editor** is `app/components/pages/PageEditor.tsx`, about 415 lines. It holds all page state and actions:
|
||||
- load, the draft, `show`, images uploaded on save;
|
||||
- save, publish changes, discard and delete;
|
||||
- mapping refusals to fields.
|
||||
- **Block fields** are edited by `BlockFields.tsx`.
|
||||
- **Rendering.** The public page and the preview render with `LandingPage` and `Block` in `CmsBlocks.tsx`. Custom HTML renders through `HtmlFrame`, a sealed frame loaded from a frame address that skips the nonce policy.
|
||||
- **Page policy.** The baseline CSP sets no `style-src`. Scripts need the per-request nonce.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals**
|
||||
- Edit the page on the page, with Desktop and Phone views.
|
||||
- Text editing in place, section actions and undo.
|
||||
- Change 2's draft controls and entries kept.
|
||||
- The form editor kept below 1024 px.
|
||||
|
||||
**Non-Goals**
|
||||
- Free placement or per-element styling.
|
||||
- Version history.
|
||||
- Editing on phones.
|
||||
- Live rendering of unsaved Custom HTML.
|
||||
- Any server or API change.
|
||||
|
||||
## Decisions
|
||||
|
||||
### 1. The canvas is a blank same-origin frame that the editor renders into
|
||||
|
||||
The editor mounts `<iframe>` with no `src` (about:blank, same origin), then renders the page into its body with `createPortal`.
|
||||
|
||||
**Styles and theme.**
|
||||
- The `<link rel=stylesheet>` and `<style>` elements in the editor's `<head>` are cloned into the frame. A MutationObserver keeps them in step when `next dev` swaps them.
|
||||
- `<html>`'s `class`, `data-theme` and `style` are copied, which carries the Inter font variable, the dark class and the variables.
|
||||
|
||||
**Why the frame.** It has its own viewport, so `sm:`, `md:` and `lg:` respond to the canvas width, as on a visitor's device. React context (messages, auth) and events work through the portal, and there is a single copy of the draft.
|
||||
|
||||
**Rejected: a canvas address that exchanges the draft by `postMessage`,** as the design doc sketched. It needs a sync protocol both ways, origin checks and a second copy of the draft, which makes undo and in-place editing harder.
|
||||
|
||||
**Security.** The canvas frame has no `sandbox`, unlike every other frame in the portal. It must be same-origin for the portal, and a sandbox without `allow-scripts` would also stop the scripts of the Custom HTML frames nested in it. It holds no data HTML: its only document is a constant blank page (`srcDoc`, no `src`), and everything in it is React-rendered as on the preview page. The portal's markup sweep test allow-lists exactly that file, constant and shape.
|
||||
|
||||
**Fallback.** Task 1 is a spike with pass criteria. If it fails (Tiptap inside the frame, focus, drag events, or production CSS), use a canvas route `/pages/canvas` that reads the draft and posts edits back. Only the canvas wiring changes.
|
||||
|
||||
### 2. Desktop is 1280 px, scaled
|
||||
|
||||
- **Desktop** renders the frame 1280 px wide and scales it with a CSS transform to the width left beside the panel. The frame is one screen tall and scrolls inside, like a device. A frame grown to its content risks a feedback loop with the page's `min-h-svh`, and a fixed screen keeps `svh` honest.
|
||||
- **Phone** is 390 px at 1:1.
|
||||
- Outlines, toolbars and "Add section" buttons are drawn inside the frame document, so they scale with the page.
|
||||
|
||||
### 3. Edit-mode hooks in `LandingPage`
|
||||
|
||||
- An optional `edit` prop on `LandingPage` provides an `EditContext`. Without it, rendering is unchanged, and the public page and preview never pass it.
|
||||
- **Plain text fields.** In edit mode, `Block` renders text fields through `<EditableText field=… max=…>`: a `contentEditable="plaintext-only"` element. It reports input on each keystroke and is never re-rendered from props while it has focus, so the caret stays.
|
||||
- **Rich text** (RICH_TEXT and IMAGE_TEXT html) renders through the existing `RichTextEditor`. A `bare` option adds a floating toolbar and drops the boxed look. It uses the same `isSafeLink` rule.
|
||||
- **Images.** An image spot is a button that opens a file input in the editor document. The chosen file previews from a data URL, as today.
|
||||
- **`Section`** gains `data-index`, an outline when hovered or selected, and the toolbar. Gaps get "+ Add section".
|
||||
- **Clicks.** Clicks on links, buttons and the form are prevented in edit mode. The FORM block already renders its preview note.
|
||||
|
||||
### 4. `HtmlFrame` listens on its own window
|
||||
|
||||
- It adds its message listener to `ref.current.ownerDocument.defaultView`. Inside the canvas, the sealed frame's parent is the canvas window, so the height and anchor messages arrive there.
|
||||
- The canvas passes `frameBase` = the preview frame address (saved draft). Changing a block's HTML sets "Save to update" on that block until the next save. After Save, the frame reloads with a cache-busting `?v=<save count>`.
|
||||
|
||||
### 5. Shared state: `usePageDraft`
|
||||
|
||||
`PageEditor`'s state and actions move, unchanged, into `usePageDraft(pageId, fromId, initialBlocks)`. Both editors use it. This is a refactor guarded by the existing editor tests. The visual editor adds:
|
||||
|
||||
- **`selected` index** (or none).
|
||||
- **History.** Arrays of `{ draft, rows }` snapshots, up to 50.
|
||||
- A text field pushes one snapshot when it gains focus and changes.
|
||||
- A structural action pushes one before it applies.
|
||||
- Undo and redo replace the state and blur the focused editable first, so a focused field is re-rendered from the restored value.
|
||||
- Ctrl+Z inside a rich-text field is Tiptap's own undo while that field has focus. Page undo applies after blur.
|
||||
- **Refusal mapping.** A refused field `blocks[i].…` sets `selected = i` and scrolls the section into view in the frame. The panel then shows `BlockFields` errors as today.
|
||||
|
||||
### 6. Layout
|
||||
|
||||
```
|
||||
┌ ← Pages Title [status] [Desktop|Phone] ↶ ↷ [Duplicate][Preview][View page][Delete] [Save] ┐
|
||||
├ unpublished-changes banner (Publish changes / Discard changes), as in change 2 ──────────────────┤
|
||||
├──────────────────── canvas ───────────────────────────────────┬──── panel (360 px) ────────────┤
|
||||
```
|
||||
|
||||
- **Panel.** It shows `BlockFields` for the selected block, which already covers every field, the look and the link name. With nothing selected it shows the page settings card and the status card from today's form.
|
||||
- **Which editor.** `matchMedia("(min-width: 1024px)")` chooses the editor. Resizing across the line switches editors with the state kept, since both use the same hook.
|
||||
|
||||
### 7. Leave guard for in-app links
|
||||
|
||||
A capture-phase click listener on `document`, active while there are unsaved changes, catches same-origin `<a href>` clicks that would leave the page. It shows the existing `ConfirmDialog`; Leave then calls `router.push`. This replaces the gap noted in `PageEditor` (`ponytail:` comment). Browser back is not guarded; this is named in the comment.
|
||||
|
||||
### 8. Drag and drop
|
||||
|
||||
Drag and drop uses native HTML5 events on the section handle inside the frame, with a drop line between sections. Keyboard users use up and down. jsdom cannot run native drag-and-drop, so the reorder function is unit-tested and the drag itself is checked live.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- **Tiptap or focus inside a portal frame.** ProseMirror reads `ownerDocument` in most places, but this is unverified for selection handling in a frame. The spike covers it, and the fallback is in Decision 1.
|
||||
- **Style cloning in production.** A production build serves hashed CSS links, which clone fine. The spike checks a `next build` once, not only `next dev`.
|
||||
- **Two editors share one hook.** Each keeps its own tests. The form editor stays the narrow-window path, and the fallback if the canvas misbehaves.
|
||||
- **Saved-only Custom HTML on the canvas.** Accepted: staff paste HTML rarely. The marker says what they see.
|
||||
|
||||
## Migration Plan
|
||||
|
||||
- Portal-only deploy, then run `sql/01-visual-editor-labels.sql`.
|
||||
- Rollback: the previous portal image, then `sql/99-rollback.sql` (labels).
|
||||
- No data change.
|
||||
@@ -0,0 +1,51 @@
|
||||
# Proposal: add-page-visual-editor
|
||||
|
||||
## Why
|
||||
|
||||
INS and CV marketing staff build a page for every event and are not technical. Today they fill in a form of blocks and check a separate preview of the last saved version. The owner asked for a Wix-like editor: staff click the page itself to change it and see the result as they work. This is change 3 of the page builder (`docs/superpowers/specs/2026-12-03-page-builder-design.md`). Changes 1 (sections) and 2 (drafts, templates, Duplicate) are live.
|
||||
|
||||
## What Changes
|
||||
|
||||
- **On-page editor** at 1024 px and wider. The page renders in a canvas inside the editor, at the desktop width scaled to fit, or at phone width (390 px). It uses the same `LandingPage` rendering as visitors see. A side panel shows the selected section's settings, or the page settings when no section is selected.
|
||||
- **Edit in place.**
|
||||
- Headings, short texts, button labels, card titles and texts, and FAQ questions and answers are edited as plain text on the canvas, with the server's length limits.
|
||||
- Rich text (Text, and Image with text) is edited in place with a small toolbar.
|
||||
- Clicking an image spot opens the file picker.
|
||||
- **Section actions.** Select, a toolbar (drag handle, up, down, duplicate, delete), and "+ Add section" between sections and at the end.
|
||||
- **Undo and redo** for the page, up to 50 steps, with Ctrl+Z, Ctrl+Shift+Z and buttons.
|
||||
- **Change 2 carried over.** The editor's top bar keeps Save, Preview, View page, Duplicate, Delete, the unpublished-changes banner with Publish changes and Discard changes, and the status. Templates and Duplicate open in the new editor.
|
||||
- **Refusals on the canvas.** A refused field's section is selected and outlined, and the panel shows the message at the field.
|
||||
- **Unsaved changes.** In-app links now ask before leaving with unsaved changes, in both editors. Today only reload and close ask.
|
||||
- **Below 1024 px** the current form editor stays, with Preview.
|
||||
|
||||
### Departures from the approved design doc
|
||||
|
||||
These are builder calls, recorded in `design.md`:
|
||||
|
||||
1. **Canvas wiring.** The editor renders the page into a blank same-origin frame itself, instead of loading a canvas address that exchanges the draft by `postMessage`. There is one copy of the draft and no message protocol. A spike task proves it first, with a canvas route as the named fallback.
|
||||
2. **Desktop view** renders at 1280 px and is scaled down to fit beside the panel, so the page's own breakpoints match a desktop visitor's. "Full width" would show the tablet layout on a laptop.
|
||||
3. **Custom HTML** on the canvas shows the last saved version, with a "Save to update" mark once its HTML is edited. It reloads after Save. Unsaved pasted HTML cannot run sealed with today's frame routes and script policy.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `landing-pages`:
|
||||
- The Page Editor, Saving And Deleting In The Editor, The Custom HTML Block In The Editor, and New Sections In The Editor change.
|
||||
- The on-page editor requirements are added: canvas, editing in place, section actions, undo, and refusals on the canvas.
|
||||
|
||||
## Impact
|
||||
|
||||
- **Portal only:**
|
||||
- New: `app/components/pages/visual/*` (canvas, panel, top bar, history).
|
||||
- `PageEditor` state moves into a shared hook used by both editors.
|
||||
- `CmsBlocks` gains edit-mode hooks, which the public page does not use.
|
||||
- `HtmlFrame` listens on the window of the document it is in.
|
||||
- A leave guard for in-app links.
|
||||
- **Security:** the editor canvas is the portal's only frame without a `sandbox`. It must be same-origin for the editor to render into it, and a sandbox would also stop scripts in the Custom HTML frames nested inside. It loads only a constant blank document with no `src`, so no stored HTML ever runs as the portal. The markup sweep test allow-lists exactly that file and shape (design Decision 1).
|
||||
- **No server, API, database or SQL changes.** New labels only, with a label SQL file.
|
||||
- **No new dependencies.** Tiptap is already installed; dragging uses native drag-and-drop.
|
||||
@@ -0,0 +1,133 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: The Page Editor
|
||||
|
||||
At 1024 px and wider the editor SHALL be the on-page editor. Below 1024 px it SHALL be the form editor. Both SHALL offer the title, a slug filled from the title until edited, a meta description with a 160-character counter, the status, adding, moving and removing blocks, and images uploaded only on save. A FORM block SHALL pick from the company's enabled events that have not ended.
|
||||
|
||||
#### Scenario: Slug follows the title until edited
|
||||
|
||||
- **GIVEN** a new page
|
||||
- **WHEN** staff type the title "Hotel Technology"
|
||||
- **THEN** the slug becomes `hotel-technology`
|
||||
|
||||
#### Scenario: Narrow window keeps the form
|
||||
|
||||
- **WHEN** staff open a page in a window 900 px wide
|
||||
- **THEN** the form editor shows, with Preview
|
||||
|
||||
### Requirement: Saving And Deleting In The Editor
|
||||
|
||||
Server field errors SHALL show at their fields, keeping all entered values. After a save the editor SHALL offer a link to view the page. Deleting a page SHALL ask first. With unsaved edits, reloading, closing and following an in-app link SHALL ask first.
|
||||
|
||||
#### Scenario: Server error at its field
|
||||
|
||||
- **WHEN** staff save a HERO button link `javascript:alert(1)`
|
||||
- **THEN** the error shows at that button link and every entered value stays
|
||||
|
||||
#### Scenario: Leaving by an in-app link
|
||||
|
||||
- **GIVEN** staff changed a heading and did not save
|
||||
- **WHEN** they click Pages in the menu
|
||||
- **THEN** the editor asks before leaving, and Cancel keeps them on the page with the change
|
||||
|
||||
### Requirement: The Custom HTML Block In The Editor
|
||||
|
||||
The editor SHALL offer adding a Custom HTML block, edited in a monospace text box with a 200000-character counter and a note that forms inside it do not send. On the canvas the block SHALL show its last saved version as a sealed frame, marked "Save to update" while its HTML has unsaved edits. The editor SHALL offer a "hide page header" switch.
|
||||
|
||||
#### Scenario: Adding a Custom HTML block
|
||||
|
||||
- **WHEN** staff add a Custom HTML block and paste HTML into it
|
||||
- **THEN** the block shows the pasted HTML, the character count and the note about forms
|
||||
|
||||
#### Scenario: Unsaved HTML on the canvas
|
||||
|
||||
- **GIVEN** a saved page with a Custom HTML block
|
||||
- **WHEN** staff change its HTML in the panel
|
||||
- **THEN** the canvas marks the block "Save to update"
|
||||
- **AND** after Save the canvas shows the new HTML
|
||||
|
||||
#### Scenario: Hiding the header
|
||||
|
||||
- **WHEN** staff turn on "hide page header" and save
|
||||
- **THEN** reading the page returns "hide header" on
|
||||
|
||||
### Requirement: New Sections In The Editor
|
||||
|
||||
Both editors SHALL offer adding FEATURES, STEPS, TRUST and CTA blocks, editing their fields, adding, removing and reordering cards, and choosing any block's look. Refusals SHALL show at the field they name, including card fields.
|
||||
|
||||
#### Scenario: A refused card title shows at its field
|
||||
|
||||
- **GIVEN** staff editing a page with a FEATURES block
|
||||
- **WHEN** the save is refused on field `blocks[0].cards[1].title`
|
||||
- **THEN** the message shows at the second card's title field
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: The Page Canvas
|
||||
|
||||
The on-page editor SHALL show the page on a canvas, rendered as visitors see it, with a Desktop view (1280 px wide, scaled to fit) and a Phone view (390 px wide). Changes SHALL show on the canvas as they are made, before saving. Links and buttons on the canvas SHALL NOT navigate, and the sign-up form SHALL show its preview note.
|
||||
|
||||
#### Scenario: Phone view uses the phone layout
|
||||
|
||||
- **GIVEN** a page with a FEATURES block of three cards
|
||||
- **WHEN** staff switch to Phone
|
||||
- **THEN** the cards stack in one column on the canvas
|
||||
|
||||
#### Scenario: A change shows before saving
|
||||
|
||||
- **WHEN** staff change a FEATURES card title in the side panel
|
||||
- **THEN** the canvas shows the new title at once
|
||||
|
||||
### Requirement: Edit Text On The Page
|
||||
|
||||
Clicking a heading, short text, button label, card title or text, or FAQ question or answer on the canvas SHALL edit it in place as plain text, with the server's length limit shown when close. Rich text SHALL be edited in place with bold, italic, link, lists and alignment, and links SHALL follow the page link rule. An empty field SHALL show a faded cue naming it, and empty rich text SHALL keep room to click into. Clicking an image spot SHALL open the file picker.
|
||||
|
||||
#### Scenario: Edit a heading in place
|
||||
|
||||
- **WHEN** staff click the hero heading on the canvas and type "Hotel week"
|
||||
- **THEN** the canvas and the side panel show "Hotel week"
|
||||
|
||||
#### Scenario: An unsafe link is refused in rich text
|
||||
|
||||
- **WHEN** staff add the link `javascript:alert(1)` in a Text block on the canvas
|
||||
- **THEN** the link is not added and the toolbar says why
|
||||
|
||||
### Requirement: Section Selection And Actions
|
||||
|
||||
Clicking a section on the canvas SHALL select it, outline it and show its settings in the side panel. With none selected, the panel SHALL show the page settings. A selected section SHALL offer drag, up, down, duplicate and delete. "Add section" between sections and at the end SHALL offer every block type. Up and down SHALL work from the keyboard. A section that is added, duplicated or moved SHALL be brought into view on the canvas.
|
||||
|
||||
#### Scenario: Duplicate a section
|
||||
|
||||
- **WHEN** staff select the second section and press Duplicate
|
||||
- **THEN** a copy appears as the third section and is selected
|
||||
|
||||
#### Scenario: Add a section between two
|
||||
|
||||
- **WHEN** staff press Add section between the first and second sections and choose Steps
|
||||
- **THEN** a Steps section appears second and is selected
|
||||
|
||||
#### Scenario: Add a section from the side panel
|
||||
|
||||
- **GIVEN** the canvas shows the top of a long page
|
||||
- **WHEN** staff press Add Text in the side panel
|
||||
- **THEN** the canvas scrolls to the new Text section at the end, which shows a faded "Content" cue to type into
|
||||
|
||||
### Requirement: Undo And Redo
|
||||
|
||||
The on-page editor SHALL undo and redo page changes, up to 50 steps, by buttons and by Ctrl+Z and Ctrl+Shift+Z. The keys SHALL work wherever focus is in the editor, including after the focused control is removed or disabled, except inside a field outside the editor. Typing in one field SHALL be one step. Saving SHALL NOT clear the history.
|
||||
|
||||
#### Scenario: Undo a delete
|
||||
|
||||
- **GIVEN** staff deleted the FAQ section
|
||||
- **WHEN** they press Ctrl+Z
|
||||
- **THEN** the FAQ section is back in its place with its content
|
||||
|
||||
### Requirement: Refusals On The Canvas
|
||||
|
||||
When a save or publish is refused on a block field, the editor SHALL select that block, outline it, scroll it into view and show the message at the field in the side panel. A refusal on a page field SHALL show in the page settings.
|
||||
|
||||
#### Scenario: A form without an event
|
||||
|
||||
- **GIVEN** a page from the Event sign-up template
|
||||
- **WHEN** staff save without choosing the form's event
|
||||
- **THEN** the form section is selected and outlined and the panel shows the message at the Event field
|
||||
@@ -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';
|
||||
@@ -0,0 +1,58 @@
|
||||
# Tasks: add-page-visual-editor
|
||||
|
||||
Design: `design.md`. Every task is TDD. Work is serial in the main session, with a self-review per task.
|
||||
|
||||
- Verify (portal): `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`
|
||||
|
||||
## 1. Foundations
|
||||
|
||||
- [x] 1.1 **Spike, kept only if it passes:** render `LandingPage` into a blank frame by portal, with copied styles and theme. It passes when all of these work, in `next dev` and in one `next build` + `next start`:
|
||||
- Tailwind breakpoints follow the frame width (390 vs 1280).
|
||||
- Fonts and dark mode look right.
|
||||
- A Tiptap editor inside the frame types, selects and applies bold.
|
||||
- A `contentEditable` field keeps its caret while typing.
|
||||
- Native drag events fire.
|
||||
- A Custom HTML frame inside it reports its height.
|
||||
|
||||
On failure, stop and switch to the canvas-route fallback (design Decision 1), noting why.
|
||||
Passed 2026-12-03 in `next dev` and `next build` + `next start`: 390 px stacks the cards and 1280 px shows three columns; Inter and dark mode follow the editor live; Tiptap typed and applied bold; a plain field kept its caret; dragstart and drop fired inside the scaled frame; a Custom HTML frame grew to 4419 px after 1.2. The frame scrolls inside rather than growing (design Decision 2).
|
||||
- [x] 1.2 `HtmlFrame` listens on its own document's window (test: a frame inside another document still resizes).
|
||||
- [x] 1.3 Move `PageEditor` state and actions into `usePageDraft`, with no behaviour change. All existing `PageEditor*.test.tsx` stay green and unchanged.
|
||||
- [x] 1.4 Leave guard for in-app links in the form editor (test: an in-app link click with unsaved edits asks; Cancel stays, Leave navigates).
|
||||
|
||||
## 2. Canvas
|
||||
|
||||
- [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).
|
||||
- [x] 2.4 Custom HTML on the canvas: the saved-draft frame, the "Save to update" mark, and a reload after save.
|
||||
|
||||
## 3. Editor
|
||||
|
||||
- [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.
|
||||
- [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
|
||||
|
||||
- [x] 4.1 `docs/deployment.md` §12: the on-page editor for staff, the narrow-window form, and Custom HTML showing after Save.
|
||||
- [x] 4.2 Live check with Playwright (snapshot, find and screenshots only; no `eval`), on disposable pages, at 1280 px and at 900 px for the form, with Desktop and Phone views:
|
||||
- Create from a template, edit headings and a card in place, change a look in the panel, and add, duplicate, move and delete sections.
|
||||
- Undo and redo.
|
||||
- Save without an event: the form is outlined with the message at Event.
|
||||
- Choose the event and save. Publish changes.
|
||||
- Rich text with a safe link and a refused unsafe one.
|
||||
- A Custom HTML block: the "Save to update" mark, then the new HTML after save.
|
||||
- Leaving by a menu link with unsaved changes.
|
||||
- Done 2026-12-03, re-run on fresh code after a full reload: Fast Refresh had not applied edits on this page. Also checked: one undo step per Ctrl+Z from three places, drag to reorder, Look, and Duplicate and Move up revealing their section. Found and fixed on the way:
|
||||
- Ctrl+Z did nothing right after a toolbar delete: focus fell to the canvas body.
|
||||
- Ctrl+Z also did nothing once Redo went disabled: focus fell to the page body.
|
||||
- A new empty Text section was a thin line under its Add section button.
|
||||
- A section added from the panel stayed out of view.
|
||||
@@ -0,0 +1,28 @@
|
||||
import { render, waitFor, within } from "@testing-library/react";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { CanvasFrame } from "./CanvasFrame";
|
||||
|
||||
// add-page-visual-editor: the canvas renders into its own blank document, with the editor's styles and theme.
|
||||
const frame = () => document.querySelector("iframe") as HTMLIFrameElement;
|
||||
|
||||
describe("CanvasFrame", () => {
|
||||
it("renders its children inside the frame's document, at the given size, carrying the editor's styles and theme", async () => {
|
||||
const style = document.head.appendChild(document.createElement("style"));
|
||||
style.textContent = ".x{color:red}";
|
||||
document.documentElement.classList.add("dark");
|
||||
try {
|
||||
render(<CanvasFrame width={390} height={700} title="Canvas"><p>On the canvas</p></CanvasFrame>);
|
||||
expect(frame()).toHaveStyle({ width: "390px", height: "700px" });
|
||||
const inner = () => frame().contentDocument!;
|
||||
await waitFor(() => expect(within(inner().body).getByText("On the canvas")).toBeInTheDocument());
|
||||
expect(document.body).not.toHaveTextContent("On the canvas");
|
||||
expect(inner().documentElement).toHaveClass("dark");
|
||||
expect(inner().head.querySelector("style")?.textContent).toBe(".x{color:red}");
|
||||
document.documentElement.classList.remove("dark");
|
||||
await waitFor(() => expect(inner().documentElement).not.toHaveClass("dark"));
|
||||
} finally {
|
||||
style.remove();
|
||||
document.documentElement.classList.remove("dark");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
|
||||
const BLANK = "<!doctype html><html><head></head><body></body></html>";
|
||||
|
||||
/** Copies the editor's stylesheets and <html> class, style and lang into the frame and keeps them in step; returns the stop. */
|
||||
function mirror(doc: Document): () => void {
|
||||
const syncHead = () => doc.head.replaceChildren(...[...document.head.querySelectorAll('link[rel="stylesheet"], style')].map((n) => n.cloneNode(true)));
|
||||
const syncRoot = () => {
|
||||
const root = document.documentElement;
|
||||
doc.documentElement.className = root.className;
|
||||
doc.documentElement.setAttribute("style", root.getAttribute("style") ?? "");
|
||||
doc.documentElement.lang = root.lang;
|
||||
};
|
||||
syncHead();
|
||||
syncRoot();
|
||||
doc.body.className = document.body.className;
|
||||
doc.body.style.margin = "0";
|
||||
const heads = new MutationObserver(syncHead);
|
||||
heads.observe(document.head, { childList: true, subtree: true, characterData: true });
|
||||
const roots = new MutationObserver(syncRoot);
|
||||
roots.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style", "lang"] });
|
||||
return () => { heads.disconnect(); roots.disconnect(); };
|
||||
}
|
||||
|
||||
/**
|
||||
* A blank same-origin frame that its children render into by portal (add-page-visual-editor, design Decision 1).
|
||||
* The frame is a device screen: its own viewport, so the page's breakpoints follow its width, and it scrolls inside.
|
||||
*/
|
||||
export function CanvasFrame({ width, height, title, children }: { width: number; height: number; title: string; children: ReactNode }) {
|
||||
// A container in the loaded blank document, which React removes the portal from cleanly when the frame goes.
|
||||
// srcDoc plus onLoad, so no browser swaps the document out after the first render.
|
||||
const [root, setRoot] = useState<HTMLElement | null>(null);
|
||||
const stop = useRef<() => void>(undefined);
|
||||
useEffect(() => () => stop.current?.(), []);
|
||||
return (
|
||||
<>
|
||||
<iframe title={title} srcDoc={BLANK} className="block border-0 bg-background" style={{ width, height }}
|
||||
onLoad={(e) => {
|
||||
const doc = e.currentTarget.contentDocument;
|
||||
if (!doc) return;
|
||||
stop.current?.();
|
||||
stop.current = mirror(doc);
|
||||
setRoot(doc.body.appendChild(doc.createElement("div")));
|
||||
}} />
|
||||
{root ? createPortal(children, root) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
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("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("offers empty rich text as a spot to type: a faded cue that goes once there is text", async () => {
|
||||
const { rerender } = render(<LandingPage company={company} page={page([{ type: "RICH_TEXT", html: "" }])} edit={editor()} preview />);
|
||||
await screen.findByRole("textbox", { name: "Content" });
|
||||
const cue = screen.getByText("Content", { selector: "p[aria-hidden]" });
|
||||
expect(cue.parentElement!.className).toContain("[&_.ProseMirror]:min-h-24");
|
||||
rerender(<LandingPage company={company} page={page([{ type: "RICH_TEXT", html: "<p>Hi</p>" }])} edit={editor()} preview />);
|
||||
expect(screen.queryByText("Content", { selector: "p[aria-hidden]" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
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" }]);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { act, render, screen } from "@testing-library/react";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { describe, it, expect, onTestFinished, vi } from "vitest";
|
||||
import { LandingPage, type PublicBlock } from "./CmsBlocks";
|
||||
import { FRAME_SANDBOX } from "@/app/lib/frameHtml";
|
||||
|
||||
@@ -58,6 +58,17 @@ describe("LandingPage: Custom HTML", () => {
|
||||
expect(frame().style.height).toBe("2400px");
|
||||
});
|
||||
|
||||
it("grows inside another document too: it listens on its own document's window (add-page-visual-editor)", () => {
|
||||
const host = document.createElement("iframe");
|
||||
document.body.appendChild(host);
|
||||
onTestFinished(() => host.remove());
|
||||
const inner = host.contentDocument!;
|
||||
render(<LandingPage company={company} page={page([HTML])} />, { container: inner.body.appendChild(inner.createElement("div")) });
|
||||
const sealed = inner.querySelector("iframe") as HTMLIFrameElement;
|
||||
act(() => { host.contentWindow!.dispatchEvent(new MessageEvent("message", { data: { type: "colite-frame-height", height: 2400 }, source: sealed.contentWindow })); });
|
||||
expect(sealed.style.height).toBe("2400px");
|
||||
});
|
||||
|
||||
it("hides the company header and shows the title to screen readers only when the page says so", () => {
|
||||
render(<LandingPage company={company} page={page([HTML], true)} />);
|
||||
expect(screen.queryByRole("img", { name: "INS Sdn Bhd" })).not.toBeInTheDocument();
|
||||
|
||||
@@ -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, 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
|
||||
@@ -28,67 +29,80 @@ 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":
|
||||
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">
|
||||
<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}
|
||||
{block.html ? <SafeHtml html={block.html} className={PROSE} /> : null}
|
||||
<ButtonLink block={block} />
|
||||
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold" />
|
||||
<RichSpot index={index} html={block.html} className={PROSE}>{block.html ? <SafeHtml html={block.html} className={PROSE} /> : null}</RichSpot>
|
||||
{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 +110,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 +119,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 +130,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 +148,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 +168,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 +184,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 +192,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 +215,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,179 @@
|
||||
"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";
|
||||
|
||||
// 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={`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>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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>;
|
||||
}
|
||||
|
||||
// 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} relative ${html ? "" : "[&_.ProseMirror]:min-h-24"}`}>
|
||||
{/* An empty editor is a thin line under the section's Add section button: it gets room, and a faded cue like
|
||||
the plain fields' marks the spot to type. */}
|
||||
{html ? null : <p aria-hidden="true" className="pointer-events-none absolute top-0 left-0 opacity-50">{t("PagesContent")}</p>}
|
||||
<RichTextEditor bare label={t("PagesContent")} value={html ?? ""} onChange={(value) => edit.html(index, value)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -8,18 +8,21 @@ export function HtmlFrame({ id, src, title }: { id?: string; src: string; title:
|
||||
const ref = useRef<HTMLIFrameElement>(null);
|
||||
const [size, setSize] = useState<FrameHeight>({ height: START_HEIGHT, steps: [] });
|
||||
useEffect(() => {
|
||||
// The frame's parent window: the page's, or the editor canvas's when rendered into it (add-page-visual-editor).
|
||||
const host = ref.current?.ownerDocument.defaultView;
|
||||
if (!host) return;
|
||||
const onMessage = (e: MessageEvent) => {
|
||||
const frame = ref.current;
|
||||
if (!frame || e.source !== frame.contentWindow) return;
|
||||
const anchor = frameAnchor(e.data);
|
||||
if (!anchor) return setSize((s) => nextFrameHeight(s, e.data));
|
||||
// add-page-anchor-links: the frame's own target first, else a named block of this page.
|
||||
if (anchor.y !== null) return window.scrollTo({ top: frame.getBoundingClientRect().top + window.scrollY + anchor.y, behavior: "smooth" });
|
||||
const block = document.getElementById(anchor.name);
|
||||
if (anchor.y !== null) return host.scrollTo({ top: frame.getBoundingClientRect().top + host.scrollY + anchor.y, behavior: "smooth" });
|
||||
const block = host.document.getElementById(anchor.name);
|
||||
if (block?.closest("main")) block.scrollIntoView({ behavior: "smooth" });
|
||||
};
|
||||
window.addEventListener("message", onMessage);
|
||||
return () => window.removeEventListener("message", onMessage);
|
||||
host.addEventListener("message", onMessage);
|
||||
return () => host.removeEventListener("message", onMessage);
|
||||
}, []);
|
||||
return <iframe ref={ref} id={id} src={src} title={title} sandbox={FRAME_SANDBOX} loading="lazy" className="block w-full border-0" style={{ height: `${size.height}px` }} />;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import Link from "next/link";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import { LeaveGuard } from "./LeaveGuard";
|
||||
|
||||
// add-page-visual-editor: unsaved edits are guarded against in-app links too, not only reloads.
|
||||
beforeEach(() => memoryRouter.reset("/pages/5"));
|
||||
|
||||
const menu = (
|
||||
<nav>
|
||||
<Link href="/events">Events</Link>
|
||||
<a href="/p/INS/hotel" target="_blank" rel="noopener noreferrer">View page</a>
|
||||
<a href="#top">Top</a>
|
||||
</nav>
|
||||
);
|
||||
|
||||
describe("LeaveGuard", () => {
|
||||
it("asks before an in-app link leaves unsaved edits: Cancel stays, Leave goes", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<>{menu}<LeaveGuard dirty /></>);
|
||||
await user.click(screen.getByRole("link", { name: "Events" }));
|
||||
expect(screen.getByRole("dialog", { name: "Leave without saving?" })).toBeInTheDocument();
|
||||
await user.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
expect(memoryRouter.push).not.toHaveBeenCalled();
|
||||
|
||||
await user.click(screen.getByRole("link", { name: "Events" }));
|
||||
await user.click(screen.getByRole("button", { name: "Leave" }));
|
||||
expect(memoryRouter.push).toHaveBeenCalledWith("/events");
|
||||
});
|
||||
|
||||
it("lets links through when nothing is unsaved, and never stops a new tab or a link within the page", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { rerender } = render(<>{menu}<LeaveGuard dirty={false} /></>);
|
||||
await user.click(screen.getByRole("link", { name: "Events" }));
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
|
||||
rerender(<>{menu}<LeaveGuard dirty /></>);
|
||||
await user.click(screen.getByRole("link", { name: "View page" }));
|
||||
await user.click(screen.getByRole("link", { name: "Top" }));
|
||||
await user.keyboard("{Control>}");
|
||||
await user.click(screen.getByRole("link", { name: "Events" }));
|
||||
await user.keyboard("{/Control}");
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
/** The in-app address a plain left click on this event would go to, or null when the click stays or opens elsewhere. */
|
||||
function leavingTo(e: MouseEvent): string | null {
|
||||
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return null;
|
||||
const link = (e.target as Element | null)?.closest?.("a[href]") as HTMLAnchorElement | null;
|
||||
if (!link || (link.target && link.target !== "_self") || link.hasAttribute("download")) return null;
|
||||
const url = new URL(link.href, location.href);
|
||||
if (url.origin !== location.origin) return null;
|
||||
if (url.pathname === location.pathname && url.search === location.search) return null; // a #name on this page
|
||||
return url.pathname + url.search + url.hash;
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks before an in-app link leaves unsaved edits (add-page-visual-editor). The browser asks for reloads and closing
|
||||
* (usePageDraft). ponytail: browser Back is not guarded; the App Router has no hook for it.
|
||||
*/
|
||||
export function LeaveGuard({ dirty }: { dirty: boolean }) {
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
const [to, setTo] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!dirty) return;
|
||||
// Capture phase on the document: before the link's own handler, which then sees the click is taken.
|
||||
const onClick = (e: MouseEvent) => {
|
||||
const href = leavingTo(e);
|
||||
if (!href) return;
|
||||
e.preventDefault();
|
||||
setTo(href);
|
||||
};
|
||||
document.addEventListener("click", onClick, true);
|
||||
return () => document.removeEventListener("click", onClick, true);
|
||||
}, [dirty]);
|
||||
return to ? (
|
||||
<ConfirmDialog
|
||||
title={t("PagesLeaveTitle")}
|
||||
message={t("PagesLeaveMessage")}
|
||||
confirmLabel={t("PagesLeave")}
|
||||
destructive
|
||||
onConfirm={() => { setTo(null); router.push(to); }}
|
||||
onCancel={() => setTo(null)}
|
||||
/>
|
||||
) : null;
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import Link from "next/link";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ getPage: vi.fn(), listAdminEvents: vi.fn(), useAdminAuth: vi.fn(), useCompanyScope: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/adminPages", () => ({ getPage: mocks.getPage }));
|
||||
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: a menu link with unsaved edits asks first, in the form editor too.
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
memoryRouter.reset("/pages/5");
|
||||
mocks.useAdminAuth.mockReturnValue({ isSuper: false, companyCode: "INS" });
|
||||
mocks.useCompanyScope.mockReturnValue({ companyId: undefined, companies: [], codeOf: () => "INS" });
|
||||
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
|
||||
mocks.getPage.mockResolvedValue({ id: 5, companyId: 2, slug: "hotel", title: "Hotel", metaDescription: null, status: "DRAFT", blocks: [] });
|
||||
});
|
||||
|
||||
describe("PageEditor: leaving with unsaved edits", () => {
|
||||
it("asks before a menu link only once something is changed", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<><Link href="/events">Events</Link><PageEditor pageId={5} /></>);
|
||||
const title = await screen.findByLabelText("Title");
|
||||
await user.click(screen.getByRole("link", { name: "Events" }));
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
|
||||
await user.type(title, " day");
|
||||
await user.click(screen.getByRole("link", { name: "Events" }));
|
||||
expect(screen.getByRole("dialog", { name: "Leave without saving?" })).toBeInTheDocument();
|
||||
await user.click(screen.getByRole("button", { name: "Leave" }));
|
||||
expect(memoryRouter.push).toHaveBeenCalledWith("/events");
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useRef, useState, useSyncExternalStore, type RefObject } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
|
||||
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
|
||||
@@ -12,324 +11,203 @@ import { Switch } from "@/app/components/ui/switch";
|
||||
import { Textarea } from "@/app/components/ui/textarea";
|
||||
import { ErrorState } from "@/app/components/ui/states";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { CopyAddress } from "./CopyAddress";
|
||||
import { BLOCK_LABELS, BLOCK_TYPES, emptyBlock, emptyPage, pageAddress, pageBody, withTitle, type CmsBlock, type CmsPage, type CmsPageDraft, type PageStatus } from "@/app/lib/cmsPages";
|
||||
import { deletePage, discardPage, getPage, publishPage, savePage, uploadPageImage } from "@/app/lib/services/adminPages";
|
||||
import { listAdminEvents } from "@/app/lib/services/adminEvents";
|
||||
import { BLOCK_LABELS, BLOCK_TYPES, pageAddress, type CmsBlock } from "@/app/lib/cmsPages";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { BlockFields, type EventOption } from "./BlockFields";
|
||||
import { BlockFields } from "./BlockFields";
|
||||
import { usePageDraft } from "./usePageDraft";
|
||||
import { LeaveGuard } from "./LeaveGuard";
|
||||
import { VisualEditor } from "./visual/VisualEditor";
|
||||
|
||||
// The landing-page editor, ported from babyboo's PageEditor. Every block carries a stable key, so a chosen image
|
||||
// follows its block through moves and removals. Block images upload on Save, just before the page is saved,
|
||||
// each at most once even when a later step fails.
|
||||
// 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.
|
||||
|
||||
interface Row {
|
||||
key: number;
|
||||
block: CmsBlock;
|
||||
}
|
||||
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 }
|
||||
|
||||
function readDataUrl(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result as string);
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
const malaysiaToday = () => new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Kuala_Lumpur" }).format(new Date());
|
||||
|
||||
function FieldError({ message }: { message?: string }) {
|
||||
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({ pageId, fromId, initialBlocks }: { pageId?: number; fromId?: number; initialBlocks?: CmsBlock[] }) {
|
||||
export function PageEditor(props: { pageId?: number; fromId?: number; initialBlocks?: CmsBlock[] }) {
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
const { isSuper, companyCode } = useAdminAuth();
|
||||
const scope = useCompanyScope();
|
||||
const justSaved = useSearchParams()?.get("saved") === "1";
|
||||
const [draft, setDraft] = useState<CmsPageDraft>(() => ({ ...emptyPage(), companyId: scope.companyId }));
|
||||
const [rows, setRows] = useState<Row[]>(() => (initialBlocks ?? []).map((block, i) => ({ key: -1 - i, block })));
|
||||
const [pending, setPending] = useState<Record<number, { file: File; preview?: string }>>({});
|
||||
// The page as last loaded or saved: what "View page" points at.
|
||||
const [saved, setSaved] = useState<{ slug: string; status: PageStatus } | null>(null);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const loadId = pageId ?? fromId;
|
||||
const [loading, setLoading] = useState(loadId != null);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [summary, setSummary] = useState<string | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(justSaved ? "PagesSaved" : null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const p = usePageDraft(props);
|
||||
const wide = useSyncExternalStore(onWideChange, wideNow, () => false);
|
||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||
const [confirmDiscard, setConfirmDiscard] = useState(false);
|
||||
// A published page's edits are saved as a draft; visitors see the live version until Publish changes.
|
||||
const [hasDraft, setHasDraft] = useState(false);
|
||||
// Bumped when a save leaves a draft: Save sits below a long form, so the banner is scrolled into view.
|
||||
const [revealDraft, setRevealDraft] = useState(0);
|
||||
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 (revealDraft) draftBanner.current?.scrollIntoView?.({ behavior: "smooth", block: "nearest" });
|
||||
}, [revealDraft]);
|
||||
const [events, setEvents] = useState<EventOption[]>([]);
|
||||
const nextKey = useRef(0);
|
||||
const toRows = (blocks: CmsBlock[]) => blocks.map((block) => ({ key: ++nextKey.current, block }));
|
||||
const isNew = draft.id == null;
|
||||
|
||||
/** Shows a loaded page: its draft when there is one, else the live content. */
|
||||
function show(p: CmsPage) {
|
||||
const c = p.draft ?? p;
|
||||
setDraft({ id: p.id, companyId: p.companyId, slug: c.slug, slugTouched: true, title: c.title, metaDescription: c.metaDescription ?? "", status: p.status, hideHeader: !!c.hideHeader, blocks: [] });
|
||||
setRows(toRows(c.blocks ?? []));
|
||||
setPending({});
|
||||
setSaved({ slug: p.slug, status: p.status });
|
||||
setHasDraft(!!p.draft);
|
||||
setDirty(false);
|
||||
}
|
||||
const code = (isSuper ? scope.codeOf(draft.companyId) : companyCode) || "";
|
||||
|
||||
useEffect(() => {
|
||||
if (loadId == null) return;
|
||||
let cancelled = false;
|
||||
getPage(loadId)
|
||||
.then((p) => {
|
||||
if (cancelled) return;
|
||||
show(p);
|
||||
if (pageId == null) {
|
||||
// Duplicate: the same company's content as a new, unsaved draft page.
|
||||
setDraft((d) => ({ ...d, id: undefined, status: "DRAFT", title: `${d.title} (copy)`, slug: `${d.slug}-copy` }));
|
||||
setSaved(null);
|
||||
setHasDraft(false);
|
||||
setDirty(true);
|
||||
}
|
||||
})
|
||||
.catch((err: unknown) => { if (!cancelled) setLoadError(err instanceof ApiError && err.status === 404 ? "PagesNotFound" : "PagesLoadFailed"); })
|
||||
.finally(() => { if (!cancelled) setLoading(false); });
|
||||
return () => { cancelled = true; };
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- show only sets state; load again only for another page.
|
||||
}, [loadId]);
|
||||
|
||||
// The FORM picker: the page company's enabled events that have not ended (Malaysia dates).
|
||||
const eventsCompany = isSuper ? draft.companyId : undefined;
|
||||
useEffect(() => {
|
||||
if (isSuper && !eventsCompany) return;
|
||||
let live = true;
|
||||
const today = malaysiaToday();
|
||||
listAdminEvents({ enabled: "Y", page: 1, pageSize: 100, sortBy: "name", sortDir: "asc", companyId: eventsCompany })
|
||||
.then((r) => { if (live) setEvents(r.items.filter((e) => !e.endDate || e.endDate >= today).map((e) => ({ uuid: e.uuid, name: e.name }))); })
|
||||
.catch(() => {}); // the picker stays empty; a saved event still shows as unavailable
|
||||
return () => { live = false; };
|
||||
}, [isSuper, eventsCompany]);
|
||||
|
||||
// Unsaved edits: the browser asks before a reload or close. ponytail: in-app links are not guarded; add a router guard if staff lose work that way.
|
||||
useEffect(() => {
|
||||
if (!dirty) return;
|
||||
const warn = (e: BeforeUnloadEvent) => e.preventDefault();
|
||||
window.addEventListener("beforeunload", warn);
|
||||
return () => window.removeEventListener("beforeunload", warn);
|
||||
}, [dirty]);
|
||||
|
||||
const edit = <T,>(fn: (v: T) => void) => (v: T) => { setDirty(true); fn(v); };
|
||||
const patch = edit((next: Partial<CmsPageDraft>) => setDraft((d) => ({ ...d, ...next })));
|
||||
const updateBlock = (key: number, update: (block: CmsBlock) => CmsBlock) => {
|
||||
setDirty(true);
|
||||
setRows((rs) => rs.map((r) => (r.key === key ? { ...r, block: update(r.block) } : r)));
|
||||
};
|
||||
const moveBlock = (index: number, delta: -1 | 1) => {
|
||||
setDirty(true);
|
||||
setRows((rs) => {
|
||||
const next = [...rs];
|
||||
[next[index], next[index + delta]] = [next[index + delta], next[index]];
|
||||
return next;
|
||||
});
|
||||
};
|
||||
const removeBlock = (key: number) => {
|
||||
setDirty(true);
|
||||
setRows((rs) => rs.filter((r) => r.key !== key));
|
||||
setPending(({ [key]: _dropped, ...rest }) => rest);
|
||||
};
|
||||
const chooseImage = (key: number, file: File) => {
|
||||
setDirty(true);
|
||||
setPending((p) => ({ ...p, [key]: { file } }));
|
||||
readDataUrl(file)
|
||||
.then((preview) => setPending((p) => (p[key]?.file === file ? { ...p, [key]: { file, preview } } : p)))
|
||||
.catch(() => {});
|
||||
};
|
||||
|
||||
function showError(err: unknown) {
|
||||
const data = err instanceof ApiError ? (err.data as { code?: string; details?: { field?: string } } | undefined) : undefined;
|
||||
const field = data?.details?.field;
|
||||
const message = data?.code ? t(data.code) : t("PagesSaveFailed");
|
||||
if (field) setErrors({ [field === "file" ? "blocks" : field]: message });
|
||||
else setSummary(message);
|
||||
}
|
||||
|
||||
async function save(): Promise<boolean> {
|
||||
setSummary(null);
|
||||
setNotice(null);
|
||||
setErrors({});
|
||||
if (isNew && isSuper && !draft.companyId) {
|
||||
setErrors({ companyId: t("ChooseCompany") });
|
||||
return false;
|
||||
}
|
||||
setSaving(true);
|
||||
const next = rows.map((r) => ({ ...r }));
|
||||
const left = { ...pending };
|
||||
try {
|
||||
for (const row of next) {
|
||||
if (!left[row.key]) continue;
|
||||
const data = (await readDataUrl(left[row.key].file)).split(",")[1];
|
||||
row.block = { ...row.block, imageId: (await uploadPageImage(draft.companyId, data)).id };
|
||||
delete left[row.key];
|
||||
}
|
||||
const page = await savePage(draft.id, pageBody({ ...draft, blocks: next.map((r) => r.block) }));
|
||||
setDraft((d) => ({ ...d, id: page.id, companyId: page.companyId }));
|
||||
setSaved({ slug: page.slug, status: page.status });
|
||||
setHasDraft(!!page.draft);
|
||||
if (page.draft) setRevealDraft((n) => n + 1);
|
||||
setDirty(false);
|
||||
setNotice("PagesSaved");
|
||||
if (isNew) router.replace(`/pages/${page.id}?saved=1`);
|
||||
return true;
|
||||
} catch (err) {
|
||||
showError(err);
|
||||
return false;
|
||||
} finally {
|
||||
// Uploaded images stay on their blocks and leave the pending set, success or not.
|
||||
setRows(next);
|
||||
setPending(left);
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves the current edits, then makes the draft live. */
|
||||
async function publishChanges() {
|
||||
if (draft.id == null || !(await save())) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
show(await publishPage(draft.id));
|
||||
setNotice("PagesChangesPublished");
|
||||
} catch (err) {
|
||||
setNotice(null);
|
||||
showError(err);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function discardChanges() {
|
||||
if (draft.id == null) return;
|
||||
setSaving(true);
|
||||
setSummary(null);
|
||||
setErrors({});
|
||||
try {
|
||||
show(await discardPage(draft.id));
|
||||
setNotice("PagesChangesDiscarded");
|
||||
} catch (err) {
|
||||
showError(err);
|
||||
} finally {
|
||||
setConfirmDiscard(false);
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
if (draft.id == null) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
await deletePage(draft.id);
|
||||
setDirty(false);
|
||||
router.push("/pages");
|
||||
} catch (err) {
|
||||
setConfirmDelete(false);
|
||||
showError(err);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (loadError) return <ErrorState message={t(loadError)} />;
|
||||
if (loading) return null;
|
||||
|
||||
const blockErrors = (index: number) => {
|
||||
const prefix = `blocks[${index}].`;
|
||||
return Object.fromEntries(Object.entries(errors).flatMap(([path, m]) => (path.startsWith(prefix) ? [[path.slice(prefix.length), m]] : [])));
|
||||
};
|
||||
if (p.revealDraft) draftBanner.current?.scrollIntoView?.({ behavior: "smooth", block: "nearest" });
|
||||
}, [p.revealDraft]);
|
||||
|
||||
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>
|
||||
{summary && <p role="alert" className="text-sm text-destructive">{summary}</p>}
|
||||
{notice && <p role="status" className="text-sm text-positive">{t(notice)}</p>}
|
||||
{hasDraft && draft.status === "PUBLISHED" ? (
|
||||
<div 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 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">
|
||||
{isSuper && 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) => { patch({ companyId: Number(v) }); setRows((rs) => rs.map((r) => (r.block.type === "FORM" ? { ...r, block: { ...r.block, eventUuid: null } } : r))); }}>
|
||||
<SelectTrigger id="page-company" aria-invalid={!!errors.companyId} className="w-full"><SelectValue placeholder={t("SelectCompany")} /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{scope.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) => { const v = e.target.value; setDirty(true); setDraft((d) => withTitle(d, v)); }} />
|
||||
<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) => 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) => 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}
|
||||
@@ -337,79 +215,38 @@ export function PageEditor({ pageId, fromId, initialBlocks }: { pageId?: number;
|
||||
block={row.block}
|
||||
index={index}
|
||||
count={rows.length}
|
||||
errors={blockErrors(index)}
|
||||
errors={p.blockErrors(index)}
|
||||
saving={saving}
|
||||
events={events}
|
||||
pendingImage={pending[row.key] && { name: pending[row.key].file.name, preview: pending[row.key].preview }}
|
||||
onChange={(update) => updateBlock(row.key, update)}
|
||||
onMove={(delta) => moveBlock(index, delta)}
|
||||
onRemove={() => removeBlock(row.key)}
|
||||
onChooseImage={(file) => chooseImage(row.key, file)}
|
||||
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(index, delta)}
|
||||
onRemove={() => p.removeBlock(row.key)}
|
||||
onChooseImage={(file) => p.chooseImage(row.key, file)}
|
||||
/>
|
||||
))}
|
||||
<FieldError message={errors.blocks} />
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{BLOCK_TYPES.map((type) => (
|
||||
<Button key={type} type="button" variant="outline" size="sm" disabled={saving}
|
||||
onClick={() => { setDirty(true); setRows((rs) => [...rs, { key: ++nextKey.current, block: emptyBlock(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>
|
||||
</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={() => 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) => 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 save()}>{t("Save")}</Button>
|
||||
<Button type="button" disabled={saving} onClick={() => void p.save()}>{t("Save")}</Button>
|
||||
</div>
|
||||
|
||||
{confirmDiscard ? (
|
||||
<ConfirmDialog
|
||||
title={t("PagesDiscardTitle")}
|
||||
message={t("PagesDiscardMessage", { title: draft.title })}
|
||||
confirmLabel={t("PagesDiscardChanges")}
|
||||
destructive
|
||||
busy={saving}
|
||||
onConfirm={() => void discardChanges()}
|
||||
onCancel={() => setConfirmDiscard(false)}
|
||||
/>
|
||||
) : null}
|
||||
{confirmDelete ? (
|
||||
<ConfirmDialog
|
||||
title={t("PagesDeleteTitle")}
|
||||
message={t("PagesDeleteMessage", { title: draft.title })}
|
||||
confirmLabel={t("PagesDelete")}
|
||||
destructive
|
||||
busy={saving}
|
||||
onConfirm={() => void remove()}
|
||||
onCancel={() => setConfirmDelete(false)}
|
||||
/>
|
||||
) : null}
|
||||
</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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ getPage: vi.fn(), savePage: vi.fn(), listAdminEvents: vi.fn(), useAdminAuth: vi.fn(), useCompanyScope: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/adminPages", () => ({ getPage: mocks.getPage, savePage: mocks.savePage }));
|
||||
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 { moveItem, usePageDraft } from "./usePageDraft";
|
||||
|
||||
// add-page-visual-editor: the on-page editor's selection, section actions, undo and refusal mapping.
|
||||
const stored = {
|
||||
id: 5, companyId: 2, slug: "hotel", title: "Hotel", metaDescription: null, status: "DRAFT" as const,
|
||||
company: { code: "INS", name: "INS Sdn Bhd", logoImageId: 4, accentColor: null },
|
||||
blocks: [
|
||||
{ type: "HERO" as const, heading: "Hi" },
|
||||
{ type: "FAQ" as const, items: [{ question: "Q", answer: "A" }] },
|
||||
{ type: "HTML" as const, html: "<p>x</p>" },
|
||||
],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
memoryRouter.reset("/pages/5");
|
||||
mocks.useAdminAuth.mockReturnValue({ isSuper: false, companyCode: "INS" });
|
||||
mocks.useCompanyScope.mockReturnValue({ companyId: undefined, companies: [], codeOf: () => "INS" });
|
||||
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
|
||||
mocks.getPage.mockResolvedValue(stored);
|
||||
mocks.savePage.mockImplementation(async (id: number, body: object) => ({ ...stored, ...body, id }));
|
||||
});
|
||||
|
||||
async function loaded() {
|
||||
const hook = renderHook(() => usePageDraft({ pageId: 5 }));
|
||||
await waitFor(() => expect(hook.result.current.loading).toBe(false));
|
||||
return hook;
|
||||
}
|
||||
const types = (r: { current: ReturnType<typeof usePageDraft> }) => r.current.rows.map((row) => row.block.type);
|
||||
|
||||
describe("moveItem", () => {
|
||||
it("moves one item to a new place, keeping the others in order", () => {
|
||||
expect(moveItem(["a", "b", "c", "d"], 0, 2)).toEqual(["b", "c", "a", "d"]);
|
||||
expect(moveItem(["a", "b", "c", "d"], 3, 1)).toEqual(["a", "d", "b", "c"]);
|
||||
expect(moveItem(["a", "b"], 1, 1)).toEqual(["a", "b"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("usePageDraft for the on-page editor", () => {
|
||||
it("keeps the company's branding from the loaded page", async () => {
|
||||
const { result } = await loaded();
|
||||
expect(result.current.branding).toEqual(stored.company);
|
||||
});
|
||||
|
||||
it("duplicates a section below itself and selects the copy", async () => {
|
||||
const { result } = await loaded();
|
||||
act(() => result.current.duplicateBlock(1));
|
||||
expect(types(result)).toEqual(["HERO", "FAQ", "FAQ", "HTML"]);
|
||||
expect(result.current.rows[2].block).toEqual(result.current.rows[1].block);
|
||||
expect(result.current.rows[2].key).not.toBe(result.current.rows[1].key);
|
||||
expect(result.current.selected).toBe(2);
|
||||
});
|
||||
|
||||
it("adds a section between two and selects it", async () => {
|
||||
const { result } = await loaded();
|
||||
act(() => result.current.insertBlock(1, "STEPS"));
|
||||
expect(types(result)).toEqual(["HERO", "STEPS", "FAQ", "HTML"]);
|
||||
expect(result.current.selected).toBe(1);
|
||||
});
|
||||
|
||||
it("brings an added, duplicated or moved section into view", async () => {
|
||||
const { result } = await loaded();
|
||||
act(() => result.current.addBlock("CTA"));
|
||||
expect(result.current.revealed).toMatchObject({ index: 3 });
|
||||
act(() => result.current.duplicateBlock(0));
|
||||
expect(result.current.revealed).toMatchObject({ index: 1 });
|
||||
act(() => result.current.moveBlock(0, 1));
|
||||
expect(result.current.revealed).toMatchObject({ index: 1 });
|
||||
act(() => result.current.moveBlockTo(4, 0));
|
||||
expect(result.current.revealed).toMatchObject({ index: 0 });
|
||||
});
|
||||
|
||||
it("drags a section to a new place, and the selection follows it", async () => {
|
||||
const { result } = await loaded();
|
||||
act(() => result.current.select(0));
|
||||
act(() => result.current.moveBlockTo(0, 2));
|
||||
expect(types(result)).toEqual(["FAQ", "HTML", "HERO"]);
|
||||
expect(result.current.selected).toBe(2);
|
||||
});
|
||||
|
||||
it("undoes typing in one field as one step, redoes it, and keeps history across a save", async () => {
|
||||
const { result } = await loaded();
|
||||
const key = result.current.rows[0].key;
|
||||
act(() => result.current.text(key, "heading", "Ho"));
|
||||
act(() => result.current.text(key, "heading", "Hot"));
|
||||
act(() => result.current.text(key, "heading", "Hotel week"));
|
||||
await act(async () => { await result.current.save(); });
|
||||
expect(result.current.canUndo).toBe(true);
|
||||
act(() => result.current.undo());
|
||||
expect(result.current.rows[0].block.heading).toBe("Hi");
|
||||
expect(result.current.canUndo).toBe(false);
|
||||
act(() => result.current.redo());
|
||||
expect(result.current.rows[0].block.heading).toBe("Hotel week");
|
||||
});
|
||||
|
||||
it("brings a deleted section back in its place with its content", async () => {
|
||||
const { result } = await loaded();
|
||||
act(() => result.current.removeBlock(result.current.rows[1].key));
|
||||
expect(types(result)).toEqual(["HERO", "HTML"]);
|
||||
act(() => result.current.undo());
|
||||
expect(types(result)).toEqual(["HERO", "FAQ", "HTML"]);
|
||||
expect(result.current.rows[1].block.items).toEqual([{ question: "Q", answer: "A" }]);
|
||||
});
|
||||
|
||||
it("keeps at most 50 steps", async () => {
|
||||
const { result } = await loaded();
|
||||
for (let i = 0; i < 55; i++) act(() => result.current.insertBlock(0, "CTA"));
|
||||
let undone = 0;
|
||||
while (result.current.canUndo) { act(() => result.current.undo()); undone++; }
|
||||
expect(undone).toBe(50);
|
||||
});
|
||||
|
||||
it("marks a Custom HTML block stale once its HTML or place differs from the saved page, until the next save", async () => {
|
||||
const { result } = await loaded();
|
||||
expect(result.current.stale(2)).toBe(false);
|
||||
act(() => result.current.updateBlock(result.current.rows[2].key, (b) => ({ ...b, html: "<p>y</p>" })));
|
||||
expect(result.current.stale(2)).toBe(true);
|
||||
const version = result.current.frameVersion;
|
||||
await act(async () => { await result.current.save(); });
|
||||
expect(result.current.stale(2)).toBe(false);
|
||||
expect(result.current.frameVersion).toBe(version + 1);
|
||||
act(() => result.current.moveBlockTo(2, 0));
|
||||
expect(result.current.stale(0)).toBe(true);
|
||||
});
|
||||
|
||||
it("selects the block a refusal names, and clears the selection for a page field", async () => {
|
||||
const { result } = await loaded();
|
||||
mocks.savePage.mockRejectedValueOnce(new ApiError("x", 422, { code: "PagesEventRequired", details: { field: "blocks[1].eventUuid" } }));
|
||||
await act(async () => { await result.current.save(); });
|
||||
expect(result.current.selected).toBe(1);
|
||||
expect(result.current.revealed).toEqual({ index: 1, n: 1 });
|
||||
mocks.savePage.mockRejectedValueOnce(new ApiError("x", 422, { code: "PagesSlugTaken", details: { field: "slug" } }));
|
||||
await act(async () => { await result.current.save(); });
|
||||
expect(result.current.selected).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,383 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { emptyBlock, emptyPage, pageBody, withTitle, type BlockType, type CmsBlock, type CmsPage, type CmsPageDraft, type PageStatus } from "@/app/lib/cmsPages";
|
||||
import { setField } from "./CmsEdit";
|
||||
import { deletePage, discardPage, getPage, publishPage, savePage, uploadPageImage } from "@/app/lib/services/adminPages";
|
||||
import { listAdminEvents } from "@/app/lib/services/adminEvents";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import type { EventOption } from "./BlockFields";
|
||||
|
||||
// The landing-page editor's state and actions, shared by the form editor and the on-page editor
|
||||
// (add-page-visual-editor). Every block carries a stable key, so a chosen image follows its block through moves and
|
||||
// removals. Block images upload on Save, just before the page is saved, each at most once even when a later step fails.
|
||||
|
||||
export interface Row {
|
||||
key: number;
|
||||
block: CmsBlock;
|
||||
}
|
||||
|
||||
export function readDataUrl(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result as string);
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
/** The list with one item moved from one place to another. */
|
||||
export function moveItem<T>(list: T[], from: number, to: number): T[] {
|
||||
const next = [...list];
|
||||
const [item] = next.splice(from, 1);
|
||||
next.splice(to, 0, item);
|
||||
return next;
|
||||
}
|
||||
|
||||
type Pending = Record<number, { file: File; preview?: string }>;
|
||||
/** One undo step: the page as it was. */
|
||||
interface Snapshot { draft: CmsPageDraft; rows: Row[]; pending: Pending }
|
||||
const HISTORY = 50;
|
||||
|
||||
const malaysiaToday = () => new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Kuala_Lumpur" }).format(new Date());
|
||||
|
||||
/** pageId edits a page; fromId opens an unsaved copy of one (Duplicate); initialBlocks start a new page (templates). */
|
||||
export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: number; fromId?: number; initialBlocks?: CmsBlock[] }) {
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
const { isSuper, companyCode } = useAdminAuth();
|
||||
const scope = useCompanyScope();
|
||||
const justSaved = useSearchParams()?.get("saved") === "1";
|
||||
const [draft, setDraft] = useState<CmsPageDraft>(() => ({ ...emptyPage(), companyId: scope.companyId }));
|
||||
const [rows, setRows] = useState<Row[]>(() => (initialBlocks ?? []).map((block, i) => ({ key: -1 - i, block })));
|
||||
const [pending, setPending] = useState<Pending>({});
|
||||
// The page as last loaded or saved: what "View page" points at.
|
||||
const [saved, setSaved] = useState<{ slug: string; status: PageStatus } | null>(null);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const loadId = pageId ?? fromId;
|
||||
const [loading, setLoading] = useState(loadId != null);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [summary, setSummary] = useState<string | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(justSaved ? "PagesSaved" : null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
// A published page's edits are saved as a draft; visitors see the live version until Publish changes.
|
||||
const [hasDraft, setHasDraft] = useState(false);
|
||||
// Bumped when a save leaves a draft, so the editor can bring its banner into view.
|
||||
const [revealDraft, setRevealDraft] = useState(0);
|
||||
const [events, setEvents] = useState<EventOption[]>([]);
|
||||
const [branding, setBranding] = useState<CmsPage["company"]>(undefined);
|
||||
// The on-page editor (add-page-visual-editor): the selected block, and a block to bring into view (a refusal).
|
||||
const [selected, setSelected] = useState<number | null>(null);
|
||||
const [revealed, setRevealed] = useState<{ index: number; n: number } | null>(null);
|
||||
// Custom HTML blocks as last loaded or saved, by block key: the canvas shows that version until the next save.
|
||||
const [savedHtml, setSavedHtml] = useState<Record<number, { index: number; html?: string }>>({});
|
||||
const [frameVersion, setFrameVersion] = useState(0);
|
||||
const [past, setPast] = useState<Snapshot[]>([]);
|
||||
const [future, setFuture] = useState<Snapshot[]>([]);
|
||||
// The field being typed into: typing on in it stays one undo step.
|
||||
const typing = useRef<string | null>(null);
|
||||
const nextKey = useRef(0);
|
||||
const toRows = (blocks: CmsBlock[]) => blocks.map((block) => ({ key: ++nextKey.current, block }));
|
||||
const isNew = draft.id == null;
|
||||
|
||||
const remember = (rs: Row[]) => {
|
||||
setSavedHtml(Object.fromEntries(rs.flatMap((r, index) => (r.block.type === "HTML" ? [[r.key, { index, html: r.block.html }]] : []))));
|
||||
setFrameVersion((v) => v + 1);
|
||||
};
|
||||
|
||||
/** Shows a loaded page: its draft when there is one, else the live content. */
|
||||
function show(p: CmsPage) {
|
||||
const c = p.draft ?? p;
|
||||
setDraft({ id: p.id, companyId: p.companyId, slug: c.slug, slugTouched: true, title: c.title, metaDescription: c.metaDescription ?? "", status: p.status, hideHeader: !!c.hideHeader, blocks: [] });
|
||||
if (p.company) setBranding(p.company);
|
||||
const loadedRows = toRows(c.blocks ?? []);
|
||||
setRows(loadedRows);
|
||||
remember(loadedRows);
|
||||
setPending({});
|
||||
setSaved({ slug: p.slug, status: p.status });
|
||||
setHasDraft(!!p.draft);
|
||||
setDirty(false);
|
||||
}
|
||||
const code = (isSuper ? scope.codeOf(draft.companyId) : companyCode) || "";
|
||||
|
||||
useEffect(() => {
|
||||
if (loadId == null) return;
|
||||
let cancelled = false;
|
||||
getPage(loadId)
|
||||
.then((p) => {
|
||||
if (cancelled) return;
|
||||
show(p);
|
||||
if (pageId == null) {
|
||||
// Duplicate: the same company's content as a new, unsaved draft page.
|
||||
setDraft((d) => ({ ...d, id: undefined, status: "DRAFT", title: `${d.title} (copy)`, slug: `${d.slug}-copy` }));
|
||||
setSaved(null);
|
||||
setHasDraft(false);
|
||||
setDirty(true);
|
||||
}
|
||||
})
|
||||
.catch((err: unknown) => { if (!cancelled) setLoadError(err instanceof ApiError && err.status === 404 ? "PagesNotFound" : "PagesLoadFailed"); })
|
||||
.finally(() => { if (!cancelled) setLoading(false); });
|
||||
return () => { cancelled = true; };
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- show only sets state; load again only for another page.
|
||||
}, [loadId]);
|
||||
|
||||
// The FORM picker: the page company's enabled events that have not ended (Malaysia dates).
|
||||
const eventsCompany = isSuper ? draft.companyId : undefined;
|
||||
useEffect(() => {
|
||||
if (isSuper && !eventsCompany) return;
|
||||
let live = true;
|
||||
const today = malaysiaToday();
|
||||
listAdminEvents({ enabled: "Y", page: 1, pageSize: 100, sortBy: "name", sortDir: "asc", companyId: eventsCompany })
|
||||
.then((r) => { if (live) setEvents(r.items.filter((e) => !e.endDate || e.endDate >= today).map((e) => ({ uuid: e.uuid, name: e.name }))); })
|
||||
.catch(() => {}); // the picker stays empty; a saved event still shows as unavailable
|
||||
return () => { live = false; };
|
||||
}, [isSuper, eventsCompany]);
|
||||
|
||||
// Unsaved edits: the browser asks before a reload or close.
|
||||
useEffect(() => {
|
||||
if (!dirty) return;
|
||||
const warn = (e: BeforeUnloadEvent) => e.preventDefault();
|
||||
window.addEventListener("beforeunload", warn);
|
||||
return () => window.removeEventListener("beforeunload", warn);
|
||||
}, [dirty]);
|
||||
|
||||
/**
|
||||
* Starts a change: one undo step per action, and per field while it is typed into (`field`), until another field
|
||||
* or action. Marks the page unsaved.
|
||||
*/
|
||||
const step = (field: string | null) => {
|
||||
if (field === null || typing.current !== field) {
|
||||
setPast((p) => [...p, { draft, rows, pending }].slice(-HISTORY));
|
||||
setFuture([]);
|
||||
}
|
||||
typing.current = field;
|
||||
setDirty(true);
|
||||
};
|
||||
/** Typing in a field ended (it lost focus): the next change is a new step. */
|
||||
const endTyping = () => { typing.current = null; };
|
||||
/** Puts back a snapshot, keeping the page's identity (an undo past the first save must not create a second page). */
|
||||
const restore = (s: Snapshot) => {
|
||||
setDraft({ ...s.draft, id: draft.id, companyId: draft.id != null ? draft.companyId : s.draft.companyId });
|
||||
setRows(s.rows);
|
||||
setPending(s.pending);
|
||||
typing.current = null;
|
||||
setDirty(true);
|
||||
};
|
||||
const undo = () => {
|
||||
const prev = past.at(-1);
|
||||
if (!prev) return;
|
||||
setPast(past.slice(0, -1));
|
||||
setFuture([{ draft, rows, pending }, ...future]);
|
||||
restore(prev);
|
||||
};
|
||||
const redo = () => {
|
||||
const next = future[0];
|
||||
if (!next) return;
|
||||
setFuture(future.slice(1));
|
||||
setPast([...past, { draft, rows, pending }].slice(-HISTORY));
|
||||
restore(next);
|
||||
};
|
||||
|
||||
const patch = (next: Partial<CmsPageDraft>) => {
|
||||
step(`page:${Object.keys(next).join()}`);
|
||||
setDraft((d) => ({ ...d, ...next }));
|
||||
};
|
||||
const setTitle = (title: string) => {
|
||||
step("page:title");
|
||||
setDraft((d) => withTitle(d, title));
|
||||
};
|
||||
/** A super admin's new page changes company: FORM blocks lose their event, which belongs to the old one. */
|
||||
const changeCompany = (companyId: number) => {
|
||||
step(null);
|
||||
setDraft((d) => ({ ...d, companyId }));
|
||||
setRows((rs) => rs.map((r) => (r.block.type === "FORM" ? { ...r, block: { ...r.block, eventUuid: null } } : r)));
|
||||
};
|
||||
const setBlock = (key: number, update: (block: CmsBlock) => CmsBlock) =>
|
||||
setRows((rs) => rs.map((r) => (r.key === key ? { ...r, block: update(r.block) } : r)));
|
||||
/** A change from the block's fields (form or side panel). */
|
||||
const updateBlock = (key: number, update: (block: CmsBlock) => CmsBlock) => {
|
||||
step(`panel:${key}`);
|
||||
setBlock(key, update);
|
||||
};
|
||||
/** A plain text field typed into on the canvas. */
|
||||
const text = (key: number, path: string, value: string) => {
|
||||
step(`${key}:${path}`);
|
||||
setBlock(key, (b) => setField(b, path, value));
|
||||
};
|
||||
/** Rich text typed into on the canvas. */
|
||||
const html = (key: number, value: string) => {
|
||||
step(`${key}:html`);
|
||||
setBlock(key, (b) => ({ ...b, html: value }));
|
||||
};
|
||||
/** Brings a section into view on the canvas: one just added, copied, moved, or refused by the server. */
|
||||
const reveal = (index: number) => setRevealed((r) => ({ index, n: (r?.n ?? 0) + 1 }));
|
||||
const moveBlockTo = (from: number, to: number) => {
|
||||
if (from === to) return;
|
||||
step(null);
|
||||
setRows((rs) => moveItem(rs, from, to));
|
||||
setSelected((s) => (s === from ? to : s));
|
||||
reveal(to);
|
||||
};
|
||||
const moveBlock = (index: number, delta: -1 | 1) => moveBlockTo(index, index + delta);
|
||||
const removeBlock = (key: number) => {
|
||||
step(null);
|
||||
setRows((rs) => rs.filter((r) => r.key !== key));
|
||||
setPending(({ [key]: _dropped, ...rest }) => rest);
|
||||
setSelected(null);
|
||||
};
|
||||
/** A new block of that type at that place, selected. */
|
||||
const insertBlock = (at: number, type: BlockType) => {
|
||||
step(null);
|
||||
setRows((rs) => [...rs.slice(0, at), { key: ++nextKey.current, block: emptyBlock(type) }, ...rs.slice(at)]);
|
||||
setSelected(at);
|
||||
reveal(at);
|
||||
};
|
||||
const addBlock = (type: BlockType) => insertBlock(rows.length, type);
|
||||
/** A copy of the block below it, selected; a chosen image not saved yet goes with it. */
|
||||
const duplicateBlock = (index: number) => {
|
||||
const row = rows[index];
|
||||
if (!row) return;
|
||||
step(null);
|
||||
const key = ++nextKey.current;
|
||||
setRows((rs) => [...rs.slice(0, index + 1), { key, block: structuredClone(row.block) }, ...rs.slice(index + 1)]);
|
||||
if (pending[row.key]) setPending((p) => ({ ...p, [key]: p[row.key] }));
|
||||
setSelected(index + 1);
|
||||
reveal(index + 1);
|
||||
};
|
||||
/** A Custom HTML block whose canvas frame does not show its current HTML: changed or moved since the last save. */
|
||||
const stale = (index: number) => {
|
||||
const row = rows[index];
|
||||
if (row?.block.type !== "HTML") return false;
|
||||
const saved = savedHtml[row.key];
|
||||
return draft.id == null || !saved || saved.index !== index || saved.html !== row.block.html;
|
||||
};
|
||||
const chooseImage = (key: number, file: File) => {
|
||||
step(null);
|
||||
setPending((p) => ({ ...p, [key]: { file } }));
|
||||
readDataUrl(file)
|
||||
.then((preview) => setPending((p) => (p[key]?.file === file ? { ...p, [key]: { file, preview } } : p)))
|
||||
.catch(() => {});
|
||||
};
|
||||
|
||||
function showError(err: unknown) {
|
||||
const data = err instanceof ApiError ? (err.data as { code?: string; details?: { field?: string } } | undefined) : undefined;
|
||||
const field = data?.details?.field;
|
||||
const message = data?.code ? t(data.code) : t("PagesSaveFailed");
|
||||
if (field) setErrors({ [field === "file" ? "blocks" : field]: message });
|
||||
else setSummary(message);
|
||||
// The on-page editor selects the refused block and brings it into view; a page field shows in the page settings.
|
||||
const block = field?.match(/^blocks\[(\d+)\]/);
|
||||
if (block) {
|
||||
const index = Number(block[1]);
|
||||
setSelected(index);
|
||||
reveal(index);
|
||||
} else if (field) setSelected(null);
|
||||
}
|
||||
|
||||
async function save(): Promise<boolean> {
|
||||
setSummary(null);
|
||||
setNotice(null);
|
||||
setErrors({});
|
||||
if (isNew && isSuper && !draft.companyId) {
|
||||
setErrors({ companyId: t("ChooseCompany") });
|
||||
return false;
|
||||
}
|
||||
setSaving(true);
|
||||
const next = rows.map((r) => ({ ...r }));
|
||||
const left = { ...pending };
|
||||
try {
|
||||
for (const row of next) {
|
||||
if (!left[row.key]) continue;
|
||||
const data = (await readDataUrl(left[row.key].file)).split(",")[1];
|
||||
row.block = { ...row.block, imageId: (await uploadPageImage(draft.companyId, data)).id };
|
||||
delete left[row.key];
|
||||
}
|
||||
const page = await savePage(draft.id, pageBody({ ...draft, blocks: next.map((r) => r.block) }));
|
||||
setDraft((d) => ({ ...d, id: page.id, companyId: page.companyId }));
|
||||
setSaved({ slug: page.slug, status: page.status });
|
||||
setHasDraft(!!page.draft);
|
||||
if (page.draft) setRevealDraft((n) => n + 1);
|
||||
setDirty(false);
|
||||
remember(next);
|
||||
setNotice("PagesSaved");
|
||||
if (isNew) router.replace(`/pages/${page.id}?saved=1`);
|
||||
return true;
|
||||
} catch (err) {
|
||||
showError(err);
|
||||
return false;
|
||||
} finally {
|
||||
// Uploaded images stay on their blocks and leave the pending set, success or not.
|
||||
setRows(next);
|
||||
setPending(left);
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves the current edits, then makes the draft live. */
|
||||
async function publishChanges() {
|
||||
if (draft.id == null || !(await save())) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
show(await publishPage(draft.id));
|
||||
setNotice("PagesChangesPublished");
|
||||
} catch (err) {
|
||||
setNotice(null);
|
||||
showError(err);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function discardChanges() {
|
||||
if (draft.id == null) return;
|
||||
setSaving(true);
|
||||
setSummary(null);
|
||||
setErrors({});
|
||||
try {
|
||||
show(await discardPage(draft.id));
|
||||
setNotice("PagesChangesDiscarded");
|
||||
} catch (err) {
|
||||
showError(err);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
/** Deletes the page and leaves for the list; false when refused. */
|
||||
async function remove(): Promise<boolean> {
|
||||
if (draft.id == null) return false;
|
||||
setSaving(true);
|
||||
try {
|
||||
await deletePage(draft.id);
|
||||
setDirty(false);
|
||||
router.push("/pages");
|
||||
return true;
|
||||
} catch (err) {
|
||||
showError(err);
|
||||
return false;
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
/** The refusals for one block, keyed by its own field path. */
|
||||
const blockErrors = (index: number) => {
|
||||
const prefix = `blocks[${index}].`;
|
||||
return Object.fromEntries(Object.entries(errors).flatMap(([path, m]) => (path.startsWith(prefix) ? [[path.slice(prefix.length), m]] : [])));
|
||||
};
|
||||
|
||||
return {
|
||||
draft, rows, pending, saved, dirty, loading, loadError, errors, summary, notice, saving, hasDraft, revealDraft, events,
|
||||
code, isNew, isSuper, companies: scope.companies, branding,
|
||||
selected, select: setSelected, revealed, frameVersion, stale,
|
||||
canUndo: past.length > 0, canRedo: future.length > 0, undo, redo, endTyping,
|
||||
patch, setTitle, changeCompany, updateBlock, text, html, moveBlock, moveBlockTo, removeBlock, addBlock, insertBlock, duplicateBlock,
|
||||
chooseImage, blockErrors,
|
||||
save, publishChanges, discardChanges, remove,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
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("undoes with Ctrl+Z when nothing is focused (a button that just went disabled lets focus fall to the page)", async () => {
|
||||
const canvas = await open();
|
||||
fireEvent.click(section(2));
|
||||
fireEvent.click(canvas.getByRole("button", { name: "Remove block" }));
|
||||
fireEvent.keyDown(document.body, { key: "z", ctrlKey: true });
|
||||
expect(canvas.getByRole("textbox", { name: "Question 1" })).toHaveTextContent("Parking?");
|
||||
});
|
||||
|
||||
it("undoes with Ctrl+Z right after a toolbar delete, when focus falls to the canvas", async () => {
|
||||
const canvas = await open();
|
||||
fireEvent.click(section(2));
|
||||
fireEvent.click(canvas.getByRole("button", { name: "Remove block" }));
|
||||
fireEvent.keyDown(frame().contentDocument!.body, { key: "z", ctrlKey: true });
|
||||
expect(canvas.getByRole("textbox", { name: "Question 1" })).toHaveTextContent("Parking?");
|
||||
});
|
||||
|
||||
it("undoes one step per Ctrl+Z from the editor's own buttons", async () => {
|
||||
const canvas = await open();
|
||||
fireEvent.click(section(1));
|
||||
fireEvent.click(canvas.getByRole("button", { name: "Remove block" }));
|
||||
fireEvent.click(section(1));
|
||||
fireEvent.click(canvas.getByRole("button", { name: "Remove block" }));
|
||||
fireEvent.keyDown(screen.getByRole("button", { name: "Save" }), { key: "z", ctrlKey: true });
|
||||
expect(canvas.getByText("Parking?")).toBeInTheDocument();
|
||||
expect(canvas.queryAllByRole("textbox", { name: "Title" })).toHaveLength(0);
|
||||
});
|
||||
|
||||
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,230 @@
|
||||
"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 | globalThis.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);
|
||||
};
|
||||
// Focus that fell out of the editor (a toolbar button removed with its section drops it on the canvas body; a
|
||||
// button that just went disabled drops it on the page): the key still undoes, unless the editor already handled it
|
||||
// or it is typing in some other field.
|
||||
useEffect(() => {
|
||||
const onBody = (e: globalThis.KeyboardEvent) => {
|
||||
const el = e.target as HTMLElement;
|
||||
if (!e.defaultPrevented && !el.isContentEditable && !el.closest?.("input, textarea, select")) onKeyDown(e);
|
||||
};
|
||||
const docs = [document, canvas.current?.querySelector("iframe")?.contentDocument].filter((d): d is Document => !!d);
|
||||
docs.forEach((d) => d.addEventListener("keydown", onBody));
|
||||
return () => docs.forEach((d) => d.removeEventListener("keydown", onBody));
|
||||
});
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -76,6 +76,8 @@ export interface CmsPage {
|
||||
draft?: PageContent | null;
|
||||
/** List rows: the page has unpublished changes. */
|
||||
hasDraft?: boolean;
|
||||
/** The page company's branding, on a single page read (the editor's canvas and preview render with it). */
|
||||
company?: { code: string; name: string; logoImageId?: number | null; accentColor?: string | null };
|
||||
}
|
||||
|
||||
/** What a draft holds; status and company stay on the page. */
|
||||
|
||||
@@ -757,6 +757,21 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
PagesDiscardChanges: "Discard changes",
|
||||
PagesDiscardTitle: "Discard unpublished changes?",
|
||||
PagesDiscardMessage: "Your unpublished changes to \"{title}\" will be lost. Visitors keep seeing the published version.",
|
||||
PagesLeaveTitle: "Leave without saving?",
|
||||
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.",
|
||||
@@ -870,6 +885,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.",
|
||||
|
||||
@@ -741,6 +741,21 @@
|
||||
"PagesDiscardChanges": "放弃修改",
|
||||
"PagesDiscardTitle": "放弃未发布的修改?",
|
||||
"PagesDiscardMessage": "“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。",
|
||||
"PagesLeaveTitle": "不保存就离开?",
|
||||
"PagesLeaveMessage": "此页面的修改尚未保存。离开将丢失这些修改,确定离开吗?",
|
||||
"PagesLeave": "离开",
|
||||
"PagesSaveToUpdate": "保存后更新",
|
||||
"PagesAddSection": "添加区块",
|
||||
"PagesDragSection": "拖动以移动",
|
||||
"PagesDuplicateSection": "复制区块",
|
||||
"PagesPageSettings": "页面设置",
|
||||
"PagesCanvas": "页面画布",
|
||||
"PagesCanvasView": "画布视图",
|
||||
"PagesDesktop": "桌面",
|
||||
"PagesPhone": "手机",
|
||||
"PagesUndo": "撤销",
|
||||
"PagesRedo": "重做",
|
||||
"PagesUntitled": "未命名页面",
|
||||
"PagesChangesPublished": "修改已发布。",
|
||||
"PagesChangesDiscarded": "修改已放弃。",
|
||||
"PagesPreviewDraftBanner": "未发布修改的预览。访客看到的仍是已发布的版本。",
|
||||
@@ -855,6 +870,7 @@
|
||||
"PagesDivider": "分隔线",
|
||||
"PagesLink": "链接",
|
||||
"PagesLinkPrompt": "链接地址(https://、mailto:、tel:、/ 或 #名称)",
|
||||
"PagesLinkRefused": "不允许此链接。请使用 https://、mailto:、tel:、以 / 开头的路径或 #名称。",
|
||||
"PagesClearFormatting": "清除格式",
|
||||
"PagesTooManyBlocks": "每个网页最多 30 个区块。",
|
||||
"PagesUnknownType": "不支持此区块类型。",
|
||||
|
||||
@@ -34,6 +34,13 @@ const SANDBOX_ALLOWED: Record<string, string> = {
|
||||
"components/pages/HtmlFrame.tsx": "FRAME_SANDBOX",
|
||||
};
|
||||
|
||||
// add-page-visual-editor design Decision 1: the editor canvas is a same-origin frame the editor renders its own React
|
||||
// tree into by portal, so it cannot be sandboxed (that would also strip scripts from the Custom HTML frames nested in
|
||||
// it). It holds no data HTML: its only document is this file's constant blank page, with no src.
|
||||
const UNSANDBOXED_ALLOWED: Record<string, { srcDoc: string; html: string }> = {
|
||||
"components/pages/CanvasFrame.tsx": { srcDoc: "BLANK", html: `const BLANK = "<!doctype html><html><head></head><body></body></html>";` },
|
||||
};
|
||||
|
||||
function sourceFiles(dir: string, out: string[] = []): string[] {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
if (entry.name === "node_modules" || entry.name === ".next") continue;
|
||||
@@ -68,7 +75,12 @@ function iframeProblems(fileName: string, src: string): string[] {
|
||||
const value = sandbox?.initializer;
|
||||
const allowed = SANDBOX_ALLOWED[fileName];
|
||||
const named = !!allowed && !!value && ts.isJsxExpression(value) && value.expression?.getText(sf) === allowed;
|
||||
if (!named && (!value || !ts.isStringLiteral(value) || value.text !== "")) {
|
||||
const attr = (n: string) => props.find((p): p is ts.JsxAttribute => ts.isJsxAttribute(p) && p.name.getText(sf) === n);
|
||||
const canvas = UNSANDBOXED_ALLOWED[fileName];
|
||||
const srcDoc = attr("srcDoc")?.initializer;
|
||||
const blank = !!canvas && !sandbox && !attr("src") && src.includes(canvas.html)
|
||||
&& !!srcDoc && ts.isJsxExpression(srcDoc) && srcDoc.expression?.getText(sf) === canvas.srcDoc;
|
||||
if (!named && !blank && (!value || !ts.isStringLiteral(value) || value.text !== "")) {
|
||||
problems.push(`${fileName}:${line} iframe without sandbox=""`);
|
||||
}
|
||||
}
|
||||
@@ -151,6 +163,16 @@ describe("iframe checker", () => {
|
||||
expect(iframeProblems("components/pages/HtmlFrame.tsx", src.replace("FRAME_SANDBOX", "mode"))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("accepts the editor canvas unsandboxed only in its file, with its constant blank document and no src", () => {
|
||||
const blank = `const BLANK = "<!doctype html><html><head></head><body></body></html>";\n`;
|
||||
const src = `${blank}export const X = () => <iframe title="t" srcDoc={BLANK} />;`;
|
||||
expect(iframeProblems("components/pages/CanvasFrame.tsx", src)).toEqual([]);
|
||||
expect(iframeProblems("fixture.tsx", src)).toHaveLength(1);
|
||||
expect(iframeProblems("components/pages/CanvasFrame.tsx", src.replace("srcDoc={BLANK}", "srcDoc={html}"))).toHaveLength(1);
|
||||
expect(iframeProblems("components/pages/CanvasFrame.tsx", src.replace("srcDoc={BLANK}", "srcDoc={BLANK} src={u}"))).toHaveLength(1);
|
||||
expect(iframeProblems("components/pages/CanvasFrame.tsx", src.replace("<body></body>", "<body><script>x()</script></body>"))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rejects a non-empty or computed sandbox", () => {
|
||||
expect(check(`<iframe sandbox="allow-scripts" srcDoc={html} />`)).toHaveLength(1);
|
||||
expect(check(`<iframe sandbox={mode} srcDoc={html} />`)).toHaveLength(1);
|
||||
|
||||
Reference in new issue
Block a user