Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
29 lines
1.7 KiB
TypeScript
29 lines
1.7 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useRef, useState } from "react";
|
|
import { FRAME_SANDBOX, frameAnchor, nextFrameHeight, START_HEIGHT, type FrameHeight } from "@/app/lib/frameHtml";
|
|
|
|
/** 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(() => {
|
|
// 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 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" });
|
|
};
|
|
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` }} />;
|
|
}
|