feat(pages): #name links and block ids on landing pages
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
1efdfe97d0
commit
5b5ee728c7
9 files changed
+45
-11
No files matched your search
@@ -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`
|
||||
|
||||
@@ -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(<LandingPage company={company} page={page([{ ...HTML, anchor: "story" }])} />);
|
||||
expect(frame()).toHaveAttribute("id", "story");
|
||||
});
|
||||
|
||||
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");
|
||||
|
||||
@@ -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(<LandingPage company={company} page={page([
|
||||
{ type: "HERO", heading: "Hi", buttonLabel: "Sign up", buttonUrl: "#signup" },
|
||||
{ type: "FORM", heading: "Join", closed: true, anchor: "signup" },
|
||||
{ type: "RICH_TEXT", html: "<p>x</p>", 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(<LandingPage company={company} page={page([{ type: "FORM", heading: "Join", closed: true }])} />);
|
||||
expect(screen.getByText("Sign-up is closed.")).toBeInTheDocument();
|
||||
|
||||
@@ -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 }: {
|
||||
<h1 className={page.hideHeader ? "sr-only" : `${WIDTH} mb-10 text-3xl font-semibold sm:text-4xl`}>{page.title}</h1>
|
||||
<div className="space-y-10">
|
||||
{page.blocks.map((block, i) => block.type === "HTML"
|
||||
? <HtmlFrame key={i} src={`${frames}/${i}`} title={page.title} />
|
||||
: <div key={i} className={WIDTH}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} /></div>)}
|
||||
? <HtmlFrame key={i} id={anchorId(block.anchor)} src={`${frames}/${i}`} title={page.title} />
|
||||
: <div key={i} id={anchorId(block.anchor)} className={WIDTH}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} /></div>)}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -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<HTMLIFrameElement>(null);
|
||||
const [size, setSize] = useState<FrameHeight>({ 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 <iframe ref={ref} src={src} title={title} sandbox={FRAME_SANDBOX} loading="lazy" className="block w-full border-0" style={{ height: `${size.height}px` }} />;
|
||||
return <iframe ref={ref} id={id} src={src} title={title} sandbox={FRAME_SANDBOX} loading="lazy" className="block w-full border-0" style={{ height: `${size.height}px` }} />;
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -23,5 +23,6 @@ describe("sanitizePageHtml (landing-page rich text allow-list)", () => {
|
||||
expect(sanitizePageHtml('<a href="tel:+60123">t</a>')).toContain('href="tel:+60123"');
|
||||
expect(sanitizePageHtml('<a href="/p/INS/x">s</a>')).toContain('href="/p/INS/x"');
|
||||
expect(sanitizePageHtml('<a href="http://plain.com">h</a>')).not.toContain("plain.com");
|
||||
expect(sanitizePageHtml('<a href="#signup">j</a>')).toBe('<a href="#signup">j</a>');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user