Compare commits
66
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d42e60d104 | ||
|
|
7f43869444 | ||
|
|
5c216551fa | ||
|
|
68159086a9 | ||
|
|
cd3c2e1987 | ||
|
|
d977467182 | ||
|
|
5f2ddf90ba | ||
|
|
d31661fd3e | ||
|
|
af1bab4afa | ||
|
|
54ceb7b631 | ||
|
|
537ac65dc0 | ||
|
|
ede3da1cbe | ||
|
|
6b3498d123 | ||
|
|
7e916b77b9 | ||
|
|
b768b66f6f | ||
|
|
5f4f3bc1ee | ||
|
|
55d9535ef2 | ||
|
|
a0691188ca | ||
|
|
de40c60eb9 | ||
|
|
3b977fc277 | ||
|
|
a0d10fc169 | ||
|
|
168529585a | ||
|
|
7b098208bb | ||
|
|
57942f6eae | ||
|
|
fac045fad1 | ||
|
|
8203839b09 | ||
|
|
cd85faa60e | ||
|
|
da39c9bd84 | ||
|
|
8e56e9844e | ||
|
|
7075058824 | ||
|
|
d2711a5aa9 | ||
|
|
00f195882c | ||
|
|
42ea067c84 | ||
|
|
8cb68a2dcb | ||
|
|
f2f293ea58 | ||
|
|
cc962ebfcf | ||
|
|
2ff117e41d | ||
|
|
1b5d62403d | ||
|
|
ae47a277ba | ||
|
|
2deec54154 | ||
|
|
915f5d316b | ||
|
|
7229437ced | ||
|
|
92e62fb3fd | ||
|
|
93acebf162 | ||
|
|
0f1b3af1ef | ||
|
|
25b4f5f39d | ||
|
|
bd8a31e4c8 | ||
|
|
5b5ee728c7 | ||
|
|
1efdfe97d0 | ||
|
|
c20a0c105c | ||
|
|
f66219f247 | ||
|
|
5b11e90303 | ||
|
|
d602cca2cd | ||
|
|
b7d771e2f4 | ||
|
|
51ef5b9611 | ||
|
|
a99b18fbfd | ||
|
|
a1d13fe8d7 | ||
|
|
72394df1d7 | ||
|
|
56fb94ab81 | ||
|
|
909c1754c0 | ||
|
|
e3f08bc6cf | ||
|
|
66e2e488d9 | ||
|
|
d5384c6ac0 | ||
|
|
26b285cc0a | ||
|
|
d195b6f91b | ||
|
|
dd6cbfe71c |
No files matched your search
+23
-5
@@ -150,13 +150,19 @@ Run the three in order before the new services-system, gateway and mobile-api go
|
|||||||
| `openspec/changes/archive/2026-12-02-add-landing-pages/sql/03-company-branding.sql` | Adds `logo_image_id` and `accent_color` to `service-system`.`company`. DDL. |
|
| `openspec/changes/archive/2026-12-02-add-landing-pages/sql/03-company-branding.sql` | Adds `logo_image_id` and `accent_color` to `service-system`.`company`. DDL. |
|
||||||
| `openspec/changes/archive/2026-12-02-add-landing-pages/sql/04-module.sql` | Adds the Pages back-office module (`BO_PAGES`) under Events. No role gets it; super admins grant it under Roles. |
|
| `openspec/changes/archive/2026-12-02-add-landing-pages/sql/04-module.sql` | Adds the Pages back-office module (`BO_PAGES`) under Events. No role gets it; super admins grant it under Roles. |
|
||||||
| `openspec/changes/archive/2026-12-02-add-landing-pages/sql/05-page-labels.sql` | Adds the landing-page labels in English and Chinese. Run it only where `add-zh-cn-messages/sql/03` already ran before this change; the regenerated 03 already includes them. |
|
| `openspec/changes/archive/2026-12-02-add-landing-pages/sql/05-page-labels.sql` | Adds the landing-page labels in English and Chinese. Run it only where `add-zh-cn-messages/sql/03` already ran before this change; the regenerated 03 already includes them. |
|
||||||
| `openspec/changes/add-custom-html-block/sql/01-hide-header.sql` | Adds `hide_header` to `service-counter`.`cms_page`, the "Hide page header" option. DDL. |
|
| `openspec/changes/archive/2026-12-03-add-custom-html-block/sql/01-hide-header.sql` | Adds `hide_header` to `service-counter`.`cms_page`, the "Hide page header" option. DDL. |
|
||||||
| `openspec/changes/add-custom-html-block/sql/02-html-block-labels.sql` | Adds the Custom HTML block labels in English and Chinese. Same rule as `05-page-labels.sql`: only where `add-zh-cn-messages/sql/03` already ran. |
|
| `openspec/changes/archive/2026-12-03-add-custom-html-block/sql/02-html-block-labels.sql` | Adds the Custom HTML block labels in English and Chinese. Same rule as `05-page-labels.sql`: only where `add-zh-cn-messages/sql/03` already ran. |
|
||||||
|
| `openspec/changes/archive/2026-12-03-add-lead-notifications/sql/01-notification-columns.sql` | Turns the unused `service-system`.`notification` table into the staff bell: converts it to utf8mb4 and adds the recipient, company, type, link, collapse and read columns and two indexes. DDL. |
|
||||||
|
| `openspec/changes/archive/2026-12-03-add-lead-notifications/sql/02-notification-labels.sql` | Adds the bell's labels in English and Chinese. Same rule as `05-page-labels.sql`: only where `add-zh-cn-messages/sql/03` already ran. |
|
||||||
|
| `openspec/changes/archive/2026-12-03-add-page-anchor-links/sql/01-anchor-labels.sql` | Adds the "Link name" labels and updates the link hint and the bad-link message, in English and Chinese. Same rule as `05-page-labels.sql`: only where `add-zh-cn-messages/sql/03` already ran. No DDL: link names live in the page's blocks JSON. |
|
||||||
|
| `openspec/changes/archive/2026-12-03-add-page-sections/sql/01-section-labels.sql` | Adds the labels for the new page sections (feature cards, steps, trust strip, call to action), section looks and icons, in English and Chinese. Same rule as `05-page-labels.sql`: only where `add-zh-cn-messages/sql/03` already ran. No DDL: sections live in the page's blocks JSON. |
|
||||||
|
|
||||||
Run them in order before the new services-counter, services-system and mobile-api go live: the new services read the new columns on every event lead and company query. `01` to `03` need a user that may alter tables. `99-rollback.sql` in the same folder removes the module and drops the two tables and the columns, which deletes every page, image, page address and campaign tag.
|
Run them in order before the new services-counter, services-system and mobile-api go live: the new services read the new columns on every event lead and company query. `01` to `03` need a user that may alter tables. `99-rollback.sql` in the same folder removes the module and drops the two tables and the columns, which deletes every page, image, page address and campaign tag.
|
||||||
|
|
||||||
**Review the privacy notice before go-live.** The seeded text is a starting template written for the PDPA, not legal advice. INS and CV should each have theirs checked; a super admin changes it under **Companies → Privacy notice**. A company with no notice has no working QR codes.
|
**Review the privacy notice before go-live.** The seeded text is a starting template written for the PDPA, not legal advice. INS and CV should each have theirs checked; a super admin changes it under **Companies → Privacy notice**. A company with no notice has no working QR codes.
|
||||||
|
|
||||||
|
**Lead notifications (`add-lead-notifications`).** Run `01` before the new services-system goes live; it reads the new columns on every inbox query. Check first that the table is empty (`SELECT COUNT(*) FROM `service-system`.`notification`` returns 0). `01` needs a user that may alter tables. `99-rollback.sql` in the same folder drops the columns, the indexes and the labels, which deletes every notification's read state.
|
||||||
|
|
||||||
**Database user:**
|
**Database user:**
|
||||||
- Create one user with `SELECT, INSERT, UPDATE, DELETE, EXECUTE` on the five schemas, and on `service-whatsapp` once that exists. EXECUTE is needed: service-member calls a stored function.
|
- Create one user with `SELECT, INSERT, UPDATE, DELETE, EXECUTE` on the five schemas, and on `service-whatsapp` once that exists. EXECUTE is needed: service-member calls a stored function.
|
||||||
- Every Java service reads the same variables (section 6): `MYSQLHOST`, `MYSQLPORT`, `MYSQLUSER`, `MYSQLPWD`.
|
- Every Java service reads the same variables (section 6): `MYSQLHOST`, `MYSQLPORT`, `MYSQLUSER`, `MYSQLPWD`.
|
||||||
@@ -251,6 +257,8 @@ The keys:
|
|||||||
|
|
||||||
`service-whatsapp` also reads `MYSQLHOST`, `MYSQLPORT`, `MYSQLUSER` and `MYSQLPWD`. It uses no Pub/Sub, Redis or `key.json`. mobile-api reads the secrets on each request, so a rotated secret needs no restart there; `service-whatsapp` reads them at startup.
|
`service-whatsapp` also reads `MYSQLHOST`, `MYSQLPORT`, `MYSQLUSER` and `MYSQLPWD`. It uses no Pub/Sub, Redis or `key.json`. mobile-api reads the secrets on each request, so a rotated secret needs no restart there; `service-whatsapp` reads them at startup.
|
||||||
|
|
||||||
|
**`service-counter`, optional:** `LEADS_FOLLOWUPNOTICE_CRON` overrides when the daily follow-up summary runs (Spring cron, six fields, Malaysia time). Default `0 0 8 * * *`, 08:00. Run one service-counter replica, or the summary is sent once per replica; a second send on the same day only refreshes an unread summary.
|
||||||
|
|
||||||
**`service-log`:**
|
**`service-log`:**
|
||||||
|
|
||||||
| Variable | Kind | Value |
|
| Variable | Kind | Value |
|
||||||
@@ -423,7 +431,7 @@ data:
|
|||||||
- An image removed from a page stays stored; nothing deletes unused images.
|
- An image removed from a page stays stored; nothing deletes unused images.
|
||||||
- The editor warns about unsaved edits only on reload or close, not when staff click another link in the back office.
|
- The editor warns about unsaved edits only on reload or close, not when staff click another link in the back office.
|
||||||
- A standing enquiries event (section 12) appears in event lists and dashboards like any event.
|
- A standing enquiries event (section 12) appears in event lists and dashboards like any event.
|
||||||
- Links accept only `https://`, `mailto:`, `tel:` or a path starting with `/`. A same-page `#anchor` link (for example a hero button that jumps to the form) is refused; use the page's own path instead.
|
- Links accept only `https://`, `mailto:`, `tel:`, a path starting with `/`, or `#` plus a block's link name.
|
||||||
|
|
||||||
## 11. Connecting WhatsApp (Meta)
|
## 11. Connecting WhatsApp (Meta)
|
||||||
|
|
||||||
@@ -447,14 +455,24 @@ If nothing arrives: the mobile-api log says `WhatsApp webhook forward failed: <s
|
|||||||
|
|
||||||
## 12. Landing pages
|
## 12. Landing pages
|
||||||
|
|
||||||
Marketing builds public pages under **Events → Pages**. Each page has blocks (hero, text, image with text, FAQ and a sign-up form) and is a draft until published. Its address is `/p/<company-code>/<slug>`.
|
Marketing builds public pages under **Events → Pages**. Each page has blocks (hero, text, image with text, feature cards, steps, trust strip, call to action, FAQ, sign-up form and custom HTML) and is a draft until published. Every block except custom HTML has a look: Default, Light grey, Dark or Company colour; the last three draw the block as a full-width band. In dark mode the Dark band shows light, as the page's colours invert. Its address is `/p/<company-code>/<slug>`.
|
||||||
|
|
||||||
1. **Module.** Grant `BO_PAGES` to the roles that build pages.
|
1. **Module.** Grant `BO_PAGES` to the roles that build pages.
|
||||||
2. **Branding.** A super admin sets each company's logo and accent colour under **Companies → Branding**. Buttons on the company's pages use the accent colour, with black or white text, whichever is easier to read. Without them the page shows the company name and the default blue.
|
2. **Branding.** A super admin sets each company's logo and accent colour under **Companies → Branding**. Buttons on the company's pages use the accent colour, with black or white text, whichever is easier to read. Without them the page shows the company name and the default blue.
|
||||||
3. **Standing enquiries event.** A sign-up form always belongs to an event. For general enquiries, each company creates one event, for example "INS website enquiries", with a far-off end date and its sales team, and picks it in the form block. Sign-ups from a landing page are never marked as attended, so this event does not inflate attendance. Name it clearly: it shows in event lists and dashboards.
|
3. **Standing enquiries event.** A sign-up form always belongs to an event. For general enquiries, each company creates one event, for example "INS website enquiries", with a far-off end date and its sales team, and picks it in the form block. Sign-ups from a landing page are never marked as attended, so this event does not inflate attendance. Name it clearly: it shows in event lists and dashboards.
|
||||||
4. **The INS page.** The INS proof of concept (`ins-landing-page`, never deployed) is content, not code: rebuild it by hand in the editor after deploy. Its test leads are not imported.
|
4. **The INS page.** The INS proof of concept (`ins-landing-page`, never deployed) is content, not code: rebuild it by hand in the editor after deploy. Its test leads are not imported.
|
||||||
5. **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.
|
- **Rebuild it as sections.** The INS page is pasted HTML today, which only a developer can maintain. Rebuild it from sections (hero, trust strip, feature cards, steps, FAQ, sign-up form, call to action) so marketing can edit it, then delete the Custom HTML block.
|
||||||
|
- **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. **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.
|
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.
|
**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.
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
# Lead notifications (bell) — design
|
||||||
|
|
||||||
|
Date: 2026-12-02. Status: draft for owner approval.
|
||||||
|
|
||||||
|
## Intent
|
||||||
|
|
||||||
|
Sales staff need to know about new work without refreshing lists: a lead assigned to them, a new sign-up from a landing page, an incoming WhatsApp message, and follow-ups due. This is feature-list item 12, needed before go-live on 2027-01-15. On 2026-12-02 the owner chose the in-app bell only (no email, no WhatsApp alerts) and approved the recommended approach and recipient rules.
|
||||||
|
|
||||||
|
## Goals
|
||||||
|
|
||||||
|
- A bell in the portal header with an unread badge, a drop-down of recent notifications and a full notifications page.
|
||||||
|
- Each notification links straight to the lead, or to the WhatsApp chat.
|
||||||
|
- Read state is stored on the server, so it survives a reload and follows the user to another device.
|
||||||
|
- Four triggers:
|
||||||
|
- lead assigned to me;
|
||||||
|
- new landing-page sign-up;
|
||||||
|
- incoming WhatsApp message on a chat I own;
|
||||||
|
- follow-ups due today.
|
||||||
|
- English and Chinese text, following the user's language.
|
||||||
|
- Company scoping: a user only ever receives notifications about their own company's leads.
|
||||||
|
|
||||||
|
## Non-goals
|
||||||
|
|
||||||
|
- Email, WhatsApp or browser push alerts.
|
||||||
|
- Per-user notification settings (mute a type). Add when staff ask for it.
|
||||||
|
- Admin broadcast messages (babyboo has them; Co-Lite has no need yet).
|
||||||
|
- Purging old notifications. Rows are small; add a purge when the table grows.
|
||||||
|
|
||||||
|
## Anti-goals
|
||||||
|
|
||||||
|
- A notification that reveals another company's lead, or a lead to someone who may not see it.
|
||||||
|
- A noisy bell: one alert per WhatsApp message during a busy chat would train staff to ignore it.
|
||||||
|
- A notification failure that breaks the action behind it. A sign-up, an assignment or an inbound message must succeed even when the notification cannot be written.
|
||||||
|
|
||||||
|
## Approaches
|
||||||
|
|
||||||
|
1. **Port babyboo's bell (chosen).** Each trigger writes one notification row per recipient in `service-system`.`notification`. Babyboo extended that table and built the admin inbox API and the header bell (`add-admin-internal-notifications`, 2026-10-07); the flow is proven.
|
||||||
|
2. **Counts only.** The bell shows numbers computed from existing data (new leads, unread chats, follow-ups due). Cheaper, but no list, no link to the item, and no record of the moment a lead was assigned. Not chosen.
|
||||||
|
|
||||||
|
## Design
|
||||||
|
|
||||||
|
### Storage (service-system)
|
||||||
|
|
||||||
|
Extend the existing, unused `notification` table the way babyboo did, plus a company id:
|
||||||
|
|
||||||
|
- `recipient_type` (`A` for staff; only `A` is used now), `title`, `type`, `link`, `seen`, `read_at`, `company_id`.
|
||||||
|
- Index `(recipient_type, receiver, seen, create_date_time)`.
|
||||||
|
- `receiver` holds the staff user id.
|
||||||
|
- `title` and `message` hold message codes and parameters (JSON), not text, so the bell renders in the reader's language (babyboo's `renderNotice` pattern). Parameters hold only what the bell shows: the lead's name and the event name. No phone numbers or email addresses.
|
||||||
|
|
||||||
|
Endpoints in service-system: create (one or many rows), list mine (newest first, paged), unread count, mark one read, mark all read. The mark-read endpoints only touch rows whose receiver is the caller.
|
||||||
|
|
||||||
|
### Admin API and portal
|
||||||
|
|
||||||
|
- mobile-api: `GET /api/admin/notifications`, `GET /api/admin/notifications/unread-count`, `POST /api/admin/notifications/{id}/read`, `POST /api/admin/notifications/read-all`. The caller is always the signed-in user; no user id is taken from the request.
|
||||||
|
- Portal: babyboo's `NotificationsBell` in the header (polls the unread count every 30 seconds while the tab is visible) and a `/notifications` page. Opening the drop-down marks the shown items read; clicking an item opens its link.
|
||||||
|
- Every signed-in staff user has the bell. No new module permission: a user only ever sees their own notifications.
|
||||||
|
|
||||||
|
### Triggers and recipients
|
||||||
|
|
||||||
|
| Trigger | Where | Who gets it |
|
||||||
|
|---|---|---|
|
||||||
|
| Lead assigned | services-counter, wherever the salesperson of an event lead changes to someone (manual assignment, assignment at capture, re-assignment) | The new salesperson. Not the person who made the change, when they assigned it to themselves. |
|
||||||
|
| New landing-page sign-up | services-counter, registration with source `WEB` | The assigned salesperson when there is one. Otherwise everyone on the event's sales team (`event_salesperson`). Nobody when the event has no sales team. |
|
||||||
|
| Incoming WhatsApp message | services-whatsapp, inbound message on a conversation | The chat owner. Nobody when the chat has no owner (the shared inbox already shows it). One unread notification per chat: while the owner has an unread notification for that chat, a new message updates its time instead of adding another. |
|
||||||
|
| Follow-ups due | services-counter, a daily job at 08:00 Malaysia time | Each salesperson with event leads whose `next_follow_up_date` is today or earlier and whose status is still open. One summary notification per salesperson per day ("3 follow-ups due, 1 overdue"), linking to their event leads list. |
|
||||||
|
|
||||||
|
A new sign-up that is also assigned at capture sends one notification to the salesperson (the sign-up), not two.
|
||||||
|
|
||||||
|
### Delivery
|
||||||
|
|
||||||
|
- Senders call service-system's create endpoint over REST, after their transaction commits, with a 2-second timeout. A failure is logged with ids only and never fails the action. This copies `WhatsappNotifier`.
|
||||||
|
- ponytail: no retry or queue. A lost notification is an inconvenience, not lost data: the lead, the chat and the follow-up date are all still there. Add a Pub/Sub topic if losses show up.
|
||||||
|
- The daily job must not send twice when the service runs more than one copy, or restarts: it records the day it last ran for each company (or uses the existing scheduler lock pattern, if the codebase has one).
|
||||||
|
|
||||||
|
### Labels
|
||||||
|
|
||||||
|
New labels in English and Chinese, shipped as SQL in the change folder, the same way as earlier changes.
|
||||||
|
|
||||||
|
## Constraints
|
||||||
|
|
||||||
|
- New and changed tables carry a company id.
|
||||||
|
- Logs never contain lead names, phone numbers or email addresses.
|
||||||
|
- The notification store is written only through service-system; other services never write its table directly.
|
||||||
|
|
||||||
|
## Left to the builder
|
||||||
|
|
||||||
|
- The exact link targets (lead detail page, chat page, event leads list with a follow-up filter if one exists).
|
||||||
|
- Whether the daily job lives in services-counter or service-system, as long as it runs once per day per company.
|
||||||
|
- Page size of the notifications list and how many items the drop-down shows.
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# Same-page anchor links on landing pages — design
|
||||||
|
|
||||||
|
Approved by the owner on 2026-12-03 (small change).
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
Marketing wants a button near the top of a landing page to jump to the sign-up form further down. Today the editor, the portal and services-counter all refuse a `#anchor` link, and blocks carry no `id` to jump to. On the INS "hotel-technology" page (a Custom HTML block followed by a FORM block), the pasted HTML's own `#consult` and `#top` links do nothing: the sealed frame is sized to its full height, so it never scrolls itself, and as an opaque-origin frame it may not scroll the page around it.
|
||||||
|
|
||||||
|
## Goals
|
||||||
|
|
||||||
|
- Staff can name any block and link to it with `#name` from a button, from rich text, or from inside a Custom HTML block.
|
||||||
|
- In-frame links to an `id` inside the same Custom HTML block work again.
|
||||||
|
|
||||||
|
## Non-goals
|
||||||
|
|
||||||
|
- No automatic ids (`block-3`): they break when blocks are reordered.
|
||||||
|
- No change to how the sealed frame is sandboxed. The frame gets no new grants.
|
||||||
|
|
||||||
|
## Approaches
|
||||||
|
|
||||||
|
1. **An optional link name per block (chosen).** One new optional field, unique per page, stored in the existing blocks JSON. Works for every block type and survives reordering.
|
||||||
|
2. Automatic positional ids (`block-3`). No editor change, but links break silently when blocks move.
|
||||||
|
3. A fixed `id="form"` on the FORM block only. Covers the main case, but not other blocks or `#top`.
|
||||||
|
|
||||||
|
## Design
|
||||||
|
|
||||||
|
- **Link name.** Each block has an optional "Link name": lowercase letters, digits and `-`, starting with a letter or digit and not with `reg-` (the sign-up form's field ids), at most 40 characters, unique on the page. services-counter checks it. The public page renders it as the block's `id`.
|
||||||
|
- **`#name` links.** Button links and rich-text links also accept `#` followed by a name of that pattern. The same rule is in services-counter, the portal's `isSafeLink`, the rich-text editor and the public sanitiser.
|
||||||
|
- **Frame bridge.** The frame document's injected script, which already reports its height, also catches clicks on `#name` links inside the frame and posts the name and, when the frame holds an element with that `id`, the element's offset. The page acts on such a message only from its own frame and only for a name of the pattern. It scrolls to the frame's top plus that offset when the frame has the target; otherwise to a block on the page with that link name; otherwise it does nothing. The frame link's default action is prevented, so the frame never navigates.
|
||||||
|
|
||||||
|
## Left to the builder
|
||||||
|
|
||||||
|
Field placement in the editor, label wording, and smooth vs instant scrolling.
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
# Landing-page builder for marketing staff — design
|
||||||
|
|
||||||
|
Status: approved by the owner on 2026-12-03, including the two calls below.
|
||||||
|
|
||||||
|
Owner calls, 2026-12-03:
|
||||||
|
- **Draft and live are separate (option b).** Edits to a published page stay a draft until Publish; visitors see the published version meanwhile.
|
||||||
|
- **Order.** The three changes ship in order. Whether go-live waits for the on-page editor is decided nearer 2027-01-15; until then the form editor stays.
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
Marketing staff at INS and CV build a landing page for every event. They are not technical. Today they fill in a form of blocks and open a separate preview of the last saved version, and the one real page (INS "hotel-technology") is pasted HTML that only a developer can change. The owner wants a Wix-like experience: staff edit the page itself and see the result as they work, and start from templates rather than a blank page.
|
||||||
|
|
||||||
|
Success: a marketing staff member, without help, creates an event page from a template, changes its text and images on the page, links its form to the event, checks it at phone size, and publishes it, in well under an hour.
|
||||||
|
|
||||||
|
## Goals
|
||||||
|
|
||||||
|
- Edit on the page: click text to change it, click a section to change its settings, add, move, duplicate and remove sections, and see the change at once.
|
||||||
|
- Desktop and phone views in the editor, each showing the page exactly as visitors on that device see it.
|
||||||
|
- Templates: start a page from a ready-made design, or copy an earlier event's page.
|
||||||
|
- Enough section types to build a page like the INS one without code.
|
||||||
|
|
||||||
|
## Non-goals
|
||||||
|
|
||||||
|
- Free placement of elements anywhere on a canvas (owner chose stacking sections, 2026-12-03).
|
||||||
|
- Per-element styling: fonts, sizes or colours chosen per text. Each section has a small set of looks instead.
|
||||||
|
- Animations, page version history, scheduled publishing, custom domains, A/B tests.
|
||||||
|
- Editing pages on a phone: the on-page editor is for laptop and desktop screens.
|
||||||
|
|
||||||
|
## Anti-goals
|
||||||
|
|
||||||
|
- A page that looks fine in the editor but broken on a visitor's phone.
|
||||||
|
- An editor that saves anything the server would not accept, or shows something different from the public page.
|
||||||
|
- Weakening the landing-page rules: block validation, HTML sanitising, the sealed Custom HTML frame, and company scoping all stay as they are.
|
||||||
|
|
||||||
|
## Constraints
|
||||||
|
|
||||||
|
- Go-live is 2027-01-15. The work ships as three changes, each usable on its own, so a late editor does not hold back the rest. The current form editor keeps working until the on-page editor replaces it.
|
||||||
|
- Pages stay one JSON list of blocks in `cms_page.blocks`, checked by services-counter. New section types extend that list; the editor writes the same JSON.
|
||||||
|
- Tailwind 3.4 with viewport breakpoints (`sm:`, `md:`): a block's phone layout depends on the window width, not the width of its container.
|
||||||
|
- Owner rules apply: TDD, Playwright checks, no Tastefully customer data, and SQL only in the change folders.
|
||||||
|
|
||||||
|
## Approaches considered
|
||||||
|
|
||||||
|
**How staff place content** (owner's choice): stacking full-width sections (chosen) versus free placement on a canvas. Free placement roughly doubles the build and makes phone layouts the staff's problem.
|
||||||
|
|
||||||
|
**How the editor is built** (my call, the owner handed over the how):
|
||||||
|
|
||||||
|
1. **Our own editor on the existing blocks (chosen).** The page renders in edit mode inside a same-origin frame. Text becomes editable in place (Tiptap, already installed, for rich text), and a side panel reuses today's block fields. Pros: the data, validation, sanitising and public rendering do not change; no large dependency. Cons: drag-and-drop, selection and undo are ours to build and test.
|
||||||
|
2. **An open-source page-builder library (Puck, MIT).** It ships drag-and-drop, a fields panel, an outline and undo. Pros: less UI to build. Cons: a large new dependency with its own look and data format (an adapter both ways), and its in-place text editing is less mature than Tiptap (unverified for the current version). Rejected: the parts it saves us are the smaller parts of the work.
|
||||||
|
3. **An HTML builder (GrapesJS).** It produces free-form HTML and CSS. Rejected: it bypasses block validation and sanitising, it cannot hold the lead form, and it is free placement.
|
||||||
|
|
||||||
|
**Phone view** (my call): render the page in a frame of the chosen width, so the page's own breakpoints apply, as visitors see it. The alternative, container queries, needs a Tailwind plugin and changes to every block's and the sign-up form's classes, which the QR registration pages share.
|
||||||
|
|
||||||
|
**Templates** (my call): starter templates shipped with the portal, plus "Duplicate page". Templates saved by staff per company would need a new table and screens; duplicating last event's page covers the "every event" case without them.
|
||||||
|
|
||||||
|
## Design
|
||||||
|
|
||||||
|
### Change 1: `add-page-sections` (new section types and section looks)
|
||||||
|
|
||||||
|
New block types, each validated in services-counter, rendered by the public page and edited in today's form:
|
||||||
|
|
||||||
|
- `FEATURES`: heading, optional intro, 2 to 6 cards, each with an icon from a fixed list (about 12 Lucide icons), a title and a short text.
|
||||||
|
- `STEPS`: heading, 2 to 6 numbered steps, each with a title and a short text.
|
||||||
|
- `TRUST`: 2 to 6 short items in one strip (for example "Certified with LG · Samsung · Philips").
|
||||||
|
- `CTA`: a full-width band with a heading, a short text and a button.
|
||||||
|
|
||||||
|
Every block gains a look: `DEFAULT`, `MUTED`, `DARK` or `ACCENT` (the company's accent colour). The look sets the background and the text colour, which is always readable on it. Sections become full-width bands with their content centred, so a page reads like the INS design. The HERO image becomes optional: a hero without an image uses its look's background.
|
||||||
|
|
||||||
|
Limits follow the existing ones: headings 120 characters, short texts 300, card and step titles 80.
|
||||||
|
|
||||||
|
### Change 2: `add-page-drafts-and-templates`
|
||||||
|
|
||||||
|
**Draft and live.**
|
||||||
|
|
||||||
|
- `cms_page` gains a nullable JSON column `draft` holding the editable content: slug, title, description, hide-header and blocks.
|
||||||
|
- A page that has never been published works as today: Save writes the page itself.
|
||||||
|
- A published page saves into `draft` instead. Visitors keep seeing the published content.
|
||||||
|
- **Publish** copies the draft into the page and clears it.
|
||||||
|
- **Discard changes** clears the draft.
|
||||||
|
- Unpublishing works as today.
|
||||||
|
- The draft passes the same checks as a save, including a unique slug among the company's pages. Publish checks it again, because an event may have ended since.
|
||||||
|
- The editor and the staff preview show the draft when there is one. The pages list marks such pages "Unpublished changes".
|
||||||
|
|
||||||
|
**Templates.**
|
||||||
|
|
||||||
|
|
||||||
|
- "New page" first asks for a starting point: Blank, or a starter template with a thumbnail and one line on what it is for. Starters at launch: **Event sign-up** (hero, trust strip, features, steps, FAQ, sign-up form, CTA) and **Service showcase** (hero, image with text, features, FAQ, CTA, form). Placeholder text tells staff what to write ("Your event name"). Templates hold no images; the editor marks the image spots to fill in.
|
||||||
|
- A template's sign-up form has no event yet. Saving tells staff to pick one, as today.
|
||||||
|
- "Duplicate" on the pages list and in the editor copies a page into a new draft of the same company, with slug `<slug>-copy` and status Draft. It runs in the portal (load, then save as new). It needs no new API.
|
||||||
|
- Starters live in portal code as block lists, with their own tests that every starter passes the same rules as a save.
|
||||||
|
|
||||||
|
### Change 3: `add-page-visual-editor` (the on-page editor)
|
||||||
|
|
||||||
|
Layout, at 1024 px and wider:
|
||||||
|
|
||||||
|
```
|
||||||
|
┌ ← Pages Hotel day ▾ Draft [Desktop|Phone] ↶ ↷ [Preview] [Save] [Publish] ┐
|
||||||
|
├───────────────────────────────────────────────────────────────┬───────────────────────┤
|
||||||
|
│ ┌──────── canvas (the page, at the chosen width) ────────┐ │ Section: Features │
|
||||||
|
│ │ HERO "Hotel technology that just works" │ │ Look: [Muted ▾] │
|
||||||
|
│ │ ┌─[⠿ ↑ ↓ ⧉ 🗑]──────────────────────────────────────┐ │ │ Link name: [ ] │
|
||||||
|
│ │ │ FEATURES (selected) click any text to edit │ │ │ Cards: 3 [+ card] │
|
||||||
|
│ │ └─────────────────────────────────────────────────────┘ │ │ Icon card 1: [Wifi▾] │
|
||||||
|
│ │ [ + Add section ] │ │ │
|
||||||
|
│ └─────────────────────────────────────────────────────────┘ │ │
|
||||||
|
└───────────────────────────────────────────────────────────────┴───────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Canvas.** A same-origin frame showing the page through the same `LandingPage` component the public page uses, in edit mode, at full width (Desktop) or 390 px (Phone). The editor and the canvas exchange the draft and the edit events by `postMessage`, and each accepts messages only from the other. Custom HTML blocks stay sealed frames inside the canvas, showing the unsaved HTML.
|
||||||
|
- **Select.** Hovering a section outlines it. Clicking selects it and shows its toolbar: drag handle, up, down, duplicate, delete. The side panel shows that section's settings, which are today's block fields plus the look and the link name. With nothing selected, the panel shows the page settings: title, address, description, header, status.
|
||||||
|
- **Edit text in place.** Clicking a heading, a short text or a button label edits it in place as plain text, with the same length limits as the server, shown when close. Rich text (Text and Image-with-text blocks) edits in place with Tiptap and a small floating toolbar (bold, italic, link, lists, alignment). Links are typed in the side panel or the toolbar's link box, and follow the existing link rule.
|
||||||
|
- **Images.** Clicking an image, or an empty image spot, opens the file picker. The new image shows at once and uploads on save, as today.
|
||||||
|
- **Add and move.** "+ Add section" between sections and at the end opens a picker of section types with small thumbnails. Sections move by dragging the handle (native drag-and-drop) or with the up and down buttons; the buttons are also the keyboard path.
|
||||||
|
- **Undo and redo.** Page-level, up to 50 steps, with Ctrl+Z and Ctrl+Shift+Z.
|
||||||
|
- **Saving.** Save keeps the draft; Publish saves with status Published. Server refusals show on the canvas (the section is outlined, and the panel shows the field's message), using today's error paths. Leaving with unsaved changes asks first, including in-app links (this closes today's gap).
|
||||||
|
- **Below 1024 px** the editor shows today's form, with Preview, because the canvas and panel do not fit.
|
||||||
|
|
||||||
|
The server and the public page do not change in this change, apart from edit-mode hooks in `LandingPage` that only the canvas uses.
|
||||||
|
|
||||||
|
## Left to the builder
|
||||||
|
|
||||||
|
- The exact icon list, the starter templates' wording, the thumbnail images, and the colours of each look within the design tokens.
|
||||||
|
- Undo grouping (one step per word or per field).
|
||||||
|
- Whether the canvas reuses `BlockFields` sub-components for the side panel or splits them.
|
||||||
|
|
||||||
|
## Sequencing
|
||||||
|
|
||||||
|
1. `add-page-sections`: about 3 to 4 days.
|
||||||
|
2. `add-page-drafts-and-templates`: about 4 days.
|
||||||
|
3. `add-page-visual-editor`: about 2 to 3 weeks.
|
||||||
|
|
||||||
|
Each is its own OpenSpec change, approved before it is built. Once change 1 is out, the INS page can be rebuilt as sections instead of pasted HTML. Staff do this in the editor; it is content, not code.
|
||||||
@@ -506,3 +506,20 @@ INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `ic
|
|||||||
-- add-custom-html-block: the hide-header page option
|
-- add-custom-html-block: the hide-header page option
|
||||||
USE `service-counter`;
|
USE `service-counter`;
|
||||||
ALTER TABLE `cms_page` ADD COLUMN `hide_header` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Hide the company header and the page title on the public page' AFTER `status`;
|
ALTER TABLE `cms_page` ADD COLUMN `hide_header` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Hide the company header and the page title on the public page' AFTER `status`;
|
||||||
|
-- add-lead-notifications: the staff notification bell
|
||||||
|
USE `service-system`;
|
||||||
|
ALTER TABLE `notification`
|
||||||
|
CONVERT TO CHARACTER SET utf8mb4,
|
||||||
|
ADD COLUMN `recipient_type` char(1) NULL COMMENT 'A = staff user' AFTER `receiver`,
|
||||||
|
ADD COLUMN `company_id` bigint NULL AFTER `recipient_type`,
|
||||||
|
ADD COLUMN `title` varchar(255) NULL COMMENT 'Message code' AFTER `company_id`,
|
||||||
|
ADD COLUMN `type` varchar(45) NULL COMMENT 'LEAD_ASSIGNED, WEB_SIGNUP, WHATSAPP_MESSAGE, FOLLOW_UP_DUE' AFTER `message`,
|
||||||
|
ADD COLUMN `link` varchar(512) NULL COMMENT 'Portal path opened on click' AFTER `type`,
|
||||||
|
ADD COLUMN `collapse_key` varchar(100) NULL COMMENT 'An unread row with the same receiver and key is updated, not duplicated' AFTER `link`,
|
||||||
|
ADD COLUMN `seen` tinyint(1) NOT NULL DEFAULT 0 AFTER `collapse_key`,
|
||||||
|
ADD COLUMN `read_at` datetime NULL AFTER `seen`,
|
||||||
|
ADD INDEX `idx_notification_inbox` (`recipient_type`, `receiver`, `seen`, `create_date_time`),
|
||||||
|
ADD INDEX `idx_notification_collapse` (`receiver`, `collapse_key`, `seen`);
|
||||||
|
-- add-page-drafts-and-templates: a published page's unpublished draft
|
||||||
|
USE `service-counter`;
|
||||||
|
ALTER TABLE `cms_page` ADD COLUMN `draft` json NULL COMMENT 'Unpublished changes of a published page: slug, title, metaDescription, hideHeader, blocks' AFTER `blocks`;
|
||||||
@@ -1461,6 +1461,72 @@ INSERT INTO message (code, content, area) SELECT 'PagesPreviewBanner', JSON_OBJE
|
|||||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '预览。网页发布后访客才能看到。') WHERE LOWER(code) = LOWER('PagesPreviewBanner') AND area = 'A';
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '预览。网页发布后访客才能看到。') WHERE LOWER(code) = LOWER('PagesPreviewBanner') AND area = 'A';
|
||||||
INSERT INTO message (code, content, area) SELECT 'PagesViewPage', JSON_OBJECT('en_US', 'View page', 'zh_CN', '查看网页'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesViewPage') AND area = 'A');
|
INSERT INTO message (code, content, area) SELECT 'PagesViewPage', JSON_OBJECT('en_US', 'View page', 'zh_CN', '查看网页'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesViewPage') AND area = 'A');
|
||||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '查看网页') WHERE LOWER(code) = LOWER('PagesViewPage') AND area = 'A';
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '查看网页') WHERE LOWER(code) = LOWER('PagesViewPage') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesDuplicate', JSON_OBJECT('en_US', 'Duplicate', 'zh_CN', '复制'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDuplicate') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制') WHERE LOWER(code) = LOWER('PagesDuplicate') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesDuplicateNamed', JSON_OBJECT('en_US', 'Duplicate {title}', 'zh_CN', '复制 {title}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDuplicateNamed') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制 {title}') WHERE LOWER(code) = LOWER('PagesDuplicateNamed') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesChooseStart', JSON_OBJECT('en_US', 'How do you want to start?', 'zh_CN', '您想如何开始?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChooseStart') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '您想如何开始?') WHERE LOWER(code) = LOWER('PagesChooseStart') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesStartBlank', JSON_OBJECT('en_US', 'Blank page', 'zh_CN', '空白网页'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesStartBlank') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '空白网页') WHERE LOWER(code) = LOWER('PagesStartBlank') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesStartBlankHint', JSON_OBJECT('en_US', 'Start empty and add sections yourself.', 'zh_CN', '从空白开始,自行添加区块。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesStartBlankHint') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '从空白开始,自行添加区块。') WHERE LOWER(code) = LOWER('PagesStartBlankHint') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesTemplateEvent', JSON_OBJECT('en_US', 'Event sign-up', 'zh_CN', '活动报名'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateEvent') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '活动报名') WHERE LOWER(code) = LOWER('PagesTemplateEvent') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesTemplateEventHint', JSON_OBJECT('en_US', 'A page for one event: headline, benefits, steps, questions and the sign-up form.', 'zh_CN', '为单个活动准备的网页:标题、优势、步骤、常见问题和报名表。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateEventHint') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '为单个活动准备的网页:标题、优势、步骤、常见问题和报名表。') WHERE LOWER(code) = LOWER('PagesTemplateEventHint') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesTemplateShowcase', JSON_OBJECT('en_US', 'Service showcase', 'zh_CN', '服务展示'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateShowcase') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '服务展示') WHERE LOWER(code) = LOWER('PagesTemplateShowcase') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesTemplateShowcaseHint', JSON_OBJECT('en_US', 'Present a service with benefits, steps and a call to action, ending with the sign-up form.', 'zh_CN', '介绍一项服务:优势、步骤和行动号召,最后是报名表。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateShowcaseHint') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '介绍一项服务:优势、步骤和行动号召,最后是报名表。') WHERE LOWER(code) = LOWER('PagesTemplateShowcaseHint') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesHasDraft', JSON_OBJECT('en_US', 'Unpublished changes', 'zh_CN', '有未发布的修改'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHasDraft') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '有未发布的修改') WHERE LOWER(code) = LOWER('PagesHasDraft') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesDraftBanner', JSON_OBJECT('en_US', 'You have unpublished changes. Visitors still see the published version until you publish them.', 'zh_CN', '您有未发布的修改。发布之前,访客看到的仍是已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDraftBanner') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '您有未发布的修改。发布之前,访客看到的仍是已发布的版本。') WHERE LOWER(code) = LOWER('PagesDraftBanner') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesPublishChanges', JSON_OBJECT('en_US', 'Publish changes', 'zh_CN', '发布修改'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPublishChanges') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '发布修改') WHERE LOWER(code) = LOWER('PagesPublishChanges') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesDiscardChanges', JSON_OBJECT('en_US', 'Discard changes', 'zh_CN', '放弃修改'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardChanges') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '放弃修改') WHERE LOWER(code) = LOWER('PagesDiscardChanges') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesDiscardTitle', JSON_OBJECT('en_US', 'Discard unpublished changes?', 'zh_CN', '放弃未发布的修改?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardTitle') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '放弃未发布的修改?') WHERE LOWER(code) = LOWER('PagesDiscardTitle') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesDiscardMessage', JSON_OBJECT('en_US', 'Your unpublished changes to "{title}" will be lost. Visitors keep seeing the published version.', 'zh_CN', '“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardMessage') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。') WHERE LOWER(code) = LOWER('PagesDiscardMessage') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT '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');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '修改已放弃。') WHERE LOWER(code) = LOWER('PagesChangesDiscarded') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesPreviewDraftBanner', JSON_OBJECT('en_US', 'Preview of unpublished changes. Visitors still see the published version.', 'zh_CN', '未发布修改的预览。访客看到的仍是已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPreviewDraftBanner') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '未发布修改的预览。访客看到的仍是已发布的版本。') WHERE LOWER(code) = LOWER('PagesPreviewDraftBanner') AND area = 'A';
|
||||||
INSERT INTO message (code, content, area) SELECT 'PagesSaved', JSON_OBJECT('en_US', 'Page saved.', 'zh_CN', '网页已保存。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesSaved') AND area = 'A');
|
INSERT INTO message (code, content, area) SELECT 'PagesSaved', JSON_OBJECT('en_US', 'Page saved.', 'zh_CN', '网页已保存。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesSaved') AND area = 'A');
|
||||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '网页已保存。') WHERE LOWER(code) = LOWER('PagesSaved') AND area = 'A';
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '网页已保存。') WHERE LOWER(code) = LOWER('PagesSaved') AND area = 'A';
|
||||||
INSERT INTO message (code, content, area) SELECT 'PagesSaveFailed', JSON_OBJECT('en_US', 'Could not save the page. Try again.', 'zh_CN', '无法保存网页,请重试。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesSaveFailed') AND area = 'A');
|
INSERT INTO message (code, content, area) SELECT 'PagesSaveFailed', JSON_OBJECT('en_US', 'Could not save the page. Try again.', 'zh_CN', '无法保存网页,请重试。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesSaveFailed') AND area = 'A');
|
||||||
@@ -1491,12 +1557,114 @@ INSERT INTO message (code, content, area) SELECT 'PagesBlockForm', JSON_OBJECT('
|
|||||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '报名表') WHERE LOWER(code) = LOWER('PagesBlockForm') AND area = 'A';
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '报名表') WHERE LOWER(code) = LOWER('PagesBlockForm') AND area = 'A';
|
||||||
INSERT INTO message (code, content, area) SELECT 'PagesBlockHtml', JSON_OBJECT('en_US', 'Custom HTML', 'zh_CN', '自定义 HTML'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockHtml') AND area = 'A');
|
INSERT INTO message (code, content, area) SELECT 'PagesBlockHtml', JSON_OBJECT('en_US', 'Custom HTML', 'zh_CN', '自定义 HTML'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockHtml') AND area = 'A');
|
||||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '自定义 HTML') WHERE LOWER(code) = LOWER('PagesBlockHtml') AND area = 'A';
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '自定义 HTML') WHERE LOWER(code) = LOWER('PagesBlockHtml') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesBlockFeatures', JSON_OBJECT('en_US', 'Feature cards', 'zh_CN', '功能卡片'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockFeatures') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '功能卡片') WHERE LOWER(code) = LOWER('PagesBlockFeatures') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesBlockSteps', JSON_OBJECT('en_US', 'Steps', 'zh_CN', '步骤'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockSteps') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '步骤') WHERE LOWER(code) = LOWER('PagesBlockSteps') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesBlockTrust', JSON_OBJECT('en_US', 'Trust strip', 'zh_CN', '信任条'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockTrust') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '信任条') WHERE LOWER(code) = LOWER('PagesBlockTrust') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesBlockCta', JSON_OBJECT('en_US', 'Call to action', 'zh_CN', '行动号召'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockCta') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '行动号召') WHERE LOWER(code) = LOWER('PagesBlockCta') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesLook', JSON_OBJECT('en_US', 'Look', 'zh_CN', '外观'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLook') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '外观') WHERE LOWER(code) = LOWER('PagesLook') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesLookDefault', JSON_OBJECT('en_US', 'Default', 'zh_CN', '默认'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLookDefault') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '默认') WHERE LOWER(code) = LOWER('PagesLookDefault') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesLookMuted', JSON_OBJECT('en_US', 'Light grey', 'zh_CN', '浅灰'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLookMuted') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '浅灰') WHERE LOWER(code) = LOWER('PagesLookMuted') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesLookDark', JSON_OBJECT('en_US', 'Dark', 'zh_CN', '深色'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLookDark') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '深色') WHERE LOWER(code) = LOWER('PagesLookDark') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesLookAccent', JSON_OBJECT('en_US', 'Company colour', 'zh_CN', '公司主色'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLookAccent') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '公司主色') WHERE LOWER(code) = LOWER('PagesLookAccent') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIntro', JSON_OBJECT('en_US', 'Intro', 'zh_CN', '简介'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIntro') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '简介') WHERE LOWER(code) = LOWER('PagesIntro') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesCardN', JSON_OBJECT('en_US', 'Card {number}', 'zh_CN', '卡片 {number}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCardN') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '卡片 {number}') WHERE LOWER(code) = LOWER('PagesCardN') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesStepN', JSON_OBJECT('en_US', 'Step {number}', 'zh_CN', '步骤 {number}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesStepN') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '步骤 {number}') WHERE LOWER(code) = LOWER('PagesStepN') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesItemN', JSON_OBJECT('en_US', 'Item {number}', 'zh_CN', '项目 {number}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesItemN') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '项目 {number}') WHERE LOWER(code) = LOWER('PagesItemN') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesCardIcon', JSON_OBJECT('en_US', 'Icon', 'zh_CN', '图标'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCardIcon') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '图标') WHERE LOWER(code) = LOWER('PagesCardIcon') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesCardTitle', JSON_OBJECT('en_US', 'Title', 'zh_CN', '标题'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCardTitle') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '标题') WHERE LOWER(code) = LOWER('PagesCardTitle') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesCardText', JSON_OBJECT('en_US', 'Text', 'zh_CN', '文字'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCardText') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '文字') WHERE LOWER(code) = LOWER('PagesCardText') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesAddCard', JSON_OBJECT('en_US', 'Add card', 'zh_CN', '添加卡片'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddCard') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加卡片') WHERE LOWER(code) = LOWER('PagesAddCard') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesAddStep', JSON_OBJECT('en_US', 'Add step', 'zh_CN', '添加步骤'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddStep') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加步骤') WHERE LOWER(code) = LOWER('PagesAddStep') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesAddItem', JSON_OBJECT('en_US', 'Add item', 'zh_CN', '添加项目'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddItem') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加项目') WHERE LOWER(code) = LOWER('PagesAddItem') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesRemoveCard', JSON_OBJECT('en_US', 'Remove', 'zh_CN', '移除'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesRemoveCard') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '移除') WHERE LOWER(code) = LOWER('PagesRemoveCard') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconWifi', JSON_OBJECT('en_US', 'WiFi', 'zh_CN', 'WiFi'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconWifi') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', 'WiFi') WHERE LOWER(code) = LOWER('PagesIconWifi') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconPhone', JSON_OBJECT('en_US', 'Phone', 'zh_CN', '电话'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconPhone') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '电话') WHERE LOWER(code) = LOWER('PagesIconPhone') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconTv', JSON_OBJECT('en_US', 'TV', 'zh_CN', '电视'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconTv') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '电视') WHERE LOWER(code) = LOWER('PagesIconTv') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconMonitor', JSON_OBJECT('en_US', 'Screen', 'zh_CN', '屏幕'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconMonitor') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '屏幕') WHERE LOWER(code) = LOWER('PagesIconMonitor') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconLock', JSON_OBJECT('en_US', 'Lock', 'zh_CN', '门锁'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconLock') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门锁') WHERE LOWER(code) = LOWER('PagesIconLock') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconShieldCheck', JSON_OBJECT('en_US', 'Security', 'zh_CN', '安全'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconShieldCheck') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '安全') WHERE LOWER(code) = LOWER('PagesIconShieldCheck') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconCloud', JSON_OBJECT('en_US', 'Cloud', 'zh_CN', '云端'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconCloud') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '云端') WHERE LOWER(code) = LOWER('PagesIconCloud') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconWrench', JSON_OBJECT('en_US', 'Service', 'zh_CN', '维修服务'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconWrench') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '维修服务') WHERE LOWER(code) = LOWER('PagesIconWrench') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconHeadset', JSON_OBJECT('en_US', 'Support', 'zh_CN', '客服支持'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconHeadset') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '客服支持') WHERE LOWER(code) = LOWER('PagesIconHeadset') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconUsers', JSON_OBJECT('en_US', 'People', 'zh_CN', '人员'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconUsers') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '人员') WHERE LOWER(code) = LOWER('PagesIconUsers') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconCalendar', JSON_OBJECT('en_US', 'Calendar', 'zh_CN', '日历'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconCalendar') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '日历') WHERE LOWER(code) = LOWER('PagesIconCalendar') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconStar', JSON_OBJECT('en_US', 'Star', 'zh_CN', '星标'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconStar') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '星标') WHERE LOWER(code) = LOWER('PagesIconStar') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesCardCount', JSON_OBJECT('en_US', 'Use 2 to 6 cards.', 'zh_CN', '请使用 2 至 6 张卡片。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCardCount') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请使用 2 至 6 张卡片。') WHERE LOWER(code) = LOWER('PagesCardCount') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesBadIcon', JSON_OBJECT('en_US', 'Choose an icon from the list.', 'zh_CN', '请从列表中选择图标。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadIcon') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请从列表中选择图标。') WHERE LOWER(code) = LOWER('PagesBadIcon') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesBadLook', JSON_OBJECT('en_US', 'Choose a look from the list.', 'zh_CN', '请从列表中选择外观。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadLook') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请从列表中选择外观。') WHERE LOWER(code) = LOWER('PagesBadLook') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesUnusedField', JSON_OBJECT('en_US', 'This section doesn''t use this field.', 'zh_CN', '此区块不使用该字段。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUnusedField') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此区块不使用该字段。') WHERE LOWER(code) = LOWER('PagesUnusedField') AND area = 'A';
|
||||||
INSERT INTO message (code, content, area) SELECT 'PagesHtml', JSON_OBJECT('en_US', 'HTML', 'zh_CN', 'HTML'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHtml') AND area = 'A');
|
INSERT INTO message (code, content, area) SELECT 'PagesHtml', JSON_OBJECT('en_US', 'HTML', 'zh_CN', 'HTML'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHtml') AND area = 'A');
|
||||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', 'HTML') WHERE LOWER(code) = LOWER('PagesHtml') AND area = 'A';
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', 'HTML') WHERE LOWER(code) = LOWER('PagesHtml') AND area = 'A';
|
||||||
INSERT INTO message (code, content, area) SELECT 'PagesHtmlHint', JSON_OBJECT('en_US', 'Forms inside the pasted HTML don''t send. Add a Sign-up form block to collect leads.', 'zh_CN', '粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHtmlHint') AND area = 'A');
|
INSERT INTO message (code, content, area) SELECT 'PagesHtmlHint', JSON_OBJECT('en_US', 'Forms inside the pasted HTML don''t send. Add a Sign-up form block to collect leads.', 'zh_CN', '粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHtmlHint') AND area = 'A');
|
||||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。') WHERE LOWER(code) = LOWER('PagesHtmlHint') AND area = 'A';
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。') WHERE LOWER(code) = LOWER('PagesHtmlHint') AND area = 'A';
|
||||||
INSERT INTO message (code, content, area) SELECT 'PagesHideHeader', JSON_OBJECT('en_US', 'Hide page header', 'zh_CN', '隐藏页面顶栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHideHeader') AND area = 'A');
|
INSERT INTO message (code, content, area) SELECT 'PagesHideHeader', JSON_OBJECT('en_US', 'Hide page header', 'zh_CN', '隐藏页面顶栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHideHeader') AND area = 'A');
|
||||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '隐藏页面顶栏') WHERE LOWER(code) = LOWER('PagesHideHeader') AND area = 'A';
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '隐藏页面顶栏') WHERE LOWER(code) = LOWER('PagesHideHeader') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NotificationsTitle', JSON_OBJECT('en_US', 'Notifications', 'zh_CN', '通知'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsTitle') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '通知') WHERE LOWER(code) = LOWER('NotificationsTitle') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NotificationsUnread', JSON_OBJECT('en_US', 'Notifications, {count} unread', 'zh_CN', '通知,{count} 条未读'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsUnread') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '通知,{count} 条未读') WHERE LOWER(code) = LOWER('NotificationsUnread') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NotificationsEmpty', JSON_OBJECT('en_US', 'No notifications yet.', 'zh_CN', '暂无通知。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsEmpty') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '暂无通知。') WHERE LOWER(code) = LOWER('NotificationsEmpty') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NotificationsLoadFailed', JSON_OBJECT('en_US', 'Couldn''t load notifications.', 'zh_CN', '无法加载通知。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsLoadFailed') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '无法加载通知。') WHERE LOWER(code) = LOWER('NotificationsLoadFailed') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NotificationsMarkAllRead', JSON_OBJECT('en_US', 'Mark all read', 'zh_CN', '全部标为已读'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsMarkAllRead') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '全部标为已读') WHERE LOWER(code) = LOWER('NotificationsMarkAllRead') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NotificationsSeeAll', JSON_OBJECT('en_US', 'See all', 'zh_CN', '查看全部'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsSeeAll') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '查看全部') WHERE LOWER(code) = LOWER('NotificationsSeeAll') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NotificationsUnreadBadge', JSON_OBJECT('en_US', 'Unread', 'zh_CN', '未读'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsUnreadBadge') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '未读') WHERE LOWER(code) = LOWER('NotificationsUnreadBadge') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NoticeLeadAssigned', JSON_OBJECT('en_US', 'Lead assigned to you', 'zh_CN', '有新线索分配给你'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeLeadAssigned') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '有新线索分配给你') WHERE LOWER(code) = LOWER('NoticeLeadAssigned') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NoticeWebSignup', JSON_OBJECT('en_US', 'New sign-up', 'zh_CN', '新的报名'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWebSignup') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '新的报名') WHERE LOWER(code) = LOWER('NoticeWebSignup') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NoticeLeadBody', JSON_OBJECT('en_US', '{lead} · {event}', 'zh_CN', '{lead} · {event}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeLeadBody') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '{lead} · {event}') WHERE LOWER(code) = LOWER('NoticeLeadBody') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NoticeFollowUpDue', JSON_OBJECT('en_US', 'Follow-ups due', 'zh_CN', '待跟进'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeFollowUpDue') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '待跟进') WHERE LOWER(code) = LOWER('NoticeFollowUpDue') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NoticeFollowUpBody', JSON_OBJECT('en_US', '{due} due today, {overdue} overdue', 'zh_CN', '今天到期 {due} 条,已逾期 {overdue} 条'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeFollowUpBody') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '今天到期 {due} 条,已逾期 {overdue} 条') WHERE LOWER(code) = LOWER('NoticeFollowUpBody') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NoticeWhatsappMessage', JSON_OBJECT('en_US', 'New WhatsApp message', 'zh_CN', '新的 WhatsApp 消息'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWhatsappMessage') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '新的 WhatsApp 消息') WHERE LOWER(code) = LOWER('NoticeWhatsappMessage') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NoticeWhatsappBody', JSON_OBJECT('en_US', 'From {name}', 'zh_CN', '来自 {name}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWhatsappBody') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '来自 {name}') WHERE LOWER(code) = LOWER('NoticeWhatsappBody') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NoticeWhatsappBodyNoName', JSON_OBJECT('en_US', 'From a new contact', 'zh_CN', '来自新联系人'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWhatsappBodyNoName') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '来自新联系人') WHERE LOWER(code) = LOWER('NoticeWhatsappBodyNoName') AND area = 'A';
|
||||||
INSERT INTO message (code, content, area) SELECT 'PagesMoveUp', JSON_OBJECT('en_US', 'Move up', 'zh_CN', '上移'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesMoveUp') AND area = 'A');
|
INSERT INTO message (code, content, area) SELECT 'PagesMoveUp', JSON_OBJECT('en_US', 'Move up', 'zh_CN', '上移'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesMoveUp') AND area = 'A');
|
||||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '上移') WHERE LOWER(code) = LOWER('PagesMoveUp') AND area = 'A';
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '上移') WHERE LOWER(code) = LOWER('PagesMoveUp') AND area = 'A';
|
||||||
INSERT INTO message (code, content, area) SELECT 'PagesMoveDown', JSON_OBJECT('en_US', 'Move down', 'zh_CN', '下移'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesMoveDown') AND area = 'A');
|
INSERT INTO message (code, content, area) SELECT 'PagesMoveDown', JSON_OBJECT('en_US', 'Move down', 'zh_CN', '下移'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesMoveDown') AND area = 'A');
|
||||||
@@ -1577,8 +1745,10 @@ INSERT INTO message (code, content, area) SELECT 'PagesDivider', JSON_OBJECT('en
|
|||||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '分隔线') WHERE LOWER(code) = LOWER('PagesDivider') AND area = 'A';
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '分隔线') WHERE LOWER(code) = LOWER('PagesDivider') AND area = 'A';
|
||||||
INSERT INTO message (code, content, area) SELECT 'PagesLink', JSON_OBJECT('en_US', 'Link', 'zh_CN', '链接'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLink') AND area = 'A');
|
INSERT INTO message (code, content, area) SELECT 'PagesLink', JSON_OBJECT('en_US', 'Link', 'zh_CN', '链接'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLink') AND area = 'A');
|
||||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接') WHERE LOWER(code) = LOWER('PagesLink') AND area = 'A';
|
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 /)', 'zh_CN', '链接地址(https://、mailto:、tel: 或 /)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLinkPrompt') 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';
|
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');
|
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';
|
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');
|
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');
|
||||||
@@ -1595,8 +1765,16 @@ INSERT INTO message (code, content, area) SELECT 'PagesFaqCount', JSON_OBJECT('e
|
|||||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请添加 1 至 30 个问题。') WHERE LOWER(code) = LOWER('PagesFaqCount') AND area = 'A';
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请添加 1 至 30 个问题。') WHERE LOWER(code) = LOWER('PagesFaqCount') AND area = 'A';
|
||||||
INSERT INTO message (code, content, area) SELECT 'PagesButtonPair', JSON_OBJECT('en_US', 'Fill in both the button label and the button link, or neither.', 'zh_CN', '按钮文字和按钮链接需同时填写或同时留空。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesButtonPair') AND area = 'A');
|
INSERT INTO message (code, content, area) SELECT 'PagesButtonPair', JSON_OBJECT('en_US', 'Fill in both the button label and the button link, or neither.', 'zh_CN', '按钮文字和按钮链接需同时填写或同时留空。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesButtonPair') AND area = 'A');
|
||||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '按钮文字和按钮链接需同时填写或同时留空。') WHERE LOWER(code) = LOWER('PagesButtonPair') AND area = 'A';
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '按钮文字和按钮链接需同时填写或同时留空。') WHERE LOWER(code) = LOWER('PagesButtonPair') AND area = 'A';
|
||||||
INSERT INTO message (code, content, area) SELECT 'PagesBadLink', JSON_OBJECT('en_US', 'Use a link that starts with https://, mailto:, tel: or /.', 'zh_CN', '链接须以 https://、mailto:、tel: 或 / 开头。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadLink') AND area = 'A');
|
INSERT INTO message (code, content, area) SELECT 'PagesBadLink', JSON_OBJECT('en_US', 'Use a link that starts with https://, mailto:, tel:, / or #.', 'zh_CN', '链接须以 https://、mailto:、tel:、/ 或 # 开头。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadLink') AND area = 'A');
|
||||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接须以 https://、mailto:、tel: 或 / 开头。') WHERE LOWER(code) = LOWER('PagesBadLink') AND area = 'A';
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接须以 https://、mailto:、tel:、/ 或 # 开头。') WHERE LOWER(code) = LOWER('PagesBadLink') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesAnchor', JSON_OBJECT('en_US', 'Link name (optional)', 'zh_CN', '链接名称(可选)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAnchor') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接名称(可选)') WHERE LOWER(code) = LOWER('PagesAnchor') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesAnchorHint', JSON_OBJECT('en_US', 'Link to this block with #name, for example #signup. Lowercase letters, digits and - only.', 'zh_CN', '用 #名称 链接到此区块,例如 #signup。仅限小写字母、数字和 -。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAnchorHint') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '用 #名称 链接到此区块,例如 #signup。仅限小写字母、数字和 -。') WHERE LOWER(code) = LOWER('PagesAnchorHint') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesBadAnchor', JSON_OBJECT('en_US', 'Use lowercase letters, digits and - (up to 40), starting with a letter or digit and not with reg-.', 'zh_CN', '请使用小写字母、数字和 -(最多 40 个),以字母或数字开头,且不能以 reg- 开头。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadAnchor') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请使用小写字母、数字和 -(最多 40 个),以字母或数字开头,且不能以 reg- 开头。') WHERE LOWER(code) = LOWER('PagesBadAnchor') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesAnchorTaken', JSON_OBJECT('en_US', 'Another block on this page already has this link name.', 'zh_CN', '本页已有其他区块使用此链接名称。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAnchorTaken') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '本页已有其他区块使用此链接名称。') WHERE LOWER(code) = LOWER('PagesAnchorTaken') AND area = 'A';
|
||||||
INSERT INTO message (code, content, area) SELECT 'PagesScript', JSON_OBJECT('en_US', 'Scripts and event handlers are not allowed.', 'zh_CN', '不允许使用脚本或事件处理程序。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesScript') AND area = 'A');
|
INSERT INTO message (code, content, area) SELECT 'PagesScript', JSON_OBJECT('en_US', 'Scripts and event handlers are not allowed.', 'zh_CN', '不允许使用脚本或事件处理程序。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesScript') AND area = 'A');
|
||||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不允许使用脚本或事件处理程序。') WHERE LOWER(code) = LOWER('PagesScript') AND area = 'A';
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不允许使用脚本或事件处理程序。') WHERE LOWER(code) = LOWER('PagesScript') AND area = 'A';
|
||||||
INSERT INTO message (code, content, area) SELECT 'PagesBadImage', JSON_OBJECT('en_US', 'Upload the image again.', 'zh_CN', '请重新上传图片。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadImage') AND area = 'A');
|
INSERT INTO message (code, content, area) SELECT 'PagesBadImage', JSON_OBJECT('en_US', 'Upload the image again.', 'zh_CN', '请重新上传图片。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadImage') 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.
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-12-02
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# Design
|
||||||
|
|
||||||
|
The full design is `docs/superpowers/specs/2026-12-02-lead-notifications-design.md` (approved 2026-12-02). This file records the technical decisions.
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
- `service-system`.`notification` exists from Tastefully (`id, receiver, message, create_date_time`, `utf8mb3`) and is empty. services-system has a thin `NotificationController` (save, find by receiver).
|
||||||
|
- Babyboo extended the same table and built the admin inbox API and bell (`add-admin-internal-notifications`, 2026-10-07). Its files are the porting source: services-system `Notification`/`NotificationService`/`NotificationController`, mobile-api `AdminNotificationController`/`AdminNotificationService`, portal `NotificationsBell.tsx`, `app/notifications/page.tsx`, `app/api/notifications/**`, `app/lib/services/notifications.ts`.
|
||||||
|
- services-counter already calls another service best-effort after commit: `WhatsappNotifier` (2-second timeout, never throws, `TransactionSynchronization.afterCommit`).
|
||||||
|
- Assignment points in services-counter: `EventLeadService` capture and update (`salespersonChanged`), `RegistrationService` new capture and `alreadyCaptured` (`assign`). The event's sales team is `event_salesperson`.
|
||||||
|
- Inbound WhatsApp: `WebhookIngestService` calls `WaConversationRepository.recordInbound`. The chat owner is `wa_conversation.owner_user_id`.
|
||||||
|
- Leads due: `event_lead.next_follow_up_date`, `status`, `salesperson_user_id`. The lead dashboard already counts overdue follow-ups.
|
||||||
|
- The portal has `usePolling` (babyboo used `useVisiblePolling`).
|
||||||
|
|
||||||
|
## Goals / Non-Goals
|
||||||
|
|
||||||
|
**Goals:** the bell, the four triggers, server read state, both languages, company scoping.
|
||||||
|
|
||||||
|
**Non-Goals:** email, WhatsApp or push alerts; per-user settings; broadcasts; purging.
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
1. **One row per recipient** in `notification`, `recipient_type = 'A'`, `receiver` = user id as text (the column is `varchar(45)`), `company_id` set. Babyboo's model; read state is a column.
|
||||||
|
2. **Codes, not text.** `type` is `LEAD_ASSIGNED`, `WEB_SIGNUP`, `WHATSAPP_MESSAGE` or `FOLLOW_UP_DUE`. `title` and `message` hold a label code and a JSON parameter object (lead name, event name, counts). The bell renders them with `t()`. No phone numbers or emails in parameters.
|
||||||
|
3. **Collapse key.** An optional `collapse_key` on create: when the receiver already has an unread row with that key, the create updates that row's message and time and marks nothing else; otherwise it inserts. WhatsApp uses `WA:<conversation uuid>`; the follow-up summary uses `FOLLOW_UP:<date>`, so a second run of the job on the same day before the user reads it does not duplicate.
|
||||||
|
- ponytail: a job rerun after the user read the summary adds a second one that day. Add a run record if that happens in practice.
|
||||||
|
4. **Delivery is a REST call after commit**, copying `WhatsappNotifier`: 2-second timeout, no retry, failures logged with ids only. Counter and WhatsApp each get one small `StaffNotifier` posting to services-system's create endpoint.
|
||||||
|
- ponytail: no queue; a lost notification leaves the lead, chat and follow-up date in place. Move to Pub/Sub if losses show up.
|
||||||
|
5. **Recipients are resolved by the sender**, which already has the data: counter knows the salesperson and the event's sales team; WhatsApp knows the chat owner. services-system only stores and serves rows.
|
||||||
|
6. **Self-assignment is silent.** When the staff user making the change is the new salesperson, no "lead assigned" notification is sent. The counter compares the request's acting user with the new salesperson.
|
||||||
|
7. **A web sign-up assigned at capture sends one notification**, of type `WEB_SIGNUP`, to the salesperson. A web sign-up without a salesperson goes to every user in `event_salesperson` for that event; none when the team is empty.
|
||||||
|
8. **Follow-up job** in services-counter, `@Scheduled(cron = "${leads.follow-up-notice.cron:0 0 8 * * *}", zone = "Asia/Kuala_Lumpur")`. It groups open event leads with `next_follow_up_date <= today` by company and salesperson, and sends one summary each (due today count, overdue count) linking to the event leads list. Leads without a salesperson are skipped.
|
||||||
|
9. **Admin API** in mobile-api reads the user id and company from the session, never from the request. Mark-read endpoints change only the caller's rows; another user's id returns 404.
|
||||||
|
10. **Bell** ported from babyboo: polls the unread count every 30 seconds while visible, the drop-down shows the newest 10, opening it marks the shown items read, clicking navigates to `link`. `/notifications` lists 20 per page with "Mark all read". Every signed-in user gets it; no module permission.
|
||||||
|
11. **Charset.** The DDL converts the table to `utf8mb4` (it is empty), so names with any characters are stored.
|
||||||
|
|
||||||
|
## Risks / Trade-offs
|
||||||
|
|
||||||
|
- [Lost notifications on a services-system outage] → the underlying data is unaffected; logs show the failures.
|
||||||
|
- [Noisy bell for busy salespeople] → the WhatsApp collapse and the daily summary limit it; per-user settings come later if asked.
|
||||||
|
- [Leaking another company's lead] → recipients come from the same company's data; the API filters by the session user; tests cover a second company.
|
||||||
|
- [Links that the reader may not open] → links point to pages that still check access; a notification only names a lead its recipient is assigned to or on the team for.
|
||||||
|
|
||||||
|
## Migration Plan
|
||||||
|
|
||||||
|
Run `sql/01` (additive columns on an empty table) before deploying the services, then `sql/02` labels. Rollback: `sql/99-rollback.sql` drops the columns and labels; the old services ignore them.
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None.
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# Proposal
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
Sales staff learn about new work only by refreshing lists. A lead assigned to them, a sign-up from a landing page, a customer's WhatsApp reply and a follow-up falling due all go unnoticed until someone looks. This is feature-list item 12, needed before go-live on 2027-01-15. On 2026-12-02 the owner chose an in-app bell only and approved the design: `docs/superpowers/specs/2026-12-02-lead-notifications-design.md`.
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
- **Bell in the portal header** for every signed-in staff user:
|
||||||
|
- an unread badge, refreshed every 30 seconds while the tab is visible;
|
||||||
|
- a drop-down of recent notifications, each linking to its lead or chat;
|
||||||
|
- a full notifications page;
|
||||||
|
- read state kept on the server.
|
||||||
|
- **Four triggers:**
|
||||||
|
- a lead assigned to someone notifies that salesperson;
|
||||||
|
- a landing-page sign-up notifies the assigned salesperson, else the event's sales team;
|
||||||
|
- an inbound WhatsApp message notifies the chat owner, at most one unread notification per chat;
|
||||||
|
- a daily 08:00 (Malaysia) summary of follow-ups due or overdue, per salesperson.
|
||||||
|
- **Text follows the reader's language**: notifications store message codes and parameters, not text.
|
||||||
|
- **Best effort:** a notification that cannot be written never fails the sign-up, assignment or message behind it.
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
|
||||||
|
- `lead-notifications`: the staff bell, its read state, and the four triggers with their recipients.
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
|
||||||
|
None. The triggers add a side effect to lead capture, lead assignment and WhatsApp intake without changing their specified behaviour.
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- **services-system:** the unused `notification` table gains `recipient_type`, `company_id`, `title`, `type`, `link`, `collapse_key`, `seen`, `read_at` and an index, and moves to `utf8mb4`. New endpoints: create, list mine, unread count, mark read, mark all read.
|
||||||
|
- **SQL:** `sql/01-notification-columns.sql` (DDL), `sql/02-notification-labels.sql` (labels), `sql/99-rollback.sql`. Mirror 01 into `local/seed/`.
|
||||||
|
- **services-counter:** a notifier called after commit on assignment and on web sign-up; a daily follow-up job.
|
||||||
|
- **services-whatsapp:** a notifier called after an inbound message is recorded.
|
||||||
|
- **mobile-api:** `/api/admin/notifications` (list, unread count, read, read all), always for the signed-in user.
|
||||||
|
- **Portal:** `NotificationsBell` in the header, `/notifications` page, BFF routes, labels with Chinese. Ported from babyboo.
|
||||||
|
- **Gateway:** unchanged; `/api/admin/**` is already routed.
|
||||||
|
- **Dependencies:** none.
|
||||||
+132
@@ -0,0 +1,132 @@
|
|||||||
|
## Purpose
|
||||||
|
|
||||||
|
In-app notifications for staff: a bell with unread state, and alerts when a lead is assigned, a landing-page sign-up arrives, a customer sends a WhatsApp message, or follow-ups fall due.
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Staff Notification Bell
|
||||||
|
|
||||||
|
The portal SHALL show every signed-in staff user a bell in the header with the count of their unread notifications, refreshed at least every 30 seconds while the page is visible. Opening the bell SHALL list their newest notifications, newest first, and mark the listed ones read. Choosing a notification SHALL open the page it links to.
|
||||||
|
|
||||||
|
#### Scenario: Unread count and opening the bell
|
||||||
|
|
||||||
|
- **GIVEN** a salesperson has 3 unread notifications
|
||||||
|
- **WHEN** they open any portal page
|
||||||
|
- **THEN** the bell shows 3
|
||||||
|
- **WHEN** they open the bell
|
||||||
|
- **THEN** the 3 notifications are listed newest first
|
||||||
|
- **AND** after a reload the bell shows no unread count
|
||||||
|
|
||||||
|
#### Scenario: A notification opens its lead
|
||||||
|
|
||||||
|
- **GIVEN** a "lead assigned" notification for lead L
|
||||||
|
- **WHEN** the salesperson chooses it
|
||||||
|
- **THEN** the portal opens lead L
|
||||||
|
|
||||||
|
### Requirement: Notifications Page
|
||||||
|
|
||||||
|
The portal SHALL provide a notifications page listing the signed-in user's notifications, newest first and paged, showing which are unread, with an action to mark all of them read.
|
||||||
|
|
||||||
|
#### Scenario: Mark all read
|
||||||
|
|
||||||
|
- **GIVEN** a user with 25 notifications, 5 of them unread
|
||||||
|
- **WHEN** they open the notifications page and choose "Mark all read"
|
||||||
|
- **THEN** none of their notifications is unread
|
||||||
|
- **AND** the bell shows no unread count
|
||||||
|
|
||||||
|
### Requirement: Notifications Are Private To Their Recipient
|
||||||
|
|
||||||
|
The system SHALL show and change a user's notifications only for that user, identified from their session. A request naming another user's notification SHALL be refused as not found. A notification SHALL only name a lead of the recipient's own company.
|
||||||
|
|
||||||
|
#### Scenario: Another user's notification
|
||||||
|
|
||||||
|
- **GIVEN** notification N belongs to user A
|
||||||
|
- **WHEN** user B asks to mark N read
|
||||||
|
- **THEN** the request is refused as not found
|
||||||
|
- **AND** N stays unread for user A
|
||||||
|
|
||||||
|
#### Scenario: Two companies
|
||||||
|
|
||||||
|
- **GIVEN** an INS salesperson and a CV salesperson
|
||||||
|
- **WHEN** a CV lead is assigned to the CV salesperson
|
||||||
|
- **THEN** only the CV salesperson is notified
|
||||||
|
|
||||||
|
### Requirement: Notifications Follow The Reader's Language
|
||||||
|
|
||||||
|
A notification SHALL be stored as message codes with parameters and shown in the reader's current portal language. Its parameters SHALL NOT include phone numbers or email addresses.
|
||||||
|
|
||||||
|
#### Scenario: Chinese reader
|
||||||
|
|
||||||
|
- **GIVEN** a "lead assigned" notification
|
||||||
|
- **WHEN** a user with the portal in Chinese opens the bell
|
||||||
|
- **THEN** the notification text is in Chinese, with the lead's name
|
||||||
|
|
||||||
|
### Requirement: Lead Assigned Notification
|
||||||
|
|
||||||
|
When an event lead's salesperson is set or changed to a user, the system SHALL notify that user, linking to the lead. It SHALL NOT notify a user who assigned the lead to themselves, and SHALL NOT notify anyone when the salesperson is cleared.
|
||||||
|
|
||||||
|
#### Scenario: Manager assigns a lead
|
||||||
|
|
||||||
|
- **WHEN** a manager assigns event lead L to salesperson S
|
||||||
|
- **THEN** S gets one "lead assigned" notification naming L and its event
|
||||||
|
|
||||||
|
#### Scenario: Self-assignment
|
||||||
|
|
||||||
|
- **WHEN** salesperson S assigns lead L to themselves
|
||||||
|
- **THEN** no notification is created
|
||||||
|
|
||||||
|
### Requirement: Landing Page Sign-up Notification
|
||||||
|
|
||||||
|
When a landing-page sign-up creates or updates an event lead, the system SHALL notify the lead's salesperson if it has one, otherwise every member of the event's sales team, once each. With no salesperson and no sales team, nobody SHALL be notified.
|
||||||
|
|
||||||
|
#### Scenario: Unassigned sign-up
|
||||||
|
|
||||||
|
- **GIVEN** event E has sales team members S1 and S2
|
||||||
|
- **WHEN** a visitor signs up on a page whose form belongs to E, and no salesperson is assigned
|
||||||
|
- **THEN** S1 and S2 each get one "new sign-up" notification
|
||||||
|
|
||||||
|
#### Scenario: Assigned at capture
|
||||||
|
|
||||||
|
- **WHEN** a web sign-up is captured already assigned to S
|
||||||
|
- **THEN** S gets exactly one notification, the "new sign-up" one
|
||||||
|
|
||||||
|
### Requirement: WhatsApp Message Notification
|
||||||
|
|
||||||
|
When an inbound WhatsApp message is recorded on a chat with an owner, the system SHALL notify the owner, linking to the chat. While the owner has an unread notification for that chat, a further message SHALL update it rather than add another. A chat without an owner SHALL notify nobody.
|
||||||
|
|
||||||
|
#### Scenario: Busy chat
|
||||||
|
|
||||||
|
- **GIVEN** salesperson S owns a chat
|
||||||
|
- **WHEN** the customer sends 4 messages before S opens the bell
|
||||||
|
- **THEN** S has one unread notification for that chat, timed at the last message
|
||||||
|
|
||||||
|
#### Scenario: Unowned chat
|
||||||
|
|
||||||
|
- **WHEN** a message arrives on a chat without an owner
|
||||||
|
- **THEN** no notification is created
|
||||||
|
|
||||||
|
### Requirement: Follow-ups Due Notification
|
||||||
|
|
||||||
|
Every day at 08:00 Malaysia time, the system SHALL send each salesperson with open event leads whose next follow-up date is today or earlier one summary notification giving the count due today and the count overdue, linking to their event leads.
|
||||||
|
|
||||||
|
#### Scenario: Morning summary
|
||||||
|
|
||||||
|
- **GIVEN** salesperson S has 2 open leads due today and 1 open lead due yesterday
|
||||||
|
- **WHEN** the daily run happens
|
||||||
|
- **THEN** S gets one notification saying 2 due today and 1 overdue
|
||||||
|
|
||||||
|
#### Scenario: Nothing due
|
||||||
|
|
||||||
|
- **GIVEN** salesperson S has no open lead due today or earlier
|
||||||
|
- **WHEN** the daily run happens
|
||||||
|
- **THEN** S gets no notification
|
||||||
|
|
||||||
|
### Requirement: Notifications Never Block The Action
|
||||||
|
|
||||||
|
A failure to create a notification SHALL NOT fail or roll back the sign-up, assignment or inbound message that caused it. The failure SHALL be logged without names, phone numbers or email addresses.
|
||||||
|
|
||||||
|
#### Scenario: Notification store down
|
||||||
|
|
||||||
|
- **GIVEN** the notification store cannot be reached
|
||||||
|
- **WHEN** a visitor signs up on a landing page
|
||||||
|
- **THEN** the sign-up succeeds and the lead is saved
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
-- Co-Lite change add-lead-notifications: the staff notification bell.
|
||||||
|
-- Target: `service-system`.`notification`, the unused table from Tastefully. Pre-check (read-only):
|
||||||
|
-- SELECT COUNT(*) FROM `service-system`.`notification`; -- expect 0
|
||||||
|
-- The table is converted to utf8mb4 (names in any script) and gains babyboo's bell columns plus company_id
|
||||||
|
-- and collapse_key. Existing columns keep their meaning. Run once.
|
||||||
|
SET NAMES utf8mb4;
|
||||||
|
USE `service-system`;
|
||||||
|
ALTER TABLE `notification`
|
||||||
|
CONVERT TO CHARACTER SET utf8mb4,
|
||||||
|
ADD COLUMN `recipient_type` char(1) NULL COMMENT 'A = staff user' AFTER `receiver`,
|
||||||
|
ADD COLUMN `company_id` bigint NULL AFTER `recipient_type`,
|
||||||
|
ADD COLUMN `title` varchar(255) NULL COMMENT 'Message code' AFTER `company_id`,
|
||||||
|
ADD COLUMN `type` varchar(45) NULL COMMENT 'LEAD_ASSIGNED, WEB_SIGNUP, WHATSAPP_MESSAGE, FOLLOW_UP_DUE' AFTER `message`,
|
||||||
|
ADD COLUMN `link` varchar(512) NULL COMMENT 'Portal path opened on click' AFTER `type`,
|
||||||
|
ADD COLUMN `collapse_key` varchar(100) NULL COMMENT 'An unread row with the same receiver and key is updated, not duplicated' AFTER `link`,
|
||||||
|
ADD COLUMN `seen` tinyint(1) NOT NULL DEFAULT 0 AFTER `collapse_key`,
|
||||||
|
ADD COLUMN `read_at` datetime NULL AFTER `seen`,
|
||||||
|
ADD INDEX `idx_notification_inbox` (`recipient_type`, `receiver`, `seen`, `create_date_time`),
|
||||||
|
ADD INDEX `idx_notification_collapse` (`receiver`, `collapse_key`, `seen`);
|
||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
-- The labels added by add-lead-notifications, 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 'NotificationsTitle', JSON_OBJECT('en_US', 'Notifications', 'zh_CN', '通知'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsTitle') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '通知') WHERE LOWER(code) = LOWER('NotificationsTitle') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NotificationsUnread', JSON_OBJECT('en_US', 'Notifications, {count} unread', 'zh_CN', '通知,{count} 条未读'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsUnread') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '通知,{count} 条未读') WHERE LOWER(code) = LOWER('NotificationsUnread') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NotificationsEmpty', JSON_OBJECT('en_US', 'No notifications yet.', 'zh_CN', '暂无通知。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsEmpty') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '暂无通知。') WHERE LOWER(code) = LOWER('NotificationsEmpty') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NotificationsLoadFailed', JSON_OBJECT('en_US', 'Couldn''t load notifications.', 'zh_CN', '无法加载通知。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsLoadFailed') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '无法加载通知。') WHERE LOWER(code) = LOWER('NotificationsLoadFailed') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NotificationsMarkAllRead', JSON_OBJECT('en_US', 'Mark all read', 'zh_CN', '全部标为已读'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsMarkAllRead') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '全部标为已读') WHERE LOWER(code) = LOWER('NotificationsMarkAllRead') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NotificationsSeeAll', JSON_OBJECT('en_US', 'See all', 'zh_CN', '查看全部'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsSeeAll') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '查看全部') WHERE LOWER(code) = LOWER('NotificationsSeeAll') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NotificationsUnreadBadge', JSON_OBJECT('en_US', 'Unread', 'zh_CN', '未读'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsUnreadBadge') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '未读') WHERE LOWER(code) = LOWER('NotificationsUnreadBadge') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NoticeLeadAssigned', JSON_OBJECT('en_US', 'Lead assigned to you', 'zh_CN', '有新线索分配给你'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeLeadAssigned') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '有新线索分配给你') WHERE LOWER(code) = LOWER('NoticeLeadAssigned') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NoticeWebSignup', JSON_OBJECT('en_US', 'New sign-up', 'zh_CN', '新的报名'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWebSignup') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '新的报名') WHERE LOWER(code) = LOWER('NoticeWebSignup') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NoticeLeadBody', JSON_OBJECT('en_US', '{lead} · {event}', 'zh_CN', '{lead} · {event}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeLeadBody') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '{lead} · {event}') WHERE LOWER(code) = LOWER('NoticeLeadBody') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NoticeFollowUpDue', JSON_OBJECT('en_US', 'Follow-ups due', 'zh_CN', '待跟进'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeFollowUpDue') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '待跟进') WHERE LOWER(code) = LOWER('NoticeFollowUpDue') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NoticeFollowUpBody', JSON_OBJECT('en_US', '{due} due today, {overdue} overdue', 'zh_CN', '今天到期 {due} 条,已逾期 {overdue} 条'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeFollowUpBody') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '今天到期 {due} 条,已逾期 {overdue} 条') WHERE LOWER(code) = LOWER('NoticeFollowUpBody') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NoticeWhatsappMessage', JSON_OBJECT('en_US', 'New WhatsApp message', 'zh_CN', '新的 WhatsApp 消息'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWhatsappMessage') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '新的 WhatsApp 消息') WHERE LOWER(code) = LOWER('NoticeWhatsappMessage') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NoticeWhatsappBody', JSON_OBJECT('en_US', 'From {name}', 'zh_CN', '来自 {name}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWhatsappBody') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '来自 {name}') WHERE LOWER(code) = LOWER('NoticeWhatsappBody') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'NoticeWhatsappBodyNoName', JSON_OBJECT('en_US', 'From a new contact', 'zh_CN', '来自新联系人'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWhatsappBodyNoName') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '来自新联系人') WHERE LOWER(code) = LOWER('NoticeWhatsappBodyNoName') AND area = 'A';
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
-- Co-Lite change add-lead-notifications: rollback. Drops the bell columns and labels; the previous release never
|
||||||
|
-- reads them. The charset change is left in place (utf8mb4 holds everything utf8mb3 did).
|
||||||
|
SET NAMES utf8mb4;
|
||||||
|
USE `service-system`;
|
||||||
|
ALTER TABLE `notification`
|
||||||
|
DROP INDEX `idx_notification_inbox`,
|
||||||
|
DROP INDEX `idx_notification_collapse`,
|
||||||
|
DROP COLUMN `recipient_type`,
|
||||||
|
DROP COLUMN `company_id`,
|
||||||
|
DROP COLUMN `title`,
|
||||||
|
DROP COLUMN `type`,
|
||||||
|
DROP COLUMN `link`,
|
||||||
|
DROP COLUMN `collapse_key`,
|
||||||
|
DROP COLUMN `seen`,
|
||||||
|
DROP COLUMN `read_at`;
|
||||||
|
DELETE FROM message WHERE code IN ('NotificationsTitle', 'NotificationsUnread', 'NotificationsEmpty', 'NotificationsLoadFailed', 'NotificationsMarkAllRead', 'NotificationsSeeAll', 'NotificationsUnreadBadge', 'NoticeLeadAssigned', 'NoticeWebSignup', 'NoticeLeadBody', 'NoticeFollowUpDue', 'NoticeFollowUpBody', 'NoticeWhatsappMessage', 'NoticeWhatsappBody', 'NoticeWhatsappBodyNoName') AND area = 'A';
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Tasks: add-lead-notifications
|
||||||
|
|
||||||
|
Design: `design.md` and `docs/superpowers/specs/2026-12-02-lead-notifications-design.md`. Every task is TDD. Work is serial in the main session, with a self-review per task. Porting source: babyboo's `add-admin-internal-notifications`.
|
||||||
|
|
||||||
|
## 1. Store and API
|
||||||
|
|
||||||
|
- [x] 1.1 SQL: `sql/01-notification-columns.sql` (columns, index, `utf8mb4`), `sql/99-rollback.sql`; mirror 01 into `local/seed/`.
|
||||||
|
- [x] 1.2 services-system: the extended `Notification`; create (with `collapse_key`), list mine (paged), unread count, mark one read (own rows only), mark all read.
|
||||||
|
- Verify: `mvn -T 1C -B -pl solvway-services-system -am verify`
|
||||||
|
- [x] 1.3 mobile-api: `/api/admin/notifications`, `/unread-count`, `/{id}/read`, `/read-all`, user and company from the session.
|
||||||
|
- Verify: `mvn -T 1C -B -pl solvway-mobile-api -am verify`
|
||||||
|
|
||||||
|
## 2. Triggers
|
||||||
|
|
||||||
|
- [x] 2.1 services-counter `StaffNotifier` (after commit, 2 s timeout, never throws, ids-only logs).
|
||||||
|
- Lead assigned at capture and on update, not on self-assignment or clearing.
|
||||||
|
- Web sign-up to the salesperson, else the event's sales team; one notification when assigned at capture.
|
||||||
|
- [x] 2.2 services-counter daily follow-up summary job (08:00 Asia/Kuala_Lumpur, cron property), one per salesperson with open leads due today or overdue.
|
||||||
|
- Verify (2.1, 2.2): `mvn -T 1C -B -pl solvway-services-counter -am verify`
|
||||||
|
- [x] 2.3 services-whatsapp: notify the chat owner after an inbound message is recorded, collapse key `WA:<conversation uuid>`; no owner, no notification.
|
||||||
|
- Verify: `mvn -T 1C -B -pl solvway-services-whatsapp -am verify`
|
||||||
|
|
||||||
|
## 3. Portal
|
||||||
|
|
||||||
|
- [x] 3.1 BFF routes `app/api/notifications/**` and `app/lib/services/notifications.ts`.
|
||||||
|
- [x] 3.2 `NotificationsBell` in the header (30 s polling while visible, newest 10, opening marks read, click opens the link) and the `/notifications` page with "Mark all read".
|
||||||
|
- [x] 3.3 Labels in `defaultMessages.ts` with Chinese in `zh_CN.seed.json`, then `npm run i18n:sql`. `sql/02-notification-labels.sql` holds only the new labels.
|
||||||
|
- Verify (3.1 to 3.3): `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`
|
||||||
|
|
||||||
|
## 4. Release
|
||||||
|
|
||||||
|
- [x] 4.1 `docs/deployment.md`: the SQL rows and the follow-up job's cron property.
|
||||||
|
- [x] 4.2 Live Playwright check on the local stack, signed in as two users of different companies:
|
||||||
|
- assigning a lead notifies the salesperson and not the other company;
|
||||||
|
- a landing-page sign-up notifies the event's sales team;
|
||||||
|
- a WhatsApp message (mock) on an owned chat shows one notification per chat;
|
||||||
|
- the follow-up job (run by setting its cron for the test) gives the summary;
|
||||||
|
- the bell, the page and "Mark all read" work in English and Chinese, at 1280 and 360 px.
|
||||||
|
- [x] 4.3 Whole-branch self-review (security: recipient scoping, own-rows-only read endpoints, no personal data in logs or parameters), then the PR to main and the merge.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-12-03
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
## Context
|
||||||
|
|
||||||
|
See `docs/superpowers/specs/2026-12-03-page-anchor-links-design.md`. Blocks are one JSON column on `cms_page`; services-counter validates them; mobile-api passes them through as maps; the portal renders them. Custom HTML runs in an opaque-origin frame (`allow-scripts allow-popups allow-popups-to-escape-sandbox`) whose injected script already posts height reports, which `HtmlFrame` accepts only from its own `contentWindow`.
|
||||||
|
|
||||||
|
## Goals / Non-Goals
|
||||||
|
|
||||||
|
**Goals:** named block targets; `#name` links from buttons, rich text and Custom HTML.
|
||||||
|
|
||||||
|
**Non-Goals:** automatic ids; any new frame permission; scroll offsets for a sticky header (the public page has none).
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
1. **Field `anchor` on the block**, pattern `^(?!reg-)[a-z0-9][a-z0-9-]{0,39}$`, unique per page. `reg-` is reserved because the sign-up form renders its fields with literal `reg-*` ids. Stored in the blocks JSON, so no DDL. Refusal codes: `PagesBadAnchor`, `PagesAnchorTaken`.
|
||||||
|
2. **Link rule.** `#` plus the same pattern is a safe link everywhere a link is checked: `CmsBlockValidator.safeLink`, `isSafeLink`, the editor's `SAFE_LINK`, and the sanitiser (sanitize-html already keeps scheme-less hrefs; a test pins it).
|
||||||
|
3. **Ids.** The block wrapper in `CmsBlocks` gets `id={anchor}` for every type, the HTML frame included. Rendered only when the name matches the pattern, so rows written another way cannot inject odd ids.
|
||||||
|
4. **Frame bridge.** The injected script adds one click listener: for `a[href^="#"]` with a valid name it prevents the default and posts `{type:"colite-frame-anchor", name, y}`, where `y` is the in-frame element's document offset or `null`. `HtmlFrame` checks the source window as for heights, validates the message in a pure `frameAnchor()` helper, then scrolls the window to `frame top + y`, or to `document.getElementById(name)`, else ignores it. Smooth scroll.
|
||||||
|
5. **Messages are data only.** The page never navigates or evaluates anything from a frame message; it only scrolls.
|
||||||
|
|
||||||
|
## Risks / Trade-offs
|
||||||
|
|
||||||
|
- A frame script could post anchor requests at will → it can only scroll its own page, which it could already make tall. Accepted.
|
||||||
|
- A link name equal to an id the portal already uses on that page (e.g. `main`) would clash → the sign-up form's field ids all start with `reg-`, which link names may not; other ids on the page come from `useId` and cannot match the pattern. The staff preview runs inside the back-office shell, whose ids are not checked against link names.
|
||||||
|
- Pages saved by an older release lose link names → only on rollback; noted in the proposal.
|
||||||
|
|
||||||
|
## Migration Plan
|
||||||
|
|
||||||
|
Deploy services-counter and the portal; run `sql/01-anchor-labels.sql`. Rollback: previous images and `sql/99-rollback.sql`.
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
## Why
|
||||||
|
|
||||||
|
Landing pages cannot link within themselves. Buttons and rich-text links refuse `#anchor`, blocks have no id to jump to, and links inside a Custom HTML block do nothing because the sealed frame never scrolls and may not scroll the page. The INS page's "Get My Free Consultation" button therefore cannot take visitors to the sign-up form. Design: `docs/superpowers/specs/2026-12-03-page-anchor-links-design.md`.
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
- Each block gets an optional link name, unique on the page, rendered as the block's id.
|
||||||
|
- Button and rich-text links accept `#name`.
|
||||||
|
- The Custom HTML frame reports clicks on `#name` links to the page, which scrolls to the target inside the frame or to the named block.
|
||||||
|
- New and changed editor labels in English and Chinese.
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
|
||||||
|
None.
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
|
||||||
|
- `landing-pages`: same-page links and block link names.
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- services-counter: `CmsBlock` gains `anchor`; `CmsBlockValidator` checks it and accepts `#name` links. No DDL: blocks are stored as JSON.
|
||||||
|
- mobile-api: none (blocks pass through as maps).
|
||||||
|
- Portal: `cmsPages.ts` (`isSafeLink`, model), `RichTextEditor.tsx`, `pageHtml.ts`, `frameHtml.ts` (script and message parsing), `HtmlFrame.tsx`, `CmsBlocks.tsx` (ids), `BlockFields.tsx` (field), labels.
|
||||||
|
- SQL: `sql/01-anchor-labels.sql` and `sql/99-rollback.sql` (labels only).
|
||||||
|
- Older releases ignore the new field on read, and a page saved by an older release loses its link names.
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
## MODIFIED Requirements
|
||||||
|
|
||||||
|
### Requirement: Page Content Cannot Run Scripts
|
||||||
|
|
||||||
|
A button SHALL have both a label and a link or neither. The link SHALL start with a single `/`, `https://`, `mailto:`, `tel:`, or `#` plus a valid block link name. A save SHALL be refused when RICH_TEXT or IMAGE_TEXT HTML holds a `script` element, an `on*` attribute or a `javascript:` URL. The public page SHALL also sanitise that HTML against an allow-list. HTML blocks are exempt: they only run sealed.
|
||||||
|
|
||||||
|
#### Scenario: Script link on a button
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a HERO button link `javascript:alert(1)`
|
||||||
|
- **THEN** the save is refused on field `blocks[0].buttonUrl`
|
||||||
|
|
||||||
|
#### Scenario: Script in rich text
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with rich text holding `<img src=x onerror=alert(1)>`
|
||||||
|
- **THEN** the save is refused on that block's HTML field
|
||||||
|
|
||||||
|
#### Scenario: Script in an HTML block
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with an HTML block holding `<script>document.title = "x"</script>`
|
||||||
|
- **THEN** the save succeeds
|
||||||
|
|
||||||
|
#### Scenario: Same-page button link
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a HERO button link `#signup`
|
||||||
|
- **THEN** the save succeeds
|
||||||
|
|
||||||
|
#### Scenario: Malformed same-page link
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a HERO button link `#Sign Up`
|
||||||
|
- **THEN** the save is refused on field `blocks[0].buttonUrl`
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Block Link Names
|
||||||
|
|
||||||
|
Any block MAY carry a link name. A link name SHALL be 1 to 40 characters of lowercase letters, digits and `-`, starting with a letter or digit, SHALL NOT start with `reg-` (the sign-up form's own field ids), and SHALL be unique within the page. A save breaking either rule SHALL be refused on that block's link-name field, writing nothing. The public page and the staff preview SHALL give the block that name as its element id, so a `#name` link scrolls to it.
|
||||||
|
|
||||||
|
#### Scenario: Hero button jumps to the form
|
||||||
|
|
||||||
|
- **GIVEN** a published page whose FORM block has the link name `signup` and whose HERO button links to `#signup`
|
||||||
|
- **WHEN** a visitor clicks the button
|
||||||
|
- **THEN** the page scrolls to the form
|
||||||
|
|
||||||
|
#### Scenario: Duplicate link name
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with two blocks named `signup`
|
||||||
|
- **THEN** the save is refused on field `blocks[1].anchor` and nothing is written
|
||||||
|
|
||||||
|
#### Scenario: Reserved link name
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a block named `reg-email`
|
||||||
|
- **THEN** the save is refused on field `blocks[0].anchor` and nothing is written
|
||||||
|
|
||||||
|
#### Scenario: Bad link name
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a block named `Sign Up`
|
||||||
|
- **THEN** the save is refused on field `blocks[0].anchor` and nothing is written
|
||||||
|
|
||||||
|
### Requirement: Same-Page Links From A Custom HTML Frame
|
||||||
|
|
||||||
|
A click on a `#name` link inside a Custom HTML block SHALL scroll the page, without navigating the frame. The target SHALL be the element with that id inside the same frame when there is one, otherwise the block on the page with that link name, otherwise nothing happens. The page SHALL act only on such requests from its own frames and only for names of the link-name pattern. The frame SHALL gain no new sandbox permissions.
|
||||||
|
|
||||||
|
#### Scenario: Link to the form below the frame
|
||||||
|
|
||||||
|
- **GIVEN** a published page with an HTML block holding `<a href="#signup">` and a FORM block named `signup`
|
||||||
|
- **WHEN** a visitor clicks that link
|
||||||
|
- **THEN** the page scrolls to the form
|
||||||
|
|
||||||
|
#### Scenario: Link inside the frame
|
||||||
|
|
||||||
|
- **GIVEN** a published HTML block whose content holds `<a href="#top">` near its bottom and an element with id `top` at its start
|
||||||
|
- **WHEN** a visitor scrolls down and clicks that link
|
||||||
|
- **THEN** the page scrolls back to the start of the frame
|
||||||
|
|
||||||
|
#### Scenario: Another window asks to scroll
|
||||||
|
|
||||||
|
- **WHEN** a different window posts a same-page link request to the page
|
||||||
|
- **THEN** the page does not scroll
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
-- The labels added or changed by add-page-anchor-links, 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 '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 'PagesBadLink', JSON_OBJECT('en_US', 'Use a link that starts with https://, mailto:, tel:, / or #.', 'zh_CN', '链接须以 https://、mailto:、tel:、/ 或 # 开头。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadLink') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接须以 https://、mailto:、tel:、/ 或 # 开头。') WHERE LOWER(code) = LOWER('PagesBadLink') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesAnchor', JSON_OBJECT('en_US', 'Link name (optional)', 'zh_CN', '链接名称(可选)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAnchor') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接名称(可选)') WHERE LOWER(code) = LOWER('PagesAnchor') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesAnchorHint', JSON_OBJECT('en_US', 'Link to this block with #name, for example #signup. Lowercase letters, digits and - only.', 'zh_CN', '用 #名称 链接到此区块,例如 #signup。仅限小写字母、数字和 -。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAnchorHint') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '用 #名称 链接到此区块,例如 #signup。仅限小写字母、数字和 -。') WHERE LOWER(code) = LOWER('PagesAnchorHint') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesBadAnchor', JSON_OBJECT('en_US', 'Use lowercase letters, digits and - (up to 40), starting with a letter or digit and not with reg-.', 'zh_CN', '请使用小写字母、数字和 -(最多 40 个),以字母或数字开头,且不能以 reg- 开头。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadAnchor') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请使用小写字母、数字和 -(最多 40 个),以字母或数字开头,且不能以 reg- 开头。') WHERE LOWER(code) = LOWER('PagesBadAnchor') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesAnchorTaken', JSON_OBJECT('en_US', 'Another block on this page already has this link name.', 'zh_CN', '本页已有其他区块使用此链接名称。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAnchorTaken') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '本页已有其他区块使用此链接名称。') WHERE LOWER(code) = LOWER('PagesAnchorTaken') AND area = 'A';
|
||||||
|
-- PagesLinkPrompt and PagesBadLink already exist: their English changes too.
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.en_US', 'Link address (https://, mailto:, tel:, / or #name)') WHERE LOWER(code) = LOWER('PagesLinkPrompt') AND area = 'A';
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.en_US', 'Use a link that starts with https://, mailto:, tel:, / or #.') WHERE LOWER(code) = LOWER('PagesBadLink') AND area = 'A';
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- Co-Lite change add-page-anchor-links: rollback of the labels. Blocks keep their link names in the JSON; the previous
|
||||||
|
-- release ignores them on read, and a page saved by it loses them. Pages with #name links must be edited before
|
||||||
|
-- they are saved under the previous release, which refuses such links.
|
||||||
|
SET NAMES utf8mb4;
|
||||||
|
USE `service-system`;
|
||||||
|
DELETE FROM message WHERE code IN ('PagesAnchor', 'PagesAnchorHint', 'PagesBadAnchor', 'PagesAnchorTaken') AND area = 'A';
|
||||||
|
UPDATE message SET content = JSON_SET(content, '$.en_US', 'Link address (https://, mailto:, tel: or /)', '$.zh_CN', '链接地址(https://、mailto:、tel: 或 /)') WHERE LOWER(code) = LOWER('PagesLinkPrompt') AND area = 'A';
|
||||||
|
UPDATE message SET content = JSON_SET(content, '$.en_US', 'Use a link that starts with https://, mailto:, tel: or /.', '$.zh_CN', '链接须以 https://、mailto:、tel: 或 / 开头。') WHERE LOWER(code) = LOWER('PagesBadLink') AND area = 'A';
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# Tasks: add-page-anchor-links
|
||||||
|
|
||||||
|
Design: `design.md`. Every task is TDD. Work is serial in the main session, with a self-review per task.
|
||||||
|
|
||||||
|
## 1. services-counter
|
||||||
|
|
||||||
|
- [x] 1.1 `CmsBlock.anchor`; `CmsBlockValidator`: link-name pattern and uniqueness (`PagesBadAnchor`, `PagesAnchorTaken` on `blocks[i].anchor`), `#name` accepted by `safeLink`.
|
||||||
|
- Verify: `mvn -T 1C -B -pl solvway-services-counter -am verify`
|
||||||
|
|
||||||
|
## 2. Portal
|
||||||
|
|
||||||
|
- [x] 2.1 Link rules: `isSafeLink`, the rich-text editor's `SAFE_LINK`, a sanitiser test that `#name` hrefs survive; block ids in `CmsBlocks` (pattern-checked).
|
||||||
|
- [x] 2.2 Frame bridge: click listener in the frame script, `frameAnchor()` message check, `HtmlFrame` scroll (own frame only).
|
||||||
|
- [x] 2.3 Editor: "Link name" field per block with field errors; label changes in `defaultMessages.ts` and `zh_CN.seed.json`, then `npm run i18n:sql`; `sql/01-anchor-labels.sql` (new labels, plus English and Chinese updates of `PagesBadLink` and `PagesLinkPrompt`) and `sql/99-rollback.sql`.
|
||||||
|
- Verify (2.1 to 2.3): `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`
|
||||||
|
|
||||||
|
## 3. Release
|
||||||
|
|
||||||
|
- [x] 3.1 `docs/deployment.md`: SQL rows, drop the `#anchor` known gap, add the INS page note (name the FORM block `signup`, change the HTML's `#consult` to `#signup`).
|
||||||
|
- [x] 3.2 Live check (Playwright) on a local portal: hero button to a named form block; Custom HTML `#name` to the form and `#top` inside the frame; refusals for a bad and a duplicate link name; 1280 and 360 px.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-12-03
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
## Context
|
||||||
|
|
||||||
|
Design: `docs/superpowers/specs/2026-12-03-page-builder-design.md`, change 2. A page is one `cms_page` row (slug, title, meta description, status, hide header, blocks JSON), saved whole by `CmsPageService.save` after `CmsBlockValidator`; mobile-api scopes every call to the caller's company; the portal editor saves through `/api/pages`.
|
||||||
|
|
||||||
|
## Goals / Non-Goals
|
||||||
|
|
||||||
|
**Goals:** draft and live separation for published pages; Publish changes and Discard changes; starter templates; Duplicate.
|
||||||
|
|
||||||
|
**Non-Goals:** version history; scheduled publishing; templates saved by staff; drafts for pages that were never published (they have no visitors, so they save directly as today).
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
1. **One nullable JSON column `draft`** on `cms_page`, holding `{slug, title, metaDescription, hideHeader, blocks}`. Status and company stay on the row.
|
||||||
|
2. **Save rules** (`/counter/cmsPage/save`, unchanged request):
|
||||||
|
- New page, or a stored page whose status is DRAFT: writes the row as today (including going straight to PUBLISHED).
|
||||||
|
- Stored page PUBLISHED, request status PUBLISHED: validates exactly as today and writes the content into `draft`. The live columns do not change.
|
||||||
|
- Stored page PUBLISHED, request status DRAFT (unpublish): writes the row from the request and clears `draft`; with no visitors the split no longer matters.
|
||||||
|
- Slug uniqueness is checked against the other pages' live slugs, as today.
|
||||||
|
3. **Publish** (`/counter/cmsPage/publish`, body: id and user): when a draft exists, validates it again (an event may have ended, an image may be gone) and checks its slug again, copies it into the live columns, clears it. With no draft it returns the page unchanged. A refusal comes back like a save refusal, so the editor shows it at its field.
|
||||||
|
4. **Discard** (`/counter/cmsPage/discard`, body: id): clears `draft`.
|
||||||
|
5. **Reads.** `findById` returns the live fields plus `draft` (or null). `search` rows carry `hasDraft`. `findPublished` reads only the live columns, so visitors never see a draft.
|
||||||
|
6. **mobile-api** adds `POST /api/admin/pages/{id}/publish` and `/discard`, each loading the page through the caller's scope first (another company's page is "not found"), relaying refusals like save.
|
||||||
|
7. **Portal editor.** It edits the draft when there is one, else the live content. On a published page:
|
||||||
|
- **Save** stores the draft; a banner then says visitors still see the published version, with **Publish changes** and **Discard changes** (Discard asks first);
|
||||||
|
- **Publish changes** saves the current edits, then publishes.
|
||||||
|
- Status radio Draft plus Save unpublishes, as today.
|
||||||
|
- "View page" opens the live page; Preview shows the draft.
|
||||||
|
8. **Pages list** shows an "Unpublished changes" badge next to the status for rows with `hasDraft`.
|
||||||
|
9. **Templates** are block lists in portal code (`app/lib/pageTemplates.ts`), English placeholder text, no images, the FORM block with no event and link name `signup`, buttons linking to `#signup`.
|
||||||
|
- **Event sign-up:** HERO (Dark), TRUST, FEATURES, STEPS (Muted), FAQ, FORM (Muted).
|
||||||
|
- **Service showcase:** HERO (Dark), TRUST, FEATURES, STEPS, FAQ, CTA (Accent), FORM (Muted).
|
||||||
|
- `/pages/new` first shows a picker (Blank and the two templates, each with a one-line description); choosing one opens the editor filled with its blocks. A test runs every template through the same rules the server applies, apart from the event and images that staff fill in.
|
||||||
|
10. **Duplicate** (list row action and editor button) opens `/pages/new?from=<id>`. The editor loads that page (its draft if any), clears the id, sets status Draft, title "<title> (copy)" and slug "<slug>-copy", same company. Nothing is stored until Save. No new API.
|
||||||
|
|
||||||
|
## Risks / Trade-offs
|
||||||
|
|
||||||
|
- Two staff editing one published page overwrite each other's draft (last save wins), as today for live pages. Accepted.
|
||||||
|
- A draft's slug can collide with a page published after the draft was saved → Publish checks again and refuses on `slug`.
|
||||||
|
- Rollback drops unpublished drafts → noted in `99-rollback.sql`; publish or note drafts first.
|
||||||
|
|
||||||
|
## Migration Plan
|
||||||
|
|
||||||
|
1. Run `sql/01-page-draft.sql` (DDL) before the new services-counter starts.
|
||||||
|
2. Deploy services-counter, mobile-api, the portal; run `sql/02-draft-template-labels.sql`.
|
||||||
|
Rollback: previous images, then `sql/99-rollback.sql`.
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
## Why
|
||||||
|
|
||||||
|
Marketing staff will edit pages that are already live and that printed QR codes point to. Today every Save on a published page changes it for visitors at once, so half-finished edits go live. Staff also start each event page from a blank form, though most event pages share one shape. This is change 2 of the page builder: `docs/superpowers/specs/2026-12-03-page-builder-design.md`.
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
- Published pages keep a separate draft. Saving a published page stores the draft; visitors keep seeing the published version until staff press **Publish changes**. **Discard changes** drops the draft. Unpublishing and pages never published work as today.
|
||||||
|
- The staff preview and the editor show the draft when there is one. The pages list marks pages with unpublished changes.
|
||||||
|
- **New page** first offers a starting point: Blank, **Event sign-up** or **Service showcase** (starter templates built from the section types).
|
||||||
|
- **Duplicate** copies a page into a new draft of the same company.
|
||||||
|
- New labels in English and Chinese.
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
|
||||||
|
None.
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
|
||||||
|
- `landing-pages`: draft and live content, starter templates, duplicate.
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- DDL: `cms_page.draft` (nullable JSON) in `sql/01-page-draft.sql`; mirror in `local/seed/`.
|
||||||
|
- services-counter: save writes the draft for a published page; new publish and discard endpoints; `findById` returns the draft; list rows carry `hasDraft`; `findPublished` unchanged.
|
||||||
|
- mobile-api: publish and discard admin endpoints, scoped like save.
|
||||||
|
- Portal: BFF routes, editor buttons and banner, list badge, preview, template picker, duplicate, labels.
|
||||||
|
- Rollback: `sql/99-rollback.sql` drops the column, which loses unpublished drafts; the previous release saves published pages directly again.
|
||||||
+83
@@ -0,0 +1,83 @@
|
|||||||
|
## MODIFIED Requirements
|
||||||
|
|
||||||
|
### Requirement: The Pages List
|
||||||
|
|
||||||
|
`/pages` SHALL list the pages in scope with their title, public address, status, an "Unpublished changes" mark when a published page has a draft, and last update, with a search by title or slug and an Add page action. Each row SHALL open its editor and offer Duplicate. Pages SHALL appear in the sidebar for users with `BO_PAGES`.
|
||||||
|
|
||||||
|
#### Scenario: Draft in the list
|
||||||
|
|
||||||
|
- **GIVEN** INS page `launch` is a draft
|
||||||
|
- **WHEN** INS staff open `/pages`
|
||||||
|
- **THEN** its row shows status Draft and address `/p/INS/launch`
|
||||||
|
|
||||||
|
#### Scenario: Unpublished changes in the list
|
||||||
|
|
||||||
|
- **GIVEN** INS page `hotel` is published and has a saved draft
|
||||||
|
- **WHEN** INS staff open `/pages`
|
||||||
|
- **THEN** its row shows status Published and "Unpublished changes"
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Published Pages Keep A Separate Draft
|
||||||
|
|
||||||
|
Saving a published page with status Published SHALL store the content as the page's draft, checked by the same rules as any save, and SHALL NOT change what visitors see. Saving a published page with status Draft SHALL unpublish it, write the content to the page and drop any draft. A page that is not published SHALL save directly, as before. The staff preview and the editor SHALL show the draft when there is one.
|
||||||
|
|
||||||
|
#### Scenario: Editing a live page does not change it for visitors
|
||||||
|
|
||||||
|
- **GIVEN** INS page `hotel` is published with heading "Hotel day"
|
||||||
|
- **WHEN** staff change the heading to "Hotel week" and save
|
||||||
|
- **THEN** visitors still see "Hotel day"
|
||||||
|
- **AND** the editor and the staff preview show "Hotel week"
|
||||||
|
|
||||||
|
#### Scenario: Unpublishing drops the draft
|
||||||
|
|
||||||
|
- **GIVEN** a published page with a draft
|
||||||
|
- **WHEN** staff choose status Draft and save
|
||||||
|
- **THEN** the page is a draft with the saved content and no separate draft
|
||||||
|
|
||||||
|
### Requirement: Publish And Discard Changes
|
||||||
|
|
||||||
|
Publishing a page's changes SHALL check its draft again by the same rules, including a unique slug, then make it the page's content and drop the draft. A refusal SHALL show at its field and change nothing. Discarding changes SHALL ask first, then drop the draft so the editor shows the published content again. Both SHALL be limited to pages in the caller's company scope.
|
||||||
|
|
||||||
|
#### Scenario: Publish changes
|
||||||
|
|
||||||
|
- **GIVEN** published page `hotel` has a draft with heading "Hotel week"
|
||||||
|
- **WHEN** staff press Publish changes
|
||||||
|
- **THEN** visitors see "Hotel week" and the page has no draft
|
||||||
|
|
||||||
|
#### Scenario: Publish refused for a taken slug
|
||||||
|
|
||||||
|
- **GIVEN** a draft with slug `launch` and another page published with slug `launch` since
|
||||||
|
- **WHEN** staff press Publish changes
|
||||||
|
- **THEN** the publish is refused on field `slug` and visitors still see the old content
|
||||||
|
|
||||||
|
#### Scenario: Discard changes
|
||||||
|
|
||||||
|
- **GIVEN** published page `hotel` has a draft
|
||||||
|
- **WHEN** staff press Discard changes and confirm
|
||||||
|
- **THEN** the draft is gone and the editor shows the published content
|
||||||
|
|
||||||
|
#### Scenario: Another company's page
|
||||||
|
|
||||||
|
- **WHEN** CV staff ask to publish INS page `hotel`
|
||||||
|
- **THEN** the request is answered "not found" and nothing changes
|
||||||
|
|
||||||
|
### Requirement: Starter Templates
|
||||||
|
|
||||||
|
New page SHALL first offer Blank, Event sign-up and Service showcase. A template SHALL fill the editor with its sections, placeholder text, a sign-up form with link name `signup` and no event, and buttons linking to `#signup`; nothing is stored until staff save. Every template's sections SHALL pass the server's block rules once an event is chosen.
|
||||||
|
|
||||||
|
#### Scenario: Start from the event template
|
||||||
|
|
||||||
|
- **WHEN** staff choose New page, then Event sign-up
|
||||||
|
- **THEN** the editor shows a hero, trust strip, feature cards, steps, FAQ and a sign-up form, filled with placeholder text
|
||||||
|
- **AND** saving it without choosing the form's event is refused on that event field
|
||||||
|
|
||||||
|
### Requirement: Duplicate A Page
|
||||||
|
|
||||||
|
Duplicate SHALL open the editor with a copy of the page's current content (its draft when there is one), as a new unsaved draft page of the same company titled "<title> (copy)" with slug "<slug>-copy". Nothing SHALL be stored until staff save.
|
||||||
|
|
||||||
|
#### Scenario: Duplicate last event's page
|
||||||
|
|
||||||
|
- **GIVEN** INS page `hotel` titled "Hotel day"
|
||||||
|
- **WHEN** staff press Duplicate on it and save
|
||||||
|
- **THEN** a new draft INS page `hotel-copy` titled "Hotel day (copy)" exists with the same sections
|
||||||
+5
@@ -0,0 +1,5 @@
|
|||||||
|
-- Co-Lite change add-page-drafts-and-templates: a published page's unpublished draft.
|
||||||
|
-- Run before the new services-counter starts. DDL: needs a user that may alter tables.
|
||||||
|
USE `service-counter`;
|
||||||
|
ALTER TABLE `cms_page`
|
||||||
|
ADD COLUMN `draft` json NULL COMMENT 'Unpublished changes of a published page: slug, title, metaDescription, hideHeader, blocks' AFTER `blocks`;
|
||||||
+39
@@ -0,0 +1,39 @@
|
|||||||
|
-- The labels added by add-page-drafts-and-templates, cut from the output of `npm run i18n:sql`. Run it only in an environment that already ran add-zh-cn-messages/sql/03-zh-cn-messages.sql; otherwise run that 03 file, which includes these labels.
|
||||||
|
SET NAMES utf8mb4;
|
||||||
|
USE `service-system`;
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesHasDraft', JSON_OBJECT('en_US', 'Unpublished changes', 'zh_CN', '有未发布的修改'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHasDraft') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '有未发布的修改') WHERE LOWER(code) = LOWER('PagesHasDraft') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesDraftBanner', JSON_OBJECT('en_US', 'You have unpublished changes. Visitors still see the published version until you publish them.', 'zh_CN', '您有未发布的修改。发布之前,访客看到的仍是已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDraftBanner') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '您有未发布的修改。发布之前,访客看到的仍是已发布的版本。') WHERE LOWER(code) = LOWER('PagesDraftBanner') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesPublishChanges', JSON_OBJECT('en_US', 'Publish changes', 'zh_CN', '发布修改'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPublishChanges') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '发布修改') WHERE LOWER(code) = LOWER('PagesPublishChanges') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesDiscardChanges', JSON_OBJECT('en_US', 'Discard changes', 'zh_CN', '放弃修改'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardChanges') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '放弃修改') WHERE LOWER(code) = LOWER('PagesDiscardChanges') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesDiscardTitle', JSON_OBJECT('en_US', 'Discard unpublished changes?', 'zh_CN', '放弃未发布的修改?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardTitle') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '放弃未发布的修改?') WHERE LOWER(code) = LOWER('PagesDiscardTitle') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesDiscardMessage', JSON_OBJECT('en_US', 'Your unpublished changes to "{title}" will be lost. Visitors keep seeing the published version.', 'zh_CN', '“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardMessage') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。') WHERE LOWER(code) = LOWER('PagesDiscardMessage') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesChangesPublished', JSON_OBJECT('en_US', 'Changes published.', 'zh_CN', '修改已发布。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChangesPublished') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '修改已发布。') WHERE LOWER(code) = LOWER('PagesChangesPublished') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesChangesDiscarded', JSON_OBJECT('en_US', 'Changes discarded.', 'zh_CN', '修改已放弃。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChangesDiscarded') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '修改已放弃。') WHERE LOWER(code) = LOWER('PagesChangesDiscarded') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesPreviewDraftBanner', JSON_OBJECT('en_US', 'Preview of unpublished changes. Visitors still see the published version.', 'zh_CN', '未发布修改的预览。访客看到的仍是已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPreviewDraftBanner') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '未发布修改的预览。访客看到的仍是已发布的版本。') WHERE LOWER(code) = LOWER('PagesPreviewDraftBanner') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesDuplicate', JSON_OBJECT('en_US', 'Duplicate', 'zh_CN', '复制'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDuplicate') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制') WHERE LOWER(code) = LOWER('PagesDuplicate') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesDuplicateNamed', JSON_OBJECT('en_US', 'Duplicate {title}', 'zh_CN', '复制 {title}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDuplicateNamed') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制 {title}') WHERE LOWER(code) = LOWER('PagesDuplicateNamed') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesChooseStart', JSON_OBJECT('en_US', 'How do you want to start?', 'zh_CN', '您想如何开始?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChooseStart') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '您想如何开始?') WHERE LOWER(code) = LOWER('PagesChooseStart') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesStartBlank', JSON_OBJECT('en_US', 'Blank page', 'zh_CN', '空白网页'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesStartBlank') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '空白网页') WHERE LOWER(code) = LOWER('PagesStartBlank') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesStartBlankHint', JSON_OBJECT('en_US', 'Start empty and add sections yourself.', 'zh_CN', '从空白开始,自行添加区块。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesStartBlankHint') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '从空白开始,自行添加区块。') WHERE LOWER(code) = LOWER('PagesStartBlankHint') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesTemplateEvent', JSON_OBJECT('en_US', 'Event sign-up', 'zh_CN', '活动报名'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateEvent') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '活动报名') WHERE LOWER(code) = LOWER('PagesTemplateEvent') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesTemplateEventHint', JSON_OBJECT('en_US', 'A page for one event: headline, benefits, steps, questions and the sign-up form.', 'zh_CN', '为单个活动准备的网页:标题、优势、步骤、常见问题和报名表。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateEventHint') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '为单个活动准备的网页:标题、优势、步骤、常见问题和报名表。') WHERE LOWER(code) = LOWER('PagesTemplateEventHint') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesTemplateShowcase', JSON_OBJECT('en_US', 'Service showcase', 'zh_CN', '服务展示'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateShowcase') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '服务展示') WHERE LOWER(code) = LOWER('PagesTemplateShowcase') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesTemplateShowcaseHint', JSON_OBJECT('en_US', 'Present a service with benefits, steps and a call to action, ending with the sign-up form.', 'zh_CN', '介绍一项服务:优势、步骤和行动号召,最后是报名表。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateShowcaseHint') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '介绍一项服务:优势、步骤和行动号召,最后是报名表。') WHERE LOWER(code) = LOWER('PagesTemplateShowcaseHint') AND area = 'A';
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- Co-Lite change add-page-drafts-and-templates: rollback. Dropping the column loses every unpublished draft:
|
||||||
|
-- publish or note them first. Then deploy the previous services-counter, which saves published pages directly.
|
||||||
|
USE `service-counter`;
|
||||||
|
ALTER TABLE `cms_page` DROP COLUMN `draft`;
|
||||||
|
|
||||||
|
-- Labels (02-draft-template-labels.sql).
|
||||||
|
USE `service-system`;
|
||||||
|
DELETE FROM message WHERE code IN ('PagesHasDraft', 'PagesDraftBanner', 'PagesPublishChanges', 'PagesDiscardChanges', 'PagesDiscardTitle', 'PagesDiscardMessage', 'PagesChangesPublished', 'PagesChangesDiscarded', 'PagesPreviewDraftBanner', 'PagesDuplicate', 'PagesDuplicateNamed', 'PagesChooseStart', 'PagesStartBlank', 'PagesStartBlankHint', 'PagesTemplateEvent', 'PagesTemplateEventHint', 'PagesTemplateShowcase', 'PagesTemplateShowcaseHint') AND area = 'A';
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Tasks: add-page-drafts-and-templates
|
||||||
|
|
||||||
|
Design: `design.md` and `docs/superpowers/specs/2026-12-03-page-builder-design.md` (change 2). Every task is TDD. Work is serial in the main session, with a self-review per task.
|
||||||
|
|
||||||
|
## 1. Data and services
|
||||||
|
|
||||||
|
- [x] 1.1 SQL: `sql/01-page-draft.sql`, `sql/99-rollback.sql`; mirror 01 into `local/seed/`; apply locally.
|
||||||
|
- [x] 1.2 services-counter: `draft` on the entity and DTO, `hasDraft` on list rows; save rules for published pages; publish (re-validate, slug check) and discard endpoints; `findPublished` unchanged.
|
||||||
|
- Verify: `mvn -T 1C -B -pl solvway-services-counter -am verify`
|
||||||
|
- [x] 1.3 mobile-api: `POST /api/admin/pages/{id}/publish` and `/discard`, scoped, refusals relayed like save.
|
||||||
|
- Verify: `mvn -T 1C -B -pl solvway-mobile-api -am verify`
|
||||||
|
|
||||||
|
## 2. Portal
|
||||||
|
|
||||||
|
- [x] 2.1 BFF routes for publish and discard; services; the editor loads the draft, the published-page banner with Publish changes and Discard changes (confirm); preview shows the draft; list badge.
|
||||||
|
- [x] 2.2 Templates (`pageTemplates.ts`, with a rules test) and the start picker on New page; Duplicate in the list and editor.
|
||||||
|
- [x] 2.3 Labels in `defaultMessages.ts` and `zh_CN.seed.json`, `npm run i18n:sql`, `sql/02-draft-template-labels.sql`; rollback lines.
|
||||||
|
- Verify (2.1 to 2.3): `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`
|
||||||
|
|
||||||
|
## 3. Release
|
||||||
|
|
||||||
|
- [x] 3.1 `docs/deployment.md`: SQL rows (01 before services-counter starts), the draft behaviour for staff.
|
||||||
|
- [x] 3.2 Live check (Playwright), on disposable pages: edit a published page and save (the visitor still sees the old version, preview shows the new); Publish changes; Discard changes; New page from each template (refused without an event, then saved); Duplicate; 1280 and 360 px.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-12-03
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
## Context
|
||||||
|
|
||||||
|
Design: `docs/superpowers/specs/2026-12-03-page-builder-design.md`, change 1. Blocks are one JSON list per page, validated by `CmsBlockValidator`, passed through mobile-api as maps, rendered by `LandingPage`/`Block` in `CmsBlocks.tsx`, and edited by `BlockFields.tsx`.
|
||||||
|
|
||||||
|
## Goals / Non-Goals
|
||||||
|
|
||||||
|
**Goals:** four new section types, a look per section, an optional hero image, form-editor support.
|
||||||
|
|
||||||
|
**Non-Goals:** the on-page editor and templates (changes 2 and 3); per-element colours or fonts.
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
1. **One `cards` list** for FEATURES, STEPS and TRUST: items `{icon, title, text}`. FEATURES uses all three (icon required, from a fixed list); STEPS uses title and text (numbered by position); TRUST uses title only. Fields a type does not use are refused, so stored JSON stays clean. Limits: 2 to 6 cards, title 80, text 300.
|
||||||
|
2. **Icons** are a fixed list of Lucide names: `wifi, phone, tv, monitor, lock, shield-check, cloud, wrench, headset, users, calendar, star`. The server checks the name; the portal maps names to components, so no icon markup is stored.
|
||||||
|
3. **CTA** is heading (required), text (optional) and a button (required: a CTA without one has no purpose). Same link rule as other buttons.
|
||||||
|
4. **Look** is an optional block field `look`: `DEFAULT` (or absent), `MUTED`, `DARK`, `ACCENT`. Any block type may carry it. Non-default looks render the block as a full-width band (background across the window, content in the usual width, vertical padding); `ACCENT` uses the company accent with `contrastText` for the text, falling back to the default primary colour. `DEFAULT` renders as today, so existing pages are unchanged.
|
||||||
|
5. **Hero image optional.** A hero without an image already renders as plain text in the renderer; only the validator's requirement goes. A given image must still be the company's.
|
||||||
|
6. **Editor.** Each new type gets an "Add …" button, its fields, and a card list with add/remove/move like FAQ items. The look picker is a select on every block.
|
||||||
|
|
||||||
|
## Risks / Trade-offs
|
||||||
|
|
||||||
|
- A Dark or Accent band right after another band of the same look merges visually → acceptable; staff see it in the preview.
|
||||||
|
- `HTML` blocks ignore a look: a Custom HTML block is a full design of its own, so the editor does not offer the picker for it and the renderer draws no band.
|
||||||
|
- Rollback: pages saved with new types must be edited before the previous release saves them; their new sections render as nothing under it.
|
||||||
|
|
||||||
|
## Migration Plan
|
||||||
|
|
||||||
|
Deploy services-counter and the portal; run `sql/01-section-labels.sql`. Rollback: previous images and `sql/99-rollback.sql`.
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
## Why
|
||||||
|
|
||||||
|
Marketing staff will build a landing page for every event and are not technical. Today's blocks (hero, text, image with text, FAQ, form, custom HTML) cannot produce a page like the INS design without pasting HTML, which only a developer can maintain. This is change 1 of the page builder: `docs/superpowers/specs/2026-12-03-page-builder-design.md`.
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
- New section types: FEATURES (icon cards), STEPS (numbered steps), TRUST (a strip of short items) and CTA (a call-to-action band).
|
||||||
|
- Every section gets a look: Default, Muted, Dark or Accent (the company colour), drawn as a full-width band with readable text. Default keeps today's appearance, so existing pages do not change.
|
||||||
|
- A HERO image becomes optional.
|
||||||
|
- The form editor gains the new types, their fields and the look picker; labels in English and Chinese.
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
|
||||||
|
None.
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
|
||||||
|
- `landing-pages`: new section types, section looks, optional hero image.
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- services-counter: `CmsBlock` gains `look` and `cards`; `CmsBlockValidator` rules for the new types. No DDL (blocks are JSON).
|
||||||
|
- mobile-api: none (blocks pass through).
|
||||||
|
- Portal: `cmsPages.ts`, `CmsBlocks.tsx`, `BlockFields.tsx`, `PageEditor.tsx` (add buttons), labels.
|
||||||
|
- SQL: `sql/01-section-labels.sql`, `sql/99-rollback.sql` (labels only).
|
||||||
|
- Rollback: the previous release refuses the new types and fields when such a page is saved, and renders unknown types as nothing.
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
## MODIFIED Requirements
|
||||||
|
|
||||||
|
### Requirement: A Page Is An Ordered List Of Typed Blocks
|
||||||
|
|
||||||
|
A page SHALL belong to one company and have a slug, a title, an optional meta description, a status (Draft or Published), a "hide header" flag that defaults to off, and an ordered list of zero to 30 blocks. The block types SHALL be HERO, RICH_TEXT, IMAGE_TEXT, FAQ, FORM, HTML, FEATURES, STEPS, TRUST and CTA. Blocks SHALL be returned in the order they were saved, and a valid save SHALL replace all of a page's blocks.
|
||||||
|
|
||||||
|
#### Scenario: Blocks read back in order
|
||||||
|
|
||||||
|
- **WHEN** staff save page `hotel-technology` with blocks HERO, RICH_TEXT, FORM
|
||||||
|
- **THEN** reading the page returns those three blocks in that order with their fields
|
||||||
|
|
||||||
|
#### Scenario: A save replaces the blocks
|
||||||
|
|
||||||
|
- **GIVEN** a page whose blocks are HERO and FAQ
|
||||||
|
- **WHEN** it is saved with only a RICH_TEXT block
|
||||||
|
- **THEN** the page has only that RICH_TEXT block
|
||||||
|
|
||||||
|
#### Scenario: An HTML block and the header flag read back
|
||||||
|
|
||||||
|
- **WHEN** staff save a page with "hide header" on and blocks HTML, FORM
|
||||||
|
- **THEN** reading the page returns "hide header" on and the HTML block with its HTML unchanged
|
||||||
|
|
||||||
|
#### Scenario: New section types read back
|
||||||
|
|
||||||
|
- **WHEN** staff save a page with blocks FEATURES, STEPS, TRUST and CTA
|
||||||
|
- **THEN** reading the page returns those four blocks in that order with their cards and fields
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Card Sections
|
||||||
|
|
||||||
|
A FEATURES, STEPS or TRUST block SHALL have 2 to 6 cards, with titles of at most 80 characters and texts of at most 300. FEATURES SHALL have a heading, an optional intro and cards with an icon from the fixed list, a title and a text. STEPS SHALL have a heading and numbered cards with a title and a text. TRUST SHALL have only card titles. A save breaking these rules, or using a card field its type lacks, SHALL be refused on that field.
|
||||||
|
|
||||||
|
#### Scenario: Feature cards show their icons
|
||||||
|
|
||||||
|
- **GIVEN** a published page with a FEATURES block of three cards with icons `wifi`, `tv` and `lock`
|
||||||
|
- **WHEN** a visitor opens it
|
||||||
|
- **THEN** the page shows the heading and three cards, each with its icon, title and text
|
||||||
|
|
||||||
|
#### Scenario: Unknown icon
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a FEATURES card whose icon is `rocket-launcher`
|
||||||
|
- **THEN** the save is refused on field `blocks[0].cards[0].icon`
|
||||||
|
|
||||||
|
#### Scenario: Too few cards
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a STEPS block of one card
|
||||||
|
- **THEN** the save is refused on field `blocks[0].cards`
|
||||||
|
|
||||||
|
#### Scenario: Steps are numbered
|
||||||
|
|
||||||
|
- **GIVEN** a published page with a STEPS block of three steps
|
||||||
|
- **WHEN** a visitor opens it
|
||||||
|
- **THEN** the steps show the numbers 1, 2 and 3 in order
|
||||||
|
|
||||||
|
### Requirement: Call-To-Action Band
|
||||||
|
|
||||||
|
A CTA block SHALL have a heading of at most 120 characters, an optional text of at most 300, and a button with both a label and a link following the button link rule. A save without the button SHALL be refused on the button field.
|
||||||
|
|
||||||
|
#### Scenario: A CTA needs its button
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a CTA block that has a heading and no button
|
||||||
|
- **THEN** the save is refused on field `blocks[0].buttonLabel`
|
||||||
|
|
||||||
|
### Requirement: Section Looks
|
||||||
|
|
||||||
|
Any block MAY carry a look: Default, Muted, Dark or Accent. Default, or no look, SHALL render as before. Muted, Dark and Accent SHALL render the block as a full-width band in that colour with text readable on it; Accent SHALL use the company's accent colour, or the default primary colour when the company has none. Any other look SHALL be refused on that block's look field.
|
||||||
|
|
||||||
|
#### Scenario: A dark band
|
||||||
|
|
||||||
|
- **GIVEN** a published page whose CTA block has the Dark look
|
||||||
|
- **WHEN** a visitor opens it
|
||||||
|
- **THEN** the CTA shows as a dark full-width band with light text
|
||||||
|
|
||||||
|
#### Scenario: Existing pages unchanged
|
||||||
|
|
||||||
|
- **GIVEN** a page saved before this change, whose blocks have no look
|
||||||
|
- **WHEN** a visitor opens it
|
||||||
|
- **THEN** it renders as it did before
|
||||||
|
|
||||||
|
#### Scenario: Unknown look
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a block whose look is `NEON`
|
||||||
|
- **THEN** the save is refused on field `blocks[0].look`
|
||||||
|
|
||||||
|
### Requirement: Hero Image Is Optional
|
||||||
|
|
||||||
|
A HERO block MAY have no image; it then shows its heading, text and button on its look's background. When it has an image, the image SHALL still belong to the page's company.
|
||||||
|
|
||||||
|
#### Scenario: Hero without an image
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a HERO block that has a heading and no image
|
||||||
|
- **THEN** the save succeeds
|
||||||
|
|
||||||
|
### Requirement: New Sections In The Editor
|
||||||
|
|
||||||
|
The page editor 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 under the second card's title field
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
-- The labels added by add-page-sections, 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 'PagesBlockFeatures', JSON_OBJECT('en_US', 'Feature cards', 'zh_CN', '功能卡片'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockFeatures') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '功能卡片') WHERE LOWER(code) = LOWER('PagesBlockFeatures') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesBlockSteps', JSON_OBJECT('en_US', 'Steps', 'zh_CN', '步骤'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockSteps') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '步骤') WHERE LOWER(code) = LOWER('PagesBlockSteps') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesBlockTrust', JSON_OBJECT('en_US', 'Trust strip', 'zh_CN', '信任条'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockTrust') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '信任条') WHERE LOWER(code) = LOWER('PagesBlockTrust') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesBlockCta', JSON_OBJECT('en_US', 'Call to action', 'zh_CN', '行动号召'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockCta') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '行动号召') WHERE LOWER(code) = LOWER('PagesBlockCta') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesLook', JSON_OBJECT('en_US', 'Look', 'zh_CN', '外观'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLook') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '外观') WHERE LOWER(code) = LOWER('PagesLook') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesLookDefault', JSON_OBJECT('en_US', 'Default', 'zh_CN', '默认'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLookDefault') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '默认') WHERE LOWER(code) = LOWER('PagesLookDefault') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesLookMuted', JSON_OBJECT('en_US', 'Light grey', 'zh_CN', '浅灰'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLookMuted') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '浅灰') WHERE LOWER(code) = LOWER('PagesLookMuted') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesLookDark', JSON_OBJECT('en_US', 'Dark', 'zh_CN', '深色'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLookDark') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '深色') WHERE LOWER(code) = LOWER('PagesLookDark') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesLookAccent', JSON_OBJECT('en_US', 'Company colour', 'zh_CN', '公司主色'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLookAccent') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '公司主色') WHERE LOWER(code) = LOWER('PagesLookAccent') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIntro', JSON_OBJECT('en_US', 'Intro', 'zh_CN', '简介'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIntro') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '简介') WHERE LOWER(code) = LOWER('PagesIntro') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesCardN', JSON_OBJECT('en_US', 'Card {number}', 'zh_CN', '卡片 {number}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCardN') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '卡片 {number}') WHERE LOWER(code) = LOWER('PagesCardN') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesStepN', JSON_OBJECT('en_US', 'Step {number}', 'zh_CN', '步骤 {number}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesStepN') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '步骤 {number}') WHERE LOWER(code) = LOWER('PagesStepN') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesItemN', JSON_OBJECT('en_US', 'Item {number}', 'zh_CN', '项目 {number}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesItemN') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '项目 {number}') WHERE LOWER(code) = LOWER('PagesItemN') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesCardIcon', JSON_OBJECT('en_US', 'Icon', 'zh_CN', '图标'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCardIcon') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '图标') WHERE LOWER(code) = LOWER('PagesCardIcon') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesCardTitle', JSON_OBJECT('en_US', 'Title', 'zh_CN', '标题'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCardTitle') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '标题') WHERE LOWER(code) = LOWER('PagesCardTitle') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesCardText', JSON_OBJECT('en_US', 'Text', 'zh_CN', '文字'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCardText') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '文字') WHERE LOWER(code) = LOWER('PagesCardText') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesAddCard', JSON_OBJECT('en_US', 'Add card', 'zh_CN', '添加卡片'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddCard') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加卡片') WHERE LOWER(code) = LOWER('PagesAddCard') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesAddStep', JSON_OBJECT('en_US', 'Add step', 'zh_CN', '添加步骤'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddStep') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加步骤') WHERE LOWER(code) = LOWER('PagesAddStep') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesAddItem', JSON_OBJECT('en_US', 'Add item', 'zh_CN', '添加项目'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddItem') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加项目') WHERE LOWER(code) = LOWER('PagesAddItem') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesRemoveCard', JSON_OBJECT('en_US', 'Remove', 'zh_CN', '移除'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesRemoveCard') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '移除') WHERE LOWER(code) = LOWER('PagesRemoveCard') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconWifi', JSON_OBJECT('en_US', 'WiFi', 'zh_CN', 'WiFi'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconWifi') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', 'WiFi') WHERE LOWER(code) = LOWER('PagesIconWifi') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconPhone', JSON_OBJECT('en_US', 'Phone', 'zh_CN', '电话'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconPhone') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '电话') WHERE LOWER(code) = LOWER('PagesIconPhone') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconTv', JSON_OBJECT('en_US', 'TV', 'zh_CN', '电视'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconTv') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '电视') WHERE LOWER(code) = LOWER('PagesIconTv') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconMonitor', JSON_OBJECT('en_US', 'Screen', 'zh_CN', '屏幕'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconMonitor') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '屏幕') WHERE LOWER(code) = LOWER('PagesIconMonitor') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconLock', JSON_OBJECT('en_US', 'Lock', 'zh_CN', '门锁'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconLock') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '门锁') WHERE LOWER(code) = LOWER('PagesIconLock') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconShieldCheck', JSON_OBJECT('en_US', 'Security', 'zh_CN', '安全'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconShieldCheck') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '安全') WHERE LOWER(code) = LOWER('PagesIconShieldCheck') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconCloud', JSON_OBJECT('en_US', 'Cloud', 'zh_CN', '云端'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconCloud') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '云端') WHERE LOWER(code) = LOWER('PagesIconCloud') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconWrench', JSON_OBJECT('en_US', 'Service', 'zh_CN', '维修服务'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconWrench') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '维修服务') WHERE LOWER(code) = LOWER('PagesIconWrench') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconHeadset', JSON_OBJECT('en_US', 'Support', 'zh_CN', '客服支持'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconHeadset') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '客服支持') WHERE LOWER(code) = LOWER('PagesIconHeadset') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconUsers', JSON_OBJECT('en_US', 'People', 'zh_CN', '人员'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconUsers') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '人员') WHERE LOWER(code) = LOWER('PagesIconUsers') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconCalendar', JSON_OBJECT('en_US', 'Calendar', 'zh_CN', '日历'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconCalendar') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '日历') WHERE LOWER(code) = LOWER('PagesIconCalendar') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesIconStar', JSON_OBJECT('en_US', 'Star', 'zh_CN', '星标'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesIconStar') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '星标') WHERE LOWER(code) = LOWER('PagesIconStar') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesCardCount', JSON_OBJECT('en_US', 'Use 2 to 6 cards.', 'zh_CN', '请使用 2 至 6 张卡片。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesCardCount') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请使用 2 至 6 张卡片。') WHERE LOWER(code) = LOWER('PagesCardCount') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesBadIcon', JSON_OBJECT('en_US', 'Choose an icon from the list.', 'zh_CN', '请从列表中选择图标。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadIcon') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请从列表中选择图标。') WHERE LOWER(code) = LOWER('PagesBadIcon') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesBadLook', JSON_OBJECT('en_US', 'Choose a look from the list.', 'zh_CN', '请从列表中选择外观。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadLook') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请从列表中选择外观。') WHERE LOWER(code) = LOWER('PagesBadLook') AND area = 'A';
|
||||||
|
INSERT INTO message (code, content, area) SELECT 'PagesUnusedField', JSON_OBJECT('en_US', 'This section doesn''t use this field.', 'zh_CN', '此区块不使用该字段。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUnusedField') AND area = 'A');
|
||||||
|
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '此区块不使用该字段。') WHERE LOWER(code) = LOWER('PagesUnusedField') AND area = 'A';
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
-- Co-Lite change add-page-sections: rollback of the labels. Pages using FEATURES, STEPS, TRUST, CTA, a look or an
|
||||||
|
-- image-less hero must be edited before the previous release saves them; it refuses those, and renders the new
|
||||||
|
-- section types as nothing.
|
||||||
|
USE `service-system`;
|
||||||
|
DELETE FROM message WHERE code IN ('PagesBlockFeatures', 'PagesBlockSteps', 'PagesBlockTrust', 'PagesBlockCta', 'PagesLook', 'PagesLookDefault', 'PagesLookMuted', 'PagesLookDark', 'PagesLookAccent', 'PagesIntro', 'PagesCardN', 'PagesStepN', 'PagesItemN', 'PagesCardIcon', 'PagesCardTitle', 'PagesCardText', 'PagesAddCard', 'PagesAddStep', 'PagesAddItem', 'PagesRemoveCard', 'PagesIconWifi', 'PagesIconPhone', 'PagesIconTv', 'PagesIconMonitor', 'PagesIconLock', 'PagesIconShieldCheck', 'PagesIconCloud', 'PagesIconWrench', 'PagesIconHeadset', 'PagesIconUsers', 'PagesIconCalendar', 'PagesIconStar', 'PagesCardCount', 'PagesBadIcon', 'PagesBadLook', 'PagesUnusedField') AND area = 'A';
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# Tasks: add-page-sections
|
||||||
|
|
||||||
|
Design: `design.md` and `docs/superpowers/specs/2026-12-03-page-builder-design.md` (change 1). Every task is TDD. Work is serial in the main session, with a self-review per task.
|
||||||
|
|
||||||
|
## 1. services-counter
|
||||||
|
|
||||||
|
- [x] 1.1 `CmsBlock.look` and `cards` (`CmsCard` record: icon, title, text); `CmsBlockValidator`: FEATURES, STEPS, TRUST, CTA rules, the icon list, the look values, HERO image optional.
|
||||||
|
- Verify: `mvn -T 1C -B -pl solvway-services-counter -am verify`
|
||||||
|
|
||||||
|
## 2. Portal
|
||||||
|
|
||||||
|
- [x] 2.1 Model and renderer: types, `emptyBlock`, `BLOCK_LABELS`, icon map; `CmsBlocks` renders the four new types and the looks (full-width bands, readable text, Accent from the company colour); Default unchanged.
|
||||||
|
- [x] 2.2 Editor: add buttons, fields and card lists (add, remove, move) for the new types, the look select on every block, inline card errors; labels in `defaultMessages.ts` and `zh_CN.seed.json`, `npm run i18n:sql`, `sql/01-section-labels.sql` and `sql/99-rollback.sql`.
|
||||||
|
- Verify (2.1 to 2.2): `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`
|
||||||
|
|
||||||
|
## 3. Release
|
||||||
|
|
||||||
|
- [x] 3.1 `docs/deployment.md`: SQL row; landing-pages notes (new sections, looks, rebuilding the INS page as sections).
|
||||||
|
- [x] 3.2 Live check (Playwright) on a local portal: build a disposable page with every new type and each look; refusals (unknown look is API-only, so check a too-few-cards and a missing CTA button); preview and public page at 1280 and 360 px.
|
||||||
@@ -8,7 +8,7 @@ Public landing pages per company, built by staff from blocks in the back office
|
|||||||
|
|
||||||
### Requirement: A Page Is An Ordered List Of Typed Blocks
|
### Requirement: A Page Is An Ordered List Of Typed Blocks
|
||||||
|
|
||||||
A page SHALL belong to one company and have a slug, a title, an optional meta description, a status (Draft or Published) and an ordered list of zero to 30 blocks. The block types SHALL be HERO, RICH_TEXT, IMAGE_TEXT, FAQ and FORM. Blocks SHALL be returned in the order they were saved, and a valid save SHALL replace all of a page's blocks.
|
A page SHALL belong to one company and have a slug, a title, an optional meta description, a status (Draft or Published), a "hide header" flag that defaults to off, and an ordered list of zero to 30 blocks. The block types SHALL be HERO, RICH_TEXT, IMAGE_TEXT, FAQ, FORM, HTML, FEATURES, STEPS, TRUST and CTA. Blocks SHALL be returned in the order they were saved, and a valid save SHALL replace all of a page's blocks.
|
||||||
|
|
||||||
#### Scenario: Blocks read back in order
|
#### Scenario: Blocks read back in order
|
||||||
|
|
||||||
@@ -21,6 +21,16 @@ A page SHALL belong to one company and have a slug, a title, an optional meta de
|
|||||||
- **WHEN** it is saved with only a RICH_TEXT block
|
- **WHEN** it is saved with only a RICH_TEXT block
|
||||||
- **THEN** the page has only that RICH_TEXT block
|
- **THEN** the page has only that RICH_TEXT block
|
||||||
|
|
||||||
|
#### Scenario: An HTML block and the header flag read back
|
||||||
|
|
||||||
|
- **WHEN** staff save a page with "hide header" on and blocks HTML, FORM
|
||||||
|
- **THEN** reading the page returns "hide header" on and the HTML block with its HTML unchanged
|
||||||
|
|
||||||
|
#### Scenario: New section types read back
|
||||||
|
|
||||||
|
- **WHEN** staff save a page with blocks FEATURES, STEPS, TRUST and CTA
|
||||||
|
- **THEN** reading the page returns those four blocks in that order with their cards and fields
|
||||||
|
|
||||||
### Requirement: Page Fields Are Validated Server-Side
|
### Requirement: Page Fields Are Validated Server-Side
|
||||||
|
|
||||||
A page save SHALL be refused with the offending field path, writing nothing, when the slug does not match `^[a-z0-9]+(-[a-z0-9]+)*$`, is longer than 80 characters or is used by another page of the same company, ignoring case; or when the title is blank or longer than 120 characters; or when the meta description is longer than 160 characters.
|
A page save SHALL be refused with the offending field path, writing nothing, when the slug does not match `^[a-z0-9]+(-[a-z0-9]+)*$`, is longer than 80 characters or is used by another page of the same company, ignoring case; or when the title is blank or longer than 120 characters; or when the meta description is longer than 160 characters.
|
||||||
@@ -39,13 +49,18 @@ A page save SHALL be refused with the offending field path, writing nothing, whe
|
|||||||
|
|
||||||
### Requirement: Block Fields Are Validated Server-Side
|
### Requirement: Block Fields Are Validated Server-Side
|
||||||
|
|
||||||
A page save SHALL be refused with the offending field path, writing nothing, when a block has an unknown type, a required field is blank, or a text exceeds its limit: heading 120, text and FAQ question 300, button label 40, FAQ answer 2000, HTML 100000 characters. A FAQ SHALL have 1 to 30 items. `imagePosition` SHALL be LEFT or RIGHT.
|
A page save SHALL be refused with the offending field path, writing nothing, when a block has an unknown type, a required field is blank, or a text exceeds its limit: heading 120, text and FAQ question 300, button label 40, FAQ answer 2000, rich-text HTML 100000 characters, and an HTML block's HTML 200000 characters. An HTML block's HTML SHALL NOT be blank. A FAQ SHALL have 1 to 30 items. `imagePosition` SHALL be LEFT or RIGHT.
|
||||||
|
|
||||||
#### Scenario: Too many blocks
|
#### Scenario: Too many blocks
|
||||||
|
|
||||||
- **WHEN** a page is saved with 31 blocks
|
- **WHEN** a page is saved with 31 blocks
|
||||||
- **THEN** the save is refused and nothing is written
|
- **THEN** the save is refused and nothing is written
|
||||||
|
|
||||||
|
#### Scenario: HTML block too long
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with an HTML block of 200001 characters
|
||||||
|
- **THEN** the save is refused on field `blocks[0].html` and nothing is written
|
||||||
|
|
||||||
### Requirement: Block References Stay Inside The Company
|
### Requirement: Block References Stay Inside The Company
|
||||||
|
|
||||||
A block's image SHALL be an image of the page's company, and a FORM block's event SHALL be an event of the page's company. Otherwise the save SHALL be refused on that field.
|
A block's image SHALL be an image of the page's company, and a FORM block's event SHALL be an event of the page's company. Otherwise the save SHALL be refused on that field.
|
||||||
@@ -58,7 +73,7 @@ A block's image SHALL be an image of the page's company, and a FORM block's even
|
|||||||
|
|
||||||
### Requirement: Page Content Cannot Run Scripts
|
### Requirement: Page Content Cannot Run Scripts
|
||||||
|
|
||||||
A button SHALL have both a label and a link or neither. The link SHALL be a same-site path starting with a single `/`, an `https://` URL, a `mailto:` link or a `tel:` link. A save SHALL be refused when any HTML holds a `script` element, an `on*` attribute or a `javascript:` URL. The public page SHALL also sanitise all HTML against an allow-list before rendering it.
|
A button SHALL have both a label and a link or neither. The link SHALL start with a single `/`, `https://`, `mailto:`, `tel:`, or `#` plus a valid block link name. A save SHALL be refused when RICH_TEXT or IMAGE_TEXT HTML holds a `script` element, an `on*` attribute or a `javascript:` URL. The public page SHALL also sanitise that HTML against an allow-list. HTML blocks are exempt: they only run sealed.
|
||||||
|
|
||||||
#### Scenario: Script link on a button
|
#### Scenario: Script link on a button
|
||||||
|
|
||||||
@@ -70,6 +85,21 @@ A button SHALL have both a label and a link or neither. The link SHALL be a same
|
|||||||
- **WHEN** a page is saved with rich text holding `<img src=x onerror=alert(1)>`
|
- **WHEN** a page is saved with rich text holding `<img src=x onerror=alert(1)>`
|
||||||
- **THEN** the save is refused on that block's HTML field
|
- **THEN** the save is refused on that block's HTML field
|
||||||
|
|
||||||
|
#### Scenario: Script in an HTML block
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with an HTML block holding `<script>document.title = "x"</script>`
|
||||||
|
- **THEN** the save succeeds
|
||||||
|
|
||||||
|
#### Scenario: Same-page button link
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a HERO button link `#signup`
|
||||||
|
- **THEN** the save succeeds
|
||||||
|
|
||||||
|
#### Scenario: Malformed same-page link
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a HERO button link `#Sign Up`
|
||||||
|
- **THEN** the save is refused on field `blocks[0].buttonUrl`
|
||||||
|
|
||||||
### Requirement: Page Images
|
### Requirement: Page Images
|
||||||
|
|
||||||
Staff with `BO_PAGES` SHALL upload images for their company in PNG, JPEG or WebP, each at most 2 MB, checked by the file's content and not by its name. Anyone SHALL be able to read an image by its id, so that public pages can show it.
|
Staff with `BO_PAGES` SHALL upload images for their company in PNG, JPEG or WebP, each at most 2 MB, checked by the file's content and not by its name. Anyone SHALL be able to read an image by its id, so that public pages can show it.
|
||||||
@@ -163,7 +193,7 @@ Pages and page images SHALL follow the company scoping rules: staff see, edit an
|
|||||||
|
|
||||||
### Requirement: The Pages List
|
### Requirement: The Pages List
|
||||||
|
|
||||||
`/pages` SHALL list the pages in scope with their title, public address, status and last update, with a search by title or slug and an Add page action. Each row SHALL open its editor. Pages SHALL appear in the sidebar for users with `BO_PAGES`.
|
`/pages` SHALL list the pages in scope with their title, public address, status, an "Unpublished changes" mark when a published page has a draft, and last update, with a search by title or slug and an Add page action. Each row SHALL open its editor and offer Duplicate. Pages SHALL appear in the sidebar for users with `BO_PAGES`.
|
||||||
|
|
||||||
#### Scenario: Draft in the list
|
#### Scenario: Draft in the list
|
||||||
|
|
||||||
@@ -171,6 +201,12 @@ Pages and page images SHALL follow the company scoping rules: staff see, edit an
|
|||||||
- **WHEN** INS staff open `/pages`
|
- **WHEN** INS staff open `/pages`
|
||||||
- **THEN** its row shows status Draft and address `/p/INS/launch`
|
- **THEN** its row shows status Draft and address `/p/INS/launch`
|
||||||
|
|
||||||
|
#### Scenario: Unpublished changes in the list
|
||||||
|
|
||||||
|
- **GIVEN** INS page `hotel` is published and has a saved draft
|
||||||
|
- **WHEN** INS staff open `/pages`
|
||||||
|
- **THEN** its row shows status Published and "Unpublished changes"
|
||||||
|
|
||||||
### Requirement: The Page Editor
|
### Requirement: The Page Editor
|
||||||
|
|
||||||
The editor SHALL offer the title, a slug filled from the title until edited, a meta description with a 160-character counter, the status and the block list. Blocks SHALL be added, moved up or down and removed. A chosen image SHALL be uploaded only when the page is saved. A FORM block SHALL pick from the company's enabled events that have not ended.
|
The editor SHALL offer the title, a slug filled from the title until edited, a meta description with a 160-character counter, the status and the block list. Blocks SHALL be added, moved up or down and removed. A chosen image SHALL be uploaded only when the page is saved. A FORM block SHALL pick from the company's enabled events that have not ended.
|
||||||
@@ -189,3 +225,261 @@ Server field errors SHALL show next to their fields, keeping all entered values.
|
|||||||
|
|
||||||
- **WHEN** staff save a HERO button link `javascript:alert(1)`
|
- **WHEN** staff save a HERO button link `javascript:alert(1)`
|
||||||
- **THEN** the error shows next to that button link and every entered value stays
|
- **THEN** the error shows next to that button link and every entered value stays
|
||||||
|
|
||||||
|
### Requirement: Custom HTML Runs Sealed
|
||||||
|
|
||||||
|
The public page and the staff preview SHALL show each HTML block in a sandboxed frame loaded from its own address. Each frame response SHALL carry a Content-Security-Policy whose `sandbox` directive allows scripts and pop-ups only, so the HTML runs with an opaque origin even when the address is opened directly, and whose `frame-ancestors` directive allows only the Co-Lite site. The frame element SHALL NOT grant same-origin, form submission, top-level navigation or modal dialogs.
|
||||||
|
|
||||||
|
#### Scenario: Public frame is sealed
|
||||||
|
|
||||||
|
- **GIVEN** INS page `hotel-technology` is published with an HTML block at index 0
|
||||||
|
- **WHEN** a visitor's browser loads `/p/INS/hotel-technology/frame/0`
|
||||||
|
- **THEN** the response is the block's HTML with a `sandbox` policy that allows scripts and pop-ups and not same-origin
|
||||||
|
- **AND** its `frame-ancestors` allows only the Co-Lite site
|
||||||
|
|
||||||
|
#### Scenario: Pasted HTML cannot reach the visitor's session
|
||||||
|
|
||||||
|
- **GIVEN** a published HTML block whose script reads `document.cookie` and calls `/api/auth/session`
|
||||||
|
- **WHEN** the page is shown
|
||||||
|
- **THEN** the script sees no Co-Lite cookies and its call carries no Co-Lite session
|
||||||
|
|
||||||
|
### Requirement: Custom HTML Frame Addresses
|
||||||
|
|
||||||
|
The public frame address SHALL be `/p/<company>/<slug>/frame/<block index>` and SHALL answer only for an HTML block of a published page; every other request SHALL get the same not-found response. The preview frame address SHALL be `/pages/<id>/preview/frame/<block index>` and SHALL require a signed-in user with `BO_PAGES` who may see that page.
|
||||||
|
|
||||||
|
#### Scenario: No frame for a draft, a missing block or a non-HTML block
|
||||||
|
|
||||||
|
- **WHEN** a visitor loads the frame address of a draft page, of block 7 of a page with 3 blocks, or of a FORM block
|
||||||
|
- **THEN** each answers with the same not-found response
|
||||||
|
|
||||||
|
#### Scenario: Staff preview of a draft frame
|
||||||
|
|
||||||
|
- **GIVEN** a draft page with an HTML block
|
||||||
|
- **WHEN** a signed-in user with `BO_PAGES` of that page's company opens the preview
|
||||||
|
- **THEN** the frame shows the draft HTML, sealed as on the public page
|
||||||
|
- **AND** the same address without a session sends the browser to sign in
|
||||||
|
|
||||||
|
### Requirement: Custom HTML Frame Height
|
||||||
|
|
||||||
|
The frame SHALL grow to fit its content, between 100 and 20000 pixels, using height reports sent by that frame only. Before the first report it SHALL be 600 pixels tall.
|
||||||
|
|
||||||
|
#### Scenario: A tall paste grows the frame
|
||||||
|
|
||||||
|
- **GIVEN** a published HTML block whose content is 3000 pixels tall
|
||||||
|
- **WHEN** a visitor opens the page
|
||||||
|
- **THEN** the frame is 3000 pixels tall and shows no inner scroll bar
|
||||||
|
|
||||||
|
#### Scenario: Another frame cannot resize it
|
||||||
|
|
||||||
|
- **WHEN** a different window posts a height report to the page
|
||||||
|
- **THEN** the frame's height does not change
|
||||||
|
|
||||||
|
### Requirement: The Custom HTML Block In The Editor
|
||||||
|
|
||||||
|
The editor SHALL offer "Add Custom HTML", which adds an HTML block with a monospace text box, a 200000-character counter and a note that forms inside the pasted HTML do not send and the sign-up form block collects leads. The editor SHALL also offer a "hide page header" switch for the page.
|
||||||
|
|
||||||
|
#### 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: Hiding the header
|
||||||
|
|
||||||
|
- **WHEN** staff turn on "hide page header" and save
|
||||||
|
- **THEN** reading the page returns "hide header" on
|
||||||
|
|
||||||
|
### Requirement: Hide Page Header
|
||||||
|
|
||||||
|
When a page's "hide header" flag is on, its public page and its preview SHALL NOT show the company header or the page title, and SHALL still use the page title in the browser title and the page metadata.
|
||||||
|
|
||||||
|
#### Scenario: Header hidden
|
||||||
|
|
||||||
|
- **GIVEN** INS page `hotel-technology` has "hide header" on
|
||||||
|
- **WHEN** a visitor opens it
|
||||||
|
- **THEN** no company logo bar or page title heading shows above the first block
|
||||||
|
- **AND** the browser title is still the page title
|
||||||
|
|
||||||
|
### Requirement: Block Link Names
|
||||||
|
|
||||||
|
Any block MAY carry a link name. A link name SHALL be 1 to 40 characters of lowercase letters, digits and `-`, starting with a letter or digit, SHALL NOT start with `reg-` (the sign-up form's own field ids), and SHALL be unique within the page. A save breaking either rule SHALL be refused on that block's link-name field, writing nothing. The public page and the staff preview SHALL give the block that name as its element id, so a `#name` link scrolls to it.
|
||||||
|
|
||||||
|
#### Scenario: Hero button jumps to the form
|
||||||
|
|
||||||
|
- **GIVEN** a published page whose FORM block has the link name `signup` and whose HERO button links to `#signup`
|
||||||
|
- **WHEN** a visitor clicks the button
|
||||||
|
- **THEN** the page scrolls to the form
|
||||||
|
|
||||||
|
#### Scenario: Duplicate link name
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with two blocks named `signup`
|
||||||
|
- **THEN** the save is refused on field `blocks[1].anchor` and nothing is written
|
||||||
|
|
||||||
|
#### Scenario: Reserved link name
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a block named `reg-email`
|
||||||
|
- **THEN** the save is refused on field `blocks[0].anchor` and nothing is written
|
||||||
|
|
||||||
|
#### Scenario: Bad link name
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a block named `Sign Up`
|
||||||
|
- **THEN** the save is refused on field `blocks[0].anchor` and nothing is written
|
||||||
|
|
||||||
|
### Requirement: Same-Page Links From A Custom HTML Frame
|
||||||
|
|
||||||
|
A click on a `#name` link inside a Custom HTML block SHALL scroll the page, without navigating the frame. The target SHALL be the element with that id inside the same frame when there is one, otherwise the block on the page with that link name, otherwise nothing happens. The page SHALL act only on such requests from its own frames and only for names of the link-name pattern. The frame SHALL gain no new sandbox permissions.
|
||||||
|
|
||||||
|
#### Scenario: Link to the form below the frame
|
||||||
|
|
||||||
|
- **GIVEN** a published page with an HTML block holding `<a href="#signup">` and a FORM block named `signup`
|
||||||
|
- **WHEN** a visitor clicks that link
|
||||||
|
- **THEN** the page scrolls to the form
|
||||||
|
|
||||||
|
#### Scenario: Link inside the frame
|
||||||
|
|
||||||
|
- **GIVEN** a published HTML block whose content holds `<a href="#top">` near its bottom and an element with id `top` at its start
|
||||||
|
- **WHEN** a visitor scrolls down and clicks that link
|
||||||
|
- **THEN** the page scrolls back to the start of the frame
|
||||||
|
|
||||||
|
#### Scenario: Another window asks to scroll
|
||||||
|
|
||||||
|
- **WHEN** a different window posts a same-page link request to the page
|
||||||
|
- **THEN** the page does not scroll
|
||||||
|
|
||||||
|
### Requirement: Card Sections
|
||||||
|
|
||||||
|
A FEATURES, STEPS or TRUST block SHALL have 2 to 6 cards, with titles of at most 80 characters and texts of at most 300. FEATURES SHALL have a heading, an optional intro and cards with an icon from the fixed list, a title and a text. STEPS SHALL have a heading and numbered cards with a title and a text. TRUST SHALL have only card titles. A save breaking these rules, or using a card field its type lacks, SHALL be refused on that field.
|
||||||
|
|
||||||
|
#### Scenario: Feature cards show their icons
|
||||||
|
|
||||||
|
- **GIVEN** a published page with a FEATURES block of three cards with icons `wifi`, `tv` and `lock`
|
||||||
|
- **WHEN** a visitor opens it
|
||||||
|
- **THEN** the page shows the heading and three cards, each with its icon, title and text
|
||||||
|
|
||||||
|
#### Scenario: Unknown icon
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a FEATURES card whose icon is `rocket-launcher`
|
||||||
|
- **THEN** the save is refused on field `blocks[0].cards[0].icon`
|
||||||
|
|
||||||
|
#### Scenario: Too few cards
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a STEPS block of one card
|
||||||
|
- **THEN** the save is refused on field `blocks[0].cards`
|
||||||
|
|
||||||
|
#### Scenario: Steps are numbered
|
||||||
|
|
||||||
|
- **GIVEN** a published page with a STEPS block of three steps
|
||||||
|
- **WHEN** a visitor opens it
|
||||||
|
- **THEN** the steps show the numbers 1, 2 and 3 in order
|
||||||
|
|
||||||
|
### Requirement: Call-To-Action Band
|
||||||
|
|
||||||
|
A CTA block SHALL have a heading of at most 120 characters, an optional text of at most 300, and a button with both a label and a link following the button link rule. A save without the button SHALL be refused on the button field.
|
||||||
|
|
||||||
|
#### Scenario: A CTA needs its button
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a CTA block that has a heading and no button
|
||||||
|
- **THEN** the save is refused on field `blocks[0].buttonLabel`
|
||||||
|
|
||||||
|
### Requirement: Section Looks
|
||||||
|
|
||||||
|
Any block MAY carry a look: Default, Muted, Dark or Accent. Default, or no look, SHALL render as before. Muted, Dark and Accent SHALL render the block as a full-width band in that colour with text readable on it; Accent SHALL use the company's accent colour, or the default primary colour when the company has none. Any other look SHALL be refused on that block's look field.
|
||||||
|
|
||||||
|
#### Scenario: A dark band
|
||||||
|
|
||||||
|
- **GIVEN** a published page whose CTA block has the Dark look
|
||||||
|
- **WHEN** a visitor opens it
|
||||||
|
- **THEN** the CTA shows as a dark full-width band with light text
|
||||||
|
|
||||||
|
#### Scenario: Existing pages unchanged
|
||||||
|
|
||||||
|
- **GIVEN** a page saved before this change, whose blocks have no look
|
||||||
|
- **WHEN** a visitor opens it
|
||||||
|
- **THEN** it renders as it did before
|
||||||
|
|
||||||
|
#### Scenario: Unknown look
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a block whose look is `NEON`
|
||||||
|
- **THEN** the save is refused on field `blocks[0].look`
|
||||||
|
|
||||||
|
### Requirement: Hero Image Is Optional
|
||||||
|
|
||||||
|
A HERO block MAY have no image; it then shows its heading, text and button on its look's background. When it has an image, the image SHALL still belong to the page's company.
|
||||||
|
|
||||||
|
#### Scenario: Hero without an image
|
||||||
|
|
||||||
|
- **WHEN** a page is saved with a HERO block that has a heading and no image
|
||||||
|
- **THEN** the save succeeds
|
||||||
|
|
||||||
|
### Requirement: New Sections In The Editor
|
||||||
|
|
||||||
|
The page editor 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 under the second card's title field
|
||||||
|
|
||||||
|
### Requirement: Published Pages Keep A Separate Draft
|
||||||
|
|
||||||
|
Saving a published page with status Published SHALL store the content as the page's draft, checked by the same rules as any save, and SHALL NOT change what visitors see. Saving a published page with status Draft SHALL unpublish it, write the content to the page and drop any draft. A page that is not published SHALL save directly, as before. The staff preview and the editor SHALL show the draft when there is one.
|
||||||
|
|
||||||
|
#### Scenario: Editing a live page does not change it for visitors
|
||||||
|
|
||||||
|
- **GIVEN** INS page `hotel` is published with heading "Hotel day"
|
||||||
|
- **WHEN** staff change the heading to "Hotel week" and save
|
||||||
|
- **THEN** visitors still see "Hotel day"
|
||||||
|
- **AND** the editor and the staff preview show "Hotel week"
|
||||||
|
|
||||||
|
#### Scenario: Unpublishing drops the draft
|
||||||
|
|
||||||
|
- **GIVEN** a published page with a draft
|
||||||
|
- **WHEN** staff choose status Draft and save
|
||||||
|
- **THEN** the page is a draft with the saved content and no separate draft
|
||||||
|
|
||||||
|
### Requirement: Publish And Discard Changes
|
||||||
|
|
||||||
|
Publishing a page's changes SHALL check its draft again by the same rules, including a unique slug, then make it the page's content and drop the draft. A refusal SHALL show at its field and change nothing. Discarding changes SHALL ask first, then drop the draft so the editor shows the published content again. Both SHALL be limited to pages in the caller's company scope.
|
||||||
|
|
||||||
|
#### Scenario: Publish changes
|
||||||
|
|
||||||
|
- **GIVEN** published page `hotel` has a draft with heading "Hotel week"
|
||||||
|
- **WHEN** staff press Publish changes
|
||||||
|
- **THEN** visitors see "Hotel week" and the page has no draft
|
||||||
|
|
||||||
|
#### Scenario: Publish refused for a taken slug
|
||||||
|
|
||||||
|
- **GIVEN** a draft with slug `launch` and another page published with slug `launch` since
|
||||||
|
- **WHEN** staff press Publish changes
|
||||||
|
- **THEN** the publish is refused on field `slug` and visitors still see the old content
|
||||||
|
|
||||||
|
#### Scenario: Discard changes
|
||||||
|
|
||||||
|
- **GIVEN** published page `hotel` has a draft
|
||||||
|
- **WHEN** staff press Discard changes and confirm
|
||||||
|
- **THEN** the draft is gone and the editor shows the published content
|
||||||
|
|
||||||
|
#### Scenario: Another company's page
|
||||||
|
|
||||||
|
- **WHEN** CV staff ask to publish INS page `hotel`
|
||||||
|
- **THEN** the request is answered "not found" and nothing changes
|
||||||
|
|
||||||
|
### Requirement: Starter Templates
|
||||||
|
|
||||||
|
New page SHALL first offer Blank, Event sign-up and Service showcase. A template SHALL fill the editor with its sections, placeholder text, a sign-up form with link name `signup` and no event, and buttons linking to `#signup`; nothing is stored until staff save. Every template's sections SHALL pass the server's block rules once an event is chosen.
|
||||||
|
|
||||||
|
#### Scenario: Start from the event template
|
||||||
|
|
||||||
|
- **WHEN** staff choose New page, then Event sign-up
|
||||||
|
- **THEN** the editor shows a hero, trust strip, feature cards, steps, FAQ and a sign-up form, filled with placeholder text
|
||||||
|
- **AND** saving it without choosing the form's event is refused on that event field
|
||||||
|
|
||||||
|
### Requirement: Duplicate A Page
|
||||||
|
|
||||||
|
Duplicate SHALL open the editor with a copy of the page's current content (its draft when there is one), as a new unsaved draft page of the same company titled "<title> (copy)" with slug "<slug>-copy". Nothing SHALL be stored until staff save.
|
||||||
|
|
||||||
|
#### Scenario: Duplicate last event's page
|
||||||
|
|
||||||
|
- **GIVEN** INS page `hotel` titled "Hotel day"
|
||||||
|
- **WHEN** staff press Duplicate on it and save
|
||||||
|
- **THEN** a new draft INS page `hotel-copy` titled "Hotel day (copy)" exists with the same sections
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
# lead-notifications Specification
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
In-app notifications for staff: a bell with unread state, and alerts when a lead is assigned, a landing-page sign-up arrives, a customer sends a WhatsApp message, or follow-ups fall due.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
### Requirement: Staff Notification Bell
|
||||||
|
|
||||||
|
The portal SHALL show every signed-in staff user a bell in the header with the count of their unread notifications, refreshed at least every 30 seconds while the page is visible. Opening the bell SHALL list their newest notifications, newest first, and mark the listed ones read. Choosing a notification SHALL open the page it links to.
|
||||||
|
|
||||||
|
#### Scenario: Unread count and opening the bell
|
||||||
|
|
||||||
|
- **GIVEN** a salesperson has 3 unread notifications
|
||||||
|
- **WHEN** they open any portal page
|
||||||
|
- **THEN** the bell shows 3
|
||||||
|
- **WHEN** they open the bell
|
||||||
|
- **THEN** the 3 notifications are listed newest first
|
||||||
|
- **AND** after a reload the bell shows no unread count
|
||||||
|
|
||||||
|
#### Scenario: A notification opens its lead
|
||||||
|
|
||||||
|
- **GIVEN** a "lead assigned" notification for lead L
|
||||||
|
- **WHEN** the salesperson chooses it
|
||||||
|
- **THEN** the portal opens lead L
|
||||||
|
|
||||||
|
### Requirement: Notifications Page
|
||||||
|
|
||||||
|
The portal SHALL provide a notifications page listing the signed-in user's notifications, newest first and paged, showing which are unread, with an action to mark all of them read.
|
||||||
|
|
||||||
|
#### Scenario: Mark all read
|
||||||
|
|
||||||
|
- **GIVEN** a user with 25 notifications, 5 of them unread
|
||||||
|
- **WHEN** they open the notifications page and choose "Mark all read"
|
||||||
|
- **THEN** none of their notifications is unread
|
||||||
|
- **AND** the bell shows no unread count
|
||||||
|
|
||||||
|
### Requirement: Notifications Are Private To Their Recipient
|
||||||
|
|
||||||
|
The system SHALL show and change a user's notifications only for that user, identified from their session. A request naming another user's notification SHALL be refused as not found. A notification SHALL only name a lead of the recipient's own company.
|
||||||
|
|
||||||
|
#### Scenario: Another user's notification
|
||||||
|
|
||||||
|
- **GIVEN** notification N belongs to user A
|
||||||
|
- **WHEN** user B asks to mark N read
|
||||||
|
- **THEN** the request is refused as not found
|
||||||
|
- **AND** N stays unread for user A
|
||||||
|
|
||||||
|
#### Scenario: Two companies
|
||||||
|
|
||||||
|
- **GIVEN** an INS salesperson and a CV salesperson
|
||||||
|
- **WHEN** a CV lead is assigned to the CV salesperson
|
||||||
|
- **THEN** only the CV salesperson is notified
|
||||||
|
|
||||||
|
### Requirement: Notifications Follow The Reader's Language
|
||||||
|
|
||||||
|
A notification SHALL be stored as message codes with parameters and shown in the reader's current portal language. Its parameters SHALL NOT include phone numbers or email addresses.
|
||||||
|
|
||||||
|
#### Scenario: Chinese reader
|
||||||
|
|
||||||
|
- **GIVEN** a "lead assigned" notification
|
||||||
|
- **WHEN** a user with the portal in Chinese opens the bell
|
||||||
|
- **THEN** the notification text is in Chinese, with the lead's name
|
||||||
|
|
||||||
|
### Requirement: Lead Assigned Notification
|
||||||
|
|
||||||
|
When an event lead's salesperson is set or changed to a user, the system SHALL notify that user, linking to the lead. It SHALL NOT notify a user who assigned the lead to themselves, and SHALL NOT notify anyone when the salesperson is cleared.
|
||||||
|
|
||||||
|
#### Scenario: Manager assigns a lead
|
||||||
|
|
||||||
|
- **WHEN** a manager assigns event lead L to salesperson S
|
||||||
|
- **THEN** S gets one "lead assigned" notification naming L and its event
|
||||||
|
|
||||||
|
#### Scenario: Self-assignment
|
||||||
|
|
||||||
|
- **WHEN** salesperson S assigns lead L to themselves
|
||||||
|
- **THEN** no notification is created
|
||||||
|
|
||||||
|
### Requirement: Landing Page Sign-up Notification
|
||||||
|
|
||||||
|
When a landing-page sign-up creates or updates an event lead, the system SHALL notify the lead's salesperson if it has one, otherwise every member of the event's sales team, once each. With no salesperson and no sales team, nobody SHALL be notified.
|
||||||
|
|
||||||
|
#### Scenario: Unassigned sign-up
|
||||||
|
|
||||||
|
- **GIVEN** event E has sales team members S1 and S2
|
||||||
|
- **WHEN** a visitor signs up on a page whose form belongs to E, and no salesperson is assigned
|
||||||
|
- **THEN** S1 and S2 each get one "new sign-up" notification
|
||||||
|
|
||||||
|
#### Scenario: Assigned at capture
|
||||||
|
|
||||||
|
- **WHEN** a web sign-up is captured already assigned to S
|
||||||
|
- **THEN** S gets exactly one notification, the "new sign-up" one
|
||||||
|
|
||||||
|
### Requirement: WhatsApp Message Notification
|
||||||
|
|
||||||
|
When an inbound WhatsApp message is recorded on a chat with an owner, the system SHALL notify the owner, linking to the chat. While the owner has an unread notification for that chat, a further message SHALL update it rather than add another. A chat without an owner SHALL notify nobody.
|
||||||
|
|
||||||
|
#### Scenario: Busy chat
|
||||||
|
|
||||||
|
- **GIVEN** salesperson S owns a chat
|
||||||
|
- **WHEN** the customer sends 4 messages before S opens the bell
|
||||||
|
- **THEN** S has one unread notification for that chat, timed at the last message
|
||||||
|
|
||||||
|
#### Scenario: Unowned chat
|
||||||
|
|
||||||
|
- **WHEN** a message arrives on a chat without an owner
|
||||||
|
- **THEN** no notification is created
|
||||||
|
|
||||||
|
### Requirement: Follow-ups Due Notification
|
||||||
|
|
||||||
|
Every day at 08:00 Malaysia time, the system SHALL send each salesperson with open event leads whose next follow-up date is today or earlier one summary notification giving the count due today and the count overdue, linking to their event leads.
|
||||||
|
|
||||||
|
#### Scenario: Morning summary
|
||||||
|
|
||||||
|
- **GIVEN** salesperson S has 2 open leads due today and 1 open lead due yesterday
|
||||||
|
- **WHEN** the daily run happens
|
||||||
|
- **THEN** S gets one notification saying 2 due today and 1 overdue
|
||||||
|
|
||||||
|
#### Scenario: Nothing due
|
||||||
|
|
||||||
|
- **GIVEN** salesperson S has no open lead due today or earlier
|
||||||
|
- **WHEN** the daily run happens
|
||||||
|
- **THEN** S gets no notification
|
||||||
|
|
||||||
|
### Requirement: Notifications Never Block The Action
|
||||||
|
|
||||||
|
A failure to create a notification SHALL NOT fail or roll back the sign-up, assignment or inbound message that caused it. The failure SHALL be logged without names, phone numbers or email addresses.
|
||||||
|
|
||||||
|
#### Scenario: Notification store down
|
||||||
|
|
||||||
|
- **GIVEN** the notification store cannot be reached
|
||||||
|
- **WHEN** a visitor signs up on a landing page
|
||||||
|
- **THEN** the sign-up succeeds and the lead is saved
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { NextResponse, type NextRequest } from "next/server";
|
||||||
|
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||||
|
import { getToken } from "@/app/lib/server/session";
|
||||||
|
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||||
|
|
||||||
|
export async function POST(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const token = await getToken();
|
||||||
|
if (!token) return unauthorized();
|
||||||
|
const { id } = await params;
|
||||||
|
if (!/^\d+$/.test(id)) return badRequest("A numeric notification id is required.");
|
||||||
|
const result = await callMobileApi<unknown>(`/api/admin/notifications/${encodeURIComponent(id)}/read`, { method: "POST", token });
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return new NextResponse(null, { status: 204 });
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||||
|
import { getToken } from "@/app/lib/server/session";
|
||||||
|
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||||
|
|
||||||
|
export async function POST() {
|
||||||
|
const token = await getToken();
|
||||||
|
if (!token) return unauthorized();
|
||||||
|
const result = await callMobileApi<{ count: number }>("/api/admin/notifications/read-all", { method: "POST", token });
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { NextResponse, type NextRequest } from "next/server";
|
||||||
|
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||||
|
import { getToken } from "@/app/lib/server/session";
|
||||||
|
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||||
|
|
||||||
|
// GET -> /api/admin/notifications: the signed-in user's own inbox, newest first. Side-effect free.
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const token = await getToken();
|
||||||
|
if (!token) return unauthorized();
|
||||||
|
const params = new URL(req.url).searchParams;
|
||||||
|
const qs = new URLSearchParams();
|
||||||
|
for (const k of ["page", "size"]) {
|
||||||
|
const v = params.get(k);
|
||||||
|
if (v && /^\d+$/.test(v)) qs.set(k, v);
|
||||||
|
}
|
||||||
|
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/notifications?${qs.toString()}`, { token });
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||||
|
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||||
|
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||||
|
|
||||||
|
import * as list from "./route";
|
||||||
|
import * as count from "./unread-count/route";
|
||||||
|
import * as readAll from "./read-all/route";
|
||||||
|
import * as readOne from "./[id]/read/route";
|
||||||
|
|
||||||
|
type Req = Parameters<typeof list.GET>[0];
|
||||||
|
const req = (url: string, init: RequestInit = {}) => new Request(`http://localhost${url}`, init) as unknown as Req;
|
||||||
|
const ctx = (id: string) => ({ params: Promise.resolve({ id }) });
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
mocks.getToken.mockResolvedValue("jwt");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { items: [], total: 0 } });
|
||||||
|
});
|
||||||
|
|
||||||
|
// add-lead-notifications: the bell's routes only ever act on the signed-in user's own notifications.
|
||||||
|
describe("notification routes", () => {
|
||||||
|
it("refuse without a session", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue(null);
|
||||||
|
expect((await list.GET(req("/api/notifications"))).status).toBe(401);
|
||||||
|
expect((await count.GET()).status).toBe(401);
|
||||||
|
expect((await readAll.POST()).status).toBe(401);
|
||||||
|
expect((await readOne.POST(req("/api/notifications/1/read", { method: "POST" }), ctx("1"))).status).toBe(401);
|
||||||
|
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("list forwards only numeric page and size", async () => {
|
||||||
|
const res = await list.GET(req("/api/notifications?page=2&size=10&receiver=9&x=1"));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/notifications?page=2&size=10", { token: "jwt" });
|
||||||
|
|
||||||
|
await list.GET(req("/api/notifications?page=-1&size=abc"));
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/notifications?", { token: "jwt" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("unread count and read-all call mobile-api", async () => {
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { count: 3 } });
|
||||||
|
expect(await (await count.GET()).json()).toEqual({ count: 3 });
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/notifications/unread-count", { token: "jwt" });
|
||||||
|
|
||||||
|
await readAll.POST();
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/notifications/read-all", { method: "POST", token: "jwt" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("mark read takes a numeric id only and answers 204", async () => {
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: undefined });
|
||||||
|
const ok = await readOne.POST(req("/api/notifications/42/read", { method: "POST" }), ctx("42"));
|
||||||
|
expect(ok.status).toBe(204);
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/notifications/42/read", { method: "POST", token: "jwt" });
|
||||||
|
|
||||||
|
mocks.callMobileApi.mockClear();
|
||||||
|
const bad = await readOne.POST(req("/api/notifications/..%2Fx/read", { method: "POST" }), ctx("../x"));
|
||||||
|
expect(bad.status).toBe(400);
|
||||||
|
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("pass an upstream failure through", async () => {
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Not found", status: 404 });
|
||||||
|
const res = await readOne.POST(req("/api/notifications/7/read", { method: "POST" }), ctx("7"));
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||||
|
import { getToken } from "@/app/lib/server/session";
|
||||||
|
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const token = await getToken();
|
||||||
|
if (!token) return unauthorized();
|
||||||
|
const result = await callMobileApi<{ count: number }>("/api/admin/notifications/unread-count", { token });
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { NextResponse, type NextRequest } from "next/server";
|
||||||
|
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||||
|
import { getToken } from "@/app/lib/server/session";
|
||||||
|
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||||
|
|
||||||
|
type Ctx = { params: Promise<{ id: string }> };
|
||||||
|
|
||||||
|
export async function POST(_req: NextRequest, { params }: Ctx) {
|
||||||
|
const token = await getToken();
|
||||||
|
if (!token) return unauthorized();
|
||||||
|
const { id } = await params;
|
||||||
|
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/pages/${encodeURIComponent(id)}/discard`, { method: "POST", token });
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { NextResponse, type NextRequest } from "next/server";
|
||||||
|
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||||
|
import { getToken } from "@/app/lib/server/session";
|
||||||
|
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||||
|
|
||||||
|
type Ctx = { params: Promise<{ id: string }> };
|
||||||
|
|
||||||
|
export async function POST(_req: NextRequest, { params }: Ctx) {
|
||||||
|
const token = await getToken();
|
||||||
|
if (!token) return unauthorized();
|
||||||
|
const { id } = await params;
|
||||||
|
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/pages/${encodeURIComponent(id)}/publish`, { method: "POST", token });
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -8,6 +8,8 @@ vi.mock("@/app/lib/server/clientContext", () => ({ clientIp: () => "203.0.113.9"
|
|||||||
import * as list from "./route";
|
import * as list from "./route";
|
||||||
import * as one from "./[id]/route";
|
import * as one from "./[id]/route";
|
||||||
import * as images from "./images/route";
|
import * as images from "./images/route";
|
||||||
|
import * as publish from "./[id]/publish/route";
|
||||||
|
import * as discard from "./[id]/discard/route";
|
||||||
import * as form from "../public/pages/[company]/[slug]/form/[block]/route";
|
import * as form from "../public/pages/[company]/[slug]/form/[block]/route";
|
||||||
import * as image from "../public/page-images/[id]/route";
|
import * as image from "../public/page-images/[id]/route";
|
||||||
import * as branding from "../companies/[id]/branding/route";
|
import * as branding from "../companies/[id]/branding/route";
|
||||||
@@ -42,6 +44,10 @@ describe("admin page routes", () => {
|
|||||||
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages/1", { method: "PUT", body: { title: "T" }, token: "jwt" });
|
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages/1", { method: "PUT", body: { title: "T" }, token: "jwt" });
|
||||||
await one.DELETE(req("/api/pages/1", { method: "DELETE" }), ctx({ id: "1" }));
|
await one.DELETE(req("/api/pages/1", { method: "DELETE" }), ctx({ id: "1" }));
|
||||||
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages/1", { method: "DELETE", token: "jwt" });
|
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages/1", { method: "DELETE", token: "jwt" });
|
||||||
|
await publish.POST(req("/api/pages/1/publish", { method: "POST" }), ctx({ id: "1/x" }));
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages/1%2Fx/publish", { method: "POST", token: "jwt" });
|
||||||
|
await discard.POST(req("/api/pages/1/discard", { method: "POST" }), ctx({ id: "1" }));
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages/1/discard", { method: "POST", token: "jwt" });
|
||||||
await list.POST(req("/api/pages", { method: "POST", body: JSON.stringify({ title: "T" }) }));
|
await list.POST(req("/api/pages", { method: "POST", body: JSON.stringify({ title: "T" }) }));
|
||||||
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages", { method: "POST", body: { title: "T" }, token: "jwt" });
|
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages", { method: "POST", body: { title: "T" }, token: "jwt" });
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ export default function CompanyPicker() {
|
|||||||
if (!isSuper) return null;
|
if (!isSuper) return null;
|
||||||
return (
|
return (
|
||||||
<Select value={companyId === undefined ? ALL : String(companyId)} onValueChange={(v) => setCompanyId(v === ALL ? undefined : Number(v))}>
|
<Select value={companyId === undefined ? ALL : String(companyId)} onValueChange={(v) => setCompanyId(v === ALL ? undefined : Number(v))}>
|
||||||
<SelectTrigger aria-label={t("Company")} className="min-w-36">
|
<SelectTrigger aria-label={t("Company")} className="max-w-28 sm:max-w-none sm:min-w-36">
|
||||||
<SelectValue />
|
<SelectValue />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ import CompanyPicker from "./CompanyPicker";
|
|||||||
import { clearStoredCompany } from "@/app/lib/CompanyScope";
|
import { clearStoredCompany } from "@/app/lib/CompanyScope";
|
||||||
import LocaleSwitcher from "./LocaleSwitcher";
|
import LocaleSwitcher from "./LocaleSwitcher";
|
||||||
import ChangePasswordDialog from "./ChangePasswordDialog";
|
import ChangePasswordDialog from "./ChangePasswordDialog";
|
||||||
|
import NotificationsBell from "./NotificationsBell";
|
||||||
|
|
||||||
// The authenticated shell's header: user menu reads the signed-in name from
|
// The authenticated shell's header: user menu reads the signed-in name from
|
||||||
// AdminAuthContext (session hydration, Task 5), and logout calls the
|
// AdminAuthContext (session hydration, Task 5), and logout calls the
|
||||||
@@ -75,9 +76,10 @@ export default function Header() {
|
|||||||
</SheetContent>
|
</SheetContent>
|
||||||
</Sheet>
|
</Sheet>
|
||||||
<Breadcrumbs />
|
<Breadcrumbs />
|
||||||
<div className="ml-auto flex items-center gap-2">
|
<div className="ml-auto flex items-center gap-1 sm:gap-2">
|
||||||
<CompanyPicker />
|
<CompanyPicker />
|
||||||
<LocaleSwitcher />
|
<LocaleSwitcher />
|
||||||
|
<NotificationsBell />
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import { render, screen, waitFor } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
|
||||||
|
const svc = vi.hoisted(() => ({
|
||||||
|
getUnreadCount: vi.fn(),
|
||||||
|
listNotifications: vi.fn(),
|
||||||
|
markRead: vi.fn(),
|
||||||
|
markAllRead: vi.fn(),
|
||||||
|
}));
|
||||||
|
vi.mock("@/app/lib/services/notifications", async (orig) => ({
|
||||||
|
...(await orig<typeof import("@/app/lib/services/notifications")>()),
|
||||||
|
...svc,
|
||||||
|
}));
|
||||||
|
|
||||||
|
import NotificationsBell from "./NotificationsBell";
|
||||||
|
|
||||||
|
const row = (id: number, seen: boolean, link: string | null = `/leads/${id}`) => ({
|
||||||
|
id, title: "NoticeLeadAssigned", type: "LEAD_ASSIGNED", link, seen, createDateTime: "2026-12-02T09:00:00",
|
||||||
|
message: '{"code":"NoticeLeadBody","params":{"lead":"Ali","event":"Expo"}}',
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
svc.getUnreadCount.mockResolvedValue(2);
|
||||||
|
svc.listNotifications.mockResolvedValue({ items: [row(1, false), row(2, false), row(3, true)], total: 3 });
|
||||||
|
svc.markRead.mockResolvedValue(undefined);
|
||||||
|
svc.markAllRead.mockResolvedValue(undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
// add-lead-notifications: the header bell.
|
||||||
|
describe("NotificationsBell", () => {
|
||||||
|
it("shows the unread count from the server", async () => {
|
||||||
|
render(<NotificationsBell />);
|
||||||
|
expect(await screen.findByText("2")).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole("button", { name: /2 unread/i })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("opening it lists the newest 10 in the reader's language and marks the unread ones read", async () => {
|
||||||
|
render(<NotificationsBell />);
|
||||||
|
await screen.findByText("2");
|
||||||
|
svc.getUnreadCount.mockResolvedValue(0);
|
||||||
|
await userEvent.click(screen.getByRole("button", { name: /notifications/i }));
|
||||||
|
|
||||||
|
expect(svc.listNotifications).toHaveBeenCalledWith(0, 10);
|
||||||
|
expect(await screen.findAllByText("Lead assigned to you")).toHaveLength(3);
|
||||||
|
expect(screen.getAllByText("Ali · Expo")).toHaveLength(3);
|
||||||
|
await waitFor(() => expect(svc.markRead).toHaveBeenCalledTimes(2));
|
||||||
|
expect(svc.markRead).toHaveBeenCalledWith(1);
|
||||||
|
expect(svc.markRead).toHaveBeenCalledWith(2);
|
||||||
|
await waitFor(() => expect(screen.queryByText("2")).not.toBeInTheDocument());
|
||||||
|
});
|
||||||
|
|
||||||
|
it("each item links to its target, and only to a path on this site", async () => {
|
||||||
|
svc.listNotifications.mockResolvedValue({ items: [row(1, true), row(2, true, "//evil.example")], total: 2 });
|
||||||
|
render(<NotificationsBell />);
|
||||||
|
await userEvent.click(await screen.findByRole("button", { name: /notifications/i }));
|
||||||
|
|
||||||
|
const items = await screen.findAllByRole("menuitem", { name: /Lead assigned to you/ });
|
||||||
|
expect(items[0]).toHaveAttribute("href", "/leads/1");
|
||||||
|
expect(items[1]).not.toHaveAttribute("href");
|
||||||
|
expect(screen.getByRole("menuitem", { name: /see all/i })).toHaveAttribute("href", "/notifications");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("says so when there are none, or when loading fails", async () => {
|
||||||
|
svc.listNotifications.mockResolvedValue({ items: [], total: 0 });
|
||||||
|
const { unmount } = render(<NotificationsBell />);
|
||||||
|
await userEvent.click(await screen.findByRole("button", { name: /notifications/i }));
|
||||||
|
expect(await screen.findByText("No notifications yet.")).toBeInTheDocument();
|
||||||
|
unmount();
|
||||||
|
|
||||||
|
svc.listNotifications.mockRejectedValue(new Error("down"));
|
||||||
|
render(<NotificationsBell />);
|
||||||
|
await userEvent.click(await screen.findByRole("button", { name: /notifications/i }));
|
||||||
|
expect(await screen.findByRole("alert")).toHaveTextContent("Couldn't load notifications.");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("recounts at once when another screen changes read state", async () => {
|
||||||
|
render(<NotificationsBell />);
|
||||||
|
await screen.findByText("2");
|
||||||
|
svc.getUnreadCount.mockResolvedValue(0);
|
||||||
|
|
||||||
|
window.dispatchEvent(new Event("notifications:changed"));
|
||||||
|
|
||||||
|
await waitFor(() => expect(screen.queryByText("2")).not.toBeInTheDocument());
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a failing unread count leaves the bell quiet instead of breaking the header", async () => {
|
||||||
|
svc.getUnreadCount.mockRejectedValue(new Error("down"));
|
||||||
|
render(<NotificationsBell />);
|
||||||
|
expect(await screen.findByRole("button", { name: /notifications/i })).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText("0")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { Bell } from "lucide-react";
|
||||||
|
import { Button } from "@/app/components/ui/button";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/app/components/ui/dropdown-menu";
|
||||||
|
import { useLocale, useT } from "@/app/lib/i18n/MessagesProvider";
|
||||||
|
import { usePolling } from "@/app/lib/hooks/usePolling";
|
||||||
|
import {
|
||||||
|
getUnreadCount,
|
||||||
|
isSitePath,
|
||||||
|
listNotifications,
|
||||||
|
markAllRead,
|
||||||
|
markRead,
|
||||||
|
NOTIFICATIONS_CHANGED,
|
||||||
|
noticeText,
|
||||||
|
noticeTime,
|
||||||
|
type AdminNotification,
|
||||||
|
} from "@/app/lib/services/notifications";
|
||||||
|
|
||||||
|
const POLL_MS = 30_000;
|
||||||
|
|
||||||
|
// add-lead-notifications: the header bell. The unread count polls while the tab is visible; opening the menu loads
|
||||||
|
// the newest 10 and marks the unread ones read (read state lives on the server, so it follows the user).
|
||||||
|
export default function NotificationsBell() {
|
||||||
|
const t = useT();
|
||||||
|
const locale = useLocale();
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [unread, setUnread] = useState(0);
|
||||||
|
const [items, setItems] = useState<AdminNotification[] | null>(null);
|
||||||
|
const [failed, setFailed] = useState(false);
|
||||||
|
|
||||||
|
const refreshCount = () => getUnreadCount().then(setUnread).catch(() => {});
|
||||||
|
usePolling(refreshCount, POLL_MS, NOTIFICATIONS_CHANGED, !open);
|
||||||
|
|
||||||
|
async function onOpenChange(next: boolean) {
|
||||||
|
setOpen(next);
|
||||||
|
if (!next) return;
|
||||||
|
setItems(null);
|
||||||
|
setFailed(false);
|
||||||
|
try {
|
||||||
|
const page = await listNotifications(0, 10);
|
||||||
|
setItems(page.items);
|
||||||
|
const unseen = page.items.filter((i) => !i.seen).map((i) => i.id);
|
||||||
|
if (unseen.length) {
|
||||||
|
await Promise.allSettled(unseen.map((id) => markRead(id)));
|
||||||
|
await refreshCount();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
setFailed(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onMarkAll() {
|
||||||
|
await markAllRead().catch(() => {});
|
||||||
|
setItems((list) => list?.map((i) => ({ ...i, seen: true })) ?? list);
|
||||||
|
await refreshCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
const when = (iso: string) => noticeTime(iso, locale);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DropdownMenu open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="relative size-9"
|
||||||
|
aria-label={unread > 0 ? t("NotificationsUnread", { count: unread }) : t("NotificationsTitle")}
|
||||||
|
>
|
||||||
|
<Bell aria-hidden="true" className="size-4" />
|
||||||
|
{unread > 0 && (
|
||||||
|
<span
|
||||||
|
aria-hidden="true"
|
||||||
|
className="absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-destructive px-1 text-[10px] leading-none font-semibold text-destructive-foreground"
|
||||||
|
>
|
||||||
|
{unread > 99 ? "99+" : unread}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end" className="w-80 max-w-[calc(100vw-2rem)]">
|
||||||
|
<div className="flex items-center justify-between gap-2 pr-1">
|
||||||
|
<DropdownMenuLabel>{t("NotificationsTitle")}</DropdownMenuLabel>
|
||||||
|
<Button variant="link" size="sm" className="h-auto p-0 text-xs" onClick={onMarkAll}>
|
||||||
|
{t("NotificationsMarkAllRead")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
{failed ? (
|
||||||
|
<p role="alert" className="px-2 py-3 text-sm text-destructive">{t("NotificationsLoadFailed")}</p>
|
||||||
|
) : items === null ? (
|
||||||
|
<p className="px-2 py-3 text-sm text-muted-foreground">{t("Loading")}</p>
|
||||||
|
) : items.length === 0 ? (
|
||||||
|
<p className="px-2 py-3 text-sm text-muted-foreground">{t("NotificationsEmpty")}</p>
|
||||||
|
) : (
|
||||||
|
<div className="max-h-96 overflow-y-auto">
|
||||||
|
{items.map((item) => {
|
||||||
|
const { title, body } = noticeText(item, t);
|
||||||
|
const inner = (
|
||||||
|
<span className="flex w-full min-w-0 items-start gap-2">
|
||||||
|
<span className="min-w-0 flex-1">
|
||||||
|
<span className="block truncate text-sm font-medium">{title}</span>
|
||||||
|
{body && <span className="block truncate text-xs text-muted-foreground">{body}</span>}
|
||||||
|
<span className="block text-xs text-muted-foreground">{when(item.createDateTime)}</span>
|
||||||
|
</span>
|
||||||
|
{!item.seen && <span aria-hidden="true" className="mt-1.5 size-2 shrink-0 rounded-full bg-primary" />}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
return isSitePath(item.link) ? (
|
||||||
|
<DropdownMenuItem key={item.id} asChild>
|
||||||
|
<Link href={item.link}>{inner}</Link>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
) : (
|
||||||
|
<DropdownMenuItem key={item.id}>{inner}</DropdownMenuItem>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem asChild>
|
||||||
|
<Link href="/notifications" className="justify-center text-sm">{t("NotificationsSeeAll")}</Link>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
import { ArrowDown, ArrowUp, Plus, Trash2 } from "lucide-react";
|
import { ArrowDown, ArrowUp, Plus, Trash2 } from "lucide-react";
|
||||||
import { BLOCK_LABELS, imageSrc, type CmsBlock } from "@/app/lib/cmsPages";
|
import { BLOCK_LABELS, ICONS, LOOKS, imageSrc, type CmsBlock, type CmsCard, type Look } from "@/app/lib/cmsPages";
|
||||||
import { Button } from "@/app/components/ui/button";
|
import { Button } from "@/app/components/ui/button";
|
||||||
import { Input } from "@/app/components/ui/input";
|
import { Input } from "@/app/components/ui/input";
|
||||||
import { Label } from "@/app/components/ui/label";
|
import { Label } from "@/app/components/ui/label";
|
||||||
@@ -12,7 +12,7 @@ import { RichTextEditor } from "./RichTextEditor";
|
|||||||
|
|
||||||
// One block of the page editor, ported from babyboo's BlockFields: a fieldset with move/remove and its type's fields.
|
// One block of the page editor, ported from babyboo's BlockFields: a fieldset with move/remove and its type's fields.
|
||||||
|
|
||||||
/** Field paths (relative to the block) each type shows inline; any other error shows at the block's top. */
|
/** Field paths (relative to the block) each type shows inline; any other error shows at the block's top. Every type also shows "anchor". */
|
||||||
const INLINE: Record<string, string[]> = {
|
const INLINE: Record<string, string[]> = {
|
||||||
HERO: ["imageId", "heading", "text", "buttonLabel", "buttonUrl"],
|
HERO: ["imageId", "heading", "text", "buttonLabel", "buttonUrl"],
|
||||||
RICH_TEXT: ["html"],
|
RICH_TEXT: ["html"],
|
||||||
@@ -20,8 +20,25 @@ const INLINE: Record<string, string[]> = {
|
|||||||
FAQ: ["heading", "items"],
|
FAQ: ["heading", "items"],
|
||||||
FORM: ["heading", "eventUuid"],
|
FORM: ["heading", "eventUuid"],
|
||||||
HTML: ["html"],
|
HTML: ["html"],
|
||||||
|
FEATURES: ["heading", "text", "cards"],
|
||||||
|
STEPS: ["heading", "cards"],
|
||||||
|
TRUST: ["cards"],
|
||||||
|
CTA: ["heading", "text", "buttonLabel", "buttonUrl"],
|
||||||
|
};
|
||||||
|
const LISTED = /^(items\[\d+\]\.(question|answer)|cards\[\d+\]\.(icon|title|text))$/;
|
||||||
|
|
||||||
|
// add-page-sections: labels for looks, feature icons and each card type's wording.
|
||||||
|
const LOOK_LABELS: Record<Look, string> = { DEFAULT: "PagesLookDefault", MUTED: "PagesLookMuted", DARK: "PagesLookDark", ACCENT: "PagesLookAccent" };
|
||||||
|
const ICON_LABELS: Record<string, string> = {
|
||||||
|
wifi: "PagesIconWifi", phone: "PagesIconPhone", tv: "PagesIconTv", monitor: "PagesIconMonitor", lock: "PagesIconLock",
|
||||||
|
"shield-check": "PagesIconShieldCheck", cloud: "PagesIconCloud", wrench: "PagesIconWrench", headset: "PagesIconHeadset",
|
||||||
|
users: "PagesIconUsers", calendar: "PagesIconCalendar", star: "PagesIconStar",
|
||||||
|
};
|
||||||
|
const CARD_KINDS: Record<string, { legend: string; add: string; icon: boolean; text: boolean; empty: CmsCard }> = {
|
||||||
|
FEATURES: { legend: "PagesCardN", add: "PagesAddCard", icon: true, text: true, empty: { icon: "star", title: "", text: "" } },
|
||||||
|
STEPS: { legend: "PagesStepN", add: "PagesAddStep", icon: false, text: true, empty: { title: "", text: "" } },
|
||||||
|
TRUST: { legend: "PagesItemN", add: "PagesAddItem", icon: false, text: false, empty: { title: "" } },
|
||||||
};
|
};
|
||||||
const LISTED = /^items\[\d+\]\.(question|answer)$/;
|
|
||||||
const SELECT = "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm disabled:cursor-not-allowed disabled:opacity-50";
|
const SELECT = "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm disabled:cursor-not-allowed disabled:opacity-50";
|
||||||
|
|
||||||
export interface EventOption {
|
export interface EventOption {
|
||||||
@@ -64,9 +81,9 @@ export function BlockFields(props: {
|
|||||||
const t = useT();
|
const t = useT();
|
||||||
const set = (patch: Partial<CmsBlock>) => onChange((b) => ({ ...b, ...patch }));
|
const set = (patch: Partial<CmsBlock>) => onChange((b) => ({ ...b, ...patch }));
|
||||||
const fid = (name: string) => `block-${id}-${name}`;
|
const fid = (name: string) => `block-${id}-${name}`;
|
||||||
const topErrors = Object.entries(errors).filter(([path]) => !INLINE[block.type]?.includes(path) && !LISTED.test(path));
|
const topErrors = Object.entries(errors).filter(([path]) => path !== "anchor" && path !== "look" && !INLINE[block.type]?.includes(path) && !LISTED.test(path));
|
||||||
|
|
||||||
const text = (name: "heading" | "text" | "buttonLabel" | "buttonUrl", labelCode: string) => (
|
const text = (name: "heading" | "text" | "buttonLabel" | "buttonUrl" | "anchor", labelCode: string) => (
|
||||||
<Field id={fid(name)} label={t(labelCode)} error={errors[name]}>
|
<Field id={fid(name)} label={t(labelCode)} error={errors[name]}>
|
||||||
<Input id={fid(name)} value={block[name] ?? ""} disabled={saving} aria-invalid={!!errors[name]} onChange={(e) => set({ [name]: e.target.value })} />
|
<Input id={fid(name)} value={block[name] ?? ""} disabled={saving} aria-invalid={!!errors[name]} onChange={(e) => set({ [name]: e.target.value })} />
|
||||||
</Field>
|
</Field>
|
||||||
@@ -97,6 +114,56 @@ export function BlockFields(props: {
|
|||||||
</Field>
|
</Field>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const kind = CARD_KINDS[block.type];
|
||||||
|
const cards = block.cards ?? [];
|
||||||
|
const setCards = (next: CmsCard[]) => set({ cards: next });
|
||||||
|
const moveCard = (i: number, delta: -1 | 1) => {
|
||||||
|
const next = [...cards];
|
||||||
|
[next[i], next[i + delta]] = [next[i + delta], next[i]];
|
||||||
|
setCards(next);
|
||||||
|
};
|
||||||
|
const cardList = kind ? (
|
||||||
|
<>
|
||||||
|
{cards.map((card, i) => {
|
||||||
|
const err = (f: string) => errors[`cards[${i}].${f}`];
|
||||||
|
const cardField = (f: "title" | "text", labelCode: string, multiline: boolean) => (
|
||||||
|
<Field id={fid(`c${i}${f}`)} label={t(labelCode)} error={err(f)}>
|
||||||
|
{multiline
|
||||||
|
? <Textarea id={fid(`c${i}${f}`)} rows={2} value={card[f] ?? ""} disabled={saving} aria-invalid={!!err(f)}
|
||||||
|
onChange={(e) => setCards(cards.map((c, j) => (j === i ? { ...c, [f]: e.target.value } : c)))} />
|
||||||
|
: <Input id={fid(`c${i}${f}`)} value={card[f] ?? ""} disabled={saving} aria-invalid={!!err(f)}
|
||||||
|
onChange={(e) => setCards(cards.map((c, j) => (j === i ? { ...c, [f]: e.target.value } : c)))} />}
|
||||||
|
</Field>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<fieldset key={i} className="space-y-2 rounded-md border p-3">
|
||||||
|
<legend className="px-1 text-sm font-medium">{t(kind.legend, { number: i + 1 })}</legend>
|
||||||
|
{kind.icon ? (
|
||||||
|
<Field id={fid(`c${i}icon`)} label={t("PagesCardIcon")} error={err("icon")}>
|
||||||
|
<select id={fid(`c${i}icon`)} className={SELECT} value={card.icon ?? "star"} disabled={saving} aria-invalid={!!err("icon")}
|
||||||
|
onChange={(e) => setCards(cards.map((c, j) => (j === i ? { ...c, icon: e.target.value } : c)))}>
|
||||||
|
{Object.keys(ICONS).map((name) => <option key={name} value={name}>{t(ICON_LABELS[name])}</option>)}
|
||||||
|
</select>
|
||||||
|
</Field>
|
||||||
|
) : null}
|
||||||
|
{cardField("title", "PagesCardTitle", false)}
|
||||||
|
{kind.text ? cardField("text", "PagesCardText", true) : null}
|
||||||
|
<div className="flex flex-wrap gap-1">
|
||||||
|
<Button type="button" variant="ghost" size="sm" disabled={saving || i === 0} onClick={() => moveCard(i, -1)}>{t("PagesMoveUp")}</Button>
|
||||||
|
<Button type="button" variant="ghost" size="sm" disabled={saving || i === cards.length - 1} onClick={() => moveCard(i, 1)}>{t("PagesMoveDown")}</Button>
|
||||||
|
<Button type="button" variant="ghost" size="sm" disabled={saving || cards.length <= 2} onClick={() => setCards(cards.filter((_, j) => j !== i))}>{t("PagesRemoveCard")}</Button>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
<FieldError message={errors.cards} />
|
||||||
|
<Button type="button" variant="outline" size="sm" disabled={saving || cards.length >= 6} onClick={() => setCards([...cards, { ...kind.empty }])}>
|
||||||
|
<Plus aria-hidden="true" className="size-4" />
|
||||||
|
{t(kind.add)}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
) : null;
|
||||||
|
|
||||||
const items = block.items ?? [];
|
const items = block.items ?? [];
|
||||||
const setItems = (next: typeof items) => set({ items: next });
|
const setItems = (next: typeof items) => set({ items: next });
|
||||||
|
|
||||||
@@ -195,6 +262,49 @@ export function BlockFields(props: {
|
|||||||
</Field>
|
</Field>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{block.type === "FEATURES" && (
|
||||||
|
<>
|
||||||
|
{text("heading", "PagesHeading")}
|
||||||
|
<Field id={fid("text")} label={t("PagesIntro")} error={errors.text}>
|
||||||
|
<Textarea id={fid("text")} rows={2} value={block.text ?? ""} disabled={saving} aria-invalid={!!errors.text} onChange={(e) => set({ text: e.target.value })} />
|
||||||
|
</Field>
|
||||||
|
{cardList}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{block.type === "STEPS" && (
|
||||||
|
<>
|
||||||
|
{text("heading", "PagesHeading")}
|
||||||
|
{cardList}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{block.type === "TRUST" && cardList}
|
||||||
|
|
||||||
|
{block.type === "CTA" && (
|
||||||
|
<>
|
||||||
|
{text("heading", "PagesHeading")}
|
||||||
|
{text("text", "PagesText")}
|
||||||
|
{text("buttonLabel", "PagesButtonLabel")}
|
||||||
|
{text("buttonUrl", "PagesButtonLink")}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{block.type !== "HTML" && (
|
||||||
|
<Field id={fid("look")} label={t("PagesLook")} error={errors.look}>
|
||||||
|
<select id={fid("look")} className={SELECT} value={block.look ?? "DEFAULT"} disabled={saving} aria-invalid={!!errors.look}
|
||||||
|
onChange={(e) => set({ look: e.target.value as Look })}>
|
||||||
|
{LOOKS.map((look) => <option key={look} value={look}>{t(LOOK_LABELS[look])}</option>)}
|
||||||
|
</select>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* add-page-anchor-links: the block's id on the page, the target of #name links. */}
|
||||||
|
<div className="space-y-1">
|
||||||
|
{text("anchor", "PagesAnchor")}
|
||||||
|
<p className="text-xs text-muted-foreground">{t("PagesAnchorHint")}</p>
|
||||||
|
</div>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -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 { act, render, screen } from "@testing-library/react";
|
||||||
import { describe, it, expect } from "vitest";
|
import { describe, it, expect, onTestFinished, vi } from "vitest";
|
||||||
import { LandingPage, type PublicBlock } from "./CmsBlocks";
|
import { LandingPage, type PublicBlock } from "./CmsBlocks";
|
||||||
import { FRAME_SANDBOX } from "@/app/lib/frameHtml";
|
import { FRAME_SANDBOX } from "@/app/lib/frameHtml";
|
||||||
|
|
||||||
@@ -21,6 +21,30 @@ describe("LandingPage: Custom HTML", () => {
|
|||||||
expect(document.querySelector("script")).toBeNull();
|
expect(document.querySelector("script")).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("gives a named HTML block its link name as the frame's id", () => {
|
||||||
|
render(<LandingPage company={company} page={page([{ ...HTML, anchor: "story" }])} />);
|
||||||
|
expect(frame()).toHaveAttribute("id", "story");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("scrolls the page for a #name link in its own frame: to the frame's target, else to the named block", () => {
|
||||||
|
const scrollTo = vi.spyOn(window, "scrollTo").mockImplementation(() => {});
|
||||||
|
const into = vi.fn();
|
||||||
|
Element.prototype.scrollIntoView = into;
|
||||||
|
render(<LandingPage company={company} page={page([HTML, { type: "FORM", heading: "Join", closed: true, anchor: "signup" }])} />);
|
||||||
|
vi.spyOn(frame(), "getBoundingClientRect").mockReturnValue({ top: 100 } as DOMRect);
|
||||||
|
const ask = (data: unknown, source: MessageEventSource | null) => act(() => { window.dispatchEvent(new MessageEvent("message", { data, source })); });
|
||||||
|
ask({ type: "colite-frame-anchor", name: "signup", y: null }, window);
|
||||||
|
expect(into).not.toHaveBeenCalled();
|
||||||
|
ask({ type: "colite-frame-anchor", name: "signup", y: null }, frame().contentWindow);
|
||||||
|
expect(into).toHaveBeenCalledTimes(1);
|
||||||
|
expect(into.mock.contexts[0]).toBe(document.getElementById("signup"));
|
||||||
|
ask({ type: "colite-frame-anchor", name: "top", y: 300 }, frame().contentWindow);
|
||||||
|
expect(scrollTo).toHaveBeenCalledWith({ top: 400, behavior: "smooth" });
|
||||||
|
ask({ type: "colite-frame-anchor", name: "nowhere", y: null }, frame().contentWindow);
|
||||||
|
expect(into).toHaveBeenCalledTimes(1);
|
||||||
|
expect(scrollTo).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
it("uses the preview's frame address when given", () => {
|
it("uses the preview's frame address when given", () => {
|
||||||
render(<LandingPage company={company} page={page([HTML])} frameBase="/pages/5/preview/frame" preview />);
|
render(<LandingPage company={company} page={page([HTML])} frameBase="/pages/5/preview/frame" preview />);
|
||||||
expect(frame()).toHaveAttribute("src", "/pages/5/preview/frame/0");
|
expect(frame()).toHaveAttribute("src", "/pages/5/preview/frame/0");
|
||||||
@@ -34,6 +58,17 @@ describe("LandingPage: Custom HTML", () => {
|
|||||||
expect(frame().style.height).toBe("2400px");
|
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", () => {
|
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)} />);
|
render(<LandingPage company={company} page={page([HTML], true)} />);
|
||||||
expect(screen.queryByRole("img", { name: "INS Sdn Bhd" })).not.toBeInTheDocument();
|
expect(screen.queryByRole("img", { name: "INS Sdn Bhd" })).not.toBeInTheDocument();
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import { render, screen, within } from "@testing-library/react";
|
||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { LandingPage, type PublicBlock } from "./CmsBlocks";
|
||||||
|
|
||||||
|
// add-page-sections: card sections, the CTA band, section looks and the image-less hero.
|
||||||
|
const company = { code: "INS", name: "INS Sdn Bhd", logoImageId: null, accentColor: "#FFEE00" };
|
||||||
|
const page = (blocks: PublicBlock[]) => ({ slug: "hotel", title: "Hotel day", blocks });
|
||||||
|
|
||||||
|
describe("LandingPage: sections", () => {
|
||||||
|
it("shows feature cards with their icons, titles and texts", () => {
|
||||||
|
render(<LandingPage company={company} page={page([{
|
||||||
|
type: "FEATURES", heading: "What we do", text: "One partner.",
|
||||||
|
cards: [{ icon: "wifi", title: "Managed WiFi", text: "Guests connect." }, { icon: "tv", title: "In-room TV", text: "Casting." }],
|
||||||
|
}])} />);
|
||||||
|
expect(screen.getByRole("heading", { name: "What we do" })).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("One partner.")).toBeInTheDocument();
|
||||||
|
const items = screen.getAllByRole("listitem");
|
||||||
|
expect(items).toHaveLength(2);
|
||||||
|
expect(within(items[0]).getByRole("heading", { name: "Managed WiFi" })).toBeInTheDocument();
|
||||||
|
expect(items[0].querySelector("svg.lucide-wifi")).not.toBeNull();
|
||||||
|
expect(items[1].querySelector("svg.lucide-tv")).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("numbers steps in order", () => {
|
||||||
|
render(<LandingPage company={company} page={page([{
|
||||||
|
type: "STEPS", heading: "How it works",
|
||||||
|
cards: [{ title: "Survey", text: "We visit." }, { title: "Install", text: "We fit it." }, { title: "Support", text: "We stay." }],
|
||||||
|
}])} />);
|
||||||
|
const list = screen.getByRole("list");
|
||||||
|
expect(list.tagName).toBe("OL");
|
||||||
|
const items = within(list).getAllByRole("listitem");
|
||||||
|
expect(items.map((li) => li.textContent)).toEqual(["1SurveyWe visit.", "2InstallWe fit it.", "3SupportWe stay."]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows a trust strip of short items", () => {
|
||||||
|
render(<LandingPage company={company} page={page([{ type: "TRUST", cards: [{ title: "Certified with LG" }, { title: "Local support" }] }])} />);
|
||||||
|
expect(screen.getAllByRole("listitem").map((li) => li.textContent)).toEqual(["Certified with LG", "Local support"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows a call-to-action band with its button, and drops an unsafe one", () => {
|
||||||
|
render(<LandingPage company={company} page={page([
|
||||||
|
{ type: "CTA", heading: "Ready?", text: "Talk to us.", buttonLabel: "Get a quote", buttonUrl: "#signup" },
|
||||||
|
{ type: "CTA", heading: "Bad", buttonLabel: "Evil", buttonUrl: "javascript:alert(1)" },
|
||||||
|
])} />);
|
||||||
|
expect(screen.getByRole("heading", { name: "Ready?" })).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole("link", { name: "Get a quote" })).toHaveAttribute("href", "#signup");
|
||||||
|
expect(screen.queryByRole("link", { name: "Evil" })).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("draws a non-default look as a full-width band and leaves default blocks as before", () => {
|
||||||
|
render(<LandingPage company={company} page={page([
|
||||||
|
{ type: "CTA", heading: "Dark", buttonLabel: "Go", buttonUrl: "/x", look: "DARK" },
|
||||||
|
{ type: "CTA", heading: "Accent", buttonLabel: "Go", buttonUrl: "/x", look: "ACCENT" },
|
||||||
|
{ type: "CTA", heading: "Muted", buttonLabel: "Go", buttonUrl: "/x", look: "MUTED" },
|
||||||
|
{ type: "CTA", heading: "Plain", buttonLabel: "Go", buttonUrl: "/x" },
|
||||||
|
{ type: "CTA", heading: "Junk", buttonLabel: "Go", buttonUrl: "/x", look: "NEON" as never },
|
||||||
|
])} />);
|
||||||
|
const band = (name: string) => screen.getByRole("heading", { name }).closest("[data-look]");
|
||||||
|
expect(band("Dark")).toHaveAttribute("data-look", "DARK");
|
||||||
|
expect(band("Dark")).toHaveClass("bg-foreground", "text-background");
|
||||||
|
expect(band("Accent")).toHaveClass("bg-primary", "text-primary-foreground");
|
||||||
|
expect(band("Muted")).toHaveClass("bg-muted");
|
||||||
|
expect(band("Plain")).toBeNull();
|
||||||
|
expect(band("Junk")).toBeNull();
|
||||||
|
// On an accent band the button flips, so it never matches the band's colour.
|
||||||
|
expect(within(band("Accent") as HTMLElement).getByRole("link", { name: "Go" })).toHaveClass("bg-background", "text-foreground");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows a hero without an image as text on its look's background", () => {
|
||||||
|
render(<LandingPage company={company} page={page([{ type: "HERO", heading: "No picture", buttonLabel: "Join", buttonUrl: "#signup", look: "DARK" }])} />);
|
||||||
|
expect(screen.getByRole("heading", { name: "No picture" })).toBeInTheDocument();
|
||||||
|
expect(document.querySelector("main img")).toBeNull();
|
||||||
|
expect(screen.getByRole("link", { name: "Join" })).toBeInTheDocument();
|
||||||
|
// On a band the hero takes the band's colours; its own grey box would put light text on a light background.
|
||||||
|
expect(screen.getByRole("heading", { name: "No picture" }).closest("section")).not.toHaveClass("bg-muted");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -35,6 +35,17 @@ describe("LandingPage", () => {
|
|||||||
expect(screen.getByRole("link", { name: "Mail" })).toHaveAttribute("href", "mailto:a@b.c");
|
expect(screen.getByRole("link", { name: "Mail" })).toHaveAttribute("href", "mailto:a@b.c");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("gives a named block its link name as id, so a #name button jumps to it", () => {
|
||||||
|
render(<LandingPage company={company} page={page([
|
||||||
|
{ type: "HERO", heading: "Hi", buttonLabel: "Sign up", buttonUrl: "#signup" },
|
||||||
|
{ type: "FORM", heading: "Join", closed: true, anchor: "signup" },
|
||||||
|
{ type: "RICH_TEXT", html: "<p>x</p>", anchor: 'bad" onclick="x' },
|
||||||
|
])} />);
|
||||||
|
expect(screen.getByRole("link", { name: "Sign up" })).toHaveAttribute("href", "#signup");
|
||||||
|
expect(document.getElementById("signup")).toHaveTextContent("Sign-up is closed.");
|
||||||
|
expect(document.querySelectorAll("main [id]")).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
it("a closed form says so; the preview shows a note instead of a form", () => {
|
it("a closed form says so; the preview shows a note instead of a form", () => {
|
||||||
const { unmount } = render(<LandingPage company={company} page={page([{ type: "FORM", heading: "Join", closed: true }])} />);
|
const { unmount } = render(<LandingPage company={company} page={page([{ type: "FORM", heading: "Join", closed: true }])} />);
|
||||||
expect(screen.getByText("Sign-up is closed.")).toBeInTheDocument();
|
expect(screen.getByText("Sign-up is closed.")).toBeInTheDocument();
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import type { CSSProperties, ReactNode } from "react";
|
import type { CSSProperties, ReactNode } from "react";
|
||||||
import { contrastText, imageSrc, isSafeLink, type CmsBlock } from "@/app/lib/cmsPages";
|
import { ICONS, LOOKS, anchorId, contrastText, imageSrc, isSafeLink, type CmsBlock, type Look } from "@/app/lib/cmsPages";
|
||||||
import type { RegistrationInfo } from "@/app/lib/services/publicRegistration";
|
import type { RegistrationInfo } from "@/app/lib/services/publicRegistration";
|
||||||
import { SafeHtml } from "./SafeHtml";
|
import { SafeHtml } from "./SafeHtml";
|
||||||
import { LandingForm } from "./LandingForm";
|
import { LandingForm } from "./LandingForm";
|
||||||
import { HtmlFrame } from "./HtmlFrame";
|
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;
|
// 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
|
// images are this company's uploads; buttons render only for a safe link, checked again here. A Custom HTML block is
|
||||||
@@ -20,69 +21,145 @@ export interface Branding {
|
|||||||
|
|
||||||
const PROSE = "space-y-3 text-base leading-relaxed [&_a]:text-primary [&_a]:underline [&_blockquote]:border-l-2 [&_blockquote]:pl-3 [&_h2]:text-2xl [&_h2]:font-semibold [&_h3]:text-xl [&_h3]:font-semibold [&_ol]:list-decimal [&_ol]:pl-5 [&_ul]:list-disc [&_ul]:pl-5";
|
const PROSE = "space-y-3 text-base leading-relaxed [&_a]:text-primary [&_a]:underline [&_blockquote]:border-l-2 [&_blockquote]:pl-3 [&_h2]:text-2xl [&_h2]:font-semibold [&_h3]:text-xl [&_h3]:font-semibold [&_ol]:list-decimal [&_ol]:pl-5 [&_ul]:list-disc [&_ul]:pl-5";
|
||||||
|
|
||||||
function ButtonLink({ block }: { block: CmsBlock }) {
|
// add-page-sections: non-default looks are full-width bands. On an accent band the button flips to stay visible.
|
||||||
if (!block.buttonLabel || !isSafeLink(block.buttonUrl)) return null;
|
const BANDS: Record<Exclude<Look, "DEFAULT">, string> = {
|
||||||
|
MUTED: "bg-muted text-foreground",
|
||||||
|
DARK: "bg-foreground text-background",
|
||||||
|
ACCENT: "bg-primary text-primary-foreground",
|
||||||
|
};
|
||||||
|
const bandOf = (look: unknown) => (LOOKS.includes(look as Look) && look !== "DEFAULT" ? (look as Exclude<Look, "DEFAULT">) : 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 external = /^https:/i.test(block.buttonUrl!);
|
||||||
|
const colours = bandOf(block.look) === "ACCENT" ? "bg-background text-foreground" : "bg-primary text-primary-foreground";
|
||||||
return (
|
return (
|
||||||
<a href={block.buttonUrl} {...(external ? { target: "_blank", rel: "noopener noreferrer" } : {})}
|
<a href={block.buttonUrl} {...(external ? { target: "_blank", rel: "noopener noreferrer" } : {})}
|
||||||
className="inline-flex h-11 items-center rounded-md bg-primary px-5 text-sm font-medium text-primary-foreground hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
|
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>
|
</a>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function BlockImage({ id, className }: { id?: number | null; className: string }) {
|
function Block({ block, index, company, slug, preview, edit }: { block: PublicBlock; index: number; company: string; slug: string; preview?: boolean; edit?: boolean }) {
|
||||||
// eslint-disable-next-line @next/next/no-img-element -- an uploaded image of unknown size
|
const image = block.imageId ? imageSrc(block.imageId) : undefined;
|
||||||
return id ? <img src={imageSrc(id)} alt="" className={className} /> : null;
|
const button = <ButtonLink block={block} index={index} edit={edit} />;
|
||||||
}
|
|
||||||
|
|
||||||
function Block({ block, index, company, slug, preview }: { block: PublicBlock; index: number; company: string; slug: string; preview?: boolean }) {
|
|
||||||
switch (block.type) {
|
switch (block.type) {
|
||||||
case "HERO":
|
case "HERO":
|
||||||
return (
|
return (
|
||||||
<section className="relative overflow-hidden rounded-lg bg-muted">
|
<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" />
|
<ImageSpot index={index} src={image} className="absolute inset-0 h-full w-full object-cover" corner />
|
||||||
<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"}>
|
<HeroShade index={index} image={!!image}
|
||||||
{block.heading ? <h2 className="text-3xl font-semibold sm:text-4xl">{block.heading}</h2> : null}
|
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"
|
||||||
{block.text ? <p className="max-w-2xl text-lg">{block.text}</p> : null}
|
plain="flex flex-col gap-3 p-6">
|
||||||
<div><ButtonLink block={block} /></div>
|
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-3xl font-semibold sm:text-4xl" />
|
||||||
</div>
|
<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>
|
</section>
|
||||||
);
|
);
|
||||||
case "RICH_TEXT":
|
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":
|
case "IMAGE_TEXT":
|
||||||
return (
|
return (
|
||||||
<section className="grid items-center gap-6 md:grid-cols-2">
|
<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">
|
<div className="space-y-3">
|
||||||
{block.heading ? <h2 className="text-2xl font-semibold">{block.heading}</h2> : null}
|
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold" />
|
||||||
{block.html ? <SafeHtml html={block.html} className={PROSE} /> : null}
|
<RichSpot index={index} html={block.html} className={PROSE}>{block.html ? <SafeHtml html={block.html} className={PROSE} /> : null}</RichSpot>
|
||||||
<ButtonLink block={block} />
|
{button}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
case "FAQ":
|
case "FAQ":
|
||||||
return block.items?.length ? (
|
return block.items?.length ? (
|
||||||
<section className="space-y-3">
|
<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">
|
<div className="divide-y rounded-lg border">
|
||||||
{block.items.map((item, i) => (
|
{block.items.map((item, i) => {
|
||||||
<details key={i} name={`faq-${index}`} className="group p-4">
|
const question = <Text as="span" index={index} path={`items.${i}.question`} value={item.question} max={300} code="PagesQuestionN" n={i + 1} />;
|
||||||
<summary className="cursor-pointer font-medium">{item.question}</summary>
|
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" />;
|
||||||
<p className="mt-2 whitespace-pre-line text-muted-foreground">{item.answer}</p>
|
// In edit mode every answer shows: a <summary> would toggle on a click or a typed space.
|
||||||
</details>
|
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>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
) : null;
|
) : null;
|
||||||
case "FORM":
|
case "FORM":
|
||||||
return (
|
return (
|
||||||
<section className="mx-auto w-full max-w-md space-y-4 rounded-lg border bg-card p-6 shadow-card">
|
<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} />
|
<LandingForm companyCode={company} slug={slug} index={index} info={block.closed ? undefined : block.form} preview={preview} />
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
|
case "FEATURES":
|
||||||
|
return (
|
||||||
|
<section className="space-y-6">
|
||||||
|
<div className="max-w-2xl space-y-2">
|
||||||
|
<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) => {
|
||||||
|
const Icon = card.icon ? ICONS[card.icon] : undefined;
|
||||||
|
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}
|
||||||
|
<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>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
case "STEPS":
|
||||||
|
return (
|
||||||
|
<section className="space-y-6">
|
||||||
|
<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">
|
||||||
|
<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>
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
case "TRUST":
|
||||||
|
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}><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">
|
||||||
|
<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:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -90,11 +167,24 @@ function Block({ block, index, company, slug, preview }: { block: PublicBlock; i
|
|||||||
|
|
||||||
const WIDTH = "mx-auto w-full max-w-5xl px-4";
|
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, index, children }: { block: PublicBlock; index: number; children: ReactNode }) {
|
||||||
|
const band = bandOf(block.look);
|
||||||
|
if (!band) return <EditSection index={index}><div id={anchorId(block.anchor)} className={WIDTH}>{children}</div></EditSection>;
|
||||||
|
return (
|
||||||
|
<EditSection index={index}>
|
||||||
|
<div id={anchorId(block.anchor)} data-look={band} className={`py-12 ${BANDS[band]}`}>
|
||||||
|
<div className={WIDTH}>{children}</div>
|
||||||
|
</div>
|
||||||
|
</EditSection>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A whole landing page: the company header (logo, accent), the title as the only h1, then the blocks. Custom HTML
|
* 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.
|
* 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;
|
company: Branding;
|
||||||
page: { slug: string; title: string; hideHeader?: boolean; blocks: PublicBlock[] };
|
page: { slug: string; title: string; hideHeader?: boolean; blocks: PublicBlock[] };
|
||||||
banner?: ReactNode;
|
banner?: ReactNode;
|
||||||
@@ -102,12 +192,14 @@ export function LandingPage({ company, page, banner, preview, frameBase }: {
|
|||||||
preview?: boolean;
|
preview?: boolean;
|
||||||
/** Where block frames load from; the public page's frame address by default. */
|
/** Where block frames load from; the public page's frame address by default. */
|
||||||
frameBase?: string;
|
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 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 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;
|
const style = accent ? ({ "--primary": accent, "--primary-foreground": contrastText(accent), "--ring": accent } as CSSProperties) : undefined;
|
||||||
return (
|
const body = (
|
||||||
<div style={style} className="min-h-svh bg-background">
|
<div style={style} className="min-h-svh bg-background" onClickCapture={edit ? stopNavigation : undefined}>
|
||||||
{banner}
|
{banner}
|
||||||
{page.hideHeader ? null : <header className="border-b bg-card">
|
{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">
|
<div className="mx-auto flex max-w-5xl items-center gap-3 px-4 py-3">
|
||||||
@@ -123,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>
|
<h1 className={page.hideHeader ? "sr-only" : `${WIDTH} mb-10 text-3xl font-semibold sm:text-4xl`}>{page.title}</h1>
|
||||||
<div className="space-y-10">
|
<div className="space-y-10">
|
||||||
{page.blocks.map((block, i) => block.type === "HTML"
|
{page.blocks.map((block, i) => block.type === "HTML"
|
||||||
? <HtmlFrame key={i} src={`${frames}/${i}`} title={page.title} />
|
? <HtmlSpot key={i} index={i}><HtmlFrame id={anchorId(block.anchor)} src={`${frames}/${i}${edit ? `?v=${edit.frameVersion}` : ""}`} title={page.title} /></HtmlSpot>
|
||||||
: <div key={i} className={WIDTH}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} /></div>)}
|
: <Section key={i} block={block} index={i}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} edit={!!edit} /></Section>)}
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,19 +1,28 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { FRAME_SANDBOX, nextFrameHeight, START_HEIGHT, type FrameHeight } from "@/app/lib/frameHtml";
|
import { FRAME_SANDBOX, frameAnchor, nextFrameHeight, START_HEIGHT, type FrameHeight } from "@/app/lib/frameHtml";
|
||||||
|
|
||||||
/** A Custom HTML block: the sealed frame, sized by height reports from that frame's own window only. */
|
/** A Custom HTML block: the sealed frame, sized by height reports and scrolled to by #name requests from that frame's own window only. */
|
||||||
export function HtmlFrame({ src, title }: { src: string; title: string }) {
|
export function HtmlFrame({ id, src, title }: { id?: string; src: string; title: string }) {
|
||||||
const ref = useRef<HTMLIFrameElement>(null);
|
const ref = useRef<HTMLIFrameElement>(null);
|
||||||
const [size, setSize] = useState<FrameHeight>({ height: START_HEIGHT, steps: [] });
|
const [size, setSize] = useState<FrameHeight>({ height: START_HEIGHT, steps: [] });
|
||||||
useEffect(() => {
|
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 onMessage = (e: MessageEvent) => {
|
||||||
if (!ref.current || e.source !== ref.current.contentWindow) return;
|
const frame = ref.current;
|
||||||
setSize((s) => nextFrameHeight(s, e.data));
|
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 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);
|
host.addEventListener("message", onMessage);
|
||||||
return () => window.removeEventListener("message", onMessage);
|
return () => host.removeEventListener("message", onMessage);
|
||||||
}, []);
|
}, []);
|
||||||
return <iframe ref={ref} src={src} title={title} sandbox={FRAME_SANDBOX} loading="lazy" className="block w-full border-0" style={{ height: `${size.height}px` }} />;
|
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,59 @@
|
|||||||
|
import { render, screen, waitFor } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
import { ApiError } from "@/app/lib/clientApi";
|
||||||
|
|
||||||
|
// add-page-anchor-links: each block's optional link name, the target of #name links.
|
||||||
|
const mocks = vi.hoisted(() => ({
|
||||||
|
getPage: vi.fn(), savePage: vi.fn(), deletePage: vi.fn(), uploadPageImage: vi.fn(),
|
||||||
|
listAdminEvents: vi.fn(), useAdminAuth: vi.fn(), useCompanyScope: vi.fn(),
|
||||||
|
}));
|
||||||
|
vi.mock("@/app/lib/services/adminPages", () => ({ getPage: mocks.getPage, savePage: mocks.savePage, deletePage: mocks.deletePage, uploadPageImage: mocks.uploadPageImage }));
|
||||||
|
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";
|
||||||
|
|
||||||
|
const stored = {
|
||||||
|
id: 5, companyId: 2, slug: "hotel", title: "Hotel", metaDescription: null, status: "PUBLISHED" as const, hideHeader: true,
|
||||||
|
blocks: [{ type: "HTML" as const, html: "<h1>Designed</h1>", anchor: "story" }, { type: "RICH_TEXT" as const, html: "<p>Hi</p>" }],
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
memoryRouter.reset("/pages/5");
|
||||||
|
mocks.useAdminAuth.mockReturnValue({ isSuper: false, companyCode: "INS" });
|
||||||
|
mocks.useCompanyScope.mockReturnValue({ companyId: undefined, companies: [{ id: 2, code: "INS", name: "INS", status: "A" }], codeOf: (id?: number) => (id === 2 ? "INS" : "") });
|
||||||
|
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
|
||||||
|
mocks.getPage.mockResolvedValue(stored);
|
||||||
|
mocks.savePage.mockImplementation(async (id: number | undefined, body: object) => ({ ...stored, ...body, id: id ?? 7 }));
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("PageEditor: link names", () => {
|
||||||
|
it("shows and saves each block's link name, dropping a blank one", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<PageEditor pageId={5} />);
|
||||||
|
const [first, second] = await screen.findAllByLabelText("Link name (optional)");
|
||||||
|
expect(first).toHaveValue("story");
|
||||||
|
expect(screen.getAllByText(/Link to this block with #name/)).toHaveLength(2);
|
||||||
|
await user.clear(first);
|
||||||
|
await user.type(second, "signup");
|
||||||
|
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||||
|
await waitFor(() => expect(mocks.savePage).toHaveBeenCalled());
|
||||||
|
expect(mocks.savePage.mock.calls[0][1].blocks).toEqual([{ type: "HTML", html: "<h1>Designed</h1>" }, { type: "RICH_TEXT", html: "<p>Hi</p>", anchor: "signup" }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows a refused link name at its field", async () => {
|
||||||
|
mocks.savePage.mockRejectedValue(new ApiError("x", 422, { code: "PagesAnchorTaken", details: { field: "blocks[1].anchor" } }));
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<PageEditor pageId={5} />);
|
||||||
|
const second = (await screen.findAllByLabelText("Link name (optional)"))[1];
|
||||||
|
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||||
|
expect(await screen.findByText("Another block on this page already has this link name.")).toBeInTheDocument();
|
||||||
|
expect(second.closest("div")).toHaveTextContent("Another block on this page already has this link name.");
|
||||||
|
expect(second).toHaveAttribute("aria-invalid", "true");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { describe, it, expect, vi, beforeEach } 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", () => ({
|
||||||
|
getPage: mocks.getPage, savePage: mocks.savePage, deletePage: mocks.deletePage, uploadPageImage: mocks.uploadPageImage,
|
||||||
|
publishPage: mocks.publishPage, discardPage: mocks.discardPage,
|
||||||
|
}));
|
||||||
|
vi.mock("@/app/lib/services/adminEvents", () => ({ listAdminEvents: mocks.listAdminEvents }));
|
||||||
|
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||||
|
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
|
||||||
|
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||||
|
|
||||||
|
import { memoryRouter } from "@/test/memoryRouter";
|
||||||
|
import { PageEditor } from "./PageEditor";
|
||||||
|
|
||||||
|
// add-page-drafts-and-templates: a published page's edits stay a draft until Publish changes.
|
||||||
|
const live = {
|
||||||
|
id: 5, companyId: 2, slug: "hotel", title: "Hotel day", metaDescription: null, status: "PUBLISHED" as const, hideHeader: false,
|
||||||
|
blocks: [{ type: "CTA" as const, heading: "Live heading", buttonLabel: "Go", buttonUrl: "#signup" }], draft: null, hasDraft: false,
|
||||||
|
};
|
||||||
|
const draft = { slug: "hotel-week", title: "Hotel week", metaDescription: null, hideHeader: false, blocks: [{ type: "CTA" as const, heading: "Draft heading", buttonLabel: "Go", buttonUrl: "#signup" }] };
|
||||||
|
const withDraft = { ...live, draft, hasDraft: true };
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
memoryRouter.reset("/pages/5");
|
||||||
|
mocks.useAdminAuth.mockReturnValue({ isSuper: false, companyCode: "INS" });
|
||||||
|
mocks.useCompanyScope.mockReturnValue({ companyId: undefined, companies: [], codeOf: (id?: number) => (id === 2 ? "INS" : "") });
|
||||||
|
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
|
||||||
|
mocks.getPage.mockResolvedValue(live);
|
||||||
|
mocks.savePage.mockResolvedValue(withDraft);
|
||||||
|
mocks.publishPage.mockResolvedValue({ ...live, slug: "hotel-week", title: "Hotel week", blocks: draft.blocks });
|
||||||
|
mocks.discardPage.mockResolvedValue(live);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("PageEditor drafts", () => {
|
||||||
|
it("edits the draft when there is one, while View page stays on the live address", async () => {
|
||||||
|
mocks.getPage.mockResolvedValue(withDraft);
|
||||||
|
render(<PageEditor pageId={5} />);
|
||||||
|
expect(await screen.findByLabelText("Title")).toHaveValue("Hotel week");
|
||||||
|
expect(screen.getByLabelText("Heading")).toHaveValue("Draft heading");
|
||||||
|
expect(screen.getByRole("link", { name: "View page" })).toHaveAttribute("href", "/p/INS/hotel");
|
||||||
|
expect(screen.getByText(/Visitors still see the published version/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("saving a published page shows the banner, and Publish changes saves then publishes", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<PageEditor pageId={5} />);
|
||||||
|
expect(await screen.findByLabelText("Title")).toHaveValue("Hotel day");
|
||||||
|
expect(screen.queryByText(/Visitors still see the published version/)).not.toBeInTheDocument();
|
||||||
|
await user.clear(screen.getByLabelText("Title"));
|
||||||
|
await user.type(screen.getByLabelText("Title"), "Hotel week");
|
||||||
|
const scroll = vi.fn();
|
||||||
|
Element.prototype.scrollIntoView = scroll;
|
||||||
|
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||||
|
expect(await screen.findByText(/Visitors still see the published version/)).toBeInTheDocument();
|
||||||
|
// Save sits at the bottom of a long form: the banner is brought into view.
|
||||||
|
await waitFor(() => expect(scroll).toHaveBeenCalled());
|
||||||
|
expect(scroll.mock.contexts[0]).toHaveTextContent(/Visitors still see the published version/);
|
||||||
|
expect(screen.getByLabelText("Title")).toHaveValue("Hotel week");
|
||||||
|
|
||||||
|
await user.click(screen.getByRole("button", { name: "Publish changes" }));
|
||||||
|
await waitFor(() => expect(mocks.publishPage).toHaveBeenCalledWith(5));
|
||||||
|
expect(mocks.savePage).toHaveBeenCalledTimes(2);
|
||||||
|
expect(mocks.savePage.mock.invocationCallOrder[1]).toBeLessThan(mocks.publishPage.mock.invocationCallOrder[0]);
|
||||||
|
await waitFor(() => expect(screen.queryByText(/Visitors still see the published version/)).not.toBeInTheDocument());
|
||||||
|
expect(screen.getByRole("status")).toHaveTextContent("Changes published");
|
||||||
|
expect(screen.getByRole("link", { name: "View page" })).toHaveAttribute("href", "/p/INS/hotel-week");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("offers Duplicate for a saved page", async () => {
|
||||||
|
render(<PageEditor pageId={5} />);
|
||||||
|
expect(await screen.findByRole("link", { name: "Duplicate" })).toHaveAttribute("href", "/pages/new?from=5");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a publish refusal shows at its field and keeps the banner", async () => {
|
||||||
|
mocks.getPage.mockResolvedValue(withDraft);
|
||||||
|
mocks.publishPage.mockRejectedValue(new ApiError("x", 409, { code: "PagesSlugTaken", details: { field: "slug" } }));
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<PageEditor pageId={5} />);
|
||||||
|
await user.click(await screen.findByRole("button", { name: "Publish changes" }));
|
||||||
|
expect(await screen.findByRole("alert")).toHaveTextContent("Another page already uses this slug.");
|
||||||
|
expect(screen.getByText(/Visitors still see the published version/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Discard changes asks first, then shows the live page again", async () => {
|
||||||
|
mocks.getPage.mockResolvedValue(withDraft);
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<PageEditor pageId={5} />);
|
||||||
|
await user.click(await screen.findByRole("button", { name: "Discard changes" }));
|
||||||
|
expect(mocks.discardPage).not.toHaveBeenCalled();
|
||||||
|
await user.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Discard changes" }));
|
||||||
|
await waitFor(() => expect(mocks.discardPage).toHaveBeenCalledWith(5));
|
||||||
|
expect(await screen.findByLabelText("Title")).toHaveValue("Hotel day");
|
||||||
|
expect(screen.getByLabelText("Heading")).toHaveValue("Live heading");
|
||||||
|
expect(screen.queryByText(/Visitors still see the published version/)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
import { ApiError } from "@/app/lib/clientApi";
|
||||||
|
|
||||||
|
// add-page-sections: the new section types, their cards and the look picker in the form editor.
|
||||||
|
const mocks = vi.hoisted(() => ({
|
||||||
|
getPage: vi.fn(), savePage: vi.fn(), deletePage: vi.fn(), uploadPageImage: vi.fn(),
|
||||||
|
listAdminEvents: vi.fn(), useAdminAuth: vi.fn(), useCompanyScope: vi.fn(),
|
||||||
|
}));
|
||||||
|
vi.mock("@/app/lib/services/adminPages", () => ({ getPage: mocks.getPage, savePage: mocks.savePage, deletePage: mocks.deletePage, uploadPageImage: mocks.uploadPageImage }));
|
||||||
|
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";
|
||||||
|
|
||||||
|
const stored = {
|
||||||
|
id: 5, companyId: 2, slug: "hotel", title: "Hotel", metaDescription: null, status: "DRAFT" as const, hideHeader: false,
|
||||||
|
blocks: [
|
||||||
|
{ type: "STEPS" as const, heading: "How it works", cards: [{ title: "Survey", text: "We visit." }, { title: "Install", text: "We fit it." }] },
|
||||||
|
{ 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: [{ id: 2, code: "INS", name: "INS", status: "A" }], codeOf: (id?: number) => (id === 2 ? "INS" : "") });
|
||||||
|
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
|
||||||
|
mocks.getPage.mockResolvedValue(stored);
|
||||||
|
mocks.savePage.mockImplementation(async (id: number | undefined, body: object) => ({ ...stored, ...body, id: id ?? 7 }));
|
||||||
|
});
|
||||||
|
|
||||||
|
const group = (name: string) => screen.getByRole("group", { name });
|
||||||
|
|
||||||
|
describe("PageEditor: sections", () => {
|
||||||
|
it("adds feature cards with icons and a look, and saves them", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<PageEditor pageId={5} />);
|
||||||
|
await screen.findByDisplayValue("How it works");
|
||||||
|
await user.click(screen.getByRole("button", { name: "Add Feature cards" }));
|
||||||
|
const block = group("Block 3: Feature cards");
|
||||||
|
await user.type(within(block).getByLabelText("Heading"), "What we do");
|
||||||
|
await user.type(within(block).getByLabelText("Intro"), "One partner.");
|
||||||
|
const card1 = within(block).getByRole("group", { name: "Card 1" });
|
||||||
|
await user.selectOptions(within(card1).getByLabelText("Icon"), "WiFi");
|
||||||
|
await user.type(within(card1).getByLabelText("Title"), "Managed WiFi");
|
||||||
|
await user.type(within(card1).getByLabelText("Text"), "Guests connect.");
|
||||||
|
const card2 = within(block).getByRole("group", { name: "Card 2" });
|
||||||
|
await user.type(within(card2).getByLabelText("Title"), "TV");
|
||||||
|
await user.type(within(card2).getByLabelText("Text"), "Casting.");
|
||||||
|
await user.selectOptions(within(block).getByLabelText("Look"), "Dark");
|
||||||
|
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||||
|
await waitFor(() => expect(mocks.savePage).toHaveBeenCalled());
|
||||||
|
expect(mocks.savePage.mock.calls[0][1].blocks[2]).toEqual({
|
||||||
|
type: "FEATURES", heading: "What we do", text: "One partner.", look: "DARK",
|
||||||
|
cards: [{ icon: "wifi", title: "Managed WiFi", text: "Guests connect." }, { icon: "star", title: "TV", text: "Casting." }],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps 2 to 6 cards and moves them", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<PageEditor pageId={5} />);
|
||||||
|
await screen.findByDisplayValue("How it works");
|
||||||
|
const block = group("Block 1: Steps");
|
||||||
|
expect(within(within(block).getByRole("group", { name: "Step 1" })).getByRole("button", { name: "Remove" })).toBeDisabled();
|
||||||
|
await user.click(within(within(block).getByRole("group", { name: "Step 2" })).getByRole("button", { name: "Move up" }));
|
||||||
|
expect(within(within(block).getByRole("group", { name: "Step 1" })).getByLabelText("Title")).toHaveValue("Install");
|
||||||
|
const add = within(block).getByRole("button", { name: "Add step" });
|
||||||
|
for (let i = 0; i < 4; i++) await user.click(add);
|
||||||
|
expect(add).toBeDisabled();
|
||||||
|
expect(within(within(block).getByRole("group", { name: "Step 6" })).getByRole("button", { name: "Remove" })).toBeEnabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("offers no look for a Custom HTML block", async () => {
|
||||||
|
render(<PageEditor pageId={5} />);
|
||||||
|
await screen.findByDisplayValue("How it works");
|
||||||
|
expect(within(group("Block 1: Steps")).getByLabelText("Look")).toBeInTheDocument();
|
||||||
|
expect(within(group("Block 2: Custom HTML")).queryByLabelText("Look")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows a refused card field at that card", async () => {
|
||||||
|
mocks.savePage.mockRejectedValue(new ApiError("x", 422, { code: "PagesTooLong", details: { field: "blocks[0].cards[1].title" } }));
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<PageEditor pageId={5} />);
|
||||||
|
await screen.findByDisplayValue("How it works");
|
||||||
|
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||||
|
const step2 = within(group("Block 1: Steps")).getByRole("group", { name: "Step 2" });
|
||||||
|
expect(await within(step2).findByText("Too long.")).toBeInTheDocument();
|
||||||
|
expect(within(step2).getByLabelText("Title")).toHaveAttribute("aria-invalid", "true");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -79,8 +79,8 @@ describe("PageEditor", () => {
|
|||||||
await screen.findByLabelText("Event");
|
await screen.findByLabelText("Event");
|
||||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||||
const link = screen.getAllByLabelText("Button link")[0];
|
const link = screen.getAllByLabelText("Button link")[0];
|
||||||
expect(await screen.findByText("Use a link that starts with https://, mailto:, tel: or /.")).toBeInTheDocument();
|
expect(await screen.findByText("Use a link that starts with https://, mailto:, tel:, / or #.")).toBeInTheDocument();
|
||||||
expect(link.closest("div")).toHaveTextContent("Use a link that starts with https://, mailto:, tel: or /.");
|
expect(link.closest("div")).toHaveTextContent("Use a link that starts with https://, mailto:, tel:, / or #.");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("uploads a chosen image on save and puts its id on the block", async () => {
|
it("uploads a chosen image on save and puts its id on the block", async () => {
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState, useSyncExternalStore, type RefObject } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useRouter, useSearchParams } from "next/navigation";
|
|
||||||
import { Button } from "@/app/components/ui/button";
|
import { Button } from "@/app/components/ui/button";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
|
||||||
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
|
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
|
||||||
@@ -12,249 +11,203 @@ import { Switch } from "@/app/components/ui/switch";
|
|||||||
import { Textarea } from "@/app/components/ui/textarea";
|
import { Textarea } from "@/app/components/ui/textarea";
|
||||||
import { ErrorState } from "@/app/components/ui/states";
|
import { ErrorState } from "@/app/components/ui/states";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
|
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 { CopyAddress } from "./CopyAddress";
|
||||||
import { BLOCK_LABELS, BLOCK_TYPES, emptyBlock, emptyPage, pageAddress, pageBody, withTitle, type CmsBlock, type CmsPageDraft, type PageStatus } from "@/app/lib/cmsPages";
|
import { BLOCK_LABELS, BLOCK_TYPES, pageAddress, type CmsBlock } from "@/app/lib/cmsPages";
|
||||||
import { deletePage, getPage, savePage, uploadPageImage } from "@/app/lib/services/adminPages";
|
|
||||||
import { listAdminEvents } from "@/app/lib/services/adminEvents";
|
|
||||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
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
|
// The landing-page editor, ported from babyboo's PageEditor. State and actions live in usePageDraft, owned here so
|
||||||
// follows its block through moves and removals. Block images upload on Save, just before the page is saved,
|
// they survive a window resize that switches between the on-page editor (1024 px and up) and the form editor.
|
||||||
// each at most once even when a later step fails.
|
|
||||||
|
|
||||||
interface Row {
|
export type Draft = ReturnType<typeof usePageDraft>;
|
||||||
key: number;
|
/** Asks before the destructive actions; the dialogs are the editor's, whichever layout shows. */
|
||||||
block: CmsBlock;
|
export interface Ask { remove(): void; discard(): void }
|
||||||
}
|
|
||||||
|
|
||||||
function readDataUrl(file: File): Promise<string> {
|
export function FieldError({ message }: { message?: 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 }) {
|
|
||||||
return message ? <p role="alert" className="text-sm text-destructive">{message}</p> : null;
|
return message ? <p role="alert" className="text-sm text-destructive">{message}</p> : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function PageEditor({ pageId }: { pageId?: number }) {
|
const WIDE = "(min-width: 1024px)";
|
||||||
|
const wideNow = () => window.matchMedia(WIDE).matches;
|
||||||
|
const onWideChange = (cb: () => void) => {
|
||||||
|
const query = window.matchMedia(WIDE);
|
||||||
|
query.addEventListener("change", cb);
|
||||||
|
return () => query.removeEventListener("change", cb);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** pageId edits a page; fromId opens an unsaved copy of one (Duplicate); initialBlocks start a new page (templates). */
|
||||||
|
export function PageEditor(props: { pageId?: number; fromId?: number; initialBlocks?: CmsBlock[] }) {
|
||||||
const t = useT();
|
const t = useT();
|
||||||
const router = useRouter();
|
const p = usePageDraft(props);
|
||||||
const { isSuper, companyCode } = useAdminAuth();
|
const wide = useSyncExternalStore(onWideChange, wideNow, () => false);
|
||||||
const scope = useCompanyScope();
|
|
||||||
const justSaved = useSearchParams()?.get("saved") === "1";
|
|
||||||
const [draft, setDraft] = useState<CmsPageDraft>(() => ({ ...emptyPage(), companyId: scope.companyId }));
|
|
||||||
const [rows, setRows] = useState<Row[]>([]);
|
|
||||||
const [pending, setPending] = useState<Record<number, { file: File; preview?: string }>>({});
|
|
||||||
// The page as last loaded or saved: what "View page" points at.
|
|
||||||
const [saved, setSaved] = useState<{ slug: string; status: PageStatus } | null>(null);
|
|
||||||
const [dirty, setDirty] = useState(false);
|
|
||||||
const [loading, setLoading] = useState(pageId != null);
|
|
||||||
const [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 [confirmDelete, setConfirmDelete] = useState(false);
|
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||||
const [events, setEvents] = useState<EventOption[]>([]);
|
const [confirmDiscard, setConfirmDiscard] = useState(false);
|
||||||
const nextKey = useRef(0);
|
const ask: Ask = { remove: () => setConfirmDelete(true), discard: () => setConfirmDiscard(true) };
|
||||||
const toRows = (blocks: CmsBlock[]) => blocks.map((block) => ({ key: ++nextKey.current, block }));
|
|
||||||
const isNew = draft.id == null;
|
|
||||||
const code = (isSuper ? scope.codeOf(draft.companyId) : companyCode) || "";
|
|
||||||
|
|
||||||
useEffect(() => {
|
if (p.loadError) return <ErrorState message={t(p.loadError)} />;
|
||||||
if (pageId == null) return;
|
if (p.loading) return null;
|
||||||
let cancelled = false;
|
|
||||||
getPage(pageId)
|
|
||||||
.then((p) => {
|
|
||||||
if (cancelled) return;
|
|
||||||
setDraft({ id: p.id, companyId: p.companyId, slug: p.slug, slugTouched: true, title: p.title, metaDescription: p.metaDescription ?? "", status: p.status, hideHeader: !!p.hideHeader, blocks: [] });
|
|
||||||
setRows(toRows(p.blocks ?? []));
|
|
||||||
setSaved({ slug: p.slug, status: p.status });
|
|
||||||
})
|
|
||||||
.catch((err: unknown) => { if (!cancelled) setLoadError(err instanceof ApiError && err.status === 404 ? "PagesNotFound" : "PagesLoadFailed"); })
|
|
||||||
.finally(() => { if (!cancelled) setLoading(false); });
|
|
||||||
return () => { cancelled = true; };
|
|
||||||
}, [pageId]);
|
|
||||||
|
|
||||||
// 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() {
|
|
||||||
setSummary(null);
|
|
||||||
setNotice(null);
|
|
||||||
setErrors({});
|
|
||||||
if (isNew && isSuper && !draft.companyId) {
|
|
||||||
setErrors({ companyId: t("ChooseCompany") });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
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 });
|
|
||||||
setDirty(false);
|
|
||||||
setNotice("PagesSaved");
|
|
||||||
if (isNew) router.replace(`/pages/${page.id}?saved=1`);
|
|
||||||
} catch (err) {
|
|
||||||
showError(err);
|
|
||||||
} finally {
|
|
||||||
// Uploaded images stay on their blocks and leave the pending set, success or not.
|
|
||||||
setRows(next);
|
|
||||||
setPending(left);
|
|
||||||
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]] : [])));
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<>
|
||||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
{wide ? <VisualEditor p={p} ask={ask} /> : <FormEditor p={p} ask={ask} />}
|
||||||
{saved && code ? <span className="mr-auto"><CopyAddress address={pageAddress(code, saved.slug)} /></span> : null}
|
<LeaveGuard dirty={p.dirty} />
|
||||||
{draft.id != null ? (
|
{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>
|
<Button variant="outline" asChild>
|
||||||
<Link href={`/pages/${draft.id}/preview`}>{t("PagesPreview")}</Link>
|
<Link href={`/pages/${draft.id}/preview`}>{t("PagesPreview")}</Link>
|
||||||
</Button>
|
</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}
|
) : null}
|
||||||
{saved?.status === "PUBLISHED" && code ? (
|
<div className="space-y-1.5">
|
||||||
<Button variant="outline" asChild>
|
<Label htmlFor="page-title">{t("Title")}</Label>
|
||||||
<a href={pageAddress(code, saved.slug)} target="_blank" rel="noopener noreferrer">{t("PagesViewPage")}</a>
|
<Input id="page-title" value={draft.title} disabled={saving} aria-invalid={!!errors.title} onChange={(e) => p.setTitle(e.target.value)} />
|
||||||
</Button>
|
<FieldError message={errors.title} />
|
||||||
) : null}
|
</div>
|
||||||
</div>
|
<div className="space-y-1.5">
|
||||||
{summary && <p role="alert" className="text-sm text-destructive">{summary}</p>}
|
<Label htmlFor="page-slug">{t("PagesSlug")}</Label>
|
||||||
{notice && <p role="status" className="text-sm text-positive">{t(notice)}</p>}
|
<Input id="page-slug" value={draft.slug} disabled={saving} aria-invalid={!!errors.slug} onChange={(e) => p.patch({ slug: e.target.value, slugTouched: true })} />
|
||||||
|
<p className="text-xs text-muted-foreground">{t("PagesAddressHint", { address: pageAddress(code || "…", draft.slug || "…") })}</p>
|
||||||
|
<FieldError message={errors.slug} />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="page-meta">{t("PagesMetaDescription")}</Label>
|
||||||
|
<Textarea id="page-meta" rows={3} value={draft.metaDescription} disabled={saving} aria-invalid={!!errors.metaDescription} onChange={(e) => p.patch({ metaDescription: e.target.value })} />
|
||||||
|
<p className="tabular text-xs text-muted-foreground">{`${draft.metaDescription.trim().length}/160`}</p>
|
||||||
|
<FieldError message={errors.metaDescription} />
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Draft or published, and the hide-header switch. */
|
||||||
|
export function StatusSettings({ p }: { p: Draft }) {
|
||||||
|
const t = useT();
|
||||||
|
const { draft, errors, saving } = p;
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader><CardTitle>{t("Status")}</CardTitle></CardHeader>
|
||||||
|
<CardContent className="space-y-2">
|
||||||
|
{(["DRAFT", "PUBLISHED"] as const).map((s) => (
|
||||||
|
<label key={s} className="flex items-center gap-2 text-sm">
|
||||||
|
<input type="radio" name="page-status" value={s} checked={draft.status === s} disabled={saving} onChange={() => p.patch({ status: s })} />
|
||||||
|
{t(s === "PUBLISHED" ? "PagesPublished" : "PagesDraft")}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
<FieldError message={errors.status} />
|
||||||
|
<div className="flex items-center gap-2 pt-2 text-sm">
|
||||||
|
<Switch id="page-hide-header" checked={draft.hideHeader} disabled={saving} onCheckedChange={(on) => p.patch({ hideHeader: on })} />
|
||||||
|
<Label htmlFor="page-hide-header">{t("PagesHideHeader")}</Label>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The form editor: narrow windows. */
|
||||||
|
function FormEditor({ p, ask }: { p: Draft; ask: Ask }) {
|
||||||
|
const t = useT();
|
||||||
|
const { draft, rows, errors, saving } = p;
|
||||||
|
// Save sits below a long form, so the unpublished-changes banner is scrolled into view after a save that leaves one.
|
||||||
|
const draftBanner = useRef<HTMLDivElement>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
if (p.revealDraft) draftBanner.current?.scrollIntoView?.({ behavior: "smooth", block: "nearest" });
|
||||||
|
}, [p.revealDraft]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<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="grid gap-4 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<Card>
|
<PageSettings p={p} />
|
||||||
<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>
|
|
||||||
|
|
||||||
{rows.map((row, index) => (
|
{rows.map((row, index) => (
|
||||||
<BlockFields
|
<BlockFields
|
||||||
key={row.key}
|
key={row.key}
|
||||||
@@ -262,68 +215,38 @@ export function PageEditor({ pageId }: { pageId?: number }) {
|
|||||||
block={row.block}
|
block={row.block}
|
||||||
index={index}
|
index={index}
|
||||||
count={rows.length}
|
count={rows.length}
|
||||||
errors={blockErrors(index)}
|
errors={p.blockErrors(index)}
|
||||||
saving={saving}
|
saving={saving}
|
||||||
events={events}
|
events={p.events}
|
||||||
pendingImage={pending[row.key] && { name: pending[row.key].file.name, preview: pending[row.key].preview }}
|
pendingImage={p.pending[row.key] && { name: p.pending[row.key].file.name, preview: p.pending[row.key].preview }}
|
||||||
onChange={(update) => updateBlock(row.key, update)}
|
onChange={(update) => p.updateBlock(row.key, update)}
|
||||||
onMove={(delta) => moveBlock(index, delta)}
|
onMove={(delta) => p.moveBlock(index, delta)}
|
||||||
onRemove={() => removeBlock(row.key)}
|
onRemove={() => p.removeBlock(row.key)}
|
||||||
onChooseImage={(file) => chooseImage(row.key, file)}
|
onChooseImage={(file) => p.chooseImage(row.key, file)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
<FieldError message={errors.blocks} />
|
<FieldError message={errors.blocks} />
|
||||||
|
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
{BLOCK_TYPES.map((type) => (
|
{BLOCK_TYPES.map((type) => (
|
||||||
<Button key={type} type="button" variant="outline" size="sm" disabled={saving}
|
<Button key={type} type="button" variant="outline" size="sm" disabled={saving} onClick={() => p.addBlock(type)}>
|
||||||
onClick={() => { setDirty(true); setRows((rs) => [...rs, { key: ++nextKey.current, block: emptyBlock(type) }]); }}>
|
|
||||||
{t("PagesAddBlock", { type: t(BLOCK_LABELS[type]) })}
|
{t("PagesAddBlock", { type: t(BLOCK_LABELS[type]) })}
|
||||||
</Button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-4">
|
<div className="space-y-4"><StatusSettings p={p} /></div>
|
||||||
<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>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||||
{draft.id != null ? (
|
{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")}
|
{t("PagesDelete")}
|
||||||
</Button>
|
</Button>
|
||||||
) : <span />}
|
) : <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>
|
</div>
|
||||||
|
|
||||||
{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>
|
</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,28 +1,32 @@
|
|||||||
"use client";
|
"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 { EditorContent, useEditor, useEditorState, type Editor } from "@tiptap/react";
|
||||||
import StarterKit from "@tiptap/starter-kit";
|
import StarterKit from "@tiptap/starter-kit";
|
||||||
import TextAlign from "@tiptap/extension-text-align";
|
import TextAlign from "@tiptap/extension-text-align";
|
||||||
import { AlignCenter, AlignLeft, AlignRight, Bold, Eraser, Italic, Link as LinkIcon, List, ListOrdered, Minus, Quote, Strikethrough, Underline } from "lucide-react";
|
import { AlignCenter, AlignLeft, AlignRight, Bold, Eraser, Italic, Link as LinkIcon, List, ListOrdered, Minus, Quote, Strikethrough, Underline } from "lucide-react";
|
||||||
import { Button } from "@/app/components/ui/button";
|
import { Button } from "@/app/components/ui/button";
|
||||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||||
|
import { isSafeLink } from "@/app/lib/cmsPages";
|
||||||
|
|
||||||
// Ported from babyboo's RichTextEditor, trimmed for landing pages: no YouTube, tables, inline images, emoji,
|
// Ported from babyboo's RichTextEditor, trimmed for landing pages: no YouTube, tables, inline images, emoji,
|
||||||
// colour or HTML source view. The public page sanitises the HTML again with an allow-list.
|
// colour or HTML source view. The public page sanitises the HTML again with an allow-list.
|
||||||
const SAFE_LINK = /^(https:\/\/|mailto:|tel:|\/(?!\/))/i;
|
// Links follow the page rule in cmsPages (isSafeLink), the same one services-counter applies to buttons.
|
||||||
|
|
||||||
const htmlOf = (editor: Editor) => (editor.isEmpty ? "" : editor.getHTML());
|
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;
|
id?: string;
|
||||||
label?: string;
|
label?: string;
|
||||||
value: string;
|
value: string;
|
||||||
onChange: (html: string) => void;
|
onChange: (html: string) => void;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
invalid?: 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 t = useT();
|
||||||
|
const [refused, setRefused] = useState(false);
|
||||||
const emitted = useRef(value);
|
const emitted = useRef(value);
|
||||||
const editor = useEditor({
|
const editor = useEditor({
|
||||||
immediatelyRender: false,
|
immediatelyRender: false,
|
||||||
@@ -32,11 +36,11 @@ export function RichTextEditor({ id, label, value, onChange, disabled, invalid }
|
|||||||
StarterKit.configure({
|
StarterKit.configure({
|
||||||
heading: { levels: [2, 3] },
|
heading: { levels: [2, 3] },
|
||||||
trailingNode: false,
|
trailingNode: false,
|
||||||
link: { openOnClick: false, protocols: ["https", "mailto", "tel"], isAllowedUri: (url) => SAFE_LINK.test(url) },
|
link: { openOnClick: false, protocols: ["https", "mailto", "tel"], isAllowedUri: (url) => isSafeLink(url) },
|
||||||
}),
|
}),
|
||||||
TextAlign.configure({ types: ["heading", "paragraph"], alignments: ["left", "center", "right"] }),
|
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 }) => {
|
onUpdate: ({ editor }) => {
|
||||||
const html = htmlOf(editor);
|
const html = htmlOf(editor);
|
||||||
emitted.current = html;
|
emitted.current = html;
|
||||||
@@ -75,13 +79,17 @@ export function RichTextEditor({ id, label, value, onChange, disabled, invalid }
|
|||||||
|
|
||||||
function addLink() {
|
function addLink() {
|
||||||
const url = window.prompt(t("PagesLinkPrompt"));
|
const url = window.prompt(t("PagesLinkPrompt"));
|
||||||
if (!url || !SAFE_LINK.test(url)) return;
|
setRefused(!!url && !isSafeLink(url));
|
||||||
|
if (!url || !isSafeLink(url)) return;
|
||||||
run((e) => e.chain().focus().extendMarkRange("link").setLink({ href: url }).run());
|
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 (
|
return (
|
||||||
<div className="space-y-2">
|
<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="flex flex-wrap items-center gap-1" role="toolbar" aria-label={t("PagesToolbar")}>
|
<div className={toolbar} role="toolbar" aria-label={t("PagesToolbar")}>
|
||||||
<select aria-label={t("PagesTextStyle")} title={t("PagesTextStyle")} disabled={off} value={state?.level ?? "0"}
|
<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"
|
className="h-9 rounded-md border border-input bg-transparent px-2 text-sm"
|
||||||
onChange={(ev) => {
|
onChange={(ev) => {
|
||||||
@@ -105,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("PagesDivider"), <Minus />, () => run((e) => e.chain().focus().setHorizontalRule().run()))}
|
||||||
{btn(t("PagesLink"), <LinkIcon />, addLink, state?.active.link)}
|
{btn(t("PagesLink"), <LinkIcon />, addLink, state?.active.link)}
|
||||||
{btn(t("PagesClearFormatting"), <Eraser />, () => run((e) => e.chain().focus().unsetAllMarks().clearNodes().run()))}
|
{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>
|
||||||
<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} />
|
<EditorContent editor={editor} />
|
||||||
</div>
|
</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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { BLOCK_TYPES, ICONS, LOOKS, emptyBlock, emptyPage, pageBody } from "./cmsPages";
|
||||||
|
|
||||||
|
// add-page-sections: the new block types in the editor model and the save body.
|
||||||
|
describe("cmsPages: sections", () => {
|
||||||
|
it("offers the four new types, the server's icon list and looks", () => {
|
||||||
|
expect(BLOCK_TYPES).toEqual(expect.arrayContaining(["FEATURES", "STEPS", "TRUST", "CTA"]));
|
||||||
|
expect(Object.keys(ICONS).sort()).toEqual(["calendar", "cloud", "headset", "lock", "monitor", "phone", "shield-check", "star", "tv", "users", "wifi", "wrench"]);
|
||||||
|
expect(LOOKS).toEqual(["DEFAULT", "MUTED", "DARK", "ACCENT"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("starts each card section with the minimum cards and only the fields its type uses", () => {
|
||||||
|
expect(emptyBlock("FEATURES")).toEqual({ type: "FEATURES", heading: "", text: "", cards: [{ icon: "star", title: "", text: "" }, { icon: "star", title: "", text: "" }] });
|
||||||
|
expect(emptyBlock("STEPS")).toEqual({ type: "STEPS", heading: "", cards: [{ title: "", text: "" }, { title: "", text: "" }] });
|
||||||
|
expect(emptyBlock("TRUST")).toEqual({ type: "TRUST", cards: [{ title: "" }, { title: "" }] });
|
||||||
|
expect(emptyBlock("CTA")).toEqual({ type: "CTA", heading: "", text: "", buttonLabel: "", buttonUrl: "" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("trims card fields and drops a default look on save", () => {
|
||||||
|
const body = pageBody({
|
||||||
|
...emptyPage(), title: "T", slug: "t",
|
||||||
|
blocks: [
|
||||||
|
{ type: "STEPS", heading: " How ", look: "DEFAULT", cards: [{ title: " Survey ", text: " We visit. " }, { title: "Fit", text: "" }] },
|
||||||
|
{ type: "CTA", heading: "Go", look: "DARK", buttonLabel: "Join", buttonUrl: "#signup" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(body.blocks).toEqual([
|
||||||
|
{ type: "STEPS", heading: "How", cards: [{ title: "Survey", text: "We visit." }, { title: "Fit", text: "" }] },
|
||||||
|
{ type: "CTA", heading: "Go", look: "DARK", buttonLabel: "Join", buttonUrl: "#signup" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, it, expect } from "vitest";
|
import { describe, it, expect } from "vitest";
|
||||||
import { contrastText, emptyPage, isSafeLink, pageBody, slugify, withTitle } from "./cmsPages";
|
import { anchorId, contrastText, emptyPage, isSafeLink, pageBody, slugify, withTitle } from "./cmsPages";
|
||||||
|
|
||||||
describe("cmsPages helpers", () => {
|
describe("cmsPages helpers", () => {
|
||||||
it("slug follows the title until edited", () => {
|
it("slug follows the title until edited", () => {
|
||||||
@@ -29,4 +29,11 @@ describe("cmsPages helpers", () => {
|
|||||||
for (const ok of ["/p/INS/a", "https://x.com", "mailto:a@b.c", "tel:+60123"]) expect(isSafeLink(ok), ok).toBe(true);
|
for (const ok of ["/p/INS/a", "https://x.com", "mailto:a@b.c", "tel:+60123"]) expect(isSafeLink(ok), ok).toBe(true);
|
||||||
for (const bad of ["//evil.com", "javascript:alert(1)", "http://x.com", "https://a b", "/\\evil", undefined]) expect(isSafeLink(bad), String(bad)).toBe(false);
|
for (const bad of ["//evil.com", "javascript:alert(1)", "http://x.com", "https://a b", "/\\evil", undefined]) expect(isSafeLink(bad), String(bad)).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("a same-page link is # plus a block link name", () => {
|
||||||
|
for (const ok of ["#signup", "#top", "#2-rooms", "#" + "a".repeat(40)]) expect(isSafeLink(ok), ok).toBe(true);
|
||||||
|
for (const bad of ["#", "#Sign Up", "#-x", "#signup/x", "#a\"b", "#" + "a".repeat(41), "#reg-consent"]) expect(isSafeLink(bad), bad).toBe(false);
|
||||||
|
expect(anchorId("signup")).toBe("signup");
|
||||||
|
for (const bad of [undefined, "", "Sign Up", "x\" onclick=\"y", "reg-email"]) expect(anchorId(bad), String(bad)).toBeUndefined();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -1,9 +1,21 @@
|
|||||||
// Landing-page blocks and the editor's pure helpers (add-landing-pages), ported from babyboo's cmsPages.ts
|
// Landing-page blocks and the editor's pure helpers (add-landing-pages), ported from babyboo's cmsPages.ts
|
||||||
// minus the product blocks. Images are page_image ids, served at /api/public/page-images/<id>.
|
// minus the product blocks. Images are page_image ids, served at /api/public/page-images/<id>.
|
||||||
|
|
||||||
export type BlockType = "HERO" | "RICH_TEXT" | "IMAGE_TEXT" | "FAQ" | "FORM" | "HTML";
|
import { Calendar, Cloud, Headset, Lock, Monitor, Phone, ShieldCheck, Star, Tv, Users, Wifi, Wrench, type LucideIcon } from "lucide-react";
|
||||||
|
|
||||||
export const BLOCK_TYPES: BlockType[] = ["HERO", "RICH_TEXT", "IMAGE_TEXT", "FAQ", "FORM", "HTML"];
|
export type BlockType = "HERO" | "RICH_TEXT" | "IMAGE_TEXT" | "FAQ" | "FORM" | "HTML" | "FEATURES" | "STEPS" | "TRUST" | "CTA";
|
||||||
|
|
||||||
|
export const BLOCK_TYPES: BlockType[] = ["HERO", "RICH_TEXT", "IMAGE_TEXT", "FEATURES", "STEPS", "TRUST", "CTA", "FAQ", "FORM", "HTML"];
|
||||||
|
|
||||||
|
/** Feature-card icons by the name services-counter accepts (add-page-sections). */
|
||||||
|
export const ICONS: Record<string, LucideIcon> = {
|
||||||
|
wifi: Wifi, phone: Phone, tv: Tv, monitor: Monitor, lock: Lock, "shield-check": ShieldCheck,
|
||||||
|
cloud: Cloud, wrench: Wrench, headset: Headset, users: Users, calendar: Calendar, star: Star,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Section looks: DEFAULT renders as before; the others are full-width bands. */
|
||||||
|
export const LOOKS = ["DEFAULT", "MUTED", "DARK", "ACCENT"] as const;
|
||||||
|
export type Look = (typeof LOOKS)[number];
|
||||||
|
|
||||||
export const BLOCK_LABELS: Record<BlockType, string> = {
|
export const BLOCK_LABELS: Record<BlockType, string> = {
|
||||||
HERO: "PagesBlockHero",
|
HERO: "PagesBlockHero",
|
||||||
@@ -12,8 +24,19 @@ export const BLOCK_LABELS: Record<BlockType, string> = {
|
|||||||
FAQ: "PagesBlockFaq",
|
FAQ: "PagesBlockFaq",
|
||||||
FORM: "PagesBlockForm",
|
FORM: "PagesBlockForm",
|
||||||
HTML: "PagesBlockHtml",
|
HTML: "PagesBlockHtml",
|
||||||
|
FEATURES: "PagesBlockFeatures",
|
||||||
|
STEPS: "PagesBlockSteps",
|
||||||
|
TRUST: "PagesBlockTrust",
|
||||||
|
CTA: "PagesBlockCta",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** A FEATURES (icon, title, text), STEPS (title, text) or TRUST (title) card. */
|
||||||
|
export interface CmsCard {
|
||||||
|
icon?: string;
|
||||||
|
title: string;
|
||||||
|
text?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface CmsFaqItem {
|
export interface CmsFaqItem {
|
||||||
question: string;
|
question: string;
|
||||||
answer: string;
|
answer: string;
|
||||||
@@ -29,6 +52,10 @@ export interface CmsBlock {
|
|||||||
html?: string;
|
html?: string;
|
||||||
imagePosition?: "LEFT" | "RIGHT";
|
imagePosition?: "LEFT" | "RIGHT";
|
||||||
items?: CmsFaqItem[];
|
items?: CmsFaqItem[];
|
||||||
|
/** Optional link name: the block's id on the page, the target of a #name link (add-page-anchor-links). */
|
||||||
|
anchor?: string;
|
||||||
|
look?: Look;
|
||||||
|
cards?: CmsCard[];
|
||||||
/** The FORM block's event (a Snowflake uuid, kept as a string). */
|
/** The FORM block's event (a Snowflake uuid, kept as a string). */
|
||||||
eventUuid?: string | null;
|
eventUuid?: string | null;
|
||||||
}
|
}
|
||||||
@@ -45,6 +72,21 @@ export interface CmsPage {
|
|||||||
hideHeader?: boolean;
|
hideHeader?: boolean;
|
||||||
blocks: CmsBlock[];
|
blocks: CmsBlock[];
|
||||||
updatedAt?: string | null;
|
updatedAt?: string | null;
|
||||||
|
/** Unpublished changes of a published page (editor reads only). */
|
||||||
|
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. */
|
||||||
|
export interface PageContent {
|
||||||
|
slug: string;
|
||||||
|
title: string;
|
||||||
|
metaDescription: string | null;
|
||||||
|
hideHeader?: boolean;
|
||||||
|
blocks: CmsBlock[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CmsPageDraft {
|
export interface CmsPageDraft {
|
||||||
@@ -78,6 +120,14 @@ export function emptyBlock(type: BlockType): CmsBlock {
|
|||||||
return { type, heading: "", eventUuid: null };
|
return { type, heading: "", eventUuid: null };
|
||||||
case "HTML":
|
case "HTML":
|
||||||
return { type, html: "" };
|
return { type, html: "" };
|
||||||
|
case "FEATURES":
|
||||||
|
return { type, heading: "", text: "", cards: [{ icon: "star", title: "", text: "" }, { icon: "star", title: "", text: "" }] };
|
||||||
|
case "STEPS":
|
||||||
|
return { type, heading: "", cards: [{ title: "", text: "" }, { title: "", text: "" }] };
|
||||||
|
case "TRUST":
|
||||||
|
return { type, cards: [{ title: "" }, { title: "" }] };
|
||||||
|
case "CTA":
|
||||||
|
return { type, heading: "", text: "", buttonLabel: "", buttonUrl: "" };
|
||||||
default:
|
default:
|
||||||
return { type };
|
return { type };
|
||||||
}
|
}
|
||||||
@@ -111,6 +161,12 @@ export function pageBody(draft: CmsPageDraft) {
|
|||||||
out.items = (val as CmsFaqItem[]).map((it) => ({ question: it.question.trim(), answer: it.answer.trim() }));
|
out.items = (val as CmsFaqItem[]).map((it) => ({ question: it.question.trim(), answer: it.answer.trim() }));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if (key === "cards") {
|
||||||
|
// Trimmed but kept, so a blank card field is refused at its own path.
|
||||||
|
out.cards = (val as CmsCard[]).map((c) => Object.fromEntries(Object.entries(c).map(([k, x]) => [k, typeof x === "string" ? x.trim() : x])));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (key === "look" && val === "DEFAULT") continue;
|
||||||
const v = typeof val === "string" ? val.trim() : val;
|
const v = typeof val === "string" ? val.trim() : val;
|
||||||
if (!blank(v)) out[key] = v;
|
if (!blank(v)) out[key] = v;
|
||||||
}
|
}
|
||||||
@@ -131,9 +187,16 @@ export function contrastText(hex: string): "#000000" | "#FFFFFF" {
|
|||||||
return (lum + 0.05) / 0.05 > 1.05 / (lum + 0.05) ? "#000000" : "#FFFFFF";
|
return (lum + 0.05) / 0.05 > 1.05 / (lum + 0.05) ? "#000000" : "#FFFFFF";
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The counter's link rule: same-site path, https, mailto or tel. Checked again before rendering a button. */
|
/** A block link name, as services-counter checks it. "reg-" is reserved: the sign-up form's fields use it as ids. */
|
||||||
|
export const ANCHOR = /^(?!reg-)[a-z0-9][a-z0-9-]{0,39}$/;
|
||||||
|
|
||||||
|
/** The link name when it is valid, for use as an element id. */
|
||||||
|
export const anchorId = (name: string | undefined) => (name && ANCHOR.test(name) ? name : undefined);
|
||||||
|
|
||||||
|
/** The counter's link rule: same-site path, https, mailto, tel or #name. Checked again before rendering a button. */
|
||||||
export function isSafeLink(url: string | undefined): boolean {
|
export function isSafeLink(url: string | undefined): boolean {
|
||||||
if (!url || url.length > 1000 || /[\s\\\u0000-\u001f]/.test(url)) return false;
|
if (!url || url.length > 1000 || /[\s\\\u0000-\u001f]/.test(url)) return false;
|
||||||
|
if (url.startsWith("#")) return ANCHOR.test(url.slice(1));
|
||||||
if (url.startsWith("/")) return !url.startsWith("//");
|
if (url.startsWith("/")) return !url.startsWith("//");
|
||||||
return /^(https:\/\/|mailto:|tel:)/i.test(url);
|
return /^(https:\/\/|mailto:|tel:)/i.test(url);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||||
|
import { frameDocument } from "./frameHtml";
|
||||||
|
|
||||||
|
// add-page-anchor-links: the injected frame script turns clicks on #name links into requests to the page.
|
||||||
|
function runFrameScript(body: string) {
|
||||||
|
document.body.innerHTML = body;
|
||||||
|
const code = frameDocument("").match(/<script>([\s\S]*)<\/script>/)![1];
|
||||||
|
new Function(code)();
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => vi.restoreAllMocks());
|
||||||
|
|
||||||
|
describe("frame script: same-page links", () => {
|
||||||
|
it("asks the page to scroll, with the in-frame target's offset when the frame has it, and never navigates the frame", () => {
|
||||||
|
const post = vi.spyOn(window.parent, "postMessage").mockImplementation(() => {});
|
||||||
|
runFrameScript('<div id="top">Top</div><a href="#top">Back</a><a href="#signup"><span>Join</span></a>');
|
||||||
|
const back = new MouseEvent("click", { bubbles: true, cancelable: true });
|
||||||
|
document.querySelector('a[href="#top"]')!.dispatchEvent(back);
|
||||||
|
expect(back.defaultPrevented).toBe(true);
|
||||||
|
expect(post).toHaveBeenCalledWith({ type: "colite-frame-anchor", name: "top", y: 0 }, "*");
|
||||||
|
const join = new MouseEvent("click", { bubbles: true, cancelable: true });
|
||||||
|
document.querySelector("span")!.dispatchEvent(join);
|
||||||
|
expect(join.defaultPrevented).toBe(true);
|
||||||
|
expect(post).toHaveBeenCalledWith({ type: "colite-frame-anchor", name: "signup", y: null }, "*");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves other links alone", () => {
|
||||||
|
const post = vi.spyOn(window.parent, "postMessage").mockImplementation(() => {});
|
||||||
|
runFrameScript('<a href="https://wa.me/1">WA</a><a href="#Bad Name">Bad</a>');
|
||||||
|
post.mockClear();
|
||||||
|
for (const a of document.querySelectorAll("a")) {
|
||||||
|
const click = new MouseEvent("click", { bubbles: true, cancelable: true });
|
||||||
|
a.dispatchEvent(click);
|
||||||
|
expect(click.defaultPrevented).toBe(false);
|
||||||
|
}
|
||||||
|
expect(post.mock.calls.filter(([d]) => (d as { type: string }).type === "colite-frame-anchor")).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, it, expect } from "vitest";
|
import { describe, it, expect } from "vitest";
|
||||||
import { FRAME_SANDBOX, frameDocument, frameResponse, nextFrameHeight, START_HEIGHT } from "./frameHtml";
|
import { FRAME_SANDBOX, frameAnchor, frameDocument, frameResponse, nextFrameHeight, START_HEIGHT } from "./frameHtml";
|
||||||
|
|
||||||
// add-custom-html-block: pasted HTML runs sealed, in its own document with a sandbox policy, and reports its height.
|
// add-custom-html-block: pasted HTML runs sealed, in its own document with a sandbox policy, and reports its height.
|
||||||
describe("frameHtml", () => {
|
describe("frameHtml", () => {
|
||||||
@@ -54,4 +54,15 @@ describe("frameHtml", () => {
|
|||||||
for (const h of [900, 1250, 1900, 2000, 2600]) t = nextFrameHeight(t, { type: "colite-frame-height", height: h });
|
for (const h of [900, 1250, 1900, 2000, 2600]) t = nextFrameHeight(t, { type: "colite-frame-height", height: h });
|
||||||
expect(t.height).toBe(2600);
|
expect(t.height).toBe(2600);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// add-page-anchor-links: a frame asks its page to scroll to a #name target.
|
||||||
|
it("reads a same-page link request: a valid name and the in-frame offset, or nothing", () => {
|
||||||
|
expect(frameAnchor({ type: "colite-frame-anchor", name: "signup", y: null })).toEqual({ name: "signup", y: null });
|
||||||
|
expect(frameAnchor({ type: "colite-frame-anchor", name: "top", y: 120.4 })).toEqual({ name: "top", y: 120 });
|
||||||
|
expect(frameAnchor({ type: "colite-frame-anchor", name: "top", y: -5 })).toEqual({ name: "top", y: 0 });
|
||||||
|
for (const junk of [null, "x", { type: "colite-frame-height", height: 5 }, { type: "colite-frame-anchor", name: "Sign Up", y: null }, { type: "colite-frame-anchor", name: "reg-email", y: null },
|
||||||
|
{ type: "colite-frame-anchor", name: "a", y: "1" }, { type: "colite-frame-anchor", name: "a", y: Infinity }, { type: "colite-frame-anchor", y: null }]) {
|
||||||
|
expect(frameAnchor(junk), JSON.stringify(junk)).toBeNull();
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -10,15 +10,24 @@ export const START_HEIGHT = 600;
|
|||||||
const MIN_HEIGHT = 100;
|
const MIN_HEIGHT = 100;
|
||||||
const MAX_HEIGHT = 20000;
|
const MAX_HEIGHT = 20000;
|
||||||
|
|
||||||
// Posts the document height to the parent page on load and whenever it changes.
|
export const FRAME_ANCHOR_MESSAGE = "colite-frame-anchor";
|
||||||
const HEIGHT_SCRIPT =
|
/** A block link name, as in cmsPages (kept here as a string for the frame script). */
|
||||||
`<script>(function(){function s(){parent.postMessage({type:"${FRAME_MESSAGE}",height:Math.ceil(document.documentElement.scrollHeight)},"*")}` +
|
const ANCHOR_SOURCE = "^(?!reg-)[a-z0-9][a-z0-9-]{0,39}$";
|
||||||
`addEventListener("load",s);if(window.ResizeObserver)new ResizeObserver(s).observe(document.documentElement);s()})();</script>`;
|
const ANCHOR = new RegExp(ANCHOR_SOURCE);
|
||||||
|
|
||||||
/** The pasted HTML with the height script before its last </body>, or appended when it is a fragment. */
|
// Posts the document height to the parent page on load and whenever it changes. A click on a #name link
|
||||||
|
// (add-page-anchor-links) asks the page to scroll instead: the frame is as tall as its content and never scrolls.
|
||||||
|
const FRAME_SCRIPT =
|
||||||
|
`<script>(function(){function s(){parent.postMessage({type:"${FRAME_MESSAGE}",height:Math.ceil(document.documentElement.scrollHeight)},"*")}` +
|
||||||
|
`addEventListener("load",s);if(window.ResizeObserver)new ResizeObserver(s).observe(document.documentElement);s();` +
|
||||||
|
`document.addEventListener("click",function(e){var a=e.target&&e.target.closest&&e.target.closest('a[href^="#"]');if(!a)return;` +
|
||||||
|
`var n=a.getAttribute("href").slice(1);if(!/${ANCHOR_SOURCE}/.test(n))return;e.preventDefault();var t=document.getElementById(n);` +
|
||||||
|
`parent.postMessage({type:"${FRAME_ANCHOR_MESSAGE}",name:n,y:t?Math.round(t.getBoundingClientRect().top+scrollY):null},"*")})})();</script>`;
|
||||||
|
|
||||||
|
/** The pasted HTML with the frame script before its last </body>, or appended when it is a fragment. */
|
||||||
export function frameDocument(html: string): string {
|
export function frameDocument(html: string): string {
|
||||||
const at = html.toLowerCase().lastIndexOf("</body>");
|
const at = html.toLowerCase().lastIndexOf("</body>");
|
||||||
return at < 0 ? html + HEIGHT_SCRIPT : html.slice(0, at) + HEIGHT_SCRIPT + html.slice(at);
|
return at < 0 ? html + FRAME_SCRIPT : html.slice(0, at) + FRAME_SCRIPT + html.slice(at);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function frameResponse(html: string, { preview }: { preview: boolean }): Response {
|
export function frameResponse(html: string, { preview }: { preview: boolean }): Response {
|
||||||
@@ -65,3 +74,12 @@ export function nextFrameHeight(state: FrameHeight, data: unknown): FrameHeight
|
|||||||
if (a !== undefined && b !== undefined && Math.abs(a - step) <= 2 && Math.abs(b - step) <= 2) return state;
|
if (a !== undefined && b !== undefined && Math.abs(a - step) <= 2 && Math.abs(b - step) <= 2) return state;
|
||||||
return { height, steps: [...state.steps, step].slice(-2) };
|
return { height, steps: [...state.steps, step].slice(-2) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A same-page link request from a frame: a valid link name and the target's offset in the frame (null when the frame lacks it). Junk is null. */
|
||||||
|
export function frameAnchor(data: unknown): { name: string; y: number | null } | null {
|
||||||
|
const d = data as { type?: unknown; name?: unknown; y?: unknown } | null;
|
||||||
|
if (!d || typeof d !== "object" || d.type !== FRAME_ANCHOR_MESSAGE || typeof d.name !== "string" || !ANCHOR.test(d.name)) return null;
|
||||||
|
if (d.y === null) return { name: d.name, y: null };
|
||||||
|
if (typeof d.y !== "number" || !Number.isFinite(d.y)) return null;
|
||||||
|
return { name: d.name, y: Math.min(MAX_HEIGHT, Math.max(0, Math.round(d.y))) };
|
||||||
|
}
|
||||||
@@ -63,6 +63,14 @@ describe("preview frame", () => {
|
|||||||
expect(res.headers.get("content-security-policy")).toMatch(/^sandbox allow-scripts/);
|
expect(res.headers.get("content-security-policy")).toMatch(/^sandbox allow-scripts/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("serves the unpublished changes' HTML block when the page has a draft", async () => {
|
||||||
|
const draft = { slug: "hotel", title: "Hotel", blocks: [{ type: "HTML", html: "<p>draft only</p>" }] };
|
||||||
|
mocks.callMobileApi.mockResolvedValueOnce({ ok: true, data: { slug: "hotel", title: "Hotel", blocks: [{ type: "FAQ" }], draft } });
|
||||||
|
const res = await preview.GET(req, ctx({ id: "5", block: "0" }));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(await res.text()).toContain("draft only");
|
||||||
|
});
|
||||||
|
|
||||||
it("is not found without a session, for a bad id, a refused page or a non-HTML block", async () => {
|
it("is not found without a session, for a bad id, a refused page or a non-HTML block", async () => {
|
||||||
mocks.getToken.mockResolvedValueOnce(null);
|
mocks.getToken.mockResolvedValueOnce(null);
|
||||||
expect((await preview.GET(req, ctx({ id: "5", block: "0" }))).status).toBe(404);
|
expect((await preview.GET(req, ctx({ id: "5", block: "0" }))).status).toBe(404);
|
||||||
|
|||||||
@@ -742,6 +742,39 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
|||||||
PagesPreview: "Preview",
|
PagesPreview: "Preview",
|
||||||
PagesPreviewBanner: "Preview. Visitors see this page only once it is published.",
|
PagesPreviewBanner: "Preview. Visitors see this page only once it is published.",
|
||||||
PagesViewPage: "View page",
|
PagesViewPage: "View page",
|
||||||
|
PagesDuplicate: "Duplicate",
|
||||||
|
PagesDuplicateNamed: "Duplicate {title}",
|
||||||
|
PagesChooseStart: "How do you want to start?",
|
||||||
|
PagesStartBlank: "Blank page",
|
||||||
|
PagesStartBlankHint: "Start empty and add sections yourself.",
|
||||||
|
PagesTemplateEvent: "Event sign-up",
|
||||||
|
PagesTemplateEventHint: "A page for one event: headline, benefits, steps, questions and the sign-up form.",
|
||||||
|
PagesTemplateShowcase: "Service showcase",
|
||||||
|
PagesTemplateShowcaseHint: "Present a service with benefits, steps and a call to action, ending with the sign-up form.",
|
||||||
|
PagesHasDraft: "Unpublished changes",
|
||||||
|
PagesDraftBanner: "You have unpublished changes. Visitors still see the published version until you publish them.",
|
||||||
|
PagesPublishChanges: "Publish changes",
|
||||||
|
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.",
|
||||||
PagesSaved: "Page saved.",
|
PagesSaved: "Page saved.",
|
||||||
PagesSaveFailed: "Could not save the page. Try again.",
|
PagesSaveFailed: "Could not save the page. Try again.",
|
||||||
PagesNotFound: "Page not found.",
|
PagesNotFound: "Page not found.",
|
||||||
@@ -757,9 +790,60 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
|||||||
PagesBlockFaq: "FAQ",
|
PagesBlockFaq: "FAQ",
|
||||||
PagesBlockForm: "Sign-up form",
|
PagesBlockForm: "Sign-up form",
|
||||||
PagesBlockHtml: "Custom HTML",
|
PagesBlockHtml: "Custom HTML",
|
||||||
|
PagesBlockFeatures: "Feature cards",
|
||||||
|
PagesBlockSteps: "Steps",
|
||||||
|
PagesBlockTrust: "Trust strip",
|
||||||
|
PagesBlockCta: "Call to action",
|
||||||
|
PagesLook: "Look",
|
||||||
|
PagesLookDefault: "Default",
|
||||||
|
PagesLookMuted: "Light grey",
|
||||||
|
PagesLookDark: "Dark",
|
||||||
|
PagesLookAccent: "Company colour",
|
||||||
|
PagesIntro: "Intro",
|
||||||
|
PagesCardN: "Card {number}",
|
||||||
|
PagesStepN: "Step {number}",
|
||||||
|
PagesItemN: "Item {number}",
|
||||||
|
PagesCardIcon: "Icon",
|
||||||
|
PagesCardTitle: "Title",
|
||||||
|
PagesCardText: "Text",
|
||||||
|
PagesAddCard: "Add card",
|
||||||
|
PagesAddStep: "Add step",
|
||||||
|
PagesAddItem: "Add item",
|
||||||
|
PagesRemoveCard: "Remove",
|
||||||
|
PagesIconWifi: "WiFi",
|
||||||
|
PagesIconPhone: "Phone",
|
||||||
|
PagesIconTv: "TV",
|
||||||
|
PagesIconMonitor: "Screen",
|
||||||
|
PagesIconLock: "Lock",
|
||||||
|
PagesIconShieldCheck: "Security",
|
||||||
|
PagesIconCloud: "Cloud",
|
||||||
|
PagesIconWrench: "Service",
|
||||||
|
PagesIconHeadset: "Support",
|
||||||
|
PagesIconUsers: "People",
|
||||||
|
PagesIconCalendar: "Calendar",
|
||||||
|
PagesIconStar: "Star",
|
||||||
|
PagesCardCount: "Use 2 to 6 cards.",
|
||||||
|
PagesBadIcon: "Choose an icon from the list.",
|
||||||
|
PagesBadLook: "Choose a look from the list.",
|
||||||
|
PagesUnusedField: "This section doesn't use this field.",
|
||||||
PagesHtml: "HTML",
|
PagesHtml: "HTML",
|
||||||
PagesHtmlHint: "Forms inside the pasted HTML don't send. Add a Sign-up form block to collect leads.",
|
PagesHtmlHint: "Forms inside the pasted HTML don't send. Add a Sign-up form block to collect leads.",
|
||||||
PagesHideHeader: "Hide page header",
|
PagesHideHeader: "Hide page header",
|
||||||
|
NotificationsTitle: "Notifications",
|
||||||
|
NotificationsUnread: "Notifications, {count} unread",
|
||||||
|
NotificationsEmpty: "No notifications yet.",
|
||||||
|
NotificationsLoadFailed: "Couldn't load notifications.",
|
||||||
|
NotificationsMarkAllRead: "Mark all read",
|
||||||
|
NotificationsSeeAll: "See all",
|
||||||
|
NotificationsUnreadBadge: "Unread",
|
||||||
|
NoticeLeadAssigned: "Lead assigned to you",
|
||||||
|
NoticeWebSignup: "New sign-up",
|
||||||
|
NoticeLeadBody: "{lead} · {event}",
|
||||||
|
NoticeFollowUpDue: "Follow-ups due",
|
||||||
|
NoticeFollowUpBody: "{due} due today, {overdue} overdue",
|
||||||
|
NoticeWhatsappMessage: "New WhatsApp message",
|
||||||
|
NoticeWhatsappBody: "From {name}",
|
||||||
|
NoticeWhatsappBodyNoName: "From a new contact",
|
||||||
PagesMoveUp: "Move up",
|
PagesMoveUp: "Move up",
|
||||||
PagesMoveDown: "Move down",
|
PagesMoveDown: "Move down",
|
||||||
PagesRemoveBlock: "Remove block",
|
PagesRemoveBlock: "Remove block",
|
||||||
@@ -800,7 +884,8 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
|||||||
PagesQuote: "Quote",
|
PagesQuote: "Quote",
|
||||||
PagesDivider: "Divider",
|
PagesDivider: "Divider",
|
||||||
PagesLink: "Link",
|
PagesLink: "Link",
|
||||||
PagesLinkPrompt: "Link address (https://, mailto:, tel: or /)",
|
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",
|
PagesClearFormatting: "Clear formatting",
|
||||||
// Server refusals (the code is the message key; the field says where it shows)
|
// Server refusals (the code is the message key; the field says where it shows)
|
||||||
PagesTooManyBlocks: "A page can have at most 30 blocks.",
|
PagesTooManyBlocks: "A page can have at most 30 blocks.",
|
||||||
@@ -810,7 +895,11 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
|||||||
PagesBadImagePosition: "Choose left or right.",
|
PagesBadImagePosition: "Choose left or right.",
|
||||||
PagesFaqCount: "Add between 1 and 30 questions.",
|
PagesFaqCount: "Add between 1 and 30 questions.",
|
||||||
PagesButtonPair: "Fill in both the button label and the button link, or neither.",
|
PagesButtonPair: "Fill in both the button label and the button link, or neither.",
|
||||||
PagesBadLink: "Use a link that starts with https://, mailto:, tel: or /.",
|
PagesBadLink: "Use a link that starts with https://, mailto:, tel:, / or #.",
|
||||||
|
PagesAnchor: "Link name (optional)",
|
||||||
|
PagesAnchorHint: "Link to this block with #name, for example #signup. Lowercase letters, digits and - only.",
|
||||||
|
PagesBadAnchor: "Use lowercase letters, digits and - (up to 40), starting with a letter or digit and not with reg-.",
|
||||||
|
PagesAnchorTaken: "Another block on this page already has this link name.",
|
||||||
PagesScript: "Scripts and event handlers are not allowed.",
|
PagesScript: "Scripts and event handlers are not allowed.",
|
||||||
PagesBadImage: "Upload the image again.",
|
PagesBadImage: "Upload the image again.",
|
||||||
PagesBadEvent: "Choose one of this company's events.",
|
PagesBadEvent: "Choose one of this company's events.",
|
||||||
|
|||||||
@@ -726,6 +726,39 @@
|
|||||||
"PagesMetaDescription": "搜索引擎描述",
|
"PagesMetaDescription": "搜索引擎描述",
|
||||||
"PagesPreview": "预览",
|
"PagesPreview": "预览",
|
||||||
"PagesPreviewBanner": "预览。网页发布后访客才能看到。",
|
"PagesPreviewBanner": "预览。网页发布后访客才能看到。",
|
||||||
|
"PagesDuplicate": "复制",
|
||||||
|
"PagesDuplicateNamed": "复制 {title}",
|
||||||
|
"PagesChooseStart": "您想如何开始?",
|
||||||
|
"PagesStartBlank": "空白网页",
|
||||||
|
"PagesStartBlankHint": "从空白开始,自行添加区块。",
|
||||||
|
"PagesTemplateEvent": "活动报名",
|
||||||
|
"PagesTemplateEventHint": "为单个活动准备的网页:标题、优势、步骤、常见问题和报名表。",
|
||||||
|
"PagesTemplateShowcase": "服务展示",
|
||||||
|
"PagesTemplateShowcaseHint": "介绍一项服务:优势、步骤和行动号召,最后是报名表。",
|
||||||
|
"PagesHasDraft": "有未发布的修改",
|
||||||
|
"PagesDraftBanner": "您有未发布的修改。发布之前,访客看到的仍是已发布的版本。",
|
||||||
|
"PagesPublishChanges": "发布修改",
|
||||||
|
"PagesDiscardChanges": "放弃修改",
|
||||||
|
"PagesDiscardTitle": "放弃未发布的修改?",
|
||||||
|
"PagesDiscardMessage": "“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。",
|
||||||
|
"PagesLeaveTitle": "不保存就离开?",
|
||||||
|
"PagesLeaveMessage": "此页面的修改尚未保存。离开将丢失这些修改,确定离开吗?",
|
||||||
|
"PagesLeave": "离开",
|
||||||
|
"PagesSaveToUpdate": "保存后更新",
|
||||||
|
"PagesAddSection": "添加区块",
|
||||||
|
"PagesDragSection": "拖动以移动",
|
||||||
|
"PagesDuplicateSection": "复制区块",
|
||||||
|
"PagesPageSettings": "页面设置",
|
||||||
|
"PagesCanvas": "页面画布",
|
||||||
|
"PagesCanvasView": "画布视图",
|
||||||
|
"PagesDesktop": "桌面",
|
||||||
|
"PagesPhone": "手机",
|
||||||
|
"PagesUndo": "撤销",
|
||||||
|
"PagesRedo": "重做",
|
||||||
|
"PagesUntitled": "未命名页面",
|
||||||
|
"PagesChangesPublished": "修改已发布。",
|
||||||
|
"PagesChangesDiscarded": "修改已放弃。",
|
||||||
|
"PagesPreviewDraftBanner": "未发布修改的预览。访客看到的仍是已发布的版本。",
|
||||||
"PagesViewPage": "查看网页",
|
"PagesViewPage": "查看网页",
|
||||||
"PagesSaved": "网页已保存。",
|
"PagesSaved": "网页已保存。",
|
||||||
"PagesSaveFailed": "无法保存网页,请重试。",
|
"PagesSaveFailed": "无法保存网页,请重试。",
|
||||||
@@ -765,8 +798,59 @@
|
|||||||
"PagesFormEventHint": "报名会成为此活动的线索。一般咨询请选择长期的咨询活动。",
|
"PagesFormEventHint": "报名会成为此活动的线索。一般咨询请选择长期的咨询活动。",
|
||||||
"PagesBlockHtml": "自定义 HTML",
|
"PagesBlockHtml": "自定义 HTML",
|
||||||
"PagesHtml": "HTML",
|
"PagesHtml": "HTML",
|
||||||
|
"PagesBlockFeatures": "功能卡片",
|
||||||
|
"PagesBlockSteps": "步骤",
|
||||||
|
"PagesBlockTrust": "信任条",
|
||||||
|
"PagesBlockCta": "行动号召",
|
||||||
|
"PagesLook": "外观",
|
||||||
|
"PagesLookDefault": "默认",
|
||||||
|
"PagesLookMuted": "浅灰",
|
||||||
|
"PagesLookDark": "深色",
|
||||||
|
"PagesLookAccent": "公司主色",
|
||||||
|
"PagesIntro": "简介",
|
||||||
|
"PagesCardN": "卡片 {number}",
|
||||||
|
"PagesStepN": "步骤 {number}",
|
||||||
|
"PagesItemN": "项目 {number}",
|
||||||
|
"PagesCardIcon": "图标",
|
||||||
|
"PagesCardTitle": "标题",
|
||||||
|
"PagesCardText": "文字",
|
||||||
|
"PagesAddCard": "添加卡片",
|
||||||
|
"PagesAddStep": "添加步骤",
|
||||||
|
"PagesAddItem": "添加项目",
|
||||||
|
"PagesRemoveCard": "移除",
|
||||||
|
"PagesIconWifi": "WiFi",
|
||||||
|
"PagesIconPhone": "电话",
|
||||||
|
"PagesIconTv": "电视",
|
||||||
|
"PagesIconMonitor": "屏幕",
|
||||||
|
"PagesIconLock": "门锁",
|
||||||
|
"PagesIconShieldCheck": "安全",
|
||||||
|
"PagesIconCloud": "云端",
|
||||||
|
"PagesIconWrench": "维修服务",
|
||||||
|
"PagesIconHeadset": "客服支持",
|
||||||
|
"PagesIconUsers": "人员",
|
||||||
|
"PagesIconCalendar": "日历",
|
||||||
|
"PagesIconStar": "星标",
|
||||||
|
"PagesCardCount": "请使用 2 至 6 张卡片。",
|
||||||
|
"PagesBadIcon": "请从列表中选择图标。",
|
||||||
|
"PagesBadLook": "请从列表中选择外观。",
|
||||||
|
"PagesUnusedField": "此区块不使用该字段。",
|
||||||
"PagesHtmlHint": "粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。",
|
"PagesHtmlHint": "粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。",
|
||||||
"PagesHideHeader": "隐藏页面顶栏",
|
"PagesHideHeader": "隐藏页面顶栏",
|
||||||
|
"NotificationsTitle": "通知",
|
||||||
|
"NotificationsUnread": "通知,{count} 条未读",
|
||||||
|
"NotificationsEmpty": "暂无通知。",
|
||||||
|
"NotificationsLoadFailed": "无法加载通知。",
|
||||||
|
"NotificationsMarkAllRead": "全部标为已读",
|
||||||
|
"NotificationsSeeAll": "查看全部",
|
||||||
|
"NotificationsUnreadBadge": "未读",
|
||||||
|
"NoticeLeadAssigned": "有新线索分配给你",
|
||||||
|
"NoticeWebSignup": "新的报名",
|
||||||
|
"NoticeLeadBody": "{lead} · {event}",
|
||||||
|
"NoticeFollowUpDue": "待跟进",
|
||||||
|
"NoticeFollowUpBody": "今天到期 {due} 条,已逾期 {overdue} 条",
|
||||||
|
"NoticeWhatsappMessage": "新的 WhatsApp 消息",
|
||||||
|
"NoticeWhatsappBody": "来自 {name}",
|
||||||
|
"NoticeWhatsappBodyNoName": "来自新联系人",
|
||||||
"PagesFormClosed": "报名已截止。",
|
"PagesFormClosed": "报名已截止。",
|
||||||
"PagesFormPreview": "发布后的网页会在此显示报名表。",
|
"PagesFormPreview": "发布后的网页会在此显示报名表。",
|
||||||
"PagesToolbar": "格式",
|
"PagesToolbar": "格式",
|
||||||
@@ -785,7 +869,8 @@
|
|||||||
"PagesQuote": "引用",
|
"PagesQuote": "引用",
|
||||||
"PagesDivider": "分隔线",
|
"PagesDivider": "分隔线",
|
||||||
"PagesLink": "链接",
|
"PagesLink": "链接",
|
||||||
"PagesLinkPrompt": "链接地址(https://、mailto:、tel: 或 /)",
|
"PagesLinkPrompt": "链接地址(https://、mailto:、tel:、/ 或 #名称)",
|
||||||
|
"PagesLinkRefused": "不允许此链接。请使用 https://、mailto:、tel:、以 / 开头的路径或 #名称。",
|
||||||
"PagesClearFormatting": "清除格式",
|
"PagesClearFormatting": "清除格式",
|
||||||
"PagesTooManyBlocks": "每个网页最多 30 个区块。",
|
"PagesTooManyBlocks": "每个网页最多 30 个区块。",
|
||||||
"PagesUnknownType": "不支持此区块类型。",
|
"PagesUnknownType": "不支持此区块类型。",
|
||||||
@@ -794,7 +879,11 @@
|
|||||||
"PagesBadImagePosition": "请选择左或右。",
|
"PagesBadImagePosition": "请选择左或右。",
|
||||||
"PagesFaqCount": "请添加 1 至 30 个问题。",
|
"PagesFaqCount": "请添加 1 至 30 个问题。",
|
||||||
"PagesButtonPair": "按钮文字和按钮链接需同时填写或同时留空。",
|
"PagesButtonPair": "按钮文字和按钮链接需同时填写或同时留空。",
|
||||||
"PagesBadLink": "链接须以 https://、mailto:、tel: 或 / 开头。",
|
"PagesBadLink": "链接须以 https://、mailto:、tel:、/ 或 # 开头。",
|
||||||
|
"PagesAnchor": "链接名称(可选)",
|
||||||
|
"PagesAnchorHint": "用 #名称 链接到此区块,例如 #signup。仅限小写字母、数字和 -。",
|
||||||
|
"PagesBadAnchor": "请使用小写字母、数字和 -(最多 40 个),以字母或数字开头,且不能以 reg- 开头。",
|
||||||
|
"PagesAnchorTaken": "本页已有其他区块使用此链接名称。",
|
||||||
"PagesScript": "不允许使用脚本或事件处理程序。",
|
"PagesScript": "不允许使用脚本或事件处理程序。",
|
||||||
"PagesBadImage": "请重新上传图片。",
|
"PagesBadImage": "请重新上传图片。",
|
||||||
"PagesBadEvent": "请选择本公司的活动。",
|
"PagesBadEvent": "请选择本公司的活动。",
|
||||||
|
|||||||
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user