feat(pages): a footer section with contact links, and a thank-you text on landing forms #78

Merged
ngqile merged 1 commits from add-landing-thanks-and-footer into main 2026-12-04 03:45:38 +00:00
26 changed files with 551 additions and 33 deletions

No files matched your search

+2
View File
@@ -472,4 +472,6 @@ A form stops taking sign-ups when its event is disabled, its end date has passed
**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.
**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.
+10
View File
@@ -1733,6 +1733,16 @@ INSERT INTO message (code, content, area) SELECT 'PagesFormHeading', JSON_OBJECT
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 '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');
@@ -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).
@@ -16,16 +16,17 @@ import { CopyAddress } from "./CopyAddress";
/** 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", "fullWidth", "formHeading", "formText", "cards"],
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"],
FORM: ["heading", "eventUuid", "thanksText"],
HTML: ["html"],
FEATURES: ["heading", "text", "cards"],
STEPS: ["heading", "cards"],
TRUST: ["cards"],
CTA: ["heading", "text", "buttonLabel", "buttonUrl"],
FOOTER: ["cards", "text"],
};
const LISTED = /^(items\[\d+\]\.(question|answer)|cards\[\d+\]\.(icon|title|text))$/;
@@ -37,11 +38,13 @@ const ICON_LABELS: Record<string, string> = {
users: "PagesIconUsers", calendar: "PagesIconCalendar", star: "PagesIconStar",
};
// add-hero-full-width: a hero's points are title-only cards, and it may have none.
const CARD_KINDS: Record<string, { legend: string; add: string; icon: boolean; text: boolean; min: number; empty: CmsCard }> = {
FEATURES: { legend: "PagesCardN", add: "PagesAddCard", icon: true, text: true, min: 2, empty: { icon: "star", title: "", text: "" } },
STEPS: { legend: "PagesStepN", add: "PagesAddStep", icon: false, text: true, min: 2, empty: { title: "", text: "" } },
TRUST: { legend: "PagesItemN", add: "PagesAddItem", icon: false, text: false, min: 2, empty: { title: "" } },
HERO: { legend: "PagesPointN", add: "PagesAddPoint", icon: false, text: false, min: 0, empty: { title: "" } },
// 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";
@@ -89,7 +92,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" | "formHeading" | "formText", labelCode: string) => (
const text = (name: "heading" | "text" | "buttonLabel" | "buttonUrl" | "anchor" | "formHeading" | "formText" | "thanksText", 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>
@@ -124,7 +127,7 @@ export function BlockFields(props: {
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(e.target.value ? { eventUuid: e.target.value } : { eventUuid: null, formHeading: undefined, formText: undefined })}>
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) ? (
@@ -195,7 +198,7 @@ export function BlockFields(props: {
);
})}
<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>
@@ -238,6 +241,7 @@ export function BlockFields(props: {
<>
{text("formHeading", "PagesFormHeading")}
{text("formText", "PagesFormText")}
{text("thanksText", "PagesThanksText")}
</>
) : null}
</>
@@ -318,6 +322,7 @@ export function BlockFields(props: {
<>
{text("heading", "PagesHeading")}
{eventPicker("PagesFormEvent", "PagesChooseEvent")}
{text("thanksText", "PagesThanksText")}
</>
)}
@@ -340,6 +345,13 @@ export function BlockFields(props: {
{block.type === "TRUST" && cardList}
{block.type === "FOOTER" && (
<>
{cardList}
{text("text", "PagesFooterLegal")}
</>
)}
{block.type === "CTA" && (
<>
{text("heading", "PagesHeading")}
@@ -168,3 +168,65 @@ describe("utmTags", () => {
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");
});
});
@@ -76,7 +76,7 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
<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} />
<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";
@@ -87,7 +87,7 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
return (
<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 bg-gradient-to-r from-black/75 via-black/45 to-black/10 text-white" plain="">
<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}
@@ -164,7 +164,7 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
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} />
<LandingForm companyCode={company} slug={slug} index={index} info={block.closed ? undefined : block.form} preview={preview} thanks={block.thanksText} />
</section>
);
case "FEATURES":
@@ -221,6 +221,21 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
{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;
}
@@ -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} />;
}
@@ -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) =>
@@ -76,6 +76,31 @@ 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" }],
});
});
it("offers no look for a Custom HTML block", async () => {
render(<PageEditor pageId={5} />);
await screen.findByDisplayValue("How it works");
@@ -152,6 +152,27 @@ describe("PageEditor", () => {
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();
@@ -68,6 +68,14 @@ describe("usePageDraft for the on-page editor", () => {
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);
@@ -193,14 +193,14 @@ export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: numbe
};
/**
* 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 and text go with its form (add-hero-full-width).
* 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) => {
if (!r.block.eventUuid) return r;
const { formHeading: _h, formText: _t, ...block } = r.block;
const { formHeading: _h, formText: _t, thanksText: _k, ...block } = r.block;
return { ...r, block: { ...block, eventUuid: null } };
}));
};
@@ -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>
);
+8 -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";
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"];
/** Feature-card icons by the name services-counter accepts (add-page-sections). */
export const ICONS: Record<string, LucideIcon> = {
@@ -28,9 +28,10 @@ export const BLOCK_LABELS: Record<BlockType, string> = {
STEPS: "PagesBlockSteps",
TRUST: "PagesBlockTrust",
CTA: "PagesBlockCta",
FOOTER: "PagesBlockFooter",
};
/** A FEATURES (icon, title, text), STEPS (title, text) or TRUST (title) card; a HERO's points are title-only cards. */
/** 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;
@@ -62,6 +63,8 @@ export interface CmsBlock {
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;
}
export type PageStatus = "DRAFT" | "PUBLISHED";
@@ -132,6 +135,8 @@ export function emptyBlock(type: BlockType): CmsBlock {
return { type, cards: [{ title: "" }, { title: "" }] };
case "CTA":
return { type, heading: "", text: "", 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;
}
@@ -878,6 +878,11 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
PagesAddPoint: "Add point",
PagesFormHeading: "Form heading",
PagesFormText: "Form text",
PagesThanksText: "Thank-you text",
PagesBlockFooter: "Footer",
PagesColumnN: "Column {number}",
PagesAddColumn: "Add column",
PagesFooterLegal: "Legal line",
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",
@@ -863,6 +863,11 @@
"PagesAddPoint": "添加要点",
"PagesFormHeading": "表单标题",
"PagesFormText": "表单说明",
"PagesThanksText": "感谢语",
"PagesBlockFooter": "页脚",
"PagesColumnN": "第 {number} 栏",
"PagesAddColumn": "添加栏",
"PagesFooterLegal": "版权声明",
"PagesUploadImage": "上传图片",
"PagesUploadImageHint": "PNG、JPEG 或 WebP,最大 2 MB。将链接粘贴到您的 HTML 中,例如 img 标签的 src。",
"PagesToolbar": "格式",
@@ -12,7 +12,7 @@ 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, 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). Any block may carry anchor and look.
*/
@Getter
@Setter
@@ -40,4 +40,6 @@ public class CmsBlock {
/** 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;
}
@@ -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-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,7 @@ 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", "HERO");
private static final Set<String> CARD_TYPES = Set.of("FEATURES", "STEPS", "TRUST", "HERO", "FOOTER");
private static final Pattern SCRIPT = Pattern.compile("(?i)<\\s*script|\\son[a-z]+\\s*=|javascript\\s*:");
private CmsBlockValidator() {
@@ -62,6 +62,10 @@ 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");
}
switch (b.getType()) {
case "HERO" -> {
if (b.getImageId() != null) {
@@ -77,7 +81,7 @@ public final class CmsBlockValidator {
}
// 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, false, false);
cards(b, path, 0, 6, false, false);
}
max(b.getFormHeading(), path + ".formHeading", 80);
max(b.getFormText(), path + ".formText", 200);
@@ -87,6 +91,10 @@ public final class CmsBlockValidator {
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" -> {
@@ -106,6 +114,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");
}
@@ -114,18 +123,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, 2, 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, 2, false, true);
cards(b, path, 2, 6, false, true);
}
case "TRUST" -> {
if (b.getHeading() != null) {
throw refuse(path + ".heading", "PagesUnusedField");
}
cards(b, path, 2, 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");
@@ -185,10 +201,10 @@ public final class CmsBlockValidator {
}
}
/** min 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, int min, 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() < min || 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++) {
@@ -272,4 +272,66 @@ class CmsBlockValidatorTest {
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");
}
}