feat(pages): canvas frame spike passes; Custom HTML frames listen on their own window

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-03 14:36:17 +08:00
1 parent 55d9535ef2
commit 5f4f3bc1ee
5 files changed
+74 -8

No files matched your search

@@ -44,7 +44,7 @@ The editor mounts `<iframe>` with no `src` (about:blank, same origin), then rend
### 2. Desktop is 1280 px, scaled
- **Desktop** renders the frame 1280 px wide and scales it with a CSS transform to the width left beside the panel. The canvas height follows the frame's content.
- **Desktop** renders the frame 1280 px wide and scales it with a CSS transform to the width left beside the panel. The frame is one screen tall and scrolls inside, like a device (the spike found that growing it to its content loops, since a landing page is at least one screen tall: `min-h-svh`).
- **Phone** is 390 px at 1:1.
- Outlines, toolbars and "Add section" buttons are drawn inside the frame document, so they scale with the page.
@@ -6,7 +6,7 @@ Design: `design.md`. Every task is TDD. Work is serial in the main session, with
## 1. Foundations
- [ ] 1.1 **Spike, kept only if it passes:** render `LandingPage` into a blank frame by portal, with copied styles and theme. It passes when all of these work, in `next dev` and in one `next build` + `next start`:
- [x] 1.1 **Spike, kept only if it passes:** render `LandingPage` into a blank frame by portal, with copied styles and theme. It passes when all of these work, in `next dev` and in one `next build` + `next start`:
- Tailwind breakpoints follow the frame width (390 vs 1280).
- Fonts and dark mode look right.
- A Tiptap editor inside the frame types, selects and applies bold.
@@ -15,7 +15,8 @@ Design: `design.md`. Every task is TDD. Work is serial in the main session, with
- A Custom HTML frame inside it reports its height.
On failure, stop and switch to the canvas-route fallback (design Decision 1), noting why.
- [ ] 1.2 `HtmlFrame` listens on its own document's window (test: a frame inside another document still resizes).
Passed 2026-12-03 in `next dev` and `next build` + `next start`: 390 px stacks the cards and 1280 px shows three columns; Inter and dark mode follow the editor live; Tiptap typed and applied bold; a plain field kept its caret; dragstart and drop fired inside the scaled frame; a Custom HTML frame grew to 4419 px after 1.2. The frame scrolls inside rather than growing (design Decision 2).
- [x] 1.2 `HtmlFrame` listens on its own document's window (test: a frame inside another document still resizes).
- [ ] 1.3 Move `PageEditor` state and actions into `usePageDraft`, with no behaviour change. All existing `PageEditor*.test.tsx` stay green and unchanged.
- [ ] 1.4 Leave guard for in-app links in the form editor (test: an in-app link click with unsaved edits asks; Cancel stays, Leave navigates).
@@ -0,0 +1,51 @@
"use client";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
const BLANK = "<!doctype html><html><head></head><body></body></html>";
/** Copies the editor's stylesheets and <html> class, style and lang into the frame and keeps them in step; returns the stop. */
function mirror(doc: Document): () => void {
const syncHead = () => doc.head.replaceChildren(...[...document.head.querySelectorAll('link[rel="stylesheet"], style')].map((n) => n.cloneNode(true)));
const syncRoot = () => {
const root = document.documentElement;
doc.documentElement.className = root.className;
doc.documentElement.setAttribute("style", root.getAttribute("style") ?? "");
doc.documentElement.lang = root.lang;
};
syncHead();
syncRoot();
doc.body.className = document.body.className;
doc.body.style.margin = "0";
const heads = new MutationObserver(syncHead);
heads.observe(document.head, { childList: true, subtree: true, characterData: true });
const roots = new MutationObserver(syncRoot);
roots.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style", "lang"] });
return () => { heads.disconnect(); roots.disconnect(); };
}
/**
* A blank same-origin frame that its children render into by portal (add-page-visual-editor, design Decision 1).
* The frame is a device screen: its own viewport, so the page's breakpoints follow its width, and it scrolls inside.
* (Growing it to its content would loop, since the page is at least one screen tall.)
*/
export function CanvasFrame({ width, height, title, children }: { width: number; height: number; title: string; children: ReactNode }) {
// The loaded blank document's body; srcDoc plus onLoad so no browser swaps the document after the first render.
const [body, setBody] = useState<HTMLElement | null>(null);
const stop = useRef<() => void>(undefined);
useEffect(() => () => stop.current?.(), []);
return (
<>
<iframe title={title} srcDoc={BLANK} className="block border-0 bg-background" style={{ width, height }}
onLoad={(e) => {
const doc = e.currentTarget.contentDocument;
if (!doc) return;
stop.current?.();
stop.current = mirror(doc);
setBody(doc.body);
}} />
{body ? createPortal(children, body) : null}
</>
);
}
@@ -1,5 +1,5 @@
import { act, render, screen } from "@testing-library/react";
import { describe, it, expect, vi } from "vitest";
import { describe, it, expect, onTestFinished, vi } from "vitest";
import { LandingPage, type PublicBlock } from "./CmsBlocks";
import { FRAME_SANDBOX } from "@/app/lib/frameHtml";
@@ -58,6 +58,17 @@ describe("LandingPage: Custom HTML", () => {
expect(frame().style.height).toBe("2400px");
});
it("grows inside another document too: it listens on its own document's window (add-page-visual-editor)", () => {
const host = document.createElement("iframe");
document.body.appendChild(host);
onTestFinished(() => host.remove());
const inner = host.contentDocument!;
render(<LandingPage company={company} page={page([HTML])} />, { container: inner.body.appendChild(inner.createElement("div")) });
const sealed = inner.querySelector("iframe") as HTMLIFrameElement;
act(() => { host.contentWindow!.dispatchEvent(new MessageEvent("message", { data: { type: "colite-frame-height", height: 2400 }, source: sealed.contentWindow })); });
expect(sealed.style.height).toBe("2400px");
});
it("hides the company header and shows the title to screen readers only when the page says so", () => {
render(<LandingPage company={company} page={page([HTML], true)} />);
expect(screen.queryByRole("img", { name: "INS Sdn Bhd" })).not.toBeInTheDocument();
@@ -8,18 +8,21 @@ export function HtmlFrame({ id, src, title }: { id?: string; src: string; title:
const ref = useRef<HTMLIFrameElement>(null);
const [size, setSize] = useState<FrameHeight>({ height: START_HEIGHT, steps: [] });
useEffect(() => {
// The frame's parent window: the page's, or the editor canvas's when rendered into it (add-page-visual-editor).
const host = ref.current?.ownerDocument.defaultView;
if (!host) return;
const onMessage = (e: MessageEvent) => {
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 (anchor.y !== null) return host.scrollTo({ top: frame.getBoundingClientRect().top + host.scrollY + anchor.y, behavior: "smooth" });
const block = host.document.getElementById(anchor.name);
if (block?.closest("main")) block.scrollIntoView({ behavior: "smooth" });
};
window.addEventListener("message", onMessage);
return () => window.removeEventListener("message", onMessage);
host.addEventListener("message", onMessage);
return () => host.removeEventListener("message", onMessage);
}, []);
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` }} />;
}