From bd8a31e4c84e86f7db7fe35b8ed2036c2426775e Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 3 Dec 2026 09:22:05 +0800 Subject: [PATCH] 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 , or appended when it is a fragment. */ +// Posts the document height to the parent page on load and whenever it changes. A click on a #name link +// (add-page-anchor-links) asks the page to scroll instead: the frame is as tall as its content and never scrolls. +const FRAME_SCRIPT = + ``; + +/** The pasted HTML with the frame script before its last , or appended when it is a fragment. */ export function frameDocument(html: string): string { const at = html.toLowerCase().lastIndexOf(""); - return at < 0 ? html + HEIGHT_SCRIPT : html.slice(0, at) + HEIGHT_SCRIPT + html.slice(at); + return at < 0 ? html + FRAME_SCRIPT : html.slice(0, at) + FRAME_SCRIPT + html.slice(at); } export function frameResponse(html: string, { preview }: { preview: boolean }): Response { @@ -65,3 +74,12 @@ export function nextFrameHeight(state: FrameHeight, data: unknown): FrameHeight if (a !== undefined && b !== undefined && Math.abs(a - step) <= 2 && Math.abs(b - step) <= 2) return state; return { height, steps: [...state.steps, step].slice(-2) }; } + +/** A same-page link request from a frame: a valid link name and the target's offset in the frame (null when the frame lacks it). Junk is null. */ +export function frameAnchor(data: unknown): { name: string; y: number | null } | null { + const d = data as { type?: unknown; name?: unknown; y?: unknown } | null; + if (!d || typeof d !== "object" || d.type !== FRAME_ANCHOR_MESSAGE || typeof d.name !== "string" || !ANCHOR.test(d.name)) return null; + if (d.y === null) return { name: d.name, y: null }; + if (typeof d.y !== "number" || !Number.isFinite(d.y)) return null; + return { name: d.name, y: Math.min(MAX_HEIGHT, Math.max(0, Math.round(d.y))) }; +}