Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(editor): reload embedded HTML previews (#9436)

Frezcdff37867b7c1
diff --git a/packages/views/editor/dynamic-block.tsx b/packages/views/editor/dynamic-block.tsx
index e6ef10e05b..3364230cf2 100644
--- a/packages/views/editor/dynamic-block.tsx
+++ b/packages/views/editor/dynamic-block.tsx
@@ -32,6 +32,7 @@ import {
CodeXml,
Copy,
Maximize2,
+ RotateCw,
TriangleAlert,
Workflow,
} from "lucide-react";
@@ -87,6 +88,8 @@ interface DynamicBlockProps {
error?: DynamicBlockError | null;
/** Shows the fullscreen button when set. */
onFullscreen?: () => void;
+ /** Reloads the current preview when the kind supports it. */
+ onReload?: () => void;
/** Reveals the mounted preview while its surface is enlarged. */
fullscreen?: boolean;
/** Focus returns here when the kind's fullscreen surface closes. */
@@ -105,6 +108,7 @@ export function DynamicBlock({
source,
error,
onFullscreen,
+ onReload,
fullscreen = false,
fullscreenButtonRef,
preview,
@@ -180,6 +184,19 @@ export function DynamicBlock({
{t(($) => $.dynamic_block.source)}
</TabsTrigger>
</TabsList>
+ {onReload && (
+ <IconButton
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className="text-muted-foreground"
+ disabled={view !== "preview"}
+ onClick={onReload}
+ label={t(($) => $.attachment.reload)}
+ >
+ <RotateCw />
+ </IconButton>
+ )}
{onFullscreen && (
<IconButton
ref={fullscreenButtonRef}
diff --git a/packages/views/editor/extensions/code-block-view.test.tsx b/packages/views/editor/extensions/code-block-view.test.tsx
index 2b10a99902..1fe4ffe34f 100644
--- a/packages/views/editor/extensions/code-block-view.test.tsx
+++ b/packages/views/editor/extensions/code-block-view.test.tsx
@@ -5,6 +5,7 @@ import {
fireEvent,
render,
screen,
+ within,
} from "@testing-library/react";
import { mockNativeDialog } from "../test-utils/native-dialog";
@@ -43,6 +44,7 @@ vi.mock("../../i18n", () => ({
fullscreen: "Fullscreen",
close_preview: "Close",
},
+ attachment: { reload: "Reload" },
}),
}),
}));
@@ -152,6 +154,33 @@ describe("CodeBlockView — html language toggle", () => {
expect(screen.queryByRole("button", { name: "Show source" })).toBeNull();
expect(screen.queryByRole("button", { name: "Show preview" })).toBeNull();
expect(document.querySelector("iframe")).toBeNull();
+ expect(screen.queryByRole("button", { name: "Reload" })).toBeNull();
+ });
+
+ it("reloads inline and enlarged HTML while preserving the editor and surface", () => {
+ render(<CodeBlockView {...makeProps("html", "<p>hello</p>")} />);
+ const original = document.querySelector("iframe");
+ const content = screen.getByTestId("nvc");
+ fireEvent.click(screen.getByRole("button", { name: "Reload" }));
+ const inline = document.querySelector("iframe");
+ expect(inline).not.toBe(original);
+ expect(inline?.getAttribute("srcdoc")).toBe("<p>hello</p>");
+ expect(screen.getByTestId("nvc")).toBe(content);
+
+ fireEvent.click(screen.getByRole("button", { name: "Show source" }));
+ expect(screen.getByRole("button", { name: "Reload" }).hasAttribute("disabled")).toBe(true);
+ fireEvent.click(screen.getByRole("button", { name: "Fullscreen" }));
+ const dialog = screen.getByRole("dialog");
+ fireEvent.click(within(dialog).getByRole("button", { name: "Reload" }));
+ const enlarged = dialog.querySelector("iframe");
+ expect(enlarged).not.toBe(inline);
+ expect(enlarged?.getAttribute("sandbox")).toBe("allow-scripts");
+ expect(screen.getByRole("dialog")).toBe(dialog);
+ expect(document.querySelectorAll("iframe")).toHaveLength(1);
+ fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));
+ expect(document.querySelector("iframe")).toBe(enlarged);
+ expect(screen.getByTestId("nvc")).toBe(content);
+ expect(content.closest("pre")?.className).not.toContain("sr-only");
});
it("defers source edits until the retained preview is visible", () => {
diff --git a/packages/views/editor/extensions/code-block-view.tsx b/packages/views/editor/extensions/code-block-view.tsx
index 1aea72549b..48ae29c40f 100644
--- a/packages/views/editor/extensions/code-block-view.tsx
+++ b/packages/views/editor/extensions/code-block-view.tsx
@@ -3,7 +3,7 @@
import { useState } from "react";
import { NodeViewWrapper, NodeViewContent } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
-import { Code as CodeIcon, Copy, Check, Eye, Maximize2 } from "lucide-react";
+import { Code as CodeIcon, Copy, Check, Eye, Maximize2, RotateCw } from "lucide-react";
import { IconButton } from "@multica/ui/components/common/icon-button";
import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
import { HtmlPreviewSurface } from "../html-preview-surface";
@@ -29,6 +29,8 @@ function CodeBlockView({ node }: NodeViewProps) {
const { t } = useT("editor");
const [copied, setCopied] = useState(false);
const [fullscreen, setFullscreen] = useState(false);
+ const [reloadKey, setReloadKey] = useState(0);
+ const reload = () => setReloadKey((key) => key + 1);
// HTML blocks default to "preview"; the user can flip to "source" to
// edit the markup directly. Note: the source `<pre>` MUST stay mounted
// (just hidden) so ProseMirror keeps its NodeView bindings — unmounting
@@ -84,9 +86,11 @@ function CodeBlockView({ node }: NodeViewProps) {
open={fullscreen}
inlineHeight={showHtmlPreview ? HTML_PREVIEW_HEIGHT_PX : 0}
onOpenChange={setFullscreen}
+ onReload={reload}
title={t(($) => $.code_block.html_preview)}
>
<CodeBlockIframe
+ key={reloadKey}
html={debouncedHtml}
title={t(($) => $.code_block.html_preview)}
heightClassName={fullscreen ? "h-full" : "h-[480px]"}
@@ -130,6 +134,19 @@ function CodeBlockView({ node }: NodeViewProps) {
</button>
</TooltipHint>
)}
+ {isHtml && (
+ <IconButton
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className="text-muted-foreground"
+ disabled={!showHtmlPreview}
+ label={t(($) => $.attachment.reload)}
+ onClick={reload}
+ >
+ <RotateCw className="h-3.5 w-3.5" />
+ </IconButton>
+ )}
{isHtml && (
<IconButton
type="button"
diff --git a/packages/views/editor/html-block-preview.test.tsx b/packages/views/editor/html-block-preview.test.tsx
index 1895c71b0d..428bb00b33 100644
--- a/packages/views/editor/html-block-preview.test.tsx
+++ b/packages/views/editor/html-block-preview.test.tsx
@@ -5,6 +5,7 @@ import {
fireEvent,
render,
screen,
+ within,
} from "@testing-library/react";
import { mockNativeDialog } from "./test-utils/native-dialog";
@@ -162,6 +163,88 @@ describe("HtmlBlockPreview — errors", () => {
});
});
+describe("HtmlBlockPreview — reload", () => {
+ it("reloads only the requested frame and restarts height measurement after a script error", () => {
+ render(
+ <>
+ <HtmlBlockPreview html="<p>first</p>" title="First" />
+ <HtmlBlockPreview html="<p>second</p>" title="Second" />
+ </>,
+ );
+ const frames = document.querySelectorAll("iframe");
+ const first = frames[0]!;
+ const second = frames[1]!;
+ const block = first.closest('[data-dynamic-block="html"]') as HTMLElement;
+ for (const height of [200, 300, 400, 500]) post(first, { type: "height", height });
+ post(first, { type: "error", message: "Network unavailable" });
+ expect(within(block).getByRole("alert").textContent).toContain("Network unavailable");
+ const staleWindow = first.contentWindow;
+ const srcDoc = first.getAttribute("srcdoc");
+
+ fireEvent.click(within(block).getByRole("button", { name: "Reload" }));
+
+ const fresh = block.querySelector("iframe")!;
+ expect(fresh).not.toBe(first);
+ expect(first.isConnected).toBe(false);
+ expect(second.isConnected).toBe(true);
+ expect(fresh.getAttribute("srcdoc")).toBe(srcDoc);
+ expect(fresh.getAttribute("sandbox")).toBe("allow-scripts");
+ expect(within(block).queryByRole("alert")).toBeNull();
+ expect(within(block).getByText("Rendering...")).toBeTruthy();
+ act(() => {
+ window.dispatchEvent(new MessageEvent("message", {
+ source: staleWindow,
+ data: { [HTML_BLOCK_MESSAGE_KEY]: 1, type: "error", message: "Stale error" },
+ }));
+ });
+ expect(within(block).queryByRole("alert")).toBeNull();
+ post(fresh, { type: "height", height: 600 });
+ expect(fresh.parentElement?.style.height).toBe("600px");
+ expect(within(block).queryByText("Rendering...")).toBeNull();
+ });
+
+ it("waits for the reloaded document before restarting the missing-bridge timeout", () => {
+ vi.useFakeTimers();
+ try {
+ render(<HtmlBlockPreview html="<p>no bridge reports</p>" />);
+ fireEvent.load(inlineFrame());
+ act(() => vi.advanceTimersByTime(1000));
+ expect(screen.queryByText("Rendering...")).toBeNull();
+
+ fireEvent.click(screen.getByRole("button", { name: "Reload" }));
+ act(() => vi.advanceTimersByTime(1000));
+ expect(screen.getByText("Rendering...")).toBeTruthy();
+ fireEvent.load(inlineFrame());
+ act(() => vi.advanceTimersByTime(1000));
+ expect(screen.queryByText("Rendering...")).toBeNull();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("reloads inside the same enlarged surface and retains source selection on close", () => {
+ render(<HtmlBlockPreview html="<p>hi</p>" />);
+ const original = inlineFrame();
+ fireEvent.click(screen.getByRole("tab", { name: "Source" }));
+ const source = screen.getByTestId("code-block-static");
+ expect(screen.getByRole("button", { name: "Reload" }).hasAttribute("disabled")).toBe(true);
+ fireEvent.click(screen.getByRole("button", { name: "Fullscreen" }));
+ const dialog = screen.getByRole("dialog");
+
+ fireEvent.click(within(dialog).getByRole("button", { name: "Reload" }));
+
+ expect(screen.getByRole("dialog")).toBe(dialog);
+ const fresh = dialog.querySelector("iframe");
+ expect(fresh).not.toBe(original);
+ expect(document.querySelectorAll("iframe")).toHaveLength(1);
+ expect(source.isConnected).toBe(true);
+ fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));
+ expect(screen.getByRole("tab", { name: "Source" }).getAttribute("aria-selected")).toBe("true");
+ fireEvent.click(screen.getByRole("tab", { name: "Preview" }));
+ expect(inlineFrame()).toBe(fresh);
+ });
+});
+
describe("HtmlBlockPreview — fullscreen", () => {
it("enlarges the loaded iframe without creating another document", () => {
render(<HtmlBlockPreview html="<p>hi</p>" />);
diff --git a/packages/views/editor/html-block-preview.tsx b/packages/views/editor/html-block-preview.tsx
index 2d80675726..6990f0daac 100644
--- a/packages/views/editor/html-block-preview.tsx
+++ b/packages/views/editor/html-block-preview.tsx
@@ -14,7 +14,7 @@
* `<NodeViewContent as="code" />` so the user can continue typing.
*/
-import { useEffect, useLayoutEffect, useReducer, useRef, useState } from "react";
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { cn } from "@multica/ui/lib/utils";
import { HtmlPreviewSurface } from "./html-preview-surface";
import { useT } from "../i18n";
@@ -105,8 +105,14 @@ export function HtmlBlockPreview({ html, title }: HtmlBlockPreviewProps) {
const [srcDoc, setSrcDoc] = useState<string | null>(null);
const [error, setError] = useState<DynamicBlockError | null>(null);
const [fullscreen, setFullscreen] = useState(false);
+ const [reloadKey, setReloadKey] = useState(0);
const frameTitle = t(($) => $.code_block.html_preview);
+ const reload = () => {
+ setError(null);
+ setReloadKey((key) => key + 1);
+ };
+
// Built after mount: the theme tokens come from the host's computed style.
// A theme switch rebuilds the document, which reruns its scripts — a chart
// reads its colors when it draws, so this is the only way it can follow.
@@ -126,6 +132,7 @@ export function HtmlBlockPreview({ html, title }: HtmlBlockPreviewProps) {
error={error}
fullscreen={fullscreen}
onFullscreen={() => setFullscreen(true)}
+ onReload={reload}
preview={({ active }) => (
<HtmlBlockBody
key={html}
@@ -134,6 +141,8 @@ export function HtmlBlockPreview({ html, title }: HtmlBlockPreviewProps) {
title={frameTitle}
active={active}
fullscreen={fullscreen}
+ reloadKey={reloadKey}
+ onReload={reload}
onFullscreenChange={setFullscreen}
onError={setError}
/>
@@ -149,6 +158,8 @@ function HtmlBlockBody({
title,
active,
fullscreen,
+ reloadKey,
+ onReload,
onFullscreenChange,
onError,
}: {
@@ -157,15 +168,24 @@ function HtmlBlockBody({
title: string;
active: boolean;
fullscreen: boolean;
+ reloadKey: number;
+ onReload: () => void;
onFullscreenChange: (open: boolean) => void;
onError: (error: DynamicBlockError) => void;
}) {
const iframeRef = useRef<HTMLIFrameElement>(null);
- const [measured, reportHeight] = useReducer(nextHtmlBlockHeight, INITIAL_HTML_BLOCK_HEIGHT);
+ const [measured, setMeasured] = useState(INITIAL_HTML_BLOCK_HEIGHT);
const [cachedHeight, setCachedHeight] = useState<number | null>(null);
const [loaded, setLoaded] = useState(false);
const [timedOut, setTimedOut] = useState(false);
+ useLayoutEffect(() => {
+ setMeasured(INITIAL_HTML_BLOCK_HEIGHT);
+ setLoaded(false);
+ setTimedOut(false);
+ setCachedHeight(readCachedHeight(html));
+ }, [html, srcDoc, reloadKey]);
+
// The listener is registered once; these refs give it the current values.
const activeRef = useRef(active);
const onErrorRef = useRef(onError);
@@ -175,10 +195,6 @@ function HtmlBlockBody({
onErrorRef.current = onError;
});
- useEffect(() => {
- setCachedHeight(readCachedHeight(html));
- }, [html]);
-
useEffect(() => {
if (!active || fullscreen) return;
// Fullscreen reports were ignored, but the bridge deduplicated them.
@@ -202,7 +218,9 @@ function HtmlBlockBody({
}
// A hidden frame lays out at zero width; what it reports is not its
// height. It reports again once it is shown and resized back.
- if (activeRef.current) reportHeight(message.height);
+ if (activeRef.current) {
+ setMeasured((previous) => nextHtmlBlockHeight(previous, message.height));
+ }
};
window.addEventListener("message", onMessage);
return () => window.removeEventListener("message", onMessage);
@@ -229,6 +247,7 @@ function HtmlBlockBody({
open={fullscreen}
inlineHeight={active ? bodyHeight : 0}
onOpenChange={onFullscreenChange}
+ onReload={onReload}
title={title}
>
<div
@@ -237,6 +256,7 @@ function HtmlBlockBody({
>
{srcDoc != null && (
<CodeBlockIframe
+ key={reloadKey}
ref={iframeRef}
html={srcDoc}
title={title}
diff --git a/packages/views/editor/html-preview-surface.tsx b/packages/views/editor/html-preview-surface.tsx
index ee6b95f8d1..7fd357b506 100644
--- a/packages/views/editor/html-preview-surface.tsx
+++ b/packages/views/editor/html-preview-surface.tsx
@@ -8,7 +8,7 @@ import {
type MouseEvent,
type ReactNode,
} from "react";
-import { X } from "lucide-react";
+import { RotateCw, X } from "lucide-react";
import { Button } from "@multica/ui/components/ui/button";
import { useT } from "../i18n";
@@ -22,6 +22,7 @@ export function HtmlPreviewSurface({
open,
inlineHeight,
onOpenChange,
+ onReload,
title,
children,
}: {
@@ -29,6 +30,7 @@ export function HtmlPreviewSurface({
/** The inline body's height, or zero when its preview is hidden. */
inlineHeight: number;
onOpenChange: (open: boolean) => void;
+ onReload?: () => void;
title: string;
children: ReactNode;
}) {
@@ -102,17 +104,30 @@ export function HtmlPreviewSurface({
<span id={titleId} className="sr-only">
{title}
</span>
- <Button
- ref={closeRef}
- type="button"
- variant="ghost"
- size="icon-sm"
- className="absolute top-2 right-2"
- aria-label={t(($) => $.code_block.close_preview)}
- onClick={() => dialogRef.current?.close()}
- >
- <X />
- </Button>
+ <div className="absolute top-2 right-2 flex gap-1">
+ {onReload && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ title={t(($) => $.attachment.reload)}
+ aria-label={t(($) => $.attachment.reload)}
+ onClick={onReload}
+ >
+ <RotateCw />
+ </Button>
+ )}
+ <Button
+ ref={closeRef}
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t(($) => $.code_block.close_preview)}
+ onClick={() => dialogRef.current?.close()}
+ >
+ <X />
+ </Button>
+ </div>
</>
)}
</dialog>