feat(pages): #name links inside Custom HTML scroll the page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
1 parent
5b5ee728c7
commit
bd8a31e4c8
6 files changed
+106
-13
No files matched your search
@@ -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`
|
||||
|
||||
|
||||
@@ -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(<LandingPage company={company} page={page([HTML, { type: "FORM", heading: "Join", closed: true, anchor: "signup" }])} />);
|
||||
vi.spyOn(frame(), "getBoundingClientRect").mockReturnValue({ top: 100 } as DOMRect);
|
||||
const ask = (data: unknown, source: MessageEventSource | null) => act(() => { window.dispatchEvent(new MessageEvent("message", { data, source })); });
|
||||
ask({ type: "colite-frame-anchor", name: "signup", y: null }, window);
|
||||
expect(into).not.toHaveBeenCalled();
|
||||
ask({ type: "colite-frame-anchor", name: "signup", y: null }, frame().contentWindow);
|
||||
expect(into).toHaveBeenCalledTimes(1);
|
||||
expect(into.mock.contexts[0]).toBe(document.getElementById("signup"));
|
||||
ask({ type: "colite-frame-anchor", name: "top", y: 300 }, frame().contentWindow);
|
||||
expect(scrollTo).toHaveBeenCalledWith({ top: 400, behavior: "smooth" });
|
||||
ask({ type: "colite-frame-anchor", name: "nowhere", y: null }, frame().contentWindow);
|
||||
expect(into).toHaveBeenCalledTimes(1);
|
||||
expect(scrollTo).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("uses the preview's frame address when given", () => {
|
||||
render(<LandingPage company={company} page={page([HTML])} frameBase="/pages/5/preview/frame" preview />);
|
||||
expect(frame()).toHaveAttribute("src", "/pages/5/preview/frame/0");
|
||||
|
||||
@@ -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<HTMLIFrameElement>(null);
|
||||
const [size, setSize] = useState<FrameHeight>({ 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);
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
// @vitest-environment jsdom
|
||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import { frameDocument } from "./frameHtml";
|
||||
|
||||
// add-page-anchor-links: the injected frame script turns clicks on #name links into requests to the page.
|
||||
function runFrameScript(body: string) {
|
||||
document.body.innerHTML = body;
|
||||
const code = frameDocument("").match(/<script>([\s\S]*)<\/script>/)![1];
|
||||
new Function(code)();
|
||||
}
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
describe("frame script: same-page links", () => {
|
||||
it("asks the page to scroll, with the in-frame target's offset when the frame has it, and never navigates the frame", () => {
|
||||
const post = vi.spyOn(window.parent, "postMessage").mockImplementation(() => {});
|
||||
runFrameScript('<div id="top">Top</div><a href="#top">Back</a><a href="#signup"><span>Join</span></a>');
|
||||
const back = new MouseEvent("click", { bubbles: true, cancelable: true });
|
||||
document.querySelector('a[href="#top"]')!.dispatchEvent(back);
|
||||
expect(back.defaultPrevented).toBe(true);
|
||||
expect(post).toHaveBeenCalledWith({ type: "colite-frame-anchor", name: "top", y: 0 }, "*");
|
||||
const join = new MouseEvent("click", { bubbles: true, cancelable: true });
|
||||
document.querySelector("span")!.dispatchEvent(join);
|
||||
expect(join.defaultPrevented).toBe(true);
|
||||
expect(post).toHaveBeenCalledWith({ type: "colite-frame-anchor", name: "signup", y: null }, "*");
|
||||
});
|
||||
|
||||
it("leaves other links alone", () => {
|
||||
const post = vi.spyOn(window.parent, "postMessage").mockImplementation(() => {});
|
||||
runFrameScript('<a href="https://wa.me/1">WA</a><a href="#Bad Name">Bad</a>');
|
||||
post.mockClear();
|
||||
for (const a of document.querySelectorAll("a")) {
|
||||
const click = new MouseEvent("click", { bubbles: true, cancelable: true });
|
||||
a.dispatchEvent(click);
|
||||
expect(click.defaultPrevented).toBe(false);
|
||||
}
|
||||
expect(post.mock.calls.filter(([d]) => (d as { type: string }).type === "colite-frame-anchor")).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { FRAME_SANDBOX, frameDocument, frameResponse, nextFrameHeight, START_HEIGHT } from "./frameHtml";
|
||||
import { FRAME_SANDBOX, frameAnchor, frameDocument, frameResponse, nextFrameHeight, START_HEIGHT } from "./frameHtml";
|
||||
|
||||
// add-custom-html-block: pasted HTML runs sealed, in its own document with a sandbox policy, and reports its height.
|
||||
describe("frameHtml", () => {
|
||||
@@ -54,4 +54,15 @@ describe("frameHtml", () => {
|
||||
for (const h of [900, 1250, 1900, 2000, 2600]) t = nextFrameHeight(t, { type: "colite-frame-height", height: h });
|
||||
expect(t.height).toBe(2600);
|
||||
});
|
||||
|
||||
// add-page-anchor-links: a frame asks its page to scroll to a #name target.
|
||||
it("reads a same-page link request: a valid name and the in-frame offset, or nothing", () => {
|
||||
expect(frameAnchor({ type: "colite-frame-anchor", name: "signup", y: null })).toEqual({ name: "signup", y: null });
|
||||
expect(frameAnchor({ type: "colite-frame-anchor", name: "top", y: 120.4 })).toEqual({ name: "top", y: 120 });
|
||||
expect(frameAnchor({ type: "colite-frame-anchor", name: "top", y: -5 })).toEqual({ name: "top", y: 0 });
|
||||
for (const junk of [null, "x", { type: "colite-frame-height", height: 5 }, { type: "colite-frame-anchor", name: "Sign Up", y: null },
|
||||
{ type: "colite-frame-anchor", name: "a", y: "1" }, { type: "colite-frame-anchor", name: "a", y: Infinity }, { type: "colite-frame-anchor", y: null }]) {
|
||||
expect(frameAnchor(junk), JSON.stringify(junk)).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -10,15 +10,24 @@ export const START_HEIGHT = 600;
|
||||
const MIN_HEIGHT = 100;
|
||||
const MAX_HEIGHT = 20000;
|
||||
|
||||
// Posts the document height to the parent page on load and whenever it changes.
|
||||
const HEIGHT_SCRIPT =
|
||||
`<script>(function(){function s(){parent.postMessage({type:"${FRAME_MESSAGE}",height:Math.ceil(document.documentElement.scrollHeight)},"*")}` +
|
||||
`addEventListener("load",s);if(window.ResizeObserver)new ResizeObserver(s).observe(document.documentElement);s()})();</script>`;
|
||||
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 </body>, or appended when it is a fragment. */
|
||||
// Posts the document height to the parent page on load and whenever it changes. A click on a #name link
|
||||
// (add-page-anchor-links) asks the page to scroll instead: the frame is as tall as its content and never scrolls.
|
||||
const FRAME_SCRIPT =
|
||||
`<script>(function(){function s(){parent.postMessage({type:"${FRAME_MESSAGE}",height:Math.ceil(document.documentElement.scrollHeight)},"*")}` +
|
||||
`addEventListener("load",s);if(window.ResizeObserver)new ResizeObserver(s).observe(document.documentElement);s();` +
|
||||
`document.addEventListener("click",function(e){var a=e.target&&e.target.closest&&e.target.closest('a[href^="#"]');if(!a)return;` +
|
||||
`var n=a.getAttribute("href").slice(1);if(!/${ANCHOR_SOURCE}/.test(n))return;e.preventDefault();var t=document.getElementById(n);` +
|
||||
`parent.postMessage({type:"${FRAME_ANCHOR_MESSAGE}",name:n,y:t?Math.round(t.getBoundingClientRect().top+scrollY):null},"*")})})();</script>`;
|
||||
|
||||
/** The pasted HTML with the frame script before its last </body>, or appended when it is a fragment. */
|
||||
export function frameDocument(html: string): string {
|
||||
const at = html.toLowerCase().lastIndexOf("</body>");
|
||||
return at < 0 ? html + HEIGHT_SCRIPT : html.slice(0, at) + HEIGHT_SCRIPT + html.slice(at);
|
||||
return at < 0 ? html + FRAME_SCRIPT : html.slice(0, at) + FRAME_SCRIPT + html.slice(at);
|
||||
}
|
||||
|
||||
export function frameResponse(html: string, { preview }: { preview: boolean }): Response {
|
||||
@@ -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))) };
|
||||
}
|
||||
Reference in new issue
Block a user