Compare commits

...
Author SHA1 Message Date
ngqileandClaude Opus 5.5 cc2d1c794e docs: archive add-landing-page-polish
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 12:28:28 +08:00
ngqile c21a31e10f Merge pull request 'feat(pages): a top bar section, section labels and serif headings' (#80) from add-landing-page-polish into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 04:28:21 +00:00
ngqileandClaude Opus 5.5 e4ad18a8a3 feat(pages): a top bar section, section labels and serif headings
Landing pages gain a Top bar section (the company logo and an optional button,
kept at the top of the window, first section only), a short label above the
headings of five section types, and serif section headings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 12:28:09 +08:00
ngqile 2a69826e66 Merge pull request 'docs: archive add-landing-thanks-and-footer' (#79) from archive-landing-thanks-and-footer into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 03:45:57 +00:00
ngqileandClaude Opus 5.5 92412cb300 docs: archive add-landing-thanks-and-footer
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 11:45:49 +08:00
ngqile 35e9b796f7 Merge pull request 'feat(pages): a footer section with contact links, and a thank-you text on landing forms' (#78) from add-landing-thanks-and-footer into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 03:45:38 +00:00
ngqileandClaude Opus 5.5 3446f261be feat(pages): a footer section with contact links, and a thank-you text on landing forms
Landing pages gain a Footer section (1 to 4 columns of title and text, a legal
line under a divider) whose phone numbers, emails and web addresses show as
links. The Form block and a hero with a form may carry a thank-you text shown
after sign-up, with the same links. Full-width heroes get a lighter shade.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 11:45:25 +08:00
ngqile 5a1aa447d5 Merge pull request 'docs: archive add-compact-landing-form' (#77) from archive-compact-landing-form into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 02:47:28 +00:00
ngqileandClaude Opus 5.5 2697a591aa docs: archive add-compact-landing-form
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 10:47:20 +08:00
ngqile 23840e8fbf Merge pull request 'feat(pages): a short sign-up form on landing pages, and coloured sections join' (#76) from add-compact-landing-form into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 02:47:12 +00:00
ngqileandClaude Opus 5.5 ba6ab7554d feat(pages): a short sign-up form on landing pages, and coloured sections join
Landing-page forms drop job title, ask for one service in a dropdown and fold the
privacy notice behind one line above the consent box. QR, invitation and customer
forms keep the full form. Sections with a colour look join with no gap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 10:47:02 +08:00
ngqile a7129b417e Merge pull request 'docs: archive add-html-image-upload' (#75) from archive-html-image-upload into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 02:10:43 +00:00
ngqileandClaude Opus 5.5 a83752c34e docs: archive add-html-image-upload
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 10:10:35 +08:00
ngqile bba99993cb Merge pull request 'feat(pages): upload an image from a Custom HTML block and copy its link' (#74) from add-html-image-upload into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 02:10:26 +00:00
ngqileandClaude Opus 5.5 1136046fc2 feat(pages): upload an image from a Custom HTML block and copy its link
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 10:10:15 +08:00
ngqile 44eace2bcb Merge pull request 'docs: archive add-hero-full-width' (#73) from archive-hero-full-width into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 01:47:05 +00:00
ngqileandClaude Opus 5.5 dc5cfd1c54 docs: archive add-hero-full-width
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 09:46:57 +08:00
ngqile fae25c11a6 Merge pull request 'feat(pages): a hero can run full width with points and a form card heading' (#72) from add-hero-full-width into main
CI / build-and-publish (push) Failing after 0s
2026-12-04 01:46:44 +00:00
ngqileandClaude Opus 5.5 b55b8d2d86 feat(pages): a hero can run full width with points and a form card heading
A full-width hero spans the window with a larger serif headline and a lighter
left-to-right shade. It may list up to 6 points and give its form card a heading
and text. Full-width neighbours join with no gap. Custom HTML frames now shrink
to 20 px and re-report their height when the page asks, so a short top bar no
longer leaves a blank band.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 09:46:32 +08:00
ngqile dbb58e6e94 Merge pull request 'fix(pages): a short Custom HTML block shrinks to its content height' (#71) from fix-frame-content-height into main
CI / build-and-publish (push) Failing after 0s
2026-12-03 12:07:10 +00:00
60 changed files with 2245 additions and 102 deletions

No files matched your search

+10
View File
@@ -466,4 +466,14 @@ A form stops taking sign-ups when its event is disabled, its end date has passed
**Release add-hero-signup-form (SQL, in its OpenSpec change folder):** deploy services-counter, mobile-api and the portal (any order), then run `sql/01-hero-form-labels.sql` (labels only). A hero section can now carry the sign-up form for an event, beside its text. Rollback: the previous images. A hero saved with an event keeps it in its JSON. The old code ignores it and shows the hero without a form, so add a Sign-up form section to those pages if you roll back.
**Release add-hero-full-width (SQL, in its OpenSpec change folder):** deploy services-counter, then the portal, then run `sql/01-hero-full-width-labels.sql` (labels only). Deploy services-counter first, because the portal's editor saves the new hero fields. A hero can now run full width, carry bullet points, and give its form card a heading. Custom HTML frames now shrink to fit short content and no longer leave a gap next to a full-width hero. Rollback: the previous images. Saved heroes keep the new fields in their JSON; the old code ignores them and shows the boxed hero. The old services-counter refuses to save a hero that has points or a form heading, so remove them before saving such a page.
**Release add-html-image-upload (SQL, in its OpenSpec change folder):** deploy the portal, then run `sql/01-html-image-labels.sql` (labels only). A Custom HTML block's panel can now upload an image and show its link to copy. Rollback: the previous portal image.
**Release add-compact-landing-form (SQL, in its OpenSpec change folder):** deploy the portal, then run `sql/01-compact-form-labels.sql` (labels only). Landing-page sign-up forms drop job title, ask for one service in a dropdown, and fold the privacy notice behind one line. Coloured sections now join with no gap. QR, invitation and customer forms are unchanged. Before go-live, the PDPA owner should confirm the folded notice. Rollback: the previous portal image.
**Release add-landing-thanks-and-footer (SQL, in its OpenSpec change folder):** deploy services-counter and the portal together, then run `sql/01-thanks-footer-labels.sql` (labels only). Landing pages gain a Footer section (1 to 4 columns, a legal line, contact links) and a thank-you text on the Form block and on a hero with a form. Full-width heroes get a lighter shade. Deploy the counter first: an older counter refuses pages that use the new fields. Rollback: the previous images; pages saved with a Footer or thank-you text then fail to save until the release is back.
**Release add-landing-page-polish (SQL, in its OpenSpec change folder):** deploy services-counter first, then the portal, then run `sql/01-polish-labels.sql` (labels only). Landing pages gain a Top bar section (the company logo and an optional button, kept at the top of the window, first section only) and an optional small label above the headings of Feature cards, Steps, Image with text, FAQ and Call to action. Section headings on every landing page, CV included, now use the serif typeface. Rollback: the previous images; pages saved with a top bar or labels then fail to save until the release is back.
**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.
+36
View File
@@ -1117,6 +1117,12 @@ INSERT INTO message (code, content, area) SELECT 'RegCompany', JSON_OBJECT('en_U
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '公司') WHERE LOWER(code) = LOWER('RegCompany') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'RegJobTitle', JSON_OBJECT('en_US', 'Job title', 'zh_CN', '职位'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegJobTitle') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '职位') WHERE LOWER(code) = LOWER('RegJobTitle') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'RegServiceInterest', JSON_OBJECT('en_US', 'Service interested in (optional)', 'zh_CN', '感兴趣的服务(可选)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegServiceInterest') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '感兴趣的服务(可选)') WHERE LOWER(code) = LOWER('RegServiceInterest') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'RegChooseService', JSON_OBJECT('en_US', 'Choose a service', 'zh_CN', '选择服务'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegChooseService') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '选择服务') WHERE LOWER(code) = LOWER('RegChooseService') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'RegNoticeSummary', JSON_OBJECT('en_US', 'How we use your details (English / Bahasa Malaysia)', 'zh_CN', '我们如何使用您的资料(English / Bahasa Malaysia)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegNoticeSummary') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '我们如何使用您的资料(English / Bahasa Malaysia)') WHERE LOWER(code) = LOWER('RegNoticeSummary') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'RegInterests', JSON_OBJECT('en_US', 'Interests (optional)', 'zh_CN', '兴趣(可选)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegInterests') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '兴趣(可选)') WHERE LOWER(code) = LOWER('RegInterests') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'RegNoticeEn', JSON_OBJECT('en_US', 'English', 'zh_CN', '英文'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegNoticeEn') AND area = 'A');
@@ -1717,6 +1723,36 @@ INSERT INTO message (code, content, area) SELECT 'PagesHeroForm', JSON_OBJECT('e
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '报名表单') WHERE LOWER(code) = LOWER('PagesHeroForm') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesNoForm', JSON_OBJECT('en_US', 'No form', 'zh_CN', '不显示表单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesNoForm') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不显示表单') WHERE LOWER(code) = LOWER('PagesNoForm') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesFullWidth', JSON_OBJECT('en_US', 'Full width', 'zh_CN', '全宽'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFullWidth') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '全宽') WHERE LOWER(code) = LOWER('PagesFullWidth') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesPointN', JSON_OBJECT('en_US', 'Point {number}', 'zh_CN', '要点 {number}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPointN') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '要点 {number}') WHERE LOWER(code) = LOWER('PagesPointN') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesAddPoint', JSON_OBJECT('en_US', 'Add point', 'zh_CN', '添加要点'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddPoint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加要点') WHERE LOWER(code) = LOWER('PagesAddPoint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesFormHeading', JSON_OBJECT('en_US', 'Form heading', 'zh_CN', '表单标题'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormHeading') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '表单标题') WHERE LOWER(code) = LOWER('PagesFormHeading') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesFormText', JSON_OBJECT('en_US', 'Form text', 'zh_CN', '表单说明'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormText') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '表单说明') WHERE LOWER(code) = LOWER('PagesFormText') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesThanksText', JSON_OBJECT('en_US', 'Thank-you text', 'zh_CN', '感谢语'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesThanksText') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '感谢语') WHERE LOWER(code) = LOWER('PagesThanksText') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesBlockFooter', JSON_OBJECT('en_US', 'Footer', 'zh_CN', '页脚'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockFooter') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '页脚') WHERE LOWER(code) = LOWER('PagesBlockFooter') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesColumnN', JSON_OBJECT('en_US', 'Column {number}', 'zh_CN', '第 {number} 栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesColumnN') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '第 {number} 栏') WHERE LOWER(code) = LOWER('PagesColumnN') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesAddColumn', JSON_OBJECT('en_US', 'Add column', 'zh_CN', '添加栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddColumn') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加栏') WHERE LOWER(code) = LOWER('PagesAddColumn') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesFooterLegal', JSON_OBJECT('en_US', 'Legal line', 'zh_CN', '版权声明'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFooterLegal') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '版权声明') WHERE LOWER(code) = LOWER('PagesFooterLegal') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesBlockTopBar', JSON_OBJECT('en_US', 'Top bar', 'zh_CN', '顶栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockTopBar') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '顶栏') WHERE LOWER(code) = LOWER('PagesBlockTopBar') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesEyebrow', JSON_OBJECT('en_US', 'Label', 'zh_CN', '小标签'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesEyebrow') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '小标签') WHERE LOWER(code) = LOWER('PagesEyebrow') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTopBarFirst', JSON_OBJECT('en_US', 'The top bar must be the first section.', 'zh_CN', '顶栏必须是第一个区块。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTopBarFirst') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '顶栏必须是第一个区块。') WHERE LOWER(code) = LOWER('PagesTopBarFirst') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesUploadImage', JSON_OBJECT('en_US', 'Upload image', 'zh_CN', '上传图片'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUploadImage') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '上传图片') WHERE LOWER(code) = LOWER('PagesUploadImage') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesUploadImageHint', JSON_OBJECT('en_US', 'PNG, JPEG or WebP up to 2 MB. Paste the link into your HTML, for example in an img tag''s src.', 'zh_CN', 'PNG、JPEG 或 WebP,最大 2 MB。将链接粘贴到您的 HTML 中,例如 img 标签的 src。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUploadImageHint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', 'PNG、JPEG 或 WebP,最大 2 MB。将链接粘贴到您的 HTML 中,例如 img 标签的 src。') WHERE LOWER(code) = LOWER('PagesUploadImageHint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesToolbar', JSON_OBJECT('en_US', 'Formatting', 'zh_CN', '格式'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesToolbar') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '格式') WHERE LOWER(code) = LOWER('PagesToolbar') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTextStyle', JSON_OBJECT('en_US', 'Text style', 'zh_CN', '文字样式'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTextStyle') AND area = 'A');
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-04
@@ -0,0 +1,44 @@
# Proposal
## Why
The INS sign-up form on the standalone landing page is short: full name, email, phone, company, a single "service" dropdown and the button. Co-Lite's landing-page form is roughly three times as long. Most of that comes from three things: the full English and Malay privacy notice shown in the form, five interest checkboxes, and a job-title field that INS does not ask for. On the rebuilt Hotel technology page, the form card is taller than two screens.
The coloured sections at the end of the page have a second problem: they are separated by pale gaps. The dark call to action and the dark footer therefore read as two footers.
The owner chose the following on 2026-12-04: a collapsed privacy notice, one interest as a dropdown, and no job title on landing pages.
## What Changes
- **Landing-page forms are compact.** This covers the FORM block and a hero's form; QR, invitation and customer sign-up forms are unchanged.
- The interests are a single optional dropdown ("Service interested in"), so a submission carries at most one interest.
- There is no job-title field.
- The privacy notice is folded behind one line, "How we use your details (English / Bahasa Malaysia)", just above the consent box. It opens to the full bilingual notice.
- The consent box itself and its wording do not change.
- **Coloured sections join.** A block with a non-default look (light grey, dark or company colour) counts as full width, like Custom HTML and the full-width hero. Two such blocks next to each other join with no gap.
Not changing:
- The server: it already accepts a submission without a job title and with zero or one interest.
- The QR, invitation and customer forms.
- The notice text, which consent still covers.
## Capabilities
### New Capabilities
None.
### Modified Capabilities
- `landing-pages`:
- modifies "Full-Width Blocks Join Without Gaps";
- adds "Compact Landing-Page Form".
## Impact
- Portal:
- `RegistrationForm.tsx` gains a `compact` option;
- `LandingForm.tsx` passes it;
- `CmsBlocks.tsx` extends `bleeds()` to banded looks;
- new labels.
- The compliance owner should confirm that a folded notice next to the consent box meets PDPA. The owner was told this when they chose it.
@@ -0,0 +1,45 @@
## ADDED Requirements
### Requirement: Compact Landing-Page Form
A landing page's sign-up form, in a FORM block or a hero, SHALL show name, mobile, email and company, the event's interests as one optional dropdown, the privacy notice folded behind a single line that opens it in full, and the consent box. It SHALL NOT show a job-title field. QR, invitation and customer sign-up forms SHALL keep their full layout.
#### Scenario: Short form on the page
- **GIVEN** a page whose hero has an event with five interests
- **WHEN** a visitor opens the page
- **THEN** the form shows name, mobile, email, company, a "Service interested in" dropdown and the consent box, with no job title and no interest checkboxes
- **AND** the privacy notice is folded behind "How we use your details"
#### Scenario: Pick one service
- **WHEN** the visitor chooses "Cloud IP PABX" in the dropdown and submits
- **THEN** the submission carries that one interest
#### Scenario: Read the notice
- **WHEN** the visitor opens "How we use your details"
- **THEN** the full English and Malay notice shows above the consent box
#### Scenario: QR form unchanged
- **WHEN** a visitor opens an event's QR sign-up form
- **THEN** it shows job title, the interest checkboxes and the full notice as before
## MODIFIED Requirements
### Requirement: Full-Width Blocks Join Without Gaps
A full-width HERO, a Custom HTML block, and a block with a non-default look SHALL join with no gap when two of them are next to each other. Other blocks SHALL keep their usual spacing.
#### Scenario: Top bar runs straight into the hero
- **GIVEN** a Custom HTML top bar followed by a full-width HERO
- **WHEN** a visitor opens the page
- **THEN** the hero starts directly under the top bar, with no gap
#### Scenario: Dark call to action runs into a dark footer
- **GIVEN** a CTA block with the Dark look followed by a text block with the Dark look
- **WHEN** a visitor opens the page
- **THEN** the two bands join with no gap between them
@@ -0,0 +1,9 @@
-- The labels added by add-compact-landing-form, 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 'RegServiceInterest', JSON_OBJECT('en_US', 'Service interested in (optional)', 'zh_CN', '感兴趣的服务(可选)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegServiceInterest') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '感兴趣的服务(可选)') WHERE LOWER(code) = LOWER('RegServiceInterest') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'RegChooseService', JSON_OBJECT('en_US', 'Choose a service', 'zh_CN', '选择服务'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegChooseService') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '选择服务') WHERE LOWER(code) = LOWER('RegChooseService') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'RegNoticeSummary', JSON_OBJECT('en_US', 'How we use your details (English / Bahasa Malaysia)', 'zh_CN', '我们如何使用您的资料(English / Bahasa Malaysia)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('RegNoticeSummary') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '我们如何使用您的资料(English / Bahasa Malaysia)') WHERE LOWER(code) = LOWER('RegNoticeSummary') AND area = 'A';
@@ -0,0 +1,39 @@
# Tasks
## 1. Portal
- [x] 1.1 `RegistrationForm` `compact` option, passed by `LandingForm`:
- no job title;
- interests in one optional `<select>` ("Service interested in", first option "Choose a service"), which sets `interestIds` to `[]` or `[id]`;
- the notice inside a `<details>` with the summary "How we use your details (English / Bahasa Malaysia)", just above the consent box.
Verify: tests for the landing form (fields, one interest posted, the notice folded and openable) and for the QR form (unchanged) fail first, then pass.
- [x] 1.2 `CmsBlocks.tsx` `bleeds()`: a block with a non-default look counts too. Verify: a render test (a dark CTA followed by a dark text block has no gap) fails first, then passes.
- [x] 1.3 Add the labels (`RegServiceInterest`, `RegChooseService`, `RegNoticeSummary`) to `defaultMessages.ts`, `zh_CN.seed.json` and `sql/01-compact-form-labels.sql`, and regenerate the local seed.
## 2. Verification
- [x] 2.1 Use Playwright on port 3001 for `/p/INS/hotel-technology-native` at 1280 px and 390 px:
- check the short form;
- check that the notice opens;
- check that the closing bands join;
- check that an event's QR form (opened from Events) still shows the full form.
- [x] 2.2 Run the full vitest (exit 0), tsc, lint and `openspec validate --strict`. Add a release note.
## Notes (2026-12-04)
- **Red first:**
- the compact-form tests (fields, one service posted, the notice folded) and the band-join test failed first;
- the full-form test passed from the start, as the baseline it guards.
- **Live check** on `/p/INS/hotel-technology-native` (port 3001):
- the hero form shows name, mobile, email, company and "Service interested in", with no job title;
- the notice opens from "How we use your details";
- the hero runs into the trust strip;
- the dark call to action and the dark footer join into one ending.
- **Fix from the live check:** joined bands had lost their colour. `Section` treated every joining block as a full-width hero. Now only a full-width hero skips the page width, and the band test also checks the colour.
- **Not checked live:** the QR form staying full. The `RegistrationForm` test covers it (job title, checkboxes, notice open).
- **Results:** vitest 2002 passed (exit 0); tsc clean; lint 0 errors (the 4 warnings were already there).
## Workflow follow-up
- Open a PR to `main` and merge it. Archive the change on its own branch, with its own PR.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-04
@@ -0,0 +1,25 @@
# Design
## Context
The HERO block renders inside `Section`, which wraps every non-HTML block in the page width (`max-w-5xl px-4`). The page's block list is `space-y-10`. Custom HTML blocks already render outside `Section`, so they run full width. The hero-with-form layout comes from add-hero-signup-form.
## Approaches
1. **A `fullWidth` option on HERO (chosen).** Explicit and opt-in, so existing heroes and templates do not change. It costs one boolean and one switch in the editor.
2. **Make every hero with a form full width.** This needs no new field, but it silently changes existing pages and ties two unrelated choices together.
3. **Build the hero in Custom HTML.** This cannot work: a sealed frame cannot hold the real sign-up form (see add-hero-signup-form).
## Decisions
- **Points reuse `cards`.** They use title-only cards, as the trust strip does. The DTO does not change, and the editor reuses the trust strip's item list (`PagesItemN`, `PagesAddItem`). On a HERO the validator allows 0 to 6 cards. FEATURES, STEPS and TRUST keep their 2 to 6 rule.
- **Joins.** A block counts as "bleed" when it is HTML, or when it is a full-width HERO. When a block and the block before it are both bleed, the block gets no top margin. Two Custom HTML blocks next to each other therefore join as well. That changes current pages, but only toward what Custom HTML sections expect: built sections are designed to stack.
- **A full-width hero is not wrapped in `Section`.** It renders outside the page width, in the same way as `HtmlSpot`. Its inner content uses a wider container (`max-w-6xl px-4`).
- **Font.** The headline uses Tailwind's `font-serif`, the system serif. No web font is added, so there is no new dependency and no third-party request.
- **Shade.** The full-width shade is a left-to-right gradient, from `black/75` through `black/45` to `black/10`. It stays black-based, because the design-token test refuses raw colours, and the white text sits on the dark side. On phones the layout stacks and the form card is solid, so contrast holds.
- **Form heading and text.** These are plain text fields edited with `Text` in place, in the same way as the hero heading. They are refused on a hero without an event, so they cannot hide in saved data.
## Risks
- **Contrast with a light photo on the right.** The text sits on the left, over the darkest part of the shade, and the right side holds the solid form card. This is acceptable.
- **Editor controls on the edge.** On the full-width canvas, the image button and the toolbar sit at the window's edge. They are already positioned inside the section by the PR #66 fix.
@@ -0,0 +1,59 @@
# Proposal
## Why
The INS Hotel technology page is being rebuilt in Co-Lite to match INS's standalone landing page (`~/Projects/ins-landing-page`). Since add-hero-signup-form, the form sits beside the hero text, but the hero still looks unlike the original in five ways:
- it is a rounded box inside the page width, with grey space around it, where the original runs edge to edge directly under the top bar;
- its shade is near-black over the whole photo, where the original fades from dark on the left to a clear photo on the right;
- its headline is small and pinned to the top, where the original's is large, serif and vertically centred;
- it has no bullet points under the text;
- the form card has no title or subtitle ("Get a free consultation" / "Tell us about your property…").
Marketing staff cannot fix any of these from the editor.
## What Changes
- A HERO block gains a **Full width** option (`fullWidth`). A full-width hero:
- spans the whole window, with square corners and no page margin;
- is taller, with a larger serif headline, vertically centred;
- uses a lighter shade that runs from dark on the left to almost clear on the right.
- Full-width heroes and Custom HTML blocks that sit next to each other join with no gap, so a Custom HTML top bar runs straight into the hero.
- Custom HTML frames (found in the live check):
- they may shrink to 20 px instead of 100 px, so a 68 px top bar leaves no blank band;
- the page asks each frame for its height once it listens and when the frame loads, because the frame's first report could arrive before the page was ready, leaving it at 600 px.
- A HERO block may carry up to 6 **points**, short title-only lines (`cards`, 80 characters each) shown as a bullet list under its text. The editor reuses the trust strip's item list.
- A HERO with an event may carry a **form heading** (`formHeading`, 80 characters) and **form text** (`formText`, 200 characters), shown at the top of the form card. Both can be typed in place on the canvas.
- The server validates the new fields:
- `fullWidth` is a boolean;
- the hero takes 0 to 6 points, each a non-empty title of at most 80 characters, with no icon or text;
- the form heading and form text are refused on a hero without an event.
- New editor labels in English and Chinese, with an SQL label file for real environments.
Not changing:
- The heroes that exist today. Without the option they look as they do now.
- The sign-up form's fields, the privacy notice and the consent box. They are shared with QR sign-up, and the notice and consent are required by the data-protection rules.
- Field labels and the interests checkboxes.
- The submit button colour, which follows the company's accent colour. For INS's gold button, set INS's accent colour in Companies; that is a setting, not code.
- The red wave decoration at the bottom of the INS hero, which is left out.
## Capabilities
### New Capabilities
None.
### Modified Capabilities
- `landing-pages`: adds "Full-Width Hero", "Hero Points" and "Hero Form Heading".
## Impact
- services-counter: `CmsBlock` gains `fullWidth`, `formHeading` and `formText`. `CmsBlockValidator` lets a HERO carry `cards` as points and checks the new fields.
- mobile-api: none. Public blocks pass through as maps.
- Portal:
- `CmsBlocks.tsx` renders the hero layout and the joins between full-width blocks;
- `BlockFields.tsx` gets the Full width switch, the points list and the form heading and text;
- `cmsPages.ts` gets the types;
- new labels in `defaultMessages.ts` and `zh_CN.seed.json`.
- Data: no schema change, because the blocks are JSON. The new labels need a SQL label file in this change folder for real environments.
@@ -0,0 +1,86 @@
## ADDED Requirements
### Requirement: Full-Width Hero
A HERO block MAY be marked full width. A full-width hero SHALL span the whole window with square corners, show its heading larger and centred top to bottom in the hero's opening height (not beside a long form), and use a shade that is darker on the text side than on the far side. A hero that is not marked full width SHALL look as it did before. The server SHALL refuse a `fullWidth` value that is not true or false.
#### Scenario: Hero runs edge to edge under a Custom HTML top bar
- **GIVEN** page `/p/INS/hotel-technology` with a Custom HTML top bar followed by a full-width HERO with an image and an event
- **WHEN** a visitor opens the page in a 1280 px window
- **THEN** the hero spans the full window width
- **AND** the form card sits beside the heading
#### Scenario: Existing hero unchanged
- **WHEN** a visitor opens a page whose HERO block is not marked full width
- **THEN** the hero sits inside the page width with rounded corners, as before
#### Scenario: Turn on full width in the editor
- **GIVEN** staff editing a page with a HERO block
- **WHEN** they switch on "Full width" in the hero's settings
- **THEN** the canvas shows the hero across the full width
### Requirement: Full-Width Blocks Join Without Gaps
A full-width HERO and a Custom HTML block next to each other SHALL join with no gap between them, and so SHALL two Custom HTML blocks next to each other. Other blocks SHALL keep their usual spacing.
#### Scenario: Top bar runs straight into the hero
- **GIVEN** a Custom HTML top bar followed by a full-width HERO
- **WHEN** a visitor opens the page
- **THEN** the hero starts directly under the top bar, with no gap
### Requirement: Hero Points
A HERO block MAY carry up to 6 points, each a non-empty title of at most 80 characters, with no icon and no text. The hero SHALL show its points as a bulleted list under its text. The server SHALL refuse more than 6 points, an empty or over-long point, and a point with an icon or text, naming the field.
#### Scenario: Points under the hero text
- **GIVEN** a HERO block with points "One accountable partner instead of five vendors" and "Local support team in Malaysia"
- **WHEN** a visitor opens the page
- **THEN** both points show as a bulleted list under the hero text
#### Scenario: Too many points refused
- **WHEN** staff save a HERO block with 7 points
- **THEN** the save is refused at `blocks[n].cards`
### Requirement: Hero Form Heading
A HERO block with an event MAY carry a form heading of at most 80 characters and a form text of at most 200 characters. The hero SHALL show them at the top of its form card, above the form. The server SHALL refuse either on a hero without an event. On the canvas, staff SHALL be able to type both in place.
#### Scenario: Card shows its heading
- **GIVEN** a HERO block with an event, form heading "Get a free consultation" and form text "Tell us about your property. It takes under a minute."
- **WHEN** a visitor opens the page
- **THEN** the form card starts with that heading and text, followed by the form
#### Scenario: Form heading without a form refused
- **WHEN** staff save a HERO block with a form heading and no event
- **THEN** the save is refused at `blocks[n].formHeading`
## MODIFIED Requirements
### Requirement: Custom HTML Frame Height
The frame SHALL grow or shrink to fit its content, between 20 and 20000 pixels, using height reports sent by that frame only. Before the first report it SHALL be 600 pixels tall. The frame SHALL report the height of its content, not of its own window, and SHALL report again whenever the page asks, which the page SHALL do once it listens and when the frame loads.
#### 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: A short top bar shrinks the frame
- **GIVEN** a published HTML block holding only a 68 pixel top bar
- **WHEN** a visitor opens the page, even if the frame loaded before the page was ready
- **THEN** the frame is 68 pixels tall, with no blank space below the 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
@@ -0,0 +1,13 @@
-- The labels added by add-hero-full-width, 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 'PagesFullWidth', JSON_OBJECT('en_US', 'Full width', 'zh_CN', '全宽'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFullWidth') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '全宽') WHERE LOWER(code) = LOWER('PagesFullWidth') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesPointN', JSON_OBJECT('en_US', 'Point {number}', 'zh_CN', '要点 {number}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPointN') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '要点 {number}') WHERE LOWER(code) = LOWER('PagesPointN') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesAddPoint', JSON_OBJECT('en_US', 'Add point', 'zh_CN', '添加要点'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddPoint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加要点') WHERE LOWER(code) = LOWER('PagesAddPoint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesFormHeading', JSON_OBJECT('en_US', 'Form heading', 'zh_CN', '表单标题'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormHeading') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '表单标题') WHERE LOWER(code) = LOWER('PagesFormHeading') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesFormText', JSON_OBJECT('en_US', 'Form text', 'zh_CN', '表单说明'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormText') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '表单说明') WHERE LOWER(code) = LOWER('PagesFormText') AND area = 'A';
@@ -0,0 +1,69 @@
# Tasks
## 1. Server
- [x] 1.1 services-counter `CmsBlock`: add `fullWidth` (Boolean), `formHeading` and `formText`. `CmsBlockValidator` HERO rules:
- allow `cards` on a HERO, 0 to 6 of them, each with a title that is required and at most 80 characters, and no icon or text;
- `formHeading` at most 80 characters and `formText` at most 200;
- refuse `formHeading` or `formText` without `eventUuid` (`PagesUnusedField`).
Verify: new validator tests fail first, then pass; `mvn -T 1C -pl solvway-services-counter verify`.
## 2. Portal
- [x] 2.1 `cmsPages.ts` types. In `CmsBlocks.tsx`:
- the HERO shows its points as a bulleted list;
- the form card shows `formHeading` and `formText`, editable in place;
- a full-width HERO renders outside the page width, with a larger serif heading, vertical centring and the lighter left-to-right shade;
- adjacent bleed blocks (HTML, or a full-width HERO) get no gap between them.
Verify: render tests fail first, then pass; vitest exit 0.
- [x] 2.2 `BlockFields.tsx`:
- the Hero gets a "Full width" switch, the points list (reusing the trust strip's item list), and the form heading and text fields, shown only when an event is picked;
- `INLINE.HERO` includes `formHeading`, `formText` and the points;
- add the labels to `defaultMessages.ts`, `zh_CN.seed.json` and `sql/01-hero-full-width-labels.sql`, and regenerate `local/seed/04-zh-cn-messages.sql`.
Verify: editor tests fail first, then pass; tsc and lint clean.
## 3. Verification
- [x] 3.1 Rebuild services-counter. Use Playwright on port 3001 to edit `/p/INS/hotel-technology` through the editor:
- turn on Full width;
- add the three INS points;
- set the form heading and text;
- publish the page.
Then check the published page at 1280 px and 390 px against the INS page, and check a save with 7 points shows the refusal on the canvas.
- [x] 3.2 Run the full portal vitest (exit 0), tsc, lint, Maven verify for services-counter, and `openspec validate add-hero-full-width --strict`.
- [x] 3.3 Add a release note to `docs/deployment.md` (label SQL).
## Notes (2026-12-04)
- **Red first:**
- the validator tests failed on points and the form heading;
- the render tests failed on full width, points, the card heading and the joins;
- the editor and company-switch tests failed;
- the frame floor, ask and answer tests failed.
- **Changed existing tests:**
- `CmsBlocks.html.test.tsx` "starts a header-less page flush at the top" now checks that the first block row has no top margin. It used to check for a `space-y` class, which is no longer how spacing works. It still asserts that the hidden title is outside the spacing.
- `frameHtml.test.ts` clamp test: the floor is now 20 px, per the modified "Custom HTML Frame Height" requirement. It also checks that 68 stays 68.
- **Live check** (port 3001, rebuilt counter), on `/p/INS/hotel-technology` through the editor:
- Full width switched on;
- three points and the form heading and text typed on the canvas;
- saved and published.
- **Published result at 1280 px:**
- the hero runs flush under the top bar and into the rest of the page;
- the serif headline is centred in the first screen;
- the points show in the accent colour, and the card has its heading.
- **Published result at 390 px:** the layout stacks, with the card below the text.
- **Fixes from the live check:**
- the text is centred in the opening height, not beside the long form;
- the frame floor is 20 px;
- the page asks frames for their height (both added to the spec).
- **Not reachable in the UI, covered by the validator tests:**
- 7 points, because Add point stops at 6;
- a form heading without a form, because No form clears it.
## Workflow follow-up
- Open a PR to `main` and merge it. Archive the change on its own branch, with its own PR.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-04
@@ -0,0 +1,44 @@
# Proposal
## Why
Custom HTML blocks hold whole designed sections, such as the INS Hotel technology page. Their images must be served from somewhere. Today the only way to get an image link is to upload it as a hero image and read its id back, or to ask a developer. Marketing staff need to upload an image from the Custom HTML block itself and get a link they can paste into their HTML.
## What Changes
- The Custom HTML block's panel gains an **Upload image** file picker. Choosing a file uploads it at once, for the page's company, with the same checks as every page image:
- PNG, JPEG or WebP;
- at most 2 MB;
- the type is checked by the file's content.
- Each upload made while the panel is open shows:
- a small preview;
- its link (`/api/public/page-images/<id>`) in a read-only box;
- a **Copy link** button.
- A refused upload shows its reason under the picker.
- A new page with no company chosen yet asks for one first.
- The link is relative, so it works on the published page and inside the sealed frame. The INS top bar's logo already loads this way.
Not changing:
- The server. The existing `POST /api/pages/images` upload and the public image address are used as they are.
- Saving. The upload does not touch the page's HTML; staff paste the link where they want it.
- Unused images. They stay stored, as an unused hero upload would. Clean-up is left for later.
- The list of uploads, which is not saved. It shows this session's uploads only.
## Capabilities
### New Capabilities
None.
### Modified Capabilities
- `landing-pages`: adds "Image Upload For Custom HTML".
## Impact
- Portal:
- `BlockFields.tsx`, the HTML block panel;
- the editor passes the page's company to the panel (or the panel reads it from the draft hook);
- `uploadPageImage` already exists.
- New labels in `defaultMessages.ts` and `zh_CN.seed.json`, a regenerated local seed, and a SQL label file in this change folder.
- No server or schema change.
@@ -0,0 +1,23 @@
## ADDED Requirements
### Requirement: Image Upload For Custom HTML
A Custom HTML block's panel in the editor SHALL offer an image upload for the page's company, under the same checks as other page images. On success it SHALL show the image's preview and its public link with a copy button; on refusal it SHALL show the reason. The upload SHALL NOT change the block's HTML.
#### Scenario: Upload an image for the HTML
- **GIVEN** staff editing an INS page with a Custom HTML block
- **WHEN** they choose `lobby.webp` under "Upload image" in that block's panel
- **THEN** the image is stored for INS and the panel shows its preview and the link `/api/public/page-images/<id>`
- **AND** "Copy link" copies that link, and the block's HTML is unchanged
#### Scenario: Refused upload
- **WHEN** staff choose a 3 MB JPEG under "Upload image"
- **THEN** the panel shows that the image is too large, and no link appears
#### Scenario: New page without a company
- **GIVEN** a super admin's new page with no company chosen
- **WHEN** they choose a file under "Upload image"
- **THEN** nothing is uploaded and the panel asks them to choose a company
@@ -0,0 +1,7 @@
-- The labels added by add-html-image-upload, 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 'PagesUploadImage', JSON_OBJECT('en_US', 'Upload image', 'zh_CN', '上传图片'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUploadImage') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '上传图片') WHERE LOWER(code) = LOWER('PagesUploadImage') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesUploadImageHint', JSON_OBJECT('en_US', 'PNG, JPEG or WebP up to 2 MB. Paste the link into your HTML, for example in an img tag''s src.', 'zh_CN', 'PNG、JPEG 或 WebP,最大 2 MB。将链接粘贴到您的 HTML 中,例如 img 标签的 src。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesUploadImageHint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', 'PNG、JPEG 或 WebP,最大 2 MB。将链接粘贴到您的 HTML 中,例如 img 标签的 src。') WHERE LOWER(code) = LOWER('PagesUploadImageHint') AND area = 'A';
@@ -0,0 +1,34 @@
# Tasks
## 1. Portal
- [x] 1.1 HTML block panel: an "Upload image" file picker (`image/png,image/jpeg,image/webp`) uploads at once through `uploadPageImage(companyId, base64)`.
- Each success adds a row: preview, a read-only link `/api/public/page-images/<id>`, and a "Copy link" button that uses the clipboard.
- A refusal shows the translated server reason under the picker.
- With no company, the panel shows "Choose a company." and does not upload.
- The block's HTML is never changed.
Verify: editor tests (success row and copy, refusal, no company, HTML unchanged) fail first, then pass; vitest exit 0; tsc; lint.
- [x] 1.2 Add the labels (`PagesUploadImage`, `PagesUploadImageHint`; the copy button reuses the page-address copy button) to `defaultMessages.ts`, `zh_CN.seed.json` and `sql/01-html-image-labels.sql`, and regenerate `local/seed/04-zh-cn-messages.sql`.
## 2. Verification
- [x] 2.1 Use Playwright on port 3001, signing in through the form and opening Hotel technology from Pages.
- In a Custom HTML block, upload an image, copy the link, and check that the panel shows the preview and the link.
- Upload a file that is not an image and see the refusal.
- Do not change the published page.
- [x] 2.2 Run the full portal vitest (exit 0), tsc, lint, and `openspec validate add-html-image-upload --strict`. Add a release note to `docs/deployment.md` (label SQL).
## Notes (2026-12-04)
- **Red first:** the success, refusal and no-company editor tests all failed, because there was no "Upload image" picker yet. They pass now.
- **Live check** (port 3001): signed in through the form, then opened Hotel technology from Pages.
- In block 3 (Custom HTML), uploaded `hero-bg.webp`. The panel showed the preview and `/api/public/page-images/7` with a copy button.
- A text file named `.png` was refused with "Use a PNG, JPEG or WebP image."
- The page was not saved or published.
- **Fix from the live check:** the link was shown twice (a read-only box and the copy button's text). It now shows once, beside its copy button, which reuses the page-address copy button with a `relative` option.
- **Results:** vitest 1997 passed (exit 0); tsc clean; lint 0 errors (the 4 warnings were already there).
## Workflow follow-up
- Open a PR to `main` and merge it. Archive the change on its own branch, with its own PR.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-04
@@ -0,0 +1,24 @@
# Design
## Context
The company header and the page title are drawn by `LandingPage`, and "hide page header" (`hideHeader`) removes both. Page settings are database columns threaded through services-counter, mobile-api and the portal. Blocks are JSON validated by `CmsBlockValidator`, so a new block or block field needs no schema change.
## Approaches
1. **A Top bar block, used with "hide page header" (chosen).** It is JSON only: no migration, and no changes to the page records in three services. The INS page already uses "hide page header" with a Custom HTML top bar, so this is a native swap for the same layout.
2. **New page settings** ("hide title", header button label and link, heading font). This is the natural model, but it means four new columns and changes to every page DTO, the draft record, the admin and public APIs, and the settings panel. That is about ten times the work for the same result.
3. **Keep the top bar in Custom HTML.** This is what the original page does; the native page exists to avoid it.
## Decisions
- **The top bar is the first block only.** The server refuses it anywhere else (`PagesTopBarFirst`), because a sticky bar in the middle of a page would cover the content as the visitor scrolls past it. The bar is `sticky top-0` with a card background and a bottom border. It runs full width (it counts as bleed), so it joins a full-width hero below it with no gap.
- **Top bar fields.** Only `buttonLabel` and `buttonUrl` (the pair rule, at most 40 characters, a safe link) plus the usual `anchor`. A heading, text, image, cards or look are refused (`PagesUnusedField`). The logo comes from the company's branding, as the default header's does.
- **The label (`eyebrow`).** At most 40 characters, allowed on FEATURES, STEPS, IMAGE_TEXT, FAQ and CTA, and refused on other types. It renders as a `p` above the h2, not as part of the heading, so screen readers read the heading on its own. It can be edited in place on the canvas.
- **Label colour.** On the DARK band it uses `text-primary`, the accent colour. On light backgrounds the accent can be too pale (INS gold on white is about 2:1), so it uses the accent mixed with the foreground colour, `color-mix(in srgb, var(--primary) 60%, var(--foreground))`. On the ACCENT band it uses the band's own text colour.
- **Serif headings.** Section h2s get `font-serif`, Tailwind's system serif, as the full-width hero does. No web font is added. This changes every landing page, CV's included. It is a small change, and it matches the hero.
## Risks
- **CV pages change font.** CV's section headings become serif. If CV wants sans-serif, a later change can make the font a company setting.
- **Sticky bar and same-page links.** A `#name` jump lands with the heading under the bar. `scroll-margin-top` on the named blocks keeps them clear when a top bar exists.
@@ -0,0 +1,42 @@
# Proposal
## Why
The native INS page (`/p/INS/hotel-technology-native`) now matches INS's standalone page in content, but it still looks different at the top and in its section headings:
- INS has a white top bar with the logo on the left and a "Get My Free Consultation" button on the right. The bar stays at the top while the visitor scrolls. Our page has two choices: show the company header and the page title, which INS does not have, or hide both, which also hides the logo.
- INS puts a small gold uppercase label above each section heading ("Services", "How we work", "Why Infinity", "FAQ"). We have no such label.
- INS's section headings are serif. Ours are sans-serif, except for the full-width hero.
## What Changes
- **Top bar block** (`TOPBAR`). It shows the company logo on the left (the company name when there is no logo) and an optional button on the right (`buttonLabel` and `buttonUrl`, with the same link rules as other buttons). It stays at the top of the window while the page scrolls. It may only be the first block. Together with "hide page header", it gives INS's layout: the logo and button stay, and the title and the default header go.
- **Section labels** (`eyebrow`, at most 40 characters). Feature cards, Steps, Image with text, FAQ and Call to action may carry a short label. It shows above the heading in small uppercase letters in the accent colour, darkened on light backgrounds so it stays readable.
- **Serif section headings.** Section headings (h2) on landing pages use the same serif as the full-width hero.
- New editor labels in English and Chinese, with an SQL label file.
Not changing:
- The page settings and the database. "Hide page header" already exists, and the new fields live in the block JSON.
- Card and step layout, and the bullet style in rich text.
- The default company header on pages without a top bar.
## Capabilities
### New Capabilities
None.
### Modified Capabilities
- `landing-pages`: adds "Top Bar Block", "Section Labels" and "Serif Section Headings".
## Impact
- services-counter: `CmsBlock` gains `eyebrow`. `CmsBlockValidator` validates TOPBAR and `eyebrow`.
- mobile-api: none. Public blocks pass through as maps.
- Portal:
- `cmsPages.ts`: the TOPBAR type, its label and empty block, and `eyebrow`;
- `CmsBlocks.tsx`: renders the top bar, the labels and the serif headings;
- `BlockFields.tsx`: the top bar's button and the label field;
- labels in `defaultMessages.ts` and `zh_CN.seed.json`.
- Data: no schema change. The new labels need a SQL label file in this change folder.
@@ -0,0 +1,42 @@
## ADDED Requirements
### Requirement: Top Bar Block
A page's first block MAY be a top bar. The top bar SHALL show the company logo, or the company name when there is no logo, and an optional button, and SHALL stay at the top of the window while the page scrolls. The server SHALL refuse a top bar that is not the first block, or one that carries fields other than its button and link name.
#### Scenario: Logo and button without the page title
- **GIVEN** page `/p/INS/hotel-technology-native` with "hide page header" on, a top bar with the button "Get My Free Consultation" linking to `#consult`, and a full-width hero
- **WHEN** a visitor opens the page and scrolls down
- **THEN** the INS logo and the button stay at the top of the window
- **AND** no page title heading shows, and the hero starts directly under the bar
#### Scenario: Top bar further down is refused
- **WHEN** staff save a page whose top bar is the second block
- **THEN** the save is refused with the reason naming that block
### Requirement: Section Labels
Feature cards, Steps, Image with text, FAQ and Call to action blocks MAY carry a label of at most 40 characters. The page SHALL show the label above the block's heading, in small uppercase letters in the accent colour. The server SHALL refuse a longer label, or a label on any other block type.
#### Scenario: Label above a heading
- **GIVEN** a Feature cards block with the label "Services" and the heading "Everything your guests touch, handled by one team"
- **WHEN** a visitor opens the page
- **THEN** "Services" shows in small uppercase letters directly above the heading
#### Scenario: Type a label in the editor
- **GIVEN** staff editing a Steps block
- **WHEN** they type "How we work" in its label field and save
- **THEN** the page keeps the label
### Requirement: Serif Section Headings
Section headings on landing pages SHALL use the serif typeface that the full-width hero uses.
#### Scenario: Feature heading in serif
- **WHEN** a visitor opens a page with a Feature cards block
- **THEN** its heading uses the serif typeface
@@ -0,0 +1,9 @@
-- The labels added by add-landing-page-polish, 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 'PagesBlockTopBar', JSON_OBJECT('en_US', 'Top bar', 'zh_CN', '顶栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockTopBar') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '顶栏') WHERE LOWER(code) = LOWER('PagesBlockTopBar') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesEyebrow', JSON_OBJECT('en_US', 'Label', 'zh_CN', '小标签'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesEyebrow') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '小标签') WHERE LOWER(code) = LOWER('PagesEyebrow') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTopBarFirst', JSON_OBJECT('en_US', 'The top bar must be the first section.', 'zh_CN', '顶栏必须是第一个区块。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTopBarFirst') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '顶栏必须是第一个区块。') WHERE LOWER(code) = LOWER('PagesTopBarFirst') AND area = 'A';
@@ -0,0 +1,55 @@
# Tasks
## 1. Server
- [x] 1.1 services-counter `CmsBlock`: add `eyebrow`. `CmsBlockValidator`:
- TOPBAR is allowed only at index 0 (`PagesTopBarFirst`); it takes the button pair and `anchor` only, and any other field is refused (`PagesUnusedField`);
- `eyebrow` at most 40 characters on FEATURES, STEPS, IMAGE_TEXT, FAQ and CTA, and refused elsewhere (`PagesUnusedField`).
Verify: new validator tests fail first, then pass; `mvn -T 1C -pl solvway-services-counter verify`.
## 2. Portal
- [x] 2.1 `CmsBlocks.tsx`:
- renders TOPBAR (logo or name, optional button, sticky, full width, joins a full-width hero);
- renders the label above section headings, in the accent colour, darkened on light backgrounds;
- renders section h2s in serif;
- named blocks keep clear of a sticky bar when jumped to.
Verify: render tests fail first, then pass; vitest exit 0.
- [x] 2.2 Editor:
- `cmsPages.ts`: TOPBAR type, label and empty block; `eyebrow`;
- `BlockFields.tsx`: the top bar's button fields, and the label field on the five types; the label is editable in place on the canvas;
- labels in `defaultMessages.ts`, `zh_CN.seed.json` and `sql/01-polish-labels.sql`; regenerate `local/seed/04-zh-cn-messages.sql`.
Verify: editor tests fail first, then pass; tsc and lint clean.
## 3. Verification
- [x] 3.1 Rebuild services-counter. Use Playwright on port 3001 to edit `/p/INS/hotel-technology-native` through the editor:
- turn on "hide page header";
- add a top bar first, with "Get My Free Consultation" linking to `#consult`;
- add the labels "Services", "How we work", "Why Infinity" and "FAQ";
- publish.
Check the published page at 1280 px and 390 px against the INS page, including the bar staying put on scroll.
- [x] 3.2 Run the full portal vitest (exit 0), tsc, lint, Maven verify for services-counter, and `openspec validate add-landing-page-polish --strict`.
- [x] 3.3 Add a release note to `docs/deployment.md` (label SQL).
## Notes (2026-12-04)
- **Red first:**
- the validator tests failed on the top bar and the labels;
- the render tests failed on the top bar, the scroll margin, the labels and the serif headings;
- the editor test failed on the label field and the top bar.
- **Changed existing tests:** none. One of my own new render tests changed before going green: the sticky class sits on the top bar's row, not on the header. A sticky element only sticks inside its parent, and the header's parent is just as tall as the header.
- **Live check** (port 3001, rebuilt counter), on `/p/INS/hotel-technology-native` through the editor:
- "hide page header" was already on;
- added a Top bar section, moved it first, and set "Get My Free Consultation" linking to `#consult`;
- typed the labels "Services", "How we work", "Why Infinity" and "FAQ" on the canvas;
- saved and published.
- **Published result:**
- at 1280 px the logo and button sit in a white bar above the full-width hero, with no title, and the bar stays at the top while scrolling;
- the labels show in darkened gold uppercase above serif headings;
- at 390 px the bar keeps the logo and button, and the hero stacks.
- **Not reachable in the UI, covered by the validator tests:** a top bar that is not first is refused (the server rule; the editor's Move up and Move down allow it, and the refusal shows on the canvas).
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-04
@@ -0,0 +1,30 @@
# Design
## Context
Landing blocks are JSON validated by `CmsBlockValidator` and rendered by `CmsBlocks.tsx`. Card blocks (FEATURES, STEPS, TRUST, HERO points) share `cards` and the editor's card list in `BlockFields.tsx`. Text is edited in place with `Text`, which renders plain text outside the editor. The landing form's done state is `VisitorState` with the `RegThanks` heading.
## Approaches
1. **A FOOTER block built on `cards` (chosen).** Columns are cards with a title and text, the legal line is the block's `text`. The DTO gains nothing for the footer, and the editor reuses the card list. Staff get a footer that looks right without formatting.
2. **Columns and link colours on the Rich Text block.** This keeps one block type, but staff would have to build columns and links by hand, and every rich text block would gain layout options.
3. **Keep the footer in Custom HTML.** This is what the original page does; the native page exists to avoid it.
For the thank-you text, a field on the form-bearing blocks is the only sensible way: the message belongs to the page, not to the event, because one event can have several pages.
## Decisions
- **Links are found, not typed.** One helper splits plain text into text and links:
- `+` followed by digits, spaces and dashes (at least 8 digits) becomes `tel:` with only `+` and digits;
- an email address becomes `mailto:`;
- `https://…` and `www.…` become `https://` links that open in a new tab with `rel="noopener noreferrer"`.
It builds React elements, never HTML, so text stays text. `Text` gains a `links` flag that uses it outside the editor; in the editor the text stays editable as now.
- **Footer validation.** 1 to 4 cards, each with a required title (80) and required text (300), no icon. `text` at most 300. No heading.
- **Footer look.** `emptyBlock("FOOTER")` sets `look: "DARK"`. Links use the existing link colour (`text-primary`), which is the company's accent colour, so INS's footer links are gold.
- **Thank-you text.** `thanksText` (200) on FORM, and on HERO only with an event, like `formHeading`. `LandingForm` takes it as `thanks` and passes it to `VisitorState`'s text, through the link helper. Choosing "No form" on a hero, or changing company, clears it along with the event.
- **Shade.** The design-token test refuses raw colours, so the shade stays black-based: `from-black/55 to-black/10 to-70%` from the `md` width, and an even `black/60` below it. White text keeps contrast because the text sits on the darker left.
## Risks
- **Phone detection.** Only numbers written with `+` become links. A local number like "03-7623 9807" stays plain text. This is deliberate, to avoid linking dates or prices.
- **Lighter shade over a bright photo.** The headline could lose contrast. The hero heading is large and bold, and INS uses the same shade; staff can pick a darker photo.
@@ -0,0 +1,48 @@
# Proposal
## Why
The INS Hotel technology page is being rebuilt in Co-Lite without Custom HTML, to match INS's standalone page (`~/Projects/ins-landing-page`). After add-compact-landing-form, the content matches, but three things still differ, and marketing staff cannot fix them from the editor:
- After signing up, INS shows "Thanks! Our team will contact you shortly. Prefer to talk now? Call +60 12-833 2775", with the number as a tap-to-call link. Our landing form shows the same generic thank-you on every page.
- INS's footer has up to three columns (company and address, "Talk to us" with phone and email, website). The phone, email and web address are gold links, and the © line sits under a thin divider. Ours is one stacked column of plain rich text.
- INS's hero shade is lighter, so more of the photo shows. Ours is near-black on the text side.
## What Changes
- **Thank-you text.** The FORM block and a HERO with an event MAY carry `thanksText` (at most 200 characters). After a visitor signs up, it shows under the "Thank you" heading. Phone numbers that start with `+`, email addresses, and `https://` or `www.` web addresses in it become links. Without it, the thank-you stays as it is now. The server refuses it on a HERO without an event.
- **Footer block.** A new block type, FOOTER:
- 1 to 4 columns, each a bold title (80 characters) and text (300 characters, line breaks kept);
- an optional legal line (`text`, 300 characters) under a thin divider;
- phone numbers, emails and web addresses in the column text become links in the link colour;
- a new footer starts with the dark look; staff may change the look as on any block.
- **Lighter full-width hero shade.** The full-width hero's shade runs from about half dark on the text side to almost clear at 70% of the width, like INS. On phones, where the text sits over the whole photo, the shade is an even dark layer.
- New editor labels in English and Chinese, with an SQL label file for real environments.
Not changing:
- QR and invitation sign-up thank-you screens.
- The Rich Text block. Existing footers built with it keep working.
- Heroes that are not full width.
## Capabilities
### New Capabilities
None.
### Modified Capabilities
- `landing-pages`: adds "Thank-You Text On Landing Forms" and "Footer Block".
## Impact
- services-counter: `CmsBlock` gains `thanksText`. `CmsBlockValidator` checks `thanksText` on FORM and HERO and validates the FOOTER type.
- mobile-api: none. Public blocks pass through as maps.
- Portal:
- `cmsPages.ts`: the FOOTER type, its empty block and label;
- a small link-finding helper used by the footer and the thank-you text;
- `CmsBlocks.tsx` renders the footer, passes the thank-you text and lightens the shade;
- `LandingForm.tsx` shows the thank-you text;
- `BlockFields.tsx` gets the footer's columns and legal line, and the thank-you field on FORM and HERO;
- labels in `defaultMessages.ts` and `zh_CN.seed.json`.
- Data: no schema change, because the blocks are JSON. The new labels need a SQL label file in this change folder.
@@ -0,0 +1,64 @@
## ADDED Requirements
### Requirement: Thank-You Text On Landing Forms
A FORM block, and a HERO block with an event, MAY carry a thank-you text of at most 200 characters. After a visitor signs up through that block's form, the page SHALL show the text, with contact links, under the thank-you heading. Without it, the thank-you SHALL look as before. The server SHALL refuse an over-long thank-you text, or one on a HERO without an event.
#### Scenario: Visitor sees the page's thank-you text with a call link
- **GIVEN** page `/p/INS/hotel-technology-native` whose hero form has the thank-you text "Prefer to talk now? Call +60 12-833 2775."
- **WHEN** a visitor signs up through the hero form
- **THEN** the page shows the thank-you heading and "Prefer to talk now? Call +60 12-833 2775."
- **AND** "+60 12-833 2775" is a link to `tel:+60128332775`
#### Scenario: No thank-you text keeps today's message
- **WHEN** a visitor signs up through a FORM block without a thank-you text
- **THEN** the page shows only the thank-you heading and the "register another" button, as before
#### Scenario: Thank-you text on a hero without a form is refused
- **WHEN** staff save a HERO block without an event but with a thank-you text
- **THEN** the save is refused with the reason naming the hero's thank-you field
#### Scenario: Set the thank-you text in the editor
- **GIVEN** staff editing a hero that has an event
- **WHEN** they type a thank-you text in the hero's settings and save
- **THEN** the page keeps the text
- **AND** choosing "No form" on the hero clears it
### Requirement: Footer Block
A page MAY hold FOOTER blocks: 1 to 4 columns, each a required title (80 characters) and text (300 characters), and an optional legal line (300 characters). The page SHALL show the columns side by side on wide screens and stacked on phones, keep line breaks, show contact links in the column text, and put the legal line under a thin divider. A new footer SHALL start with the dark look. The server SHALL refuse a footer that breaks these limits, or that has a heading or a column icon.
#### Scenario: Visitor sees a three-column footer with links
- **GIVEN** a published page whose footer has the columns "Infinity Networks Security Sdn Bhd", "Talk to us" with "+603-7623 9807" and "info@infinitynetworks.com.my", and "Website" with "www.infinitynetworks.com.my", and a legal line
- **WHEN** a visitor opens the page in a 1280 px window
- **THEN** the three columns sit side by side on a dark band
- **AND** the phone links to `tel:+60376239807`, the email to `mailto:info@infinitynetworks.com.my`, and the website to `https://www.infinitynetworks.com.my`
- **AND** the legal line sits under a divider
#### Scenario: Add a footer in the editor
- **GIVEN** staff editing a page
- **WHEN** they add a Footer section
- **THEN** the canvas shows a dark footer with two empty columns to type into
- **AND** they can add columns up to 4 and type the legal line
#### Scenario: Footer with five columns is refused
- **WHEN** a page is saved with a footer of 5 columns
- **THEN** the save is refused with the reason naming the footer's columns
### Requirement: Contact Links In Plain Text
Where this spec says text shows contact links, the page SHALL show phone numbers that start with `+` as `tel:` links holding only `+` and digits, email addresses as `mailto:` links, and `https://` or `www.` addresses as `https://` links that open in a new tab. Everything else SHALL stay plain text, never HTML.
#### Scenario: Text with markup stays text
- **GIVEN** a footer column text "<b>Call</b> +60 12-833 2775"
- **WHEN** a visitor opens the page
- **THEN** "<b>Call</b>" shows as written
- **AND** "+60 12-833 2775" links to `tel:+60128332775`
@@ -0,0 +1,13 @@
-- The labels added by add-landing-thanks-and-footer, 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 'PagesThanksText', JSON_OBJECT('en_US', 'Thank-you text', 'zh_CN', '感谢语'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesThanksText') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '感谢语') WHERE LOWER(code) = LOWER('PagesThanksText') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesBlockFooter', JSON_OBJECT('en_US', 'Footer', 'zh_CN', '页脚'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockFooter') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '页脚') WHERE LOWER(code) = LOWER('PagesBlockFooter') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesColumnN', JSON_OBJECT('en_US', 'Column {number}', 'zh_CN', '第 {number} 栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesColumnN') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '第 {number} 栏') WHERE LOWER(code) = LOWER('PagesColumnN') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesAddColumn', JSON_OBJECT('en_US', 'Add column', 'zh_CN', '添加栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddColumn') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加栏') WHERE LOWER(code) = LOWER('PagesAddColumn') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesFooterLegal', JSON_OBJECT('en_US', 'Legal line', 'zh_CN', '版权声明'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFooterLegal') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '版权声明') WHERE LOWER(code) = LOWER('PagesFooterLegal') AND area = 'A';
@@ -0,0 +1,52 @@
# Tasks
## 1. Server
- [x] 1.1 services-counter `CmsBlock`: add `thanksText`. `CmsBlockValidator`:
- `thanksText` at most 200 on FORM and HERO; refused on a HERO without `eventUuid` and on every other type (`PagesUnusedField`);
- FOOTER: no heading; 1 to 4 cards, each with a required title (80) and required text (300) and no icon; `text` at most 300.
Verify: new validator tests fail first, then pass; `mvn -T 1C -pl solvway-services-counter verify`.
## 2. Portal
- [x] 2.1 Link helper and rendering:
- a helper that turns plain text into text and links (`+` phone numbers, emails, `https://` and `www.` addresses), building elements, never HTML;
- `Text` gains `links`;
- `CmsBlocks.tsx` renders FOOTER (columns, line breaks, legal line under a divider), passes `thanksText` to `LandingForm`, and lightens the full-width hero shade;
- `LandingForm.tsx` shows the thank-you text under the heading.
Verify: render tests fail first, then pass; vitest exit 0.
- [x] 2.2 Editor:
- `cmsPages.ts`: FOOTER type, label and empty block (dark look, two columns);
- `BlockFields.tsx`: the footer's columns (1 to 4) and legal line; the thank-you field on FORM, and on HERO when an event is picked; "No form" and company change clear it;
- labels in `defaultMessages.ts`, `zh_CN.seed.json`, `sql/01-thanks-footer-labels.sql`; regenerate `local/seed/04-zh-cn-messages.sql`.
Verify: editor tests fail first, then pass; tsc and lint clean.
## 3. Verification
- [x] 3.1 Rebuild services-counter. Use Playwright on port 3001 to edit `/p/INS/hotel-technology-native` through the editor:
- set the hero's thank-you text to "Prefer to talk now? Call +60 12-833 2775.";
- replace the rich text footer with a Footer section matching INS;
- publish.
Check the published page at 1280 px and 390 px. The thank-you screen needs a real sign-up, which writes a record: check it in the editor preview path only if it does not save, otherwise ask the owner first.
- [x] 3.2 Run the full portal vitest (exit 0), tsc, lint, Maven verify for services-counter, and `openspec validate add-landing-thanks-and-footer --strict`.
- [x] 3.3 Add a release note to `docs/deployment.md` (label SQL).
## Notes (2026-12-04)
- **Red first:**
- the validator tests failed on the thank-you text and the footer;
- the render tests failed on the thank-you text, the footer and the link helper (missing module);
- the editor tests failed on the Footer section, the hero's thank-you field and the company switch.
- **Changed existing tests:** none. Two of my own new editor tests were fixed before going green: column names shift after a removal, and the Form block has its own thank-you field, so the hero checks are scoped to block 1.
- **Design-token checks:** the phone shade uses an even black gradient (`bg-black/60` is refused), and the divider uses `border-muted-foreground/30` (`border-current/15` is not in Tailwind 3).
- **Live check** (port 3001, rebuilt counter), on `/p/INS/hotel-technology-native` through the editor:
- typed the hero's thank-you text "Prefer to talk now? Call +60 12-833 2775.";
- added a Footer section with three columns and the legal line, and removed the old Text footer;
- saved and published.
- **Published result:** at 1280 px the three columns sit side by side on the dark band with gold tel, mailto and https links, and the legal line sits under a divider; at 390 px they stack. The hero shade is lighter.
- **Not run live:** the thank-you screen itself, because it needs a real sign-up, which writes a record. The render tests cover it (thank-you text and the tel link after a mocked sign-up).
- **Not reachable in the UI, covered by the validator tests:** 5 footer columns (Add column stops at 4), and a thank-you text on a hero without a form (No form clears it).
+227 -1
View File
@@ -278,7 +278,7 @@ The public frame address SHALL be `/p/<company>/<slug>/frame/<block index>` and
### 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.
The frame SHALL grow or shrink to fit its content, between 20 and 20000 pixels, using height reports sent by that frame only. Before the first report it SHALL be 600 pixels tall. The frame SHALL report the height of its content, not of its own window, and SHALL report again whenever the page asks, which the page SHALL do once it listens and when the frame loads.
#### Scenario: A tall paste grows the frame
@@ -286,6 +286,12 @@ The frame SHALL grow to fit its content, between 100 and 20000 pixels, using hei
- **WHEN** a visitor opens the page
- **THEN** the frame is 3000 pixels tall and shows no inner scroll bar
#### Scenario: A short top bar shrinks the frame
- **GIVEN** a published HTML block holding only a 68 pixel top bar
- **WHEN** a visitor opens the page, even if the frame loaded before the page was ready
- **THEN** the frame is 68 pixels tall, with no blank space below the bar
#### Scenario: Another frame cannot resize it
- **WHEN** a different window posts a height report to the page
@@ -605,3 +611,223 @@ A HERO block MAY name an event. When it does, the hero SHALL show Co-Lite's sign
- **WHEN** they pick `INS website enquiries` under the hero's sign-up form setting
- **THEN** the canvas shows the form card beside the hero text
- **AND** choosing "No form" removes it
### Requirement: Full-Width Hero
A HERO block MAY be marked full width. A full-width hero SHALL span the whole window with square corners, show its heading larger and centred top to bottom in the hero's opening height (not beside a long form), and use a shade that is darker on the text side than on the far side. A hero that is not marked full width SHALL look as it did before. The server SHALL refuse a `fullWidth` value that is not true or false.
#### Scenario: Hero runs edge to edge under a Custom HTML top bar
- **GIVEN** page `/p/INS/hotel-technology` with a Custom HTML top bar followed by a full-width HERO with an image and an event
- **WHEN** a visitor opens the page in a 1280 px window
- **THEN** the hero spans the full window width
- **AND** the form card sits beside the heading
#### Scenario: Existing hero unchanged
- **WHEN** a visitor opens a page whose HERO block is not marked full width
- **THEN** the hero sits inside the page width with rounded corners, as before
#### Scenario: Turn on full width in the editor
- **GIVEN** staff editing a page with a HERO block
- **WHEN** they switch on "Full width" in the hero's settings
- **THEN** the canvas shows the hero across the full width
### Requirement: Full-Width Blocks Join Without Gaps
A full-width HERO, a Custom HTML block, and a block with a non-default look SHALL join with no gap when two of them are next to each other. Other blocks SHALL keep their usual spacing.
#### Scenario: Top bar runs straight into the hero
- **GIVEN** a Custom HTML top bar followed by a full-width HERO
- **WHEN** a visitor opens the page
- **THEN** the hero starts directly under the top bar, with no gap
#### Scenario: Dark call to action runs into a dark footer
- **GIVEN** a CTA block with the Dark look followed by a text block with the Dark look
- **WHEN** a visitor opens the page
- **THEN** the two bands join with no gap between them
### Requirement: Hero Points
A HERO block MAY carry up to 6 points, each a non-empty title of at most 80 characters, with no icon and no text. The hero SHALL show its points as a bulleted list under its text. The server SHALL refuse more than 6 points, an empty or over-long point, and a point with an icon or text, naming the field.
#### Scenario: Points under the hero text
- **GIVEN** a HERO block with points "One accountable partner instead of five vendors" and "Local support team in Malaysia"
- **WHEN** a visitor opens the page
- **THEN** both points show as a bulleted list under the hero text
#### Scenario: Too many points refused
- **WHEN** staff save a HERO block with 7 points
- **THEN** the save is refused at `blocks[n].cards`
### Requirement: Hero Form Heading
A HERO block with an event MAY carry a form heading of at most 80 characters and a form text of at most 200 characters. The hero SHALL show them at the top of its form card, above the form. The server SHALL refuse either on a hero without an event. On the canvas, staff SHALL be able to type both in place.
#### Scenario: Card shows its heading
- **GIVEN** a HERO block with an event, form heading "Get a free consultation" and form text "Tell us about your property. It takes under a minute."
- **WHEN** a visitor opens the page
- **THEN** the form card starts with that heading and text, followed by the form
#### Scenario: Form heading without a form refused
- **WHEN** staff save a HERO block with a form heading and no event
- **THEN** the save is refused at `blocks[n].formHeading`
### Requirement: Image Upload For Custom HTML
A Custom HTML block's panel in the editor SHALL offer an image upload for the page's company, under the same checks as other page images. On success it SHALL show the image's preview and its public link with a copy button; on refusal it SHALL show the reason. The upload SHALL NOT change the block's HTML.
#### Scenario: Upload an image for the HTML
- **GIVEN** staff editing an INS page with a Custom HTML block
- **WHEN** they choose `lobby.webp` under "Upload image" in that block's panel
- **THEN** the image is stored for INS and the panel shows its preview and the link `/api/public/page-images/<id>`
- **AND** "Copy link" copies that link, and the block's HTML is unchanged
#### Scenario: Refused upload
- **WHEN** staff choose a 3 MB JPEG under "Upload image"
- **THEN** the panel shows that the image is too large, and no link appears
#### Scenario: New page without a company
- **GIVEN** a super admin's new page with no company chosen
- **WHEN** they choose a file under "Upload image"
- **THEN** nothing is uploaded and the panel asks them to choose a company
### Requirement: Compact Landing-Page Form
A landing page's sign-up form, in a FORM block or a hero, SHALL show name, mobile, email and company, the event's interests as one optional dropdown, the privacy notice folded behind a single line that opens it in full, and the consent box. It SHALL NOT show a job-title field. QR, invitation and customer sign-up forms SHALL keep their full layout.
#### Scenario: Short form on the page
- **GIVEN** a page whose hero has an event with five interests
- **WHEN** a visitor opens the page
- **THEN** the form shows name, mobile, email, company, a "Service interested in" dropdown and the consent box, with no job title and no interest checkboxes
- **AND** the privacy notice is folded behind "How we use your details"
#### Scenario: Pick one service
- **WHEN** the visitor chooses "Cloud IP PABX" in the dropdown and submits
- **THEN** the submission carries that one interest
#### Scenario: Read the notice
- **WHEN** the visitor opens "How we use your details"
- **THEN** the full English and Malay notice shows above the consent box
#### Scenario: QR form unchanged
- **WHEN** a visitor opens an event's QR sign-up form
- **THEN** it shows job title, the interest checkboxes and the full notice as before
### Requirement: Thank-You Text On Landing Forms
A FORM block, and a HERO block with an event, MAY carry a thank-you text of at most 200 characters. After a visitor signs up through that block's form, the page SHALL show the text, with contact links, under the thank-you heading. Without it, the thank-you SHALL look as before. The server SHALL refuse an over-long thank-you text, or one on a HERO without an event.
#### Scenario: Visitor sees the page's thank-you text with a call link
- **GIVEN** page `/p/INS/hotel-technology-native` whose hero form has the thank-you text "Prefer to talk now? Call +60 12-833 2775."
- **WHEN** a visitor signs up through the hero form
- **THEN** the page shows the thank-you heading and "Prefer to talk now? Call +60 12-833 2775."
- **AND** "+60 12-833 2775" is a link to `tel:+60128332775`
#### Scenario: No thank-you text keeps today's message
- **WHEN** a visitor signs up through a FORM block without a thank-you text
- **THEN** the page shows only the thank-you heading and the "register another" button, as before
#### Scenario: Thank-you text on a hero without a form is refused
- **WHEN** staff save a HERO block without an event but with a thank-you text
- **THEN** the save is refused with the reason naming the hero's thank-you field
#### Scenario: Set the thank-you text in the editor
- **GIVEN** staff editing a hero that has an event
- **WHEN** they type a thank-you text in the hero's settings and save
- **THEN** the page keeps the text
- **AND** choosing "No form" on the hero clears it
### Requirement: Footer Block
A page MAY hold FOOTER blocks: 1 to 4 columns, each a required title (80 characters) and text (300 characters), and an optional legal line (300 characters). The page SHALL show the columns side by side on wide screens and stacked on phones, keep line breaks, show contact links in the column text, and put the legal line under a thin divider. A new footer SHALL start with the dark look. The server SHALL refuse a footer that breaks these limits, or that has a heading or a column icon.
#### Scenario: Visitor sees a three-column footer with links
- **GIVEN** a published page whose footer has the columns "Infinity Networks Security Sdn Bhd", "Talk to us" with "+603-7623 9807" and "info@infinitynetworks.com.my", and "Website" with "www.infinitynetworks.com.my", and a legal line
- **WHEN** a visitor opens the page in a 1280 px window
- **THEN** the three columns sit side by side on a dark band
- **AND** the phone links to `tel:+60376239807`, the email to `mailto:info@infinitynetworks.com.my`, and the website to `https://www.infinitynetworks.com.my`
- **AND** the legal line sits under a divider
#### Scenario: Add a footer in the editor
- **GIVEN** staff editing a page
- **WHEN** they add a Footer section
- **THEN** the canvas shows a dark footer with two empty columns to type into
- **AND** they can add columns up to 4 and type the legal line
#### Scenario: Footer with five columns is refused
- **WHEN** a page is saved with a footer of 5 columns
- **THEN** the save is refused with the reason naming the footer's columns
### Requirement: Contact Links In Plain Text
Where this spec says text shows contact links, the page SHALL show phone numbers that start with `+` as `tel:` links holding only `+` and digits, email addresses as `mailto:` links, and `https://` or `www.` addresses as `https://` links that open in a new tab. Everything else SHALL stay plain text, never HTML.
#### Scenario: Text with markup stays text
- **GIVEN** a footer column text "<b>Call</b> +60 12-833 2775"
- **WHEN** a visitor opens the page
- **THEN** "<b>Call</b>" shows as written
- **AND** "+60 12-833 2775" links to `tel:+60128332775`
### Requirement: Top Bar Block
A page's first block MAY be a top bar. The top bar SHALL show the company logo, or the company name when there is no logo, and an optional button, and SHALL stay at the top of the window while the page scrolls. The server SHALL refuse a top bar that is not the first block, or one that carries fields other than its button and link name.
#### Scenario: Logo and button without the page title
- **GIVEN** page `/p/INS/hotel-technology-native` with "hide page header" on, a top bar with the button "Get My Free Consultation" linking to `#consult`, and a full-width hero
- **WHEN** a visitor opens the page and scrolls down
- **THEN** the INS logo and the button stay at the top of the window
- **AND** no page title heading shows, and the hero starts directly under the bar
#### Scenario: Top bar further down is refused
- **WHEN** staff save a page whose top bar is the second block
- **THEN** the save is refused with the reason naming that block
### Requirement: Section Labels
Feature cards, Steps, Image with text, FAQ and Call to action blocks MAY carry a label of at most 40 characters. The page SHALL show the label above the block's heading, in small uppercase letters in the accent colour. The server SHALL refuse a longer label, or a label on any other block type.
#### Scenario: Label above a heading
- **GIVEN** a Feature cards block with the label "Services" and the heading "Everything your guests touch, handled by one team"
- **WHEN** a visitor opens the page
- **THEN** "Services" shows in small uppercase letters directly above the heading
#### Scenario: Type a label in the editor
- **GIVEN** staff editing a Steps block
- **WHEN** they type "How we work" in its label field and save
- **THEN** the page keeps the label
### Requirement: Serif Section Headings
Section headings on landing pages SHALL use the serif typeface that the full-width hero uses.
#### Scenario: Feature heading in serif
- **WHEN** a visitor opens a page with a Feature cards block
- **THEN** its heading uses the serif typeface
@@ -1,29 +1,33 @@
"use client";
import type { ReactNode } from "react";
import { useState, type ReactNode } from "react";
import { ArrowDown, ArrowUp, Plus, Trash2 } from "lucide-react";
import { BLOCK_LABELS, ICONS, LOOKS, imageSrc, type CmsBlock, type CmsCard, type Look } from "@/app/lib/cmsPages";
import { Button } from "@/app/components/ui/button";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Switch } from "@/app/components/ui/switch";
import { Textarea } from "@/app/components/ui/textarea";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { RichTextEditor } from "./RichTextEditor";
import { CopyAddress } from "./CopyAddress";
// 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. Every type also shows "anchor". */
const INLINE: Record<string, string[]> = {
HERO: ["imageId", "heading", "text", "buttonLabel", "buttonUrl", "eventUuid"],
HERO: ["imageId", "heading", "text", "buttonLabel", "buttonUrl", "eventUuid", "fullWidth", "formHeading", "formText", "thanksText", "cards"],
RICH_TEXT: ["html"],
IMAGE_TEXT: ["imageId", "imagePosition", "heading", "html", "buttonLabel", "buttonUrl"],
FAQ: ["heading", "items"],
FORM: ["heading", "eventUuid"],
IMAGE_TEXT: ["imageId", "imagePosition", "eyebrow", "heading", "html", "buttonLabel", "buttonUrl"],
FAQ: ["eyebrow", "heading", "items"],
FORM: ["heading", "eventUuid", "thanksText"],
HTML: ["html"],
FEATURES: ["heading", "text", "cards"],
STEPS: ["heading", "cards"],
FEATURES: ["eyebrow", "heading", "text", "cards"],
STEPS: ["eyebrow", "heading", "cards"],
TRUST: ["cards"],
CTA: ["heading", "text", "buttonLabel", "buttonUrl"],
CTA: ["eyebrow", "heading", "text", "buttonLabel", "buttonUrl"],
FOOTER: ["cards", "text"],
TOPBAR: ["buttonLabel", "buttonUrl"],
};
const LISTED = /^(items\[\d+\]\.(question|answer)|cards\[\d+\]\.(icon|title|text))$/;
@@ -34,10 +38,14 @@ const ICON_LABELS: Record<string, string> = {
"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: "" } },
// add-hero-full-width: a hero's points are title-only cards, and it may have none.
// add-landing-thanks-and-footer: a footer's columns are title-and-text cards, 1 to 4.
const CARD_KINDS: Record<string, { legend: string; add: string; icon: boolean; text: boolean; min: number; max: number; empty: CmsCard }> = {
FEATURES: { legend: "PagesCardN", add: "PagesAddCard", icon: true, text: true, min: 2, max: 6, empty: { icon: "star", title: "", text: "" } },
STEPS: { legend: "PagesStepN", add: "PagesAddStep", icon: false, text: true, min: 2, max: 6, empty: { title: "", text: "" } },
TRUST: { legend: "PagesItemN", add: "PagesAddItem", icon: false, text: false, min: 2, max: 6, empty: { title: "" } },
HERO: { legend: "PagesPointN", add: "PagesAddPoint", icon: false, text: false, min: 0, max: 6, empty: { title: "" } },
FOOTER: { legend: "PagesColumnN", add: "PagesAddColumn", icon: false, text: true, min: 1, max: 4, empty: { title: "", text: "" } },
};
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";
@@ -76,6 +84,8 @@ export function BlockFields(props: {
onMove: (delta: -1 | 1) => void;
onRemove: () => void;
onChooseImage: (file: File) => void;
/** Uploads an image for a Custom HTML block at once (add-html-image-upload); rejects with the reason to show. */
onUploadImage?: (file: File) => Promise<number>;
}) {
const { block, id, index, count, errors, saving, events, pendingImage, onChange, onMove, onRemove } = props;
const t = useT();
@@ -83,7 +93,7 @@ export function BlockFields(props: {
const fid = (name: string) => `block-${id}-${name}`;
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" | "anchor", labelCode: string) => (
const text = (name: "heading" | "text" | "buttonLabel" | "buttonUrl" | "anchor" | "formHeading" | "formText" | "thanksText" | "eyebrow", labelCode: string) => (
<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 })} />
</Field>
@@ -95,12 +105,30 @@ export function BlockFields(props: {
</Field>
);
// add-html-image-upload: this panel's uploads, newest first; their links are pasted into the HTML by hand.
const [uploads, setUploads] = useState<number[]>([]);
const [uploadError, setUploadError] = useState<string | null>(null);
const [uploading, setUploading] = useState(false);
async function upload(file: File) {
if (!props.onUploadImage) return;
setUploadError(null);
setUploading(true);
try {
const imageId = await props.onUploadImage(file);
setUploads((u) => [imageId, ...u]);
} catch (err) {
setUploadError(err instanceof Error ? err.message : String(err));
} finally {
setUploading(false);
}
}
const preview = pendingImage?.preview ?? (block.imageId ? imageSrc(block.imageId) : undefined);
// The FORM block's event, and the hero's optional sign-up form (add-hero-signup-form): the same picker and hint.
const eventPicker = (labelCode: string, emptyCode: string) => (
<Field id={fid("event")} label={t(labelCode)} error={errors.eventUuid}>
<select id={fid("event")} className={SELECT} value={block.eventUuid ?? ""} disabled={saving} aria-invalid={!!errors.eventUuid}
onChange={(e) => set({ eventUuid: e.target.value || null })}>
onChange={(e) => set(e.target.value ? { eventUuid: e.target.value } : { eventUuid: null, formHeading: undefined, formText: undefined, thanksText: undefined })}>
<option value="">{t(emptyCode)}</option>
{events.map((ev) => <option key={ev.uuid} value={ev.uuid}>{ev.name}</option>)}
{block.eventUuid && !events.some((ev) => ev.uuid === block.eventUuid) ? (
@@ -140,8 +168,8 @@ export function BlockFields(props: {
<>
{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)}>
const cardField = (f: "title" | "text", label: string, multiline: boolean) => (
<Field id={fid(`c${i}${f}`)} label={label} 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)))} />
@@ -160,18 +188,18 @@ export function BlockFields(props: {
</select>
</Field>
) : null}
{cardField("title", "PagesCardTitle", false)}
{kind.text ? cardField("text", "PagesCardText", true) : null}
{cardField("title", kind.min ? t("PagesCardTitle") : t(kind.legend, { number: i + 1 }), false)}
{kind.text ? cardField("text", t("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>
<Button type="button" variant="ghost" size="sm" disabled={saving || cards.length <= kind.min} 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 }])}>
<Button type="button" variant="outline" size="sm" disabled={saving || cards.length >= kind.max} onClick={() => setCards([...cards, { ...kind.empty }])}>
<Plus aria-hidden="true" className="size-4" />
{t(kind.add)}
</Button>
@@ -204,7 +232,19 @@ export function BlockFields(props: {
{text("text", "PagesText")}
{text("buttonLabel", "PagesButtonLabel")}
{text("buttonUrl", "PagesButtonLink")}
<div className="flex items-center gap-2">
<Switch id={fid("fullWidth")} checked={!!block.fullWidth} disabled={saving} onCheckedChange={(on) => set({ fullWidth: on || undefined })} />
<Label htmlFor={fid("fullWidth")}>{t("PagesFullWidth")}</Label>
</div>
{cardList}
{eventPicker("PagesHeroForm", "PagesNoForm")}
{block.eventUuid ? (
<>
{text("formHeading", "PagesFormHeading")}
{text("formText", "PagesFormText")}
{text("thanksText", "PagesThanksText")}
</>
) : null}
</>
)}
@@ -219,6 +259,7 @@ export function BlockFields(props: {
<option value="RIGHT">{t("PagesImageRight")}</option>
</select>
</Field>
{text("eyebrow", "PagesEyebrow")}
{text("heading", "PagesHeading")}
{richText("PagesText")}
{text("buttonLabel", "PagesButtonLabel")}
@@ -228,6 +269,7 @@ export function BlockFields(props: {
{block.type === "FAQ" && (
<>
{text("eyebrow", "PagesEyebrow")}
{text("heading", "PagesHeading")}
{items.map((item, i) => (
<div key={i} className="space-y-2 rounded-md border p-3">
@@ -260,16 +302,36 @@ export function BlockFields(props: {
<p className="text-xs text-muted-foreground">{t("PagesHtmlHint")}</p>
</Field>
)}
{block.type === "HTML" && props.onUploadImage && (
<Field id={fid("upload")} label={t("PagesUploadImage")} error={uploadError ?? undefined}>
<Input id={fid("upload")} type="file" accept="image/png,image/jpeg,image/webp" disabled={saving || uploading}
onChange={(e) => {
const file = e.target.files?.[0];
e.target.value = "";
if (file) void upload(file);
}} />
<p className="text-xs text-muted-foreground">{t("PagesUploadImageHint")}</p>
{uploads.map((imageId) => (
<div key={imageId} className="flex items-center gap-2 rounded-md border p-2">
{/* eslint-disable-next-line @next/next/no-img-element -- an uploaded image of unknown size */}
<img src={imageSrc(imageId)} alt={t("PagesImagePreview")} className="size-12 rounded object-cover" />
<CopyAddress address={imageSrc(imageId)} relative />
</div>
))}
</Field>
)}
{block.type === "FORM" && (
<>
{text("heading", "PagesHeading")}
{eventPicker("PagesFormEvent", "PagesChooseEvent")}
{text("thanksText", "PagesThanksText")}
</>
)}
{block.type === "FEATURES" && (
<>
{text("eyebrow", "PagesEyebrow")}
{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 })} />
@@ -280,6 +342,7 @@ export function BlockFields(props: {
{block.type === "STEPS" && (
<>
{text("eyebrow", "PagesEyebrow")}
{text("heading", "PagesHeading")}
{cardList}
</>
@@ -287,8 +350,24 @@ export function BlockFields(props: {
{block.type === "TRUST" && cardList}
{/* add-landing-page-polish: the top bar's button; its logo comes from the company. */}
{block.type === "TOPBAR" && (
<>
{text("buttonLabel", "PagesButtonLabel")}
{text("buttonUrl", "PagesButtonLink")}
</>
)}
{block.type === "FOOTER" && (
<>
{cardList}
{text("text", "PagesFooterLegal")}
</>
)}
{block.type === "CTA" && (
<>
{text("eyebrow", "PagesEyebrow")}
{text("heading", "PagesHeading")}
{text("text", "PagesText")}
{text("buttonLabel", "PagesButtonLabel")}
@@ -296,7 +375,7 @@ export function BlockFields(props: {
</>
)}
{block.type !== "HTML" && (
{block.type !== "HTML" && block.type !== "TOPBAR" && (
<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 })}>
@@ -58,6 +58,18 @@ describe("LandingPage: Custom HTML", () => {
expect(frame().style.height).toBe("2400px");
});
// add-hero-full-width: the frame's first report can arrive before the page listens, so the page asks once it does.
it("asks its frame for a height report once it listens, and again when the frame loads", () => {
const sealed = { postMessage: vi.fn() };
const getter = vi.spyOn(HTMLIFrameElement.prototype, "contentWindow", "get").mockReturnValue(sealed as unknown as Window);
onTestFinished(() => getter.mockRestore());
render(<LandingPage company={company} page={page([HTML])} />);
expect(sealed.postMessage).toHaveBeenCalledWith({ type: "colite-frame-ask" }, "*");
sealed.postMessage.mockClear();
act(() => { frame().dispatchEvent(new Event("load")); });
expect(sealed.postMessage).toHaveBeenCalledWith({ type: "colite-frame-ask" }, "*");
});
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);
@@ -80,6 +92,7 @@ describe("LandingPage: Custom HTML", () => {
render(<LandingPage company={company} page={page([HTML], true)} />);
const title = screen.getByRole("heading", { level: 1, name: "Hotel day" });
expect(title.parentElement!.className).not.toMatch(/space-y/);
expect(frame().parentElement!.className).toMatch(/space-y/);
// add-hero-full-width: spacing is a top margin on each block row after the first, so the first row has none.
expect(frame().closest("main > div > div")).not.toHaveClass("mt-10");
});
});
@@ -1,4 +1,4 @@
import { render, screen } from "@testing-library/react";
import { render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { LandingPage, type PublicBlock } from "./CmsBlocks";
@@ -103,8 +103,175 @@ describe("LandingPage", () => {
});
});
// add-hero-full-width: edge-to-edge hero, points, the form card's heading, and flush full-width neighbours.
describe("LandingPage full-width hero", () => {
const ins = { type: "HERO" as const, heading: "One partner", fullWidth: true, eventUuid: "77", closed: true,
cards: [{ title: "One accountable partner" }, { title: "Local support team in Malaysia" }],
formHeading: "Get a free consultation", formText: "Tell us about your property." };
it("runs outside the page width with square corners; a plain hero stays boxed in the page width", () => {
render(<LandingPage company={company} page={page([ins, { type: "HERO", heading: "Boxed" }])} />);
const wide = screen.getByRole("heading", { name: "One partner" }).closest("section")!;
expect(wide.closest(".max-w-5xl")).toBeNull();
expect(wide).not.toHaveClass("rounded-lg");
const boxed = screen.getByRole("heading", { name: "Boxed" }).closest("section")!;
expect(boxed.closest(".max-w-5xl")).not.toBeNull();
expect(boxed).toHaveClass("rounded-lg");
});
it("shows its points as a list under the text", () => {
render(<LandingPage company={company} page={page([ins])} />);
const hero = screen.getByRole("heading", { name: "One partner" }).closest("section")!;
const items = within(hero).getAllByRole("listitem");
expect(items.map((li) => li.textContent)).toEqual(["One accountable partner", "Local support team in Malaysia"]);
});
it("starts the form card with its heading and text", () => {
render(<LandingPage company={company} page={page([ins])} />);
const title = screen.getByRole("heading", { name: "Get a free consultation" });
const card = title.parentElement!.parentElement!;
expect(card).toHaveTextContent(/^Get a free consultation\s*Tell us about your property\./);
expect(card).toHaveTextContent("Sign-up is closed.");
});
it("joins a Custom HTML block and a full-width hero with no gap; other blocks keep theirs", () => {
render(<LandingPage company={company} frameBase="/f" page={page([
{ type: "HTML", html: "<header>Top</header>" }, ins, { type: "HTML", html: "<p>Rest</p>" }, { type: "RICH_TEXT", html: "<p>After</p>" },
])} />);
const rows = Array.from(document.querySelector("main > div")!.children);
expect(rows.map((r) => r.classList.contains("mt-10"))).toEqual([false, false, false, true]);
});
});
// add-compact-landing-form: a page's form is the short one, and coloured bands join.
describe("LandingPage compact form and bands", () => {
it("a page's form has no job title and a service dropdown", () => {
render(<LandingPage company={company} page={page([{ type: "FORM", form: { ...info, interests: [{ id: 3, name: "Cloud IP PABX" }] } }])} />);
expect(screen.queryByLabelText("Job title")).not.toBeInTheDocument();
expect(screen.getByRole("combobox", { name: "Service interested in (optional)" })).toBeInTheDocument();
});
it("joins a dark call to action and a dark text block with no gap", () => {
render(<LandingPage company={company} page={page([
{ type: "RICH_TEXT", html: "<p>Intro</p>" },
{ type: "CTA", heading: "Talk to us", look: "DARK" },
{ type: "RICH_TEXT", html: "<p>Footer</p>", look: "DARK" },
])} />);
const rows = Array.from(document.querySelector("main > div")!.children);
expect(rows.map((r) => r.classList.contains("mt-10"))).toEqual([false, true, false]);
expect(rows.slice(1).map((r) => r.querySelector("[data-look]")?.getAttribute("data-look"))).toEqual(["DARK", "DARK"]);
});
});
describe("utmTags", () => {
it("reads the three tags, capped at 100 characters", () => {
expect(utmTags("?utm_source=" + "x".repeat(150))).toEqual({ utmSource: "x".repeat(100), utmMedium: undefined, utmCampaign: undefined });
});
});
// add-landing-thanks-and-footer: the page's own thank-you text, and the footer block.
describe("LandingPage thank-you text and footer", () => {
async function signUp() {
const user = userEvent.setup();
await user.type(screen.getByLabelText("Your name"), "Tan");
await user.type(screen.getByLabelText("Mobile number"), "0125550101");
await user.click(screen.getByRole("checkbox"));
await user.click(screen.getByRole("button", { name: "Register" }));
}
it("a hero form shows its thank-you text after sign-up, with the number as a call link", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(new Response("", { status: 201 }));
render(<LandingPage company={company} page={page([{ type: "HERO", heading: "One partner", eventUuid: "77", form: info,
thanksText: "Prefer to talk now? Call +60 12-833 2775." }])} />);
await signUp();
const done = await screen.findByRole("status");
expect(done).toHaveTextContent("Thank you, you're registered for INS enquiries");
expect(done).toHaveTextContent("Prefer to talk now? Call +60 12-833 2775.");
expect(within(done).getByRole("link", { name: "+60 12-833 2775" })).toHaveAttribute("href", "tel:+60128332775");
});
it("a form block without a thank-you text keeps today's thank-you", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(new Response("", { status: 201 }));
render(<LandingPage company={company} page={page([{ type: "FORM", form: info }])} />);
await signUp();
const done = await screen.findByRole("status");
expect(done.querySelector("p")).toBeNull();
expect(within(done).getByRole("button", { name: "Register another person" })).toBeInTheDocument();
});
const footer: PublicBlock = { type: "FOOTER", look: "DARK", text: "© 2026 Infinity Networks Security Sdn Bhd. All rights reserved.", cards: [
{ title: "Infinity Networks Security Sdn Bhd", text: "Unit 2-6, Infinity Tower\nPetaling Jaya, Malaysia" },
{ title: "Talk to us", text: "+603-7623 9807\ninfo@infinitynetworks.com.my" },
{ title: "Website", text: "www.infinitynetworks.com.my" },
] };
it("shows a footer's columns side by side with contact links, and the legal line under a divider", () => {
render(<LandingPage company={company} page={page([footer])} />);
const foot = screen.getByRole("contentinfo");
expect(foot.closest("[data-look]")).toHaveAttribute("data-look", "DARK");
const columns = within(foot).getAllByRole("listitem");
expect(columns).toHaveLength(3);
expect(columns[0].parentElement).toHaveClass("md:grid-cols-3");
expect(within(columns[0]).getByText(/Unit 2-6/)).toHaveClass("whitespace-pre-line");
expect(within(foot).getByRole("link", { name: "+603-7623 9807" })).toHaveAttribute("href", "tel:+60376239807");
expect(within(foot).getByRole("link", { name: "info@infinitynetworks.com.my" })).toHaveAttribute("href", "mailto:info@infinitynetworks.com.my");
const site = within(foot).getByRole("link", { name: "www.infinitynetworks.com.my" });
expect(site).toHaveAttribute("href", "https://www.infinitynetworks.com.my");
expect(site).toHaveAttribute("target", "_blank");
expect(site).toHaveAttribute("rel", "noopener noreferrer");
expect(within(foot).getByText(/^© 2026/)).toHaveClass("border-t");
});
it("keeps markup in footer text as text", () => {
render(<LandingPage company={company} page={page([{ type: "FOOTER", cards: [{ title: "Call", text: "<b>Call</b> +60 12-833 2775" }] }])} />);
const foot = screen.getByRole("contentinfo");
expect(foot.querySelector("b")).toBeNull();
expect(foot).toHaveTextContent("<b>Call</b> +60 12-833 2775");
expect(within(foot).getByRole("link", { name: "+60 12-833 2775" })).toHaveAttribute("href", "tel:+60128332775");
});
});
// add-landing-page-polish: the top bar, section labels and serif headings.
describe("LandingPage polish", () => {
const bar: PublicBlock = { type: "TOPBAR", buttonLabel: "Get My Free Consultation", buttonUrl: "#consult" };
const hero: PublicBlock = { type: "HERO", heading: "One partner", fullWidth: true };
it("a top bar shows the logo and its button, stays at the top, and joins the hero", () => {
render(<LandingPage company={company} page={{ ...page([bar, hero]), hideHeader: true }} />);
const top = screen.getByRole("banner");
expect(within(top).getByRole("img", { name: "INS Sdn Bhd" })).toHaveAttribute("src", "/api/public/page-images/4");
expect(within(top).getByRole("link", { name: "Get My Free Consultation" })).toHaveAttribute("href", "#consult");
// The row sticks, not the header: a sticky element only sticks inside its parent.
expect(top.closest("main > div > div")).toHaveClass("sticky", "top-0");
expect(top.closest(".max-w-5xl")).toBeNull();
expect(screen.getAllByRole("banner")).toHaveLength(1);
const rows = Array.from(document.querySelector("main > div")!.children);
expect(rows.map((r) => r.classList.contains("mt-10"))).toEqual([false, false]);
});
it("a top bar without a logo shows the company name, and no button without one", () => {
render(<LandingPage company={{ ...company, logoImageId: null }} page={{ ...page([{ type: "TOPBAR" }]), hideHeader: true }} />);
const top = screen.getByRole("banner");
expect(top).toHaveTextContent("INS Sdn Bhd");
expect(within(top).queryByRole("link")).toBeNull();
});
it("named blocks keep clear of a sticky bar when jumped to", () => {
render(<LandingPage company={company} page={page([bar, { type: "FORM", heading: "Join", closed: true, anchor: "consult" }])} />);
expect(document.getElementById("consult")).toHaveClass("scroll-mt-24");
});
it("shows a section's label above its heading, and section headings in serif", () => {
render(<LandingPage company={company} page={page([
{ type: "FEATURES", eyebrow: "Services", heading: "Everything your guests touch", cards: [{ icon: "wifi", title: "WiFi", text: "Fast." }] },
{ type: "FAQ", eyebrow: "FAQ", heading: "Questions hotels ask us", items: [{ question: "Q", answer: "A" }], look: "DARK" },
])} />);
const heading = screen.getByRole("heading", { level: 2, name: "Everything your guests touch" });
expect(heading).toHaveClass("font-serif");
const label = heading.previousElementSibling!;
expect(label).toHaveTextContent("Services");
expect(label).toHaveClass("uppercase");
expect(screen.getByRole("heading", { level: 2, name: "Questions hotels ask us" })).toHaveClass("font-serif");
expect(screen.getByRole("heading", { level: 2, name: "Questions hotels ask us" }).previousElementSibling).toHaveClass("text-primary");
});
});
@@ -42,36 +42,96 @@ function ButtonLink({ block, index, edit }: { block: CmsBlock; index: number; ed
);
}
// add-landing-page-polish: a section's serif heading, with its optional label above. The label is the accent colour,
// darkened toward the text colour on light backgrounds, where a pale accent would be hard to read.
const LABEL_COLOUR: Record<string, string> = {
DARK: "text-primary",
ACCENT: "opacity-80",
LIGHT: "text-[color-mix(in_srgb,var(--primary)_60%,var(--foreground))]",
};
const LABELLED = ["FEATURES", "STEPS", "IMAGE_TEXT", "FAQ", "CTA"];
function SectionHeading({ block, index, className }: { block: CmsBlock; index: number; className: string }) {
const band = bandOf(block.look);
return (
<>
{LABELLED.includes(block.type) && <Text as="p" index={index} path="eyebrow" value={block.eyebrow} max={40} code="PagesEyebrow"
className={`mb-2 text-xs font-semibold tracking-widest uppercase ${LABEL_COLOUR[band === "DARK" || band === "ACCENT" ? band : "LIGHT"]}`} />}
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className={`font-serif font-semibold ${className}`} />
</>
);
}
function Block({ block, index, company, slug, preview, edit }: { block: PublicBlock; index: number; company: string; slug: string; preview?: boolean; edit?: boolean }) {
const image = block.imageId ? imageSrc(block.imageId) : undefined;
const button = <ButtonLink block={block} index={index} edit={edit} />;
switch (block.type) {
case "HERO": {
const wide = !!block.fullWidth;
const points = block.cards?.length ? (
<ul className="space-y-2">
{block.cards.map((card, i) => (
<li key={i} className="flex items-baseline gap-3 before:size-2 before:shrink-0 before:rounded-full before:bg-primary">
<Text as="span" index={index} path={`cards.${i}.title`} value={card.title} max={80} code="PagesPointN" n={i + 1} />
</li>
))}
</ul>
) : null;
const words = (
<>
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-3xl font-semibold sm:text-4xl" />
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading"
className={wide ? "font-serif text-4xl leading-tight font-semibold sm:text-5xl" : "text-3xl font-semibold sm:text-4xl"} />
<Text as="p" index={index} path="text" value={block.text} max={300} code="PagesText" className="max-w-2xl text-lg" />
{points}
<div>{button}</div>
</>
);
// add-hero-signup-form: with an event, the sign-up form sits in a card beside the text (below it on phones).
if (block.eventUuid) {
// Top padding leaves room for the editor's image button in the corner.
const grid = "grid items-start gap-6 px-6 pt-16 pb-6 md:grid-cols-[minmax(0,1fr)_minmax(0,26rem)] md:px-10 md:pb-10";
// add-hero-full-width: the card may open with its own heading and text.
const card = block.eventUuid ? (
<div className="space-y-4 rounded-lg border bg-card p-6 text-card-foreground shadow-card">
{block.formHeading || block.formText || edit ? (
<div className="space-y-1">
<Text as="h3" index={index} path="formHeading" value={block.formHeading} max={80} code="PagesFormHeading" className="font-serif text-2xl font-semibold" />
<Text as="p" index={index} path="formText" value={block.formText} max={200} code="PagesFormText" className="text-sm text-muted-foreground" />
</div>
) : null}
<LandingForm companyCode={company} slug={slug} index={index} info={block.closed ? undefined : block.form} preview={preview} thanks={block.thanksText} />
</div>
) : null;
const back = bandOf(block.look) ? "" : "bg-muted";
if (wide) {
// Edge to edge; the shade is darkest behind the text and clears toward the far side. The text is centred in the
// hero's opening height, not beside a long form, so it stays in the first screen.
const grid = `mx-auto grid w-full max-w-6xl items-start gap-8 px-4 pt-16 pb-12 ${card ? "md:grid-cols-[minmax(0,1fr)_minmax(0,28rem)]" : ""}`;
return (
<section className={`relative overflow-hidden rounded-lg ${bandOf(block.look) ? "" : "bg-muted"}`}>
<section className={`relative overflow-hidden ${back}`}>
<ImageSpot index={index} src={image} className="absolute inset-0 h-full w-full object-cover" corner />
<HeroShade index={index} image={!!image} shaded={`relative ${grid} bg-gradient-to-r from-black/80 via-black/60 to-black/40 text-white sm:min-h-96`} plain={grid}>
<div className="flex flex-col gap-3">{words}</div>
<div className="rounded-lg border bg-card p-6 text-card-foreground shadow-card">
<LandingForm companyCode={company} slug={slug} index={index} info={block.closed ? undefined : block.form} preview={preview} />
<HeroShade index={index} image={!!image} shaded="relative bg-gradient-to-r from-black/60 to-black/60 text-white md:from-black/55 md:to-black/10 md:to-70%" plain="">
<div className={grid}>
<div className="flex flex-col justify-center gap-4 md:min-h-[32rem]">{words}</div>
{card}
</div>
</HeroShade>
</section>
);
}
if (card) {
// Top padding leaves room for the editor's image button in the corner.
const grid = "grid items-start gap-6 px-6 pt-16 pb-6 md:grid-cols-[minmax(0,1fr)_minmax(0,26rem)] md:px-10 md:pb-10";
return (
<section className={`relative overflow-hidden rounded-lg ${back}`}>
<ImageSpot index={index} src={image} className="absolute inset-0 h-full w-full object-cover" corner />
<HeroShade index={index} image={!!image} shaded={`relative ${grid} bg-gradient-to-r from-black/80 via-black/60 to-black/40 text-white sm:min-h-96`} plain={grid}>
<div className="flex flex-col gap-3">{words}</div>
{card}
</HeroShade>
</section>
);
}
return (
<section className={`relative overflow-hidden rounded-lg ${bandOf(block.look) ? "" : "bg-muted"}`}>
<section className={`relative overflow-hidden rounded-lg ${back}`}>
<ImageSpot index={index} src={image} className="absolute inset-0 h-full w-full object-cover" corner />
<HeroShade index={index} image={!!image}
shaded="relative flex min-h-72 flex-col justify-end gap-3 bg-gradient-to-t from-black/80 via-black/50 to-transparent p-6 text-white sm:min-h-96"
@@ -94,7 +154,7 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
</div>
) : null}
<div className="space-y-3">
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold" />
<SectionHeading block={block} index={index} className="text-2xl" />
<RichSpot index={index} html={block.html} className={PROSE}>{block.html ? <SafeHtml html={block.html} className={PROSE} /> : null}</RichSpot>
{button}
</div>
@@ -103,7 +163,7 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
case "FAQ":
return block.items?.length ? (
<section className="space-y-3">
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-2xl font-semibold" />
<SectionHeading block={block} index={index} className="text-2xl" />
<div className="divide-y rounded-lg border">
{block.items.map((item, i) => {
const question = <Text as="span" index={index} path={`items.${i}.question`} value={item.question} max={300} code="PagesQuestionN" n={i + 1} />;
@@ -124,15 +184,15 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
case "FORM":
return (
<section className="mx-auto w-full max-w-md space-y-4 rounded-lg border bg-card p-6 shadow-card">
<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} />
<SectionHeading block={block} index={index} className="text-2xl" />
<LandingForm companyCode={company} slug={slug} index={index} info={block.closed ? undefined : block.form} preview={preview} thanks={block.thanksText} />
</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" />
<SectionHeading block={block} index={index} className="text-2xl 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">
@@ -152,7 +212,7 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
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" />
<SectionHeading block={block} index={index} className="text-2xl 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">
@@ -177,11 +237,26 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
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" />
<SectionHeading block={block} index={index} className="text-2xl 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>
);
case "FOOTER":
// add-landing-thanks-and-footer: columns of title and text with contact links, the legal line under a divider.
return (
<footer role="contentinfo" className="text-sm [&_a]:text-primary [&_a]:hover:underline">
<ul className={`grid gap-8 ${["", "", "md:grid-cols-2", "md:grid-cols-3", "md:grid-cols-4"][block.cards?.length ?? 0]}`}>
{(block.cards ?? []).map((card, i) => (
<li key={i} className="space-y-1.5">
<Text as="h2" index={index} path={`cards.${i}.title`} value={card.title} max={80} code="PagesCardTitle" className="font-semibold" />
<Text as="p" index={index} path={`cards.${i}.text`} value={card.text} max={300} code="PagesCardText" multiline links className="whitespace-pre-line opacity-80" />
</li>
))}
</ul>
<Text as="p" index={index} path="text" value={block.text} max={300} code="PagesFooterLegal" className="mt-8 border-t border-muted-foreground/30 pt-4 text-xs opacity-70" />
</footer>
);
default:
return null;
}
@@ -189,13 +264,39 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
const WIDTH = "mx-auto w-full max-w-5xl px-4";
/** add-landing-page-polish: the company logo (or name) and an optional button, kept at the top of the window. */
function TopBar({ block, index, company, edit }: { block: CmsBlock; index: number; company: Branding; edit: boolean }) {
return (
<header role="banner" id={anchorId(block.anchor)} className="border-b bg-card/95 backdrop-blur">
<div className="mx-auto flex max-w-6xl items-center justify-between gap-3 px-4 py-3">
{company.logoImageId ? (
// eslint-disable-next-line @next/next/no-img-element -- the company's uploaded logo
<img src={imageSrc(company.logoImageId)} alt={company.name} className="h-10 w-auto" />
) : (
<span className="text-lg font-semibold">{company.name}</span>
)}
<ButtonLink block={block} index={index} edit={edit} />
</div>
</header>
);
}
/**
* Blocks that run the full window width: Custom HTML, a full-width hero, and a coloured band (add-compact-landing-form).
* Two of them in a row join with no gap.
*/
const bleeds = (block: PublicBlock) => block.type === "HTML" || block.type === "TOPBAR" || (block.type === "HERO" && !!block.fullWidth) || !!bandOf(block.look);
/** 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>;
// add-hero-full-width: a full-width hero sets its own width.
if (block.type === "HERO" && block.fullWidth) return <EditSection index={index}><div id={anchorId(block.anchor)}>{children}</div></EditSection>;
// add-landing-page-polish: a #name jump lands clear of a sticky top bar.
if (!band) return <EditSection index={index}><div id={anchorId(block.anchor)} className={`scroll-mt-24 ${WIDTH}`}>{children}</div></EditSection>;
return (
<EditSection index={index}>
<div id={anchorId(block.anchor)} data-look={band} className={`py-12 ${BANDS[band]}`}>
<div id={anchorId(block.anchor)} data-look={band} className={`scroll-mt-16 py-12 ${BANDS[band]}`}>
<div className={WIDTH}>{children}</div>
</div>
</EditSection>
@@ -235,10 +336,17 @@ export function LandingPage({ company, page, banner, preview, frameBase, edit }:
</header>}
<main className={page.hideHeader ? "pb-8" : "py-8"}>
<h1 className={page.hideHeader ? "sr-only" : `${WIDTH} mb-10 text-3xl font-semibold sm:text-4xl`}>{page.title}</h1>
<div className="space-y-10">
{page.blocks.map((block, i) => block.type === "HTML"
? <HtmlSpot key={i} index={i}><HtmlFrame id={anchorId(block.anchor)} src={`${frames}/${i}${edit ? `?v=${edit.frameVersion}` : ""}`} title={page.title} /></HtmlSpot>
: <Section key={i} block={block} index={i}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} edit={!!edit} /></Section>)}
<div>
{page.blocks.map((block, i) => (
// A top bar's row is what sticks: a sticky element only sticks inside its parent, and the rows share the page's.
<div key={i} className={block.type === "TOPBAR" ? "sticky top-0 z-20" : i > 0 && !(bleeds(block) && bleeds(page.blocks[i - 1])) ? "mt-10" : undefined}>
{block.type === "TOPBAR"
? <EditSection index={i}><TopBar block={block} index={i} company={company} edit={!!edit} /></EditSection>
: block.type === "HTML"
? <HtmlSpot index={i}><HtmlFrame id={anchorId(block.anchor)} src={`${frames}/${i}${edit ? `?v=${edit.frameVersion}` : ""}`} title={page.title} /></HtmlSpot>
: <Section block={block} index={i}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} edit={!!edit} /></Section>}
</div>
))}
</div>
</main>
</div>
@@ -4,6 +4,7 @@ import { createContext, useContext, useLayoutEffect, useRef, type ElementType, t
import dynamic from "next/dynamic";
import { ImagePlus } from "lucide-react";
import { BLOCK_LABELS, type CmsBlock } from "@/app/lib/cmsPages";
import { contactLinks } from "@/app/lib/contactLinks";
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
@@ -45,7 +46,7 @@ export function setField(block: CmsBlock, path: string, value: string): CmsBlock
* 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 }: {
export function Text({ as: Tag, index, path, value, max, code, n, className, multiline, links }: {
as: ElementType;
index: number;
path: string;
@@ -56,9 +57,11 @@ export function Text({ as: Tag, index, path, value, max, code, n, className, mul
n?: number;
className?: string;
multiline?: boolean;
/** Outside the editor, show contact details as links (add-landing-thanks-and-footer). */
links?: boolean;
}) {
const edit = useEdit();
if (!edit) return value ? <Tag className={className}>{value}</Tag> : null;
if (!edit) return value ? <Tag className={className}>{links ? contactLinks(value) : 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} />;
}
@@ -5,14 +5,14 @@ import { Check, Copy } from "lucide-react";
import { Button } from "@/app/components/ui/button";
import { useT } from "@/app/lib/i18n/MessagesProvider";
/** A page address with a button that copies its full URL (this site's origin plus the path). */
export function CopyAddress({ address }: { address: string }) {
/** A page address with a button that copies its full URL (this site's origin plus the path), or the path itself when `relative`. */
export function CopyAddress({ address, relative }: { address: string; relative?: boolean }) {
const t = useT();
const [state, setState] = useState<"idle" | "copied" | "failed">("idle");
async function copy() {
try {
await navigator.clipboard.writeText(`${window.location.origin}${address}`);
await navigator.clipboard.writeText(relative ? address : `${window.location.origin}${address}`);
setState("copied");
setTimeout(() => setState("idle"), 2000);
} catch {
@@ -1,7 +1,10 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { FRAME_SANDBOX, frameAnchor, nextFrameHeight, START_HEIGHT, type FrameHeight } from "@/app/lib/frameHtml";
import { FRAME_ASK_MESSAGE, FRAME_SANDBOX, frameAnchor, nextFrameHeight, START_HEIGHT, type FrameHeight } from "@/app/lib/frameHtml";
// add-hero-full-width: the frame may have reported before this page listened; ask on mount, and again when it loads.
const ask = (frame: HTMLIFrameElement | null) => frame?.contentWindow?.postMessage({ type: FRAME_ASK_MESSAGE }, "*");
/** 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({ id, src, title }: { id?: string; src: string; title: string }) {
@@ -22,7 +25,8 @@ export function HtmlFrame({ id, src, title }: { id?: string; src: string; title:
if (block?.closest("main")) block.scrollIntoView({ behavior: "smooth" });
};
host.addEventListener("message", onMessage);
ask(ref.current);
return () => host.removeEventListener("message", onMessage);
}, []);
return <iframe ref={ref} id={id} src={src} title={title} sandbox={FRAME_SANDBOX} loading="lazy" className="block w-full border-0" style={{ height: `${size.height}px` }} />;
return <iframe ref={ref} id={id} src={src} title={title} sandbox={FRAME_SANDBOX} loading="lazy" onLoad={(e) => ask(e.currentTarget)} className="block w-full border-0" style={{ height: `${size.height}px` }} />;
}
@@ -7,6 +7,7 @@ import { VisitorState } from "@/app/components/registration/VisitorCard";
import { RegistrationForm } from "@/app/components/registration/RegistrationForm";
import { publicCall, type RegistrationBody, type RegistrationInfo } from "@/app/lib/services/publicRegistration";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { contactLinks } from "@/app/lib/contactLinks";
const UTM = ["utm_source", "utm_medium", "utm_campaign"] as const;
@@ -18,7 +19,8 @@ export function utmTags(search: string): { utmSource?: string; utmMedium?: strin
}
// A landing page's FORM block: the QR sign-up form, posting to the page's block, with the visitor's UTM tags.
export function LandingForm({ companyCode, slug, index, info, preview }: { companyCode: string; slug: string; index: number; info?: RegistrationInfo; preview?: boolean }) {
// add-landing-thanks-and-footer: `thanks` is the page's own text under the thank-you, with contact links.
export function LandingForm({ companyCode, slug, index, info, preview, thanks }: { companyCode: string; slug: string; index: number; info?: RegistrationInfo; preview?: boolean; thanks?: string }) {
const t = useT();
const [phase, setPhase] = useState<"form" | "done" | "closed">(info ? "form" : "closed");
@@ -26,6 +28,7 @@ export function LandingForm({ companyCode, slug, index, info, preview }: { compa
if (phase === "closed" || !info) return <VisitorState icon={AlertCircle} heading={t("PagesFormClosed")} role="status" />;
if (phase === "done") {
return <VisitorState icon={CheckCircle2} heading={t("RegThanks", { event: info.eventName })} role="status"
text={thanks ? contactLinks(thanks) : undefined}
action={<Button className="h-11" onClick={() => setPhase("form")}>{t("RegAnother")}</Button>} />;
}
const submit = (body: RegistrationBody) =>
@@ -33,5 +36,5 @@ export function LandingForm({ companyCode, slug, index, info, preview }: { compa
method: "POST",
body: JSON.stringify({ ...body, ...utmTags(window.location.search) }),
});
return <RegistrationForm info={info} submit={submit} onDone={() => setPhase("done")} onInactive={() => setPhase("closed")} />;
return <RegistrationForm info={info} submit={submit} onDone={() => setPhase("done")} onInactive={() => setPhase("closed")} compact />;
}
@@ -64,4 +64,42 @@ describe("PageEditor: Custom HTML", () => {
expect(box.closest("div")).toHaveTextContent("Too long.");
expect(box).toHaveAttribute("aria-invalid", "true");
});
// add-html-image-upload: upload an image from the block's panel and copy its link; the HTML stays as it was.
it("uploads an image at once for the page's company and shows its link to copy", async () => {
mocks.uploadPageImage.mockResolvedValueOnce({ id: 42 });
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
await screen.findByLabelText("HTML");
await user.upload(screen.getByLabelText("Upload image"), new File(["png"], "lobby.png", { type: "image/png" }));
expect(await screen.findByText("/api/public/page-images/42")).toBeInTheDocument();
expect(mocks.uploadPageImage).toHaveBeenCalledWith(2, btoa("png"));
expect(screen.getByRole("img", { name: "Image preview" })).toHaveAttribute("src", "/api/public/page-images/42");
const write = vi.spyOn(navigator.clipboard, "writeText");
await user.click(screen.getByRole("button", { name: "Copy link /api/public/page-images/42" }));
expect(write).toHaveBeenCalledWith("/api/public/page-images/42");
expect(screen.getByLabelText("HTML")).toHaveValue("<h1>Designed</h1>");
expect(mocks.savePage).not.toHaveBeenCalled();
});
it("shows a refused upload's reason and no link", async () => {
mocks.uploadPageImage.mockRejectedValueOnce(new ApiError("x", 422, { code: "PagesImageTooLarge" }));
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
await screen.findByLabelText("HTML");
await user.upload(screen.getByLabelText("Upload image"), new File(["big"], "big.jpg", { type: "image/jpeg" }));
expect(await screen.findByText("The image is larger than 2 MB.")).toBeInTheDocument();
expect(screen.queryByText(/\/api\/public\/page-images\//)).not.toBeInTheDocument();
});
it("asks a super admin's new page for a company before uploading", async () => {
mocks.useAdminAuth.mockReturnValue({ isSuper: true, companyCode: null });
memoryRouter.reset("/pages/new");
const user = userEvent.setup();
render(<PageEditor />);
await user.click(screen.getByRole("button", { name: "Add Custom HTML" }));
await user.upload(await screen.findByLabelText("Upload image"), new File(["png"], "lobby.png", { type: "image/png" }));
expect(await screen.findByText("Choose a company.")).toBeInTheDocument();
expect(mocks.uploadPageImage).not.toHaveBeenCalled();
});
});
@@ -76,6 +76,50 @@ describe("PageEditor: sections", () => {
expect(within(within(block).getByRole("group", { name: "Step 6" })).getByRole("button", { name: "Remove" })).toBeEnabled();
});
// add-landing-thanks-and-footer: a dark footer of 1 to 4 columns with a legal line.
it("adds a dark footer with columns and a legal line, and keeps 1 to 4 columns", async () => {
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
await screen.findByDisplayValue("How it works");
await user.click(screen.getByRole("button", { name: "Add Footer" }));
const block = group("Block 3: Footer");
expect(within(block).getByLabelText("Look")).toHaveValue("DARK");
const col1 = within(block).getByRole("group", { name: "Column 1" });
await user.type(within(col1).getByLabelText("Title"), "Talk to us");
await user.type(within(col1).getByLabelText("Text"), "+603-7623 9807");
await user.click(within(within(block).getByRole("group", { name: "Column 2" })).getByRole("button", { name: "Remove" }));
expect(within(col1).getByRole("button", { name: "Remove" })).toBeDisabled();
await user.type(within(block).getByLabelText("Legal line"), "© 2026 INS");
const add = within(block).getByRole("button", { name: "Add column" });
for (let i = 0; i < 3; i++) await user.click(add);
expect(add).toBeDisabled();
for (const n of [4, 3, 2]) await user.click(within(within(block).getByRole("group", { name: `Column ${n}` })).getByRole("button", { name: "Remove" }));
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: "FOOTER", look: "DARK", text: "© 2026 INS", cards: [{ title: "Talk to us", text: "+603-7623 9807" }],
});
});
// add-landing-page-polish: the top bar's button, and a label above a section's heading.
it("adds a top bar with a button and no look, and saves a section label", async () => {
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
await screen.findByDisplayValue("How it works");
await user.type(within(group("Block 1: Steps")).getByLabelText("Label"), "How we work");
await user.click(screen.getByRole("button", { name: "Add Top bar" }));
const block = group("Block 3: Top bar");
expect(within(block).queryByLabelText("Look")).not.toBeInTheDocument();
expect(within(block).queryByLabelText("Label")).not.toBeInTheDocument();
await user.type(within(block).getByLabelText("Button label"), "Get My Free Consultation");
await user.type(within(block).getByLabelText("Button link"), "#consult");
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalled());
const blocks = mocks.savePage.mock.calls[0][1].blocks;
expect(blocks[0]).toMatchObject({ type: "STEPS", eyebrow: "How we work" });
expect(blocks[2]).toEqual({ type: "TOPBAR", buttonLabel: "Get My Free Consultation", buttonUrl: "#consult" });
});
it("offers no look for a Custom HTML block", async () => {
render(<PageEditor pageId={5} />);
await screen.findByDisplayValue("How it works");
@@ -125,6 +125,54 @@ describe("PageEditor", () => {
expect(mocks.savePage.mock.calls[1][1].blocks[0].eventUuid ?? null).toBeNull();
});
// add-hero-full-width: Full width, points, and the form card's heading and text (only while the hero has a form).
it("saves a full-width hero with points and a form heading; No form drops the heading and text", async () => {
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
const picker = await screen.findByLabelText("Sign-up form");
expect(screen.queryByLabelText("Form heading")).not.toBeInTheDocument();
await user.click(screen.getByRole("switch", { name: "Full width" }));
await user.click(screen.getByRole("button", { name: "Add point" }));
await user.type(screen.getByRole("textbox", { name: "Point 1" }), "Local support team");
await waitFor(() => expect(within(picker).getByRole("option", { name: "Website enquiries" })).toBeInTheDocument());
await user.selectOptions(picker, "3312726793093644288");
await user.type(screen.getByLabelText("Form heading"), "Get a free consultation");
await user.type(screen.getByLabelText("Form text"), "It takes a minute.");
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalledTimes(1));
expect(mocks.savePage.mock.calls[0][1].blocks[0]).toMatchObject({
type: "HERO", fullWidth: true, cards: [{ title: "Local support team" }],
formHeading: "Get a free consultation", formText: "It takes a minute.",
});
await user.selectOptions(screen.getByLabelText("Sign-up form"), "");
expect(screen.queryByLabelText("Form heading")).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalledTimes(2));
const hero = mocks.savePage.mock.calls[1][1].blocks[0];
expect([hero.formHeading, hero.formText]).toEqual([undefined, undefined]);
});
// add-landing-thanks-and-footer: the hero's thank-you text, only while it has a form.
it("saves a hero's thank-you text; No form drops it", async () => {
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
const picker = await screen.findByLabelText("Sign-up form");
// The FORM block (block 2) has its own thank-you field; these checks are the hero's.
const hero = () => within(screen.getByRole("group", { name: /^Block 1/ }));
expect(hero().queryByLabelText("Thank-you text")).not.toBeInTheDocument();
await waitFor(() => expect(within(picker).getByRole("option", { name: "Website enquiries" })).toBeInTheDocument());
await user.selectOptions(picker, "3312726793093644288");
await user.type(hero().getByLabelText("Thank-you text"), "Call +60 12-833 2775.");
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalledTimes(1));
expect(mocks.savePage.mock.calls[0][1].blocks[0]).toMatchObject({ type: "HERO", thanksText: "Call +60 12-833 2775." });
await user.selectOptions(screen.getByLabelText("Sign-up form"), "");
expect(hero().queryByLabelText("Thank-you text")).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalledTimes(2));
expect(mocks.savePage.mock.calls[1][1].blocks[0].thanksText).toBeUndefined();
});
it("a super admin must choose a company for a new page", async () => {
mocks.useAdminAuth.mockReturnValue({ isSuper: true, companyCode: null });
const user = userEvent.setup();
@@ -223,6 +223,7 @@ function FormEditor({ p, ask }: { p: Draft; ask: Ask }) {
onMove={(delta) => p.moveBlock(index, delta)}
onRemove={() => p.removeBlock(row.key)}
onChooseImage={(file) => p.chooseImage(row.key, file)}
onUploadImage={p.uploadImage}
/>
))}
<FieldError message={errors.blocks} />
@@ -58,6 +58,24 @@ describe("usePageDraft for the on-page editor", () => {
expect(result.current.rows.map((r) => r.block.eventUuid ?? null)).toEqual([null, null, null]);
});
// add-hero-full-width: the form card's heading and text go with the form, or the server refuses the save.
it("a company switch also drops a hero's form heading and text", async () => {
mocks.getPage.mockResolvedValueOnce({ ...stored, blocks: [
{ type: "HERO" as const, heading: "Hi", eventUuid: "77", formHeading: "Get a free consultation", formText: "Quick." },
] });
const { result } = await loaded();
act(() => result.current.changeCompany(3));
expect(result.current.rows[0].block).toEqual({ type: "HERO", heading: "Hi", eventUuid: null });
});
// add-landing-thanks-and-footer: a hero's thank-you text goes with its form too.
it("a company switch also drops a hero's thank-you text", async () => {
mocks.getPage.mockResolvedValueOnce({ ...stored, blocks: [{ type: "HERO" as const, heading: "Hi", eventUuid: "77", thanksText: "Call us." }] });
const { result } = await loaded();
act(() => result.current.changeCompany(3));
expect(result.current.rows[0].block).toEqual({ type: "HERO", heading: "Hi", eventUuid: null });
});
it("keeps the company's branding from the loaded page", async () => {
const { result } = await loaded();
expect(result.current.branding).toEqual(stored.company);
@@ -191,11 +191,18 @@ export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: numbe
step("page:title");
setDraft((d) => withTitle(d, title));
};
/** A super admin's new page changes company: FORM blocks and hero sign-up forms lose their event, which belongs to the old one. */
/**
* A super admin's new page changes company: FORM blocks and hero sign-up forms lose their event, which belongs to the old one,
* and a hero's form heading, form text and thank-you text go with its form (add-hero-full-width, add-landing-thanks-and-footer).
*/
const changeCompany = (companyId: number) => {
step(null);
setDraft((d) => ({ ...d, companyId }));
setRows((rs) => rs.map((r) => (r.block.eventUuid ? { ...r, block: { ...r.block, eventUuid: null } } : r)));
setRows((rs) => rs.map((r) => {
if (!r.block.eventUuid) return r;
const { formHeading: _h, formText: _t, thanksText: _k, ...block } = r.block;
return { ...r, block: { ...block, eventUuid: null } };
}));
};
const setBlock = (key: number, update: (block: CmsBlock) => CmsBlock) =>
setRows((rs) => rs.map((r) => (r.key === key ? { ...r, block: update(r.block) } : r)));
@@ -318,6 +325,20 @@ export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: numbe
}
}
/**
* add-html-image-upload: uploads an image for a Custom HTML block at once, for the page's company. Resolves to its id;
* rejects with the reason to show (no company yet, or the server's refusal).
*/
async function uploadImage(file: File): Promise<number> {
if (isSuper && !draft.companyId) throw new Error(t("ChooseCompany"));
try {
return (await uploadPageImage(draft.companyId, (await readDataUrl(file)).split(",")[1])).id;
} catch (err) {
const code = err instanceof ApiError ? (err.data as { code?: string } | undefined)?.code : undefined;
throw new Error(t(code ?? "PagesSaveFailed"));
}
}
/** Saves the current edits, then makes the draft live. */
async function publishChanges() {
if (draft.id == null || !(await save())) return;
@@ -377,7 +398,7 @@ export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: numbe
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,
chooseImage, uploadImage, blockErrors,
save, publishChanges, discardChanges, remove,
};
}
@@ -198,6 +198,7 @@ export function VisualEditor({ p, ask }: { p: Draft; ask: Ask }) {
onMove={(delta) => p.moveBlock(selected, delta)}
onRemove={() => p.removeBlock(row.key)}
onChooseImage={(f) => p.chooseImage(row.key, f)}
onUploadImage={p.uploadImage}
/>
</>
) : (
@@ -0,0 +1,49 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { RegistrationForm } from "./RegistrationForm";
// add-compact-landing-form: landing pages use a short form; QR, invitation and customer forms keep the full one.
const info = {
eventName: "INS enquiries", startDate: "2026-12-01", endDate: "2099-12-31", location: "KL", companyName: "INS",
notice: { id: 1, textEn: "English text", textMs: "Teks Melayu" },
interests: [{ id: 11, name: "WiFi Managed Services" }, { id: 12, name: "Cloud IP PABX" }],
};
const base = { info, onDone: () => {}, onInactive: () => {} };
describe("RegistrationForm compact", () => {
it("has no job title, one service dropdown, and the notice folded above the consent box", async () => {
const user = userEvent.setup();
render(<RegistrationForm {...base} submit={async () => undefined} compact />);
expect(screen.queryByLabelText("Job title")).not.toBeInTheDocument();
expect(screen.queryByRole("checkbox", { name: "WiFi Managed Services" })).not.toBeInTheDocument();
const service = screen.getByRole("combobox", { name: "Service interested in (optional)" });
expect(service).toHaveValue("");
expect(screen.getByRole("option", { name: "Choose a service" })).toBeInTheDocument();
const notice = screen.getByText("English text").closest("details")!;
expect(notice).not.toHaveAttribute("open");
await user.click(screen.getByText("How we use your details (English / Bahasa Malaysia)"));
expect(notice).toHaveAttribute("open");
expect(notice.compareDocumentPosition(screen.getByRole("checkbox")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
it("posts the one chosen service", async () => {
const submit = vi.fn().mockResolvedValue(undefined);
const user = userEvent.setup();
render(<RegistrationForm {...base} submit={submit} compact />);
await user.type(screen.getByLabelText("Your name"), "Tan");
await user.type(screen.getByLabelText("Mobile number"), "0125550101");
await user.selectOptions(screen.getByRole("combobox", { name: "Service interested in (optional)" }), "12");
await user.click(screen.getByRole("checkbox"));
await user.click(screen.getByRole("button", { name: "Register" }));
expect(submit.mock.calls[0][0]).toMatchObject({ interestIds: [12], jobTitle: "" });
});
it("keeps the full form without the option", () => {
render(<RegistrationForm {...base} submit={async () => undefined} />);
expect(screen.getByLabelText("Job title")).toBeInTheDocument();
expect(screen.getByRole("checkbox", { name: "WiFi Managed Services" })).toBeInTheDocument();
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
expect(screen.getByText("English text").closest("details")).toBeNull();
});
});
@@ -15,6 +15,7 @@ const FIELDS = ["name", "mobile", "email", "companyName", "jobTitle", "consent"]
const ROW = "flex min-h-11 w-full cursor-pointer items-center gap-3 rounded-md border p-3";
const CONSENT_ROW = "flex min-h-11 w-full cursor-pointer items-start gap-3 rounded-md border p-3 leading-normal";
const BOX = "size-6";
const NOTICE = "rounded-md bg-muted p-3 text-xs text-muted-foreground";
export function apiData(err: unknown): { status?: number; code?: string; error?: string; field?: string } {
if (!(err instanceof ApiError)) return {};
@@ -40,11 +41,13 @@ interface Props {
onDone: () => void;
/** The code or invitation was switched off: the page shows its own message. */
onInactive: () => void;
/** add-compact-landing-form: a landing page's short form: no job title, one service dropdown, the notice folded. */
compact?: boolean;
}
// The visitor registration form shared by /r, /i and /c: fields, bilingual privacy notice and consent.
// The event header comes from the VisitorCard around it.
export function RegistrationForm({ tooManyKey, info, initial, submit, onDone, onInactive }: Props) {
export function RegistrationForm({ tooManyKey, info, initial, submit, onDone, onInactive, compact }: Props) {
const t = useT();
const [form, setForm] = useState<RegistrationBody>({ ...EMPTY, ...initial });
const [errors, setErrors] = useState<Record<string, string>>({});
@@ -94,6 +97,42 @@ export function RegistrationForm({ tooManyKey, info, initial, submit, onDone, on
);
};
const interestBoxes = (
<fieldset className="space-y-2">
<legend className="text-sm font-medium">{t("RegInterests")}</legend>
{info.interests.map((i) => (
<Label key={i.id} htmlFor={`reg-interest-${i.id}`} className={ROW}>
<Checkbox
className={BOX}
id={`reg-interest-${i.id}`}
checked={form.interestIds.includes(i.id)}
onCheckedChange={(on) => set({ interestIds: on ? [...form.interestIds, i.id] : form.interestIds.filter((x) => x !== i.id) })}
/>
{i.name}
</Label>
))}
</fieldset>
);
// add-compact-landing-form: a landing page asks for at most one service.
const serviceDropdown = (
<div className="space-y-1.5">
<Label htmlFor="reg-service">{t("RegServiceInterest")}</Label>
<select id="reg-service" className="flex h-11 w-full rounded-md border border-input bg-transparent px-3 text-base shadow-sm disabled:opacity-50"
value={form.interestIds[0] ?? ""} disabled={saving} onChange={(e) => set({ interestIds: e.target.value ? [Number(e.target.value)] : [] })}>
<option value="">{t("RegChooseService")}</option>
{info.interests.map((i) => <option key={i.id} value={i.id}>{i.name}</option>)}
</select>
</div>
);
const notice = (
<>
<h2 className="font-semibold text-foreground">{t("RegNoticeEn")}</h2>
<p className="whitespace-pre-line">{info.notice.textEn}</p>
<h2 className="font-semibold text-foreground">{t("RegNoticeMs")}</h2>
<p className="whitespace-pre-line">{info.notice.textMs}</p>
</>
);
return (
<form onSubmit={onSubmit} className="space-y-4" noValidate>
{formError && <p role="alert" className="text-sm text-destructive">{formError}</p>}
@@ -101,29 +140,16 @@ export function RegistrationForm({ tooManyKey, info, initial, submit, onDone, on
{field("mobile", t("RegMobile"), "tel", t("RegContactHint"))}
{field("email", t("RegEmail"), "email")}
{field("companyName", t("RegCompany"))}
{field("jobTitle", t("RegJobTitle"))}
{info.interests.length > 0 && (
<fieldset className="space-y-2">
<legend className="text-sm font-medium">{t("RegInterests")}</legend>
{info.interests.map((i) => (
<Label key={i.id} htmlFor={`reg-interest-${i.id}`} className={ROW}>
<Checkbox
className={BOX}
id={`reg-interest-${i.id}`}
checked={form.interestIds.includes(i.id)}
onCheckedChange={(on) => set({ interestIds: on ? [...form.interestIds, i.id] : form.interestIds.filter((x) => x !== i.id) })}
/>
{i.name}
</Label>
))}
</fieldset>
{compact ? null : field("jobTitle", t("RegJobTitle"))}
{info.interests.length > 0 && (compact ? serviceDropdown : interestBoxes)}
{compact ? (
<details className={NOTICE}>
<summary className="cursor-pointer font-medium text-foreground">{t("RegNoticeSummary")}</summary>
<div className="mt-2 space-y-2">{notice}</div>
</details>
) : (
<div className={`space-y-2 ${NOTICE}`}>{notice}</div>
)}
<div className="space-y-2 rounded-md bg-muted p-3 text-xs text-muted-foreground">
<h2 className="font-semibold text-foreground">{t("RegNoticeEn")}</h2>
<p className="whitespace-pre-line">{info.notice.textEn}</p>
<h2 className="font-semibold text-foreground">{t("RegNoticeMs")}</h2>
<p className="whitespace-pre-line">{info.notice.textMs}</p>
</div>
<Label htmlFor="reg-consent" className={CONSENT_ROW}>
<Checkbox id="reg-consent" className={`${BOX} mt-0.5`} checked={form.consent} onCheckedChange={(on) => set({ consent: on === true })} aria-invalid={!!errors.consent} aria-describedby={errors.consent ? "reg-consent-error" : undefined} />
<span className="space-y-1 font-normal">
@@ -34,7 +34,7 @@ export function VisitorCard({ event, title, children }: { event?: EventHeader; t
interface StateProps {
icon: LucideIcon;
heading: string;
text?: string;
text?: ReactNode;
action?: ReactNode;
role?: "status" | "alert";
tone?: "default" | "error";
@@ -52,7 +52,7 @@ export function VisitorState({ icon: Icon, heading, text, action, role, tone = "
<Icon className={`size-6 ${iconClassName ?? ""}`} aria-hidden="true" />
</span>
<Heading className="text-lg font-semibold text-balance">{heading}</Heading>
{text && <p className="text-sm text-muted-foreground">{text}</p>}
{text && <p className="text-sm text-muted-foreground [&_a]:font-medium [&_a]:text-primary [&_a]:underline">{text}</p>}
{action}
</div>
);
+17 -3
View File
@@ -3,9 +3,9 @@
import { Calendar, Cloud, Headset, Lock, Monitor, Phone, ShieldCheck, Star, Tv, Users, Wifi, Wrench, type LucideIcon } from "lucide-react";
export type BlockType = "HERO" | "RICH_TEXT" | "IMAGE_TEXT" | "FAQ" | "FORM" | "HTML" | "FEATURES" | "STEPS" | "TRUST" | "CTA";
export type BlockType = "HERO" | "RICH_TEXT" | "IMAGE_TEXT" | "FAQ" | "FORM" | "HTML" | "FEATURES" | "STEPS" | "TRUST" | "CTA" | "FOOTER" | "TOPBAR";
export const BLOCK_TYPES: BlockType[] = ["HERO", "RICH_TEXT", "IMAGE_TEXT", "FEATURES", "STEPS", "TRUST", "CTA", "FAQ", "FORM", "HTML"];
export const BLOCK_TYPES: BlockType[] = ["HERO", "RICH_TEXT", "IMAGE_TEXT", "FEATURES", "STEPS", "TRUST", "CTA", "FAQ", "FORM", "HTML", "FOOTER", "TOPBAR"];
/** Feature-card icons by the name services-counter accepts (add-page-sections). */
export const ICONS: Record<string, LucideIcon> = {
@@ -28,9 +28,11 @@ export const BLOCK_LABELS: Record<BlockType, string> = {
STEPS: "PagesBlockSteps",
TRUST: "PagesBlockTrust",
CTA: "PagesBlockCta",
FOOTER: "PagesBlockFooter",
TOPBAR: "PagesBlockTopBar",
};
/** A FEATURES (icon, title, text), STEPS (title, text) or TRUST (title) card. */
/** A FEATURES (icon, title, text), STEPS (title, text) or TRUST (title) card; a HERO's points are title-only cards; a FOOTER's columns are title-and-text cards. */
export interface CmsCard {
icon?: string;
title: string;
@@ -58,6 +60,14 @@ export interface CmsBlock {
cards?: CmsCard[];
/** The FORM block's event (a Snowflake uuid, kept as a string). */
eventUuid?: string | null;
/** add-hero-full-width: a HERO across the whole window, and its form card's heading (80) and text (200). */
fullWidth?: boolean;
formHeading?: string;
formText?: string;
/** add-landing-thanks-and-footer: text (200) under the thank-you after a sign-up; FORM, or HERO with an event. */
thanksText?: string;
/** add-landing-page-polish: a short label (40) above the heading of FEATURES, STEPS, IMAGE_TEXT, FAQ and CTA. */
eyebrow?: string;
}
export type PageStatus = "DRAFT" | "PUBLISHED";
@@ -128,6 +138,10 @@ export function emptyBlock(type: BlockType): CmsBlock {
return { type, cards: [{ title: "" }, { title: "" }] };
case "CTA":
return { type, heading: "", text: "", buttonLabel: "", buttonUrl: "" };
case "TOPBAR":
return { type, buttonLabel: "", buttonUrl: "" };
case "FOOTER":
return { type, look: "DARK", text: "", cards: [{ title: "", text: "" }, { title: "", text: "" }] };
default:
return { type };
}
@@ -0,0 +1,32 @@
import { render } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import { contactLinks } from "./contactLinks";
// add-landing-thanks-and-footer: plain text with its phone numbers, emails and web addresses as links.
const links = (text: string) => {
const { container } = render(<p>{contactLinks(text)}</p>);
return { text: container.textContent, hrefs: Array.from(container.querySelectorAll("a")).map((a) => [a.textContent, a.getAttribute("href")]) };
};
describe("contactLinks", () => {
it("links + phone numbers, emails, https and www addresses, and keeps the rest", () => {
const text = "Call +60 12-833 2775 or +603-7623 9807, mail info@ins.my, see https://ins.my/a?b=1 or www.ins.my.";
const out = links(text);
expect(out.text).toBe(text);
expect(out.hrefs).toEqual([
["+60 12-833 2775", "tel:+60128332775"],
["+603-7623 9807", "tel:+60376239807"],
["info@ins.my", "mailto:info@ins.my"],
["https://ins.my/a?b=1", "https://ins.my/a?b=1"],
["www.ins.my", "https://www.ins.my"],
]);
});
it("leaves short numbers, local numbers and dates alone", () => {
expect(links("03-7623 9807 on 2026-12-04, +60 12").hrefs).toEqual([]);
});
it("never makes javascript or http links", () => {
expect(links("javascript:alert(1) http://ins.my").hrefs).toEqual([]);
});
});
@@ -0,0 +1,21 @@
import type { ReactNode } from "react";
// add-landing-thanks-and-footer: + phone numbers (8+ digits), emails, and https:// or www. addresses in plain text become links.
// It builds elements, never HTML, so the text stays text.
const CONTACT = /(\+\d[\d -]{6,}\d)|([\w.+-]+@[\w-]+(?:\.[\w-]+)+)|((?:https:\/\/|www\.)[^\s<>"]*[^\s<>".,;:!?)])/g;
export function contactLinks(text: string): ReactNode[] {
const out: ReactNode[] = [];
let last = 0;
for (const m of text.matchAll(CONTACT)) {
const [whole, phone, email] = m;
if (phone && phone.replace(/\D/g, "").length < 8) continue;
out.push(text.slice(last, m.index));
const href = phone ? `tel:+${phone.replace(/\D/g, "")}` : email ? `mailto:${email}` : whole.startsWith("www.") ? `https://${whole}` : whole;
const external = !phone && !email;
out.push(<a key={m.index} href={href} {...(external ? { target: "_blank", rel: "noopener noreferrer" } : {})}>{whole}</a>);
last = m.index + whole.length;
}
out.push(text.slice(last));
return out;
}
@@ -47,4 +47,13 @@ describe("frame script: height report", () => {
runFrameScript("<header>Top bar</header>");
expect(post).toHaveBeenCalledWith({ type: "colite-frame-height", height: 70 }, "*");
});
it("reports again when the page asks", () => {
const post = vi.spyOn(window.parent, "postMessage").mockImplementation(() => {});
vi.spyOn(document.documentElement, "getBoundingClientRect").mockReturnValue({ height: 68 } as DOMRect);
runFrameScript("<header>Top bar</header>");
post.mockClear();
window.dispatchEvent(new MessageEvent("message", { data: { type: "colite-frame-ask" } }));
expect(post).toHaveBeenCalledWith({ type: "colite-frame-height", height: 68 }, "*");
});
});
@@ -33,11 +33,13 @@ describe("frameHtml", () => {
expect(frameResponse("<p>x</p>", { preview: false }).headers.get("cache-control")).not.toBe("no-store");
});
it("clamps a reported height between 100 and 20000 pixels and ignores junk", () => {
// add-hero-full-width: the floor is 20 px, so a 68 px top bar keeps its own height.
it("clamps a reported height between 20 and 20000 pixels and ignores junk", () => {
const start = { height: START_HEIGHT, steps: [] };
expect(START_HEIGHT).toBe(600);
expect(nextFrameHeight(start, { type: "colite-frame-height", height: 3000 }).height).toBe(3000);
expect(nextFrameHeight(start, { type: "colite-frame-height", height: 10 }).height).toBe(100);
expect(nextFrameHeight(start, { type: "colite-frame-height", height: 68 }).height).toBe(68);
expect(nextFrameHeight(start, { type: "colite-frame-height", height: 10 }).height).toBe(20);
expect(nextFrameHeight(start, { type: "colite-frame-height", height: 99999 }).height).toBe(20000);
for (const junk of [null, "600", { type: "other", height: 900 }, { type: "colite-frame-height", height: "900" }, { type: "colite-frame-height", height: NaN }]) {
expect(nextFrameHeight(start, junk)).toBe(start);
+5 -3
View File
@@ -6,8 +6,10 @@ export const FRAME_SANDBOX = "allow-scripts allow-popups allow-popups-to-escape-
/** The frame document's own policy. next.config sends it too: config headers replace a route's header of the same name. */
export const FRAME_CSP = `sandbox ${FRAME_SANDBOX}; frame-ancestors 'self'`;
export const FRAME_MESSAGE = "colite-frame-height";
/** The page asks a frame to report its height again: its first report can come before the page listens (add-hero-full-width). */
export const FRAME_ASK_MESSAGE = "colite-frame-ask";
export const START_HEIGHT = 600;
const MIN_HEIGHT = 100;
const MIN_HEIGHT = 20;
const MAX_HEIGHT = 20000;
export const FRAME_ANCHOR_MESSAGE = "colite-frame-anchor";
@@ -15,11 +17,11 @@ export const FRAME_ANCHOR_MESSAGE = "colite-frame-anchor";
const ANCHOR_SOURCE = "^(?!reg-)[a-z0-9][a-z0-9-]{0,39}$";
const ANCHOR = new RegExp(ANCHOR_SOURCE);
// Posts the content height (not scrollHeight, which never drops below the frame itself) to the parent page on load and whenever it changes. A click on a #name link
// Posts the content height (not scrollHeight, which never drops below the frame itself) to the parent page on load, whenever it changes, and when the page asks. 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.getBoundingClientRect().height)},"*")}` +
`addEventListener("load",s);if(window.ResizeObserver)new ResizeObserver(s).observe(document.documentElement);s();` +
`addEventListener("load",s);addEventListener("message",function(e){if(e.data&&e.data.type==="${FRAME_ASK_MESSAGE}")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>`;
@@ -568,6 +568,9 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
RegContactHint: "Mobile or email is required",
RegCompany: "Company",
RegJobTitle: "Job title",
RegServiceInterest: "Service interested in (optional)",
RegChooseService: "Choose a service",
RegNoticeSummary: "How we use your details (English / Bahasa Malaysia)",
RegInterests: "Interests (optional)",
RegNoticeEn: "English",
RegNoticeMs: "Bahasa Malaysia",
@@ -870,6 +873,21 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
PagesFormPreview: "The sign-up form shows here on the published page.",
PagesHeroForm: "Sign-up form",
PagesNoForm: "No form",
PagesFullWidth: "Full width",
PagesPointN: "Point {number}",
PagesAddPoint: "Add point",
PagesFormHeading: "Form heading",
PagesFormText: "Form text",
PagesThanksText: "Thank-you text",
PagesBlockFooter: "Footer",
PagesColumnN: "Column {number}",
PagesAddColumn: "Add column",
PagesFooterLegal: "Legal line",
PagesBlockTopBar: "Top bar",
PagesEyebrow: "Label",
PagesTopBarFirst: "The top bar must be the first section.",
PagesUploadImage: "Upload image",
PagesUploadImageHint: "PNG, JPEG or WebP up to 2 MB. Paste the link into your HTML, for example in an img tag's src.",
PagesToolbar: "Formatting",
PagesTextStyle: "Text style",
PagesParagraph: "Paragraph",
@@ -552,6 +552,9 @@
"RegContactHint": "手机或电子邮件为必填项",
"RegCompany": "公司",
"RegJobTitle": "职位",
"RegServiceInterest": "感兴趣的服务(可选)",
"RegChooseService": "选择服务",
"RegNoticeSummary": "我们如何使用您的资料(English / Bahasa Malaysia)",
"RegInterests": "兴趣(可选)",
"RegNoticeEn": "英文",
"RegNoticeMs": "马来文",
@@ -855,6 +858,21 @@
"PagesFormPreview": "发布后的网页会在此显示报名表。",
"PagesHeroForm": "报名表单",
"PagesNoForm": "不显示表单",
"PagesFullWidth": "全宽",
"PagesPointN": "要点 {number}",
"PagesAddPoint": "添加要点",
"PagesFormHeading": "表单标题",
"PagesFormText": "表单说明",
"PagesThanksText": "感谢语",
"PagesBlockFooter": "页脚",
"PagesColumnN": "第 {number} 栏",
"PagesAddColumn": "添加栏",
"PagesFooterLegal": "版权声明",
"PagesBlockTopBar": "顶栏",
"PagesEyebrow": "小标签",
"PagesTopBarFirst": "顶栏必须是第一个区块。",
"PagesUploadImage": "上传图片",
"PagesUploadImageHint": "PNG、JPEG 或 WebP,最大 2 MB。将链接粘贴到您的 HTML 中,例如 img 标签的 src。",
"PagesToolbar": "格式",
"PagesTextStyle": "文字样式",
"PagesParagraph": "段落",
@@ -10,9 +10,10 @@ import java.util.List;
/**
* One landing-page block. Which fields apply depends on {@code type}:
* HERO (imageId, heading, text, button, optional eventUuid for a sign-up form beside the text), RICH_TEXT (html), IMAGE_TEXT (imageId, imagePosition, heading, html, button),
* HERO (imageId, heading, text, button, optional eventUuid for a sign-up form beside the text, fullWidth, formHeading and formText, cards as title-only points), RICH_TEXT (html), IMAGE_TEXT (imageId, imagePosition, heading, html, button),
* FAQ (heading, items), FORM (heading, eventUuid), HTML (html), FEATURES (heading, text, cards), STEPS (heading, cards),
* TRUST (cards), CTA (heading, text, button). Any block may carry anchor and look.
* TRUST (cards), CTA (heading, text, button), FOOTER (cards as title-and-text columns, text as the legal line),
* TOPBAR (button only; the first block). Any block may carry anchor and look.
*/
@Getter
@Setter
@@ -35,4 +36,13 @@ public class CmsBlock {
/** A Snowflake value beyond JavaScript number precision: written as a string, read from either. */
@JsonSerialize(using = ToStringSerializer.class)
private Long eventUuid;
/** add-hero-full-width: a HERO spanning the whole window. */
private Boolean fullWidth;
/** add-hero-full-width: heading (80) and text (200) at the top of a HERO's form card; only with an event. */
private String formHeading;
private String formText;
/** add-landing-thanks-and-footer: text (200) under the thank-you after a sign-up; FORM, or HERO with an event. */
private String thanksText;
/** add-landing-page-polish: a short label (40) above the heading of FEATURES, STEPS, IMAGE_TEXT, FAQ and CTA. */
private String eyebrow;
}
@@ -17,7 +17,7 @@ import java.util.regex.Pattern;
* Co-Lite changes: images are uploaded ids of the page's company, FORM points at an event of that company,
* buttons may also use mailto: and tel:, and rich-text HTML holding scripts is refused (the public page sanitises as well).
* The HTML block (custom HTML) is exempt from the script check: it is served only inside a sandboxed frame.
* add-page-sections adds FEATURES, STEPS, TRUST and CTA, a look on any block, and makes the HERO image optional.
* add-landing-page-polish adds TOPBAR and section labels. add-landing-thanks-and-footer adds FOOTER and the thank-you text. add-page-sections adds FEATURES, STEPS, TRUST and CTA, a look on any block, and makes the HERO image optional.
* Throws 422 on the first violation, with the reason "path|MessageCode".
*/
public final class CmsBlockValidator {
@@ -27,7 +27,9 @@ public final class CmsBlockValidator {
/** Section looks and feature icons (add-page-sections). */
private static final Set<String> LOOKS = Set.of("DEFAULT", "MUTED", "DARK", "ACCENT");
static final Set<String> ICONS = Set.of("wifi", "phone", "tv", "monitor", "lock", "shield-check", "cloud", "wrench", "headset", "users", "calendar", "star");
private static final Set<String> CARD_TYPES = Set.of("FEATURES", "STEPS", "TRUST");
private static final Set<String> CARD_TYPES = Set.of("FEATURES", "STEPS", "TRUST", "HERO", "FOOTER");
/** add-landing-page-polish: blocks that may carry a short label above their heading. */
private static final Set<String> EYEBROW_TYPES = Set.of("FEATURES", "STEPS", "IMAGE_TEXT", "FAQ", "CTA");
private static final Pattern SCRIPT = Pattern.compile("(?i)<\\s*script|\\son[a-z]+\\s*=|javascript\\s*:");
private CmsBlockValidator() {
@@ -62,6 +64,16 @@ public final class CmsBlockValidator {
if (b.getCards() != null && !CARD_TYPES.contains(b.getType())) {
throw refuse(path + ".cards", "PagesUnusedField");
}
// add-landing-thanks-and-footer: a thank-you text belongs to a block with a sign-up form.
if (b.getThanksText() != null && !"FORM".equals(b.getType()) && !"HERO".equals(b.getType())) {
throw refuse(path + ".thanksText", "PagesUnusedField");
}
if (b.getEyebrow() != null) {
if (!EYEBROW_TYPES.contains(b.getType())) {
throw refuse(path + ".eyebrow", "PagesUnusedField");
}
max(b.getEyebrow(), path + ".eyebrow", 40);
}
switch (b.getType()) {
case "HERO" -> {
if (b.getImageId() != null) {
@@ -75,6 +87,22 @@ public final class CmsBlockValidator {
if (b.getEventUuid() != null && !ownEvent.test(b.getEventUuid())) {
throw refuse(path + ".eventUuid", "PagesBadEvent");
}
// add-hero-full-width: up to 6 title-only points, and a form card heading and text only with a form.
if (b.getCards() != null) {
cards(b, path, 0, 6, false, false);
}
max(b.getFormHeading(), path + ".formHeading", 80);
max(b.getFormText(), path + ".formText", 200);
if (b.getEventUuid() == null && b.getFormHeading() != null) {
throw refuse(path + ".formHeading", "PagesUnusedField");
}
if (b.getEventUuid() == null && b.getFormText() != null) {
throw refuse(path + ".formText", "PagesUnusedField");
}
max(b.getThanksText(), path + ".thanksText", 200);
if (b.getEventUuid() == null && b.getThanksText() != null) {
throw refuse(path + ".thanksText", "PagesUnusedField");
}
}
case "RICH_TEXT" -> html(b.getHtml(), path + ".html");
case "HTML" -> {
@@ -94,6 +122,7 @@ public final class CmsBlockValidator {
case "FAQ" -> faq(b, path);
case "FORM" -> {
max(b.getHeading(), path + ".heading", 120);
max(b.getThanksText(), path + ".thanksText", 200);
if (b.getEventUuid() == null || !ownEvent.test(b.getEventUuid())) {
throw refuse(path + ".eventUuid", "PagesBadEvent");
}
@@ -102,18 +131,25 @@ public final class CmsBlockValidator {
required(b.getHeading(), path + ".heading");
max(b.getHeading(), path + ".heading", 120);
max(b.getText(), path + ".text", 300);
cards(b, path, true, true);
cards(b, path, 2, 6, true, true);
}
case "STEPS" -> {
required(b.getHeading(), path + ".heading");
max(b.getHeading(), path + ".heading", 120);
cards(b, path, false, true);
cards(b, path, 2, 6, false, true);
}
case "TRUST" -> {
if (b.getHeading() != null) {
throw refuse(path + ".heading", "PagesUnusedField");
}
cards(b, path, false, false);
cards(b, path, 2, 6, false, false);
}
case "FOOTER" -> {
if (b.getHeading() != null) {
throw refuse(path + ".heading", "PagesUnusedField");
}
cards(b, path, 1, 4, false, true);
max(b.getText(), path + ".text", 300);
}
case "CTA" -> {
required(b.getHeading(), path + ".heading");
@@ -122,6 +158,24 @@ public final class CmsBlockValidator {
required(b.getButtonLabel(), path + ".buttonLabel");
button(b, path);
}
case "TOPBAR" -> {
// add-landing-page-polish: the company logo and an optional button, sticky, so only at the top.
if (i > 0) {
throw refuse(path + ".type", "PagesTopBarFirst");
}
unused(path, "heading", b.getHeading());
unused(path, "text", b.getText());
unused(path, "html", b.getHtml());
unused(path, "imageId", b.getImageId());
unused(path, "imagePosition", b.getImagePosition());
unused(path, "items", b.getItems());
unused(path, "eventUuid", b.getEventUuid());
unused(path, "fullWidth", b.getFullWidth());
unused(path, "formHeading", b.getFormHeading());
unused(path, "formText", b.getFormText());
unused(path, "look", b.getLook());
button(b, path);
}
default -> throw refuse(path + ".type", "PagesUnknownType");
}
}
@@ -131,6 +185,12 @@ public final class CmsBlockValidator {
return new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, path + "|" + code);
}
private static void unused(String path, String field, Object value) {
if (value != null) {
throw refuse(path + "." + field, "PagesUnusedField");
}
}
static void required(String value, String path) {
if (value == null || value.isBlank()) {
throw refuse(path, "PagesRequired");
@@ -173,10 +233,10 @@ public final class CmsBlockValidator {
}
}
/** 2 to 6 cards; an icon from the list where the type uses one, a title (80), a text (300) where used, nothing else. */
private static void cards(CmsBlock b, String path, boolean icon, boolean text) {
/** min to max cards; an icon from the list where the type uses one, a title (80), a text (300) where used, nothing else. */
private static void cards(CmsBlock b, String path, int min, int max, boolean icon, boolean text) {
List<CmsCard> cards = b.getCards();
if (cards == null || cards.size() < 2 || cards.size() > 6) {
if (cards == null || cards.size() < min || cards.size() > max) {
throw refuse(path + ".cards", "PagesCardCount");
}
for (int i = 0; i < cards.size(); i++) {
@@ -1,6 +1,7 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.dto.CmsBlock;
import com.solvway.services.counter.dto.CmsCard;
import com.solvway.services.counter.dto.CmsFaqItem;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
@@ -216,4 +217,179 @@ class CmsBlockValidatorTest {
again.setAnchor("signup");
refused(List.of(named, again), "blocks[1].anchor", "PagesAnchorTaken");
}
// add-hero-full-width: points are title-only cards, 0 to 6 of them.
private static List<CmsCard> points(int n) {
List<CmsCard> out = new ArrayList<>();
for (int i = 0; i < n; i++) out.add(new CmsCard(null, "Local support team in Malaysia", null));
return out;
}
@Test
void aHeroMayCarryUpToSixTitleOnlyPoints() {
CmsBlock one = hero();
one.setCards(points(1));
CmsBlock six = hero();
six.setCards(points(6));
assertThatCode(() -> validate(List.of(one, six))).doesNotThrowAnyException();
CmsBlock seven = hero();
seven.setCards(points(7));
refused(List.of(seven), "blocks[0].cards", "PagesCardCount");
CmsBlock blank = hero();
blank.setCards(List.of(new CmsCard(null, " ", null)));
refused(List.of(blank), "blocks[0].cards[0].title", "PagesRequired");
CmsBlock longPoint = hero();
longPoint.setCards(List.of(new CmsCard(null, "x".repeat(81), null)));
refused(List.of(longPoint), "blocks[0].cards[0].title", "PagesTooLong");
CmsBlock withIcon = hero();
withIcon.setCards(List.of(new CmsCard("wifi", "WiFi", null)));
refused(List.of(withIcon), "blocks[0].cards[0].icon", "PagesUnusedField");
CmsBlock withText = hero();
withText.setCards(List.of(new CmsCard(null, "WiFi", "More")));
refused(List.of(withText), "blocks[0].cards[0].text", "PagesUnusedField");
}
@Test
void aHeroWithAFormMayCarryAFormHeadingAndText() {
CmsBlock ok = hero();
ok.setEventUuid(OWN_EVENT);
ok.setFullWidth(true);
ok.setFormHeading("Get a free consultation");
ok.setFormText("Tell us about your property. It takes under a minute.");
assertThatCode(() -> validate(List.of(ok))).doesNotThrowAnyException();
CmsBlock longHeading = hero();
longHeading.setEventUuid(OWN_EVENT);
longHeading.setFormHeading("x".repeat(81));
refused(List.of(longHeading), "blocks[0].formHeading", "PagesTooLong");
CmsBlock longText = hero();
longText.setEventUuid(OWN_EVENT);
longText.setFormText("x".repeat(201));
refused(List.of(longText), "blocks[0].formText", "PagesTooLong");
CmsBlock noForm = hero();
noForm.setFormHeading("Get a free consultation");
refused(List.of(noForm), "blocks[0].formHeading", "PagesUnusedField");
CmsBlock noFormText = hero();
noFormText.setFormText("Tell us more");
refused(List.of(noFormText), "blocks[0].formText", "PagesUnusedField");
}
// add-landing-thanks-and-footer: a thank-you text on a form, and the FOOTER block.
@Test
void aFormOrAHeroWithAFormMayCarryAThankYouText() {
CmsBlock heroOk = hero();
heroOk.setEventUuid(OWN_EVENT);
heroOk.setThanksText("Prefer to talk now? Call +60 12-833 2775.");
CmsBlock formOk = form(OWN_EVENT);
formOk.setThanksText("x".repeat(200));
assertThatCode(() -> validate(List.of(heroOk, formOk))).doesNotThrowAnyException();
CmsBlock tooLong = form(OWN_EVENT);
tooLong.setThanksText("x".repeat(201));
refused(List.of(tooLong), "blocks[0].thanksText", "PagesTooLong");
CmsBlock heroLong = hero();
heroLong.setEventUuid(OWN_EVENT);
heroLong.setThanksText("x".repeat(201));
refused(List.of(heroLong), "blocks[0].thanksText", "PagesTooLong");
CmsBlock noForm = hero();
noForm.setThanksText("Thanks");
refused(List.of(noForm), "blocks[0].thanksText", "PagesUnusedField");
CmsBlock elsewhere = rich("<p>Hi</p>");
elsewhere.setThanksText("Thanks");
refused(List.of(elsewhere), "blocks[0].thanksText", "PagesUnusedField");
}
private static CmsBlock footer(int columns) {
CmsBlock b = new CmsBlock();
b.setType("FOOTER");
List<CmsCard> cards = new ArrayList<>();
for (int i = 0; i < columns; i++) cards.add(new CmsCard(null, "Talk to us", "+603-7623 9807\ninfo@infinitynetworks.com.my"));
b.setCards(cards);
return b;
}
@Test
void aFooterHasOneToFourColumnsAndALegalLine() {
CmsBlock one = footer(1);
CmsBlock four = footer(4);
four.setText("© 2026 Infinity Networks Security Sdn Bhd. All rights reserved.");
four.setLook("DARK");
assertThatCode(() -> validate(List.of(one, four))).doesNotThrowAnyException();
refused(List.of(footer(0)), "blocks[0].cards", "PagesCardCount");
refused(List.of(footer(5)), "blocks[0].cards", "PagesCardCount");
CmsBlock none = footer(1);
none.setCards(null);
refused(List.of(none), "blocks[0].cards", "PagesCardCount");
CmsBlock noText = footer(1);
noText.setCards(List.of(new CmsCard(null, "Website", " ")));
refused(List.of(noText), "blocks[0].cards[0].text", "PagesRequired");
CmsBlock longTitle = footer(1);
longTitle.setCards(List.of(new CmsCard(null, "x".repeat(81), "y")));
refused(List.of(longTitle), "blocks[0].cards[0].title", "PagesTooLong");
CmsBlock icon = footer(1);
icon.setCards(List.of(new CmsCard("phone", "Talk to us", "y")));
refused(List.of(icon), "blocks[0].cards[0].icon", "PagesUnusedField");
CmsBlock heading = footer(1);
heading.setHeading("Contact");
refused(List.of(heading), "blocks[0].heading", "PagesUnusedField");
CmsBlock legal = footer(1);
legal.setText("x".repeat(301));
refused(List.of(legal), "blocks[0].text", "PagesTooLong");
}
// add-landing-page-polish: the top bar block, first only, and section labels.
private static CmsBlock topBar() {
CmsBlock b = new CmsBlock();
b.setType("TOPBAR");
return b;
}
@Test
void aTopBarIsTheFirstBlockWithAnOptionalButtonOnly() {
CmsBlock withButton = topBar();
withButton.setButtonLabel("Get My Free Consultation");
withButton.setButtonUrl("#consult");
CmsBlock target = form(OWN_EVENT);
target.setAnchor("consult");
assertThatCode(() -> validate(List.of(withButton, target))).doesNotThrowAnyException();
assertThatCode(() -> validate(List.of(topBar()))).doesNotThrowAnyException();
refused(List.of(hero(), topBar()), "blocks[1].type", "PagesTopBarFirst");
CmsBlock half = topBar();
half.setButtonLabel("Go");
refused(List.of(half), "blocks[0].buttonUrl", "PagesButtonPair");
CmsBlock heading = topBar();
heading.setHeading("Hi");
refused(List.of(heading), "blocks[0].heading", "PagesUnusedField");
CmsBlock text = topBar();
text.setText("Hi");
refused(List.of(text), "blocks[0].text", "PagesUnusedField");
CmsBlock image = topBar();
image.setImageId(OWN_IMAGE);
refused(List.of(image), "blocks[0].imageId", "PagesUnusedField");
CmsBlock html = topBar();
html.setHtml("<p>x</p>");
refused(List.of(html), "blocks[0].html", "PagesUnusedField");
CmsBlock look = topBar();
look.setLook("DARK");
refused(List.of(look), "blocks[0].look", "PagesUnusedField");
CmsBlock cards = topBar();
cards.setCards(points(1));
refused(List.of(cards), "blocks[0].cards", "PagesUnusedField");
}
@Test
void sectionLabelsOnFiveTypesUpToFortyCharacters() {
CmsBlock steps = new CmsBlock();
steps.setType("STEPS");
steps.setHeading("From first survey to day-to-day care");
steps.setCards(List.of(new CmsCard(null, "Design", "We survey."), new CmsCard(null, "Install", "We fit.")));
steps.setEyebrow("How we work");
CmsBlock faqBlock = faq(1);
faqBlock.setEyebrow("x".repeat(40));
assertThatCode(() -> validate(List.of(steps, faqBlock))).doesNotThrowAnyException();
CmsBlock tooLong = faq(1);
tooLong.setEyebrow("x".repeat(41));
refused(List.of(tooLong), "blocks[0].eyebrow", "PagesTooLong");
CmsBlock onHero = hero();
onHero.setEyebrow("Hotels");
refused(List.of(onHero), "blocks[0].eyebrow", "PagesUnusedField");
}
}