Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
52 lines
2.4 KiB
TypeScript
52 lines
2.4 KiB
TypeScript
"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.
|
|
*/
|
|
export function CanvasFrame({ width, height, title, children }: { width: number; height: number; title: string; children: ReactNode }) {
|
|
// A container in the loaded blank document, which React removes the portal from cleanly when the frame goes.
|
|
// srcDoc plus onLoad, so no browser swaps the document out after the first render.
|
|
const [root, setRoot] = 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);
|
|
setRoot(doc.body.appendChild(doc.createElement("div")));
|
|
}} />
|
|
{root ? createPortal(children, root) : null}
|
|
</>
|
|
);
|
|
}
|