From c20a0c105cfd34615382ce14a4e5934403dccf67 Mon Sep 17 00:00:00 2001
From: ngqile
Date: Thu, 3 Dec 2026 09:13:15 +0800
Subject: [PATCH 1/8] docs: design and OpenSpec change add-page-anchor-links
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
---
.../2026-12-03-page-anchor-links-design.md | 33 +++++++++
.../add-page-anchor-links/.openspec.yaml | 2 +
.../changes/add-page-anchor-links/design.md | 27 +++++++
.../changes/add-page-anchor-links/proposal.md | 28 +++++++
.../specs/landing-pages/spec.md | 73 +++++++++++++++++++
.../changes/add-page-anchor-links/tasks.md | 20 +++++
6 files changed, 183 insertions(+)
create mode 100644 docs/superpowers/specs/2026-12-03-page-anchor-links-design.md
create mode 100644 openspec/changes/add-page-anchor-links/.openspec.yaml
create mode 100644 openspec/changes/add-page-anchor-links/design.md
create mode 100644 openspec/changes/add-page-anchor-links/proposal.md
create mode 100644 openspec/changes/add-page-anchor-links/specs/landing-pages/spec.md
create mode 100644 openspec/changes/add-page-anchor-links/tasks.md
diff --git a/docs/superpowers/specs/2026-12-03-page-anchor-links-design.md b/docs/superpowers/specs/2026-12-03-page-anchor-links-design.md
new file mode 100644
index 0000000..ddfa17c
--- /dev/null
+++ b/docs/superpowers/specs/2026-12-03-page-anchor-links-design.md
@@ -0,0 +1,33 @@
+# Same-page anchor links on landing pages — design
+
+Approved by the owner on 2026-12-03 (small change).
+
+## Why
+
+Marketing wants a button near the top of a landing page to jump to the sign-up form further down. Today the editor, the portal and services-counter all refuse a `#anchor` link, and blocks carry no `id` to jump to. On the INS "hotel-technology" page (a Custom HTML block followed by a FORM block), the pasted HTML's own `#consult` and `#top` links do nothing: the sealed frame is sized to its full height, so it never scrolls itself, and as an opaque-origin frame it may not scroll the page around it.
+
+## Goals
+
+- Staff can name any block and link to it with `#name` from a button, from rich text, or from inside a Custom HTML block.
+- In-frame links to an `id` inside the same Custom HTML block work again.
+
+## Non-goals
+
+- No automatic ids (`block-3`): they break when blocks are reordered.
+- No change to how the sealed frame is sandboxed. The frame gets no new grants.
+
+## Approaches
+
+1. **An optional link name per block (chosen).** One new optional field, unique per page, stored in the existing blocks JSON. Works for every block type and survives reordering.
+2. Automatic positional ids (`block-3`). No editor change, but links break silently when blocks move.
+3. A fixed `id="form"` on the FORM block only. Covers the main case, but not other blocks or `#top`.
+
+## Design
+
+- **Link name.** Each block has an optional "Link name": lowercase letters, digits and `-`, starting with a letter or digit, at most 40 characters, unique on the page. services-counter checks it. The public page renders it as the block's `id`.
+- **`#name` links.** Button links and rich-text links also accept `#` followed by a name of that pattern. The same rule is in services-counter, the portal's `isSafeLink`, the rich-text editor and the public sanitiser.
+- **Frame bridge.** The frame document's injected script, which already reports its height, also catches clicks on `#name` links inside the frame and posts the name and, when the frame holds an element with that `id`, the element's offset. The page acts on such a message only from its own frame and only for a name of the pattern. It scrolls to the frame's top plus that offset when the frame has the target; otherwise to a block on the page with that link name; otherwise it does nothing. The frame link's default action is prevented, so the frame never navigates.
+
+## Left to the builder
+
+Field placement in the editor, label wording, and smooth vs instant scrolling.
diff --git a/openspec/changes/add-page-anchor-links/.openspec.yaml b/openspec/changes/add-page-anchor-links/.openspec.yaml
new file mode 100644
index 0000000..2a83988
--- /dev/null
+++ b/openspec/changes/add-page-anchor-links/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-12-03
diff --git a/openspec/changes/add-page-anchor-links/design.md b/openspec/changes/add-page-anchor-links/design.md
new file mode 100644
index 0000000..1773673
--- /dev/null
+++ b/openspec/changes/add-page-anchor-links/design.md
@@ -0,0 +1,27 @@
+## Context
+
+See `docs/superpowers/specs/2026-12-03-page-anchor-links-design.md`. Blocks are one JSON column on `cms_page`; services-counter validates them; mobile-api passes them through as maps; the portal renders them. Custom HTML runs in an opaque-origin frame (`allow-scripts allow-popups allow-popups-to-escape-sandbox`) whose injected script already posts height reports, which `HtmlFrame` accepts only from its own `contentWindow`.
+
+## Goals / Non-Goals
+
+**Goals:** named block targets; `#name` links from buttons, rich text and Custom HTML.
+
+**Non-Goals:** automatic ids; any new frame permission; scroll offsets for a sticky header (the public page has none).
+
+## Decisions
+
+1. **Field `anchor` on the block**, pattern `^[a-z0-9][a-z0-9-]{0,39}$`, unique per page. Stored in the blocks JSON, so no DDL. Refusal codes: `PagesBadAnchor`, `PagesAnchorTaken`.
+2. **Link rule.** `#` plus the same pattern is a safe link everywhere a link is checked: `CmsBlockValidator.safeLink`, `isSafeLink`, the editor's `SAFE_LINK`, and the sanitiser (sanitize-html already keeps scheme-less hrefs; a test pins it).
+3. **Ids.** The block wrapper in `CmsBlocks` gets `id={anchor}` for every type, the HTML frame included. Rendered only when the name matches the pattern, so rows written another way cannot inject odd ids.
+4. **Frame bridge.** The injected script adds one click listener: for `a[href^="#"]` with a valid name it prevents the default and posts `{type:"colite-frame-anchor", name, y}`, where `y` is the in-frame element's document offset or `null`. `HtmlFrame` checks the source window as for heights, validates the message in a pure `frameAnchor()` helper, then scrolls the window to `frame top + y`, or to `document.getElementById(name)`, else ignores it. Smooth scroll.
+5. **Messages are data only.** The page never navigates or evaluates anything from a frame message; it only scrolls.
+
+## Risks / Trade-offs
+
+- A frame script could post anchor requests at will → it can only scroll its own page, which it could already make tall. Accepted.
+- A link name equal to an id the portal already uses on that page (e.g. `main`) would clash → the public page renders no ids of its own apart from block anchors; the preview shell may, so only behaviour on the public page is specified.
+- Pages saved by an older release lose link names → only on rollback; noted in the proposal.
+
+## Migration Plan
+
+Deploy services-counter and the portal; run `sql/01-anchor-labels.sql`. Rollback: previous images and `sql/99-rollback.sql`.
diff --git a/openspec/changes/add-page-anchor-links/proposal.md b/openspec/changes/add-page-anchor-links/proposal.md
new file mode 100644
index 0000000..42adf92
--- /dev/null
+++ b/openspec/changes/add-page-anchor-links/proposal.md
@@ -0,0 +1,28 @@
+## Why
+
+Landing pages cannot link within themselves. Buttons and rich-text links refuse `#anchor`, blocks have no id to jump to, and links inside a Custom HTML block do nothing because the sealed frame never scrolls and may not scroll the page. The INS page's "Get My Free Consultation" button therefore cannot take visitors to the sign-up form. Design: `docs/superpowers/specs/2026-12-03-page-anchor-links-design.md`.
+
+## What Changes
+
+- Each block gets an optional link name, unique on the page, rendered as the block's id.
+- Button and rich-text links accept `#name`.
+- The Custom HTML frame reports clicks on `#name` links to the page, which scrolls to the target inside the frame or to the named block.
+- New and changed editor labels in English and Chinese.
+
+## Capabilities
+
+### New Capabilities
+
+None.
+
+### Modified Capabilities
+
+- `landing-pages`: same-page links and block link names.
+
+## Impact
+
+- services-counter: `CmsBlock` gains `anchor`; `CmsBlockValidator` checks it and accepts `#name` links. No DDL: blocks are stored as JSON.
+- mobile-api: none (blocks pass through as maps).
+- Portal: `cmsPages.ts` (`isSafeLink`, model), `RichTextEditor.tsx`, `pageHtml.ts`, `frameHtml.ts` (script and message parsing), `HtmlFrame.tsx`, `CmsBlocks.tsx` (ids), `BlockFields.tsx` (field), labels.
+- SQL: `sql/01-anchor-labels.sql` and `sql/99-rollback.sql` (labels only).
+- Older releases ignore the new field on read, and a page saved by an older release loses its link names.
diff --git a/openspec/changes/add-page-anchor-links/specs/landing-pages/spec.md b/openspec/changes/add-page-anchor-links/specs/landing-pages/spec.md
new file mode 100644
index 0000000..79ce69a
--- /dev/null
+++ b/openspec/changes/add-page-anchor-links/specs/landing-pages/spec.md
@@ -0,0 +1,73 @@
+## MODIFIED Requirements
+
+### Requirement: Page Content Cannot Run Scripts
+
+A button SHALL have both a label and a link or neither. The link SHALL start with a single `/`, `https://`, `mailto:`, `tel:`, or `#` plus a valid block link name. A save SHALL be refused when RICH_TEXT or IMAGE_TEXT HTML holds a `script` element, an `on*` attribute or a `javascript:` URL. The public page SHALL also sanitise that HTML against an allow-list. HTML blocks are exempt: they only run sealed.
+
+#### Scenario: Script link on a button
+
+- **WHEN** a page is saved with a HERO button link `javascript:alert(1)`
+- **THEN** the save is refused on field `blocks[0].buttonUrl`
+
+#### Scenario: Script in rich text
+
+- **WHEN** a page is saved with rich text holding `
`
+- **THEN** the save is refused on that block's HTML field
+
+#### Scenario: Script in an HTML block
+
+- **WHEN** a page is saved with an HTML block holding ``
+- **THEN** the save succeeds
+
+#### Scenario: Same-page button link
+
+- **WHEN** a page is saved with a HERO button link `#signup`
+- **THEN** the save succeeds
+
+#### Scenario: Malformed same-page link
+
+- **WHEN** a page is saved with a HERO button link `#Sign Up`
+- **THEN** the save is refused on field `blocks[0].buttonUrl`
+
+## ADDED Requirements
+
+### Requirement: Block Link Names
+
+Any block MAY carry a link name. A link name SHALL be 1 to 40 characters of lowercase letters, digits and `-`, starting with a letter or digit, and SHALL be unique within the page. A save breaking either rule SHALL be refused on that block's link-name field, writing nothing. The public page and the staff preview SHALL give the block that name as its element id, so a `#name` link scrolls to it.
+
+#### Scenario: Hero button jumps to the form
+
+- **GIVEN** a published page whose FORM block has the link name `signup` and whose HERO button links to `#signup`
+- **WHEN** a visitor clicks the button
+- **THEN** the page scrolls to the form
+
+#### Scenario: Duplicate link name
+
+- **WHEN** a page is saved with two blocks named `signup`
+- **THEN** the save is refused on field `blocks[1].anchor` and nothing is written
+
+#### Scenario: Bad link name
+
+- **WHEN** a page is saved with a block named `Sign Up`
+- **THEN** the save is refused on field `blocks[0].anchor` and nothing is written
+
+### Requirement: Same-Page Links From A Custom HTML Frame
+
+A click on a `#name` link inside a Custom HTML block SHALL scroll the page, without navigating the frame. The target SHALL be the element with that id inside the same frame when there is one, otherwise the block on the page with that link name, otherwise nothing happens. The page SHALL act only on such requests from its own frames and only for names of the link-name pattern. The frame SHALL gain no new sandbox permissions.
+
+#### Scenario: Link to the form below the frame
+
+- **GIVEN** a published page with an HTML block holding `` and a FORM block named `signup`
+- **WHEN** a visitor clicks that link
+- **THEN** the page scrolls to the form
+
+#### Scenario: Link inside the frame
+
+- **GIVEN** a published HTML block whose content holds `` near its bottom and an element with id `top` at its start
+- **WHEN** a visitor scrolls down and clicks that link
+- **THEN** the page scrolls back to the start of the frame
+
+#### Scenario: Another window asks to scroll
+
+- **WHEN** a different window posts a same-page link request to the page
+- **THEN** the page does not scroll
diff --git a/openspec/changes/add-page-anchor-links/tasks.md b/openspec/changes/add-page-anchor-links/tasks.md
new file mode 100644
index 0000000..e870d62
--- /dev/null
+++ b/openspec/changes/add-page-anchor-links/tasks.md
@@ -0,0 +1,20 @@
+# Tasks: add-page-anchor-links
+
+Design: `design.md`. Every task is TDD. Work is serial in the main session, with a self-review per task.
+
+## 1. services-counter
+
+- [ ] 1.1 `CmsBlock.anchor`; `CmsBlockValidator`: link-name pattern and uniqueness (`PagesBadAnchor`, `PagesAnchorTaken` on `blocks[i].anchor`), `#name` accepted by `safeLink`.
+ - Verify: `mvn -T 1C -B -pl solvway-services-counter -am verify`
+
+## 2. Portal
+
+- [ ] 2.1 Link rules: `isSafeLink`, the rich-text editor's `SAFE_LINK`, a sanitiser test that `#name` hrefs survive; block ids in `CmsBlocks` (pattern-checked).
+- [ ] 2.2 Frame bridge: click listener in the frame script, `frameAnchor()` message check, `HtmlFrame` scroll (own frame only).
+- [ ] 2.3 Editor: "Link name" field per block with field errors; label changes in `defaultMessages.ts` and `zh_CN.seed.json`, then `npm run i18n:sql`; `sql/01-anchor-labels.sql` (new labels, plus English and Chinese updates of `PagesBadLink` and `PagesLinkPrompt`) and `sql/99-rollback.sql`.
+ - Verify (2.1 to 2.3): `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`
+
+## 3. Release
+
+- [ ] 3.1 `docs/deployment.md`: SQL rows, drop the `#anchor` known gap, add the INS page note (name the FORM block `signup`, change the HTML's `#consult` to `#signup`).
+- [ ] 3.2 Live check (Playwright) on a local portal: hero button to a named form block; Custom HTML `#name` to the form and `#top` inside the frame; refusals for a bad and a duplicate link name; 1280 and 360 px.
From 1efdfe97d0a3a16ee1168b82154b1ae0511c0320 Mon Sep 17 00:00:00 2001
From: ngqile
Date: Thu, 3 Dec 2026 09:18:15 +0800
Subject: [PATCH 2/8] feat(pages): block link names and #name links in
services-counter
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
---
.../changes/add-page-anchor-links/tasks.md | 2 +-
.../services/counter/dto/CmsBlock.java | 2 ++
.../counter/service/CmsBlockValidator.java | 19 +++++++++-
.../service/CmsBlockValidatorTest.java | 35 +++++++++++++++++++
4 files changed, 56 insertions(+), 2 deletions(-)
diff --git a/openspec/changes/add-page-anchor-links/tasks.md b/openspec/changes/add-page-anchor-links/tasks.md
index e870d62..38adfa2 100644
--- a/openspec/changes/add-page-anchor-links/tasks.md
+++ b/openspec/changes/add-page-anchor-links/tasks.md
@@ -4,7 +4,7 @@ Design: `design.md`. Every task is TDD. Work is serial in the main session, with
## 1. services-counter
-- [ ] 1.1 `CmsBlock.anchor`; `CmsBlockValidator`: link-name pattern and uniqueness (`PagesBadAnchor`, `PagesAnchorTaken` on `blocks[i].anchor`), `#name` accepted by `safeLink`.
+- [x] 1.1 `CmsBlock.anchor`; `CmsBlockValidator`: link-name pattern and uniqueness (`PagesBadAnchor`, `PagesAnchorTaken` on `blocks[i].anchor`), `#name` accepted by `safeLink`.
- Verify: `mvn -T 1C -B -pl solvway-services-counter -am verify`
## 2. Portal
diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/CmsBlock.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/CmsBlock.java
index 6ad7e88..0e39143 100644
--- a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/CmsBlock.java
+++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/CmsBlock.java
@@ -25,6 +25,8 @@ public class CmsBlock {
private String imagePosition;
private String buttonLabel;
private String buttonUrl;
+ /** Optional link name: the block's id on the public page, the target of a #name link (add-page-anchor-links). */
+ private String anchor;
private List items;
/** A Snowflake value beyond JavaScript number precision: written as a string, read from either. */
@JsonSerialize(using = ToStringSerializer.class)
diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/CmsBlockValidator.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/CmsBlockValidator.java
index 2cc9727..b6e49b8 100644
--- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/CmsBlockValidator.java
+++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/CmsBlockValidator.java
@@ -5,7 +5,9 @@ import com.solvway.services.counter.dto.CmsFaqItem;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
+import java.util.HashSet;
import java.util.List;
+import java.util.Set;
import java.util.function.LongPredicate;
import java.util.regex.Pattern;
@@ -18,6 +20,8 @@ import java.util.regex.Pattern;
*/
public final class CmsBlockValidator {
private static final int MAX_BLOCKS = 30;
+ /** A block link name (add-page-anchor-links); a same-page link is "#" plus one. */
+ static final Pattern ANCHOR = Pattern.compile("[a-z0-9][a-z0-9-]{0,39}");
private static final Pattern SCRIPT = Pattern.compile("(?i)<\\s*script|\\son[a-z]+\\s*=|javascript\\s*:");
private CmsBlockValidator() {
@@ -30,12 +34,22 @@ public final class CmsBlockValidator {
if (blocks.size() > MAX_BLOCKS) {
throw refuse("blocks", "PagesTooManyBlocks");
}
+ Set anchors = new HashSet<>();
for (int i = 0; i < blocks.size(); i++) {
CmsBlock b = blocks.get(i);
String path = "blocks[" + i + "]";
if (b == null || b.getType() == null) {
throw refuse(path + ".type", "PagesUnknownType");
}
+ String anchor = b.getAnchor();
+ if (anchor != null && !anchor.isEmpty()) {
+ if (!ANCHOR.matcher(anchor).matches()) {
+ throw refuse(path + ".anchor", "PagesBadAnchor");
+ }
+ if (!anchors.add(anchor)) {
+ throw refuse(path + ".anchor", "PagesAnchorTaken");
+ }
+ }
switch (b.getType()) {
case "HERO" -> {
image(b, path, ownImage);
@@ -132,13 +146,16 @@ public final class CmsBlockValidator {
}
/**
- * A same-site path, https, mailto or tel link, at most 1000 characters. Browsers turn "\" into "/" and drop
+ * A same-site path, https, mailto or tel link, or "#" plus a block link name; at most 1000 characters. Browsers turn "\" into "/" and drop
* whitespace inside URLs, so "/\evil" would become protocol-relative: such characters are refused outright.
*/
static boolean safeLink(String url) {
if (url.length() > 1000 || url.chars().anyMatch(c -> c == '\\' || c <= 0x20 || c == 0x7f || Character.isSpaceChar(c) || c == 0xFEFF)) {
return false;
}
+ if (url.startsWith("#")) {
+ return ANCHOR.matcher(url.substring(1)).matches();
+ }
if (url.startsWith("//")) {
return false;
}
diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/CmsBlockValidatorTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/CmsBlockValidatorTest.java
index c263e73..3321378 100644
--- a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/CmsBlockValidatorTest.java
+++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/CmsBlockValidatorTest.java
@@ -166,4 +166,39 @@ class CmsBlockValidatorTest {
refused(List.of(custom("x".repeat(200_001))), "blocks[0].html", "PagesTooLong");
refused(List.of(custom(" ")), "blocks[0].html", "PagesRequired");
}
+
+ @Test
+ void buttonsMayLinkToANamedBlockOnTheSamePage() {
+ for (String good : List.of("#signup", "#top", "#a", "#2-rooms")) {
+ CmsBlock b = hero();
+ b.setButtonLabel("Go");
+ b.setButtonUrl(good);
+ assertThatCode(() -> validate(List.of(b))).as(good).doesNotThrowAnyException();
+ }
+ for (String bad : List.of("#", "#Sign Up", "#-x", "#signup/x", "#" + "a".repeat(41))) {
+ CmsBlock b = hero();
+ b.setButtonLabel("Go");
+ b.setButtonUrl(bad);
+ refused(List.of(b), "blocks[0].buttonUrl", "PagesBadLink");
+ }
+ }
+
+ @Test
+ void linkNamesFollowThePatternAndAreUniqueOnThePage() {
+ CmsBlock named = form(OWN_EVENT);
+ named.setAnchor("signup");
+ CmsBlock other = rich("x
");
+ other.setAnchor("a".repeat(40));
+ CmsBlock blank = rich("y
");
+ blank.setAnchor("");
+ assertThatCode(() -> validate(List.of(hero(), named, other, blank))).as("a blank name is no name").doesNotThrowAnyException();
+ for (String bad : List.of("Sign Up", "-x", " x", "a".repeat(41), "sign_up")) {
+ CmsBlock b = rich("x
");
+ b.setAnchor(bad);
+ refused(List.of(b), "blocks[0].anchor", "PagesBadAnchor");
+ }
+ CmsBlock again = custom("x
");
+ again.setAnchor("signup");
+ refused(List.of(named, again), "blocks[1].anchor", "PagesAnchorTaken");
+ }
}
From 5b5ee728c7af72c0296803ea803e1c2b17d68d1c Mon Sep 17 00:00:00 2001
From: ngqile
Date: Thu, 3 Dec 2026 09:20:35 +0800
Subject: [PATCH 3/8] feat(pages): #name links and block ids on landing pages
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
---
openspec/changes/add-page-anchor-links/tasks.md | 2 +-
.../app/components/pages/CmsBlocks.html.test.tsx | 5 +++++
.../app/components/pages/CmsBlocks.test.tsx | 11 +++++++++++
.../app/components/pages/CmsBlocks.tsx | 6 +++---
.../app/components/pages/HtmlFrame.tsx | 4 ++--
.../app/components/pages/RichTextEditor.tsx | 7 ++++---
solvway-admin-portal/app/lib/cmsPages.test.ts | 9 ++++++++-
solvway-admin-portal/app/lib/cmsPages.ts | 11 ++++++++++-
solvway-admin-portal/app/lib/pageHtml.test.ts | 1 +
9 files changed, 45 insertions(+), 11 deletions(-)
diff --git a/openspec/changes/add-page-anchor-links/tasks.md b/openspec/changes/add-page-anchor-links/tasks.md
index 38adfa2..394e0ae 100644
--- a/openspec/changes/add-page-anchor-links/tasks.md
+++ b/openspec/changes/add-page-anchor-links/tasks.md
@@ -9,7 +9,7 @@ Design: `design.md`. Every task is TDD. Work is serial in the main session, with
## 2. Portal
-- [ ] 2.1 Link rules: `isSafeLink`, the rich-text editor's `SAFE_LINK`, a sanitiser test that `#name` hrefs survive; block ids in `CmsBlocks` (pattern-checked).
+- [x] 2.1 Link rules: `isSafeLink`, the rich-text editor's `SAFE_LINK`, a sanitiser test that `#name` hrefs survive; block ids in `CmsBlocks` (pattern-checked).
- [ ] 2.2 Frame bridge: click listener in the frame script, `frameAnchor()` message check, `HtmlFrame` scroll (own frame only).
- [ ] 2.3 Editor: "Link name" field per block with field errors; label changes in `defaultMessages.ts` and `zh_CN.seed.json`, then `npm run i18n:sql`; `sql/01-anchor-labels.sql` (new labels, plus English and Chinese updates of `PagesBadLink` and `PagesLinkPrompt`) and `sql/99-rollback.sql`.
- Verify (2.1 to 2.3): `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`
diff --git a/solvway-admin-portal/app/components/pages/CmsBlocks.html.test.tsx b/solvway-admin-portal/app/components/pages/CmsBlocks.html.test.tsx
index d69f1a9..e130051 100644
--- a/solvway-admin-portal/app/components/pages/CmsBlocks.html.test.tsx
+++ b/solvway-admin-portal/app/components/pages/CmsBlocks.html.test.tsx
@@ -21,6 +21,11 @@ describe("LandingPage: Custom HTML", () => {
expect(document.querySelector("script")).toBeNull();
});
+ it("gives a named HTML block its link name as the frame's id", () => {
+ render();
+ expect(frame()).toHaveAttribute("id", "story");
+ });
+
it("uses the preview's frame address when given", () => {
render();
expect(frame()).toHaveAttribute("src", "/pages/5/preview/frame/0");
diff --git a/solvway-admin-portal/app/components/pages/CmsBlocks.test.tsx b/solvway-admin-portal/app/components/pages/CmsBlocks.test.tsx
index 9f5319a..3095875 100644
--- a/solvway-admin-portal/app/components/pages/CmsBlocks.test.tsx
+++ b/solvway-admin-portal/app/components/pages/CmsBlocks.test.tsx
@@ -35,6 +35,17 @@ describe("LandingPage", () => {
expect(screen.getByRole("link", { name: "Mail" })).toHaveAttribute("href", "mailto:a@b.c");
});
+ it("gives a named block its link name as id, so a #name button jumps to it", () => {
+ render(x
", anchor: 'bad" onclick="x' },
+ ])} />);
+ expect(screen.getByRole("link", { name: "Sign up" })).toHaveAttribute("href", "#signup");
+ expect(document.getElementById("signup")).toHaveTextContent("Sign-up is closed.");
+ expect(document.querySelectorAll("main [id]")).toHaveLength(1);
+ });
+
it("a closed form says so; the preview shows a note instead of a form", () => {
const { unmount } = render();
expect(screen.getByText("Sign-up is closed.")).toBeInTheDocument();
diff --git a/solvway-admin-portal/app/components/pages/CmsBlocks.tsx b/solvway-admin-portal/app/components/pages/CmsBlocks.tsx
index de9af42..5cdd65f 100644
--- a/solvway-admin-portal/app/components/pages/CmsBlocks.tsx
+++ b/solvway-admin-portal/app/components/pages/CmsBlocks.tsx
@@ -1,5 +1,5 @@
import type { CSSProperties, ReactNode } from "react";
-import { contrastText, imageSrc, isSafeLink, type CmsBlock } from "@/app/lib/cmsPages";
+import { anchorId, contrastText, imageSrc, isSafeLink, type CmsBlock } from "@/app/lib/cmsPages";
import type { RegistrationInfo } from "@/app/lib/services/publicRegistration";
import { SafeHtml } from "./SafeHtml";
import { LandingForm } from "./LandingForm";
@@ -123,8 +123,8 @@ export function LandingPage({ company, page, banner, preview, frameBase }: {
{page.title}
{page.blocks.map((block, i) => block.type === "HTML"
- ?
- :
)}
+ ?
+ :
)}
diff --git a/solvway-admin-portal/app/components/pages/HtmlFrame.tsx b/solvway-admin-portal/app/components/pages/HtmlFrame.tsx
index e64922a..1ca0e79 100644
--- a/solvway-admin-portal/app/components/pages/HtmlFrame.tsx
+++ b/solvway-admin-portal/app/components/pages/HtmlFrame.tsx
@@ -4,7 +4,7 @@ import { useEffect, useRef, useState } from "react";
import { FRAME_SANDBOX, nextFrameHeight, START_HEIGHT, type FrameHeight } from "@/app/lib/frameHtml";
/** A Custom HTML block: the sealed frame, sized by height reports from that frame's own window only. */
-export function HtmlFrame({ src, title }: { src: string; title: string }) {
+export function HtmlFrame({ id, src, title }: { id?: string; src: string; title: string }) {
const ref = useRef(null);
const [size, setSize] = useState({ height: START_HEIGHT, steps: [] });
useEffect(() => {
@@ -15,5 +15,5 @@ export function HtmlFrame({ src, title }: { src: string; title: string }) {
window.addEventListener("message", onMessage);
return () => window.removeEventListener("message", onMessage);
}, []);
- return ;
+ return ;
}
diff --git a/solvway-admin-portal/app/components/pages/RichTextEditor.tsx b/solvway-admin-portal/app/components/pages/RichTextEditor.tsx
index dffccb2..3a52642 100644
--- a/solvway-admin-portal/app/components/pages/RichTextEditor.tsx
+++ b/solvway-admin-portal/app/components/pages/RichTextEditor.tsx
@@ -7,10 +7,11 @@ import TextAlign from "@tiptap/extension-text-align";
import { AlignCenter, AlignLeft, AlignRight, Bold, Eraser, Italic, Link as LinkIcon, List, ListOrdered, Minus, Quote, Strikethrough, Underline } from "lucide-react";
import { Button } from "@/app/components/ui/button";
import { useT } from "@/app/lib/i18n/MessagesProvider";
+import { isSafeLink } from "@/app/lib/cmsPages";
// Ported from babyboo's RichTextEditor, trimmed for landing pages: no YouTube, tables, inline images, emoji,
// colour or HTML source view. The public page sanitises the HTML again with an allow-list.
-const SAFE_LINK = /^(https:\/\/|mailto:|tel:|\/(?!\/))/i;
+// Links follow the page rule in cmsPages (isSafeLink), the same one services-counter applies to buttons.
const htmlOf = (editor: Editor) => (editor.isEmpty ? "" : editor.getHTML());
@@ -32,7 +33,7 @@ export function RichTextEditor({ id, label, value, onChange, disabled, invalid }
StarterKit.configure({
heading: { levels: [2, 3] },
trailingNode: false,
- link: { openOnClick: false, protocols: ["https", "mailto", "tel"], isAllowedUri: (url) => SAFE_LINK.test(url) },
+ link: { openOnClick: false, protocols: ["https", "mailto", "tel"], isAllowedUri: (url) => isSafeLink(url) },
}),
TextAlign.configure({ types: ["heading", "paragraph"], alignments: ["left", "center", "right"] }),
],
@@ -75,7 +76,7 @@ export function RichTextEditor({ id, label, value, onChange, disabled, invalid }
function addLink() {
const url = window.prompt(t("PagesLinkPrompt"));
- if (!url || !SAFE_LINK.test(url)) return;
+ if (!url || !isSafeLink(url)) return;
run((e) => e.chain().focus().extendMarkRange("link").setLink({ href: url }).run());
}
diff --git a/solvway-admin-portal/app/lib/cmsPages.test.ts b/solvway-admin-portal/app/lib/cmsPages.test.ts
index 570df92..61e6da1 100644
--- a/solvway-admin-portal/app/lib/cmsPages.test.ts
+++ b/solvway-admin-portal/app/lib/cmsPages.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { contrastText, emptyPage, isSafeLink, pageBody, slugify, withTitle } from "./cmsPages";
+import { anchorId, contrastText, emptyPage, isSafeLink, pageBody, slugify, withTitle } from "./cmsPages";
describe("cmsPages helpers", () => {
it("slug follows the title until edited", () => {
@@ -29,4 +29,11 @@ describe("cmsPages helpers", () => {
for (const ok of ["/p/INS/a", "https://x.com", "mailto:a@b.c", "tel:+60123"]) expect(isSafeLink(ok), ok).toBe(true);
for (const bad of ["//evil.com", "javascript:alert(1)", "http://x.com", "https://a b", "/\\evil", undefined]) expect(isSafeLink(bad), String(bad)).toBe(false);
});
+
+ it("a same-page link is # plus a block link name", () => {
+ for (const ok of ["#signup", "#top", "#2-rooms", "#" + "a".repeat(40)]) expect(isSafeLink(ok), ok).toBe(true);
+ for (const bad of ["#", "#Sign Up", "#-x", "#signup/x", "#a\"b", "#" + "a".repeat(41)]) expect(isSafeLink(bad), bad).toBe(false);
+ expect(anchorId("signup")).toBe("signup");
+ for (const bad of [undefined, "", "Sign Up", "x\" onclick=\"y"]) expect(anchorId(bad), String(bad)).toBeUndefined();
+ });
});
diff --git a/solvway-admin-portal/app/lib/cmsPages.ts b/solvway-admin-portal/app/lib/cmsPages.ts
index 27c7e09..8d17b39 100644
--- a/solvway-admin-portal/app/lib/cmsPages.ts
+++ b/solvway-admin-portal/app/lib/cmsPages.ts
@@ -29,6 +29,8 @@ export interface CmsBlock {
html?: string;
imagePosition?: "LEFT" | "RIGHT";
items?: CmsFaqItem[];
+ /** Optional link name: the block's id on the page, the target of a #name link (add-page-anchor-links). */
+ anchor?: string;
/** The FORM block's event (a Snowflake uuid, kept as a string). */
eventUuid?: string | null;
}
@@ -131,9 +133,16 @@ export function contrastText(hex: string): "#000000" | "#FFFFFF" {
return (lum + 0.05) / 0.05 > 1.05 / (lum + 0.05) ? "#000000" : "#FFFFFF";
}
-/** The counter's link rule: same-site path, https, mailto or tel. Checked again before rendering a button. */
+/** A block link name, as services-counter checks it. */
+export const ANCHOR = /^[a-z0-9][a-z0-9-]{0,39}$/;
+
+/** The link name when it is valid, for use as an element id. */
+export const anchorId = (name: string | undefined) => (name && ANCHOR.test(name) ? name : undefined);
+
+/** The counter's link rule: same-site path, https, mailto, tel or #name. Checked again before rendering a button. */
export function isSafeLink(url: string | undefined): boolean {
if (!url || url.length > 1000 || /[\s\\\u0000-\u001f]/.test(url)) return false;
+ if (url.startsWith("#")) return ANCHOR.test(url.slice(1));
if (url.startsWith("/")) return !url.startsWith("//");
return /^(https:\/\/|mailto:|tel:)/i.test(url);
}
diff --git a/solvway-admin-portal/app/lib/pageHtml.test.ts b/solvway-admin-portal/app/lib/pageHtml.test.ts
index 6bb87a2..5b4e23a 100644
--- a/solvway-admin-portal/app/lib/pageHtml.test.ts
+++ b/solvway-admin-portal/app/lib/pageHtml.test.ts
@@ -23,5 +23,6 @@ describe("sanitizePageHtml (landing-page rich text allow-list)", () => {
expect(sanitizePageHtml('t')).toContain('href="tel:+60123"');
expect(sanitizePageHtml('s')).toContain('href="/p/INS/x"');
expect(sanitizePageHtml('h')).not.toContain("plain.com");
+ expect(sanitizePageHtml('j')).toBe('j');
});
});
From bd8a31e4c84e86f7db7fe35b8ed2036c2426775e Mon Sep 17 00:00:00 2001
From: ngqile
Date: Thu, 3 Dec 2026 09:22:05 +0800
Subject: [PATCH 4/8] feat(pages): #name links inside Custom HTML scroll the
page
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
---
.../changes/add-page-anchor-links/tasks.md | 2 +-
.../components/pages/CmsBlocks.html.test.tsx | 21 +++++++++-
.../app/components/pages/HtmlFrame.tsx | 14 +++++--
.../app/lib/frameHtml.anchor.test.ts | 39 +++++++++++++++++++
.../app/lib/frameHtml.test.ts | 13 ++++++-
solvway-admin-portal/app/lib/frameHtml.ts | 30 +++++++++++---
6 files changed, 106 insertions(+), 13 deletions(-)
create mode 100644 solvway-admin-portal/app/lib/frameHtml.anchor.test.ts
diff --git a/openspec/changes/add-page-anchor-links/tasks.md b/openspec/changes/add-page-anchor-links/tasks.md
index 394e0ae..a788d2a 100644
--- a/openspec/changes/add-page-anchor-links/tasks.md
+++ b/openspec/changes/add-page-anchor-links/tasks.md
@@ -10,7 +10,7 @@ Design: `design.md`. Every task is TDD. Work is serial in the main session, with
## 2. Portal
- [x] 2.1 Link rules: `isSafeLink`, the rich-text editor's `SAFE_LINK`, a sanitiser test that `#name` hrefs survive; block ids in `CmsBlocks` (pattern-checked).
-- [ ] 2.2 Frame bridge: click listener in the frame script, `frameAnchor()` message check, `HtmlFrame` scroll (own frame only).
+- [x] 2.2 Frame bridge: click listener in the frame script, `frameAnchor()` message check, `HtmlFrame` scroll (own frame only).
- [ ] 2.3 Editor: "Link name" field per block with field errors; label changes in `defaultMessages.ts` and `zh_CN.seed.json`, then `npm run i18n:sql`; `sql/01-anchor-labels.sql` (new labels, plus English and Chinese updates of `PagesBadLink` and `PagesLinkPrompt`) and `sql/99-rollback.sql`.
- Verify (2.1 to 2.3): `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`
diff --git a/solvway-admin-portal/app/components/pages/CmsBlocks.html.test.tsx b/solvway-admin-portal/app/components/pages/CmsBlocks.html.test.tsx
index e130051..fbd92cb 100644
--- a/solvway-admin-portal/app/components/pages/CmsBlocks.html.test.tsx
+++ b/solvway-admin-portal/app/components/pages/CmsBlocks.html.test.tsx
@@ -1,5 +1,5 @@
import { act, render, screen } from "@testing-library/react";
-import { describe, it, expect } from "vitest";
+import { describe, it, expect, vi } from "vitest";
import { LandingPage, type PublicBlock } from "./CmsBlocks";
import { FRAME_SANDBOX } from "@/app/lib/frameHtml";
@@ -26,6 +26,25 @@ describe("LandingPage: Custom HTML", () => {
expect(frame()).toHaveAttribute("id", "story");
});
+ it("scrolls the page for a #name link in its own frame: to the frame's target, else to the named block", () => {
+ const scrollTo = vi.spyOn(window, "scrollTo").mockImplementation(() => {});
+ const into = vi.fn();
+ Element.prototype.scrollIntoView = into;
+ render();
+ vi.spyOn(frame(), "getBoundingClientRect").mockReturnValue({ top: 100 } as DOMRect);
+ const ask = (data: unknown, source: MessageEventSource | null) => act(() => { window.dispatchEvent(new MessageEvent("message", { data, source })); });
+ ask({ type: "colite-frame-anchor", name: "signup", y: null }, window);
+ expect(into).not.toHaveBeenCalled();
+ ask({ type: "colite-frame-anchor", name: "signup", y: null }, frame().contentWindow);
+ expect(into).toHaveBeenCalledTimes(1);
+ expect(into.mock.contexts[0]).toBe(document.getElementById("signup"));
+ ask({ type: "colite-frame-anchor", name: "top", y: 300 }, frame().contentWindow);
+ expect(scrollTo).toHaveBeenCalledWith({ top: 400, behavior: "smooth" });
+ ask({ type: "colite-frame-anchor", name: "nowhere", y: null }, frame().contentWindow);
+ expect(into).toHaveBeenCalledTimes(1);
+ expect(scrollTo).toHaveBeenCalledTimes(1);
+ });
+
it("uses the preview's frame address when given", () => {
render();
expect(frame()).toHaveAttribute("src", "/pages/5/preview/frame/0");
diff --git a/solvway-admin-portal/app/components/pages/HtmlFrame.tsx b/solvway-admin-portal/app/components/pages/HtmlFrame.tsx
index 1ca0e79..6ab5533 100644
--- a/solvway-admin-portal/app/components/pages/HtmlFrame.tsx
+++ b/solvway-admin-portal/app/components/pages/HtmlFrame.tsx
@@ -1,16 +1,22 @@
"use client";
import { useEffect, useRef, useState } from "react";
-import { FRAME_SANDBOX, nextFrameHeight, START_HEIGHT, type FrameHeight } from "@/app/lib/frameHtml";
+import { FRAME_SANDBOX, frameAnchor, nextFrameHeight, START_HEIGHT, type FrameHeight } from "@/app/lib/frameHtml";
-/** A Custom HTML block: the sealed frame, sized by height reports from that frame's own window only. */
+/** A Custom HTML block: the sealed frame, sized by height reports and scrolled to by #name requests from that frame's own window only. */
export function HtmlFrame({ id, src, title }: { id?: string; src: string; title: string }) {
const ref = useRef(null);
const [size, setSize] = useState({ height: START_HEIGHT, steps: [] });
useEffect(() => {
const onMessage = (e: MessageEvent) => {
- if (!ref.current || e.source !== ref.current.contentWindow) return;
- setSize((s) => nextFrameHeight(s, e.data));
+ const frame = ref.current;
+ if (!frame || e.source !== frame.contentWindow) return;
+ const anchor = frameAnchor(e.data);
+ if (!anchor) return setSize((s) => nextFrameHeight(s, e.data));
+ // add-page-anchor-links: the frame's own target first, else a named block of this page.
+ if (anchor.y !== null) return window.scrollTo({ top: frame.getBoundingClientRect().top + window.scrollY + anchor.y, behavior: "smooth" });
+ const block = document.getElementById(anchor.name);
+ if (block?.closest("main")) block.scrollIntoView({ behavior: "smooth" });
};
window.addEventListener("message", onMessage);
return () => window.removeEventListener("message", onMessage);
diff --git a/solvway-admin-portal/app/lib/frameHtml.anchor.test.ts b/solvway-admin-portal/app/lib/frameHtml.anchor.test.ts
new file mode 100644
index 0000000..0cbd446
--- /dev/null
+++ b/solvway-admin-portal/app/lib/frameHtml.anchor.test.ts
@@ -0,0 +1,39 @@
+// @vitest-environment jsdom
+import { describe, it, expect, vi, afterEach } from "vitest";
+import { frameDocument } from "./frameHtml";
+
+// add-page-anchor-links: the injected frame script turns clicks on #name links into requests to the page.
+function runFrameScript(body: string) {
+ document.body.innerHTML = body;
+ const code = frameDocument("").match(/`;
+export const FRAME_ANCHOR_MESSAGE = "colite-frame-anchor";
+/** A block link name, as in cmsPages (kept here as a string for the frame script). */
+const ANCHOR_SOURCE = "^[a-z0-9][a-z0-9-]{0,39}$";
+const ANCHOR = new RegExp(ANCHOR_SOURCE);
-/** The pasted HTML with the height script before its last