scaling-swarms / frontend /src /editor /embeds /HtmlEmbedView.tsx
tfrere's picture
tfrere HF Staff
Cursor
perf(frontend): mount embed iframes and load images only near the viewport
6d7d323
Raw History Blame Contribute Delete
14.8 kB
import React, { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { NodeViewWrapper } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
import type { ComponentDef, ComponentField } from "../components/registry";
import { buildDoc, DEFAULT_EMBED_HEIGHT } from "./build-doc";
import type { EmbedStore } from "./embed-store";
import { isDraftDirty, type EmbedDraft, type EmbedDraftStore } from "./embed-drafts";
import { useTheme } from "../../hooks/useTheme";
import { useStudioPresence } from "../../hooks/useStudioPresence";
import type { HocuspocusProvider } from "@hocuspocus/provider";
import { Sparkles } from "lucide-react";
import { InlineEmbedEdit, type InlineStudioDeps } from "./InlineEmbedEdit";
/** Phones get the inline edit bar instead of the full-screen studio. */
const NARROW_QUERY = "(max-width: 900px)";
/**
* Resolve embed store from the editor's storage.
* The store is injected by Editor.tsx into editor.storage.htmlEmbed.embedStore.
*/
function useEmbedStore(editor: NodeViewProps["editor"]): EmbedStore | null {
return (editor.storage.htmlEmbed as any)?.embedStore ?? null;
}
/** Fired by App once it has put the studio deps into editor storage. */
export const EMBED_STUDIO_READY_EVENT = "embed-studio-ready";
function useHtmlEmbedStorage(editor: NodeViewProps["editor"]) {
// Node views can mount before App injects the studio deps: re-read then.
const [, setTick] = useState(0);
useEffect(() => {
const bump = () => setTick((t) => t + 1);
window.addEventListener(EMBED_STUDIO_READY_EVENT, bump);
return () => window.removeEventListener(EMBED_STUDIO_READY_EVENT, bump);
}, []);
const storage = (editor.storage.htmlEmbed as any) ?? {};
return {
drafts: (storage.drafts ?? null) as EmbedDraftStore | null,
provider: (storage.provider ?? null) as HocuspocusProvider | null,
studio: (storage.studio ?? null) as InlineStudioDeps | null,
};
}
function useDraft(drafts: EmbedDraftStore | null, src: string): EmbedDraft | undefined {
const [draft, setDraft] = useState<EmbedDraft | undefined>(() => (drafts && src ? drafts.get(src) : undefined));
useEffect(() => {
if (!drafts || !src) {
setDraft(undefined);
return;
}
setDraft(drafts.get(src));
return drafts.observe(() => setDraft(drafts.get(src)));
}, [drafts, src]);
return draft;
}
function FieldRow({
field,
value,
onChange,
}: {
field: ComponentField;
value: unknown;
onChange: (val: unknown) => void;
}) {
if (field.type === "boolean") {
return (
<label className="embed-field-row embed-field-checkbox">
<input
type="checkbox"
checked={!!value}
onChange={(e) => onChange(e.target.checked)}
/>
{field.label}
</label>
);
}
return (
<div className="embed-field-row">
<span className="embed-field-label">{field.label}</span>
<input
type="text"
value={String(value ?? "")}
placeholder={field.placeholder || field.label}
onChange={(e) => onChange(e.target.value)}
className="embed-field-input"
/>
</div>
);
}
/** Start loading a chart when it gets this close to the viewport. */
const MOUNT_MARGIN = "800px 0px";
/**
* True once `ref` has come near the viewport, then stays true so the chart
* keeps its state. Long articles then only boot the charts the reader sees.
*/
function useNearViewport(ref: React.RefObject<HTMLElement | null>, mounted: boolean): boolean {
const [near, setNear] = useState(() => typeof IntersectionObserver === "undefined");
useEffect(() => {
const el = ref.current;
if (near || !mounted || !el) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((e) => e.isIntersecting)) {
setNear(true);
observer.disconnect();
}
},
{ rootMargin: MOUNT_MARGIN },
);
observer.observe(el);
return () => observer.disconnect();
}, [near, mounted, ref]);
return near;
}
/** Safely parse the stored height attribute (legacy: string; new: number). */
function parseStoredHeight(raw: unknown): number {
if (typeof raw === "number" && raw > 0) return Math.round(raw);
const n = parseInt(String(raw ?? ""), 10);
return Number.isFinite(n) && n > 0 ? n : DEFAULT_EMBED_HEIGHT;
}
export function makeHtmlEmbedView(def: ComponentDef) {
function HtmlEmbedNodeView({ node, updateAttributes, editor }: NodeViewProps) {
const src = (node.attrs.src as string) || "";
const title = (node.attrs.title as string) || "";
const storedHeight = parseStoredHeight(node.attrs.height);
const { isDark, primaryColor } = useTheme();
const embedStore = useEmbedStore(editor);
const { drafts, provider, studio } = useHtmlEmbedStorage(editor);
const [inlineOpen, setInlineOpen] = useState(false);
const [inlineView, setInlineView] = useState<"before" | "after">("after");
const peers = useStudioPresence(provider, src);
const draft = useDraft(drafts, src);
const hasDraft = isDraftDirty(draft);
const [html, setHtml] = useState("");
const [iframeHeight, setIframeHeight] = useState(storedHeight);
const [showSettings, setShowSettings] = useState(false);
const iframeRef = useRef<HTMLIFrameElement>(null);
const previewRef = useRef<HTMLDivElement>(null);
const nearViewport = useNearViewport(previewRef, !!html);
// Sync from embed store
useEffect(() => {
if (!embedStore || !src) return;
setHtml(embedStore.get(src));
return embedStore.observeKey(src, setHtml);
}, [embedStore, src]);
// Build full document for srcdoc.
// NOTE: only depends on `html` – theme changes are pushed via postMessage
// below so we don't reload the iframe (which would lose chart state).
// While the inline edit bar is open, the chart shows the draft (After)
// or what the article has (Before).
const showDraft = inlineOpen && hasDraft && inlineView === "after" && !!draft?.html;
const displayHtml = showDraft ? draft!.html : html;
const srcdoc = useMemo(() => {
if (!displayHtml) return "";
return buildDoc(displayHtml, { isDark, primaryColor });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [displayHtml]);
// Hot-swap theme inside the iframe without reload.
useEffect(() => {
const frame = iframeRef.current;
if (!frame || !html) return;
const win = frame.contentWindow;
if (!win) return;
const send = () => {
try {
win.postMessage(
{
type: "setTheme",
theme: isDark ? "dark" : "light",
primaryColor,
},
"*",
);
} catch {
/* cross-origin / not yet loaded – will retry on load */
}
};
send();
const onLoad = () => send();
frame.addEventListener("load", onLoad);
return () => frame.removeEventListener("load", onLoad);
}, [isDark, primaryColor, html, nearViewport]);
// Listen for height reports from the iframe.
// - Apply immediately to the visible iframe (React state) for smooth resize.
// - Debounce the PM transaction (node attribute) so document history isn't
// polluted with noisy updates during animations.
const lastPersistedRef = useRef<number>(storedHeight);
const persistTimerRef = useRef(0);
useEffect(() => {
const handler = (e: MessageEvent) => {
if (e.data?.type !== "embedResize") return;
const frame = iframeRef.current;
if (!frame || e.source !== frame.contentWindow) return;
const h = Math.max(0, Math.ceil(e.data.height));
if (!h) return;
setIframeHeight((prev) => (prev === h ? prev : h));
if (h !== lastPersistedRef.current) {
clearTimeout(persistTimerRef.current);
persistTimerRef.current = window.setTimeout(() => {
if (h !== lastPersistedRef.current) {
lastPersistedRef.current = h;
updateAttributes({ height: h });
}
}, 800);
}
};
window.addEventListener("message", handler);
return () => {
window.removeEventListener("message", handler);
clearTimeout(persistTimerRef.current);
};
}, [updateAttributes]);
// Reset persisted tracker when the underlying node attribute changes from
// the outside (undo/redo, collab remote update).
useEffect(() => {
lastPersistedRef.current = storedHeight;
}, [storedHeight]);
const handleFieldChange = useCallback(
(fieldName: string, value: unknown) => {
updateAttributes({ [fieldName]: value });
},
[updateAttributes],
);
const hasContent = !!html;
// Metadata fields (exclude height - managed automatically from iframe)
const editableFields = def.fields.filter((f) => f.name !== "height");
return (
<NodeViewWrapper data-component="htmlEmbed">
<div contentEditable={false} className="embed-view">
{/* Header */}
<div className="embed-header">
<div className="embed-header-left">
<span className="embed-header-icon">📊</span>
<span className="embed-header-label">
{title || src || "HTML Embed"}
</span>
{src && title && (
<span className="embed-header-src">{src}</span>
)}
{peers.length > 0 ? (
<span
className="embed-header-badge embed-header-badge--live"
style={{ ["--peer" as string]: peers[0].color }}
title="Open in the Embed Studio"
>
{peers.length === 1
? `${peers[0].name} is editing this chart`
: `${peers.length} people are editing this chart`}
</span>
) : hasDraft ? (
<span className="embed-header-badge" title="Changes made in the Embed Studio that are not applied yet">
Unapplied draft{draft?.author ? ` by ${draft.author}` : ""}
</span>
) : null}
</div>
<div className="embed-header-actions">
<button
className="embed-btn"
onClick={() => setShowSettings(!showSettings)}
title="Settings"
>
{showSettings ? "Close" : "Settings"}
</button>
{hasContent && studio && drafts && embedStore && (
<button
className={`embed-btn ${inlineOpen ? "embed-btn-active" : ""}`}
onClick={() => setInlineOpen((o) => !o)}
title="Ask AI to change this chart, right here"
aria-pressed={inlineOpen}
>
<Sparkles size={13} />
Ask AI
</button>
)}
{hasContent && (
<button
className="embed-btn embed-btn-primary"
onClick={() => {
if (studio && drafts && window.matchMedia?.(NARROW_QUERY).matches) {
setInlineOpen(true);
return;
}
window.dispatchEvent(
new CustomEvent("open-embed-studio", { detail: { src } }),
);
}}
title="Open Embed Studio"
>
Edit
</button>
)}
</div>
</div>
{/* Settings panel */}
{showSettings && (
<div className="embed-settings">
{editableFields.map((f) => (
<FieldRow
key={f.name}
field={f}
value={node.attrs[f.name]}
onChange={(v) => handleFieldChange(f.name, v)}
/>
))}
</div>
)}
{/* Preview */}
{hasContent ? (
<div ref={previewRef} className={`embed-preview ${showDraft ? "embed-preview--draft" : ""}`}>
{nearViewport ? (
<iframe
ref={iframeRef}
srcDoc={srcdoc}
title={title || src || "Chart preview"}
sandbox="allow-scripts allow-same-origin"
className="embed-iframe"
style={{
height: iframeHeight,
minHeight: Math.min(storedHeight, 120),
}}
/>
) : (
<div className="embed-iframe" style={{ height: iframeHeight }} aria-hidden="true" />
)}
</div>
) : (
<div className="embed-empty">
{src ? (
<>
<span className="embed-empty-icon">📊</span>
<span>
No content for <code>{src}</code>
</span>
<button
className="embed-btn embed-btn-primary"
onClick={() => {
window.dispatchEvent(
new CustomEvent("open-embed-studio", { detail: { src } }),
);
}}
>
Create Chart
</button>
</>
) : (
<>
<span className="embed-empty-icon">📊</span>
<span>Set a source filename in settings to link an embed</span>
<button
className="embed-btn"
onClick={() => setShowSettings(true)}
>
Open Settings
</button>
</>
)}
</div>
)}
{inlineOpen && hasContent && studio && drafts && embedStore && (
<InlineEmbedEdit
src={src}
embedStore={embedStore}
drafts={drafts}
draft={draft}
deps={studio}
view={inlineView}
onView={setInlineView}
onClose={() => setInlineOpen(false)}
onOpenStudio={() => {
setInlineOpen(false);
window.dispatchEvent(new CustomEvent("open-embed-studio", { detail: { src } }));
}}
/>
)}
</div>
</NodeViewWrapper>
);
}
HtmlEmbedNodeView.displayName = "HtmlEmbedView";
return HtmlEmbedNodeView;
}